cupy - 了解 cp.RawKernel 中的网格和块
问题描述
第 11 页的https://buildmedia.readthedocs.org/media/pdf/cupy/latest/cupy.pdf中显示的关于使用 cp.RawKernel的示例在网格的使用方面对我来说并不清楚,因为矩阵是方形的。
我尝试改变矩阵的形状并尝试使用网格和块。我不清楚为什么要获得正确的结果我必须设置网格 8 和块 8,例如 multiply((8, ), (8, ), (p, q, z)) # grid, block and arguments
import cupy as cp #Importing CuPy
#Defining the CUDA kernel
multiply = cp.RawKernel(r'''
extern "C" __global__
void multiply(const int* p, const int* q, int* z) {
int tid = blockDim.x * blockIdx.x + threadIdx.x;
z[tid] = p[tid] + q[tid];
}
''', 'multiply')
#First two arrays are set as 0,1,2,3....upto 300
p = cp.arange(30, dtype=cp.int).reshape(6,5)
q = cp.arange(30, dtype=cp.int).reshape(6,5)
#Setting a new array with zeros to pass to kernel for computation
z = cp.zeros((6,5), dtype=cp.int)
#Invoking the kernel with a grid of 250 blocks, each consisting of 1024 threads
multiply((6, ), (5, ), (p, q, z)) # grid, block and arguments
#Displaying the output computed on the kernel
print(z)
我期待检索正确的结果设置,如上面的代码 multiply((6, ), (5, ), (p, q, z)) # grid, block and arguments
你能帮我么?
解决方案
您还更改了您引用的示例中的数据类型,但您做错了。
如果您指定正确的 cupy 数据类型 ( cp.int32
) 以匹配您选择的原始内核数据类型 ( int
),那么您的代码对我来说可以正常工作,如下所示:
$ cat t7.py
import cupy as cp #Importing CuPy
#Defining the CUDA kernel
multiply = cp.RawKernel(r'''
extern "C" __global__
void multiply(const int* p, const int* q, int* z) {
int tid = blockDim.x * blockIdx.x + threadIdx.x;
z[tid] = p[tid] + q[tid];
}
''', 'multiply')
#First two arrays are set as 0,1,2,3....upto 300
p = cp.arange(30, dtype=cp.int32).reshape(6,5)
q = cp.arange(30, dtype=cp.int32).reshape(6,5)
#Setting a new array with zeros to pass to kernel for computation
z = cp.zeros((6,5), dtype=cp.int32)
#Invoking the kernel with a grid of 250 blocks, each consisting of 1024 threads
multiply((6, ), (5, ), (p, q, z)) # grid, block and arguments
#Displaying the output computed on the kernel
print(z)
$ python t7.py
[[ 0 2 4 6 8]
[10 12 14 16 18]
[20 22 24 26 28]
[30 32 34 36 38]
[40 42 44 46 48]
[50 52 54 56 58]]
$
推荐阅读
- android - 颤振:未处理的异常:ServicesBinding.defaultBinaryMessenger
- bash - 为什么 sed 命令可以交互工作,但不能在我的脚本中工作?[更新]
- angular - Angular - 当无效表单绑定到也是一个角度组件的子表单控制器时,父表单不更新
- javascript - 提交表单,包含 2 个事件
- javascript - JQuery获取所选按钮旁边的当前复选框值
- rust - 如何将具体整数转换为通用整数?
- c# - 如何设置多个操作方法来处理仅因传递参数而异的获取请求?
- javascript - Navigo 路由器有问题,它不会在路由之间导航
- c# - 如何模拟实现多个接口的类并将模拟对象转换回类类型?
- java - Elasticsearch 匹配完整的术语数组