在PyCUDA上开始使用共享内存

rec*_*ner 0 python cuda gpgpu pycuda pyopencl

我试图通过使用以下代码来了解共享内存:

import pycuda.driver as drv
import pycuda.tools
import pycuda.autoinit
import numpy
from pycuda.compiler import SourceModule

src='''
__global__ void reduce0(float *g_idata, float *g_odata) {
extern __shared__ float sdata[];
// each thread loads one element from global to shared mem
unsigned int tid = threadIdx.x;
unsigned int i = blockIdx.x*blockDim.x + threadIdx.x;

sdata[tid] = g_idata[i];
__syncthreads();
// do reduction in shared mem
for(unsigned int s=1; s < blockDim.x; s *= 2) {
   if (tid % (2*s) == 0) {
      sdata[tid] += sdata[tid + s];
   }
__syncthreads();
}
// write result for this block to global mem
if (tid == 0) g_odata[blockIdx.x] = sdata[0];
}
'''

mod = SourceModule(src)
reduce0=mod.get_function('reduce0')

a = numpy.random.randn(400).astype(numpy.float32)

dest = numpy.zeros_like(a)
reduce0(drv.In(a),drv.Out(dest),block=(400,1,1))
Run Code Online (Sandbox Code Playgroud)

我看不出任何明显错误的东西,但我不断收到同步错误而且它没有运行.

任何帮助非常感谢.

小智 6

当你指定

extern __shared__ float sdata[];
Run Code Online (Sandbox Code Playgroud)

你告诉编译器调用者将提供共享内存.在PyCUDA中,通过shared=nnnn在调用CUDA函数的行上指定来完成.在你的情况下,像:

reduce0(drv.In(a),drv.Out(dest),block=(400,1,1),shared=4*400)
Run Code Online (Sandbox Code Playgroud)

或者,您可以删除extern关键字,并直接指定共享内存:

__shared__ float sdata[400];
Run Code Online (Sandbox Code Playgroud)