
Matrix Multiplication on Multi-Processors: MPI4PY
In this scenario, each processor handles a portion of the matrices, performing computations independently, and then the results are combined to obtain the final result. This parallelization technique leverages the capabilities of multiple processors to expedite the overall computation time.
Code:
from mpi4py import MPI
import numpy as np
# Function to perform matrix multiplication
def matrix_multiply(A, B):
C = np.zeros((A.shape[0], B.shape[1]))
for i in range(A.shape[0]):
for j in range(B.shape[1]):
for k in range(A.shape[1]):
C[i][j] += A[i][k] * B[k][j]
return C
# Initialize MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
# Master process
if rank == 0:
# Generate matrices A and B
A = np.random.rand(2, 2)
B = np.random.rand(2, 2)
# Split matrices for distribution
chunk_size = A.shape[0] // size
A_chunks = [A[i:i+chunk_size] for i in range(0, A.shape[0], chunk_size)]
# Send parts of A and B to worker processes
for i in range(1, size):
comm.send(A_chunks[i-1], dest=i, tag=1)
comm.send(B, dest=i, tag=2)
# Calculate its own part of multiplication
C_partial = matrix_multiply(A_chunks[0], B)
# Collect results from worker processes
for i in range(1, size):
C_partial += comm.recv(source=i, tag=3)
# Print the resulting matrix
print("Resulting matrix C:")
print(C_partial)
# Worker processes
else:
# Receive matrix chunks from master
A_chunk = comm.recv(source=0, tag=1)
B = comm.recv(source=0, tag=2)
# Perform multiplication
C_partial = matrix_multiply(A_chunk, B)
# Send back the result to master
comm.send(C_partial, dest=0, tag=3)
Explanation
Import MPI Module and Initialize MPI Environment
from mpi4py import MPIThis line imports the MPI module from the mpi4py package, enabling the use of MPI functionalities.
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()These lines initialize the MPI environment. MPI.COMM_WORLD creates a communicator object representing all processes in the MPI world. comm.Get_rank() returns the rank of the current process in the communicator, and comm.Get_size() returns the total number of processes in the communicator.
Function to Perform Matrix Multiplication
def matrix_multiply(A, B):
C = np.zeros((A.shape[0], B.shape[1]))
for i in range(A.shape[0]):
for j in range(B.shape[1]):
for k in range(A.shape[1]):
C[i][j] += A[i][k] * B[k][j]
return CThis function matrix_multiply takes two matrices A and B as input and returns their multiplication C. It initializes an empty matrix C with dimensions derived from the multiplication of matrices A and B. Then, it performs matrix multiplication using nested loops to iterate through rows and columns of matrices A and B, computing each element of matrix C.
Master Process
if rank == 0:
A = np.random.rand(2, 2)
B = np.random.rand(2, 2)In the master process (rank 0), random matrices A and B of size 2×2 are generated.
chunk_size = A.shape[0] // size
A_chunks = [A[i:i+chunk_size] for i in range(0, A.shape[0], chunk_size)]The matrices A is split into chunks based on the total number of processes (size). Each chunk is of size chunk_size, and the list A_chunks contains these chunks.
for i in range(1, size):
comm.send(A_chunks[i-1], dest=i, tag=1)
comm.send(B, dest=i, tag=2)Parts of matrices A and B are sent to worker processes using comm.send(). Each chunk of A along with the entire matrix B is sent to a different worker process.
C_partial = matrix_multiply(A_chunks[0], B)The master process calculates its own partial result of matrix multiplication using the first chunk of matrix A.
for i in range(1, size):
C_partial += comm.recv(source=i, tag=3)The master process receives partial results from each worker process using comm.recv(), aggregates them, and stores the final result in C_partial.
print("Resulting matrix C:")
print(C_partial)Finally, the resulting matrix C is printed.
Worker Processes
else:
A_chunk = comm.recv(source=0, tag=1)
B = comm.recv(source=0, tag=2)In the worker processes (rank != 0), chunks of matrix A and entire matrix B are received from the master process using comm.recv().
C_partial = matrix_multiply(A_chunk, B)Each worker process performs matrix multiplication using its received chunk of matrix A and matrix B.
comm.send(C_partial, dest=0, tag=3)The resulting partial matrix C_partial is sent back to the master process using comm.send().
22 thoughts on “Matrix Multiplication on Multi-Processors: MPI4PY”
Howdy! Do you know if they make any plugins to protect against hackers?
I’m kinda paranoid about losing everything I’ve worked
hard on. Any recommendations?
If some one wishes to be updated with newest technologies after
that he must be pay a quick visit this website and be up to date daily.
Good information. Lucky me I recently found your website
by accident (stumbleupon). I’ve saved it for later!
I loved as much as you’ll receive carried out right here.
The sketch is attractive, your authored subject matter stylish.
nonetheless, you command get bought an edginess over that you
wish be delivering the following. unwell unquestionably come further
formerly again since exactly the same nearly very often inside case you shield this increase.
You can definitely see your enthusiasm within the article you write.
The world hopes for more passionate writers such as you who
aren’t afraid to say how they believe. Always go after your heart.
Hi there, I enjoy reading through your article. I like to write a
little comment to support you.
Hi friends, how is everything, and what you want to say regarding this
article, in my view its truly awesome designed for me.
Spot on with this write-up, I actually think this amazing site needs far more
attention. I’ll probably be back again to read through
more, thanks for the info!
I’m excited to uncover this site. I need to to thank you for ones time for this
particularly fantastic read!! I definitely enjoyed every little bit of it and i also
have you saved to fav to check out new information on your site.
What’s Happening i am new to this, I stumbled upon this I’ve discovered It absolutely useful
and it has aided me out loads. I’m hoping to contribute & aid other customers like
its helped me. Great job.
Your mode of describing everything in this paragraph is really
fastidious, every one be capable of effortlessly understand it, Thanks a lot.
Nice post. I learn something totally new and challenging on sites I stumbleupon everyday.
It will always be helpful to read articles from other writers and
use something from other web sites.
Piece of writing writing is also a excitement,
if you know then you can write or else it is complex to write.
receive daily calm shouldn’t be gruelling. research our full https://www.cornbreadhemp.com/collections/adaptogen-drinks selection to receive high-potency CBD oil colour, CBD gummies, and CBD extracts give for relaxation. Modern life brings unvarying accentuate, only instinctive CBD interacts with your physical structure to touch on balance. Our non-intoxicating CBD products fork out efficient moderation without English outcome. advance your routine with unobjectionable, hemp-derived CBD designed for real ensue. chew the fat our CBD frequent, bargain CBD online, and get everlasting CBD wellness with every bingle venereal disease!
Hello, Neat post. There’s a problem along with your web site
in web explorer, would check this? IE still is the marketplace chief and a large section of other folks will leave out your magnificent writing
because of this problem.
I’ve been surfing online more than 4 hours today, yet I never found any interesting article like yours.
It is pretty worth enough for me. In my view, if all website owners and bloggers made good content as you
did, the internet will be a lot more useful than ever before.
Today, I went to the beach front with my children. I found a sea shell and gave it to my
4 year old daughter and said “You can hear the ocean if you put this to your ear.”
She put the shell to her ear and screamed.
There was a hermit crab inside and it pinched her
ear. She never wants to go back! LoL I know this is entirely
off topic but I had to tell someone!
Inspiring quest there. What happened after? Take care!
Hey! This post couldn’t be written any better! Reading through
this post reminds me of my previous room mate! He always kept talking
about this. I will forward this post to him. Pretty sure he will have a
good read. Thank you for sharing!
Hello, Neat post. There’s a problem together with your website in internet explorer,
might check this? IE nonetheless is the marketplace chief and a huge component to folks
will omit your wonderful writing due to this problem.
Just had my first big win and the withdrawal was processed in minutes. I am genuinely impressed with the efficiency here. Visit 9999wingame now.
I delight in, result in I discovered just what I used to be looking for.
You have ended my four day lengthy hunt! God Bless you
man. Have a great day. Bye