mpi_book
mpi_book
Victor Eijkhout
I MPI 15
3
CONTENTS
Victor Eijkhout 5
CONTENTS
II OpenMP 335
Victor Eijkhout 7
CONTENTS
Victor Eijkhout 9
CONTENTS
41 Kokkos 554
41.1 Parallel code execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
41.2 Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
41.3 Execution and memory spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
41.4 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
41.5 Stuff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
41.6 Full source code of examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
Victor Eijkhout 11
CONTENTS
54 Bibliography 630
Victor Eijkhout 13
CONTENTS
MPI
This section of the book teaches MPI (‘Message Passing Interface’), the dominant model for distributed
memory programming in science and engineering. It will instill the following competencies.
Basic level:
• The student will understand the SPMD model and how it is realized in MPI (chapter 2).
• The student will know the basic collective calls, both with and without a root process, and can
use them in applications (chapter 3).
• The student knows the basic blocking and non-blocking point-to-point calls, and how to use
them (chapter 4).
Intermediate level:
• The students knows about derived datatypes and can use them in communication routines
(chapter 6).
• The student knows about intra-communicators, and some basic calls for creating subcommuni-
cators (chapter 7); also Cartesian process topologies (section 11.1).
• The student understands the basic design of MPI I/O calls and can use them in basic applications
(chapter 10).
• The student understands about graph process topologies and neighborhood collectives (sec-
tion 11.2).
Advanced level:
• The student understands one-sided communication routines, including window creation rou-
tines, and synchronization mechanisms (chapter 9).
• The student understands MPI shared memory, its advantages, and how it is based on windows
(chapter 12).
• The student understands MPI process spawning mechanisms and inter-communicators (chap-
ter 8).
In this chapter you will learn the use of the main tool for distributed memory programming: the Message
Passing Interface (MPI) library. The MPI library has about 250 routines, many of which you may never
need. Since this is a textbook, not a reference manual, we will focus on the important concepts and give the
important routines for each concept. What you learn here should be enough for most common purposes.
You are advised to keep a reference document handy, in case there is a specialized routine, or to look up
subtleties about the routines you use.
17
1. Getting started with MPI
1.2 History
Before the MPI standard was developed in 1993-4, there were many libraries for distributed memory
computing, often proprietary to a vendor platform. MPI standardized the inter-process communication
mechanisms. Other features, such as process management in PVM, or parallel I/O were omitted. Later
versions of the standard have included many of these features.
Since MPI was designed by a large number of academic and commercial participants, it quickly became a
standard. A few packages from the pre-MPI era, such as Charmpp [17], are still in use since they support
mechanisms that do not exist in MPI.
1. A command variant is mpirun; your local cluster may have a different mechanism.
You see that in both scenarios the parallel program is started by the mpiexec command using an Single
Program Multiple Data (SPMD) mode of execution: all hosts execute the same program. It is possible for
different hosts to execute different programs, but we will not consider that in this book.
There can be options and environment variables that are specific to some MPI installations, or to the
network.
• mpich and its derivatives such as Intel MPI or Cray MPI have mpiexec options: https://www.
mpich.org/static/docs/v3.1/www1/mpiexec.html
Remark 1 In OpenMPI, these commands are binary executables by default, but you can make it a shell
script by passing the --enable-script-wrapper-compilers option at configure time.
Victor Eijkhout 19
1. Getting started with MPI
MPI programs can be run on many different architectures. Obviously it is your ambition (or at least your
dream) to run your code on a cluster with a hundred thousand processors and a fast network. But maybe
you only have a small cluster with plain ethernet. Or maybe you’re sitting in a plane, with just your laptop.
An MPI program can be run in all these circumstances – within the limits of your available memory of
course.
The way this works is that you do not start your executable directly, but you use a program, typically
called mpiexec or something similar, which makes a connection to all available processors and starts a
run of your executable there. So if you have a thousand nodes in your cluster, mpiexec can start your
program once on each, and if you only have your laptop it can start a few instances there. In the latter
case you will of course not get great performance, but at least you can test your code for correctness.
Python note 1: Running mpi4py programs. Load the TACC-provided python:
module load python
and run it as:
ibrun python-mpi yourprogram.py
1.5.3 Fortran
Fortran note 1: Formatting of Fortran notes. Fortran-specific notes will be indicated with a note like this.
Traditionally, Fortran bindings for MPI look very much like the C ones, except that each routine has a final
error return parameter. You will find that a lot of MPI code in Fortran conforms to this.
However, in the MPI 3 standard it is recommended that an MPI implementation providing a Fortran in-
terface provide a module named mpi_f08 that can be used in a Fortran program. This incorporates the
following improvements:
• This defines MPI routines to have an optional final parameter for the error.
• There are some visible implications of using the mpi_f08 module, mostly related to the fact
that some of the ‘MPI datatypes’ such as MPI_Comm, which were declared as Integer previously,
are now a Fortran Type. See the following sections for details: Communicator 7.1, Datatype 6.1,
Info 15.1.1, Op 3.10.2, Request 4.2.1, Status 4.3, Window 9.1.
• The mpi_f08 module solves a problem with previous Fortran90 bindings: Fortran90 is a strongly
typed language, so it is not possible to pass argument by reference to their address, as C/C++ do
with the void* type for send and receive buffers. This was solved by having separate routines
for each datatype, and providing an Interface block in the MPI module. If you manage to
request a version that does not exist, the compiler will display a message like
There is no matching specific subroutine for this generic subroutine call [MPI_Send]
For details see http://mpi-forum.org/docs/mpi-3.1/mpi31-report/node409.htm.
1.5.4 Python
Python note 2: Python notes. Python-specific notes will be indicated with a note like this.
The mpi4py package [6, 5] of python bindings is not defined by the MPI standards committee. Instead, it
is the work of an individual, Lisandro Dalcin.
In a way, the Python interface is the most elegant. It uses Object-Oriented (OO) techniques such as meth-
ods on objects, and many default arguments.
Notable about the Python bindings is that many communication routines exist in two variants:
• a version that can send arbitrary Python objects. These routines have lowercase names such as
bcast; and
• a version that sends numpy objects; these routines have names such as Bcast. Their syntax can
be slightly different.
The first version looks more ‘pythonic’, is easier to write, and can do things like sending python ob-
jects, but it is also decidedly less efficient since data is packed and unpacked with pickle. As a common
sense guideline, use the numpy interface in the performance-critical parts of your code, and the pythonic
interface only for complicated actions in a setup phase.
Codes with mpi4py can be interfaced to other languages through Swig or conversion routines.
Data in numpy can be specified as a simple object, or [data, (count,displ), datatype].
Victor Eijkhout 21
1. Getting started with MPI
1.5.5.1 C
The typically C routine specification in MPI looks like:
int MPI_Comm_size(MPI_Comm comm,int *nprocs)
However, the error codes are hardly ever useful, and there is not much your program can do to
recover from an error. Most people call the routine as
MPI_Comm_size( /* parameter ... */ );
• Finally, there is a ‘star’ parameter. This means that the routine wants an address, rather than a
value. You would typically write:
MPI_Comm my_comm = MPI_COMM_WORLD; // using a predefined value
int nprocs;
MPI_Comm_size( comm, &nprocs );
Seeing a ‘star’ parameter usually means either: the routine has an array argument, or: the routine
internally sets the value of a variable. The latter is the case here.
1.5.5.2 Fortran
The Fortran specification looks like:
The syntax of using this routine is close to this specification: you write
Type(MPI_Comm) :: comm = MPI_COMM_WORLD
! legacy: Integer :: comm = MPI_COMM_WORLD
Integer :: comm = MPI_COMM_WORLD
Integer :: size,ierr
CALL MPI_Comm_size( comm, size ) ! without the optional ierr
• Most Fortran routines have the same parameters as the corresponding C routine, except that
they all have the error code as final parameter, instead of as a function result. As with C, you
can ignore the value of that parameter. Just don’t forget it.
• The types of the parameters are given in the specification.
• Where C routines have MPI_Comm and MPI_Request and such parameters, Fortran has INTEGER
parameters, or sometimes arrays of integers.
1.5.5.3 Python
The Python interface to MPI uses classes and objects. Thus, a specification like:
MPI.Comm.Send(self, buf, int dest, int tag=0)
• Next, you need a Comm object. Often you will use the predefined communicator
comm = MPI.COMM_WORLD
• The keyword self indicates that the actual routine Send is a method of the Comm object, so you
call:
comm.Send( .... )
• Parameters that are listed by themselves, such as buf, as positional. Parameters that are listed
with a type, such as int dest are keyword parameters. Keyword parameters that have a value
specified, such as int tag=0 are optional, with the default value indicated. Thus, the typical
call for this routine is:
comm.Send(sendbuf,dest=other)
Victor Eijkhout 23
1. Getting started with MPI
specifying the send buffer as positional parameter, the destination as keyword parameter, and
using the default value for the optional tag.
Some python routines are ‘class methods’, and their specification lacks the self keyword. For instance:
MPI.Request.Waitall(type cls, requests, statuses=None)
would be used as
MPI.Request.Waitall(requests)
1.6 Review
Review 1.1. What determines the parallelism of an MPI job?
1. The size of the cluster you run on.
2. The number of cores per cluster node.
3. The parameters of the MPI starter (mpiexec, ibrun,…)
Review 1.2. T/F: the number of cores of your laptop is the limit of how many MPI proceses
you can start up.
Review 1.3. Do the following languages have an object-oriented interface to MPI? In what
sense?
1. C
2. C++
3. Fortran2008
4. Python
Victor Eijkhout 25
Chapter 2
more than one process, using the time slicing of the Operating System (OS), but that would give you no
extra performance.
These days the situation is more complicated. You can still talk about a node in a cluster, but now a node
can contain more than one processor chip (sometimes called a socket), and each processor chip probably
has multiple cores. Figure 2.2 shows how you could explore this using a mix of MPI between the nodes,
and a shared memory programming system on the nodes.
However, since each core can act like an independent processor, you can also have multiple MPI processes
per node. To MPI, the cores look like the old completely separate processors. This is the ‘pure MPI’ model
26
2.1. The SPMD model
of figure 2.3, which we will use in most of this part of the book. (Hybrid computing will be discussed in
chapter 45.)
This is somewhat confusing: the old processors needed MPI programming, because they were physically
separated. The cores on a modern processor, on the other hand, share the same memory, and even some
caches. In its basic mode MPI seems to ignore all of this: each core receives an MPI process and the
programmer writes the same send/receive call no matter where the other process is located. In fact, you
can’t immediately see whether two cores are on the same node or different nodes. Of course, on the
implementation level MPI uses a different communication mechanism depending on whether cores are
Victor Eijkhout 27
2. MPI topic: Functional parallelism
on the same socket or on different nodes, so you don’t have to worry about lack of efficiency.
Remark 2 In some rare cases you may want to run in an Multiple Program Multiple Data (MPMD) mode,
rather than SPMD. This can be achieved either on the OS level (see section 15.9.4), using options of the mpiexec
mechanism, or you can use MPI’s built-in process management; chapter 8. Like I said, this concerns only rare
cases.
2.2.1 Headers
If you use MPI commands in a program file, be sure to include the proper header file, mpi.h for C/C++.
#include "mpi.h" // for C
The internals of these files can be different between MPI installations, so you can not compile one file
against one mpi.h file and another file, even with the same compiler on the same machine, against a
different MPI.
Fortran note 2: MPI module. For MPI use from Fortran, use an MPI module.
use mpi ! pre 3.0
use mpi_f08 ! 3.0 standard
New language developments, such as large counts; section 6.4.2 will only be included in the
mpi_f08 module, not in the earlier mechanisms.
The header file mpif.h is deprecated as of MPI-4.1: it may be supported by installations, but
doing so is strongly discouraged.
Python note 3: Import mpi module. It’s easiest to
from mpi4py import MPI
to your file.
Victor Eijkhout 29
2. MPI topic: Functional parallelism
Remark 3 For hybrid MPI-plus-threads programming there is also a call MPI_Init_thread. For that, see sec-
tion 13.1.
nicator, but many implementations will terminate all processes. The value parameter is returned to the
environment.
Code: Output:
// return.c mpicc -o return return.o
MPI_Abort(MPI_COMM_WORLD,17); mpirun -n 1 ./return ; \
echo "MPI program
↪return code $?"
application called
↪MPI_Abort(MPI_COMM_WORLD,
↪17) - process 0
MPI program return code 17
Victor Eijkhout 31
2. MPI topic: Functional parallelism
Once MPI has been initialized, the MPI_INFO_ENV object contains a number of key/value pairs describing
run-specific information; see section 15.1.1.1.
The MPI_Init routines takes a reference to argc and argv for the following reason: the MPI_Init calls
filters out the arguments to mpirun or mpiexec, thereby lowering the value of argc and elimitating some
of the argv arguments.
On the other hand, the commandline arguments that are meant for mpiexec wind up in the MPI_INFO_ENV
object as a set of key/value pairs; see section 15.1.1.
Since all processes in an MPI job are instantiations of the same executable, you’d think that they all execute
the exact same instructions, which would not be terribly useful. You will now learn how to distinguish
processes from each other, so that together they can start doing useful work.
In the following exercise you will print out the hostname of each MPI process with MPI_Get_processor_name
(figure 2.6) as a first way of distinguishing between processes. This routine has a character buffer argu-
ment, which needs to be allocated by you. The length of the buffer is also passed, and on return that
parameter has the actually used length. The maximum needed length is MPI_MAX_PROCESSOR_NAME.
MPI.Get_processor_name()
Code: Output:
// procname.c make[3]: `procname' is up to
int name_length = MPI_MAX_PROCESSOR_NAME; ↪date.
char proc_name[name_length]; TACC: Starting up job
MPI_Get_processor_name(proc_name,&name_length); ↪4328411
printf("Process %d/%d is running on node <<%s>>\n", TACC: Starting parallel
procid,nprocs,proc_name); ↪tasks...
This process is running on
↪node
↪<<c205-036.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-036.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-036.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-036.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-036.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-035.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-035.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-035.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-035.frontera.tacc.utexas.edu>>
This process is running on
↪node
↪<<c205-035.frontera.tacc.utexas.edu>>
TACC: Shutdown complete.
↪Exiting.
Victor Eijkhout 33
2. MPI topic: Functional parallelism
Exercise 2.3. Use the command MPI_Get_processor_name. Confirm that you are able to run a
program that uses two different nodes.
MPL note 4: Processor name. The processor_name call is an environment method returning a std::string:
std::string mpl::environment::processor_name ();
2.3.2 Communicators
First we need to introduce the concept of communicator, which is an abstract description of a group of
processes. For now you only need to know about the existence of the MPI_Comm data type, and that there
is a pre-defined communicator MPI_COMM_WORLD which describes all the processes involved in your parallel
run.
In the procedural languages C, a communicator is a variable that is passed to most routines:
#include <mpi.h>
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Send( /* stuff */ comm );
Fortran note 4: Communicator type. In Fortran, pre-2008 a communicator was an opaque handle, stored in
an Integer. With Fortran 2008, communicators are derived types:
use mpi_f098
Type(MPI_Comm} :: comm = MPI_COMM_WORLD
call MPI_Send( ... comm )
MPL note 5: World communicator. The naive way of declaring a communicator would be:
// commrank.cxx
mpl::communicator comm_world =
mpl::environment::comm_world();
MPL note 6: Communicator copying. The communicator class has its copy operator deleted; however, copy
initialization exists:
// commcompare.cxx
const mpl::communicator &comm =
mpl::environment::comm_world();
cout << "same: " << boolalpha << (comm==comm) << endl;
mpl::communicator copy =
mpl::environment::comm_world();
cout << "copy: " << boolalpha << (comm==copy) << endl;
// correct!
void comm_ref( const mpl::communicator &comm );
Victor Eijkhout 35
2. MPI topic: Functional parallelism
MPI.Comm.Get_size(self)
MPI.Comm.Get_rank(self)
Python note 6: Communicator rank and size. Rank and size are methods of the communicator object. Note
that their names are slightly different from the MPI standard names.
comm = MPI.COMM_WORLD
procid = comm.Get_rank()
nprocs = comm.Get_size()
MPL note 8: Rank and size. The rank of a process (by mpl::communicator::rank) and the size of a commu-
nicator (by mpl::communicator::size) are both methods of the communicator class:
const mpl::communicator &comm_world =
mpl::environment::comm_world();
int procid = comm_world.rank();
int nprocs = comm_world.size();
Practice is a little more complicated than this. But we will start exploring this notion of processes deciding
on their activity based on their process number.
Victor Eijkhout 37
2. MPI topic: Functional parallelism
Being able to tell processes apart is already enough to write some applications, without knowing any
other MPI. We will look at a simple parallel search algorithm: based on its rank, a processor can find
its section of a search space. For instance, in Monte Carlo codes a large number of random samples is
generated and some computation performed on each. (This particular example requires each MPI process
to run an independent random number generator, which is not entirely trivial.)
Exercise 2.6. Is the number 𝑁 = 2, 000, 000, 111 prime? Let each process test a disjoint set
of integers, and print out any factor they find. You don’t have to test all
integers < 𝑁 : any factor is at most √𝑁 ≈ 45, 200.
(Hint: i%0 probably gives a runtime error.)
Can you find more than one solution?
(There is a skeleton for this exercise under the name prime.)
Remark 4 Normally, we expect parallel algorithms to be faster than sequential. Now consider the above
exercise. Suppose the number we are testing is divisible by some small prime number, but every process has a
large block of numbers to test. In that case the sequential algorithm would have been faster than the parallel
one. Food for thought.
As another example, in Boolean satisfiability problems a number of points in a search space needs to be
evaluated. Knowing a process’s rank is enough to let it generate its own portion of the search space. The
computation of the Mandelbrot set can also be considered as a case of functional parallelism. However,
the image that is constructed is data that needs to be kept on one processor, which breaks the symmetry
of the parallel run.
Of course, at the end of a functionally parallel run you need to summarize the results, for instance printing
out some total. The mechanisms for that you will learn next.
and fill it so that process 0 has the integers 0 ⋯ 9, process 1 has 10 ⋯ 19, et cetera.
It may be hard to print the output in a non-messy way.
If the array size is not perfectly divisible by the number of processors, we have to come up with a division
that is uneven, but not too much. You could for instance, write
int Nglobal, // is something large
Nlocal = Nglobal/ntids,
excess = Nglobal%ntids;
if (mytid==ntids-1)
Nlocal += excess;
Exercise 2.8. Argue that this strategy is not optimal. Can you come up with a better
distribution? Load balancing is further discussed in HPC book, section-2.10.
Victor Eijkhout 39
2. MPI topic: Functional parallelism
A certain class of MPI routines are called ‘collective’, or more correctly: ‘collective on a communicator’.
This means that if process one in that communicator calls that routine, they all need to call that routine.
In this chapter we will discuss collective routines that are about combining the data on all processes in
that communicator, but there are also operations such as opening a shared file that are collective, which
will be discussed in a later chapter.
41
3. MPI topic: Collectives
3. Let each process compute a random number. You want to print on what
processor the maximum value is computed.
Think about time and space complexity of your suggestions.
𝑁 𝑁
1 ∑ 𝑥𝑖
𝜎= ∑(𝑥 − 𝜇)2 where 𝜇= 𝑖
𝑁 −1 𝑖 𝑖 𝑁
√
and assume that every process stores just one 𝑥𝑖 value.
1. The calculation of the average 𝜇 is a reduction, since all the distributed values need to be added.
2. Now every process needs to compute 𝑥𝑖 − 𝜇 for its value 𝑥𝑖 , so 𝜇 is needed everywhere. You can
compute this by doing a reduction followed by a broadcast, but it is better to use a so-called
allreduce operation, which does the reduction and leaves the result on all processors.
3. The calculation of ∑𝑖 (𝑥𝑖 − 𝜇) is another sum of distributed data, so we need another reduction
operation. Depending on whether each process needs to know 𝜎 , we can again use an allreduce.
3.1.2 Synchronization
Collectives are operations that involve all processes in a communicator. A collective is a single call, and
it blocks on all processors, meaning that a process calling a collective cannot proceed until the other
processes have similarly called the collective.
That does not mean that all processors exit the call at the same time: because of implementational details
and network latency they need not be synchronized in their execution. However, semantically we can say
that a process can not finish a collective until every other process has at least started the collective.
In addition to these collective operations, there are operations that are said to be ‘collective on their
communicator’, but which do not involve data movement. Collective then means that all processors must
call this routine; not to do so is an error that will manifest itself in ‘hanging’ code. One such example is
MPI_File_open.
Victor Eijkhout 43
3. MPI topic: Collectives
3.2 Reduction
3.2.1 Reduce to all
Above we saw a couple of scenarios where a quantity is reduced, with all proceses getting the result. The
MPI call for this is MPI_Allreduce (figure 3.1).
Example: we give each process a random number, and sum these numbers together. The result should be
approximately 1/2 times the number of processes.
// allreduce.c
float myrandom,sumrandom;
myrandom = (float) rand()/(float)RAND_MAX;
// add the random variables together
MPI_Allreduce(&myrandom,&sumrandom,
1,MPI_FLOAT,MPI_SUM,comm);
// the result should be approx nprocs/2:
if (procno==nprocs-1)
printf("Result %6.9f compared to .5\n",sumrandom/nprocs);
Or:
MPI_Count buffersize = 1000;
double *indata,*outdata;
indata = (double*) malloc( buffersize*sizeof(double) );
outdata = (double*) malloc( buffersize*sizeof(double) );
MPI_Allreduce_c(indata,outdata,buffersize,
MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
Remark 5 Routines with both a send and receive buffer should not alias these. Instead, see the discussion of
MPI_IN_PLACE; section 3.3.2.
𝜉 = ∑ 𝑥𝑖
𝑖
𝑥𝑖′ ← 𝑥𝑖 /𝜉
𝜉 ′ = ∑ 𝑥𝑖′
𝑖
Victor Eijkhout 45
3. MPI topic: Collectives
which we approximate by
𝑁 −1
𝑓𝑛 =̂ ∑ 𝑓 (𝑖ℎ)𝑒 −𝑖𝑛𝜋/𝑁
𝑖=0
Note the parentheses after the operator. Also note that the operator comes first, not last.
Available: max, min, plus, multiplies, logical_and, logical_or, logical_xor, bit_and, bit_or,
bit_xor.
MPL implementation note: The reduction operator has to be compatible with T(T,T)>
For more about operators, see section 3.10.
Exercise 3.5. The Gram-Schmidt method is a simple way to orthogonalize two vectors:
𝑢 ← 𝑢 − (𝑢 𝑡 𝑣)/(𝑢 𝑡 𝑢)
But for arrays we use the fact that arrays and addresses are more-or-less equivalent in:
float xx[2],yy[2];
MPI_Allreduce( xx,yy,2,MPI_FLOAT, ... );
Victor Eijkhout 47
3. MPI topic: Collectives
but that is not necessary. The compiler will not complain if you leave out the cast.
C++ note 1: Buffer treatment. Treatment of scalars in C++ is the same as in C. However, for arrays you
have the choice between C-style arrays, and std::vector or std::array. For the latter there are
two ways of dealing with buffers:
vector<float> xx(25);
MPI_Send( xx.data(),25,MPI_FLOAT, .... );
MPI_Send( &xx[0],25,MPI_FLOAT, .... );
Fortran note 5: MPI send/recv buffers. In Fortran parameters are always passed by reference, so the buffer
is treated the same way:
Real*4 :: x
Real*4,dimension(2) :: xx
call MPI_Allreduce( x,1,MPI_REAL4, ... )
call MPI_Allreduce( xx,2,MPI_REAL4, ... )
In discussing OO languages, we first note that the official C++ Application Programmer Interface (API)
has been removed from the standard.
Specification of the buffer/count/datatype triplet is not needed explicitly in OO languages.
Python note 7: Buffers from numpy. Most MPI routines in Python have both a variant that can send arbi-
trary Python data, and one that is based on numpy arrays. The former looks the most ‘pythonic’,
and is very flexible, but is usually demonstrably inefficient.
## allreduce.py
random_number = random.randint(1,random_bound)
# native mode send
max_random = comm.allreduce(random_number,op=MPI.MAX)
In the numpy variant, all buffers are numpy objects, which carry information about their type
and size. For scalar reductions this means we have to create an array for the receive buffer, even
though only one element is used.
myrandom = np.empty(1,dtype=int)
myrandom[0] = random_number
allrandom = np.empty(nprocs,dtype=int)
# numpy mode send
comm.Allreduce(myrandom,allrandom[:1],op=MPI.MAX)
Python note 8: Buffers from subarrays. In many examples you will pass a whole Numpy array as send/re-
ceive buffer. Should want to use a buffer that corresponds to a subset of an array, you can use
the following notation:
MPI_Whatever( buffer[...,5] # more stuff
Code: Output:
## bcastcolumn.py int size: 4
datatype = np.intc i
elementsize = datatype().itemsize [[ 0 0 0 0 0 0]
typechar = datatype().dtype.char [-1 1 1 1 1 1]
buffer = np.zeros( [nprocs,nprocs], dtype=datatype) [-1 -1 2 2 2 2]
buffer[:,:] = -1 [-1 -1 -1 3 3 3]
for proc in range(nprocs): [-1 -1 -1 -1 4 4]
if procid==proc: [ 5 5 5 5 5 5]]
buffer[proc,:] = proc
comm.Bcast\
( [ np.frombuffer\
( buffer.data,
dtype=datatype,
offset=(proc*nprocs+proc)*elementsize ),
nprocs-proc, typechar ],
root=proc )
MPL note 10: Scalar buffers. Buffer type handling is done through polymorphism and templating: no ex-
plicit indiation of types.
Scalars are handled as such:
float x,y;
comm.bcast( 0,x ); // note: root first
comm.allreduce( mpl::plus<float>(), x,y ); // op first
where the reduction function needs to be compatible with the type of the buffer.
MPL note 11: Vector buffers. If your buffer is a std::vector you need to take the .data() component of it:
vector<float> xx(2),yy(2);
comm.allreduce( mpl::plus<float>(),
xx.data(), yy.data(), mpl::contiguous_layout<float>(2) );
The contiguous_layout is a ‘derived type’; this will be discussed in more detail elsewhere (see
note 43 and later). For now, interpret it as a way of indicating the count/type part of a buffer
specification.
MPL note 12: Iterator buffers. MPL point-to-point routines have a way of specifying the buffer(s) through
a begin and end iterator.
// sendrange.cxx
vector<double> v(15);
comm_world.send(v.begin(), v.end(), 1); // send to rank 1
comm_world.recv(v.begin(), v.end(), 0); // receive from rank 0
Victor Eijkhout 49
3. MPI topic: Collectives
comm_world.reduce
( mpl::plus<int>(),0,
my_number_of_elements,total_number_of_elements );
} else {
comm_world.reduce
( mpl::plus<int>(),0,my_number_of_elements );
}
• There is the original data, and the data resulting from the reduction. It is a design decision of
MPI that it will not by default overwrite the original data. The send data and receive data are of
the same size and type: if every processor has one real number, the reduced result is again one
real number.
• It is possible to indicate explicitly that a single buffer is used, and thereby the original data
overwritten; see section 3.3.2 for this ‘in place’ mode.
• There is a reduction operator. Popular choices are MPI_SUM, MPI_PROD and MPI_MAX, but compli-
cated operators such as finding the location of the maximum value exist. (For the full list, see
section 3.10.1.) You can also define your own operators; section 3.10.2.
• There is a root process that receives the result of the reduction. Since the nonroot processes do
not receive the reduced data, they can actually leave the receive buffer undefined.
// reduce.c
float myrandom = (float) rand()/(float)RAND_MAX,
result;
int target_proc = nprocs-1;
// add all the random variables together
MPI_Reduce(&myrandom,&result,1,MPI_FLOAT,MPI_SUM,
target_proc,comm);
// the result should be approx nprocs/2:
void mpl::communicator::reduce
// root, in place
( F f,int root_rank,T & sendrecvdata ) const
( F f,int root_rank,T * sendrecvdata,const contiguous_layout< T > & l ) const
// non-root
( F f,int root_rank,const T & senddata ) const
( F f,int root_rank,
const T * senddata,const contiguous_layout< T > & l ) const
// general
( F f,int root_rank,const T & senddata,T & recvdata ) const
( F f,int root_rank,
const T * senddata,T * recvdata,const contiguous_layout< T > & l ) const
Python:
if (procno==target_proc)
printf("Result %6.3f compared to nprocs/2=%5.2f\n",
result,nprocs/2.);
Exercise 3.6. Write a program where each process computes a random number, and
process 0 finds and prints the maximum generated value. Let each process print its
value, just to check the correctness of your program.
Collective operations can also take an array argument, instead of just a scalar. In that case, the operation
is applied pointwise to each location in the array.
Exercise 3.7. Create on each process an array of length 2 integers, and put the values 1, 2 in
it on each process. Do a sum reduction on that array. Can you predict what the
Victor Eijkhout 51
3. MPI topic: Collectives
Now every process only has a receive buffer, so this has the advantage of saving half the memory. Each
process puts its input values in the receive buffer, and these are overwritten by the reduced result.
The above example used MPI_IN_PLACE in MPI_Allreduce; in MPI_Reduce it’s little tricky. The reasoning is a
follows:
• In MPI_Reduce every process has a buffer to contribute, but only the root needs a receive buffer.
Therefore, MPI_IN_PLACE takes the place of the receive buffer on any processor except for the
root …
• … while the root, which needs a receive buffer, has MPI_IN_PLACE takes the place of the send
buffer. In order to contribute its value, the root needs to put this in the receive buffer.
Here is one way you could write the in-place version of MPI_Reduce:
if (procno==root)
MPI_Reduce(MPI_IN_PLACE,myrandoms,
nrandoms,MPI_FLOAT,MPI_SUM,root,comm);
else
MPI_Reduce(myrandoms,MPI_IN_PLACE,
nrandoms,MPI_FLOAT,MPI_SUM,root,comm);
However, as a point of style, having different versions of a a collective in different branches of a condition
is infelicitous. The following may be preferable:
float *sendbuf,*recvbuf;
if (procno==root) {
sendbuf = MPI_IN_PLACE; recvbuf = myrandoms;
} else {
sendbuf = myrandoms; recvbuf = MPI_IN_PLACE;
}
MPI_Reduce(sendbuf,recvbuf,
nrandoms,MPI_FLOAT,MPI_SUM,root,comm);
In Fortran you can not do these address calculations. You can use the solution with a conditional:
!! reduceinplace.F90
call random_number(mynumber)
target_proc = ntids-1;
! add all the random variables together
if (mytid.eq.target_proc) then
result = mytid
call MPI_Reduce(MPI_IN_PLACE,result,1,MPI_REAL,MPI_SUM,&
target_proc,comm)
else
mynumber = mytid
call MPI_Reduce(mynumber,result,1,MPI_REAL,MPI_SUM,&
target_proc,comm)
end if
Python note 9: In-place collectives. The value MPI.IN_PLACE can be used for the send buffer:
## allreduceinplace.py
myrandom = np.empty(1,dtype=int)
myrandom[0] = random_number
comm.Allreduce(MPI.IN_PLACE,myrandom,op=MPI.MAX)
MPL note 14: Reduce in place. The in-place variant is activated by specifying only one instead of two buffer
arguments.
float
xrank = static_cast<float>( comm_world.rank() ),
xreduce;
// separate recv buffer
comm_world.allreduce(mpl::plus<float>(), xrank,xreduce);
// in place
comm_world.allreduce(mpl::plus<float>(), xrank);
Victor Eijkhout 53
3. MPI topic: Collectives
template<typename T >
void mpl::communicator::bcast
( int root, T & data ) const
( int root, T * data, const layout< T > & l ) const
Python:
Note that the buffers are of type T *, so it is necessary to take the data() of any std::vector and
such.
3.3.3 Broadcast
A broadcast models the scenario where one process, the ‘root’ process, owns some data, and it communi-
cates it to all other processes.
The broadcast routine MPI_Bcast (figure 3.3) has the following structure:
MPI_Bcast( data..., root , comm);
Here:
• There is only one buffer, the send buffer. Before the call, the root process has data in this buffer;
the other processes allocate a same sized buffer, but for them the contents are irrelevant.
• The root is the process that is sending its data. Typically, it will be the root of a broadcast tree.
Example: in general we can not assume that all processes get the commandline arguments, so we broadcast
them from process 0.
// init.c
if (procno==0) {
if ( argc==1 || // the program is called without parameter
( argc>1 && !strcmp(argv[1],"-h") ) // user asked for help
) {
printf("\nUsage: init [0-9]+\n");
MPI_Abort(comm,1);
}
input_argument = atoi(argv[1]);
}
MPI_Bcast(&input_argument,1,MPI_INT,0,comm);
Python note 10: Sending objects. In python it is both possible to send objects, and to send more C-like
buffers. The two possibilities correspond (see section 1.5.4) to different routine names; the
buffers have to be created as numpy objects.
We illustrate both the general Python and numpy variants. In the former variant the result is
given as a function return; in the numpy variant the send buffer is reused.
## bcast.py
# first native
if procid==root:
buffer = [ 5.0 ] * dsize
else:
buffer = [ 0.0 ] * dsize
buffer = comm.bcast(obj=buffer,root=root)
if not reduce( lambda x,y:x and y,
[ buffer[i]==5.0 for i in range(len(buffer)) ] ):
print( "Something wrong on proc %d: native buffer <<%s>>" \
% (procid,str(buffer)) )
MPL note 15: Broadcast. The broadcast call comes in two variants, with scalar argument and general lay-
out:
template<typename T >
void mpl::communicator::bcast
( int root_rank, T &data ) const;
Victor Eijkhout 55
3. MPI topic: Collectives
void mpl::communicator::bcast
( int root_rank, T *data, const layout< T > &l ) const;
where we ignore the update of the righthand side, or the formation of the inverse.
Let a matrix be distributed with each process storing one column. Implement the
Gauss-Jordan algorithm as a series of broadcasts: in iteration 𝑘 process 𝑘 computes
(𝑘)
and broadcasts the scaling vector {ℓ𝑖 }𝑖 . Replicate the right-hand side on all
processors.
(There is a skeleton for this exercise under the name jordan.)
Exercise 3.9. Add partial pivoting to your implementation of Gauss-Jordan elimination.
Change your implementation to let each processor store multiple columns, but still
do one broadcast per column. Is there a way to have only one broadcast per
processor?
process ∶ 0 1 2 ⋯ 𝑝−1
data ∶ 𝑥0 𝑥1 𝑥2 ⋯ 𝑥𝑝−1
𝑝−1
inclusive ∶ 𝑥0 𝑥0 ⊕ 𝑥1 𝑥0 ⊕ 𝑥1 ⊕ 𝑥2 ⋯ ⊕𝑖=0 𝑥𝑖
𝑝−2
exclusive ∶ unchanged 𝑥0 𝑥0 ⊕ 𝑥1 ⋯ ⊕𝑖=0 𝑥𝑖
// scan.c
// add all the random variables together
MPI_Scan(&myrandom,&result,1,MPI_FLOAT,MPI_SUM,comm);
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
2 2 13 1 17 2 2 13 1 17
2 0 1 1 3 minus 1 × 1/3
4 5 32 1 41 0 1 6 1 7 take this row 1
0 1 6 1 7
⇈ ⇈ ⇈
-2 -3 -16 1 -21 0 -1 -3 1 -4
0 0 3 1 3 take this row 1/3
Step 1: Step 8:
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 matrix sol rhs action Step 15:
𝑠𝑐𝑎𝑙𝑖𝑛𝑔
2 2 13 1 17 take this row 1/2 2 2 13 1 17 minus 2 × 1
↑ ↑ ↑ matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
4 5 32 1 41 0 1 6 1 7 take this row 1 2 0 0 1 2 −1/3
-2 -3 -16 1 -21 0 -1 -3 1 -4 0 1 6 1 7
Step 2: Step 9:
0 0 3 1 3 take this row 1/3
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
2 2 13 1 17 take this row 1/2 2 0 1 1 3 −2 Step 16:
↓ ↓ ↓
4 5 32 1 41 minus 4 × (1/2) 0 1 6 1 7 take this row 1
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
-2 -3 -16 1 -21 0 -1 -3 1 -4 2 0 0 1 2 −1/3
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 0 1 0 1 1
2 2 13 1 17 take this row 1/2 2 0 1 1 3 −2
⇊ ⇊ ⇊ 0 0 3 1 3 take this row
0 1 6 1 7 −2 0 1 6 1 7 take this row 1
Step 18:
-2 -3 -16 1 -21 minus (−2) × (1/2) 0 0 3 1 3 +1
Step 5: Step 12: matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
2 0 0 1 2 −1/3
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
2 2 13 1 17 take this row 1/2 2 0 1 1 3 −2 0 1 0 1 1 −2/3
0 1 6 1 7 −2 0 1 6 1 7 second column done 1 0 0 3 1 3 third column done 1/3
0 -1 -3 1 -4 +1 0 0 3 1 3 +1
Finished:
Step 6: Step 13:
matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔 matrix sol rhs action 𝑠𝑐𝑎𝑙𝑖𝑛𝑔
2 2 13 1 17 first column done 1/2 2 0 1 1 3 2 0 0 1 2
0 1 6 1 7 −2 0 1 6 1 7 0 1 0 1 1
Victor Eijkhout 57
3. MPI topic: Collectives
In python mode the result is a function return value, with numpy the result is passed as the second
parameter.
## scan.py
mycontrib = 10+random.randint(1,nprocs)
myfirst = 0
mypartial = comm.scan(mycontrib)
sbuf = np.empty(1,dtype=int)
rbuf = np.empty(1,dtype=int)
sbuf[0] = mycontrib
comm.Scan(sbuf,rbuf)
You can use any of the given reduction operators, (for the list, see section 3.10.1), or a user-defined one.
In the latter case, the MPI_Op operations do not return an error code.
MPL note 16: Scan operations. As in the C/F interfaces, MPL interfaces to the scan routines have the same
calling sequences as the ‘Allreduce’ routine.
Victor Eijkhout 59
3. MPI topic: Collectives
0 … 𝑛𝑝 − 1 to a global numbering one does a scan with the number of local elements as input. The output
is then the global number of the first local variable.
As an example, setting Fast Fourier Transform (FFT) coefficients requires this translation. If the local sizes
are all equal, determining the global index of the first element is an easy calculation. For the irregular
case, we first do a scan:
// fft.c
MPI_Allreduce( &localsize,&globalsize,1,MPI_INT,MPI_SUM, comm );
globalsize += 1;
int myfirst=0;
MPI_Exscan( &localsize,&myfirst,1,MPI_INT,MPI_SUM, comm );
𝑋𝑖 = 𝑥𝑖 if 𝑦𝑖 = 0
{
𝑋𝑖 = 𝑋𝑖−1 + 𝑥𝑖 if 𝑦𝑖 = 1
(This is the basis for the implementation of the sparse matrix vector product as prefix operation; see HPC
book, section-27.2.) This means that 𝑋𝑖 sums the segments between locations where 𝑦𝑖 = 0 and the first
subsequent place where 𝑦𝑖 = 1. To implement this, you need a user-defined operator
𝑋 𝑋1 𝑋2
𝑋 = 𝑥 1 + 𝑥2 if 𝑦2 == 1
( 𝑥 ) = ( 𝑥1 ) ⨁ ( 𝑥2 ) ∶ {
𝑦 𝑦1 𝑦2 𝑋 = 𝑥2 if 𝑦2 == 0
This operator is not communitative, and it needs to be declared as such with MPI_Op_create; see sec-
tion 3.10.2
In the MPI_Scatter operation, the root spreads information to all other processes. The difference with a
broadcast is that it involves individual information from/to every process. Thus, the gather operation
typically has an array of items, one coming from each sending process, and scatter has an array, with an
Victor Eijkhout 61
3. MPI topic: Collectives
// gather.c
// we assume that each process has a value "localsize"
// the root process collects these values
if (procno==root)
localsizes = (int*) malloc( nprocs*sizeof(int) );
This will also be the basis of a more elaborate example in section 3.9.
Exercise 3.13. Let each process compute a random number. You want to print the
maximum value and on what processor it is computed. What collective(s) do you
use? Write a short program.
The MPI_Scatter operation is in some sense the inverse of the gather: the root process has an array of
length 𝑛𝑝 where 𝑝 is the number of processors and 𝑛 the number of elements each processor will receive.
int MPI_Scatter
(void* sendbuf, int sendcount, MPI_Datatype sendtype,
void* recvbuf, int recvcount, MPI_Datatype recvtype,
int root, MPI_Comm comm)
If more than a single scalar is gathered, or scattered into, it becomes necessary to specify a
layout:
vector<float> vrecv(2),vsend(2*nprocs);
mpl::contiguous_layout<float> twonums(2);
void mpl::communicator::gather
( int root_rank, const T & senddata ) const
( int root_rank, const T & senddata, T * recvdata ) const
( int root_rank, const T * senddata, const layout< T > & sendl ) const
( int root_rank, const T * senddata, const layout< T > & sendl,
T * recvdata, const layout< T > & recvl ) const
Python:
MPI.Comm.Gather
(self, sendbuf, recvbuf, int root=0)
comm_world.scatter
(0, vsend.data(),twonums, vrecv.data(),twonums );
MPL note 18: Gather on nonroot. Logically speaking, on every nonroot process, the gather call only has a
send buffer. MPL supports this by having two variants that only specify the send data.
if (procno==0) {
vector<int> size_buffer(nprocs);
comm_world.gather
(
0,my_number_of_elements,size_buffer.data()
);
} else {
/*
* If you are not the root, do versions with only send buffers
*/
comm_world.gather
Victor Eijkhout 63
3. MPI topic: Collectives
( 0,my_number_of_elements );
3.5.1 Examples
In some applications, each process computes a row or column of a matrix, but for some calculation (such
as the determinant) it is more efficient to have the whole matrix on one process. You should of course
only do this if this matrix is essentially smaller than the full problem, such as an interface system or the
last coarsening level in multigrid.
Figure 3.6 pictures this. Note that conceptually we are gathering a two-dimensional object, but the buffer
is of course one-dimensional. You will later see how this can be done more elegantly with the ‘subarray’
datatype; section 6.3.4.
Another thing you can do with a distributed matrix is to transpose it.
// itransposeblock.c
for (int iproc=0; iproc<nprocs; iproc++) {
MPI_Scatter( regular,1,MPI_DOUBLE,
&(transpose[iproc]),1,MPI_DOUBLE,
iproc,comm);
}
In this example, each process scatters its column. This needs to be done only once, yet the scatter happens
in a loop. The trick here is that a process only originates the scatter when it is the root, which happens
only once. Why do we need a loop? That is because each element of a process’ row originates from a
different scatter operation.
Exercise 3.14. Can you rewrite this code so that it uses a gather rather than a scatter? Does
that change anything essential about structure of the code?
Exercise 3.15. Take the code from exercise 3.11 and extend it to gather all local buffers onto
rank zero. Since the local arrays are of differing lengths, this requires MPI_Gatherv.
How do you construct the lengths and displacements arrays?
(There is a skeleton for this exercise under the name scangather.)
3.5.2 Allgather
Figure 3.7: All gather collects all data onto every process
The MPI_Allgather (figure 3.7) routine does the same gather onto every process: each process winds up
with the totality of all data; figure 3.7.
This routine can be used in the simplest implementation of the dense matrix-vector product to give each
processor the full input; see HPC book, section-6.2.3.
The MPI_IN_PLACE keyword can be used with an all-gather:
1. Use MPI_IN_PLACE for the send buffer;
2. send count and datetype are ignored by MPI;
3. each process needs to put its ‘send content’ in the correct location of the gather buffer.
Some cases look like an all-gather but can be implemented more efficiently. Let’s consider as an example
Victor Eijkhout 65
3. MPI topic: Collectives
the set difference of two distributed vectors. That is, you have two distributed vectors, and you want
to create a new vector, again distributed, that contains those elements of the one that do not appear in
the other. You could implement this by gathering the second vector on each processor, but this may be
prohibitive in memory usage.
Exercise 3.16. Can you think of another algorithm for taking the set difference of two
distributed vectors. Hint: look up bucket brigade algorithm; section 4.1.5. What is the
time and space complexity of this algorithm? Can you think of other advantages
beside a reduction in workspace?
3.6 All-to-all
The all-to-all operation MPI_Alltoall (figure 3.8) can be seen as a collection of simultaneous broadcasts
or simultaneous gathers. The parameter specification is much like an allgather, with a separate send and
receive buffer, and no root specified. As with the gather call, the receive count corresponds to an individual
receive, not the total amount.
Unlike the gather call, the send buffer now obeys the same principle: with a send count of 1, the buffer
has a length of the number of processes.
The typical application for such data transposition is in the FFT algorithm, where it can take tens of
percents of the running time on large clusters.
We will consider another application of data transposition, namely radix sort, but we will do that in a
couple of steps. First of all:
Exercise 3.17. In the initial stage of a radix sort, each process considers how many
elements to send to every other process. Use MPI_Alltoall to derive from this how
many elements they will receive from every other process.
3.6.2 All-to-all-v
The major part of the radix sort algorithm consist of every process sending some of its elements to each
of the other processes. The routine MPI_Alltoallv (figure 3.9) is used for this pattern:
• Every process scatters its data to all others,
• but the amount of data is different per process.
Exercise 3.18. The actual data shuffle of a radix sort can be done with MPI_Alltoallv. Finish
the code of exercise 3.17.
Victor Eijkhout 67
3. MPI topic: Collectives
3.7 Reduce-scatter
There are several MPI collectives that are functionally equivalent to a combination of others. You have
already seen MPI_Allreduce which is equivalent to a reduction followed by a broadcast. Often such com-
binations can be more efficient than using the individual calls; see HPC book, section-6.1.
Here is another example: MPI_Reduce_scatter is equivalent to a reduction on an array of data (meaning a
pointwise reduction on each array location) followed by a scatter of this array to the individual processes.
We will discuss this routine, or rather its variant MPI_Reduce_scatter_block (figure 3.10), using an impor-
tant example: the sparse matrix-vector product (see HPC book, section-6.5.1 for background information).
Each process contains one or more matrix rows, so by looking at indices the process can decide what other
processes it needs to receive data from, that is, each process knows how many messages it will receive,
and from which processes. The problem is for a process to find out what other processes it needs to send
data to.
Let’s set up the data:
// reducescatter.c
int
// data that we know:
*i_recv_from_proc = (int*) malloc(nprocs*sizeof(int)),
*procs_to_recv_from, nprocs_to_recv_from=0,
// data we are going to determin:
*procs_to_send_to,nprocs_to_send_to;
Each process creates an array of ones and zeros, describing who it needs data from. Ideally, we only need
the array procs_to_recv_from but initially we need the (possibly much larger) array i_recv_from_proc.
Next, the MPI_Reduce_scatter_block call then computes, on each process, how many messages it needs to
send.
MPI_Reduce_scatter_block
(i_recv_from_proc,&nprocs_to_send_to,1,MPI_INT,
MPI_SUM,comm);
Victor Eijkhout 69
3. MPI topic: Collectives
We do not yet have the information to which processes to send. For that, each process sends a zero-size
message to each of its senders. Conversely, it then does a receive to with MPI_ANY_SOURCE to discover who is
requesting data from it. The crucial point to the MPI_Reduce_scatter_block call is that, without it, a process
would not know how many of these zero-size messages to expect.
/*
* Send a zero-size msg to everyone that you receive from,
* just to let them know that they need to send to you.
*/
MPI_Request send_requests[nprocs_to_recv_from];
for (int iproc=0; iproc<nprocs_to_recv_from; iproc++) {
int proc=procs_to_recv_from[iproc];
double send_buffer=0.;
MPI_Isend(&send_buffer,0,MPI_DOUBLE, /*to:*/ proc,0,comm,
&(send_requests[iproc]));
}
/*
* Do as many receives as you know are coming in;
* use wildcards since you don't know where they are coming from.
* The source is a process you need to send to.
*/
procs_to_send_to = (int*)malloc( nprocs_to_send_to * sizeof(int) );
for (int iproc=0; iproc<nprocs_to_send_to; iproc++) {
double recv_buffer;
MPI_Status status;
MPI_Recv(&recv_buffer,0,MPI_DOUBLE,MPI_ANY_SOURCE,MPI_ANY_TAG,comm,
&status);
procs_to_send_to[iproc] = status.MPI_SOURCE;
}
MPI_Waitall(nprocs_to_recv_from,send_requests,MPI_STATUSES_IGNORE);
The MPI_Reduce_scatter (figure 3.10) call is more general: instead of indicating the mere presence of a
message between two processes, by having individual receive counts one can, for instance, indicate the
size of the messages.
We can look at reduce-scatter as a limited form of the all-to-all data transposition discussed above (sec-
tion 3.6.1). Suppose that the matrix 𝐶 contains only 0/1, indicating whether or not a messages is send,
rather than the actual amounts. If a receiving process only needs to know how many messages to receive,
rather than where they come from, it is enough to know the column sum, rather than the full column (see
figure 3.9).
Another application of the reduce-scatter mechanism is in the dense matrix-vector product, if a two-
dimensional data distribution is used.
Exercise 3.19. Implement the dense matrix-vector product, where the matrix is distributed
by columns: each process stores 𝐴∗𝑗 for a disjoint set of 𝑗-values. At the start and
end of the algorithm each process should store a distinct part of the input and
output vectors. Argue that this can be done naively with an MPI_Reduce operation,
but more efficiently using MPI_Reduce_scatter.
For discussion, see HPC book, section-6.2.2.
3.7.1 Examples
An important application of this is establishing an irregular communication pattern. Assume that each
process knows which other processes it wants to communicate with; the problem is to let the other pro-
cesses know about this. The solution is to use MPI_Reduce_scatter to find out how many processes want
to communicate with you
MPI_Reduce_scatter_block
(i_recv_from_proc,&nprocs_to_send_to,1,MPI_INT,
MPI_SUM,comm);
and then wait for precisely that many messages with a source value of MPI_ANY_SOURCE.
/*
* Send a zero-size msg to everyone that you receive from,
* just to let them know that they need to send to you.
*/
MPI_Request send_requests[nprocs_to_recv_from];
for (int iproc=0; iproc<nprocs_to_recv_from; iproc++) {
int proc=procs_to_recv_from[iproc];
double send_buffer=0.;
MPI_Isend(&send_buffer,0,MPI_DOUBLE, /*to:*/ proc,0,comm,
&(send_requests[iproc]));
}
/*
* Do as many receives as you know are coming in;
* use wildcards since you don't know where they are coming from.
* The source is a process you need to send to.
Victor Eijkhout 71
3. MPI topic: Collectives
*/
procs_to_send_to = (int*)malloc( nprocs_to_send_to * sizeof(int) );
for (int iproc=0; iproc<nprocs_to_send_to; iproc++) {
double recv_buffer;
MPI_Status status;
MPI_Recv(&recv_buffer,0,MPI_DOUBLE,MPI_ANY_SOURCE,MPI_ANY_TAG,comm,
&status);
procs_to_send_to[iproc] = status.MPI_SOURCE;
}
MPI_Waitall(nprocs_to_recv_from,send_requests,MPI_STATUSES_IGNORE);
Use of MPI_Reduce_scatter to implement the two-dimensional matrix-vector product. Set up separate row
and column communicators with MPI_Comm_split, use MPI_Reduce_scatter to combine local products.
MPI_Allgather(&my_x,1,MPI_DOUBLE,
local_x,1,MPI_DOUBLE,environ.col_comm);
MPI_Reduce_scatter(local_y,&my_y,&ione,MPI_DOUBLE,
MPI_SUM,environ.row_comm);
3.8 Barrier
A barrier call, MPI_Barrier (figure 3.11) is a routine that blocks all processes until they have all reached
the barrier call. Thus it achieves time synchronization of the processes.
This call’s simplicity is contrasted with its usefulness, which is very limited. It is almost never necessary
to synchronize processes through a barrier: for most purposes it does not matter if processors are out of
sync. Conversely, collectives (except the new nonblocking ones; section 3.11) introduce a barrier of sorts
themselves.
same for all). In the regular MPI_Gather call the root processor had a buffer of size 𝑛𝑃, where 𝑛 is the
number of elements produced on each processor, and 𝑃 the number of processors. The contribution from
processor 𝑝 would go into locations 𝑝𝑛, … , (𝑝 + 1)𝑛 − 1.
For the variable case, we first need to compute the total required buffer size. This can be done through a
simple MPI_Reduce with MPI_SUM as reduction operator: the buffer size is ∑𝑝 𝑛𝑝 where 𝑛𝑝 is the number of
elements on processor 𝑝. But you can also postpone this calculation for a minute.
The next question is where the contributions of the processor will go into this buffer. For the contribution
from processor 𝑝 that is ∑𝑞<𝑝 𝑛𝑝 , … ∑𝑞≤𝑝 𝑛𝑝 − 1. To compute this, the root processor needs to have all the
𝑛𝑝 numbers, and it can collect them with an MPI_Gather call.
We now have all the ingredients. All the processors specify a send buffer just as with MPI_Gather. However,
the receive buffer specification on the root is more complicated. It now consists of:
For example, in an MPI_Gatherv (figure 3.12) call each process has an individual number of items to con-
tribute. To gather this, the root process needs to find these individual amounts with an MPI_Gather call,
and locally construct the offsets array. Note how the offsets array has size ntids+1: the final offset value
is automatically the total size of all incoming data. See the example below.
There are various calls where processors can have buffers of differing sizes.
• In MPI_Scatterv (figure 3.13) the root process has a different amount of data for each recipient.
• In MPI_Gatherv, conversely, each process contributes a different sized send buffer to the re-
ceived result; MPI_Allgatherv (figure 3.14) does the same, but leaves its result on all processes;
MPI_Alltoallv does a different variable-sized gather on each process.
We use MPI_Gatherv to do an irregular gather onto a root. We first need an MPI_Gather to determine offsets.
Victor Eijkhout 73
3. MPI topic: Collectives
template<typename T>
void gatherv
(int root_rank, const T *senddata, const layout<T> &sendl,
T *recvdata, const layouts<T> &recvls, const displacements &recvdispls) const
(int root_rank, const T *senddata, const layout<T> &sendl,
T *recvdata, const layouts<T> &recvls) const
(int root_rank, const T *senddata, const layout<T> &sendl ) const
Python:
Code: Output:
// gatherv.c make[3]: `gatherv' is up to
// we assume that each process has an array "localdata" ↪date.
// of size "localsize" TACC: Starting up job
↪4328411
// the root process decides how much data will be coming: TACC: Starting parallel
// allocate arrays to contain size and offset information ↪tasks...
if (procno==root) { Local sizes: 13, 12, 13, 14,
localsizes = (int*) malloc( nprocs*sizeof(int) ); ↪11, 12, 14, 6, 12, 8,
offsets = (int*) malloc( nprocs*sizeof(int) ); Collected:
}
// everyone contributes their local size info ↪0:1,1,1,1,1,1,1,1,1,1,1,1,1;
MPI_Gather(&localsize,1,MPI_INT, 1:2,2,2,2,2,2,2,2,2,2,2,2;
localsizes,1,MPI_INT,root,comm);
// the root constructs the offsets array ↪2:3,3,3,3,3,3,3,3,3,3,3,3,3;
if (procno==root) {
int total_data = 0; ↪3:4,4,4,4,4,4,4,4,4,4,4,4,4,4;
for (int i=0; i<nprocs; i++) { 4:5,5,5,5,5,5,5,5,5,5,5;
offsets[i] = total_data; 5:6,6,6,6,6,6,6,6,6,6,6,6;
total_data += localsizes[i];
} ↪6:7,7,7,7,7,7,7,7,7,7,7,7,7,7;
Victoralldata
Eijkhout = (int*) malloc( total_data*sizeof(int) ); 7:8,8,8,8,8,8; 75
} 8:9,9,9,9,9,9,9,9,9,9,9,9;
// everyone contributes their data 9:10,10,10,10,10,10,10,10;
MPI_Gatherv(localdata,localsize,MPI_INT, TACC: Shutdown complete.
↪Exiting.
↪alldata,localsizes,offsets,MPI_INT,root,comm);
3. MPI topic: Collectives
## gatherv.py
# implicitly using root=0
globalsize = comm.reduce(localsize)
if procid==0:
print("Global size=%d" % globalsize)
collecteddata = np.empty(globalsize,dtype=int)
counts = comm.gather(localsize)
comm.Gatherv(localdata, [collecteddata, counts])
// allgatherv.c
MPI_Allgather
( &my_count,1,MPI_INT,
recv_counts,1,MPI_INT, comm );
int accumulate = 0;
for (int i=0; i<nprocs; i++) {
recv_displs[i] = accumulate; accumulate += recv_counts[i]; }
int *global_array = (int*) malloc(accumulate*sizeof(int));
MPI_Allgatherv
( my_array,procno+1,MPI_INT,
global_array,recv_counts,recv_displs,MPI_INT, comm );
In python the receive buffer has to contain the counts and displacements arrays.
## allgatherv.py
mycount = procid+1
my_array = np.empty(mycount,dtype=np.float64)
my_count = np.empty(1,dtype=int)
my_count[0] = mycount
comm.Allgather( my_count,recv_counts )
accumulate = 0
for p in range(nprocs):
recv_displs[p] = accumulate; accumulate += recv_counts[p]
global_array = np.empty(accumulate,dtype=np.float64)
comm.Allgatherv( my_array, [global_array,recv_counts,recv_displs,MPI.DOUBLE] )
Victor Eijkhout 77
3. MPI topic: Collectives
Fortran note 6: Min/maxloc types. The original Fortran interface to MPI was designed around Fortran77
features, so it is not using Fortran derived types (Type keyword). Instead, all integer indices
are stored in whatever the type is that is being reduced. The available result types are then
MPI_2REAL, MPI_2DOUBLE_PRECISION, MPI_2INTEGER.
Likewise, the input needs to be arrays of such type. Consider this example:
Real*8,dimension(2,N) :: input,output
call MPI_Reduce( input,output, N, MPI_2DOUBLE_PRECISION, &
MPI_MAXLOC, root, comm )
MPI.Op.create(cls,function,bool commute=False)
Python note 11: Define reduction operator. In python, Op.Create is a class method for the MPI class.
rwz = MPI.Op.Create(reduceWithoutZero)
positive_minimum = np.zeros(1,dtype=intc)
comm.Allreduce(data[procid],positive_minimum,rwz);
For example, here is an operator for finding the smallest nonzero number in an array of nonnegative
integers:
*(int*)inout = m;
}
Victor Eijkhout 79
3. MPI topic: Collectives
Python note 12: Reduction function. The python equivalent of such a function receives bare buffers as
arguments. Therefore, it is best to turn them first into NumPy arrays using np.frombuffer:
## reductpositive.py
def reduceWithoutZero(in_buf, inout_buf, datatype):
typecode = MPI._typecode(datatype)
assert typecode is not None ## check MPI datatype is built-in
dtype = np.dtype(typecode)
n = in_array[0]; r = inout_array[0]
if n==0:
m = r
elif r==0:
m = n
elif n<r:
m = n
else:
m = r
inout_array[0] = m
The assert statement accounts for the fact that this mapping of MPI datatype to NumPy dtype
only works for built-in MPI datatypes.
MPL note 20: User-defined operators. A user-defined operator can be a templated class with an operator().
Example:
// reduceuser.cxx
template<typename T>
class lcm {
public:
T operator()(T a, T b) {
T zero=T();
T t((a/gcd(a, b))*b);
if (t<zero)
return -t;
return t;
}
comm_world.reduce(lcm<int>(), 0, v, result);
The function has an array length argument len, to allow for pointwise reduction on a whole array at
once. The inoutvec array contains partially reduced results, and is typically overwritten by the function.
‖𝑥‖1 ≡ ∑ |𝑥𝑖 |.
𝑖
This sets the operator to MPI_OP_NULL. This is not necessary in OO languages, where the destructor takes
care of it.
You can query the commutativity of an operator with MPI_Op_commutative (figure 3.16).
𝑦 ← 𝐴𝑥 + (𝑥 𝑡 𝑥)𝑦
involves a matrix-vector product, which is dominated by computation in the sparse matrix case, and an
inner product which is typically dominated by the communication cost. You would code this as
Victor Eijkhout 81
3. MPI topic: Collectives
This can also be used for 3D FFT operations [14]. Occasionally, a nonblocking collective can be used for
nonobvious purposes, such as the MPI_Ibarrier in [15].
These have roughly the same calling sequence as their blocking counterparts, except that they output an
MPI_Request. You can then use an MPI_Wait call to make sure the collective has completed.
𝛼 ← 𝑥𝑡 𝑦
𝛽 ← ‖𝑧‖∞
Remark 6 Blocking and nonblocking don’t match: either all processes call the nonblocking or all call the
blocking one. Thus the following code is incorrect:
if (rank==root)
MPI_Reduce( &x /* ... */ root,comm );
else
MPI_Ireduce( &x /* ... */ );
This is unlike the point-to-point behavior of nonblocking calls: you can catch a message with MPI_Irecv that
was sent with MPI_Send.
Remark 7 Unlike sends and received, collectives have no identifying tag. With blocking collectives that does
not lead to ambiguity problems. With nonblocking collectives it means that all processes need to issue them
in identical order.
Victor Eijkhout 83
3. MPI topic: Collectives
// ireducescalar.cxx
float x{1.},sum;
auto reduce_request =
comm_world.ireduce(mpl::plus<float>(), 0, x, sum);
reduce_request.wait();
if (comm_world.rank()==0) {
std::cout << "sum = " << sum << '\n';
}
3.11.1 Examples
3.11.1.1 Array transpose
To illustrate the overlapping of multiple nonblocking collectives, consider transposing a data matrix. Ini-
tially, each process has one row of the matrix; after transposition each process has a column. Since each
row needs to be distributed to all processes, algorithmically this corresponds to a series of scatter calls,
one originating from each process.
// itransposeblock.c
for (int iproc=0; iproc<nprocs; iproc++) {
MPI_Scatter( regular,1,MPI_DOUBLE,
&(transpose[iproc]),1,MPI_DOUBLE,
iproc,comm);
}
&(transpose[iproc]),1,MPI_DOUBLE,
iproc,comm,scatter_requests+iproc);
}
MPI_Waitall(nprocs,scatter_requests,MPI_STATUSES_IGNORE);
Exercise 3.22. Can you implement the same algorithm with MPI_Igather?
3.11.1.2 Stencils
The ever-popular five-point stencil evaluation does not look like a collective operation, and indeed, it is
usually evaluated with (nonblocking) send/recv operations. However, if we create a subcommunicator on
each subdomain that contains precisely that domain and its neighbors, (see figure 3.10) we can formu-
late the communication pattern as a gather on each of these. With ordinary collectives this can not be
formulated in a deadlock-free manner, but nonblocking collectives make this feasible.
We will see an even more elegant formulation of this operation in section 11.2.
Victor Eijkhout 85
3. MPI topic: Collectives
One scenario would be local refinement, where some processes decide to refine their subdomain, which
fact they need to communicate to their neighbors. The problem here is that most processes are not among
these neighbors, so they should not post a receive of any type. Instead, any refining process sends to its
neighbors, and every process posts a barrier.
// ibarrierprobe.c
if (i_do_send) {
/*
* Pick a random process to send to,
* not yourself.
*/
int receiver = rand()%nprocs;
MPI_Ssend(&data,1,MPI_FLOAT,receiver,0,comm);
}
/*
* Everyone posts the non-blocking barrier
* and gets a request to test/wait for
*/
MPI_Request barrier_request;
MPI_Ibarrier(comm,&barrier_request);
Now every process alternately probes for messages and tests for completion of the barrier. Probing is done
through the nonblocking MPI_Iprobe call, while testing completion of the barrier is done through MPI_Test.
for ( ; ; step++) {
int barrier_done_flag=0;
MPI_Test(&barrier_request,&barrier_done_flag,
MPI_STATUS_IGNORE);
//stop if you're done!
if (barrier_done_flag) {
break;
} else {
// if you're not done with the barrier:
int flag; MPI_Status status;
MPI_Iprobe
( MPI_ANY_SOURCE,MPI_ANY_TAG,
comm, &flag, &status );
if (flag) {
// absorb message!
We can use a nonblocking barrier to good effect, utilizing the idle time that would result from a blocking
barrier. In the following code fragment processes test for completion of the barrier, and failing to detect
such completion, perform some local work.
// findbarrier.c
MPI_Request final_barrier;
MPI_Ibarrier(comm,&final_barrier);
int global_finish=mysleep;
do {
int all_done_flag=0;
MPI_Test(&final_barrier,&all_done_flag,MPI_STATUS_IGNORE);
if (all_done_flag) {
break;
} else {
int flag; MPI_Status status;
// force progress
MPI_Iprobe
( MPI_ANY_SOURCE,MPI_ANY_TAG,
comm, &flag, MPI_STATUS_IGNORE );
printf("[%d] going to work for another second\n",procid);
sleep(1);
global_finish++;
}
} while (1);
every other process. While this describes the semantics of the operation, in practice the implementation
works quite differently.
The time that a message takes can simply be modeled as
𝛼 + 𝛽𝑛,
where 𝛼 is the latency, a one time delay from establishing the communication between two processes,
and 𝛽 is the time-per-byte, or the inverse of the bandwidth, and 𝑛 the number of bytes sent.
Under the assumption that a processor can only send one message at a time, the broadcast in figure 3.11
would take a time proportional to the number of processors.
Victor Eijkhout 87
3. MPI topic: Collectives
Exercise 3.23. What is the total time required for a broadcast involving 𝑝 processes? Give 𝛼
and 𝛽 terms separately.
One way to ameliorate that is to structure the broadcast in a tree-like fashion. This is depicted in fig-
ure 3.12.
Exercise 3.24. How does the communication time now depend on the number of
processors, again 𝛼 and 𝛽 terms separately.
What would be a lower bound on the 𝛼, 𝛽 terms?
The theory of the complexity of collectives is described in more detail in HPC book, section-6.1; see
also [3].
the send operations on all processors will occur after the root executes the broadcast. Conversely, in a
reduce operation the root may have to wait for other processors. This is illustrated in figure 3.13, which
gives a TAU trace of a reduction operation on two nodes, with two six-core sockets (processors) each. We
see that1 :
• In each socket, the reduction is a linear accumulation;
• on each node, cores zero and six then combine their result;
• after which the final accumulation is done through the network.
We also see that the two nodes are not perfectly in sync, which is normal for MPI applications. As a result,
core 0 on the first node will sit idle until it receives the partial result from core 12, which is on the second
node.
While collectives synchronize in a loose sense, it is not possible to make any statements about events
before and after the collectives between processors:
1. This uses mvapich version 1.6; in version 1.9 the implementation of an on-node reduction has changed to simulate shared
memory.
Figure 3.13: Trace of a reduction operation between two dual-socket 12-core nodes
...event 1...
MPI_Bcast(....);
...event 2....
Note the MPI_ANY_SOURCE parameter in the receive calls on processor 1. One obvious execution of this would
be:
Victor Eijkhout 89
3. MPI topic: Collectives
3.14.1 Scalability
We are motivated to write parallel software from two considerations. First of all, if we have a certain
problem to solve which normally takes time 𝑇 , then we hope that with 𝑝 processors it will take time 𝑇 /𝑝.
If this is true, we call our parallelization scheme scalable in time. In practice, we often accept small extra
terms: as you will see below, parallelization often adds a term log2 𝑝 to the running time.
Exercise 3.25. Discuss scalability of the following algorithms:
• You have an array of floating point numbers. You need to compute the sine of
each
• You a two-dimensional array, denoting the interval [−2, 2]2 . You want to make
a picture of the Mandelbrot set, so you need to compute the color of each point.
• The primality test of exercise 2.6.
There is also the notion that a parallel algorithm can be scalable in space: more processors gives you more
memory so that you can run a larger problem.
Exercise 3.26. Discuss space scalability in the context of modern processor design.
Victor Eijkhout 91
3. MPI topic: Collectives
Simple ring Let the root only send to the next process, and that one send to its neighbor. This scheme
is known as a bucket brigade; see also section 4.1.5.
What is the expected performance of this in terms of 𝛼, 𝛽?
Run some tests and confirm.
Pipelined ring In a ring broadcast, each process needs to receive the whole message before it can
pass it on. We can increase the efficiency by breaking up the message and sending it in multiple parts.
(See figure 3.15.) This will be advantageous for messages that are long enough that the bandwidth cost
dominates the latency.
Assume a send buffer of length more than 1. Divide the send buffer into a number of chunks. The root
sends the chunks successively to the next process, and each process sends on whatever chunks it receives.
What is the expected performance of this in terms of 𝛼, 𝛽? Why is this better than the simple ring?
Run some tests and confirm.
Recursive doubling Collectives such as broadcast can be implemented through recursive doubling,
where the root sends to another process, then the root and the other process send to two more, those
four send to four more, et cetera. However, in an actual physical architecture this scheme can be realized
in multiple ways that have drastically different performance.
First consider the implementation where process 0 is the root, and it starts by sending to process 1; then
they send to 2 and 3; these four send to 4–7, et cetera. If the architecture is a linear array of procesors,
this will lead to contention: multiple messages wanting to go through the same wire. (This is also related
to the concept of bisecection bandwidth.)
In the following analyses we will assume wormhole routing: a message sets up a path through the network,
reserving the necessary wires, and performing a send in time independent of the distance through the
network. That is, the send time for any message can be modeled as
𝑇 (𝑛) = 𝛼 + 𝛽𝑛
regardless source and destination, as long as the necessary connections are available.
Exercise 3.27. Analyze the running time of a recursive doubling broad cast as just
described, with wormhole routing.
Implement this broadcast in terms of blocking MPI send and receive calls. If you
have SimGrid available, run tests with a number of parameters.
The alternative, that avoids contention, is to let each doubling stage divide the network into separate
halves. That is, process 0 sends to 𝑃/2, after which these two repeat the algorithm in the two halves of
the network, sending to 𝑃/4 and 3𝑃/4 respectively.
Exercise 3.28. Analyze this variant of recursive doubling. Code it and measure runtimes on
SimGrid.
Exercise 3.29. Revisit exercise 3.27 and replace the blocking calls by nonblocking
MPI_Isend / MPI_Irecv calls.
Make sure to test that the data is correctly propagated.
MPI implementations often have multiple algorithms, which they dynamicaly switch between. Sometimes
you can determine the choice yourself through environment variables.
TACC note. For Intel MPI , see https://software.intel.com/en-us/
mpi-developer-reference-linux-i-mpi-adjust-family-environment-variables.
Victor Eijkhout 93
3. MPI topic: Collectives
give the approximate MPI-based code that computes the maximum value in the
array, and leaves the result on every processor.
Review 3.37.
double data[Nglobal];
int myfirst = /* something */, mylast = /* something */;
for (int i=myfirst; i<mylast; i++) {
if (i>0 && i<N-1) {
process_point( data,i,Nglobal );
}
}
void process_point( double *data,int i,int N ) {
data[i-1] = g(i-1); data[i] = g(i); data[i+1] = g(i+1);
data[i] = f(data[i-1],data[i],data[i+1]);
}
Is this scalable in time? Is this scalable in space? What is the missing MPI call?
Review 3.38.
double data[Nlocal+2]; // include left and right neighbor
int myfirst = /* something */, mylast = myfirst+Nlocal;
for (int i=0; i<Nlocal; i++) {
if (i>0 && i<N-1) {
process_point( data,i,Nlocal );
}
void process_point( double *data,int i0,int n ) {
int i = i0+1;
data[i-1] = g(i-1); data[i] = g(i); data[i+1] = g(i+1);
data[i] = f(data[i-1],data[i],data[i+1]);
}
Is this scalable in time? Is this scalable in space? What is the missing MPI call?
Review 3.39. With data as in the previous question, given the code for normalizing the
array, that is, scaling each element so that ‖𝑥‖2 = 1.
Review 3.40. Just like MPI_Allreduce is equivalent to MPI_Reduce following by MPI_Bcast,
MPI_Reduce_scatter is equivalent to at least one of the following combinations. Select
those that are equivalent, and discuss differences in time or space complexity:
Victor Eijkhout 95
3. MPI topic: Collectives
As seen in figure 2.6, we give each processor a contiguous subset of the 𝑥𝑖 s and 𝑦𝑖 s. Let’s define 𝑖𝑝 as the
first index of 𝑦 that is computed by processor 𝑝. (What is the last index computed by processor 𝑝? How
many indices are computed on that processor?)
We often talk about the owner computes model of parallel computing: each processor ‘owns’ certain data
items, and it computes their value. The values used for this computation need of course not be local, and
this is where the need for communication arises.
Let’s investigate how processor 𝑝 goes about computing 𝑦𝑖 for the 𝑖-values it owns. Let’s assume that
process 𝑝 also stores the values 𝑥𝑖 for these same indices. Now, for many values 𝑖 it can evalute the com-
putation
𝑦𝑖 = (𝑥𝑖−1 + 𝑥𝑖 + 𝑥𝑖+1 )/3
locally (figure 4.1).
However, there is a problem with computing 𝑦 in the first index 𝑖𝑝 on processor 𝑝:
The point to the left, 𝑥𝑖𝑝 −1 , is not stored on process 𝑝 (it is stored on 𝑝−1), so it is not immediately available
for use by process 𝑝. (figure 4.2). There is a similar story with the last index that 𝑝 tries to compute: that
involves a value that is only present on 𝑝 + 1.
You see that there is a need for processor-to-processor, or technically point-to-point, information ex-
change. MPI realizes this through matched send and receive calls:
• One process does a send to a specific other process;
• the other process does a specific receive from that source.
We will now discuss the send and receive routines in detail.
97
4. MPI topic: Point-to-point
Since we are programming in SPMD mode, this means our program looks like:
if ( /* I am process A */ ) {
MPI_Send( /* to: */ B ..... );
MPI_Recv( /* from: */ B ... );
} else if ( /* I am process B */ ) {
MPI_Recv( /* from: */ A ... );
MPI_Send( /* to: */ A ..... );
}
Remark 8 The structure of the send and receive calls shows the symmetric nature of MPI: every target process
is reached with the same send call, no matter whether it’s running on the same multicore chip as the sender, or
template<typename T >
void mpl::communicator::send
( const T scalar&,int dest,tag = tag(0) ) const
( const T *buffer,const layout< T > &,int dest,tag = tag(0) ) const
( iterT begin,iterT end,int dest,tag = tag(0) ) const
T : scalar type
begin : begin iterator
end : end iterator
Python:
Python native:
MPI.Comm.send(self, obj, int dest, int tag=0)
Python numpy:
MPI.Comm.Send(self, buf, int dest, int tag=0)
on a computational node halfway across the machine room, taking several network hops to reach. Of course,
any self-respecting MPI implementation optimizes for the case where sender and receiver have access to the
same shared memory. This means that a send/recv pair is realized as a copy operation from the sender buffer
to the receiver buffer, rather than a network transfer.
Victor Eijkhout 99
4. MPI topic: Point-to-point
Buffer The send buffer is described by a trio of buffer/count/datatype. See section 3.2.4 for discussion.
Target The messsage target is an explicit process rank to send to. This rank is a number from zero up
to the result of MPI_Comm_size. It is allowed for a process to send to itself, but this may lead to a runtime
deadlock; see section 4.1.4 for discussion. The value MPI_PROC_NULL is allowed: using that as a target causes
no message to be sent or received.
Tag Next, a message can have a tag. Many applications have each sender send only one message at a
time to a given receiver. For the case where there are multiple simultaneous messages between the same
sender / receiver pair, the tag can be used to disambiguate between the messages.
Often, a tag value of zero is safe to use. Indeed, OO interfaces to MPI typically have the tag as an optional
parameter with value zero. If you do use tag values, you can use the key MPI_TAG_UB to query what the
maximum value is that can be used; see section 15.1.2.
Communicator Finally, in common with the vast majority of MPI calls, there is a communicator ar-
gument that provides a context for the send transaction. In order to match a send and receive operation,
they need to be in the same communicator.
MPL note 23: Buffer type safety.
• Data type is templated: derived by the compiler.
• Count > 1 is declared in the datatype.
MPL note 24: Blocking send and receive. MPL uses a default value for the tag, and it can deduce the type
of the buffer. Sending a scalar becomes:
// sendscalar.cxx
if (comm_world.rank()==0) {
double pi=3.14;
comm_world.send(pi, 1); // send to rank 1
cout << "sent: " << pi << '\n';
} else if (comm_world.rank()==1) {
double pi=0;
comm_world.recv(pi, 0); // receive from rank 0
cout << "got : " << pi << '\n';
}
// sendbuffer.cxx
std::vector<double> v(8);
mpl::contiguous_layout<double> v_layout(v.size());
comm_world.send(v.data(), v_layout, 1); // send to rank 1
comm_world.recv(v.data(), v_layout, 0); // receive from rank 0
Buffer The receive buffer has the same buffer/count/data parameters as the send call. However, the
count argument here indicates the size of the buffer, rather than the actual length of a message. This sets
an upper bound on the length of the incoming message.
• For receiving messages with unknown length, use MPI_Probe; section 4.4.1.
• A message longer than the buffer size will give an overflow error, either returning an error, or
ending your program; see section 15.2.2.
The length of the received message can be determined from the status object; see section 4.3 for more
detail.
Source Mirroring the target argument of the MPI_Send call, MPI_Recv has a message source argument. This
can be either a specific rank, or it can be the MPI_ANY_SOURCE wildcard. In the latter case, the actual source
can be determined after the message has been received; see section 4.3. A source value of MPI_PROC_NULL
is also allowed, which makes the receive succeed immediately with no data received.
MPL note 27: Any source. The constant mpl::any_source equals MPI_ANY_SOURCE (by constexpr).
template<typename T >
status mpl::communicator::recv
( T &,int,tag = tag(0) ) const inline
( T *,const layout< T > &,int,tag = tag(0) ) const
( iterT begin,iterT end,int source, tag t = tag(0) ) const
Python:
Tag Similar to the messsage source, the message tag of a receive call can be a specific value or a wildcard,
in this case MPI_ANY_TAG.
Python note 13: Message tags. Python calls sensible use a default tag=0, but you can specify your own tag
value. On the receive call, the tag wildcard is MPI.ANY_TAG.
Status The MPI_Recv command has one parameter that the send call lacks: the MPI_Status object, de-
scribing the message status. This gives information about the message received, for instance if you used
wildcards for source or tag. See section 4.3 for more about the status object.
Remark 9 If you’re not interested in the status, as is the case in many examples in this book, you can specify
the constant MPI_STATUS_IGNORE. Note that the signature of MPI_Recv lists the status parameter as ‘output’; this
‘direction’ of the parameter of course only applies if you do not specify this constant.
Exercise 4.1. Implement the ping-pong program. Add a timer using MPI_Wtime. For the
status argument of the receive call, use MPI_STATUS_IGNORE.
• Run multiple ping-pongs (say a thousand) and put the timer around the loop.
The first run may take longer; try to discard it.
• Run your code with the two communicating processes first on the same node,
then on different nodes. Do you see a difference?
• Then modify the program to use longer messages. How does the timing
increase with message size?
For bonus points, can you do a regression to determine 𝛼, 𝛽?
(There is a skeleton for this exercise under the name pingpong.)
Exercise 4.2. Take your pingpong program and modify it to let half the processors be
source and the other half the targets. Does the pingpong time increase? Does the
observed behavior depend on how you choose the two sets?
Figure 4.3: Illustration of an ideal (left) and actual (right) send-receive interaction
somewhere in the network there is buffer capacity for all messages that are in transit. This is not the case:
data resides on the sender, and the sending call blocks, until the receiver has received all of it. (There is a
exception for small messages, as explained in the next section.)
The use of MPI_Send and MPI_Recv is known as blocking communication: when your code reaches a send or
receive call, it blocks until the call is succesfully completed. Technically, blocking operations are called
non-local since their execution depends on factors that are not local to the process. See section 5.4.
4.1.4.1 Deadlock
Suppose two process need to exchange data, and consider the following pseudo-code, which purports to
exchange data between processes 0 and 1:
Imagine that the two processes execute this code. They both issue the send call… and then can’t go on,
because they are both waiting for the other to issue the send call corresponding to their receive call. This
is known as deadlock.
With a synchronous protocol you should get deadlock, since the send calls will be waiting for the receive
operation to be posted.
In practice, however, this code will often work. The reason is that MPI implementations sometimes send
small messages regardless of whether the receive has been posted. This is known as an eager send, and it
relies on the availability of some amount of available buffer space. The size under which this behavior is
used is sometimes referred to as the eager limit.
To illustrate eager and blocking behavior in MPI_Send, consider an example where we send gradually larger
messages. From the screen output you can see what the largest message was that fell under the eager limit;
after that the code hangs because of a deadlock.
// sendblock.c
other = 1-procno;
/* loop over increasingly large messages */
for (int size=1; size<2000000000; size*=10) {
sendbuf = (int*) malloc(size*sizeof(int));
recvbuf = (int*) malloc(size*sizeof(int));
if (!sendbuf || !recvbuf) {
printf("Out of memory\n"); MPI_Abort(comm,1);
}
MPI_Send(sendbuf,size,MPI_INT,other,0,comm);
MPI_Recv(recvbuf,size,MPI_INT,other,0,comm,&status);
/* If control reaches this point, the send call
did not block. If the send call blocks,
we do not reach this point, and the program will hang.
*/
if (procno==0)
printf("Send did not block for size %d\n",size);
free(sendbuf); free(recvbuf);
}
!! sendblock.F90
other = 1-mytid
size = 1
do
allocate(sendbuf(size)); allocate(recvbuf(size))
print *,size
call MPI_Send(sendbuf,size,MPI_INTEGER,other,0,comm,err)
call MPI_Recv(recvbuf,size,MPI_INTEGER,other,0,comm,status,err)
if (mytid==0) then
print *,"MPI_Send did not block for size",size
end if
deallocate(sendbuf); deallocate(recvbuf)
size = size*10
if (size>2000000000) goto 20
end do
20 continue
## sendblock.py
size = 1
while size<2000000000:
sendbuf = np.empty(size, dtype=int)
recvbuf = np.empty(size, dtype=int)
comm.Send(sendbuf,dest=other)
comm.Recv(sendbuf,source=other)
if procid<other:
print("Send did not block for",size)
size *= 10
If you want a code to exhibit the same blocking behavior for all message sizes, you force the send call
to be blocking by using MPI_Ssend, which has the same calling sequence as MPI_Send, but which does not
allow eager sends.
// ssendblock.c
other = 1-procno;
sendbuf = (int*) malloc(sizeof(int));
recvbuf = (int*) malloc(sizeof(int));
size = 1;
MPI_Ssend(sendbuf,size,MPI_INT,other,0,comm);
MPI_Recv(recvbuf,size,MPI_INT,other,0,comm,&status);
printf("This statement is not reached\n");
Formally you can describe deadlock as follows. Draw up a graph where every process is a node, and draw
a directed arc from process A to B if A is waiting for B. There is deadlock if this directed graph has a loop.
The solution to the deadlock in the above example is to first do the send from 0 to 1, and then from 1 to 0
(or the other way around). So the code would look like:
if ( /* I am processor 0 */ ) {
send(target=other);
receive(source=other);
} else {
receive(source=other);
send(target=other);
}
Eager sends also influences non-blocking sends. The wait call after a non-blocking send will return imme-
diately, regardless any receive call, if the message is under the eager limit:
Code: Output:
// eageri.c Setting eager limit to 5000
printf("Sending %lu elements\n",n); ↪bytes
MPI_Request request; TACC: Starting up job
MPI_Isend(buffer,n,MPI_DOUBLE,processB,0,comm,&request); ↪4049189
MPI_Wait(&request,MPI_STATUS_IGNORE); TACC: Starting parallel
printf(".. concluded\n"); ↪tasks...
Sending 1 elements
.. concluded
Sending 10 elements
.. concluded
Sending 100 elements
.. concluded
Sending 1000 elements
^C[[email protected]]
↪Sending Ctrl-C to
↪processes as requested
The eager limit is implementation-specific. For instance, for Intel MPI there is a variable
I_MPI_EAGER_THRESHOLD (old versions) or I_MPI_SHM_EAGER_THRESHOLD; for mvapich2 it is
MV2_IBA_EAGER_THRESHOLD, and for OpenMPI the --mca options btl_openib_eager_limit and
btl_openib_rndv_eager_limit.
4.1.4.3 Serialization
There is a second, even more subtle problem with blocking communication. Consider the scenario where
every processor needs to pass data to its successor, that is, the processor with the next higher rank. The
basic idea would be to first send to your successor, then receive from your predecessor. Since the last
processor does not have a successor it skips the send, and likewise the first processor skips the receive.
The pseudo-code looks like:
successor = mytid+1; predecessor = mytid-1;
if ( /* I am not the last processor */ )
send(target=successor);
Exercise 4.3. (Classroom exercise) Each student holds a piece of paper in the right hand
– keep your left hand behind your back – and we want to execute:
1. Give the paper to your right neighbor;
2. Accept the paper from your left neighbor.
Including boundary conditions for first and last process, that becomes the following
program:
1. If you are not the rightmost student, turn to the right and give the paper to
your right neighbor.
2. If you are not the leftmost student, turn to your left and accept the paper from
your left neighbor.
This code does not deadlock. All processors but the last one block on the send call, but the last processor
executes the receive call. Thus, the processor before the last one can do its send, and subsequently continue
to its receive, which enables another send, et cetera.
In one way this code does what you intended to do: it will terminate (instead of hanging forever on a
deadlock) and exchange data the right way. However, the execution now suffers from unexpected serial-
ization: only one processor is active at any time, so what should have been a parallel operation becomes
It is possible to orchestrate your processes to get an efficient and deadlock-free execution, but doing so is
a bit cumbersome.
Exercise 4.5. The above solution treated every processor equally. Can you come up with a
solution that uses blocking sends and receives, but does not suffer from the
serialization behavior?
There are better solutions which we will explore in the next section.
𝑥0 = 1 on process zero
{
𝑥𝑝 = 𝑥𝑝−1 + (𝑝 + 1)2 on process 𝑝
Use MPI_Send and MPI_Recv; make sure to get the order right.
Food for thought: all quantities involved here are integers. Is it a good idea to use
the integer datatype here?
(There is a skeleton for this exercise under the name bucketblock.)
Remark 10 There is an MPI_Scan routine (section 3.4) that performs the same computation, but computa-
tionally more efficiently. Thus, this exercise only serves to illustrate the principle.
with the right choice of source and destination. For instance, to send data to your right neighbor:
MPI_Comm_rank(comm,&procno);
MPI_Sendrecv( ....
/* from: */ procno-1
... ...
/* to: */ procno+1
... );
template<typename T >
status mpl::communicator::sendrecv
( const T & senddata, int dest, tag sendtag,
T & recvdata, int source, tag recvtag
) const
( const T * senddata, const layout< T > & sendl, int dest, tag sendtag,
T * recvdata, const layout< T > & recvl, int source, tag recvtag
) const
( iterT1 begin1, iterT1 end1, int dest, tag sendtag,
iterT2 begin2, iterT2 end2, int source, tag recvtag
) const
Python:
Sendrecv(self,
sendbuf, int dest, int sendtag=0,
recvbuf=None, int source=ANY_SOURCE, int recvtag=ANY_TAG,
Status status=None)
This scheme is correct for all processes but the first and last. In order to use the sendrecv call on these
processes, we use MPI_PROC_NULL for the non-existing processes that the endpoints communicate with.
MPI_Comm_rank( .... &procno );
if ( /* I am not the first processor */ )
predecessor = procno-1;
else
predecessor = MPI_PROC_NULL;
if ( /* I am not the last processor */ )
successor = procno+1;
else
successor = MPI_PROC_NULL;
sendrecv(from=predecessor,to=successor);
Remark 11 The MPI_Sendrecv can inter-operate with the normal send and receive calls, both blocking and
non-blocking. Thus it would also be possible to replace the MPI_Sendrecv calls at the end points by simple sends
or receives.
MPL note 28: Send-recv call. The send-recv call in MPL has the same possibilities for specifying the send
and receive buffer as the separate send and recv calls: scalar, layout, iterator. However, out of the
nine conceivably possible routine signatures, only the versions are available where the send and
receive buffer are specified the same way. Also, the send and receive tag need to be specified;
they do not have default values.
// sendrecv.cxx
mpl::tag t0(0);
comm_world.sendrecv
( mydata,sendto,t0,
leftdata,recvfrom,t0 );
Exercise 4.8. Implement the above three-point combination scheme using MPI_Sendrecv;
every processor only has a single number to send to its neighbor.
(There is a skeleton for this exercise under the name sendrecv.)
Hints for this exercise:
• Each process does one send and one receive; if a process needs to skip one or the other, you can
specify MPI_PROC_NULL as the other process in the send or receive specification. In that case the
corresponding action is not taken.
• As with the simple send/recv calls, processes have to match up: if process 𝑝 specifies 𝑝 ′ as the
destination of the send part of the call, 𝑝 ′ needs to specify 𝑝 as the source of the recv part.
The following exercise lets you implement a sorting algorithm with the send-receive call1 .
Exercise 4.9. A very simple sorting algorithm is swap sort or odd-even transposition sort:
pairs of processors compare data, and if necessary exchange. The elementary step is
called a compare-and-swap: in a pair of processors each sends their data to the other;
one keeps the minimum values, and the other the maximum. For simplicity, in this
exercise we give each processor just a single number.
The transposition sort algorithm is split in even and odd stages, where in the even
stage processors 2𝑖 and 2𝑖 + 1 compare and swap data, and in the odd stage
processors 2𝑖 + 1 and 2𝑖 + 2 compare and swap. You need to repeat this 𝑃/2 times,
where 𝑃 is the number of processors; see figure 4.7.
Implement this algorithm using MPI_Sendrecv. (Use MPI_PROC_NULL for the edge cases
if needed.) Use a gather call to print the global state of the distributed array at the
beginning and end of the sorting process.
Remark 12 It is not possible to use MPI_IN_PLACE for the buffers, as in section 3.3.2. Instead, the routine
MPI_Sendrecv_replace (figure 4.4) has only one buffer, used as both send and receive buffer. Of course, this
requires the send and receive messages to fit in that one buffer.
Exercise 4.10. Extend this exercise to the case where each process hold an equal number of
elements, more than 1. Consider figure 4.8 for inspiration. Is it coincidence that the
algorithm takes the same number of steps as in the single scalar case?
The following material is for the recently released MPI-4 standard and may not be supported yet.
𝑦𝑖 = 𝑥𝑖−1 + 𝑥𝑖 + 𝑥𝑖+1 ∶ 𝑖 = 1, … , 𝑁 − 1
are organized in a general graph pattern. Here, the numbers of sends and receive of a processor do not
need to match.
In such cases, one wants a possibility to state ‘these are the expected incoming messages’, without having
to wait for them in sequence. Likewise, one wants to declare the outgoing messages without having to do
them in any particular sequence. Imposing any sequence on the sends and receives is likely to run into
the serialization behavior observed above, or at least be inefficient.
By contrast, the nonblocking calls MPI_Isend (figure 4.5) and MPI_Irecv (figure 4.6) (where the ‘I’ stands
for ‘immediate’ or ‘incomplete’ ) do not wait for their counterpart: in effect they tell the runtime system
‘here is some data and please send it as follows’ or ‘here is some buffer space, and expect such-and-such
data to come’. This is illustrated in figure 4.10.
// isendandirecv.c
template<typename T >
irequest mpl::communicator::isend
( const T & data, int dest, tag t = tag(0) ) const;
( const T * data, const layout< T > & l, int dest, tag t = tag(0) ) const;
( iterT begin, iterT end, int dest, tag t = tag(0) ) const;
Python:
double recv_data;
MPI_Request request;
MPI_Irecv
( /* recv buffer/count/type: */ &recv_data,1,MPI_DOUBLE,
/* from: */ sender, /* tag: */ 0,
/* communicator: */ comm,
/* request: */ &request);
MPI_Wait(&request,MPI_STATUS_IGNORE);
template<typename T >
irequest mpl::communicator::irecv
( const T & data, int src, tag t = tag(0) ) const;
( const T * data, const layout< T > & l, int src, tag t = tag(0) ) const;
( iterT begin, iterT end, int src, tag t = tag(0) ) const;
Python:
} else {
double recv=0.;
MPI_Request request;
MPI_Irecv( &recv,1,MPI_DOUBLE,sender,0,comm,&request);
do_some_work();
MPI_Wait(&request,MPI_STATUS_IGNORE);
}
(Note that this example uses a mix of blocking and non-blocking operations: a blocking send is paired
with a non-blocking receive.)
The request is passed by reference, so that the wait routine can free it:
• The wait call deallocates the request object, and
• sets the value of the variable to MPI_REQUEST_NULL.
(See section 4.2.4 for details.)
MPL note 29: Requests from nonblocking calls. Nonblocking routines have an irequest as function result.
Note: not a parameter passed by reference, as in the C interface. The various wait calls are
methods of the irequest class.
double recv_data;
mpl::irequest recv_request =
comm_world.irecv( recv_data,sender );
recv_request.wait();
This means that the normal sequence of first declaring, and then filling in, the request variable
is not possible.
MPL implementation note: The wait call always returns a status object; not assigning
it means that the destructor is called on it.
Now we discuss in some detail the various wait calls. These are blocking; for the nonblocking versions
see section 4.2.3.
However, this would be inefficient if the first request is fulfilled much later than the others: your waiting
process would have lots of idle time. In that case, use one of the following routines.
The output argument is an array or MPI_Status object. If you don’t need the status objects, you can pass
MPI_STATUSES_IGNORE.
As an illustration, we realize exercise 4.4, and its trace in figure 4.4, with non-blocking execution and
MPI_Waitall. Figure 4.11 shows the trace of this variant of the code.
Python note 15: Request arrays. An array of requests (for the waitall/some/any calls) is an ordinary Python
MPI.Request.Waitany( requests,status=None )
class method, returns index
list:
## irecvloop.py
requests = []
sendbuffer = np.empty( nprocs, dtype=int )
recvbuffer = np.empty( nprocs, dtype=int )
for p in range(nprocs):
left_p = (p-1) % nprocs
right_p = (p+1) % nprocs
requests.append( comm.Isend\
( sendbuffer[p:p+1],dest=left_p) )
requests.append( comm.Irecv\
( sendbuffer[p:p+1],source=right_p) )
MPI.Request.Waitall(requests)
Note that this routine takes a single status argument, passed by reference, and not an array of statuses!
Fortran note 7: Index of requests. The index parameter is the index in the array of requests, which is a
Fortran array, so it uses 1-based indexing.
!! irecvsource.F90
if (mytid==ntids-1) then
do p=1,ntids-1
print *,"post"
call MPI_Irecv(recv_buffer(p),1,MPI_INTEGER,p-1,0,comm,&
requests(p),err)
end do
do p=1,ntids-1
call MPI_Waitany(ntids-1,requests,index,MPI_STATUS_IGNORE,err)
write(*,'("Message from",i3,":",i5)') index,recv_buffer(index)
end do
!! waitnull.F90
Type(MPI_Request),dimension(:),allocatable :: requests
allocate(requests(ntids-1))
call MPI_Waitany(ntids-1,requests,index,MPI_STATUS_IGNORE)
if ( .not. requests(index)==MPI_REQUEST_NULL) then
print *,"This request should be null:",index
!! waitnull.F90
Type(MPI_Request),dimension(:),allocatable :: requests
allocate(requests(ntids-1))
call MPI_Waitany(ntids-1,requests,index,MPI_STATUS_IGNORE)
if ( .not. requests(index)==MPI_REQUEST_NULL) then
print *,"This request should be null:",index
MPL note 30: Request pools. Instead of an array of requests, use an irequest_pool object, which acts like a
vector of requests, meaning that you can push onto it.
// irecvsource.cxx
mpl::irequest_pool recv_requests;
for (int p=0; p<nprocs-1; p++) {
recv_requests.push( comm_world.irecv( recv_buffer[p], p ) );
}
You can not declare a pool of a fixed size and assign elements.
MPL note 31: Wait any. The irequest_pool class has methods waitany, waitall, testany, testall, waitsome,
testsome.
## irecvsource.py
if procid==nprocs-1:
receive_buffer = np.empty(nprocs-1,dtype=int)
requests = [ None ] * (nprocs-1)
for sender in range(nprocs-1):
requests[sender] = comm.Irecv(receive_buffer[sender:sender+1],source=sender)
# alternatively: requests = [ comm.Irecv(s) for s in .... ]
status = MPI.Status()
for sender in range(nprocs-1):
ind = MPI.Request.Waitany(requests,status=status)
if ind!=status.Get_source():
print("sender mismatch: %d vs %d" % (ind,status.Get_source()))
print("received from",ind)
else:
mywait = random.randint(1,2*nprocs)
print("[%d] wait for %d seconds" % (procid,mywait))
time.sleep(mywait)
mydata = np.empty(1,dtype=int)
mydata[0] = procid
comm.Send([mydata,MPI.INT],dest=nprocs-1)
Each process except for the root does a blocking send; the root posts MPI_Irecv from all other processors,
then loops with MPI_Waitany until all requests have come in. Use MPI_SOURCE to test the index parameter of
the wait call.
Note the MPI_STATUS_IGNORE parameter: we know everything about the incoming message, so we do not
need to query a status object. Contrast this with the example in section 4.3.1.
Remark 13 The routines that can return multiple statuses, can return the error condition MPI_ERR_IN_STATUS,
indicating that one of the statuses was in error. See section 4.3.3.
Exercise 4.13.
(There is a skeleton for this exercise under the name isendirecv.) Now use
nonblocking send/receive routines to implement the three-point averaging operation
𝑦𝑖 = (𝑥𝑖−1 + 𝑥𝑖 + 𝑥𝑖+1 )/3 ∶ 𝑖 = 1, … , 𝑁 − 1
on a distributed array. There are two approaches to the first and last process:
1. you can use MPI_PROC_NULL for the ‘missing’ communications;
2. you can skip these communications altogether, but now you have to count the
requests carefully.
This is known as overlapping computation and communication, or latency hiding. See also asynchronous
progress; section 15.4.
Unfortunately, a lot of this communication involves activity in user space, so the solution would have
been to let it be handled by a separate thread. Until recently, processors were not efficient at doing such
multi-threading, so true overlap stayed a promise for the future. Some network cards have support for
this overlap, but it requires a nontrivial combination of hardware, firmware, and MPI implementation.
Exercise 4.14.
(There is a skeleton for this exercise under the name isendirecvarray.) Take your
code of exercise 4.13 and modify it to use latency hiding. Operations that can be
performed without needing data from neighbors should be performed in between
the MPI_Isend / MPI_Irecv calls and the corresponding MPI_Wait calls.
Remark 14 You have now seen various send types: blocking, nonblocking, synchronous. Can a receiver see
what kind of message was sent? Are different receive routines needed? The answer is that, on the receiving
end, there is nothing to distinguish a nonblocking or synchronous message. The MPI_Recv call can match any
of the send routines you have seen so far, and conversely a message sent with MPI_Send can be received by
MPI_Irecv.
• On the other hand, when a nonblocking send call returns, the actual send may not have been
executed, so the send buffer may not be safe to overwrite. Similarly, when the recv call returns,
you do not know for sure that the expected data is in it. Only after the corresponding wait call
are you use that the buffer has been sent, or has received its contents.
• To send multiple messages with nonblocking calls you therefore have to allocate multiple
buffers.
double **buffers;
for ( ... p ... ) {
buffers[p] = // fill in the data
MPI_Send( buffers[p], ... /* to: */ p );
}
MPI_Wait( /* the requests */ );
// irecvloop.c
MPI_Request requests =
(MPI_Request*) malloc( 2*nprocs*sizeof(MPI_Request) );
recv_buffers = (int*) malloc( nprocs*sizeof(int) );
send_buffers = (int*) malloc( nprocs*sizeof(int) );
for (int p=0; p<nprocs; p++) {
int
left_p = (p-1+nprocs) % nprocs,
right_p = (p+1) % nprocs;
send_buffer[p] = nprocs-p;
MPI_Isend(sendbuffer+p,1,MPI_INT, right_p,0, requests+2*p);
MPI_Irecv(recvbuffer+p,1,MPI_INT, left_p,0, requests+2*p+1);
}
/* your useful code here */
MPI_Waitall(2*nprocs,requests,MPI_STATUSES_IGNORE);
If the test is true, the request is deallocated and set to MPI_REQUEST_NULL, or, in the case of an active persistent
request (section 5.1), set to inactive.
Analogous to MPI_Wait, MPI_Waitany, MPI_Waitall, MPI_Waitsome, there are MPI_Test (figure 4.10),
MPI_Testany, MPI_Testall, MPI_Testsome.
Exercise 4.15. Read section HPC book, section-6.5 and give pseudo-code for the distributed
sparse matrix-vector product using the above idiom for using MPI_Test... calls.
Discuss the advantages and disadvantages of this approach. The answer is not going
to be black and white: discuss when you expect which approach to be preferable.
reqest.Test()
Correspondingly, calls to MPI_Wait or MPI_Test free this object, setting the handle to MPI_REQUEST_NULL.
(There is an exception for persistent communications where the request is only set to ‘inactive’; sec-
tion 5.1.) Thus, it is wise to issue wait calls even if you know that the operation has succeeded. For in-
stance, if all receive calls are concluded, you know that the corresponding send calls are finished and there
is no strict need to wait for their requests. However, omitting the wait calls would lead to a memory leak.
Another way around this is to call MPI_Request_free (figure 4.11), which sets the request variable to
MPI_REQUEST_NULL, and marks the object for deallocation after completion of the operation. Conceivably,
one could issue a nonblocking call, and immediately call MPI_Request_free, dispensing with any wait call.
However, this makes it hard to know when the operation is concluded and when the buffer is safe to
reuse [25].
You can inspect the status of a request without freeing the request object with MPI_Request_get_status
(figure 4.12).
• If you are expecting multiple incoming messages, it may be most efficient to deal with them in
the order in which they arrive. So, instead of waiting for a specific message, you would specify
MPI_ANY_SOURCE or MPI_ANY_TAG in the description of the receive message. Now you have to be
able to ask ‘who did this message come from, and what is in it’.
• Maybe you know the sender of a message, but the amount of data is unknown. In that case you
can overallocate your receive buffer, and after the message is received ask how big it was, or
you can ‘probe’ an incoming message and allocate enough data when you find out how much
data is being sent.
To do this, the receive call has a MPI_Status parameter. The MPI_Status object is a structure (in C a struct,
in F90 an array, in F2008 a derived type) with freely accessible members:
• MPI_SOURCE gives the source of the message; see section 4.3.1.
• MPI_TAG gives the tag with which the message was received; see section 4.3.2.
• MPI_ERROR gives the error status of the receive call; see section 4.3.3.
• The number of items in the message can be deduced from the status object, not as a structure
member, but through a function call to MPI_Get_count; see section 4.3.4.
Fortran note 8: Status object in f08. The mpi_f08 module turns many handles (such as communicators)
from Fortran Integers into Types. Retrieving the integer from the type is usually done through
the %val member, but for the status object this is more difficult. The routines MPI_Status_f2f08
and MPI_Status_f082f convert between these. (Remarkably, these routines are even available
in C, where they operate on MPI_Fint, MPI_F08_status arguments.)
Python note 16: Status object. The status object is explicitly created before being passed to the receive
routine. It has the usual query method for the message count:
## pingpongbig.py
status = MPI.Status()
comm.Recv( rdata,source=0,status=status)
count = status.Get_count(MPI.DOUBLE)
status.Get_tag()
status.Get_elements()
status.Get_error()
status.Is_cancelled()
Should you need them, there are even Set variants of these. https://mpi4py.readthedocs.
io/en/stable/reference/mpi4py.MPI.Status.html
MPL note 33: Status object. The mpl::status_t object is created by the receive (or wait) call:
mpl::contiguous_layout<double> target_layout(count);
mpl::status_t recv_status =
comm_world.recv(target.data(),target_layout, the_other);
recv_count = recv_status.get_count<double>();
4.3.1 Source
In some applications it makes sense that a message can come from one of a number of processes. In
this case, it is possible to specify MPI_ANY_SOURCE as the source. To find out the source where the message
actually came from, you would use the MPI_SOURCE field of the status object that is delivered by MPI_Recv
or the MPI_Wait... call after an MPI_Irecv.
MPI_Recv(recv_buffer+p,1,MPI_INT, MPI_ANY_SOURCE,0,comm,
&status);
sender = status.MPI_SOURCE;
There are various scenarios where receiving from ‘any source’ makes sense. One is that of the manager-
worker model. The manager task would first send data to the worker tasks, then issues a blocking wait
for the data of whichever process finishes first.
In Fortran2008 style, the source is a member of the Status type.
!! anysource.F90
Type(MPI_Status) :: status
allocate(recv_buffer(ntids-1))
do p=0,ntids-2
call MPI_Recv(recv_buffer(p+1),1,MPI_INTEGER,&
MPI_ANY_SOURCE,0,comm,status)
sender = status%MPI_SOURCE
MPL note 34: Status source querying. The status object can be queried:
int source = recv_status.source();
4.3.2 Tag
In some circumstances, a tag wildcard can be used on the receive operation: MPI_ANY_TAG. The actual tag
of a message can be retrieved as the MPI_TAG member in the status structure.
There are not many cases where this is needed.
• Messages from a single source, even non-blocking, are non-overtaking. This means that mes-
sages can be distinguished by their order.
• Messages from multiple sources can be distinguished by the source field.
• Retrieving the message tag might be needed if information is encoded in it.
• The non-overtaking argument does not apply in the case of hybrid computing: two threads may
send messages that do not have an MPI-imposed order. See the example in section 45.1.
MPL note 35: Tag types. Tag are int or an enum typ:
template<typename T >
tag_t (T t);
tag_t (int t);
Example:
// inttag.cxx
enum class tag : int { ping=1, pong=2 };
int pinger = 0, ponger = world.size()-1;
if (world.rank()==pinger) {
world.send(x, 1, tag::ping);
world.recv(x, 1, tag::pong);
} else if (world.rank()==ponger) {
world.recv(x, 0, tag::ping);
world.send(x, 0, tag::pong);
}
MPL note 36: Message tag. MPL differs from other APIs in its treatment of tags: a tag is not directly an
integer, but an object of class tag.
// sendrecv.cxx
mpl::tag t0(0);
comm_world.sendrecv
( mydata,sendto,t0,
leftdata,recvfrom,t0 );
The tag class has a couple of methods such as mpl::tag::any() (for the MPI_ANY_TAG wildcard in
receive calls) and mpl::tag::up() (maximal tag, found from the MPI_TAG_UB attribute).
4.3.3 Error
For functions that return a single status, any error is returned as the function result. For a function re-
turning multiple statuses, such as MPI_Waitall, the presence of an error in one of the receives is indicated
by a result of MPI_ERR_IN_STATUS. Any errors during the receive operation can be found as the MPI_ERROR
member of the status structure.
template<typename T>
int mpl::status::get_count () const
template<typename T>
int mpl::status::get_count (const layout<T> &l) const
Python:
4.3.4 Count
If the amount of data received is not known a priori, the count of elements received can be found by
MPI_Get_count (figure 4.13):
// count.c
if (procid==0) {
int sendcount = (rand()>.5) ? N : N-1;
MPI_Send( buffer,sendcount,MPI_FLOAT,target,0,comm );
} else if (procid==target) {
MPI_Status status;
int recvcount;
MPI_Recv( buffer,N,MPI_FLOAT,0,0, comm, &status );
MPI_Get_count(&status,MPI_FLOAT,&recvcount);
printf("Received %d elements\n",recvcount);
}
Code: Output:
!! count.F90 make[3]: `count' is up to
if (procid==0) then ↪date.
sendcount = N TACC: Starting up job
call random_number(fraction) ↪4051425
if (fraction>.5) then TACC: Setting up parallel
print *,"One less" ; sendcount = N-1 ↪environment for
end if ↪MVAPICH2+mpispawn.
call MPI_Send( TACC: Starting parallel
↪buffer,sendcount,MPI_REAL,target,0,comm ) ↪tasks...
else if (procid==target) then One less
call MPI_Recv( buffer,N,MPI_REAL,0,0, comm, status ) Received 9
call MPI_Get_count(status,MPI_FLOAT,recvcount) ↪elements
print *,"Received",recvcount,"elements" TACC: Shutdown complete.
end if ↪Exiting.
This may be necessary since the count argument to MPI_Recv is the buffer size, not an indication of the
actually received number of data items.
Remarks.
• Unlike the source and tag, the message count is not directly a member of the status structure.
• The ‘count’ returned is the number of elements of the specified datatype. If this is a derived
type (section 6.3) this is not the same as the number of predefined datatype elements. For that,
use MPI_Get_elements (figure 4.14) or MPI_Get_elements_x which returns the number of basic el-
ements.
MPL note 37: Receive count. The get_count function is a method of the status object. The argument type
is handled through templating:
// recvstatus.cxx
double pi=0;
auto s = comm_world.recv(pi, 0); // receive from rank 0
int c = s.get_count<double>();
std::cout << "got : " << c << " scalar(s): " << pi << '\n';
but this may incur idle time if the messages arrive out of order.
Instead, we use the MPI_ANY_SOURCE specifier to give a wildcard behavior to the receive call: using this
value for the ‘source’ value means that we accept mesages from any source within the communicator,
and messages are only matched by tag value. (Note that size and type of the receive buffer are not used
for message matching!)
We then retrieve the actual source from the MPI_Status object through the MPI_SOURCE field.
// anysource.c
if (procno==nprocs-1) {
/*
* The last process receives from every other process
*/
int *recv_buffer;
recv_buffer = (int*) malloc((nprocs-1)*sizeof(int));
/*
* Messages can come in in any order, so use MPI_ANY_SOURCE
*/
MPI_Status status;
for (int p=0; p<nprocs-1; p++) {
err = MPI_Recv(recv_buffer+p,1,MPI_INT, MPI_ANY_SOURCE,0,comm,
&status); CHK(err);
int sender = status.MPI_SOURCE;
printf("Message from sender=%d: %d\n",
sender,recv_buffer[p]);
}
free(recv_buffer);
} else {
/*
* Each rank waits an unpredictable amount of time,
* then sends to the last process in line.
*/
float randomfraction = (rand() / (double)RAND_MAX);
int randomwait = (int) ( nprocs * randomfraction );
printf("process %d waits for %e/%d=%d\n",
procno,randomfraction,nprocs,randomwait);
sleep(randomwait);
err = MPI_Send(&randomwait,1,MPI_INT, nprocs-1,0,comm); CHK(err);
}
## anysource.py
rstatus = MPI.Status()
comm.Recv(rbuf,source=MPI.ANY_SOURCE,status=rstatus)
print("Message came from %d" % rstatus.Get_source())
The manager-worker model is a design patterns that offers an opportunity for inspecting the MPI_SOURCE
field of the MPI_Status object describing the data that was received. All workers processes model their
work by waitin a random amount of time, and the manager process accepts messages from any source.
// anysource.c
if (procno==nprocs-1) {
/*
* The last process receives from every other process
*/
int *recv_buffer;
recv_buffer = (int*) malloc((nprocs-1)*sizeof(int));
/*
* Messages can come in in any order, so use MPI_ANY_SOURCE
*/
MPI_Status status;
for (int p=0; p<nprocs-1; p++) {
err = MPI_Recv(recv_buffer+p,1,MPI_INT, MPI_ANY_SOURCE,0,comm,
&status); CHK(err);
int sender = status.MPI_SOURCE;
printf("Message from sender=%d: %d\n",
sender,recv_buffer[p]);
}
free(recv_buffer);
} else {
/*
* Each rank waits an unpredictable amount of time,
* then sends to the last process in line.
*/
float randomfraction = (rand() / (double)RAND_MAX);
int randomwait = (int) ( nprocs * randomfraction );
printf("process %d waits for %e/%d=%d\n",
procno,randomfraction,nprocs,randomwait);
sleep(randomwait);
err = MPI_Send(&randomwait,1,MPI_INT, nprocs-1,0,comm); CHK(err);
}
// probe.c
if (procno==receiver) {
MPI_Status status;
MPI_Probe(sender,0,comm,&status);
int count;
MPI_Get_count(&status,MPI_FLOAT,&count);
float recv_buffer[count];
MPI_Recv(recv_buffer,count,MPI_FLOAT, sender,0,comm,MPI_STATUS_IGNORE);
} else if (procno==sender) {
float buffer[buffer_size];
ierr = MPI_Send(buffer,buffer_size,MPI_FLOAT, receiver,0,comm); CHK(ierr);
}
There is a problem with the MPI_Probe call in a multithreaded environment: the following scenario can
happen.
1. A thread determines by probing that a certain message has come in.
2. It issues a blocking receive call for that message…
3. But in between the probe and the receive call another thread has already received the message.
4. … Leaving the first thread in a blocked state with no message to receive.
This is solved by MPI_Mprobe (figure 4.17), which after a successful probe removes the message from the
matching queue: the list of messages that can be matched by a receive call. The thread that matched the
probe now issues an MPI_Mrecv (figure 4.18) call on that message through an object of type MPI_Message.
4.4.2 Errors
MPI routines return MPI_SUCCESS upon succesful completion. The following error codes can be returned
(see section 15.2.1 for details) for completion with error by both send and receive operations: MPI_ERR_COMM,
MPI_ERR_COUNT, MPI_ERR_TYPE, MPI_ERR_TAG, MPI_ERR_RANK.
Apart from its bare data, each message has a message envelope. This has enough information to distinguish
messages from each other: the source, destination, tag, communicator.
˜
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Recv(rbuffer,buflen,MPI_INT,p,0,comm,MPI_STATUS_IGNORE);
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm);
int ireq = 0;
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Isend(sbuffers[p],buflen,MPI_INT,p,0,comm,&(requests[ireq++]));
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Recv(rbuffer,buflen,MPI_INT,p,0,comm,MPI_STATUS_IGNORE);
MPI_Waitall(nprocs-1,requests,MPI_STATUSES_IGNORE);
int ireq = 0;
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Irecv(rbuffers[p],buflen,MPI_INT,p,0,comm,&(requests[ireq++]));
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm);
MPI_Waitall(nprocs-1,requests,MPI_STATUSES_IGNORE);
int ireq = 0;
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Irecv(rbuffers[p],buflen,MPI_INT,p,0,comm,&(requests[ireq++]));
MPI_Waitall(nprocs-1,requests,MPI_STATUSES_IGNORE);
for (int p=0; p<nprocs; p++)
if (p!=procid)
MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm);
Fortran codes:
do p=0,nprocs-1
if (p/=procid) then
call MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm,ierr)
end if
end do
do p=0,nprocs-1
if (p/=procid) then
call MPI_Recv(rbuffer,buflen,MPI_INT,p,0,comm,MPI_STATUS_IGNORE,ierr)
end if
end do
do p=0,nprocs-1
if (p/=procid) then
call MPI_Recv(rbuffer,buflen,MPI_INT,p,0,comm,MPI_STATUS_IGNORE,ierr)
end if
end do
do p=0,nprocs-1
if (p/=procid) then
call MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm,ierr)
end if
end do
ireq = 0
do p=0,nprocs-1
if (p/=procid) then
call MPI_Isend(sbuffers(1,p+1),buflen,MPI_INT,p,0,comm,&
requests(ireq+1),ierr)
ireq = ireq+1
end if
end do
do p=0,nprocs-1
if (p/=procid) then
call MPI_Recv(rbuffer,buflen,MPI_INT,p,0,comm,MPI_STATUS_IGNORE,ierr)
end if
end do
call MPI_Waitall(nprocs-1,requests,MPI_STATUSES_IGNORE,ierr)
ireq = 0
do p=0,nprocs-1
if (p/=procid) then
call MPI_Irecv(rbuffers(1,p+1),buflen,MPI_INT,p,0,comm,&
requests(ireq+1),ierr)
ireq = ireq+1
end if
end do
do p=0,nprocs-1
if (p/=procid) then
call MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm,ierr)
end if
end do
call MPI_Waitall(nprocs-1,requests,MPI_STATUSES_IGNORE,ierr)
// block5.F90
ireq = 0
do p=0,nprocs-1
if (p/=procid) then
call MPI_Irecv(rbuffers(1,p+1),buflen,MPI_INT,p,0,comm,&
requests(ireq+1),ierr)
ireq = ireq+1
end if
end do
call MPI_Waitall(nprocs-1,requests,MPI_STATUSES_IGNORE,ierr)
do p=0,nprocs-1
if (p/=procid) then
call MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm,ierr)
end if
end do
// ring3.c // ring4.c
MPI_Request req1,req2; MPI_Request req1,req2;
MPI_Irecv(&y,1,MPI_DOUBLE,prev,0,comm,&req1); MPI_Irecv(&y,1,MPI_DOUBLE,prev,0,comm,&req1);
MPI_Isend(&x,1,MPI_DOUBLE,next,0,comm,&req2); MPI_Isend(&x,1,MPI_DOUBLE,next,0,comm,&req2);
MPI_Wait(&req1,MPI_STATUS_IGNORE); MPI_Wait(&req2,MPI_STATUS_IGNORE);
MPI_Wait(&req2,MPI_STATUS_IGNORE); MPI_Wait(&req1,MPI_STATUS_IGNORE);
Can we have one nonblocking and one blocking call? Do these scenarios block?
// ring1.c // ring2.c
MPI_Request req; MPI_Request req;
MPI_Issend(&x,1,MPI_DOUBLE,next,0,comm,&req); MPI_Irecv(&y,1,MPI_DOUBLE,prev,0,comm,&req);
MPI_Recv(&y,1,MPI_DOUBLE,prev,0,comm, MPI_Ssend(&x,1,MPI_DOUBLE,next,0,comm);
MPI_STATUS_IGNORE); MPI_Wait(&req,MPI_STATUS_IGNORE);
MPI_Wait(&req,MPI_STATUS_IGNORE);
MPL note 38: Persistent requests. MPL returns a prequest from persistent ‘init’ routines, rather than an
irequest (MPL note 29):
template<typename T >
prequest send_init (const T &data, int dest, tag t=tag(0)) const;
141
5. MPI topic: Communication modes
The main persistent point-to-point routines are MPI_Send_init (figure 5.1), which has the same calling
sequence as MPI_Isend, and MPI_Recv_init, which has the same calling sequence as MPI_Irecv.
In the following example a ping-pong is implemented with persistent communication. Since we use per-
sistent operations for both send and receive on the ‘ping’ process, we use MPI_Startall (figure 5.2) to start
both at the same time, and MPI_Waitall to test their completion. (There is MPI_Start for starting a single
persistent transfer.)
Code: Output:
// persist.c make[3]: `persist' is up to date.
if (procno==src) { TACC: Starting up job 4328411
/* TACC: Starting parallel tasks...
* Send ping, receive pong Pingpong size=1: t=1.2123e-04
*/ Pingpong size=10: t=4.2826e-06
MPI_Send_init Pingpong size=100: t=7.1507e-06
(send,s,MPI_DOUBLE,tgt,0,comm, Pingpong size=1000: t=1.2084e-05
requests+0); Pingpong size=10000: t=3.7668e-05
MPI_Recv_init Pingpong size=100000: t=3.4415e-04
(recv,s,MPI_DOUBLE,tgt,0,comm, Persistent size=1: t=3.8177e-06
requests+1); Persistent size=10: t=3.2410e-06
for (int n=0; n<NEXPERIMENTS; n++) { Persistent size=100: t=4.0468e-06
fill_buffer(send,s,n); Persistent size=1000: t=1.1525e-05
MPI_Startall(2,requests); Persistent size=10000: t=4.1672e-05
MPI_Waitall(2,requests, Persistent size=100000: t=2.8648e-04
MPI_STATUSES_IGNORE); TACC: Shutdown complete. Exiting.
int r = chck_buffer(send,s,n);
if (!r) printf("buffer problem %d\n",s);
}
} else if (procno==tgt) {
/*
* Receive ping, send pong
*/
MPI_Send_init
(recv,s,MPI_DOUBLE,src,0,comm,
requests+0);
MPI_Recv_init
(recv,s,MPI_DOUBLE,src,0,comm,
requests+1);
for (int n=0; n<NEXPERIMENTS; n++) {
// receive
MPI_Start(requests+1);
↪MPI_Wait(requests+1,MPI_STATUS_IGNORE);
// send
MPI_Start(requests+0);
↪MPI_Wait(requests+0,MPI_STATUS_IGNORE);
}
}
MPI_Request_free(requests+0);
MPI_Request_free(requests+1);
(Ask yourself: why does the sender use MPI_Startall and MPI_Waitall, but the receiver uses MPI_Start and
MPI_Wait twice?)
## persist.py
requests = [ None ] * 2
sendbuf = np.ones(size,dtype=int)
recvbuf = np.ones(size,dtype=int)
if procid==src:
print("Size:",size)
times[isize] = MPI.Wtime()
for n in range(nexperiments):
requests[0] = comm.Isend(sendbuf[0:size],dest=tgt)
requests[1] = comm.Irecv(recvbuf[0:size],source=tgt)
MPI.Request.Waitall(requests)
sendbuf[0] = sendbuf[0]+1
times[isize] = MPI.Wtime()-times[isize]
elif procid==tgt:
for n in range(nexperiments):
comm.Recv(recvbuf[0:size],source=src)
comm.Send(recvbuf[0:size],dest=src)
As with ordinary send commands, there are persistent variants of the other send modes:
• MPI_Bsend_init for buffered communication, section 5.5;
• MPI_Ssend_init for synchronous communication, section 5.3.1;
• MPI_Rsend_init for ready sends, section 15.8.
// powerpersist1.c
double localnorm,globalnorm=1.;
MPI_Request reduce_request;
MPI_Allreduce_init
( &localnorm,&globalnorm,1,MPI_DOUBLE,MPI_SUM,
comm,MPI_INFO_NULL,&reduce_request);
for (int it=0; ; it++) {
/*
* Matrix vector product
*/
matmult(indata,outdata,buffersize);
Some points.
• Metadata arrays, such as of counts and datatypes, must not be altered until the MPI_Request_free
call.
• The initialization call is nonlocal (for this particular case of persistent collectives), so it can block
until all processes have performed it.
• Multiple persistent collective can be initialized, in which case they satisfy the same restrictions
as ordinary collectives, in particular on ordering. Thus, the following code is incorrect:
// WRONG
if (procid==0) {
MPI_Reduce_init( /* ... */ &req1);
MPI_Bcast_init( /* ... */ &req2);
} else {
MPI_Bcast_init( /* ... */ &req2);
MPI_Reduce_init( /* ... */ &req1);
}
However, after initialization the start calls can be in arbitrary order, and in different order among
the processes.
Available persistent collectives are: MPI_Barrier_init MPI_Bcast_init MPI_Reduce_init MPI_Allreduce_init
MPI_Reduce_scatter_init MPI_Reduce_scatter_block_init MPI_Gather_init MPI_Gatherv_init
MPI_Allgather_init MPI_Allgatherv_init MPI_Scatter_init MPI_Scatterv_init MPI_Alltoall_init
MPI_Alltoallv_init MPI_Alltoallw_init MPI_Scan_init MPI_Exscan_init
End of MPI-4 material
The receiving side is largely the mirror image of the sending side:
double *recvbuffer = (double*)malloc(bufsize*sizeof(double));
MPI_Request recv_request;
MPI_Precv_init
(recvbuffer,nparts,SIZE,MPI_DOUBLE,src,0,
comm,MPI_INFO_NULL,&recv_request);
for (int it=0; it<ITERATIONS; it++) {
MPI_Start(&recv_request); int r=1,flag;
for (int ip=0; ip<nparts; ip++) // cycle this many times
for (int ap=0; ap<nparts; ap++) { // check specific part
MPI_Parrived(recv_request,ap,&flag);
if (flag) {
r *= chck_buffer
(recvbuffer,partitions[ap],partitions[ap+1],ap);
break; }
}
MPI_Wait(&recv_request,MPI_STATUS_IGNORE);
}
MPI_Request_free(&recv_request);
• a partitioned send can only be matched with a partitioned receive, so we start with an
MPI_Precv_init.
On the other hand, buffered communication (routines MPI_Bsend, MPI_Ibsend, MPI_Bsend_init; section 5.5) is
local: the presence of an explicit buffer means that a send operation can complete no matter whether the
receive has been posted.
The synchronous send (routines MPI_Ssend, MPI_Issend, MPI_Ssend_init; section 15.8) is again nonlocal (even
in the nonblocking variant) since it will only complete when the receive call has completed.
Finally, the ready mode send (MPI_Rsend, MPI_Irsend) is nonlocal in the sense that its only correct use is
when the corresponding receive has been issued.
// bufring.c
int bsize = BUFLEN*sizeof(float);
float
*sbuf = (float*) malloc( bsize ),
*rbuf = (float*) malloc( bsize );
MPI_Pack_size( BUFLEN,MPI_FLOAT,comm,&bsize);
bsize += MPI_BSEND_OVERHEAD;
float
*buffer = (float*) malloc( bsize );
MPI_Buffer_attach( buffer,bsize );
err = MPI_Bsend(sbuf,BUFLEN,MPI_FLOAT,next,0,comm);
MPI_Recv (rbuf,BUFLEN,MPI_FLOAT,prev,0,comm,MPI_STATUS_IGNORE);
MPI_Buffer_detach( &buffer,&bsize );
MPL note 39: Buffered send. Creating and attaching a buffer is done through bsend_buffer and a support
routine bsend_size helps in calculating the buffer size:
// bufring.cxx
vector<float> sbuf(BUFLEN), rbuf(BUFLEN);
int size{ comm_world.bsend_size<float>(mpl::contiguous_layout<float>(BUFLEN)) };
mpl::bsend_buffer buff(size);
comm_world.bsend(sbuf.data(),mpl::contiguous_layout<float>(BUFLEN), next);
In the examples you have seen so far, every time data was sent it was as a contiguous buffer with elements
of a single type. In practice you may want to send noncontiguous or heterogeneous data.
• As an example of noncontiguous data, communicating the real parts of an array of complex
numbers means specifying every other number.
• Heterogeneous data is needed when communicating a C structure or Fortran type with more
than one type of element.
The datatypes you have dealt with so far are known as predefined datatypes; the datatypes you create to
deal with other data are known as derived datatypes.
Fortran note 9: Derived types for handles. In Fortran before 2008, datatypes variables are stored in Integer
variables. With the Fortran2008 standard, datatypes are Fortran derived types:
!! vector.F90
Type(MPI_Datatype) :: newvectortype
Implementationwise speaking, these types have exactly one member, MPI_VAL, which is the same
integer as was used for that datatype in the earlier Fortran version.
Python note 17: Data types. There is a class
mpi4py.MPI.Datatype
154
6.2. Predefined data types
which are themselves objects with methods for creating derived types; see section 6.3.1.
MPL note 41: Datatype handling. MPL mostly handles datatypes through subclasses of the layout class.
Layouts are MPL routines are templated over the data type.
// sendlong.cxx
mpl::contiguous_layout<long long> v_layout(v.size());
comm.send(v.data(), v_layout, 1); // send to rank 1
6.2.1 C/C++
Here we illustrate for C/C++ the correspondence between a type used to declare a variable, and how this
type appears in MPI communication routines:
long int i;
MPI_Send(&i,1,MPI_LONG,target,tag,comm);
• There is support for C11 fixed width integer types; see table 6.3.
• The MPI_LONG_INT type is not an integer type, but rather a long and an int packed together; see
section 3.10.1.1.
• See section 6.2.4 for MPI_Aint and more about byte counting.
6.2.2 Fortran
Table 6.4 lists standard Fortran types and common extensions. Not all the types in the right table
need be supported; for instance MPI_INTEGER16 may not exist, in which case it will be equivalent to
MPI_DATATYPE_NULL.
uint8_t MPI_UINT8_T
uint16_t MPI_UINT16_T
uint32_t MPI_UINT32_T
uint64_t MPI_UINT64_T
MPI_INTEGER1
MPI_CHARACTER Character(Len=1) MPI_INTEGER2
MPI_INTEGER MPI_INTEGER4
MPI_REAL MPI_INTEGER8
MPI_DOUBLE_PRECISION MPI_INTEGER16
MPI_COMPLEX MPI_REAL2
MPI_LOGICAL MPI_REAL4
MPI_BYTE MPI_REAL8
MPI_PACKED MPI_DOUBLE_COMPLEX
Complex(Kind=Kind(0.d0))
Table 6.4: Standard Fortran types (left) and common extension (right)
Code: Output:
!! kindsend.F90 Fortran type has range
Integer,parameter :: digits=16 ↪ 18
Integer,parameter :: ip = Selected_Int_Kind(digits) Sending: 729000000000000
Integer (kind=ip) :: data Received: 729000000000000
Type(MPI_Datatype) :: mpi_ip
Call MPI_Type_create_f90_integer(digits,mpi_ip)
if (rank==0) then
print *,"Fortran type has range",range(data)
call MPI_Send( data,1,mpi_ip, 1,0,comm )
else if (rank==1) then
call MPI_Recv( data,1,mpi_ip, 0,0,comm,
↪MPI_STATUS_IGNORE )
Remark 15 The MPI types thus created are predefined data types, so there is no need to commit or free them.
6.2.3 Python
Python note 18: Predefined data types. This section 6.2.3 discusses of predefined datatypes in Python.
In python, all buffer data comes from Numpy.
In this table we see that Numpy has three integer types, one corresponding to C ints, and two with the
number of bits explicitly indicated. There used to be a np.int type, but this is deprecated as of Numpy
1.20.
Examples:
Code: Output:
## inttype.py Size of numpy int32: 4
sizeofint = np.dtype('int32').itemsize Size of C int: 4
print("Size of numpy int32: {}".format(sizeofint))
sizeofint = np.dtype('intc').itemsize
print("Size of C int: {}".format(sizeofint))
## allgatherv.py
mycount = procid+1
my_array = np.empty(mycount,dtype=np.float64)
## typesize.py
datatype = MPI.FLOAT
typecode = MPI._typecode(datatype)
assert typecode is not None # check MPI datatype is built-in
dtype = np.dtype(typecode)
integer(kind=MPI_ADDRESS_KIND) :: winsize
Using this integer kind to compute the size of a window also requires being able to query the
size of the datatype in that window. See section 6.2.5 for details.
Example usage in MPI_Win_create:
call MPI_Sizeof(windowdata,window_element_size,ierr)
window_size = window_element_size*500
call MPI_Win_create( windowdata,window_size,window_element_size,... )
Python note 19: Size of numpy types. Here is a good way for finding the size of numpy datatypes in bytes:
## putfence.py
intsize = np.dtype('int').itemsize
window_data = np.zeros(2,dtype=int)
win = MPI.Win.Create(window_data,intsize,comm=comm)
In some circumstances you may want to find the MPI type that corresponds to a type in your programming
language.
• In C++ functions and classes can be templated, meaning that the type is not fully known:
template<typename T> {
class something<T> {
public:
void dosend(T input) {
MPI_Send( &input,1,/* ????? */ );
};
};
(Note that in MPL this is hardly ever needed because MPI calls are templated there.)
• Petsc installations use a generic identifier PetscScalar (or PetscReal) with a
configuration-dependent realization.
• The size of a datatype is not always statically known, for instance if the Fortran KIND keyword
is used.
Datatypes in C can be translated to MPI types with MPI_Type_match_size (figure 6.4) where the typeclass
argument is one of MPI_TYPECLASS_REAL, MPI_TYPECLASS_INTEGER, MPI_TYPECLASS_COMPLEX.
Code: Output:
// typematch.c mpiexec -n 1 ./typematch
float x5; float: size=4, mpi size=4
double x10; double: size=8, mpi size=8
int s5,s10;
MPI_Datatype mpi_x5,mpi_x10;
MPI_Type_match_size
(MPI_TYPECLASS_REAL,sizeof(x5),&mpi_x5);
MPI_Type_match_size
(MPI_TYPECLASS_REAL,sizeof(x10),&mpi_x10);
MPI_Type_size(mpi_x5,&s5);
printf("float: size=%d, mpi size=%d\n",
sizeof(x5),s5);
MPI_Type_size(mpi_x10,&s10);
printf("double: size=%d, mpi size=%d\n",
sizeof(x10),s10);
The space that MPI takes for a structure type can be queried in a variety of ways. First of all MPI_Type_size
(figure 6.5) counts the datatype size as the number of bytes occupied by the data in a type. That means
that in an MPI vector datatype it does not count the gaps.
// typesize.c
MPI_Type_vector(count,bs,stride,MPI_DOUBLE,&newtype);
MPI_Type_commit(&newtype);
MPI_Type_size(newtype,&size);
ASSERT( size==(count*bs)*sizeof(double) );
the nonoptional error parameter!). This routine is deprecated in MPI-4: use of storage_size (which
reports the number of bits) and/or c_sizeof (from the iso_c_binding module, which reports bytes) is
recommended.
!! matchkind.F90
call MPI_Sizeof(x10,s10,ierr)
call MPI_Type_match_size(MPI_TYPECLASS_REAL,s10,mpi_x10)
call MPI_Type_size(mpi_x10,s10)
print *,"10 positions supported, MPI type size is",s10
In Fortran2008:
Type(MPI_Datatype) :: newvectortype
call MPI_Type_something( <oldtype specification>, &
newvectortype)
call MPI_Type_commit(newvectortype)
!! code that uses your type
call MPI_Type_free(newvectortype)
Python note 20: Derived type handling. The various type creation routines are methods of the datatype
classes, after which commit and free are methods on the new type.
## vector.py
source = np.empty(stride*count,dtype=np.float64)
target = np.empty(count,dtype=np.float64)
if procid==sender:
newvectortype = MPI.DOUBLE.Create_vector(count,1,stride)
newvectortype.Commit()
comm.Send([source,1,newvectortype],dest=the_other)
newvectortype.Free()
elif procid==receiver:
comm.Recv([target,count,MPI.DOUBLE],source=the_other)
MPL note 43: Derived type handling. In MPL type creation routines are in the main namespace, templated
over the datatypes.
// vector.cxx
vector<double>
source(stride*count);
if (procno==sender) {
mpl::strided_vector_layout<double>
newvectortype(count,1,stride);
comm_world.send
(source.data(),newvectortype,the_other);
}
The commit call is part of the type creation, and freeing is done in the destructor.
MPL note 44: Layouts.
namespace mpl {
template <typename T> class layout; // Basisklasse
!! contiguous.F90
integer :: newvectortype
if (mytid==sender) then
call MPI_Type_contiguous(count,MPI_DOUBLE_PRECISION,newvectortype)
call MPI_Type_commit(newvectortype)
call MPI_Send(source,1,newvectortype,receiver,0,comm)
call MPI_Type_free(newvectortype)
else if (mytid==receiver) then
call MPI_Recv(target,count,MPI_DOUBLE_PRECISION,sender,0,comm,&
recv_status)
call MPI_Get_count(recv_status,MPI_DOUBLE_PRECISION,recv_count)
!ASSERT(count==recv_count);
end if
## contiguous.py
source = np.empty(count,dtype=np.float64)
target = np.empty(count,dtype=np.float64)
if procid==sender:
newcontiguoustype = MPI.DOUBLE.Create_contiguous(count)
newcontiguoustype.Commit()
comm.Send([source,1,newcontiguoustype],dest=the_other)
newcontiguoustype.Free()
elif procid==receiver:
comm.Recv([target,count,MPI.DOUBLE],source=the_other)
MPL note 45: Contiguous type. The MPL interface makes extensive use of contiguous_layout, as it is the
main way to declare a nonscalar buffer; see note 11.
MPL note 46: Contiguous composing. Contiguous layouts can only use predefined types or other contigu-
ous layouts as their ‘old’ type. To make a contiguous type for other layouts, use vector_layout:
// contiguous.cxx
mpl::contiguous_layout<int> type1(7);
mpl::vector_layout<int> type2(8,type1);
Figure 6.2: A vector datatype is built up out of strided blocks of elements of a constituent type
in figure 6.2.
The vector datatype gives the first nontrivial illustration that datatypes can be different on the sender and
receiver. If the sender sends b blocks of length l each, the receiver can receive them as bl contiguous
elements, either as a contiguous datatype, or as a contiguous buffer of an predefined type; see figure 6.3.
The receiver has no knowledge of the stride of the datatype on the sender.
In this example a vector type is created only on the sender, in order to send a strided subset of an array;
the receiver receives the data as a contiguous block.
// vector.c
source = (double*) malloc(stride*count*sizeof(double));
target = (double*) malloc(count*sizeof(double));
MPI_Datatype newvectortype;
if (procno==sender) {
MPI_Type_vector(count,1,stride,MPI_DOUBLE,&newvectortype);
MPI_Type_commit(&newvectortype);
MPI_Send(source,1,newvectortype,the_other,0,comm);
MPI_Type_free(&newvectortype);
} else if (procno==receiver) {
MPI_Status recv_status;
int recv_count;
MPI_Recv(target,count,MPI_DOUBLE,the_other,0,comm,
&recv_status);
MPI_Get_count(&recv_status,MPI_DOUBLE,&recv_count);
ASSERT(recv_count==count);
}
We illustrate Fortran2008:
if (mytid==sender) then
call MPI_Type_vector(count,1,stride,MPI_DOUBLE_PRECISION,&
newvectortype)
call MPI_Type_commit(newvectortype)
call MPI_Send(source,1,newvectortype,receiver,0,comm)
call MPI_Type_free(newvectortype)
if ( .not. newvectortype==MPI_DATATYPE_NULL) then
print *,"Trouble freeing datatype"
else
print *,"Datatype successfully freed"
end if
else if (mytid==receiver) then
call MPI_Recv(target,count,MPI_DOUBLE_PRECISION,sender,0,comm,&
recv_status)
call MPI_Get_count(recv_status,MPI_DOUBLE_PRECISION,recv_count)
end if
In legacy mode Fortran90, code stays the same except that the type is declared as Integer:
!! vector.F90
integer :: newvectortype
integer :: recv_count
call MPI_Type_vector(count,1,stride,MPI_DOUBLE_PRECISION,&
newvectortype,err)
call MPI_Type_commit(newvectortype,err)
Python note 21: Vector type. The vector creation routine is a method of the datatype class. For the general
discussion, see section 6.3.1.
## vector.py
source = np.empty(stride*count,dtype=np.float64)
target = np.empty(count,dtype=np.float64)
if procid==sender:
newvectortype = MPI.DOUBLE.Create_vector(count,1,stride)
newvectortype.Commit()
comm.Send([source,1,newvectortype],dest=the_other)
newvectortype.Free()
elif procid==receiver:
comm.Recv([target,count,MPI.DOUBLE],source=the_other)
MPL note 47: Vector type. MPL has the strided_vector_layout class as equivalent of the vector type:
// vector.cxx
vector<double>
source(stride*count);
if (procno==sender) {
mpl::strided_vector_layout<double>
newvectortype(count,1,stride);
comm_world.send
(source.data(),newvectortype,the_other);
}
then a column has 𝑀 blocks of one element, spaced 𝑁 locations apart. In other words:
Figure 6.4: Memory layout of a row and column of a matrix in column-major storage
MPI_Datatype MPI_column;
MPI_Type_vector(
/* count= */ M, /* blocklength= */ 1, /* stride= */ N,
MPI_DOUBLE, &MPI_column );
The second column is just a little trickier: you now need to pick out elements with the same stride, but
starting at A[0][1].
MPI_Send( &(mat[0][1]), 1,MPI_column, ... );
You can make this marginally more efficient (and harder to read) by replacing the index expression by
mat+1.
Exercise 6.2. Suppose you have a matrix of size 4𝑁 × 4𝑁 , and you want to send the
elements A[4*i][4*j] with 𝑖, 𝑗 = 0, … , 𝑁 − 1. How would you send these elements
with a single transfer?
Exercise 6.3. Allocate a matrix on processor zero, using Fortran column-major storage.
Using 𝑃 sendrecv calls, distribute the rows of this matrix among the processors.
Python note 22: Sending from the middle of a matrix. In C and Fortran it’s easy to apply a derived type to
data in the middle of an array, for instance to extract an arbitrary column out of a C matrix,
or row out of a Fortran matrix. While Python has no trouble describing sections from an array,
usually it copies these instead of taking the address. Therefore, it is necessary to convert the
matrix to a buffer and compute an explicit offset in bytes:
## rowcol.py
rowsize = 4; colsize = 5
Figure 6.5: Send strided data from process zero to all others
coltype = MPI.INT.Create_vector(4, 1, 5)
coltype.Commit()
columntosend = 2
comm.Send\
( [np.frombuffer(matrix.data, intc,
offset=columntosend*np.dtype('intc').itemsize),
1,coltype],
receiver)
Exercise 6.4. Let processor 0 have an array 𝑥 of length 10𝑃, where 𝑃 is the number of
processors. Elements 0, 𝑃, 2𝑃, … , 9𝑃 should go to processor zero, 1, 𝑃 + 1, 2𝑃 + 1, … to
processor 1, et cetera.
• Code this as a sequence of send/recv calls, using a vector datatype for the send,
and a contiguous buffer for the receive.
• For simplicity, skip the send to/from zero. What is the most elegant solution if
you want to include that case?
• For testing, define the array as 𝑥[𝑖] = 𝑖.
(There is a skeleton for this exercise under the name stridesend.)
Exercise 6.5. Write code to compare the time it takes to send a strided subset from an array:
copy the elements by hand to a smaller buffer, or use a vector data type. What do
you find? You may need to test on fairly large arrays.
MPI.Datatype.Create_subarray
(self, sizes, subsizes, starts, int order=ORDER_C)
Exercise 6.6. Assume that your number of processors is 𝑃 = 𝑄 3 , and that each process has
an array of identical size. Use MPI_Type_create_subarray to gather all data onto a root
process. Use a sequence of send and receive calls; MPI_Gather does not work here.
(There is a skeleton for this exercise under the name cubegather.)
Fortran note 11: Subarrays. Subarrays are naturally supported in Fortran through array sections.
!! section.F90
integer,parameter :: siz=20
real,dimension(siz,siz) :: matrix = [ ((j+(i-1)*siz,i=1,siz),j=1,siz) ]
real,dimension(2,2) :: submatrix
if (procno==0) then
call MPI_Send(matrix(1:2,1:2),4,MPI_REAL,1,0,comm)
else if (procno==1) then
call MPI_Recv(submatrix,4,MPI_REAL,0,0,comm,MPI_STATUS_IGNORE)
if (submatrix(2,2)==22) then
print *,"Yay"
else
print *,"nay...."
end if
end if
However, there is a subtlety with non-blocking operations: for a non-contiguous buffer a tem-
porary is created, which is released after the MPI call. This is correct for blocking sends, but for
non-blocking the temporary has to stay around till the wait call.
!! sectionisend.F90
integer :: siz
real,dimension(:,:),allocatable :: matrix
real,dimension(2,2) :: submatrix
siz = 20
allocate( matrix(siz,siz) )
matrix = reshape( [ ((j+(i-1)*siz,i=1,siz),j=1,siz) ], (/siz,siz/) )
call MPI_Isend(matrix(1:2,1:2),4,MPI_REAL,1,0,comm,request)
call MPI_Wait(request,MPI_STATUS_IGNORE)
deallocate(matrix)
The possibilities for the order parameter are MPI_ORDER_C and MPI_ORDER_FORTRAN. However, this has noth-
ing to do with the order of traversal of elements; it determines how the bounds of the subarray are inter-
preted. As an example, we fill a 4 × 4 array in C order with the numbers 0 ⋯ 15, and send the [0, 1] × [0 ⋯ 4]
slice two ways, first C order, then Fortran order:
// row2col.c
#define SIZE 4
int
sizes[2], subsizes[2], starts[2];
sizes[0] = SIZE; sizes[1] = SIZE;
subsizes[0] = SIZE/2; subsizes[1] = SIZE;
starts[0] = starts[1] = 0;
MPI_Type_create_subarray
(2,sizes,subsizes,starts,
MPI_ORDER_C,MPI_DOUBLE,&rowtype);
MPI_Type_create_subarray
(2,sizes,subsizes,starts,
MPI_ORDER_FORTRAN,MPI_DOUBLE,&coltype);
The receiver receives the following, formatted to bring out where the numbers originate:
Received C order:
0.000 1.000 2.000 3.000
4.000 5.000 6.000 7.000
Received F order:
0.000 1.000
4.000 5.000
8.000 9.000
12.000 13.000
MPI.Datatype.Create_indexed(self, blocklengths,displacements )
With the cyclic distribution, the amount of cyclicity can be indicated by setting dargs[id] to a certain
number.
With the block distribution, blocks can be set explicitly in dargs[id], but MPI_DISTRIBUTE_DFLT_DARG causes
an even distribution to be found.
Ordering can be MPI_ORDER_C or MPI_ORDER_FORTRAN.
MPI_Datatype newvectortype;
if (procno==sender) {
MPI_Type_indexed(count,blocklengths,displacements,MPI_INT,&newvectortype);
MPI_Type_commit(&newvectortype);
MPI_Send(source,1,newvectortype,the_other,0,comm);
MPI_Type_free(&newvectortype);
} else if (procno==receiver) {
MPI_Status recv_status;
int recv_count;
MPI_Recv(target,targetbuffersize,MPI_INT,the_other,0,comm,
&recv_status);
MPI_Get_count(&recv_status,MPI_INT,&recv_count);
ASSERT(recv_count==count);
}
## indexed.py
displacements = np.empty(count,dtype=int)
blocklengths = np.empty(count,dtype=int)
source = np.empty(totalcount,dtype=np.float64)
target = np.empty(count,dtype=np.float64)
if procid==sender:
newindextype = MPI.DOUBLE.Create_indexed(blocklengths,displacements)
newindextype.Commit()
comm.Send([source,1,newindextype],dest=the_other)
newindextype.Free()
elif procid==receiver:
comm.Recv([target,count,MPI.DOUBLE],source=the_other)
MPL note 49: Indexed type. In MPL, the indexed_layout is based on a vector of 2-tuples denoting block
length / block location.
// indexed.cxx
const int count = 5;
mpl::contiguous_layout<int>
fiveints(count);
mpl::indexed_layout<int>
indexed_where{ { {1,2}, {1,3}, {1,5}, {1,7}, {1,11} } };
if (procno==sender) {
comm_world.send( source_buffer.data(),indexed_where, receiver );
} else if (procno==receiver) {
auto recv_status =
comm_world.recv( target_buffer.data(),fiveints, sender );
int recv_count = recv_status.get_count<int>();
assert(recv_count==count);
}
MPL note 50: Layouts for gatherv. The size/displacement arrays for MPI_Gatherv / MPI_Alltoallv are han-
dled through a layouts object, which is basically a vector of layout objects.
mpl::layouts<int> receive_layout;
for ( int iproc=0,loc=0; iproc<nprocs; iproc++ ) {
auto siz = size_buffer.at(iproc);
receive_layout.push_back
( mpl::indexed_layout<int>( {{ siz,loc }} ) );
loc += siz;
}
MPL note 51: Indexed block type. For the case where all block lengths are the same, use
indexed_block_layout:
// indexedblock.cxx
mpl::indexed_block_layout<int>
indexed_where( 1, {2,3,5,7,11} );
comm_world.send( source_buffer.data(),indexed_where, receiver );
You can also MPI_Type_create_hindexed which describes blocks of a single old type, but with index locations
in bytes, rather than in multiples of the old type.
int MPI_Type_create_hindexed
(int count, int blocklens[], MPI_Aint indices[],
MPI_Datatype old_type,MPI_Datatype *newtype)
A slightly simpler version, MPI_Type_create_hindexed_block (figure 6.13) assumes constant block length.
There is an important difference between the hindexed and the above MPI_Type_indexed: that one de-
scribed offsets from a base location; these routines describes absolute memory addresses. You can use this
to send for instance the elements of a linked list. You would traverse the list, recording the addresses of
the elements with MPI_Get_address (figure 6.14). (The routine MPI_Address is deprecated.)
In C++ you can use this to send an std::<vector>, that is, a vector object from the C++ standard library, if
the component type is a pointer.
} point;
has two blocks, one of a single integer, and one of two floats. This is illustrated in figure 6.7.
count The number of blocks in this datatype. The blocklengths, displacements, types arguments
have to be at least of this length.
blocklengths array containing the lengths of the blocks of each datatype.
displacements array describing the relative location of the blocks of each datatype.
types array containing the datatypes; each block in the new type is of a single datatype; there can be
multiple blocks consisting of the same type.
In this example, unlike the previous ones, both sender and receiver create the structure type. With struc-
tures it is no longer possible to send as a derived type and receive as a array of a simple type. (It would
be possible to send as one structure type and receive as another, as long as they have the same datatype
signature.)
// struct.c
struct object {
char c;
double x[2];
int i;
};
MPI_Datatype newstructuretype;
int structlen = 3;
int blocklengths[structlen]; MPI_Datatype types[structlen];
MPI_Aint displacements[structlen];
/*
* where are the components relative to the structure?
*/
MPI_Aint current_displacement=0;
// one character
blocklengths[0] = 1; types[0] = MPI_CHAR;
displacements[0] = (size_t)&(myobject.c) - (size_t)&myobject;
// two doubles
blocklengths[1] = 2; types[1] = MPI_DOUBLE;
displacements[1] = (size_t)&(myobject.x) - (size_t)&myobject;
// one int
blocklengths[2] = 1; types[2] = MPI_INT;
displacements[2] = (size_t)&(myobject.i) - (size_t)&myobject;
MPI_Type_create_struct(structlen,blocklengths,displacements,types,&newstructuretype);
MPI_Type_commit(&newstructuretype);
if (procno==sender) {
MPI_Send(&myobject,1,newstructuretype,the_other,0,comm);
} else if (procno==receiver) {
MPI_Recv(&myobject,1,newstructuretype,the_other,0,comm,MPI_STATUS_IGNORE);
}
MPI_Type_free(&newstructuretype);
Note the displacement calculations in this example, which involve some not so elegant pointer arith-
metic. The following Fortran code uses MPI_Get_address, which is more elegant, and in fact the only way
address calculations can be done in Fortran.
!! struct.F90
Type object
character :: c
real*8,dimension(2) :: x
integer :: i
end type object
type(object) :: myobject
integer,parameter :: structlen = 3
type(MPI_Datatype) :: newstructuretype
integer,dimension(structlen) :: blocklengths
type(MPI_Datatype),dimension(structlen) :: types;
MPI_Aint,dimension(structlen) :: displacements
if (procno==sender) then
call MPI_Send(myobject,1,newstructuretype,receiver,0,comm)
else if (procno==receiver) then
call MPI_Recv(myobject,1,newstructuretype,sender,0,comm,MPI_STATUS_IGNORE)
end if
call MPI_Type_free(newstructuretype)
since you do not know the way the compiler lays out the structure in memory1 .
If you want to send more than one structure, you have to worry more about padding in the structure. You
can solve this by adding an extra type MPI_UB for the ‘upper bound’ on the structure:
displacements[3] = sizeof(myobject); types[3] = MPI_UB;
MPI_Type_create_struct(struclen+1,.....);
MPL note 52: Struct type scalar. One could describe the MPI struct type as a collection of displacements, to
be applied to any set of items that conforms to the specifications. An MPL heterogeneous_layout
on the other hand, incorporates the actual data. Thus you could write
// structscalar.cxx
char c; double x; int i;
if (procno==sender) {
c = 'x'; x = 2.4; i = 37; }
mpl::heterogeneous_layout object( c,x,i );
if (procno==sender)
1. Homework question: what does the language standard say about this?
comm_world.send( mpl::absolute,object,receiver );
else if (procno==receiver)
comm_world.recv( mpl::absolute,object,sender );
Here, the absolute indicates the lack of an implicit buffer: the layout is absolute rather than a
relative description.
MPL note 53: Struct type general. More complicated data than scalars takes more work:
// struct.cxx
char c; vector<double> x(2); int i;
if (procno==sender) {
c = 'x'; x[0] = 2.7; x[1] = 1.5; i = 37; }
mpl::heterogeneous_layout object
( c,
mpl::make_absolute(x.data(),mpl::vector_layout<double>(2)),
i );
if (procno==sender) {
comm_world.send( mpl::absolute,object,receiver );
} else if (procno==receiver) {
comm_world.recv( mpl::absolute,object,sender );
}
6.4.1 C
For every routine, such as MPI_Send with an integer count, there is a corresponding MPI_Send_c with a
count of type MPI_Count.
MPI_Count buffersize = 1000;
double *indata,*outdata;
indata = (double*) malloc( buffersize*sizeof(double) );
outdata = (double*) malloc( buffersize*sizeof(double) );
MPI_Allreduce_c(indata,outdata,buffersize,
MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
Code: Output:
// pingpongbig.c make[3]: `pingpongbig' is up to date.
assert( sizeof(MPI_Count)>4 ); Ping-pong between ranks 0--1, repeated 10
for ( int power=3; power<=10; power++) { ↪times
MPI_Count length=pow(10,power); MPI Count has 8 bytes
buffer = (double*)malloc( Size: 10^3, (repeats=10000)
↪length*sizeof(double) ); Time 1.399211e-05 for size 10^3: 1.1435
MPI_Ssend_c ↪Gb/sec
(buffer,length,MPI_DOUBLE, Size: 10^4, (repeats=10000)
processB,0,comm); Time 4.077882e-05 for size 10^4: 3.9236
MPI_Recv_c ↪Gb/sec
(buffer,length,MPI_DOUBLE, Size: 10^5, (repeats=1000)
processB,0,comm,MPI_STATUS_IGNORE); Time 1.532863e-04 for size 10^5: 10.4380
↪Gb/sec
Size: 10^6, (repeats=1000)
Time 1.418844e-03 for size 10^6: 11.2768
↪Gb/sec
Size: 10^7, (repeats=100)
Time 1.443470e-02 for size 10^7: 11.0844
↪Gb/sec
Size: 10^8, (repeats=100)
Time 1.540918e-01 for size 10^8: 10.3834
↪Gb/sec
Size: 10^9, (repeats=10)
Time 1.813220e+00 for size 10^9: 8.8241
↪Gb/sec
Size: 10^10, (repeats=10)
Time 1.846741e+01 for size 10^10: 8.6639
↪Gb/sec
6.4.2 Fortran
The count parameter can be declared to be
use mpi_f08
Integer(kind=MPI_COUNT_KIND) :: count
Since Fortran has polymorphism, the same routine names can be used.
The legit way of coding: … but you can see what’s under the hood:
!! typecheckkind.F90 !! typecheck8.F90
integer(8) :: source,n=1 integer(8) :: source,n=1
call MPI_Init() call MPI_Init()
call MPI_Send(source,n,MPI_INTEGER8, & call MPI_Send(source,n,MPI_INTEGER8, &
1,0,MPI_COMM_WORLD) 1,0,MPI_COMM_WORLD)
Routines using this type are not available unless using the mpi_f08 module.
End of MPI-4 material
!! pingpongbig.F90
integer :: power,countbytes
Integer(KIND=MPI_COUNT_KIND) :: length
call MPI_Sizeof(length,countbytes,ierr)
if (procno==0) &
print *,"Bytes in count:",countbytes
length = 10**power
allocate( senddata(length),recvdata(length) )
call MPI_Send(senddata,length,MPI_DOUBLE_PRECISION, &
processB,0, comm)
call MPI_Recv(recvdata,length,MPI_DOUBLE_PRECISION, &
processB,0, comm,MPI_STATUS_IGNORE)
We use the same trick for the receive call, but now we catch the status parameter which will later tell us
how many elements of the basic type were sent:
} else if (procno==receiver) {
MPI_Status recv_status;
MPI_Recv(target,nblocks,blocktype,sender,0,comm,
&recv_status);
When we query how many of the basic elements are in the buffer (remember that in the receive call the
buffer length is an upper bound on the number of elements received) do we need a counter that is larger
than an integer. MPI has introduced a type MPI_Count for this, and new routines such as MPI_Get_elements_x
(figure 4.14) that return a count of this type:
MPI_Count recv_count;
MPI_Get_elements_x(&recv_status,MPI_FLOAT,&recv_count);
gives as output:
size of size_t = 8
0 68719476736 68719476736 0 68719476736
Clearly, not only do operations go left-to-right, but casting is done that way too: the computed subexpressions
are only cast to size_t if one operand is.
Above, we did not actually create a datatype that was bigger than 2G, but if you do so, you can query its
extent by MPI_Type_get_extent_x (figure 6.17) and MPI_Type_get_true_extent_x (figure 6.17).
Python note 23: Big data. Since python has unlimited size integers there is no explicit need for the
‘x’ variants of routines. Internally, MPI.Status.Get_elements is implemented in terms of
MPI_Get_elements_x.
Similarly, using MPI_Type_get_extent counts the gaps in a struct induced by alignment issues.
See section 6.3.7 for the code defining the structure type.
Figure 6.9: True lower bound and extent of a subarray data type
The subarray datatype need not start at the first element of the buffer, so the extent is an overstatement
of how much data is involved. In fact, the lower bound is zero, and the extent equals the size of the block
from which the subarray is taken. The routine MPI_Type_get_true_extent (figure 6.17) returns the lower
bound, indicating where the data starts, and the extent from that point. This is illustrated in figure 6.9.
Code: Output:
// trueextent.c In basic array of 192 bytes
int sender = 0, receiver = 1, the_other = 1-procno; find sub array of 48 bytes
int sizes[2] = {4,6},subsizes[2] = {2,3},starts[2] = {1,2}; Found lb=64, extent=72
MPI_Datatype subarraytype; Computing lb=64 extent=72
MPI_Type_create_subarray Non-true lb=0, extent=192,
(2,sizes,subsizes,starts, ↪computed=192
MPI_ORDER_C,MPI_DOUBLE,&subarraytype); Finished
MPI_Type_commit(&subarraytype); received: 8.500 9.500
↪10.500 14.500 15.500
MPI_Aint true_lb,true_extent,extent; ↪16.500
MPI_Type_get_true_extent 1,2
(subarraytype,&true_lb,&true_extent); 1,3
MPI_Aint 1,4
comp_lb = sizeof(double) * 2,2
( starts[0]*sizes[1]+starts[1] ), 2,3
comp_extent = sizeof(double) * 2,4
( sizes[1]-starts[1] // first row
+ starts[1]+subsizes[1] // last row
+ ( subsizes[0]>1 ? subsizes[0]-2 : 0 )*sizes[1]
↪);
ASSERT(true_lb==comp_lb);
ASSERT(true_extent==comp_extent);
MPI_Send(source,1,subarraytype,the_other,0,comm);
MPI_Type_free(&subarraytype);
There are also ‘big data’ routines MPI_Type_get_extent_x MPI_Type_get_true_extent_x that has an MPI_Count
as output.
The following material is for the recently released MPI-4 standard and may not be supported yet.
6.6.2.1 Example 1
In the examples of derived types so far we always used a send count of 1. What happens if you use a larger
count?
Consider a vector type, with a send count of 2.
MPI_Type_vector( count,bs,stride,oldtype,&one_n_type );
MPI_Type_contiguous( 2,&one_n_type,&two_n_type );
Figure 6.10: Contiguous type of two vectors, before and after resizing the extent.
The difference is pictured in figure 6.10, where the two illustrates the result of using a send count of 2,
and the bottom the desired effect.
To show how this problem can be solved by resizing the extent, let’s look at a specific example, and
consider sending more than one derived type, from a buffer containing consecutive integers:
// vectorpadsend.c
for (int i=0; i<max_elements; i++) sendbuffer[i] = i;
MPI_Type_vector(count,blocklength,stride,MPI_INT,&stridetype);
MPI_Type_commit(&stridetype);
MPI_Send( sendbuffer,ntypes,stridetype, receiver,0, comm );
6.6.2.2 Example 2
For another example, let’s revisit exercise 6.4 (and figure 6.5) where each process makes a buffer of integers
that will be interleaved in a gather call: Strided data was sent in individual transactions. Would it be
possible to address all these interleaved packets in one gather or scatter call?
The problem here is that MPI uses the extent of the send type in a scatter, or the receive type in a gather:
if that type is 20 bytes big from its first to its last element, then data will be read out 20 bytes apart in a
scatter, or written 20 bytes apart in a gather. This ignores the ‘gaps’ in the type! (See exercise 6.4.)
int *mydata = (int*) malloc( localsize*sizeof(int) );
for (int i=0; i<localsize; i++)
mydata[i] = i*nprocs+procno;
MPI_Gather( mydata,localsize,MPI_INT,
/* rest to be determined */ );
An ordinary gather call will of course not interleave, but put the data end-to-end:
MPI_Gather( mydata,localsize,MPI_INT,
gathered,localsize,MPI_INT, // abutting
root,comm );
Using a strided type still puts data end-to-end, but now there are unwritten gaps in the gather buffer:
MPI_Gather( mydata,localsize,MPI_INT,
gathered,1,stridetype, // abut with gaps
root,comm );
This is illustrated in figure 6.11. A sample printout of the result would be:
0 1879048192 1100361260 3 3 0 6 0 0 9 1 198654
The trick is to use MPI_Type_create_resized to make the extent of the type only one int long:
// interleavegather.c
MPI_Datatype interleavetype;
MPI_Type_create_resized(stridetype,0,sizeof(int),&interleavetype);
MPI_Type_commit(&interleavetype);
MPI_Gather( mydata,localsize,MPI_INT,
gathered,1,interleavetype, // shrunk extent
root,comm );
Now data is written with the same stride, but at starting points equal to the shrunk extent:
0 1 2 3 4 5 6 7 8 9 10 11
This is illustrated in figure 6.12.
Fortran note 12: Extent as Aint. The lowerbound and extent parameters are of type
Integer(kind=MPI_Address_kind):
!! stridescatter.F90
integer(kind=MPI_Address_kind) :: l,e
call MPI_Type_get_extent(scattertype,l,e)
e = c_sizeof(i)
call MPI_Type_create_resized(scattertype,l,e,interleavetype)
call MPI_Type_commit(interleavetype)
Exercise 6.7. Rewrite exercise 6.4 to use a gather, rather than individual messages.
MPL note 54: Extent resizing. Resizing a datatype does not give a new type, but does the resize ‘in place’:
void layout::resize(ssize_t lb, ssize_t extent);
Does it bother you (a little) that in the vector type you have to specify explicitly how many blocks there
are? It would be nice if you could create a ‘block with padding’ and then send however many of those.
Well, you can introduce that padding by resizing a type, making it a little larger.
// stridestretch.c
MPI_Datatype oneblock;
MPI_Type_vector(1,1,stride,MPI_DOUBLE,&oneblock);
MPI_Type_commit(&oneblock);
MPI_Aint block_lb,block_x;
MPI_Type_get_extent(oneblock,&block_lb,&block_x);
printf("One block has extent: %ld\n",block_x);
MPI_Datatype paddedblock;
MPI_Type_create_resized(oneblock,0,stride*sizeof(double),&paddedblock);
MPI_Type_commit(&paddedblock);
MPI_Type_get_extent(paddedblock,&block_lb,&block_x);
printf("Padded block has extent: %ld\n",block_x);
There is a second solution to this problem, using a structure type. This does not use resizing, but rather
indicates a displacement that reaches to the end of the structure. We do this by putting a type MPI_UB at
this displacement:
int blens[2]; MPI_Aint displs[2];
MPI_Datatype types[2], paddedblock;
blens[0] = 1; blens[1] = 1;
displs[0] = 0; displs[1] = 2 * sizeof(double);
types[0] = MPI_DOUBLE; types[1] = MPI_UB;
MPI_Type_struct(2, blens, displs, types, &paddedblock);
MPI_Type_commit(&paddedblock);
MPI_Status recv_status;
MPI_Recv(target,count,paddedblock,the_other,0,comm,&recv_status);
The target type is harder to describe. First we note that each contiguous block from the source type can
be described as a vector type with:
• 𝑏 blocks,
• of size 1 each,
• stided by the global 𝑗-size of the matrix.
MPI_Datatype targetcolumn;
MPI_Type_vector( blocksize_i,1,jsize, MPI_INT,&targetcolumn);
MPI_Type_commit( &targetcolumn );
For the full type at the receiving process we now need to pack 𝑏 of these lines together.
Exercise 6.8. Finish the code.
• What is the extent of the targetcolumn type?
• What is the spacing of the first elements of the blocks? How do you therefore
resize the targetcolumn type?
MPI_COMBINER_VECTOR) and the number of parameters; the second routine is then used to retrieve the
actual parameters.
6.8 Packing
One of the reasons for derived datatypes is dealing with noncontiguous data. In older communication
libraries this could only be done by packing data from its original containers into a buffer, and likewise
unpacking it at the receiver into its destination data structures.
MPI offers this packing facility, partly for compatibility with such libraries, but also for reasons of flexibil-
ity. Unlike with derived datatypes, which transfers data atomically, packing routines add data sequentially
to the buffer and unpacking takes them sequentially.
This means that one could pack an integer describing how many floating point numbers are in the rest
of the packed message. Correspondingly, the unpack routine could then investigate the first integer and
based on it unpack the right number of floating point numbers.
MPI offers the following:
• The MPI_Pack command adds data to a send buffer;
• the MPI_Unpack command retrieves data from a receive buffer;
• the buffer is sent with a datatype of MPI_PACKED.
With MPI_Pack (figure 6.19) data elements can be added to a buffer one at a time. The position parameter
is updated each time by the packing routine.
Conversely, MPI_Unpack (figure 6.20) retrieves one element from the buffer at a time. You need to specify
A packed buffer is sent or received with a datatype of MPI_PACKED. The sending routine uses the position
parameter to specify how much data is sent, but the receiving routine does not know this value a priori,
so has to specify an upper bound.
Code: Output:
if (procno==sender) { [0] pack 8.401877e-01
position = 0; [0] pack 3.943829e-01
MPI_Pack(&nsends,1,MPI_INT, [0] pack 7.830992e-01
buffer,buflen,&position,comm); [0] pack 7.984400e-01
for (int i=0; i<nsends; i++) { [0] pack 9.116474e-01
double value = rand()/(double)RAND_MAX; [0] pack 1.975514e-01
printf("[%d] pack %e\n",procno,value);
MPI_Pack(&value,1,MPI_DOUBLE,
buffer,buflen,&position,comm);
}
MPI_Pack(&nsends,1,MPI_INT,
buffer,buflen,&position,comm);
MPI_Send(buffer,position,MPI_PACKED,other,0,comm);
} else if (procno==receiver) {
int irecv_value;
double xrecv_value;
MPI_Recv(buffer,buflen,MPI_PACKED,other,0,
comm,MPI_STATUS_IGNORE);
position = 0;
MPI_Unpack(buffer,buflen,&position,
&nsends,1,MPI_INT,comm);
for (int i=0; i<nsends; i++) {
MPI_Unpack(buffer,buflen,
&position,&xrecv_value,1,MPI_DOUBLE,comm);
printf("[%d] unpack %e\n",procno,xrecv_value);
}
MPI_Unpack(buffer,buflen,&position,
&irecv_value,1,MPI_INT,comm);
ASSERT(irecv_value==nsends);
}
You can precompute the size of the required buffer with MPI_Pack_size (figure 6.21).
Code: Output:
// pack.c 1 chars: 1
for (int i=1; i<=4; i++) { 2 chars: 2
MPI_Pack_size(i,MPI_CHAR,comm,&s); 3 chars: 3
printf("%d chars: %d\n",i,s); 4 chars: 4
} 1 unsigned shorts: 2
for (int i=1; i<=4; i++) { 2 unsigned shorts: 4
MPI_Pack_size(i,MPI_UNSIGNED_SHORT,comm,&s); 3 unsigned shorts: 6
printf("%d unsigned shorts: %d\n",i,s); 4 unsigned shorts: 8
} 1 ints: 4
for (int i=1; i<=4; i++) { 2 ints: 8
MPI_Pack_size(i,MPI_INT,comm,&s); 3 ints: 12
printf("%d ints: %d\n",i,s); 4 ints: 16
}
with dynamically created arrays. Write code to send and receive this structure.
A communicator is an object describing a group of processes. In many applications all processes work
together closely coupled, and the only communicator you need is MPI_COMM_WORLD, the group describing all
processes that your job starts with.
In this chapter you will see ways to make new groups of MPI processes: subgroups of the original
world communicator. Chapter 8 discusses dynamic process management, which, while not extending
MPI_COMM_WORLD does extend the set of available processes. That chapter also discusses the ‘sessions
model’, which is another way to constructing communicators.
Examples:
// C:
#include <mpi.h>
MPI_Comm comm = MPI_COMM_WORLD;
201
7. MPI topic: Communicators
MPL note 55: Predefined communicators. The environment namespace has the equivalents of MPI_COMM_WORLD
and MPI_COMM_SELF:
const communicator& mpl::environment::comm_world();
const communicator& mpl::environment::comm_self();
You can name your communicators with MPI_Comm_set_name, which could improve the quality of error
messages when they arise.
Python note 25: Communicator duplication. Duplicate communicators are created as output of the dupli-
cation routine:
newcomm = comm.Dup()
MPL note 57: Communicator duplication. Communicators can be duplicated but only during initialization.
Copy assignment has been deleted. Thus:
// LEGAL:
mpl::communicator init = comm;
// WRONG:
mpl::communicator init;
init = comm;
You may wonder what ‘an exact copy’ means precisely. For this, think of a communicator as a context
label that you can attach to, among others, operations such as sends and receives. And it’s that label that
counts, not what processes are in the communicator. A send and a receive ‘belong together’ if they have
the same communicator context. Conversely, a send in one communicator can not be matched to a receive
in a duplicate communicator, made by MPI_Comm_dup.
Testing whether two communicators are really the same is then more than testing if they comprise the
same processes. The call MPI_Comm_compare returns MPI_IDENT if two communicator values are the same,
and not if one is derived from the other by duplication:
Code: Output:
// commcompare.c assign: comm==copy: 1
int result; congruent: 0
MPI_Comm copy = comm; not equal: 0
MPI_Comm_compare(comm,copy,&result); duplicate: comm==copy: 0
printf("assign: comm==copy: %d \n", congruent: 1
result==MPI_IDENT); not equal: 0
printf(" congruent: %d \n",
result==MPI_CONGRUENT);
printf(" not equal: %d \n",
result==MPI_UNEQUAL);
MPI_Comm_dup(comm,©);
MPI_Comm_compare(comm,copy,&result);
printf("duplicate: comm==copy: %d \n",
result==MPI_IDENT);
printf(" congruent: %d \n",
result==MPI_CONGRUENT);
printf(" not equal: %d \n",
result==MPI_UNEQUAL);
MPI_Isend(...); MPI_Irecv(...);
// library call
MPI_Waitall(...);
and suppose that the library has receive calls. Now it is possible that the receive in the library inadvertently
catches the message that was sent in the outer environment.
Let us consider an example. First of all, here is code where the library stores the communicator of the
calling program:
// commdupwrong.cxx
class library {
private:
MPI_Comm comm;
int procno,nprocs,other;
MPI_Request request[2];
public:
library(MPI_Comm incomm) {
comm = incomm;
MPI_Comm_rank(comm,&procno);
other = 1-procno;
};
int communication_start();
int communication_end();
};
This models a main program that does a simple message exchange, and it makes two calls to library
routines. Unbeknown to the user, the library also issues send and receive calls, and they turn out to
interfere.
Here
• The main program does a send,
• the library call function_start does a send and a receive; because the receive can match either
send, it is paired with the first one;
• the main program does a receive, which will be paired with the send of the library call;
• both the main program and the library do a wait call, and in both cases all requests are succes-
fully fulfilled, just not the way you intended.
To prevent this confusion, the library should duplicate the outer communicator with MPI_Comm_dup and
send all messages with respect to its duplicate. Now messages from the user code can never reach the
library software, since they are on different communicators.
// commdupright.cxx
class library {
private:
MPI_Comm comm;
int procno,nprocs,other;
MPI_Request request[2];
public:
library(MPI_Comm incomm) {
MPI_Comm_dup(incomm,&comm);
MPI_Comm_rank(comm,&procno);
other = 1-procno;
};
~library() {
MPI_Comm_free(&comm);
}
int communication_start();
int communication_end();
};
Note how the preceding example performs the MPI_Comm_free cal in a C++ destructor.
## commdup.py
class Library():
def __init__(self,comm):
# wrong: self.comm = comm
self.comm = comm.Dup()
self.other = self.comm.Get_size()-self.comm.Get_rank()-1
self.requests = [ None ] * 2
def __del__(self):
if self.comm.Get_rank()==0: print(".. freeing communicator")
self.comm.Free()
def communication_start(self):
sendbuf = np.empty(1,dtype=int); sendbuf[0] = 37
recvbuf = np.empty(1,dtype=int)
self.requests[0] = self.comm.Isend( sendbuf, dest=other,tag=2 )
self.requests[1] = self.comm.Irecv( recvbuf, source=other )
def communication_end(self):
MPI.Request.Waitall(self.requests)
mylibrary = Library(comm)
my_requests[0] = comm.Isend( sendbuffer,dest=other,tag=1 )
mylibrary.communication_start()
my_requests[1] = comm.Irecv( recvbuffer,source=other )
MPI.Request.Waitall(my_requests,my_status)
mylibrary.communication_end()
7.3 Sub-communicators
In many scenarios you divide a large job over all the available processors. However, your job may have
two or more parts that can be considered as jobs by themselves. In that case it makes sense to divide your
processors into subgroups accordingly.
Suppose that you are running a simulation where inputs are generated, a computation is performed on
them, and the results of this computation are analyzed or rendered graphically. You could then consider
dividing your processors in three groups corresponding to generation, computation, rendering. As long
as you only do sends and receives, this division works fine. However, if one group of processes needs to
perform a collective operation, you don’t want the other groups involved in this. Thus, you really want
the three groups to be distinct from each other: you want them to be in separate communicators.
In order to make such subsets of processes, MPI has the mechanism of taking a subset of MPI_COMM_WORLD
(or other communicator) and turning that subset into a new communicator.
Now you understand why the MPI collective calls had an argument for the communicator. A collective
involves all processes of that communicator. If only the world communicator existed, no such argument
would be needed, but by making a communicator that contains a subset of all available processes, you
can do a collective on that subset.
The usage is as follows:
• You create a new communicator with routines such as MPI_Comm_dup (section 7.2), MPI_Comm_split
(section 7.4), MPI_Comm_create (section 7.5), MPI_Intercomm_create (section 7.6), MPI_Comm_spawn
(section 8.1);
• you use that communiator for a while;
• and you call MPI_Comm_free when you are done with it; this also sets the communicator variable
to MPI_COMM_NULL. A similar routine, MPI_Comm_disconnect waits for all pending communication
to finish. Both are collective.
Here is one example of communicator splitting. Suppose your processors are in a two-dimensional grid:
MPI_Comm_rank( MPI_COMM_WORLD, &mytid );
proc_i = mytid % proc_column_length;
proc_j = mytid / proc_column_length;
Because of the SPMD nature of the program, you are now doing in parallel a broadcast in every processor
column. Such operations often appear in dense linear algebra.
Exercise 7.1. Organize your processes in a grid, and make subcommunicators for the rows
and columns. For this compute the row and column number of each process.
In the row and column communicator, compute the rank. For instance, on a 2 × 3
processor grid you should find:
Global ranks: Ranks in row: Ranks in colum:
0 1 2 0 1 2 0 0 0
3 4 5 0 1 2 1 1 1
Check that the rank in the row communicator is the column number, and the other
way around.
Run your code on different number of processes, for instance a number of rows and
columns that is a power of 2, or that is a prime number.
(There is a skeleton for this exercise under the name procgrid.)
Python note 26: Comm split key is optional. In Python, the ‘key’ argument is optional:
Code: Output:
## commsplit.py Proc 0 -> 0 -> 0
mydata = procid Proc 2 -> 1 -> 0
Proc 6 -> 3 -> 1
# communicator modulo 2 Proc 4 -> 2 -> 1
color = procid%2 Proc 3 -> 1 -> 0
mod2comm = comm.Split(color) Proc 7 -> 3 -> 1
procid2 = mod2comm.Get_rank() Proc 1 -> 0 -> 0
Proc 5 -> 2 -> 1
# communicator modulo 4 recursively
color = procid2 % 2
mod4comm = mod2comm.Split(color)
procid4 = mod4comm.Get_rank()
MPL note 59: Communicator splitting. In MPL, splitting a communicator is done as one of the overloads
of the communicator constructor;
// commsplit.cxx
// create sub communicator modulo 2
int color2 = procno % 2;
There is also a routine MPI_Comm_split_type which uses a type rather than a key to split the communicator.
We will see this in action in section 12.1.
As another example of communicator splitting, consider the recursive algorithm for matrix transposition.
Processors are organized in a square grid. The matrix is divided on 2 × 2 block form.
Exercise 7.2. Implement a recursive algorithm for matrix transposition:
3. Make a new communicator object from the group with using MPI_Comm_create (figure 7.5), col-
lective on the old communicator.
4. On the ranks that were not in the subgroup, the resulting communicator value will be
MPI_COMM_NULL.
There is also a routine MPI_Comm_create_group that only needs to be called on the group that constitutes
the new communicator.
MPI_Group_size(group, size)
MPI_Group_rank(group, rank)
Certain MPI types, MPI_Win and MPI_File, are created on a communicator. While you can not directly
extract that communicator from the object, you can get the group with MPI_Win_get_group and
MPI_File_get_group.
There is a pre-defined empty group MPI_GROUP_EMPTY, which can be used as an input to group construc-
tion routines, or appear as the result of such operations as a zero intersection. This not the same as
MPI_GROUP_NULL, which is the output of invalid operations on groups, or the result of MPI_Group_free.
MPL note 60: Raw group handles. Should you need the MPI_Datatype object contained in an MPL group,
there is an access function native_handle.
7.5.2 Examples
Suppose you want to split the world communicator into one manager process, with the remaining pro-
cesses workers.
// portapp.c
MPI_Comm comm_work;
{
MPI_Group world_group,work_group;
MPI_Comm_group( comm_world,&world_group );
Exercise 7.3. Write a code that does a scaling study: your code needs to contain a loop over
increasingly sized subsets of MPI_COMM_WORLD.
for (int subsize=1; subsize<=worldsize; subsize++) {
MPI_Comm subcomm;
// form `subcomm' to be of size `subsize'
MPI_Allreduce( /* stuff */ subcomm );
}
Carefully address which process do the various communicator and group calls; in
particular do MPI_Comm_free and MPI_Group_free on the right processes.
7.6 Intercommunicators
In several scenarios it may be desirable to have a way to communicate between communicators. For
instance, an application can have clearly functionally separated modules (preprocessor, simulation, post-
processor) that need to stream data pairwise. In another example, dynamically spawned processes (sec-
tion 8.1) get their own value of MPI_COMM_WORLD, but still need to communicate with the process(es) that
spawned them. In this section we will discuss the inter-communicator mechanism that serves such use
cases.
Communicating between disjoint communicators can of course be done by having a communicator that
overlaps them, but this would be complicated: since the ‘inter’ communication happens in the overlap
communicator, you have to translate its ordering into those of the two worker communicators. It would
be easier to express messages directly in terms of those communicators, and this is what happens in an
inter-communicator.
A call to MPI_Intercomm_create (figure 7.8) involves the following communicators:
• Two local communicators, which in this context are known as intra-communicators: one process
in each will act as the local leader, connected to the remote leader;
• The peer communicator, often MPI_COMM_WORLD, that contains the local communicators;
• An inter-communicator that allows the leaders of the subcommunicators to communicate with
the other subcommunicator.
Even though the intercommunicator connects only two proceses, it is collective on the peer communicator.
• Likewise, the receiver specifies as source the local number of the sender in its
sub-communicator.
In one way, this design makes sense: processors are referred to in their natural, local, numbering. On the
other hand, it means that each group needs to know how the local ordering of the other group is arranged.
Using a complicated key value makes this difficult.
if (i_am_local_leader) {
if (color==0) {
interdata = 1.2;
int inter_target = local_number_of_other_leader;
printf("[%d] sending interdata %e to %d\n",
procno,interdata,inter_target);
MPI_Send(&interdata,1,MPI_DOUBLE,inter_target,0,intercomm);
} else {
MPI_Status status;
MPI_Recv(&interdata,1,MPI_DOUBLE,MPI_ANY_SOURCE,MPI_ANY_TAG,intercomm,&status);
int inter_source = status.MPI_SOURCE;
printf("[%d] received interdata %e from %d\n",
procno,interdata,inter_source);
if (inter_source!=local_number_of_other_leader)
fprintf(stderr,
"Got inter communication from unexpected %d; s/b %d\n",
inter_source,local_number_of_other_leader);
}
}
Intercomm.Get_remote_size(self)
Intercomm.Get_remote_group(self)
In this course we have up to now only considered the SPMD model of running MPI programs. In some
rare cases you may want to run in an MPMD mode, rather than SPMD. This can be achieved either on the
OS level, using options of the mpiexec mechanism, or you can use MPI’s built-in process management.
Read on if you’re interested in the latter.
219
8. MPI topic: Process management
MPI.Intracomm.Spawn(self,
command, args=None, int maxprocs=1, Info info=INFO_NULL,
int root=0, errcodes=None)
returns an intracommunicator
• If the spawned process takes no commandline arguments, a value of MPI_ARGV_NULL can be used,
in both C and Fortran. In C this is the same as NULL.
• Unline the argv argument of a main program, the argv argument passed in the spawn call does
not contain the name of the executable.
}
int work_n = universe_size - world_n;
if (world_p==0) {
printf("A universe of size %d leaves room for %d workers\n",
universe_size,work_n);
printf(".. spawning from %s\n",procname);
}
## spawnmanager.py
try :
universe_size = comm.Get_attr(MPI.UNIVERSE_SIZE)
if universe_size is None:
print("Universe query returned None")
universe_size = nprocs + 4
else:
print("World has {} ranks in a universe of {}"\
.format(nprocs,universe_size))
except :
print("Exception querying universe size")
universe_size = nprocs + 4
nworkers = universe_size - nprocs
A process can detect whether it was a spawning or a spawned process by using MPI_Comm_get_parent: the
resulting intercommunicator is MPI_COMM_NULL on the parent processes.
// spawnapp.c
MPI_Comm comm_parent;
MPI_Comm_get_parent(&comm_parent);
int is_child = (comm_parent!=MPI_COMM_NULL);
if (is_child) {
int nworkers,workerno;
MPI_Comm_size(MPI_COMM_WORLD,&nworkers);
MPI_Comm_rank(MPI_COMM_WORLD,&workerno);
printf("I detect I am worker %d/%d running on %s\n",
workerno,nworkers,procname);
The spawned program looks very much like a regular MPI program, with its own initialization and finalize
calls.
// spawnworker.c
MPI_Comm_size(MPI_COMM_WORLD,&nworkers);
MPI_Comm_rank(MPI_COMM_WORLD,&workerno);
MPI_Comm_get_parent(&parent);
## spawnworker.py
parentcomm = comm.Get_parent()
nparents = parentcomm.Get_remote_size()
Spawned processes wind up with a value of MPI_COMM_WORLD of their own, but managers and workers can
find each other regardless. The spawn routine returns the intercommunicator to the parent; the children
can find it through MPI_Comm_get_parent (section 7.6.3). The number of spawning processes can be found
through MPI_Comm_remote_size on the parent communicator.
Running spawnapp with usize=12, wsize=4
%%
%% manager output
%%
A universe of size 12 leaves room for 8 workers
.. spawning from c209-026.frontera.tacc.utexas.edu
%%
%% worker output
%%
Worker deduces 8 workers and 4 parents
I detect I am worker 0/8 running on c209-027.frontera.tacc.utexas.edu
I detect I am worker 1/8 running on c209-027.frontera.tacc.utexas.edu
I detect I am worker 2/8 running on c209-027.frontera.tacc.utexas.edu
I detect I am worker 3/8 running on c209-027.frontera.tacc.utexas.edu
I detect I am worker 4/8 running on c209-028.frontera.tacc.utexas.edu
I detect I am worker 5/8 running on c209-028.frontera.tacc.utexas.edu
I detect I am worker 6/8 running on c209-028.frontera.tacc.utexas.edu
I detect I am worker 7/8 running on c209-028.frontera.tacc.utexas.edu
8.1.4 MPMD
Instead of spawning a single executable, you can spawn multiple with MPI_Comm_spawn_multiple. In that
case a process can retrieve with the attribute MPI_APPNUM which of the executables it is; section 15.1.2.
Commandline arguments are handled similarly to MPI_Comm_spawn (section 8.1.1), except that that there
is now an array of arrays of strings. If not executables take commandline argumentscommandline argu-
ments!of multiple spawns, the value MPI_ARGVS_NULL can be passed. If only certain executables take no
arguments, for them an array of length 1 needs to be passed containing only the null-terminator.
/*
* The workers collective connect over the inter communicator
*/
MPI_Comm intercomm;
MPI_Comm_connect( myport,MPI_INFO_NULL,0,comm_work,&intercomm );
if (work_p==0) {
int manage_n;
MPI_Comm_remote_size(intercomm,&manage_n);
printf("%d workers connected to %d managers\n",work_n,manage_n);
If the named port does not exist (or has been closed), MPI_Comm_connect raises an error of class MPI_ERR_PORT.
The client can sever the connection with MPI_Comm_disconnect.
Running the above code on 5 processes gives:
# exchange port name:
Host sent port <<tag#0$OFA#000010e1:0001cde9:0001cdee$rdma_port#1024$rdma_host#10:16:225:0:1:205:199:25
Worker received port <<tag#0$OFA#000010e1:0001cde9:0001cdee$rdma_port#1024$rdma_host#10:16:225:0:1:205:
# Comm accept/connect
host accepted connection
4 workers connected to 1 managers
Intel note. Start the hydra name server and use the corresponding mpi starter:
hydra_nameserver &
MPIEXEC=mpiexec.hydra
There is an environment variable, but that doesn’t seem to be needed.
export I_MPI_HYDRA_NAMESERVER=`hostname`:8008
It is also possible to specify the name server as an argument to the job starter.
At the end of a run, the service should be unpublished with MPI_Unpublish_name (figure 8.6). Unpublishing
a nonexisting or already unpublished service gives an error code of MPI_ERR_SERVICE.
MPI provides no guarantee of fairness in servicing connection attempts. That is, connection attempts are
not necessarily satisfied in the order in which they were initiated, and competition from other connection
attempts may prevent a particular connection attempt from being satisfied.
8.3 Sessions
The most common way of initializing MPI, with MPI_Init (or MPI_Init_thread) and MPI_Finalize, is known
as the world model which can be described as:
1. There is a single call to MPI_Init or MPI_Init_thread;
2. There is a single call to MPI_Finalize;
3. With very few exceptions, all MPI calls appear in between the initialize and finalize calls.
MPI_Session the_session;
MPI_Session_init
( session_request_info,MPI_ERRORS_ARE_FATAL,
&the_session );
MPI_Session_finalize( &the_session );
The MPI_Info object that is passed to MPI_Session_init can be null, or it can be used to request a threading
level:
// session.c
MPI_Info session_request_info = MPI_INFO_NULL;
MPI_Info_create(&session_request_info);
char thread_key[] = "mpi_thread_support_level";
MPI_Info_set(session_request_info,
thread_key,"MPI_THREAD_MULTIPLE");
Other info keys can be implementation-dependent, but the key thread_support is pre-defined.
The error handler argument accepts a pre-defined error handler (section 15.2.2) or one created by
MPI_Session_create_errhandler.
A session has a number of process sets. Process sets are indicated with a Uniform Resource Identifier (URI),
where the URIs mpi://WORLD and mpi://SELF are always defined.
Code: Output:
int npsets; mpiexec -n 2 ./session
MPI_Session_get_num_psets Could not obtain thread
( the_session,MPI_INFO_NULL,&npsets ); ↪level,flag=0
if (mainproc) Number of process sets: 2
printf("Number of process sets: %d\n",npsets); Process set 0:
for (int ipset=0; ipset<npsets; ipset++) { ↪<<mpi://WORLD>>
int len_pset; char name_pset[MPI_MAX_PSET_NAME_LEN]; Process set 1:
MPI_Session_get_nth_pset ↪<<mpi://SELF>>
( the_session,MPI_INFO_NULL, Found WORLD as pset 0
ipset,&len_pset,name_pset ); World has 2 processes
if (mainproc)
printf("Process set %2d: <<%s>>\n",
ipset,name_pset);
The following partial code creates a communicator equivalent to MPI_COMM_WORLD in the session model:
MPI_Group world_group = MPI_GROUP_NULL;
MPI_Comm world_comm = MPI_COMM_NULL;
MPI_Group_from_session_pset
( the_session,world_name,&world_group );
MPI_Comm_create_from_group
( world_group,"victor-code-session.c",
MPI_INFO_NULL,MPI_ERRORS_ARE_FATAL,
&world_comm );
MPI_Group_free( &world_group );
int procid = -1, nprocs = 0;
MPI_Comm_size(world_comm,&nprocs);
MPI_Comm_rank(world_comm,&procid);
However, comparing communicators (with MPI_Comm_compare) from the session and world model, or from
different sessions, is undefined behavior.
Get the info object (section 15.1.1) from a process set: MPI_Session_get_pset_info. This info object always
has the key mpi_size.
8.3.4 Example
As an example of the use of sessions, we declare a library class, where each library object starts and ends
its own session:
// sessionlib.cxx
class Library {
private:
MPI_Comm world_comm; MPI_Session session;
public:
Library() {
MPI_Info info = MPI_INFO_NULL;
MPI_Session_init
( MPI_INFO_NULL,MPI_ERRORS_ARE_FATAL,&session );
char world_name[] = "mpi://WORLD";
MPI_Group world_group;
MPI_Group_from_session_pset
( session,world_name,&world_group );
MPI_Comm_create_from_group
( world_group,"world-session",
MPI_INFO_NULL,MPI_ERRORS_ARE_FATAL,
&world_comm );
MPI_Group_free( &world_group );
};
~Library() { MPI_Session_finalize(&session); };
Now we create a main program, using the world model, which activates two libraries, passing data to
them by parameter:
int main(int argc,char **argv) {
Library lib1,lib2;
MPI_Init(0,0);
MPI_Comm world = MPI_COMM_WORLD;
int procno,nprocs;
MPI_Comm_rank(world,&procno);
MPI_Comm_size(world,&nprocs);
auto sum1 = lib1.compute(procno);
auto sum2 = lib2.compute(procno+1);
Note that no mpi calls will go between main program and either of the libraries, or between the two
libraries, but this seems to make sense in this scenario.
End of MPI-4 material
Above, you saw point-to-point operations of the two-sided type: they require the co-operation of a sender
and receiver. This co-operation could be loose: you can post a receive with MPI_ANY_SOURCE as sender, but
there had to be both a send and receive call. This two-sidedness can be limiting. Consider code where the
receiving process is a dynamic function of the data:
x = f();
p = hash(x);
MPI_Send( x, /* to: */ p );
The problem is now: how does p know to post a receive, and how does everyone else know not to?
In this section, you will see one-sided communication routines where a process can do a ‘put’ or ‘get’ op-
eration, writing data to or reading it from another processor, without that other processor’s involvement.
In one-sided MPI operations, known as Remote Memory Access (RMA) operations in the standard, or
as Remote Direct Memory Access (RDMA) in other literature, there are still two processes involved: the
origin, which is the process that originates the transfer, whether this is a ‘put’ or a ‘get’, and the target
whose memory is being accessed. Unlike with two-sided operations, the target does not perform an action
that is the counterpart of the action on the origin.
That does not mean that the origin can access arbitrary data on the target at arbitrary times. First of all,
one-sided communication in MPI is limited to accessing only a specifically declared memory area on the
target: the target declares an area of memory that is accessible to other processes. This is known as a
window. Windows limit how origin processes can access the target’s memory: you can only ‘get’ data
from a window or ‘put’ it into a window; all the other memory is not reachable from other processes. On
the origin there is no such limitation; any data can function as the source of a ‘put’ or the recipient of a
‘get operation.
The alternative to having windows is to use distributed shared memory or virtual shared memory: memory
is distributed but acts as if it shared. The so-called Partitioned Global Address Space (PGAS) languages
such as Unified Parallel C (UPC) use this model.
Within one-sided communication, MPI has two modes: active RMA and passive RMA. In active RMA, or
active target synchronization, the target sets boundaries on the time period (the ‘epoch’) during which its
window can be accessed. The main advantage of this mode is that the origin program can perform many
232
9.1. Windows
small transfers, which are aggregated behind the scenes. This would be appropriate for applications that
are structured in a Bulk Synchronous Parallel (BSP) mode with supersteps. Active RMA acts much like
asynchronous transfer with a concluding MPI_Waitall.
In passive RMA, or passive target synchronization, the target process puts no limitation on when its window
can be accessed. (PGAS languages such as UPC are based on this model: data is simply read or written at
will.) While intuitively it is attractive to be able to write to and read from a target at arbitrary time, there
are problems. For instance, it requires a remote agent on the target, which may interfere with execution
of the main thread, or conversely it may not be activated at the optimal time. Passive RMA is also very
hard to debug and can lead to race conditions.
9.1 Windows
In one-sided communication, each processor can make an area of memory, called a window, available to
one-sided transfers. This is stored in a variable of type MPI_Win. A process can put an arbitrary item from
its own memory (not limited to any window) to the window of another process, or get something from
the other process’ window in its own memory.
A window can be characteristized as follows:
• The window is defined on a communicator, so the create call is collective; see figure 9.1.
• The window size can be set individually on each process. A zero size is allowed, but since win-
dow creation is collective, it is not possible to skip the create call.
• You can set a ‘displacement unit’ for the window: this is a number of bytes that will be used as
the indexing unit. For example if you use sizeof(double) as the displacement unit, an MPI_Put
to location 8 will go to the 8th double. That’s easier than having to specify the 64th byte.
• The window is the target of data in a put operation, or the source of data in a get operation; see
figure 9.2.
• There can be memory associated with a window, so it needs to be freed explicitly with
MPI_Win_free.
MPI.Win.Create
(memory, int disp_unit=1,
Info info=INFO_NULL, Intracomm comm=COMM_SELF)
MPI_Info info;
MPI_Win window;
MPI_Win_allocate( /* size info */, info, comm, &memory, &window );
// do put and get calls
MPI_Win_free( &window );
Figure 9.2: Put and get between process memory and windows
2. You can let MPI do the allocation, so that MPI can perform various optimizations regarding
placement of the memory. The user code then receives the pointer to the data from MPI. This
can again be done in two ways:
• Use MPI_Win_allocate (figure 9.2) to create the data and the window in one call.
• If a communicator is on a shared memory (see section 12.1) you can create a window
in that shared memory with MPI_Win_allocate_shared. This will be useful for MPI shared
memory; see chapter 12.
3. Finally, you can create a window with MPI_Win_create_dynamic which postpones the allocation;
see section 9.5.2.
First of all, MPI_Win_create creates a window from a pointer to memory. The data array must not be
PARAMETER or static const.
The size parameter is measured in bytes. In C this can be done with the sizeof operator;
// putfencealloc.c
MPI_Win the_window;
int *window_data;
MPI_Win_allocate(2*sizeof(int),sizeof(int),
MPI_INFO_NULL,comm,
&window_data,&the_window);
Next, one can obtain the memory from MPI by using MPI_Win_allocate, which has the data pointer as
output. Note the void* in the C signature; it is still necessary to pass a pointer to a pointer:
double *window_data;
MPI_Win_allocate( ... &window_data ... );
The routine MPI_Alloc_mem (figure 9.3) performs only the allocation part of MPI_Win_allocate, after which
you need to MPI_Win_create.
• An error of MPI_ERR_NO_MEM indicates that no memory could be allocated.
The following material is for the recently released MPI-4 standard and may not be supported yet.
• Allocated memory can be aligned by specifying an MPI_Info key of
mpi_minimum_memory_alignment.
End of MPI-4 material
This memory is freed with MPI_Free_mem:
// getfence.c
int *number_buffer = NULL;
MPI_Alloc_mem
( /* size: */ 2*sizeof(int),
MPI_INFO_NULL,&number_buffer);
MPI_Win_create
( number_buffer,2*sizeof(int),sizeof(int),
MPI_INFO_NULL,comm,&the_window);
MPI_Win_free(&the_window);
MPI_Free_mem(number_buffer);
Python note 28: Window buffers. Unlike in C, the python window allocate call does not return a pointer to
the buffer memory, but an MPI.memory object. Should you need the bare memory, there are the
following options:
• Window objects expose the Python buffer interface. So you can do Pythonic things like
mview = memoryview(win)
array = numpy.frombuffer(win, dtype='i4')
• If you really want the raw base pointer (as an integer), you can do any of these:
base, size, disp_unit = win.atts
base = win.Get_attr(MPI.WIN_BASE)
• You can use mpi4py’s builtin memoryview/buffer-like type, but I do not recommend it, much
better to use NumPy as above:
mem = win.tomemory() # type(mem) is MPI.memory, similar to memoryview, but quite
↪limited in functionality
base = mem.address
size = mem.nbytes
MPI_Win_fence(0,win);
MPI_Get( /* operands */, win);
MPI_Win_fence(0, win);
// the `got' data is available
In between the two fences the window is exposed, and while it is you should not access it locally. If you
absolutely need to access it locally, you can use an RMA operation for that. Also, there can be only one
remote process that does a put; multiple accumulate accesses are allowed.
Fences are, together with other window calls, collective operations. That means they imply some amount
of synchronization between processes. Consider:
MPI_Win_fence( ... win ... ); // start an epoch
if (mytid==0) // do lots of work
MPI_Win_fence( ... win ... ); // end the epoch
and assume that all processes execute the first fence more or less at the same time. The zero process does
work before it can do the second fence call, but all other processes can call it immediately. However, they
can not finish that second fence call until all one-sided communication is finished, which means they wait
for the zero process.
As a further restriction, you can not mix MPI_Get with MPI_Put or MPI_Accumulate calls in a single epoch.
Hence, we can characterize an epoch as an access epoch on the origin, and as an exposure epoch on the
target.
Figure 9.3: A trace of a one-sided communication epoch where process zero only originates a one-sided
transfer
Assertions are an integer parameter: you can combine assertions by adding them or using logical-or. The
value zero is always correct. For further information, see section 9.6.
In other words, this turns your window into the target for a remote access. There is a non-blocking version
MPI_Win_test of MPI_Win_wait.
In other words, these calls border the access to a remote window, with the current processor being the
origin of the remote access.
In the following snippet a single processor puts data on one other. Note that they both have their own
definition of the group, and that the receiving process only does the post and wait calls.
// postwaitwin.c
MPI_Comm_group(comm,&all_group);
if (procno==origin) {
MPI_Group_incl(all_group,1,&target,&two_group);
// access
MPI_Win_start(two_group,0,the_window);
MPI_Put( /* data on origin: */ &my_number, 1,MPI_INT,
/* data on target: */ target,0, 1,MPI_INT,
the_window);
MPI_Win_complete(the_window);
}
if (procno==target) {
MPI_Group_incl(all_group,1,&origin,&two_group);
// exposure
MPI_Win_post(two_group,0,the_window);
MPI_Win_wait(the_window);
}
Both pairs of operations declare a group of processors; see section 7.5.1 for how to get such a group from
a communicator. On an origin processor you would specify a group that includes the targets you will
interact with, on a target processor you specify a group that includes the possible origins.
Send, Receive and Reduce, except that of course only one process makes a call. Since one process does all
the work, its calling sequence contains both a description of the data on the origin (the calling process)
and the target (the affected other process).
As in the two-sided case, MPI_PROC_NULL can be used as a target rank.
The Accumulate routine has an MPI_Op argument that can be any of the usual operators, but no user-
defined ones (see section 3.10.1).
9.3.1 Put
The MPI_Put (figure 9.6) call can be considered as a one-sided send. As such, it needs to specify
• the target rank
• the data to be sent from the origin, and
• the location where it is to be written on the target.
The description of the data on the origin is the usual trio of buffer/count/datatype. However, the descrip-
tion of the data on the target is more complicated. It has a count and a datatype, but additionally it has
a displacement with respect to the start of the window on the target. This displacement can be given
in bytes, so its type is MPI_Aint, but strictly speaking it is a multiple of the displacement unit that was
specified in the window definition.
Specifically, data is written starting at
window_base + target_disp × disp_unit.
Here is a single put operation. Note that the window create and window fence calls are collective, so they
have to be performed on all processors of the communicator that was used in the create call.
// putfence.c
MPI_Win the_window;
MPI_Win_create
(&window_data,2*sizeof(int),sizeof(int),
MPI_INFO_NULL,comm,&the_window);
MPI_Win_fence(0,the_window);
if (procno==0) {
MPI_Put
( /* data on origin: */ &my_number, 1,MPI_INT,
/* data on target: */ other,1, 1,MPI_INT,
the_window);
}
MPI_Win_fence(0,the_window);
MPI_Win_free(&the_window);
Fortran note 13: Displacement unit. The disp_unit variable is declared as an integer of ‘kind’
MPI_ADDRESS_KIND:
!! putfence.F90
integer(kind=MPI_ADDRESS_KIND) :: target_displacement
target_displacement = 1
call MPI_Put( my_number, 1,MPI_INTEGER, &
other,target_displacement, &
1,MPI_INTEGER, &
the_window)
Prior to Fortran2008, specifying a literal constant, such as 0, could lead to bizarre runtime errors;
the solution was to specify a zero-valued variable of the right type. With the mpi_f08 module
this is no longer allowed. Instead you get an error such as
error #6285: There is no matching specific subroutine for this generic subroutine call. [MPI
Python note 29: MPI one-sided transfer routines. MPI_Put (and Get and Accumulate) accept at minimum the
origin buffer and the target rank. The displacement is by default zero.
Exercise 9.1. Revisit exercise 4.3 and solve it using MPI_Put.
(There is a skeleton for this exercise under the name rightput.)
Exercise 9.2. Write code where:
• process 0 computes a random number 𝑟
• if 𝑟 < .5, zero writes in the window on 1;
• if 𝑟 ≥ .5, zero writes in the window on 2.
(There is a skeleton for this exercise under the name randomput.)
9.3.2 Get
The MPI_Get (figure 9.7) call is very similar.
Example:
MPI_Win_fence(0,the_window);
if (procno==0) {
MPI_Get( /* data on origin: */ &my_number, 1,MPI_INT,
/* data on target: */ other,1, 1,MPI_INT,
the_window);
}
MPI_Win_fence(0,the_window);
Next, we split the update in the core part, which can be done purely from local values, and the boundary,
which needs local and halo values. Update of the core can overlap the communication of the halo.
for ( .... ) {
update_boundary(A);
MPI_Win_fence((MPI_MODE_NOPUT | MPI_MODE_NOPRECEDE), win);
for(i=0; i < fromneighbors; i++)
MPI_Get( ... );
update_core(A);
MPI_Win_fence(MPI_MODE_NOSUCCEED, win);
}
The MPI_MODE_NOPRECEDE and MPI_MODE_NOSUCCEED assertions still hold, but the Get operation implies that
instead of MPI_MODE_NOSTORE in the second fence, we use MPI_MODE_NOPUT in the first.
9.3.4 Accumulate
A third one-sided routine is MPI_Accumulate (figure 9.8) which does a reduction operation on the results
that are being put.
Accumulate is an atomic reduction with remote result. This means that multiple accumulates to a single
target in the same epoch give the correct result. As with MPI_Reduce, the order in which the operands are
accumulated is undefined.
The same predefined operators are available, but no user-defined ones. There is one extra operator:
MPI_REPLACE, this has the effect that only the last result to arrive is retained.
• One process stores a table of work descriptors, and a pointer to the first unprocessed descriptor;
• Each process reads the pointer, reads the corresponding descriptor, and increments the pointer;
and
• A process that has read a descriptor then executes the corresponding task.
The problem is that reading and updating the pointer is not an atomic operation, so it is possible that
multiple processes get hold of the same value; conversely, multiple updates of the pointer may lead to
work descriptors being skipped. These different overall behaviors, depending on precise timing of lower
level events, are called a race condition.
In MPI-3 some atomic routines have been added. Both MPI_Fetch_and_op (figure 9.10) and
MPI_Get_accumulate (figure 9.11) atomically retrieve data from the window indicated, and apply an
operator, combining the data on the target with the data on the origin. Unlike Put and Get, it is safe to
have multiple atomic operations in the same epoch.
Both routines perform the same operations: return data before the operation, then atomically update data
on the target, but MPI_Get_accumulate is more flexible in data type handling. The more simple routine,
MPI_Fetch_and_op, which operates on only a single element, allows for faster implementations, in particular
through hardware support.
Use of MPI_NO_OP as the MPI_Op turns these routines into an atomic Get. Similarly, using MPI_REPLACE turns
them into an atomic Put.
Exercise 9.5. Redo exercise 9.4 using MPI_Fetch_and_op. The problem is again to make sure
all processes have the same view of the shared counter.
## passive.py
if procid==repository:
# repository process creates a table of inputs
# and associates it with the window
win_mem = np.empty( ninputs,dtype=np.float32 )
win = MPI.Win.Create( win_mem,comm=comm )
else:
# everyone else has an empty window
win = MPI.Win.Create( None,comm=comm )
if procid!=repository:
contribution = np.empty( 1,dtype=np.float32 )
contribution[0] = 1.*procid
table_element = np.empty( 1,dtype=np.float32 )
win.Lock( repository,lock_type=MPI.LOCK_EXCLUSIVE )
win.Fetch_and_op( contribution,table_element,repository,0,MPI.SUM)
win.Unlock( repository )
Finally, MPI_Compare_and_swap (figure 9.12) swaps the origin and target data if the target data equals some
comparison value.
We start by considering the naive approach, where we execute the above scheme literally with MPI_Get
and MPI_Put:
// countdownput.c
MPI_Win_fence(0,the_window);
int counter_value;
MPI_Get( &counter_value,1,MPI_INT,
counter_process,0,1,MPI_INT,
the_window);
MPI_Win_fence(0,the_window);
if (i_am_available) {
int decrement = -1;
counter_value += decrement;
MPI_Put
( &counter_value, 1,MPI_INT,
counter_process,0,1,MPI_INT,
the_window);
}
MPI_Win_fence(0,the_window);
This scheme is correct if only process has a true value for i_am_available: that processes ‘owns’ the current
counter values, and it correctly updates the counter through the MPI_Put operation. However, if more than
one process is available, they get duplicate counter values, and the update is also incorrect. If we run this
program, we see that the counter did not get decremented by the total number of ‘put’ calls.
Exercise 9.6. Supposing only one process is available, what is the function of the middle of
the three fences? Can it be omitted?
We can fix the decrement of the counter by using MPI_Accumulate for the counter update, since it is atomic:
multiple updates in the same epoch all get processed.
// countdownacc.c
MPI_Win_fence(0,the_window);
int counter_value;
MPI_Get( &counter_value,1,MPI_INT,
counter_process,0,1,MPI_INT,
the_window);
MPI_Win_fence(0,the_window);
if (i_am_available) {
int decrement = -1;
MPI_Accumulate
( &decrement, 1,MPI_INT,
counter_process,0,1,MPI_INT,
MPI_SUM,
the_window);
}
MPI_Win_fence(0,the_window);
This scheme still suffers from the problem that processes will obtain duplicate counter values. The true
solution is to combine the ‘get’ and ‘put’ operations into one atomic action; in this case MPI_Fetch_and_op:
MPI_Win_fence(0,the_window);
int
counter_value;
if (i_am_available) {
int
decrement = -1;
total_decrement++;
MPI_Fetch_and_op
( /* operate with data from origin: */ &decrement,
/* retrieve data from target: */ &counter_value,
MPI_INT, counter_process, 0, MPI_SUM,
the_window);
}
MPI_Win_fence(0,the_window);
if (i_am_available) {
my_counter_values[n_my_counter_values++] = counter_value;
}
Now, if there are multiple accesses, each retrieves the counter value and updates it in one atomic, that is,
indivisible, action.
MPI.Win.Lock(self,
int rank, int lock_type=LOCK_EXCLUSIVE, int assertion=0)
Remark 18 The possibility to lock a window is not guaranteed for windows that are not created (possibly
internally) by MPI_Alloc_mem, that is, all but MPI_Win_create.
• while the remaining process spins until the others have performed their
update.
Use an atomic operation for the latter process to read out the shared value.
Can you replace the exclusive lock with a shared one?
(There is a skeleton for this exercise under the name lockfetch.)
Exercise 9.8. As exercise 9.7, but now use a shared lock: all processes acquire the lock
simultaneously and keep it as long as is needed.
The problem here is that coherence between window buffers and local variables is
now not forced by a fence or releasing a lock. Use MPI_Win_flush_local to force
coherence of a window (on another process) and the local variable from
MPI_Fetch_and_op.
(There is a skeleton for this exercise under the name lockfetchshared.)
• The assertion value can be zero, or MPI_MODE_NOCHECK, which asserts that no other process will
acquire a competing lock.
• There is no ‘locktype’ parameter: this is a shared lock.
The corresponding unlock is MPI_Win_unlock_all.
The expected use of a ‘lock/unlock all’ is that they surround an extended epoch with get/put and flush
calls.
If the passive target epoch is of greater duration, and no unlock operation is used to ensure completion,
the following calls are available.
Remark 19 Using flush routines with active target synchronization (or generally outside a passive target
epoch) you are likely to get a message
Wrong synchronization of RMA calls
With MPI_Win_flush_local_all local operations are concluded for all targets. This will typically be used
with MPI_Win_lock_all (section 9.4.2).
At first sight, the code looks like splitting up a MPI_Win_create call into separate creation of the window
and declaration of the buffer:
// windynamic.c
MPI_Win_create_dynamic(MPI_INFO_NULL,comm,&the_window);
if (procno==data_proc)
window_buffer = (int*) malloc( 2*sizeof(int) );
MPI_Win_attach(the_window,window_buffer,2*sizeof(int));
buffer, here the displacement is an absolute address. This means that we need to get the address of the
window buffer with MPI_Get_address and communicate it to the other processes:
MPI_Aint data_address;
if (procno==data_proc) {
MPI_Get_address(window_buffer,&data_address);
}
MPI_Bcast(&data_address,1,MPI_AINT,data_proc,comm);
Location of the data, that is, the displacement parameter, is then given as an absolute location of the start
of the buffer plus a count in bytes; in other words, the displacement unit is 1. In this example we use
MPI_Get to find the second integer in a window buffer:
Notes.
• The attached memory can be released with MPI_Win_detach (figure 9.20).
• The above fragments show that an origin process has the actual address of the window buffer.
It is an error to use this if the buffer is not attached to a window.
• In particular, one has to make sure that the attach call is concluded before performing RMA
operations on the window.
• MPI_WIN_SIZE and MPI_WIN_DISP_UNIT for obtaining the size and window displacement unit:
MPI_Aint *size;
MPI_Win_get_attr(win, MPI_WIN_SIZE, &size, &flag),
int *disp_unit;
MPI_Win_get_attr(win, MPI_WIN_DISP_UNIT, &disp_unit, &flag),
Window information objects (see section 15.1.1) can be set and retrieved:
int MPI_Win_set_info(MPI_Win win, MPI_Info info)
9.6 Assertions
The routines
• (Active target synchronization) MPI_Win_fence, MPI_Win_post, MPI_Win_start;
• (Passive target synchronization) MPI_Win_lock, MPI_Win_lockall,
take an argument through which assertions can be passed about the activity before, after, and during the
epoch. The value zero is always allowed, by you can make your program more efficient by specifying one
or more of the following, combined by bitwise OR in C/C++ or IOR in Fortran.
• MPI_Win_start Supports the option:
– MPI_MODE_NOCHECK the matching calls to MPI_Win_post have already completed on all target
processes when the call to MPI_Win_start is made. The nocheck option can be specified in
a start call if and only if it is specified in each matching post call. This is similar to the
optimization of “ready-send” that may save a handshake when the handshake is implicit
in the code. (However, ready-send is matched by a regular receive, whereas both start and
post must specify the nocheck option.)
• MPI_Win_post supports the following options:
– MPI_MODE_NOCHECK the matching calls to MPI_Win_start have not yet occurred on any origin
processes when the call to MPI_Win_post is made. The nocheck option can be specified by
a post call if and only if it is specified by each matching start call.
– MPI_MODE_NOSTORE the local window was not updated by local stores (or local get or receive
calls) since last synchronization. This may avoid the need for cache synchronization at the
post call.
– MPI_MODE_NOPUT the local window will not be updated by put or accumulate calls after the
post call, until the ensuing (wait) synchronization. This may avoid the need for cache
synchronization at the wait call.
• MPI_Win_fence supports the following options:
– MPI_MODE_NOSTORE the local window was not updated by local stores (or local get or receive
calls) since last synchronization.
– MPI_MODE_NOPUT the local window will not be updated by put or accumulate calls after the
fence call, until the ensuing (fence) synchronization.
– MPI_MODE_NOPRECEDE the fence does not complete any sequence of locally issued RMA calls.
If this assertion is given by any process in the window group, then it must be given by all
processes in the group.
– MPI_MODE_NOSUCCEED the fence does not start any sequence of locally issued RMA calls. If
the assertion is given by any process in the window group, then it must be given by all
processes in the group.
• MPI_Win_lock and MPI_Win_lock_all support the following option:
– MPI_MODE_NOCHECK no other process holds, or will attempt to acquire a conflicting lock, while
the caller holds the window lock. This is useful when mutual exclusion is achieved by other
means, but the coherence operations that may be attached to the lock and unlock calls are
still required.
9.7 Implementation
You may wonder how one-sided communication is realized1 . Can a processor somehow get at another
processor’s data? Unfortunately, no.
Active target synchronization is implemented in terms of two-sided communication. Imagine that the
first fence operation does nothing, unless it concludes prior one-sided operations. The Put and Get calls
do nothing involving communication, except for marking with what processors they exchange data. The
concluding fence is where everything happens: first a global operation determines which targets need to
issue send or receive calls, then the actual sends and receive are executed.
Exercise 9.9. Assume that only Get operations are performed during an epoch. Sketch how
these are translated to send/receive pairs. The problem here is how the senders find
out that they need to send. Show that you can solve this with an MPI_Reduce_scatter
call.
The previous paragraph noted that a collective operation was necessary to determine the two-sided traffic.
Since collective operations induce some amount of synchronization, you may want to limit this.
Exercise 9.10. Argue that the mechanism with window post/wait/start/complete operations
still needs a collective, but that this is less burdensome.
Passive target synchronization needs another mechanism entirely. Here the target process needs to have
a background task (process, thread, daemon,…) running that listens for requests to lock the window. This
can potentially be expensive.
#define MASTER 0
This chapter discusses the I/O support of MPI, which is intended to alleviate the problems inherent in par-
allel file access. Let us first explore the issues. This story partly depends on what sort of parallel computer
are you running on. Here are some of the hardware scenarios you may encounter:
• On networks of workstations each node will have a separate drive with its own file system.
• On many clusters there will be a shared file system that acts as if every process can access every
file.
• Cluster nodes may or may not have a private file system.
Based on this, the following strategies are possible, even before we start talking about MPI I/O.
• One process can collect all data with MPI_Gather and write it out. There are at least three things
wrong with this: it uses network bandwidth for the gather, it may require a large amount of
memory on the root process, and centralized writing is a bottleneck.
• Absent a shared file system, writing can be parallelized by letting every process create a unique
file and merge these after the run. This makes the I/O symmetric, but collecting all the files is a
bottleneck.
• Even with a with a shared file system this approach is possible, but it can put a lot of strain on
the file system, and the post-processing can be a significant task.
• Using a shared file system, there is nothing against every process opening the same existing file
for reading, and using an individual file pointer to get its unique data.
• … but having every process open the same file for output is probably not a good idea. For
instance, if two processes try to write at the end of the file, you may need to synchronize them,
and synchronize the file system flushes.
For these reasons, MPI has a number of routines that make it possible to read and write a single file from
a large number of processes, giving each process its own well-defined location where to access the data.
These locations can use MPI derived datatypes for both the source data (that is, in memory) and target
data (that is, on disk). Thus, in one call that is collective on a communicator each process can address data
that is not contiguous in memory, and place it in locations that are not contiguous on disc.
There are dedicated libraries for file I/O, such as hdf5, netcdf , or silo. However, these often add header
information to a file that may not be understandable to post-processing applications. With MPI I/O you
are in complete control of what goes to the file. (A useful tool for viewing your file is the unix utility od.)
263
10. MPI topic: File I/O
TACC note. Each node has a private /tmp file system (typically flash storage), to which you can write
files. Considerations:
• Since these drives are separate from the shared file system, you don’t have to worry about
stress on the file servers.
• These temporary file systems are wiped after your job finishes, so you have to do the
post-processing in your job script.
• The capacity of these local drives are fairly limited; see the userguide for exact numbers.
Even though the file is opened on a communicator, it is a class method for the MPI.File class,
rather than for the communicator object. The latter is passed in as an argument.
File access modes:
• MPI_MODE_RDONLY: read only,
• MPI_MODE_RDWR: reading and writing,
• MPI_MODE_WRONLY: write only,
all other fields of this argument are undefined. It can not be used if the file was opened with
MPI_MODE_SEQUENTIAL.
• If all processes execute a write at the same logical time, it is better to use the collective call
MPI_File_write_all.
• MPI_File_read (figure 10.4) This routine attempts to read the specified data from the locations
specified in the current file view. The number of items read is returned in the MPI_Status argu-
ment; all other fields of this argument are undefined. It can not be used if the file was opened
with MPI_MODE_SEQUENTIAL.
• If all processes execute a read at the same logical time, it is better to use the collective call
MPI_File_read_all (figure 10.5).
• MPI_File_write_at: combine write and seek. The collective variant is MPI_File_write_at_all; sec-
tion 10.2.2.
Writing to and reading from a parallel file is rather similar to sending a receiving:
• The process uses an predefined data type or a derived datatype to describe what elements in an
array go to file, or are read from file.
• In the simplest case, your read or write that data to the file using an offset, or first having done
a seek operation.
• But you can also set a ‘file view’ to describe explicitly what elements in the file will be involved.
Just like there are blocking and nonblocking sends, there are also nonblocking writes and
reads: MPI_File_iwrite (figure 10.6), MPI_File_iread operations, and their collective versions
MPI_File_iwrite_all, MPI_File_iread_all.
These routines output an MPI_Request object, which can then be tested with MPI_Wait or MPI_Test.
Nonblocking collective I/O functions much like other nonblocking collectives (section 3.11): the request
is satisfied if all processes finish the collective.
There are also split collectives that function like nonblocking collective I/O, but with the request/wait
mechanism: MPI_File_write_all_begin / MPI_File_write_all_end (and similarly MPI_File_read_all_begin /
MPI_File_read_all_end) where the second routine blocks until the collective write/read has been con-
cluded.
(mpifile,
offset,MPI_INT,scattertype,
"native",MPI_INFO_NULL);
Exercise 10.4.
(There is a skeleton for this exercise under the name viewwrite.) Write a file in the
same way as in exercise 10.1, but now use MPI_File_write and use MPI_File_set_view
to set a view that determines where the data is written.
You can get very creative effects by setting the view to a derived datatype.
Fortran note 14: Offset literals. In Fortran you have to assure that the displacement parameter is of ‘kind’
MPI_OFFSET_KIND. In particular, you can not specify a literal zero ‘0’ as the displacement; use
0_MPI_OFFSET_KIND instead.
Shared file pointers require that the same view is used on all processes. Also, these operations are less
efficient because of the need to maintain the shared pointer.
10.3 Consistency
It is possible for one process to read data previously writte by another process. For this, it is of course
necessary to impose a temporal order, for instance by using MPI_Barrier, or using a zero-byte send from
the writing to the reading process.
However, the file also needs to be declared atomic: MPI_File_set_atomicity.
10.4 Constants
MPI_SEEK_SET used to be called SEEK_SET which gave conflicts with the C++ library. This had to be cir-
cumvented with
make CPPFLAGS="-DMPICH_IGNORE_CXX_SEEK -DMPICH_SKIP_MPICXX"
and such.
The default I/O error handler can be queried and set with MPI_File_get_errhandler and
MPI_File_set_errhandler respectively, passing MPI_FILE_NULL as argument.
A communicator describes a group of processes, but the structure of your computation may not be such
that every process will communicate with every other process. For instance, in a computation that is math-
ematically defined on a Cartesian 2D grid, the processes themselves act as if they are two-dimensionally
ordered and communicate with N/S/E/W neighbors. If MPI had this knowledge about your application, it
could conceivably optimize for it, for instance by renumbering the ranks so that communicating processes
are closer together physically in your cluster.
The mechanism to declare this structure of a computation to MPI is known as a virtual topology. The
following types of topology are defined:
• MPI_UNDEFINED: this values holds for communicators where no topology has explicitly been spec-
ified.
• MPI_CART: this value holds for Cartesian toppologies, where processes act as if they are ordered
in a multi-dimensional ‘brick’; see section 11.1.
• MPI_GRAPH: this value describes the graph topology that was defined in MPI-1; section 11.2.4.
It is unnecessarily burdensome, since each process needs to know the total graph, and should
therefore be considered obsolete; the type MPI_DIST_GRAPH should be used instead.
• MPI_DIST_GRAPH: this value describes the distributed graph topology where each process only
describes the edges in the process graph that touch itself; see section 11.2.
These values can be discovered with the routine MPI_Topo_test.
275
11. MPI topic: Topologies
Code: Output:
// cartdims.c mpicc -o cartdims cartdims.o
int *dimensions = (int*) Cartesian grid size: 3 dim: 1
↪malloc(dim*sizeof(int)); 3
for (int idim=0; idim<dim; idim++) Cartesian grid size: 3 dim: 2
dimensions[idim] = 0; 3 x 1
MPI_Dims_create(nprocs,dim,dimensions); Cartesian grid size: 4 dim: 1
4
Cartesian grid size: 4 dim: 2
2 x 2
Cartesian grid size: 4 dim: 3
2 x 2 x 1
Cartesian grid size: 12 dim: 1
12
Cartesian grid size: 12 dim: 2
4 x 3
Cartesian grid size: 12 dim: 3
3 x 2 x 2
Cartesian grid size: 12 dim: 4
3 x 2 x 2 x 1
If the dimensions array is nonzero in a component, that one is not touched. Of course, the product of the
specified dimensions has to divide in the input number of nodes.
(The Cartesian grid can have fewer processes than the input communicator: any processes not included
get MPI_COMM_NULL as output.)
For a given communicator, you can test what type it is with MPI_Topo_test (figure 11.2):
int world_type,cart_type;
MPI_Topo_test( comm,&world_type);
MPI_Topo_test( cart_comm,&cart_type );
if (procno==0) {
printf("World comm type=%d, Cart comm type=%d\n",
world_type,cart_type);
printf("no topo =%d, cart top =%d\n",
MPI_UNDEFINED,MPI_CART);
}
For a Cartesian communicator, you can retrieve its information with MPI_Cartdim_get and MPI_Cart_get:
int dim;
MPI_Cartdim_get( cart_comm,&dim );
int *dimensions = (int*) malloc(dim*sizeof(int));
int *periods = (int*) malloc(dim*sizeof(int));
int *coords = (int*) malloc(dim*sizeof(int));
MPI_Cart_get( cart_comm,dim,dimensions,periods,coords );
MPI_Comm comm2d;
int periodic[ndim]; periodic[0] = periodic[1] = 0;
MPI_Cart_create(comm,ndim,dimensions,periodic,1,&comm2d);
MPI_Cart_coords(comm2d,procno,ndim,coord_2d);
MPI_Cart_rank(comm2d,coord_2d,&rank_2d);
printf("I am %d: (%d,%d); originally %d\n",
rank_2d,coord_2d[0],coord_2d[1],procno);
The reorder parameter to MPI_Cart_create indicates whether processes can have a rank in the new com-
municator that is different from in the old one.
MPI_Cart_create
( comm,dim,dimensions,periods,
0,&period_comm );
We shift process 0 in dimensions 0 and 1. In dimension 0 we get a wrapped-around source, and a target
that is the next process in row-major ordering; in dimension 1 we get MPI_PROC_NULL as source, and a
legitimate target.
Code: Output:
int pred,succ; Grid of size 6 in 3
MPI_Cart_shift ↪dimensions:
(period_comm,/* dim: */ 0,/* up: */ 1, 3 x 2 x 1
&pred,&succ); Shifting process 0.
printf("periodic dimension 0:\n src=%d, tgt=%d\n", periodic dimension 0:
pred,succ); src=4, tgt=2
MPI_Cart_shift non-periodic dimension 1:
(period_comm,/* dim: */ 1,/* up: */ 1, src=-1, tgt=1
&pred,&succ);
printf("non-periodic dimension 1:\n src=%d, tgt=%d\n",
pred,succ);
The routine MPI_Cart_sub (figure 11.5) is similar to MPI_Comm_split, in that it splits a communicator into
disjoint subcommunicators. In this case, it splits a Cartesian communicator into disjoint Cartesian commu-
nicators, each corresponding to a subset of the dimensions. This subset inherits both sizes and periodicity
from the original communicator.
Code: Output:
MPI_Cart_sub( period_comm,remain,&hyperplane ); hyperplane has dimension 2,
if (procno==0) { ↪type 2
MPI_Topo_test( hyperplane,&topo_type ); periodic: 1,0,
MPI_Cartdim_get( hyperplane,&hyperdim );
printf("hyperplane has dimension %d, type %d\n",
hyperdim,topo_type);
MPI_Cart_get( hyperplane,dim,dims,period,coords );
printf(" periodic: ");
for (int id=0; id<2; id++)
printf("%d,",period[id]);
printf("\n");
11.1.5 Reordering
The MPI_Cart_create routine has a possibility of reordering ranks. If this is applied, the routine
MPI_Cart_map gives the result of this. Given the same parameters as MPI_Cart_create, it returns the
re-ordered rank for the calling process.
Figure 11.1: Illustration of a distributed graph topology where each node has four neighbors
In many calculations on a grid (using the term in its mathematical, Finite Element Method (FEM), sense), a
grid point will collect information from grid points around it. Under a sensible distribution of the grid over
processes, this means that each process will collect information from a number of neighbor processes. The
number of neighbors is dependent on that process. For instance, in a 2D grid (and assuming a five-point
stencil for the computation) most processes communicate with four neighbors; processes on the edge with
three, and processes in the corners with two.
dist_graph_communicator
(const communicator &old_comm,
const source_set &ss, const dest_set &ds, bool reorder=true)
where:
class dist_graph_communicator::source_set : private set< pair<int,int> >
class dist_graph_communicator::dest_set : private set< pair<int,int> >
Python:
MPI.Comm.Create_dist_graph
(self, sources, degrees, destinations, weights=None, Info info=INFO_NULL, bool reorder=False)
returns graph communicator
for; that is, who this process will be sending to.1 . Consequently, some amount of processing – including
communication – is needed to build the converse information, the ranks that will be sending to a process.
MPL note 61: Distributed graph creation. The class mpl::dist_graph_communicator only has a constructor
corresponding to MPI_Dist_graph_create.
Figure 11.1 describes the common five-point stencil structure. If we let each process only describe itself,
we get the following:
• nsources= 1 because the calling process describes on node in the graph: itself.
• sources is an array of length 1, containing the rank of the calling process.
• degrees is an array of length 1, containing the degree (probably: 4) of this process.
• destinations is an array of length the degree of this process, probably again 4. The elements
of this array are the ranks of the neighbor nodes; strictly speaking the ones that this process
will send to.
• weights is an array declaring the relative importance of the destinations. For an unweighted
graph use MPI_UNWEIGHTED. In the case the graph is weighted, but the degree of a source is zero,
you can pass an empty array as MPI_WEIGHTS_EMPTY.
• reorder (int in C, LOGICAL in Fortran) indicates whether MPI is allowed to shuffle processes
to achieve greater locality.
The resulting communicator has all the processes of the original communicator, with the same ranks.
In other words MPI_Comm_size and MPI_Comm_rank gives the same values on the graph communicator, as
on the intra-communicator that it is constructed from. To get information about the grouping, use
MPI_Dist_graph_neighbors and MPI_Dist_graph_neighbors_count; section 11.2.3.
By way of example we build an unsymmetric graph, that is, an edge 𝑣1 → 𝑣2 between vertices 𝑣1 , 𝑣2 does
not imply an edge 𝑣2 → 𝑣1 .
Code:
// graph.c
for ( int i=0; i<=1; i++ ) {
int neighb_i = proci+i;
if (neighb_i<0 || neighb_i>=idim)
continue;
int j = 1-i;
int neighb_j = procj+j;
if (neighb_j<0 || neighb_j>=jdim)
continue;
destinations[ degree++ ] =
PROC(neighb_i,neighb_j,idim,jdim);
}
MPI_Dist_graph_create
(comm,
/* I specify just one proc: me */ 1,
&procno,°ree,destinations,weights,
MPI_INFO_NULL,0,
&comm2d
);
1. I disagree with this design decision. Specifying your sources is usually easier than specifying your destinations.
However, we can’t rely on the sources being ordered, so the following segment performs an explicit query
for the source neighbors:
Code: Output:
int indegree=4, sources[indegree], 0 inbound:
inweights[indegree],weighted; 1 inbound: 0
int outdegree=4, targets[outdegree], 1 inbound: 0
outweights[outdegree]; 2 inbound: 1 2
MPI_Dist_graph_neighbors_count 1 inbound: 2
(comm2d, 2 inbound: 4 3
&indegree,&outdegree,
&weighted);
MPI_Dist_graph_neighbors
(comm2d,
indegree,sources,inweights,
outdegree,targets,outweights
);
Python note 31: Graph communicators. Graph communicator creation is a method of the Comm class, and
the graph communicator is a function return result:
graph_comm = oldcomm.Create_dist_graph(sources, degrees, destinations)
Exercise 11.1. Revisit exercise 4.3 and solve it using MPI_Dist_graph_create. Use figure 11.2
for inspiration.
Use a degree value of 1.
(There is a skeleton for this exercise under the name rightgraph.)
The previous exercise can be done with a degree value of:
• 1, reflecting that each process communicates with just 1 other; or
• 2, reflecting that you really gather from two processes.
In the latter case, results do not wind up in the receive buffer in order of increasing process number as
with a traditional gather. Rather, you need to use MPI_Dist_graph_neighbors to find their sequencing; see
section 11.2.3.
Another neighbor collective is MPI_Neighbor_alltoall.
The vector variants are MPI_Neighbor_allgatherv and MPI_Neighbor_alltoallv.
There is a heterogenous (multiple datatypes) variant: MPI_Neighbor_alltoallw.
The list is: MPI_Neighbor_allgather, MPI_Neighbor_allgatherv, MPI_Neighbor_alltoall,
MPI_Neighbor_alltoallv, MPI_Neighbor_alltoallw.
11.2.3 Query
There are two routines for querying the neighbors of a process: MPI_Dist_graph_neighbors_count (fig-
ure 11.8) and MPI_Dist_graph_neighbors (figure 11.9).
While this information seems derivable from the graph construction, that is not entirely true for two
reasons.
1. With the nonadjoint version MPI_Dist_graph_create, only outdegrees and destinations are spec-
ified; this call then supplies the indegrees and sources;
2. As observed above, the order in which data is placed in the receive buffer of a gather call is not
determined by the create call, but can only be queried this way.
11.2.5 Re-ordering
Similar to the MPI_Cart_map routine (section 11.1.5), the routine MPI_Graph_map gives a re-ordered rank for
the calling process.
Some programmers are under the impression that MPI would not be efficient on shared memory, since all
operations are done through what looks like network calls. This is not correct: many MPI implementations
have optimizations that detect shared memory and can exploit it, so that data is copied, rather than going
through a communication layer. (Conversely, programming systems for shared memory such as OpenMP
can actually have inefficiencies associated with thread handling.) The main inefficiency associated with
using MPI on shared memory is then that processes can not actually share data.
The one-sided MPI calls (chapter 9) can also be used to emulate shared memory, in the sense that an
origin process can access data from a target process without the target’s active involvement. However,
these calls do not distinguish between actually shared memory and one-sided access across the network.
In this chapter we will look at the ways MPI can interact with the presence of actual shared memory.
(This functionality was added in the MPI-3 standard.) This relies on the MPI_Win windows concept, but
otherwise uses direct access of other processes’ memory.
289
12. MPI topic: Shared memory
MPI.Comm.Split_type(
self, int split_type, int key=0, Info info=INFO_NULL)
Exercise 12.1. Write a program that uses MPI_Comm_split_type to analyze for a run
1. How many nodes there are;
2. How many processes there are on each node.
If you run this program on an unequal distribution, say 10 processes on 3 nodes,
what distribution do you find?
Nodes: 3; processes: 10
TACC: Starting up job 4210429
TACC: Starting parallel tasks...
There are 3 nodes
Node sizes: 4 3 3
TACC: Shutdown complete. Exiting.
Remark 20 The OpenMPI implementation of MPI has a number of non-standard split types, such as
OMPI_COMM_TYPE_SOCKET; see https://www.open-mpi.org/doc/v4.1/man3/MPI_Comm_split_type.
3.php
MPL note 64: Split by shared memory. Similar to ordinary communicator splitting 59:
communicator::split_shared.
if (onnode_procid==0)
window_size = sizeof(double);
else window_size = 0;
MPI_Win_allocate_shared
( window_size,sizeof(double),MPI_INFO_NULL,
nodecomm,
&window_data,&node_window);
The memory allocated by MPI_Win_allocate_shared is contiguous between the processes. This makes it
possible to do address calculation. However, if a cluster node has a Non-Uniform Memory Access (NUMA)
structure, for instance if two sockets have memory directly attached to each, this would increase latency
for some processes. To prevent this, the key alloc_shared_noncontig can be set to true in the MPI_Info
object.
The following material is for the recently released MPI-4 standard and may not be supported yet.
In the contiguous case, the mpi_minimum_memory_alignment info argument (section 9.1.1) applies only to the
memory on the first process; in the noncontiguous case it applies to all.
End of MPI-4 material
// numa.c
MPI_Info window_info;
MPI_Info_create(&window_info);
MPI_Info_set(window_info,"alloc_shared_noncontig","true");
MPI_Win_allocate_shared( window_size,sizeof(double),window_info,
nodecomm,
&window_data,&node_window);
MPI_Info_free(&window_info);
Let’s explore this. We create a shared window where each process stores exactly one double, that is,
8 bytes. The following code fragment queries the window locations, and prints the distance in bytes to
the window on process 0.
for (int p=1; p<onnode_nprocs; p++) {
MPI_Aint window_sizep; int windowp_unit; double *winp_addr;
MPI_Win_shared_query( node_window,p,
&window_sizep,&windowp_unit, &winp_addr );
distp = (size_t)winp_addr-(size_t)win0_addr;
if (procno==0)
printf("Distance %d to zero: %ld\n",p,(long)distp);
With the default strategy, these windows are contiguous, and so the distances are multiples of 8 bytes.
Not so for the the non-contiguous allocation:
The explanation here is that each window is placed on its own small page, which on this particular system
has a size of 4K.
Remark 21 The ampersand operator in C is not a physical address, but a virtual address. The translation
of where pages are placed in physical memory is determined by the page table.
// sharedshared.c
MPI_Win_allocate_shared(3,sizeof(int),info,sharedcomm,&shared_baseptr,&shared_window);
While the MPI standard itself makes no mention of threads – process being the primary unit of compu-
tation – the use of threads is allowed. Below we will discuss what provisions exist for doing so.
Using threads and other shared memory models in combination with MPI leads of course to the question
how race conditions are handled. Example of a code with a data race that pertains to MPI:
#pragma omp sections
#pragma omp section
MPI_Send( x, /* to process 2 */ )
#pragma omp section
MPI_Recv( x, /* from process 3 */ )
The MPI standard here puts the burden on the user: this code is not legal, and behavior is not defined.
296
13.1. MPI support for threading
The mvapich implementation of MPI does have the required threading support, but you need to set this
environment variable:
export MV2_ENABLE_AFFINITY=0
Another solution is to run your code like this:
ibrun tacc_affinity <my_multithreaded_mpi_executable
Intel MPI uses an environment variable to turn on thread support:
I_MPI_LIBRARY_KIND=<value>
where
release : multi-threaded with global lock
release_mt : multi-threaded with per-object lock for thread-split
The mpiexec program usually propagates environment variables, so the value of OMP_NUM_THREADS when
you call mpiexec will be seen by each MPI process.
• It is possible to use blocking sends in threads, and let the threads block. This does away with
the need for polling.
• You can not send to a thread number: use the MPI message tag to send to a specific thread.
Exercise 13.1. Consider the 2D heat equation and explore the mix of MPI/OpenMP
parallelism:
• Give each node one MPI process that is fully multi-threaded.
• Give each core an MPI process and don’t use multi-threading.
Discuss theoretically why the former can give higher performance. Implement both
schemes as special cases of the general hybrid case, and run tests to find the optimal
mix.
// thread.c
MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE,&threading);
comm = MPI_COMM_WORLD;
MPI_Comm_rank(comm,&procno);
MPI_Comm_size(comm,&nprocs);
if (procno==0) {
switch (threading) {
case MPI_THREAD_MULTIPLE : printf("Glorious multithreaded MPI\n"); break;
case MPI_THREAD_SERIALIZED : printf("No simultaneous MPI from threads\n"); break;
case MPI_THREAD_FUNNELED : printf("MPI from main thread\n"); break;
case MPI_THREAD_SINGLE : printf("no threading supported\n"); break;
}
}
MPI_Finalize();
Recent versions of MPI have a standardized way of reading out performance variables: the tools interface
which improves on the old interface described in section 15.6.2.
These matching calls can be made multiple times, after MPI has already been initialized with MPI_Init or
MPI_Init_thread.
300
14.2. Control variables
// cvar.c
MPI_T_cvar_get_num(&ncvar);
printf("#cvars: %d\n",ncvar);
for (int ivar=0; ivar<ncvar; ivar++) {
char name[100]; int namelen = 100;
char desc[256]; int desclen = 256;
int verbosity,bind,scope;
MPI_Datatype datatype;
MPI_T_enum enumtype;
MPI_T_cvar_get_info
(ivar,
name,&namelen,
&verbosity,&datatype,&enumtype,desc,&desclen,&bind,&scope
);
printf("cvar %3d: %s\n %s\n",ivar,name,desc);
Remark 22 There is no constant indicating a maximum buffer length for these variables. However, you can
do the following:
1. Call the info routine with NULL values for the buffers, reading out the buffer lengths;
2. allocate the buffers with sufficient length, that is, including an extra position for the null terminator;
and
3. calling the info routine a second time, filling in the string buffers.
Conversely, given a variable name, its index can be retrieved with MPI_T_cvar_get_index:
int MPI_T_cvar_get_index(const char *name, int *cvar_index)
int name_len=256,desc_len=256,
verbosity,var_class,binding,isreadonly,iscontiguous,isatomic;
char var_name[256],description[256];
MPI_Datatype datatype; MPI_T_enum enumtype;
for (int pvar=0; pvar<npvar; pvar++) {
name_len = 256; desc_len=256;
MPI_T_pvar_get_info(pvar,var_name,&name_len,
&verbosity,&var_class,
&datatype,&enumtype,
description,&desc_len,
&binding,&isreadonly,&iscontiguous,&isatomic);
if (procid==0)
printf("pvar %d: %d/%s = %s\n",pvar,var_class,var_name,description);
}
• The readonly variable indicates that the variable can not be written.
• The continuous variable requires use of MPI_T_pvar_start and MPI_T_pvar_stop.
Given a name, the index can be retried with MPI_T_pvar_get_index:
int MPI_T_pvar_get_index(const char *name, int var_class, int *pvar_index)
(If a routine takes both a session and handle argument, and the two are not associated, an error of
MPI_T_ERR_INVALID_HANDLE is returned.)
Passing MPI_T_PVAR_ALL_HANDLES to the stop call attempts to stop all variables within the session. Failure
to stop a variable returns MPI_T_ERR_PVAR_NO_STARTSTOP.
Variables can be read and written with MPI_T_pvar_read and MPI_T_pvar_write:
int MPI_T_pvar_read
(MPI_T_pvar_session session, MPI_T_pvar_handle handle,
void* buf)
int MPI_T_pvar_write
(MPI_T_pvar_session session, MPI_T_pvar_handle handle,
const void* buf)
If the variable can not be written (see the readonly parameter of MPI_T_pvar_get_info),
MPI_T_ERR_PVAR_NO_WRITE is returned.
For a given category name the index can be found with MPI_T_category_get_index:
int MPI_T_category_get_index(const char *name, int *cat_index)
14.5 Events
// mpitevent.c
int nsource;
MPI_T_source_get_num(&nsource);
int name_len=256,desc_len=256;
char var_name[256],description[256];
MPI_T_source_order ordering;
MPI_Count ticks_per_second,max_ticks;
MPI_Info info;
MPI_Datatype datatype; MPI_T_enum enumtype;
for (int source=0; source<nsource; source++) {
name_len = 256; desc_len=256;
MPI_T_source_get_info(source,var_name,&name_len,
description,&desc_len,
&ordering,&ticks_per_second,&max_ticks,&info);
Certain MPI routines can accept MPI_Info objects. (For files, see section 15.1.1.3, for windows, see sec-
tion 9.5.4.) These contain key-value pairs that can offer system or implementation dependent information.
Info objects can be created with MPI_Info_create (figure 15.1) and deleted with MPI_Info_free (figure 15.2);
there is one info object, named MPI_INFO_ENV, which is created by MPI_Init or MPI_Init_thread; see sec-
tion 15.1.1.1.
Keys are then set with MPI_Info_set (figure 15.3), and they can be queried with MPI_Info_get (figure 15.4).
Note that the output of the ‘get’ routine is not allocated: it is a buffer that is passed. The maximum
length of a key is given by the parameter MPI_MAX_INFO_KEY. You can delete a key from an info object with
MPI_Info_delete (figure 15.5).
307
15. MPI leftover topics
Copying a communicator with MPI_Comm_dup does not cause the info to be copied; to propagate information
to the copy there is MPI_Comm_dup_with_info (section 7.2).
• MPI_File_open
• MPI_File_set_view
• MPI_File_set_info; collective. The converse routine is MPI_File_get_info.
The following keys are defined in the MPI-2 standard:
• access_style: A comma separated list of one or more of: read_once, write_once,
read_mostly, write_mostly, sequential, reverse_sequential, random
• collective_buffering: true or false; enables or disables buffering on collective I/O operations
• cb_block_size: integer block size for collective buffering, in bytes
• cb_buffer_size: integer buffer size for collective buffering, in bytes
• cb_nodes: integer number of MPI processes used in collective buffering
• chunked: a comma separated list of integers describing the dimensions of a multidimensional
array to be accessed using subarrays, starting with the most significant dimension (1st in C, last
in Fortran)
• chunked_item: a comma separated list specifying the size of each array entry, in bytes
• chunked_size: a comma separated list specifying the size of the subarrays used in chunking
• file_perm: UNIX file permissions at time of creation, in octal
• io_node_list: a comma separated list of I/O nodes to use
The following material is for the recently released MPI-4 standard and may not be supported yet.
• mpi_minimum_memory_alignment: aligment of allocated memory.
End of MPI-4 material
• nb_proc: integer number of processes expected to access a file simultaneously
• num_io_nodes: integer number of I/O nodes to use
• striping_factor: integer number of I/O nodes/devices a file should be striped across
• striping_unit: integer stripe size, in bytes
Additionally, file system-specific keys can exist.
15.1.2 Attributes
Some runtime (or installation dependendent) values are available as attributes through MPI_Comm_set_attr
(figure 15.8) and MPI_Comm_get_attr (figure 15.9) for communicators, or MPI_Win_get_attr,
MPI_Type_get_attr. (The MPI-2 routine MPI_Attr_get is deprecated). The flag parameter has two functions:
• it returns whether the attributed was found;
• if on entry it was set to false, the value parameter is ignored and the routines only tests whether
the key is present.
The return value parameter is subtle: while it is declared void*, it is actually the address of a void* pointer.
// tags.c
int tag_upperbound;
void *v; int flag=1;
ierr = MPI_Comm_get_attr(comm,MPI_TAG_UB,&v,&flag);
tag_upperbound = *(int*)v;
## tags.py
tag_upperbound = comm.Get_attr(MPI.TAG_UB)
if procid==0:
print("Determined tag upperbound: {}".format(tag_upperbound))
Attributes are:
• MPI_TAG_UB Upper bound for tag value. (The lower bound is zero.) Note that MPI_TAG_UB is the
key, not the actual upper bound! This value has to be at least 32767.
• MPI_HOST Host process rank, if such exists, MPI_PROC_NULL, otherwise. The standard does not de-
fine what it means to be a host, or even whether there should be one to begin with.
• MPI_IO rank of a node that has regular I/O facilities. Nodes in the same communicator may return
different values for this parameter. If this return MPI_ANY_SOURCE, all ranks can perform I/O.
• MPI_WTIME_IS_GLOBAL Boolean variable that indicates whether clocks are synchronized.
Also:
• MPI_UNIVERSE_SIZE: the total number of processes that can be created. This can be more than the
size of MPI_COMM_WORLD if the host list is larger than the number of initially started processes. See
section 8.1.
• MPI_APPNUM: if MPI is used in MPMD mode (section 15.9.4), or if MPI_Comm_spawn_multiple is used
(section 8.1), this attribute reports the how-manieth program we are in.
Fortran note 15: Attribute querying. Fortran has none of this double indirection stuff. The value of the
attribute is returned immediately, as an integer of kind MPI_ADDRESS_KIND:
!! tags.F90
logical :: flag
integer(KIND=MPI_ADDRESS_KIND) :: attr_v,tag_upperbound
call MPI_Comm_get_attr(comm,MPI_TAG_UB,attr_v,flag,ierr)
tag_upperbound = attr_v
print '("Determined tag upperbound: ",i9)', tag_upperbound
This uses a function type MPI_Comm_attr_function. This function is copied when a communicator is dupli-
cated; section 7.2. Free with MPI_Comm_free_keyval.
The library version can be queried with MPI_Get_library_version. The result string has to fit in
MPI_MAX_LIBRARY_VERSION_STRING.
Python note 34: MPI Version. A function is available for version and subversion, as well as explicit param-
eters:
Code: Output:
## version.py (3, 1)
print(MPI.Get_version()) 3
print(MPI.VERSION) 1
print(MPI.SUBVERSION)
• MPI errors: an MPI routine can exit prematurely for various reasons, such as receiving much more data
than its buffer can accomodate. Such errors, as well as the more common type mentioned above, typically
cause your whole execution to terminate. That is, if one incarnation of your executable exits, the MPI
runtime will kill all others.
• Deadlocks and other hanging executions: there are various scenarios where your processes individually
do not exit, but are all waiting for each other. This can happen if two processes are both waiting for a
message from each other, and this can be helped by using nonblocking calls. In another scenario, through
an error in program logic, one process will be waiting for more messages (including nonblocking ones)
than are sent to it.
While it is desirable for an MPI implementation to return an error, this is not always possible. Therefore, some
scenarios, whether supplying certain procedure arguments, or doing a certain sequence of procedure calls, are
simply marked as ‘erroneous’, and the state of MPI after an erroneous call is undefined.
Remark 23 The routine MPI_Errhandler_set is deprecated, replaced by its MPI-2 variant MPI_Comm_set_errhandler.
By default, MPI uses MPI_ERRORS_ARE_FATAL, except for file operations; see section 10.5.
Python note 36: Error policy. The policy for dealing with errors can be set through the mpi4py.rc object
(section 2.2.2):
mpi4py.rc.errors # default: "exception"
15.2.2.1 Abort
The default behavior, where the full run is aborted, is equivalent to your code having the following call to
MPI_Comm_set_errhandler(MPI_COMM_WORLD,MPI_ERRORS_ARE_FATAL);
The handler MPI_ERRORS_ARE_FATAL, even though it is associated with a communicator, causes the whole application
to abort.
The following material is for the recently released MPI-4 standard and may not be supported yet.
The handler MPI_ERRORS_ABORT (MPI-4) aborts on the processes in the communicator for which it is specified.
End of MPI-4 material
15.2.2.2 Return
Another simple possibility is to specify MPI_ERRORS_RETURN:
MPI_Comm_set_errhandler(MPI_COMM_WORLD,MPI_ERRORS_RETURN);
which causes the error code to be returned to the user. This gives you the opportunity to write code that handles
the error return value; see the next section.
For instance,
Fatal error in MPI_Waitall:
See the MPI_ERROR field in MPI_Status for the error code
You could then retrieve the MPI_ERROR field of the status, and print out an error string with MPI_Error_string or
maximal size MPI_MAX_ERROR_STRING:
MPI_Comm_set_errhandler(MPI_COMM_WORLD,MPI_ERRORS_RETURN);
ierr = MPI_Waitall(2*ntids-2,requests,status);
if (ierr!=0) {
char errtxt[MPI_MAX_ERROR_STRING];
for (int i=0; i<2*ntids-2; i++) {
int err = status[i].MPI_ERROR;
int len=MPI_MAX_ERROR_STRING;
MPI_Error_string(err,errtxt,&len);
printf("Waitall error: %d %s\n",err,errtxt);
}
MPI_Abort(MPI_COMM_WORLD,0);
}
One cases where errors can be handled is that of MPI file I/O: if an output file has the wrong permissions, code can
possibly progress without writing data, or writing to a temporary file.
MPI operators (MPI_Op) do not return an error code. In case of an error they call MPI_Abort; if MPI_ERRORS_RETURN
is the error handler, error codes may be silently ignored.
You can create your own error handler with MPI_Comm_create_errhandler (figure 15.12), which is then installed
with MPI_Comm_set_errhandler. You can retrieve the error handler with MPI_Comm_get_errhandler.
MPL note 66: Communicator errhandler. MPL does not allow for access to the wrapped communicators. However,
for MPI_COMM_WORLD, the routine MPI_Comm_set_errhandler can be called directly.
This error number is larger than MPI_ERR_LASTCODE, the upper bound on built-in error codes. The attribute
MPI_LASTUSEDCODE records the last issued value.
Your new error code is then defined in this class with MPI_Add_error_code, and an error string can be added with
MPI_Add_error_string:
int nonzero_code;
MPI_Add_error_code(nonzero_class,&nonzero_code);
MPI_Add_error_string(nonzero_code,"Attempting to send zero buffer");
You can then call an error handler with this code. For instance to have a wrapped send routine that will not send
zero-sized messages:
// errorclass.c
int MyPI_Send( void *buffer,int n,MPI_Datatype type, int target,int tag,MPI_Comm comm) {
if (n==0)
MPI_Comm_call_errhandler( comm,nonzero_code );
MPI_Ssend(buffer,n,type,target,tag,comm);
return MPI_SUCCESS;
};
Here we used the default error handler associated with the communicator, but one can set a different one with
MPI_Comm_create_errhandler.
which gives:
Trying to send buffer of length 1
.. success
Trying to send buffer of length 0
Abort(1073742081) on node 0 (rank 0 in comm 0):
Fatal error in MPI_Comm_call_errhandler: Attempting to send zero buffer
• The call for MPI_Init in Fortran does not have the commandline arguments; they need to be handled
separately.
• The routine MPI_Sizeof is only available in Fortran, it provides the functionality of the C/C++ operator
sizeof.
the wait call does not involve the buffer, so the compiler can translate this into
call MPI_Isend( buf, ..., request )
register = buf(1)
call MPI_Wait(request)
print *,register
Preventing this is possible with a Fortran2018 mechanism. First of all the buffer should be declared asynchronous
<type>,Asynchronous :: buf
and introducing
IF (.NOT. MPI_ASYNC_PROTECTS_NONBLOCKING) &
CALL MPI_F_SYNC_REG( buf )
15.4 Progress
The concept asynchronous progress describes that MPI messages continue on their way through the network, while
the application is otherwise busy.
The problem here is that, unlike straight MPI_Send and MPI_Recv calls, communication of this sort can typically not
be off-loaded to the network card, so different mechanisms are needed.
This can happen in a number of ways:
• Compute nodes may have a dedicated communications processor. The Intel Paragon was of this design;
modern multicore processors are a more efficient realization of this idea.
• The MPI library may reserve a core or thread for communications processing. This is implementation
dependent; see Intel MPI information below.
• Reserving a core, or a thread in a continuous busy-wait spin loop, takes away possible performance from
the code. For this reason, Ruhela et al. [23] propose using a pthreads signal to wake up the progress
thread.
• Absent such dedicated resources, the application can force MPI to make progress by occasional calls to
a polling routine such as MPI_Iprobe.
Remark 24 The MPI_Probe call is somewhat similar, in spirit if not quite in functionality, as MPI_Test. However, they
behave differently with respect to progress. Quoting the standard:
The MPI implementation of MPI_Probe and MPI_Iprobe needs to guarantee progress: if a call to
MPI_Probe has been issued by a process, and a send that matches the probe has been initiated by
some process, then the call to MPI_Probe will return.
In other words: probing causes MPI to make progress. On the other hand,
A call to MPI_Test returns flag = true if the operation identified by request is complete.
In other words, if progress has been made, then testing will report completion, but by itself it does not cause completion.
A similar problem arises with passive target synchronization: it is possible that the origin process may hang until
the target process makes an MPI call.
The following commands force progress: MPI_Win_test, MPI_Request_get_status.
Intel note. Only available with the release_mt and debug_mt versions of the Intel MPI library. Set
I_MPI_ASYNC_PROGRESS to 1 to enable asynchronous progress threads, and
I_MPI_ASYNC_PROGRESS_THREADS to set the number of progress threads.
See https://software.intel.com/en-us/
mpi-developer-guide-linux-asynchronous-progress-control,
https://software.intel.com/en-us/
mpi-developer-reference-linux-environment-variables-for-asynchronous-progress-control
Progress issues play with: MPI_Test, MPI_Request_get_status, MPI_Win_test.
15.6.1 Timing
MPI has a wall clock timer: MPI_Wtime (figure 15.13) which gives the number of seconds from a certain point in the
past. (Note the absence of the error parameter in the fortran call.)
MPI.Wtime()
MPI.Wtick()
double t;
t = MPI_Wtime();
for (int n=0; n<NEXPERIMENTS; n++) {
// do something;
}
t = MPI_Wtime()-t; t /= NEXPERIMENTS;
Timing in parallel is a tricky issue. For instance, most clusters do not have a central clock, so you can not relate start
and stop times on one process to those on another. You can test for a global clock as followsMPI_WTIME_IS_GLOBAL:
int *v,flag;
MPI_Attr_get( comm, MPI_WTIME_IS_GLOBAL, &v, &flag );
if (mytid==0) printf("Time synchronized? %d->%d\n",flag,*v);
Normally you don’t worry about the starting point for this timer: you call it before and after an event and subtract
the values.
t = MPI_Wtime();
// something happens here
t = MPI_Wtime()-t;
If you execute this on a single processor you get fairly reliable timings, except that you would need to subtract the
overhead for the timer. This is the usual way to measure timer overhead:
t = MPI_Wtime();
// absolutely nothing here
t = MPI_Wtime()-t;
Exercise 15.1. This scheme also has some overhead associated with it. How would you measure that?
No matter what sort of timing you are doing, it is good to know the accuracy of your timer. The routine MPI_Wtick
gives the smallest possible timer increment. If you find that your timing result is too close to this ‘tick’, you need to
find a better timer (for CPU measurements there are cycle-accurate timers), or you need to increase your running
time, for instance by increasing the amount of data.
Remark 25 This section describes MPI profiling before the introduction of the MPI tools interface. For that, see chap-
ter 14.
MPI allows you to write your own profiling interface. To make this possible, every routine MPI_Something calls a
routine PMPI_Something that does the actual work. You can now write your MPI_... routine which calls PMPI_...,
and inserting your own profiling calls. See figure 15.1.
By default, the MPI routines are defined as weak linker symbols as a synonym of the PMPI ones. In the gcc case:
#pragma weak MPI_Send = PMPI_Send
As you can see in figure 15.2, normally only the PMPI routines show up in the stack trace.
Eager limit Short blocking messages are handled by a simpler mechanism than longer. The limit on what is
considered ‘short’ is known as the eager limit (section 4.1.4.2), and you could tune your code by increasing its value.
However, note that a process may likely have a buffer accomodating eager sends for every single other process.
This may eat into your available memory.
Blocking versus nonblocking The issue of blocking versus nonblocking communication is something of a red
herring. While nonblocking communication allows latency hiding, we can not consider it an alternative to blocking
sends, since replacing nonblocking by blocking calls will usually give deadlock.
Still, even if you use nonblocking communication for the mere avoidance of deadlock or serialization (section 4.1.4.3),
bear in mind the possibility of overlap of communication and computation. This also brings us to our next point.
Looking at it the other way around, in a code with blocking sends you may get better performance from nonblocking,
even if that is not structurally necessary.
Progress MPI is not magically active in the background, especially if the user code is doing scalar work that
does not involve MPI. As sketched in section 15.4, there are various ways of ensuring that latency hiding actually
happens.
Persistent sends If a communication between the same pair of processes, involving the same buffer, happens
regularly, it is possible to set up a persistent communication. See section 5.1.
Buffering MPI uses internal buffers, and the copying from user data to these buffers may affect performance.
For instance, derived types (section 6.3) can typically not be streamed straight through the network (this requires
special hardware support [18]) so they are first copied. Somewhat surprisingly, we find that buffered communication
(section 5.5) does not help. Perhaps MPI implementors have not optimized this mode since it is so rarely used.
Graph topology and neighborhood collectives Load balancing and communication minimization are im-
portant in irregular applications. There are dedicated programs for this (ParMetis, Zoltan), and libraries such as
PETSc may offer convenient access to such capabilities.
In the declaration of a graph topology (section 11.2) MPI is allowed to reorder processes, which could be used to
support such activities. It can also serve for better message sequencing when neighborhood collectives are used.
Network issues In the discussion so far we have assumed that the network is a perfect conduit for data. However,
there are issues of port design, in particular caused by oversubscription that adversely affect performance. While in
an ideal world it may be possible to set up routine to avoid this, in the actual practice of a supercomputer cluster,
network contention or message collision from different user jobs is hard to avoid.
Offloading and onloading There are different philosophies of network card design: Mellanox, being a network
card manufacturer, believes in off-loading network activity to the Network Interface Card (NIC), while Intel, being
a processor manufacturer, believes in ‘on-loading’ activity to the process. There are argument either way.
15.6.4 MPIR
MPIR is the informally specified debugging interface for processes acquisition and message queue extraction.
15.7 Determinism
MPI processes are only synchronized to a certain extent, so you may wonder what guarantees there are that running
a code twice will give the same result. You need to consider two cases: first of all, if the two runs are on different
numbers of processors there are already numerical problems; see HPC book, section-3.6.5.
Let us then limit ourselves to two runs on the same set of processors. In that case, MPI is deterministic as long as you
do not use wildcards such as MPI_ANY_SOURCE. Formally, MPI messages are ‘nonovertaking’: two messages between
the same sender-receiver pair will arrive in sequence. Actually, they may not arrive in sequence: they are matched
in sequence in the user program. If the second message is much smaller than the first, it may actually arrive earlier
in the lower transport layer.
When the barrier is reached, the receive has been posted, so it is safe to do a ready send. However, global barriers
are not a good idea. Instead you would just synchronize the two processes involved.
Exercise 15.2. Give pseudo-code for a scheme where you synchronize the two processes through the
exchange of a blocking zero-size message.
The name of the variable is implementation dependent, for mpich and its derivates such as Intel MPI it is PMI_RANK.
(There is a similar PMI_SIZE.)
If you are only interested in displaying the rank
• srun has an option --label.
as
mpiexec -n 4 ./abort ; \
echo "Return code from ${MPIRUN} is <<$$?>>"
gives
TACC: Starting up job 3760534
TACC: Starting parallel tasks...
application called MPI_Abort(MPI_COMM_WORLD, 37) - process 3
TACC: MPI job exited with code: 37
TACC: Shutdown complete. Exiting.
Return code from ibrun is <<37>>
• MPI_MAX_DATAREP_STRING
• MPI_MAX_INFO_KEY
• MPI_MAX_INFO_VAL
• MPI_MAX_OBJECT_NAME
• MPI_MAX_PORT_NAME
• MPI_VERSION
• MPI_SUBVERSION
Fortran note 16: Fortran-only compile-time constants.
• MPI_STATUS_SIZE. No longer needed with Fortran2008 support; see section 8.
• MPI_ADDRESS_KIND
• MPI_COUNT_KIND
• MPI_INTEGER_KIND
• MPI_OFFSET_KIND
• MPI_SUBARRAYS_SUPPORTED
• MPI_ASYNC_PROTECTS_NONBLOCKING
The following are the link-time constants:
• MPI_BOTTOM
• MPI_STATUS_IGNORE
• MPI_STATUSES_IGNORE
• MPI_ERRCODES_IGNORE
• MPI_IN_PLACE
• MPI_ARGV_NULL
• MPI_ARGVS_NULL
• MPI_UNWEIGHTED
• MPI_WEIGHTS_EMPTY
Assorted constants:
• MPI_PROC_NULL and other ..._NULL constants.
• MPI_ANY_SOURCE
• MPI_ANY_TAG
• MPI_UNDEFINED
• MPI_BSEND_OVERHEAD
• MPI_KEYVAL_INVALID
• MPI_LOCK_EXCLUSIVE
• MPI_LOCK_SHARED
• MPI_ROOT
(This section was inspired by http://blogs.cisco.com/performance/mpi-outside-of-c-and-fortran.)
// cancel.c
fprintf(stderr,"get set, go!\n");
if (procno==nprocs-1) {
MPI_Status status;
MPI_Recv(dummy,0,MPI_INT, MPI_ANY_SOURCE,0,comm,
&status);
first_tid = status.MPI_SOURCE;
MPI_Bcast(&first_tid,1,MPI_INT, nprocs-1,comm);
fprintf(stderr,"[%d] first msg came from %d\n",procno,first_tid);
} else {
float randomfraction = (rand() / (double)RAND_MAX);
int randomwait = (int) ( nprocs * randomfraction );
MPI_Request request;
fprintf(stderr,"[%d] waits for %e/%d=%d\n",
procno,randomfraction,nprocs,randomwait);
sleep(randomwait);
MPI_Isend(dummy,0,MPI_INT, nprocs-1,0,comm,
&request);
MPI_Bcast(&first_tid,1,MPI_INT, nprocs-1,comm
);
if (procno!=first_tid) {
MPI_Cancel(&request);
fprintf(stderr,"[%d] canceled\n",procno);
}
}
After the cancelling operation it is still necessary to call MPI_Request_free, MPI_Wait, or MPI_Test in order to free
the request object.
The MPI_Cancel operation is local, so it can not be used for nonblocking collectives or one-sided transfers.
15.11 Literature
Online resources:
• MPI 1 Complete reference:
http://www.netlib.org/utk/papers/mpi-book/mpi-book.html
• Official MPI documents:
http://www.mpi-forum.org/docs/
• List of all MPI routines:
http://www.mcs.anl.gov/research/projects/mpi/www/www3/
Tutorial books on MPI:
• Using MPI [12] by some of the original authors.
MPI Examples
Figure 16.1 illustrates the ‘intra’ (left) and ‘inter’ (right) scheme for letting all processes communicate in pairs. With
intra-communication, the messages do not rely on the network so we expect to measure high bandwidth. With
inter-communication, all messages go through the network and we expect to measure a lower number.
However, there are more issues to explore, which we will now do.
First of all we need to find pairs of processes. Consecutive pairs:
330
16.1. Bandwidth and halfbandwidth
// halfbandwidth.cxx
int sender = procid - procid%2, receiver = sender+1;
400 379
25.5
25
20.3 20.7 300
20 19.4
msec
15 200 189
132
10 99.4
100
5
0 0
14 20 28 56 14 20 28 56
#cores per node #cores per node
Figure 16.2: Time as a function of core count. Left: on node. Right: between nodes.
The halfbandwidth is measured as the total number of bytes sent divided by the total time. Both numbers are
measured outside a repeat loop that does each transaction 100 times.
auto duration = myclock::now()-start_time;
auto microsec_duration = std::chrono::duration_cast<std::chrono::microseconds>(duration);
int total_ping_count;
MPI_Allreduce(&pingcount,&total_ping_count,1,MPI_INT,MPI_SUM,comm);
long bytes = buffersize * sizeof(double) * total_ping_count;
float fsec = microsec_duration.count() * 1.e-6,
halfbandwidth = bytes / fsec;
In the left graph of figure 16.2 we see that the time for 𝑃/2 simultaneous pingpongs stays fairly constant. This
reflects the fact that, on node, the pingpong operations are data copies, which proceed simultaneously. Thus, the
time is independent of the number of cores that are moving data. The exception is the final data point: with all cores
active we take up more than the available bandwidth on the node.
In the right graph, each pingpong is inter-node, going through the network. Here we see the runtime go up linearly
with the number of pingpongs, or somewhat worse than that. This reflects the fact that network transfers are done
sequentially. (Actually, message can be broken up in packets, as long as they satisfy MPI message semantics. This
does not alter our argument.)
Next we explore the influence of the buffer size on performance. The right graph in figure 16.3 show that inter-node
bandwidth is almost independent of the buffer size. This means that even our smallest buffer is large enough to
overcome any MPI startup cost.
400 40
350
300 30
23
Gbyte/sec
240 21 22 22
20
20 17
200
145 146
130
10
100
42
0
0
1000 3000 10000 30000 10000003000000 1000 3000 10000 30000 10000003000000
buffer size buffer size
Figure 16.3: Bandwidth as a function of buffer size. Left: on node. Right: between nodes.
On other hand, the left graph shows a more complicated pattern. Initially, the bandwidth increases, possibly reflect-
ing the decreasing importance of MPI startup. For the final data points, however, performance drops again. This is
due to the fact that the data size overflows cache size, and we are dominated by bandwidth from memory, rather
than cache.
OPENMP
This section of the book teaches OpenMP (‘Open Multi Processing’), the dominant model for shared memory pro-
gramming in science and engineering. It will instill the following competencies.
Basic level:
• Threading model: the student will understand the threading model of OpenMP, and the relation between
threads and cores (chapter 17); the concept of a parallel region and private versus shared data (chapter 18).
• Loop parallelism: the student will be able to parallelize loops, and understand the impediments to paral-
lelization, and iteration scheduling (chapter 19; reductions (chapter 20).
• The student will understand the concept of worksharing constructs, and its implications for synchro-
nization (chapter 21).
Intermediate level:
• The student will understand the abstract notion of synchronization, its implementations in OpenMP, and
implications for performance (chapter 23).
• The student will understand the task model as underlying the thread model, be able to write code that
spawns tasks, and be able to distinguish when tasks are needed versus simpler worksharing constructs
(chapter 24).
• The student will understand thread/code affinity, how to control it, and possible implications for perfor-
mance (chapter 25).
Advanced level:
• The student will understand the OpenMP memory model, and sequential consistency (chapter 28.8).
• The student will understand SIMD processing, the extent to which compilers do this outside of OpenMP,
and how OpenMP can specify further opportunities for SIMD-ization (chapter 26).
• The student will understand offloading to Graphics Processing Units (GPUs), and the OpenMP directives
for effecting this (chapter 27).
This chapter explains the basic concepts of OpenMP, and helps you get started on running your first OpenMP
program.
Figure 17.1 pictures a typical design of a node: within one enclosure you find two sockets, single processor chips,
plus an accelerator. (The picture is of a node of the TACC Stampede cluster no longer in serivce, with two sockets
and an Intel Xeon PHI co-processor.)
337
17. Getting started with OpenMP
Your personal laptop or desktop computer will probably have one socket, most supercomputers have nodes with
two or four sockets. In either case there can be a GPU as co-processor; supercomputer clusters can also have other
types of accelerators. OpenMP versions as of OpenMP-4.0 target such offloadable devices.
To see where OpenMP operates we need to dig into the sockets. Figure 17.2 shows a picture of an Intel Sandybridge
socket. You recognize a structure with eight cores: independent processing units, that all have access to the same
memory. (In figure 17.1 you saw four memory chips, or DIMMs, attached to each of the two sockets; all of the sixteen
cores have access to all that memory.) OpenMP makes it easy to explore all these cores in the same program. The
OpenMP-5.0 standard also added the possibility to offload computations to the GPU or other accelerator.
To summarize the structure of the architecture that OpenMP targets:
• A node has a number of sockets, typically 1, 2, or 4;
• each socket has a number of cores, as of 2022 this can be up to 64;
• each core is an independent processing unit, with access to all the memory on the node.
• There can be an accelerator, which can be used to offload computations to.
go away and the original thread is left (‘join’), but while the team of threads created by the fork exists, you have
parallelism available to you. The part of the execution between fork and join is known as a parallel region.
Figure 17.3 gives a simple picture of this: a thread forks into a team of threads, and these threads themselves can
fork again.
The threads that are forked are all copies of the master thread: they have access to all that was computed so far;
this is their shared data. Of course, if the threads were completely identical the parallelism would be pointless, so
they also have private data, and they can identify themselves: they know their thread number. This allows you to
do meaningful parallel computations with threads.
This brings us to the third important concept: that of work sharing constructs. In a team of threads, initially there
will be replicated execution; a work sharing construct divides available work over the threads.
So there you have it: OpenMP uses teams of threads, and inside a parallel region the work is
distributed over the threads with a work sharing construct. Threads can access shared data,
and they have some private data.
An important difference between OpenMP and MPI is that parallelism in OpenMP is dynamically activated by a
thread spawning a team of threads. Furthermore, the number of threads used can differ between parallel regions,
and threads can create threads recursively. This is known as as dynamic mode. By contrast, in an MPI program the
number of running processes is (mostly) constant throughout the run, and determined by factors external to the
program.
#include "omp.h"
or
#include "omp_lib.h"
OpenMP is handled by extensions to your regular compiler, typically by adding an option to your commandline:
# gcc
gcc -o foo foo.c -fopenmp
# Intel compiler
icc -o foo foo.c -qopenmp
If you have separate compile and link stages, you need that option in both.
When you use the above compiler options, the OpenMP macro, (or cpp macro) _OPENMP will be defined. Thus, you
can have conditional compilation by writing
#ifdef _OPENMP
...
#else
...
#endif
The value of this macro is a decimal value yyyymm denoting the OpenMP standard release that this compiler sup-
ports; see section 28.7.
Fortran note 17: OpenMP version. The parameter openmp_version contains the version in yyyymm format.
!! version.F90
integer :: standard
standard = openmp_version
17.3.1 Directives
OpenMP is not magic, so you have to tell it when something can be done in parallel. This is mostly done through
directives; additional specifications can be done through library calls.
In C/C++ the pragma mechanism is used: annotations for the benefit of the compiler that are otherwise not part of
the language. This looks like:
#pragma omp somedirective clause(value,othervalue)
statement;
with
• the #pragma omp sentinel to indicate that an OpenMP directive is coming;
• a directive, such as parallel;
• and possibly clauses with values.
• After the directive comes either a single statement or a block in curly braces.
Directives in C/C++ are case-sensitive. Directives can be broken over multiple lines by escaping the line end.
Fortran note 18: OpenMP sentinel. The sentinel in Fortran looks like a comment:
!$omp directive clause(value)
statements
!$omp end directive
The difference with the C directive is that Fortran does not have code blocks, so there is an explicit end-of
directive line.
If you break a directive over more than one line, all but the last line need to have a continuation character,
and each line needs to have the sentinel:
!$omp parallel &
!$omp num_threads(7)
tp = omp_get_thread_num()
!$omp end parallel
The directives are case-insensitive. In Fortran fixed-form source files (which is the only possibility in
Fortran77), c$omp and *$omp are allowed too.
Exercise 17.1. Write a ‘hello world’ program, where the print statement is in a parallel region.
Compile and run.
Run your program with different values of the environment variable OMP_NUM_THREADS. If
you know how many cores your machine has, can you set the value higher?
Let’s start exploring how OpenMP handles parallelism, using the following functions:
• omp_get_num_threads reports how many threads are currently active, and
• omp_get_thread_num reports the number of the thread that makes the call.
• omp_get_num_procs reports the number of available cores.
Exercise 17.2. Take the hello world program of exercise 17.1 and insert the above functions, before,
in, and after the parallel region. What are your observations?
Exercise 17.3. Extend the program from exercise 17.2. Make a complete program based on these
lines:
Code: Output:
// reduct.c With 4 threads, sum s/b 6
int tsum=0; Sum is 6
#pragma omp parallel Sum is 5
{ Sum is 1
tsum += // expression Sum is 4
} Sum is 6
printf("Sum is %d\n",tsum); Sum is 5
Sum is 6
Sum is 5
Sum is 3
Sum is 4
Compile and run again. (In fact, run your program a number of times.) Do you see
something unexpected? Can you think of an explanation?
If the above puzzles you, read about race conditions in HPC book, section-2.6.1.5.
main () {
// no variable `x' define here
{
int x = 5;
if (somecondition) { x = 6; }
printf("x=%e\n",x); // prints 5 or 6
}
printf("x=%e\n",x); // syntax error: `x' undefined
}
Fortran has simpler rules, since it does not have blocks inside blocks.
OpenMP has similar rules concerning data in parallel regions and other OpenMP constructs. First of all, data is
visible in enclosed scopes:
main() {
int x;
#pragma omp parallel
{
// you can use and set `x' here
}
printf("x=%e\n",x); // value depends on what
// happened in the parallel region
}
There is an important difference: each thread in the team gets its own instance of the enclosed variable.
This is illustrated in figure 17.4.
In addition to such scoped variables, which live on a stack, there are variables on the heap, typically created by a
call to malloc (in C) or new (in C++). Rules for them are more complicated.
Summarizing the above, there are
• shared variables, where each thread refers to the same data item, and
• private variables, where each thread has its own instance.
In addition to using scoping, OpenMP also uses options on the directives to control whether data is private or shared.
Many of the difficulties of parallel programming with OpenMP stem from the use of shared variables. For instance,
if two threads update a shared variable, there is no guarantee an the order on the updates.
We will discuss all this in detail in section 22.
To ask how much parallelism is actually used in your parallel region, use omp_get_num_threads. To query these hard-
ware limits, use omp_get_num_procs. You can query the maximum number of threads with omp_get_max_threads.
This equals the value of OMP_NUM_THREADS, not the number of actually active threads in a parallel region.
Another limit on the number of threads is imposed when you use nested parallel regions. This can arise if you have
a parallel region in a subprogram which is sometimes called sequentially, sometimes in parallel. For details, see
section 18.2.
It would be pointless to have the block be executed identically by all threads. One way to get a meaningful parallel
code is to use the function omp_get_thread_num to find out which thread you are, and execute work that is individual
to that thread. This function gives a number relative to the current team; recall from figure 17.3 that new teams can
be created recursively.
There is also a function omp_get_num_threads to find out the total number of threads.
The first thing we want to do is create a team of threads. This is done with a parallel region. Here is a very simple
example where each thread outputs its number:
Code: Output:
// hello.c Hello world from 1!
#pragma omp parallel Hello world from 0!
{ Hello world from 2!
int t = omp_get_thread_num(); Hello world from 3!
printf("Hello world from %d!\n",t);
}
or in Fortran
Code: Output:
!! hello.F90 Missing output for helloompf
!$omp parallel
print *,"Hello world!"
!$omp end parallel
C++ note 2: Output streams in parallel. The use of cout may give jumbled output:lines can break at each <<.Use
stringstream to form a single stream to output.
347
18. OpenMP topic: Parallel regions
// hello.cxx
#pragma omp parallel
{
int t = omp_get_thread_num();
stringstream proctext;
proctext << "Hello world from " << t << endl;
cerr << proctext.str();
}
C++ note 3: Parallel regions in lambdas. OpenMP parallel regions can be in functions, including lambda expres-
sions.
const int s = [] () {
int s;
# pragma omp parallel
# pragma omp master
s = 2 * omp_get_num_threads();
return s; }();
Remark 27 In future versions of OpenMP, the master thread will be called the primary thread. In 5.1 the master
construct will be deprecated, and masked (with added functionality) will take its place. In 6.0 master will disappear from
the Spec, including proc_bind master “variable” and combined master constructs (master taskloop, etc.)
Exercise 18.1. What happens if you call omp_get_thread_num and omp_get_num_threads outside a
parallel region?
What happens if you call a function from inside a parallel region, and that function itself contains a parallel region?
int main() {
...
#pragma omp parallel
{
...
func(...)
...
}
} // end of main
void func(...) {
#pragma omp parallel
{
...
}
}
Since any thread can create a team, you may expect that every thread, in its call to func, will create its own new
team. This is called nested parallelism and it works as described.
However, by default, the nested parallel region will have only one thread. You need to allow non-trivial nested
parallelism explicitly.
To allow nested thread creation, use the environment variable OMP_MAX_ACTIVE_LEVELS (default: 1) to set
the number of levels of parallel nesting. Equivalently, there are functions omp_set_max_active_levels and
omp_get_max_active_levels:
OMP_MAX_ACTIVE_LEVELS=3
or
void omp_set_max_active_levels(int);
int omp_get_max_active_levels(void);
Remark 28 A deprecated mechanism is to set the environment variable OMP_NESTED (default: false) or its corresponding
function:
OMP_NESTED=true
or
omp_set_nested(1)
Nested parallelism can happen with nested loops, but it’s also possible to have a sections construct and a loop
nested. Example:
Code: Output:
// sectionnest.c Nesting: false
#pragma omp parallel sections reduction(+:s) Threads: 2, speedup: 2.0
{ Threads: 4, speedup: 2.0
#pragma omp section Threads: 8, speedup: 2.0
{ Threads: 12, speedup: 2.0
double s1=0; Nesting: true
omp_set_num_threads(team); Threads: 2, speedup: 1.8
#pragma omp parallel for reduction(+:s1) Threads: 4, speedup: 3.7
for (int i=0; i<N; i++) { Threads: 8, speedup: 6.9
Threads: 12, speedup: 10.4
the body of the function f falls in the dynamic scope of the parallel region, so the for loop will be parallelized.
If the function may be called both from inside and outside parallel regions, you can test which is the case with
omp_in_parallel.
C++ note 4: Dynamic scope for class methods. Dynamic scope holds for class methods as for any other function:
Code: Output:
// nested.cxx executing: OMP_MAX_ACTIVE_LEVELS=2
class c { ↪OMP_PROC_BIND=true OMP_NUM_THREADS=2
public: ↪./nested
void f() { 2
cout 2
<< omp_get_num_threads()
<< '\n';
};
};
int main() {
c my_object;
#pragma omp parallel
my_object.f();
In effect, this is how you would parallelize a loop in MPI: the parallel pragma creates a team of threads, each thread
executes the block of code, and based on its thread number finds a unique block of work to do.
Exercise 19.1. What are some important differences between the resulting OpenMP and MPI code?
353
19. OpenMP topic: Loop parallelism
Remark 29 In this example the loop variable is declared in the loop header, as is the preferred practice, but if you don’t
do it this way, the loop variable is automatically made private to the threads.
Leaving the work distribution to OpenMP has several advantages. For one, you don’t have to calculate the loop
segments for the threads yourself, but you can also tell OpenMP to assign the loop iterations according to different
schedules (section 19.3).
Fortran note 19: OMP do pragma. The for pragma only exists in C; there is a correspondingly named do pragma in
Fortran.
$!omp parallel
$!omp do
do i=1,N
! something with i
end do
$!omp end do
$!omp end parallel
It is important to realize that the parallel directive does not immediately distribute any work: all threads start
out executing the same code. As an illustration, figure 19.1 shows the execution on four threads of code that has
instructions between the parallel and for directives:
The code before and after the loop is executed identically in each thread; the loop iterations are spread over the four
threads.
The do and for pragmas do not themselves create parallelism: they take the team of threads that is active, and
divide the loop iterations over them. This means that the omp for or omp do directive needs to be inside a parallel
region. Outside of a parallel region they would execute sequentially.
As an illustration:
Code: Output:
// parfor.c %%%% equal thread/core counts %%%%
#pragma omp parallel Threads entering parallel region: 4
{ thread 3 executing iter 3
int Threads entering parallel region: 4
nthreads = omp_get_num_threads(), thread 0 executing iter 0
thread_num = omp_get_thread_num(); Threads entering parallel region: 4
printf("Threads entering parallel region: thread 2 executing iter 2
↪%d\n", Threads entering parallel region: 4
nthreads); thread 1 executing iter 1
#pragma omp for
for (int iter=0; iter<nthreads; iter++)
printf("thread %d executing iter %d\n",
thread_num,iter);
}
Exercise 19.2. What would happen in the above example if you increase the number of threads to be
larger than the number of cores?
It is also possible to have a combined omp parallel for or omp parallel do directive.
#pragma omp parallel for
for (int i=0; .....
C++ note 5: Custom iterators. OpenMP can parallelize any range-based loop with a random-access iterator.
// iterator.cxx
class NewVector {
public:
// iterator stuff
class iter;
iter begin();
iter end();
};
The following methods are needed for the contained iter class:
NewVector::iter& operator++();
int& operator*();
bool operator==( const NewVector::iter &other ) const;
bool operator!=( const NewVector::iter &other ) const;
// needed to OpenMP
int operator-( const NewVector::iter& other ) const;
NewVector::iter& operator+=( int add );
Remark 30 The loop index needs to be an integer value for the loop to be parallelizable. Unsigned values are allowed
as of OpenMP-3.
The iterations of this loop are independent, and hence can be computed in parallel in any order, if the right-hand-side
expression does not contain any references to x, or at best x[i].
Leaving considerations of the right-hand-side expression aside, we can more generally say that a loop is paralleliz-
able if in
for (int i=low; i<hi; i++)
x[ f(i) ] = // expression
Argue that this does not satisfy the above consition. Can you rewrite this loop to be
parallelizable?
19.1.4 Exercises
Exercise 19.4. Compute 𝜋 by numerical integration. We use the fact that 𝜋 is the area of the unit
circle, and we approximate this by computing the area of a quarter circle using Riemann
sums.
• Let 𝑓 (𝑥) = √1 − 𝑥 2 be the function that describes the quarter circle for 𝑥 = 0 … 1;
• Then we compute
𝑁 −1
𝜋/4 ≈ ∑ Δ𝑥𝑓 (𝑥𝑖 ) where 𝑥𝑖 = 𝑖Δ𝑥 and Δ𝑥 = 1/𝑁
𝑖=0
Write a program for this, and parallelize it using OpenMP parallel for directives.
1. Put a parallel directive around your loop. Does it still compute the right result? Does
the time go down with the number of threads? (The answers should be no and no.)
2. Change the parallel to parallel for (or parallel do). Now is the result correct?
Does execution speed up? (The answers should now be no and yes.)
3. Put a critical directive in front of the update. (Yes and very much no.)
4. Remove the critical and add a clause reduction(+:quarterpi) to the for directive.
Now it should be correct and efficient.
Use different numbers of cores and compute the speedup you attain over the sequential
computation. Is there a performance difference between the OpenMP code with 1 thread and
the sequential code?
Remark 31 In this exercise you may have seen the runtime go up a couple of times where you weren’t expecting it.
The issue here is false sharing; see HPC book, section-3.6.5 for more explanation.
19.2 An example
To illustrate the speedup of perfectly parallel calculations, we consider a simple code that applies the same calcula-
tion to each element of an array.
All tests are done on the TACC Frontera cluster, which has dual-socket Intel Cascade Lake nodes, with a total of 56
cores. We control affinity by setting OMP_PROC_BIND=true.
Here is the essential code fragment:
// speedup.c
#pragma omp parallel for
for (int ip=0; ip<N; ip++) {
for (int jp=0; jp<M; jp++) {
double f = sin( values[ip] );
values[ip] = f;
}
}
Exercise 19.5. Verify that the outer loop is parallel, but the inner one is not.
Exercise 19.6. Compare the time for the sequential code and the single-threaded OpenMP code. Try
different optimization levels, and different compilers if you have them.
• Do you sometimes get a significant difference? What would be an explanation?
• Does your compiler have a facility for generating optimization reports? For instance
-qoptreport=5 for the Intel compiler.
Now we investigate the influence of two parameters:
1. the OpenMP thread count: while we have 56 cores, values larger than that are allowed; and
2. the size of the problem: the smaller the problem, the larger the relative overhead of creating and syn-
chronizing the team of threads.
We execute the above computation several times to even out effects of cache loading.
The results are in figure 19.2:
• While the problem size is always larger than the number of threads, only for the largest problem, which
has at least 400 points per thread, is the speedup essentially linear.
• OpenMP allows for the number of threads to be larger than the core count, but there is no performance
improvement in doing so.
The above tests did not use hyperthreads, since that is disabled on Frontera. However, the Intel Knights Landing
nodes of the TACC Stampede2 cluster have four hyperthreads per core. Table 19.3 shows that this will indeed give a
modest speedup.
For reference, the commandlines executed were:
# frontera
make localclean run_speedup EXTRA_OPTIONS=-DN=200 NDIV=8 NP=112
make localclean run_speedup EXTRA_OPTIONS=-DN=2000 NDIV=8 NP=112
make localclean run_speedup EXTRA_OPTIONS=-DN=20000 NDIV=8 NP=112
# stampede2
make localclean run_speedup NDIV=8 EXTRA_OPTIONS="-DN=200000 -DM=1000" NP=272
C++ note 6: Range syntax. Parallel loops in C++ can use range-based syntax as of OpenMP-5.0:
// vecdata.cxx
#pragma omp parallel for
for ( auto& elt : values ) {
elt = 5.f;
}
float sum{0.f};
#pragma omp parallel for reduction(+:sum)
60 𝑁 = 200
55.42 𝑁 = 2000
𝑁 = 20000
48.5
41.75
40.4 41.61 41.55
34.81
33.2
Speedup
1 14 28 42 56 70 84 98 112
#Threads
Tests not reported here show exactly the same speedup as the C code.
C++ note 7: C++20 ranges header. The C++20 ranges library is also supported:
// range.cxx
# pragma omp parallel for reduction(+:count)
for ( auto e : data )
count += e;
# pragma omp parallel for reduction(+:count)
for ( auto e : data
| std::ranges::views::drop(1) )
count += e;
# pragma omp parallel for reduction(+:count)
for ( auto e : data
| std::ranges::views::transform
( []( auto e ) { return 2*e; } ) )
count += e;
𝑁 = 200
43.2
39.7
38.1
36.8
33.7
29.7
Speedup
20.6
20
10.4
10
5
1 0.32
The first distinction we now have to make is between static and dynamic schedules. With static schedules, the
iterations are assigned purely based on the number of iterations and the number of threads (and the chunk parameter;
see later). In dynamic schedules, on the other hand, iterations are assigned to threads that are unoccupied. Dynamic
schedules are a good idea if iterations take an unpredictable amount of time, so that load balancing is needed.
Figure 19.4 illustrates this: assume that each core gets assigned two (blocks of) iterations and these blocks take
gradually less and less time. You see from the left picture that thread 1 gets two fairly long blocks, where as thread 4
gets two short blocks, thus finishing much earlier. (This phenomenon of threads having unequal amounts of work
is known as load imbalance.) On the other hand, in the right figure thread 4 gets block 5, since it finishes the first
set of blocks early. The effect is a perfect load balancing.
The default static schedule is to assign one consecutive block of iterations to each thread. If you want different sized
blocks you can define a chunk size:
#pragma omp for schedule(static[,chunk])
(where the square brackets indicate an optional argument). With static scheduling, the compiler will determine
the assignment of loop iterations to the threads at compile time, so, provided the iterations take roughly the same
amount of time, this is the most efficient at runtime.
The choice of a chunk size is often a balance between the low overhead of having only a few chunks, versus the
load balancing effect of having smaller chunks.
Exercise 19.7. Why is a chunk size of 1 typically a bad idea? (Hint: think about cache lines, and read
HPC book, section-1.4.2.)
In dynamic scheduling OpenMP will put blocks of iterations (the default chunk size is 1) in a task queue, and the
threads take one of these tasks whenever they are finished with the previous.
#pragma omp for schedule(static[,chunk])
While this schedule may give good load balancing if the iterations take very differing amounts of time to execute,
it does carry runtime overhead for managing the queue of iteration tasks.
Finally, there is the guided schedule, which gradually decreases the chunk size. The thinking here is that large
chunks carry the least overhead, but smaller chunks are better for load balancing. The various schedules are illus-
trated in figure 19.5.
If you don’t want to decide on a schedule in your code, you can specify the runtime schedule. The actual schedule
will then at runtime be read from the OMP_SCHEDULE environment variable. You can even just leave it to the runtime
library by specifying auto
Exercise 19.8. Write a simple prime number tester and a loop that counts primes:
// primesched.c
for (int n = 0; n < N; n++) {
if (is_prime(n))
j++;
}
Do you expect a dynamic schedule to be better than a static one? Finish the program and
test with different schedules.
Exercise 19.9. We continue with exercise 19.4. We add ‘adaptive integration’: where needed, the
program refines the step size1 . This means that the iterations no longer take a predictable
amount of time.
1. Use the omp parallel for construct to parallelize the loop. As in the previous lab, you
may at first see an incorrect result. Use the reduction clause to fix this.
2. Your code should now see a decent speedup, but possible not for all cores. It is possible
to get completely linear speedup by adjusting the schedule.
Start by using schedule(static,n). Experiment with values for 𝑛. When can you get a
better speedup? Explain this.
1. It doesn’t actually do this in a mathematically sophisticated way, so this code is more for the sake of the example.
3. Since this code is somewhat dynamic, try schedule(dynamic). This will actually give a
fairly bad result. Why? Use schedule(dynamic,$n$) instead, and experiment with
values for 𝑛.
4. Finally, use schedule(guided), where OpenMP uses a heuristic. What results does that
give?
Exercise 19.10. Program the LU factorization algorithm without pivoting.
for k=1,n:
A[k,k] = 1./A[k,k]
for i=k+1,n:
A[i,k] = A[i,k]/A[k,k]
for j=k+1,n:
A[i,j] = A[i,j] - A[i,k]*A[k,j]
Its mirror call is omp_set_schedule, which sets the value that is used when schedule value runtime is used. It is in
effect equivalent to setting the environment variable OMP_SCHEDULE.
void omp_set_schedule (omp_sched_t kind, int modifier);
Here are the various schedules you can set with the schedule clause:
affinity Set by using value omp_sched_affinity
auto The schedule is left up to the implementation. Set by using value omp_sched_auto
static value: 1. The modifier parameter is the chunk size. Can also be set by using value omp_sched_static
dynamic value: 2. The modifier parameter is the chunk size; default 1. Can also be set by using value
omp_sched_dynamic
guided Value: 3. The modifier parameter is the chunk size. Set by using value omp_sched_guided
runtime Use the value of the OMP_SCHEDULE environment variable. Set by using value omp_sched_runtime
19.4 Reductions
So far we have focused on loops with independent iterations. Reductions are a common type of loop with depen-
dencies. There is an extended discussion of reductions in chapter 20.
all 𝑁 2 iterations are independent, but a regular omp for directive will only parallelize one level. The collapse clause
will parallelize more than one level:
#pragma omp for collapse(2)
for ( int i=0; i<N; i++ )
for ( int j=0; j<N; j++ )
A[i][j] = B[i][j] + C[i][j]
It is only possible to collapse perfectly nested loops, that is, the loop body of the outer loop can consist only of the
inner loop; there can be no statements before or after the inner loop in the loop body of the outer loop. That is, the
two loops in
for ( int i=0; i<N; i++ ) {
y[i] = 0.;
for ( int j=0; j<N; j++)
y[i] += A[i][j] * x[j]
}
it is not true that all function evaluations happen more or less at the same time, followed by all print statements.
The print statements can really happen in any order. The ordered clause coupled with the ordered directive can
force execution in the right order:
#pragma omp parallel for ordered
for ( ... i ... ) {
... f(i) ...
#pragma omp ordered
printf("something with %d\n",i);
}
There is a limitation: each iteration can encounter only one ordered directive.
19.7 nowait
An OpenMP loop is a worksharing construct, after which execution in the parallel region goes back to replicated
execution. To synchronize this, OpenMP inserts a barrier, meaning that threads wait for each other to reach this
point. See section 23.1.1 for details.
The implicit barrier at the end of a work sharing construct can be cancelled with a nowait clause. This has the effect
that threads that are finished can continue with the next code in the parallel region:
#pragma omp parallel
{
#pragma omp for nowait
for (int i=0; i<N; i++) {
...
}
// more parallel code
}
In the following example, threads that are finished with the first loop can start on the second. Note that this requires
both loops to have the same schedule. We specify the static schedule here to have an identical scheduling of iterations
over threads:
#pragma omp parallel
{
x = local_computation()
#pragma omp for schedule(static) nowait
for (int i=0; i<N; i++) {
x[i] = ...
}
#pragma omp for schedule(static)
for (int i=0; i<N; i++) {
y[i] = ... x[i] ...
}
}
We replace the while loop by a for loop that examines all locations:
result = -1;
#pragma omp parallel for
for (int i=0; i<imax; i++) {
if (a[i]!=0 && result<0) result = i;
}
You have now solved a slightly different problem: the result variable contains the last location where a[i] is zero.
you will find that the sum value depends on the number of threads, and is likely not the same as when you execute
the code sequentially. The problem here is the race condition involving the sum variable, since this variable is shared
between all threads.
We will discuss several strategies of dealing with this.
369
20. OpenMP topic: Reductions
// sectionreduct.c
float y=0;
#pragma omp parallel reduction(+:y)
#pragma omp sections
{
#pragma omp section
y += f();
#pragma omp section
y += g();
}
Another reduction, this time over a parallel region, without any work sharing:
// reductpar.c
m = INT_MIN;
#pragma omp parallel reduction(max:m) num_threads(ndata)
{
int t = omp_get_thread_num();
int d = data[t];
m = d>m ? d : m;
};
If you want to reduce multiple variables with the same operator, use
reduction(+:x,y,z)
For multiple reduction with different operators, use more than one clause.
Remark 32 A reduction is one of those cases where the parallel execution can have a slightly different
value from the one that is computed sequentially, because floating point operations are not associative, so
roundoffomp!reduction!roundoff will lead to differing results. See HPC book, section-3.6.5 for more explanation.
The OpenMP standard does not even specify that two runs with the same number of threads, and the same
scheduling, have to give identical results. Some runtimes may have a setting to enforce this; for instance
KMP_DETERMINISTIC_REDUCTION for the Intel runtime.
This is a good solution if the amount of serialization in the critical section is small compared to computing the
functions 𝑓 , 𝑔, ℎ. On the other hand, you may not want to do that in a loop:
double result = 0;
#pragma omp parallel
{
double local_result;
# pragma omp for
for (i=0; i<N; i++) {
local_result = f(x,i);
# pragma omp critical
result += local_result;
} // end of for loop
}
Exercise 20.1. Can you think of a small modification of this code, that still uses a critical section, that
is more efficient? Time both codes.
While this code is correct, it may be inefficient because of a phenomemon called false sharing. Even though the
threads write to separate variables, those variables are likely to be on the same cacheline (see HPC book, section-
1.4.2 for an explanation). This means that the cores will be wasting a lot of time and bandwidth updating each
other’s copy of this cacheline.
False sharing can be prevent by giving each thread its own cacheline:
double result,local_results[3][8];
#pragma omp parallel
{
int num = omp_get_thread_num();
if (num==0) local_results[num][1] = f(x)
// et cetera
}
A more elegant solution gives each thread a true local variable, and uses a critical section to sum these, at the very
end:
double result = 0;
#pragma omp parallel
{
double local_result;
local_result = .....
C++ note 9: Reductions on vectors. Use the data method to extract the array on which to reduce. Also, the reduction
clause wants a variable, not an expression, for the array, so you need an extra bare pointer:
// reductarray.cxx
vector<int> data(nthreads,0);
int *datadata = data.data();
#pragma omp parallel for schedule(static,1) \
reduction(+:datadata[:nthreads])
for (int it=0; it<nthreads; it++) {
for (int i=0; i<nthreads; i++)
datadata[i]++;
}
20.2.3 Types
Reduction can be applied to any type for which the operator is defined. The types to which max/min are applicable
are limited.
Each thread does a partial reduction, but its initial value is not the user-supplied init_x value, but a value dependent
on the operator. In the end, the partial results will then be combined with the user initial value. The initialization
values are mostly self-evident, such as zero for addition and one for multiplication. For min and max they are
respectively the maximal and minimal representable value of the result type.
Figure 20.1: Reduction of four items on two threads, taking into account initial values.
Figure 20.1 illustrates this, where 1,2,3,4 are four data items, i is the OpenMP initialization, and u is the user
initialization; each p stands for a partial reduction value. The figure is based on execution using two threads.
Exercise 20.3. Write a program to test the fact that the partial results are initialized to the unit of the
reduction operator.
1. In non-Object-Oriented (OO) languages you can define a function, and declare that to be a reduction
operator with the declare reduction construct.
2. In OO languages (C++ and Fortran2003) you can overload ordinary operators for types, including class
objects.
where:
identifier is a name; this can be overloaded for different types, and redefined in inner scopes.
typelist is a list of types.
combiner is an expression that updates the internal variable omp_out as function of itself and omp_in.
initializer sets omp_priv to the identity of the reduction; this can be an expression or a brace initializer.
C++ note 10: Lambda expressions in declared reductions. You can use lambda expressions in the explicit expression:
// reductexpr.cxx
#pragma omp declare reduction\
(minabs : int : \
omp_out = \
[] (int x,int y) -> int { \
return abs(x) > abs(y) ? abs(y) : abs(x); } \
(omp_in,omp_out) ) \
initializer (omp_priv=limit::max())
You can not assign the lambda expression to a variable and use that, because omp_in/out are the only
variables allowed in the explicit expression.
Exercise 20.4. Write a reduction routine that operates on an array of nonnegative integers, finding
the smallest nonzero one. If the array has size zero, or entirely consists of zeros, return -1.
C++ note 11: Reduction over iterators. Support for C++ iterators
#pragma omp declare reduction (merge : std::vector<int>
: omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))
C++ note 12: Templated reductions. You can reduce with a templated function if you put both the declaration and
the reduction in the same templated function:
template<typename T>
T generic_reduction( vector<T> tdata ) {
#pragma omp declare reduction \
(rwzt:T:omp_out=reduce_without_zero<T>(omp_out,omp_in)) \
initializer(omp_priv=-1.f)
T tmin = -1;
C++ note 13: Example: reduction over a map. You can do a reduction over a std::map by merging thread-local maps:
C++ note 14: Reduction on class objects. Reduction can be applied to any class for which the reduction operator is
defined as operator+ or whichever operator the case may be.
A default constructor is required for the internally used init value; see figure 20.1.
A ‘scan’ or prefix operation is like a reduction, except that you’re interested in the partial results. For this OpenMP,
as of OpenMP-5.0, has the scan directive. This needs the following:
• In the body of the parallel loop there is a scan directive that allows you to store the partial results. For
inclusive scans the reduction variable is updated before the scan pragma:
sumvar // update
#pragma omp scan inclusive(sumvar)
partials[i] = sumvar
For exclusive scans the reduction variable is updated after the scan pragma:
partials[i] = sumvar
#pragma omp scan inclusive(sumvar)
sumvar // update
Code: Output:
// scanintsum.c Summing : 1 2 3 4 5 6 7 8
partial_sum=0; Inclusive: 1 3 6 10 15 21 28 36
#pragma omp parallel for Exclusive: 0 1 3 6 10 15 21 28
↪reduction(inscan,+:partial_sum)
for (int i=0; i<nthreads; i++) {
partial_sum += amounts[i];
# pragma omp scan
↪inclusive(partial_sum)
inc_partials[i] = partial_sum;
}
partial_sum=0;
#pragma omp parallel for
↪reduction(inscan,+:partial_sum)
for (int i=0; i<nthreads; i++) {
exc_partials[i] = partial_sum;
# pragma omp scan
↪exclusive(partial_sum)
partial_sum += amounts[i];
}
The declaration of a parallel region establishes a team of threads. This offers the possibility of parallelism, but to
actually get meaningful parallel activity you need something more. OpenMP uses the concept of a work sharing
construct: a way of dividing parallelizable work over a team of threads.
You have already seen loop parallelism as a way of distributing parallel work in chapter 19. We will now discuss
other work sharing constructs.
21.2 Sections
A parallel loop is an example of independent work units that are numbered. If you have a pre-determined number of
independent work units, the sections is more appropriate. In a sections construct can be any number of section
constructs. These need to be independent, and they can be execute by any available thread in the current team,
including having multiple sections done by the same thread.
#pragma omp sections
{
#pragma omp section
// one calculation
#pragma omp section
// another calculation
}
This construct can be used to divide large blocks of independent work. Suppose that in the following line, both f(x)
and g(x) are big calculations:
y = f(x) + g(x)
380
21.3. Single/master
Instead of using two temporaries, you could also use a critical section; see section 23.2.2. However, the best solution
is have a reduction clause on the parallel sections directive. For the sum
y = f(x) + g(x)
21.3 Single/master
The single pragma limits the execution of a block to a single thread. This can for instance be used to print tracing
information or doing I/O operations.
#pragma omp parallel
{
#pragma omp single
printf("We are starting this section!\n");
// parallel stuff
}
The point of the single directive in this last example is that the computation needs to be done only once, because
of the shared memory. Since it’s a work sharing construct there is an implicit barrier after it, which guarantees that
all threads have the correct value in their local memory (see section 23.4).
Exercise 21.1. What is the difference between this approach and how the same computation would
be parallelized in MPI?
The master directive also enforces execution on a single thread, specifically the master thread of the team. This is
not a work sharing construct, and therefore does not have the synchronization through the implicit barrier.
Exercise 21.2. Modify the above code to read:
int a;
#pragma omp parallel
{
#pragma omp master
a = f(); // some computation
#pragma omp sections
// various different computations using a
}
With results:
SIMD times :
0.07115 0.04053 0.02498 0.01609 0.01210 0.01247 0.01765 0.02689
Speedup:
1 1.75549 2.84828 4.422 5.88017 5.70569 4.03116 2.64597
Workshare times:
0.06188 0.03186 0.01625 0.00867 0.00619 0.00379 0.00354 0.00373
Speedup:
1 1.94225 3.808 7.13725 9.99677 16.3272 17.4802 16.5898
In a parallel region there are two types of data: private and shared. In this sections we will see the various way you
can control what category your data falls under; for private data items we also discuss how their values relate to
shared data.
Example:
int x = 5;
#pragma omp parallel
{
x = x+1;
printf("shared: x is %d\n",x);
}
All threads increment the same variable, so after the loop it will have a value of five plus the number of threads; or
maybe less because of the data races involved. This issue is discussed in HPC book, section-2.6.1.5; see 23.2.2 for a
solution to data races in OpenMP.
In the following example, each thread creates a private variable x and sets it to a unique value:
385
22. OpenMP topic: Controlling thread data
Code: Output:
// private.c Thread 3 sets x to 4
int x=5; Thread 2 sets x to 3
#pragma omp parallel num_threads(4) Thread 0 sets x to 1
{ Thread 1 sets x to 2
int t = omp_get_thread_num(), Outer x is still 5
x = t+1;
printf("Thread %d sets x to
↪%d\n",t,x);
}
printf("Outer x is still %d\n",x);
After the parallel region the outer variable x will still have the value 5: there is no storage association between the
private variable and global one.
Fortran note 21: Private variables in parallel region. The Fortran language does not have this concept of scope, so
you have to use a private clause:
Code: Output:
!! private.F90 Thread 0 sets x to 1
x=5 Thread 2 sets x to 3
!$omp parallel private(x,t) Thread 3 sets x to 4
↪num_threads(4) Thread 1 sets x to 2
t = omp_get_thread_num() Outer x is still 5
x = t+1
print '("Thread ",i2," sets x to
↪",i2)',t,x
!$omp end parallel
print '("Outer x is still ",i2)',x
C++ note 15: Privatizing class members. Class members can only be privatized from (non-static) class methods:
class foo {
private:
int x;
public:
void f() {
#pragma omp parallel private x
g()
}
}
The private directive declares data to have a separate copy in the memory of each thread. Such private variables
are initialized as they would be in a main program. Any computed value goes away at the end of the parallel region.
(However, see lastprivate below.) Thus, you should not rely on any initial value, or on the value of the outer
variable after the region.
int x = 5;
#pragma omp parallel private(x)
{
x = x+1; // dangerous
printf("private: x is %d\n",x);
}
printf("after: x is %d\n",x);
Data that is declared private with the private directive is put on a separate stack per thread. The OpenMP standard
does not dictate the size of these stacks, but beware of stack overflow. A typical default is a few megabytes;
you can control it with the environment variable OMP_STACKSIZE. (You can find the current value by setting
OMP_DISPLAY_ENV.) Its values can be literal or with suffixes:
A normal Unix process also has a stack, but this is independent of the OpenMP stacks for private data. You can query
or set the Unix stack with ulimit:
[] ulimit -s
64000
[] ulimit -s 8192
[] ulimit -s
8192
The Unix stack can grow dynamically as space is needed. This does not hold for the OpenMP stacks: they are
immediately allocated at their requested size. Thus it is important not too make them too large.
Functions that are called from a parallel region fall in the dynamic scope of that parallel region. The rules for variables
in that function are as follows:
Fortran note 22: Saved variables. Variables in subprograms are private, as in C, except if the have the Save attribute.
This attribute is implicitly given to any variable that has value-initialized.
In the following example we have two almost identical routines, except that the first does
value-initialization on the local variable, thereby in effect making it shared. The second routine does
not have that problem.
Code: Output:
subroutine savehello Hello from 3
use omp_lib Hello from 3
implicit none Hello from 3
integer :: thread = -1 Hello from 3
thread = omp_get_thread_num() World from 0
print *,"Hello from",thread World from 1
end subroutine savehello World from 2
subroutine finehello World from 3
use omp_lib
implicit none
integer :: thread
thread = omp_get_thread_num()
print *,"World from",thread
end subroutine finehello
By the above rules, the variables x,s,c are all shared variables. However, the values they receive in one iteration
are not used in a next iteration, so they behave in fact like private variables to each iteration.
• In both C and Fortran you can declare these variables private in the parallel for directive.
• In C you can also define the variables locally inside the loop.
Sometimes, even if you forget to declare these temporaries as private, the code may still give the correct output.
That is because the compiler can sometimes eliminate them from the loop body, since it detects that their values
are not otherwise used.
22.5 Default
There are default rules for whether data in OpenMP constructs is private or shared, and you can control this explic-
itly.
First the default behavior:
• Variables declared outside a a parallel region are shared as described above;
• Loop variables in an omp for are private;
• Local variables in the parallel region are private.
You can alter this default behavior with the default clause:
• The shared clause means that all variables from the outer scope are shared in the parallel region; any
private variables need to be declared explicitly. This is the default behavior.
• The private clause means that all outer variables become private in the parallel region. They are not
initialized; see the next option. Any shared variables in the parallel region need to be declared explicitly.
This value is not available in C.
• The firstprivate clause means all outer variables are private in the parallel region, and initialized
with their outer value. Any shared variables need to be declared explicitly. This value is not available
in C.
• The none option is good for debugging, because it forces you to specify for each variable in the parallel
region whether it’s private or shared. Also, if your code behaves differently in parallel from sequential
there is probably a data race. Specifying the status of every variable is a good way to debug this.
The variable t behaves like a private variable, except that it is initialized to the outside value.
Secondly, you may want a private value to be preserved to the environment outside the parallel region. This really
only makes sense in one case, where you preserve a private variable from the last iteration of a parallel loop, or the
last section in an sections construct. This is done with lastprivate:
#pragma omp parallel for \
lastprivate(tmp)
for (int i=0; i<N; i+) {
tmp = ......
x[i] = .... tmp ....
}
..... tmp ....
The rules for arrays are slightly different from those for scalar data:
int array[100];
integer,dimension(:) :: array(100}
Example of the first type: each thread gets a private copy of the array, properly initialized.
Code: Output:
int array[nthreads]; Executing: OMP_PROC_BIND=true OMP_NUM_THREADS=4
for (int i=0; i<nthreads; i++) ↪./alloc
array[i] = 0; Array result:
0:0, 1:0, 2:0, 3:0,
#pragma omp parallel
↪firstprivate(array)
{
int t = omp_get_thread_num();
array[t] = t+1;
}
Of course, since only the private copy is altered, the original array is unaffected.
On the other hand, in the following example each thread gets a private pointer, but all pointers point to the same
object:
Code: Output:
// alloc.c Array result:
int *array = 0:0, 1:1, 2:2, 3:3,
(int*) malloc(nthreads*sizeof(int));
for (int i=0; i<nthreads; i++)
array[i] = 0;
Code: Output:
// alloc.c Array result:
int *array = 0:0, 1:1, 2:2, 3:3,
(int*) malloc(nthreads*sizeof(int));
for (int i=0; i<nthreads; i++)
array[i] = 0;
and
Code: Output:
// alloc.cxx Missing output for privvector
vector<int> array(nthreads);
// threadprivate.c
static int tp;
#pragma omp threadprivate(tp)
Fortran note 23: Private common blocks. Named common blocks can be made thread-private with the syntax
$!OMP threadprivate( /blockname/ )
Example:
Code: Output:
!! threadprivate.F90 Thread 0 sets x to 1
common /threaddata/tp Thread 2 sets x to 3
integer :: tp Thread 3 sets x to 4
!$omp threadprivate(/threaddata/) Thread 1 sets x to 2
Outer x is still 5
On the other hand, if the thread private data starts out identical in all threads, the copyin clause can be used:
#pragma omp threadprivate(private_var)
private_var = 1;
#pragma omp parallel copyin(private_var)
private_var += omp_get_thread_num()
If one thread needs to set all thread private data to its value, the copyprivate clause can be used:
#pragma omp parallel
{
...
#pragma omp single copyprivate(private_var)
private_var = read_data();
...
}
C++ note 17: Threadprivate random number generators. The new C++ random header has a threadsafe generator, by
virtue of the statement in the standard that no STL object can rely on global state. The usual idiom can
not be made threadsafe because of the initialization:
static random_device rd;
static mt19937 rng(rd);
int main() {
22.9 Allocators
OpenMP was initially designed for shared memory. With accelerators (see chapter 27), non-coherent memory was
added to this. In the OpenMP-5 standard, the story is further complicated, to account for new memory types such
as high-bandwidth memory and non-volatile memory.
In the constructs for declaring parallel regions above, you had little control over in what order threads executed
the work they were assigned. This section will discuss synchronization constructs: ways of telling threads to bring
a certain order to the sequence in which they do things.
• critical: a section of code can only be executed by one thread at a time; see 23.2.2.
• atomic Atomic update of a single memory location. Only certain specified syntax patterns are supported.
This was added in order to be able to use hardware support for atomic updates.
• barrier: section 23.1.
• locks: section 23.3.
• flush: section 23.4.
Loop-related synchronization constructs were discussed earlier:
• ordered: section 19.6.
• nowait: section 19.7.
23.1 Barrier
A barrier defines a point in the code where all active threads will stop until all threads have arrived at that point.
With this, you can guarantee that certain calculations are finished. For instance, in this code snippet, computation
of y can not proceed until another thread has computed its value of x.
#pragma omp parallel
{
int mytid = omp_get_thread_num();
x[mytid] = some_calculation();
y[mytid] = x[mytid]+x[mytid+1];
}
396
23.2. Mutual exclusion
You can also put each parallel loop in a parallel region of its own, but there is some overhead associated with creating
and deleting the team of threads in between the regions.
At the end of a parallel region the team of threads is dissolved and only the master thread continues. Therefore,
there is an implicit barrier at the end of a parallel region. This barrier behavior can be canceled with the nowait
clause.
You will often see the idiom
#pragma omp parallel
{
#pragma omp for nowait
for (i=0; i<N; i++)
a[i] = // some expression
#pragma omp for
for (i=0; i<N; i++)
b[i] = ...... a[i] ......
Here the nowait clause implies that threads can start on the second loop while other threads are still working on
the first. Since the two loops use the same schedule here, an iteration that uses a[i] can indeed rely on it that that
value has been computed.
Code: Output:
// race.c On 1 threads:
#pragma omp parallel for Counter should be 100000, is 100000
↪shared(counter) On 2 threads:
for (int i=0; i<count; i++) Counter should be 100000, is 100000
counter += f(counter,i); On 4 threads:
printf("Counter should be %d, is Counter should be 100000, is 75000
↪%d\n", On 8 threads:
count,counter); Counter should be 100000, is 87500
On 12 threads:
Counter should be 100000, is 100000
The basic rule about multiple-thread access of a single data item is:
Any memory location that is written by one thread, can not be read by another thread in the
same parallel region, if no synchronization is done.
To start with that last clause: any workshare construct ends with an implicit barrier, so data written before that
barrier can safely be read after it.
but this should really be done with a reduction clause, which will be far more efficient.
A good use of critical sections is doing file writes or database updates.
Exercise 23.1. Consider a loop where each iteration updates a variable.
#pragma omp parallel for shared(result)
for ( i ) {
result += some_function_of(i);
}
Discuss qualitatively the difference between:
• turning the update statement into a critical section, versus
• letting the threads accumulate into a private variable tmp as above, and summing
these after the loop.
Do an Ahmdal-style quantitative analysis of the first case, assuming that you do 𝑛 iterations
on 𝑝 threads, and each iteration has a critical section that takes a fraction 𝑓 . Assume the
number of iterations 𝑛 is a multiple of the number of threads 𝑝. Also assume the default
static distribution of loop iterations over the threads.
Critical sections are an easy way to turn an existing code into a correct parallel code. However, there are performance
disadvantages to critical sections, and sometimes a more drastic rewrite is called for.
A critical section works by acquiring a lock, which carries a substantial overhead. Furthermore, if your code has
multiple critical sections, they are all mutually exclusive: if a thread is in one critical section, the other ones are all
blocked.
The problem with critical sections being mutually exclusive can be mitigated by naming them:
#pragma omp critical (optional_name_in_parens)
On the other hand, the syntax for atomic sections is limited to the update of a single memory location, but such
sections are not exclusive and they can be more efficient, since they assume that there is a hardware mechanism for
making them critical. See the next section.
4. omp atomic capture can accommodate a single statement similar to omp atomic update, or a block that
essentially combines a read and update form.
23.3 Locks
OpenMP also has the traditional mechanism of a lock. A lock is somewhat similar to a critical section: it guarantees
that some instructions can only be performed by one process at a time. However, a critical section is indeed about
code; a lock is about data. With a lock you make sure that some data elements can only be touched by one process
at a time.
23.3.1 Routines
Create/destroy:
void omp_init_lock(omp_lock_t *lock);
void omp_destroy_lock(omp_lock_t *lock);
omp_set_lock(&lockb);
for (i=0; i<N; i++)
b[i] = .. a[i] ..
omp_unset_lock(&lockb);
omp_unset_lock(&locka);
}
omp_set_lock(&locka);
for (i=0; i<N; i++)
a[i] = .. b[i] ..
omp_unset_lock(&locka);
omp_unset_lock(&lockb);
}
} /* end of sections */
} /* end of parallel region */
// lockobject.cxx
class atomic_int {
private:
omp_lock_t the_lock;
int _value{0};
public:
atomic_int() {
omp_init_lock(&the_lock);
};
atomic_int( const atomic_int& )
= delete;
atomic_int& operator=( const atomic_int& )
= delete;
~atomic_int() {
omp_destroy_lock(&the_lock);
};
Running this:
atomic_int my_object;
vector<std::thread> threads;
for (int ithread=0; ithread<NTHREADS; ithread++) {
threads.push_back
( std::thread(
[=,&my_object] () {
for (int iop=0; iop<nops; iop++)
my_object += 1; } ) );
}
for ( auto &t : threads )
t.join();
but that is unnecessarily restrictive. If there are enough bins in the histogram, and if the some_function takes
enough time, there are unlikely to be conflicting writes. The solution then is to create an array of locks, with one
lock for each count location.
Another solution would be to give each thread a local copy of the result array, and perform a reduction on these.
See section 20.2.2.
We start by sketching the basic single-threaded solution. The naive code looks like:
int main() {
value = new int[nmax+1];
value[0] = 1;
value[1] = 1;
fib(10);
}
int fib(int n) {
int i, j, result;
if (n>=2) {
i=fib(n-1); j=fib(n-2);
value[n] = i+j;
}
return value[n];
}
However, this is inefficient, since most intermediate values will be computed more than once. We solve this by
keeping track of which results are known:
...
done = new int[nmax+1];
for (i=0; i<=nmax; i++)
done[i] = 0;
done[0] = 1;
done[1] = 1;
...
int fib(int n) {
int i, j;
if (!done[n]) {
i = fib(n-1); j = fib(n-2);
value[n] = i+j; done[n] = 1;
}
return value[n];
}
The OpenMP parallel solution calls for two different ideas. First of all, we parallelize the recursion by using tasks
(section 24:
int fib(int n) {
int i, j;
if (n>=2) {
#pragma omp task shared(i) firstprivate(n)
i=fib(n-1);
#pragma omp task shared(j) firstprivate(n)
j=fib(n-2);
#pragma omp taskwait
value[n] = i+j;
}
return value[n];
}
This computes the right solution, but, as in the naive single-threaded solution, it recomputes many of the interme-
diate values.
A naive addition of the done array leads to data races, and probably an incorrect solution:
int fib(int n) {
int i, j, result;
if (!done[n]) {
#pragma omp task shared(i) firstprivate(n)
i=fib(n-1);
#pragma omp task shared(i) firstprivate(n)
j=fib(n-2);
#pragma omp taskwait
value[n] = i+j;
done[n] = 1;
}
return value[n];
}
For instance, there is no guarantee that the done array is updated later than the value array, so a thread can think
that done[n-1] is true, but value[n-1] does not have the right value yet.
One solution to this problem is to use a lock, and make sure that, for a given index n, the values done[n] and
value[n] are never touched by more than one thread at a time:
int fib(int n)
{
int i, j;
omp_set_lock( &(dolock[n]) );
if (!done[n]) {
#pragma omp task shared(i) firstprivate(n)
i = fib(n-1);
#pragma omp task shared(j) firstprivate(n)
j = fib(n-2);
#pragma omp taskwait
value[n] = i+j;
done[n] = 1;
}
omp_unset_lock( &(dolock[n]) );
return value[n];
}
This solution is correct, optimally efficient in the sense that it does not recompute anything, and it uses tasks to
obtain a parallel execution.
However, the efficiency of this solution is only up to a constant. A lock is still being set, even if a value is already
computed and therefore will only be read. This can be solved with a complicated use of critical sections, but we will
forego this.
Tasks are a mechanism that OpenMP uses behind the scenes: if you specify something as being a task, OpenMP will
create a ‘block of work’: a section of code plus the data environment in which it occurred. This block is set aside
for execution at some later point. Thus, task-based code usually looks something like this:
#pragma omp parallel
{
// generate a bunch of tasks
# pragma omp taskwait
// the result from the tasks is now available
}
For instance, a parallel loop was always implicitly translated to something like:
406
24.1. Task generation
because the parallel region creates a team, and each thread in the team executes the task-generating code. Instead,
we use the following idiom:
#pragma omp parallel
#pragma omp single
for (int ib=0; ib<nblocks; ib++) {
// setup stuff
# pragma omp task
// task stuff
}
In the first example, the variable count is declared outside the parallel region and is therefore shared. When the
print statement is executed, all tasks will have been generated, and so count will be zero. Thus, the output will
likely be 0,50.
In the second example, the count variable is private to the thread creating the tasks, and so it will be firstprivate
in the task, preserving the value that was current when the task was created.
Explanation: when the statement computing z is executed, the task computing y has only been scheduled; it has
not necessarily been executed yet.
In order to have a guarantee that a task is finished, you need the taskwait directive. The following creates two
tasks, which can be executed in parallel, and then waits for the results:
Code Execution
x = f(); the variable x gets a value
#pragma omp task
{ y1 = g1(x); }
two tasks are created with the current value of x
#pragma omp task
{ y2 = g2(x); }
#pragma omp taskwait the thread waits until the tasks are finished
z = h(y1)+h(y2); the variable z is computed using the task results
The task pragma is followed by a structured block. Each time the structured block is encountered, a new task
is generated. On the other hand taskwait is a standalone directive; the code that follows is just code, it is not a
structured block belonging to the directive.
You can indicate task dependencies in several ways:
1. Using the ‘task wait’ directive you can explicitly indicate the join of the forked tasks. The instruction
after the wait directive will therefore be dependent on the spawned tasks.
2. The taskgroup directive is discussed in section 24.3.1.
3. The taskloop directive is discussed in section 24.3.2.
4. Each OpenMP task can have a depend clause, indicating what data dependency of the task; section 24.4. By
indicating what data is produced or absorbed by the tasks, the scheduler can construct the dependency
graph for you.
it is conceivable that the second task is executed before the first, possibly leading to an incorrect result. This is
remedied by specifying:
#pragma omp task depend(out:x)
x = f()
#pragma omp task depend(in:x)
y = g(x)
for i in [1:N]:
for j in [1:N]:
x[i,j] = x[i-1,j]+x[i,j-1]
• Observe that the second loop nest is not amenable to OpenMP loop parallelism.
• Can you think of a way to realize the computation with OpenMP loop parallelism?
Hint: you need to rewrite the code so that the same operations are done in a different
order.
• Use tasks with dependencies to make this code parallel without any rewriting: the
only change is to add OpenMP directives.
Tasks dependencies are used to indicated how two uses of one data item relate to each other. Since either use can
be a read or a write, there are four types of dependencies.
RaW (Read after Write) The second task reads an item that the first task writes. The second task has to be exe-
cuted after the first:
... omp task depend(OUT:x)
foo(x)
... omp task depend( IN:x)
foo(x)
WaR (Write after Read) The first task reads and item, and the second task overwrites it. The second task has to
be executed second to prevent overwriting the initial value:
... omp task depend( IN:x)
foo(x)
... omp task depend(OUT:x)
foo(x)
WaW (Write after Write) Both tasks set the same variable. Since the variable can be used by an intermediate
task, the two writes have to be executed in this order.
... omp task depend(OUT:x)
foo(x)
... omp task depend(OUT:x)
foo(x)
RaR (Read after Read) Both tasks read a variable. Since neither tasks has an ‘out’ declaration, they can run in
either order.
The task group can contain both task that contribute to the reduction, and ones that don’t. The former type needs
a clause in_reduction:
#pragma omp task in_reduction(+:sum)
100
As an example, here the sum ∑𝑖=1 𝑖 is computed with tasks:
// taskreduct.c
#pragma omp parallel
#pragma omp single
{
#pragma omp taskgroup task_reduction(+:sum)
for (int itask=1; itask<=bound; itask++) {
#pragma omp task in_reduction(+:sum)
sum += itask;
}
}
24.6 More
24.6.1 Scheduling points
Normally, a task stays tied to the thread that first executes it. However, at a task scheduling point the thread may
switch to the execution of another task created by the same team.
• There is a scheduling point after explicit task creation. This means that, in the above examples, the thread
creating the tasks can also participate in executing them.
• There is a scheduling point at taskwait and taskyield.
On the other hand a task created with them untied clause on the task pragma is never tied to one thread. This means
that after suspension at a scheduling point any thread can resume execution of the task. If you do this, beware that
the value of a thread-id does not stay fixed. Also locks become a problem.
Example: if a thread is waiting for a lock, with a scheduling point it can suspend the task and work on another task.
while (!omp_test_lock(lock))
#pragma omp taskyield
;
• The if clause may still lead to recursively generated tasks. On the other hand, final will execute the
code, and will also skip any recursively created tasks:
#pragma omp task final(level<3)
If you want to indicate that certain tasks are more important than others, use the priority clause:
#pragma omp task priority(5)
24.7 Examples
24.7.1 Fibonacci
As an example of the use of tasks, consider computing an array of Fibonacci values:
// taskgroup0.c
for (int i=2; i<N; i++)
{
fibo_values[i] = fibo_values[i-1]+fibo_values[i-2];
}
If you simply turn each calculation into a task, results will be unpredictable (confirm this!) since tasks can be
executed in any sequence. To solve this, we put dependencies on the tasks:
// taskgroup2.c
for (int i=2; i<N; i++)
#pragma omp task \
depend(out:fibo_values[i]) \
depend(in:fibo_values[i-1],fibo_values[i-2])
{
fibo_values[i] = fibo_values[i-1]+fibo_values[i-2];
}
Putting a single task group around the double loop, and use depend clauses to make the
execution satisfy the proper dependencies.
415
25. OpenMP topic: Affinity
We see pretty much perfect speedup for the OMP_PLACES=cores strategy; with OMP_PLACES=sockets we probably
get occasional collisions where two threads wind up on the same core.
Next we take a program for computing the time evolution of the heat equation:
(𝑡+1) (𝑡) (𝑡) (𝑡)
𝑡 = 0, 1, 2, … ∶ ∀𝑖 ∶ 𝑥𝑖 = 2𝑥𝑖 − 𝑥𝑖−1 − 𝑥𝑖+1
This is a bandwidth-bound operation because the amount of computation per data item is low.
Again we see that OMP_PLACES=sockets gives worse performance for high core counts, probably because
of threads winding up on the same core. The thing to observe in this example is that with 6 or 8 cores the
OMP_PROC_BIND=spread strategy gives twice the performance of OMP_PROC_BIND=close.
The reason for this is that a single socket does not have enough bandwidth for all eight cores on the socket. Therefore,
dividing the eight threads over two sockets gives each thread a higher available bandwidth than putting all threads
on one socket.
}
}
There is now a big difference in runtime depending on how close the threads are. We test this on a processor with
both cores and hyperthreads. First we bind the OpenMP threads to the cores:
OMP_NUM_THREADS=2 OMP_PLACES=cores OMP_PROC_BIND=close ./sharing
run time = 4752.231836usec
sum = 80000000.0
Next we force the OpenMP threads to bind to hyperthreads inside one core:
OMP_PLACES=threads OMP_PROC_BIND=close ./sharing
run time = 941.970110usec
sum = 80000000.0
Of course in this example the inner loop is pretty much meaningless and parallelism does not speed up anything:
OMP_NUM_THREADS=1 OMP_PLACES=cores OMP_PROC_BIND=close ./sharing
run time = 806.669950usec
sum = 80000000.0
However, we see that the two-thread result is almost as fast, meaning that there is very little parallelization overhead.
25.2 First-touch
The affinity issue shows up in the first-touch phenomemon.
A little background knowledge. Memory is organized in memory pages, and what we think of as ‘addresses’ really
virtual addresses, mapped to physical addresses, through a page table.
This means that data in your program can be anywhere in physical memory. In particular, on a dual socket node,
the memory can be mapped to either of the sockets.
The next thing to know is that memory allocated with malloc and like routines is not immediately mapped; that
only happens when data is written to it. In light of this, consider the following OpenMP code:
double *x = (double*) malloc(N*sizeof(double));
Since the initialization loop is not parallel it is executed by the master thread, making all the memory associated with
the socket of that thread. Subsequent access by the other socket will then access data from memory not attached to
that socket.
Let’s consider an example. We make the initialization parallel subject to an option:
// heat.c
#pragma omp parallel if (init>0)
{
#pragma omp for
for (int i=0; i<N; i++)
y[i] = x[i] = 0.;
x[0] = 0; x[N-1] = 1.;
}
If the initialization is not parallel, the array will be mapped to the socket of the master thread; if it is parallel, it may
be mapped to different sockets, depending on where the threads run.
As a simple application we run a heat equation, which is parallel, though not embarassingly so:
for (int it=0; it<1000; it++) {
#pragma omp parallel for
for (int i=1; i<N-1; i++)
y[i] = ( x[i-1]+x[i]+x[i+1] )/3.;
#pragma omp parallel for
for (int i=1; i<N-1; i++)
x[i] = y[i];
}
On the TACC Frontera machine, with dual 28-core Intel Cascade Lake processors, we use the following settings:
export OMP_PLACES=cores
export OMP_PROC_BIND=close
# no parallel initialization
make heat && OMP_NUM_THREADS=56 ./heat
# yes parallel initialization
make heat && OMP_NUM_THREADS=56 ./heat 1
25.2.1 C++
The problem with realizing first-touch in C++ is that std::vector fills its allocation with default values. This is
known as ‘value-initialization’, and it makes
vector<double> x(N);
Running the code with the regular definition of a vector, and the above modification, reproduces the runtimes of
the C variant above.
Another option is to wrap memory allocated with new in a unique_ptr:
// heatptr.cxx
unique_ptr<double[]> x( new double[N] );
unique_ptr<double[]> y( new double[N] );
Note that this gives fairly elegant code, since square bracket indexing is overloaded for unique_ptr. The only disad-
vantage is that we can not query the size of these arrays. Or do bound checking with at, but in high performance
contexts that is usually not appropriate anyway.
25.2.2 Remarks
You could move pages with move_pages.
By regarding affinity, in effect you are adopting an SPMD style of programming. You could make this explicit by
having each thread allocate its part of the arrays separately, and storing a private pointer as threadprivate [19].
However, this makes it impossible for threads to access each other’s parts of the distributed array, so this is only
suitable for total data parallel or embarrassingly parallel applications.
25.4 Tests
We take a simple loop and consider the influence of binding parameters.
// speedup.c
#pragma omp parallel for
for (int ip=0; ip<N; ip++) {
for (int jp=0; jp<M; jp++) {
double f = sin( values[ip] );
values[ip] = f;
}
}
25.4.1 Lonestar 6
Lonestar 6, dual socket AMD Milan, total 112 cores: figure 25.1.
110
false
100 96.04
91.9 close
93.41
90.17
88.58 88.75
spread
85.82
84.61
80.53
78.54
75.67
73.69
69.55
65.2963.564.67
62.3
58.54
57.34
51.47
Speedup
50.21
50 44.69
44.17
41.41
39.71 41.03
38.47 38.27
36.43 38.41 37.03
33.21 35.68
34.89
33.06 31.8
27.91
27.43 29.1 28.93
27.92
25.65
25
16.56
16.29
16.03
8.39
8.2
8.15
1
1
1 8 16 24 32 40 48 56 64 72 80 88 96 104112120128
#Threads
Figure 25.1: Speedup as function of thread count, Lonestar 6 cluster, different binding parameters
25.4.2 Frontera
Intel Cascade Lake, dual socket, 56 cores total; figure 25.2.
For all core counts to half the total, performance for all binding strategies seems equal. After that , close and
spread perform equally, but the speedup for the false value gives erratic numbers.
false
70.93
70.75
close
spread
63.04
62.61
60.41
60
54.88
54.66 54.99
46.4
46.35
45.82
38.21
Speedup
40 37.74
37.32
27.46 28.96
26.69
26.68
20
15.3
15.21
15.13
7.29
7.24
7.22
1
1
1 7 14 21 28 35 42 49 56
#Threads
Figure 25.2: Speedup as function of thread count, Frontera cluster, different binding parameters
25.4.5 Longhorn
Dual 20-core IBM Power9, 4 hyperthreads; 25.5
Unlike the Intel processors, here we use the hyperthreads. Figure 25.5 shows dip in the speedup at 40 threads. For
higher thread counts the speedup increases to well beyond the physical core count of 40.
40 false
37.67
close
35.13
34.78
spread
32.56 33.11
32.99
30.99
30 27.86 27.05 27.27
26.2
22.96 22.82
20.63
Speedup
20
17.6 18.28
17.48
13.52
12.08
11.37
10 9.35
6.05
5.92
4.66
1.02
1.01
0.97
1
1 6 12 18 24 30 36 42 48
#Threads
Figure 25.3: Speedup as function of thread count, Stampede2 skylake cluster, different binding parameters
false
86.52
true
73.92
61.79
50 48.9
Speedup
39.2 39.96
40 36.69 36.42
29.82
30 26.31
22.2
20 16.77
9.32
7.68
10
1
1
1 9 19 29 38 48 58 68
#Threads
Figure 25.4: Speedup as function of thread count, Stampede2 Knights Landing cluster, different binding
parameters
60 false
56.09
56
close
spread
44.24
43.31 42.08
40 38.73
38.12
35.17
35.06
31.83 32.91
30.54
Speedup
28.83 27.57
25.01 26.36 23.6
20.29 19.7
20 17.45
17.4
10.19
10.1
10.08
0.98
1
1
1 10 20 30 40 50 60 70 80
#Threads
Figure 25.5: Speedup as function of thread count, Longhorn cluster, different binding parameters
You can declare a loop to be executable with vector instructions with simd.
Remark 34 Depending on your compiler, it may be necessary to give an extra option enabling SIMD:
• -fopenmp-simd for GCC / Clang, and
• -qopenmp-simd for ICC.
427
26. OpenMP topic: SIMD processing
This chapter explains the mechanisms for offloading work to a Graphics Processing Unit (GPU), introduced in
OpenMP-4.0.
The memory of a processor and that of an attached GPU are not coherent: there are separate memory spaces and
writing data in one is not automatically reflected in the other.
OpenMP transfers data (or maps it) when you enter an target construct.
#pragma omp target
{
// do stuff on the GPU
}
You can test whether the target region is indeed executed on a device with omp_is_initial_device:
#pragma omp target
if (omp_is_initial_device()) printf("Offloading failed\n");
432
27.2. Execution on the device
Also update to (synchronize data from host to device), update from (synchronize data to host from device).
435
28. OpenMP remaining topics
• OMP_PLACES Specifies on which CPUs the theads should be placed; section 25.1.
• OMP_STACKSIZE Set default thread stack size; section 22.2.
• OMP_SCHEDULE How threads are scheduled; section 19.3.
• OMP_THREAD_LIMIT Set the maximum number of threads; see section 27.2.
• OMP_WAIT_POLICY How waiting threads are handled; ICV wait-policy-var. Values: ACTIVE for keeping
threads spinning, PASSIVE for possibly yielding the processor when threads are waiting. There is no
runtime function for setting this.
There are 4 ICVs that behave as if each thread has its own copy of them. The default is implementation-defined
unless otherwise noted.
• It may be possible to adjust dynamically the number of threads for a parallel region. Variable:
OMP_DYNAMIC; routines: omp_set_dynamic, omp_get_dynamic.
• If a code contains nested parallel regions, the inner regions may create new teams, or they may be
executed by the single thread that encounters them. Variable: OMP_NESTED; routines omp_set_nested,
omp_get_nested. Allowed values are TRUE and FALSE; the default is false.
• The number of threads used for an encountered parallel region can be controlled. Variable:
OMP_NUM_THREADS; routines omp_set_num_threads, omp_get_max_threads.
• The schedule for a parallel loop can be set. Variable: OMP_SCHEDULE; routines omp_set_schedule,
omp_get_schedule.
Nonobvious syntax:
export OMP_SCHEDULE="static,100"
Other settings:
• omp_get_num_threads: query the number of threads active at the current place in the code; this can be
lower than what was set with omp_set_num_threads. For a meaningful answer, this should be done in a
parallel region.
• omp_get_thread_num
• omp_in_parallel: test if you are in a parallel region.
• omp_get_num_procs: query the physical number of cores available.
Other environment variables:
• OMP_STACKSIZE controls the amount of space that is allocated as per-thread stack; the space for private
variables; see section 22.2.
• OMP_WAIT_POLICY determines the behavior of threads that wait, for instance for critical section:
– ACTIVE puts the thread in a spin-lock, where it actively checks whether it can continue;
– PASSIVE puts the thread to sleep until the Operating System (OS) wakes it up.
The ‘active’ strategy uses CPU while the thread is waiting; on the other hand, activating it after the
wait is instantaneous. With the ‘passive’ strategy, the thread does not use any CPU while waiting, but
activating it again is expensive. Thus, the passive strategy only makes sense if threads will be waiting
for a (relatively) long time.
• OMP_PROC_BIND with values TRUE and FALSE can bind threads to a processor. On the one hand, doing so
can minimize data movement; on the other hand, it may increase load imbalance.
28.2 Timing
OpenMP has a wall clock timer routine omp_get_wtime
double omp_get_wtime(void);
The starting point is arbitrary and is different for each program run; however, in one run it is identical for all threads.
This timer has a resolution given by omp_get_wtick.
Exercise 28.1. Use the timing routines to demonstrate speedup from using multiple threads.
• Write a code segment that takes a measurable amount of time, that is, it should take a
multiple of the tick time.
• Write a parallel loop and measure the speedup. You can for instance do this
for (int use_threads=1; use_threads<=nthreads; use_threads++) {
#pragma omp parallel for num_threads(use_threads)
for (int i=0; i<nthreads; i++) {
.....
}
if (use_threads==1)
time1 = tend-tstart;
else // compute speedup
• In order to prevent the compiler from optimizing your loop away, let the body
compute a result and use a reduction to preserve these results.
...
for ( .... ) {
int ivalue = next_one();
}
has a clear race condition, as the iterations of the loop may get different next_one values, as they are supposed
to, or not. This can be solved by using an critical pragma for the next_one call; another solution is to use an
threadprivate declaration for isave. This is for instance the right solution if the next_one routine implements a
random number generator.
Dynamism Creating a thread team takes time. In practice, a team is not created and deleted for each parallel
region, but creating teams of different sizes, or recursize thread creation, may introduce overhead.
Load imbalance Even if your program is parallel, you need to worry about load balance. In the case of a parallel
loop you can set the schedule clause to dynamic, which evens out the work, but may cause increased
communication.
Communication Cache coherence causes communication. Threads should, as much as possible, refer to their own
data.
• Threads are likely to read from each other’s data. That is largely unavoidable.
• Threads writing to each other’s data should be avoided: it may require synchronization, and it
causes coherence traffic.
• If threads can migrate, data that was local at one time is no longer local after migration.
• Reading data from one socket that was allocated on another socket is inefficient; see section 25.2.
Affinity Both data and execution threads can be bound to a specific locale to some extent. Using local data is
more efficient than remote data, so you want to use local data, and minimize the extent to which data or
execution can move.
• See the above points about phenomena that cause communication.
• Section 25.1.1 describes how you can specify the binding of threads to places. There can, but does
not need, to be an effect on affinity. For instance, if an OpenMP thread can migrate between hard-
ware threads, cached data will stay local. Leaving an OpenMP thread completely free to migrate
can be advantageous for load balancing, but you should only do that if data affinity is of lesser
importance.
• Static loop schedules have a higher chance of using data that has affinity with the place of execu-
tion, but they are worse for load balancing. On the other hand, the nowait clause can aleviate some
of the problems with static loop schedules.
Binding You can choose to put OpenMP threads close together or to spread them apart. Having them close together
makes sense if they use lots of shared data. Spreading them apart may increase bandwidth. (See the
examples in section 25.1.2.)
Synchronization Barriers are a form of synchronization. They are expensive by themselves, and they expose load
imbalance. Implicit barriers happen at the end of worksharing constructs; they can be removed with
nowait.
Critical sections imply a loss of parallelism, but they are also slow as they are realized through operating
system functions. These are often quite costly, taking many thousands of cycles. Critical sections should
be used only if the parallel work far outweighs it.
28.5 Accelerators
In OpenMP-4.0 there is support for offloading work to an accelerator or co-processor:
#pragma omp target [clauses]
The openmp.org website maintains a record of which compilers support which standards: https://www.openmp.
org/resources/openmp-compilers-tools/.
Under any reasonable interpretation of parallel execution, the possible values for r1,r2 are 1, 1 0, 1 or 1, 0. This is
known as sequential consistency: the parallel outcome is consistent with a sequential execution that interleaves the
parallel computations, respecting their local statement orderings. (See also HPC book, section-2.6.1.6.)
However, running this, we get a small number of cases where 𝑟1 = 𝑟2 = 0. There are two possible explanations:
1. The compiler is allowed to interchange the first and second statements, since there is no dependence
between them; or
2. The thread is allowed to have a local copy of the variable that is not coherent with the value in memory.
We fix this by flushing both a,b:
// weak2.c
int a=0,b=0,r1,r2;
#pragma omp parallel sections shared(a, b, r1, r2)
{
#pragma omp section
{
a = 1;
#pragma omp flush (a,b)
r1 = b;
tasks++;
}
#pragma omp section
{
b = 1;
#pragma omp flush (a,b)
r2 = a;
tasks++;
}
}
OpenMP Review
443
29. OpenMP Review
29.2.2 Parallelism
Can the following loops be parallelized? If so, how? (Assume that all arrays are already filled in, and that there are
no out-of-bounds errors.)
// variant #1 // variant #3
for (i=0; i<N; i++) { for (i=1; i<N; i++) {
x[i] = a[i]+b[i+1]; x[i] = a[i]+b[i+1];
a[i] = 2*x[i] + c[i+1]; a[i] = 2*x[i-1] + c[i+1];
} }
// variant #2 // variant #4
for (i=0; i<N; i++) { for (i=1; i<N; i++) {
x[i] = a[i]+b[i+1]; x[i] = a[i]+b[i+1];
a[i] = 2*x[i+1] + c[i+1]; a[i+1] = 2*x[i-1] + c[i+1];
} }
! variant #1 ! variant #3
do i=1,N do i=2,N
x(i) = a(i)+b(i+1) x(i) = a(i)+b(i+1)
a(i) = 2*x(i) + c(i+1) a(i) = 2*x(i-1) + c(i+1)
end do end do
! variant #2 ! variant #3
do i=1,N do i=2,N
x(i) = a(i)+b(i+1) x(i) = a(i)+b(i+1)
a(i) = 2*x(i+1) + c(i+1) a(i+1) = 2*x(i-1) + c(i+1)
end do end do
// variant #1 // variant #4
int nt; int nt;
#pragma omp parallel #pragma omp parallel
{ {
nt = omp_get_thread_num(); #pragma omp master
printf("thread number: %d\n",nt); {
} nt = omp_get_thread_num();
printf("thread number: %d\n",nt);
// variant #2 }
int nt; }
#pragma omp parallel private(nt)
{ // variant #5
nt = omp_get_thread_num(); int nt;
printf("thread number: %d\n",nt); #pragma omp parallel
} {
#pragma omp critical
// variant #3 {
int nt; nt = omp_get_thread_num();
#pragma omp parallel printf("thread number: %d\n",nt);
{ }
#pragma omp single }
{
nt = omp_get_thread_num();
printf("thread number: %d\n",nt);
}
}
nt = omp_get_thread_num()
! variant #1 print *,"thread number:",nt
integer nt !$OMP end single
!$OMP parallel !$OMP end parallel
nt = omp_get_thread_num()
print *,"thread number:",nt
!$OMP end parallel
! variant #2
integer nt
!$OMP parallel private(nt)
nt = omp_get_thread_num()
print *,"thread number:",nt
!$OMP end parallel
! variant #3
integer nt
!$OMP parallel
!$OMP single
! variant #4 ! variant #5
integer nt integer nt
!$OMP parallel !$OMP parallel
!$OMP master !$OMP critical
nt = omp_get_thread_num() nt = omp_get_thread_num()
print *,"thread number:",nt print *,"thread number:",nt
!$OMP end master !$OMP end critical
!$OMP end parallel !$OMP end parallel
29.2.3.2
The following is an attempt to parallelize a serial code. Assume that all variables and arrays are defined. What errors
and potential problems do you see in this code? How would you fix them?
29.2.3.3
Assume two threads. What does the following program output?
int a;
#pragma omp parallel private(a) {
...
a = 0;
#pragma omp for
for (int i = 0; i < 10; i++)
{
#pragma omp atomic
a++; }
#pragma omp single
printf("a=%e\n",a);
}
29.2.4 Reductions
29.2.4.1
Is the following code correct? Is it efficient? If not, can you improve it?
#pragma omp parallel shared(r)
{
int x;
x = f(omp_get_thread_num());
#pragma omp critical
r += f(x);
}
29.2.4.2
Compare two fragments:
// variant 1 // variant 2
#pragma omp parallel reduction(+:s) #pragma omp parallel
#pragma omp for #pragma omp for reduction(+:s)
for (i=0; i<N; i++) for (i=0; i<N; i++)
s += f(i); s += f(i);
! variant 1 ! variant 2
!$OMP parallel reduction(+:s) !$OMP parallel
!$OMP do !$OMP do reduction(+:s)
do i=1,N do i=1,N
s += f(i); s += f(i);
end do end do
!$OMP end do !$OMP end do
!$OMP end parallel !$OMP end parallel
29.2.5 Barriers
Are the following two code fragments well defined?
return 0;
#pragma omp parallel private(i) }
↪shared(icount)
{
#pragma omp critical
{ icount++;
for (i=0; i<100; i++)
iarray[icount][i] = 1;
}
}
iarray(icount,i) = 1
!$OMP parallel private(i) shared(icount) end do
!$OMP critical !$OMP critical
icount = icount+1 !$OMP end parallel
do i=1,100
29.2.7 Tasks
Fix two things in the following example:
print *,"sum=",x+y+z
!$OMP end single
!$OMP end parallel
29.2.8 Scheduling
Compare these two fragments. Do they compute the same result? What can you say about their efficiency?
How would you make the second loop more efficient? Can you do something similar for the first loop?
OpenMP Examples
𝐹⃖⃗𝑖 = ∑ 𝐹⃖⃗𝑖𝑗 .
𝑗≠𝑖
/* Force on p1 from p2 */
struct force force_calc( struct point p1,struct point p2 ) {
double dx = p2.x - p1.x, dy = p2.y - p1.y;
double f = p1.c * p2.c / sqrt( dx*dx + dy*dy );
struct force exert = {dx,dy,f};
return exert;
}
Force accumulation:
void add_force( struct force *f,struct force g ) {
f->x += g.x; f->y += g.y; f->f += g.f;
}
void sub_force( struct force *f,struct force g ) {
f->x -= g.x; f->y -= g.y; f->f += g.f;
}
453
30. OpenMP Examples
Here 𝐹⃖⃗𝑖𝑗 is only computed for 𝑗 > 𝑖, and then added to both 𝐹⃖⃗𝑖 and 𝐹⃖⃗𝑗 .
In C++ we use the overloaded operators:
for (int ip=0; ip<N; ip++) {
for (int jp=ip+1; jp<N; jp++) {
force f = points[ip].force_calc(points[jp]);
forces[ip] += f;
forces[jp] -= f;
}
}
Exercise 30.1. Argue that both the outer loop and the inner are not directly parallelizable.
We will now explore a number of different strategies for parallelization. All tests are done on the TACC Frontera
cluster, which has dual-socket Intel Cascade Lake nodes, with a total of 56 cores. Our code uses 10 thousand particles,
and each interaction evaluation is repeated 10 times to eliminate cache loading effects.
if (ip==jp) continue;
struct force f = force_calc(points[ip],points[jp]);
sumforce.x += f.x; sumforce.y += f.y; sumforce.f += f.f;
} // end parallel jp loop
add_force( forces+ip, sumforce );
} // end ip loop
In C++ we use the fact that we can reduce on any class that has an addition operator:
for (int ip=0; ip<N; ip++) {
force sumforce;
#pragma omp parallel for reduction(+:sumforce)
for (int jp=0; jp<N; jp++) {
if (ip==jp) continue;
force f = points[ip].force_calc(points[jp]);
sumforce += f;
} // end parallel jp loop
forces[ip] += sumforce;
} // end ip loop
This increases the scalar work by a factor of two, but surprisingly, on a single thread the run time improves: we
measure a speedup of 6.51 over the supposedly ‘optimal’ code.
Exercise 30.2. What would be an explanation?
However, increasing the number of threads has limited benefits for this strategy. Figure 30.1 shows that the speedup
is not only sublinear: it actually decreases with increasing core count.
Exercise 30.3. What would be an explanation?
10
6
Speedup
2
Reference
1 18 37 56
20
15
Speedup
10
Reference
0
1 18 37 56
In post-order tree traversal you visit the subtrees before visiting the root. This is the traversal that you use to find
summary information about a tree, for instance the sum of all nodes, and the sums of nodes of all subtrees:
𝑠 ← ∑𝑐 𝑠𝑐
60
50
40
Speedup
30
20
10
Reference
0
1 18 37 56
101.7
101.3 Ideal
101
Speedup
100.7
100
1 18 37 56
#Threads
Sequential Inner loop reduction Triangle atomic Full atomic
if (attempt.has_value())
return attempt;
} // end if(feasible)
}
return {};
};
We create a task for each column, and since they are in a loop we use taskgroup rather than taskwait.
#pragma omp taskgroup
for (int col=0; col<N; col++) {
placement next = current;
next.at(iqueen) = col;
#pragma omp task firstprivate(next)
if (feasible(next)) {
// stuff
} // end if(feasible)
}
However, the sequential program had return and break statements in the loop, which is not allowed in workshare
constructs such as taskgroup. Therefore we introduce a return variable, declared as shared:
// queens0.cxx
optional<placement> result = {};
#pragma omp taskgroup
for (int col=0; col<N; col++) {
placement next = current;
next.at(iqueen) = col;
#pragma omp task firstprivate(next) shared(result)
if (feasible(next)) {
if (iqueen==N-1) {
result = next;
} else { // do next level
auto attempt = place_queen(iqueen+1,next);
if (attempt.has_value()) {
result = attempt;
}
} // end if(iqueen==N-1)
} // end if(feasible)
}
return result;
So that was easy, this computes the right solution, and it uses OpenMP tasks. Done?
Actually this runs very slowly because, now that we’ve dispensed with all early breaks from the loop, we in effect
traverse the whole search tree. (It’s not quite breadth-first, though.) Figure 30.5 shows this for 𝑁 = 12 with the Intel
compiler (version 2019) in the left panel, and the GNU compiler (version 9.1) in the middle. In both cases, the blue
bars give the result for the code with only the taskgroup directive, with time plotted as function of core count.
We see that, for the Intel compiler, running time indeed goes down with core count. So, while we compute too much
(the whole search space), at least parallelization helps. With a number of threads greater than the problem size, the
benefit of parallelization disappears, which makes some sort of sense.
We also see that the GCC compiler is really bad at OpenMP tasks: the running time actually increases with the
number of threads.
Fortunately, with OpenMP-4 we can break out of the loop with a cancel of the task group:
// queenfinal.cxx
5
4.1 25 24.2 23.7
4 22.5
20.5
20
3 2.7
15
sec
sec
15
2
2
10 9.3
1
1 0.68 0.63 5
0.59
2.3
0 0
1 2 4 8 12 13 14 1 2 4 8 12 13 14
#cores used #cores used
Figure 30.5: Using taskgroups for 𝑁 = 12; left Intel compiler, right GCC
if (feasible(next)) {
if (iqueen==N-1) {
result = next;
#pragma omp cancel taskgroup
} else { // do next level
auto attempt = place_queen(iqueen+1,next);
if (attempt.has_value()) {
result = attempt;
#pragma omp cancel taskgroup
}
} // end if (iqueen==N-1)
} // end if (feasible)
Surprisingly, this does not immediately give a performance improvement. The reason for this is that cancellation is
disabled by default, and we have to set the environment variable
OMP_CANCELLATION=true
With that, we get very good performance, as figure 30.6 shows, which lists sequential time, and multicore running
time on the code with cancel directives. Running time is now approximately the same as the sequential time. Some
questions are still left:
• Why does the time go up with core count?
• Why is the multicore code slower than the sequential code, and would the parallel code be faster than
sequential if the amount of scalar work (for instance in the feasible function) would be larger?
One observation not reported here is that the GNU compiler has basically the same running time with and without
cancellation. This is again shows that the GNU compiler is really bad at OpenMP tasks.
⋅10−2
1.6
1.4
1.2
1.1 ⋅ 10−2
1 ⋅ 10−2 1 ⋅ 10−2
1
0.8
sec
6 ⋅ 10−3
0.6
5 ⋅ 10−3
4 ⋅ 10−3
0.4
0.2
1 ⋅ 10−3
4 ⋅ 10−4
0
−0.2
seq 1 2 4 8 12 13 14
#cores used
C++ note 20: List filtering example. We will do this example only in C++ because of its ease of handling
std::vectors.
There are two problems here. First is the race condition on the filtered array. Even if we fix this with a critical region,
there remains the lack of ordering of inserted elements.
The key to the solution is to let each thread have a local array, and then to concatenate these:
#pragma omp parallel
{
vector<int> local;
# pragma omp for
for ( auto e : data )
if ( f(e) )
local.push_back(e);
filtered += local;
}
The problem here is that OpenMP reductions can not be declared non-commutative, so the contributions from the
threads may not appear in order.
Code: Output:
// filteratomic.cxx Mod 5: 5 10 15 20 25 30 35 40 45 50
# pragma omp critical
if (threadnum==ithread) {
filtered += local;
ithread++;
The problem here is that threads who decide it’s not their turn will simply skip the append operation: there is no
way to tell them to wait their turn. (You could experiment with a while loop. Try it.)
The best solution is to use a completely different mechanism.
// filtertask.cxx Mod 5: 5 10 15 20 25 30 35 40 45 50 55 60 65 70
# pragma omp task \ ↪75 80 85 90 95 100
shared(filtered,ithread)
{
// wait your turn
while (threadnum>ithread) {
# pragma omp taskyield
}
// merge
filtered += local;
ithread++;
}
One reason this doesn’t work, is that the compiler will see that the flag is never used in the producing section, and
that is never changed in the consuming section, so it may optimize these statements, to the point of optimizing
them away.
The producer then needs to do:
... do some producing work ...
#pragma omp flush
#pragma atomic write
flag = 1;
#pragma omp flush(flag)
This code strictly speaking has a race condition on the flag variable.
The solution is to make this an atomic operation and use an atomic pragma here: the producer has
#pragma atomic write
flag = 1;
PETSC
Chapter 31
PETSc basics
Remark 35 The PETSc library has hundreds of routines. In this chapter and the next few we will only touch on a basic
subset of these. The full list of man pages can be found at https://petsc.org/release/docs/manualpages/
singleindex.html. Each man page comes with links to related routines, as well as (usually) example codes for that
routine.
468
31.1. What is PETSc and why?
MatMult(A,x,y); // y <- Ax
VecCopy(y,res); // r <- y
VecAXPY(res,-1.,b); // r <- r - b
31.1.4.2 Fortran
A Fortran90 interface exists. The Fortran77 interface is only of interest for historical reasons.
To use Fortran, include both a module and a cpp header file:
#include "petsc/finclude/petscXXX.h"
use petscXXX
(here XXX stands for one of the PETSc types, but including petsc.h and using use petsc gives inclusion of the
whole library.)
Variables can be declared with their type (Vec, Mat, KSP et cetera), but internally they are Fortran Type objects so
they can be declared as such.
Example:
#include "petsc/finclude/petscvec.h"
use petscvec
Vec b
type(tVec) x
The output arguments of many query routines are optional in PETSc. While in C a generic NULL can be passed,
Fortran has type-specific nulls, such as PETSC_NULL_INTEGER, PETSC_NULL_OBJECT.
31.1.4.3 Python
A python interface was written by Lisandro Dalcin. It can be added to to PETSc at installation time; section 31.3.
This book discusses the Python interface in short remarks in the appropriate sections.
31.1.5 Documentation
PETSc comes with a manual in pdf form and web pages with the documentation for every routine. The starting
point is the web page https://petsc.org/release/documentation/.
There is also a mailing list with excellent support for questions and bug reports.
TACC note. For questions specific to using PETSc on TACC resources, submit tickets to the TACC or XSEDE
portal.
If don’t want to include those configuration files, you can find out the include options by:
cd $PETSC_DIR
make getincludedirs
make getlinklibs
and copying the results into your compilation script.
There is an example makefile $PETSC_DIR/share/petsc/Makefile.user you can take for inspiration. Invoked
without arguments it prints out the relevant variables:
[c:246] make -f ! $PETSC_DIR/share/petsc/Makefile.user
CC=/Users/eijkhout/Installation/petsc/petsc-3.13/macx-clang-debug/bin/mpicc
CXX=/Users/eijkhout/Installation/petsc/petsc-3.13/macx-clang-debug/bin/mpicxx
FC=/Users/eijkhout/Installation/petsc/petsc-3.13/macx-clang-debug/bin/mpif90
CFLAGS=-Wall -Wwrite-strings -Wno-strict-aliasing -Wno-unknown-pragmas -fstack-protector -Qunused-argum
CXXFLAGS=-Wall -Wwrite-strings -Wno-strict-aliasing -Wno-unknown-pragmas -fstack-protector -fvisibility
FFLAGS=-m64 -g
CPPFLAGS=-I/Users/eijkhout/Installation/petsc/petsc-3.13/macx-clang-debug/include -I/Users/eijkhout/Ins
LDFLAGS=-L/Users/eijkhout/Installation/petsc/petsc-3.13/macx-clang-debug/lib -Wl,-rpath,/Users/eijkhout
LDLIBS=-lpetsc -lm
TACC note. On TACC clusters, a petsc installation is loaded by commands such as
module load petsc/3.16
Use module avail petsc to see what configurations exist. The basic versions are
# development
module load petsc/3.11-debug
# production
module load petsc/3.11
Other installations are real versus complex, or 64bit integers instead of the default 32. The command
module spider petsc
tells you all the available petsc versions. The listed modules have a naming convention such as
petsc/3.11-i64debug where the 3.11 is the PETSc release (minor patches are not included in this
version; TACC aims to install only the latest patch, but generally several versions are available), and
i64debug describes the debug version of the installation with 64bit integers.
31.2.2 Running
PETSc programs use MPI for parallelism, so they are started like any other MPI program:
mpiexec -n 5 -machinefile mf \
your_petsc_program option1 option2 option3
TACC note. On TACC clusters, use ibrun.
Input Parameters:
argc - count of number of command line arguments
args - the command line arguments
file - [optional] PETSc database file.
help - [optional] Help message to print, use NULL for no message
Fortran:
call PetscInitialize(file,ierr)
Input parameters:
ierr - error return code
file - [optional] PETSc database file,
use PETSC_NULL_CHARACTER to not check for code specific file.
int flag;
MPI_Initialized(&flag);
if (flag)
printf("MPI was initialized by PETSc\n");
else
printf("MPI not yet initialized\n");
If your main program is in C, but some of your PETSc calls are in Fortran files, it is necessary to call
PetscInitializeFortran after PetscInitialize.
!! init.F90
call PetscInitialize(PETSC_NULL_CHARACTER,ierr)
CHKERRA(ierr)
call MPI_Initialized(flag,ierr)
CHKERRA(ierr)
if (flag) then
print *,"MPI was initialized by PETSc"
Python note 37: Init, and with commandline options. The following works if you don’t need commandline options.
from petsc4py import PETSc
To pass commandline arguments to PETSc, do:
import sys
from petsc4py import init
init(sys.argv)
from petsc4py import PETSc
After initialization, you can use MPI_COMM_WORLD or PETSC_COMM_WORLD (which is created by MPI_Comm_dup and used
internally by PETSc):
MPI_Comm comm = PETSC_COMM_WORLD;
MPI_Comm_rank(comm,&mytid);
MPI_Comm_size(comm,&ntids);
31.3.1 Versions
PETSc is up to version 3.18.x as of this writing. Older versions may miss certain routines, or display certain bugs.
However, older versions may also contain routines and keywords that have subsequently been removed. PETSc
version are not backwards compatible!
The version is stored in macros PETSC_VERSION, PETSC_VERSION_MAJOR, PETSC_VERSION_MINOR,
PETSC_VERSION_SUBMINOR.
31.3.2 Debug
For any set of options, you will typically make two installations: one with -with-debugging=yes and once no.
See section 38.1.1 for more detail on the differences between debug and non-debug mode.
31.3.4 Variants
• Scalars: the option -with-scalar-type has values real, complex; -with-precision has values single,
double, __float128, __fp16.
Remark 36 There are two packages that PETSc is capable of downloading and install, but that you may want to avoid:
• fblaslapack: this gives you BLAS/LAPACK through the Fortran ‘reference implementation’. If you have
an optimized version, such as Intel’s mkl available, this will give much higher performance.
• mpich: this installs a MPI implementation, which may be required for your laptop. However, supercomputer
clusters will already have an MPI implementation that uses the high-speed network. PETSc’s downloaded
version does not do that. Again, finding and using the already installed software may greatly improve your
performance.
31.4.1 Slepc
Most external packages add functionality to the lower layers of Petsc. For instance, the Hypre package adds some
preconditioners to Petsc’s repertoire (section 35.1.7.3), while Mumps (section 35.2) makes it possible to use the LU
preconditioner in parallel.
On the other hand, there are packages that use Petsc as a lower level tool. In particular, the eigenvalue solver package
Slepc [27] can be installed through the options
--download-slepc=<no,yes,filename,url>
Download and install slepc current: no
--download-slepc-commit=commitid
The commit id from a git repository to use for the build of slepc current: 0
--download-slepc-configure-arguments=string
Additional configure arguments for the build of SLEPc
The slepc header files wind up in the same directory as the petsc headers, so no change to your compilation rules
are needed. However, you need to add -lslepc to the link line.
PETSc objects
The way the distribution is done is by contiguous blocks: with 10 processes and 1000 components in a vector, process
0 gets the range 0 ⋯ 99, process 1 gets 1 ⋯ 199, et cetera. This simple scheme suffices for many cases, but PETSc has
facilities for more sophisticated load balancing.
477
32. PETSc objects
Synopsis
#include "petscsys.h"
PetscErrorCode PetscSplitOwnership
(MPI_Comm comm,PetscInt *n,PetscInt *N)
Input Parameters
comm - MPI communicator that shares the object being divided
n - local length (or PETSC_DECIDE to have it set)
N - global length (or PETSC_DECIDE)
// split.c
N = 100; n = PETSC_DECIDE;
PetscSplitOwnership(comm,&n,&N);
PetscPrintf(comm,"Global %d, local %d\n",N,n);
N = PETSC_DECIDE; n = 10;
PetscSplitOwnership(comm,&n,&N);
PetscPrintf(comm,"Global %d, local %d\n",N,n);
While PETSc objects are implemented using local memory on each process, conceptually they act like global objects,
with a global indexing scheme. Thus, each process can query which elements out of the global object are stored
locally. For vectors, the relevant routine is VecGetOwnershipRange, which returns two parameters, low and high,
respectively the first element index stored, and one-more-than-the-last index stored.
This gives the idiom:
VecGetOwnershipRange(myvector,&low,&high);
for (int myidx=low; myidx<high; myidx++)
// do something at index myidx
These conversions between local and global size can also be done explicitly, using the PetscSplitOwnership (fig-
ure 32.1) routine. This routine takes two parameter, for the local and global size, and whichever one is initialized to
PETSC_DECIDE gets computed from the other.
32.2 Scalars
Unlike programming languages that explicitly distinguish between single and double precision numbers, PETSc has
only a single scalar type: PetscScalar. The precision of this is determined at installation time. In fact, a PetscScalar
can even be a complex number if the installation specified that the scalar type is complex.
Even in applications that use complex numbers there can be quantities that are real: for instance, the norm of a
complex vector is a real number. For that reason, PETSc also has the type PetscReal. There is also an explicit
PetscComplex.
Furthermore, there is
32.2.1 Integers
Integers in PETSc are likewise of a size determined at installation time: PetscInt can be 32 or 64 bits. The latter
possibility is useful for indexing into large vectors and matrices. Furthermore, there is a PetscErrorCode type for
catching the return code of PETSc routines; see section 38.1.2.
For compatibility with other packages there are two more integer types:
• PetscBLASInt is the integer type used by the Basic Linear Algebra Subprograms (BLAS) / Linear Alge-
bra Package (LAPACK) library. This is 32-bits if the -download-blas-lapack option is used, but it can
be 64-bit if MKL is used. The routine PetscBLASIntCast casts a PetscInt to PetscBLASInt, or returns
PETSC_ERR_ARG_OUTOFRANGE if it is too large.
• PetscMPIInt is the integer type of the MPI library, which is always 32-bits. The routine PetscMPIIntCast
casts a PetscInt to PetscMPIInt, or returns PETSC_ERR_ARG_OUTOFRANGE if it is too large.
Many external packages do not support 64-bit integers.
32.2.2 Complex
Numbers of type PetscComplex have a precision matching PetscReal.
Form a complex number using PETSC_i:
PetscComplex x = 1.0 + 2.0 * PETSC_i;
The real and imaginary part can be extract with the functions PetscRealPart and PetscImaginaryPart which return
a PetscReal.
There are also routines VecRealPart and VecImaginaryPart that replace a vector with its real or imaginary part
respectively. Likewise MatRealPart and MatImaginaryPart.
32.2.4 Booleans
There is a PetscBool datatype with values PETSC_TRUE and PETSC_FALSE.
F:
VecCreate( comm,v,ierr )
MPI_Comm :: comm
Vec :: v
PetscErrorCode :: ierr
Python:
vec = PETSc.Vec()
vec.create()
# or:
vec = PETSc.Vec().create()
Collective on Vec
Input Parameters:
v -the vector
The corresponding routine VecDestroy (figure 32.3) deallocates data and zeros the pointer. (This and all other De-
stroy routines are collective because of underlying MPI technicalities.)
The vector type needs to be set with VecSetType (figure 32.4).
The most common vector types are:
Collective on Vec
Input Parameters:
vec- The vector object
method- The name of the vector type
• VECSEQ for sequential vectors, that is, living on a single process; This is typically created on the
MPI_COMM_SELF or PETSC_COMM_SELF communicator.
• VECMPI for a vector distributed over the communicator. This is typically created on the MPI_COMM_WORLD
or PETSC_COMM_WORLD communicator, or one derived from it.
• VECSTANDARD is VECSEQ when used on a single process, or VECMPI on multiple.
You may wonder why these types exist: you could have just one type, which would be as parallel as possible. The
reason is that in a parallel run you may occasionally have a separate linear system on each process, which would
require a sequential vector (and matrix) on each process, not part of a larger linear system.
Once you have created one vector, you can make more like it by VecDuplicate,
VecDuplicate(Vec old,Vec *new);
or VecDuplicateVecs
VecDuplicateVecs(Vec old,PetscInt n,Vec **new);
for multiple vectors. For the latter, there is a joint destroy call VecDestroyVecs:
VecDestroyVecs(PetscInt n,Vec **vecs);
The size is queried with VecGetSize (figure 32.6) for the global size and VecGetLocalSize (figure 32.6) for the local
size.
Each processor gets a contiguous part of the vector. Use VecGetOwnershipRange (figure 32.7) to query the first index
Input Parameters
v :the vector
n : the local size (or PETSC_DECIDE to have it set)
N : the global size (or PETSC_DECIDE)
Python:
PETSc.Vec.setSizes(self, size, bsize=None)
size is a tuple of local/global
C:
#include "petscvec.h"
PetscErrorCode VecGetSize(Vec x,PetscInt *gsize)
PetscErrorCode VecGetLocalSize(Vec x,PetscInt *lsize)
Input Parameter
x -the vector
Output Parameters
gsize - the global length of the vector
lsize - the local length of the vector
Python:
PETSc.Vec.getLocalSize(self)
PETSc.Vec.getSize(self)
PETSc.Vec.getSizes(self)
Input parameter:
x - the vector
Output parameters:
low - the first local element, pass in NULL if not interested
high - one more than the last local element, pass in NULL if not interested
Fortran note:
use PETSC_NULL_INTEGER for NULL.
Input Parameters:
alpha - the scalar
x, y - the vectors
Output Parameter:
y - output vector
Python:
PETSc.Vec.view(self, Viewer viewer=None)
As you will see in section 32.4.1, you can also create vectors based on the layout of a matrix, using MatCreateVecs.
Collective on Vec
Input Parameters:
x, y - the vectors
Output Parameter:
val - the dot product
Input Parameters:
x - the vector
alpha - the scalar
Output Parameter:
x - the scaled vector
PetscCall( VecView(signal,PETSC_VIEWER_STDOUT_WORLD) );
PetscCall( MatMult(transform,signal,frequencies) );
PetscCall( VecScale(frequencies,1./Nglobal) );
PetscCall( VecView(frequencies,PETSC_VIEWER_STDOUT_WORLD) );
but the routine call also use more general PetscViewer objects, for instance to dump a vector to file.
Here are a couple of representative vector routines:
PetscReal lambda;
ierr = VecNorm(y,NORM_2,&lambda); CHKERRQ(ierr);
ierr = VecScale(y,1./lambda); CHKERRQ(ierr);
Exercise 32.1. Create a vector where the values are a single sine wave. using VecGetSize,
VecGetLocalSize, VecGetOwnershipRange. Quick visual inspection:
ibrun vec -n 12 -vec_view
(There is a skeleton for this exercise under the name vec.)
Exercise 32.2. Use the routines VecDot (figure 32.10), VecScale (figure 32.11) and VecNorm
(figure 32.12) to compute the inner product of vectors x,y, scale the vector x, and check its
norm:
𝑝 ← 𝑥𝑡𝑦
𝑥 ← 𝑥/𝑝
𝑛 ← ‖𝑥‖2
Python note 42: Vector operations. The plus operator is overloaded so that
Python:
PETSc.Vec.norm(self, norm_type=None)
x+y
is defined.
x.sum() # max,min,....
x.dot(y)
x.norm(PETSc.NormType.NORM_INFINITY)
In the general case, setting elements in a PETSc vector is done through a function VecSetValue (figure 32.13) for
setting elements that uses global numbering; any process can set any elements in the vector. There is also a routine
VecSetValues (figure 32.14) for setting multiple elements. This is mostly useful for setting dense subblocks of a
block matrix.
We illustrate both routines by setting a single element with VecSetValue, and two elements with VecSetValues. In
the latter case we need an array of length two for both the indices and values. The indices need not be successive.
Not Collective
Input Parameters
v- the vector
row- the row location of the entry
value- the value to insert
mode- either INSERT_VALUES or ADD_VALUES
Not Collective
Input Parameters:
x - vector to insert in
ni - number of elements to add
ix - indices where to add
y - array of values
iora - either INSERT_VALUES or ADD_VALUES, where
ADD_VALUES adds values to any existing entries, and
INSERT_VALUES replaces existing entries with new values
i = 1; v = 3.14;
VecSetValue(x,i,v,INSERT_VALUES);
ii[0] = 1; ii[1] = 2; vv[0] = 2.7; vv[1] = 3.1;
VecSetValues(x,2,ii,vv,INSERT_VALUES);
Fortran note 26: Setting values. The value/values routines work the same way in Fortran. Note that despite type
checking, using the ‘values’ routine and passing scalars, is allowed:
Python note 43: Setting vector values. Single element:
x.setValue(0,1.)
Multiple elements:
x.setValues( [2*procno,2*procno+1], [2.,3.] )
Using VecSetValue for specifying a local vector element corresponds to simple insertion in the local array. However,
an element that belongs to another process needs to be transferred. This done in two calls: VecAssemblyBegin
(figure 32.15) and VecAssemblyEnd.
Collective on Vec
Input Parameter
vec -the vector
if (myrank==0) then
do vecidx=0,globalsize-1
vecelt = vecidx
call VecSetValue(vector,vecidx,vecelt,INSERT_VALUES,ierr)
end do
end if
call VecAssemblyBegin(vector,ierr)
call VecAssemblyEnd(vector,ierr)
(If you know the MPI library, you’ll recognize that the first call corresponds to posting nonblocking send and receive
calls; the second then contains the wait calls. Thus, the existence of these separate calls make latency hiding possible.)
VecAssemblyBegin(myvec);
// do work that does not need the vector myvec
VecAssemblyEnd(myvec);
Elements can either be inserted with INSERT_VALUES, or added with ADD_VALUES in the VecSetValue / VecSetValues
call. You can not immediately mix these modes; to do so you need to call VecAssemblyBegin / VecAssemblyEnd in
between add/insert phases.
Input Parameters:
x- the vector
a- location of pointer to array obtained from VecGetArray()
Fortran90:
#include <petsc/finclude/petscvec.h>
use petscvec
VecRestoreArrayF90(Vec x,{Scalar, pointer :: xx_v(:)},integer ierr)
Input Parameters:
x- vector
xx_v- the Fortran90 pointer to the array
PETSc insists that you properly release this pointer again with VecRestoreArray (figure 32.17) or
VecRestoreArrayRead (figure 32.17).
In the following example, a vector is scaled through direct array access. Note the differing calls for the source and
target vector, and note the const qualifier on the source array:
// vecarray.c
PetscScalar const *in_array;
PetscScalar *out_array;
VecGetArrayRead(x,&in_array);
VecGetArray(y,&out_array);
PetscInt localsize;
VecGetLocalSize(x,&localsize);
for (int i=0; i<localsize; i++)
out_array[i] = 2*in_array[i];
VecRestoreArrayRead(x,&in_array);
VecRestoreArray(y,&out_array);
This example also uses VecGetLocalSize to determine the size of the data accessed. Even running in a distributed
context you can only get the array of local elements. Accessing the elements from another process requires explicit
communication; see section 32.5.2.
#include "petscvec.h"
PetscErrorCode VecPlaceArray(Vec vec,const PetscScalar array[])
PetscErrorCode VecReplaceArray(Vec vec,const PetscScalar array[])
Input Parameters
vec - the vector
array - the array
Fortran note 27: F90 array access through pointer. There are routines such as VecGetArrayF90 (with corresponding
VecRestoreArrayF90) that return a (Fortran) pointer to a one-dimensional array.
!! vecset.F90
Vec :: vector
PetscScalar,dimension(:),pointer :: elements
call VecGetArrayF90(vector,elements,ierr)
write (msg,10) myrank,elements(1)
10 format("First element on process",i3,":",f7.4,"\n")
call PetscSynchronizedPrintf(comm,msg,ierr)
call PetscSynchronizedFlush(comm,PETSC_STDOUT,ierr)
call VecRestoreArrayF90(vector,elements,ierr)
!! vecarray.F90
PetscScalar,dimension(:),Pointer :: &
in_array,out_array
call VecGetArrayReadF90( x,in_array,ierr )
call VecGetArrayF90( y,out_array,ierr )
call VecGetLocalSize( x,localsize,ierr )
do index=1,localsize
out_array(index) = 2*in_array(index)
end do
call VecRestoreArrayReadF90( x,in_array,ierr )
call VecRestoreArrayF90( y,out_array,ierr )
Python:
mat = PETSc.Mat()
mat.create()
# or:
mat = PETSc.Mat().create()
Collective on Mat
Input Parameters:
mat- the matrix object
matype- matrix type
Since these operations are each other’s inverses, usually you don’t need to know the file format. But just in case:
PetscInt VEC_FILE_CLASSID
PetscInt number of rows
PetscScalar *values of all entries
That is, the file starts with a magic number, then the number of vector elements, and subsequently all scalar values.
Input Parameters
A : the matrix
m : number of local rows (or PETSC_DECIDE)
n : number of local columns (or PETSC_DECIDE)
M : number of global rows (or PETSC_DETERMINE)
N : number of global columns (or PETSC_DETERMINE)
Python:
PETSc.Mat.setSizes(self, size, bsize=None)
where 'size' is a tuple of 2 global sizes
or a tuple of 2 local/global pairs
Just as with vectors, there is a local and global size; except that that now applies to rows and columns. Set sizes with
MatSetSizes (figure 32.21) and subsequently query them with MatSizes (figure 32.22). The concept of local column
size is tricky: since a process stores a full block row you may expect the local column size to be the full matrix size,
but that is not true. The exact definition will be discussed later, but for square matrices it is a safe strategy to let the
local row and column size to be equal.
Instead of querying a matrix size and creating vectors accordingly, the routine MatCreateVecs (figure 32.23) can be
used. (Sometimes this is even required; see section 32.4.9.)
Python:
PETSc.Mat.getSize(self) # tuple of global sizes
PETSc.Mat.getLocalSize(self) # tuple of local sizes
PETSc.Mat.getSizes(self) # tuple of local/global size tuples
#include "petscmat.h"
PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
Collective on Mat
Input Parameter
mat - the matrix
Output Parameter;
right - (optional) vector that the matrix can be multiplied against
left - (optional) vector that the matrix vector product can be stored in
matrix can be anywhere between completely empty and completely filled in. It would be possible to have a dynamic
approach where, as elements are specified, the space grows; however, repeated allocations and re-allocations are
inefficient. For this reason PETSc puts a small burden on the programmer: you need to specify a bound on how
many elements the matrix will contain.
We explain this by looking at some cases. First we consider a matrix that only lives on a single process. You would
then use MatSeqAIJSetPreallocation (figure 32.24). In the case of a tridiagonal matrix you would specify that each
row has three elements:
MatSeqAIJSetPreallocation(A,3, NULL);
If the matrix is less regular you can use the third argument to give an array of explicit row lengths:
int *rowlengths;
// allocate, and then:
for (int row=0; row<nrows; row++)
rowlengths[row] = // calculation of row length
MatSeqAIJSetPreallocation(A,NULL,rowlengths);
In case of a distributed matrix you need to specify this bound with respect to the block structure of the matrix.
As illustrated in figure 32.2, a matrix has a diagonal part and an off-diagonal part. The diagonal part describes the
matrix elements that couple elements of the input and output vector that live on this process. The off-diagonal part
contains the matrix elements that are multiplied with elements not on this process, in order to compute elements
that do live on this process.
Input Parameters
B - the matrix
nz/d_nz/o_nz - number of nonzeros per row in matrix or
diagonal/off-diagonal portion of local submatrix
nnz/d_nnz/o_nnz - array containing the number of nonzeros in the various rows of
the sequential matrix / diagonal / offdiagonal part of the local submatrix
or NULL (PETSC_NULL_INTEGER in Fortran) if nz/d_nz/o_nz is used.
Python:
PETSc.Mat.setPreallocationNNZ(self, [nnz_d,nnz_o] )
PETSc.Mat.setPreallocationCSR(self, csr)
PETSc.Mat.setPreallocationDense(self, array)
Off−diagonal block
has off−processor connections
A B
The preallocation specification now has separate parameters for these diagonal and off-diagonal parts: with
MatMPIAIJSetPreallocation (figure 32.24). you specify for both either a global upper bound on the number of
nonzeros, or a detailed listing of row lengths. For the matrix of the Laplace equation, this specification would seem
to be:
MatMPIAIJSetPreallocation(A, 3, NULL, 2, NULL);
However, this is only correct if the block structure from the parallel division equals that from the lines in the domain.
In general it may be necessary to use values that are an overestimate. It is then possible to contract the storage by
copying the matrix.
Specifying bounds on the number of nonzeros is often enough, and not too wasteful. However, if many rows have
Input Parameters
m : the matrix
row : the row location of the entry
col : the column location of the entry
value : the value to insert
mode : either INSERT_VALUES or ADD_VALUES
Python:
PETSc.Mat.setValue(self, row, col, value, addv=None)
also supported:
A[row,col] = value
Input Parameters
mat- the matrix
type- type of assembly, either MAT_FLUSH_ASSEMBLY
or MAT_FINAL_ASSEMBLY
Python:
assemble(self, assembly=None)
assemblyBegin(self, assembly=None)
assemblyEnd(self, assembly=None)
fewer nonzeros than these bounds, a lot of space is wasted. In that case you can replace the NULL arguments by an
array that lists for each row the number of nonzeros in that row.
#include "petscmat.h"
PetscErrorCode MatGetRow
(Mat mat,PetscInt row,
PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
PetscErrorCode MatRestoreRow
(Mat mat,PetscInt row,
PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
Input Parameters:
mat - the matrix
row - the row to get
Output Parameters
ncols - if not NULL, the number of nonzeros in the row
cols - if not NULL, the column numbers
vals - if not NULL, the values
PETSc sparse matrices are very flexible: you can create them empty and then start adding elements. However, this
is very inefficient in execution since the OS needs to reallocate the matrix every time it grows a little. Therefore,
PETSc has calls for the user to indicate how many elements the matrix will ultimately contain.
MatSetOption(A, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE)
Input Parameters
mat - the matrix
x - the vector to be multiplied
Output Parameters
y - the result
Input Parameters
mat - the matrix
x, y - the vectors
Output Parameters
z -the result
Notes
The vectors x and z cannot be the same.
where -mat_view is activated by the assembly routine, while -ksp_mat_view shows only the matrix used as operator
for a KSP object. Without further option refinements this will display the matrix elements inside the sparsity pattern.
Using a sub-option draw will cause the sparsity pattern to be displayed in an X11 window.
Collective
Input Parameters:
comm- MPI communicator
m- number of local rows (must be given)
n- number of local columns (must be given)
M- number of global rows (may be PETSC_DETERMINE)
N- number of global columns (may be PETSC_DETERMINE)
ctx- pointer to data needed by the shell matrix routines
Output Parameter:
A -the matrix
32.4.6 Submatrices
Given a parallel matrix, there are two routines for extracting submatrices:
• MatCreateSubMatrix creates a single parallel submatrix.
• MatCreateSubMatrices creates a sequential submatrix on each process.
The routine that implements the actual product should have the same signature as MatMult, accepting a matrix and
two vectors. The key to realizing your own product routine lies in the ‘context’ argument to the create routine. With
MatShellSetContext (figure 32.32) you pass a pointer to some structure that contains all contextual information you
need. In your multiplication routine you then retrieve this with MatShellGetContext (figure 32.33).
What operation is specified is determined by a keyword MATOP_<OP> where OP is the name of the matrix routine,
minus the Mat part, in all caps.
Input Parameters:
mat- the shell matrix
op- the name of the operation
g- the function that provides the operation.
Input Parameters
mat - the shell matrix
ctx - the context
MatCreate(comm,&A);
MatSetSizes(A,localsize,localsize,matrix_size,matrix_size);
MatSetType(A,MATSHELL);
MatSetFromOptions(A);
MatShellSetOperation(A,MATOP_MULT,(void*)&mymatmult);
MatShellSetContext(A,(void*)Diag);
MatSetUp(A);
The routine signature has this argument as a void* but it’s not necessary to cast it to that. Getting the context
means that a pointer to your structure needs to be set
struct matrix_data *mystruct;
MatShellGetContext( A, &mystruct );
Somewhat confusingly, the Get routine also has a void* argument, even though it’s really a pointer variable.
Not Collective
Input Parameter:
mat -the matrix, should have been created with MatCreateShell()
Output Parameter:
ctx -the user provided context
The fftw library does not scale the output vector, so a forward followed by a backward pass gives a result that is too
large by the vector size.
// fftsine.c
PetscCall( VecView(signal,PETSC_VIEWER_STDOUT_WORLD) );
PetscCall( MatMult(transform,signal,frequencies) );
PetscCall( VecScale(frequencies,1./Nglobal) );
PetscCall( VecView(frequencies,PETSC_VIEWER_STDOUT_WORLD) );
#include "petscvec.h"
PetscErrorCode VecScatterCreate(Vec xin,IS ix,Vec yin,IS iy,VecScatter *newctx)
Input Parameters:
xin : a vector that defines the layout of vectors from which we scatter
yin : a vector that defines the layout of vectors to which we scatter
ix : the indices of xin to scatter (if NULL scatters all values)
iy : the indices of yin to hold results (if NULL fills entire vector yin)
Output Parameter
newctx : location to store the new scatter context
PetscCall( ISCreateStride(comm,Nglobal/2,1,2,&oddeven) );
}
After this, there are various query and set operations on index sets.
You can read out the indices of a set by ISGetIndices and ISRestoreIndices.
Note that the index set is applied to the input vector, since it describes the components to be moved. The output
vector uses NULL since these components are placed in sequence.
Exercise 32.3. Modify this example so that the components are still separated odd/even, but now
placed in descending order on each process.
Exercise 32.4. Can you extend this example so that process 𝑝 receives all indices that are multiples
of 𝑝? Is your solution correct if Nglobal is not a multiple of nprocs?
32.7 Partitionings
By default, PETSc uses partitioning of matrices and vectors based on consecutive blocks of variables. In regular
cases that is not a bad strategy. However, for some matrices a permutation and re-division can be advantageous.
For instance, one could look at the adjacency graph, and minimize the number of edge cuts or the sum of the edge
weights.
This functionality is not built into PETSc, but can be provided by graph partitioning packages such as ParMetis or
Zoltan. The basic object is the MatPartitioning, with routines for
• Create and destroy: MatPartitioningCreate, MatPartitioningDestroy;
• Setting the type MatPartitioningSetType to an explicit partitioner, or something generated as the dual
or a refinement of the current matrix;
• Apply with MatPartitioningApply, giving a distribued IS object, which can then be used in
MatCreateSubMatrix to repartition.
Illustrative example:
MatPartitioning part;
MatPartitioningCreate(comm,&part);
MatPartitioningSetType(part,MATPARTITIONINGPARMETIS);
MatPartitioningApply(part,&is);
/* get new global number of each old global number */
ISPartitioningToNumbering(is,&isn);
ISBuildTwoSided(is,NULL,&isrows);
MatCreateSubMatrix(A,isrows,isrows,MAT_INITIAL_MATRIX,&perA);
Other scenario:
MatPartitioningSetAdjacency(part,A);
MatPartitioningSetType(part,MATPARTITIONINGHIERARCH);
MatPartitioningHierarchicalSetNcoarseparts(part,2);
MatPartitioningHierarchicalSetNfineparts(part,2);
Grid support
PETSc’s DM objects raise the abstraction level from the linear algebra problem to the physics problem: they allow
for a more direct expression of operators in terms of their domain of definition. In this section we look at the DMDA
‘distributed array’ objects, which correspond to problems defined on Cartesian grids. Distributed arrays make it
easier to construct the coefficient matrix of an operator that is defined as a stencil on a 1/2/3-dimensional Cartesian
grid.
The main creation routine exists in three variants that mostly differ their number of parameters. For instance,
DMDACreate2d has parameters along the x,y axes. However, DMDACreate1d has no parameter for the stencil type,
since in 1D those are all the same, or for the process distribution.
504
33.1. Grid definition
Input Parameters
Output Parameter
• partitionx,partitiony are arrays giving explicit partitionings of the grid over the processors, or
PETSC_NULL for default distributions.
Code: Output:
After you define a DM object, each process has a contiguous subdomain out of the total grid. You can query its size
and location with DMDAGetCorners, or query that and all other information with DMDAGetLocalInfo (figure 33.2),
which returns an DMDALocalInfo (figure 33.3) structure.
(A DMDALocalInfo struct is the same for 1/2/3 dimensions, so certain fields may not be applicable to your specific
PDE.)
DMDALocalInfo :: info(DMDA_LOCAL_INFO_SIZE)
info(DMDA_LOCAL_INFO_DIM)
info(DMDA_LOCAL_INFO_DOF) etc.
The entries bx,by,bz, st, and da are not accessible from Fortran.
On each point of the domain, we describe the stencil at that point. First of all, we now have the information to
compute the 𝑥, 𝑦 coordinates of the domain points:
PetscReal **xyarray;
PetscCall( DMDAVecGetArray(grid,xy,&xyarray) );
for (int j=info.ys; j<info.ys+info.ym; j++) {
for (int i=info.xs; i<info.xs+info.xm; i++) {
PetscReal x = i*hx, y = j*hy;
xyarray[j][i] = x*y;
}
}
PetscCall( DMDAVecRestoreArray(grid,xy,&xyarray) );
In some circumstances, we want to perform stencil operations on the vector of a DMDA grid. This requires having
the halo region. Above, you already saw the gxs,gxm and other quantities relating to the halo of each process’
subdomain.
What we need is a way to make vectors that contain these halo points.
• You can make a traditonal vector corresponding to a grid with DMCreateGlobalVector; if you need this
vector only for a short while, use DMGetGlobalVector and DMRestoreGlobalVector.
• You can make a vector including halo points with DMCreateLocalVector; if you need this vector only for
a short while, use DMGetLocalVector and DMRestoreLocalVector.
• If you have a ‘global’ vector, you can made the corresponding ‘local’ vector, filling in its halo points, with
DMGlobalToLocal; after operating on a local vector, you can copy its non-halo part back to a global vector
with DMLocalToGlobal.
Here we set up a local vector for operations:
Vec ghostvector;
PetscCall( DMGetLocalVector(grid,&ghostvector) );
PetscCall( DMGlobalToLocal(grid,xy,INSERT_VALUES,ghostvector) );
PetscReal **xyarray,**gh;
PetscCall( DMDAVecGetArray(grid,xy,&xyarray) );
PetscCall( DMDAVecGetArray(grid,ghostvector,&gh) );
// computation on the arrays
PetscCall( DMDAVecRestoreArray(grid,xy,&xyarray) );
PetscCall( DMDAVecRestoreArray(grid,ghostvector,&gh) );
PetscCall( DMLocalToGlobal(grid,ghostvector,INSERT_VALUES,xy) );
PetscCall( DMRestoreLocalVector(grid,&ghostvector) );
The actual operations involve some tests for the actual presence of the halo:
for (int j=info.ys; j<info.ys+info.ym; j++) {
for (int i=info.xs; i<info.xs+info.xm; i++) {
if (info.gxs<info.xs && info.gys<info.ys)
if (i-1>=info.gxs && i+1<=info.gxs+info.gxm &&
j-1>=info.gys && j+1<=info.gys+info.gym )
xyarray[j][i] =
( gh[j-1][i] + gh[j][i-1] + gh[j][i+1] + gh[j+1][i] )
/4.;
Each matrix element row,col is a combination of two MatStencil objects. Technically, this is a struct with members
i,j,k,s for the domain coordinates and the number of the field.
MatStencil row;
row.i = i; row.j = j;
We could construct the columns in this row one by one, but MatSetValuesStencil can set multiple rows or columns
at a time, so we construct all columns at the same time:
MatStencil col[5];
PetscScalar v[5];
PetscInt ncols = 0;
/**** diagonal element ****/
col[ncols].i = i; col[ncols].j = j;
v[ncols++] = 4.;
The other ‘legs’ of the stencil need to be set conditionally: the connection to (𝑖 − 1, 𝑗) is missing on the top row of
the domain, and the connection to (𝑖, 𝑗 − 1) is missing on the left column. In all:
// grid2d.c
for (int j=info.ys; j<info.ys+info.ym; j++) {
for (int i=info.xs; i<info.xs+info.xm; i++) {
MatStencil row,col[5];
PetscScalar v[5];
PetscInt ncols = 0;
row.j = j; row.i = i;
/**** local connection: diagonal element ****/
col[ncols].j = j; col[ncols].i = i; v[ncols++] = 4.;
/* boundaries: top and bottom row */
if (i>0) {col[ncols].j = j; col[ncols].i = i-1; v[ncols++] = -1.;}
if (i<info.mx-1) {col[ncols].j = j; col[ncols].i = i+1; v[ncols++] = -1.;}
/* boundary left and right */
if (j>0) {col[ncols].j = j-1; col[ncols].i = i; v[ncols++] = -1.;}
if (j<info.my-1) {col[ncols].j = j+1; col[ncols].i = i; v[ncols++] = -1.;}
PetscCall( MatSetValuesStencil(A,1,&row,ncols,col,v,INSERT_VALUES) );
}
}
After this, you don’t use VecSetValues, but set elements directly in the raw array, obtained by DMDAVecGetArray:
PetscReal **xyarray;
PetscCall( DMDAVecGetArray(grid,xy,&xyarray) );
for (int j=info.ys; j<info.ys+info.ym; j++) {
for (int i=info.xs; i<info.xs+info.xm; i++) {
PetscReal x = i*hx, y = j*hy;
xyarray[j][i] = x*y;
}
}
PetscCall( DMDAVecRestoreArray(grid,xy,&xyarray) );
2. You can create a ‘local’ vector, which is sequential and defined on PETSC_COMM_SELF, that has not only
the points local to the process, but also the ‘halo’ region with the extent specified in the definition of the
DMDACreate call. For this, use DMCreateLocalVector:
With this subdomain information you can then start to create the coefficient matrix:
DM grid;
PetscInt i_first,j_first,i_local,j_local;
DMDAGetCorners(grid,&i_first,&j_first,NULL,&i_local,&j_local,NULL);
for ( PetscInt i_index=i_first; i_index<i_first+i_local; i_index++) {
for ( PetscInt j_index=j_first; j_index<j_first+j_local; j_index++) {
// construct coefficients for domain point (i_index,j_index)
}
}
Note that indexing here is in terms of the grid, not in terms of the matrix.
For a simple example, consider 1-dimensional smoothing. From DMDAGetCorners we need only the parameters in
𝑖-direction:
// grid1d.c
PetscInt i_first,i_local;
PetscCall( DMDAGetCorners(grid,&i_first,NULL,NULL,&i_local,NULL,NULL) );
for (PetscInt i_index=i_first; i_index<i_first+i_local; i_index++) {
We then use a single loop to set elements for the local range in 𝑖-direction:
MatStencil row = {0},col[3] = {{0}};
PetscScalar v[3];
PetscInt ncols = 0;
row.i = i_index;
col[ncols].i = i_index; v[ncols] = 2.;
ncols++;
if (i_index>0) { col[ncols].i = i_index-1; v[ncols] = 1.; ncols++; }
if (i_index<i_global-1) { col[ncols].i = i_index+1; v[ncols] = 1.; ncols++; }
PetscCall( MatSetValuesStencil(A,1,&row,ncols,col,v,INSERT_VALUES) );
and parallel:
513
34. Finite Elements support
Code: Output:
14 32 15 30 16 10
8 20 9 18 10
7 5 3 1
21 20 31 28 29 15 11
14 19 16 17
1 6 1 2
11 22 12 26 13 7 16 68 20
14 79
2 3 2 3
19 18 23 24 25 13 12 17
12 18
13 19
0 4 0 0
8 17 9 27 10 4 11 45 15 56
// plexsphere.c
ierr = DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd);
ierr = PetscSectionCreate(PetscObjectComm((PetscObject) dm), &s);
ierr = DMSetLocalSection(dm, s);
ierr = PetscSectionDestroy(&s);
PETSc solvers
Probably the most important activity in PETSc is solving a linear system. This is done through a solver object: an
object of the class KSP. (This stands for Krylov SPace solver.) The solution routine KSPSolve takes a matrix and a
right-hand-side and gives a solution; however, before you can call this some amount of setup is needed.
There two very different ways of solving a linear system: through a direct method, essentially a variant of Gaussian
elimination; or through an iterative method that makes successive approximations to the solution. In PETSc there
are only iterative methods. We will show how to achieve direct methods later. The default linear system solver in
PETSc is fully parallel, and will work on many linear systems, but there are many settings and customizations to
tailor the solver to your specific problem.
?𝑥 ∶ 𝐴𝑥 = 𝑏
The elementary textbook way of solving this is through an LU factorization, also known as Gaussian elimination:
𝐿𝑈 ← 𝐴, 𝐿𝑧 = 𝑏, 𝑈 𝑥 = 𝑧.
While PETSc has support for this, its basic design is geared towards so-called iterative solution methods. Instead of
directly computing the solution to the system, they compute a sequence of approximations that, with luck, converges
to the true solution:
while not converged
𝑥𝑖+1 ← 𝑓 (𝑥𝑖 )
The interesting thing about iterative methods is that the iterative step only involves the matrix-vector product:
while not converged
𝑟𝑖 = 𝐴𝑥𝑖 − 𝑏
𝑥𝑖+1 ← 𝑓 (𝑟𝑖 )
This residual is also crucial in determining whether to stop the iteration: since we (clearly) can not measure the
distance to the true solution, we use the size of the residual as a proxy measurement.
517
35. PETSc solvers
Python:
ksp = PETSc.KSP()
ksp.create()
# or:
ksp = PETSc.KSP().create()
The remaining point to know is that iterative methods feature a preconditioner. Mathematically this is equivalent
to transforming the linear system to
𝑀 −1 𝐴𝑥 = 𝑀 −1 𝑏
so conceivably we could iterate on the transformed matrix and right-hand side. However, in practice we apply the
preconditioner in each iteration:
while not converged
𝑟𝑖 = 𝐴𝑥𝑖 − 𝑏
𝑧𝑖 = 𝑀 −1 𝑟𝑖
𝑥𝑖+1 ← 𝑓 (𝑧𝑖 )
In this schematic presentation we have left the nature of the 𝑓 () update function unspecified. Here, many possibilities
exist; the primary choice here is of the iterative method type, such as ‘conjugate gradients’, ‘generalized minimum
residual’, or ‘bi-conjugate gradients stabilized’. (We will go into direct solvers in section 35.2.)
Quantifying issues of convergence speed is difficult; see HPC book, section-5.5.14.
using various default settings. The vectors and the matrix have to be conformly partitioned. The KSPSetOperators
call takes two operators: one is the actual coefficient matrix, and the second the one that the preconditioner is
derived from. In some cases it makes sense to specify a different matrix here. (You can retrieve the operators with
KSPGetOperators.) The call KSPSetFromOptions can cover almost all of the settings discussed next.
KSP objects have many options to control them, so it is convenient to call KSPView (or use the commandline option
-ksp_view) to get a listing of all the settings.
Input Parameters:
ksp- the Krylov subspace context
rtol- the relative convergence tolerance, relative decrease in the
(possibly preconditioned) residual norm
abstol- the absolute convergence tolerance absolute size of the
(possibly preconditioned) residual norm
dtol- the divergence tolerance, amount (possibly preconditioned)
residual norm can increase before KSPConvergedDefault() concludes that
the method is diverging
maxits- maximum number of iterations to use
35.1.3 Tolerances
Since neither solution nor solution speed is guaranteed, an iterative solver is subject to some tolerances:
• a relative tolerance for when the residual has been reduced enough;
• an absolute tolerance for when the residual is objectively small;
• a divergence tolerance that stops the iteration if the residual grows by too much; and
• a bound on the number of iterations, regardless any progress the process may still be making.
These tolerances are set with KSPSetTolerances (figure 35.2), or options -ksp_atol, -ksp_rtol, -ksp_divtol,
-ksp_max_it. Specify to PETSC_DEFAULT to leave a value unaltered.
In the next section we will see how you can determine which of these tolerances caused the solver to stop.
Input Parameter
ksp -the KSP context
Output Parameter
reason -negative value indicates diverged, positive value converged,
see KSPConvergedReason
Python:
r = KSP.getConvergedReason(self)
where r in PETSc.KSP.ConvergedReason
Input Parameters:
ksp : the Krylov space context
type : a known method
Input Parameters
ksp - iterative context
B - block of right-hand sides
Output Parameter
X - block of solutions
• KSPCG: only for symmetric positive definite systems. It has a cost of both work and storage that is constant
in the number of iterations.
There are variants such as KSPPIPECG that are mathematically equivalent, but possibly higher performing
at large scale.
• KSPGMRES: a minimization method that works for nonsymmetric and indefinite systems. However, to
satisfy this theoretical property it needs to store the full residual history to orthogonalize each compute
residual to, implying that storage is linear, and work quadratic, in the number of iterations. For this
reason, GMRES is always used in a truncated variant, that regularly restarts the orthogonalization. The
restart length can be set with the routine KSPGMRESSetRestart or the option -ksp_gmres_restart.
• KSPBCGS: a quasi-minimization method; uses less memory than GMRES.
Depending on the iterative method, there can be several routines to tune its workings. Especially if you’re still
experimenting with what method to choose, it may be more convenient to specify these choices through comman-
dline options, rather than explicitly coded routines. In that case, a single call to KSPSetFromOptions is enough to
incorporate those.
35.1.7 Preconditioners
Another part of an iterative solver is the preconditioner. The mathematical background of this is given in sec-
tion 35.1.1. The preconditioner acts to make the coefficient matrix better conditioned, which will improve the con-
vergence speed; it can even be that without a suitable preconditioner a solver will not converge at all.
35.1.7.1 Background
The mathematical requirement that the preconditioner 𝑀 satisfy 𝑀 ≈ 𝐴 can take two forms:
1. We form an explicit approximation to 𝐴−1 ; this is known as a sparse approximate inverse.
2. We form an operator 𝑀 (often given in factored or other implicit) form, such that 𝑀 ≈ 𝐴, and solving a
system 𝑀𝑥 = 𝑦 for 𝑥 can be done relatively quickly.
In deciding on a preconditioner, we now have to balance the following factors.
1. What is the cost of constructing the preconditioner? This should not be more than the gain in solution
time of the iterative method.
2. What is the cost per iteration of applying the preconditioner? There is clearly no point in using a precon-
ditioner that decreases the number of iterations by a certain amount, but increases the cost per iteration
much more.
3. Many preconditioners have parameter settings that make these considerations even more complicated:
low parameter values may give a preconditioner that is cheaply to apply but does not improve conver-
gence much, while large parameter values make the application more costly but decrease the number of
iterations.
35.1.7.2 Usage
Unlike most of the other PETSc object types, a PC object is typically not explicitly created. Instead, it is created as
part of the KSP object, and can be retrieved from it.
PC prec;
KSPGetPC(solver,&prec);
PCSetType(prec,PCILU);
Beyond setting the type of the preconditioner, there are various type-specific routines for setting various parameters.
Some of these can get quite tedious, and it is more convenient to set them through commandline options.
35.1.7.3 Types
Method PCType Options Database Name
Jacobi PCJACOBI jacobi
Block Jacobi PCBJACOBI bjacobi
SOR (and SSOR) PCSOR sor
SOR with Eisenstat trick PCEISENSTAT eisenstat
Incomplete Cholesky PCICC icc
Incomplete LU PCILU ilu
Additive Schwarz PCASM asm
Generalized Additive Schwarz PCGASM gasm
Algebraic Multigrid PCGAMG gamg
Balancing Domain Decomposition PCBDDC bddc
by Constraints Linear solver
Use iterative method PCKSP ksp
Combination of preconditioners PCCOMPOSITE composite
LU PCLU lu
Cholesky PCCHOLESKY cholesky
No preconditioning PCNONE none
Shell for user-defined PC PCSHELL shell
35.1.7.3.1 Sparse approximate inverses The inverse of a sparse matrix (at least, those from PDEs) is typically
dense. Therefore, we aim to construct a sparse approximate inverse.
PETSc offers two such preconditioners, both of which require an external package.
• PCSPAI. This is a preconditioner that can only be used in single-processor runs, or as local solver in a
block preconditioner; section 35.1.7.3.3.
• As part of the PCHYPRE package, the parallel variant parasails is available.
-pc_type hypre -pc_hypre_type parasails
35.1.7.3.2 Incomplete factorizations The 𝐿𝑈 factorization of a matrix stemming from PDEs problems has several
practical problems:
• It takes (considerably) more storage space than the coefficient matrix, and
• it correspondingly takes more time to apply.
For instance, for a three-dimensional PDE in 𝑁 variables, the coefficient matrix can take storage space 7𝑁 , while
the 𝐿𝑈 factorization takes 𝑂(𝑁 5/3 ).
35.1.7.3.3 Block methods Certain preconditioners seem almost intrinsically sequential. For instance, an ILU so-
lution is sequential between the variables. There is a modest amount of parallelism, but that is hard to explore.
Taking a step back, one of the problems with parallel preconditioners lies in the cross-process connections in the
matrix. If only those were not present, we could solve the linear system on each process independently. Well, since
a preconditioner is an approximate solution to begin with, ignoring those connections only introduces an extra
degree of approxomaticity.
Figure 35.1: Illustration of block Jacobi and Additive Schwarz preconditioners: left domains and subdo-
mains, right the corresponding submatrices
35.1.7.3.6 Shell preconditioners You already saw that, in an iterative methods, the coefficient matrix can be given
operationally as a shell matrix; section 32.4.7. Similarly, the preconditioner matrix can be specified operationally by
specifying type PCSHELL.
This needs specification of the application routine through PCShellSetApply:
PCShellSetApply(PC pc,PetscErrorCode (*apply)(PC,Vec,Vec));
If the shell preconditioner requires setup, a routine for this can be specified with PCShellSetSetUp:
PCShellSetSetUp(PC pc,PetscErrorCode (*setup)(PC));
By default no monitor is set, meaning that the iteration process runs without output. The option -ksp_monitor
activates printing a norm of the residual. This corresponds to setting KSPMonitorDefault as the monitor.
This actually outputs the ‘preconditioned norm’ of the residual, which is not the L2 norm, but the
square root of 𝑟 𝑡 𝑀 −1 𝑟, a quantity that is computed in the course of the iteration process. Specifying
KSPMonitorTrueResidualNorm (with corresponding option -ksp_monitor_true_residual) as the monitor prints
the actual norm √𝑟 𝑡 𝑟. However, to compute this involves extra computation, since this quantity is not normally
computed.
where the solver variable is of type MatSolverType, and can be MATSOLVERMUMS and such when specified in source:
// direct.c
PetscCall( KSPCreate(comm,&Solver) );
PetscCall( KSPSetOperators(Solver,A,A) );
PetscCall( KSPSetType(Solver,KSPPREONLY) );
{
PC Prec;
PetscCall( KSPGetPC(Solver,&Prec) );
PetscCall( PCSetType(Prec,PCLU) );
PetscCall( PCFactorSetMatSolverType(Prec,MATSOLVERMUMPS) );
}
#include "petscksp.h"
PetscErrorCode KSPSetFromOptions(KSP ksp)
Collective on ksp
Input Parameters
ksp - the Krylov space context
? ∶ 𝑓 (𝑥) = 0
𝑥
𝑓 (𝑥) = 𝐴𝑥 − 𝑏,
529
36. PETSC nonlinear solvers
Collective on SNES
Input Parameters
snes - the SNES context
b - the constant part of the equation F(x) = b, or NULL to use zero.
x - the solution vector.
Comparing the above to the introductory description you see that the Hessian is not specified here. An analytic
Hessian can be dispensed with if you instruct PETSc to approximate it by finite differences:
𝑓 (𝑥 + ℎ𝑦) − 𝑓 (𝑥)
𝐻 (𝑥)𝑦 ≈
ℎ
with ℎ some finite diference. The commandline option -snes_fd forces the use of this finite difference approxima-
tion. However, it may lead to a large number of function evaluations. The option -snes_fd_color applies a coloring
to the variables, leading to a drastic reduction in the number of function evaluations.
If you can form the analytic Jacobian / Hessian, you can specify it with SNESSetJacobian (figure 36.2), where the
Jacobian is a function of type SNESJacobianFunction (figure 36.3).
Specifying the Jacobian:
Mat J;
ierr = MatCreate(comm,&J); CHKERRQ(ierr);
ierr = MatSetType(J,MATSEQDENSE); CHKERRQ(ierr);
ierr = MatSetSizes(J,n,n,N,N); CHKERRQ(ierr);
ierr = MatSetUp(J); CHKERRQ(ierr);
ierr = SNESSetJacobian(solver,J,J,&Jacobian,NULL); CHKERRQ(ierr);
Input Parameters
snes - the SNES context
Amat - the matrix that defines the (approximate) Jacobian
Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
J - Jacobian evaluation routine (if NULL then SNES retains any previously set value)
ctx - [optional] user-defined context for private data for the Jacobian evaluation routine
Collective on snes
Input Parameters
x - input vector, the Jacobian is to be computed at this value
ctx - [optional] user-defined Jacobian context
Output Parameters
Amat - the matrix that defines the (approximate) Jacobian
Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
36.2 Time-stepping
For cases
𝑢𝑡 = 𝐺(𝑡, 𝑢)
call TSSetRHSFunction.
#include "petscts.h"
PetscErrorCode TSSetRHSFunction
(TS ts,Vec r,
PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),
void *ctx);
Some GPUs can accomodate MPI by being directly connected to the network through GPUDirect Remote Memory
Access (RMA). If not, use this runtime option:
-use_gpu_aware_mpi 0
More conveniently, add this to your .petscrc file; section 38.3.3.
// cudainit.c
PetscDeviceType cuda = PETSC_DEVICE_CUDA;
ierr = PetscDeviceInitialize(cuda);
PetscBool has_cuda;
has_cuda = PetscDeviceInitialized(cuda);
533
37. PETSc GPU support
37.3.1 Vectors
Analogous to vector creation as before, there are specific create calls VecCreateSeqCUDA,
VecCreateMPICUDAWithArray, or the type can be set in VecSetType:
// kspcu.c
#ifdef PETSC_HAVE_CUDA
ierr = VecCreateMPICUDA(comm,localsize,PETSC_DECIDE,&Rhs);
#else
ierr = VecCreateMPI(comm,localsize,PETSC_DECIDE,&Rhs);
#endif
The type VECCUDA is sequential or parallel dependent on the run; specific types are VECSEQCUDA, VECMPICUDA.
37.3.2 Matrices
ierr = MatCreate(comm,&A);
#ifdef PETSC_HAVE_CUDA
ierr = MatSetType(A,MATMPIAIJCUSPARSE);
#else
ierr = MatSetType(A,MATMPIAIJ);
#endif
Dense matrices can be created with specific calls MatCreateDenseCUDA, MatCreateSeqDenseCUDA, or by setting types
MATDENSECUDA, MATSEQDENSECUDA, MATMPIDENSECUDA.
Sparse matrices: MATAIJCUSPARSE which is sequential or distributed depending on how the program is started. Spe-
cific types are: MATMPIAIJCUSPARSE, MATSEQAIJCUSPARSE.
37.4 Other
The memories of a CPU and GPU are not coherent. This means that routines such as PetscMalloc1 can not imme-
diately be used for GPU allocation. Use the routines PetscMallocSetCUDAHost and PetscMallocResetCUDAHost to
switch the allocator to GPU memory and back.
// cudamatself.c
Mat cuda_matrix;
PetscScalar *matdata;
ierr = PetscMallocSetCUDAHost();
ierr = PetscMalloc1(global_size*global_size,&matdata);
ierr = PetscMallocResetCUDAHost();
ierr = MatCreateDenseCUDA
(comm,
global_size,global_size,global_size,global_size,
matdata,
&cuda_matrix);
PETSc tools
(In many codes you may see a macro CHKERRQ; which was the mechanism pre-PETSc-3.18; see section 38.1.2.2.) This
macro detects any error code, reports it, and exits the current routine.
For a good traceback, surround the executable part of any subprogram with PetscFunctionBeginUser and
PetscFunctionReturn, where the latter has the return value as parameter. (The routine PetscFunctionBegin does
the same, but should only be used for PETSc library routines.)
536
38.1. Error checking and debugging
Input Parameters:
comm - A communicator, so that the error can be collective
ierr - nonzero error code, see the list of standard error codes in include/petscerror.h
message - error message in the printf format
arg1,arg2,arg3 - argument (for example an integer, string or double)
PetscFunctionReturn(0);
}
Remark 37 In this example, the use of PETSC_COMM_SELF indicates that this error is individually generated on a process;
use PETSC_COMM_WORLD only if the same error would be detected everywhere.
Exercise 38.1. Look up the definition of SETERRQ1. Write a routine to compute square roots that is
used as follows:
x = 1.5; ierr = square_root(x,&rootx); CHKERRQ(ierr);
PetscPrintf(PETSC_COMM_WORLD,"Root of %f is %f\n",x,rootx);
x = -2.6; ierr = square_root(x,&rootx); CHKERRQ(ierr);
PetscPrintf(PETSC_COMM_WORLD,"Root of %f is %f\n",x,rootx);
3. Other error checking macros are CHKERRABORT which aborts immediately, and CHKERRMPI.
Fortran note 29: Error code handling. In the main program, use CHKERRA and SETERRA. Also beware that these error
‘commands’ are macros, and after expansion may interfere with Fortran line length, so they should only
be used in .F90 files.
C++ note 21: Exception handling. The macro CHCKERCXX handles exceptions.
38.1.3.1 Valgrind
Valgrind is rather verbose in its output. To limit the number of processs that run under valgrind:
mpiexec -n 3 valgrind --track-origins=yes ./app -args : -n 5 ./app -args
Fortran:
PetscPrintf(MPI_Comm, character(*), PetscErrorCode ierr)
Python:
PETSc.Sys.Print(type cls, *args, **kwargs)
kwargs:
comm : communicator object
Fortran:
PetscSynchronizedPrintf(MPI_Comm, character(*), PetscErrorCode ierr)
python:
PETSc.Sys.syncPrint(type cls, *args, **kargs)
kwargs:
comm : communicator object
flush : if True, do synchronizedFlush
other keyword args as for python3 print function
Fortran:
PetscSynchronizedFlush(comm,fd,err)
Integer :: comm
fd is usually PETSC_STDOUT
PetscErrorCode :: err
python:
PETSc.Sys.syncFlush(type cls, comm=None)
#include "petscviewer.h"
PetscErrorCode PetscViewerRead(PetscViewer viewer, void *data, PetscInt num, PetscInt *count, PetscDataType dtype)
Collective
Input Parameters
viewer - The viewer
data - Location to write the data
num - Number of items of data to read
datatype - Type of data to read
Output Parameters
count -number of items of data actually read, or NULL
Fortran note 31: Printing and newlines. The Fortran calls are only wrappers around C routines, so you can use \n
newline characters in the Fortran string argument to PetscPrintf.
The file to flush is typically PETSC_STDOUT.
Python note 45: Petsc print and python print. Since the print routines use the python print call, they automatically
include the trailing newline. You don’t have to specify it as in the C calls.
38.2.2 Viewers
In order to export PETSc matrix or vector data structures there is a PetscViewer object type. This is a quite general
concept of viewing: it encompasses ascii output to screen, binary dump to file, or communication to a running
Matlab process. Calls such as MatView or KSPView accept a PetscViewer argument.
In cases where this makes sense, there is also an inverse ‘load’ operation. See section 32.3.5 for vectors.
Some viewers are predefined, such as PETSC_VIEWER_STDOUT_WORLD for ascii rendering to standard out. (In C, spec-
ifying zero or NULL also uses this default viewer; for Fortran use PETSC_NULL_VIEWER.)
PetscViewerCreate(comm,&viewer);
PetscViewerSetType(viewer,PETSCVIEWERBINARY);
#include "petscsys.h"
PetscErrorCode PetscObjectViewFromOptions(PetscObject obj,PetscObject bobj,const char
↪optionname[])
PetscErrorCode VecViewFromOptions(Vec A,PetscObject obj,const char name[])
giving:
Vec Object: space local 4 MPI processes
type: mpi
Process [0]
[ ... et cetera ... ]
The selling point for this approach is that running your code with
mpiexec yourprogram -help
will display these options as a block. Together with a ton of other options, unfortunately.
#include "petscsys.h"
#include "petsctime.h"
PetscErrorCode PetscGetCPUTime(PetscLogDouble *t)
PetscErrorCode PetscTime(PetscLogDouble *v)
You can then use options -time_ksp_monitor and such. Note that the prefix does not have a leading dash, but it
does have the trailing underscore.
Similar routines: MatSetOptionsPrefix, PCSetOptionsPrefix, PetscObjectSetOptionsPrefix,
PetscViewerSetOptionsPrefix, SNESSetOptionsPrefix, TSSetOptionsPrefix, VecSetOptionsPrefix, and some
more obscure ones.
Options can be specified in a file .petscrc in the user’s home directory or the current directory.
Finally, an environment variable PETSC_OPTIONS can be set.
The rc file is processed first, then the environment variable, then any commandline arguments. This parsing is done
in PetscInitialize, so any values from PetscOptionsSetValue override this.
The routine PetscGetCPUTime is less useful, since it measures only time spent in computation, and ignores things
such as communication.
38.4.1 Logging
Petsc does a lot of logging on its own operations. Additionally, you can introduce your own routines into this log.
The simplest way to display statistics is to run with an option -log_view. This takes an optional file name argument:
mpiexec -n 10 yourprogram -log_view :statistics.txt
The corresponding routine is PetscLogView.
C:
#include <petscsys.h>
PetscErrorCode PetscMalloc1(size_t m1,type **r1)
Input Parameter:
m1 - number of elements to allocate (may be zero)
Output Parameter:
r1 - memory allocated
C:
#include <petscsys.h>
PetscErrorCode PetscFree(void *memory)
Input Parameter:
memory - memory to free (the pointer is ALWAYS set to NULL upon sucess)
PETSc topics
39.1 Communicators
PETSc has a ‘world’ communicator, which by default equals MPI_COMM_WORLD. If you want to run PETSc on a subset
of processes, you can assign a subcommunicator to the variable PETSC_COMM_WORLD in between the calls to MPI_Init
and PetscInitialize. Petsc communicators are of type PetscComm.
547
39. PETSc topics
Co-array Fortran
This chapter explains the basic concepts of Co-array Fortran (CAF), and helps you get started on running your first
program.
40.3 Basics
Co-arrays are defined by giving them, in addition to the Dimension, a Codimension
Complex,codimension(*) :: number
Integer,dimension(:,:,:),codimension[-1:1,*] :: grid
This means we are respectively declaring an array with a single number on each image, or a three-dimensional grid
spread over a two-dimensional processor grid.
Traditional-like syntax can also be used:
Complex :: number[*]
Integer :: grid(10,20,30)[-1:1,*]
Unlike Message Passing Interface (MPI), which normally only supports a linear process numbering, CAF allows for
multi-dimensional process grids. The last dimension is always specified as *, meaning it is determined at runtime.
550
40.3. Basics
If you call this_image with a co-array as argument, it will return the image index, as a tuple of cosubscripts,
rather than a linear index. Given such a set of subscripts, image_index will return the linear index.
The functions lcobound and ucobound give the lower and upper bound on the image subscripts, as a linear index,
or a tuple if called with a co-array variable.
40.3.3 Synchronization
The fortran standard forbids race conditions:
If a variable is defined on an image in a segment, it shall not be referenced, defined or become
undefined in a segment on another image unless the segments are ordered.
That is, you should not cause them to happen. The language and runtime are certainly not going to help yu with
that.
Well, a little. After remote updates you can synchronize images with the sync call. The easiest variant is a global
synchronization:
sync all
While remote operations in CAF are nicely one-sided, synchronization is not: if image p issues a call
sync(q)
or a local one:
if (procid==1) &
number[procid+1] = number[procid]
if (procid<=2) sync images( (/1,2/) )
if (procid==2) &
number[procid-1] = 2*number[procid]
if (procid<=2) sync images( (/2,1/) )
Note that the local sync call is done on both images involved.
Example of how you would synchronize a collective:
if ( this_image() .eq. 1 ) sync images( * )
if ( this_image() .ne. 1 ) sync images( 1 )
Here image 1 synchronizes with all others, but the others don’t synchronize with each other.
if (procid==1) then
sync images( (/procid+1/) )
else if (procid==nprocs) then
sync images( (/procid-1/) )
else
sync images( (/procid-1,procid+1/) )
end if
40.3.4 Collectives
Collectives are not part of CAF as of the 2008 Fortran standard.
Kokkos
Much of this material is based on the Kokkos Tutorial that Jeff Miles and Christian Trott gave April 21-24, 2020.
Include file:
// hello.cxx
#include "Kokkos_Core.hpp"
554
41.1. Parallel code execution
41.1.2 Reduction
Reductions add a parameter to the construct: the reduction variable.
double pi{0.};
int n{100};
Kokkos::parallel_reduce
( "PI",
n,
KOKKOS_LAMBDA ( int i, double& partial ) {
double h = 1./n, x = i*h;
partial += h * sqrt( 1-x*x );
},
pi
);
• The parallel construct has an optional name. This is useful for profiling and debugging.
• Instead of an explicit lambda capture, we use KOKKOS_LAMBDA which does a [=] capture, and adds clauses
for GPU execution, if needed.
• The lambda expression now takes two parameters: the iteration number, and the reduction variable. This
is the thread-private variable, not the final one.
• The final argument is the global reduction variable.
For reductions other than summing, a reducer is needed.
// reduxmax.cxx
double max=0.;
Kokkos::parallel_reduce
( npoints,
KOKKOS_LAMBDA (int i,double& m) {
if (x(i)>m)
m = x(i);
},
Kokkos::Max<double>(max)
);
cout << "max: " << max << "\n";
update += y[ j ] * temp2;
},
result
);
You can also leave all the loops to Kokkos, with an RangePolicy or MDRangePolicy. Here you indicate the rank (as
in: number of dimensions) of the object, as well as arrays of first/last values. In the above examples
Kokkos::parallel_reduce( N, ... );
// equivalent:
Kokkos::parallel_reduce( Kokkos:RangePolicy<>(0,N), ... );
Note the multi-D indexing in this example: this parenthesis notation gets translated to the correct row/column-
major depending on whether the code runs on a CPU or GPU; see section 19.5.2.
41.2 Data
One of the problems Kokkos addresses is the coherence of data between main processor and attached devicees such
GPUs. This is handled through the Kokkos::View mechanism.
// matsum.cxx
int m=10,n=100;
Kokkos::View<double**> matrix("flat",m,n);
assert( matrix.extent(0)==10 );
These act like C++ shared_ptr, so capturing them by value gives you the data by reference anyway. Storage is
automatically freed, RAII-style, when they go out of scope.
Indexing is best done with a Fortran-style notation:
matrix(i,j)
Values are
• LayoutLeft where, Fortran-style, the leftmost index is stride 1; this is the default for CudaSpace.
• LayoutRight where, C-style, the leftmost index is stride 1; this is the default for HostSpace.
• LayoutStride, LayoutTiled and others.
• User-defined.
Practically speaking, the traversal of a two-dimensional array is now a function of
• the layout, possible determined by the memory space, and
• the indexing in in the functor:
Kokkos:parallel_whatever(
N,
KOKKOS_LAMBDA ( size_t i ) {
matrix(i,j) or matrix(j,i); }
);
The default
Kokkos::parallel_for( N, ...
is equivalent to
Kokkos::parallel_for( RangePolicy<>(N), ...
Available memory spaces include: HostSpace, CudaSpace, CudaUVMSpace. Leaving out the memory space argument
is equivalent to
View<double**,DefaultExecutionSpace::memory_space> x(1,2);
Examples:
View<double*,HostSpace> hostarray(5);
View<double*,CudaSpace> cudaarray(5);
The CudaSpace is only available if Kokkos has been configured with Compute-Unified Device Architecture (CUDA)
41.4 Configuration
An accelerator-free installation with OpenMP:
cmake \
-D Kokkos_ENABLE_SERIAL=ON -D Kokkos_ENABLE_OPENMP=ON
Threading is not compatible with OpenMP:
-D Kokkos_ENABLE_THREADS=ON
Cuda installation:
cmake \
-D Kokkos_ENABLE_CUDA=ON -D Kokkos_ARCH_TURING75=ON -D Kokkos_ENABLE_CUDA_LAMBDA=ON
41.5 Stuff
There are init/finalize calls, which are not always needed.
// pi.cxx
Kokkos::initialize(argc,argv);
Kokkos::finalize();
Parallelism control:
--kokkos-threads=123 # threads
--kokkos-numa=45 # numa regions
--kokkos-device=6 * GPU id to use
This chapter explains the basic concepts of Sycl/Dpc++, and helps you get started on running your first program.
• SYCL is a C++-based language for portable parallel programming.
• Data Parallel C++ (DPCPP) is Intel’s extension of Sycl.
• OneAPI is Intel’s compiler suite, which contains the DPCPP compiler.
Intel DPC++ extension. The various Intel extensions are listed here: https://spec.oneapi.com/versions/
latest/elements/dpcpp/source/index.html#extensions-table
42.1 Logistics
Headers:
#include <CL/sycl.hpp>
You can now include namespace, but with care! If you use
using namespace cl;
you have to prefix all SYCL class with sycl::, which is a bit of a bother. However, if you use
using namespace cl::sycl;
you run into the fact that SYCL has its own versions of many Standard Template Library (STL) commands, and so
you will get name collisions. The most obvious example is that the cl::sycl name space has its own versions of
cout and endl. Therefore you have to use explicitly std::cout and std::end. Using the wrong I/O will cause tons
of inscrutable error messages. Additionally, SYCL has its own version of free, and of several math routines.
Intel DPC++ extension.
using namespace sycl;
561
42. Sycl, OneAPI, DPC++
You can query what type of device you are dealing with by is_host, is_cpu, is_gpu.
42.3 Queues
The execution mechanism of SYCL is the queue: a sequence of actions that will be executed on a selected device. The
only user action is submitting actions to a queue; the queue is executed at the end of the scope where it is declared.
Queue execution is asynchronous with host code.
The following example explicitly assigns the queue to the CPU device using the sycl::cpu_selector.
// cpuname.cxx
sycl::queue myqueue( sycl::cpu_selector{} );
The sycl::host_selector bypasses any devices and make the code run on the host.
It is good for your sanity to print the name of the device you are running on:
// devname.cxx
std::cout << myqueue.get_device().get_info<sycl::info::device::name>()
<< std::endl;
If you try to select a device that is not available, a sycl::runtime_error exception will be thrown.
Intel DPC++ extension.
#include "CL/sycl/intel/fpga_extensions.hpp"
fpga_selector
42.4 Kernels
One kernel per submit.
myqueue.submit( [&] ( handler &commandgroup ) {
commandgroup.parallel_for<uniquename>
( range<1>{N},
[=] ( id<1> idx ) { ... idx }
)
} );
Note that the lambda in the kernel captures by value. Capturing by reference makes no sense, since the kernel is
executed on a device.
cgh.single_task(
[=]() {
// kernel function is executed EXACTLY once on a SINGLE work-item
});
myevent.wait();
cgh.parallel_for(
nd_range<3>( {1024,1024,1024},{16,16,16} ),
// using 3D in this example
[=](nd_item<3> myID) {
// kernel function is executed on an n-dimensional range (NDrange)
});
cgh.parallel_for_work_group(
range<2>(1024,1024),
// using 2D in this example
[=](group<2> myGroup) {
// kernel function is executed once per work-group
});
grp.parallel_for_work_item(
range<1>(1024),
// using 1D in this example
[=](h_item<1> myItem) {
// kernel function is executed once per work-item
});
cgh.parallel_for<class foo>(
range<1>{D*D*D},
[=](id<1> item) {
xx[ item[0] ] = 2 * item[0] + 1;
}
)
While the C++ vectors remain one-dimensional, DPCPP allows you to make multi-dimensional buffers:
std::vector<int> y(D*D*D);
buffer<int,1> y_buf(y.data(), range<1>(D*D*D));
cgh.parallel_for<class foo2D>
(range<2>{D,D*D},
[=](id<2> item) {
yy[ item[0] + D*item[1] ] = 2;
}
);
Intel DPC++ extension. There is an implicit conversion from the one-dimensional sycl::id<1> to size_t, so
[=](sycl::id<1> i) {
data[i] = i;
}
constexpr size_t B = 4;
sycl::range<2> local_range(B, B);
sycl::range<2> tile_range = local_range + sycl::range<2>(2, 2); // Includes boundary cells
auto tile = local_accessor<float, 2>(tile_range, h); // see templated def'n above
We first copy global data into an array local to the work group:
sycl::id<2> offset(1, 1);
h.parallel_for
( sycl::nd_range<2>(stencil_range, local_range, offset),
[=] ( sycl::nd_item<2> it ) {
// Load this tile into work-group local memory
sycl::id<2> lid = it.get_local_id();
sycl::range<2> lrange = it.get_local_range();
for (int ti = lid[0]; ti < B + 2; ti += lrange[0]) {
for (int tj = lid[1]; tj < B + 2; tj += lrange[1]) {
int gi = ti + B * it.get_group(0);
int gj = tj + B * it.get_group(1);
tile[ti][tj] = input[gi][gj];
}
}
Global coordinates in the input are computed from the nd_item’s coordinate and group:
[=] ( sycl::nd_item<2> it ) {
for (int ti ... ) {
for (int tj ... ) {
int gi = ti + B * it.get_group(0);
int gj = tj + B * it.get_group(1);
... = input[gi][gj];
Local coordinates in the tile, including boundary, I DON’T QUITE GET THIS YET.
[=] ( sycl::nd_item<2> it ) {
sycl::id<2> lid = it.get_local_id();
sycl::range<2> lrange = it.get_local_range();
for (int ti = lid[0]; ti < B + 2; ti += lrange[0]) {
for (int tj = lid[1]; tj < B + 2; tj += lrange[1]) {
tile[ti][tj] = ..
To get this working correctly would need either a reduction primitive or atomics on the accumulator. The 2020
proposed standard has improved atomics.
// reduct1d.cxx
auto input_values = array_buffer.get_access<sycl::access::mode::read>(h);
auto sum_reduction = sycl::reduction( scalar_buffer,h,std::plus<>() );
h.parallel_for
( array_range,sum_reduction,
[=]( sycl::id<1> index,auto& sum )
{
sum += input_values[index];
}
); // end of parallel for
42.5.4 Reductions
Reduction operations were added in the the SYCL 2020 Provisional Standard, meaning that they are not yet finalized.
Here a sycl::reduction object is created from the target data and the reduction operator. This is then passed to
the parallel_for and its combine method is called.
// reductimpl.cxx
floattype
*host_float = (floattype*)malloc( sizeof(floattype) ),
*devc_float = (floattype*)malloc_device( sizeof(floattype),dev,ctx );
[&](sycl::handler &cgh) {
cgh.memcpy(devc_float,host_float,sizeof(floattype));
}
Note the corresponding free call that also has the queue as parameter.
Note that you need to be in a parallel task. The following gives a segmentation error:
[&](sycl::handler &cgh) {
shar_float[0] = host_float[0];
}
Remark 38 sycl::range takes a size_t parameter; specifying an int may give a compiler warning about a narrow-
ing conversion.
Inside the kernel, the array is then unpacked from the buffer:
myqueue.submit( [&] (handler &h) {
auto deviceAccessorA =
bufferA.get_access<access::mode::read_write>(h);
However, the get_access function results in a sycl::accessor, not a pointer to a simple type. The precise type is
templated and complicated, so this is a good place to use auto.
Accessors can have a mode associated: sycl::access::mode::read sycl::access::mode::write
Intel DPC++ extension.
array<floattype,1> leftsum{0.};
#ifdef __INTEL_CLANG_COMPILER
sycl::buffer leftbuf(leftsum);
#else
sycl::range<1> scalar{1};
sycl::buffer<floattype,1> leftbuf(leftsum.data(),scalar);
42.6.3 Querying
The function get_range can query the size of either a buffer or an accessor:
// range2.cxx
sycl::buffer<int, 2>
a_buf(a.data(), sycl::range<2>(N, M)),
b_buf(b.data(), sycl::range<2>(N, M)),
c_buf(c.data(), sycl::range<2>(N, M));
sycl::range<2>
a_range = a_buf.get_range(),
b_range = b_buf.get_range();
if (a_range==b_range) {
sycl::accessor c = c_buf.get_access<sycl::access::mode::write>(h);
( a_range,
[=]( sycl::id<2> idx ) {
c[idx] = a[idx] + b[idx];
} );
Since the end of a queue does not flush stdout, it may be necessary to call sycl::queue::wait
myQueue.wait();
42.10 Examples
42.10.1 Kernels in a loop
The following idiom works:
sycl::event last_event = queue.submit( [&] (sycl::handler &h) {
for (int iteration=0; iteration<N; iteration++) {
last_event = queue.submit( [&] (sycl::handler &h) {
h.depends_on(last_event);
Python multiprocessing
Python has a multiprocessing toolbox. This is a parallel processing library that relies on subprocesses, rather than
threads.
43.2 Process
A process is an object that will execute a python function:
## quicksort.py
import multiprocessing as mp
import random
import os
if __name__ == '__main__':
numbers = [ random.randint(1,50) for i in range(32) ]
process = mp.Process(target=quicksort,args=[numbers])
574
43.3. Pools and mapping
process.start()
process.join()
Creating a process does not start it: for that use the start function. Execution of the process is not guaranteed until
you call the join function on it:
if __name__ == '__main__':
for p in processes:
p.start()
for p in processes:
p.join()
By making the start and join calls less regular than in a loop like this, arbitrarily complicated code can be produced.
43.2.1 Arguments
Arguments can be passed to the function of the process with the args keyword. This accepts a list (or tuple) of
arguments, leading to a somewhat strange syntax for a single argument:
proc = Process(target=print_func, args=(name,))
The target function of a process can get hold of that process with the current_process function.
Of course you can also query os.getpid() but that does not offer any further possibilities.
def say_name(iproc):
print(f"Process {os.getpid()} has name: {mp.current_process().name}")
if __name__ == '__main__':
processes = [ mp.Process(target=say_name,name=f"proc{iproc}",args=[iproc])
for iproc in range(6) ]
Note that this is also the easiest way to get return values from a process, which is not directly possible with a
Process object. Other approaches are using a shared object, or an object in a Queue or Pipe object; see below.
Exercise 43.1. Do you see a way to improve the speed of this calculation?
43.4.1 Pipes
A pipe, object type Pipe, corresponds to what used to be called a channel in older parallel programming systems:
a First-In / First-Out (FIFO) object into which one process can place items, and from which another process can take
them. However, a pipe is not associated with any particular pair: creating the pipe gives the entrace and exit from
the pipe
q_entrance,q_exit = mp.Pipe()
which can then can put and get items, using the send and recv commands.
## pipemulti.py
def add_to_pipe(v,q):
for i in range(10):
print(f"put {v}")
q.send(v)
time.sleep(1)
q.send("END")
def print_from_pipe(q):
ends = 0
while True:
v = q.recv()
print(f"Got: {v}")
if v=="END":
ends += 1
if ends==2:
break
print("pipe is empty")
43.4.2 Queues
THE REST
Chapter 44
There is much that can be said about computer architecture. However, in the context of parallel programming we
are mostly concerned with the following:
• How many networked nodes are there, and does the network have a structure that we need to pay
attention to?
• On a compute node, how many sockets (or other Non-Uniform Memory Access (NUMA) domains) are
there?
• For each socket, how many cores and hyperthreads are there? Are caches shared?
44.1.2 hwloc
The open source package hwloc does similar reporting to cpuinfo, but it has been ported to many platforms. Addi-
tionally, it can generate ascii and pdf graphic renderings of the architecture.
580
44.2. Full source code of examples
Hybrid computing
So far, you have learned to use MPI for distributed memory and OpenMP for shared memory parallel programming.
However, distribute memory architectures actually have a shared memory component, since each cluster node is
typically of a multicore design. Accordingly, you could program your cluster using MPI for inter-node and OpenMP
for intra-node parallelism.
You now have to find the right balance between processes and threads, since each can keep a core fully busy.
Complicating this story, a node can have more than one socket, and corresponding NUMA domain. Figure 45.1
illustrates three modes: pure MPI with no threads used; one MPI process per node and full multi-threading; two
MPI processes per node, one per socket, and multiple threads on each socket.
582
45.1. Concurrency
45.1 Concurrency
With hybrid multi-process / multi-thread computing, one thing that goes out the door is the sequential semantics
of each MPI process. For instance, the fact that messages between a single sender and a single receiver are non-
overtaking no longer holds if the messages originated in different threads.
↪MPI_Waitall(2,requests,MPI_STATUSES_IGNORE);
45.2 Affinity
In the preceeding chapters we mostly considered all MPI nodes or OpenMP thread as being in one flat pool. However,
for high performance you need to worry about affinity: the question of which process or thread is placed where,
and how efficiently they can interact.
process 𝑝 interacts mostly with 𝑝 + 1 will be efficient, while communication with large jumps will be less
so.
• If the cluster network has a structure (processor grid as opposed to fat-tree), placement of processes has
an effect on program efficiency. MPI tries to address this with graph topology; section 11.2.
• Even on a single node there can be asymmetries. Figure 45.2 illustrates the structure of the four sockets
of the Ranger supercomputer (no longer in production). Two cores have no direct connection.
This asymmetry affects both MPI processes and threads on that node.
• Another problem with multi-socket designs is that each socket has memory attached to it. While every
socket can address all the memory on the node, its local memory is faster to access. This asymmetry
becomes quite visible in the first-touch phenomemon; section 25.2.
• If a node has fewer MPI processes than there are cores, you want to be in control of their placement.
Also, the operating system can migrate processes, which is detrimental to performance since it negates
data locality. For this reason, utilities such as numactl (and at TACC tacc_affinity) can be used to
pin a thread or process to a specific core.
• Processors with hyperthreading or hardware threads introduce another level or worry about where
threads go.
Machine (32GB)
L3 (20MB) eth0
L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) eth1
L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB)
PCI 1a03:2000
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#6 Core P#7
PCI 8086:1d02
PU P#0 PU P#1 PU P#2 PU P#3 PU P#4 PU P#5 PU P#6 PU P#7
sda
L3 (20MB) ib0
L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB)
PCI 8086:225c
L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB)
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#6 Core P#7
Host: c401−402.stampede.tacc.utexas.edu
Indexes: physical
Date: Tue 07 Jun 2016 01:06:43 PM CDT
Machine (1024GB)
L3 (20MB) eth2
L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) eth3
L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB)
PCI 14e4:165f
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#6 Core P#7 eth0
eth1
PCI 1000:005b
sda
PCI 10de:0dd8
PCI 102b:0534
PCI 8086:1d02
sr0
L3 (20MB) ib0
L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB)
PCI 10de:0dd8
L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB)
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#6 Core P#7
Socket P#2
L3 (20MB)
L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB)
L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB)
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#6 Core P#7
Socket P#3
L3 (20MB)
L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB) L1d (32KB)
L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB) L1i (32KB)
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#6 Core P#7
Host: c400-106.stampede.tacc.utexas.edu
Indexes: physical
Date: Tue 07 Jun 2016 04:49:53 PM CDT
Machine (64GB)
Socket P#0
L3 (30MB)
L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB)
L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB)
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#8 Core P#9 Core P#10 Core P#11 Core P#12 Core P#13
PU P#0 PU P#1 PU P#2 PU P#3 PU P#4 PU P#5 PU P#6 PU P#7 PU P#8 PU P#9 PU P#10 PU P#11
PU P#24 PU P#25 PU P#26 PU P#27 PU P#28 PU P#29 PU P#30 PU P#31 PU P#32 PU P#33 PU P#34 PU P#35
Socket P#1
L3 (30MB)
L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB) L2 (256KB)
L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB) L1 (32KB)
Core P#0 Core P#1 Core P#2 Core P#3 Core P#4 Core P#5 Core P#8 Core P#9 Core P#10 Core P#11 Core P#12 Core P#13
PU P#12 PU P#13 PU P#14 PU P#15 PU P#16 PU P#17 PU P#18 PU P#19 PU P#20 PU P#21 PU P#22 PU P#23
PU P#36 PU P#37 PU P#38 PU P#39 PU P#40 PU P#41 PU P#42 PU P#43 PU P#44 PU P#45 PU P#46 PU P#47
Host: nid00015
Indexes: physical
Date: Tue 07 Jun 2016 04:18:47 PM CDT
Figure 45.3 depicts a Stampede compute node, which is a two-socket Intel Sandybridge design; figure 45.4 shows
a Stampede largemem node, which is a four-socket design. Finally, figure 45.5 shows a Lonestar5 compute node,
a two-socket design with 12-core Intel Haswell processors with two hardware threads each.
45.5 Discussion
The performance implications of the pure MPI strategy versus hybrid are subtle.
• First of all, we note that there is no obvious speedup: in a well balanced MPI application all cores are
busy all the time, so using threading can give no immediate improvement.
• Both MPI and OpenMP are subject to Amdahl’s law that quantifies the influence of sequential code; in
hybrid computing there is a new version of this law regarding the amount of code that is MPI-parallel,
but not OpenMP-parallel.
• MPI processes run unsynchronized, so small variations in load or in processor behavior can be tolerated.
The frequent barriers in OpenMP constructs make a hybrid code more tightly synchronized, so load
balancing becomes more critical.
• On the other hand, in OpenMP codes it is easier to divide the work into more tasks than there are threads,
so statistically a certain amount of load balancing happens automatically.
• Each MPI process has its own buffers, so hybrid takes less buffer overhead.
Exercise 45.1. Review the scalability argument for 1D versus 2D matrix decomposition in HPC book,
section-6.2. Would you get scalable performance from doing a 1D decomposition (for
instance, of the rows) over MPI processes, and decomposing the other directions (the
columns) over OpenMP threads?
Another performance argument we need to consider concerns message traffic. If let all threads make MPI calls (see
section 13.1) there is going to be little difference. However, in one popular hybrid computing strategy we would
keep MPI calls out of the OpenMP regions and have them in effect done by the master thread. In that case there
are only MPI messages between nodes, instead of between cores. This leads to a decrease in message traffic, though
this is hard to quantify. The number of messages goes down approximately by the number of cores per node, so this
is an advantage if the average message size is small. On the other hand, the amount of data sent is only reduced if
there is overlap in content between the messages.
Limiting MPI traffic to the master thread also means that no buffer space is needed for the on-node communication.
int totalcores;
MPI_Reduce(&ncores,&totalcores,1,MPI_INT,MPI_SUM,0,comm);
if (procid==0) {
printf("Omp procs on this process: %d\n",ncores);
printf("Omp procs total: %d\n",totalcores);
}
Running this with Intel MPI (version 19) gives the following:
---- nprocs: 14
Omp procs on this process: 4
Omp procs total: 56
---- nprocs: 15
Omp procs on this process: 3
Omp procs total: 45
---- nprocs: 16
Omp procs on this process: 3
Omp procs total: 48
We see that
• Each process get an equal number of cores, and
• Some cores will go unused.
While the OpenMP ‘proc’ count is such that the MPI processes will not oversubscribe cores, the actual placement
of processes and threads is not expressed here. This assignment is known as affinity and it is determined by the
MPI/OpenMP runtime system. Typically it can be controlled through environment variables, but one hopes the
default assignment makes sense. Figure 45.6 illustrates this for the Intel Knights Landing:
export OMP_NUM_THREADS=16
There is a third choice, in between these extremes, that makes sense. A cluster node often has more than one socket,
so you could put one MPI process on each socket, and use a number of threads equal to the number of cores per
socket.
export OMP_NUM_THREADS=8
ibrun tacc_affinity yourprogram
The tacc_affinity script unsets the following variables:
export MV2_USE_AFFINITY=0
export MV2_ENABLE_AFFINITY=0
export VIADEV_USE_AFFINITY=0
export VIADEV_ENABLE_AFFINITY=0
If you don’t use tacc_affinity you may want to do this by hand, otherwise mvapich2 will use its own affinity
rules.
Support libraries
There are many libraries related to parallel programming to make life easier, or at least more interesting, for you.
46.1 SimGrid
SimGrid [16] is a simulator for distributed systems. It can for instance be used to explore the effects of architectural
parameters. It has been used to simulate large scale operations such as High Performance Linpack (HPL) [4].
46.2 Other
ParaMesh
Global Arrays
Hdf5 and Silo
591
46. Support libraries
CLASS PROJECTS
Chapter 47
Here are some guidelines for how to submit assignments and projects. As a general rule, consider programming as
an experimental science, and your writeup as a report on some tests you have done: explain the problem you’re
addressing, your strategy, your results.
Turn in a writeup in pdf form (Word and text documents are not acceptable) that was generated from a text pro-
cessing program such (preferably) LATEX (for a tutorial, see Tutorials book, section-15).
594
47.2. The parallel part
47.1.4 Reporting
Include both code snippets and graphs.
Screenshots of code snippets are not acceptable. Use at least a verbatim/monospace mode in your text processor,
but better, use the LATEX listings package or equivalent.
Graphs can be generated any number of ways. Kudos if you can figure out the LATEX tikz package, but Matlab or
Excel are acceptable too. No screenshots though.
For parallel runs you can, but are not required to, use TAU plots; see Tutorials book, section-18.
47.2.2 Graphs
In parallel programming, speedup and scaling are the test of how good your work is. So it’s up to you to report this
as well as you can.
If you do a scaling analysis, a graph reporting runtimes should not have a linear time axis. (Curved graphs are hard
to read. Can you see the difference between 𝑂(√𝑛) and 𝑂(log 𝑛) behavior in a graph?) Try to find a way to compare
your results to a straight line, such as constant time, or linearly increasing performance.
It is up to you to decide what quantity to report. This may depend on your application.
Use enough data points! Writing a short script to run your program multiple times takes very little time.
Warmup Exercises
48.2 Collectives
It is a good idea to be able to collect statistics, so before we do anything interesting, we will look at MPI collectives;
section 3.1.
Take a look at time_max.cxx. This program sleeps for a random number of seconds:
wait = (int) ( 6.*rand() / (double)RAND_MAX );
tstart = MPI_Wtime();
sleep(wait);
tstop = MPI_Wtime();
jitter = tstop-tstart-wait;
and measures how long the sleep actually was:
if (mytid==0)
sendbuf = MPI_IN_PLACE;
else sendbuf = (void*)&jitter;
MPI_Reduce(sendbuf,(void*)&jitter,1,MPI_DOUBLE,MPI_MAX,0,comm);
597
48. Warmup Exercises
In the code, this quantity is called ‘jitter’, which is a term for random deviations in a system.
Exercise 48.1. Change this program to compute the average jitter by changing the reduction
operator.
Exercise 48.2. Now compute the standard deviation
∑𝑖 (𝑥𝑖 − 𝑚)2
𝜎=
√ 𝑛
where 𝑚 is the average value you computed in the previous exercise.
• Solve this exercise twice: once by following the reduce by a broadcast operation and
once by using an Allreduce.
• Run your code both on a single cluster node and on multiple nodes, and inspect the
TAU trace. Some MPI implementations are optimized for shared memory, so the trace
on a single node may not look as expected.
• Can you see from the trace how the allreduce is implemented?
Exercise 48.3. Finally, use a gather call to collect all the values on processor zero, and print them out.
Is there any process that behaves very differently from the others?
}
if (!error) printf("Success!\n");
free(gather_buffer);
}
Mandelbrot set
If you’ve never heard the name Mandelbrot set, you probably recognize the picture; figure 49.1 Its formal definition
is as follows:
A point 𝑐 in the complex plane is part of the Mandelbrot set if the series 𝑥𝑛 defined by
𝑥0 = 0
{
𝑥𝑛+1 = 𝑥𝑛2 + 𝑐
satisfies
∀𝑛 ∶ |𝑥𝑛 | ≤ 2.
It is easy to see that only points 𝑐 in the bounding circle |𝑐| < 2 qualify, but apart from that it’s hard to say much
without a lot more thinking. Or computing; and that’s what we’re going to do.
600
49.1. Invocation
In this set of exercises you are going to take an example program mandel_main.cxx and extend it to use a variety
of MPI programming constructs. This program has been set up as a manager-worker model: there is one manager
processor (for a change this is the last processor, rather than zero) which gives out work to, and accepts results
from, the worker processors. It then takes the results and constructs an image file from them.
49.1 Invocation
The mandel_main program is called as
mpirun -np 123 mandel_main steps 456 iters 789
where the steps parameter indicates how many steps in 𝑥, 𝑦 direction there are in the image, and iters gives the
maximum number of iterations in the belong test.
If you forget the parameter, you can call the program with
mandel_serial -h
and it will print out the usage information.
49.2 Tools
The driver part of the Mandelbrot program is simple. There is a circle object that can generate coordinates
class circle {
public :
circle(double stp,int bound);
void next_coordinate(struct coordinate& xy);
int is_valid_coordinate(struct coordinate xy);
void invalid_coordinate(struct coordinate& xy);
and a global routine that tests whether a coordinate is in the set, at least up to an iteration bound. It returns zero if
the series from the given starting point has not diverged, or the iteration number in which it diverged if it did so.
int belongs(struct coordinate xy,int itbound) {
double x=xy.x, y=xy.y; int it;
for (it=0; it<itbound; it++) {
double xx,yy;
xx = x*x - y*y + xy.x;
yy = 2*x*y + xy.y;
x = xx; y = yy;
if (x*x+y*y>4.) {
return it;
}
}
return 0;
}
In the former case, the point could be in the Mandelbrot set, and we colour it black, in the latter case we give it a
colour depending on the iteration number.
if (iteration==0)
memset(colour,0,3*sizeof(float));
else {
float rfloat = ((float) iteration) / workcircle->infty;
colour[0] = rfloat;
colour[1] = MAX((float)0,(float)(1-2*rfloat));
colour[2] = MAX((float)0,(float)(2*(rfloat-.5)));
}
We use a fairly simple code for the worker processes: they execute a loop in which they wait for input, process it,
return the result.
void queue::wait_for_work(MPI_Comm comm,circle *workcircle) {
MPI_Status status; int ntids;
MPI_Comm_size(comm,&ntids);
int stop = 0;
while (!stop) {
struct coordinate xy;
int res;
MPI_Recv(&xy,1,coordinate_type,ntids-1,0, comm,&status);
stop = !workcircle->is_valid_coordinate(xy);
if (stop) break; //res = 0;
else {
res = belongs(xy,workcircle->infty);
}
MPI_Send(&res,1,MPI_INT,ntids-1,0, comm);
}
return;
}
err = MPI_Send(&xy,1,coordinate_type,
free_processor,0,comm); CHK(err);
err = MPI_Recv(&contribution,1,MPI_INT,
free_processor,0,comm, &status); CHK(err);
coordinate_to_image(xy,contribution);
total_tasks++;
free_processor = (free_processor+1)%(ntids-1);
return 0;
};
Exercise 49.1. Explain why this solution is very inefficient. Make a trace of its execution that bears
this out.
give a new round of data to all workers. Make a trace of the execution of this and report on
the total time.
You can do this by writing a new class that inherits from queue, and that provides its own
addtask method:
// mandel_bulk.cxx
class bulkqueue : public queue {
public :
bulkqueue(MPI_Comm queue_comm,circle *workcircle)
: queue(queue_comm,workcircle) {
You will also have to override the complete method: when the circle object indicates that all
coordinates have been generated, not all workers will be busy, so you need to supply the
proper MPI_Waitall call.
Exercise 49.4. Code a fully dynamic solution that uses MPI_Probe or MPI_Waitany. Make an
execution trace and report on the total running time.
In this section we will gradually build a semi-realistic example program. To get you started some pieces have already
been written: as a starting point look at code/mpi/c/grid.cxx.
This is easy enough to implement sequentially, but in parallel this requires some care.
Let’s divide the grid 𝐺 and divide it over a two-dimension grid of 𝑝𝑖 × 𝑝𝑗 processors. (Other strategies exist, but this
one scales best; see section HPC book, section-6.5.) Formally, we define two sequences of points
0 = 𝑖0 < ⋯ < 𝑖𝑝𝑖 < 𝑖𝑝𝑖 +1 = 𝑛𝑖 , 0 < 𝑗0 < ⋯ < 𝑗𝑝𝑗 < 𝑖𝑝𝑗 +1 = 𝑛𝑗
From formula (50.1) you see that the processor then needs one row of points on each side surrounding its part of
the grid. A picture makes this clear; see figure 50.1. These elements surrounding the processor’s own part are called
the halo or ghost region of that processor.
The problem is now that the elements in the halo are stored on a different processor, so communication is needed
to gather them. In the upcoming exercises you will have to use different strategies for doing so.
606
50.2. Code basics
Figure 50.1: A grid divided over processors, with the ‘ghost’ region indicated
ierr = parameters_from_commandline
(argc,argv,comm,&ni,&nj,&pi,&pj,&nit);
if (ierr) return MPI_Abort(comm,1);
From the processor parameters we make a processor grid object:
processor_grid *pgrid = new processor_grid(comm,pi,pj);
and from the numerical parameters we make a number grid:
number_grid *grid = new number_grid(pgrid,ni,nj);
Number grids have a number of methods defined. To set the value of all the elements belonging to a processor to
that processor’s number:
grid->set_test_values();
To set random values:
grid->set_random_values();
If you want to visualize the whole grid, the following call gathers all values on processor zero and prints them:
grid->gather_and_print();
Next we need to look at some data structure details.
The definition of the number_grid object starts as follows:
class number_grid {
public:
processor_grid *pgrid;
double *values,*shadow;
where values contains the elements owned by the processor, and shadow is intended to contain the values plus
the ghost region. So how does shadow receive those values? Well, the call looks like
grid->build_shadow();
and you will need to supply the implementation of that. Once you’ve done so, there is a routine that prints out the
shadow array of each processor
grid->print_shadow();
In the file code/mpi/c/grid_impl.cxx you can see several uses of the macro INDEX. This translates from a two-
dimensional coordinate system to one-dimensional. Its main use is letting you use (𝑖, 𝑗) coordinates for indexing the
processor grid and the number grid: for processors you need the translation to the linear rank, and for the grid you
need the translation to the linear array that holds the values.
A good example of the use of INDEX is in the number_grid::relax routine: this takes points from the shadow array
and averages them into a point of the values array. (To understand the reason for this particular averaging, see HPC
book, section-4.2.3 and HPC book, section-5.5.3.) Note how the INDEX macro is used to index in a ilength×jlength
target array values, while reading from a (ilength + 2) × (jlength + 2) source array shadow.
for (i=0; i<ilength; i++) {
for (j=0; j<jlength; j++) {
int c=0;
double new_value=0.;
for (c=0; c<5; c++) {
int ioff=i+1+ioffsets[c],joff=j+1+joffsets[c];
new_value += coefficients[c] *
shadow[ INDEX(ioff,joff,ilength+2,jlength+2) ];
}
values[ INDEX(i,j,ilength,jlength) ] = new_value/8.;
}
}
N-body problems
N-body problems describe the motion of particles under the influence of forces such as gravity. There are many
approaches to this problem, some exact, some approximate. Here we will explore a number of them.
For background reading see HPC book, section-10.
609
51. N-body problems
DIDACTICS
Chapter 52
Teaching guide
Based on two lectures per week, here is an outline of how MPI can be taught in a college course. Links to the relevant
exercises.
612
52.1. Full source code of examples
Distributed memory programming, typically through the MPI library, is the de facto standard for programming large
scale parallelism, with up to millions of individual processes. Its dominant paradigm of Single Program Multiple
Data (SPMD) programming is different from threaded and multicore parallelism, to an extent that students have a
hard time switching models. In contrast to threaded programming, which allows for a view of the execution with
central control and a central repository of data, SPMD programming has a symmetric model where all processes
are active all the time, with none privileged, and where data is distributed.
This model is counterintuitive to the novice parallel programmer, so care needs to be taken how to instill the proper
‘mental model’. Adoption of an incorrect mental model leads to broken or inefficient code.
We identify problems with the currently common way of teaching MPI, and propose a structuring of MPI courses
that is geared to explicit reinforcing the symmetric model. Additionally, we advocate starting from realistic scenar-
ios, rather than writing artificial code just to exercise newly-learned routines.
53.1 Introduction
The MPI library [24, 21] is the de facto tool for large scale parallelism as it is used in engineering sciences. In this
paper we want to discuss the manner it is usually taught, and propose a rethinking.
We argue that the topics are typically taught in a sequence that is essentially dictated by level of complexity in the
implementation, rather than by conceptual considerations. Our argument will be for a sequencing of topics, and
use of examples, that is motivated by typical applications of the MPI library, and that explicitly targets the required
mental model of the parallelism model underlying MPI.
We have written an open-source textbook [9] with exercise sets that follows the proposed sequencing of topics and
the motivating applications.
614
53.2. Implied mental models
The main motivation for MPI is the fact that it can be scaled to more or less arbitrary scales, currently up to millions
of cores [1]. Contrast this with threaded programming, which is limited more or less by the core count on a single
node, currently about 70.
Considering this background, the target audience for MPI teaching consists of upper level undergraduate students,
graduate students, and even post-doctoral researchers who are engaging for the first time in large scale simulations.
The typical participant in an MPI course is likely to understand more than the basics of linear algebra and some
amount of numerics of Partial Diffential Equation (PDE).
This mental model corresponds closely to the way algorithms are described in the mathematical literature of par-
allelism, and it is actually correct to an extent in the context of threaded libraries such as OpenMP, where there is
indeed initially a single thread of execution, which in some places spawns a team of threads to execute certain sec-
tions of code in parallel. However, in MPI this model is factually incorrect, since there are always multiple processes
active, with none essentially priviliged over others, and no shared or central data store.
3. To first order; second order effects such as affinity complicate this story.
Supersteps as a computational model allow for small differences in control flow, for instance conditional inside a
big parallelizable loop, but otherwise imply a form of centralized control (as above) on the level of major algorithm
steps. However, codes using the pipeline model of parallelism, such idioms as
MPI_Recv( /* from: */ my_process-1)
// do some major work
MPI_Send( /* to : */ my_process+1)
fall completely outside either the sequential semantics or BSP model and require an understanding of one pro-
cess’ control being dependent on another’s. Gaining an mental model for this sort of unsynchronized execution is
nontrivial to achieve. We target this explicitly in section 53.5.1.
53.3.1 Criticism
We offer three points of criticism against this traditional approach to teaching MPI.
First of all, there is no real reason for teaching collectives after two-sided routines. They are not harder, nor require
the latter as prerequisite. In fact, their interface is simpler for a beginner, requiring one line for a collective, as
opposed to at least two for a send/receive pair, probably surrounded by conditionals testing the process rank. More
importantly, they reinforce the symmetric process view, certainly in the case of the MPI_All... routines.
Our second point of criticism is regarding the blocking and nonblocking two-sided communication routines. The
blocking routines are typically taught first, with a discussion of how blocking behavior can lead to load unbalance
and therefore inefficiency. The nonblocking routines are then motivated from a point of latency hiding and solving
the problems inherent in blocking. In our view such performance considerations should be secondary. Nonblocking
routines should instead be taught as the natural solution to a conceptual problem, as explained below.
Thirdly, starting with point-to-point routines stems from a Communicating Sequential Processes (CSP)[13] view of
a program: each process stands on its own, and any global behavior is an emergent property of the run. This may
make sense for the teacher who know how concepts are realized ‘under the hood’, but it does not lead to additional
insight with the students. We believe that a more fruitful approach to MPI programming starts from the global
behavior, and then derives the MPI process in a top-down manner.
Based on this discussion of possible applications, and in view of the likely background of course attendants, we
consider Finite Difference solution of PDEs as a prototypical application that exercises both the simplest and more
sophisticated mechanisms. During a typical MPI training, even a one-day short course, we insert a lecture on sparse
matrices and their computational structure to motivate the need for various MPI constructs.
4. The MPI_Reduce call performs a reduction on data found on all processes, leaving the result on a ‘root’ process. With
MPI_Allreduce the result is left on all processes.
explain; it certainly reinforces the symmetric mindset. There is also essentially no difference in efficiency.
Certainly, in most applications the ‘allreduce’ is the more common mechanism, for instance where the algorithm
requires computations such as
𝑦 ̄ ← 𝑥/‖
̄ 𝑥‖̄
where 𝑥, 𝑦 are distributed vectors. The quantity ‖𝑥‖̄ is then needed on all processes, making the Allreduce the
natural choice. The rooted reduction is typically only used for final results. Therefore we advocate introducing both
rooted and nonrooted collectives, but letting the students initially do exercises with the nonrooted variants.
This has the added advantage of not bothering the students initially with the asymmetric treatment of the receive
buffer between the root and all other processes.
The lecturer stresses that the global structure of the distributed array is only ‘in the programmer’s mind’: each MPI
process sees an array with indexing starting at zero. The following snippet of code is given for the students to use
in subsequent exercises:
int myfirst = .....;
for (int ilocal=0; ilocal<nlocal; ilocal++) {
int iglobal = myfirst+ilocal;
array[ilocal] = f(iglobal);
}
At this point, the students can code a second variant of the primality testing exercise above, but with an array
allocated to store the integer range. Since collectives are now known, it becomes possible to have a single summary
statement from one process, rather than a partial result statement from each.
The inner product of two distributed vectors is a second illustration of working with distributed data. In this case,
the reduction for collecting the global result is slightly more useful than the collective in the previous examples.
For this example no translation from local to global numbering is needed.
applied to an array. Students who know about PDEs will recognize that with different coefficients this is the heat
equation; for others a graphics ‘blur’ operation can be used as illustration, if they accept that a one-dimensional
pixel array is a stand-in for a true graphic.
Under the ’owner computes’ regime, where the process that stores location 𝑦𝑖 performs the full calculation of that
quantity, we see the need for communication in order to compute the first and last element of the local part of 𝑦:
We then state that this data transfer is realized in MPI by two-sided send/receive pairs.
5. In this operations, process A sends to B, and B subsequenty sends to A. Thus the time for a message is half the time of a
ping-pong. It is not possible to measure a single message directly, since processes can not be synchronized that finely.
This could be implemented with blocking sends and receive calls, but students recognize how this could be some-
where between tedious and error-prone. Instead, to prevent deadlock and serialization as described above, we now
offer the MPI_Sendrecv routine6 . Students are asked to implement the classroom exercise above with the sendrecv
routine. Ideally, they use timing or tracing to gather evidence that no serialization is happening.
As a nontrivial example (in fact, this takes enough programming that one might assign it as an exam question, rather
than an exercise during a workshop) students can now implement an odd-even transposition sort algorithm using
MPI_Sendrecv as the main tool. For simplicity they can use a single array element per process. (If each process has
a subarray one has to make sure their solution has the right parallel complexity. It is easy to make errors here and
implement a correct algorithm that, however, performs too slowly.)
Note that students have at this point not done any serious exercises with the blocking communication calls, other
than the ping-pong. No such exercises will in fact be done.
Implementing the three-point averaging with nonblocking calls is at this point an excellent exercise.
Note that we have here motivated the nonblocking routines to solve a symmetric problem. Doing this should teach
the students the essential point that each nonblocking call needs its own buffer and generates its own request.
Viewing nonblocking routines as a performance alternative to blocking routines is likely to lead to students re-
using buffers or failing to save the request objects. Doing so is a correctness bug that is very hard to find, and at
large scale it induces a memory leak since many requests objects are lost.
However, didactically these topics do not require the careful attention that the introduction of the basic concepts
needs, so we will not go into further detail here.
6. The MPI_Sendrecv call combines a send a receive operation, specifying for each process both a sending and receiving
communication. The execution guarantees that no deadlock or serialization will occur.
We have arrived at the somewhat unusual solution of having students act out the program in front of the class.
With each student acting out the program, any interaction is clearly visible to an extent that is hard to achieve any
other way.
53.5.1 Sequentialization
Our prime example is to illustrate the blocking behavior of MPI_Send and MPI_Recv7 . Deadlock is easy enough to
understand as a consequence of blocking – in the simplest case of deadlock to processes are both blocked expecting
a receive from the other – but there are more subtle effects that will come as a surprise to students. (This was alluded
to in section 53.4.7.)
Executing this program, the students first all turn to the right, and they see that giving data to a neighbor is not
possible because no one is executing the receive instruction. The last process is not sending, so moves on to the
receive instruction, after which the penultimate process can receive, et cetera.
This exercise makes the students see, better than any explanation or diagram, how a parallel program can compute
the right result, but with unexpectedly low performance because of the interaction of the processes. (In fact, we
have had explicit feedback that this game was the biggest lightbulb moment of the class.)
7. Blocking is defined as the process executing a send or receive call halting until the corresponding operation is executing.
53.5.2 Ping-pong
While in general we emphasize the symmetry of MPI processes, during the discussion of send and receive calls we
act out the ping-pong operation (one process sending data to another, followed by the other sending data back),
precisely to demonstrate how asymmetric actions are handled. For this, two students throw a pen back and forth
between them, calling out ‘send’ and ‘receive’ when they do so.
The teacher then asks each student what program they executed, which is ‘send-receive’ for the one, and ‘receive-
send’ for the other student. Incorporating this in the SPMD model then leads to a code with conditionals to determine
the right action for the right process.
We have at one point tried to have a pair of student act out a ‘race condition’ in shared memory programming, but
modeling this quickly became too complicated to be convincing.
We cover the following topics, with division over two days in the workshop format:
• Day 1: familiarity with SPMD, collectives, blocking and nonblocking two-sided communication.
• Day 2: exposure to: sub-communicators, derived datatypes. Two of the following: MPI-I/O, one-sided
communication, process management, the profiling and tools interfaces, neighborhood collectives.
53.6.1 Exercises
On day 1 the students do approximately 10 programming exercises, mostly finishing a skeleton code given by the
instructor. For the day 2 material students do two exercises per topic, again starting with a given skeleton. (Skeleton
codes are available as part of the repository [9].)
The design of these skeleton codes is an interesting problem in view of our concern with mental models. The
skeletons are intended to take the grunt work away from the students, to both indicate a basic code structure and
relieve them from making elementary coding errors that have no bearing on learning MPI. On the other hand, the
skeletons should leave enough unspecified that multiple solutions are possible, including wrong ones: we want
students to be confronted with conceptual errors in their thinking, and a too-far-finished skeleton would prevent
them from doing that.
Example: the prime finding exercise mentioned above (which teaches the notion of functional parallelim) has the
following skeleton:
int myfactor;
// Specify the loop header:
// for ( ... myfactor ... )
for (
/**** your code here ****/
) {
if (bignum%myfactor==0)
printf("Process %d found factor %d\n",
procno,myfactor);
}
This leaves open the possibility of both a blockwise and a cyclic distribution of the search space, as well as incorrect
solutions where each process runs through the whole search space.
53.6.2 Projects
Students in our academic course do a programming project in place of a final exam. Students can choose between
one of a set of standard projects, or doing a project of their own choosing. In the latter case, some students will
do a project in context of their graduate research, which means that they have an existing codebase; others will
write code from scratch. It is this last category, that will most clearly demonstrate their correct understanding of
the mental model underlying SPMD programs. However, we note that this is only a fraction of the students in our
course, a fraction made even smaller by the fact that we also give a choice of doing a project in OpenMP rather than
MPI. Since OpenMP is, at least to the beginning programmer, simpler to use, there is an in fact a clear preference
for it among the students who pick their own project.
One obvious solution to online teaching is automated grading: a student submits an exercise, which is then run
through a checker program that tests the correct output. Especially if the programming assignment takes input, a
checker script can uncover programming errors, notably in boundary cases.
However, the whole target of this paper is to uncover conceptual misunderstandings, for instance such as can lead to
correct results with sub-optimal performance. In a classroom situation such misunderstandings are quickly caught
and cleared up, but to achieve this in a context of automated grading we need to go further.
We have started experiments with actually parsing code submitted by the students. This effort started in a beginning
programming class taught by the present author, but is now being extended to the MPI courses.
It is possible to uncover misconceptions in students’ understanding by detecting the typical manifestations of such
misconceptions. For instance, the code in section 53.5.4 can be uncovered by detecting a loop where the upper
bound involves a variable that was set by MPI_Comm_size. Many MPI codes have no need for such a loop over all
processes, so detecting one leads to an alert for the student.
Note that no tools exist for such automated evaluation. The source code analysis needed falls far short of full
parsing. On the other hand, the sort of constructs is it supposed to detect, are normally not of interest to the writers
of compilers and source translators. This means that by writing fairly modest parsers (say, less than 200 lines of
python) we can perform a sophisticated analysis of the students’ codes. We hope to report on this in more detail in
a follow-up paper.
53.9 Summary
In this paper we have introduced a nonstandard sequence for presenting the basic mechanisms in MPI. Rather
than starting with sends and receives and building up from there, we start with mechanisms that emphasize the
inherent symmetry between processes in the SPMD programming model. This symmetry requires a substantial shift
in mindset of the programmer, and therefore we target it explicitly.
In general, it is the opinion of this author that it pays off to teach from the basis of instilling a mental model, rather
than of presenting topics in some order of (perceived) complexity or sophistication.
Comparing our presentation as outlined above to the standard presentation, we recognize the downplaying of the
blocking send and receive calls. While students learn these, and in fact learn them before other send and receive
mechanisms, they will recognize the dangers and difficulties in using them, and will have the combined sendrecv
call as well as nonblocking routines as standard tools in their arsenal.
Bibliography
[1] Pavan Balaji, Darius Buntinas, David Goodell, William Gropp, Sameer Kumar, Ewing Lusk, Rajeev Thakur, and
Jesper Larsson Träff. MPI on millions of cores. Parallel Processing Letters, 21(01):45–60, 2011. [Cited on page 615.]
[2] Y. Ben-David Kolikant. Gardeners and cinema tickets: High schools’ preconceptions of concurrency. Computer
Science Education, 11:221–245, 2001. [Cited on page 616.]
[3] Ernie Chan, Marcel Heimlich, Avi Purkayastha, and Robert van de Geijn. Collective communication: theory,
practice, and experience. Concurrency and Computation: Practice and Experience, 19:1749–1783, 2007. [Cited on
page 88.]
[4] Tom Cornebize, Franz C Heinrich, Arnaud Legrand, and Jérôme Vienne. Emulating High Performance Linpack
on a Commodity Server at the Scale of a Supercomputer. working paper or preprint, December 2017. [Cited on
page 591.]
[5] Lisandro Dalcin. MPI for Python, homepage. https://github.com/mpi4py/mpi4py. [Cited on page 21.]
[6] Lisandro Dalcin and Yao-Lung L. Fang. mpi4py: Status update after 12 years of development. Computing in
Science & Engineering, 23(4):47–54, 2021. [Cited on page 21.]
[7] Saeed Dehnadi, Richard Bornat, and Ray Adams. Meta-analysis of the effect of consistency on success in early
learning of programming. In Psychology of Programming Interest Group PPIG 2009, pages 1–13. University of
Limerick, Ireland, 2009. [Cited on page 615.]
[8] Peter J. Denning. Computational thinking in science. American Scientist, pages 13–17, 2017. [Cited on page 615.]
[9] Victor Eijkhout. Parallel Programming in MPI and OpenMP. 2016. available for download: https://
bitbucket.org/VictorEijkhout/parallel-computing-book/src. [Cited on pages 614 and 625.]
[10] Victor Eijkhout. Performance of MPI sends of non-contiguous data. arXiv e-prints, page arXiv:1809.10778, Sep
2018. [Cited on page 323.]
[11] Brice Goglin. Managing the Topology of Heterogeneous Cluster Nodes with Hardware Locality (hwloc). In
International Conference on High Performance Computing & Simulation (HPCS 2014), Bologna, Italy, July 2014.
IEEE. [Cited on page 584.]
[12] W. Gropp, E. Lusk, and A. Skjellum. Using MPI. The MIT Press, 1994. [Cited on page 328.]
[13] C.A.R. Hoare. Communicating Sequential Processes. Prentice Hall, 1985. ISBN-10: 0131532715, ISBN-13: 978-
0131532717. [Cited on page 617.]
[14] Torsten Hoefler, Prabhanjan Kambadur, Richard L. Graham, Galen Shipman, and Andrew Lumsdaine. A case
for standard non-blocking collective operations. In Proceedings, Euro PVM/MPI, Paris, France, October 2007.
[Cited on page 82.]
[15] Torsten Hoefler, Christian Siebert, and Andrew Lumsdaine. Scalable communication protocols for dynamic
sparse data exchange. SIGPLAN Not., 45(5):159–168, January 2010. [Cited on page 82.]
[16] INRIA. SimGrid homepage. http://simgrid.gforge.inria.fr/. [Cited on page 591.]
[17] L. V. Kale and S. Krishnan. Charm++: Parallel programming with message-driven objects. In Parallel Program-
ming using C++, G. V. Wilson and P. Lu, editors, pages 175–213. MIT Press, 1996. [Cited on page 18.]
630
[18] M. Li, H. Subramoni, K. Hamidouche, X. Lu, and D. K. Panda. High performance mpi datatype support with
user-mode memory registration: Challenges, designs, and benefits. In 2015 IEEE International Conference on
Cluster Computing, pages 226–235, Sept 2015. [Cited on page 323.]
[19] Zhenying Liu, Barbara Chapman, Tien-Hsiung Weng, and Oscar Hernandez. Improving the performance
of openmp by array privatization. In Proceedings of the OpenMP Applications and Tools 2003 International
Conference on OpenMP Shared Memory Parallel Programming, WOMPAT’03, pages 244–259, Berlin, Heidelberg,
2003. Springer-Verlag. [Cited on page 421.]
[20] Robert McLay. T3pio: TACC’s terrific too for parallel I/O. https://github.com/TACC/t3pio. [Cited on page 269.]
[21] MPI forum: MPI documents. http://www.mpi-forum.org/docs/docs.html. [Cited on page 614.]
[22] The OpenMP API specification for parallel programming. http://openmp.org/wp/
openmp-specifications/. [Cited on page 618.]
[23] Amit Ruhela, Hari Subramoni, Sourav Chakraborty, Mohammadreza Bayatpour, Pouya Kousha, and Dha-
baleswar K. Panda. Efficient asynchronous communication progress for mpi without dedicated resources.
EuroMPI’18, New York, NY, USA, 2018. Association for Computing Machinery. [Cited on page 318.]
[24] Marc Snir, Steve Otto, Steven Huss-Lederman, David Walker, and Jack Dongarra. MPI: The Complete Reference,
Volume 1, The MPI-1 Core. MIT Press, second edition edition, 1998. [Cited on page 614.]
[25] Jeff Squyres. Mpi-request-free is evil. Cisco Blogs, January 2013. https://blogs.cisco.com/
performance/mpi_request_free-is-evil. [Cited on page 126.]
[26] R. Thakur, W. Gropp, and B. Toonen. Optimizing the synchronization operations in MPI one-sided communi-
cation. Int’l Journal of High Performance Computing Applications, 19:119–128, 2005. [Cited on page 259.]
[27] Universitat Politecnica de Valencia. SLEPC – Scalable software for Eigenvalue Problem Computations. http:
//www.grycap.upv.es/slepc/. [Cited on page 475.]
[28] Leslie G. Valiant. A bridging model for parallel computation. Commun. ACM, 33:103–111, August 1990. [Cited
on page 616.]
[29] P.C. Wason and P.N. Johnson-Laird. Thinking and Reasoning. Harmondsworth: Penguin, 1968. [Cited on page 615.]
List of acronyms
632
Chapter 56
General Index
633
Index
634
INDEX
Lists of notes
643
57.2 Fortran notes
MPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1 Formatting of Fortran notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2 MPI module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3 Processor name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4 Communicator type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5 MPI send/recv buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
6 Min/maxloc types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
7 Index of requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8 Status object in f08 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
9 Derived types for handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
10 Byte counting types in Fortran . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
11 Subarrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
12 Extent as Aint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
13 Displacement unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
14 Offset literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
15 Attribute querying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
16 Fortran-only compile-time constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
OpenMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
17 OpenMP version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
18 OpenMP sentinel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
19 OMP do pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
20 Reductions on derived types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
21 Private variables in parallel region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
22 Saved variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
23 Private common blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
24 Array sizes in map clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
PETSc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
25 Petsc Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
26 Setting values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
27 F90 array access through pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
28 Backtrace on error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
29 Error code handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
30 Print string construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
31 Printing and newlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
644
57.3 C++ notes
MPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1 Buffer treatment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
OpenMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
2 Output streams in parallel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
3 Parallel regions in lambdas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
4 Dynamic scope for class methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
5 Custom iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
6 Range syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
7 C++20 ranges header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
8 C++20 ranges speedup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
9 Reductions on vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
10 Lambda expressions in declared reductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
11 Reduction over iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
12 Templated reductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
13 Example: reduction over a map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
14 Reduction on class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
15 Privatizing class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
16 Vectors are copied, unlike arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
17 Threadprivate random number generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
18 Lock inside overloaded operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
19 Uninitialized containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
20 List filtering example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
PETSc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
21 Exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
1 Notes format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2 Header file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3 Init, finalize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
645
LIST OF MPL NOTES
4 Processor name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5 World communicator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6 Communicator copying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7 Communicator passing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
8 Rank and size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
9 Reduction operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
10 Scalar buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
11 Vector buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
12 Iterator buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
13 Send vs recv buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
14 Reduce in place . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
15 Broadcast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
16 Scan operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
17 Gather/scatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
18 Gather on nonroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
19 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
20 User-defined operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
21 Lambda operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
22 Nonblocking collectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
23 Buffer type safety . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
24 Blocking send and receive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
25 Sending arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
26 Iterator layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
27 Any source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
28 Send-recv call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
29 Requests from nonblocking calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
30 Request pools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
31 Wait any . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
32 Request handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
33 Status object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
34 Status source querying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
35 Tag types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
36 Message tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
37 Receive count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
38 Persistent requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
39 Buffered send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
40 Buffer attach and detach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
41 Datatype handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
42 Native MPI data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
43 Derived type handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
44 Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
45 Contiguous type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
46 Contiguous composing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
47 Vector type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
48 Subarray layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
49 Indexed type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
50 Layouts for gatherv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
51 Indexed block type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
52 Struct type scalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
MPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1 Running mpi4py programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2 Python notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3 Import mpi module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4 Initialize/finalize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5 Communicator objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6 Communicator rank and size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7 Buffers from numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
8 Buffers from subarrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
9 In-place collectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
10 Sending objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
11 Define reduction operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
12 Reduction function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
13 Message tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
14 Handling a single request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
15 Request arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
16 Status object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
17 Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
18 Predefined data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
19 Size of numpy types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
20 Derived type handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
21 Vector type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
647
LIST OF PYTHON NOTES
MPI_2INT, 78
MPI_2INTEGER, 78
MPI_2REAL, 78
MPI_Abort, 30, 81, 316, 325
MPI_Accumulate, 238, 245, 251, 257
MPI_Add_error_class, 316
MPI_Add_error_code, 316
MPI_Add_error_string, 316
MPI_Address (deprecated), 178
0_MPI_OFFSET_KIND, 270
MPI_ADDRESS_KIND, 155, 160, 242, 311, 327
access_style, 310 MPI_AINT, 160
accumulate_ops, 257 MPI_Aint, 155, 156, 160, 160, 184, 191, 237, 241
accumulate_ordering, 257 in Fortran, 160
alloc_shared_noncontig, 292 MPI_Aint_add, 160, 237
MPI_Aint_diff, 160, 237
cb_block_size, 310 MPI_Allgather, 65, 95
cb_buffer_size, 310 MPI_Allgather_init, 145
cb_nodes, 310 MPI_Allgatherv, 73
chunked, 310 MPI_Allgatherv_init, 145
chunked_item, 310 MPI_Alloc_mem, 234, 236, 252, 314
chunked_size, 310 MPI_Allreduce, 44, 45, 52, 69, 94, 95
collective_buffering, 310 MPI_Allreduce_init, 144, 145
control variable, 300–302 MPI_Alltoall, 66, 67, 501
cvar, see control variable MPI_Alltoall_init, 145
MPI_Alltoallv, 67, 67, 73, 77, 177
file_perm, 310 MPI_Alltoallv_init, 145
MPI_Alltoallw_init, 145
Integer(kind=MPI_Address_kind), 192
MPI_ANY_SOURCE, 71, 89, 101, 101, 125, 127, 128, 132,
io_node_list, 310
232, 311, 314, 324, 327
irequest_pool, 121
MPI_ANY_TAG, 102, 110, 127, 129, 327
KSPSolve, 519 MPI_APPNUM, 223, 311, 326
MPI_ARGV_NULL, 220, 327
MPI.ANY_TAG, 102 MPI_ARGVS_NULL, 223, 327
mpi://SELF, 228 MPI_ASYNC_PROTECTS_NONBLOCKING, 318, 327
mpi://WORLD, 228 MPI_Attr_get, 310
MPI_2DOUBLE_PRECISION, 78 MPI_BAND, 78
649
MPI_Barrier, 72, 271, 321 MPI_Comm_get_parent, 215, 221, 222, 227
MPI_Barrier_init, 145 MPI_Comm_group, 210, 215
MPI_Bcast, 54, 94 MPI_Comm_idup, 202
MPI_Bcast_init, 145 MPI_Comm_idup_with_info, 202
MPI_BOR, 78 MPI_Comm_join, 226, 227
MPI_BOTTOM, 160, 258, 326, 327 MPI_COMM_NULL, 201, 202, 204, 207, 211, 215, 221, 276,
MPI_Bsend, 149, 149, 151 289
MPI_Bsend_init, 144, 149, 152 MPI_Comm_rank, 35, 35, 36, 208, 215, 283
MPI_BSEND_OVERHEAD, 151, 152, 327 MPI_Comm_remote_group, 216
MPI_Buffer_attach, 151, 151 MPI_Comm_remote_size, 216, 222
MPI_Buffer_detach, 151, 151 MPI_COMM_SELF, 201, 202, 481
MPI_BXOR, 78 MPI_Comm_set_attr, 310, 312
MPI_BYTE, 155, 156, 157, 163, 186 MPI_Comm_set_errhandler, 314, 315, 316
MPI_C_BOOL, 156 MPI_Comm_set_info, 309
MPI_C_COMPLEX, 156 MPI_Comm_set_name, 202
MPI_C_DOUBLE_COMPLEX, 156 MPI_Comm_size, 35, 35, 36, 100, 215, 283
MPI_C_FLOAT_COMPLEX, 156 MPI_Comm_spawn, 207, 219, 223, 319
MPI_C_LONG_DOUBLE_COMPLEX, 156 MPI_Comm_spawn_multiple, 223, 311
MPI_Cancel, 327, 328 MPI_Comm_split, 72, 207, 208, 217, 279
MPI_CART, 275 MPI_Comm_split_type, 210, 289, 290, 294
MPI_Cart_coords, 277 MPI_Comm_test_inter, 215
MPI_Cart_create, 276, 278, 280 MPI_COMM_TYPE_HW_GUIDED, 289
MPI_Cart_get, 276 MPI_COMM_TYPE_HW_UNGUIDED, 289
MPI_Cart_map, 280, 287 MPI_COMM_TYPE_SHARED, 289
MPI_Cart_rank, 277 MPI_COMM_WORLD, 34, 201, 202, 207, 208, 213, 217, 219,
MPI_Cart_sub, 279 222, 227, 229, 294, 311, 316, 319, 326, 468, 473,
MPI_Cartdim_get, 276 481
MPI_CHAR, 155, 156 MPI_Compare_and_swap, 249
MPI_CHARACTER, 157 MPI_COMPLEX, 157
MPI_Close_port, 223 MPI_CONGRUENT, 204
MPI_COMBINER_VECTOR, 195 MPI_Count, 45, 155, 182, 184, 184, 185, 188
MPI_Comm, 21–23, 34, 201, 202, 326 MPI_COUNT_KIND, 327
MPI_Comm_accept, 223, 223 MPI_Datatype, 62, 154, 155, 163, 165, 212
MPI_Comm_attr_function, 312 MPI_DATATYPE_NULL, 156, 165
MPI_Comm_compare, 203, 216, 229 MPI_Dims_create, 275
MPI_Comm_connect, 223, 224, 225, 314 MPI_DISPLACEMENT_CURRENT, 269
MPI_Comm_create, 207, 211 MPI_DIST_GRAPH, 275, 275
MPI_Comm_create_errhandler, 316, 317 MPI_Dist_graph_create, 281, 281, 283, 285, 286
MPI_Comm_create_group, 211 MPI_Dist_graph_create_adjacent, 281, 284
MPI_Comm_create_keyval, 312 MPI_Dist_graph_neighbors, 283, 284, 286, 286
MPI_Comm_delete_attr, 312 MPI_Dist_graph_neighbors_count, 283, 284, 286
MPI_Comm_disconnect, 207, 225 MPI_DISTRIBUTE_BLOCK, 175
MPI_Comm_dup, 35, 202, 203, 205, 207, 309, 473 MPI_DISTRIBUTE_CYCLIC, 175
MPI_Comm_dup_with_info, 202, 309 MPI_DISTRIBUTE_DFLT_DARG, 175
MPI_Comm_free, 206, 207, 213 MPI_DISTRIBUTE_NONE, 175
MPI_Comm_free_keyval, 312 MPI_DOUBLE, 155, 156
MPI_Comm_get_attr, 219, 310 MPI_DOUBLE_COMPLEX, 157
MPI_Comm_get_errhandler, 314, 316 MPI_DOUBLE_INT, 78, 78
MPI_Comm_get_info, 309 MPI_DOUBLE_PRECISION, 155, 157
nb_proc, 310
no_locks, 257
num_io_nodes, 310
OMPI_COMM_TYPE_SOCKET, 291
same_op, 257
same_op_no_op, 257
striping_factor, 310
striping_unit, 310
testany, 121
thread_support, 228
vector_layout, 167
wtime, 320
• ALLOCATABLE ?? • IN ?? • OPTIONAL ??
• ASYNCHRONOUS ?? • INCLUDE ?? • OUT ??
• BLOCK ?? • INOUT ??
• POINTER ??
• CHARACTER ?? • INTEGER ??
• COMMON ?? • INTENT ?? • PROCEDURE ??
• COMPLEX ?? • INTERFACE ?? • REAL ??
• CONTAINS ?? • ISO_C_BINDING ?? • SEQUENCE ??
• CONTIGUOUS ?? • ISO_FORTRAN_ENV ?? • TARGET ??
• C_F_POINTER ?? • KIND ??
• TYPE ??
• C_PTR ?? • LOGICAL ??
• EXTERNAL ?? • MODULE ?? • USER_FUNCTION ??
• FUNCTION ?? • MPI_User_function ?? • VOLATILE ??
Class Comm: Class Cartcomm: Class Class Request: Class Grequest: Class Class Datatype: Class File: Class Info:
Distgraphcomm: Class Graphcomm: Prequest: Class Status: Class Op:
Class Intercomm: Class Intracomm:
Class Topocomm: Class Group: Class Win: Class Errhandler: Class Message:
dist_schedule, 433
do, 351, 354
dynamic, 438
false, 415
final, 412
firstprivate, 389, 408, 408, 432, 450
flush, 400, 402
for, 351, 353, 354, 357, 409
_OPENMP, 340, 439
if, 412
aligned, 427 implicit barrier
atomic, 398, 399, 465 after single directive, 382
in_reduction, 411
barrier inscan, 377
cancelled by nowait, 366
barrier, 366, 396, 396 lastprivate, 367, 389
bind-var, 415 league, 433
linear, 427
cancel, 351, 412, 460, 461
chunk, 361 masked, 348
close, 415 mast taskloop, 409
collapse, 364, 364, 365 master, 296, 382, 409, 415, 416
copyin, 392
copyprivate, 382, 392 nowait, 366, 397, 438, 438
core, 415 num_threads, 344
critical, 357, 398, 399, 437
omp
declare, 374 barrier
declare simd, 427 implicit, 397
default omp for, 388
firstprivate, 389 omp_alloc, 393
none, 389 OMP_CANCELLATION, 351, 435
private, 389 omp_cgroup_mem_alloc, 394
shared, 389 omp_const_mem_alloc, 394
default, 388 omp_const_mem_space, 394
depend, 409, 413 OMP_DEFAULT_DEVICE, 435
663
omp_default_mem_alloc, 394 OMP_SCHEDULE, 362, 363, 436, 436
omp_default_mem_space, 394 omp_set_dynamic, 435, 436
omp_destroy_nest_lock, 402 omp_set_max_active_levels, 349, 435
OMP_DISPLAY_ENV, 387, 435 omp_set_nest_lock, 402
OMP_DYNAMIC, 392, 435, 436 omp_set_nested, 435, 436
omp_get_active_level, 350, 435 omp_set_num_threads, 344, 435, 436
omp_get_ancestor_thread_num, 350, 435 omp_set_schedule, 363, 435, 436
omp_get_cancellation, 351 OMP_STACKSIZE, 387, 436
omp_get_dynamic, 435, 436 omp_test_nest_lock, 402
omp_get_level, 350, 435 OMP_THREAD_LIMIT, 433, 436
omp_get_max_active_levels, 349, 435 omp_thread_mem_alloc, 394
omp_get_max_threads, 344, 435, 436 omp_unset_nest_lock, 402
omp_get_nested, 435, 436 OMP_WAIT_POLICY, 436, 436
omp_get_num_procs, 342, 344, 435, 436, 587 openmp_version, 340
omp_get_num_threads, 342, 344, 347, 348, 435, 436 ordered, 365, 366
omp_get_proc_bind, 415
omp_get_schedule, 363, 435, 436 parallel, 341, 341, 347, 351, 353, 354, 357, 418, 450
omp_get_team_size, 350, 435 parallel region
omp_get_thread_limit, 350, 433, 435 barrier at the end of, 397
omp_get_thread_num, 342, 347, 348, 435, 436 pragma, see see under pragma name
omp_get_wtick, 435, 437 priority, 412
omp_get_wtime, 435, 436 private, 386, 387, 450
omp_high_bw_mem_alloc, 394 proc_bind, 416, 418
omp_high_bw_mem_space, 394 proc_bind, 415
omp_in, 374
reduction, 357, 362, 369, 372, 374, 398, 411
omp_in_parallel, 351, 435, 436
omp_init_nest_lock, 402 safelen(𝑛), 427
omp_is_initial_device, 432 scan, 377, 377, 439
omp_large_cap_mem_alloc, 394 schedule
omp_large_cap_mem_space, 394 auto, 362
omp_low_lat_mem_alloc, 394 chunk, 361
omp_low_lat_mem_space, 394 guided, 362
OMP_MAX_ACTIVE_LEVELS, 349, 435 runtime, 362
OMP_MAX_TASK_PRIORITY, 412, 435 schedule, 361–363, 438
OMP_NESTED (deprecated), 349 section, 380
OMP_NESTED, 435, 436 sections, 349, 351, 369, 380, 389
OMP_NUM_THREADS, 340, 342, 344, 435, 436 simd, 427, 427
omp_out, 374 single, 381
OMP_PLACES, 415, 415, 417, 436 socket, 415
omp_priv, 374 spread, 415
OMP_PROC_BIND, 415, 415, 435, 436
omp_pteam_mem_alloc, 394 target
omp_sched_affinity, 363 enter data, 433
omp_sched_auto, 363 exit data, 433
omp_sched_dynamic, 363 map, 432
omp_sched_guided, 363 update from, 433
omp_sched_runtime, 363 update to, 433
omp_sched_static, 363 target, 432, 433
omp_sched_t, 363 task, 408, 409
untied, 411
wait-policy-var, 436
workshare, 382
CHCKERCXX, 538
CHKERRA, 538
CHKERRABORT, 538
CHKERRMPI, 538
CHKERRQ, 536, 538
--sub_ksp_monitor, 543 CHKMEMA, 538
-da_grid_x, 504 CHKMEMQ, 536, 538
-da_refine, 510
-da_refine_x, 510 DM, 504, 505, 510, 541
-download-blas-lapack, 479 DM_BOUNDARY_GHOSTED, 504
-download_mpich, 474 DM_BOUNDARY_NONE, 504
-ksp_atol, 519 DM_BOUNDARY_PERIODIC, 504
-ksp_converged_reason, 520 DMBoundaryType, 504
-ksp_divtol, 519 DMCreateGlobalVector, 507, 510
-ksp_gmres_restart, 521 DMCreateLocalVector, 507, 510
-ksp_mat_view, 496 DMDA, 504, 507, 509, 510
-ksp_max_it, 519 DMDA_STENCIL_BOX, 504
-ksp_monitor, 526, 543 DMDA_STENCIL_STAR, 504
-ksp_monitor_true_residual, 526 DMDACreate1d, 504
-ksp_rtol, 519 DMDACreate2d, 504, 504
-ksp_type, 520 DMDAGetCorners, 505, 511
-ksp_view, 518, 541, 543 DMDAGetLocalInfo, 505
-log_summary, 542 DMDALocalInfo, 505, 506, 509
-log_view, 544 DMDASetRefinementFactor, 510
-malloc_dump, 545 DMDAVecGetArray, 509
-mat_view, 496, 541 DMGetGlobalVector, 507
-pc_factor_levels, 523 DMGetLocalVector, 507
-snes_fd, 530 DMGlobalToLocal, 507, 510
-snes_fd_color, 530 DMGlobalToLocalBegin, 510
-vec_view, 541 DMGlobalToLocalEnd, 510
-with-precision, 474 DMLocalToGlobal, 507, 510
-with-scalar-type, 474 DMLocalToGlobalBegin, 510
666
DMLocalToGlobalEnd, 510 MatCoarsenViewFromOptions, 542
DMPLEX, 513 MatCreate, 490
DMRestoreGlobalVector, 507 MatCreateDenseCUDA, 534
DMRestoreLocalVector, 507 MatCreateFFT, 499
DMStencilType, 504 MatCreateSeqDenseCUDA, 534
DMViewFromOptions, 542 MatCreateShell, 497
MatCreateSubMatrices, 497
INSERT_VALUES, 487, 494 MatCreateSubMatrix, 497, 502
IS, 502 MatCreateVecs, 483, 491
ISCreate, 500 MatCreateVecsFFTW, 499
ISCreateBlock, 500 MATDENSECUDA, 534
ISCreateGeneral, 500 MatDenseCUDAGetArray, 534
ISCreateStride, 500 MatDenseGetArray, 495
ISGetIndices, 501 MatDenseRestoreArray, 495
ISLocalToGlobalMappingViewFromOptions, 542 MatGetArray (deprecated), 495
ISRestoreIndices, 501 MatGetRow, 495
ISViewFromOptions, 542 MatImaginaryPart, 479
MatMatMult, 496
KSP, 496, 517
MATMPIAIJ, 490
KSPBuildResidual, 526
MATMPIAIJCUSPARSE, 534
KSPBuildSolution, 526
MatMPIAIJSetPreallocation, 493
KSPConvergedDefault, 525
MATMPIBIJ, 499
KSPConvergedReason, 519
MATMPIDENSE, 490
KSPConvergedReasonView, 519
MATMPIDENSECUDA, 534
KSPConvergedReasonViewFromOptions, 542
KSPCreate, 518 MatMult, 496, 497
KSPGetConvergedReason, 519 MatMultAdd, 496
KSPGetIterationNumber, 520 MatMultHermitianTranspose, 496
KSPGetOperators, 518 MatMultTranspose, 496
KSPGetRhs, 526 MatPartitioning, 502
KSPGetSolution, 526 MatPartitioningApply, 502
KSPGMRESSetRestart, 521 MatPartitioningCreate, 502
KSPMatSolve, 521 MatPartitioningDestroy, 502
KSPMonitorDefault, 526 MatPartitioningSetType, 502
KSPMonitorSet, 526 MatPartitioningViewFromOptions, 542
KSPMonitorTrueResidualNorm, 526 MatRealPart, 479
KSPReasonView (deprecated), 519 MatRestoreArray (deprecated), 495
KSPSetConvergenceTest, 525 MatRestoreRow, 495
KSPSetFromOptions, 518, 521, 527 MATSEQAIJ, 490
KSPSetOperators, 518 MATSEQAIJCUSPARSE, 534
KSPSetOptionsPrefix, 543 MatSeqAIJGetArray, 495
KSPSetTolerances, 519 MatSeqAIJRestoreArray, 495
KSPSetType, 520 MatSeqAIJSetPreallocation, 492
KSPView, 518, 540 MATSEQDENSE, 490
KSPViewFromOptions, 542 MATSEQDENSECUDA, 534
MatSetOptionsPrefix, 544
MAT_FLUSH_ASSEMBLY, 494 MatSetSizes, 491
MATAIJCUSPARSE, 534 MatSetType, 490
MatAssemblyBegin, 494, 494 MatSetValue, 494
MatAssemblyEnd, 494, 494 MatSetValues, 494
KOKKOS_INLINE_FUNCTION, 557
KOKKOS_LAMBDA, 557
LayoutLeft, 557
LayoutRight, 557
LayoutStride, 557
LayoutTiled, 557
MDRangePolicy, 556
View, 558
671
Chapter 62
offset, 572
queue::memcpy, 568
endl, 571
free, 569
get_access, 570
get_range, 570
host_selector, 562
id<1>, 565
id<nd>, 565
is_cpu, 562
is_gpu, 562
is_host, 562
malloc, 569
malloc_device, 568
malloc_host, 568
malloc_shared, 568
nd_item, 566
672
ISBN 978-1-387-40028-7
90000
9 781387 400287