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主要实现代码:
[cpp] view plaincopy
  1. // Matrices are stored in row-major order:
  2. // M(row, col) = *(M.elements + row * M.width + col)
  3. typedef struct {
  4. int width;
  5. int height;
  6. float *elements;
  7. } Matrix;
  8. // Thread block size
  9. #define BLOCK_SIZE 16
  10. // Forward declaration of the matrix multiplication kernel
  11. __global__ void MatMulKernel(const Matrix, const Matrix, Matrix);
  12. // Matrix multiplication - Host code
  13. // Matrix dimensions are assumed to be multiples of BLOCK_SIZE
  14. void MatMul(const Matrix A, const Matrix B, Matrix C) {
  15. // Load A and B to device memory
  16. Matrix d_A;
  17. d_A.width = A.width; d_A.height = A.height;
  18. size_t size = A.width * A.height * sizeof(float);
  19. cudaMalloc(&d_A.elements, size);
  20. cudaMemcpy(d_A.elements, A.elements, size, cudaMemcpyHostToDevice);
  21. Matrix d_B;
  22. d_B.width = B.width; d_B.height = B.height;
  23. size = B.width * B.height * sizeof(float);
  24. cudaMalloc(&d_B.elements, size);
  25. cudaMemcpy(d_B.elements, B.elements, size, cudaMemcpyHostToDevice);
  26. // Allocate C in device memory
  27. Matrix d_C;
  28. d_C.width = C.width; d_C.height = C.height;
  29. size = C.width * C.height * sizeof(float);
  30. cudaMalloc(&d_C.elements, size);
  31. // Invoke kernel
  32. dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
  33. dim3 dimGrid(B.width / dimBlock.x, A.height / dimBlock.y);
  34. MatMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C);
  35. // Read C from device memory
  36. cudaMemcpy(C.elements, d_c.elements, size, cudaMemcpyDeviceToHost);
  37. // Free device memory
  38. cudaFree(d_A.elements);
  39. cudaFree(d_B.elements);
  40. cudaFree(d_C.elements);
  41. }
  42. // Matrix multiplication kernel called by MatMul()
  43. __global__ void MatMulKernel(Matrix A, Matrix B, Matrix C) {
  44. // Each thread computes one element of C
  45. // by accumulating results into Cvalue
  46. float Cvalue = 0;
  47. int row  = blockIdx.y * blockDim.y + threadIdx.y;
  48. int col = blockIdx.x * blockDim.x + threadIdx.xl
  49. for (int e = 0; e < A.width; ++e)
  50. Cvalue += A.elements[row * A.width + e] * B.elements[e * B.width + col];
  51. C.elements[row * C.width + col] = Cvalue;
  52. }

