Matrix Multiplication on Multi-Processors: MPI4PY

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 MPI

This 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 C

This 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().


Material

Download the programs (code), covering the MPI4Py.

291 thoughts on “Matrix Multiplication on Multi-Processors: MPI4PY

  1. indianpharmacy com [url=http://indiapharmast.com/#]reputable indian pharmacies[/url] reputable indian online pharmacy

  2. indianpharmacy com [url=https://indiapharmast.com/#]top 10 pharmacies in india[/url] world pharmacy india

  3. top 10 online pharmacy in india [url=http://indiapharmast.com/#]top 10 online pharmacy in india[/url] indian pharmacy paypal

  4. www canadianonlinepharmacy [url=https://canadapharmast.online/#]online canadian pharmacy[/url] canadian pharmacy com

  5. mexico pharmacies prescription drugs [url=https://mexicandeliverypharma.online/#]reputable mexican pharmacies online[/url] mexico drug stores pharmacies

  6. mexican drugstore online [url=https://mexicandeliverypharma.online/#]pharmacies in mexico that ship to usa[/url] mexican drugstore online

  7. mexican mail order pharmacies [url=https://mexicandeliverypharma.online/#]buying prescription drugs in mexico[/url] п»їbest mexican online pharmacies

  8. mexican online pharmacies prescription drugs [url=https://mexicandeliverypharma.com/#]mexican pharmaceuticals online[/url] mexico drug stores pharmacies

  9. pharmacies in mexico that ship to usa [url=https://mexicandeliverypharma.online/#]best online pharmacies in mexico[/url] best online pharmacies in mexico

  10. reputable mexican pharmacies online [url=https://mexicandeliverypharma.online/#]buying from online mexican pharmacy[/url] buying prescription drugs in mexico online

  11. mexican pharmacy [url=https://mexicandeliverypharma.online/#]mexico drug stores pharmacies[/url] best online pharmacies in mexico

  12. mexican online pharmacies prescription drugs [url=http://mexicandeliverypharma.com/#]mexico drug stores pharmacies[/url] mexican border pharmacies shipping to usa

  13. pharmacies in mexico that ship to usa [url=https://mexicandeliverypharma.com/#]mexican border pharmacies shipping to usa[/url] mexican border pharmacies shipping to usa

  14. medication from mexico pharmacy [url=http://mexicandeliverypharma.com/#]buying prescription drugs in mexico[/url] pharmacies in mexico that ship to usa

  15. purple pharmacy mexico price list [url=https://mexicandeliverypharma.online/#]buying prescription drugs in mexico[/url] mexican rx online

  16. buying from online mexican pharmacy [url=https://mexicandeliverypharma.com/#]reputable mexican pharmacies online[/url] mexican mail order pharmacies

  17. buy nolvadex online [url=https://tamoxifen.bid/#]buy tamoxifen citrate[/url] tamoxifen side effects forum

  18. lipitor rx cost [url=http://lipitor.guru/#]lipitor atorvastatin[/url] lipitor tablets 10mg price

  19. buy prescription drugs from india [url=https://indianpharmacy.company/#]top 10 online pharmacy in india[/url] reputable indian online pharmacy

  20. mexico drug stores pharmacies [url=https://mexicopharmacy.cheap/#]medication from mexico pharmacy[/url] п»їbest mexican online pharmacies

  21. reputable indian online pharmacy [url=http://indianpharmacy.company/#]reputable indian online pharmacy[/url] online shopping pharmacy india

  22. indian pharmacy [url=https://indianpharmacy.company/#]india online pharmacy[/url] indian pharmacy paypal

  23. mexico drug stores pharmacies [url=http://mexicopharmacy.cheap/#]medication from mexico pharmacy[/url] mexico drug stores pharmacies

  24. mexican border pharmacies shipping to usa [url=http://mexicopharmacy.cheap/#]mexican rx online[/url] mexican rx online

  25. Online medicine home delivery [url=https://indianpharmacy.company/#]pharmacy website india[/url] indian pharmacies safe

  26. topiramate online pharmacy [url=https://pharmbig24.com/#]levitra pharmacy coupon[/url] simvastatin at target pharmacy

  27. purple pharmacy mexico price list [url=http://mexicopharmacy.cheap/#]reputable mexican pharmacies online[/url] mexican mail order pharmacies

  28. starz bet giris: straz bet – starz bet giris
    casibom 158 giris [url=https://casibom.auction/#]casibom guncel giris adresi[/url] casibom guncel giris

  29. betine guncel giris: betine guncel – betine
    gates of olympus oyna demo [url=http://gatesofolympusoyna.online/#]gates of olympus oyna demo[/url] gates of olympus turkce

  30. gate of olympus oyna [url=http://gatesofolympusoyna.online/#]Gates of Olympus[/url] gates of olympus oyna

  31. п»їfarmacia online espaГ±a [url=https://tadalafilo.bid/#]comprar tadalafilo[/url] farmacia en casa online descuento

  32. viagra online rГЎpida [url=http://sildenafilo.men/#]viagra generico[/url] comprar viagra en espaГ±a envio urgente contrareembolso

  33. Farmacie on line spedizione gratuita [url=https://farmaciait.men/#]Farmacia online migliore[/url] migliori farmacie online 2024

  34. farmacia online senza ricetta [url=http://farmaciait.men/#]Farmacie on line spedizione gratuita[/url] Farmacie online sicure

  35. gel per erezione in farmacia [url=http://sildenafilit.pro/#]acquisto viagra[/url] cialis farmacia senza ricetta

  36. Farmacia online piГ№ conveniente [url=https://tadalafilit.com/#]Cialis generico farmacia[/url] farmacie online autorizzate elenco

  37. farmaci senza ricetta elenco [url=http://tadalafilit.com/#]Cialis generico recensioni[/url] acquisto farmaci con ricetta

  38. farmacia online senza ricetta [url=http://brufen.pro/#]BRUFEN 600 acquisto online[/url] comprare farmaci online con ricetta

  39. farmacia online senza ricetta [url=https://tadalafilit.com/#]Cialis generico farmacia[/url] comprare farmaci online all’estero

  40. pillole per erezione in farmacia senza ricetta [url=https://sildenafilit.pro/#]viagra farmacia[/url] dove acquistare viagra in modo sicuro

  41. migliori farmacie online 2024 [url=https://brufen.pro/#]BRUFEN 600 bustine prezzo[/url] Farmacia online piГ№ conveniente

  42. viagra online in 2 giorni [url=https://sildenafilit.pro/#]viagra online siti sicuri[/url] viagra generico in farmacia costo

  43. Farmacia online piГ№ conveniente [url=http://brufen.pro/#]BRUFEN 600 acquisto online[/url] Farmacie on line spedizione gratuita

  44. Be it alone or with your partner. Share all your secret thoughts with me. Dirty fantasies live chat for websites are welcome with me! Here you get uninhibited dirty talk from me, dirty and secret dreams are lived and come true. I show you horny and want to see it from you! I look forward to seeing you on cam!

  45. Not everyone who has sexual feelings or attractions to the same gender will act on them. Some people may engage in same gender sexual behavior but not identify

  46. Meilleur Viagra sans ordonnance 24h [url=http://vgrsansordonnance.com/#]Quand une femme prend du Viagra homme[/url] Viagra vente libre allemagne

  47. Viagra pas cher livraison rapide france [url=http://vgrsansordonnance.com/#]Viagra prix[/url] Viagra en france livraison rapide

  48. Viagra pas cher livraison rapide france [url=http://vgrsansordonnance.com/#]Acheter du Viagra sans ordonnance[/url] SildГ©nafil 100 mg prix en pharmacie en France

  49. pharmacie en ligne france pas cher [url=http://pharmaciepascher.pro/#]Medicaments en ligne livres en 24h[/url] п»їpharmacie en ligne france

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this:
Verified by MonsterInsights