Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Programming with MPI

OpenMP lets you use all the cores of a single node, but the largest scientific simulations run on thousands of nodes. To go beyond one node, processes have to communicate explicitly by sending messages to each other over the network. The Message Passing Interface (MPI) is the standard library for doing this.

In this lecture, we will:

Parallel programming languages

Evolution of programming methods:

Distributed memory versus shared memory

MPI history

MPI implementations

Open source libraries can be installed on almost any architecture (for example on your laptop):

Vendors also provide their own implementations, for example:

MPI tools

Debuggers and performance analysis tools:

Scientific libraries:

General concepts

Parallel processing

MPI is a library which allows process coordination and scheduling between millions of processors using a message-passing paradigm.

Message attributes

The MPI environment

Data distribution

Data (grid cells or particles) are distributed between nodes and cores using a domain decomposition strategy. On the left, a regular grid is split into 9 equal domains. On the right, the domains of a particle simulation adapt to the particle density, so that each process gets roughly the same amount of work.

MPI basics

Setting up the MPI environment

The MPI definitions are made available with:

The MPI environment is launched with the MPI_INIT() routine and terminated with the MPI_FINALIZE() routine.

C syntax:

int MPI_Init(int *argc, char ***argv);
int MPI_Finalize(void);

Fortran syntax:

call MPI_INIT(code)
call MPI_FINALIZE(code)

Who am I?

Each process can query the total number of processes in the communicator MPI_COMM_WORLD with MPI_COMM_SIZE(), and its own identifier (its rank) with MPI_COMM_RANK():

program who_am_I
  use mpi
  implicit none
  integer :: nb_procs,rank,code

  call MPI_INIT(code)

  call MPI_COMM_SIZE(MPI_COMM_WORLD,nb_procs,code)
  call MPI_COMM_RANK(MPI_COMM_WORLD,rank,code)

  print *,'I am the process ',rank,' among ',nb_procs

  call MPI_FINALIZE(code)
end program who_am_I
$ mpif90 who_am_I.f90 -o who_am_I
$ mpiexec -n 7 who_am_I
 I am the process            3  among            7
 I am the process            0  among            7
 I am the process            4  among            7
 I am the process            1  among            7
 I am the process            5  among            7
 I am the process            2  among            7
 I am the process            6  among            7

The processes print in a random order: they all run independently.

Point-to-point communications

Blocking send and receive

program point_to_point
  use mpi
  implicit none

  integer, dimension(MPI_STATUS_SIZE) :: status
  integer, parameter                  :: tag=100
  integer                             :: rank,value,code

  call MPI_INIT(code)

  call MPI_COMM_RANK(MPI_COMM_WORLD,rank,code)

  if (rank == 2) then
     value=1000
     call MPI_SEND(value,1,MPI_INTEGER,5,tag,MPI_COMM_WORLD,code)
  elseif (rank == 5) then
     call MPI_RECV(value,1,MPI_INTEGER,2,tag,MPI_COMM_WORLD,status,code)
     print *,'I, process 5, I received ',value,' from the process 2'
  end if

  call MPI_FINALIZE(code)

end program point_to_point
$ mpiexec -n 7 point_to_point
 I, process 5, I received         1000  from the process 2

With blocking send and receive, if you are not careful, you can have a deadlock. This means the processes will wait for something that will never happen. The classical mistake is to first call a blocking send towards the next process, and then call a blocking receive from the previous process.

Non-blocking send and receive

Communication costs can be large. The InfiniBand network latency is around a microsecond, equivalent to thousands of processor cycles. One has to add the cost of the message itself (limited by the bandwidth of the InfiniBand network, around 10 GB/s).

Non-blocking routines can be used to perform calculations in parallel to the communication (an additional level of parallelism). There is no risk of deadlock, but there is a risk of memory leak if the communication is not properly terminated.

The communication buffers, however, cannot be used before the proper completion of the send or receive. The user needs to test that the communication is successful in order to proceed with the data, which leads to a higher algorithmic complexity.

Computation-communication overlap.

