Productive Performance Engineering for Weather and Climate Modeling with Python
Paper · 2022 · Tal Ben-Nun, Linus Groner, Florian Deconinck et al.
Summary
A weather simulation has to move large amounts of data every time it advances the atmosphere. The fastest way to move those data depends on the machine. Code tuned to keep horizontal slices in a CPU cache can be hard to adapt to a GPU, even when the equations are unchanged. The authors take on this problem in FV3, the atmospheric solver at the heart of several weather and climate systems. They rewrite its dynamical core and driver in Python, then use a compiler to turn that source into a parallel program. Their aim is to let scientists work on the numerical method while performance engineers change how the machine executes it.
The rewrite uses GridTools for Python, or GT4Py, to describe stencils. A stencil specifies how to update a point on a grid using values at nearby points. GT4Py lets developers write these relationships without fixing details such as the order in which threads visit the grid. DaCe, the compiler framework, represents the movement of array data explicitly. It can optimize an individual stencil, combine work across stencil calls, or compile the time-stepping routine as a unit. The authors use measurements and bandwidth estimates to decide where to intervene. Their transfer tuning procedure saves search time by finding promising configurations in a recurring transport routine and testing those configurations where the same stencil combinations appear elsewhere.
On Piz Daint, the optimized Python implementation reached a speedup of up to 3.92× over the production-tuned multicore FORTRAN implementation. The global runs reached 2,400 GPUs, with a reported throughput of 0.11 simulated years per day at 2.28 km grid spacing. The Python version had 0.42× the source length by the paper’s count, although the FORTRAN version also supported capabilities outside the port’s scope. The authors also recompiled the Python code for the A100 GPUs on JUWELS Booster and ran it without changing the application source.
The work took roughly two person-years to port and validate, including the driver and testing infrastructure. The subsequent performance work combined automated search with changes that engineers devised after inspecting specific bottlenecks. The demonstrated gains apply to the nonhydrostatic dynamical core. The experiments show what can be gained when the compiler can change data layout and execution order across a large solver while the application retains its scientific structure.
Deep dive: Productive Performance Engineering for Weather and Climate Modeling with Python
How the authors rewrote the FV3 atmospheric solver in Python, tuned its data movement, and measured its performance on thousands of GPUs. · about 37 minutes to read
The problem and its context
Why the dynamical core matters
A dynamical core starts from a state of the atmosphere and advances it in time according to equations for air motion and thermodynamics. A full weather or climate system can call other routines to represent physical processes separately. Those routines have their own costs and numerical choices. The authors focus on the dynamical core because it is a substantial parallel program by itself, with dependencies that extend from neighboring grid cells to the communication between machines.
The pressure to make this software faster comes from the resolution at which scientists want to run it. The paper discusses the drive towards kilometer-scale simulations, where a finer grid can improve the representation of processes such as deep convection. Resolution also makes the execution problem harder. Grid fields have to be stored and updated, and neighboring pieces of the grid have to exchange values. A new machine may offer more bandwidth or parallel work, yet obtaining those benefits can require extensive changes if the old implementation embeds the execution strategy throughout the source.
FV3 is a demanding case because its original implementation already made careful use of the hardware it targeted. Its scientific design and its FORTRAN implementation were chosen with efficiency in mind. In the FV3 version examined here, the fully compressible Euler equations are solved on a cubed sphere with a flow-following vertical coordinate. The cubed sphere organizes the horizontal grid over the faces of a cube projected onto the sphere. That arrangement gives the code a regular grid within a face, with special work where faces meet. The vertical coordinate adds a different kind of structure. The solver can integrate motion on moving vertical surfaces and later remap the result to reference levels.
In the nonhydrostatic setup, fast sound and gravity waves that propagate vertically are treated semi-implicitly. The rest of the integration is explicit. From the point of view of execution, this distinction matters because some work can be carried out independently at many positions, while other work uses values obtained earlier along a vertical column. A common compilation strategy has to accommodate both forms. It also has to preserve the order of the outer numerical steps and the communication needed by distributed execution.
What the CPU implementation gains from its schedule
The FORTRAN code divides the horizontal grid among processes through MPI, a library interface for communication between processes. Within a node, it uses OpenMP directives for threading. The split is horizontal, so a process has a horizontal portion of the domain and the vertical levels that go with it. When a calculation needs values that belong to a neighboring process, the processes exchange boundary data. The replicated boundary values form a halo around the locally owned grid points.
Much of FV3 can work on a horizontal slice without immediately needing the slices above and below. This makes the position of the vertical loop an important performance decision. The FORTRAN implementation uses K-blocking, with K denoting the vertical dimension. Where the dependencies permit it, the vertical loop surrounds a substantial stretch of horizontal work. A process can perform multiple operations while the current planes remain close to the CPU cores in cache. When a fixed global problem is divided among more processes, the local planes can become small enough for several to fit in the L2 cache.
There is a difference between the order that makes a scientific algorithm easy to explain and the loop order that lets a particular processor reuse data. In the original FV3, the latter is part of the implementation. Changing it can mean rearranging routines, array accesses and loops that were written together to exploit CPU locality. A GPU presents a different opportunity. It can execute work for many grid points concurrently and has high off-chip memory bandwidth, but the CPU strategy for retaining planes between operations does not carry over directly. A GPU implementation has to decide which threads do the work, when to combine operations and where their intermediate values should reside.
This creates a problem even when an individual GPU kernel is easy to implement. A kernel is a unit of work launched on the GPU. If each small operation becomes a separate kernel, the program may repeatedly write an intermediate array to global memory and read it back on the next launch. Combining operations can avoid that traffic, provided their dependencies permit it. The decision can span routines that the scientific source groups separately. An implementation that optimizes only the body of each routine has a smaller view of the opportunity than one that can see how the routines are used together.
The alternatives the authors considered
The paper describes earlier efforts to accelerate portions of FV3 using CUDA FORTRAN and compiler directives such as OpenACC. Those efforts established that GPU acceleration was feasible for parts of the computation. They also illustrate a maintenance problem. Hardware-specific source and annotations can need revision as compilers, libraries and processors change. Porting selected routines also leaves decisions about how to organize the driver, distribute fields and preserve locality across routine boundaries.
Weather and climate software offers a reason to put some of those decisions in a domain-specific language. Much of the work uses recurring patterns on multidimensional fields. A language that understands a stencil can tell which offsets it reads, which positions it writes and which dimensions carry dependencies. The compiler can use that information to specialize transformations that would be difficult to infer reliably from arbitrary imperative code. The paper discusses CLAW as a FORTRAN-based example and describes DAWN and the Open Earth Compiler as routes from high-level atmospheric computations to hardware-specific code. It also points to the UK Met Office’s use of LFRic for a complete dynamical core. These were examples of separating the scientific expression from machine-specific execution before the FV3 effort.
Python brings a separate motivation. Earth system scientists already used it to process, analyze and visualize simulation output. A workflow in which a compiled simulation first writes fields to disk and a Python program reads them back incurs storage and processing costs. Researchers who want to call Python libraries while a simulation is running also need an interface to the compiled code. The paper describes approaches that passed arrays between languages, wrapped FORTRAN as a Python library, or made Python-trained components callable from FORTRAN. Other projects wrote simulation code in Python or Cython.
For FV3, the authors chose to move the driver and the numerical source into the same Python environment. That was a wider change than providing a Python interface to the existing routines. It gave the compiler a view of the calls among numerical operations as well as the operations themselves. For the choice to work, the project needed a way to retain the organization of a large scientific codebase, validate the replacement against the original and compile the frequently executed path. Those needs shaped the division of labor between GT4Py and DaCe.
The method, step by step
Port the solver and establish a numerical reference
The authors began with the existing FV3 module boundaries. The FORTRAN implementation already separated many of the numerical steps, so the Python port could keep those divisions. Each module became a class holding its fields, methods and the portion of the simulation configuration it needed. A method could invoke its own stencils or call another module. That structure let the team keep routines organized around their scientific purpose even when the compiled execution would combine or rearrange some of the work.
They captured input and output arrays from the FORTRAN implementation for the modules being ported. A standalone test could then run the corresponding Python module on the stored inputs and compare its outputs with the stored reference to a chosen numerical precision. This gives a developer a way to investigate a changed routine close to where a discrepancy first appears. It also provides a check before performance transformations are evaluated. A routine that gives the wrong result is the wrong starting point for a timing comparison.
The available test configurations depend on what a stencil reads. A stencil whose inputs do not depend on other cubed-sphere tiles can be tested on one node. The partitioner also supports testing across the faces, with multiple subdomains arranged in configurations the partitioner can express. This matters because a local update and an update at a face boundary can take different paths. The Python implementation includes a halo updater that packs boundary data, manages nonblocking MPI communication and transforms the data to account for the relative orientation of adjoining faces.
The resulting workflow starts with scientific code and a reference for its behavior, then moves the execution decisions into the compilation and tuning process.
From FV3 source to optimized distributed execution
The steps in order.
Express the grid updates as stencils
In GT4Py, a Python function decorated as a stencil describes the update. Its field types say which dimensions an array has, without building the size of the domain into the type. A horizontal area field, for example, has positions along the two horizontal dimensions but no vertical index. The function can distinguish work over different vertical intervals, and the statement that encloses an interval indicates whether the computations within it can run in parallel or must respect a vertical order.
For a horizontal stencil, points can be updated without carrying a dependency from one iteration of the grid to the next. A value used by a point can still come from a neighbor. What matters is whether it comes from an input or already defined stage, or from an update that requires the points themselves to run in a particular sequence. A vertical solver has an ordering dependency along the column. A forward or backward sweep makes earlier values in that sweep available to later levels. Independent columns still offer parallel work even when a sweep within each column has to be serial.
The paper’s flux example shows what changes when explicit loops give way to this description. The FORTRAN routine declares array extents, visits the grid with nested loops and names intermediate arrays. In the GT4Py version, the same relationships are written for an implicit current point. The neighboring value is expressed with a relative offset. The calculations can be written in grid notation, starting with the intermediate flux.
fx1 = x_area_flux × fx2
Here fx1 is the intermediate flux, x_area_flux is the input area flux and fx2 is the other input flux field. Each name on the right denotes its value at the current grid point, and × means multiplication. The equality names the value produced for that point.
area_with_x_flux = area + x_area_flux − x_area_flux[1, 0, 0]
Here area_with_x_flux is the intermediate area after accounting for the area flux. area denotes the horizontal cell area, and the unindexed x_area_flux is the value at the current point. The bracketed triple gives offsets along the first horizontal, second horizontal and vertical dimensions in that order. The 1 selects the next position along the first horizontal dimension. Both 0 entries leave their dimensions unchanged. Addition and subtraction combine the area with the flux values at the current and neighboring positions.
q_j = (q × area + fx1 − fx1[1, 0, 0]) ÷ area_with_x_flux
Here q_j is the output field and q is the input scalar at the current point. area is the same horizontal area, and fx1 is the intermediate flux just defined. fx1[1, 0, 0] is that flux at the next position along the first horizontal axis, with the other coordinates unchanged. The parentheses group the area-weighted scalar and the flux terms, and ÷ divides that group by area_with_x_flux at the current point.
There is enough information in these expressions to identify the neighboring data the result depends on. The compiler can infer buffer extents and halo requirements from such uses. It can also decide whether to allocate a field for an intermediate, calculate the value within a thread or combine statements into a single kernel. In the paper’s generated example, the kernel computes the two fx1 values needed by its output point. A value needed by adjacent threads can therefore be recomputed. The trade is extra arithmetic in exchange for avoiding some intermediate data movement and coordination.
Represent the edges and corners explicitly
The interior stencil does not describe every point on the cubed sphere. Corrections at edges and corners depend on where a point lies on the face. The authors extended GT4Py with horizontal regions so that a stencil can supply different expressions in selected parts of its horizontal domain. In a paper example, the general expression for a flux uses a correction involving a second velocity and geometric factors.
flux = dt2 × (velocity − velocity_c × cosa) ÷ sina
Here flux is the quantity assigned, and dt2 is the time-step factor in the example. velocity and velocity_c are velocity quantities read at the current position. cosa and sina are the geometric factors in the correction. The product with cosa is subtracted from velocity, and sina is the divisor.
flux = dt2 × velocity
Here flux names the same output, dt2 is the same factor and velocity is the value read at the current point. The product is the expression used on the selected lower edge of the second horizontal dimension. The region attached to this assignment defines where it takes effect.
This information also helps with communication. When a stencil is distributed, some regions read data that another process computed and others do not. The region ranges let the implementation determine which ranks must synchronize. A rank is the identity of a process participating in MPI communication. Knowing both the rank and its place within the face helps the compiler specialize work that is irrelevant to other subdomains.
Horizontal regions introduce another scheduling choice. A GPU kernel can cover the full domain and use each thread’s index to decide whether it should execute the correction. Or the compiler can generate a separate kernel whose iteration range covers only the region. The full-domain approach can keep work together, while the narrower kernel can avoid allocating threads to points that will do nothing. The choice depends on how much actual work is in the region and on where that region falls in the distributed layout.
Lower the computation to an explicit graph
After GT4Py makes domain-specific simplifications, it hands the stencil to the DaCe backend. DaCe represents programs with Stateful Dataflow Multigraphs, abbreviated SDFGs. An SDFG represents control flow as a state machine. Inside a state, an acyclic graph records data containers, computations and the transfers that connect them. A state transition can express sequencing, a choice or a return through a loop. Within a state, the graph exposes which arrays and ranges an operation must read or write.
The separation of data movement from arithmetic is central to the design. A performance engineer can ask what portion of an array a computation touches, whether a buffer is temporary and whether a value must remain available elsewhere. A transformation can then operate on the graph. Examples include removing an unnecessary allocation, storing an intermediate locally, combining operations or assigning a parallel region to an accelerator. A map in the graph defines a region of work applied over a parameterized range, such as the indices of points in part of a grid.
At first, each translated stencil computation is a library node, a high-level placeholder with enough information to expand it into a more detailed graph. Schedule attributes guide that expansion. They include the order of iteration, the dimensions to tile and the tile sizes, the hardware destination for parallel work, and the choice between parallel maps and ordered loops. A tile is a block of iterations handled as a group. The schedule can also specify which fields to cache, where to cache them and how to implement horizontal regions.
Only some settings are legal for any given access pattern. An ordered dependence along a vertical column, for instance, constrains which work can be handed to independent threads. The scheduler derives feasible options from those dependencies before the tuner chooses among them. For particular storage decisions it also has defaults. A value used by just one thread can go in that thread’s registers. Values shared across threads can go in shared memory, where accessing them may require synchronization. Stencil calls appear in the surrounding graph as library nodes, so this representation also exposes opportunities that involve more than one call.
Compile the time-stepping driver as a unit
FV3’s time integration has several nested levels. The outer physics step advances the simulation and can invoke physical parametrizations. Inside the dynamical core, the remapping loop handles tracer transport, the return from moving vertical surfaces to reference levels, and the call to the innermost integration loop. That innermost loop advances the dynamics on the moving surfaces. The spacing of the grid affects how many acoustic substeps it needs, because of the propagation of horizontal sound waves. Nonblocking halo exchanges occur at specific points inside the loop.
With only a stencil compiler, Python could still dispatch each numerical call in that structure individually. The authors instead compile the time-stepping routine into a shared library, which the Python program invokes through the original function signature. For the GPU target, the generated implementation uses C++ and CUDA. It manages storage and distributed communication as part of the compiled execution. The gain is both in dispatch and in scope. The compiler can move allocation out of the critical path, propagate constants into kernels and let a suitable data layout persist across operations that originated in different routines.
To make this possible, the authors added a Python preprocessing stage. It propagates known constants, expands loops where directed and removes code from branches that can be resolved ahead of time. This is useful when a loop uses keys to select tracer arrays from a dictionary. If the keys are known while compiling, the resulting code can refer directly to the selected arrays. The preprocessing also resolves closures, making data that a function obtained from an enclosing scope or object available explicitly to the compiled function. This lets the scientific source use classes while giving the compiler a flatter view of what each call depends on.
Flattening the call structure also brings up aliasing. The same array object can be reachable from more than one class. Treating the references as unrelated would obscure possible interactions between their reads and writes. The preprocessor analyzes the call tree and consolidates references to the same object, giving the compiler the information it needs to preserve ordering when accesses can interfere.
Certain calls still go back through the Python interpreter. The authors add automatic callbacks for functions that cannot be handled as C function pointers. NumPy and CuPy arrays can be mapped to CPU and GPU pointers, respectively. To keep the optimizer from reordering callbacks whose effects it cannot inspect, the graph gives each callback a dependency on a dummy container representing Python state. This arrangement preserves a route to activities such as diagnostics, plotting and specialized input or output while the compiled library runs the core computation.
The size of the expanded graph explains why this compilation is only the start of performance engineering. The paper counts 26,689 dataflow nodes organized into 3,179 states and 4,241 unique GPU kernels. Some kernels can be invoked repeatedly under different conditions as the control flow loops. Decisions that look small for one call can therefore affect a large share of the run. Conversely, a setting that works well for one invocation may be a poor fit for an invocation over a different range.
Establish a local schedule and layout
The first optimization pass gives individual stencils a practical starting schedule. The authors search a representative horizontal stencil and a representative vertical solver separately. The two classes need different mappings because the vertical solver carries values along a column. A schedule that spreads a horizontal update across grid points can expose parallel work directly, while a vertical sweep can run parallel columns and keep the ordered work within each column together.
Some local transformations have a clear data movement rationale. Consecutive intervals in a forward or backward sweep can be combined into one map and kernel, so that values carried across intervals do not have to be stored in global memory and loaded again at the boundary. Operations that need no coordination between threads can be fused at the thread level. When one operation consumes neighboring results from another, a fused version can sometimes calculate those results again locally. That is the choice illustrated in the flux example.
The compiler also looks at how long an intermediate is needed. Temporaries confined to a thread can be represented as local variables. The compiler can drop a load when the value will be overwritten before anything reads it. During an ordered sweep, a value reused on consecutive iterations can stay in a register until the computation is finished with it. Each transformation reduces a particular transfer between the executing thread and global memory.
Field allocation supplies related choices. The logical shape fixes the number of coordinates along each axis. Strides determine how far in memory the program moves when it advances along an axis. Padding can change those distances or shift where a field begins. The authors use an I-contiguous layout, where the first horizontal coordinate varies fastest in memory. In the workload they target, this supports wide accesses along that dimension, including when a vertical solver works on a plane at a time across independent columns.
The first element in each allocation can belong to a halo, while a kernel commonly starts with the first interior element. Aligning the start of the allocation therefore does not necessarily align the part the kernel accesses. The authors add padding before the field to align the first non-halo element. The aim is coalescing, in which nearby threads access neighboring addresses so that the hardware can serve them together. The computational layout has to complement that choice by assigning threads to grid positions in an appropriate order.
The automatic sweep chooses [Interval, Operation, K, J, I] for the horizontal stencil schedule. The last dimension maps to threadIdx.x, so adjacent threads along that axis work along the contiguous horizontal coordinate. The vertical solver uses [J, I, Interval, Operation, K], which accommodates the sweep along K while distributing work across columns. These settings furnish starting heuristics for the whole application. Later tuning can still specialize a particular occurrence whose size, dependencies or position in the graph favors a different choice.
Transfer configurations that work in recurring code
The graph exposes far more transformations than the authors could measure across the full application. Transfer tuning uses repetition to reduce the search. Suppose a stencil is immediately followed by a pointwise update. Fusing them may let the thread that computed the stencil result apply the pointwise operation before writing it out. If the same combination occurs in several places, the first successful experiment is evidence that the fusion is worth testing elsewhere.
The first phase of the procedure tunes small subgraphs called cutouts. In the FV3 study, they come from fv_tp_2d, the finite-volume transport module. For each cutout, the tuner enumerates available configurations, measures them and retains the most promising. A configuration records the stencils involved and the transformations that were applied. The paper defines these patterns using stencil names, while pointing out that a different implementation could describe motifs through more general graph properties.
M = 2
Here M is how many of the best measured configurations from each cutout are carried forward for consideration in the full dynamical core. The 2 is the value the authors use for the transport case study. It describes the candidate budget per source cutout for transfer, while the first phase searches the configurations available to that cutout.
In the second phase, the tuner searches the complete graph for matching occurrences. It tests the transferred configuration at the destination and applies it there when the local measurement improves. This prevents the favorable source timing from standing in for a measurement in a different context. The authors prune the matches further by considering the first match of a pattern per state and keeping the most performance-improving pattern. With these decisions, the tool spends time testing candidates already shown to be promising somewhere in the application.
Transfer tuning concerns execution configurations. It does not fit a predictor from meteorological data. Its inputs include the compiled graph, the set of allowed transformations and their measured running times. The only knowledge it transfers in this case is which combinations of transformations are good candidates when particular stencil patterns recur.
Use performance bounds to direct inspection
The workflow gives the engineer a way to inspect the result of tuning. Since stencils commonly spend much of their time moving fields, the authors estimate the time a kernel would need if bandwidth were its limiting resource. Their analysis counts the field elements accessed, treating each element as moved once even if several threads use it. It uses the array ranges in the graph and leaves detailed L1 and L2 cache behavior out of the estimate. The comparison is with a bandwidth-based reference for the data-access pattern.
A kernel can run on different array sizes or with different masks. The engineer is shown the maximum reported runtime and the largest configuration used for the estimate. Kernels are grouped by type and ranked by their accumulated execution times, so an operation can rise in priority because it recurs frequently. The aim is to locate kinds of work that cost substantial time across the application and still have room for improvement relative to the reference.
A gap between the timing and the bandwidth estimate can have several causes. The graph might launch far more threads than an edge operation can use. An arithmetic expression might compile into an expensive general-purpose routine. A kernel might simply have too little work to sustain the bandwidth available for a large transfer. In the paper, engineers used the report to select candidates and then read the generated schedules or code to identify the cause. They encoded the resulting fixes as transformations in the toolchain so the scientific source could retain its original organization.
Experiments and results
Machines, workload and comparison
The Piz Daint measurements used Cray XC50 nodes with an Intel Xeon E5-2690 v3 CPU and an NVIDIA Tesla P100 GPU per node, connected by Cray Aries. The CPU had 12 physical cores, and the node configuration included 64 GB of host memory and 16 GB of GPU memory. The reference was the optimized FORTRAN FV3 version used for multicore runs. Its production settings used 6 MPI ranks per node and 4 threads per rank, making use of hyperthreading. The Python implementation ran through GT4Py and DaCe with compiled GPU execution.
The experiments used double-precision values on a grid with 80 vertical levels and 192×192 horizontal points per compute node, except where a test specified a different grid size. The module tests varied the local size. The large distributed tests varied the number of nodes and the global resolution. Keeping these settings distinct matters because a speedup can reflect cache behavior at a particular local grid size, the cost of boundary work in a particular decomposition, or the balance of communication and computation in a full timestep.
The distributed benchmark started from an analytically defined zonal flow with a perturbation that develops into baroclinic instability. The analytic initialization allows the researchers to generate a starting state at the needed resolution and check the evolution visually. This benchmark is separate from the module tests that compare results with saved FORTRAN arrays. The paper reports the median of at least 10 runs for each experiment. Its main outcomes are elapsed times for modules, kernels or timesteps, speedups against the appropriate baseline, bandwidth measurements and simulated time advanced per day.
How much bandwidth is available
The authors first looked at the workload and the machine. Their PAPI measurements put load and store operations at 40.15% of executed instructions for the FORTRAN dynamical core. That instruction share establishes that movement-related instructions are common. A second set of measurements asks how quickly the two processors can move data and whether a stencil at the local domain size can exploit that capacity.
STREAM reported 43.77 GB/s on the Haswell CPU. The CUDA bandwidth test reported 501.1 GB/s on the Pascal GPU. A copy stencil, which reads one input field and writes one output field at the target size, achieved 40.99 GiB/s on the CPU and 489.83 GiB/s on the GPU. The paper uses GB/s for the benchmark figures and GiB/s for the copy-stencil figures. The authors give 11.45× as the expected maximum speedup for a bandwidth-bound comparison. A stencil sequence that reuses CPU cache, or a distributed timestep that also spends time exchanging halos, can behave quite differently from the simple streaming workload behind that expectation.
The copy experiment plays a practical role in the evaluation. If the test domain were too small to drive substantial bandwidth even for a copy, a gap in a more complicated kernel would be difficult to interpret. With the copy result as a reference, the authors can investigate when the application is benefiting from reuse, when it has too little parallel work and when its generated execution incurs another cost.
Two numerical routines at different local sizes
The Riemann solver routine riem_solver_c handles the nonhydrostatic contributions to vertical velocity and pressure perturbation in the acoustic substep. It uses a tridiagonal solve, meaning that the linear system couples each unknown to its immediate neighbors in the ordered system. The implementation divides this work into GT4Py stencils and schedules them as 22 GPU kernels. The routine gives the authors a vertical workload for which the CPU’s horizontal K-blocking strategy is a less favorable fit.
At 128×128×80, the FORTRAN Riemann solver took 12.27 ms and the GT4Py and DaCe implementation took 1.85 ms, for a reported 6.63× speedup. At the target 192×192×80 size, the corresponding times were 27.94 ms and 3.86 ms, with a 7.25× speedup. At 256×256×80, they were 52.40 ms and 6.96 ms, with a 7.53× speedup. The largest tested local size, 384×384×80, took 121.80 ms in FORTRAN and 15.31 ms on the GPU, with a 7.96× speedup.
Riemann solver elapsed time on Piz Daint at 192×192×80
The compiled GPU implementation completes the vertical solve faster at the target local size.
The numbers
| System or setting | ms |
|---|---|
| FORTRAN on CPU | 27.94 |
| GT4Py and DaCe on GPU (this paper) | 3.86 |
Relative to the smallest Riemann solver domain, the paper gives 9x as the relative size of the largest domain. The runtime scaling factors for that largest case were 9.92 for FORTRAN and 8.26 for the GPU implementation. The authors interpret the CPU trend as evidence that cache capacity and the existing schedule matter as the local problem grows. On the GPU, the time grows more slowly than the domain. The authors connect that trend to the limited parallel work exposed by the smaller horizontal grids. The larger domains have more independent columns with which to occupy the GPU.
The transport module fv_tp_2d computes fluxes for horizontal finite-volume transport. It has no dependency between vertical levels. The FORTRAN code works on horizontal slices and can reuse cached fields well. At the target size, the authors report that only ∼0.13% of FORTRAN’s load and store instructions for this workload resulted in L3 cache misses. This makes the transport module a stronger case for the original CPU schedule than the vertical solver.
For transport at 128×128×80, FORTRAN took 3.41 ms and the GPU version took 1.81 ms, giving a 1.88× speedup. At 192×192×80, the measured times were 12.31 ms and 3.41 ms, for a 3.61× speedup. At 256×256×80, they were 35.79 ms and 5.67 ms, for 6.31×. At 384×384×80, they were 106.66 ms and 13.10 ms, for 8.14×. The pattern is different from the relatively stable advantage on the Riemann solver. The CPU schedule for transport benefits strongly from the working set fitting in cache. As the local domain grows and more traffic goes off chip, the GPU’s bandwidth advantage becomes more visible.
Finite-volume transport elapsed time on Piz Daint at 192×192×80
The GPU version leads at the target local size despite effective cache reuse in the CPU implementation.
The numbers
| System or setting | ms |
|---|---|
| FORTRAN on CPU | 12.31 |
| GT4Py and DaCe on GPU (this paper) | 3.41 |
At the largest transport size, the reported time scaling factors relative to the smallest domain were 31.27 for FORTRAN and 7.23 for the GPU. The authors again see evidence that the smaller GPU cases leave capacity unused. On the CPU side, the large time increase relative to grid growth shows how much the smallest cases benefited from locality. The pair of module experiments gives a reason for examining several local sizes. The vertical solver already shows a large advantage at the small end, while the transport comparison changes substantially as the working set grows.
Tuning the distributed core
For the optimization history, the authors use the smallest distributed configuration, a 6-node run in which each node owns one cubed-sphere face. Every node therefore has the special edge and corner work for an entire face. The base FORTRAN time was 16.36 s per timestep. The default GT4Py and DaCe configuration ran in 10.87 s, with a reported 1.50× speedup. This default is a useful baseline because it measures the version before the reported sequence of scheduling and tuning changes.
The first major improvement came from applying the scheduling heuristics found in the local sweep. The time fell to 5.56 s, a configuration reported at 2.94× versus FORTRAN. The paper gives 1.96× for the speedup of this scheduling change relative to the preceding default configuration. Adding local caching brought the time to 5.45 s, and specializing the power operator brought it to 5.35 s. Splitting horizontal regions across multiple kernels brought the time to 4.82 s at the end of the first optimization cycle.
The second cycle changed the schedule of the Lagrangian contribution, pruned unnecessary region work and transferred configurations from finite-volume transport. The table reports 4.82 s after the Lagrangian scheduling change and 4.77 s after region pruning. The final transfer-tuned configuration took 4.61 s per timestep, for 3.55× versus FORTRAN. The authors report a 3.47% speedup for that transfer pass relative to the configuration immediately before it. The comparison shows what a focused late tuning pass added after the largest scheduling gains had already been captured.
FV3 timestep time across optimization stages on six Piz Daint nodes
Stencil scheduling accounts for the largest drop among the successive compiler changes shown.
The numbers
| System or setting | s |
|---|---|
| Production FORTRAN | 16.36 |
| GT4Py and DaCe default | 10.87 |
| Stencil schedule heuristics | 5.56 |
| Local caching | 5.45 |
| Specialized power operator | 5.35 |
| Regions split across kernels | 4.82 |
| Region pruning | 4.77 |
| Transfer-tuned implementation (this paper) | 4.61 |
The transfer tuning measurements also report the cost of getting those configurations. The finite-volume transport module supplied 127 possible cutouts, with at most 48 configurations for any one cutout. The authors searched 1,272 configurations in the first phase. The full-core pass automatically found and transferred 603 transformations. They estimate that a search without transfer tuning would have had ≥ 30,302,185 candidate configurations to consider. That last figure is a count of candidates, not the outcome of a measured exhaustive run.
On a single Piz Daint node, pattern extraction for the transport module took 2:42 hours. The second phase on the full core took 8:24 hours. The measured search times and the eventual timestep improvement answer different questions. One describes the cost of finding and verifying patterns. The other describes what those patterns contributed to the particular compiled timestep after the other optimizations.
Global runs and portability
The global benchmark ranges from 54 nodes at 15.6 km grid spacing to 2,400 nodes at 2.28 km. The authors keep the local grid work fixed while increasing the problem size and available nodes. This is weak scaling. The relevant comparison is how much a timestep changes as the machine tackles a finer global domain with approximately the same work assigned locally. The paper plots timestep time for both implementations, with non-parametric 95% confidence intervals.
The Python FV3 implementation shows nearly flat weak scaling in these runs. The authors attribute this to the communication per node staying similar as the problem grows. Speedups over FORTRAN reached 3.92×, somewhat higher than in the 6-node experiment. At 2.28 km, the measured throughput was 0.11 simulated years per day. Throughput expresses how far the calculation advances in simulated time for a day of execution. It is meaningful alongside the grid spacing because the amount of simulated atmosphere represented by a day of computation depends on the problem being solved.
On JUWELS Booster, the authors recompiled the same source for NVIDIA Tesla A100 GPUs. That run used 54 ranks across 14 nodes and took 1.93 seconds per timestep. The paper reports that as 2.42× faster than the Piz Daint result used for the comparison and gives 2.83× as the A100-to-P100 memory bandwidth factor. The JUWELS configuration places multiple GPUs on a node, unlike the Piz Daint arrangement. The direct evidence is that the source ran on the newer GPU system after recompilation and delivered the stated timestep time without a further tuning cycle.
Source size and engineering effort
The full Python dynamical core counted 12,450 lines, against 29,458 for the FORTRAN code. The finite-volume transport module counted 686 lines in Python and 858 in FORTRAN. The Riemann solver module counted 253 in Python and 267 in FORTRAN. The authors report 0.42× the original source length across the core. The module counts also show that the reduction was uneven, so the full-core figure should not be treated as a typical reduction for an individual routine.
Porting took approximately two person-years, including initialization, driver code and testing. After the implementation was validated, the optimization campaign took place over a six week period with four developers, including development of the tooling. The authors report that most of the individual optimization changes took days once the analysis and tuning tools and their search spaces were ready. These measurements give the source comparison context. The project reduced the volume of application code and created a reusable tuning workflow, while making a substantial initial investment in the port and the compiler infrastructure.
What the ablations show
What can be inferred from the optimization sequence
The paper has no factorial ablation of the full pipeline. Its evidence comes from successive compiler changes, targeted before-and-after measurements and comparisons across domain sizes. The sequence on 6 nodes is especially helpful because it includes the default compiled GPU implementation. The change from that starting point to the local scheduling heuristics is much larger than the subsequent adjustments. This shows that getting the general iteration and thread layout right was a high-value decision for the workload. The later gains depend on that starting point.
Local caching, power specialization, region handling and transfer tuning alter different aspects of a run. Their reported effects belong to the configuration in place when the change was made. In particular, a fusion that changes the lifetime of a value can also change the opportunity to cache it. A region split can make a later pruning pass easier to exploit. The optimization history shows how well the authors progressed through those decisions. It leaves open how much each individual transformation would contribute if applied first or combined with a different schedule.
The local alignment experiment isolates a narrower question. With the chosen field layout, pre-padding aligns the first interior element and yielded up to 20 µs (∼5%) improvement on the tested stencil. That result concerns the tested stencil and its accesses. It supports aligning the part of the field that the actual computation visits, especially when matching thread order to contiguous memory. It does not assign the same improvement to every field or to the full timestep.
Region pruning exposes idle parallel work
The first performance reports highlighted several corner kernels whose runtimes looked poor against the amount of data they accessed. A corner update in the paper uses an offset from the start of each horizontal dimension. At the selected corner the calculation itself is small.
q = sw_mult × q_corner[0, 1, 0]
Here q is the field assigned by the corner update, and sw_mult is its multiplier. q_corner is the field read by the update. The bracketed values are relative offsets along the first horizontal, second horizontal and vertical dimensions. The 1 moves the access along the second horizontal dimension, while the 0 entries keep the first horizontal and vertical coordinates fixed. The product is evaluated only over the restricted region specified for the assignment.
The problem was the difference between the region where the assignment mattered and the range over which the generated computation launched threads. A full launch could assign work across the domain even when few positions could execute the corner assignment. Some ranks did not own the corner at all. Giving those ranks the same broad launch produced idle threads without producing more useful results.
The authors built a DaCe transformation that detects the pattern, removes statements that do not apply to the rank and makes the remaining kernels cover a smaller range. The paper reports that many edge and corner kernels then ran about twice as fast, while still falling short of full GPU memory bandwidth. The suspected reason for that remaining gap is the small amount of data involved. This case shows how to interpret a bandwidth comparison for small regions. It helps locate waste, but even a well-targeted launch can have too little work to achieve the streaming rate of a large copy.
The distributed decomposition matters to that conclusion. The 6-node optimization case puts a whole face on each node, so each node handles both its face interior and the special work on its edges and corners. A finer partition assigns different parts of that work to different ranks. Pruning uses the rank’s position precisely because the share of useful work changes across the decomposition. The case illustrates the value of keeping both the grid geometry and the distribution visible to the compiler.
A bandwidth estimate can reveal an arithmetic bottleneck
The Smagorinsky diffusion stencil was another early outlier. The data-access pattern offered no apparent explanation for its high cost, and the scientific expression looked compact. Its update uses a power of the sum of squared terms.
vort = dt × (delpc²·⁰ + vort²·⁰)⁰·⁵
Here vort on the left is the updated value, while vort on the right is its value before the update. dt is the time-step factor, and delpc is the other input quantity in the diffusion expression. The superscripts ²·⁰ and ⁰·⁵ denote the powers written in the stencil as 2.0 and 0.5. The parentheses group the squared terms, and the outer power takes the square root of their sum before multiplication by dt.
Inspection of the generated code showed calls to general-purpose power routines. The authors implemented a rewrite for integer powers and the square-root case, using multiplication for the former and a square-root operation for the latter. The measured kernel time went from 511.16 µs to 129.02 µs. After the rewrite, the paper’s estimate put the kernel at 99.68% utilization of the reference bandwidth. Other kernels also benefited, and the overall speedup attributed to the power transformation was 1.81% per timestep.
The bandwidth report was useful here because it showed that an apparently ordinary stencil took much longer than its array accesses would suggest. The source of the gap was arithmetic code generation. The before-and-after timing supports that diagnosis for the measured kernel, while the smaller whole-step gain reflects how much of a timestep the affected arithmetic accounts for. The authors also report that after further tuning, most of the kernels shown in their initial bottleneck analysis were above 60% of peak memory bandwidth by their estimate. That figure describes the highlighted kernels after iteration through the workflow.
What transfer and size comparisons establish
Transfer tuning has a direct comparison at the end of the 6-node optimization sequence. The preceding region-pruned version is the relevant baseline. The performance gain after transfer shows that a configuration search on a repeated transport routine can still find improvements when a globally compiled core has already benefited from good stencil defaults and targeted manual work. The pattern tests at the destination are part of that result. A source match earned a trial, and a local gain determined whether it was kept.
The count of transferred transformations shows the reach of the matches the authors found. The final timestep measurement checks their combined effect through the normal time-stepping path. Together they provide stronger evidence than either a count of accepted transformations or an isolated cutout speedup would provide by itself. They leave unanswered how the result would change with different source routines, a different number of retained configurations, or a search that tries additional matches within each state.
The module comparisons supply a different control by changing the local grid while timing the same numerical routine on each implementation. The vertical solver has ordered work in a column and comparatively little parallel work available at the smallest size. Horizontal transport has enough reuse for the FORTRAN schedule to see very few L3 misses at the target size. As domains grow, the two GPU implementations show a benefit from having more work available, while the CPU timings show the consequences of losing cache locality. These tendencies explain why a single GPU-to-CPU speedup would give a poor account of the individual routines and why the whole-core gain is more informative when read alongside the local measurements.
Limitations
Limits the authors identify
The work covers the nonhydrostatic FV3 dynamical core. Physical parametrization packages are outside the analysis, and the FORTRAN version has options such as hydrostatic execution and nesting that complicate a direct source-length comparison. The reported line counts therefore describe the two codebases as counted in the study. Some of the difference comes from the representation and compiler infrastructure, and some can reflect differences in what the codes support.
The authors also describe restrictions that made static compilation possible. GT4Py does not support the absolute indexing or data-dependent horizontal offsets needed for some expressions in the original code. The team wrote separate variants for some edges and corners and duplicated some routines that differed only by the direction of their horizontal accesses. Certain synchronization points required splitting stencils. In performance-critical Python code, the authors avoided lists that change size dynamically and forms of introspection that alter object state during execution. They also marked loop unrolling explicitly where necessary to control the size of the generated program. These are costs of the implemented compilation approach that can affect how future numerical changes are expressed.
The bandwidth analysis is deliberately approximate. It counts access to each field element once and omits a detailed account of the cache hierarchy. The paper also describes comparing the maximum reported runtime and the largest configuration in the analysis view, which can summarize an operation that executes under several conditions. These estimates are suited to ranking and investigating kernel types. Their reported utilization percentages should be understood relative to that method, especially for small, irregular or arithmetic-heavy computations.
Portability has a measured part and an estimated part. Recompilation and execution on the A100 system were demonstrated. The authors expect other GPU architectures to require retuning because characteristics such as the number of threads grouped for execution can differ. They anticipate additional optimization work for CPUs, where different cache behavior and instruction sets can make schedules inherited from the GPU effort unsuitable. A target without an existing code generator can require backend development. The paper’s broader portability estimates describe expected effort beyond the hardware measurements.
Limits of the experimental comparisons
The primary baseline compares an optimized multicore implementation with a GPU implementation on the same supercomputer. The measured speedups include the change in processor, the organization of the program, the compiled data layout and the tuning decisions. The comparison answers how much faster the authors’ end-to-end alternative ran than the production CPU baseline under the stated conditions. Isolating the cost of the source language or the independent effect of global compilation would require additional matched configurations.
The weak-scaling runs increase global resolution as the node count rises, with local work held similar. They establish how that particular scaling path behaves. A strong-scaling study would start with a fixed global domain and divide it among increasing numbers of nodes. That would change the amount of work per rank and the relative cost of halo exchanges. The paper’s large-scale measurements do not determine where those strong-scaling tradeoffs would become limiting. The 6-node run has its own role as a stable optimization case with full-face ownership and does not reproduce all features of the larger decompositions.
The timing workload starts from an analytic perturbation with a visually checkable evolution. Stored FORTRAN inputs and outputs provide an additional numerical reference for individual modules. Neither comparison provides quantitative evidence about forecast skill or long climate integrations. The paper demonstrates that the port can be tested against the reference implementation and run at the stated resolution and speed. Assessing the scientific consequences of running complete configurations would require evidence on the resulting forecasts or climatology as well as execution time.
The evidence for transfer tuning comes from recurring patterns in one dynamical core. Stencil names are part of the matching scheme, so the transfer benefits depend partly on how the application reuses those stencils. The candidate count describes the size of a larger search space, and the measured search shows that the pruned search is feasible in FV3. Without an exhaustive result for the full graph, there is no measurement of how close the transferred configuration came to the best global configuration. Testing a match locally also leaves the full-run effect to the final integrated benchmark.
Finally, productivity is assessed through the recorded porting effort, the optimization campaign and source length. Those quantities are meaningful for understanding what the authors built and how much work it took. They do not measure how quickly another team could port a different solver, how many errors a later maintainer might make, or how long a scientific modification would take from implementation through validation. The most concrete productivity evidence is the supported workflow itself, including independent module tests and the ability to carry out the reported performance changes in the compilation toolchain.
What came after
There are no documented follow-up studies here that establish how later researchers used this FV3 implementation, extended transfer tuning or reproduced the workflow on a different atmospheric solver.
Cite
Cite as Tal Ben-Nun, Linus Groner, Florian Deconinck, Tobias Wicky, Eddie Davis, Johann Dahm, Oliver D. Elbert, Rhea George, Jeremy McGibbon, Lukas Trumper, Elynn Wu, Oliver Fuhrer, Thomas Schulthess and Torsten Hoefler. 2022. Productive Performance Engineering for Weather and Climate Modeling with Python. arXiv:2205.04148.
@misc{bennun2022productive,
title = {{Productive Performance Engineering for Weather and Climate Modeling with Python}},
author = {Tal Ben-Nun, Linus Groner, Florian Deconinck, Tobias Wicky, Eddie Davis, Johann Dahm, Oliver D. Elbert, Rhea George, Jeremy McGibbon, Lukas Trumper, Elynn Wu, Oliver Fuhrer, Thomas Schulthess and Torsten Hoefler},
year = {2022},
doi = {10.48550/arxiv.2205.04148},
eprint = {2205.04148},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.2205.04148}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/ben-2022-nun-productive-performance-engineering-weather-climate/