chundoong-lab-ta/SamsungDS22/submissions/HW4/yh1597.yang/mat_mul.cpp

92 lines
2.8 KiB
C++

#include "mat_mul.h"
#include <cstdio>
#include <cstdlib>
#include <mpi.h>
#include "util.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;
}
static void mat_mul_omp() {
// TODO: parallelize & optimize matrix multiplication
// Use num_threads per node
int tid = mpi_rank;
int is = M / mpi_world_size * tid + min(tid, M % mpi_world_size);
int ie = M / mpi_world_size * (tid + 1) + min(tid + 1, M % mpi_world_size);
int is_arr[4];
int ie_arr[4];
MPI_Status status;
MPI_Request request;
if(mpi_rank != 0) {
alloc_mat(&A, ie-is, K);
alloc_mat(&B, K, N);
alloc_mat(&C, ie-is, N);
zero_mat(C, ie-is, N);
}
for(int idx=0; idx<mpi_world_size; idx++) {
is_arr[idx] = M / mpi_world_size * idx + min(idx, M % mpi_world_size);
ie_arr[idx] = M / mpi_world_size * (idx + 1) + min(idx + 1, M % mpi_world_size);
}
//send B
MPI_Bcast(B, K*N, MPI_FLOAT, 0 /*src*/, MPI_COMM_WORLD);
// send A
if (mpi_rank == 0)
for(int proc=1; proc<mpi_world_size; proc++)
MPI_Isend(A+(K*is_arr[proc]), K*(ie_arr[proc]-is_arr[proc]), MPI_FLOAT, proc/*dst*/, proc /*tag*/, MPI_COMM_WORLD, &request);
else
MPI_Recv(A, K*(ie-is), MPI_FLOAT, 0 /*src*/, mpi_rank /*tag*/, MPI_COMM_WORLD, &status);
#define ITILESIZE (32)
#define JTILESIZE (2048)
#define KTILESIZE (2048)
#pragma omp parallel for num_threads(num_threads)
for (int ii = 0; ii < ie-is; 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-is, 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];
}
}
}
}
}
}
//send C
if (mpi_rank == 0)
for(int proc=1; proc<mpi_world_size; proc++)
MPI_Recv(C+(N*is_arr[proc]), N*(ie_arr[proc]-is_arr[proc]), MPI_FLOAT, proc /*src*/, proc /*tag*/, MPI_COMM_WORLD, &status);
else
MPI_Isend(C, N*(ie-is), MPI_FLOAT, 0 /*dst*/, mpi_rank /*tag*/, MPI_COMM_WORLD, &request);
}
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.
//if (mpi_rank == 0)
mat_mul_omp();
}