Base
The Base tutorials cover the core of AMReX: initialization, runtime
parameters, the mesh data structures (Box, BoxArray,
DistributionMapping, Geometry, MultiFab), GPU-portable kernels
with ParallelFor, ghost cells and boundary conditions, reductions, GPU
containers, load balancing, and I/O. They need no optional AMReX
components; ExternalMPI requires MPI, Tiling and StaggeredGrids run in 2D
and 3D only, and the explicit part of SIMD needs -DAMReX_SIMD=ON. Build
only this topic with -DAMReXTutorials_TOPICS=Base
(add -DAMReX_FFT=OFF if FFTW is not installed); see Getting Started.
Start with HelloWorld, MultiFab and HeatEquation, in that order.
HelloWorld
- Level:
★
- Source:
- Key APIs:
amrex::Initialize,amrex::Finalize,amrex::Print,amrex::AllPrint
The smallest AMReX program. amrex::Initialize sets up MPI and the GPU
device; amrex::Finalize releases them. AMReX objects must be destroyed
before Finalize, hence the extra scope. amrex::Print writes from
the I/O rank only, amrex::AllPrint from every rank.
int main (int argc, char* argv[])
{
// Initialize MPI and the GPU device, if enabled.
amrex::Initialize(argc, argv);
{
// amrex::Print only prints on the I/O process (rank 0).
amrex::Print() << "Hello world from AMReX version "
<< amrex::Version() << "\n";
amrex::Print() << " MPI ranks: " << amrex::ParallelDescriptor::NProcs() << "\n"
<< " OpenMP threads: " << amrex::OpenMP::get_max_threads() << "\n"
<< " GPU backend: "
#if defined(AMREX_USE_CUDA)
<< "CUDA"
#elif defined(AMREX_USE_HIP)
<< "HIP"
#elif defined(AMREX_USE_SYCL)
<< "SYCL"
#else
<< "none"
#endif
<< "\n";
// amrex::AllPrint prints on every process.
amrex::AllPrint() << " Rank " << amrex::ParallelDescriptor::MyProc()
<< " says hello\n";
}
amrex::Finalize();
}
Run:
cmake --build build --target Base_HelloWorld -j 8
cd build/Base/HelloWorld
mpiexec -n 2 ./HelloWorld
ParmParse
- Level:
★
- Source:
- Key APIs:
ParmParse::query,get,queryarr,queryAdd,queryWithParser,querytable,query_enum_case_insensitive,AMREX_ENUM,ParmParse::prettyPrintUnusedInputs
Reads runtime parameters from an inputs file and the command line:
scalars, strings, arrays, math expressions, enums, 2D tables, TOML-like
[section] headers, and unused (often misspelled) inputs. Arguments
after the inputs file, e.g. nsteps=200, override the file.
queryreturns whether the name was found and leaves the variable unchanged otherwise;getaborts if the name is missing;queryAddalso stores the default in the database.Expressions without spaces (
dt = 1.0/64) are evaluated byquery; expressions with spaces needqueryWithParser. Unknown symbols are looked up in the database, here with themy_constants.prefix.[physics]starts a table:diffusivity = 0.1below it isphysics.diffusivity.
The inputs file:
nsteps = 100
title = "ParmParse tutorial" # quotes keep the spaces in a string
n_cell = 64 32 16 # an array
# Math expressions without spaces are evaluated by query()/get().
max_grid_size = 2**5 # 32
dt = 1.0/64 # 0.015625
# Unknown symbols in an expression are looked up in the database. The
# ParmParse object is created with "my_constants" as its parser prefix, so
# `L` is found as my_constants.L.
my_constants.L = 2.0
my_constants.pi = 3.141592653589793
dx = L/32 # 0.0625
omega = 2 * pi / L # with spaces: use queryWithParser
# Names of an AMREX_ENUM, matched case-insensitively here.
time_stepper = rk2
# A 2D table: the Butcher matrix of Heun's method.
butcher_a = {{ 0.0, 0.0 }
{ 1.0, 0.0 }}
# TOML-like tables: the entries below are physics.diffusivity, etc.
[physics]
diffusivity = 0.1
gravity = 0.0 -9.81
difusivity = 0.2 # typo: reported as an unused input
[output]
plot_int = 10
Reading an enum, a table, and the entries of a section:
// Enum
auto stepper = TimeStepper::RK2;
pp.query_enum_case_insensitive("time_stepper", stepper);
amrex::Print() << "time_stepper = " << amrex::getEnumNameString(stepper) << "\n";
// 2D table
std::vector<std::vector<double>> butcher_a{{0.0, 0.0}, {1.0, 0.0}};
pp.querytable("butcher_a", butcher_a);
amrex::Print() << "butcher_a =";
for (auto const& row : butcher_a) {
amrex::Print() << " {";
for (double a : row) { amrex::Print() << " " << a; }
amrex::Print() << " }";
}
amrex::Print() << "\n";
// A prefix selects the entries of a [physics] table, i.e., physics.*
amrex::ParmParse pp_phys("physics");
Real diffusivity = 0.1_rt;
found = pp_phys.query("diffusivity", diffusivity);
Run:
cmake --build build --target Base_ParmParse -j 8
cd build/Base/ParmParse
./ParmParse inputs nsteps=200
The output ends with the misspelled physics.difusivity = 0.2 listed as
an unused input.
MultiFab
- Level:
★
- Source:
- Key APIs:
Box,BoxArray::maxSize,DistributionMapping,Geometry,RealBox,MultiFab,ParallelFor(mf, ...),MFIter,TilingIfNotGPU,Array4,FillBoundary,MultiFab::sum/norm0/norm1/norm2,WriteSingleLevelPlotfile
Builds the basic data structures: a Box for the index space of the
domain, a BoxArray that chops it into grids, a DistributionMapping
that assigns grids to MPI ranks, and a Geometry for the physical,
periodic domain. A MultiFab holds data on the grids owned by each rank,
plus ghost cells.
// Box: the index space of the domain, cells 0 to n_cell-1 in each direction.
amrex::Box domain(amrex::IntVect(0), amrex::IntVect(n_cell-1));
// BoxArray: the domain chopped into boxes of at most max_grid_size cells
// in each direction.
amrex::BoxArray ba(domain);
ba.maxSize(max_grid_size);
// DistributionMapping: which MPI rank owns which box.
amrex::DistributionMapping dm(ba);
// Geometry: the physical domain [0,1]^d, periodic in all directions.
amrex::RealBox real_box({AMREX_D_DECL(0.0_rt, 0.0_rt, 0.0_rt)},
{AMREX_D_DECL(1.0_rt, 1.0_rt, 1.0_rt)});
amrex::Geometry geom(domain, real_box, amrex::CoordSys::cartesian,
{AMREX_D_DECL(1, 1, 1)});
The same function is written into two components in two ways.
ParallelFor(mf, ...) with mf.arrays() runs one kernel over all
local boxes; it is the simplest, and on GPUs it is efficient for many small
boxes. An MFIter loop gives one Array4 per box (per tile on CPU,
with TilingIfNotGPU() and OpenMP); use it when work is organized per
box, e.g. with temporary FArrayBoxes or several kernels on the same
box.
auto const& ma = mf.arrays();
amrex::ParallelFor(mf, [=] AMREX_GPU_DEVICE (int b, int i, int j, int k)
{
ma[b](i,j,k,0) = phi_value(amrex::IntVect(AMREX_D_DECL(i,j,k)), prob_lo, dx);
});
for (amrex::MFIter mfi(mf, amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
amrex::Box const& bx = mfi.tilebox();
amrex::Array4<Real> const& a = mf.array(mfi);
amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE (int i, int j, int k)
{
a(i,j,k,1) = phi_value(amrex::IntVect(AMREX_D_DECL(i,j,k)), prob_lo, dx);
});
}
// Fill ghost cells from neighboring boxes, including periodic images.
mf.FillBoundary(geom.periodicity());
The MFIter loop is preceded by #pragma omp parallel if
(amrex::Gpu::notInLaunchRegion()) so that tiles are distributed over
OpenMP threads in CPU builds. FillBoundary fills ghost cells from
neighboring boxes and periodic images; Communication covers it
and the other communication functions in more detail. The program then
checks valid and ghost cells against the exact function and writes the
plotfile plt_multifab.
Run:
cmake --build build --target Base_MultiFab -j 8
cd build/Base/MultiFab
mpiexec -n 2 ./MultiFab inputs
HeatEquation
- Level:
★
- Source:
- Key APIs:
MultiFab,Geometry,FillBoundary,ParallelFor(mf, ...),const_arrays,WriteSingleLevelPlotfile
Solves \(\partial\phi/\partial t = D\nabla^2\phi\) with forward Euler on the periodic unit domain. The initial condition is \(\phi = 1 + \prod_d \sin(2\pi x_d)\); its sine mode decays as \(\exp(-4\pi^2 d D t)\) in \(d\) dimensions, and the program compares the result with this exact solution. The time step is \(\Delta t = \mathrm{cfl}\,\Delta x^2/(2 d D)\).
Each step fills the ghost cells and applies the standard second-order Laplacian:
// Fill ghost cells, here all from periodic images and neighbors.
phi_old.FillBoundary(geom.periodicity());
// phi_new = phi_old + dt * D * Laplacian(phi_old)
auto const& pold = phi_old.const_arrays();
auto const& pnew = phi_new.arrays();
Real const fac = dt_step * diffusion_coef;
amrex::ParallelFor(phi_new, [=] AMREX_GPU_DEVICE (int b, int i, int j, int k)
{
auto const& po = pold[b];
pnew[b](i,j,k) = po(i,j,k) + fac * (
AMREX_D_TERM((po(i+1,j,k) - 2.0_rt*po(i,j,k) + po(i-1,j,k)) * dxinv[0]*dxinv[0],
+ (po(i,j+1,k) - 2.0_rt*po(i,j,k) + po(i,j-1,k)) * dxinv[1]*dxinv[1],
+ (po(i,j,k+1) - 2.0_rt*po(i,j,k) + po(i,j,k-1)) * dxinv[2]*dxinv[2]));
});
Run:
cmake --build build --target Base_HeatEquation -j 8
cd build/Base/HeatEquation
mpiexec -n 2 ./HeatEquation inputs
Add plot_int=10 to write a plotfile every 10 steps, and e.g.
n_cell=128 stop_time=0.05 for a larger run. To see where the time goes,
build with TinyProfiler; see Profiling with TinyProfiler.
Tiling
- Level:
★★
- Source:
- Key APIs:
MFIter(mf, tile_size),TilingIfNotGPU,MFIter::tilebox,MFIter::validbox,MFIter::fabbox,MFIter::growntilebox,MFIter::nodaltilebox,MFIter::index,MFIter::LocalTileIndex,HostDevice::Atomic::Add,fabarray.mfiter_tile_size
The boxes an MFIter loop works on, and the bugs that come from picking
the wrong one. On CPU, an MFIter constructed with tiling splits each
box of a rank into tiles, and the loop body runs once per tile, in
parallel with OpenMP. tilebox() is the current tile, validbox()
the whole box the tile belongs to, and fabbox() the box with its ghost
cells. The tiles of a box do not overlap and together cover the valid box,
so tilebox() is the box for almost all kernels. growntilebox() adds
the ghost cells on the sides of the tile that lie on the boundary of the
box, so the grown tiles do not overlap either and together cover the ghost
cells; nodaltilebox(d) gives the faces of the tile in direction d,
each face belonging to one tile. validbox() is for a loop without
tiling, for work that concerns the whole box, such as per-box costs for
load balancing.
The program prints these boxes for one box of 16 cells, then counts how
many times each cell is written for several choices of the box of an
iteration. The adds are atomic so that the counts are exact where tiles
overlap; without the atomics, the overlaps are data races with OpenMP.
The loop for tilebox(), the others differ only in the box:
// Correct: each tile does its own cells.
visits.setVal(0);
#ifdef AMREX_USE_OMP
#pragma omp parallel if (amrex::Gpu::notInLaunchRegion())
#endif
for (amrex::MFIter mfi(visits, tile_size); mfi.isValid(); ++mfi) {
amrex::Box const& bx = mfi.tilebox();
auto const& a = visits.array(mfi);
amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE (int i, int j, int k)
{
amrex::HostDevice::Atomic::Add(&a(i,j,k), 1);
});
}
With tilebox() every valid cell is written once. With validbox()
in a tiled loop, every tile does the whole box: the work is multiplied by
the number of tiles, a kernel that accumulates gives a wrong answer, and
with OpenMP several threads write the same cells at the same time
(FArrayBox operations such as fab.setVal inside a tiled loop are
the same bug, since they act on the whole box by default). A tile box
grown by hand, grow(tilebox(), 1), overlaps the neighboring tiles,
where growntilebox() does not. Converting the tile box by hand with
surroundingNodes(tilebox(), d) gives the face between two tiles to
both, where nodaltilebox(d) does not. The opposite mistake,
tilebox() in per-box bookkeeping, records one tile per box instead of
the box; such work belongs in a loop without tiling, with validbox(),
as in LoadBalance.
MFIter mfi(mf, TilingIfNotGPU()) is the usual form: TilingIfNotGPU()
is true on CPU and false on GPU, where a box is already split among the
GPU threads and tiling would only make the kernels smaller. The tile size
is the runtime parameter fabarray.mfiter_tile_size, by default
1024000 8 8 in 3D on CPU builds, so tiles are not split in x and
the inner loop stays long for vectorization, and no splitting in 2D or
on GPU builds. The demonstrations pass the tile size to the MFIter
explicitly so that they show tiles in 2D and on GPU builds too. The last
part times a Laplacian with and without tiling, with the timers
laplacian_tiled and laplacian_untiled (see Profiling with TinyProfiler).
Run:
cmake --build build --target Base_Tiling -j 8
cd build/Base/Tiling
mpiexec -n 2 ./Tiling inputs
With OpenMP (-DAMReX_OMP=ON), set OMP_NUM_THREADS to see the tiles
shared among threads. For timings, build with TinyProfiler and use a
larger problem, e.g. n_cell=256 max_grid_size=128 nrepeat=20.
Communication
- Level:
★★
- Source:
- Key APIs:
FillBoundary,FillBoundary_nowait,FillBoundary_finish,ParallelCopy,ParallelAdd,SumBoundary,Geometry::periodicity
The three basic ways to exchange MultiFab data between boxes and MPI
ranks. Each valid cell holds a unique number, so every result is compared
exactly with a reference MultiFab; the program checks the full
FillBoundary and SumBoundary results.
FillBoundary copies valid data into the ghost cells of neighboring
boxes, and with geom.periodicity() also across periodic boundaries. It
can fill fewer ghost cells than the MultiFab has. The non-blocking
version returns after starting the communication, so that work that does
not need the ghost cells can be done before FillBoundary_finish:
a.FillBoundary_nowait(geom.periodicity());
// A BoxArray shifted by n_cell/4 and chopped differently, so that it
// partly lies outside the domain, with its own DistributionMapping.
amrex::BoxArray ba_dst(amrex::shift(domain, amrex::IntVect(n_cell/4)));
ba_dst.maxSize(dst_max_grid_size);
amrex::DistributionMapping dm_dst(ba_dst);
amrex::MultiFab dst(ba_dst, dm_dst, 1, 1);
dst.setVal(-1.0_rt);
a.FillBoundary_finish();
ParallelCopy copies data between MultiFabs with different
BoxArrays and DistributionMappings, e.g. after regridding.
The number of ghost cells of the source and the destination can be given,
here 0 and 1. The destination BoxArray above is shifted and partly
outside the domain; with geom.periodicity(), those cells are filled from
their periodic images. ParallelAdd adds instead of copying:
dst.ParallelCopy(a, 0, 0, 1, amrex::IntVect(0), amrex::IntVect(1), geom.periodicity());
amrex::MultiFab ref_dst(ba_dst, dm_dst, 1, 1);
auto const& rda = ref_dst.arrays();
amrex::ParallelFor(ref_dst, ref_dst.nGrowVect(), [=] AMREX_GPU_DEVICE (int b, int i, int j, int k)
{
rda[b](i,j,k) = cell_id(i,j,k,n);
});
amrex::MultiFab err_dst(ba_dst, dm_dst, 1, 1);
amrex::MultiFab::Copy(err_dst, dst, 0, 0, 1, 1);
amrex::MultiFab::Subtract(err_dst, ref_dst, 0, 0, 1, 1);
amrex::Print() << "ParallelCopy: max error = " << err_dst.norm0(0, 1) << "\n";
// ParallelAdd adds instead of copying, so dst is now 2*cell_id.
dst.ParallelAdd(a, 0, 0, 1, amrex::IntVect(0), amrex::IntVect(1), geom.periodicity());
SumBoundary is the reverse of FillBoundary: values in ghost cells
are added to the valid cells they overlap, as in deposition, e.g. of
particles near a box boundary. Here every valid cell deposits 1 into the
\(3^d\) cells around it, itself included, some of them ghost cells,
and after SumBoundary every valid cell holds \(3^d\). The ghost
cells are not updated; call FillBoundary afterwards if they are needed.
Run:
cmake --build build --target Base_Communication -j 8
cd build/Base/Communication
mpiexec -n 2 ./Communication inputs
BoundaryConditions
- Level:
★★
- Source:
- Key APIs:
BCRec,BCType::ext_dir/foextrap/reflect_even/int_dir,PhysBCFunct,GpuBndryFuncFab,FillBoundary,MFIter,ParallelFor(box, [=] (IntVect const&) ...)
Solves the heat equation on a non-periodic domain: Dirichlet values at \(x = 0\) and \(x = 1\), zero gradient in \(y\), periodic in \(z\). The solution \(\phi = \phi_{lo} + (\phi_{hi} - \phi_{lo})x + e^{-\pi^2 D t}\sin(\pi x)\) relaxes to the linear steady state and is checked against this exact solution.
Boundary conditions are given per component as a BCRec. Periodic
directions use int_dir and must match the Geometry.
amrex::Vector<amrex::BCRec> bcs(1);
bcs[0].setLo(0, amrex::BCType::ext_dir);
bcs[0].setHi(0, amrex::BCType::ext_dir);
#if (AMREX_SPACEDIM >= 2)
bcs[0].setLo(1, amrex::BCType::reflect_even);
bcs[0].setHi(1, amrex::BCType::foextrap);
#endif
#if (AMREX_SPACEDIM == 3)
bcs[0].setLo(2, amrex::BCType::int_dir);
bcs[0].setHi(2, amrex::BCType::int_dir);
#endif
// z periodic, must match the BCRec
amrex::Array<int,AMREX_SPACEDIM> is_periodic{AMREX_D_DECL(0, 0, 1)};
Ghost cells are filled in two steps. FillBoundary fills those that
overlap other boxes, including periodic images. PhysBCFunct fills those
outside the domain: AMReX handles foextrap, reflect_even,
reflect_odd and hoextrap, and calls the user functor for every such
cell to set the ext_dir values.
struct DirichletFill
{
amrex::GpuArray<Real,AMREX_SPACEDIM> phi_lo;
amrex::GpuArray<Real,AMREX_SPACEDIM> phi_hi;
AMREX_GPU_DEVICE
void operator() (amrex::IntVect const& iv, amrex::Array4<Real> const& dest,
int dcomp, int numcomp, amrex::GeometryData const& geom,
Real /*time*/, amrex::BCRec const* bcr, int bcomp,
int /*orig_comp*/) const
{
amrex::Box const& domain = geom.Domain();
for (int n = 0; n < numcomp; ++n) {
amrex::BCRec const& bc = bcr[bcomp+n];
for (int d = 0; d < AMREX_SPACEDIM; ++d) {
if (bc.lo(d) == amrex::BCType::ext_dir && iv[d] < domain.smallEnd(d)) {
dest(iv, dcomp+n) = phi_lo[d];
} else if (bc.hi(d) == amrex::BCType::ext_dir && iv[d] > domain.bigEnd(d)) {
dest(iv, dcomp+n) = phi_hi[d];
}
}
}
}
};
DirichletFill dirichlet_fill{};
dirichlet_fill.phi_lo[0] = phi_lo;
dirichlet_fill.phi_hi[0] = phi_hi;
amrex::PhysBCFunct<amrex::GpuBndryFuncFab<DirichletFill>> physbc
(geom, bcs, amrex::GpuBndryFuncFab<DirichletFill>(dirichlet_fill));
phi_old.FillBoundary(geom.periodicity());
physbc(phi_old, 0, 1, phi_old.nGrowVect(), time, 0);
For ext_dir, the ghost cell holds the value on the boundary face, so the
Laplacian uses a half-cell distance next to that boundary.
Run:
cmake --build build --target Base_BoundaryConditions -j 8
cd build/Base/BoundaryConditions
mpiexec -n 2 ./BoundaryConditions inputs
Try phi_lo=2 phi_hi=-1, or stop_time=0.5 plot_int=100 to follow
the approach to the steady state.
StaggeredGrids
- Level:
★★
- Source:
- Key APIs:
convert,IntVect::TheDimensionVector,IntVect::TheNodeVector,IndexType,MultiFab::ixType,MFIter::nodaltilebox,ParallelFor(box1, box2, box3, f1, f2, f3),OverrideSync,computeDivergence,average_face_to_cellcenter,average_cellcenter_to_face,average_node_to_cellcenter,GetArrOfPtrs,GetArrOfConstPtrs,MultiFab::Subtract,MultiFab::norm0
Data on cell centers, faces and nodes of the same grids. The BoxArray
of a MultiFab carries the index type, and convert turns the
cell-centered BoxArray into one of face-centered boxes (one more point
than cells in that direction) or node-centered boxes:
amrex::MultiFab phi(ba, dm, 1, 1);
amrex::Array<amrex::MultiFab,AMREX_SPACEDIM> umac;
for (int d = 0; d < AMREX_SPACEDIM; ++d) {
umac[d].define(amrex::convert(ba, amrex::IntVect::TheDimensionVector(d)), dm, 1, 0);
}
amrex::MultiFab psi(amrex::convert(ba, amrex::IntVect::TheNodeVector()), dm, 1, 0);
A node at index i sits at i*dx and a cell center at
(i+1/2)*dx, so the position of a point depends on ixType(). The
program sets a velocity on the faces, as a MAC projection or a
finite-volume flux needs it. In an MFIter loop over the cell-centered
data, mfi.nodaltilebox(d) is the box of the tile’s faces in direction
d; the face boxes of different tiles do not overlap, so the faces can
be written in the same loop as the cells, and ParallelFor takes one
box and one function per direction in a single launch, here a lambda
that sets one velocity component:
for (amrex::MFIter mfi(phi, amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) {
AMREX_D_TERM(amrex::Array4<Real> const& u0 = umac[0].array(mfi);,
amrex::Array4<Real> const& u1 = umac[1].array(mfi);,
amrex::Array4<Real> const& u2 = umac[2].array(mfi););
amrex::ParallelFor(AMREX_D_DECL(mfi.nodaltilebox(0), mfi.nodaltilebox(1), mfi.nodaltilebox(2)),
AMREX_D_DECL(
[=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
{
amrex::IndexType const xface(amrex::IntVect::TheDimensionVector(0));
u0(i,j,k) = shear(0, position(i, j, k, xface, plo, dx));
},
[=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
{
amrex::IndexType const yface(amrex::IntVect::TheDimensionVector(1));
u1(i,j,k) = shear(1, position(i, j, k, yface, plo, dx));
},
[=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
{
amrex::IndexType const zface(amrex::IntVect::TheDimensionVector(2));
u2(i,j,k) = shear(2, position(i, j, k, zface, plo, dx));
}));
}
A face on the boundary between two boxes is stored in both boxes, and
OverrideSync copies the value of one box to the others so that the
copies agree. The example does not need it, because the value depends only
on the index, but it is needed when the boxes compute different values,
for instance from round-off in a sum:
for (amrex::MFIter mfi(phi, amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) {
AMREX_D_TERM(amrex::Array4<Real> const& u0 = umac[0].array(mfi);,
amrex::Array4<Real> const& u1 = umac[1].array(mfi);,
amrex::Array4<Real> const& u2 = umac[2].array(mfi););
amrex::ParallelFor(AMREX_D_DECL(mfi.nodaltilebox(0), mfi.nodaltilebox(1), mfi.nodaltilebox(2)),
AMREX_D_DECL(
[=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
{
amrex::IndexType const xface(amrex::IntVect::TheDimensionVector(0));
u0(i,j,k) = shear(0, position(i, j, k, xface, plo, dx));
},
[=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
{
amrex::IndexType const yface(amrex::IntVect::TheDimensionVector(1));
u1(i,j,k) = shear(1, position(i, j, k, yface, plo, dx));
},
[=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
{
amrex::IndexType const zface(amrex::IntVect::TheDimensionVector(2));
u2(i,j,k) = shear(2, position(i, j, k, zface, plo, dx));
}));
}
// A face on a box boundary is stored in both boxes. OverrideSync makes
// the copies agree; not needed here, the value depends only on the index.
// FillBoundaryAndSync does this and fills ghost faces in one call.
for (int d = 0; d < AMREX_SPACEDIM; ++d) {
umac[d].OverrideSync(geom.periodicity());
}
Face data can have ghost faces, filled by FillBoundary like ghost
cells, and FillBoundaryAndSync does that and OverrideSync in one
call. The utilities below read valid faces only, so the example has no
ghost faces. The face-based utilities take an
Array<MultiFab*,AMREX_SPACEDIM> (GetArrOfPtrs,
GetArrOfConstPtrs): computeDivergence of the face velocity is
cell-centered, average_face_to_cellcenter gives the velocity at cell
centers, average_cellcenter_to_face the scalar on the faces, and
average_node_to_cellcenter moves nodal data to cell centers. Plotfile
viewers usually expect cell-centered data, so face and nodal data are
written to the plotfile after averaging. The discrete divergence of the
shear flow is exactly zero, and the averages reproduce linear functions to
round-off.
Run:
cmake --build build --target Base_StaggeredGrids -j 8
cd build/Base/StaggeredGrids
mpiexec -n 2 ./StaggeredGrids inputs
CheckpointRestart
- Level:
★★
- Source:
- Key APIs:
PreBuildDirectorHierarchy,MultiFabFileFullPrefix,VisMF::Write,VisMF::Read,BoxArray::writeOn/readFrom,ParallelDescriptor::ReadAndBcastFile,PlotFileData,ParallelCopy
Writes checkpoints of a heat equation run and restarts from them. A
checkpoint is a directory with a Header (step, time and BoxArray),
written by the I/O rank, and the MultiFab data, written by every rank
with VisMF.
void WriteCheckpoint (std::string const& name, int step, Real time, amrex::MultiFab const& phi)
{
// Create name/ and name/Level_0/ (on the I/O rank, then barrier).
amrex::PreBuildDirectorHierarchy(name, "Level_", 1, true);
if (amrex::ParallelDescriptor::IOProcessor()) {
std::ofstream header(name + "/Header");
if (!header.good()) { amrex::FileOpenFailed(name + "/Header"); }
header.precision(17);
header << "CheckpointRestart checkpoint\n" << step << "\n" << time << "\n";
phi.boxArray().writeOn(header);
header << "\n";
}
// Every rank writes the data it owns.
amrex::VisMF::Write(phi, amrex::MultiFabFileFullPrefix(0, name, "Level_", "phi"));
}
On restart, the BoxArray comes from the checkpoint and a new
DistributionMapping is made, so a run may restart on a different number
of MPI ranks.
void ReadCheckpoint (std::string const& name, int& step, Real& time, amrex::MultiFab& phi,
int nghost)
{
// Rank 0 reads the header and broadcasts it.
amrex::Vector<char> buffer;
amrex::ParallelDescriptor::ReadAndBcastFile(name + "/Header", buffer);
std::istringstream is(buffer.dataPtr());
std::string title;
std::getline(is, title);
is >> step >> time;
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
amrex::BoxArray ba;
ba.readFrom(is);
// A new DistributionMapping; the run may use a different number of ranks.
amrex::DistributionMapping dm(ba);
phi.define(ba, dm, 1, nghost);
amrex::VisMF::Read(phi, amrex::MultiFabFileFullPrefix(0, name, "Level_", "phi"));
}
With test_restart=1, the program restarts from the first checkpoint,
reruns the remaining steps, and checks that the result is bitwise identical
to the uninterrupted run. It also reads the final plotfile back with
PlotFileData; the data come with their own DistributionMapping, so
ParallelCopy moves them into the layout of another MultiFab.
amrex::PlotFileData pf(plotfile);
amrex::MultiFab phi_pf(phi.boxArray(), phi.DistributionMap(), 1, 0);
phi_pf.ParallelCopy(pf.get(0)); // all variables of level 0, here only "phi"
Run:
cmake --build build --target Base_CheckpointRestart -j 8
cd build/Base/CheckpointRestart
mpiexec -n 2 ./CheckpointRestart inputs
mpiexec -n 1 ./CheckpointRestart inputs restart=chk00010
mpiexec -n 2 ./CheckpointRestart inputs test_restart=1
Reductions
- Level:
★★
- Source:
- Key APIs:
ParReduce,ReduceOps,ReduceData,Reducer,ReduceOpSum/Min/Max,MultiFab::sum/min/max/norm0/norm1/norm2,Reduce::Sum,ParallelAllReduce,ParallelDescriptor::ReduceRealSum
Computes sums, minima, maxima and counts over a MultiFab and a device
vector, on CPU and GPU, and combines them across MPI ranks. The data,
\(\phi = i + j + k\), has a simple exact sum and maximum; the program
prints them next to the computed values and checks the two sums.
MultiFabmember functions (sum,norm0, …) compute common norms and already include the MPI reduction.ParReducecomputes several custom reductions over aMultiFabin one pass.ReduceOps/ReduceData, or the more compactReducer, work insideMFIterloops or over arbitrary boxes and index ranges.Reduce::Sum/Min/Maxreduce a plain array, e.g. aGpu::DeviceVector.
All except the MultiFab member functions are local to the MPI rank and
are followed by ParallelAllReduce or ParallelDescriptor::Reduce*.
ParReduce with a sum, a minimum and a maximum, followed by the MPI
reductions:
auto const& a = mf.const_arrays();
auto r = amrex::ParReduce(
amrex::TypeList<amrex::ReduceOpSum, amrex::ReduceOpMin, amrex::ReduceOpMax>{},
amrex::TypeList<Real, Real, Real>{},
mf, amrex::IntVect(0),
[=] AMREX_GPU_DEVICE (int b, int i, int j, int k)
-> amrex::GpuTuple<Real, Real, Real>
{
Real v = a[b](i,j,k);
return {v, v, v};
});
Real sum = amrex::get<0>(r);
Real vmin = amrex::get<1>(r);
Real vmax = amrex::get<2>(r);
amrex::ParallelAllReduce::Sum(sum, amrex::ParallelDescriptor::Communicator());
amrex::ParallelAllReduce::Min(vmin, amrex::ParallelDescriptor::Communicator());
amrex::ParallelAllReduce::Max(vmax, amrex::ParallelDescriptor::Communicator());
Reducer with two sums of different types:
amrex::Reducer<amrex::TypeList<amrex::ReduceOpSum, amrex::ReduceOpSum>,
amrex::TypeList<Real, Long>> reducer;
using Result_t = decltype(reducer)::Result_t;
auto const& a = mf.const_arrays();
reducer.eval(mf, amrex::IntVect(0),
[=] AMREX_GPU_DEVICE (int b, int i, int j, int k) -> Result_t
{
Real v = a[b](i,j,k);
Long even = (Long(v) % 2 == 0) ? 1 : 0;
return {v*v, even};
});
Result_t r = reducer.getResult();
Run:
cmake --build build --target Base_Reductions -j 8
cd build/Base/Reductions
mpiexec -n 2 ./Reductions inputs
GpuContainers
- Level:
★★
- Source:
- Key APIs:
Gpu::DeviceVector,Gpu::PinnedVector,Gpu::copyAsync,Gpu::streamSynchronize,ParallelForRNG,amrex::Random,Scan::PrefixSum,Scan::ExclusiveSum,The_Arena,The_Async_Arena,The_Pinned_Arena
Fills a Gpu::DeviceVector with random numbers, keeps the values above a
threshold with a prefix-sum based stream compaction, copies the results to
pinned host memory, and checks them against the same operations on the
host. The code is the same for CPU and GPU builds.
Scan::PrefixSum takes one function that produces each input and one
that consumes each partial sum, so the compaction needs no temporary
arrays:
// Uniform random numbers in [0,1); each GPU thread gets its own engine.
amrex::ParallelForRNG(n, [=] AMREX_GPU_DEVICE (int i, amrex::RandomEngine const& engine)
{
pv[i] = amrex::Random(engine);
});
// Stream compaction: keep the values above threshold, in order. The
// exclusive prefix sum of the keep flags is each kept value's output
// position, and the total is the number of kept values.
amrex::Gpu::DeviceVector<Real> kept(n);
Real* pk = kept.data();
int const nkept = amrex::Scan::PrefixSum<int>(n,
[=] AMREX_GPU_DEVICE (int i) -> int { return pv[i] > threshold; },
[=] AMREX_GPU_DEVICE (int i, int const& pos) {
if (pv[i] > threshold) { pk[pos] = pv[i]; }
},
amrex::Scan::Type::exclusive, amrex::Scan::retSum);
kept.resize(nkept);
DeviceVector memory comes from The_Arena() (device memory on GPU),
and PinnedVector from The_Pinned_Arena() (page-locked host memory,
needed for truly asynchronous copies).
copyAsync may return before the copy is done, so synchronize the stream
before using the data:
// Copy to the host. Pinned (page-locked) host memory, from
// The_Pinned_Arena(), makes asynchronous copies fast. The copy is
// asynchronous on GPU, so wait for the stream before using the data.
amrex::Gpu::PinnedVector<Real> h_values(n);
amrex::Gpu::PinnedVector<Real> h_kept(nkept);
amrex::Gpu::copyAsync(amrex::Gpu::deviceToHost, values.begin(), values.end(), h_values.begin());
amrex::Gpu::copyAsync(amrex::Gpu::deviceToHost, kept.begin(), kept.end(), h_kept.begin());
amrex::Gpu::streamSynchronize();
The_Async_Arena() is for temporaries: on GPU, memory freed there is
reused only after the work already queued on the stream is done.
Run:
cmake --build build --target Base_GpuContainers -j 8
cd build/Base/GpuContainers
./GpuContainers inputs
LoadBalance
- Level:
★★
- Source:
- Key APIs:
DistributionMapping::makeKnapSack,DistributionMapping::makeSFC,LayoutData,ParallelCopy,amrex::second,ParallelAllReduce
Rebalances the work over MPI ranks when boxes cost different amounts. The
default DistributionMapping gives every rank about the same number of
cells,
which is right when every cell costs the same. Here the cells inside a
ball do work_ratio times more work than the others, so the ranks
holding the
ball are late at every synchronization point.
The time each box takes is accumulated in a LayoutData<Real>, which is
indexed like a MultiFab in an MFIter loop. The timers need
Gpu::streamSynchronize(), because kernels run asynchronously on GPUs.
Any other measure of work can be used instead, e.g. the number of
particles in a box.
void run_and_time (amrex::MultiFab const& in, amrex::MultiFab& out,
amrex::LayoutData<Real>& cost,
amrex::GpuArray<Real,AMREX_SPACEDIM> const& dx, Real radius, int work_ratio)
{
#ifdef AMREX_USE_OMP
#pragma omp parallel if (amrex::Gpu::notInLaunchRegion())
#endif
for (amrex::MFIter mfi(in); mfi.isValid(); ++mfi) { // no tiling: one timer per box
amrex::Box const& bx = mfi.validbox();
auto const& a = in.const_array(mfi);
auto const& b = out.array(mfi);
Real const t0 = amrex::second();
amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE (int i, int j, int k)
{
amrex::IntVect const iv(AMREX_D_DECL(i,j,k));
Real r2 = 0.0_rt;
for (int d = 0; d < AMREX_SPACEDIM; ++d) {
Real const x = (iv[d] + 0.5_rt) * dx[d] - 0.25_rt;
r2 += x*x;
}
int const niter = (r2 < radius*radius) ? work_ratio : 1;
Real v = a(i,j,k);
for (int it = 0; it < niter; ++it) {
v = 4.0_rt * v * (1.0_rt - v); // logistic map, stays in [0,1]
}
b(i,j,k) = v;
});
amrex::Gpu::streamSynchronize();
cost[mfi] += amrex::second() - t0;
}
}
makeKnapSack and makeSFC build a new mapping from the costs and
return, on the I/O rank, the efficiency (average cost per rank over the
maximum) of the current and of the proposed mapping. The knapsack
algorithm balances best; the space-filling curve keeps neighboring boxes
on the same rank, which reduces communication. A new MultiFab on the
new mapping receives the data with ParallelCopy:
Real eff_cur = 0.0_rt;
Real eff_new = 0.0_rt;
amrex::DistributionMapping dm_new;
if (strategy == Strategy::knapsack) {
dm_new = amrex::DistributionMapping::makeKnapSack(cost, eff_cur, eff_new);
} else {
dm_new = amrex::DistributionMapping::makeSFC(cost, eff_cur, eff_new);
}
amrex::Print() << "Efficiency of the default mapping " << eff_cur << ", of the "
<< amrex::getEnumNameString(strategy) << " mapping " << eff_new << "\n";
// 3. Move the data to the new mapping and measure again.
amrex::MultiFab phi_new(ba, dm_new, 1, 0);
phi_new.ParallelCopy(phi);
The program measures again with the new mapping and checks that the
result does not depend on the mapping. In an application, the costs are
accumulated over some steps and the mapping redone every so often or after
regridding; with broadcastToAll = false only the I/O rank gets the
proposal, so the code can decide whether the gain is worth moving the
data. A code built on AmrCore calls SetDistributionMap and
RemakeLevel (AdvectionAmrCore shows RemakeLevel);
Amr/AmrLevel
codes override AmrLevel::estimateWork and set
amr.loadbalance_with_workestimates = 1, which rebalances at every
regrid, and on a single-level run every amr.loadbalance_level0_int
steps.
Run:
cmake --build build --target Base_LoadBalance -j 8
cd build/Base/LoadBalance
mpiexec -n 2 ./LoadBalance inputs
512 boxes on 2 ranks
Default mapping: max/avg cost per rank = 1.20104519
Efficiency of the default mapping 0.8326081387, of the knapsack mapping 0.9987378103
New mapping: max/avg cost per rank = 1.00074445
Max difference between the results: 0
PASSED
Try strategy=sfc and more ranks. On a GPU, the time of a kernel on a
small box is mostly launch overhead, so the costs only differ for large
boxes and heavy kernels, e.g. n_cell=256 max_grid_size=64
work_ratio=5000.
Parser
- Level:
★★
- Source:
- Key APIs:
Parser,IParser,setConstant,registerVariables,compile<N>,ParmParse::makeParser
Evaluates functions given as strings at runtime, here an initial condition
and a tagging criterion from the inputs file, inside GPU kernels.
amrex::Parser handles floating-point expressions and amrex::IParser
integer ones. Expressions support + - * / ^ **, comparisons, and,
or, if(cond, a, b), min, max and the usual math functions;
IParser also has floor division //.
A parser is built on the host: set the constants, register the variables in
the order they will be passed, and compile<N>() with N variables.
ParmParse::makeParser instead resolves unknown symbols from the
ParmParse database.
// 1. Parser built by hand: set the constants, then the variables in
// the order they are passed to the compiled executor.
amrex::Parser parser(function);
parser.setConstant("pi", amrex::Math::pi<double>());
parser.setConstant("A", A);
parser.registerVariables({"x", "y", "z", "t"});
auto const f1 = parser.compile<4>(); // usable on host and device
// 2. ParmParse::makeParser looks up unknown symbols in the database,
// here with the "my_constants" prefix.
amrex::ParmParse pp("", "my_constants");
amrex::Parser parser2 = pp.makeParser(function, {"x", "y", "z", "t"});
auto const f2 = parser2.compile<4>();
// 3. IParser for integer expressions, here of cell indices.
amrex::IParser iparser(tag);
iparser.setConstant("n", n_cell);
iparser.registerVariables({"i", "j", "k"});
auto const ftag = iparser.compile<3>();
The returned executor is a small object captured by value in device
lambdas; the Parser must stay alive while it is used.
amrex::ParallelFor(phi, [=] AMREX_GPU_DEVICE (int b, int i, int j, int k)
{
amrex::IntVect const iv(AMREX_D_DECL(i,j,k));
amrex::GpuArray<Real,3> x{0.0_rt, 0.0_rt, 0.0_rt}; // y = z = 0 in lower dimensions
for (int d = 0; d < AMREX_SPACEDIM; ++d) {
x[d] = prob_lo[d] + (iv[d] + 0.5_rt) * dx[d];
}
pa[b](i,j,k) = Real(f1(x[0], x[1], x[2], time));
pa2[b](i,j,k) = Real(f2(x[0], x[1], x[2], time));
ta[b](i,j,k) = int(ftag(i, j, k));
Run:
cmake --build build --target Base_Parser -j 8
cd build/Base/Parser
./Parser inputs
./Parser inputs ic.function="x*y*exp(-t)"
CompileTimeOptions
- Level:
★★★
- Source:
- Key APIs:
ParallelFor(TypeList<CompileTimeOptions<...>...>, {...}, box, f),CompileTimeOptions,if constexpr,AMREX_ENUM,BL_PROFILE
Turns runtime options into compile-time constants inside kernels. A kernel
with two runtime options, the order of a Laplacian stencil and whether to
add an absorption term, is written once with runtime branches and once with
CompileTimeOptions. AMReX compiles a specialized kernel for every
combination and launches the one that matches the runtime values. The
program checks that both versions agree and times them with BL_PROFILE
(see Profiling with TinyProfiler).
amrex::ParallelFor(
amrex::TypeList<amrex::CompileTimeOptions<int(Order::second), int(Order::fourth)>,
amrex::CompileTimeOptions<0, 1>>{},
{int(order), int(absorption)},
bx, [=] AMREX_GPU_DEVICE (int i, int j, int k, auto order_ct, auto absorption_ct)
{
amrex::IntVect const iv(AMREX_D_DECL(i,j,k));
constexpr int ord = (order_ct.value == int(Order::second)) ? 2 : 4;
Real r = laplacian<ord>(iv, p, dxinv);
// A plain `if` on a compile-time constant is optimized out
// too. (nvcc does not allow `if constexpr` blocks to be
// the first to use a captured variable, here sigma.)
if (absorption_ct.value) { r -= sigma * p(iv); }
out(i,j,k) = r;
});
The kernel receives one extra argument per option, of type
std::integral_constant<int, value>, so opt.value can be used in
if constexpr and as a template argument. Specialized kernels can drop
unused code and use fewer registers, which matters most for large GPU
kernels; the cost is compile time and binary size, which grow with the
number of combinations. AnyCTO does the same for other launch functions
such as ParallelForRNG.
Run:
cmake --build build --target Base_CompileTimeOptions -j 8
cd build/Base/CompileTimeOptions
./CompileTimeOptions inputs
For timings, build with TinyProfiler on and use e.g. n_cell=256
nrepeat=20 max_grid_size=128 and an optimized GPU build.
TagParallelFor
- Level:
★★★
- Source:
- Key APIs:
ParallelFor(Vector<Tag>, ncomp, f),ParallelFor(TagVector<Tag>, ncomp, f),TagVector,Array4BoxOrientationTag,Orientation,OrientationIter,adjCell,BL_PROFILE
Runs many small kernels as one launch. Filling the ghost cells outside the
domain boundary touches a thin box per domain face of every box at the
boundary: many small boxes of different sizes, each too small to fill a
GPU. The program fills them with a reflecting boundary condition in three
ways, checks that the results agree, and times them with BL_PROFILE
(see Profiling with TinyProfiler): one ParallelFor per box and face inside an
MFIter loop, the baseline, not recommended on GPU for many small boxes
since no launch fills the device; one ParallelFor over a Vector of
tags, which packs all the boxes into a single launch; and the same with a
TagVector built once and reused.
A tag is a small struct with a box() member (size() for 1D work)
that carries what the kernel needs, here the Array4, the thin box and
the face. The tags are built on the host:
// One tag per (local box, domain face it touches): the Array4 of the box,
// the thin box of ghost cells outside the face, and the face.
amrex::Vector<amrex::Array4BoxOrientationTag<Real>>
make_boundary_tags (amrex::MultiFab& mf, amrex::Box const& domain, int nghost)
{
amrex::Vector<amrex::Array4BoxOrientationTag<Real>> tags;
for (amrex::MFIter mfi(mf); mfi.isValid(); ++mfi) {
amrex::Box const& vbx = mfi.validbox();
for (amrex::OrientationIter oit; oit; ++oit) {
amrex::Orientation const face = oit();
if (touches(vbx, domain, face)) {
tags.push_back({mf.array(mfi), amrex::adjCell(vbx, face, nghost), face});
}
}
}
return tags;
}
The kernel receives (i, j, k, n, tag). ParallelFor over a
Vector of tags copies the tags to the device on every call, so for
repeated use the TagVector is built once. Like other ParallelFor
calls, both forms are asynchronous on GPU, so each timed loop calls
Gpu::streamSynchronize() for the timer to include the kernel:
// 3. The TagVector is built once and reused; it only needs to be
// rebuilt when the boxes or the MultiFab change.
amrex::TagVector<amrex::Array4BoxOrientationTag<Real>> tv(
make_boundary_tags(phi_cached, domain, nghost));
for (int irep = 0; irep < nrepeat; ++irep) {
BL_PROFILE("tags_cached");
amrex::ParallelFor(tv, ncomp,
[=] AMREX_GPU_DEVICE (int i, int j, int k, int n,
amrex::Array4BoxOrientationTag<Real> const& tag)
{
reflect(tag.fab, i, j, k, n, tag.face, dlo, dhi);
});
amrex::Gpu::streamSynchronize();
}
On CPU, the launch is a loop over the tags that opens its own OpenMP
parallel region, so it must not be called inside one. AMReX
provides Array4BoxTag, Array4BoxValTag,
Array4BoxOrientationTag, Array4PairTag, Array4CopyTag and
VectorTag, and any struct with box() or size() works. Use
ParallelFor(mf, ...) (MultiFab) when the work is the same
on every box, and tags for irregular sets of boxes: physical boundary
conditions, corrections at coarse/fine faces, operations on some boxes
only.
Run:
cmake --build build --target Base_TagParallelFor -j 8
cd build/Base/TagParallelFor
mpiexec -n 2 ./TagParallelFor inputs
For timings, build with TinyProfiler on and an optimized GPU build, and
use e.g. n_cell=256 nrepeat=20 tiny_profiler.print_threshold=0; the
difference between the methods grows with the number of boxes.
SIMD
- Level:
★★
- Source:
- Key APIs:
AMREX_FORCE_INLINE,AMREX_NO_INLINE,ParallelForSIMD,SIMDindex,simd::Vectorized,simd::load_1d,simd::store_1d,simd::native_simd_size_real,BL_PROFILE
Vectorization on CPUs. On CPU, ParallelFor marks its innermost loop
with AMREX_PRAGMA_SIMD, a promise to the compiler that the iterations
are independent. amrex::For has the n- and Box-based
signatures of ParallelFor and runs on GPUs the same way; on CPU it
makes no promise that the iterations are independent, so use it when they
are not. Whether the loop is vectorized depends on the kernel. The first
part writes the same function twice: with a call to a function that is
not inlined and has a branch inside, which stops the vectorizer and is
shown for illustration only, and in the recommended way, inlined and
branch-free:
// For illustration only: a call to a function the compiler cannot inline,
// with a branch inside, stops the vectorization of the loop that calls it.
AMREX_GPU_HOST_DEVICE AMREX_NO_INLINE
Real f_branch (Real p, Real c)
{
if (p > c) {
return std::sqrt(p - c);
} else {
return -std::sqrt(c - p);
}
}
// Inlined and without branches, the loop vectorizes. The arithmetic is done
// unconditionally, on an argument made safe for every lane (abs), and ?:
// only picks one of the computed values.
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE
Real f_select (Real p, Real c)
{
Real const r = std::sqrt(std::abs(p - c));
return (p > c) ? r : -r;
}
The rules behind it: keep kernels inlinable; compute every quantity
unconditionally and pick with ?:, amrex::min, amrex::max or
std::abs, on arguments that are safe in every lane; and with GCC,
add -fno-trapping-math if arithmetic inside the arms of a ?: is
to vectorize. Inactive lanes, and the compiler’s own speculation, raise
floating-point exceptions where the source code does not; the result is
correct, but the traps amrex.fpe_trap_* would stop the program, so
they are a debugging aid for scalar runs and the tests do not enable
them. Build with
-march=native to use the full vector width, and look at the
compiler’s report
(GCC -fopt-info-vec-optimized/-missed, clang
-Rpass=loop-vectorize) to see what happened.
The second part is explicit SIMD. With -DAMReX_SIMD=ON (the
header-only vir-simd library is downloaded; see Getting Started),
ParallelForSIMD<Functor> hands the kernel a SIMDindex covering
several consecutive elements, simd::load_1d returns them as a SIMD
register and simd::store_1d writes the register back. The functor
derives from simd::Vectorized<> and is generic over the value type,
amrex::Real or a register of Reals. Without the option, and on
GPUs, the same code runs one element at a time:
struct Push : amrex::simd::Vectorized<>
{
Real dt;
explicit Push (Real a_dt) : dt(a_dt) {}
template <typename T>
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE
void operator() (T& AMREX_RESTRICT x, T const& AMREX_RESTRICT v) const
{
x += v * dt;
}
};
amrex::ParallelForSIMD<Push>(n, [=] AMREX_GPU_DEVICE (auto si)
{
decltype(auto) xi = amrex::simd::load_1d(xp, si);
decltype(auto) vi = amrex::simd::load_1d(vp, si);
using T = std::remove_reference_t<decltype(xi)>;
constexpr auto method = &Push::operator()<T>;
push(xi, vi);
// Writes back only for arguments the method takes by
// non-const reference, here x; a no-op without SIMD.
amrex::simd::store_1d<method, 0>(xi, xp, si);
});
Both parts check their results against the scalar version and time the
kernels with BL_PROFILE (see Profiling with TinyProfiler). The scalar push is
already vectorized by the compiler, so the explicit version is not faster
here; explicit SIMD pays off for kernels the auto-vectorizer cannot
handle, e.g. ParticleReduceSIMD in the AMReX documentation.
Run:
cmake -S . -B build -DAMReXTutorials_TOPICS=Base -DAMReX_SIMD=ON -DCMAKE_CXX_FLAGS="-march=native"
cmake --build build --target Base_SIMD -j 8
cd build/Base/SIMD
./SIMD inputs
Part 1: max difference between the two kernels = 0
Part 2: SIMD width 4 (AMReX_SIMD=ON)
Part 2: max difference between the SIMD and the scalar push = 0
PASSED
ExternalMPI
- Level:
★★
- Source:
- Key APIs:
amrex::Initialize(argc, argv, build_parm_parse, comm, func),ParmParse::add,ParmParse::addfile,ParallelDescriptor::NProcs
Uses AMReX inside an application that manages MPI itself. The application
calls MPI_Init, splits MPI_COMM_WORLD into even and odd ranks, and
initializes AMReX on each group’s communicator. AMReX uses a duplicate of
the given communicator and does not finalize MPI; the application calls
MPI_Finalize after amrex::Finalize.
With build_parm_parse = false, AMReX ignores argc/argv. The
callback runs before AMReX reads its own parameters, so it is the place to
set them in code.
auto add_parameters = [&] ()
{
amrex::ParmParse pp_amrex("amrex");
pp_amrex.add("verbose", 0);
if (!inputs_file.empty()) {
amrex::ParmParse::addfile(inputs_file);
}
amrex::ParmParse pp;
pp.add("group", group);
};
// build_parm_parse = false: do not parse argc/argv into ParmParse.
// AMReX uses a duplicate of group_comm.
amrex::Initialize(argc, argv, false, group_comm, add_parameters);
Run (requires AMReX_MPI=ON):
cmake --build build --target Base_ExternalMPI -j 8
cd build/Base/ExternalMPI
mpiexec -n 4 ./ExternalMPI inputs