python - Pycuda 代码无法工作 : the "block" line in the call of the function doesn't work

标签 python pycuda

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

我遇到的错误是:

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

错误发生在我调用函数的 block 行上。在代码中,它位于 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的类型不正确。错误不在于 block 参数。

原因是 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),
    )

应该可以正常工作。

关于python - Pycuda 代码无法工作 : the "block" line in the call of the function doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47763388/

相关文章:

python - shell脚本监视日志中的 "word",然后终止并重新启动进程

python - 向 pyqt 列表添加标题

python - PyOpenCL 与 Python 多处理?

python - skcuda.fft 与 numpy.fft.rfft 不一样?

python - 从 timeit 访问外部变量

python - 如何在Python中从Excel列表中读取时间戳

python - 无法用pip安装pycuda

python - 如何创建Python中使用的cuda共享库

python - PyCUDA 使用字符串但不使用字符串数组

python - Opencv 上的线性倒置图像