目前,在 Python 中利用 GPU 加速进行计算很容易。仅使用 JSL 可以实现这一点吗?
谢谢专家!
64位 win10
以下是 JMP 员工 MZWald 最近对关于多核使用和 GPU 的讨论项目的回复
JMP 中的一些平台仅使用单个线程,因此拥有多个线程不会增加太多价值,但以更快的频率运行单个线程会增加价值。JMP 中的一些平台确实利用了多个线程,因此拥有更多线程/核心确实有帮助。
借助 JMP Pro 18 中的 Torch 插件,现在 GPU 首次可用于图像分类和深度学习,其执行这些任务的速度比 CPU 快几个数量级。
import pyopencl as cl
import pyopencl.array as cl_array
import numpy as np
import csv
import os
import time
# Select OpenCL platform and GPU device
platform = cl.get_platforms()[0] # Select the first platform (e.g., AMD)
device = platform.get_devices()[0] # Select the first GPU device (e.g., gfx804)
context = cl.Context([device])
queue = cl.CommandQueue(context)
# Define the GPU computation kernel (squares array elements)
kernel_code = """
__kernel void square(__global float *arr) {
int gid = get_global_id(0);
arr[gid] = arr[gid] * arr[gid];
}
"""
program = cl.Program(context, kernel_code).build()
# Create the CSV file path
csv_path = r"C:\0\results.csv" # Changed to a more common name
# Ensure the directory exists
os.makedirs(os.path.dirname(csv_path), exist_ok=True)
# Run 10,000 computation tasks
n = 10**6 # 1 million data points per computation
num_iterations = 10_000
# Pre-allocate arrays
host_array = np.empty(n, dtype=np.float32)
gpu_array = cl_array.empty(queue, host_array.shape, dtype=host_array.dtype)
# Store results
results = []
# Random number generator
rng = np.random.default_rng()
# Start timing
start_time = time.time()
for i in range(num_iterations):
# Generate random data and fill host_array
host_array[:] = rng.random(n, dtype=np.float32)
# Upload data to GPU
cl.enqueue_copy(queue, gpu_array.data, host_array)
# Compute on the GPU
program.square(queue, gpu_array.shape, None, gpu_array.data)
# Retrieve data from GPU
cl.enqueue_copy(queue, host_array, gpu_array.data)
# Record the first 5 results
results.append([i + 1] + host_array[:5].tolist())
# Progress display
if (i + 1) % 100 == 0:
print(f"Completed {i + 1}/{num_iterations} iterations...")
# Total time statistics
end_time = time.time()
total_time = end_time - start_time
print(f"Total time: {total_time:.2f} seconds")
print(f"Average time per iteration: {total_time / num_iterations:.6f} seconds")
# Write results to CSV in a single operation
with open(csv_path, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Iteration", "Result 1", "Result 2", "Result 3", "Result 4", "Result 5"]) # CSV header
writer.writerows(results)
print(f":white_heavy_check_mark:</img> Computation complete, results saved to {csv_path}")Python
如何前往JSL?
目前还不行。
使用 Python 和 PyCUDA 或 pyOpenCL 是从 JMP 中的脚本访问 GPU 的唯一方法。如我之前的一篇文章所示,您可以创建用户定义的 JSL 函数,使用 Python Execute() 在 Python 中实现功能。这样,您就可以用 Python 编写 GPU 代码,同时仍为其余脚本提供 JSL 接口。