将结构复制到设备内存CUDA

时间:2016-11-09 09:10:55

标签: c++ cuda

我是CUDA的新手,并通过了CUDA工具包文档。在那里我找到了一个矩阵乘法使用共享内存的例子。在将Matrix结构从主机存储器复制到设备存储器时,仅复制数据元素。我无法理解的是如何将其他变量复制到设备内存中。

矩阵结构如下

typedef struct {
    int width;
    int height;
    int stride; 
    float* elements;
} Matrix;

然后是数据传输发生的代码示例

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);
}

这里我不明白的是宽度,步幅和高度是如何复制到设备内存的。因为这里的cudaMalloc和cudaMemcpy仅用于元素。在理解这一点时,我有什么遗漏。

核心代码

__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) 
{
    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;
}

矩阵乘法核算法

__global__ void MatMulKernel(Matrix A, 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);
}

1 个答案:

答案 0 :(得分:2)

对于那些想知道的人,我们讨论的示例代码在Nvidia的CUDA工具包文档中,在共享内存主题中: CUDA C Programming guide : Shared memory

那么,为什么这个样本有效呢? 是的,通过使用cudaMalloc和cudaMemcpy函数,只在设备端发送“elements”数组。 是的,矩阵维度在设备端的内核中使用,而不是使用cudaMemcpy显式复制到设备内存。

您需要以相同的方式考虑数组和参数。让我解释一下如何将这些值发送到内核。

  1. 我们在CPU端声明矩阵,所有成员都未初始化
  2. 我们分配尺寸,指针仍然未初始化
  3. 我们使用API​​函数在设备端分配和复制内存,指针已初始化,但它以设备内存为目标,无法像常规主机阵列一样使用
  4. 我们将矩阵作为参数提供给内核。不是通过指针,而是通过值。
  5. 这就是诀窍。完整的结构实例作为参数给出,它包含:

    1. 三个整数,矩阵的维数
    2. 指向包含矩阵数据的数组的指针
    3. 在内核启动中将整数作为参数显然是可行的,并且它可以正常工作。 也可以将指针指向数组:指针被复制,这意味着我们创建另一个指向内存中同一区域的指针。如果我们所针对的数组是在主机内存上,它会导致错误,但是因为它已经在设备端使用API​​函数进行了初始化,所以它可以正常工作。