Pycuda 代码不起作用:函数调用中的 "block" 行不起作用

Pycuda code not working : the "block" line in the call of the function doesn't work

我想了解为什么以下 PyCUDA 代码不起作用。

我的错误是:

TypeError: invalid type on parameter #3 (0-based)

错误发生在我调用函数的块行上。在代码中,它位于 block = (MATRIX_SIZE,MATRIX_SIZE,1) 行,结束前 2 行。

有谁知道这里的错误是什么?我尝试了很多东西,但我无法弄清楚。

CUDA 代码在 C++ 中运行,我现在正尝试在 PyCUDA 中翻译它,但它失败了。

import numpy as np
from pycuda import driver, compiler, gpuarray, tools

# -- initialize the device
import pycuda.autoinit

kernel_code_template = """
__global__  void MatMult(float* C, float* A, float*B, int dimAx, int dimBx, int dimCx, int dimCy)
{
    int row = blockDim.y*blockIdx.y+threadIdx.y;
    int col = blockDim.x*blockIdx.x+threadIdx.x;

    double Result = 0;

    if (row<=dimCy-1 && col<=dimCx-1)
    {
        for (int k = 0; k < dimAx; k++)
        {
            Result += A[k + dimAx*row] * B[col + dimBx*k];
        }

        C[col + row*dimCx] = Result;
    }
}
"""

MATRIX_SIZE=3

# I create my variables :
a_cpu=np.asarray([[0,1,2],[10,11,12],[20,21,22]])
b_cpu=np.asarray([[0,0,0],[1,2,3],[4,8,12]])

a_gpu = gpuarray.to_gpu(a_cpu) 
b_gpu = gpuarray.to_gpu(b_cpu)

size_Ax=a_cpu.shape[1]
size_Bx=b_cpu.shape[1]

size_Ay=a_cpu.shape[0]

size_Cx=size_Bx # Cx=Bx because of matrix product
size_Cy=size_Ay # Cy=Ay
# create empty gpu array for the result (C = A * B)
c_gpu = gpuarray.empty((size_Cy, size_Cx), np.float32)

# get the kernel code from the template 
kernel_code=kernel_code_template
# compile the kernel code 
mod = compiler.SourceModule(kernel_code)

# get the kernel function from the compiled module
matrixmul = mod.get_function("MatMult")

# call the kernel on the card

matrixmul(
    # outputs
    c_gpu, 
    # inputs
    a_gpu, b_gpu,
    size_Ax,size_Bx,size_Cx,size_Cy,
    # (only one) block of MATRIX_SIZE x MATRIX_SIZE threads
    block = (MATRIX_SIZE,MATRIX_SIZE,1),
    )

您对错误来源的解释不正确。错误信息:

"TypeError: invalid type on parameter #3 (0-based)"

告诉您第四个参数 size_Ax 的类型不正确。错误与块参数无关。

这是因为 PyCUDA 在将数据传入和传出 GPU 时强制执行严格的类型安全。您的内核签名需要 dimAxdimBxdimCxdimCyint 值,它们是 32 位的。 Python 整数默认为 64 位。您需要将参数显式转换为正确的 ctype,例如:

matrixmul(
    # outputs
    c_gpu, 
    # inputs
    a_gpu, b_gpu,
    np.int32(size_Ax),np.int32(size_Bx),np.int32(size_Cx),np.in32(size_Cy),
    # (only one) block of MATRIX_SIZE x MATRIX_SIZE threads
    block = (MATRIX_SIZE,MATRIX_SIZE,1),
    )

应该可以正常工作。