c - 使用 CUDA 的矩阵乘法

标签 c cuda

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

除了 0 的不稳定结果外,“Width”(下面的代码)的最大大小甚至不是 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);
}

最佳答案

在这一点之前你做得很好:

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

我将其更改为 %f(因为它是一个 float )并且它们都打印得很好 :)

$ ./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

关于c - 使用 CUDA 的矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5021930/

相关文章:

c - 理解编程中的位运算符左移和右移函数的麻烦

c - 如何正确分配结构体和某些变量?

c - 如何推广方阵乘法来处理任意维度

c - C 中 strcat() 的段错误

c - 我们如何知道一个 bzip2 block 的未压缩数据的大小?

c - 如何用用户输入值填充 C 中的二维数组?

image-processing - CUDA 纹理缓存似乎有错误的数据?

python - 在 Tensorflow 中添加 GPU Op

functional-programming - 对GPU的纯函数式编程

带有 CUDA : registerPageLocked fails 的 OpenCV 2.4.4