chundoong-lab-ta/SamsungDS22/submissions/HW4/taekyung.yeo/mat_mul.cpp

99 lines
2.8 KiB
C++

#include "mat_mul.h"
#include <cstdio>
#include <cstdlib>
#include <mpi.h>
#include "util.h"
#include <immintrin.h>
#define MASTER 0
#define FROM_MASTER 1
#define FROM_WORKER 2
#define ITILESIZE (32)
#define JTILESIZE (1024)
#define KTILESIZE (1024)
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
static int mpi_rank, mpi_world_size;
MPI_Request request;
MPI_Status status;
static int min(int x, int y) {
return x < y ? x : y;
}
static void mat_mul_omp() {
// TODO: parallelize & optimize matrix multiplication
// Use num_threads per node
#pragma omp parallel for num_threads(num_threads)
for (int ii = 0; ii < M; 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(M, 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 base = M / mpi_world_size;
int extra = M % mpi_world_size;
int offset;
if (mpi_rank== 0) { //Master
offset = base + extra;
M = offset;
for(int node=1; node < mpi_world_size; node++) {
MPI_Isend(&offset, 1, MPI_INT, node, FROM_MASTER, MPI_COMM_WORLD, &request);
MPI_Isend(&A[offset*K], base*K, MPI_FLOAT, node, FROM_MASTER, MPI_COMM_WORLD, &request);
MPI_Isend(B, K*N, MPI_FLOAT, node, FROM_MASTER, MPI_COMM_WORLD, &request);
offset = offset + base;
}
mat_mul_omp();
for(int node=1; node < mpi_world_size; node++) {
MPI_Recv(&offset, 1, MPI_INT, node, FROM_WORKER, MPI_COMM_WORLD, &status);
MPI_Recv(&C[offset*N], base*N, MPI_FLOAT, node, FROM_WORKER, MPI_COMM_WORLD, &status);
}
} //if(mpi_rank==0)
else { //Worker
alloc_mat(&A, base, K);
alloc_mat(&B, K, N);
alloc_mat(&C, base, N);
zero_mat(C ,base, N);
MPI_Recv(&offset, 1, MPI_INT, MASTER, FROM_MASTER, MPI_COMM_WORLD ,&status);
MPI_Recv(A, base*K, MPI_FLOAT, MASTER, FROM_MASTER, MPI_COMM_WORLD, &status);
MPI_Recv(B, K*N, MPI_FLOAT, MASTER, FROM_MASTER, MPI_COMM_WORLD, &status);
M = base;
mat_mul_omp();
MPI_Isend(&offset, 1, MPI_INT, MASTER, FROM_WORKER, MPI_COMM_WORLD ,&request);
MPI_Isend(C, base*N, MPI_FLOAT, MASTER ,FROM_WORKER, MPI_COMM_WORLD, &request);
} //else
}