Parallelise the serial matrix multiplication C code using data parallelism with MPI. You
should implement a tile-based or submatrix approach in the parallel partitioning
design. Please refer to Figure 2 for a sample depiction of this method. If you opt for a
simpler row-based partitioning approach, you will not obtain the maximum marks for
this task. Please refer to Week 11’s lecture materials for row and tile-based
partitioning methods.
b) Only the root process can access the input matrix binary files (e.g.,
MA_1000x1000.bin & MB_1000x1000.bin). The root process reads the content of the
input binary files into its memory.
c) Implement a parallel partitioning algorithm to distribute the workload among the MPI
processes equally.
i)
ii)
iii)
The root process will distribute the input matrices to the other processes in
the MPI communicator. Note that you should apply an efficient approach in
distributing the input matrices among the MPI processes, i.e., the root
process should only send the required rows and columns of the input
matrices to the other MPI processes. If the root process broadcasts
unnecessary input data (matrices/sub-matrices) to any other MPI processes,
the method will be inefficient, and marks will be deducted.
All processes (including the root process) perform the matrix multiplication
based on the partitioning algorithm.
The root process gathers the computed matrices from other processes and
writes the results into a binary file (e.g., MC.bin). Only the root process writes
the results to a binary file.
//////////////////////////////////////////////////////////////////////////////////////
// MatrixMul_1D_bin.c
// ----------------------------------------------------------------------------------
//
// Multiplies two matrices and writes the resultant multiplication into a binary file.
//
//////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
int main()
{
// Variables
int i = 0, j = 0, k = 0;
code
Assistant
/* Clock information */
struct timespec start, end, start_compute, end_compute;
double time_taken, time_taken_compute;
clock_gettime(CLOCK_MONOTONIC, &start);
// 1. Read Matrix A
int rowA = 0, colA = 0;
printf("Matrix Multiplication using 1-Dimension Arrays - Start\n\n");
printf("Reading Matrix A - Start\n");
FILE *pFileA = fopen("MA_1500x1500.bin", "rb");
fread(&rowA, sizeof(int), 1, pFileA);
fread(&colA, sizeof(int), 1, pFileA);
int *pMatrixA = (int*)malloc((rowA*colA) * sizeof(int));
for(i = 0; i < rowA; i++){
fread(&pMatrixA[i*colA], sizeof(int), colA, pFileA);
}
fclose(pFileA);
printf("Reading Matrix A - Done\n");
// 2. Read Matrix B
int rowB = 0, colB = 0;
printf("Reading Matrix B - Start\n");
FILE *pFileB = fopen("MB_1500x1500.bin", "rb");
fread(&rowB, sizeof(int), 1, pFileB);
fread(&colB, sizeof(int), 1, pFileB);
int *pMatrixB = (int*)malloc((rowB*colB) * sizeof(int));
for(i = 0; i < rowB; i++){
fread(&pMatrixB[i*colB], sizeof(int), colB, pFileB);
}
fclose(pFileB);
printf("Reading Matrix B - Done\n");
// 3. Perform matrix multiplication
printf("Matrix Multiplication - Start\n");
int rowC = rowA, colC = colB;
unsigned long long *pMatrixC = (unsigned long long*)calloc((rowC*colC), sizeof(unsigned long long));
int commonPoint = colA;
clock_gettime(CLOCK_MONOTONIC, &start_compute); // Start the multiplication timer
for(i = 0; i < rowC; i++){
for(j = 0; j < colC; j++){
for(k = 0; k < commonPoint; k++){
pMatrixC[(i*colC)+j] += (pMatrixA[(i*colA)+k] * pMatrixB[(k*colB)+j]);
}
}
}
printf("Matrix Multiplication - Done\n");
// 4. Write resuls to a new file
clock_gettime(CLOCK_MONOTONIC, &end_compute); // Stop the multiplication timer
time_taken_compute = (end_compute.tv_sec - start_compute.tv_sec) * 1e9;
time_taken_compute = (time_taken_compute + (end_compute.tv_nsec - start_compute.tv_nsec)) * 1e-9;
printf("Matrix Multiplication time: %f\n", time_taken_compute); // Print multiplication time
printf("Matrix Multiplication - Done\n");
FILE *pFileC = fopen("MC.bin", "wb");
fwrite(&rowC, sizeof(int), 1, pFileC);
fwrite(&colC, sizeof(int), 1, pFileC);
for(i = 0; i < rowC; i++){
fwrite(&pMatrixC[i*colC], sizeof(unsigned long long), colC, pFileC); // use fwrite to write one row of columns to the file
}
fclose(pFileC);
printf("Write Resultant Matrix C to File - Done\n");
clock_gettime(CLOCK_MONOTONIC, &end);
time_taken = (end.tv_sec - start.tv_sec) * 1e9;
time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;
printf("Overall time (Including read, multiplication and write)(s): %lf\n", time_taken); // ts
// Clean up
free(pMatrixA);
free(pMatrixB);
free(pMatrixC);
printf("Matrix Multiplication using 1-Dimension Arrays - Done\n");
return 0;
}
c
//////////////////////////////////////////////////////////////////////////////////////
// MatrixMul_MPI_Tiled.c
// ----------------------------------------------------------------------------------
//
// Parallel matrix multiplication using MPI and tiled data distribution.
// Each process computes a tile of the result matrix C by multiplying
// corresponding tiles of matrices A and B.
// Only the root process reads the input matrices from the binary files and
// distributes the necessary tiles to other processes.
// The root process gathers the computed tiles from other processes and writes
// the results into a binary file.
//////////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
// Variables
int i, j, k;
int rank, num_procs;
MPI_Init(&argc, &argv); // Initialize MPI environment
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get the rank of the process
MPI_Comm_size(MPI_COMM_WORLD, &num_procs); // Get the number of processes
/* Clock information */
struct timespec start, end, start_compute, end_compute;
double time_taken, time_taken_compute;
// Start overall timer
if(rank == 0) {
clock_gettime(CLOCK_MONOTONIC, &start);
printf("Matrix Multiplication using MPI and Tiled Data Distribution - Start\n\n");
}
// Variables for matrix dimensions
int rowA = 0, colA = 0;
int rowB = 0, colB = 0;
int rowC = 0, colC = 0;
int *pMatrixA = NULL;
int *pMatrixB = NULL;
// Root process reads matrices A and B from binary files
if(rank == 0) {
// 1. Read Matrix A
printf("Reading Matrix A - Start\n");
FILE *pFileA = fopen("MA_1500x1500.bin", "rb");
fread(&rowA, sizeof(int), 1, pFileA);
fread(&colA, sizeof(int), 1, pFileA);
pMatrixA = (int*)malloc(rowA * colA * sizeof(int));
for(i = 0; i < rowA; i++){
fread(&pMatrixA[i * colA], sizeof(int), colA, pFileA);
}
fclose(pFileA);
printf("Reading Matrix A - Done\n");
// 2. Read Matrix B
printf("Reading Matrix B - Start\n");
FILE *pFileB = fopen("MB_1500x1500.bin", "rb");
fread(&rowB, sizeof(int), 1, pFileB);
fread(&colB, sizeof(int), 1, pFileB);
pMatrixB = (int*)malloc(rowB * colB * sizeof(int));
for(i = 0; i < rowB; i++){
fread(&pMatrixB[i * colB], sizeof(int), colB, pFileB);
}
fclose(pFileB);
printf("Reading Matrix B - Done\n");
if(colA != rowB) {
printf("Matrix dimensions mismatch for multiplication!\n");
MPI_Abort(MPI_COMM_WORLD, -1);
exit(-1);
}
rowC = rowA;
colC = colB;
}
// Broadcast matrix dimensions to all processes
MPI_Bcast(&rowA, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&colA, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&rowB, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&colB, 1, MPI_INT, 0, MPI_COMM_WORLD);
// Calculate the dimensions of the process grid
int dims[2] = {0, 0};
MPI_Dims_create(num_procs, 2, dims); // Let MPI decide the best dimensions
int periods[2] = {0, 0}; // No wrap-around connections
MPI_Comm cart_comm;
MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, 1, &cart_comm);
int coords[2];
MPI_Cart_coords(cart_comm, rank, 2, coords);
int grid_row = coords[0];
int grid_col = coords[1];
// Calculate local matrix dimensions for each process
int local_rows_A = rowA / dims[0];
int local_cols_A = colA / dims[1];
int local_rows_B = rowB / dims[0];
int local_cols_B = colB / dims[1];
int local_rows_C = local_rows_A;
int local_cols_C = local_cols_B;
// Handle remainder if matrices are not perfectly divisible
int row_remainder_A = rowA % dims[0];
int col_remainder_A = colA % dims[1];
int row_remainder_B = rowB % dims[0];
int col_remainder_B = colB % dims[1];
if(grid_row < row_remainder_A)
local_rows_A++;
if(grid_col < col_remainder_A)
local_cols_A++;
if(grid_row < row_remainder_B)
local_rows_B++;
if(grid_col < col_remainder_B)
local_cols_B++;
if(grid_row < row_remainder_A)
local_rows_C = local_rows_A;
if(grid_col < col_remainder_B)
local_cols_C = local_cols_B;
// Allocate local matrices
int *local_A = (int*)malloc(local_rows_A * colA * sizeof(int));
int *local_B = (int*)malloc(rowB * local_cols_B * sizeof(int));
unsigned long long *local_C = (unsigned long long*)calloc(local_rows_C * local_cols_C, sizeof(unsigned long long));
// Create MPI datatypes for submatrices
MPI_Datatype matA_block, matB_block;
MPI_Datatype matA_block_type, matB_block_type;
// For matrix A
int sizesA[2] = {rowA, colA};
int subsizesA[2] = {local_rows_A, colA};
int startsA[2] = {0, 0};
startsA[0] = grid_row * (rowA / dims[0]) + ((grid_row < row_remainder_A) ? grid_row : row_remainder_A);
MPI_Type_create_subarray(2, sizesA, subsizesA, startsA, MPI_ORDER_C, MPI_INT, &matA_block);
MPI_Type_create_resized(matA_block, 0, local_rows_A * colA * sizeof(int), &matA_block_type);
MPI_Type_commit(&matA_block_type);
// For matrix B
int sizesB[2] = {rowB, colB};
int subsizesB[2] = {rowB, local_cols_B};
int startsB[2] = {0, 0};
startsB[1] = grid_col * (colB / dims[1]) + ((grid_col < col_remainder_B) ? grid_col : col_remainder_B);
MPI_Type_create_subarray(2, sizesB, subsizesB, startsB, MPI_ORDER_C, MPI_INT, &matB_block);
MPI_Type_create_resized(matB_block, 0, rowB * local_cols_B * sizeof(int), &matB_block_type);
MPI_Type_commit(&matB_block_type);
// Create arrays for counts and displacements
int *sendcounts_A = NULL;
int *displs_A = NULL;
int *sendcounts_B = NULL;
int *displs_B = NULL;
if(rank == 0) {
sendcounts_A = (int*)malloc(num_procs * sizeof(int));
displs_A = (int*)malloc(num_procs * sizeof(int));
sendcounts_B = (int*)malloc(num_procs * sizeof(int));
displs_B = (int*)malloc(num_procs * sizeof(int));
int dispA = 0;
int dispB = 0;
for(i = 0; i < dims[0]; i++) {
for(j = 0; j < dims[1]; j++) {
int proc_rank;
int coord[2] = {i, j};
MPI_Cart_rank(cart_comm, coord, &proc_rank);
// Calculate local row sizes for A
int tmp_rows_A = rowA / dims[0];
if(i < row_remainder_A)
tmp_rows_A++;
sendcounts_A[proc_rank] = 1;
displs_A[proc_rank] = dispA;
dispA += 1;
// Calculate local column sizes for B
int tmp_cols_B = colB / dims[1];
if(j < col_remainder_B)
tmp_cols_B++;
sendcounts_B[proc_rank] = 1;
displs_B[proc_rank] = dispB;
dispB += 1;
}
}
}
// Scatter the submatrices A
MPI_Scatterv(pMatrixA, sendcounts_A, displs_A, matA_block_type,
local_A, local_rows_A * colA, MPI_INT, 0, MPI_COMM_WORLD);
// Scatter the submatrices B
MPI_Scatterv(pMatrixB, sendcounts_B, displs_B, matB_block_type,
local_B, rowB * local_cols_B, MPI_INT, 0, MPI_COMM_WORLD);
// Start computation timer
MPI_Barrier(MPI_COMM_WORLD);
clock_gettime(CLOCK_MONOTONIC, &start_compute);
// Perform local matrix multiplication
for(i = 0; i < local_rows_C; i++) {
for(j = 0; j < local_cols_C; j++) {
unsigned long long sum = 0;
for(k = 0; k < colA; k++) {
sum += (unsigned long long)local_A[i * colA + k] * (unsigned long long)local_B[k * local_cols_B + j];
}
local_C[i * local_cols_C + j] = sum;
}
}
// End computation timer
clock_gettime(CLOCK_MONOTONIC, &end_compute);
time_taken_compute = (end_compute.tv_sec - start_compute.tv_sec) + (end_compute.tv_nsec - start_compute.tv_nsec) / 1e9;
if(rank == 0) {
printf("Matrix Multiplication - Done\n");
printf("Matrix Multiplication time: %f seconds\n", time_taken_compute);
}
// Create MPI datatype for gathering the submatrices of C
MPI_Datatype matC_block;
MPI_Datatype matC_block_type;
int sizesC[2] = {rowC, colC};
int subsizesC[2] = {local_rows_C, local_cols_C};
int startsC[2] = {0, 0};
startsC[0] = grid_row * (rowC / dims[0]) + ((grid_row < row_remainder_A) ? grid_row : row_remainder_A);
startsC[1] = grid_col * (colC / dims[1]) + ((grid_col < col_remainder_B) ? grid_col : col_remainder_B);
MPI_Type_create_subarray(2, sizesC, subsizesC, startsC, MPI_ORDER_C, MPI_UNSIGNED_LONG_LONG, &matC_block);
MPI_Type_create_resized(matC_block, 0, 1, &matC_block_type);
MPI_Type_commit(&matC_block_type);
unsigned long long *pMatrixC = NULL;
if(rank == 0) {
pMatrixC = (unsigned long long*)calloc(rowC * colC, sizeof(unsigned long long));
}
// Gather the local matrices C
int *recvcounts_C = NULL;
int *displs_C = NULL;
if(rank == 0) {
recvcounts_C = (int*)malloc(num_procs * sizeof(int));
displs_C = (int*)malloc(num_procs * sizeof(int));
for(i = 0; i < num_procs; i++) {
recvcounts_C[i] = 1;
displs_C[i] = i;
}
}
MPI_Gatherv(local_C, local_rows_C * local_cols_C, MPI_UNSIGNED_LONG_LONG,
pMatrixC, recvcounts_C, displs_C, matC_block_type, 0, MPI_COMM_WORLD);
// Clean up local matrices
free(local_A);
free(local_B);
free(local_C);
// Root process writes the result to binary file
if(rank == 0) {
// 4. Write results to a new file
printf("Writing Resultant Matrix C to File - Start\n");
FILE *pFileC = fopen("MC.bin", "wb");
fwrite(&rowC, sizeof(int), 1, pFileC);
fwrite(&colC, sizeof(int), 1, pFileC);
for(i = 0; i < rowC; i++){
fwrite(&pMatrixC[i * colC], sizeof(unsigned long long), colC, pFileC);
}
fclose(pFileC);
printf("Write Resultant Matrix C to File - Done\n");
clock_gettime(CLOCK_MONOTONIC, &end);
time_taken = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1e9;
printf("Overall time (Including read, multiplication and write)(s): %lf\n", time_taken);
// Clean up
free(pMatrixA);
free(pMatrixB);
free(pMatrixC);
free(sendcounts_A);
free(displs_A);
free(sendcounts_B);
free(displs_B);
free(recvcounts_C);
free(displs_C);
}
MPI_Type_free(&matA_block_type);
MPI_Type_free(&matB_block_type);
MPI_Type_free(&matC_block_type);
if(rank == 0) {
printf("Matrix Multiplication using MPI and Tiled Data Distribution - Done\n");
}
MPI_Finalize();
return 0;
}
Notes:
MPI Initialization: The program starts by initializing the MPI environment and determining the rank and number of processes.
Process Grid Creation: We create a 2D process grid (dims[0] x dims[1]) using MPI_Dims_create and MPI_Cart_create. This grid will help us in distributing the tiles of matrices A and B among the processes.
Root Process Reads Matrices: Only the root process (rank 0) reads the matrices from the binary files.
Matrix Dimensions Broadcasted: The dimensions of the matrices are broadcasted to all processes so that they can compute their local matrix sizes.
Local Matrix Allocation: Each process allocates memory for its local tiles of matrices A, B, and C.
Creating Subarray Datatypes: We use MPI_Type_create_subarray to create MPI datatypes that represent the submatrices (tiles). This allows us to send and receive non-contiguous blocks of data efficiently.
Distributing Tiles: The root process uses MPI_Scatterv with the created subarray datatypes to distribute the necessary tiles of A and B to all processes. This ensures that each process only receives the required portion of the matrices.
Local Computation: Each process performs the matrix multiplication on its local tiles and computes its portion of the result matrix C.
Gathering Results: The root process gathers the computed tiles of C from all processes using MPI_Gatherv and writes the final result to a binary file.
Efficient Data Distribution: By using subarray datatypes and MPI_Scatterv/MPI_Gatherv, we ensure that only the necessary data is communicated between processes, adhering to the requirement of efficient data distribution.
To run the program with, for example, 4 processes:
bash
mpirun -np 4 ./MatrixMul_MPI_Tiled
Additional Considerations:
Error Handling: The program checks for matrix dimensions mismatch and aborts if the matrices cannot be multiplied.
Remainders Handling: If the matrices cannot be evenly divided among the processes, the program adjusts the local matrix sizes to handle the remainder rows and columns.
Performance Measurement: The program measures both the total execution time and the computation time (matrix multiplication time) separately.
Memory Management: All dynamically allocated memory is properly freed before the program terminates.
By following this approach, we have parallelized the matrix multiplication using a tile-based data partitioning method where each process works on a specific submatrix (tile) of the whole matrices, ensuring efficient communication and computation.