[英]Getting started with shared memory on PyCUDA
我試圖通過玩以下代碼來了解共享內存:
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))
我看不到任何明顯與此有關的錯誤,但是我不斷收到同步錯誤,並且它沒有運行。
任何幫助,不勝感激。
當您指定
extern __shared__ float sdata[];
您告訴編譯器調用者將提供共享內存。 在PyCUDA中,這是通過在調用CUDA函數的行上指定shared=nnnn
來完成的。 就您而言,類似:
reduce0(drv.In(a),drv.Out(dest),block=(400,1,1),shared=4*400)
或者,您可以刪除extern關鍵字,然后直接指定共享內存:
__shared__ float sdata[400];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.