Skip to content

docs[next]: add a shallow water model example - #3038

Merged
havogt merged 194 commits into
GridTools:mainfrom
havogt:swm-jit-backends
Nov 24, 2026
Merged

havogt merged 194 commits into
GridTools:mainfrom
havogt:swm-jit-backends

Conversation

@havogt

@havogt havogt commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Adds the NCAR SWM shallow water benchmark as a gt4py.next example in examples/swm/, running on every backend: gtfn and dace on CPU and GPU, and, with the experimental backends, embedded on NumPy, CuPy, JAX and torch, under jax.jit and under torch.compile.

The model is doubly periodic on an Arakawa C-grid, leapfrog with a Robert-Asselin filter, integrated by one fused field operator producing all six updated fields. The halo is refreshed outside the field operator, by field assignment.

A backend is selected by name plus, for JAX and torch, a device, e.g. backend, device = gtx_experimental.torch_compile, CUDA; the backend also allocates the fields.

Validation

  • every run: 100 steps against swm_numpy, and the full 4000 steps against the NCAR reference.
  • the differences are written as in swm_numpy, so embedded_numpy, embedded_cupy and gtfn_cpu match it bit-for-bit. The other backends agree to rounding (compilers reorder or fuse operations); the tolerances are absolute, 3e-12 for u, v and 1e-9 for p.

Performance comparison

Opt-in (RUN_PERFORMANCE_COMPARISON = True): every installed backend is validated, then timed on grid sizes 64 to 4096. Five warm-up steps run first (compilation, and the first step's different scalars), then five blocks of 20 steps without the halo refresh, so that steps run back to back. It reports the median time per step and the first step separately, as a table, a log-log plot and swm_timings.json.

havogt added 30 commits August 5, 2026 12:52
Port the NCAR/SWM shallow water benchmark to a single gt4py.next notebook,
alongside a NumPy reference and the 16x16 reference state after the full
4000-step run. Periodicity is applied outside GT4Py for now, which keeps the
example free of any src/ changes.
The scheme is verified against Sadourny (1975) Eq. 4 -- cu, cv, h, z are his
U, V, H and eta term for term. The constants are not from the paper, and the
'Swarztrauber 1984' attribution came from a code comment in NCAR/SWM rather
than from any reference, so point at the benchmark repo instead.
A skip entry wrapped around to a real element of the buffer, which is
masked later but still receives a cotangent under jax.grad.

Claude-Session: https://claude.ai/code/session_013m5PzT4FxbaKPxfXqiQLr5
A reduction after a narrowing premap broadcast the full table against the
narrowed field. The mask now uses the connectivity's own skip value.

Claude-Session: https://claude.ai/code/session_013m5PzT4FxbaKPxfXqiQLr5
The neighbor table travels as the traced child, so it is a runtime
argument of the compiled program rather than an inlined constant. The
aux data carries a handle to the same buffer, compared by identity, through
which `inverse_image` reads the concrete table at trace time, so domain
inference narrows under `jax.jit` exactly as it does eagerly.

`inverse_image` also answers covering image ranges from eagerly computed
table bounds instead of scanning the table.

Claude-Session: https://claude.ai/code/session_013m5PzT4FxbaKPxfXqiQLr5
… bounds on write

Also reuse the gather's index-array layout for the reduction mask, which
handles transposed table dimensions, sanitise skip indices before the
broadcast, and treat an empty table as an empty image.
…ax trace

Restricting a concrete jax connectivity inside jax.jit (e.g. for
field(E2C2V[0])) produced a traced buffer, so the later domain inference
on it failed with a ConcretizationTypeError. Slice concrete tables with
jax.ensure_compile_time_eval.
A connectivity whose table is computed inside a jax trace (e.g. from
as_offset) has no concrete values for domain inference. Assume all its
targets lie in the field and clip the gather indices, so out-of-range
targets read the boundary value. Eager execution is unchanged.
jax.jit does not need it: domain inference already reads concrete tables
through `_hyperslice`. On tables with skip values computing the bounds costs
more than a covering scan, and under jit they are recomputed per trace.
…ivity base class

The jax connectivity overrides `inverse_image` instead of an `_image_slices`
indirection, and adjusts gather indices through a `_gather_index` hook, so
shared code no longer knows about values computed in a trace. Test the clamp
on negative targets: positive ones are already clamped by jax indexing.
It is an implementation detail of premap: nothing outside the embedded
implementations calls it.
All callers pass a UnitRange, so the NamedRange branch and its dimension check
were unreachable.
- Drop the cache in FieldOffset.as_connectivity_field: it returned its input,
  and kept traced connectivities alive after the trace.
- Align the table for skip masks without broadcasting, so reductions work on
  fields with an infinite range again.
- Keep as_offset of concrete offsets concrete under a trace, so jit narrows
  like eager. Allow subclasses to override a registered builtin for this.
- Cover the f89 fix with a narrowing case, custom skip values, non-zero domain
  starts and nested jit, and fix the check that a table is not inlined.
…ssert in the inverse-image test

Also state in the ADR that writing into a connectivity buffer through
`.ndarray` is not supported.
…via ArrayOps

NdArrayField and NdArrayConnectivityField no longer carry the array
namespace as a class variable. Each field takes its array operations from
an 'ArrayOps' object resolved from the type of its buffer: the namespace
array_api_compat returns for the buffer selects a registered ArrayOps
subclass, or the default one, which is written against the Array API
standard only.

The per-library field classes (NumPyArrayField, CuPyArrayField,
JaxArrayField and their connectivity counterparts) are removed; NumPy,
CuPy and JAX differ only in NumPyOps, CuPyOps and JaxOps (gamma, scalar
operands, item assignment for JAX, conversion to NumPy). 'common._field'
and 'common._connectivity' construct an NdArrayField from any Array API
object instead of a per-type registration.

'NdArrayField.array_ns' stays the library's own module (numpy, cupy,
jax.numpy). An ArrayOps can replace a whole fbuiltins implementation via
'builtin_overrides'.
array-api-strict is added to the namespace matrix of the embedded unit
tests, which shows that NdArrayField uses only the Array API standard.
Test inputs are built with each namespace's own dtype objects. The
non-standard builtins fmod, cbrt and gamma raise NotImplementedError on
strict.

