【问题标题】:Passing array of vector in pyOpencl在 pyOpencl 中传递向量数组
【发布时间】:2017-08-09 13:00:01
【问题描述】:

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

提前致谢。

源代码:

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]

【问题讨论】:

    标签: numpy opencl pyopencl


    【解决方案1】:

    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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多