python - PyOpenCL 多维数组

标签 python numpy opencl pyopencl

我有使用 PyOpenCL 进行多维数组加法的代码。我的问题是,除了第一个维度之外,其他维度的结果都是错误的。我一直在咨询这个Link

from __future__ import absolute_import, print_function
import numpy as np
import pyopencl as cl

N = 4
a_np = np.random.rand(N,N).astype(np.float32)
b_np = np.random.rand(N,N).astype(np.float32)

ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)

mf = cl.mem_flags
a_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a_np)
b_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b_np)

prg = cl.Program(ctx, """
    __kernel void sum(
        __global const float *a_g, __global const float *b_g, __global float *res_g) {
            int i = get_global_id(1);
            int j = get_global_id(0);
            res_g[i,j] = a_g[i,j] + b_g[i,j];
    }
""").build()

res_g = cl.Buffer(ctx, mf.WRITE_ONLY, a_np.nbytes)
prg.sum(queue, a_np.shape, None, a_g, b_g, res_g)

res_np = np.empty_like(a_np)
cl.enqueue_copy(queue, res_np, res_g)

# Check on CPU with Numpy:
print(res_np - (a_np + b_np))
print(np.linalg.norm(res_np - (a_np + b_np)))
print (res_np)
print (a_np + b_np)

矩阵1:

[[ 0.2990678   0.76585543  0.71866363  0.30202991]
 [ 0.20604192  0.01989171  0.02402978  0.82826865]
 [ 0.75456071  0.62410605  0.4374246   0.85372066]
 [ 0.37000021  0.5734672   0.4250721   0.2456535 ]]

矩阵2:

[[ 0.83109927  0.53289926  0.24182947  0.39531609]
 [ 0.53014964  0.62028325  0.2397541   0.03364789]
 [ 0.83543158  0.1162187   0.21168791  0.22438531]
 [ 0.2178313   0.76118374  0.23737679  0.41660839]]

预期结果:

[[ 1.13016701  1.29875469  0.96049309  0.69734597]
 [ 0.73619157  0.64017498  0.26378387  0.86191654]
 [ 1.58999228  0.74032474  0.64911252  1.07810593]
 [ 0.5878315   1.33465099  0.66244888  0.6622619 ]]

脚本结果:

[[ 1.13016701  1.29875469  0.96049309  0.69734597]
 [ 0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.        ]
 [ 0.          0.          0.          0.        ]]

最佳答案

问题出在这里:

res_g[i,j] = a_g[i,j] + b_g[i,j];

这不是在 OpenCL 中访问多维数组元素的方式。 OpenCLC 的子集,由维基百科定义:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

如此有效地评估为: res_g[j] = a_g[j] + b_g[j];

因此正确地应该是这样的:

res[i + 大小 * j] = ...

再次查阅您提供的链接,一切都在那里。

关于python - PyOpenCL 多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45304157/

相关文章:

python - sklearn LogisticRegression python 中的 alpha

python - 具有三层深度嵌套模型的查询集过滤器(多个一对多关系)

python - 查找字典 Python 列表的差异

python - 图像 Python 的滚动统计

python - 填充蒙版框架中的孔/ block

kernel - 通过OpenCL使用OpenACC吗?

python - 使用正则表达式在 python 中的数据框或列中的大写字母之前添加空格

python - 从插值函数中检索值

static-libraries - OpenCL - 足够轻量级以进行静态链接?

macos - OS X Mavericks 中的 OpenCL 框架缺少 OpenCL header ?