The constructors read the dtype of the given array through ArrayOps and
test for skip values with the namespace's 'any' instead of the NumPy
method.
torch tensors work through array_api_compat with one ArrayOps subclass
and no field class: scalar operands of elementwise functions become 0-d
tensors (Python floats as float64, as NumPy promotes them), cbrt and
gamma have torch implementations, assigned values become tensors and
conversion to NumPy detaches and copies to the host. The embedded unit
tests run on torch when it is installed.
…orch_compile backends

The explicit jax.jit / torch.compile wrappers and the Target.jit field are
replaced by gtx_experimental.jax_jit and gtx_experimental.torch_compile.
These write out= in place like any backend, so Model calls the field
operator directly again instead of returning and rebinding the fields.
(f(I + 1) - f) / dx instead of (1.0 / dx) * (f(I + 1) - f), as swm_numpy
does. The validation comment no longer claims a different summation
order; the remaining differences come from compilers reordering or fusing
operations.
… with eager backends for numpy, cupy, jax and torch; the jit backends override its wrap
With the embedded and embedded-jit backends of GridTools#3027 as their own
allocators, every selection is a backend plus, for torch, a device. The
Target dataclass is gone; Model, run and the validation take backend= and
device=.
…bind named-collection arguments, check static_params; backend allocators can be array namespaces (review)
…c_params, lazy creation; one compile test for all
@havogt

havogt commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Written by an agent on behalf of @havogt

Comment thread examples/swm/swm.ipynb
Comment on lines +326 to +381
"class Model:\n",
" def __init__(\n",
" self,\n",
" m: int = M,\n",
" n: int = N,\n",
" *,\n",
" backend: next_backend.Backend,\n",
" device: core_defs.Device | None = None,\n",
" ):\n",
" self.m, self.n = m, n\n",
" self.domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n",
" self.interior = gtx.domain({I: (0, m), J: (0, n)})\n",
" self.step = timestep.with_backend(backend)\n",
" self.cycle = 0\n",
"\n",
" def as_halo_field(a: np.ndarray) -> gtx.Field:\n",
" return gtx.as_field(\n",
" self.domain, np.pad(a, 1, mode=\"wrap\"), allocator=backend, device=device\n",
" )\n",
"\n",
" u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n",
" self.u, self.v, self.p = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n",
" self.uold, self.vold, self.pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n",
" # A valid halo in every buffer keeps `p` nonzero there when the refresh is skipped.\n",
" self.unew, self.vnew, self.pnew = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n",
"\n",
" def advance(self, cycles: int, periodic: bool = True) -> None:\n",
" \"\"\"Integrate `cycles` more steps.\"\"\"\n",
" for _ in range(cycles):\n",
" tdt = DT if self.cycle == 0 else 2.0 * DT\n",
" alpha = 0.0 if self.cycle == 0 else ALPHA\n",
"\n",
" self.step(\n",
" self.u,\n",
" self.v,\n",
" self.p,\n",
" self.uold,\n",
" self.vold,\n",
" self.pold,\n",
" DX,\n",
" DY,\n",
" tdt,\n",
" alpha,\n",
" out=(self.unew, self.vnew, self.pnew, self.uold, self.vold, self.pold),\n",
" domain=self.interior,\n",
" offset_provider={},\n",
" )\n",
"\n",
" if periodic:\n",
" for field in (self.unew, self.vnew, self.pnew):\n",
" apply_periodic(field, self.m, self.n)\n",
"\n",
" self.u, self.unew = self.unew, self.u\n",
" self.v, self.vnew = self.vnew, self.v\n",
" self.p, self.pnew = self.pnew, self.p\n",
" self.cycle += 1\n",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test coverage

