CUDA编程指南阅读笔记(六)
4.CUDA C语言编程接口
接上文。
4.3 CUDA C Runtime
4.3.3 共享内存(Shared Memory)
共享内存是CUDA设备中非常重要的一个存储区域,有效地使用共享内存可以充分利用CUDA设备的潜能,极大提升程序性能。那么,共享内存有哪些特点呢?
1、共享内存(shared Memory)是集成在GPU处理器芯片上的(on-chip),因此相比于存在于显存颗粒中的全局内存(global Memory)和本地内存(local Memory),它具有更高的传输带宽,一般情况下,共享内存的带宽大约是全局内存带宽的7-10倍。
2、共享内存的容量很小。根据NVIDIA官方文档的说法,在计算能力1.x的设备中,每一个流多处理器(Streaming Multiprocessor)上的共享内存容量为16KB。对于计算能力2.x、3.0及3.5的设备该参数为48KB。因此共享内存是稀有资源。
3、共享内存在物理上被划分为很多块,每一块被称为一个存储体(bank)。在同一时刻,CUDA设备可以同时访问多个存储体。因此,如果一次针对共享内存的访存操作需要读取n个地址,而这n个地址恰好分布在n个不同的存储体(bank)中,那么只需要一个存取周期就可以完成n个地址的访存任务了。对于计算能力1.x的设备,共享内存被平均划分为16个存储体。而对于计算能力2.x、3.0及3.5的设备此参数为32。在共享内存中,相邻两块32bit的数据分别属于相邻的两个存储体。存储体每两个时钟周期可以传输32位数据。
4、共享内存既可以静态分配,也可以动态分配。
从共享内存的这些特点中我们可以看出,它实际上相当于一个程序员可以操控的缓存(cache),下面,我们使用矩阵乘法的例子来说明如何有效使用共享内存。
首先,我们使用最直观的方法来完成矩阵乘法C = A x B:读取A的每一行和B的每一列,顺次完成计算任务。矩阵乘法的示意图如下所示:
下面是矩阵乘法的CUDA C主要实现代码:
- //Matricesarestoredinrow-majororder:
- //M(row,col)=*(M.elements+row*M.width+col)
- typedefstruct{
- intwidth;
- intheight;
- float*elements;
- }Matrix;
- //Threadblocksize
- #defineBLOCK_SIZE16
- //Forwarddeclarationofthematrixmultiplicationkernel
- __global__voidMatMulKernel(constMatrix,constMatrix,Matrix);
- //Matrixmultiplication-Hostcode
- //MatrixdimensionsareassumedtobemultiplesofBLOCK_SIZE
- voidMatMul(constMatrixA,constMatrixB,MatrixC){
- //LoadAandBtodevicememory
- Matrixd_A;
- d_A.width=A.width;d_A.height=A.height;
- size_tsize=A.width*A.height*sizeof(float);
- cudaMalloc(&d_A.elements,size);
- cudaMemcpy(d_A.elements,A.elements,size,cudaMemcpyHostToDevice);
- Matrixd_B;
- d_B.width=B.width;d_B.height=B.height;
- size=B.width*B.height*sizeof(float);
- cudaMalloc(&d_B.elements,size);
- cudaMemcpy(d_B.elements,B.elements,size,cudaMemcpyHostToDevice);
- //AllocateCindevicememory
- Matrixd_C;
- d_C.width=C.width;d_C.height=C.height;
- size=C.width*C.height*sizeof(float);
- cudaMalloc(&d_C.elements,size);
- //Invokekernel
- dim3dimBlock(BLOCK_SIZE,BLOCK_SIZE);
- dim3dimGrid(B.width/dimBlock.x,A.height/dimBlock.y);
- MatMulKernel<<<dimGrid,dimBlock>>>(d_A,d_B,d_C);
- //ReadCfromdevicememory
- cudaMemcpy(C.elements,d_c.elements,size,cudaMemcpyDeviceToHost);
- //Freedevicememory
- cudaFree(d_A.elements);
- cudaFree(d_B.elements);
- cudaFree(d_C.elements);
- }
- //MatrixmultiplicationkernelcalledbyMatMul()
- __global__voidMatMulKernel(MatrixA,MatrixB,MatrixC){
- //EachthreadcomputesoneelementofC
- //byaccumulatingresultsintoCvalue
- floatCvalue=0;
- introw=blockIdx.y*blockDim.y+threadIdx.y;
- intcol=blockIdx.x*blockDim.x+threadIdx.xl
- for(inte=0;e<A.width;++e)
- Cvalue+=A.elements[row*A.width+e]*B.elements[e*B.width+col];
- C.elements[row*C.width+col]=Cvalue;
- }
现在我们来使用共享内存(shared memory)实现矩阵乘法。假设矩阵C可以被划分为若干个较小的子方阵Csub,我们使用一个线程块(thread block)来负责某一子方阵的计算,线程块中的每一个线程(thread)正好负责子方阵Csub中一个元素的计算。这样划分后,任何一个结果子方阵Csub'(尺寸为block_size * block_size)都是与该方阵具有相同行索引的尺寸为A.width * block_size的A的子矩阵Asub和与该方阵具有相同列索引的尺寸为block_size * B.height的B的子矩阵Bsub相乘所得到。
为了匹配设备的计算资源,两个子矩阵Asub和Bsub被划分为尽可能多的分离的维度为block_size的子方阵,Csub的值便是这些子矩阵相乘后相加所得到的结果。子矩阵乘法的执行顺序都是首先将它们从全局内存(global
memory)拷贝到共享内存(shared memory)(线程块中的每一个线程正好负责方阵一个元素的拷贝),然后由线程自己完成相应元素的计算任务,利用寄存器存储局部结果,最后将寄存器的内容与新得到的计算结果依此累加起来得到最终运算结果并将其传输到全局内存(global memory)中。
通过使用这种分治的计算策略,共享内存得到了很好的利用,采用这种方案计算完成时全局内存中矩阵A被访问的次数为B.width / block_size,矩阵B被访问的次数为A.height / block_size,很明显,这为我们节省了非常多的全局内存带宽。优化后的矩阵计算示意图如下所示:
为了提升计算效率,我们为类型Matrix增加了一个成员变量stride。__device__函数用来获得和设置子矩阵的元素。下面是优化后的代码:
- //Matricesarestoredinrow-majororder;
- //M(row,col)=*(M.elements+row*M.stride+col)
- typedefstruct{
- intwidth;
- intheight;
- intstride;
- float*elements;
- }Matrix;
- //Getamatrixelement
- __device__floatGetElement(constMatrixA,introw,intcol){
- returnA.elements[row*A.stride+col];
- }
- //Setamatrixelement
- __device__voidSetElement(MatrixA,introw,intcol,floatvalue){
- A.elements[row*A.stride+col]=value;
- }
- //GettheBLOCK_SIZExBLOCK_SIZEsub-matrixAsubofAthatis
- //locatedcolsub-matricestotherightandrowsub-matricesdown
- //fromtheupper-leftcornerofA
- __device__MatrixGetSubMatrix(MatrixA,introw,intcol){
- MatrixAsub;
- Asub.width=BLOCK_SIZE;
- Asub.height=BLOCK_SIZE;
- Asub.stride=A.stride;
- Asub.elements=&A.elements[A.stride*BLOCK_SIZE*row+BLOCK_SIZE*col];
- returnAsub;
- }
- //Threadblocksize
- #defineBLOCK_SIZE16
- //Forwarddeclarationofthematrixmultiplicationkernel
- __global__voidMatMulKernel(constMatrix,constMatrix,Matrix);
- //Matrixmultiplication-Hostcode
- //MatrixdimensionsareassumedtobemultiplesofBLOCK_SIZE
- voidMatMul(constMatrixA,constMatrixB,MatrixC){
- //LoadAandBtodevicememory
- Matrixd_A;
- d_A.width=d_A.stride=A.width;
- d_A.height=A.height;
- size_tsize=A.width*A.height*sizeof(float);
- cudaMalloc(&d_A.elements,size);
- cudaMemcpy(d_A.elements,A.elements,size,cudaMemcpyHostToDevice);
- Matrixd_B;
- d_B.width=d_B.stride=B.width;
- d_B.height=B.height;
- size=B.width*B.height*sizeof(float);
- cudaMalloc(&d_B.elements,size);
- cudaMemcpy(d_B.elements,B.elements,size,cudaMemcpyHostToDevice);
- //AllocateCindevicememory
- Matrixd_C;
- d_C.width=d_C.stride=C.width;
- d_C.height=C.height;
- size=C.width*C.height*sizeof(float);
- cudaMalloc(&d_C.elements,size);
- //Invokekernel
- dim3dimBlock(BLOCK_SIZE,BLOCK_SIZE);
- dim3dimGrid(B.width/dimBlock.x,A.height/dimBlock.y);
- MatMulKernel<<<dimGrid,dimBlock>>>(d_A,d_B,d_C);
- //ReadCfromdevicememory
- cudaMemcpy(C.elements,d_C.elements,size,cudaMemcpyDeviceToHost);
- //Freedevicememory
- cudaFree(d_A.elements);
- cudaFree(d_B.elements);
- cudaFree(d_C.elements);
- }
- //MatrixmultiplicationkernelcalledbyMatMul()
- __global__voidMatMulKernel(MatrixA,MatrixB,MatrixC){
- //Blockrowandcolumn
- intblockRow=blockIdx.y;
- intblockCol=blockIdx.x;
- //Eachthreadblockcomputesonesub-matrixCsubofC
- MatrixCsub=GetSubMatrix(C,blockRow,blockCol);
- //EachthreadcomputesoneelementofCsub
- //byaccumulatingresultsintoCvalue
- floatCvalue=0;
- //ThreadrowandcolumnwithinCsub
- introw=threadIdx.y;
- intcol=threadIdx.x;
- //Lookoverallthesub-matricesofAandBthatarerequiredtocomputeCsub
- //Multiplyeachpairofsub-matricestogetherandaccumulatetheresults
- for(intm=0;m<(A.width/BLOCK_SIZE);++m){
- //Getsub-matrixAsubofA
- MatrixAsub=GetSubMatrix(A,blockRow,m);
- //Getsub-matrixBsubofB
- MatrixBsub=GetSubMatrix(B,m,blockCol);
- //SharedmemoryusedtostoreAsubandBsubrespectively
- __shared__floatAs[BLOCK_SIZE][BLOCK_SIZE];
- __shared__floatBs[BLOCK_SIZE][BLOCK_SIZE];
- //LoadAsubandBsubfromdevicememorytosharedmemory
- //Eachthreadloadsoneelementofeachsub-matrix
- As[row][col]=GetElement(Asub,row,col);
- Bs[row][col]=GetElement(Bsub,row,col);
- //Synchronizetomakesurethesub-matricesareloaded
- //beforestartingthecomputation
- __syncthreads();
- //MultiplyAsubandBsubtogether
- for(inte=0;e<BLOCK_SIZE;++e)
- Cvalue+=As[row][e]*Bs[e][col];
- //Synchronizetomakesurethattheprecedingcomputationisdonebefore
- //loadingtwonewsub-matricesofAandBinthenextiteration
- __syncthreads();
- }
- //WriteCsubtodevicememory
- //Eachthreadwritesoneelement
- SetElement(Csub,row,col,Cvalue);
- }
-
同一个block中的线程在95行的for循环中获取到的Asub,Bsub,Csub是一样的,每个线程就负责Csub内元素的计算
http://blog.csdn.net/csgxy123/article/details/10018531
4.CUDA C语言编程接口
接上文。
4.3 CUDA C Runtime
4.3.3 共享内存(Shared Memory)
共享内存是CUDA设备中非常重要的一个存储区域,有效地使用共享内存可以充分利用CUDA设备的潜能,极大提升程序性能。那么,共享内存有哪些特点呢?
1、共享内存(shared Memory)是集成在GPU处理器芯片上的(on-chip),因此相比于存在于显存颗粒中的全局内存(global Memory)和本地内存(local Memory),它具有更高的传输带宽,一般情况下,共享内存的带宽大约是全局内存带宽的7-10倍。
2、共享内存的容量很小。根据NVIDIA官方文档的说法,在计算能力1.x的设备中,每一个流多处理器(Streaming Multiprocessor)上的共享内存容量为16KB。对于计算能力2.x、3.0及3.5的设备该参数为48KB。因此共享内存是稀有资源。
3、共享内存在物理上被划分为很多块,每一块被称为一个存储体(bank)。在同一时刻,CUDA设备可以同时访问多个存储体。因此,如果一次针对共享内存的访存操作需要读取n个地址,而这n个地址恰好分布在n个不同的存储体(bank)中,那么只需要一个存取周期就可以完成n个地址的访存任务了。对于计算能力1.x的设备,共享内存被平均划分为16个存储体。而对于计算能力2.x、3.0及3.5的设备此参数为32。在共享内存中,相邻两块32bit的数据分别属于相邻的两个存储体。存储体每两个时钟周期可以传输32位数据。
4、共享内存既可以静态分配,也可以动态分配。
从共享内存的这些特点中我们可以看出,它实际上相当于一个程序员可以操控的缓存(cache),下面,我们使用矩阵乘法的例子来说明如何有效使用共享内存。
首先,我们使用最直观的方法来完成矩阵乘法C = A x B:读取A的每一行和B的每一列,顺次完成计算任务。矩阵乘法的示意图如下所示:
下面是矩阵乘法的CUDA C主要实现代码:
- //Matricesarestoredinrow-majororder:
- //M(row,col)=*(M.elements+row*M.width+col)
- typedefstruct{
- intwidth;
- intheight;
- float*elements;
- }Matrix;
- //Threadblocksize
- #defineBLOCK_SIZE16
- //Forwarddeclarationofthematrixmultiplicationkernel
- __global__voidMatMulKernel(constMatrix,constMatrix,Matrix);
- //Matrixmultiplication-Hostcode
- //MatrixdimensionsareassumedtobemultiplesofBLOCK_SIZE
- voidMatMul(constMatrixA,constMatrixB,MatrixC){
- //LoadAandBtodevicememory
- Matrixd_A;
- d_A.width=A.width;d_A.height=A.height;
- size_tsize=A.width*A.height*sizeof(float);
- cudaMalloc(&d_A.elements,size);
- cudaMemcpy(d_A.elements,A.elements,size,cudaMemcpyHostToDevice);
- Matrixd_B;
- d_B.width=B.width;d_B.height=B.height;
- size=B.width*B.height*sizeof(float);
- cudaMalloc(&d_B.elements,size);
- cudaMemcpy(d_B.elements,B.elements,size,cudaMemcpyHostToDevice);
- //AllocateCindevicememory
- Matrixd_C;
- d_C.width=C.width;d_C.height=C.height;
- size=C.width*C.height*sizeof(float);
- cudaMalloc(&d_C.elements,size);
- //Invokekernel
- dim3dimBlock(BLOCK_SIZE,BLOCK_SIZE);
- dim3dimGrid(B.width/dimBlock.x,A.height/dimBlock.y);
- MatMulKernel<<<dimGrid,dimBlock>>>(d_A,d_B,d_C);
- //ReadCfromdevicememory
- cudaMemcpy(C.elements,d_c.elements,size,cudaMemcpyDeviceToHost);
- //Freedevicememory
- cudaFree(d_A.elements);
- cudaFree(d_B.elements);
- cudaFree(d_C.elements);
- }
- //MatrixmultiplicationkernelcalledbyMatMul()
- __global__voidMatMulKernel(MatrixA,MatrixB,MatrixC){
- //EachthreadcomputesoneelementofC
- //byaccumulatingresultsintoCvalue
- floatCvalue=0;
- introw=blockIdx.y*blockDim.y+threadIdx.y;
- intcol=blockIdx.x*blockDim.x+threadIdx.xl
- for(inte=0;e<A.width;++e)
- Cvalue+=A.elements[row*A.width+e]*B.elements[e*B.width+col];
- C.elements[row*C.width+col]=Cvalue;
- }
现在我们来使用共享内存(shared memory)实现矩阵乘法。假设矩阵C可以被划分为若干个较小的子方阵Csub,我们使用一个线程块(thread block)来负责某一子方阵的计算,线程块中的每一个线程(thread)正好负责子方阵Csub中一个元素的计算。这样划分后,任何一个结果子方阵Csub'(尺寸为block_size * block_size)都是与该方阵具有相同行索引的尺寸为A.width * block_size的A的子矩阵Asub和与该方阵具有相同列索引的尺寸为block_size * B.height的B的子矩阵Bsub相乘所得到。
为了匹配设备的计算资源,两个子矩阵Asub和Bsub被划分为尽可能多的分离的维度为block_size的子方阵,Csub的值便是这些子矩阵相乘后相加所得到的结果。子矩阵乘法的执行顺序都是首先将它们从全局内存(global
memory)拷贝到共享内存(shared memory)(线程块中的每一个线程正好负责方阵一个元素的拷贝),然后由线程自己完成相应元素的计算任务,利用寄存器存储局部结果,最后将寄存器的内容与新得到的计算结果依此累加起来得到最终运算结果并将其传输到全局内存(global memory)中。
通过使用这种分治的计算策略,共享内存得到了很好的利用,采用这种方案计算完成时全局内存中矩阵A被访问的次数为B.width / block_size,矩阵B被访问的次数为A.height / block_size,很明显,这为我们节省了非常多的全局内存带宽。优化后的矩阵计算示意图如下所示:
为了提升计算效率,我们为类型Matrix增加了一个成员变量stride。__device__函数用来获得和设置子矩阵的元素。下面是优化后的代码:
- //Matricesarestoredinrow-majororder;
- //M(row,col)=*(M.elements+row*M.stride+col)
- typedefstruct{
- intwidth;
- intheight;
- intstride;
- float*elements;
- }Matrix;
- //Getamatrixelement
- __device__floatGetElement(constMatrixA,introw,intcol){
- returnA.elements[row*A.stride+col];
- }
- //Setamatrixelement
- __device__voidSetElement(MatrixA,introw,intcol,floatvalue){
- A.elements[row*A.stride+col]=value;
- }
- //GettheBLOCK_SIZExBLOCK_SIZEsub-matrixAsubofAthatis
- //locatedcolsub-matricestotherightandrowsub-matricesdown
- //fromtheupper-leftcornerofA
- __device__MatrixGetSubMatrix(MatrixA,introw,intcol){
- MatrixAsub;
- Asub.width=BLOCK_SIZE;
- Asub.height=BLOCK_SIZE;
- Asub.stride=A.stride;
- Asub.elements=&A.elements[A.stride*BLOCK_SIZE*row+BLOCK_SIZE*col];
- returnAsub;
- }
- //Threadblocksize
- #defineBLOCK_SIZE16
- //Forwarddeclarationofthematrixmultiplicationkernel
- __global__voidMatMulKernel(constMatrix,constMatrix,Matrix);
- //Matrixmultiplication-Hostcode
- //MatrixdimensionsareassumedtobemultiplesofBLOCK_SIZE
- voidMatMul(constMatrixA,constMatrixB,MatrixC){
- //LoadAandBtodevicememory
- Matrixd_A;
- d_A.width=d_A.stride=A.width;
- d_A.height=A.height;
- size_tsize=A.width*A.height*sizeof(float);
- cudaMalloc(&d_A.elements,size);
- cudaMemcpy(d_A.elements,A.elements,size,cudaMemcpyHostToDevice);
- Matrixd_B;
- d_B.width=d_B.stride=B.width;
- d_B.height=B.height;
- size=B.width*B.height*sizeof(float);
- cudaMalloc(&d_B.elements,size);
- cudaMemcpy(d_B.elements,B.elements,size,cudaMemcpyHostToDevice);
- //AllocateCindevicememory
- Matrixd_C;
- d_C.width=d_C.stride=C.width;
- d_C.height=C.height;
- size=C.width*C.height*sizeof(float);
- cudaMalloc(&d_C.elements,size);
- //Invokekernel
- dim3dimBlock(BLOCK_SIZE,BLOCK_SIZE);
- dim3dimGrid(B.width/dimBlock.x,A.height/dimBlock.y);
- MatMulKernel<<<dimGrid,dimBlock>>>(d_A,d_B,d_C);
- //ReadCfromdevicememory
- cudaMemcpy(C.elements,d_C.elements,size,cudaMemcpyDeviceToHost);
- //Freedevicememory
- cudaFree(d_A.elements);
- cudaFree(d_B.elements);
- cudaFree(d_C.elements);
- }
- //MatrixmultiplicationkernelcalledbyMatMul()
- __global__voidMatMulKernel(MatrixA,MatrixB,MatrixC){
- //Blockrowandcolumn
- intblockRow=blockIdx.y;
- intblockCol=blockIdx.x;
- //Eachthreadblockcomputesonesub-matrixCsubofC
- MatrixCsub=GetSubMatrix(C,blockRow,blockCol);
- //EachthreadcomputesoneelementofCsub
- //byaccumulatingresultsintoCvalue
- floatCvalue=0;
- //ThreadrowandcolumnwithinCsub
- introw=threadIdx.y;
- intcol=threadIdx.x;
- //Lookoverallthesub-matricesofAandBthatarerequiredtocomputeCsub
- //Multiplyeachpairofsub-matricestogetherandaccumulatetheresults
- for(intm=0;m<(A.width/BLOCK_SIZE);++m){
- //Getsub-matrixAsubofA
- MatrixAsub=GetSubMatrix(A,blockRow,m);
- //Getsub-matrixBsubofB
- MatrixBsub=GetSubMatrix(B,m,blockCol);
- //SharedmemoryusedtostoreAsubandBsubrespectively
- __shared__floatAs[BLOCK_SIZE][BLOCK_SIZE];
- __shared__floatBs[BLOCK_SIZE][BLOCK_SIZE];
- //LoadAsubandBsubfromdevicememorytosharedmemory
- //Eachthreadloadsoneelementofeachsub-matrix
- As[row][col]=GetElement(Asub,row,col);
- Bs[row][col]=GetElement(Bsub,row,col);
- //Synchronizetomakesurethesub-matricesareloaded
- //beforestartingthecomputation
- __syncthreads();
- //MultiplyAsubandBsubtogether
- for(inte=0;e<BLOCK_SIZE;++e)
- Cvalue+=As[row][e]*Bs[e][col];
- //Synchronizetomakesurethattheprecedingcomputationisdonebefore
- //loadingtwonewsub-matricesofAandBinthenextiteration
- __syncthreads();
- }
- //WriteCsubtodevicememory
- //Eachthreadwritesoneelement
- SetElement(Csub,row,col,Cvalue);
- }
-