Which context, which stage, which map: where does each piece of code run?
GeoStack · background · the role ladder · where code runs
Abstract¶
The role ladder says how big a piece is, from a structure to a recipe. Three tiers then say where it runs (its execution context), which job it does in the pipeline (its stage), and, for the pieces that compute, what kind of map it is (its map properties). One data-assimilation window over the North Atlantic carries every section.
Three tiers¶
The tiers nest. Every piece of code has an execution context. Every pipeline step is one stage, and its context follows from it. Only the apply stage computes values, so only what runs there carries map properties. The role ladder cuts across all three; it has its own section.
Each stage is coloured by its execution context, as in the role ladder’s figures: blue is host I/O, amber setup, teal apply and violet parallelism, so Split and Combine are parallelism. Fit and plan are Apply’s setup. Tier 3 applies only to the ringed Apply stage, where values are computed.
The running example¶
Indices: runs over output cells or entries, over input cells, over members, over patches. Distances are great-circle distances in km.
Table 2:The symbols used on this page.
| Symbol | Variable role | Shape | Unit |
|---|---|---|---|
| state · , , on the model grid | , (field, y, x) | m, m s⁻¹ | |
| in · background state, from GLORYS | m, m s⁻¹ | ||
| in · observations, nadir and SWOT | , (obs,) | m | |
| const · observation operator, read at each observation | — | ||
| · observation-error covariance | m² | ||
| a map, its left inverse, its right inverse | , | — | |
| a linear operator | — | ||
| const · restriction (fine to coarse), prolongation (coarse to fine) | , | — | |
| · reach of an operator | cells | ||
| const · Gaspari–Cohn taper, , zero beyond | km → — |
Here is the length of the state, the number of observations in the window, and , the cell counts of a fine and a coarse grid.
1 · Execution contexts: where code runs¶
The first tier has four contexts. Each fixes a library, a precision and one rule about tracing, so it decides most of the engineering before a line is written. Host I/O and setup feed one compiled apply; the parallelism layer runs that apply many times.
The parallelism layer wraps the apply: it never needs a second implementation of the kernel.
Table 3:The four execution contexts: what goes in and out, in the window, and what each optimises.
| Context | In → Out | In the window | Shape · unit | Optimises |
|---|---|---|---|---|
| Host I/O · bytes ↔ carriers, per file or request, often async | files, objects, API responses → carriers | GLORYS Zarr, GEBCO NetCDF, nadir and SWOT L3 files in the window | (file,) · bytes | latency and bandwidth: concurrency, retries, prefetch. Never traced; precision as stored on disk. Lives in geocatalog, geocloud, geoproducts, xrtoolz-products. |
| Setup · geometry and data → constants, once per grid, grid pair or fit | grids, positions, training data → weights, indices, masks, statistics | remap weights GLORYS → model, the land mask, each observation’s four cells and hour | (target, k) · — | amortisation: built once, cached per grid, shipped to workers. Float64, concrete values only; a traced input raises. |
Apply · carriers → carriers, every call, under jit | state, observations, setup constants → tendencies, , analyses | the model step, , the cost and its gradient, the local solves | (member, field, y, x) · m, m s⁻¹ | FLOPs fused into one compiled call, and a busy device. Written in xp, so it runs eagerly on NumPy and compiled on JAX; computes in the data’s dtype. |
| Parallelism · one kernel → many pieces, over members, patches, chunks, files, devices | a kernel and its pieces → the pieces’ results | 32 members, 300 patches, 240 frames, many files | (piece, …) · — | throughput: fixed shapes, one transfer per batch, no oversubscribed threads. The tool follows the scope and the communication (section 4). |
2 · Pipeline stages: what a job is for¶
The second tier names the job a step does in the pipeline. There are ten stages in three acts, defined on the geo pipeline page, plus two that cut across all of them: orchestrate (decides what runs when, and resumes after a failure) and observe (logs, metrics, QC taps). Each stage optimises one thing, and its tools are chosen for that one thing. Fit and plan, which build Apply’s constants from data and from grids, have no stage of their own among the ten: they are Apply’s setup, run once before the first patch is applied, as the pipeline page fits a scene-wide statistic first and then applies it per patch.
Findno pixel is decoded
searcha question → file namesnames, not data
catalogfiles → table of footprints; table, window → rowsoptimises: one scan, many queries; no bytes read
saverows → local copiesoptimises: download once
Computesplit → apply → combine, on a lazy field
streamfiles, window → carrieroptimises: only the window’s bytes
splitcarrier → patches with halosoptimises: equal pieces, small halo
Apply’s setup, once, before the first call
fitdata → statistics optimises: fit once, reuse
plangrids → weights, indicesoptimises: geometry once per grid
applybatch, , plan → outputsoptimises: fused FLOPs
combinetiles, weights → fieldoptimises: no seams
Keepa file, a version, a record
writefield → COG, Zarr chunksoptimises: aligned chunks
commitchunks → one versionoptimises: all or nothing
publishversion → catalog recordoptimises: findable by the next run
orchestrate · observe — across every stage
The ten stages in three acts, top to bottom. Colour is the execution context (blue host I/O, amber setup, teal apply, violet parallelism); fit and plan are drawn as Apply’s setup. Each act has a figure of its own below.
2.1 Act 1 · Find: search, catalog, save¶
Finding answers “which files touch my window and time?” without reading a pixel. Search asks the archive what it holds and gets names back, not data. Catalog scans the archive once into a table of footprints and times (its index), then intersects that table with the window (its query). For the North Atlantic box this turns a full archive into the handful of GLORYS days, one GEBCO tile and the altimetry passes that cross it.
Save moves bytes, so its cost is latency and bandwidth, not FLOPs: it copies the rows’ files into a local cache once, with many downloads in flight. All three stages of the act are host I/O: threads or async, never JAX.
Table 4:The Find stages: what each takes and gives, what it optimises, and the tool.
| Stage | In → Out | Optimises | Tool |
|---|---|---|---|
| search | a question → file names | names, not data | a folder listing; STAC or CMR in production |
| catalog, its index | files → table (file,) | one scan amortised over every later query | geocatalog.build |
| catalog, its query | table, GeoSlice → rows | no bytes read; spatial index, not a loop | geocatalog.query |
| save | rows → local files | download once; parallel requests | geocatalog.stage(LocalCache, parallel=8) |
2.2 Act 2 · Compute: stream, split, apply, combine¶
The second act turns the saved files into one carrier, cuts it into pieces, computes on each piece and stitches the results back.
Stream¶
Stream decodes only the window’s byte ranges into a carrier. It is still host I/O, like save: threads or async, never JAX.
Table 5:The Stream stage.
| Stage | In → Out | Optimises | Tool |
|---|---|---|---|
| stream | files, window → GeoArray["band y x"] | bytes read window, not file | CogField, prefetch_iterable, product readers |
Split¶
Split turns one big field into many equal pieces with a halo of reach around each, so a local operator can run on a piece alone. Equal shapes matter more than equal areas: one compiled kernel, no retracing. The halo is the price, and it is paid in every piece.
corehalo
split
(patch, y, x)fixed shape
Table 6:The Split stage.
| Stage | In → Out | Optimises | Tool |
|---|---|---|---|
| split | field → (patch, y, x) + positions | equal shapes, smallest halo that covers | SpatialPatcher, SphericalCap, batch_split |
Apply, and its setup¶
Apply reads constants many times, and building them is its setup. Fit learns statistics from data (a mean, a scale, a climatology, a background covariance) and stores them with a trailing underscore. Plan builds geometry from grids alone (remap weights, the four cells and hour of each observation, a mask). Both run once, on concrete values, in float64.
data
fit
(once)
fine grid
plan
coarse grid
weights (target, k) and indices (target, k): no field values needed
Apply is the only stage that does the science. It takes a batch, and the plan, and is one jitted function vmapped over the batch axis. Everything before it exists so that this call has fixed shapes, constants already built and data already on the device.
batch
, planjit(vmap(f))
outputs
What an apply does to its input is the third tier, map properties; how big the pieces inside it are is the role ladder, rungs ⓪ to ④.
Table 7:Apply’s setup: fit and plan.
| Stage | In → Out | Optimises | Tool |
|---|---|---|---|
| apply, setup: fit | data → , stored with a trailing underscore | fit once, without races | fit_once, fit(x) -> self |
| apply, setup: plan | source grid, target grid → (target, k) | geometry once per grid pair, cached | Reproject(engine="interp"), the interp plans |
Combine¶
Combine undoes split. Each pixel is covered by several patches, and its value is their weighted mean, so the seams vanish. With weights that taper to zero at a patch edge,
where runs over the patches that cover pixel , is patch ’s value there, in the field’s unit, and its weight, dimensionless. An inverse-variance weight , with the analysis-error variance of a patch at the pixel, makes (1) the minimum-variance merge of the analyses.
overlap:
combine
one field, no seams
Table 8:The Combine stage.
| Stage | In → Out | Optimises | Tool |
|---|---|---|---|
| combine | (patch, y, x), weights → (y, x) | no seams; streaming, bounded memory | OverlapAdd, InvVarWeightedMean, max_in_flight |
2.3 Act 3 · Keep: write, commit, publish¶
Keeping is host I/O again. Write lays the field into chunks that match how it will be read; commit makes the chunks of one run a single version, visible all at once or not at all; publish adds a record to a catalog, so the next run’s query finds it. That closes the loop back to Find.
Table 9:The Keep stages.
| Stage | In → Out | Optimises | Tool |
|---|---|---|---|
| write | field → chunks | chunks aligned with patches and reads | write_cog, WriteCOG, Zarr |
| commit | chunks → version | atomic: no half-written run is ever read | PatchJournal; Icechunk (proposed) |
| publish | version → record | findable by the next query | product catalog (proposed) |
3 · Map properties: what an apply does to its input¶
Inside apply, every operator sits at one point on three independent axes. Map kind says whether information is kept (can we invert it?). Locality says which inputs each output reads (how can we parallelise it?). Linearity says whether it has an adjoint (can we take its gradient cheaply and test it?). Here is the input space, the output space, and , .
3.1 Map kind: what is kept¶
bijectionone-to-one, onto · exists
injectionnothing lost · some outputs unhit
surjectionevery output hit · inputs merge
lossy (neither)merges and misses · no inverse
Hollow rings mark outputs no input reaches. A merge (two arrows into one dot) is information lost.
Table 10:The four map kinds, with stack examples and what each buys.
| Kind | Stack examples | What it buys |
|---|---|---|
| bijection | standardise with fitted ; a flow layer; a change of variables | exact inverse; density transform |
| injection | embed, pad, prolongation , stack | a left inverse (select, crop, ) |
| surjection | select, crop, restriction , , a band mean | a right inverse; the reason DA is ill-posed |
| lossy | thresholds, masks with a fill, clipping, a quantiser | nothing to undo; keep it last or log what it drops |
3.2 Locality: which inputs each output reads¶
Locality is the sparsity of the Jacobian. Output depends on input only when the two are within reach :
where is the distance between the output’s and the input’s positions, in cells or km. Small means small halos and free parallelism; as big as the domain means one piece, or communication.
pointwise
along a dim across, along
stencil cell
regrid block = coarse cell
gatherpoint ← 4 cells
scatterpoints → a cell
global = domain
output inputs read observation
reach grows → halo grows → parallelism costs morepointwise stencil regrid local solve globalvmap anything halo, then vmap patches one device, or exchange
Locality in time follows the same pattern: a step reads its predecessor ( step), so time is sequential unless the frames are independent (a pointwise climatology, a per-frame ).
Table 11:Locality classes, an example of each, the parallel tool it calls for, and what it does to the Coupling.
| Locality | Example | Parallel tool | Coupling effect |
|---|---|---|---|
| pointwise | standardise, index, threshold | vmap, any chunking | keep |
| along a dim | a band mean, a vertical mode, a time mean | chunk the other dims | reduce, mix |
| stencil | gradient, Laplacian, advection | halo of , then patches | keep (+ halo) |
| regrid | , , reproject | chunk the target, read the footprint | regrid |
| gather | : obs ← 4 cells | vmap over observations | select |
| scatter | , binning points to cells | segment_sum, not a loop | expand |
| global | a Poisson solve, a full-domain EOF | one device, or MPI exchange | mix |
3.3 Linearity: is there an adjoint?¶
A linear operator satisfies for scalars . It has an adjoint , defined by the dot-product identity:
where and are the inner products of the input and output spaces, each a scalar. The identity is also the test: draw random , , compare both sides of (9), and a hand-written adjoint either matches to rounding or is wrong.
state
(forward) (adjoint)
obs
to rounding
The adjoint is what makes a gradient cheap. The observation part of the 3D-Var cost and its gradient are
where is the observation operator, its Jacobian ( when is linear), the observation-error covariance in m², and a dimensionless scalar. One forward and one adjoint call give the whole gradient (11), whatever the size of .
Table 12:The three linearity classes, with examples and what each buys.
| Linearity | Examples | What it buys |
|---|---|---|
| linear | as interpolation, , , a stencil, a remap plan | an adjoint, the dot-product test, CG and lineax solves |
| affine | standardise , a calibration with offset | linear after removing the offset; exact inverse if every entry of is positive |
| nonlinear | the model step, advection with WENO, a neural term | tangent-linear and adjoint by jax.jvp, jax.vjp around a state |
3.4 Ten operators on all three axes¶
Table 13:Ten operators of the window, each placed on the three axes.
| Operator | Map kind | Locality | Linearity |
|---|---|---|---|
| standardise (fitted ) | bijection | pointwise | affine |
select / crop | surjection | pointwise | linear |
embed / pad | injection | pointwise | linear |
| gradient, Laplacian | lossy (constants vanish) | stencil | linear |
| restriction | surjection | regrid | linear |
| prolongation | injection | regrid | linear |
| , bilinear in space and time | surjection | gather | linear |
| model step | bijection (smooth flow, in practice) | stencil, step | nonlinear |
| local ETKF analysis | lossy | local solve, | nonlinear |
| Poisson solve | bijection on zero-mean fields | global | linear |
3.5 One regrid, two contexts¶
Most regrids split into a setup that needs only geometry and an apply that needs only values. Take block-averaging GLORYS onto the model grid, :
Setupaverage_planonce per grid pair · NumPy, float64
In
source and target gridsGLORYS 360 × 480 and model 120 × 160; transforms and CRS onlyGrid, Grid · —
↓
Out · constants for every apply
weights and source indices9 source cells per target cell(target, k), (target, k) · —
Here is the overlap area of target cell and its -th source cell. Concrete values only; cached per grid pair.
Applyaverage_applyevery field, every frame · jit, vmap over time
In
GLORYS fieldone frame of SSH, T or S(y_s, x_s) · m, °C, psu
Constants · from the setup
enter the trace as constants(target, k) · —
↓
Out
on the model grida gather and a weighted sum: linear, regrid-local(y, x) · as input
Its adjoint is the same weights scattered back with segment_sum. The interp plans exist today; the “average” plan is missing.
Here and are the source and target grids, and the plan’s weights (dimensionless) and source-cell indices, both (target, ) with indexing a target cell’s source cells, one GLORYS frame and the same frame on the model grid, in the input’s unit.
4 · Parallel tools: which tool for which piece¶
The parallelism context splits further, by two questions. Scope: where do the pieces live (one kernel, one device, several devices, processes, machines)? Communication: are the pieces independent, or do they exchange a halo every step? Host I/O sits in a band of its own, because waiting on a network is concurrency, not compute.
All rows are parallelism, so all are violet. The two outlined in bold run inside one jit and need no code beyond the apply; the rows below add workers or devices. The right column needs the halo exchange that locality implies. The blue band is host I/O.
Table 14:Five rules for running pieces in parallel.
| Rule | Why |
|---|---|
| Never fork after JAX starts | JAX’s threads do not survive fork; use spawn, or start workers before importing JAX. |
| Budget threads | BLAS × workers × XLA threads oversubscribes the CPU; set one per worker. |
| One accelerator per process | two processes on one GPU fight over its memory. |
Random keys by fold_in | fold_in(key, patch_id) gives each piece the same draw on every rerun and every layout. |
| Ship the setup, not the recipe | send workers the built plan; rebuilding it in each worker repeats the setup once per worker. |
5 · The role ladder: how big a piece is¶
The three tiers say where code runs, which job it does and what map it is; they don’t say how big a piece is. The role ladder does, from a ⓪ structure to a ⑥ recipe, and on this page “role” means a rung and nothing else. It meets the tiers at fixed places (the ladder and the other axes): rungs ⓪ to ④ are the compiled region, where functions and Modules trace under one jit; a ⑤ step is where a carrier is unwrapped and rewrapped; every pipeline stage is a ⑤ step, the stage chain is a ⑥ recipe, and setup, beside the ladder, builds the ③ models’ state. The ocean example’s ladder draws this window’s pieces on every rung, coloured by the context they run in.
6 · Everything in one pipeline¶
The running example, tagged by context and rung. The state has entries, the ensemble members, holds the window’s observations, is the observation operator built from the plan , the observation-error covariance, the localisation taper and the block average to the coarse grid.
# Shapes: N_row = 120, N_col = 160 cells; 3 fields; N_ℰ = 32 members;
# D_y observations; N_patch = 300 patches; N_frame = 240 frames
# Units: SSH m, T °C, S psu; distances km; time s
# ── host I/O · catalog, save · ① primitives, ② strategy ──
# today (geocatalog)
# rows = {files : footprint ∩ window ≠ ∅}
# → (file,) table
rows = geocatalog.query(index, window)
# today (geocatalog)
# → local paths
paths = geocatalog.stage(rows, LocalCache(root), parallel=8)
# ── setup · Apply's plans · builds ③ models (NumPy, float64)
# proposed (average plan)
# w_ik = a_ik / ∑_k' a_ik'
# (y_s, x_s) grid, (y, x) grid → (target, 9) weights, indices
glorys_plan = average_plan(glorys_grid, model_grid)
# today* (geoops)
# y_o ≈ ∑ w x at the 4 cells and 2 hours around each obs
# (obs, 2) positions → (obs, 8) weights, indices
obs_plan = interp_plan(model_grid, obs_lonlat, obs_time)
# ── parallelism · split · ② strategy SphericalCap ───────
# today (geopatcher)
# halo = 2c, the taper cutoff
# (member, field, y, x) → (patch, member, field, y_p, x_p)
patches = batch_split(background_ensemble, SphericalCap(cutoff_km=300))
# ── apply · apply · ④ algorithm under jit(vmap) ─────────
# user
# x̄_t|t = μ_x + X̃ Wₐ (y − H μ_x), with Σ_ε⁻¹ tapered by ρ
# map the patch axis only; every patch gets all D_y observations, and ρ zeroes
# those beyond the cutoff from its centre
# (patch, member, field, y_p, x_p), (obs, 8), (obs,) → (patch, member, field, y_p, x_p)
analysis = jax.jit(jax.vmap(local_etkf, in_axes=(0, None, None)))(
patches, obs_plan, obs_values
)
# ── parallelism · combine ────────────────────────────────
# today (geopatcher)
# x_i = ∑ₚ w_i⁽ᵖ⁾ x_i⁽ᵖ⁾ / ∑ₚ w_i⁽ᵖ⁾
# (patch, member, field, y_p, x_p) → (member, field, y, x)
analysis_field = combine(analysis, OverlapAdd(taper="cosine"))
# ── apply · multiscale · ④ algorithm over a ③ plan ──────
# proposed (average plan)
# x_c = P↓ x
# (member, field, 120, 160) → (member, field, 30, 40)
coarse = jax.vmap(average_apply, in_axes=(0, None))(analysis_field, coarse_plan)
# ── host I/O · write, commit · ① primitive ──────────────
# today (geocloud)
# (field, y, x) → COG
geocloud.cog.write_cog(analysis_mean, out_uri)
# proposed (Icechunk)
# chunks → one version
session.commit("window 2026-11, local ETKF")Program 1:The window tagged by execution context, stage and rung, from the catalog query to the committed analysis.
Read down the comments: the section headers name the execution context, the stage and the rung, the today/proposed markers are the status, and every line between them is one stage. The two lines that do science, local_etkf and average_apply, are the only ④ algorithms and the only ones under jit; wrapped in a ⑤ step each, and chained, they would make the ⑥ recipe DACycle.
7 · Numbers for the running example¶
Table 15:The window’s sizes, by execution context and stage.
| Context · stage | Quantity | Value | Unit |
|---|---|---|---|
| host I/O · stream | GLORYS, 3 fields × 360 × 480 float32, per frame | 2.07 | MB |
| host I/O · save | GEBCO, 7 200 × 9 600 int16, once | 138 | MB |
| setup · plan, for apply | GLORYS → model, taps per cell | 9 | — |
| setup · plan, for apply | GEBCO → model, taps per cell (avoid: reshape-mean) | 3 600 | — |
| apply · state | 3 × 122 × 162 entries with the ghost ring | 59 292 | values |
| apply · ensemble | 57 600 × 32 float32 (no ghosts) | 7.37 | MB |
| parallel · split | patches, each one 32 × 32 eigen-decomposition | 300 | solves |
| parallel · split | per-cell local analysis instead (one per cell) | 19 200 | solves |
| apply · multiscale | coarse grid 30 × 40 | 1 200 | cells |
Sources and status
From the artifact “Roles in the GeoStack” (updated 24 November 2026), which drew on GeoStack’s execution-strategy design doc. Its facts cite no issues or pull requests. The artifact read its names in geotoolz at a8b2f17 (geocatalog, geocloud, geopatcher, geoops Coupling, Reproject, the interp plans), gridax main and pipekit at fdc9fd1 (ThreadMap, ProcessMap, AsyncMap, Tap); its today markers were checked by name in those repos, and they were not checked again against the pins for this page. The “average” plan and Icechunk commits are proposed. Two parts were changed on the way in: the artifact’s role-ladder section is cut to one paragraph, since the role ladder and its ocean example hold it in full, and its twelve pipeline stages in seven phases are replaced by the ten stages in three acts of the geo pipeline page, keeping what each stage optimises and its context. The North Atlantic numbers are illustrative but consistent: every value on this page is computed from the fact sheet at the top. The page has no notebook behind it.