Exemple d’utilisation de MPI
MPI (Message Passing Interface) est une bibliothèque et un standard de communications entre noeuds de calcul. Elle gère l’échange des messages entre les processus (transfert de données, synchronisation, opérations globales, etc.). Chaque processus dispose de ses propres données (calcul distribué). Les échanges entre 1 ou plusieurs processus se font dans un communicateur. Chaque processus est identifié pas son rang au sein du groupe.
De nombreuses implémentations différentes de la norme ont été produites, telles que OpenMPI, IntelMPI, MPICH et MVAPICH.
Dans ce qui suit, serot illustrés quelques éléments d’utilisation de cette norme, dans différents langages. Il faut noter que le standard pour C++ a été supprimé depuis MPI 3.0 et qu’il est remplacé par le standard C ou Boost MPI. Python utilise mpi4py.
Introduction
Code séquentiel
L’objectif est de paralléliser le code de base, qui écrit « Hello! ».
en C
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hello!\n");
return(0);
}
en C++
#include <iostream>
int main(int argc, char **argv)
{
std::cout << "Hello!" << std::endl;
return 0;
}
en FORTRAN
program hello
implicit none
print *, 'Hello!'
end program hello
en Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print("Hello!")
en Julia
println("Hello!")
Initialisation de MPI
Tout programme MPI est composé d’un appel à la bibliothèque, puis d’une initialisation de l’environnement, généralement e, début de programme. En fin de programme, l’environnement est quitté.
L’appel à la bibliothèque se fait, suivant les langages, en ajoutant le fichier d’en-tête ou le module approprié, comme mpi.h pour C et use mpi (MPI-2) ou use mpi_f08 (MPI-3) pour FORTRAN.
En FORTRAN, les subroutines renvoient un code d’erreur, facultatif avec mpi_f08. Attention, en C, les appels commencent par MPI_# où # est une majuscule. En Python, il n’est pas nécessaire d’initialiser l’environnement MPI (ni d’expliciter sa fin).
Les codes ci-dessous peuvent être compilés et exécutés en parallèle. Chaque processus exécute une copie du programme séquentiel.
en C
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
int ierr;
// Initialize the MPI environment
ierr = MPI_Init(&argc, &argv);
printf("Hello!\n");
// Quit the MPI environment
ierr = MPI_Finalize();
return(0);
}
en C++
#include <iostream>
#include <mpi.h>
int main(int argc, char **argv)
{
int ierr;
// Initialize the MPI environment
ierr = MPI_Init(&argc, &argv);
std::cout << "Hello!" << std::endl;
// Finalize MPI directives
ierr = MPI_Finalize();
return 0;
}
en FORTRAN
program hello
use mpi_f08
implicit none
integer :: ierr
call MPI_INIT(ierr)
print *, 'Hello!'
call MPI_FINALIZE(ierr)
end program hello
en Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import mpi4py.MPI as MPI
print("Hello!")
en Julia
using MPI
MPI.Init()
println("Hello!")
MPI.Finalize()
Identification des processus
Chaque processus a un rang parmi l’ensemble des processus en cours dans le communicateur. Les rangs dans MPI commencent à partir de 0. S’il y a N processus exécutés, le rang varie de 0 à N-1.
Modifions le programme pour que chaque processus donne son rang dans le communicateur et explicite la machine sur laquelle il travaille.
en C
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[]) {
int nprocs, mypid, name_length;
char hostname[MPI_MAX_PROCESSOR_NAME];
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the total number of tasks and the rank of the process within the communicator
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
// Get the name of the processor
MPI_Get_processor_name(hostname, &name_length);
printf("Hello! I am process %d of %d on %s.\n", mypid, nprocs, hostname);
// Quit the MPI environment
MPI_Finalize();
return 0;
}
en C++
#include <iostream>
#include <mpi.h>
int main(int argc, char **argv)
{
int nprocs, mypid, name_length;
char hostname[MPI_MAX_PROCESSOR_NAME];
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the process size and rank
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
// Get the processor name
MPI_Get_processor_name(hostname, &name_length);
std::cout << "Hello! I am process " << mypid << " of "<< nprocs << " on " << hostname <<".\n" << std::endl;
// Finalize MPI directives
MPI_Finalize();
return 0;
}
en FORTRAN
program hello
use mpi_f08
implicit none
integer :: nprocs, mypid, name_length, ierr = 0
character(MPI_MAX_PROCESSOR_NAME) :: hostname
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
call MPI_GET_PROCESSOR_NAME(hostname, name_length, ierr)
write(*, '(2A, I2, A, I2, 3A)') &
'Hello! ', &
'I am process ', mypid, &
' of ', nprocs, &
' on ', hostname(1:name_length), '.'
call MPI_FINALIZE(ierr)
end program hello
en Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mpi4py.MPI as MPI
# No need to initialize the MPI environment
comm = MPI.COMM_WORLD
# Get the process size and rank
nprocs = comm.Get_size()
mypid = comm.Get_rank()
# Get the processor name
hostname = MPI.Get_processor_name()
print("Hello! I am process {:4d} of {:4d} on {} ".format(mypid, nprocs, hostname), flush=True)
# No need to finalize the MPI environment
en Julia
# get MPI module
using MPI
# initialize MPI environment
MPI.Init()
# define the MPI communicator which is of type MPI.Comm
comm = MPI.COMM_WORLD
# Get the process size and rank
nprocs = MPI.Comm_size(comm::MPI.Comm)
mypid = MPI.Comm_rank(comm::MPI.Comm)
# Get the processor name
hostname = MPI.Get_processor_name(comm::MPI.Comm)
print("Hello world, I am process $(mypid) of $(nprocs) on $(hostname)\n")
MPI.Finalize()
Mesure du temps
Modifions le programme pour que chaque processus affiche son temps d’exécution. Il sera demandé à ce que l’affichage du temps se fasse après l’affichage des numéros et noms de machine, ce qui nécessite d’appeler une barrière de synchronisation.
en C
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[]) {
int nprocs, mypid, name_length;
char hostname[MPI_MAX_PROCESSOR_NAME];
double time_start, time_stop;
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the total number of tasks and the rank of the process within the communicator
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
// Get the name of the processor
MPI_Get_processor_name(hostname, &name_length);
// Synchronize before print and start tic chrono
MPI_Barrier(MPI_COMM_WORLD);
time_start = MPI_Wtime();
printf("Hello! I am process %d of %d on %s.\n", mypid, nprocs, hostname);
// Synchronize before stop tac chrono
MPI_Barrier(MPI_COMM_WORLD);
time_stop = MPI_Wtime();
printf("Time spent by process %d : %f sec.\n", mypid, time_stop - time_start);
// Quit the MPI environment
MPI_Finalize();
return 0;
}
en C++
#include <iostream>
#include <mpi.h>
int main(int argc, char **argv)
{
int nprocs, mypid, name_length;
char hostname[MPI_MAX_PROCESSOR_NAME];
double time_start, time_stop;
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the process size and rank
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
// Get the processor name
MPI_Get_processor_name(hostname, &name_length);
// Synchronize before print and start tic chrono
MPI_Barrier(MPI_COMM_WORLD);
time_start = MPI_Wtime();
std::cout << "Hello! I am process " << mypid << " of "<< nprocs << " on " << hostname <<".\n" << std::endl;
// Synchronize before stop tac chrono
MPI_Barrier(MPI_COMM_WORLD);
time_stop = MPI_Wtime();
std::cout << "Time spent by process " << mypid << " : " << time_stop - time_start << " sec.\n" << std::endl;
// Finalize MPI directives
MPI_Finalize();
return 0;
}
en FORTRAN
program hello
use mpi_f08
implicit none
integer :: nprocs, mypid, name_length, ierr = 0
character(MPI_MAX_PROCESSOR_NAME) :: hostname
real(kind = 8):: time_start, time_stop
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
call MPI_GET_PROCESSOR_NAME(hostname, name_length, ierr)
! synchronization point
call MPI_BARRIER(MPI_COMM_WORLD, ierr)
time_start = MPI_WTIME()
write(*, '(2A, I2, A, I2, 3A)') &
'Hello! ', &
'I am process ', mypid, &
' of ', nprocs, &
' on ', hostname(1:name_length), '.'
call MPI_BARRIER(MPI_COMM_WORLD, ierr)
time_stop = MPI_WTIME()
write(*, '(A, I2, A, E14.7, A)') 'Time spent by process ',mypid, ' : ',time_stop-time_start, ' sec.'
call MPI_FINALIZE(ierr)
end program hello
en Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mpi4py.MPI as MPI
# No need to initialize the MPI environment
comm = MPI.COMM_WORLD
# Get the process size and rank
nprocs = comm.Get_size()
mypid = comm.Get_rank()
# Get the processor name
hostname = MPI.Get_processor_name()
# Synchronize before print and start tic chrono
comm.Barrier()
time_start = MPI.Wtime()
print("Hello! I am process {:4d} of {:4d} on {} ".format(mypid, nprocs, hostname), flush=True)
# Synchronize before stop tac chrono
comm.Barrier()
time_stop = MPI.Wtime()
print("Time spent by process {:4d} : {:4f} ".format(mypid, time_stop-time_start), flush=True)
# No need to finalize the MPI environment
en Julia
# get MPI module
using MPI
# initialize MPI environment
MPI.Init()
# define the MPI communicator which is of type MPI.Comm
comm = MPI.COMM_WORLD
# Get the process size and rank
nprocs = MPI.Comm_size(comm::MPI.Comm)
mypid = MPI.Comm_rank(comm::MPI.Comm)
# Get the processor name
hostname = MPI.Get_processor_name(comm::MPI.Comm)
# Synchronize before print and start tic chrono
MPI.Barrier(comm::MPI.Comm)
time_start = MPI.Wtime()
print("Hello world, I am process $(mypid) of $(nprocs) on $(hostname)\n")
# Synchronize before stop tac chrono
MPI.Barrier(comm::MPI.Comm)
time_stop = MPI.Wtime()
print("Time spent by process $(mypid) : $(time_stop-time_start) src.\n")
MPI.Finalize()
Parallélisation sans communication
On suppose ici qu’on a plusieurs tâches indépendantes à faire.
Code séquentiel
Voici un code séquentiel effectuant une boucle itérative de taille N affichant le numéro de l’itération. On note que suivant les langages, les boucles commencent à 0 ou 1, suivant l’indice par défaut du début des tableaux, qui seront manipulés par la suite. Chaque itération de la boucle effectue une opération locale, où seul l’indice local de l’itération est utilisé : il n’y a aucune dépendance entre les itérations.
en C
#include <stdio.h>
int main(int argc, char *argv[])
{
int N = 50;
for( int i=0; i<N; i++ ) {
printf("I'm printing the number %d.\n", i);
}
return(0);
}
en C++
#include <iostream>
int main(int argc, char **argv)
{
int N = 50;
for( int i=0; i<N; i++ ) {
std::cout << "I'm printing the number " << i << "." << std::endl;
}
return 0;
}
en FORTRAN
program main
implicit none
integer :: i, N
N = 50
do i = 1, N
write(*,*) "I'm printing the number ", i, "."
end do
end program main
en Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
N = 50
for i in range(N):
print("I'm printing the number {}.".format(i))
en Julia
N = 50
for i in 1:N
println("I'm printing the number ", i, ".")
end
Code MPI
Dans les versions parallélisées avec MPI, la boucle est décomposée entre nprocs processus. On décomposera la boucle pour équilibrer la charge au mieux entre les processus.
en C
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
int i, N;
int mypid, nprocs, ierr;
int nstart, nstop, npart, ncount, nrem;
N = 50;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
ncount = N / nprocs;
nrem = N % nprocs;
if (mypid < nrem) {
nstart = mypid * (ncount + 1);
nstop = nstart + ncount;
} else {
nstart = mypid * ncount + nrem;
nstop = nstart + (ncount - 1);
}
npart = nstop - nstart + 1;
for (i = nstart; i <= nstop; i++) {
printf("I'm proc. %d printing the number %d.\n", mypid, i);
}
MPI_Finalize();
return(0);
}
en C++
#include <iostream>
#include <mpi.h>
int main(int argc, char* argv[]) {
int i, N;
int mypid, nprocs, ierr;
int nstart, nstop, npart, ncount, nrem;
N = 50;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
ncount = N / nprocs;
nrem = N % nprocs;
if (mypid < nrem) {
nstart = mypid * (ncount + 1);
nstop = nstart + ncount;
} else {
nstart = mypid * ncount + nrem;
nstop = nstart + (ncount - 1);
}
npart = nstop - nstart + 1;
for (i = nstart; i <= nstop; i++) {
std::cout << "I'm proc. " << mypid << " printing the number " << i << "." << std::endl;
}
MPI_Finalize();
return 0;
}
en FORTRAN
program main
use mpi_f08
implicit none
integer :: i, N
integer :: mypid, nprocs, ierr
integer :: nstart, nstop, npart, ncount, nrem
N = 50
call MPI_INIT(ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
ncount = N/nprocs
nrem = MOD(N,nprocs)
IF (mypid < nrem) THEN
nstart = mypid * (ncount + 1)
nstop = nstart + ncount
ELSE
nstart = mypid * ncount + nrem
nstop = nstart + (ncount - 1)
END IF
npart = nstop-nstart+1
do i = nstart, nstop
write(*,*) "I'm proc. ", mypid," printing the number ", i, "."
end do
call MPI_FINALIZE(ierr)
end program main
en Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from mpi4py import MPI
comm = MPI.COMM_WORLD
mypid = comm.Get_rank()
nprocs = comm.Get_size()
N = 50
ncount = N // nprocs
nrem = N % nprocs
if mypid < nrem:
nstart = mypid * (ncount + 1)
nstop = nstart + ncount
else:
nstart = mypid * ncount + nrem
nstop = nstart + (ncount - 1)
npart = nstop - nstart + 1
for i in range(nstart, nstop + 1):
print("I'm proc.", mypid, "printing the number", i, ".")
en Julia
using MPI
N = 50
comm = MPI.COMM_WORLD
mypid = MPI.Comm_rank(comm)
nprocs = MPI.Comm_size(comm)
ncount = div(N, nprocs)
nrem = mod(N, nprocs)
if mypid < nrem
nstart = mypid * (ncount + 1)
nstop = nstart + ncount
else
nstart = mypid * ncount + nrem
nstop = nstart + (ncount - 1)
end
npart = nstop - nstart + 1
for i = nstart:nstop
println("I'm proc. ", mypid, " printing the number ", i, ".")
end
MPI.Finalize()
Introduction aux communications point à point
Dans les programmes précédents, les processus n’échangent pas d’information. Il existe de nombreuses façon pour échanger des informations entre chacun des processus. À titre d’introduction, reprenons le programme hello dans lequel, les processus devront s’échanger des messages.
Communication point à point entre 2 processus
Le programme suivant ne fonctionne qu’avec un ensemble de deux processus. Un processus envoie à l’autre un message, constitué par un entier ayant pour valeur son rang dans le communicateur auquel s’ajoute l’entier 5. Dans l’exemple, les 2 processus échangent simultanément en une seule commande sendrecv. Pour envoyer (ou recevoir) un message, il est nécessaire d’en connaître la taille et le type. Ici, il s’agit d’une seule valeur, de type entier.
en C
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
int mypid, nprocs, ierr = 0, code;
int peer;
int var_recv, var_send;
int tag_send, tag_recv;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
// Rejeter si le nombre de processus diffère de 2
if (nprocs != 2) {
if (mypid == 0)
printf("Error: only 2 processes should be used\n");
MPI_Abort(MPI_COMM_WORLD, ierr);
} else {
// Obtenir l'ID de l'autre processus
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
// Chaque processus envoie un entier en ajoutant 5 à son rang
var_send = mypid + 5;
MPI_Sendrecv(&var_send, 1, MPI_INT, peer, tag_send,
&var_recv, 1, MPI_INT, peer, tag_recv,
MPI_COMM_WORLD, MPI_STATUS_IGNORE);
printf("I am process %d of %d and received %d from process %d\n",
mypid, nprocs, var_recv, peer);
MPI_Finalize();
return 0;
}
en C++
#include <iostream>
#include <mpi.h>
int main(int argc, char **argv)
{
int mypid, nprocs, ierr = 0, code;
int peer;
int var_recv, var_send;
int tag_send, tag_recv;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
// Rejeter si le nombre de processus diffère de 2
if (nprocs != 2) {
if (mypid == 0)
std::cout << "Error: only 2 processes should be used" << std::endl;
MPI_Abort(MPI_COMM_WORLD, ierr);
} else {
// Obtenir l'ID de l'autre processus
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
// Chaque processus envoie un entier en ajoutant 5 à son rang
var_send = mypid + 5;
MPI_Sendrecv(&var_send, 1, MPI_INT, peer, tag_send,
&var_recv, 1, MPI_INT, peer, tag_recv,
MPI_COMM_WORLD, MPI_STATUS_IGNORE);
std::cout << "I am process " << mypid << " of " << nprocs
<< " and received " << var_recv << " from process " << peer << std::endl;
MPI_Finalize();
return 0;
}
en FORTRAN
program sendrecv
use mpi_f08
implicit none
integer :: mypid, nprocs, ierr = 0, code
integer :: peer
integer :: var_recv, var_send
integer :: tag_send, tag_recv
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
! Reject if the number of processes differs from 2
if (nprocs /= 2) then
if (mypid == 0) print *, 'Error: only 2 processes should be used'
call MPI_ABORT(MPI_COMM_WORLD, ierr, code)
else
! Get the other process id number
peer = mod(mypid+1, 2)
end if
tag_send = 0
tag_recv = tag_send
! Each processus send an integer adding 5 to its rank
var_send = mypid + 5
call MPI_SENDRECV(var_send, 1, MPI_INTEGER, peer, tag_send, &
var_recv, 1, MPI_INTEGER, peer, tag_recv, &
MPI_COMM_WORLD, MPI_STATUS_IGNORE, ierr)
print *,'I am process', mypid, ' of ', nprocs, &
' and received ', var_recv, ' from process', peer
call MPI_FINALIZE(ierr)
end program sendrecv
en Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mpi4py.MPI as MPI
comm = MPI.COMM_WORLD
nprocs = comm.Get_size()
mypid = comm.Get_rank()
peer = (mypid + 1) % 2
# Chaque processus envoie un entier en ajoutant 5 à son rang
var_send = mypid + 5
var_recv = comm.sendrecv(var_send, dest=peer, source=peer)
print(f"I am process {mypid} of {nprocs} and received {var_recv} from process {peer}")
en Julia
using MPI
MPI.Init()
comm = MPI.COMM_WORLD
nprocs = MPI.Comm_size(comm::MPI.Comm)
mypid = MPI.Comm_rank(comm::MPI.Comm)
peer = (mypid + 1) % 2
tag_send = 0
tag_recv = tag_send
# Chaque processus envoie un entier en ajoutant 5 à son rang
var_send = mypid + 5
var_recv = MPI.sendrecv(var_send, peer, tag_send, peer, tag_recv, comm::MPI.comm)
println("I am process $mypid of $nprocs and received $var_recv from process $peer")
MPI.Finalize()
Ici la communication se fait par une seule commande MPI_SENDRECV afin d’éviter des problèmes de blocage dans la communication entre les deux processus. Cette commande peut être faite en deux temps, en séparant MPI_SEND et MPI_RECV. Ce sont des commandes sont dites bloquantes.
MPI_SEND est terminé lorsque toutes les données sont envoyées et que le message passé peut être écrasé.
MPI_RECV est terminé lorsque toutes les données sont reçues et peuvent être utilisées.
On peut noter que lorsque peu de données sont échangées, aucun blocage ne se produit. Il a lieu lorsque la quantité de données échangées est assez grande pour remplir la mémoire tampon utilisée pour communiquer.
Cas de blocage potentiel (deadlock)
Les programmes suivants peuvent générer des problèmes de blocage lorsque l’implémentation est synchrone. En effet, chacun des deux processus attendrait un ordre de réception qui ne viendrait jamais, puisque les deux envois resteraient en suspens.
en C
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
// WARNING: a deadlock may occur, depending of N values
// N size of the array message
#define N 1000
int main(int argc, char *argv[])
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
MPI_Status statut;
double var_send[N], var_recv[N];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0) printf("Error: only 2 processes should be used\n");
MPI_Abort(MPI_COMM_WORLD, ierr);
exit(1);
}
else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++) {
var_send[i] = (double)mypid * 5.0;
}
MPI_Send(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD);
MPI_Recv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &statut);
printf("I am process %d of %d and received ", mypid, nprocs);
for (int i = 0; i < 3; i++) {
printf("%f ", var_recv[i]);
}
printf("... from process %d\n", peer);
MPI_Finalize();
return 0;
}
en C++
#include <iostream>
#include <mpi.h>
// WARNING: a deadlock may occur, depending of N values
// N size of the array message
#define N 1000
int main(int argc, char** argv)
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
MPI_Status statut;
double var_send[N], var_recv[N];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0)
std::cout << "Error: only 2 processes should be used" << std::endl;
MPI_Abort(MPI_COMM_WORLD, ierr);
exit(1);
} else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++) {
var_send[i] = static_cast<double>(mypid) * 5.0;
}
MPI_Send(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD);
MPI_Recv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &statut);
std::cout << "I am process " << mypid << " of " << nprocs << " and received ";
for (int i = 0; i < 3; i++) {
std::cout << var_recv[i] << " ";
}
std::cout << "... from process " << peer << std::endl;
MPI_Finalize();
return 0;
}
en FORTRAN
program sendrecv
! WARNING: a deadlock may occur, depending of N values
! N size of the array message
use mpi_f08
implicit none
TYPE(MPI_STATUS) :: statut
integer :: mypid, nprocs, ierr = 0, code
integer :: peer
integer :: tag_send, tag_recv
! Large message
integer, parameter :: N=1000 ! deadlock
!integer, parameter :: N=3 ! no deadlock
double precision :: var_send(N), var_recv(N)
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
! Reject if the number of processes differs from 2
if (nprocs /= 2) then
if (mypid == 0) print *, 'Error: only 2 processes should be used'
call MPI_ABORT(MPI_COMM_WORLD, ierr, code)
else
! Get the other process id number
peer = mod(mypid+1, 2)
end if
tag_send = 0
tag_recv = tag_send
! Each process sends an array of values 5 times its rank
var_send = DBLE(mypid)*5.D0
call MPI_SEND(var_send, N, MPI_DOUBLE_PRECISION, peer, tag_send, MPI_COMM_WORLD, ierr)
call MPI_RECV(var_recv, N, MPI_DOUBLE_PRECISION, peer, tag_recv, MPI_COMM_WORLD, statut, ierr)
print *,'I am process', mypid, ' of ', nprocs, &
' and received ', var_recv(1:3), ' ... from process', peer
call MPI_FINALIZE(ierr)
end program sendrecv
en Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from mpi4py import MPI
import numpy as np
# WARNING: a deadlock may occur, depending of N values
# N size of the array message
N = 1000
comm = MPI.COMM_WORLD
nprocs = comm.Get_size()
mypid = comm.Get_rank()
if nprocs != 2:
if mypid == 0:
print("Error: only 2 processes should be used")
comm.Abort(1)
peer = (mypid + 1) % 2
tag_send = 0
tag_recv = tag_send
var_send = np.empty(N, dtype=np.float64)
var_recv = np.empty(N, dtype=np.float64)
var_send.fill(float(mypid) * 5.0)
comm.Send(var_send, dest=peer, tag=tag_send)
comm.Recv(var_recv, source=peer, tag=tag_recv)
print(f"I am process {mypid} of {nprocs} and received {var_recv[:3]} ... from process {peer}")
en Julia
using MPI
#=
# WARNING: a deadlock may occur, depending of N values
# N size of the array message
=#
const N = 1000
MPI.Init()
comm = MPI.COMM_WORLD
nprocs = MPI.Comm_size(comm)
mypid = MPI.Comm_rank(comm)
if nprocs != 2
if mypid == 0
println("Error: only 2 processes should be used")
end
MPI.Abort(comm, 1)
end
peer = mod(mypid + 1, 2)
tag_send = 0
tag_recv = tag_send
var_send = fill(float(mypid) * 5.0, N)
var_recv = zeros(Float64, N)
MPI.Send(var_send, peer, tag_send, comm)
MPI.Recv(var_recv, peer, tag_recv, comm)
println("I am process $mypid of $nprocs and received ", var_recv[1:3], " ... from process $peer")
MPI.Finalize()
Lever le blocage explicitement
Il y a plusieurs façon d’éviter le verrouillage des communications. Utiliser MPI_SENDRECV en est une, ça donne
en C
#include <stdio.h>
#include <mpi.h>
#define N 1000
int main(int argc, char *argv[])
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
MPI_Status status;
double var_send[N], var_recv[N];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0) printf("Error: only 2 processes should be used\n");
MPI_Abort(MPI_COMM_WORLD, ierr);
} else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++) {
var_send[i] = (double)mypid * 5.0;
}
MPI_Sendrecv(var_send, N, MPI_DOUBLE, peer, tag_send,
var_recv, N, MPI_DOUBLE, peer, tag_recv,
MPI_COMM_WORLD, &status);
printf("I am process %d of %d and received ", mypid, nprocs);
for (int i = 0; i < 3; i++) {
printf("%f ", var_recv[i]);
}
printf("... from process %d\n", peer);
MPI_Finalize();
return 0;
}
en C++
#include <stdio.h>
#include <mpi.h>
#define N 1000
int main(int argc, char **argv)
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
MPI_Status status;
double var_send[N], var_recv[N];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0) printf("Error: only 2 processes should be used\n");
MPI_Abort(MPI_COMM_WORLD, ierr);
} else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++) {
var_send[i] = (double)mypid * 5.0;
}
MPI_Sendrecv(var_send, N, MPI_DOUBLE, peer, tag_send,
var_recv, N, MPI_DOUBLE, peer, tag_recv,
MPI_COMM_WORLD, &status);
printf("I am process %d of %d and received ", mypid, nprocs);
for (int i = 0; i < 3; i++) {
printf("%f ", var_recv[i]);
}
printf("... from process %d\n", peer);
MPI_Finalize();
return 0;
}
en FORTRAN
program sendrecv
use mpi_f08
implicit none
TYPE(MPI_STATUS) :: statut
integer :: mypid, nprocs, ierr = 0, code
integer :: peer
integer :: tag_send, tag_recv
! Large message
integer, parameter :: N=1000
double precision :: var_send(N), var_recv(N)
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
! Reject if the number of processes differs from 2
if (nprocs /= 2) then
if (mypid == 0) print *, 'Error: only 2 processes should be used'
call MPI_ABORT(MPI_COMM_WORLD, ierr, code)
else
! Get the other process id number
peer = mod(mypid+1, 2)
end if
tag_send = 0
tag_recv = tag_send
! Each process sends an array of values 5 times its rank
var_send = DBLE(mypid)*5.D0
call MPI_SENDRECV(var_send, N, MPI_DOUBLE_PRECISION, peer, tag_send, &
var_recv, N, MPI_DOUBLE_PRECISION, peer, tag_recv, &
MPI_COMM_WORLD, statut, ierr)
print *,'I am process', mypid, ' of ', nprocs, &
' and received ', var_recv(1:3), ' ... from process', peer
call MPI_FINALIZE(ierr)
end program sendrecv
en Python
from mpi4py import MPI
N = 1000
comm = MPI.COMM_WORLD
nprocs = comm.Get_size()
mypid = comm.Get_rank()
if nprocs != 2:
if mypid == 0:
print("Error: only 2 processes should be used")
MPI.Abort()
peer = (mypid + 1) % 2
tag_send = 0
tag_recv = tag_send
var_send = [mypid * 5.0] * N
var_recv = [0.0] * N
var_recv = comm.sendrecv(var_send, dest=peer, source=peer)
print("I am process", mypid, "of", nprocs, "and received", var_recv[:3], "... from process", peer)
en Julia
using MPI
const N = 1000
MPI.Init()
comm = MPI.COMM_WORLD
nprocs = MPI.Comm_size(comm)
mypid = MPI.Comm_rank(comm)
if nprocs != 2
if mypid == 0
println("Error: only 2 processes should be used")
end
MPI.Abort(comm)
else
peer = (mypid + 1) % 2
end
tag_send = 0
tag_recv = tag_send
var_send = fill(mypid * 5.0, N)
var_recv = zeros(N)
MPI.Sendrecv!(var_send, peer, tag_send, var_recv, peer, tag_recv, comm)
println("I am process", mypid, "of", nprocs, "and received", var_recv[1:3], "... from process", peer)
MPI.Finalize()
Parfois, il est nécessaire de dissocier le réception de l’envoi. Une possibilité est d’expliciter ce qui se passe pour chacun des processus concernés par ces communications point à point.
en C
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define N 1000
int main(int argc, char *argv[])
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
MPI_Status statut;
double var_send[N], var_recv[N];
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0)
printf("Error: only 2 processes should be used\n");
MPI_Abort(MPI_COMM_WORLD, code);
}
else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++) {
var_send[i] = (double)mypid * 5.0;
}
if (mypid == 0) {
MPI_Recv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &statut);
MPI_Send(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD);
}
else {
MPI_Send(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD);
MPI_Recv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &statut);
}
printf("I am process %d of %d and received %.2f, %.2f, %.2f ... from process %d\n",
mypid, nprocs, var_recv[0], var_recv[1], var_recv[2], peer);
MPI_Finalize();
return 0;
}
en C++
#include <iostream>
#include <mpi.h>
#define N 1000
int main(int argc, char **argv)
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
MPI_Status statut;
double var_send[N], var_recv[N];
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0)
std::cout << "Error: only 2 processes should be used" << std::endl;
MPI_Abort(MPI_COMM_WORLD, code);
}
else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++) {
var_send[i] = static_cast<double>(mypid) * 5.0;
}
if (mypid == 0) {
MPI_Recv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &statut);
MPI_Send(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD);
}
else {
MPI_Send(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD);
MPI_Recv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &statut);
}
std::cout << "I am process " << mypid << " of " << nprocs << " and received "
<< var_recv[0] << ", " << var_recv[1] << ", " << var_recv[2]
<< " ... from process " << peer << std::endl;
MPI_Finalize();
return 0;
}
en FORTRAN
program sendrecv
use mpi_f08
implicit none
TYPE(MPI_STATUS) :: statut
integer :: mypid, nprocs, ierr = 0, code
integer :: peer
integer :: tag_send, tag_recv
! Large message
integer, parameter :: N=1000
double precision :: var_send(N), var_recv(N)
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
! Reject if the number of processes differs from 2
if (nprocs /= 2) then
if (mypid == 0) print *, 'Error: only 2 processes should be used'
call MPI_ABORT(MPI_COMM_WORLD, ierr, code)
else
! Get the other process id number
peer = mod(mypid+1, 2)
end if
tag_send = 0
tag_recv = tag_send
! Each process sends an array of values 5 times its rank
var_send = DBLE(mypid)*5.D0
if (mypid == 0) then
call MPI_RECV(var_recv, N, MPI_DOUBLE_PRECISION, peer, tag_recv, MPI_COMM_WORLD, statut, ierr)
call MPI_SEND(var_send, N, MPI_DOUBLE_PRECISION, peer, tag_send, MPI_COMM_WORLD, ierr)
else
call MPI_SEND(var_send, N, MPI_DOUBLE_PRECISION, peer, tag_send, MPI_COMM_WORLD, ierr)
call MPI_RECV(var_recv, N, MPI_DOUBLE_PRECISION, peer, tag_recv, MPI_COMM_WORLD, statut, ierr)
end if
print *,'I am process', mypid, ' of ', nprocs, &
' and received ', var_recv(1:3), ' ... from process', peer
call MPI_FINALIZE(ierr)
end program sendrecv
en Python
from mpi4py import MPI
import numpy as np
N = 1000
comm = MPI.COMM_WORLD
mypid = comm.Get_rank()
nprocs = comm.Get_size()
tag_send = 0
tag_recv = tag_send
var_send = np.zeros(N)
var_recv = np.zeros(N)
if nprocs != 2:
if mypid == 0:
print("Error: only 2 processes should be used")
MPI.COMM_WORLD.Abort(1)
peer = (mypid + 1) % 2
for i in range(N):
var_send[i] = float(mypid) * 5.0
if mypid == 0:
comm.Recv(var_recv, source=peer, tag=tag_recv)
comm.Send(var_send, dest=peer, tag=tag_send)
else:
comm.Send(var_send, dest=peer, tag=tag_send)
comm.Recv(var_recv, source=peer, tag=tag_recv)
print("I am process", mypid, "of", nprocs, "and received", var_recv[:3],
"... from process", peer)
MPI.Finalize()
en Julia
using MPI
const N = 1000
MPI.Init()
comm = MPI.COMM_WORLD
mypid = MPI.Comm_rank(comm)
nprocs = MPI.Comm_size(comm)
tag_send = 0
tag_recv = tag_send
var_send = zeros(Float64, N)
var_recv = zeros(Float64, N)
if nprocs != 2
if mypid == 0
println("Error: only 2 processes should be used")
end
MPI.Abort(comm, 1)
else
peer = (mypid + 1) % 2
end
for i in 1:N
var_send[i] = Float64(mypid) * 5.0
end
if mypid == 0
MPI.recv!(var_recv, peer, tag_recv, comm)
MPI.send!(var_send, peer, tag_send, comm)
else
MPI.send!(var_send, peer, tag_send, comm)
MPI.recv!(var_recv, peer, tag_recv, comm)
end
println("I am process ", mypid, " of ", nprocs, " and received ", var_recv[1:3],
" ... from process ", peer)
MPI.Finalize()
Lever le blocage avec les commandes asynchrones
Une possibilité pour lever le blocage peut être d’utiliser les commandes MPI_ISEND, MPI_IRECV et MPI_WAIT.
en C
#include <stdio.h>
#include <mpi.h>
#define N 1000
int main(int argc, char *argv[])
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
double var_send[N], var_recv[N];
MPI_Status send_status, recv_status;
MPI_Request send_request, recv_request;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0)
printf("Error: only 2 processes should be used\n");
MPI_Abort(MPI_COMM_WORLD, code);
}
else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++)
var_send[i] = (double)mypid * 5.0;
if (mypid == 0) {
MPI_Isend(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD, &send_request);
MPI_Wait(&send_request, &send_status);
}
else {
MPI_Irecv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &recv_request);
MPI_Wait(&recv_request, &recv_status);
}
if (mypid == 0) {
MPI_Irecv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &recv_request);
MPI_Wait(&recv_request, &recv_status);
}
else {
MPI_Isend(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD, &send_request);
MPI_Wait(&send_request, &send_status);
}
printf("I am process %d of %d and received ", mypid, nprocs);
for (int i = 0; i < 3; i++)
printf("%f ", var_recv[i]);
printf("... from process %d\n", peer);
MPI_Finalize();
return 0;
}
en C++
#include <iostream>
#include <mpi.h>
#define N 1000
int main(int argc, char **argv)
{
int mypid, nprocs, ierr, code;
int peer;
int tag_send, tag_recv;
double var_send[N], var_recv[N];
MPI_Status send_status, recv_status;
MPI_Request send_request, recv_request;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
if (nprocs != 2) {
if (mypid == 0)
std::cout << "Error: only 2 processes should be used" << std::endl;
MPI_Abort(MPI_COMM_WORLD, code);
}
else {
peer = (mypid + 1) % 2;
}
tag_send = 0;
tag_recv = tag_send;
for (int i = 0; i < N; i++)
var_send[i] = static_cast<double>(mypid) * 5.0;
if (mypid == 0) {
MPI_Isend(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD, &send_request);
MPI_Wait(&send_request, &send_status);
}
else {
MPI_Irecv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &recv_request);
MPI_Wait(&recv_request, &recv_status);
}
if (mypid == 0) {
MPI_Irecv(var_recv, N, MPI_DOUBLE, peer, tag_recv, MPI_COMM_WORLD, &recv_request);
MPI_Wait(&recv_request, &recv_status);
}
else {
MPI_Isend(var_send, N, MPI_DOUBLE, peer, tag_send, MPI_COMM_WORLD, &send_request);
MPI_Wait(&send_request, &send_status);
}
std::cout << "I am process " << mypid << " of " << nprocs << " and received ";
for (int i = 0; i < 3; i++)
std::cout << var_recv[i] << " ";
std::cout << "... from process " << peer << std::endl;
MPI_Finalize();
return 0;
}
en FORTRAN
program sendrecv
use mpi_f08
implicit none
TYPE(MPI_STATUS) :: send_status, recv_status
TYPE(MPI_REQUEST) :: send_request, recv_request
integer :: mypid, nprocs, ierr = 0, code
integer :: peer
integer :: tag_send, tag_recv
!integer :: send_request, recv_request
!integer :: send_status, recv_status
! Large message
integer, parameter :: N=1000
double precision :: var_send(N), var_recv(N)
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
! Reject if the number of processes differs from 2
if (nprocs /= 2) then
if (mypid == 0) print *, 'Error: only 2 processes should be used'
call MPI_ABORT(MPI_COMM_WORLD, ierr, code)
else
! Get the other process id number
peer = mod(mypid+1, 2)
end if
tag_send = 0
tag_recv = tag_send
! Each process sends an array of values 5 times its rank
var_send = DBLE(mypid)*5.D0
if (mypid == 0) then
call MPI_ISEND(var_send, N, MPI_DOUBLE_PRECISION, peer, tag_send, &
MPI_COMM_WORLD, send_request, ierr)
call MPI_WAIT(send_request, send_status, ierr)
else
call MPI_IRECV(var_recv, N, MPI_DOUBLE_PRECISION, peer, tag_recv, &
MPI_COMM_WORLD, recv_request, ierr)
call MPI_WAIT(recv_request, recv_status, ierr)
end if
if (mypid == 0) then
call MPI_IRECV(var_recv, N, MPI_DOUBLE_PRECISION, peer, tag_recv, &
MPI_COMM_WORLD, recv_request, ierr)
call MPI_WAIT(recv_request, recv_status, ierr)
else
call MPI_ISEND(var_send, N, MPI_DOUBLE_PRECISION, peer, tag_send, &
MPI_COMM_WORLD, send_request, ierr)
call MPI_WAIT(send_request, send_status, ierr)
end if
print *,'I am process', mypid, ' of ', nprocs, &
' and received ', var_recv(1:3), ' ... from process', peer
call MPI_FINALIZE(ierr)
end program sendrecv
en Python
from mpi4py import MPI
import numpy as np
N = 1000
comm = MPI.COMM_WORLD
mypid = comm.Get_rank()
nprocs = comm.Get_size()
peer = (mypid + 1) % 2
tag_send = 0
tag_recv = tag_send
var_send = np.empty(N, dtype=np.float64)
var_recv = np.empty(N, dtype=np.float64)
if nprocs != 2:
if mypid == 0:
print("Error: only 2 processes should be used")
MPI.COMM_WORLD.Abort(1)
for i in range(N):
var_send[i] = float(mypid) * 5.0
if mypid == 0:
send_request = comm.Isend([var_send, MPI.DOUBLE], dest=peer, tag=tag_send)
send_request.wait()
else:
recv_request = comm.Irecv([var_recv, MPI.DOUBLE], source=peer, tag=tag_recv)
recv_request.wait()
if mypid == 0:
recv_request = comm.Irecv([var_recv, MPI.DOUBLE], source=peer, tag=tag_recv)
recv_request.wait()
else:
send_request = comm.Isend([var_send, MPI.DOUBLE], dest=peer, tag=tag_send)
send_request.wait()
print(f"I am process {mypid} of {nprocs} and received {var_recv[:3]} ... from process {peer}")
en Julia
using MPI
const N = 1000
MPI.Init()
comm = MPI.COMM_WORLD
mypid = MPI.Comm_rank(comm)
nprocs = MPI.Comm_size(comm)
peer = (mypid + 1) % 2
tag_send = 0
tag_recv = tag_send
var_send = zeros(Float64, N)
var_recv = zeros(Float64, N)
if nprocs != 2
if mypid == 0
println("Error: only 2 processes should be used")
end
MPI.Abort(comm, 1)
end
for i in 1:N
var_send[i] = Float64(mypid) * 5.0
end
if mypid == 0
send_request = MPI.Isend(comm, var_send, peer, tag_send)
MPI.Wait(send_request)
else
recv_request = MPI.Irecv(comm, var_recv, peer, tag_recv)
MPI.Wait(recv_request)
end
if mypid == 0
recv_request = MPI.Irecv(comm, var_recv, peer, tag_recv)
MPI.Wait(recv_request)
else
send_request = MPI.Isend(comm, var_send, peer, tag_send)
MPI.Wait(send_request)
end
println("I am process $mypid of $nprocs and received $(var_recv[1:3]) ... from process $peer")
MPI.Finalize()
Somme d’un vecteur, code séquentiel
Voici un code séquentiel effectuant la somme de l’ensemble des éléments d’un vecteur de réels de taille N. Les réels sont codés en double précision.
en C
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int N, i;
double res;
double *vector;
N = 10;
// Allocate vector
vector = (double *)malloc(N * sizeof(double));
if (vector == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
// Initialize
for (i=0; i<N; i++) {
vector[i] = 1.0;
}
// Compute the sum of all elements of the vector
res = 0.0;
for (i=0; i<N; i++) {
res += vector[i];
}
// Print the result
printf("The sum of all elements in the vector is: %lf\n", res);
free(vector);
return(0);
}
en C++
#include <iostream>
#include <vector>
#include <numeric>
int main(int argc, char **argv)
{
int N = 10;
std::vector<double> vector(N, 1.0);
double res = std::accumulate(vector.begin(), vector.end(), 0.0);
std::cout << "The sum of all elements in the vector is: " << res << std::endl;
return 0;
}
en FORTRAN
program main
implicit none
integer, parameter :: dp = kind(1.d0)
integer :: N
integer :: i
real(dp) :: res
real(dp), allocatable :: vector(:)
N = 10
! Allocate
allocate(vector(N))
! Initialize
vector(:) = 1._dp
! Compute the sum of all elements of the vector
res = sum(vector)
! Print the result
print *, 'The sum of all elements in the vector is: ', res
deallocate(vector)
end program main
en Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
N = 10
vector = np.ones(N)
res = np.sum(vector)
print("The sum of all elements in the vector is:", res)
en Julia
# Define the size of the vector
N = 10
# Allocate memory for the vector
vector = zeros(Float64, N)
# Initialize the vector with ones
vector .= 1.0
# Compute the sum of all elements of the vector
res = sum(vector)
# Print the result
println("The sum of all elements in the vector is: $res")
Code MPI
On parallélise avec MPI en décomposant le calcul de la somme par tronçons répartis entre nprocs processus. Il faut noter que le calcul de la somme globale implique une opération de communication entre les processus, appelée réduction.
en C
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
int N, N_local;
int mypid, nprocs, ierr;
int ncount, nrem, istart, iend, i;
double res, local_sum;
double *vector;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
// Size of the global vector
N = 1000000000;
// Decomposition
ncount = N/nprocs;
nrem = N%nprocs;
if (mypid < nrem) {
istart = mypid * (ncount + 1);
iend = istart + ncount;
} else {
istart = mypid * ncount + nrem;
iend = istart + (ncount - 1);
}
N_local = iend - istart + 1;
// Allocate vector on each process
vector = (double *)malloc(N_local * sizeof(double));
if (vector == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
// Initialize vector on each process
for (i=0; i<N_local; i++) {
vector[i] = 1.0;
}
// Compute local sum
local_sum = 0.0;
for (i=0; i<N_local; i++) {
local_sum += vector[i];
}
// Reduce local sums to obtain global sum on process 0
MPI_Reduce(&local_sum, &res, 1, MPI_DOUBLE_PRECISION, MPI_SUM, 0, MPI_COMM_WORLD);
// After the reduction because of the implicit barrier
free(vector);
if (mypid == 0) {
// Print the result
printf("The sum of all elements in the vector is: %lf\n", res);
}
MPI_Finalize();
return 0;
}
en C++
#include <iostream>
#include <vector>
#include <numeric>
#include <mpi.h>
int main(int argc, char **argv)
{
int N;
int mypid, nprocs, ierr;
int ncount, nrem, istart, iend;
double local_sum = 0.0, global_sum = 0.0;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &mypid);
N = 1000000000;
// Distribute the vector among the processes
ncount = N / nprocs;
nrem = N % nprocs;
if (mypid < nrem) {
istart = mypid * (ncount + 1);
iend = istart + ncount;
} else {
istart = mypid * ncount + nrem;
iend = istart + (ncount - 1);
}
std::vector<double> local_vector(iend - istart + 1, 1.0);
// Compute the local sum
local_sum = std::accumulate(local_vector.begin(), local_vector.end(), 0.0);
// Reduce the local sums to obtain the global sum
MPI_Reduce(&local_sum, &global_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
// After the reduction because of the implicit barrier
delete[] vector;
if (mypid == 0) {
std::cout << "The sum of all elements in the vector is: " << global_sum << std::endl;
}
MPI_Finalize();
return 0;
}
en FORTRAN
program main
use mpi
implicit none
integer, parameter :: dp = kind(1.d0)
integer :: N, N_local
integer :: mypid, nprocs, ierr
integer :: ncount, nrem, istart, iend, i
real(dp) :: res, local_sum
real(dp), allocatable :: vector(:)
call MPI_INIT(ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD, nprocs, ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD, mypid, ierr)
! Size of the global vector
N = 1000000000
! Decomposition
ncount = N/nprocs
nrem = MOD(N,nprocs)
IF (mypid < nrem) THEN
istart = mypid * (ncount + 1)
iend = istart + ncount
ELSE
istart = mypid * ncount + nrem
iend = istart + (ncount - 1)
END IF
N_local = iend - istart + 1
! Allocate vector on each processes
allocate(vector(N_local))
! Initialize vector on each processes
vector(:) = 1.0_dp
! Compute local sum
local_sum = SUM(vector)
! Reduce local sums to obtain global sum on process 0
call MPI_REDUCE(local_sum, res, 1, MPI_DOUBLE_PRECISION, MPI_SUM, 0, MPI_COMM_WORLD, ierr)
! After the reduction because of the implicit barrier
deallocate(vector)
if (mypid == 0) then
! Print the result
print *, 'The sum of all elements in the vector is: ', res
end if
call MPI_Finalize(ierr)
end program main
en Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from mpi4py import MPI
import numpy as np
comm = MPI.COMM_WORLD
nprocs = comm.Get_size()
mypid = comm.Get_rank()
N = 1000000000
ncount = N // nprocs
nrem = N % nprocs
if mypid < nrem:
istart = mypid * (ncount + 1)
iend = istart + ncount
else:
istart = mypid * ncount + nrem
iend = istart + ncount - 1
N_local = iend - istart + 1
vector = np.ones(N_local)
local_sum = np.sum(vector)
res = np.zeros(1)
comm.Reduce(local_sum, res, op=MPI.SUM)
if mypid == 0:
print("The sum of all elements in the vector is:", res[0])
en Julia
using MPI
MPI.Init()
nprocs = MPI.Comm_size(MPI_COMM_WORLD)
mypid = MPI.Comm_rank(MPI_COMM_WORLD)
# Size of the global vector
N = 1000000000
# Decomposition
ncount = N ÷ nprocs
nrem = N % nprocs
if mypid < nrem
istart = mypid * (ncount + 1)
iend = istart + ncount
else
istart = mypid * ncount + nrem
iend = istart + (ncount - 1)
end
N_local = iend - istart + 1
# Allocate vector on each process
vector = zeros(Float64, N_local)
# Initialize
vector .= 1.0
# Compute local sum
local_sum = sum(view(vector, :))
# Reduce local sums to obtain global sum on process 0
res = MPI.Reduce(local_sum, MPI.SUM, MPI_COMM_WORLD)
# After the reduction because of the implicit barrier
MPI.Finalize()
if mypid == 0
# Print the result
println("The sum of all elements in the vector is: $res")
end