chundoong-lab-ta/SamsungDS22/submissions/HW4/yd99.park/mat_mul.cpp

92 lines
2.5 KiB
C++

#include "mat_mul.h"
#include "util.h"
#include <cstdio>
#include <cstdlib>
#include <mpi.h>
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
static int mpi_rank, mpi_world_size;
#define ISIZE (24)
#define JSIZE (1024)
#define KSIZE (1024)
#define min(a,b) ((a)>(b) ? (b) : (a))
static void mat_mul_omp() {
float ar;
#pragma omp parallel for num_threads(num_threads)
for (int ii = 0; ii < M; ii += ISIZE) {
for (int jj = 0; jj < N; jj += JSIZE) {
for (int kk = 0; kk < K; kk += KSIZE) {
for (int k = kk; k < min(kk+KSIZE,K); k++) {
for (int i = ii; i < min(ii+ISIZE,M); i++) {
ar = A[i * K + k];
for (int j = jj; j < min(jj+JSIZE,N); j++) {
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
// FIXME: for now, only root process runs the matrix multiplication.
MPI_Status status;
int SrtP[mpi_world_size] = {0,};
int EndP[mpi_world_size] = {0,};
int DivS[mpi_world_size] = {0,};
for(int i = 0; i < mpi_world_size; ++i) {
if(i != 0) SrtP[i] = M / mpi_world_size * i + min(i, M % mpi_world_size);
EndP[i] = M / mpi_world_size * (i + 1) + min(i + 1, M % mpi_world_size);
DivS[i] = EndP[i] - SrtP[i];
}
if (mpi_rank == 0)
{
for(int i = 1; i < mpi_world_size; ++i) {
MPI_Send(&A[SrtP[i]*K], DivS[i]*K, MPI_FLOAT, i, 0, MPI_COMM_WORLD);
MPI_Send(B, (K*N), MPI_FLOAT, i, 0, MPI_COMM_WORLD);
}
M = DivS[mpi_rank];
mat_mul_omp();
for(int i = 1; i < mpi_world_size; ++i) {
MPI_Recv(&C[SrtP[i]*N], DivS[i]*N, MPI_FLOAT, i, 0, MPI_COMM_WORLD, &status);
}
}
if (mpi_rank != 0)
{
alloc_mat(&A, DivS[mpi_rank], K);
alloc_mat(&B, K, N);
alloc_mat(&C, DivS[mpi_rank], N);
zero_mat(C, DivS[mpi_rank], N);
MPI_Recv(A, DivS[mpi_rank]*K, MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &status);
MPI_Recv(B, (K*N), MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &status);
M=DivS[mpi_rank];
mat_mul_omp();
MPI_Send(C, DivS[mpi_rank]*N, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);
}
}