Getting started with shared memory on PyCUDA

大城市里の小女人 提交于 2021-02-08 10:35:59

问题


I'm trying to understand shared memory by playing with the following code:

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))

I can't see anything obviously wrong with this, but I keep getting synchronization errors and it doesn't run.

Any help greatly appreciated.


回答1:


When you specify

extern __shared__ float sdata[];

you are telling the compiler that the caller will provide the shared memory. In PyCUDA, that is done by specifying shared=nnnn on the line that calls the CUDA function. In your case, something like:

reduce0(drv.In(a),drv.Out(dest),block=(400,1,1),shared=4*400)

Alternately, you can drop the extern keyword, and specify the shared memory directly:

__shared__ float sdata[400];


来源:https://stackoverflow.com/questions/30696860/getting-started-with-shared-memory-on-pycuda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!