#include "mat_mul.h" #include #include "util.h" #include #include #include #include using namespace std; static float *A, *B, *C; static int M, N, K; static int num_threads; static int mpi_rank, mpi_world_size; static int rows, offset; static void mat_mul_omp() { // TODO: parallelize & optimize matrix multiplication int iblock = 32; int jblock = 1024;//256; int kblock = 1024;//30;//32;//28; #pragma omp parallel num_threads(num_threads) #pragma omp for for(int ii = 0; ii < rows; ii+=iblock){ for(int jj = 0; jj < N; jj+=jblock){ for(int kk = 0; kk < K; kk+=kblock){ for(int k = kk; k < min(kk+kblock, K); k++){ for(int i = ii; i < min(ii+iblock, rows); i++){ float temp = A[i * K + k]; for(int j = jj; j < min(jj+jblock,N); j+=1) { C[i * N + j] += temp * B[k * N + j]; } } } } } } return; } 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; if(mpi_rank == 0){ int row_size = M/mpi_world_size; int start, end; for(int i = 1; i < mpi_world_size; i++){ start = offset = i * row_size; end = i == mpi_world_size - 1 ? M : (i+1)*row_size; rows = end - start; MPI_Isend(&offset, 1, MPI_INT, i, 1, MPI_COMM_WORLD, &request); MPI_Isend(&rows, 1, MPI_INT, i, 1, MPI_COMM_WORLD, &request); MPI_Isend(&A[offset*K], rows*K, MPI_FLOAT, i, 1, MPI_COMM_WORLD,&request); MPI_Isend(B, K*N, MPI_FLOAT, i, 1, MPI_COMM_WORLD, &request); } rows = row_size; mat_mul_omp(); for(int i = 1; i < mpi_world_size; i++){ MPI_Recv(&offset, 1, MPI_INT, i, 2, MPI_COMM_WORLD, &status); MPI_Recv(&rows, 1, MPI_INT, i, 2, MPI_COMM_WORLD, &status); MPI_Recv(&C[offset*N], rows*N, MPI_FLOAT, i, 2, MPI_COMM_WORLD, &status); } } else{ alloc_mat(&A,M,K); alloc_mat(&B,K,N); alloc_mat(&C,M,N); zero_mat(C,M,N); MPI_Recv(&offset, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, &status); MPI_Recv(&rows, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, &status); MPI_Recv(A, rows*K, MPI_FLOAT, 0, 1, MPI_COMM_WORLD, &status); MPI_Recv(B, K*N, MPI_FLOAT, 0 , 1, MPI_COMM_WORLD, &status); mat_mul_omp(); MPI_Isend(&offset, 1, MPI_INT, 0, 2, MPI_COMM_WORLD,&request); MPI_Isend(&rows, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, &request); MPI_Isend(C, rows*N, MPI_FLOAT, 0, 2, MPI_COMM_WORLD, &request); } }