Numpy pyOpencl中向量的传递数组

Numpy pyOpencl中向量的传递数组,numpy,opencl,pyopencl,Numpy,Opencl,Pyopencl,我试图将numpy数组作为opencl向量的数组传递给内核。 (np.int32->int3*的numpy数组) 但结果似乎很奇怪。 如果有人能解释为什么会这样,我们将不胜感激 提前谢谢 源代码: import pyopencl as cl import numpy as np platforms = cl.get_platforms() ctx = cl.Context(dev_type=cl.device_type.GPU, properties=[(cl.context_properti

我试图将numpy数组作为opencl向量的数组传递给内核。 (np.int32->int3*的numpy数组) 但结果似乎很奇怪。 如果有人能解释为什么会这样,我们将不胜感激

提前谢谢

源代码:

import pyopencl as cl
import numpy as np

platforms = cl.get_platforms()
ctx = cl.Context(dev_type=cl.device_type.GPU, properties=[(cl.context_properties.PLATFORM, platforms[0])])
queue = cl.CommandQueue(ctx)

rowcnt = 3
ipt = np.linspace(1, rowcnt * 3, num=rowcnt * 3, dtype=np.int32)
rst = np.ones((rowcnt * 3), dtype=np.int32)

mf = cl.mem_flags
iptbuf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=ipt)
rstbuf = cl.Buffer(ctx, mf.WRITE_ONLY, rst.nbytes)

src = '''
__kernel void test(__global int3* ipt, __global int* rst) {
    int idx = get_global_id(0);
    rst[idx * 3] = ipt[idx].x;
    rst[idx * 3 + 1] = ipt[idx].y;
    rst[idx * 3 + 2] = ipt[idx].z;
}
'''

prg = cl.Program(ctx, src).build()
prg.test(queue, (rowcnt, ), None, iptbuf, rstbuf)

cl.enqueue_copy(queue, rst, rstbuf)

print ipt
print rst
预期产出:

[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 2 3 5 6 7 9 0 0]
结果输出:

[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 2 3 5 6 7 9 0 0]
int3
(和其他type3类型)在大小和对齐方面与
int4
(和其他type4类型)相同。所以你需要在你的例子中考虑到这一点。您可以通过修改示例以使用
int4
并相应地更新所有其他相关内容来快速验证这一点

import pyopencl as cl
import numpy as np

platforms = cl.get_platforms()
ctx = cl.Context(dev_type=cl.device_type.GPU, properties=[(cl.context_properties.PLATFORM, platforms[0])])
queue = cl.CommandQueue(ctx)

rowcnt = 4
ipt = np.linspace(1, rowcnt * 4, num=rowcnt * 4, dtype=np.int32)
rst = np.ones((rowcnt * 4), dtype=np.int32)

mf = cl.mem_flags
iptbuf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=ipt)
rstbuf = cl.Buffer(ctx, mf.WRITE_ONLY, rst.nbytes)

src = '''
__kernel void test(__global int4* ipt, __global int* rst) {
    int idx = get_global_id(0);
    rst[idx * 4] = ipt[idx].x;
    rst[idx * 4 + 1] = ipt[idx].y;
    rst[idx * 4 + 2] = ipt[idx].z;
    rst[idx * 4 + 3] = ipt[idx].w;
}
'''

prg = cl.Program(ctx, src).build()
prg.test(queue, (rowcnt, ), None, iptbuf, rstbuf)

cl.enqueue_copy(queue, rst, rstbuf)

print ipt
print rst
输出:

[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]