如何使用PyCUDA中的`prepare`函数

时间:2011-08-05 09:53:08

标签: cuda pycuda

我在将prepare function(和prepared_call)传递给allocate of shared memory in PyCUDA时遇到问题。我以这种方式理解错误消息,我传递给PyCUDA的一个变量是long,而不是我想要的float32。但是我看不到变量来自哪里。

此外,在我看来,official exampledocumentation of prepare相互矛盾,关于block是否需要None

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

kernel_code ="""
__device__ void loadVector(float *target, float* source, int dimensions )
{
    for( int i = 0; i < dimensions; i++ ) target[i] = source[i];
}
__global__ void kernel(float* data, int dimensions, float* debug)
{
    extern __shared__ float mean[];
    if(threadIdx.x == 0) loadVector( mean, &data[0], dimensions );
    debug[threadIdx.x]=  mean[threadIdx.x];
}
"""

dimensions = 12
np.random.seed(23)
data = np.random.randn(dimensions).astype(np.float32)
data_gpu = gpuarray.to_gpu(data)
debug = gpuarray.zeros(dimensions, dtype=np.float32)

mod = compiler.SourceModule(kernel_code)
kernel = mod.get_function("kernel")
kernel.prepare("PiP",block = (dimensions, 1, 1),shared=data.size)
grid = (1,1)
kernel.prepared_call(grid,data_gpu,dimensions,debug)
print debug.get()

输出

Traceback (most recent call last):
File "shared_memory_minimal_example.py", line 28, in <module>
kernel.prepared_call(grid,data_gpu,dimensions,debug)
File "/usr/local/lib/python2.6/dist-packages/pycuda-0.94.2-py2.6-linux-x86_64.egg/pycuda/driver.py", line 230, in function_prepared_call
func.param_setv(0, pack(func.arg_format, *args))
pycuda._pvt_struct.error: cannot convert argument to long

1 个答案:

答案 0 :(得分:6)

我遇到了同样的问题,我花了一段时间才得出答案,所以这里就是这样。错误消息的原因是data_gpu是GPUArray实例,即您使用

创建它
data_gpu = gpuarray.to_gpu(data)

要将其传递给prepared_call,您需要执行data_gpu.gpudata以获取关联的DeviceAllocation实例(即实际指向设备内存位置的指针)。

此外,将一个块参数传递给prepare现在是deprecated - 所以正确的调用将是这样的:

data_gpu = gpuarray.to_gpu(data)
func.prepare( "P" )
grid = (1,1)
block = (1,1,1)
func.prepared_call( grid, block, data_gpu.gpudata )