可以看出,为了计算矩阵C的任何一个元素,程序都需要从全局内存(global memory)中获得矩阵A的一行和矩阵B的一列。因此,完成这一计算矩阵A被读取了B.width次,矩阵B被读取了A.height次。
        现在我们来使用共享内存(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__函数用来获得和设置子矩阵的元素。下面是优化后的代码:
[cpp] view plaincopy
  1. // Matrices are stored in row-major order;
  2. // M(row, col) = *(M.elements + row * M.stride + col)
  3. typedef struct {
  4. int width;
  5. int height;
  6. int stride;
  7. float* elements;
  8. } Matrix;
  9. // Get a matrix element
  10. __device__ float GetElement(const Matrix A, int row, int col) {
  11. return A.elements[row * A.stride + col];
  12. }
  13. // Set a matrix element
  14. __device__ void SetElement(Matrix A, int row, int col, float value) {
  15. A.elements[row * A.stride + col] = value;
  16. }
  17. // Get the BLOCK_SIZExBLOCK_SIZE sub-matrix Asub of A that is
  18. // located col sub-matrices to the right and row sub-matrices down
  19. // from the upper-left corner of A
  20. __device__ Matrix GetSubMatrix(Matrix A, int row, int col) {
  21. Matrix Asub;
  22. Asub.width = BLOCK_SIZE;
  23. Asub.height = BLOCK_SIZE;
  24. Asub.stride = A.stride;
  25. Asub.elements = &A.elements[A.stride * BLOCK_SIZE * row + BLOCK_SIZE * col];
  26. return Asub;
  27. }
  28. // Thread block size
  29. #define BLOCK_SIZE 16
  30. // Forward declaration of the matrix multiplication kernel
  31. __global__ void MatMulKernel(const Matrix, const Matrix, Matrix);
  32. // Matrix multiplication - Host code
  33. // Matrix dimensions are assumed to be multiples of BLOCK_SIZE
  34. void MatMul(const Matrix A, const Matrix B, Matrix C) {
  35. // Load A and B to device memory
  36. Matrix d_A;
  37. d_A.width = d_A.stride = A.width;
  38. d_A.height = A.height;
  39. size_t size = A.width * A.height * sizeof(float);
  40. cudaMalloc(&d_A.elements, size);
  41. cudaMemcpy(d_A.elements, A.elements, size, cudaMemcpyHostToDevice);
  42. Matrix d_B;
  43. d_B.width = d_B.stride = B.width;
  44. d_B.height = B.height;
  45. size = B.width * B.height * sizeof(float);
  46. cudaMalloc(&d_B.elements, size);
  47. cudaMemcpy(d_B.elements, B.elements, size, cudaMemcpyHostToDevice);
  48. // Allocate C in device memory
  49. Matrix d_C;
  50. d_C.width = d_C.stride = C.width;
  51. d_C.height = C.height;
  52. size = C.width * C.height * sizeof(float);
  53. cudaMalloc(&d_C.elements, size);
  54. // Invoke kernel
  55. dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
  56. dim3 dimGrid(B.width / dimBlock.x, A.height / dimBlock.y);
  57. MatMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C);
  58. // Read C from device memory
  59. cudaMemcpy(C.elements, d_C.elements, size, cudaMemcpyDeviceToHost);
  60. // Free device memory
  61. cudaFree(d_A.elements);
  62. cudaFree(d_B.elements);
  63. cudaFree(d_C.elements);
  64. }
  65. // Matrix multiplication kernel called by MatMul()
  66. __global__ void MatMulKernel(Matrix A, Matrix B, Matrix C) {
  67. // Block row and column
  68. int blockRow = blockIdx.y;
  69. int blockCol = blockIdx.x;
  70. // Each thread block computes one sub-matrix Csub of C
  71. Matrix Csub = GetSubMatrix(C, blockRow, blockCol);
  72. // Each thread computes one element of Csub
  73. // by accumulating results into Cvalue
  74. float Cvalue = 0;
  75. // Thread row and column within Csub
  76. int row = threadIdx.y;
  77. int col = threadIdx.x;
  78. // Look over all the sub-matrices of A and B that are required to compute Csub
  79. // Multiply each pair of sub-matrices together and accumulate the results
  80. for (int m = 0; m < (A.width / BLOCK_SIZE); ++m) {
  81. // Get sub-matrix Asub of A
  82. Matrix Asub = GetSubMatrix(A, blockRow, m);
  83. // Get sub-matrix Bsub of B
  84. Matrix Bsub = GetSubMatrix(B, m, blockCol);
  85. // Shared memory used to store Asub and Bsub respectively
  86. __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
  87. __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];
  88. // Load Asub and Bsub from device memory to shared memory
  89. // Each thread loads one element of each sub-matrix
  90. As[row][col] = GetElement(Asub, row, col);
  91. Bs[row][col] = GetElement(Bsub, row, col);
  92. // Synchronize to make sure the sub-matrices are loaded
  93. // before starting the computation
  94. __syncthreads();
  95. // Multiply Asub and Bsub together
  96. for (int e = 0; e < BLOCK_SIZE; ++e)
  97. Cvalue += As[row][e] * Bs[e][col];
  98. // Synchronize to make sure that the preceding computation is done before
  99. // loading two new sub-matrices of A and B in the next iteration
  100. __syncthreads();
  101. }
  102. // Write Csub to device memory
  103. // Each thread writes one element
  104. SetElement(Csub, row, col, Cvalue);
  105. }

同一个block中的线程在95行的for循环中获取到的Asub,Bsub,Csub是一样的,每个线程就负责Csub内元素的计算

http://blog.csdn.net/csgxy123/article/details/10018531

