我尝试用 opencl 实现累积和,如下所示:
__kernel void cumsum(__global float *a)
{
int gid = get_global_id(0);
int n = get_global_size(0);
for (int i = 1; i < n; i <<= 1)
if (gid & i)
a[gid] += a[(gid & -i) - 1];
}
我使用 pyopencl 调用了这段代码:
import pyopencl as cl
import pyopencl.array as cl_array
import numpy as np
a = np.random.rand(50000).astype(np.float32)
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
a_dev = cl_array.to_device(queue, a)
with open("imm/cluster.cl", 'r') as f:
prg = cl.Program(ctx, f.read()).build()
prg.cumsum(queue, a.shape, None, a_dev.data)
print(np.cumsum(a)[:33], a_dev[:33])
但是,前 32 个数字是正确的,之后它们是错误的(太低了)。这与工作组规模有关吗?我该如何解决?