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



我想了解为什么以下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:参数#3(基于0)上的无效类型"

告诉您第四参数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),
    )

应该正确工作。

最新更新