CUDA编程指南阅读笔记(六)相关推荐

  1. CUDA编程指南阅读笔记

    随着多核CPU和众核GPU的到来,并行编程已经得到了业界越来越多的重视,CPU-GPU异构程序能够极大提高现有计算机系统的运算性能,对于科学计算等运算密集型程序有着非常重要的意义.这一系列文章是根据& ...

  2. Java并发编程艺术阅读笔记(一)

    Java并发编程艺术阅读笔记(一) 1.什么是上下文切换 CPU通过时间片分配算法循环执行任务,执行完一个任务的时间片后就会切换到下一个任务.但是在切换任务之前会保存上一个任务的状态,在切换回该任务, ...

  3. CUDA PTX ISA阅读笔记(一)

    不知道这是个啥的看这里:Parallel Thread Execution ISA Version 5.0. 简要来说,PTX就是.cu代码编译出来的一种东西,然后再由PTX编译生成执行代码.如果不想 ...

  4. iPhone编程指南学习笔记

    为什么80%的码农都做不了架构师?>>>    UIWindow 在创建应用程序窗口时,您应该总是将其初始的边框尺寸设置为整个屏幕的大小.如果您的窗口是从nib文件装载得到,Inte ...

  5. wrappers.php,PHP源码阅读笔记六:stream_get_wrappers函数

    PHP源码阅读笔记stream_get_wrappers函数 stream_get_wrappers (PHP 5) stream_get_wrappers - 返回注册的数据流列表 Descript ...

  6. Google C++编程风格指南阅读笔记之命名、注释和格式

    文章目录 前言 命名约定 类型命名 变量命名 枚举命名 宏的命名 注释 注释风格 文件注释 类注释 函数注释 变量注释 类的数据成员 全局变量 实现注释 TODO注释 格式 行长度 空格还是制表符 函 ...

  7. [转载]高质量c/c++编程指南读书笔记

    一个strcpy函数的代码 能考查三个方面 (1) 编程风格 (2) 出错处理 (3) 算法复杂度分析(用于提供性能) 定义编程老手和编程高手 定义1:能长期稳定地编写出高质量程序的程序员称为编程老手 ...

  8. 程序员健康指南阅读笔记

    编程需要程序员全神贯注,这就常常导致我们忽略生活的其他方面,其中最被忽略的就是,健康状况. 职业不应该让你犯职业病,只要用对了方法,它就不会造成伤害. 做出改变 努力健康起来吧! 永别了椅子 灵活的饮 ...

  9. 高质量c/c++编程指南读书笔记1

    一个strcpy函数的代码 能考查三个方面 (1) 编程风格 (2) 出错处理 (3) 算法复杂度分析(用于提供性能) 定义编程老手和编程高手 定义1:能长期稳定地编写出高质量程序的程序员称为编程老手 ...

最新文章

  1. [转] Zend studio中开发常用
  2. iPhone游戏编程教程一步步教你游戏开发
  3. 学习笔记Spark(四)—— Spark编程基础(创建RDD、RDD算子、文件读取与存储)
  4. 密码学-hash加密
  5. 《笨办法学python》(《learn python the hard way 3thrd》)习题48(ex48)的代码实现
  6. 计算机网络相关的知识,计算机网络知识整理
  7. superset可视化-word cloud
  8. Java中父类的静态变量和静态方法的继承问题
  9. volley全然解析
  10. gtest的介绍和使用
  11. JavaScript 优先队列
  12. 项目三大文档: 项目章程, 初步的项目范围说明书 ,详细范围说明书,项目计划书
  13. rmvb 转 avi 方法
  14. java获取指定日期当月和下个月的第一天
  15. hotmail邮箱收件服务器主机名,hotmail邮箱foxmail(pop3服务器)设置方法
  16. 基于Hi3516DV300rtmp交叉编译移植
  17. Linux系统编程 50 -stat和stat函数 穿透和非穿透
  18. Elasticsearch(十)【NEST高级客户端--搜索查询】
  19. 2022年国家高新技术企业申报秘笈来了
  20. 详解Python中的File(文件)操作

热门文章

  1. 两个主机mtu不相同_案例详解:MTU不一致导致主机和RAC不断重启
  2. 八十八、CSS两列三列的布局方式
  3. 二十七、深入==与equals的区别(下篇)
  4. 六十六,完成SpringBoot项目中的员工增删查改功能
  5. 我跑了ERNIE和BERT两个模型,结果出乎意料......
  6. 2018 ACM-ICPC亚洲区域赛 北京赛区
  7. POJ 2826 An Easy Problem?! 叉积求多边形面积 【计算几何】
  8. php实现上传文件功能,简单实现php上传文件功能
  9. 中的挂起是什么意思_书房装饰挂什么画好 书法字画给你想要的诗意生活
  10. Springboot项目中配置tomcta监控日志