首页 > 解决方案 > 了解 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

解决方案


您还更改了您引用的示例中的数据类型,但您做错了。

如果您指定正确的 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]]
$

推荐阅读