97 lines
2.5 KiB
C++
97 lines
2.5 KiB
C++
#include "mat_mul.h"
|
|
#include "util.h"
|
|
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <mpi.h>
|
|
|
|
//#define MASTER 0
|
|
//#define FROM_MASTER 1
|
|
//#define FROM_WORKER 2
|
|
#define TILE_M 64
|
|
#define TILE_K 16
|
|
#define TILE_N 2048
|
|
|
|
static float *A, *B, *C;
|
|
static int M, N, K;
|
|
static int num_threads;
|
|
static int mpi_rank, mpi_world_size;
|
|
static int rows[4] = {0,};
|
|
static int offset[4] = {0,};
|
|
|
|
static void mat_mul_omp() {
|
|
int begin = 0;
|
|
int end = rows[mpi_rank];
|
|
|
|
// TODO: parallelize & optimize matrix multiplication
|
|
// Use num_threads per node
|
|
#pragma omp parallel for num_threads(num_threads) schedule(dynamic)
|
|
for (int ii = begin; ii < end; ii+= TILE_M) {
|
|
for (int kk = 0; kk < K; kk+= TILE_K) {
|
|
for (int jj = 0; jj<N; jj += TILE_N) {
|
|
int ek = kk + TILE_K < K ? (kk + TILE_K) : K;
|
|
int em = ii + TILE_M < M ? (ii + TILE_M) : M;
|
|
int en = jj + TILE_N < N ? (jj + TILE_N) : N;
|
|
for (int i = ii; i< em; ++i) {
|
|
for (int k = kk; k< ek; ++k) {
|
|
for (int j = jj; j<en; ++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;
|
|
MPI_Status status;
|
|
MPI_Request request;
|
|
// TODO: parallelize & optimize matrix multiplication on multi-node
|
|
// You must allocate & initialize A, B, C for non-root processes
|
|
|
|
int row_num = M / mpi_world_size;
|
|
|
|
for (int i =0; i<mpi_world_size; i++){
|
|
rows[i] = (i == mpi_world_size - 1) ? (M -(row_num *(mpi_world_size - 1))) : row_num;
|
|
}
|
|
|
|
for (int i = 0; i<mpi_world_size -1; i++){
|
|
offset[i+1] = offset[i] + rows[i];
|
|
}
|
|
|
|
if (mpi_rank!=0){
|
|
M = rows[mpi_rank];
|
|
alloc_mat(&A, rows[mpi_rank], K);
|
|
alloc_mat(&B, K, N);
|
|
alloc_mat(&C, rows[mpi_rank], N);
|
|
}
|
|
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_Isend(&A[offset[i]*K], rows[i]*K, MPI_FLOAT, i, 0, MPI_COMM_WORLD, &request);
|
|
} else {
|
|
MPI_Recv(A, rows[mpi_rank]*K, MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &status);
|
|
}
|
|
|
|
mat_mul_omp();
|
|
|
|
if (mpi_rank!=0) {
|
|
MPI_Isend(C, rows[mpi_rank]*N, MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &request);
|
|
} else{
|
|
for (int i =1; i< mpi_world_size; i++){
|
|
MPI_Recv(&C[offset[i] *N], rows[i]* N, MPI_FLOAT, i, 0, MPI_COMM_WORLD, &status);
|
|
}
|
|
}
|
|
// free(A);
|
|
// free(B);
|
|
// free(C);
|
|
// MPI_Finalize();
|
|
}
|
|
|