【发布时间】:2020-11-16 18:03:09
【问题描述】:
很简单,我有以下内核,它修改了C[0] 的值,其中C 是一个只有一个元素的数组。
__kernel void sigma(__global float *A, __global float *B, __global float *C) {
int i = get_global_id(0);
printf("Adding %.2f + %.2f", A[i], B[i]);
C[0] += A[i] + B[i];
}
问题是,最后C[0] 具有最后完成的线程的值,特别是在这个例子中我得到以下内容
Adding 1.00 + 0.00
Adding 2.00 + 1.00
Adding 3.00 + 1.00
Adding 4.00 + 1.00
[5.]
最后C[0] 是4.00 + 1.00。我想要的是C[0] 是(1.00 + 0.00) + (2.00 + 1.00) + (3.00 + 1.00) + (4.00 + 1.00)。所以我希望将每个线程的A[i] 和B[i] 添加到C[0]。
另外我不只是在寻找补充,我希望它与任何功能或操作兼容。
这可能是多余的,但在主机代码中,我只是在做最低限度的工作以将数据传递给内核。这个问题是否与宿主代码有关?
import pyopencl as cl, numpy as np;
ctx = cl.create_some_context(); queue = cl.CommandQueue(ctx); mf = cl.mem_flags
M = np.array([1, 2, 3, 4]).astype(np.float32) # A
V = np.array([0, 1, 1, 1]).astype(np.float32) # B
a = np.array([0]).astype(np.float32) # C
# Transfer data to GPU
A_GPU = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=M)
B_GPU = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=V)
C_GPU = cl.Buffer(ctx, mf.WRITE_ONLY, a.nbytes)
c = np.zeros(shape=a.shape, dtype= np.float32) # array to copy the result
kernel.sigma(queue, M.shape, None, A_GPU, B_GPU, C_GPU)
cl.enqueue_copy(queue, c, C_GPU).wait()
【问题讨论】: