chundoong-lab-ta/SamsungDS22/submissions/HW4/h0.kim/mat_mul.cpp

103 lines
2.8 KiB
C++

#include "mat_mul.h"
#include <cstdio>
#include <cstdlib>
#include <omp.h>
#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;
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#define IBS 32
#define JBS 2048
#define KBS 16
static int get_size_per_rank(int rank) {
const int MM = M / mpi_world_size;
if (rank == -1) return 0;
else if (rank != 0) return MM;
else return (M - (mpi_world_size - 1) * MM);
}
static int get_begin_index(int rank) {
if (rank == 0) return 0;
else if (rank == 1) return get_size_per_rank(0);
else return get_begin_index(rank - 1) + get_size_per_rank(rank - 1);
}
static void mat_mul_omp() {
const int begin = get_begin_index(mpi_rank);
const int end = get_begin_index(mpi_rank) + get_size_per_rank(mpi_rank);
#pragma omp parallel for shared(C) collapse(2) num_threads(num_threads) schedule(auto)
for (int ii = begin; ii < end; ii += IBS) {
for (int jj = 0; jj < N; jj += JBS) {
for (int kk = 0; kk < K; kk += KBS) {
for (int i = ii; i < MIN(ii + IBS, end); ++i) {
for (int k = kk; k < MIN(kk + KBS, K); ++k) {
for (int j = jj; j < MIN(N, jj + JBS); ++j) {
C[i * N + j] += A[i * K + k] * 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;
if (mpi_rank != 0) {
alloc_mat(&A, M, K);
alloc_mat(&B, K, N);
alloc_mat(&C, M, N);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Bcast(B, K * N, MPI_FLOAT, 0, MPI_COMM_WORLD);
if (mpi_rank == 0) {
for (int i = 1; i < mpi_world_size; ++i) {
MPI_Request request;
int index = get_begin_index(i) * K;
int size = get_size_per_rank(i) * K;
MPI_Isend(&A[index], size, MPI_FLOAT, i, 0, MPI_COMM_WORLD, &request);
}
} else {
MPI_Request request;
int index = get_begin_index(mpi_rank) * K;
int size = get_size_per_rank(mpi_rank) * K;
MPI_Irecv(&A[index], size, MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &request);
zero_mat(C, M, N);
MPI_Wait(&request, MPI_STATUS_IGNORE);
}
mat_mul_omp();
if (mpi_rank == 0) {
MPI_Request request[mpi_world_size];
for (int i = 1; i < mpi_world_size; ++i) {
int index = get_begin_index(i) * N;
int size = get_size_per_rank(i) * N;
MPI_Irecv(&C[index], size, MPI_FLOAT, i, 0, MPI_COMM_WORLD, &request[i]);
}
for (int i = 1; i < mpi_world_size; ++i) {
MPI_Wait(&request[i], MPI_STATUS_IGNORE);
}
} else {
int index = get_begin_index(mpi_rank) * N;
int size = get_size_per_rank(mpi_rank) * N;
MPI_Send(&C[index], size, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);
}
}