Example: halo exchange

A classical use case is a stencil computation on a 2D grid decomposed into domains. Each process needs the values of the cells along the boundaries of its 4 neighbors (North, South, West, and East), which are stored in extra “ghost” cells around its own domain.

The communications with the 4 neighbors are started with non-blocking calls. The derived datatypes rowtype and columntype describe a row and a column of the array, and the array indices of the first element of each row or column are omitted here for brevity:

SUBROUTINE start_communication(u)
  ! Send to the North and receive from the South
  CALL MPI_IRECV( u(,), 1, rowtype, neighbor(S), &
       tag, comm2d, request(1), code)
  CALL MPI_ISEND( u(,), 1, rowtype, neighbor(N), &
       tag, comm2d, request(2), code)

  ! Send to the South and receive from the North
  CALL MPI_IRECV( u(,), 1, rowtype, neighbor(N), &
       tag, comm2d, request(3), code)
  CALL MPI_ISEND( u(,), 1, rowtype, neighbor(S), &
       tag, comm2d, request(4), code)

  ! Send to the West and receive from the East
  CALL MPI_IRECV( u(,), 1, columntype, neighbor(E), &
       tag, comm2d, request(5), code)
  CALL MPI_ISEND( u(,), 1, columntype, neighbor(W), &
       tag, comm2d, request(6), code)

  ! Send to the East and receive from the West
  CALL MPI_IRECV( u(,), 1, columntype, neighbor(W), &
       tag, comm2d, request(7), code)
  CALL MPI_ISEND( u(,), 1, columntype, neighbor(E), &
       tag, comm2d, request(8), code)
END SUBROUTINE start_communication

SUBROUTINE end_communication(u)
  CALL MPI_WAITALL(2*NB_NEIGHBORS, request, tab_status, code)
END SUBROUTINE end_communication

While the messages are in flight, each process updates the interior of its domain, which does not depend on the ghost cells. Once the communications are completed, it updates the 4 boundaries:

DO WHILE ((.NOT. convergence) .AND. (it < it_max))
  it = it +1
  u(sx:ex,sy:ey) = u_new(sx:ex,sy:ey)

  ! Exchange value on the interfaces
  CALL start_communication( u )

  ! Compute u
  CALL calcul( u, u_new, sx+1, ex-1, sy+1, ey-1)

  CALL end_communication( u )

  ! North
  CALL calcul( u, u_new, sx, sx, sy, ey)
  ! South
  CALL calcul( u, u_new, ex, ex, sy, ey)
  ! West
  CALL calcul( u, u_new, sx, ex, sy, sy)
  ! East
  CALL calcul( u, u_new, sx, ex, ey, ey)

  ! Compute global error
  diffnorm = global_error (u, u_new)

  convergence = ( diffnorm < eps )

END DO

Collective communications

General concepts

Types of collectives

Scatter

Process 2 splits its array of 8 values into blocks of 2 values, and sends one block to each process (including itself):

program scatter
  use mpi
  implicit none

  integer, parameter                :: nb_values=8
  integer                           :: nb_procs,rank,block_length,i,code
  real, allocatable, dimension(:)   :: values,data

  call MPI_INIT(code)
  call MPI_COMM_SIZE(MPI_COMM_WORLD,nb_procs,code)
  call MPI_COMM_RANK(MPI_COMM_WORLD,rank,code)
  block_length=nb_values/nb_procs
  allocate(data(block_length))

  if (rank == 2) then
     allocate(values(nb_values))
     values(:)=(/(1000.+i,i=1,nb_values)/)
     print *,'I, process ',rank,'send my values array : ',&
             values(1:nb_values)
  end if

  call MPI_SCATTER(values,block_length,MPI_REAL,data,block_length, &
                   MPI_REAL,2,MPI_COMM_WORLD,code)
  print *,'I, process ',rank,', received ', data(1:block_length), &
          ' of process 2'
  call MPI_FINALIZE(code)

