Skip to main content
 首页 » 编程设计

python之PyCUDA之ElementWise 无法进行相等性检查

2025年01月19日12Renyi-Fan

我正在尝试为两个数组构建一个相等性检查器,我可以使用 PyCUDA 在我的 GPU 上运行它。

按照 PyCUDA 上给出的示例 GPU Arrays documentation page ,我试图编写自己的实现。但是虽然下面的代码按预期的算术工作,例如"z[i] = x[i] + y[i]",它返回相等检查器操作数的错误输出 "z[i] = x[i] == y[我]”。

import pycuda.gpuarray as gpuarray 
import pycuda.driver as cuda 
import pycuda.autoinit 
import numpy as np 
from pycuda.elementwise import ElementwiseKernel 
 
matrix_size = (5,) 
a = np.random.randint(2, size=matrix_size) 
b = np.random.randint(2, size=matrix_size) 
 
print a 
print b 
 
a_gpu = gpuarray.to_gpu(a)  
b_gpu = gpuarray.to_gpu(b) 
 
eq_checker = ElementwiseKernel( 
        "int *x, int *y, int *z", 
        "z[i] = x[i] == y[i]", 
        "equality_checker") 
 
c_gpu = gpuarray.empty_like(a_gpu) 
eq_checker(a_gpu, b_gpu, c_gpu) 
 
print c_gpu 

它打印出类似的东西:

[0 1 0 0 0] 
[0 1 1 1 0] 
[4294967297 4294967297          0          1          1] 

有没有人明白为什么会出现这个错误,或者至少有一个替代的 PyCUDA 方法来实现所需的功能?

请您参考如下方法:

解决了!问题是 numpy 自动返回 64 位整数,而 PyCUDA 仅标准地接受 32 位整数。

因此,这可以通过指定 numpy 生成的整数类型来解决,例如:

a = np.random.randint(2, size=matrix_size, dtype=np.int32) 
b = np.random.randint(2, size=matrix_size, dtype=np.int32) 

之后它按预期工作。