The notebook introduces real logic — the halo refresh in apply_periodic (whose
corner handling depends on copy order and full-extent strips), the swap and
in-place Robert-Asselin filter scheme in Model.advance, and the backend/device
selection in comparison_backends — none of which is covered by a test under
tests/next_tests/, contrary to the repo's "tests are the spec" rule. Since the
validation only runs when a human executes the notebook, is a CI smoke test
(e.g., a stripped script running ~100 steps on one backend, or notebook execution)
planned so regressions here fail loudly?

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
✅ Merge recommendation: Needs review
🔎 Failure modes

What: The example rots silently. The notebook depends on experimental APIs (`gt4py.next.experimental` backends, `gt4py._core.definitions`, in-place `out=` aliasing of `uold`/`vold`/`pold`, and domain-slice field assignment that must work even for immutable JAX buffers), and none of this is executed by CI. A future refactor of those internals breaks every cell of the notebook with no signal.
Where: examples/swm/swm.ipynb:Model.advance / apply_periodic
Trigger: Any later change to the experimental backend API or Field assignment semantics.
Detected by: nothing
Covered in this PR: No

What: Reference validation fails for every backend if the committed binary does not match what the notebook expects. `swm_reference.npz` could not be read during review, so the array names (`u`, `v`, `p`), shapes (presumably (17, 17) after `to_reference_layout`), and dtype are unverified, as is the claim that it is the NCAR/SWM 16x16 state after 4000 steps.
Where: examples/swm/swm.ipynb:test_matches_reference
Trigger: Running the notebook's NCAR-reference cell, which the PR description says executes on every run.
Detected by: KeyError, shape-mismatch, or assert_allclose failure raised in that cell.
Covered in this PR: No

What: cwd-dependent file access: `import swm_numpy` and `np.load("swm_reference.npz")` resolve against the kernel's working directory, so executing the notebook from anywhere other than `examples/swm` (e.g., a CI runner or papermill invoked from the repo root) fails in the first cells.
Where: examples/swm/swm.ipynb:imports / test_matches_reference
Trigger: Kernel working directory is not `examples/swm`.
Detected by: ImportError / FileNotFoundError at cell execution.
Covered in this PR: No

🏅 Score: 85
🧪 No relevant tests
🔒 No security concerns identified
🔀 No multiple PR themes
⚡ Recommended focus areas for review

Unreviewable binary
The reference data file could not be fetched, so nothing in it was reviewed: the
array names, shapes, dtype, and numerical content are unverified, and every run of
the example validates against it. Verify manually before merge that it contains
u, v, p of the expected layout produced by to_reference_layout (float64,
(M+1, N+1)) and that the Apache-2.0 provenance note in the README is sufficient for
committing NCAR/SWM data into this BSD-3-Clause repo.


⚙️ Agent run details
  • Model: openai/zai-org/GLM-5.3-Flash
  • Tokens: 19,712 in / 22,701 out / 42,413 total
  • Time cost: 176.2s
  • AI calls: 1

@egparedes egparedes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@havogt
havogt merged commit c56efff into GridTools:main Nov 24, 2026
18 checks passed
havogt added a commit that referenced this pull request Nov 24, 2026
Port of the periodicity change to the example as merged in #3038: a
make_periodic field operator with runtime shifts f(I + m), a program with
per-output domains, m and n as static parameters so that the jit backends
can shift by them, and no halo refresh on the host. The comparison now
times complete steps. The top-level copies of the example from #2749 are
removed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants