I'm a beginner in CUDA
. I am writing a program to multiply two matrices without using shared memory. Here's my program where I multiply 4x4 matrices filled with 1
.
The output is 26853932
where the correct output should be 4
.
Can someone please tell me where I am wrong. Maybe I've made a very naive mistake?
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include<stdlib.h>
//kernel deifnition
__global__ void mulKernel(int *d_M, int *d_N, int *d_P,int width)
{
int row = blockIdx.y*blockDim.y + threadIdx.y;
int col = blockIdx.x*blockDim.x + threadIdx.x;
if (row < width && col < width)
{
int pvalue=0;
for (int k = 0; k < width; k++)
{
pvalue = pvalue + (d_M[row*width + k] * d_N[k*width + col]);
}
d_P[row*width + col] = pvalue;
}
}
int main()
{
const int block_size = 2;
const int array_width = 4;
int h_M[array_width][array_width] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int h_N[array_width][array_width] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int h_P[array_width][array_width];
int size = array_width*array_width*(sizeof(int));
int *d_M, *d_N, *d_P;
//memory allocation
cudaMalloc((void**)&d_M, size);
cudaMalloc((void**)&d_N, size);
cudaMalloc((void**)&d_P, size);
//copy data from host to memory
cudaMemcpy(d_M, h_M, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_N, h_N, size, cudaMemcpyHostToDevice);
dim3 grid(array_width/block_size, array_width/block_size, 0); //grid size
dim3 block(block_size, block_size, 0); //block size
mulKernel << <grid, block >> >(d_M,d_N,d_P,array_width);
cudaMemcpy(h_P, d_P, size, cudaMemcpyDeviceToHost);
printf("%d", h_P[0][0]);
printf("Press enter to exit....\n");
getchar();
}