100 lines
2.5 KiB
C++
100 lines
2.5 KiB
C++
|
#include "mat_mul.h"
|
||
|
#include "util.h"
|
||
|
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <mpi.h>
|
||
|
#include <omp.h>
|
||
|
|
||
|
static float *A, *B, *C;
|
||
|
static int M, N, K;
|
||
|
static int num_threads;
|
||
|
static int mpi_rank, mpi_world_size;
|
||
|
|
||
|
static int min(int x, int y) {
|
||
|
return x < y ? x : y;
|
||
|
}
|
||
|
|
||
|
#define ITILESIZE (32)
|
||
|
#define JTILESIZE (1024)
|
||
|
#define KTILESIZE (1024)
|
||
|
|
||
|
static void mat_mul_omp() {
|
||
|
// TODO: parallelize & optimize matrix multiplication
|
||
|
// Use num_threads per node
|
||
|
#pragma omp parallel num_threads(num_threads) shared(A,B,C)
|
||
|
{
|
||
|
int tid = omp_get_thread_num();
|
||
|
int is = M / num_threads * tid + min(tid, M % num_threads);
|
||
|
int ie = M / num_threads * (tid + 1) + min(tid + 1, M % num_threads);
|
||
|
|
||
|
for (int ii = is; ii < ie; ii += ITILESIZE) {
|
||
|
for (int jj = 0; jj < N; jj += JTILESIZE) {
|
||
|
for (int kk = 0; kk < K; kk += KTILESIZE) {
|
||
|
|
||
|
for (int k = kk; k < min(K, kk + KTILESIZE); k++) {
|
||
|
for (int i = ii; i < min(ie, ii + ITILESIZE); i++) {
|
||
|
float ar = A[i * K + k];
|
||
|
for (int j = jj; j < min(N, jj + JTILESIZE); j+=1) {
|
||
|
C[i * N + j] += ar * B[k * N + j];
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void mat_mul(float *_A, float *_B, float *_C, int _M, int _N, int _K,
|
||
|
int _num_threads, int _mpi_rank, int _mpi_world_size) {
|
||
|
A = _A, B = _B, C = _C;
|
||
|
M = _M, N = _N, K = _K;
|
||
|
num_threads = _num_threads, mpi_rank = _mpi_rank,
|
||
|
mpi_world_size = _mpi_world_size;
|
||
|
|
||
|
// TODO: parallelize & optimize matrix multiplication on multi-node
|
||
|
// You must allocate & initialize A, B, C for non-root processes
|
||
|
|
||
|
int tag = 0;
|
||
|
MPI_Comm comm = MPI_COMM_WORLD;
|
||
|
MPI_Status stat;
|
||
|
|
||
|
int rows = M/mpi_world_size;
|
||
|
int res = M%mpi_world_size;
|
||
|
|
||
|
if(mpi_rank == 0) {
|
||
|
int offset = rows + res;
|
||
|
for(int i=1; i<mpi_world_size; i++){
|
||
|
MPI_Send(&A[offset*K], rows*K, MPI_FLOAT, i, tag, comm);
|
||
|
MPI_Send(B, K*N, MPI_FLOAT, i, tag, comm);
|
||
|
offset = offset + rows;
|
||
|
}
|
||
|
|
||
|
M = rows + res;
|
||
|
mat_mul_omp();
|
||
|
M = _M;
|
||
|
|
||
|
offset = rows + res;
|
||
|
for(int i=1; i<mpi_world_size; i++) {
|
||
|
MPI_Recv(&C[offset*N], rows*N, MPI_FLOAT, i, tag, comm, &stat);
|
||
|
offset = offset + rows;
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
M = rows;
|
||
|
|
||
|
alloc_mat(&A, M, K);
|
||
|
alloc_mat(&B, K, N);
|
||
|
MPI_Recv(A, M*K, MPI_FLOAT, 0, tag, comm, &stat);
|
||
|
MPI_Recv(B, K*N, MPI_FLOAT, 0, tag, comm, &stat);
|
||
|
|
||
|
alloc_mat(&C, M, N);
|
||
|
zero_mat(C, M, N);
|
||
|
|
||
|
mat_mul_omp();
|
||
|
|
||
|
MPI_Send(C, M*N, MPI_FLOAT, 0, tag, comm);
|
||
|
}
|
||
|
}
|