tipe/src/cnn/matrix_multiplication.cu

62 lines
1.8 KiB
Plaintext
Raw Normal View History

2022-10-14 15:45:47 +02:00
#include <stdlib.h>
#include <stdio.h>
2022-10-14 17:54:12 +02:00
#include <stdbool.h>
2022-10-14 15:45:47 +02:00
#include "../include/colors.h"
#include "../include/utils.h"
2022-10-14 15:45:47 +02:00
#define BLOCKSIZE_x 16
#define BLOCKSIZE_y 16
#ifdef __CUDACC__
2023-01-28 22:04:38 +01:00
__global__ void matrix_mul_kernel(float** Md, float** Nd, float** Pd, int n, int p, int q) {
// Chaque thread calcule toutes les multiplications utilisant l'élément Nd[tx][ty]
int tx = (blockIdx.x*blockDim.x) + threadIdx.x; // Indice de colonne
int ty = (blockIdx.y*blockDim.y) + threadIdx.y; // Indice de ligne
2022-10-19 13:05:59 +02:00
if (tx >= p || ty >= q) {
2022-10-19 13:05:59 +02:00
return;
}
for (int i = 0; i < n; i++) {
2023-01-28 22:04:38 +01:00
atomicAdd(&(Pd[i][ty]), Md[i][tx]*Nd[tx][ty]);
// P[i][ty] += P[i][tx] * N[tx][ty]
2022-10-14 15:45:47 +02:00
}
}
2022-10-14 17:54:12 +02:00
void matrix_multiplication_device(float** m1, float** m2, float** result, int n, int p, int q) {
2022-10-14 15:45:47 +02:00
// Traitement
dim3 gridSize(i_div_up(p, BLOCKSIZE_x), i_div_up(q, BLOCKSIZE_y));
2022-10-14 19:56:39 +02:00
dim3 blockSize(BLOCKSIZE_x, BLOCKSIZE_y);
2022-10-14 15:45:47 +02:00
2023-01-28 22:04:38 +01:00
matrix_mul_kernel<<<gridSize, blockSize>>>(m1, m2, result, n, p, q);
2022-10-14 15:45:47 +02:00
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );
}
2022-10-14 17:54:12 +02:00
#endif
void matrix_multiplication_host(float** m1, float** m2, float** result, int n, int p, int q) {
2022-10-14 15:45:47 +02:00
for (int i=0; i < n; i++) {
for (int j=0; j < q; j++) {
2022-10-14 17:54:12 +02:00
result[i][j] = 0.;
2022-10-14 15:45:47 +02:00
for (int k=0; k < p; k++) {
2022-10-14 18:17:29 +02:00
result[i][j] += m1[i][k] * m2[k][j];
2022-10-14 15:45:47 +02:00
}
}
}
}
2022-10-14 17:54:12 +02:00
void matrix_multiplication(float** m1, float** m2, float** result, int n, int p, int q, bool use_cuda) {
#ifdef __CUDACC__
if (use_cuda) {
matrix_multiplication_device(m1, m2, result, n, p, q);
} else {
matrix_multiplication_host(m1, m2, result, n, p, q);
}
#else
matrix_multiplication_host(m1, m2, result, n, p, q);
#endif
2022-10-14 15:45:47 +02:00
}