欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

深度学习operation: matmul之NV shader实现

程序员文章站 2022-03-10 16:51:13
最近工作需要写shader,决定开个新坑,我写过的shader都会在后续文章公开。写shader还是有必要了解一下NV GPU的硬件建构,至少知道device代码运行时的物理地址映射,CPU程序运行时有堆和栈的概念,而NV GPU 运行时是不同的,例如CPU c++ 函数内局部变量放在栈里,但NV GPU c++函数局部变量放在相应的SP寄存器里,特别是要写出高性能shader,往往需要对针对特定硬件架构做优化。此实现利用了share memory做加速。下面是工程结构:build.shnvcc...

最近工作需要写shader,决定开个新坑,我写过的shader都会在后续文章公开。
写shader还是有必要了解一下NV GPU的硬件建构,至少知道device代码运行时的物理地址映射,CPU程序运行时有堆和栈的概念,而NV GPU 运行时是不同的,例如CPU c++ 函数内局部变量放在栈里,但NV GPU c++函数局部变量放在相应的SP寄存器里,特别是要写出高性能shader,往往需要对针对特定硬件架构做优化。
此实现利用了share memory做加速。
下面是工程结构:

深度学习operation: matmul之NV shader实现
build.sh

nvcc -x cu matmul.cu -o matmul

kernels.h

#ifndef KERNELS_H
#define KERNELS_H
#include "kernels.cu"
#endif

kernels.cu

#include <cuda_runtime.h>
#include <device_launch_parameters.h>

#define BLOCK_SIZE 16

// Matrices are stored in row-major order:
// M(row, col) = *(M.elements + row * M.stride + col)
typedef struct {
    int width;
    int height;
    int stride; 
    float* elements;
} Matrix;

// Get a matrix element
__device__ float GetElement(const Matrix A, int row, int col)
{
    return A.elements[row * A.stride + col];
}

// Set a matrix element
__device__ void SetElement(Matrix A, int row, int col,
                           float value)
{
    A.elements[row * A.stride + col] = value;
}

// Get the BLOCK_SIZExBLOCK_SIZE sub-matrix Asub of A that is
// located col sub-matrices to the right and row sub-matrices down
// from the upper-left corner of A
 __device__ Matrix GetSubMatrix(Matrix A, int row, int col) 
{
	//row = 1, col = 2;
    Matrix Asub;
    Asub.width    = BLOCK_SIZE;
    Asub.height   = BLOCK_SIZE;
    Asub.stride   = A.stride;
    Asub.elements = &A.elements[A.stride * BLOCK_SIZE * row
                                         + BLOCK_SIZE * col];
    return Asub;
}

// Thread block size


// Forward declaration of the matrix multiplication kernel
__global__ void MatMulKernel(const Matrix, const Matrix, Matrix);


// Matrix multiplication kernel called by MatMul()
 __global__ void MatMulKernel(const Matrix A, const Matrix B, Matrix C)
{
    // Block row and column
    int blockRow = blockIdx.y;
    int blockCol = blockIdx.x;

    // Each thread block computes one sub-matrix Csub of C
    Matrix Csub = GetSubMatrix(C, blockRow, blockCol);

    // Each thread computes one element of Csub
    // by accumulating results into Cvalue
    float Cvalue = 0;

    // Thread row and column within Csub
    int row = threadIdx.y;
    int col = threadIdx.x;

    // Loop over all the sub-matrices of A and B that are
    // required to compute Csub
    // Multiply each pair of sub-matrices together
    // and accumulate the results
    for (int m = 0; m < (A.width / BLOCK_SIZE); ++m) {

        // Get sub-matrix Asub of A
        Matrix Asub = GetSubMatrix(A, blockRow, m);

        // Get sub-matrix Bsub of B
        Matrix Bsub = GetSubMatrix(B, m, blockCol);

        // Shared memory used to store Asub and Bsub respectively
        __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
        __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];

        // Load Asub and Bsub from device memory to shared memory
        // Each thread loads one element of each sub-matrix
        As[row][col] = GetElement(Asub, row, col);
        Bs[row][col] = GetElement(Bsub, row, col);

        // Synchronize to make sure the sub-matrices are loaded
        // before starting the computation
        __syncthreads();
        // Multiply Asub and Bsub together
        for (int e = 0; e < BLOCK_SIZE; ++e)
            Cvalue += As[row][e] * Bs[e][col];

        // 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 Csub to device memory
    // Each thread writes one element
    SetElement(Csub, row, col, Cvalue);
}

matmul.cu

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>

#include "kernels.h"

#define BLOCK_SIZE 16

int GenerateRandInt(int min, int max, int counter)
{
    srand(((int)time(0)) + counter);
    return (rand()%(max - min + 1) + min);
}


// Matrix multiplication - Host code
// Matrix dimensions are assumed to be multiples of BLOCK_SIZE
void MatMul(const Matrix A, const Matrix B, Matrix C)
{
    // Load A and B to device memory
    Matrix d_A;
    d_A.width = d_A.stride = A.width; d_A.height = A.height;
    size_t size = A.width * A.height * sizeof(float);
    cudaMalloc(&d_A.elements, size);
    cudaMemcpy(d_A.elements, A.elements, size,
               cudaMemcpyHostToDevice);
    Matrix d_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);

    // Allocate C in device memory
    Matrix d_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);

    // Invoke kernel
    dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
    dim3 dimGrid(B.width / dimBlock.x, A.height / dimBlock.y);
    MatMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C);

    // Read C from device memory
    cudaMemcpy(C.elements, d_C.elements, size,
               cudaMemcpyDeviceToHost);

    // Free device memory
    cudaFree(d_A.elements);
    cudaFree(d_B.elements);
    cudaFree(d_C.elements);
}

int main(int argc, char** argv)
{
    int size_A = BLOCK_SIZE*2*BLOCK_SIZE*3;
    float matrix_A[size_A];
    std::cout<<"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<<std::endl;
    for(int i=0; i<size_A; i++)
    {   
        matrix_A[i] = (float)GenerateRandInt(1,100,i);
        std::cout<<matrix_A[i]<<", ";
    }
    std::cout<<std::endl;
    Matrix A;
    A.height = BLOCK_SIZE*2;
    A.width = BLOCK_SIZE*3;
    A.elements = matrix_A;

    int size_B = BLOCK_SIZE*3*BLOCK_SIZE*4;
    float matrix_B[size_B];
    std::cout<<"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"<<std::endl;
    for(int i=0; i<size_B; i++)
    {   
        matrix_B[i] = (float)GenerateRandInt(1,100,i);
        std::cout<<matrix_B[i]<<", ";
    }
    std::cout<<std::endl;
    Matrix B;
    B.height = BLOCK_SIZE*3;
    B.width = BLOCK_SIZE*4;
    B.elements = matrix_B;

    int size_C = BLOCK_SIZE*2*BLOCK_SIZE*4;
    float matrix_C[size_C];
    Matrix C;
    C.height = BLOCK_SIZE*3;
    C.width = BLOCK_SIZE*4;
    C.elements = matrix_C;

    MatMul(A,B,C);

    std::cout<<"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"<<std::endl;
    for(int i=0; i<size_C; i++)
    {   
        std::cout<<C.elements[i]<<", ";
    }
    std::cout<<std::endl;

    return 0;
}

本文地址:https://blog.csdn.net/qq_33345917/article/details/107578989