Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output from mpi4py program

Tags:

python

mpi

mpi4py

I'm new in MPI using Python and I'm having some issues here. This is my code:

from mpi4py import MPI

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

if rank == 0:
        a = 1 
        comm.bcast(a, root=0)
        s = comm.reduce(a, op=MPI.SUM)
        print 'From process 0, sum =', s
elif rank == 1:
        b = 2
        comm.bcast(b, root=1)  
        x = comm.reduce(b, op=MPI.SUM)
        print 'From process 1, sum =', x

I want to print: From process PROCESS_NUMBER, sum = 3

Process 0 prints correctly, but process 1 prints None.

I can't understand why. Could anyone help me?

like image 529
Raí Lima Avatar asked Jul 02 '15 23:07

Raí Lima


1 Answers

  1. Any collective operation (Bcast, Reduce) should be called on all processes, so it is incorrect to place it inside if rank == N statement.
  2. In the second reduce you have to specify root=1.
  3. Assignment is needed in broadcast a = comm.bcast(a, root=0)

Corrected code:

from mpi4py import MPI

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

if rank == 0:
        a = 1
else:
        a = None
a = comm.bcast(a, root=0)
s = comm.reduce(a, op=MPI.SUM)
if rank == 0:
        print 'From process 0, sum =', s

if rank == 1:
        b = 2
else:
        b = None
b = comm.bcast(b, root=1)
x = comm.reduce(b, op=MPI.SUM, root=1)

if rank == 1:
        print 'From process 1, sum =', x

Result of running on 3 processes:

From process 0, sum = 3
From process 1, sum = 6
like image 176
tepl Avatar answered Sep 25 '22 13:09

tepl