使用CUDA的矩阵乘法

时间:2011-02-16 20:49:57

标签: c cuda

我对CUDA上的矩阵乘法感到震惊。得到的乘积矩阵始终为零。我已经阅读了一些示例代码,例如matrix multiplication in cuda来解决我的问题,但都是徒劳的。

除了0的不稳定结果外,“宽度”(下面的代码)的最大大小甚至不是512.我无法调试问题所在。也许我们可以在StackOverflow上讨论它。

我指的是“编程大规模并行处理器”

#include<cuda.h>
#include<stdio.h>

int main(void) {
    void MatrixMultiplication(float *, float *, float *, int);
    const int Width = 5;
    float M[Width*Width], N[Width*Width], P[Width*Width];
    for(int i = 0; i < (Width*Width) ; i++) {
        M[i] = 5;
        N[i] = 5;
        P[i] = 0;
    }
    MatrixMultiplication(M, N, P, Width);
    for(int i = 0; i < (Width*Width) ; i++) {
        printf("%d \n", P[i]);
    }
    int quit;
    scanf("%d",&quit);
    return 0;
}

//Matrix multiplication kernel - thread specification
__global__ void MatrixMulKernel(float *Md, float *Nd, float *Pd, int Width) {
    //2D Thread ID
    int tx = threadIdx.x;
    int ty = threadIdx.y;

    //Pvalue stores the Pd element that is computed by the thread
    float Pvalue = 0;

    for(int k = 0; k < Width ; ++k) {
        float Mdelement = Md[ty*Width + k];
        float Ndelement = Nd[k*Width + tx];
        Pvalue += (Mdelement*Ndelement);
    }

    Pd[ty*Width + tx] = Pvalue;
}

void MatrixMultiplication(float *M, float *N, float *P, int Width) {
    int size = Width*Width*sizeof(float);
    float *Md, *Nd, *Pd;

    //Transfer M and N to device memory
    cudaMalloc((void**)&Md, size);
    cudaMemcpy(Md,M,size,cudaMemcpyHostToDevice);
    cudaMalloc((void**)&Nd, size);
    cudaMemcpy(Nd,N,size,cudaMemcpyHostToDevice);

    //Allocate P on the device
    cudaMalloc((void**)&Pd,size);

    //Setup the execution configuration
    dim3 dimBlock(Width,Width);
    dim3 dimGrid(1,1);

    //Launch the device computation threads!
    MatrixMulKernel<<<dimGrid,dimBlock>>>(Md,Nd,Pd,Width);

    //Transfer P from device to host
    cudaMemcpy(P,Pd,size,cudaMemcpyDeviceToHost);

    //Free device matrices
    cudaFree(Md);
    cudaFree(Nd);
    cudaFree(Pd);
}

3 个答案:

答案 0 :(得分:4)

到目前为止你做得很好:

for(int i = 0; i < (Width*Width) ; i++) {
    printf("%d \n", P[i]);
}

我将它改为%f(因为它是一个浮点数)并且它们都打印得很好:)

$ ./test.exe
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000
125.000000

答案 1 :(得分:1)

我弄清楚出了什么问题。我们来分析一下:

第1点:寻求消除单调的“零值”

如上所述,您必须将 printf("%d \n", P[i]); 替换为 printf("%f \n", P[i]);

第2点:为什么程序失败的值为宽度512?

实际上即使像23这样的小值也会失败。为什么?因为23 * 23是> 512(截至今天,GPU每块可以拥有的最大线程数!)

答案 2 :(得分:0)

在你的MatrixMulKernel函数中,你的for循环就像

for(int k = 0; k < Width ; ++k) 
{
    //rest of code      
}

而不是Width,您必须使用Width*Width,因为您的数组大小为Width*Width