Repository navigation
docs[next]: add a shallow water model example - #3038
Conversation
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.
…ient limit in the ADR
…ssert in the inverse-image test Also state in the ADR that writing into a connectivity buffer through `.ndarray` is not supported.
Also date the ADR to the current state.
…with a no-wrap gather
…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.
… field set in __post_init__ (review)
…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
…ation, no compile
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)
…200 next internal cuda13 jobs
…c_params, lazy creation; one compile test for all
… overhead real models hide (review)
|
🤖 Written by an agent on behalf of @havogt |
| "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", |
There was a problem hiding this comment.
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?
PR Reviewer Guide 🔍Here are some key observations to aid the review process:
⚙️ Agent run details
|
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.
Adds the NCAR SWM shallow water benchmark as a
gt4py.nextexample inexamples/swm/, running on every backend:gtfnanddaceon CPU and GPU, and, with the experimental backends, embedded on NumPy, CuPy, JAX and torch, underjax.jitand undertorch.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
swm_numpy, and the full 4000 steps against the NCAR reference.swm_numpy, soembedded_numpy,embedded_cupyandgtfn_cpumatch it bit-for-bit. The other backends agree to rounding (compilers reorder or fuse operations); the tolerances are absolute,3e-12foru,vand1e-9forp.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 andswm_timings.json.