问题
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