<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Prerequisites
This notebook contains examples which are expected to be run with exactly 4 MPI processes; not because they wouldn't work otherwise, but simply because it's what their description assumes. For this, you need to
Step1:  In this tutorial, to run commands in parallel over the engines, we will use the %px line magic.
Step2:  Overview of MPI in Devito
Distributed-memory parallelism via MPI is designed so that users can "think sequentially" for as much as possible. The few things requested to the user are
Step3:  An Operator will then generate MPI code, including sends/receives for halo exchanges. Below, we introduce a running example through which we explain how domain decomposition as well as data access (read/write) and distribution work. Performance optimizations are discussed in a later section.
Let's start by creating a TimeFunction.
Step4:  Domain decomposition is performed when creating a Grid. Users may supply their own domain decomposition, but this is not shown in this notebook. Devito exploits the MPI Cartesian topology abstraction to logically split the Grid over the available MPI processes. Since u is defined over a decomposed Grid, its data get distributed too.
Step5:  Globally, u consists of 4x4 points -- this is what users "see". But locally, as shown above, each rank has got a 2x2 subdomain. The key point is
Step6:  The only limitation, currently, is that a data access cannot require a direct data exchange among two or more processes (e.g., the assignment u.data[0, 0] = u.data[3, 3] will raise an exception unless both entries belong to the same MPI rank).
We can finally write out a trivial Operator to try running something.
Step7:  And we can now check again the (distributed) content of our u.data
Step8:  Everything as expected. We could also peek at the generated code, because we may be curious to see what sort of MPI calls Devito has generated...
Step9:  Hang on. There's nothing MPI-specific here! At least apart from the header file #include "mpi.h". What's going on? Well, it's simple. Devito was smart enough to realize that this trivial Operator doesn't even need any sort of halo exchange -- the Eq implements a pure "map computation" (i.e., fully parallel), so it can just let each MPI process do its job without ever synchronizing with halo exchanges. We might want try again with a proper stencil Eq.
Step10:  Uh-oh -- now the generated code looks more complicated than before, though it still is pretty much human-readable. We can spot the following routines
Step11:  This is again a global data view. The shown with_halo is the "true" halo surrounding the physical domain, not the halo used for the MPI halo exchanges (often referred to as "ghost region"). So it gets trivial for a user to initialize the "true" halo region (which is typically read by a stencil Eq when an Operator iterates in proximity of the domain bounday).
Step12:  MPI and SparseFunction
A SparseFunction represents a sparse set of points which are generically unaligned with the Grid. A sparse point could be anywhere within a grid, and is therefore attached some coordinates. Given a sparse point, Devito looks at its coordinates and, based on the domain decomposition, logically assigns it to a given MPI process; this is purely logical ownership, as in Python-land, before running an Operator, the sparse point physically lives on the MPI rank which created it. Within op.apply, right before jumping to C-land, the sparse points are scattered to their logical owners; upon returning to Python-land, the sparse points are gathered back to their original location.
In the following example, we attempt injection of four sparse points into the neighboring grid points via linear interpolation.
Step13:  Let
Step14:  Performance optimizations
The Devito compiler applies several optimizations before generating code.
Redundant halo exchanges are identified and removed. A halo exchange is redundant if a prior halo exchange carries out the same Function update and the data is not “dirty” yet.
Computation/communication overlap, with explicit prodding of the asynchronous progress engine to make sure that non-blocking communications execute in background during the compute part.
Halo exchanges could also be reshuffled to maximize the extension of the computation/communication overlap region.
To run with all these optimizations enabled, instead of DEVITO_MPI=1, users should set DEVITO_MPI=full, or, equivalently
Step15:  We could now peek at the generated code to see that things now look differently.
<ASSISTANT_TASK:>
Python Code:
import ipyparallel as ipp
c = ipp.Client(profile='mpi')
Explanation: Prerequisites
This notebook contains examples which are expected to be run with exactly 4 MPI processes; not because they wouldn't work otherwise, but simply because it's what their description assumes. For this, you need to:
Install an MPI distribution on your system, such as OpenMPI, MPICH, or Intel MPI (if not already available).
Install some optional dependencies, including mpi4py and ipyparallel; from the root Devito directory, run
pip install -r requirements-optional.txt
Create an ipyparallel MPI profile, by running our simple setup script. From the root directory, run
./scripts/create_ipyparallel_mpi_profile.sh
Launch and connect to an ipyparallel cluster
We're finally ready to launch an ipyparallel cluster. Open a new terminal and run the following command
ipcluster start --profile=mpi -n 4
Once the engines have started successfully, we can connect to the cluster
End of explanation
%%px --group-outputs=engine
from mpi4py import MPI
print(f"Hi, I'm rank %d." % MPI.COMM_WORLD.rank)
Explanation: In this tutorial, to run commands in parallel over the engines, we will use the %px line magic.
End of explanation
%%px
from devito import configuration
configuration['mpi'] = True
%%px
# Keep generated code as simple as possible
configuration['language'] = 'C'
# Fix platform so that this notebook can be tested by py.test --nbval
configuration['platform'] = 'knl7210'
Explanation: Overview of MPI in Devito
Distributed-memory parallelism via MPI is designed so that users can "think sequentially" for as much as possible. The few things requested to the user are:
Like any other MPI program, run with mpirun -np X python ...
Some pre- and/or post-processing may be rank-specific (e.g., we may want to plot on a given MPI rank only, even though this might be hidden away in the next Devito releases, when newer support APIs will be provided.
Parallel I/O (if and when necessary) to populate the MPI-distributed datasets in input to a Devito Operator. If a shared file system is available, there are a few simple alternatives to pick from, such as NumPy’s memory-mapped arrays.
To enable MPI, users have two options. Either export the environment variable DEVITO_MPI=1 or, programmatically:
End of explanation
%%px
from devito import Grid, TimeFunction, Eq, Operator 
grid = Grid(shape=(4, 4))
u = TimeFunction(name="u", grid=grid, space_order=2, time_order=0)
Explanation: An Operator will then generate MPI code, including sends/receives for halo exchanges. Below, we introduce a running example through which we explain how domain decomposition as well as data access (read/write) and distribution work. Performance optimizations are discussed in a later section.
Let's start by creating a TimeFunction.
End of explanation
%%px --group-outputs=engine
u.data
Explanation: Domain decomposition is performed when creating a Grid. Users may supply their own domain decomposition, but this is not shown in this notebook. Devito exploits the MPI Cartesian topology abstraction to logically split the Grid over the available MPI processes. Since u is defined over a decomposed Grid, its data get distributed too.
End of explanation
%%px
u.data[0, 1:-1, 1:-1] = 1.
%%px --group-outputs=engine
u.data
Explanation: Globally, u consists of 4x4 points -- this is what users "see". But locally, as shown above, each rank has got a 2x2 subdomain. The key point is: for the user, the fact that u.data is distributed is completely abstracted away -- the perception is that of indexing into a classic NumPy array, regardless of whether MPI is enabled or not. All sort of NumPy indexing schemes (basic, slicing, etc.) are supported. For example, we can write into a slice-generated view of our data.
End of explanation
%%px
op = Operator(Eq(u.forward, u + 1))
summary = op.apply(time_M=0)
Explanation: The only limitation, currently, is that a data access cannot require a direct data exchange among two or more processes (e.g., the assignment u.data[0, 0] = u.data[3, 3] will raise an exception unless both entries belong to the same MPI rank).
We can finally write out a trivial Operator to try running something.
End of explanation
%%px --group-outputs=engine
u.data
Explanation: And we can now check again the (distributed) content of our u.data
End of explanation
%%px --targets 0
print(op)
Explanation: Everything as expected. We could also peek at the generated code, because we may be curious to see what sort of MPI calls Devito has generated...
End of explanation
%%px --targets 0
op = Operator(Eq(u.forward, u.dx + 1))
print(op)
Explanation: Hang on. There's nothing MPI-specific here! At least apart from the header file #include "mpi.h". What's going on? Well, it's simple. Devito was smart enough to realize that this trivial Operator doesn't even need any sort of halo exchange -- the Eq implements a pure "map computation" (i.e., fully parallel), so it can just let each MPI process do its job without ever synchronizing with halo exchanges. We might want try again with a proper stencil Eq.
End of explanation
%%px --group-outputs=engine
u.data_with_halo
Explanation: Uh-oh -- now the generated code looks more complicated than before, though it still is pretty much human-readable. We can spot the following routines:
haloupdate0 performs a blocking halo exchange, relying on three additional functions, gather0, sendrecv0, and scatter0;
gather0 copies the (generally non-contiguous) boundary data into a contiguous buffer;
sendrecv0 takes the buffered data and sends it to one or more neighboring processes; then it waits until all data from the neighboring processes is received;
scatter0 copies the received data into the proper array locations.
This is the simplest halo exchange scheme available in Devito. There are a few, and some of them apply aggressive optimizations, as shown later on.
Before looking at other scenarios and performance optimizations, there is one last thing it is worth discussing -- the data_with_halo view.
End of explanation
%%px
u.data_with_halo[:] = 1.
%%px --group-outputs=engine
u.data_with_halo
Explanation: This is again a global data view. The shown with_halo is the "true" halo surrounding the physical domain, not the halo used for the MPI halo exchanges (often referred to as "ghost region"). So it gets trivial for a user to initialize the "true" halo region (which is typically read by a stencil Eq when an Operator iterates in proximity of the domain bounday).
End of explanation
%%px
from devito import Function, SparseFunction
grid = Grid(shape=(4, 4), extent=(3.0, 3.0))
x, y = grid.dimensions
f = Function(name='f', grid=grid)
coords = [(0.5, 0.5), (1.5, 2.5), (1.5, 1.5), (2.5, 1.5)]
sf = SparseFunction(name='sf', grid=grid, npoint=len(coords), coordinates=coords)
Explanation: MPI and SparseFunction
A SparseFunction represents a sparse set of points which are generically unaligned with the Grid. A sparse point could be anywhere within a grid, and is therefore attached some coordinates. Given a sparse point, Devito looks at its coordinates and, based on the domain decomposition, logically assigns it to a given MPI process; this is purely logical ownership, as in Python-land, before running an Operator, the sparse point physically lives on the MPI rank which created it. Within op.apply, right before jumping to C-land, the sparse points are scattered to their logical owners; upon returning to Python-land, the sparse points are gathered back to their original location.
In the following example, we attempt injection of four sparse points into the neighboring grid points via linear interpolation.
End of explanation
%%px
sf.data[:] = 5.
op = Operator(sf.inject(field=f, expr=sf))
summary = op.apply()
%%px --group-outputs=engine
f.data
Explanation: Let:
* O be a grid point
* x be a halo point
* A, B, C, D be the sparse points
We show the global view, that is what the user "sees".
O --- O --- O --- O
|  A  |     |     |
O --- O --- O --- O
|     |  C  |  B  |
O --- O --- O --- O
|     |  D  |     |
O --- O --- O --- O
And now the local view, that is what the MPI ranks own when jumping to C-land.        
```
Rank 0          Rank 1
O --- O --- x   x --- O --- O
|  A  |     |   |     |     |
O --- O --- x   x --- O --- O
|     |  C  |   |  C  |  B  |
x --- x --- x   x --- x --- x
Rank 2           Rank 3
x --- x --- x   x --- x --- x
|     |  C  |   |  C  |  B  |
O --- O --- x   x --- O --- O
|     |  D  |   |  D  |     |
O --- O --- x   x --- O --- O
```
We observe that the sparse points along the boundary of two or more MPI ranks are duplicated and thus redundantly computed over multiple processes. However, the contributions from these points to the neighboring halo points are naturally ditched, so the final result of the interpolation is as expected. Let's convince ourselves that this is the case. We assign a value of $5$ to each sparse point. Since we are using linear interpolation and all points are placed at the exact center of a grid quadrant, we expect that the contribution of each sparse point to a neighboring grid point will be $5 * 0.25 = 1.25$. Based on the global view above, we eventually expect f to look like as follows:
1.25 --- 1.25 --- 0.00 --- 0.00
|         |        |        |
1.25 --- 2.50 --- 2.50 --- 1.25
|         |        |        |
0.00 --- 2.50 --- 3.75 --- 1.25
|         |        |        |
0.00 --- 1.25 --- 1.25 --- 0.00
Let's check this out.
End of explanation
%%px
configuration['mpi'] = 'full'
Explanation: Performance optimizations
The Devito compiler applies several optimizations before generating code.
Redundant halo exchanges are identified and removed. A halo exchange is redundant if a prior halo exchange carries out the same Function update and the data is not “dirty” yet.
Computation/communication overlap, with explicit prodding of the asynchronous progress engine to make sure that non-blocking communications execute in background during the compute part.
Halo exchanges could also be reshuffled to maximize the extension of the computation/communication overlap region.
To run with all these optimizations enabled, instead of DEVITO_MPI=1, users should set DEVITO_MPI=full, or, equivalently
End of explanation
%%px
op = Operator(Eq(u.forward, u.dx + 1))
# Uncomment below to show code (it's quite verbose)
# print(op)
Explanation: We could now peek at the generated code to see that things now look differently.
End of explanation
<END_TASK>