end program scatter
$ mpiexec -n 4 scatter
 I, process            2 send my values array :    1001.00000       1002.00000       1003.00000       1004.00000       1005.00000       1006.00000       1007.00000       1008.00000
 I, process            0 , received    1001.00000       1002.00000      of process 2
 I, process            1 , received    1003.00000       1004.00000      of process 2
 I, process            3 , received    1007.00000       1008.00000      of process 2
 I, process            2 , received    1005.00000       1006.00000      of process 2

All reduce

Each process contributes a value, and all processes receive the product of all the values, here 10×1×2×3×4×5×6=720010 \times 1 \times 2 \times 3 \times 4 \times 5 \times 6 = 7200:

program allreduce

  use mpi
  implicit none

  integer :: nb_procs,rank,value,product,code

  call MPI_INIT(code)
  call MPI_COMM_SIZE(MPI_COMM_WORLD,nb_procs,code)
  call MPI_COMM_RANK(MPI_COMM_WORLD,rank,code)

  if (rank == 0) then
     value=10
  else
     value=rank
  endif

  call MPI_ALLREDUCE(value,product,1,MPI_INTEGER,MPI_PROD,MPI_COMM_WORLD,code)

  print *,'I, process ',rank,', received the value of the global product ',product

  call MPI_FINALIZE(code)

end program allreduce
$ mpiexec -n 7 allreduce
 I, process            6 , received the value of the global product         7200
 I, process            2 , received the value of the global product         7200
 I, process            0 , received the value of the global product         7200
 I, process            4 , received the value of the global product         7200
 I, process            5 , received the value of the global product         7200
 I, process            3 , received the value of the global product         7200
 I, process            1 , received the value of the global product         7200

Examples

We now revisit the two examples of the OpenMP lecture, this time using MPI. They can be found in the codes/ directory. They were run on an Apple M1 Max laptop with 8 performance cores.

Computing π\pi

We compute π\pi using the integral

π=4∫0111+x2 dx\pi = 4 \int_0^1 \frac{1}{1+x^2} \, dx

approximated with the rectangle rule using n=1010n = 10^{10} points. In contrast to OpenMP, we have to distribute the work ourselves: each task computes the range of indices imin to imax it is responsible for, computes its partial sum, and the partial sums are combined using MPI_ALLREDUCE. We use MPI_WTIME to measure the elapsed time, after an MPI_BARRIER to make sure all tasks start at the same time:

compute_pi_mpi.f90
program compute_pi
  ! Declare and/or Initialize variables
  use mpi
  implicit none
  real(kind=8) :: pi = 4.d0*ATAN(1.d0)

  integer :: narg, info, myid, ncpu
  integer(kind=8) :: i, n, imin, imax
  real(kind=8) :: h = 1
  real(kind=8) :: strt, stop, x, integ, integ_tot
  character(len=80) :: arg

  ! MPI init
  call MPI_INIT(info)
  call MPI_COMM_SIZE(MPI_COMM_WORLD,ncpu,info)
  call MPI_COMM_RANK(MPI_COMM_WORLD,myid,info)

  ! Parse input
  narg = command_argument_count()
  if (narg .eq. 0) then
     n = int(1e10,kind=8)
  else if (narg .eq. 1) then
     call get_command_argument(1, arg)
     read(arg,*) n
  else
     if(myid==0)then
        write(*,*)  'Usage: ./compute_pi [n]'
     endif
     call exit(1)
  end if

  h = 1d0/dble(n)

  if(myid==0)then
     write(*,*)'Starting with ',ncpu,' tasks'
  end if

  call MPI_BARRIER(MPI_COMM_WORLD,info)
  strt = MPI_WTIME()

  imin = int(myid*dble(n)/dble(ncpu),kind=8)+1
  imax = int((myid+1)*dble(n)/dble(ncpu),kind=8)

  integ = 0d0
  do i = imin, imax
     x = dble(i)/dble(n)
     integ = integ + 1d0/(1d0+x**2)*h
  end do

  call MPI_ALLREDUCE(integ,integ_tot,1,MPI_DOUBLE_PRECISION,MPI_SUM,MPI_COMM_WORLD,info)

  stop = MPI_WTIME()

  ! Print result and timing
  if(myid==0)then
     write(*,*)4*integ_tot, PI, PI-4*integ_tot
     write(*,'(A, ES13.6, A)') 'Finished in ', stop-strt, ' s'
  endif

  call MPI_FINALIZE(info)

