chundoong-lab-ta/SamsungDS22/submissions/HW4/ih0503.choo/mat_mul.cpp

107 lines
2.7 KiB
C++
Raw Normal View History

2022-09-29 18:01:45 +09:00
#include "mat_mul.h"
#include "util.h"
#include <cstdio>
#include <cstdlib>
#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 count;
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_op(){
int tid, is, ie;
#pragma omp parallel num_threads(num_threads) private(tid, is, ie)
{
tid = omp_get_thread_num();;
is = count / num_threads * tid + min(tid, count % num_threads);
ie = count / num_threads * (tid + 1) + min(tid + 1, count % 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];
}
}
}
}
}
}
}
return NULL;
}
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;
MPI_Status status;
// 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.
int offset = (M / mpi_world_size) + 1;
int is = mpi_rank * offset;
int ie = min(is + offset, M);
count = ie - is;
if (mpi_rank == 0) {
int s, e, c;
for (int i = 1; i < mpi_world_size; i++) {
s = i * offset;
e = min(s + offset, M);
c = e - s;
if (c > 0) {
MPI_Send(&A[s * K + 0], c * K, MPI_FLOAT, i, i, MPI_COMM_WORLD);
MPI_Send(B, K * N, MPI_FLOAT, i, i, MPI_COMM_WORLD);
MPI_Send(C, c * N, MPI_FLOAT, i, i, MPI_COMM_WORLD);
}
}
mat_mul_op();
for (int i = 1; i < mpi_world_size; i++) {
s = i * offset;
e = min(s + offset, M);
c = e - s;
if (c > 0) {
MPI_Recv(&C[s * N + 0], c * N, MPI_FLOAT, i, 0, MPI_COMM_WORLD, &status);
}
}
} else {
if (count > 0) {
alloc_mat(&A, count, K);
alloc_mat(&B, K, N);
alloc_mat(&C, count, N);
MPI_Recv(A, count * K, MPI_FLOAT, 0, mpi_rank, MPI_COMM_WORLD, &status);
MPI_Recv(B, K * N, MPI_FLOAT, 0, mpi_rank, MPI_COMM_WORLD, &status);
MPI_Recv(C, count * N, MPI_FLOAT, 0, mpi_rank, MPI_COMM_WORLD, &status);
mat_mul_op();
MPI_Send(C, count * N, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);
}
}
}