CUDA Samples: matrix multiplication(C = A * B)
生活随笔
收集整理的這篇文章主要介紹了
CUDA Samples: matrix multiplication(C = A * B)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以下CUDA sample是分別用C++和CUDA實(shí)現(xiàn)的兩矩陣相乘運(yùn)算code即C= A*B,CUDA中包含了兩種核函數(shù)的實(shí)現(xiàn)方法,第一種方法來自于CUDA Samples\v8.0\0_Simple\matrixMul,第二種采用普通的方法實(shí)現(xiàn),第一種方法較快,但有些復(fù)雜,速度上約為第二種的1.3倍,并對(duì)其中使用到的CUDA函數(shù)進(jìn)行了解說,各個(gè)文件內(nèi)容如下:
funset.cpp:
#include "funset.hpp"
#include <random>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <algorithm>
#include "common.hpp"
#include <opencv2/opencv.hpp>int test_matrix_mul()
{// Matrix multiplication: C = A * B// 矩陣A、B的寬、高應(yīng)是32的整數(shù)倍const int rowsA{ 352 }, colsA{ 672 }, rowsB = colsA, colsB{ 384 };std::unique_ptr<float[]> A(new float[colsA*rowsA]);std::unique_ptr<float[]> B(new float[colsB*rowsB]);std::unique_ptr<float[]> C1(new float[rowsA*colsB]);std::unique_ptr<float[]> C2(new float[rowsA*colsB]);generator_random_number(A.get(), colsA*rowsA, -1.f, 1.f);generator_random_number(B.get(), colsB*rowsB, -1.f, 1.f);float elapsed_time1{ 0.f }, elapsed_time2{ 0.f }; // millisecondsint ret = matrix_mul_cpu(A.get(), B.get(), C1.get(), colsA, rowsA, colsB, rowsB, &elapsed_time1);if (ret != 0) PRINT_ERROR_INFO(matrix_mul_cpu);ret = matrix_mul_gpu(A.get(), B.get(), C2.get(), colsA, rowsA, colsB, rowsB, &elapsed_time2);if (ret != 0) PRINT_ERROR_INFO(matrix_mul_gpu);int count{ 0 };for (int i = 0; i < rowsA*colsB; ++i) {if (count > 100) return -1;if (fabs(C1[i] - C2[i]) > EPS_) {fprintf(stderr, "Result verification failed at element %d, C1: %f, C2: %f\n",i, C1[i], C2[i]);++count;}}fprintf(stderr, "test matrix mul: cpu run time: %f ms, gpu run time: %f ms\n", elapsed_time1, elapsed_time2);return 0;
}
matrix_mul.cpp:
#include "funset.hpp"
#include <vector>
#include <chrono>
#include "common.hpp"int matrix_mul_cpu(const float* A, const float* B, float* C, int colsA, int rowsA, int colsB, int rowsB, float* elapsed_time)
{auto start = std::chrono::steady_clock::now();CHECK(colsA == rowsB);for (int y = 0; y < rowsA; ++y) {for (int x = 0; x < colsB; ++x) {float sum{ 0.f };for (int t = 0; t < colsA; ++t) {sum += A[y * colsA + t] * B[t * colsB + x];}C[y * colsB + x] = sum;}}auto end = std::chrono::steady_clock::now();auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);*elapsed_time = duration.count() * 1.0e-6;return 0;
}
matrix_mul.cu:
#include "funset.hpp"
#include <iostream>
#include <cuda_runtime.h> // For the CUDA runtime routines (prefixed with "cuda_")
#include <device_launch_parameters.h>
#include "common.hpp"// reference: C:\ProgramData\NVIDIA Corporation\CUDA Samples\v8.0\0_Simple\matrixMul
/* __global__: 函數(shù)類型限定符;在設(shè)備上運(yùn)行;在主機(jī)端調(diào)用,計(jì)算能力3.2及以上可以在
設(shè)備端調(diào)用;聲明的函數(shù)的返回值必須是void類型;對(duì)此類型函數(shù)的調(diào)用是異步的,即在
設(shè)備完全完成它的運(yùn)行之前就返回了;對(duì)此類型函數(shù)的調(diào)用必須指定執(zhí)行配置,即用于在
設(shè)備上執(zhí)行函數(shù)時(shí)的grid和block的維度,以及相關(guān)的流(即插入<<< >>>運(yùn)算符);
a kernel,表示此函數(shù)為內(nèi)核函數(shù)(運(yùn)行在GPU上的CUDA并行計(jì)算函數(shù)稱為kernel(內(nèi)核函
數(shù)),內(nèi)核函數(shù)必須通過__global__函數(shù)類型限定符定義);*/
template <int BLOCK_SIZE>
__global__ static void matrix_mul(const float* A, const float* B, float* C, int wA, int wB)
{/* gridDim: 內(nèi)置變量,用于描述線程網(wǎng)格的維度,對(duì)于所有線程塊來說,這個(gè)變量是一個(gè)常數(shù),用來保存線程格每一維的大小,即每個(gè)線程格中線程塊的數(shù)量.一個(gè)grid最多只有二維,為dim3類型;blockDim: 內(nèi)置變量,用于說明每個(gè)block的維度與尺寸.為dim3類型,包含了block在三個(gè)維度上的尺寸信息;對(duì)于所有線程塊來說,這個(gè)變量是一個(gè)常數(shù),保存的是線程塊中每一維的線程數(shù)量;blockIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程塊的索引;用于說明當(dāng)前thread所在的block在整個(gè)grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個(gè)block在grid中各個(gè)維度上的索引信息;threadIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程索引;用于說明當(dāng)前thread在block中的位置;如果線程是一維的可獲取threadIdx.x,如果是二維的還可獲取threadIdx.y,如果是三維的還可獲取threadIdx.z;為uint3類型,包含了一個(gè)thread在block中各個(gè)維度的索引信息 */// Block indexint bx = blockIdx.x;int by = blockIdx.y;// Thread indexint tx = threadIdx.x;int ty = threadIdx.y;// Index of the first sub-matrix of A processed by the blockint aBegin = wA * BLOCK_SIZE * by;// Index of the last sub-matrix of A processed by the blockint aEnd = aBegin + wA - 1;// Step size used to iterate through the sub-matrices of Aint aStep = BLOCK_SIZE;// Index of the first sub-matrix of B processed by the blockint bBegin = BLOCK_SIZE * bx;// Step size used to iterate through the sub-matrices of Bint bStep = BLOCK_SIZE * wB;// Csub is used to store the element of the block sub-matrix that is computed by the threadfloat Csub = 0;// Loop over all the sub-matrices of A and B required to compute the block sub-matrixfor (int a = aBegin, b = bBegin; a <= aEnd; a += aStep, b += bStep) {/* __shared__: 變量類型限定符;使用__shared__限定符,或者與__device__限定符連用,此時(shí)聲明的變量位于block中的共享存儲(chǔ)器空間中,與block具有相同的生命周期,僅可通過block內(nèi)的所有線程訪問;__shared__和__constant__變量默認(rèn)為是靜態(tài)存儲(chǔ);在__shared__前可以加extern關(guān)鍵字,但表示的是變量大小由執(zhí)行參數(shù)確定;__shared__變量在聲明時(shí)不能初始化;可以將CUDA C的關(guān)鍵字__shared__添加到變量聲明中,這將使這個(gè)變量駐留在共享內(nèi)存中;CUDA C編譯器對(duì)共享內(nèi)存中的變量與普通變量將分別采取不同的處理方式 */// Declaration of the shared memory array As used to store the sub-matrix of A__shared__ float As[BLOCK_SIZE][BLOCK_SIZE];// Declaration of the shared memory array Bs used to store the sub-matrix of B__shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];// Load the matrices from device memory to shared memory; each thread loads one element of each matrixAs[ty][tx] = A[a + wA * ty + tx];Bs[ty][tx] = B[b + wB * ty + tx];/* __syncthreads: 對(duì)線程塊中的線程進(jìn)行同步;CUDA架構(gòu)將確保,除非線程塊中的每個(gè)線程都執(zhí)行了__syncthreads(),否則沒有任何線程能執(zhí)行__syncthreads()之后的指令;在同一個(gè)block中的線程通過共享存儲(chǔ)器(sharedmemory)交換數(shù)據(jù),并通過柵欄同步(可以在kernel函數(shù)中需要同步的位置調(diào)用__syncthreads()函數(shù))保證線程間能夠正確地共享數(shù)據(jù);使用clock()函數(shù)計(jì)時(shí),在內(nèi)核函數(shù)中要測(cè)量的一段代碼的開始和結(jié)束的位置分別調(diào)用一次clock()函數(shù),并將結(jié)果記錄下來。由于調(diào)用__syncthreads()函數(shù)后,一個(gè)block中的所有thread需要的時(shí)間是相同的,因此只需要記錄每個(gè)block執(zhí)行需要的時(shí)間就行了,而不需要記錄每個(gè)thread的時(shí)間 */// Synchronize to make sure the matrices are loaded__syncthreads();/* reference:https://devblogs.nvidia.com/parallelforall/new-compiler-features-cuda-8/https://stackoverflow.com/questions/22278631/what-does-pragma-unroll-do-exactly-does-it-affect-the-number-of-threads/22279341編譯器默認(rèn)情況下將循環(huán)展開小的次數(shù),#pragma unroll能夠指定循環(huán)以多少次展開(程序員必須保證按這個(gè)展開是正確的),pragma unroll 后必須緊接著處理的循環(huán),可選擇在其后接一個(gè)數(shù)字,指定必須展開多少次循環(huán),#pragma unroll 1 表示禁止編譯器將循環(huán)展開。如果沒指定次數(shù),對(duì)于常數(shù)次的循環(huán),循環(huán)將完全展開,對(duì)于不確定次數(shù)的循環(huán),循環(huán)將不會(huì)展開。*/
#pragma unroll// Multiply the two matrices together; each thread computes one element of the block sub-matrixfor (int k = 0; k < BLOCK_SIZE; ++k) {Csub += As[ty][k] * Bs[k][tx];}// Synchronize to make sure that the preceding computation is done before loading two new// sub-matrices of A and B in the next iteration__syncthreads();}// Write the block sub-matrix to device memory; each thread writes one elementint c = wB * BLOCK_SIZE * by + BLOCK_SIZE * bx;C[c + wB * ty + tx] = Csub;
}__global__ static void matrix_mul(const float* A, const float* B, float* C, int colsA, int rowsA, int colsB, int rowsB)
{int x = threadIdx.x + blockIdx.x * blockDim.x;int y = threadIdx.y + blockIdx.y * blockDim.y;int offset = x + y * blockDim.x * gridDim.x;float sum{ 0.f };for (int t = 0; t < colsA; ++t) {sum += A[y * colsA + t] * B[t * colsB + x];}C[offset] = sum;
}int matrix_mul_gpu(const float* A, const float* B, float* C, int colsA, int rowsA, int colsB, int rowsB, float* elapsed_time)
{CHECK(colsA == rowsB);/* cudaEvent_t: CUDA event types,結(jié)構(gòu)體類型, CUDA事件,用于測(cè)量GPU在某個(gè)任務(wù)上花費(fèi)的時(shí)間,CUDA中的事件本質(zhì)上是一個(gè)GPU時(shí)間戳,由于CUDA事件是在GPU上實(shí)現(xiàn)的,因此它們不適于對(duì)同時(shí)包含設(shè)備代碼和主機(jī)代碼的混合代碼計(jì)時(shí)*/cudaEvent_t start, stop;// cudaEventCreate: 創(chuàng)建一個(gè)事件對(duì)象,異步啟動(dòng)cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),start記錄起始時(shí)間cudaEventRecord(start, 0);size_t lengthA{ colsA * rowsA * sizeof(float) }, lengthB{ colsB * rowsB * sizeof(float) };size_t lengthC{ rowsA * colsB * sizeof(float) };float *d_A{ nullptr }, *d_B{ nullptr }, *d_C{ nullptr };// cudaMalloc: 在設(shè)備端分配內(nèi)存cudaMalloc(&d_A, lengthA);cudaMalloc(&d_B, lengthB);cudaMalloc(&d_C, lengthC);/* cudaMemcpy: 在主機(jī)端和設(shè)備端拷貝數(shù)據(jù),此函數(shù)第四個(gè)參數(shù)僅能是下面之一:(1). cudaMemcpyHostToHost: 拷貝數(shù)據(jù)從主機(jī)端到主機(jī)端(2). cudaMemcpyHostToDevice: 拷貝數(shù)據(jù)從主機(jī)端到設(shè)備端(3). cudaMemcpyDeviceToHost: 拷貝數(shù)據(jù)從設(shè)備端到主機(jī)端(4). cudaMemcpyDeviceToDevice: 拷貝數(shù)據(jù)從設(shè)備端到設(shè)備端(5). cudaMemcpyDefault: 從指針值自動(dòng)推斷拷貝數(shù)據(jù)方向,需要支持統(tǒng)一虛擬尋址(CUDA6.0及以上版本)cudaMemcpy函數(shù)對(duì)于主機(jī)是同步的 */cudaMemcpy(d_A, A, lengthA, cudaMemcpyHostToDevice);cudaMemcpy(d_B, B, lengthB, cudaMemcpyHostToDevice);//cudaMemcpy(d_C, C, lengthC, cudaMemcpyHostToDevice);const int block_size{ 32 };/* dim3: 基于uint3定義的內(nèi)置矢量類型,相當(dāng)于由3個(gè)unsigned int類型組成的結(jié)構(gòu)體,可表示一個(gè)三維數(shù)組,在定義dim3類型變量時(shí),凡是沒有賦值的元素都會(huì)被賦予默認(rèn)值1 */dim3 dimsA(colsA, rowsA, 1);dim3 dimsB(colsB, rowsB, 1);CHECK(dimsA.x == dimsB.y);//fprintf(stderr, "MatrixA(%d,%d), MatrixB(%d,%d)\n", dimsA.x, dimsA.y, dimsB.x, dimsB.y);dim3 threads(block_size, block_size);dim3 grid(dimsB.x / threads.x, dimsA.y / threads.y);/* <<< >>>: 為CUDA引入的運(yùn)算符,指定線程網(wǎng)格和線程塊維度等,傳遞執(zhí)行參數(shù)給CUDA編譯器和運(yùn)行時(shí)系統(tǒng),用于說明內(nèi)核函數(shù)中的線程數(shù)量,以及線程是如何組織的;尖括號(hào)中這些參數(shù)并不是傳遞給設(shè)備代碼的參數(shù),而是告訴運(yùn)行時(shí)如何啟動(dòng)設(shè)備代碼,傳遞給設(shè)備代碼本身的參數(shù)是放在圓括號(hào)中傳遞的,就像標(biāo)準(zhǔn)的函數(shù)調(diào)用一樣;不同計(jì)算能力的設(shè)備對(duì)線程的總數(shù)和組織方式有不同的約束;必須先為kernel中用到的數(shù)組或變量分配好足夠的空間,再調(diào)用kernel函數(shù),否則在GPU計(jì)算時(shí)會(huì)發(fā)生錯(cuò)誤,例如越界等;使用運(yùn)行時(shí)API時(shí),需要在調(diào)用的內(nèi)核函數(shù)名與參數(shù)列表直接以<<<Dg,Db,Ns,S>>>的形式設(shè)置執(zhí)行配置,其中:Dg是一個(gè)dim3型變量,用于設(shè)置grid的維度和各個(gè)維度上的尺寸.設(shè)置好Dg后,grid中將有Dg.x*Dg.y個(gè)block,Dg.z必須為1;Db是一個(gè)dim3型變量,用于設(shè)置block的維度和各個(gè)維度上的尺寸.設(shè)置好Db后,每個(gè)block中將有Db.x*Db.y*Db.z個(gè)thread;Ns是一個(gè)size_t型變量,指定各塊為此調(diào)用動(dòng)態(tài)分配的共享存儲(chǔ)器大小,這些動(dòng)態(tài)分配的存儲(chǔ)器可供聲明為外部數(shù)組(extern __shared__)的其他任何變量使用;Ns是一個(gè)可選參數(shù),默認(rèn)值為0;S為cudaStream_t類型,用于設(shè)置與內(nèi)核函數(shù)關(guān)聯(lián)的流.S是一個(gè)可選參數(shù),默認(rèn)值0. */matrix_mul<block_size> <<< grid, threads >>>(d_A, d_B, d_C, dimsA.x, dimsB.x); // 運(yùn)行較快//matrix_mul<< < grid, threads >> >(d_A, d_B, d_C, colsA, rowsA, colsB, rowsB);/* cudaDeviceSynchronize: kernel的啟動(dòng)是異步的, 為了定位它是否出錯(cuò), 一般需要加上cudaDeviceSynchronize函數(shù)進(jìn)行同步; 將會(huì)一直處于阻塞狀態(tài),直到前面所有請(qǐng)求的任務(wù)已經(jīng)被全部執(zhí)行完畢,如果前面執(zhí)行的某個(gè)任務(wù)失敗,將會(huì)返回一個(gè)錯(cuò)誤;當(dāng)程序中有多個(gè)流,并且流之間在某一點(diǎn)需要通信時(shí),那就必須在這一點(diǎn)處加上同步的語句,即cudaDeviceSynchronize;異步啟動(dòng)reference: https://stackoverflow.com/questions/11888772/when-to-call-cudadevicesynchronize *///cudaDeviceSynchronize();cudaMemcpy(C, d_C, lengthC, cudaMemcpyDeviceToHost);// cudaFree: 釋放設(shè)備上由cudaMalloc函數(shù)分配的內(nèi)存cudaFree(d_A);cudaFree(d_B);cudaFree(d_C);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),stop記錄結(jié)束時(shí)間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個(gè)事件完成,異步啟動(dòng)cudaEventSynchronize(stop);// cudaEventElapseTime: 計(jì)算兩個(gè)事件之間經(jīng)歷的時(shí)間,單位為毫秒,異步啟動(dòng)cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷毀事件對(duì)象,異步啟動(dòng)cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}
執(zhí)行結(jié)果如下:
GitHub:https://github.com/fengbingchun/CUDA_Test
總結(jié)
以上是生活随笔為你收集整理的CUDA Samples: matrix multiplication(C = A * B)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CUDA Samples: dot pr
- 下一篇: CUDA Samples: 获取设备属性