end program compute_pi
$ mpif90 -O3 -funroll-loops compute_pi_mpi.f90 -o compute_pi_mpi
$ mpiexec -n 8 compute_pi_mpi
 Starting with            8  tasks
   3.1415926534897523        3.1415926535897931        1.0004086448134331E-010
Finished in  1.758260E+00 s
TasksTime (s)Speedup
112.861.0
26.601.9
43.373.8
81.767.3

As with OpenMP, the speedup is close to ideal up to 8 tasks.

The power function

We now parallelize the loop computing the polynomial y=x+x2+⋯+x8y = x + x^2 + \dots + x^8 for n=108n = 10^8 elements. Each task only allocates and initializes its own part of the arrays x and y. The time of a pass is the time of the slowest task, which we obtain using MPI_REDUCE with the MPI_MAX operation:

power_mpi.f90
program power
  use mpi
  implicit none

  integer, parameter :: n=100000000
  real(kind=8), allocatable :: x(:), y(:)
  real(kind=8) :: t0, t1, dt, dt_max
  integer :: i, k, info, myid, ncpu, imin, imax, nloc

  ! MPI init
  call MPI_INIT(info)
  call MPI_COMM_SIZE(MPI_COMM_WORLD,ncpu,info)
  call MPI_COMM_RANK(MPI_COMM_WORLD,myid,info)

  ! Each task only owns its own part of the arrays
  imin = int(myid*dble(n)/dble(ncpu))+1
  imax = int((myid+1)*dble(n)/dble(ncpu))
  nloc = imax-imin+1

  allocate(x(nloc), y(nloc))
  call random_number(x)

  if(myid==0)then
     write(*,*)'Starting with ',ncpu,' tasks'
  end if

  do k=1,4
     call MPI_BARRIER(MPI_COMM_WORLD,info)
     t0 = MPI_WTIME()
     do i=1,nloc
        y(i)=x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i))))))))
     enddo
     t1 = MPI_WTIME()
     ! The pass is finished when the slowest task is finished
     dt = t1-t0
     call MPI_REDUCE(dt,dt_max,1,MPI_DOUBLE_PRECISION,MPI_MAX,0,MPI_COMM_WORLD,info)
     if(myid==0)then
        write(*,*)'pass',k,'time (ms):',1000*dt_max,y(k)
     end if
  enddo

  call MPI_FINALIZE(info)

end program power
$ mpif90 -O3 -funroll-loops power_mpi.f90 -o power_mpi
$ mpiexec -n 4 power_mpi
 Starting with            4  tasks
 pass           1 time (ms):   29.978000000000002       0.59612052417204020
 pass           2 time (ms):   15.930000000000000       0.87243766349443730
 pass           3 time (ms):   10.379000000000000        9.1774036727184136E-002
 pass           4 time (ms):   10.027000000000001       0.41342141851024644

As before, the first pass is slower because of page faults, so we report the time of the last pass:

TasksTime (ms)Speedup
137.11.0
218.22.0
410.03.7
811.93.1

We get the same disappointing result as with OpenMP: beyond 4 tasks, the speedup saturates around 3. Using MPI instead of OpenMP does not help, because all the tasks running on the same node share the same main memory, and the loop is memory bandwidth bound: for only 14 floating point operations per element, we need 24 bytes of memory traffic, and with 4 tasks we already use the maximum bandwidth of about 200 GB/s that the cores can get from the main memory on this machine.

The situation is different on a cluster: if we use 4 tasks on each of several nodes, each node brings its own memory bandwidth, and the speedup will keep increasing with the number of nodes. This is one of the reasons why MPI is so widely used on supercomputers.

OpenMP versus MPI

Conclusion

Parallel computing methods: