From 9b4f42a04563d09f37b3d5a1595ab6858debaa6e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 5 Aug 2026 12:52:57 +0200 Subject: [PATCH 001/166] docs[next]: add a shallow water model example notebook 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. --- examples/swm.ipynb | 443 +++++++++++++++++++++++++++++++++++++ examples/swm_numpy.py | 164 ++++++++++++++ examples/swm_reference.npz | Bin 0 -> 4785 bytes 3 files changed, 607 insertions(+) create mode 100644 examples/swm.ipynb create mode 100644 examples/swm_numpy.py create mode 100644 examples/swm_reference.npz diff --git a/examples/swm.ipynb b/examples/swm.ipynb new file mode 100644 index 0000000000..33c715dceb --- /dev/null +++ b/examples/swm.ipynb @@ -0,0 +1,443 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "GT4Py - GridTools Framework\n", + "\n", + "Copyright (c) 2014-2024, ETH Zurich\n", + "All rights reserved.\n", + "\n", + "Please, refer to the LICENSE file in the root directory.\n", + "SPDX-License-Identifier: BSD-3-Clause" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Shallow Water Model\n", + "\n", + "A doubly periodic shallow water model on an Arakawa C-grid, integrated with a leapfrog\n", + "scheme and a Robert-Asselin time filter. It is the NCAR\n", + "[SWM](https://github.com/NCAR/SWM) mini-app, a long-standing benchmark for comparing\n", + "programming models, written here as a single `gt4py.next` field operator.\n", + "\n", + "The prognostic equations are\n", + "\n", + "$$\n", + "\\frac{\\partial \\mathbf{V}}{\\partial t} + (\\zeta + f)\\,\\mathbf{k} \\times \\mathbf{V}\n", + " + \\nabla\\left(P + \\tfrac{1}{2}\\mathbf{V}\\cdot\\mathbf{V}\\right) = 0,\n", + "\\qquad\n", + "\\frac{\\partial P}{\\partial t} + \\nabla\\cdot(P\\mathbf{V}) = 0 ,\n", + "$$\n", + "\n", + "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975).\n", + "The four intermediates below are his mass fluxes $U$, $V$, potential vorticity $q$ and\n", + "Bernoulli function $H$, named `cu`, `cv`, `z`, `h` in the benchmark.\n", + "\n", + "**Provenance.** The *scheme* is from Sadourny (1975). The *configuration* --- the grid\n", + "spacing, time step, filter coefficient and initial condition --- is Paul Swarztrauber's\n", + "1984 NCAR benchmark setup, not a result from the paper." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "import gt4py.next as gtx\n", + "\n", + "import swm_numpy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Grid and backend\n", + "\n", + "Fields carry **one halo cell on every side**, so the domain runs from `-1` to `M+1`. All\n", + "three prognostic fields share this one index space; the C-grid staggering is expressed by\n", + "the shifts inside the operators rather than by different array shapes." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "I = gtx.Dimension(\"I\")\n", + "J = gtx.Dimension(\"J\")\n", + "\n", + "IJField = gtx.Field[gtx.Dims[I, J], gtx.float64]\n", + "\n", + "M = swm_numpy.M # 16\n", + "N = swm_numpy.N # 16\n", + "\n", + "DX = swm_numpy.DX # 100 km\n", + "DY = swm_numpy.DY\n", + "DT = swm_numpy.DT # 90 s\n", + "ALPHA = swm_numpy.ALPHA # Robert-Asselin filter coefficient\n", + "\n", + "backend = None\n", + "# backend = gtx.gtfn_cpu\n", + "# backend = gtx.gtfn_gpu" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Differential operators\n", + "\n", + "Each operator comes in two variants that differ only in shift direction. The forward form\n", + "($+1$) maps an unstaggered quantity onto a staggered location, the backward form ($-1$)\n", + "maps back. Which one a term needs is fixed by where its operands live: `p` and `h` sit at\n", + "cell centres, `u` and `cu` on $x$-faces, `v` and `cv` on $y$-faces, and `z` on corners.\n", + "\n", + "Keeping the two variants apart by hand is exactly the bookkeeping that\n", + "[staggered dimensions](../docs/development/ADRs/next/0026-Staggered_Dimensions.md) are\n", + "designed to remove; a follow-up rewrites these eight operators as four." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def avg_x(f: IJField) -> IJField:\n", + " \"\"\"Average onto the next x-face.\"\"\"\n", + " return 0.5 * (f(I + 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_y(f: IJField) -> IJField:\n", + " \"\"\"Average onto the next y-face.\"\"\"\n", + " return 0.5 * (f(J + 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_x_staggered(f: IJField) -> IJField:\n", + " \"\"\"Average an x-staggered field back onto cell centres.\"\"\"\n", + " return 0.5 * (f(I - 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_y_staggered(f: IJField) -> IJField:\n", + " \"\"\"Average a y-staggered field back onto cell centres.\"\"\"\n", + " return 0.5 * (f(J - 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_x(dx: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Forward difference in x.\"\"\"\n", + " return (1.0 / dx) * (f(I + 1) - f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_y(dy: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Forward difference in y.\"\"\"\n", + " return (1.0 / dy) * (f(J + 1) - f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_x_staggered(dx: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Backward difference in x, for an x-staggered field.\"\"\"\n", + " return (1.0 / dx) * (f - f(I - 1))\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_y_staggered(dy: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Backward difference in y, for a y-staggered field.\"\"\"\n", + " return (1.0 / dy) * (f - f(J - 1))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The timestep\n", + "\n", + "One fused field operator produces all six updated fields. The first three are the leapfrog\n", + "update of the prognostic variables; the last three are the time-filtered previous level,\n", + "\n", + "$$ u^{\\text{old}} \\leftarrow u + \\alpha\\,(u^{\\text{new}} - 2u + u^{\\text{old}}) , $$\n", + "\n", + "which suppresses the computational mode of the leapfrog scheme." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def timestep(\n", + " u: IJField,\n", + " v: IJField,\n", + " p: IJField,\n", + " uold: IJField,\n", + " vold: IJField,\n", + " pold: IJField,\n", + " dx: gtx.float64,\n", + " dy: gtx.float64,\n", + " tdt: gtx.float64,\n", + " alpha: gtx.float64,\n", + ") -> tuple[IJField, IJField, IJField, IJField, IJField, IJField]:\n", + " \"\"\"Advance one leapfrog step and return (unew, vnew, pnew, uold, vold, pold).\"\"\"\n", + " cu = avg_x(p) * u\n", + " cv = avg_y(p) * v\n", + " z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p))\n", + " h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v))\n", + "\n", + " unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt\n", + " vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt\n", + " pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt\n", + "\n", + " uold_new = u + alpha * (unew - 2.0 * u + uold)\n", + " vold_new = v + alpha * (vnew - 2.0 * v + vold)\n", + " pold_new = p + alpha * (pnew - 2.0 * p + pold)\n", + "\n", + " return unew, vnew, pnew, uold_new, vold_new, pold_new" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Periodicity\n", + "\n", + "The domain wraps in both directions. Here the halo is refreshed **outside** GT4Py, in\n", + "NumPy, after each step: the operator computes the interior only, and the halo is then\n", + "overwritten with the opposite edge.\n", + "\n", + "Rows are copied before columns, which is what fills the corners correctly.\n", + "\n", + "Expressing the wrap *inside* the field operator instead --- with `concat_where` over a\n", + "domain boundary --- is the subject of a follow-up; it needs shift offsets that are only\n", + "known at compile time rather than when the operator is traced." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def apply_periodic(field: gtx.Field, m: int = M, n: int = N) -> None:\n", + " \"\"\"Refresh the one-cell halo of `field` in place from the opposite edge.\"\"\"\n", + " a = field.ndarray\n", + " a[0, :] = a[m, :]\n", + " a[m + 1, :] = a[1, :]\n", + " a[:, 0] = a[:, n]\n", + " a[:, n + 1] = a[:, 1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Time loop\n", + "\n", + "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", + "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", + "with the filter switched off, which is how the leapfrog scheme is started." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def run(itmax: int, m: int = M, n: int = N) -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", + " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", + " domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", + " interior = gtx.domain({I: (0, m), J: (0, n)})\n", + "\n", + " u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n", + "\n", + " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", + " return gtx.as_field(domain, np.pad(a, 1, mode=\"wrap\"), allocator=backend)\n", + "\n", + " u, v, p = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + " uold, vold, pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + " unew, vnew, pnew = (gtx.zeros(domain, dtype=gtx.float64, allocator=backend) for _ in range(3))\n", + "\n", + " for cycle in range(itmax):\n", + " tdt = DT if cycle == 0 else 2.0 * DT\n", + " alpha = 0.0 if cycle == 0 else ALPHA\n", + "\n", + " timestep(\n", + " u,\n", + " v,\n", + " p,\n", + " uold,\n", + " vold,\n", + " pold,\n", + " DX,\n", + " DY,\n", + " tdt,\n", + " alpha,\n", + " out=(unew, vnew, pnew, uold, vold, pold),\n", + " domain=interior,\n", + " offset_provider={},\n", + " )\n", + "\n", + " for field in (unew, vnew, pnew):\n", + " apply_periodic(field, m, n)\n", + "\n", + " u, unew = unew, u\n", + " v, vnew = vnew, v\n", + " p, pnew = pnew, p\n", + "\n", + " return u, v, p\n", + "\n", + "\n", + "def interior_of(field: gtx.Field, m: int = M, n: int = N) -> np.ndarray:\n", + " return field.asnumpy()[1 : m + 1, 1 : n + 1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Validation against NumPy\n", + "\n", + "The companion module `swm_numpy.py` implements the same scheme with `numpy.roll`, which\n", + "gives periodicity for free and needs no halo at all. Agreement between the two is a check\n", + "that the halo bookkeeping here is right." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "STEPS = 100\n", + "\n", + "# The two implementations sum the same terms in a different order, so they agree to\n", + "# rounding rather than bit-for-bit. Tolerances are absolute because u and v cross zero.\n", + "ATOL_UV = 1e-11 # peak |u|, |v| ~ 4\n", + "ATOL_P = 1e-8 # peak |p| ~ 5e4\n", + "\n", + "\n", + "def test_matches_numpy():\n", + " u, v, p = run(STEPS)\n", + " u_ref, v_ref, p_ref = swm_numpy.run(STEPS)\n", + "\n", + " np.testing.assert_allclose(interior_of(u), u_ref, atol=ATOL_UV)\n", + " np.testing.assert_allclose(interior_of(v), v_ref, atol=ATOL_UV)\n", + " np.testing.assert_allclose(interior_of(p), p_ref, atol=ATOL_P)\n", + "\n", + "\n", + "test_matches_numpy()\n", + "print(\"GT4Py and NumPy agree after\", STEPS, \"steps\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Validation against the NCAR reference\n", + "\n", + "`swm_reference.npz` holds `u`, `v`, `p` after the full 4000-step benchmark, taken from\n", + "[NCAR/SWM](https://github.com/NCAR/SWM) `ref/16x16` (Apache-2.0). Reproducing it end to\n", + "end is the real correctness check, but it takes far longer than a notebook should in CI,\n", + "so it is opt-in." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "RUN_FULL_BENCHMARK = False\n", + "\n", + "\n", + "def test_matches_reference():\n", + " u, v, p = run(swm_numpy.ITMAX)\n", + " u_out, v_out, p_out = swm_numpy.to_reference_layout(\n", + " interior_of(u), interior_of(v), interior_of(p)\n", + " )\n", + "\n", + " reference = np.load(\"swm_reference.npz\")\n", + " np.testing.assert_allclose(u_out, reference[\"u\"], atol=ATOL_UV)\n", + " np.testing.assert_allclose(v_out, reference[\"v\"], atol=ATOL_UV)\n", + " np.testing.assert_allclose(p_out, reference[\"p\"], atol=ATOL_P)\n", + "\n", + "\n", + "if RUN_FULL_BENCHMARK:\n", + " test_matches_reference()\n", + " print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The flow\n", + "\n", + "The initial stream function sets up a pair of counter-rotating vortices; after a few\n", + "hundred steps the pressure field has developed the finer structure the scheme is meant to\n", + "handle without spurious accumulation of energy at the grid scale." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "u, v, p = run(STEPS)\n", + "\n", + "fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))\n", + "for ax, field, name in zip(axes, (u, v, p), (\"u\", \"v\", \"p\")):\n", + " image = ax.contourf(interior_of(field).T, levels=20)\n", + " ax.set_title(f\"{name} after {STEPS} steps\")\n", + " ax.set_aspect(\"equal\")\n", + " fig.colorbar(image, ax=ax)\n", + "fig.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## References\n", + "\n", + "Sadourny, R. (1975). The dynamics of finite-difference models of the shallow-water\n", + "equations. *Journal of the Atmospheric Sciences*, 32(4), 680-689.\n", + "[doi:10.1175/1520-0469(1975)032<0680:TDOFDM>2.0.CO;2](https://doi.org/10.1175/1520-0469(1975)032%3C0680:TDOFDM%3E2.0.CO;2)\n", + "\n", + "The benchmark descends from Sadourny's scheme via Paul Swarztrauber's 1984 NCAR\n", + "implementation, and is maintained today as [NCAR/SWM](https://github.com/NCAR/SWM)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/examples/swm_numpy.py b/examples/swm_numpy.py new file mode 100644 index 0000000000..7db27aa980 --- /dev/null +++ b/examples/swm_numpy.py @@ -0,0 +1,164 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +NumPy reference for the shallow water model example. + +Companion to `swm.ipynb`. The model is doubly periodic, so periodicity is expressed here +with `numpy.roll` on interior-only arrays of shape `(M, N)` -- there is no halo. The +notebook's GT4Py version instead carries one halo cell per side and updates it explicitly, +which is what makes the two implementations worth comparing. +""" + +from __future__ import annotations + +import numpy as np + + +# Model constants of the NCAR/SWM benchmark configuration. +M = 16 +N = 16 +DX = 100000.0 +DY = 100000.0 +DT = 90.0 +ALPHA = 0.001 +A = 1000000.0 +P_MEAN = 50000.0 +ITMAX = 4000 + + +def avg_x(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, -1, axis=0) + f) + + +def avg_y(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, -1, axis=1) + f) + + +def avg_x_staggered(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, 1, axis=0) + f) + + +def avg_y_staggered(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, 1, axis=1) + f) + + +def delta_x(dx: float, f: np.ndarray) -> np.ndarray: + return (np.roll(f, -1, axis=0) - f) / dx + + +def delta_y(dy: float, f: np.ndarray) -> np.ndarray: + return (np.roll(f, -1, axis=1) - f) / dy + + +def delta_x_staggered(dx: float, f: np.ndarray) -> np.ndarray: + return (f - np.roll(f, 1, axis=0)) / dx + + +def delta_y_staggered(dy: float, f: np.ndarray) -> np.ndarray: + return (f - np.roll(f, 1, axis=1)) / dy + + +def initial_conditions( + m: int = M, n: int = N, dx: float = DX, dy: float = DY, a: float = A, p_mean: float = P_MEAN +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Return the initial `u`, `v`, `p` on the interior grid, each of shape `(m, n)`. + + The velocity field is derived from a doubly periodic stream function + `psi = a * sin(2*pi*(i+0.5)/m) * sin(2*pi*(j+0.5)/n)`. + """ + d_i = 2.0 * np.pi / m + d_j = 2.0 * np.pi / n + el = n * dx + pcf = (np.pi * np.pi * a * a) / (el * el) + + psi = ( + a + * np.sin((np.arange(0, m + 1).reshape(-1, 1) + 0.5) * d_i) + * np.sin((np.arange(0, n + 1) + 0.5) * d_j) + ) + p = ( + pcf + * (np.cos(2.0 * np.arange(0, m).reshape(-1, 1) * d_i) + np.cos(2.0 * np.arange(0, n) * d_j)) + + p_mean + ) + u = -(psi[1:, 1:] - psi[1:, :-1]) / dy + v = (psi[1:, 1:] - psi[:-1, 1:]) / dx + + return u, v, p + + +def timestep( + u: np.ndarray, + v: np.ndarray, + p: np.ndarray, + uold: np.ndarray, + vold: np.ndarray, + pold: np.ndarray, + dx: float, + dy: float, + tdt: float, + alpha: float, +) -> tuple[np.ndarray, ...]: + """One leapfrog step with a Robert-Asselin time filter. Returns the six updated fields.""" + cu = avg_x(p) * u + cv = avg_y(p) * v + z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p)) + h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v)) + + unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt + vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt + pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt + + uold_new = u + alpha * (unew - 2.0 * u + uold) + vold_new = v + alpha * (vnew - 2.0 * v + vold) + pold_new = p + alpha * (pnew - 2.0 * p + pold) + + return unew, vnew, pnew, uold_new, vold_new, pold_new + + +def run( + itmax: int, + m: int = M, + n: int = N, + dx: float = DX, + dy: float = DY, + dt: float = DT, + alpha: float = ALPHA, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Integrate `itmax` steps and return the final interior `u`, `v`, `p`.""" + u, v, p = initial_conditions(m, n, dx, dy) + uold, vold, pold = u.copy(), v.copy(), p.copy() + + for cycle in range(itmax): + # The first step is forward Euler and unfiltered; afterwards leapfrog with tdt = 2*dt. + tdt = dt if cycle == 0 else 2.0 * dt + step_alpha = 0.0 if cycle == 0 else alpha + unew, vnew, pnew, uold, vold, pold = timestep( + u, v, p, uold, vold, pold, dx, dy, tdt, step_alpha + ) + u, v, p = unew, vnew, pnew + + return u, v, p + + +def to_reference_layout( + u: np.ndarray, v: np.ndarray, p: np.ndarray +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Convert interior `(M, N)` fields to the `(M+1, N+1)` layout of the NCAR/SWM dumps. + + The extra row and column are the periodic images the original Fortran carried + explicitly; which side they sit on differs per field because of the C-grid staggering. + """ + return ( + np.pad(u, ((1, 0), (0, 1)), mode="wrap"), + np.pad(v, ((0, 1), (1, 0)), mode="wrap"), + np.pad(p, ((0, 1), (0, 1)), mode="wrap"), + ) diff --git a/examples/swm_reference.npz b/examples/swm_reference.npz new file mode 100644 index 0000000000000000000000000000000000000000..6a9ca4af2f80200ce698e0040e3fd68b90eaacd2 GIT binary patch literal 4785 zcmZWtc{J2*`&SGxm4rwlTPoopkt|6P0gBQAtyzX)tyPO<9t4NVbqQ zV~H{Lb!ITkKHs07_dVzLzR!D~bKloF_kBL+TK@QauKTjL=H*l6;o;e_wdHs!pLr-k z|6VX2F`iJhI{^{fc=qtb3vRt{ttkF~*{(qr;2a^{x{B(ZF73ZIY9&)WzZS2U^~|@v zAO!hasIV>X#?3JaE5yp@iQ}sb-i)i>roXfQt-RU$^HW%C? z`w1u^)UO*Pky!08D0AMC<3Z$x((BA&t28-PkrtU0V)8fE)kJHZNvX3l>G>;~<&MecUEUU(ebdny z47zY!KDA`E@XATFT8%hI?=9yYD5uw$&>^e)1JcdKS-4qiwCaDcK}%iKSxZ z&|wS5K=+b69~Gn`?}e94r%0pMc1^9lr*%YW%YAXYxBETgVY~MVk;8BWs-?rGk-_c~ z^Y79oU-clWs8MELx}T=!&%t$n z;+8JU)rvpd?&8OpTuqhM#b-?E(1YU}CH(pq>wWjGj;w|y@s|tU>Z=l6dLOLVsN-Qa zhI{dPZ99~lsjMwm(?SJ<7HYpStmzwqqm8vC{Ig@k+XeM^LB@W|I^D9W2XGLswHjcR@$G7A4(WO`}scF@T&eCiSyy7hgfpm;5d*+r(+=A=a8ooo#ruU!@?tDKtu~}^$?w)$^%9HnjmxwG8Flm|HcOKv!fBCco%U;h`BQ z3FNW=FVV_1eR|?QMJw!|qV?+kMa#`5Lb_oU)gE%M5Z&^VqO(@7F9ZQ>x5=x2+Ggf=e@yC?^)R)Ojs0} zF|(ew&Zr&lmR`MFGtz-+x4g1kK6E4=E^+Dj?8Q^&$4lQfm&M16w7^X(VXZrKgzC8@ zscI!#BaTevQ7spv2bF1+0sH*NO^PnoI*)^F$;HmGcOP~lvmR(~U|ezLA;?eeK>RX=LZPj||d1@DXax@#WEFh)hs+~#i&kn}6dGJ0IG zjwm>M;!=LJwZq(xs$cuZ9WS#289`IL$Mla!R=eXd<}TGENuLdy4*TItdb>||9cIL2 z;g<2GZHvT<*E?;*H!TsQ>gVdsBaDL&RQx{<%bzjdc2fPI<8&LNILm^305(bUR;*D} zaj@(0!R4k~C9AMsi}n>79aZOj3h$pe!U*+z=aemJK3B;sM#g`>GY2#Nt)cscmAM&7 z$Ztro&QAQ+l>BvNKoJoZzt?VV5W4~qJkE;q|mr(C6kY7$-###B-XUwmYvJ9)r-0H&0H4C9VGN`AfD&{4YXUZd!Zk3tyY z+T?m6$53rWxHx;$t-7E6_1y^h38!ltY#^$H${T7v5aqvw!B&~C=-iv`ZME{jDTh5% z6L+AQcj~RVsfHrBtFJek9cW5I?=SmYZa+LJlN^Mxr=3i!XdOM_9;coAF6{+m`?P%B zn=%`mX7_`V`U{(Of9L*d{fB)$1wzRhi%RfaZvxwPr#STf6-urvbq+ikN^YJUi?doB zcO4ohk#k66g@y%|V#iEn(((Auk~=+PswfYR&vZTDCJPDJ?UoB|vxcuu?oq!qZUdS{ zxP1V#(sFC#_WK#gXVu=C1Am}S)yZeUCD849(!8i^o5FriiXrVo*4lC3754?T@0aj% z99yfJwt1F^Z`qK1N&Z-RZ2dkeH#Qcgy)W#lDTKeV@WQ?ABBFpion-TE`Q_-_N+I6u z2XB_D>2@d`zLshk@-r}@KT`0;u2_DvmKCBa=03`dv@3Mzdy2cI9`3s+TfJ>N#MGF; zk%Z`#=VL+qP6`0fGtNe zx6r%}6TqhfY>SO(Xr}~)9J-xtr^N^P(xM@eL@?!r-U|3dm^v3MNcC>yp|&dWFq;Oc z7WoU^x6}A{_r5tM4ttbauIs!(ZY2EuHP(^srP3TR8Z8`MPh!un7MxY^d62RWC~S zK>@DsGn(?mcfU2U%Ja zyOD>GuL%V-lw|u4(q;3;&#{119P`X?04NX9P zt*t2jR1;kp1BJL#FsZ!U(A}}nDG@p@TbK)9Yy_F16m?xbuB%NPcUdkIIEn1RAT{T^ z-wgN2HeH%eLK#pk^dM*rnnL`yki|GJApTRx0{$sv=lK5p`+5V~41`Lz$T38&*$3=B z@hEmJYGsf6jK-(0meEtE!b|$*Wy9Nb<@bcO2Jmw}If@d?(_e9jMh8dQif#7iK19D0 zEX|8P`!lP>_bbpb!>lM;c<8CgjV4$sT^d6XR5VRL3f^Y!@qC?}3A zVs*Vp9e=Ut{%kKfcFGIO=xow`eaoX!)VQh7wy~}n{baU%&Xh18c6)DUgt|(V-CtK% z7pCo+c0gg-%$E21&~n_=fpEbaesvLR4>MN_X#N&I=AKC-Mw{4QoFXc1;b*X=_)x)P z>t3?&h;APQ(0IYc@_Ry#umWv?dmAz6YSs03u=SA~Eh1U3R&mqx*@Pw0$otM+L#7|) zK)pK}B`e@Y(+VbBV0bb&BV3I)G;+@{uf;RK+2 z9$>~!bcpV!WgvrH4;ALSehN9Za66eoE4s9OTLdT$QRmg;01v6JdTJN^x%$cKa{`2M z&HIiNqUkxrnH?aOxtyR^HtRiw*vZ6xQ)kvpSDkH~JdZQ1yYy3!Eqr5_P*kOVbF>&E zgZNx!_Cn+Ovj1KvsK-BsFtiWyL8SqKi`9!USGqTx&jk&&BA7KzESK4WGMqHK$QV>% zBaz1;jmB^jxB9-0;G|?4YYA3BYZf@hSNRHac+>R-$e71G^v4_adC{8Hq|6ra~TS)92Z_X@EVoXX)O zfc#Y1SZrrf4la<|Y8KVsZpY8EZo(a$hj^p3*hiUqwqRsCS#2%&G3WXOMu_u+eU@HD zC76RL+?#Fw#~4RFK@GZ&EXRdDOvPJ(Qten2JERO}%yyc^nBul^t(brrSTt`3FwP@o zg;`}p1e^&cD)%Dt0RNW=QO0U1aGe{-Ue6)$AgTa;Dt?Ox+Q@v2t%MT5xn3MU_ZgMu z#avfl9Fzxs+!tmQHRCj?Xd)sT5~tE4m}QAX;H+-r)R}_&UL$rf7CgZ-Y`0jh7~KkdK(#<&QT>p~X1EA6Ft5|#N=lMq z*1YB>BMBDmcCxIpDU1ZCh6tPiQy2+U?}uy|IRHOIFkr*8fM8olfx)rO1WKl9h6J0a z@#`Rth!N#j5LMP8bqL^Yv$x*1U6uF0XFz|(Jby+$uz&H*-{-?^f6U(#p?^aDbl`uQ w?Ei&SY~B9dkN*?$hwJ{(+5bYKcJc81&3yLOu)iC3ULIZ^)Ryb*d;bLRe^rseZ~y=R literal 0 HcmV?d00001 From 5b7c29956e158f763c26df13669ca1ceee5a497b Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 5 Aug 2026 13:02:35 +0200 Subject: [PATCH 002/166] docs[next]: attribute the configuration to NCAR/SWM, not to a person 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. --- examples/swm.ipynb | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 33c715dceb..6f851ea438 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -33,13 +33,22 @@ "\\frac{\\partial P}{\\partial t} + \\nabla\\cdot(P\\mathbf{V}) = 0 ,\n", "$$\n", "\n", - "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975).\n", - "The four intermediates below are his mass fluxes $U$, $V$, potential vorticity $q$ and\n", - "Bernoulli function $H$, named `cu`, `cv`, `z`, `h` in the benchmark.\n", + "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975,\n", + "his Eq. 4). The four intermediates below are his mass fluxes and diagnostics,\n", "\n", - "**Provenance.** The *scheme* is from Sadourny (1975). The *configuration* --- the grid\n", - "spacing, time step, filter coefficient and initial condition --- is Paul Swarztrauber's\n", - "1984 NCAR benchmark setup, not a result from the paper." + "$$\n", + "U = \\overline{P}^{\\,x} u, \\qquad V = \\overline{P}^{\\,y} v, \\qquad\n", + "H = P + \\tfrac{1}{2}\\left(\\overline{u^2}^{\\,x} + \\overline{v^2}^{\\,y}\\right), \\qquad\n", + "\\eta = \\frac{\\delta_x v - \\delta_y u}{\\overline{P}^{\\,xy}} ,\n", + "$$\n", + "\n", + "named `cu`, `cv`, `h` and `z` here.\n", + "\n", + "**Provenance.** The *scheme* is Sadourny's. The *configuration* --- grid size, spacing,\n", + "time step, filter coefficient and initial condition --- comes from the\n", + "[NCAR/SWM](https://github.com/NCAR/SWM) benchmark rather than from the paper; Sadourny\n", + "damps the leapfrog scheme by averaging odd and even time levels every $N$ steps, not with\n", + "the per-step Robert-Asselin filter used here." ] }, { @@ -423,8 +432,9 @@ "equations. *Journal of the Atmospheric Sciences*, 32(4), 680-689.\n", "[doi:10.1175/1520-0469(1975)032<0680:TDOFDM>2.0.CO;2](https://doi.org/10.1175/1520-0469(1975)032%3C0680:TDOFDM%3E2.0.CO;2)\n", "\n", - "The benchmark descends from Sadourny's scheme via Paul Swarztrauber's 1984 NCAR\n", - "implementation, and is maintained today as [NCAR/SWM](https://github.com/NCAR/SWM)." + "The benchmark itself --- its configuration, initial condition and reference data --- is\n", + "[NCAR/SWM](https://github.com/NCAR/SWM), which implements the same model across a range of\n", + "languages and programming models." ] } ], From d10e2e5949bb0f6eeec6c16d52c9a238010f4d77 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 10 Sep 2026 13:19:37 +0200 Subject: [PATCH 003/166] fix[next]: sanitise skip-value indices before the premap gather 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 --- src/gt4py/next/embedded/nd_array_field.py | 22 +++++++------ .../ffront_tests/test_external_local_field.py | 14 +++++--- .../embedded_tests/test_nd_array_field.py | 32 ++++++++++++++++++- 3 files changed, 53 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 980c064775..7454ca5813 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -669,16 +669,18 @@ def _gather_premap(data: NdArrayField, *connectivities: common.GatherConnectivit # one index array per original field dimension (the connectivity's, or identity), broadcast over # the output domain and shifted to 0-based buffer indices, then a single advanced-index gather - take_indices = tuple( - ( - _connectivity_index_array(conn_by_codomain[dim], new_domain, xp) - if dim in conn_by_codomain - else _identity_index_array(new_domain, dim, xp) - ) - - data.domain[dim].unit_range.start - for dim in data.domain.dims - ) - new_buffer = data._ndarray[take_indices] + def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: + start = data.domain[dim].unit_range.start + if (conn := conn_by_codomain.get(dim)) is None: + return _identity_index_array(new_domain, dim, xp) - start + indices = _connectivity_index_array(conn, new_domain, xp) + if conn.skip_value is not None: + # a wrapped-around skip index is harmless for the primal, but under autodiff its + # cotangent would flow into whichever element it happens to hit + indices = xp.where(indices == conn.skip_value, start, indices) + return indices - start + + new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py index 0fc370adbb..737aceb8a7 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_external_local_field.py @@ -118,14 +118,20 @@ def test_write_local_field(unstructured_case): def testee(inp: gtx.Field[[Edge], int32]) -> gtx.Field[[Vertex, V2EDim], int32]: return inp(V2E) - out = unstructured_case.as_field( - [Vertex, V2EDim], np.zeros_like(unstructured_case.offset_provider["V2E"].asnumpy()) - ) + v2e = unstructured_case.offset_provider["V2E"] + v2e_table = v2e.asnumpy() + out = unstructured_case.as_field([Vertex, V2EDim], np.zeros_like(v2e_table)) inp = cases.allocate(unstructured_case, testee, "inp")() + valid = v2e_table != v2e.skip_value + + def allclose_at_valid_entries(ref, out): + return np.allclose(ref[valid], out[valid]) + cases.verify( unstructured_case, testee, inp, out=out, - ref=inp.asnumpy()[unstructured_case.offset_provider["V2E"].asnumpy()], + ref=inp.asnumpy()[v2e_table], + comparison=allclose_at_valid_entries, ) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 3546ceaaaa..291c8ba9ce 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -25,7 +25,11 @@ NamedRange, UnitRange, ) -from gt4py.next.embedded import exceptions as embedded_exceptions, nd_array_field +from gt4py.next.embedded import ( + context as embedded_context, + exceptions as embedded_exceptions, + nd_array_field, +) from gt4py.next.embedded.nd_array_field import _get_slices_from_domain_slice from gt4py.next.ffront import fbuiltins from gt4py.next.ffront.experimental import as_offset @@ -1825,3 +1829,29 @@ def make_connectivity(arr): return common._connectivity(arr, codomain=D0, domain=codomain).ndarray np.testing.assert_array_equal(jax.jit(make_connectivity)(offsets), offsets) + + +@pytest.mark.requires_jax +def test_jax_grad_through_premap_with_skip_values(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + e2v = common._connectivity( + jax.numpy.asarray([[0, 1], [2, -1]], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + skip_value=-1, + ) + + def loss(x): + field = common._field(x, domain=common.domain({V: (0, 4)})) + with embedded_context.update(offset_provider={"E2V": e2v}): + result = fbuiltins.neighbor_sum(fbuiltins.sqrt(field.premap(e2v)), axis=E2VDim) + return jax.numpy.sum(result.ndarray) + + x = jax.numpy.asarray([4.0, 9.0, 16.0, -1.0]) + + np.testing.assert_allclose(loss(x), 9.0) + np.testing.assert_allclose(jax.grad(loss)(x), [0.25, 1.0 / 6.0, 0.125, 0.0]) From 57f3ae099c957ee914872afd98f811a8aa4694be Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 10 Sep 2026 13:25:52 +0200 Subject: [PATCH 004/166] fix[next]: restrict the neighbor table to the field domain in reductions 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 --- src/gt4py/next/embedded/nd_array_field.py | 34 +++++++++++-------- .../embedded_tests/test_nd_array_field.py | 19 +++++++++++ 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 7454ca5813..f26cfd9121 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -320,11 +320,6 @@ def premap( connectivity = connectivity.as_connectivity_field() assert isinstance(connectivity, common.Connectivity) - # Current implementation relies on skip_value == -1: - # if we assume the indexed array has at least one element, - # we wrap around without out of bounds access - assert connectivity.skip_value is None or connectivity.skip_value == -1 - conn_fields.append(connectivity) codomains_counter[connectivity.codomain] += 1 @@ -988,18 +983,27 @@ def _builtin_op( assert common.is_neighbor_table(offset_definition) new_domain = common.Domain(*[nr for nr in field.domain if nr.dim != axis]) - broadcast_slice = tuple( - slice(None) if d in [axis, offset_definition.domain.dims[0]] else xp.newaxis - for d in field.domain.dims - ) - masked_array = xp.where( - xp.asarray(offset_definition.ndarray[broadcast_slice]) != common._DEFAULT_SKIP_VALUE, - field.ndarray, - initial_value_op(field), - ) + if offset_definition.skip_value is None: + values = field.ndarray + else: + table_domain = common.Domain(*(field.domain[d] for d in offset_definition.domain.dims)) + table = ( + offset_definition + if table_domain == offset_definition.domain + else offset_definition.restrict(table_domain) + ).ndarray + broadcast_slice = tuple( + slice(None) if d in offset_definition.domain.dims else xp.newaxis + for d in field.domain.dims + ) + values = xp.where( + xp.asarray(table[broadcast_slice]) != offset_definition.skip_value, + field.ndarray, + initial_value_op(field), + ) return field.__class__.from_array( - getattr(xp, array_builtin_name)(masked_array, axis=reduce_dim_index), domain=new_domain + getattr(xp, array_builtin_name)(values, axis=reduce_dim_index), domain=new_domain ) _builtin_op.__name__ = builtin_name diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 291c8ba9ce..c6f57bc480 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1764,6 +1764,25 @@ def test_concat(fields_data, dim, expected_data, expect_error): np.testing.assert_allclose(result.asnumpy(), expected_array) +def test_neighbor_sum_after_narrowing_premap(): + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + e2v = common._connectivity( + np.asarray([[0, 1], [2, -1], [4, 5], [6, 7]]), + codomain=V, + domain=common.domain({E: (0, 4), E2VDim: (0, 2)}), + skip_value=-1, + ) + v_field = common._field(np.arange(1.0, 5.0), domain=common.domain({V: (0, 4)})) + + with embedded_context.update(offset_provider={"E2V": e2v}): + result = fbuiltins.neighbor_sum(v_field.premap(e2v), axis=E2VDim) + + assert result.domain == common.domain({E: (0, 2)}) + np.testing.assert_array_equal(result.asnumpy(), [3.0, 3.0]) + + @pytest.mark.requires_jax def test_jax_jit_field_arguments(): import jax From 3982769a1495b35dc08f321cb9029b4f70ac8c70 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 10 Sep 2026 13:31:17 +0200 Subject: [PATCH 005/166] feat[next]: register jax connectivities as pytree nodes 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 --- src/gt4py/next/embedded/nd_array_field.py | 91 +++++++++- .../embedded_tests/test_nd_array_field.py | 169 ++++++++++++++++++ 2 files changed, 258 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index f26cfd9121..78f9faee61 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -581,8 +581,7 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co assert isinstance(image_range, common.UnitRange) assert common.UnitRange.is_finite(image_range) - xp = self.array_ns - slices = _hyperslice(self._ndarray, image_range, xp, self.skip_value) + slices = self._image_slices(image_range) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -591,6 +590,37 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co return new_domain + @property + def _index_table(self) -> core_defs.NDArrayObject: + """The table whose contents `inverse_image` inspects.""" + return self._ndarray + + @functools.cached_property + def _image_bounds(self) -> Optional[tuple[int, int, tuple[slice, ...]]]: + """`(min, max, support)` of the non-skip entries, `None` if there are none.""" + xp = self.array_ns + table = self._index_table + if self.skip_value is None: + return int(xp.min(table)), int(xp.max(table)), tuple(slice(0, n) for n in table.shape) + valid = table != self.skip_value + if not xp.any(valid): + return None + support = tuple(slice(int(xp.min(i)), int(xp.max(i)) + 1) for i in xp.nonzero(valid)) + return int(xp.min(table[valid])), int(xp.max(table[valid])), support + + def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, ...]]: + if (bounds := self._image_bounds) is not None: + value_min, value_max, support = bounds + # with the skip value inside the range, skip-only rows would be selected as well + skip_selected = self.skip_value is not None and self.skip_value in image_range + if ( + image_range.start <= value_min + and value_max < image_range.stop + and not skip_selected + ): + return support + return _hyperslice(self._index_table, image_range, self.array_ns, self.skip_value) + def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: cache_key = (id(self.ndarray), self.domain, index) @@ -1089,9 +1119,38 @@ def __setitem__( object.__setattr__(self, "_ndarray", self._ndarray.at[target_slice].set(value)) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete + class _TableHandle: + """Trace-time reference to a connectivity table, compared by buffer identity.""" + + __slots__ = ("table",) + + def __init__(self, table: core_defs.NDArrayObject) -> None: + self.table = table + + def __eq__(self, other: object) -> bool: + return isinstance(other, _TableHandle) and self.table is other.table + + def __hash__(self) -> int: + return id(self.table) + + _JaxConnectivityAuxData: TypeAlias = tuple[ + common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_TableHandle] + ] + @dataclasses.dataclass(frozen=True, eq=False) class JaxArrayConnectivityField(NdArrayConnectivityField): array_ns: ClassVar[ModuleType] = jnp + _table_handle: Optional[_TableHandle] = None + + @property + def _index_table(self) -> core_defs.NDArrayObject: + if self._table_handle is not None and isinstance(self._ndarray, jax.core.Tracer): + return self._table_handle.table + return self._ndarray + + def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, ...]]: + with jax.ensure_compile_time_eval(): + return super()._image_slices(image_range) common._field.register(jnp.ndarray, JaxArrayField.from_array) common._connectivity.register(jnp.ndarray, JaxArrayConnectivityField.from_array) @@ -1116,6 +1175,34 @@ def _unflatten_jax_field( _unflatten_jax_field, ) + def _flatten_jax_connectivity( + connectivity: JaxArrayConnectivityField, + ) -> tuple[tuple[core_defs.NDArrayObject], _JaxConnectivityAuxData]: + table = connectivity._ndarray + handle = ( + connectivity._table_handle + if isinstance(table, jax.core.Tracer) + else _TableHandle(table) + ) + return (table,), ( + connectivity.domain, + connectivity.codomain, + connectivity.skip_value, + handle, + ) + + def _unflatten_jax_connectivity( + aux_data: _JaxConnectivityAuxData, children: tuple[core_defs.NDArrayObject] + ) -> JaxArrayConnectivityField: + domain, codomain, skip_value, handle = aux_data + return JaxArrayConnectivityField(domain, children[0], codomain, skip_value, handle) + + jax.tree_util.register_pytree_node( + JaxArrayConnectivityField, # type: ignore[type-abstract, unused-ignore] # see '_unflatten_jax_field' + _flatten_jax_connectivity, + _unflatten_jax_connectivity, + ) + def _broadcast(field: common.Field, new_dimensions: Sequence[common.Dimension]) -> common.Field: if field.domain.dims == new_dimensions: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index c6f57bc480..8b9afa009c 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -9,6 +9,7 @@ import math import operator import pickle +import re from typing import Callable, Iterable, Optional import numpy as np @@ -1874,3 +1875,171 @@ def loss(x): np.testing.assert_allclose(loss(x), 9.0) np.testing.assert_allclose(jax.grad(loss)(x), [0.25, 1.0 / 6.0, 0.125, 0.0]) + + +def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: + """Two edges per vertex, both entries equal, every seventh second entry a skip value.""" + vertex = np.arange(4 * num_vertices) // 2 + table = np.stack([vertex, vertex], axis=1).astype(np.int32) + table[::7, 1] = -1 + return table + + +@pytest.mark.parametrize("skip_value", [None, -1]) +def test_inverse_image_bounds_shortcut_matches_hyperslice(skip_value): + rng = np.random.default_rng(0) + high = 6 + covering_cases = 0 + for _ in range(150): + table = rng.integers(-1 if skip_value is not None else 0, high, size=(4, 3)) + conn = common._connectivity( + table, + codomain=D0, + domain=common.domain({D1: (0, 4), D2: (0, 3)}), + skip_value=skip_value, + ) + for start in range(-1, high): + for stop in range(start + 1, high + 1): + image_range = UnitRange(start, stop) + expected = nd_array_field._hyperslice(table, image_range, np, skip_value) + if expected is None: + with pytest.raises(ValueError, match="non-contiguous or empty"): + conn.inverse_image(image_range) + else: + assert conn.inverse_image(image_range) == conn.domain.slice_at[expected] + valid = table[table != skip_value] if skip_value is not None else table + covering_cases += bool(np.all((valid >= start) & (valid < stop))) + assert covering_cases > 0 + + +def test_inverse_image_range_containing_skip_value_selects_skip_only_rows(): + conn = common._connectivity( + np.asarray([[0, 1], [-1, -1]]), + codomain=D0, + domain=common.domain({D1: (0, 2), D2: (0, 2)}), + skip_value=-1, + ) + + assert conn.inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 1), D2: (0, 2)}) + assert conn.inverse_image(UnitRange(-1, 2)) == common.domain({D1: (0, 2), D2: (0, 2)}) + + +@pytest.mark.requires_jax +def test_jax_connectivity_pytree_roundtrip(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + domain = common.domain({E: (0, 2), E2VDim: (0, 2)}) + table = jax.numpy.asarray([[0, 1], [2, -1]], dtype=np.int32) + conn = common._connectivity(table, codomain=V, domain=domain, skip_value=-1) + + children, treedef = jax.tree_util.tree_flatten(conn) + assert len(children) == 1 + assert children[0] is table + + restored = jax.tree_util.tree_unflatten(treedef, children) + assert isinstance(restored, nd_array_field.JaxArrayConnectivityField) + assert restored.domain == domain + assert restored.codomain == V + assert restored.skip_value == -1 + assert restored.inverse_image(UnitRange(0, 2)) == common.domain({E: (0, 1), E2VDim: (0, 2)}) + + same_table = common._connectivity(table, codomain=V, domain=domain, skip_value=-1) + assert jax.tree_util.tree_structure(same_table) == treedef + copied_table = common._connectivity( + jax.numpy.array(table, copy=True), codomain=V, domain=domain, skip_value=-1 + ) + assert jax.tree_util.tree_structure(copied_table) != treedef + + +@pytest.mark.requires_jax +@pytest.mark.parametrize("num_field_vertices", [300, 600], ids=["narrowing", "covering"]) +def test_jax_jit_premap_with_connectivity_argument(num_field_vertices): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = _skip_value_e2v_table(300) + conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + field_domain = common.domain({V: (0, num_field_vertices)}) + + def premap_and_reduce(field, conn): + with embedded_context.update(offset_provider={"E2V": conn}): + return fbuiltins.neighbor_sum(field.premap(conn), axis=E2VDim) + + expected = premap_and_reduce( + common._field(np.arange(num_field_vertices, dtype=np.float64), domain=field_domain), + common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1), + ) + + jitted = jax.jit(premap_and_reduce) + field = common._field( + jax.numpy.arange(num_field_vertices, dtype=np.float64), domain=field_domain + ) + conn = common._connectivity( + jax.numpy.asarray(table), codomain=V, domain=conn_domain, skip_value=-1 + ) + result = jitted(field, conn) + + assert result.domain == expected.domain + np.testing.assert_allclose(result.asnumpy(), expected.asnumpy()) + + stablehlo = jitted.lower(field, conn).as_text() + main_arguments = re.search(r"@main\(([^)]*)\)", stablehlo).group(1) + assert f"tensor<{table.shape[0]}x2xi32>" in main_arguments + assert "dense<[" not in stablehlo # the table is not inlined as a constant + + +@pytest.mark.requires_jax +def test_jax_jit_retraces_per_connectivity_buffer(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = jax.numpy.asarray(_skip_value_e2v_table(8)) + conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + field = common._field(jax.numpy.arange(8, dtype=np.float64), domain=common.domain({V: (0, 8)})) + traces = 0 + + @jax.jit + def premap(field, conn): + nonlocal traces + traces += 1 + return field.premap(conn) + + conn = common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1) + premap(field, conn) + premap(field, conn) + assert traces == 1 + + premap(field, common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1)) + assert traces == 1 + + premap( + field, + common._connectivity( + jax.numpy.array(table, copy=True), codomain=V, domain=conn_domain, skip_value=-1 + ), + ) + assert traces == 2 + + +@pytest.mark.requires_jax +def test_jax_jit_premap_non_contiguous_inverse_image_raises(): + import jax + + V = Dimension("V") + E = Dimension("E") + conn = common._connectivity( + jax.numpy.asarray([0, 5, 1], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 3)}), + ) + field = common._field(jax.numpy.arange(3, dtype=np.float64), domain=common.domain({V: (0, 3)})) + + with pytest.raises(ValueError, match="non-contiguous"): + jax.jit(lambda field, conn: field.premap(conn))(field, conn) From 82d0032660a7e6a244312a6081f2e795eb3b9f70 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 10 Sep 2026 13:39:35 +0200 Subject: [PATCH 006/166] test[next]: assert the inverse-image bounds shortcut bypasses the table scan Claude-Session: https://claude.ai/code/session_013m5PzT4FxbaKPxfXqiQLr5 --- src/gt4py/next/embedded/nd_array_field.py | 3 +-- .../embedded_tests/test_nd_array_field.py | 23 +++++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 78f9faee61..cabc691d10 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -592,12 +592,11 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co @property def _index_table(self) -> core_defs.NDArrayObject: - """The table whose contents `inverse_image` inspects.""" return self._ndarray @functools.cached_property def _image_bounds(self) -> Optional[tuple[int, int, tuple[slice, ...]]]: - """`(min, max, support)` of the non-skip entries, `None` if there are none.""" + """Smallest value, largest value and bounding hyperslice of the non-skip entries.""" xp = self.array_ns table = self._index_table if self.skip_value is None: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 8b9afa009c..0ef172b300 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1886,7 +1886,17 @@ def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: @pytest.mark.parametrize("skip_value", [None, -1]) -def test_inverse_image_bounds_shortcut_matches_hyperslice(skip_value): +def test_inverse_image_bounds_shortcut_matches_hyperslice(skip_value, monkeypatch): + hyperslice = nd_array_field._hyperslice + hyperslice_calls = 0 + + def counting_hyperslice(*args, **kwargs): + nonlocal hyperslice_calls + hyperslice_calls += 1 + return hyperslice(*args, **kwargs) + + monkeypatch.setattr(nd_array_field, "_hyperslice", counting_hyperslice) + rng = np.random.default_rng(0) high = 6 covering_cases = 0 @@ -1901,14 +1911,19 @@ def test_inverse_image_bounds_shortcut_matches_hyperslice(skip_value): for start in range(-1, high): for stop in range(start + 1, high + 1): image_range = UnitRange(start, stop) - expected = nd_array_field._hyperslice(table, image_range, np, skip_value) + expected = hyperslice(table, image_range, np, skip_value) + valid = table[table != skip_value] if skip_value is not None else table + covering = valid.size > 0 and bool(np.all((valid >= start) & (valid < stop))) + covering &= skip_value is None or skip_value not in image_range + calls_before = hyperslice_calls if expected is None: with pytest.raises(ValueError, match="non-contiguous or empty"): conn.inverse_image(image_range) else: assert conn.inverse_image(image_range) == conn.domain.slice_at[expected] - valid = table[table != skip_value] if skip_value is not None else table - covering_cases += bool(np.all((valid >= start) & (valid < stop))) + # the shortcut answers exactly the covering cases without scanning the table + assert (hyperslice_calls == calls_before) == covering + covering_cases += covering assert covering_cases > 0 From a8bcd9518d294a89c8a33b372ed12ca0d37afc9a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 16 Sep 2026 11:29:06 +0200 Subject: [PATCH 007/166] fix[next]: carry the table handle through restrict, invalidate cached 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. --- src/gt4py/next/embedded/nd_array_field.py | 82 +++++++++++++------ .../embedded_tests/test_nd_array_field.py | 80 ++++++++++++++++++ 2 files changed, 136 insertions(+), 26 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index cabc691d10..ef18e2894d 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -594,18 +594,36 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co def _index_table(self) -> core_defs.NDArrayObject: return self._ndarray + def __setitem__( + self, + index: common.AnyIndexSpec, + value: common.Field | core_defs.NDArrayObject | core_defs.IntegralScalar, + ) -> None: + super().__setitem__(index, value) + self._cache.clear() + self.__dict__.pop("_image_bounds", None) + @functools.cached_property def _image_bounds(self) -> Optional[tuple[int, int, tuple[slice, ...]]]: """Smallest value, largest value and bounding hyperslice of the non-skip entries.""" xp = self.array_ns table = self._index_table + if math.prod(table.shape) == 0: + return None if self.skip_value is None: return int(xp.min(table)), int(xp.max(table)), tuple(slice(0, n) for n in table.shape) valid = table != self.skip_value if not xp.any(valid): return None - support = tuple(slice(int(xp.min(i)), int(xp.max(i)) + 1) for i in xp.nonzero(valid)) - return int(xp.min(table[valid])), int(xp.max(table[valid])), support + support = [] + for axis in range(table.ndim): + other_axes = tuple(a for a in range(table.ndim) if a != axis) + (nonzero,) = xp.nonzero(xp.any(valid, axis=other_axes)) + support.append(slice(int(nonzero[0]), int(nonzero[-1]) + 1)) + info = xp.iinfo(table.dtype) + value_min = int(xp.min(xp.where(valid, table, info.max))) + value_max = int(xp.max(xp.where(valid, table, info.min))) + return value_min, value_max, tuple(support) def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, ...]]: if (bounds := self._image_bounds) is not None: @@ -624,15 +642,19 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: cache_key = (id(self.ndarray), self.domain, index) if (restricted_connectivity := self._cache.get(cache_key, None)) is None: - cls = self.__class__ - xp = cls.array_ns new_domain, buffer_slice = self._slice(index) - new_buffer = xp.asarray(self.ndarray[buffer_slice]) - restricted_connectivity = cls(new_domain, new_buffer, self.codomain, self.skip_value) + restricted_connectivity = self._restrict_buffer(new_domain, buffer_slice) self._cache[cache_key] = restricted_connectivity return restricted_connectivity + def _restrict_buffer( + self, new_domain: common.Domain, buffer_slice: common.RelativeIndexSequence + ) -> NdArrayConnectivityField: + cls = self.__class__ + new_buffer = cls.array_ns.asarray(self.ndarray[buffer_slice]) + return cls(new_domain, new_buffer, self.codomain, self.skip_value) + __getitem__ = restrict @@ -697,25 +719,28 @@ def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: start = data.domain[dim].unit_range.start if (conn := conn_by_codomain.get(dim)) is None: return _identity_index_array(new_domain, dim, xp) - start - indices = _connectivity_index_array(conn, new_domain, xp) - if conn.skip_value is not None: - # a wrapped-around skip index is harmless for the primal, but under autodiff its - # cotangent would flow into whichever element it happens to hit - indices = xp.where(indices == conn.skip_value, start, indices) - return indices - start + # skip entries read the domain start instead of wrapping around to an arbitrary element; + # what is gathered there, and its cotangent, is left to the reduction mask to discard + return _connectivity_index_array(conn, new_domain, xp, skip_value_replacement=start) - start new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) def _connectivity_index_array( - connectivity: common.GatherConnectivity, domain: common.Domain, xp: ModuleType + connectivity: common.GatherConnectivity, + domain: common.Domain, + xp: ModuleType, + *, + skip_value_replacement: Optional[core_defs.IntegralScalar] = None, ) -> core_defs.NDArrayObject: """`connectivity`'s index table laid out over `domain` (not yet shifted to 0-based).""" # restrict the table to the output ranges of the connectivity's own dimensions sub_domain = common.Domain(*(domain[d] for d in connectivity.domain.dims)) conn = connectivity if sub_domain == connectivity.domain else connectivity.restrict(sub_domain) arr = xp.asarray(conn.ndarray) + if skip_value_replacement is not None and conn.skip_value is not None: + arr = xp.where(arr == conn.skip_value, skip_value_replacement, arr) # the axis of `arr` for each output dimension: the connectivity's own axis, or a fresh appended one ndim = conn.domain.ndim fresh_axis = { @@ -1015,20 +1040,10 @@ def _builtin_op( if offset_definition.skip_value is None: values = field.ndarray else: - table_domain = common.Domain(*(field.domain[d] for d in offset_definition.domain.dims)) - table = ( - offset_definition - if table_domain == offset_definition.domain - else offset_definition.restrict(table_domain) - ).ndarray - broadcast_slice = tuple( - slice(None) if d in offset_definition.domain.dims else xp.newaxis - for d in field.domain.dims - ) + assert isinstance(offset_definition, common.GatherConnectivity) + table = _connectivity_index_array(offset_definition, field.domain, xp) values = xp.where( - xp.asarray(table[broadcast_slice]) != offset_definition.skip_value, - field.ndarray, - initial_value_op(field), + table != offset_definition.skip_value, field.ndarray, initial_value_op(field) ) return field.__class__.from_array( @@ -1151,6 +1166,21 @@ def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, with jax.ensure_compile_time_eval(): return super()._image_slices(image_range) + def _restrict_buffer( + self, new_domain: common.Domain, buffer_slice: common.RelativeIndexSequence + ) -> JaxArrayConnectivityField: + handle = None + if self._table_handle is not None and isinstance(self._ndarray, jax.core.Tracer): + with jax.ensure_compile_time_eval(): + handle = _TableHandle(self._table_handle.table[buffer_slice]) + return JaxArrayConnectivityField( + new_domain, + jnp.asarray(self._ndarray[buffer_slice]), + self.codomain, + self.skip_value, + handle, + ) + common._field.register(jnp.ndarray, JaxArrayField.from_array) common._connectivity.register(jnp.ndarray, JaxArrayConnectivityField.from_array) # jax >= 0.11: 'Tracer' is no longer a subclass of 'jax.Array' (only 'isinstance' says so, via diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 0ef172b300..2a8c94f6f3 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2058,3 +2058,83 @@ def test_jax_jit_premap_non_contiguous_inverse_image_raises(): with pytest.raises(ValueError, match="non-contiguous"): jax.jit(lambda field, conn: field.premap(conn))(field, conn) + + +def test_inverse_image_after_in_place_write(): + conn = common._connectivity( + np.asarray([[0, 1], [-1, -1]]), + codomain=D0, + domain=common.domain({D1: (0, 2), D2: (0, 2)}), + skip_value=-1, + ) + assert conn.inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 1), D2: (0, 2)}) + + conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) + + assert conn.inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 2), D2: (0, 2)}) + assert conn.inverse_image(UnitRange(0, 5)) == common.domain({D1: (0, 2), D2: (0, 2)}) + + +def test_inverse_image_empty_table_raises(): + conn = common._connectivity( + np.zeros((0, 2), dtype=np.int32), + codomain=D0, + domain=common.domain({D1: (0, 0), D2: (0, 2)}), + ) + + with pytest.raises(ValueError, match="non-contiguous or empty"): + conn.inverse_image(UnitRange(0, 4)) + + +def test_neighbor_sum_with_transposed_table_dims(): + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = np.asarray([[0, 1], [2, -1], [1, 3]]) + e2v = common._connectivity( + table, codomain=V, domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), skip_value=-1 + ) + data = np.arange(12, dtype=np.float64).reshape(4, 3) + ve_field = common._field(data, domain=common.domain({V: (0, 4), E: (0, 3)})) + + with embedded_context.update(offset_provider={"E2V": e2v}): + premapped = ve_field.premap(e2v) + result = fbuiltins.neighbor_sum(premapped, axis=E2VDim) + + assert premapped.domain == common.domain({E2VDim: (0, 2), E: (0, 3)}) + expected = np.zeros(3) + for e in range(3): + for n in range(2): + if table[e, n] != -1: + expected[e] += data[table[e, n], e] + assert result.domain == common.domain({E: (0, 3)}) + np.testing.assert_allclose(result.asnumpy(), expected) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_restricted_connectivity_argument(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = _skip_value_e2v_table(8) + conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + field_domain = common.domain({V: (0, 4)}) + + def premap_first_neighbor(field, conn): + return field.premap(conn[NamedIndex(E2VDim, 0)]) + + expected = premap_first_neighbor( + common._field(np.arange(4, dtype=np.float64), domain=field_domain), + common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1), + ) + result = jax.jit(premap_first_neighbor)( + common._field(jax.numpy.arange(4, dtype=np.float64), domain=field_domain), + common._connectivity( + jax.numpy.asarray(table), codomain=V, domain=conn_domain, skip_value=-1 + ), + ) + + assert result.domain == expected.domain + np.testing.assert_allclose(result.asnumpy(), expected.asnumpy()) From c118ca28bac2a4e4405597a0c43cdae798def417 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 16 Sep 2026 11:43:13 +0200 Subject: [PATCH 008/166] refactor[next]: forbid item assignment on connectivity fields --- src/gt4py/next/embedded/nd_array_field.py | 6 ++---- .../unit_tests/embedded_tests/test_nd_array_field.py | 9 +++------ 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index ef18e2894d..0aba6510f7 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -598,10 +598,8 @@ def __setitem__( self, index: common.AnyIndexSpec, value: common.Field | core_defs.NDArrayObject | core_defs.IntegralScalar, - ) -> None: - super().__setitem__(index, value) - self._cache.clear() - self.__dict__.pop("_image_bounds", None) + ) -> Never: + raise TypeError("'Connectivity' does not support item assignment.") @functools.cached_property def _image_bounds(self) -> Optional[tuple[int, int, tuple[slice, ...]]]: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 2a8c94f6f3..047e52ff67 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2060,19 +2060,16 @@ def test_jax_jit_premap_non_contiguous_inverse_image_raises(): jax.jit(lambda field, conn: field.premap(conn))(field, conn) -def test_inverse_image_after_in_place_write(): +def test_connectivity_field_setitem_raises(): conn = common._connectivity( np.asarray([[0, 1], [-1, -1]]), codomain=D0, domain=common.domain({D1: (0, 2), D2: (0, 2)}), skip_value=-1, ) - assert conn.inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 1), D2: (0, 2)}) - - conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) - assert conn.inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 2), D2: (0, 2)}) - assert conn.inverse_image(UnitRange(0, 5)) == common.domain({D1: (0, 2), D2: (0, 2)}) + with pytest.raises(TypeError, match="item assignment"): + conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) def test_inverse_image_empty_table_raises(): From 9882efeb2dee205509b0a9fbed5bef4e48337393 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 16 Sep 2026 11:43:24 +0200 Subject: [PATCH 009/166] docs[next]: say why domain inference reads the table through a property --- src/gt4py/next/embedded/nd_array_field.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 0aba6510f7..544788c374 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -592,6 +592,8 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co @property def _index_table(self) -> core_defs.NDArrayObject: + # domain inference needs concrete contents, which a traced `_ndarray` does not have; + # the jax subclass answers with the concrete table behind the tracer return self._ndarray def __setitem__( From 3709b85ef6492703688b9cd48cceddbf9f395b33 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 25 Sep 2026 23:52:22 +0200 Subject: [PATCH 010/166] fix[next]: keep restricted concrete connectivities concrete under a jax 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. --- src/gt4py/next/embedded/nd_array_field.py | 12 ++++++++--- .../embedded_tests/test_nd_array_field.py | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 544788c374..5b6c7a41b0 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -1170,12 +1170,18 @@ def _restrict_buffer( self, new_domain: common.Domain, buffer_slice: common.RelativeIndexSequence ) -> JaxArrayConnectivityField: handle = None - if self._table_handle is not None and isinstance(self._ndarray, jax.core.Tracer): + if isinstance(self._ndarray, jax.core.Tracer): + if self._table_handle is not None: + with jax.ensure_compile_time_eval(): + handle = _TableHandle(self._table_handle.table[buffer_slice]) + new_buffer = jnp.asarray(self._ndarray[buffer_slice]) + else: + # a concrete table must stay concrete under a trace: domain inference reads it with jax.ensure_compile_time_eval(): - handle = _TableHandle(self._table_handle.table[buffer_slice]) + new_buffer = jnp.asarray(self._ndarray[buffer_slice]) return JaxArrayConnectivityField( new_domain, - jnp.asarray(self._ndarray[buffer_slice]), + new_buffer, self.codomain, self.skip_value, handle, diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 047e52ff67..de046cbcde 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2008,6 +2008,26 @@ def premap_and_reduce(field, conn): assert "dense<[" not in stablehlo # the table is not inlined as a constant +@pytest.mark.requires_jax +def test_jax_jit_premap_with_closed_over_restricted_connectivity(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = np.asarray([[0, 1], [1, 2], [2, 0]], dtype=np.int32) + conn = common._connectivity( + jax.numpy.asarray(table), + codomain=V, + domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + ) + field = common._field(jax.numpy.arange(3, dtype=np.float64), domain=common.domain({V: (0, 3)})) + + result = jax.jit(lambda field: field.premap(conn[common.NamedIndex(E2VDim, 1)]))(field) + + np.testing.assert_array_equal(result.asnumpy(), table[:, 1]) + + @pytest.mark.requires_jax def test_jax_jit_retraces_per_connectivity_buffer(): import jax From 7aeff155945d7b88913733555ff25e65af4dbe89 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Sat, 26 Sep 2026 20:57:31 +0200 Subject: [PATCH 011/166] fix[next]: clamp value-dependent jax connectivities under a trace 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. --- src/gt4py/next/embedded/nd_array_field.py | 20 ++++++++++- .../embedded_tests/test_nd_array_field.py | 35 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 5b6c7a41b0..4fd2c1dccf 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -596,6 +596,11 @@ def _index_table(self) -> core_defs.NDArrayObject: # the jax subclass answers with the concrete table behind the tracer return self._ndarray + @property + def _image_unknown(self) -> bool: + """Whether the table's values are not available for domain inference.""" + return False + def __setitem__( self, index: common.AnyIndexSpec, @@ -721,7 +726,13 @@ def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: return _identity_index_array(new_domain, dim, xp) - start # skip entries read the domain start instead of wrapping around to an arbitrary element; # what is gathered there, and its cotangent, is left to the reduction mask to discard - return _connectivity_index_array(conn, new_domain, xp, skip_value_replacement=start) - start + index = ( + _connectivity_index_array(conn, new_domain, xp, skip_value_replacement=start) - start + ) + if getattr(conn, "_image_unknown", False): + # the output domain assumed all targets inside the field; out-of-range ones read its boundary + index = xp.clip(index, 0, len(data.domain[dim].unit_range) - 1) + return index new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) @@ -1162,7 +1173,14 @@ def _index_table(self) -> core_defs.NDArrayObject: return self._table_handle.table return self._ndarray + @property + def _image_unknown(self) -> bool: + return self._table_handle is None and isinstance(self._ndarray, jax.core.Tracer) + def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, ...]]: + if self._image_unknown: + # values computed inside a trace: assume every target lies in `image_range` + return tuple(slice(0, n) for n in self._ndarray.shape) with jax.ensure_compile_time_eval(): return super()._image_slices(image_range) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index de046cbcde..eb630fabed 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2028,6 +2028,41 @@ def test_jax_jit_premap_with_closed_over_restricted_connectivity(): np.testing.assert_array_equal(result.asnumpy(), table[:, 1]) +@pytest.mark.requires_jax +def test_jax_jit_premap_with_as_offset_computed_in_trace(): + import jax + + from gt4py.next.ffront import experimental + + C = Dimension("C") + K = Dimension("K", kind=DimensionKind.VERTICAL) + Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) + domain = common.domain({C: (0, 2), K: (0, 4)}) + values = np.arange(8, dtype=np.float64).reshape(2, 4) + offsets = np.asarray([[1, 1, 0, -1], [0, 2, 1, 0]], dtype=np.int32) + + def shifted(field, offset_field): + return field.premap(experimental.as_offset(Koff, offset_field + 0)) + + field = common._field(jax.numpy.asarray(values), domain=domain) + offset_field = common._field(jax.numpy.asarray(offsets), domain=domain) + expected = shifted(field, offset_field) + + result = jax.jit(shifted)(field, offset_field) + + assert result.domain == domain + np.testing.assert_array_equal(result.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal( + result.asnumpy(), np.take_along_axis(values, np.arange(4) + offsets, axis=1) + ) + + # out-of-range targets read the boundary value under a trace + beyond = common._field(jax.numpy.asarray(np.full((2, 4), 3, dtype=np.int32)), domain=domain) + np.testing.assert_array_equal( + jax.jit(shifted)(field, beyond).asnumpy(), np.repeat(values[:, -1:], 4, axis=1) + ) + + @pytest.mark.requires_jax def test_jax_jit_retraces_per_connectivity_buffer(): import jax From 25d3cc1ac489079ab702f68223f2cf12e1a96d2c Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 30 Oct 2026 16:39:28 +0100 Subject: [PATCH 012/166] refactor[next]: remove the inverse-image bounds shortcut 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. --- src/gt4py/next/embedded/nd_array_field.py | 32 -------------- .../embedded_tests/test_nd_array_field.py | 42 ------------------- 2 files changed, 74 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 8da5ea779c..e221e1f52f 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -560,39 +560,7 @@ def __setitem__( ) -> Never: raise TypeError("'Connectivity' does not support item assignment.") - @functools.cached_property - def _image_bounds(self) -> Optional[tuple[int, int, tuple[slice, ...]]]: - """Smallest value, largest value and bounding hyperslice of the non-skip entries.""" - xp = self.array_ns - table = self._index_table - if math.prod(table.shape) == 0: - return None - if self.skip_value is None: - return int(xp.min(table)), int(xp.max(table)), tuple(slice(0, n) for n in table.shape) - valid = table != self.skip_value - if not xp.any(valid): - return None - support = [] - for axis in range(table.ndim): - other_axes = tuple(a for a in range(table.ndim) if a != axis) - (nonzero,) = xp.nonzero(xp.any(valid, axis=other_axes)) - support.append(slice(int(nonzero[0]), int(nonzero[-1]) + 1)) - info = xp.iinfo(table.dtype) - value_min = int(xp.min(xp.where(valid, table, info.max))) - value_max = int(xp.max(xp.where(valid, table, info.min))) - return value_min, value_max, tuple(support) - def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, ...]]: - if (bounds := self._image_bounds) is not None: - value_min, value_max, support = bounds - # with the skip value inside the range, skip-only rows would be selected as well - skip_selected = self.skip_value is not None and self.skip_value in image_range - if ( - image_range.start <= value_min - and value_max < image_range.stop - and not skip_selected - ): - return support return _hyperslice(self._index_table, image_range, self.array_ns, self.skip_value) def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index eb630fabed..ae0a529cc4 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1885,48 +1885,6 @@ def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: return table -@pytest.mark.parametrize("skip_value", [None, -1]) -def test_inverse_image_bounds_shortcut_matches_hyperslice(skip_value, monkeypatch): - hyperslice = nd_array_field._hyperslice - hyperslice_calls = 0 - - def counting_hyperslice(*args, **kwargs): - nonlocal hyperslice_calls - hyperslice_calls += 1 - return hyperslice(*args, **kwargs) - - monkeypatch.setattr(nd_array_field, "_hyperslice", counting_hyperslice) - - rng = np.random.default_rng(0) - high = 6 - covering_cases = 0 - for _ in range(150): - table = rng.integers(-1 if skip_value is not None else 0, high, size=(4, 3)) - conn = common._connectivity( - table, - codomain=D0, - domain=common.domain({D1: (0, 4), D2: (0, 3)}), - skip_value=skip_value, - ) - for start in range(-1, high): - for stop in range(start + 1, high + 1): - image_range = UnitRange(start, stop) - expected = hyperslice(table, image_range, np, skip_value) - valid = table[table != skip_value] if skip_value is not None else table - covering = valid.size > 0 and bool(np.all((valid >= start) & (valid < stop))) - covering &= skip_value is None or skip_value not in image_range - calls_before = hyperslice_calls - if expected is None: - with pytest.raises(ValueError, match="non-contiguous or empty"): - conn.inverse_image(image_range) - else: - assert conn.inverse_image(image_range) == conn.domain.slice_at[expected] - # the shortcut answers exactly the covering cases without scanning the table - assert (hyperslice_calls == calls_before) == covering - covering_cases += covering - assert covering_cases > 0 - - def test_inverse_image_range_containing_skip_value_selects_skip_only_rows(): conn = common._connectivity( np.asarray([[0, 1], [-1, -1]]), From db939baa753f368dc0565524ba43c39da9929431 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 30 Oct 2026 16:39:28 +0100 Subject: [PATCH 013/166] docs[next]: add ADR for connectivities under JAX tracing --- .../0029-Connectivities_Under_JAX_Tracing.md | 58 +++++++++++++++++++ docs/development/ADRs/next/README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md new file mode 100644 index 0000000000..c41cdcc678 --- /dev/null +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -0,0 +1,58 @@ +--- +tags: [embedded, jax, connectivities] +--- + +# Connectivities Under JAX Tracing + +- **Status**: valid +- **Authors**: Hannes Vogt (@havogt) +- **Created**: 2026-10-30 +- **Updated**: 2026-10-30 + +In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to register jax connectivities as pytree nodes that carry a handle to the concrete table, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime. + +## Context + +`premap` uses the table in two ways that pull in opposite directions: + +- The **output domain** comes from `inverse_image`, which depends on the table's values. Under a trace it needs concrete values, and Python `slice`s cannot be staged. +- The **gather** should take the table as an argument of the compiled program. A closed-over table is inlined as a constant, which does not scale to large meshes. + +Narrowing is the common case: the field usually covers only part of the connectivity's image, so a solution that handles only covering ranges is not sufficient. + +## Decision + +`JaxArrayConnectivityField` is a pytree node. The table is the child, and the aux data holds domain, codomain, skip value and a `_TableHandle` to the same buffer. The handle compares by buffer identity, so a new wrapper around the same buffer does not retrace, while a new buffer does. Domain inference reads the table through the handle under `jax.ensure_compile_time_eval()`. + +How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: + +- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer, and flattening attached the handle. Domain inference reads the concrete table through the handle, and the gather takes the table as a runtime argument. +- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. +- **Computed inside the trace** (`as_offset(Koff, offset_field)`, where the offsets are data). The table is a tracer with no handle, because no concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. + +## Consequences + +- Domains under `jit` match eager execution when the table is concrete or has a handle. +- For a table computed in the trace, an out-of-range target raises in eager execution, but under `jit` reads the field's boundary value without an error and the domain is not narrowed. Such values are data, so no concrete bounds exist at trace time. +- Connectivities reject item assignment, because their domain lookups are cached per buffer. + +Open questions, all caused by the handle: + +- The handle is a strong reference, so the jit cache keeps every table it has seen alive until `jax.clear_caches()`. Memory stays bounded when a run uses a fixed set of tables. +- A pytree transform of a connectivity (`tree_map`, `vmap`) inside a trace changes the child but not the handle, so domain inference silently uses the old values. This is unsupported, and nothing detects it. +- `shard_map` rejects the handle when the table is sharded, so distributed execution is not supported yet. + +## Alternatives considered + +### Bounds in the aux data instead of the table + +Storing only `(min, max)` retraces per bounds rather than per buffer and holds no table reference, but cannot answer narrowing ranges. + +### For tables computed in the trace: reject them, or mask with NaN + +Accepting only concrete tables rules out dynamic offsets under `jit`. NaN makes an out-of-range read visible, but does not work for integer fields and propagates into gradients. + +## References + +- [Design proposal](https://github.com/GridTools/gt4py_knowledge/pull/25) +- [ADR 0019 - Connectivities](0019-Connectivities.md) diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index f19167ef9b..d3317bd1b6 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -38,6 +38,7 @@ Writing a new ADR is simple: ### Embedded Execution - [0022 - Limitations of embedded concat_where](0022-Limitations-of-embedded-concat_where.md) +- [0029 - Connectivities Under JAX Tracing](0029-Connectivities_Under_JAX_Tracing.md) ### Transformations From f7f60f1600647ff76a2e0b8d14ddedb22cc5a301 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 30 Oct 2026 16:49:01 +0100 Subject: [PATCH 014/166] refactor[next]: move jax domain inference handling out of the connectivity 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. --- src/gt4py/next/embedded/nd_array_field.py | 34 +++++++++++-------- .../embedded_tests/test_nd_array_field.py | 7 ++++ 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index e221e1f52f..3405443b22 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -533,7 +533,7 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co assert isinstance(image_range, common.UnitRange) assert common.UnitRange.is_finite(image_range) - slices = self._image_slices(image_range) + slices = _hyperslice(self._index_table, image_range, self.array_ns, self.skip_value) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -548,10 +548,11 @@ def _index_table(self) -> core_defs.NDArrayObject: # the jax subclass answers with the concrete table behind the tracer return self._ndarray - @property - def _image_unknown(self) -> bool: - """Whether the table's values are not available for domain inference.""" - return False + def _gather_index( + self, index: core_defs.NDArrayObject, image_range: common.UnitRange + ) -> core_defs.NDArrayObject: + """The 0-based buffer indices the gather reads for `index` from a field on `image_range`.""" + return index def __setitem__( self, @@ -560,9 +561,6 @@ def __setitem__( ) -> Never: raise TypeError("'Connectivity' does not support item assignment.") - def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, ...]]: - return _hyperslice(self._index_table, image_range, self.array_ns, self.skip_value) - def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: cache_key = (id(self.ndarray), self.domain, index) @@ -646,13 +644,11 @@ def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: return _identity_index_array(new_domain, dim, xp) - start # skip entries read the domain start instead of wrapping around to an arbitrary element; # what is gathered there, and its cotangent, is left to the reduction mask to discard + assert isinstance(conn, NdArrayConnectivityField) index = ( _connectivity_index_array(conn, new_domain, xp, skip_value_replacement=start) - start ) - if getattr(conn, "_image_unknown", False): - # the output domain assumed all targets inside the field; out-of-range ones read its boundary - index = xp.clip(index, 0, len(data.domain[dim].unit_range) - 1) - return index + return conn._gather_index(index, data.domain[dim].unit_range) new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) @@ -1097,12 +1093,20 @@ def _index_table(self) -> core_defs.NDArrayObject: def _image_unknown(self) -> bool: return self._table_handle is None and isinstance(self._ndarray, jax.core.Tracer) - def _image_slices(self, image_range: common.UnitRange) -> Optional[tuple[slice, ...]]: + def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> common.Domain: if self._image_unknown: # values computed inside a trace: assume every target lies in `image_range` - return tuple(slice(0, n) for n in self._ndarray.shape) + return self.domain with jax.ensure_compile_time_eval(): - return super()._image_slices(image_range) + return super().inverse_image(image_range) + + def _gather_index( + self, index: core_defs.NDArrayObject, image_range: common.UnitRange + ) -> core_defs.NDArrayObject: + if self._image_unknown: + # the output domain assumed all targets inside the field; out-of-range ones read its boundary + return jnp.clip(index, 0, len(image_range) - 1) + return index def _restrict_buffer( self, new_domain: common.Domain, buffer_slice: common.RelativeIndexSequence diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index ae0a529cc4..a16fba28f6 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2019,6 +2019,13 @@ def shifted(field, offset_field): np.testing.assert_array_equal( jax.jit(shifted)(field, beyond).asnumpy(), np.repeat(values[:, -1:], 4, axis=1) ) + below = common._field(jax.numpy.asarray(np.full((2, 4), -3, dtype=np.int32)), domain=domain) + np.testing.assert_array_equal( + jax.jit(shifted)(field, below).asnumpy(), + np.take_along_axis( + values, np.maximum(np.arange(4) - 3, 0)[None, :].repeat(2, axis=0), axis=1 + ), + ) @pytest.mark.requires_jax From f7b443abae8835cc6f75a5c0fc96fec79682293a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 30 Oct 2026 16:54:09 +0100 Subject: [PATCH 015/166] refactor[next]: make Connectivity.inverse_image private It is an implementation detail of premap: nothing outside the embedded implementations calls it. --- .../0029-Connectivities_Under_JAX_Tracing.md | 2 +- src/gt4py/next/common.py | 4 +- src/gt4py/next/embedded/nd_array_field.py | 14 ++++--- src/gt4py/next/iterator/embedded.py | 2 +- .../embedded_tests/test_nd_array_field.py | 40 +++++++++---------- 5 files changed, 32 insertions(+), 30 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index c41cdcc678..b20ac7409c 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -15,7 +15,7 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t `premap` uses the table in two ways that pull in opposite directions: -- The **output domain** comes from `inverse_image`, which depends on the table's values. Under a trace it needs concrete values, and Python `slice`s cannot be staged. +- The **output domain** comes from `_inverse_image`, which depends on the table's values. Under a trace it needs concrete values, and Python `slice`s cannot be staged. - The **gather** should take the table as an argument of the compiled program. A closed-over table is inlined as a constant, which does not scale to large meshes. Narrowing is the common case: the field usually covers only part of the connectivity's image, so a solution that handles only covering ranges is not sufficient. diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index 5bc53f6474..c6a0e1d716 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -1017,7 +1017,7 @@ def __gt_type__(self) -> ConnectivityType: ) @abc.abstractmethod - def inverse_image(self, image_range: UnitRange | NamedRange) -> Sequence[NamedRange]: ... + def _inverse_image(self, image_range: UnitRange | NamedRange) -> Sequence[NamedRange]: ... @property @abc.abstractmethod @@ -1296,7 +1296,7 @@ def for_translation( def for_relocation(cls, old: DimT, new: DomainDimT) -> CartesianConnectivity[DomainDimT, DimT]: return cls(new, codomain=old) - def inverse_image(self, image_range: UnitRange | NamedRange) -> Sequence[NamedRange]: + def _inverse_image(self, image_range: UnitRange | NamedRange) -> Sequence[NamedRange]: if not isinstance(image_range, UnitRange): if image_range.dim != self.codomain: raise ValueError( diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 3405443b22..78d31eef99 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -510,13 +510,13 @@ def skip_value(self) -> Optional[core_defs.IntegralScalar]: return self._skip_value # This embedded run-time cache is only used to speed up repeated calls to - # `inverse_image` and `restrict`, and it should not be considered part of + # `_inverse_image` and `restrict`, and it should not be considered part of # the connectivity field definition, and therefore it should not be serialized. @functools.cached_property def _cache(self) -> dict: return {} - def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> common.Domain: + def _inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> common.Domain: cache_key = hash((id(self.ndarray), self.domain, image_range)) if (new_domain := self._cache.get(cache_key, None)) is None: @@ -594,7 +594,7 @@ def _domain_premap(data: NdArrayField, *connectivities: common.Connectivity) -> ) current_range: common.UnitRange = data.domain[dim_idx].unit_range - new_ranges = connectivity.inverse_image(current_range) + new_ranges = connectivity._inverse_image(current_range) new_domain = new_domain.replace(dim_idx, *new_ranges) return data.__class__.from_array(data._ndarray, domain=new_domain, dtype=data.dtype) @@ -610,7 +610,7 @@ def _gather_output_domain( cod = conn.codomain # the connectivity's domain, restricted to where it maps into the codomain's range narrowed = { - nr.dim: nr.unit_range for nr in conn.inverse_image(field_domain[cod].unit_range) + nr.dim: nr.unit_range for nr in conn._inverse_image(field_domain[cod].unit_range) } # dimensions the connectivity adds that are not in the field yet introduced = [ @@ -1093,12 +1093,14 @@ def _index_table(self) -> core_defs.NDArrayObject: def _image_unknown(self) -> bool: return self._table_handle is None and isinstance(self._ndarray, jax.core.Tracer) - def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> common.Domain: + def _inverse_image( + self, image_range: common.UnitRange | common.NamedRange + ) -> common.Domain: if self._image_unknown: # values computed inside a trace: assume every target lies in `image_range` return self.domain with jax.ensure_compile_time_eval(): - return super().inverse_image(image_range) + return super()._inverse_image(image_range) def _gather_index( self, index: core_defs.NDArrayObject, image_range: common.UnitRange diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index c8ba839a8c..41b204d1ff 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -175,7 +175,7 @@ def __call__( __getitem__ = restrict # type: ignore[assignment] - def inverse_image( + def _inverse_image( self, image_range: common.UnitRange | common.NamedRange ) -> Sequence[common.NamedRange]: raise NotImplementedError diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index a16fba28f6..ac6c471033 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1348,7 +1348,7 @@ def test_nd_array_connectivity_field_getstate_excludes_runtime_caches(): codomain=V, ) - _ = e2v_conn.inverse_image(UnitRange(2, 5)) + _ = e2v_conn._inverse_image(UnitRange(2, 5)) assert "_cache" in e2v_conn.__dict__ _ = e2v_conn.__gt_buffer_info__ @@ -1430,32 +1430,32 @@ def test_connectivity_field_inverse_image_2d_domain(): # For the 'c2v_conn' defined above, the only valid range including 2 # is [0, 3). Otherwise, the inverse image would be non-contiguous. image_range = UnitRange(V_START, V_STOP) - result = c2v_conn.inverse_image(image_range) + result = c2v_conn._inverse_image(image_range) assert len(result) == 2 assert result[0] == (C, UnitRange(C_START, C_STOP)) assert result[1] == (C2V, UnitRange(C2V_START, C2V_STOP)) - result = c2v_conn.inverse_image(UnitRange(0, 2)) + result = c2v_conn._inverse_image(UnitRange(0, 2)) assert len(result) == 2 assert result[0] == (C, UnitRange(0, 2)) assert result[1] == (C2V, UnitRange(0, 2)) - result = c2v_conn.inverse_image(UnitRange(0, 1)) + result = c2v_conn._inverse_image(UnitRange(0, 1)) assert len(result) == 2 assert result[0] == (C, UnitRange(0, 1)) assert result[1] == (C2V, UnitRange(0, 2)) - result = c2v_conn.inverse_image(UnitRange(1, 2)) + result = c2v_conn._inverse_image(UnitRange(1, 2)) assert len(result) == 2 assert result[0] == (C, UnitRange(1, 2)) assert result[1] == (C2V, UnitRange(0, 2)) with pytest.raises(ValueError, match="generates non-contiguous"): - result = c2v_conn.inverse_image(UnitRange(1, 3)) + result = c2v_conn._inverse_image(UnitRange(1, 3)) with pytest.raises(ValueError, match="generates non-contiguous"): - result = c2v_conn.inverse_image(UnitRange(2, 3)) + result = c2v_conn._inverse_image(UnitRange(2, 3)) def test_connectivity_field_inverse_image_non_contiguous(): @@ -1471,14 +1471,14 @@ def test_connectivity_field_inverse_image_non_contiguous(): codomain=V, ) - result = e2v_conn.inverse_image(UnitRange(V_START, 5)) + result = e2v_conn._inverse_image(UnitRange(V_START, 5)) assert result[0] == (E, UnitRange(V_START, 5)) with pytest.raises(ValueError, match="generates non-contiguous"): - e2v_conn.inverse_image(UnitRange(V_START, 6)) + e2v_conn._inverse_image(UnitRange(V_START, 6)) with pytest.raises(ValueError, match="generates non-contiguous"): - e2v_conn.inverse_image(UnitRange(V_START, V_STOP)) + e2v_conn._inverse_image(UnitRange(V_START, V_STOP)) def test_connectivity_field_inverse_image_2d_domain_skip_values(): @@ -1510,32 +1510,32 @@ def test_connectivity_field_inverse_image_2d_domain_skip_values(): # | [-1 2 -1 -1]] image_range = UnitRange(V_START, V_STOP) - result = c2v_conn.inverse_image(image_range) + result = c2v_conn._inverse_image(image_range) assert len(result) == 2 assert result[0] == (C, UnitRange(C_START, C_STOP)) assert result[1] == (C2V, UnitRange(C2V_START, C2V_STOP)) - result = c2v_conn.inverse_image(UnitRange(0, 2)) + result = c2v_conn._inverse_image(UnitRange(0, 2)) assert len(result) == 2 assert result[0] == (C, UnitRange(0, 2)) assert result[1] == (C2V, UnitRange(0, 2)) - result = c2v_conn.inverse_image(UnitRange(0, 1)) + result = c2v_conn._inverse_image(UnitRange(0, 1)) assert len(result) == 2 assert result[0] == (C, UnitRange(0, 1)) assert result[1] == (C2V, UnitRange(1, 2)) - result = c2v_conn.inverse_image(UnitRange(1, 2)) + result = c2v_conn._inverse_image(UnitRange(1, 2)) assert len(result) == 2 assert result[0] == (C, UnitRange(1, 2)) assert result[1] == (C2V, UnitRange(0, 2)) with pytest.raises(ValueError, match="generates non-contiguous"): - result = c2v_conn.inverse_image(UnitRange(1, 3)) + result = c2v_conn._inverse_image(UnitRange(1, 3)) with pytest.raises(ValueError, match="generates non-contiguous"): - result = c2v_conn.inverse_image(UnitRange(2, 3)) + result = c2v_conn._inverse_image(UnitRange(2, 3)) @pytest.mark.parametrize( @@ -1893,8 +1893,8 @@ def test_inverse_image_range_containing_skip_value_selects_skip_only_rows(): skip_value=-1, ) - assert conn.inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 1), D2: (0, 2)}) - assert conn.inverse_image(UnitRange(-1, 2)) == common.domain({D1: (0, 2), D2: (0, 2)}) + assert conn._inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 1), D2: (0, 2)}) + assert conn._inverse_image(UnitRange(-1, 2)) == common.domain({D1: (0, 2), D2: (0, 2)}) @pytest.mark.requires_jax @@ -1917,7 +1917,7 @@ def test_jax_connectivity_pytree_roundtrip(): assert restored.domain == domain assert restored.codomain == V assert restored.skip_value == -1 - assert restored.inverse_image(UnitRange(0, 2)) == common.domain({E: (0, 1), E2VDim: (0, 2)}) + assert restored._inverse_image(UnitRange(0, 2)) == common.domain({E: (0, 1), E2VDim: (0, 2)}) same_table = common._connectivity(table, codomain=V, domain=domain, skip_value=-1) assert jax.tree_util.tree_structure(same_table) == treedef @@ -2100,7 +2100,7 @@ def test_inverse_image_empty_table_raises(): ) with pytest.raises(ValueError, match="non-contiguous or empty"): - conn.inverse_image(UnitRange(0, 4)) + conn._inverse_image(UnitRange(0, 4)) def test_neighbor_sum_with_transposed_table_dims(): From 865944c4f6f39329b7dd3604a2fb0f4869632aa9 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 2 Nov 2026 14:21:21 +0100 Subject: [PATCH 016/166] refactor[next]: restrict Connectivity._inverse_image to UnitRange All callers pass a UnitRange, so the NamedRange branch and its dimension check were unreachable. --- src/gt4py/next/common.py | 13 ++----------- src/gt4py/next/embedded/nd_array_field.py | 17 ++--------------- src/gt4py/next/iterator/embedded.py | 4 +--- 3 files changed, 5 insertions(+), 29 deletions(-) diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index c6a0e1d716..9675e08462 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -1017,7 +1017,7 @@ def __gt_type__(self) -> ConnectivityType: ) @abc.abstractmethod - def _inverse_image(self, image_range: UnitRange | NamedRange) -> Sequence[NamedRange]: ... + def _inverse_image(self, image_range: UnitRange) -> Sequence[NamedRange]: ... @property @abc.abstractmethod @@ -1296,16 +1296,7 @@ def for_translation( def for_relocation(cls, old: DimT, new: DomainDimT) -> CartesianConnectivity[DomainDimT, DimT]: return cls(new, codomain=old) - def _inverse_image(self, image_range: UnitRange | NamedRange) -> Sequence[NamedRange]: - if not isinstance(image_range, UnitRange): - if image_range.dim != self.codomain: - raise ValueError( - f"Dimension '{image_range.dim}' does not match the codomain dimension '{self.codomain}'." - ) - - image_range = image_range.unit_range - - assert isinstance(image_range, UnitRange) + def _inverse_image(self, image_range: UnitRange) -> Sequence[NamedRange]: return (named_range((self.domain_dim, image_range - self.offset)),) def premap( diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 78d31eef99..76577ccc10 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -516,21 +516,10 @@ def skip_value(self) -> Optional[core_defs.IntegralScalar]: def _cache(self) -> dict: return {} - def _inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> common.Domain: + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: cache_key = hash((id(self.ndarray), self.domain, image_range)) if (new_domain := self._cache.get(cache_key, None)) is None: - if not isinstance( - image_range, common.UnitRange - ): # TODO(havogt): cleanup duplication with CartesianConnectivity - if image_range.dim != self.codomain: - raise ValueError( - f"Dimension '{image_range.dim}' does not match the codomain dimension '{self.codomain}'." - ) - - image_range = image_range.unit_range - - assert isinstance(image_range, common.UnitRange) assert common.UnitRange.is_finite(image_range) slices = _hyperslice(self._index_table, image_range, self.array_ns, self.skip_value) @@ -1093,9 +1082,7 @@ def _index_table(self) -> core_defs.NDArrayObject: def _image_unknown(self) -> bool: return self._table_handle is None and isinstance(self._ndarray, jax.core.Tracer) - def _inverse_image( - self, image_range: common.UnitRange | common.NamedRange - ) -> common.Domain: + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if self._image_unknown: # values computed inside a trace: assume every target lies in `image_range` return self.domain diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 41b204d1ff..69bd469d8b 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -175,9 +175,7 @@ def __call__( __getitem__ = restrict # type: ignore[assignment] - def _inverse_image( - self, image_range: common.UnitRange | common.NamedRange - ) -> Sequence[common.NamedRange]: + def _inverse_image(self, image_range: common.UnitRange) -> Sequence[common.NamedRange]: raise NotImplementedError @property From 7d69dd8aa2738e51f26a8d5effbcc86ccccfe6e7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 2 Nov 2026 15:59:02 +0100 Subject: [PATCH 017/166] fix[next]: address review findings on jax connectivities - 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. --- src/gt4py/next/common.py | 4 +- src/gt4py/next/embedded/nd_array_field.py | 34 ++++- src/gt4py/next/ffront/fbuiltins.py | 17 +-- .../embedded_tests/test_nd_array_field.py | 119 +++++++++++++++++- 4 files changed, 147 insertions(+), 27 deletions(-) diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index 9675e08462..431ae55dee 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -1416,10 +1416,10 @@ def __init_subclass__(cls, **kwargs: Any) -> None: def register_builtin_func( cls, /, op: fbuiltins.BuiltInFunction[_R, _P], op_func: Optional[Callable[_P, _R]] = None ) -> Any: - assert op not in cls._builtin_func_map + assert op not in cls._builtin_func_map.maps[0] if op_func is None: # when used as a decorator return functools.partial(cls.register_builtin_func, op) - return cls._builtin_func_map.setdefault(op, op_func) + return cls._builtin_func_map.maps[0].setdefault(op, op_func) @classmethod def __gt_builtin_func__(cls, /, func: fbuiltins.BuiltInFunction[_R, _P]) -> Callable[_P, _R]: diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 76577ccc10..a8f9684aa3 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -650,7 +650,23 @@ def _connectivity_index_array( *, skip_value_replacement: Optional[core_defs.IntegralScalar] = None, ) -> core_defs.NDArrayObject: - """`connectivity`'s index table laid out over `domain` (not yet shifted to 0-based).""" + """`connectivity`'s index table broadcast over `domain` (not yet shifted to 0-based).""" + arr = _aligned_connectivity_table( + connectivity, domain, xp, skip_value_replacement=skip_value_replacement + ) + if arr.shape != domain.shape: + arr = xp.broadcast_to(arr, domain.shape) # broadcast the size-1 axes to the full shape + return arr + + +def _aligned_connectivity_table( + connectivity: common.GatherConnectivity, + domain: common.Domain, + xp: ModuleType, + *, + skip_value_replacement: Optional[core_defs.IntegralScalar] = None, +) -> core_defs.NDArrayObject: + """`connectivity`'s index table with one axis per dimension of `domain`, size 1 where it has none.""" # restrict the table to the output ranges of the connectivity's own dimensions sub_domain = common.Domain(*(domain[d] for d in connectivity.domain.dims)) conn = connectivity if sub_domain == connectivity.domain else connectivity.restrict(sub_domain) @@ -668,10 +684,7 @@ def _connectivity_index_array( ) if fresh_axis: # add size-1 axes for output dimensions the connectivity does not span arr = xp.expand_dims(arr, axis=tuple(fresh_axis.values())) - arr = xp.transpose(arr, transposed_axes) # reorder to the output dimension order - if arr.shape != domain.shape: - arr = xp.broadcast_to(arr, domain.shape) # broadcast the size-1 axes to the full shape - return arr + return xp.transpose(arr, transposed_axes) # reorder to the output dimension order def _identity_index_array( @@ -957,7 +970,7 @@ def _builtin_op( values = field.ndarray else: assert isinstance(offset_definition, common.GatherConnectivity) - table = _connectivity_index_array(offset_definition, field.domain, xp) + table = _aligned_connectivity_table(offset_definition, field.domain, xp) values = xp.where( table != offset_definition.skip_value, field.ndarray, initial_value_op(field) ) @@ -1118,6 +1131,15 @@ def _restrict_buffer( handle, ) + def _jax_as_offset( + offset: fbuiltins.FieldOffset, offset_field: NdArrayField + ) -> common.Connectivity: + # without this, adding the coordinates stages the table even for concrete offsets + with jax.ensure_compile_time_eval(): + return _as_offset(offset, offset_field) + + JaxArrayField.register_builtin_func(experimental.as_offset, _jax_as_offset) # type: ignore[arg-type] + common._field.register(jnp.ndarray, JaxArrayField.from_array) common._connectivity.register(jnp.ndarray, JaxArrayConnectivityField.from_array) # jax >= 0.11: 'Tracer' is no longer a subclass of 'jax.Array' (only 'isinstance' says so, via diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 2fd072a483..045098bf76 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -7,7 +7,6 @@ # SPDX-License-Identifier: BSD-3-Clause import dataclasses -import functools import inspect import math import operator @@ -485,10 +484,6 @@ class FieldOffset(runtime.Offset): source: common.Dimension target: tuple[common.Dimension] | tuple[common.Dimension, common.Dimension] - @functools.cached_property - def _cache(self) -> dict: - return {} - def __post_init__(self) -> None: if len(self.target) == 2 and self.target[1].kind != common.DimensionKind.LOCAL: raise ValueError("Second dimension in offset must be a local dimension.") @@ -520,16 +515,10 @@ def as_connectivity_field(self) -> common.Connectivity: assert current_offset_provider is not None offset_definition = common.get_offset(current_offset_provider, self.value) - cache_key = id(offset_definition) - if (connectivity := self._cache.get(cache_key, None)) is None: - if isinstance(offset_definition, common.Connectivity): - connectivity = offset_definition - else: - raise NotImplementedError() - - self._cache[cache_key] = connectivity + if not isinstance(offset_definition, common.Connectivity): + raise NotImplementedError() - return connectivity + return offset_definition def is_cartesian_offset(offset: FieldOffset | ts.OffsetType) -> bool: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index ac6c471033..4142170142 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1963,7 +1963,9 @@ def premap_and_reduce(field, conn): stablehlo = jitted.lower(field, conn).as_text() main_arguments = re.search(r"@main\(([^)]*)\)", stablehlo).group(1) assert f"tensor<{table.shape[0]}x2xi32>" in main_arguments - assert "dense<[" not in stablehlo # the table is not inlined as a constant + # large constants print as hex + assert 'dense<"0x' not in stablehlo + assert 'dense<"0x' in jax.jit(lambda field: field.premap(conn)).lower(field).as_text() @pytest.mark.requires_jax @@ -1973,17 +1975,18 @@ def test_jax_jit_premap_with_closed_over_restricted_connectivity(): V = Dimension("V") E = Dimension("E") E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - table = np.asarray([[0, 1], [1, 2], [2, 0]], dtype=np.int32) + table = np.asarray([[0, 1], [1, 0], [2, 2]], dtype=np.int32) conn = common._connectivity( jax.numpy.asarray(table), codomain=V, domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), ) - field = common._field(jax.numpy.arange(3, dtype=np.float64), domain=common.domain({V: (0, 3)})) + field = common._field(jax.numpy.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) result = jax.jit(lambda field: field.premap(conn[common.NamedIndex(E2VDim, 1)]))(field) - np.testing.assert_array_equal(result.asnumpy(), table[:, 1]) + assert result.domain == common.domain({E: (0, 2)}) + np.testing.assert_array_equal(result.asnumpy(), [20.0, 10.0]) @pytest.mark.requires_jax @@ -2000,7 +2003,7 @@ def test_jax_jit_premap_with_as_offset_computed_in_trace(): offsets = np.asarray([[1, 1, 0, -1], [0, 2, 1, 0]], dtype=np.int32) def shifted(field, offset_field): - return field.premap(experimental.as_offset(Koff, offset_field + 0)) + return field.premap(experimental.as_offset(Koff, offset_field)) field = common._field(jax.numpy.asarray(values), domain=domain) offset_field = common._field(jax.numpy.asarray(offsets), domain=domain) @@ -2028,6 +2031,112 @@ def shifted(field, offset_field): ) +@pytest.mark.requires_jax +def test_jax_jit_premap_with_closed_over_as_offset_narrows_like_eager(): + import jax + + from gt4py.next.ffront import experimental + + K = Dimension("K", kind=DimensionKind.VERTICAL) + Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) + domain = common.domain({K: (0, 4)}) + field = common._field(jax.numpy.asarray([0.0, 1.0, 2.0, 3.0]), domain=domain) + offset_field = common._field(jax.numpy.ones(4, dtype=np.int32), domain=domain) + + result = jax.jit(lambda field: field.premap(experimental.as_offset(Koff, offset_field)))(field) + + assert result.domain == common.domain({K: (0, 3)}) + np.testing.assert_array_equal(result.asnumpy(), [1.0, 2.0, 3.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_field_offset_does_not_leak_tracers(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + E2V = fbuiltins.FieldOffset("E2V", source=V, target=(E, E2VDim)) + conn = common._connectivity( + jax.numpy.asarray([[0, 1], [2, 3]], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + ) + field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) + + def shifted(field, conn): + with embedded_context.update(offset_provider={"E2V": conn}): + return field(E2V) + + with jax.checking_leaks(): + result = jax.jit(shifted)(field, conn) + + np.testing.assert_array_equal(result.asnumpy(), [[0.0, 1.0], [2.0, 3.0]]) + + +@pytest.mark.requires_jax +def test_nested_jax_jit_premap_narrows(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + conn = common._connectivity( + jax.numpy.asarray([[0, 1], [2, 3], [4, 5]], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + ) + field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) + + inner = jax.jit(lambda field, conn: field.premap(conn)) + result = jax.jit(lambda field, conn: inner(field, conn))(field, conn) + + assert result.domain == common.domain({E: (0, 2), E2VDim: (0, 2)}) + np.testing.assert_array_equal(result.asnumpy(), [[0.0, 1.0], [2.0, 3.0]]) + + +def test_neighbor_sum_with_custom_skip_value_and_nonzero_domain_start(): + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + conn = common._connectivity( + np.asarray([[11, 12], [13, 99]]), + codomain=V, + domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + skip_value=99, + ) + field = common._field(np.asarray([1.0, 2.0, 4.0, 8.0]), domain=common.domain({V: (10, 14)})) + + with embedded_context.update(offset_provider={"E2V": conn}): + result = fbuiltins.neighbor_sum(field.premap(conn), axis=E2VDim) + + np.testing.assert_array_equal(result.asnumpy(), [6.0, 8.0]) + + +def test_neighbor_sum_over_infinite_range(): + E = Dimension("E") + K = Dimension("K", kind=DimensionKind.VERTICAL) + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + conn = common._connectivity( + np.asarray([[0, 1], [2, -1]]), + codomain=Dimension("V"), + domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + skip_value=-1, + ) + field = common._field( + np.asarray([[1.0, 2.0], [4.0, 8.0]]), domain=common.domain({E: (0, 2), E2VDim: (0, 2)}) + ) + broadcasted = fbuiltins.broadcast(field, (E, E2VDim, K)) + + with embedded_context.update(offset_provider={"E2V": conn}): + result = fbuiltins.neighbor_sum(broadcasted, axis=E2VDim) + + assert result.domain == common.Domain( + common.named_range((E, (0, 2))), common.NamedRange(K, common.UnitRange.infinite()) + ) + np.testing.assert_array_equal(result.ndarray.ravel(), [3.0, 4.0]) + + @pytest.mark.requires_jax def test_jax_jit_retraces_per_connectivity_buffer(): import jax From 2ee7af1036d2a1b2d9c4011ecf2b3cb2b611fcf2 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 2 Nov 2026 15:59:02 +0100 Subject: [PATCH 018/166] docs[next]: correct as_offset behaviour and state the skip-value gradient limit in the ADR --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index b20ac7409c..a60004d2ff 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -27,13 +27,14 @@ Narrowing is the common case: the field usually covers only part of the connecti How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: - **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer, and flattening attached the handle. Domain inference reads the concrete table through the handle, and the gather takes the table as a runtime argument. -- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. -- **Computed inside the trace** (`as_offset(Koff, offset_field)`, where the offsets are data). The table is a tracer with no handle, because no concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. +- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way. +- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field). The table is a tracer with no handle, because no concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. ## Consequences - Domains under `jit` match eager execution when the table is concrete or has a handle. -- For a table computed in the trace, an out-of-range target raises in eager execution, but under `jit` reads the field's boundary value without an error and the domain is not narrowed. Such values are data, so no concrete bounds exist at trace time. +- A table computed from traced values behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. +- Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached per buffer. Open questions, all caused by the handle: From a8198a1023cf781c2df0980b02085529e3f93cdb Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 2 Nov 2026 16:25:18 +0100 Subject: [PATCH 019/166] docs[next]: say when a closed-over as_offset field stops being concrete --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index a60004d2ff..8852fb9f0c 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -27,7 +27,7 @@ Narrowing is the common case: the field usually covers only part of the connecti How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: - **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer, and flattening attached the handle. Domain inference reads the concrete table through the handle, and the gather takes the table as a runtime argument. -- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way. +- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). - **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field). The table is a tracer with no handle, because no concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. ## Consequences From 4179b9e5af2b7de3261fc18977aa334ec8166d6a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 17:18:21 +0100 Subject: [PATCH 020/166] fix[next]: type-check the jax connectivity code with jax installed, assert in the inverse-image test Also state in the ADR that writing into a connectivity buffer through `.ndarray` is not supported. --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 2 +- src/gt4py/next/embedded/nd_array_field.py | 4 ++-- .../unit_tests/embedded_tests/test_nd_array_field.py | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 8852fb9f0c..d85b306fc8 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -35,7 +35,7 @@ How a `premap` behaves under `jit` depends on how its connectivity reaches the c - Domains under `jit` match eager execution when the table is concrete or has a handle. - A table computed from traced values behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. -- Connectivities reject item assignment, because their domain lookups are cached per buffer. +- Connectivities reject item assignment, because their domain lookups are cached per buffer. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. Open questions, all caused by the handle: diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index a8f9684aa3..24e3b90f8a 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -1107,7 +1107,7 @@ def _gather_index( ) -> core_defs.NDArrayObject: if self._image_unknown: # the output domain assumed all targets inside the field; out-of-range ones read its boundary - return jnp.clip(index, 0, len(image_range) - 1) + return jnp.clip(index, 0, len(image_range) - 1) # type: ignore[arg-type, return-value] # `NDArrayObject` typing is not complete return index def _restrict_buffer( @@ -1125,7 +1125,7 @@ def _restrict_buffer( new_buffer = jnp.asarray(self._ndarray[buffer_slice]) return JaxArrayConnectivityField( new_domain, - new_buffer, + new_buffer, # type: ignore[arg-type] # `NDArrayObject` typing is not complete self.codomain, self.skip_value, handle, diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 4142170142..c629d0ea4b 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1399,6 +1399,9 @@ def test_connectivity_field_inverse_image(): codomain=V, ) + # the table is [9, 0, 1, ..., 8]: values 2..6 sit at positions 3..7 + assert e2v_conn._inverse_image(UnitRange(V_START, V_STOP)) == common.domain({E: (3, 8)}) + def test_connectivity_field_inverse_image_2d_domain(): V = Dimension("V") From db4bf55b102391e137b03beb0d957d964215b705 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 17:19:03 +0100 Subject: [PATCH 021/166] fix[next]: keep the jax type ignores valid when jax is not installed --- src/gt4py/next/embedded/nd_array_field.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 24e3b90f8a..93baea1ef0 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -1107,7 +1107,7 @@ def _gather_index( ) -> core_defs.NDArrayObject: if self._image_unknown: # the output domain assumed all targets inside the field; out-of-range ones read its boundary - return jnp.clip(index, 0, len(image_range) - 1) # type: ignore[arg-type, return-value] # `NDArrayObject` typing is not complete + return jnp.clip(index, 0, len(image_range) - 1) # type: ignore[arg-type, return-value, unused-ignore] # `NDArrayObject` typing is not complete return index def _restrict_buffer( @@ -1125,7 +1125,7 @@ def _restrict_buffer( new_buffer = jnp.asarray(self._ndarray[buffer_slice]) return JaxArrayConnectivityField( new_domain, - new_buffer, # type: ignore[arg-type] # `NDArrayObject` typing is not complete + new_buffer, # type: ignore[arg-type, unused-ignore] # `NDArrayObject` typing is not complete self.codomain, self.skip_value, handle, From fa9855102d4f0e91a37391e7a1c81f44a68e0441 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 17:35:20 +0100 Subject: [PATCH 022/166] test[next]: drop tests of removed shortcut code and pytree internals Also date the ADR to the current state. --- .../0029-Connectivities_Under_JAX_Tracing.md | 4 +- .../embedded_tests/test_nd_array_field.py | 53 ------------------- 2 files changed, 2 insertions(+), 55 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index d85b306fc8..0a912ef84f 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -6,8 +6,8 @@ tags: [embedded, jax, connectivities] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) -- **Created**: 2026-10-30 -- **Updated**: 2026-10-30 +- **Created**: 2026-11-06 +- **Updated**: 2026-11-06 In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to register jax connectivities as pytree nodes that carry a handle to the concrete table, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime. diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index c629d0ea4b..5123d86e10 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1888,48 +1888,6 @@ def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: return table -def test_inverse_image_range_containing_skip_value_selects_skip_only_rows(): - conn = common._connectivity( - np.asarray([[0, 1], [-1, -1]]), - codomain=D0, - domain=common.domain({D1: (0, 2), D2: (0, 2)}), - skip_value=-1, - ) - - assert conn._inverse_image(UnitRange(0, 2)) == common.domain({D1: (0, 1), D2: (0, 2)}) - assert conn._inverse_image(UnitRange(-1, 2)) == common.domain({D1: (0, 2), D2: (0, 2)}) - - -@pytest.mark.requires_jax -def test_jax_connectivity_pytree_roundtrip(): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - domain = common.domain({E: (0, 2), E2VDim: (0, 2)}) - table = jax.numpy.asarray([[0, 1], [2, -1]], dtype=np.int32) - conn = common._connectivity(table, codomain=V, domain=domain, skip_value=-1) - - children, treedef = jax.tree_util.tree_flatten(conn) - assert len(children) == 1 - assert children[0] is table - - restored = jax.tree_util.tree_unflatten(treedef, children) - assert isinstance(restored, nd_array_field.JaxArrayConnectivityField) - assert restored.domain == domain - assert restored.codomain == V - assert restored.skip_value == -1 - assert restored._inverse_image(UnitRange(0, 2)) == common.domain({E: (0, 1), E2VDim: (0, 2)}) - - same_table = common._connectivity(table, codomain=V, domain=domain, skip_value=-1) - assert jax.tree_util.tree_structure(same_table) == treedef - copied_table = common._connectivity( - jax.numpy.array(table, copy=True), codomain=V, domain=domain, skip_value=-1 - ) - assert jax.tree_util.tree_structure(copied_table) != treedef - - @pytest.mark.requires_jax @pytest.mark.parametrize("num_field_vertices", [300, 600], ids=["narrowing", "covering"]) def test_jax_jit_premap_with_connectivity_argument(num_field_vertices): @@ -2204,17 +2162,6 @@ def test_connectivity_field_setitem_raises(): conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) -def test_inverse_image_empty_table_raises(): - conn = common._connectivity( - np.zeros((0, 2), dtype=np.int32), - codomain=D0, - domain=common.domain({D1: (0, 0), D2: (0, 2)}), - ) - - with pytest.raises(ValueError, match="non-contiguous or empty"): - conn._inverse_image(UnitRange(0, 4)) - - def test_neighbor_sum_with_transposed_table_dims(): V = Dimension("V") E = Dimension("E") From 3ad1c756f135810794666057cbdac380ccb246fc Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 17:38:57 +0100 Subject: [PATCH 023/166] docs[next]: note in the ADR that the jax gather clamp may be cheaper with a no-wrap gather --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 0a912ef84f..7b9387b63a 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -34,6 +34,7 @@ How a `premap` behaves under `jit` depends on how its connectivity reaches the c - Domains under `jit` match eager execution when the table is concrete or has a handle. - A table computed from traced values behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. +- The clamp is only partly redundant with jax's own indexing, which clamps indices past the end but wraps negative ones as NumPy does. It compiles to an extra clamp next to the select jax emits for negative indices. A gather with `mode="clip", wrap_negative_indices=False` clamps both ends with no extra operations; whether that makes jax code faster is still to be investigated. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached per buffer. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. From 2571afb586e73b450db03b134d45b69d5044899c Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 20:23:46 +0100 Subject: [PATCH 024/166] refactor[next]: one NdArrayField for all array libraries, operations 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'. --- src/gt4py/next/embedded/__init__.py | 4 +- src/gt4py/next/embedded/array_libraries.py | 132 ++++++ src/gt4py/next/embedded/array_ops.py | 216 +++++++++ src/gt4py/next/embedded/nd_array_field.py | 413 ++++++++---------- src/gt4py/next/field_utils.py | 13 +- src/gt4py/next/otf/compilation_tasks.py | 2 +- tests/next_tests/definitions.py | 19 +- tests/next_tests/unit_tests/conftest.py | 28 +- .../embedded_tests/test_nd_array_field.py | 10 +- 9 files changed, 576 insertions(+), 261 deletions(-) create mode 100644 src/gt4py/next/embedded/array_libraries.py create mode 100644 src/gt4py/next/embedded/array_ops.py diff --git a/src/gt4py/next/embedded/__init__.py b/src/gt4py/next/embedded/__init__.py index 767fd5fc91..cf7ed12fdd 100644 --- a/src/gt4py/next/embedded/__init__.py +++ b/src/gt4py/next/embedded/__init__.py @@ -6,7 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -from . import common, context, exceptions, nd_array_field +from . import array_libraries, array_ops, common, context, exceptions, nd_array_field -__all__ = ["common", "context", "exceptions", "nd_array_field"] +__all__ = ["array_libraries", "array_ops", "common", "context", "exceptions", "nd_array_field"] diff --git a/src/gt4py/next/embedded/array_libraries.py b/src/gt4py/next/embedded/array_libraries.py new file mode 100644 index 0000000000..d71e167eb2 --- /dev/null +++ b/src/gt4py/next/embedded/array_libraries.py @@ -0,0 +1,132 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""`ArrayOps` of the array libraries whose arrays need more than the Array API standard.""" + +from __future__ import annotations + +import importlib.util +import math +from collections.abc import Callable +from types import ModuleType +from typing import Any + +import array_api_compat +import numpy as np + +from gt4py._core import definitions as core_defs +from gt4py.next import common +from gt4py.next.embedded import array_ops, nd_array_field + + +def _np_gamma(a: core_defs.NDArrayObject) -> core_defs.NDArrayObject: + try: + from scipy.special import gamma + except ImportError: + return np.vectorize(math.gamma, otypes=[a.dtype])(a) + return gamma(a) + + +class NumPyOps(array_ops.ArrayOps): + @property + def array_ns(self) -> ModuleType: + return np + + def asarray( + self, + data: Any, + *, + dtype: Any = None, + like: core_defs.NDArrayObject | None = None, + ) -> core_defs.NDArrayObject: + return np.asarray(data, dtype=dtype) # type: ignore[return-value] # `NDArrayObject` typing is not complete + + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + return value + + def _elementwise(self, name: str) -> Callable[..., Any]: + if name == "gamma": + return _np_gamma + return super()._elementwise(name) + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + return np.asarray(array) + + +class CuPyOps(array_ops.ArrayOps): + @property + def array_ns(self) -> ModuleType: + import cupy as cp + + return cp + + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + return value + + def _elementwise(self, name: str) -> Callable[..., Any]: + if name == "gamma": + import cupyx.scipy.special + + return cupyx.scipy.special.gamma + return super()._elementwise(name) + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + import cupy as cp + + return cp.asnumpy(array) + + +class JaxOps(array_ops.ArrayOps): + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + return value + + def _elementwise(self, name: str) -> Callable[..., Any]: + if name == "gamma": + import jax.scipy.special + + return jax.scipy.special.gamma + return super()._elementwise(name) + + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + return np.asarray(array) + + def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: + raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") + + +array_ops.register(array_api_compat.is_numpy_namespace, NumPyOps) +array_ops.register(array_api_compat.is_cupy_namespace, CuPyOps) +array_ops.register(array_api_compat.is_jax_namespace, JaxOps) + + +if importlib.util.find_spec("jax") is not None: + import jax + + # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config + jax.config.update("jax_enable_x64", True) + + def _flatten_field( + field: nd_array_field.NdArrayField, + ) -> tuple[tuple[core_defs.NDArrayObject], common.Domain]: + return (field.ndarray,), field.domain + + def _unflatten_field( + domain: common.Domain, children: tuple[core_defs.NDArrayObject] + ) -> nd_array_field.NdArrayField: + return nd_array_field.NdArrayField(domain, children[0]) # type: ignore[abstract] # mypy does not see '__gt_builtin_func__' as implemented by 'FieldBuiltinFuncRegistry' + + jax.tree_util.register_pytree_node( + nd_array_field.NdArrayField, # type: ignore[type-abstract, unused-ignore] # only reported when 'jax' is installed, see '_unflatten_field' + _flatten_field, + _unflatten_field, + ) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py new file mode 100644 index 0000000000..c703bd5511 --- /dev/null +++ b/src/gt4py/next/embedded/array_ops.py @@ -0,0 +1,216 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +Array operations of the embedded fields, per array namespace. + +`ArrayOps` implements everything `NdArrayField` does on its buffer against the +Array API standard, through the namespace `array_api_compat` returns for the +buffer. Any standard-conforming array library works without registration. + +A library that needs different behaviour, or has a faster path outside the +standard, subclasses `ArrayOps`, overrides only those methods and is registered +with `register`. The registry is keyed by a predicate on the compat namespace and +holds a factory, so registering a library does not import it. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from types import ModuleType +from typing import Any, ClassVar, Final + +import array_api_compat +import array_api_compat.numpy as compat_numpy +import numpy as np + +from gt4py._core import definitions as core_defs, types as core_types +from gt4py.next import common + + +#: gt4py builtin and operator names whose Array API name differs. +STANDARD_NAMES: Final[Mapping[str, str]] = { + "neg": "negative", + "pos": "positive", + "sub": "subtract", + "mul": "multiply", + "div": "divide", + "floordiv": "floor_divide", + "power": "pow", + "pow": "pow", + "mod": "remainder", + "invert": "logical_not", + "arcsin": "asin", + "arccos": "acos", + "arctan": "atan", + "arcsinh": "asinh", + "arccosh": "acosh", + "arctanh": "atanh", +} + + +class ArrayOps: + """ + Operations on the buffers of embedded fields for one array namespace. + + `xp` is the Array API namespace of the buffers. Field code uses `xp` directly + for standard functions and the methods of this class wherever a library may + need to differ; those methods are the override points. + """ + + #: Replacements of whole `fbuiltins` implementations for fields of this namespace. + builtin_overrides: ClassVar[Mapping[Any, Callable[..., Any]]] = {} + + xp: ModuleType + + def __init__(self, xp: ModuleType) -> None: + self.xp = xp + self._dtypes = { + scalar_type: getattr(xp, name) + for scalar_type, name in core_types.type_to_name.items() + if hasattr(xp, name) + } + # keyed by the dtype of an actual array: e.g. NumPy namespaces expose scalar types as dtypes + self._scalar_types = { + xp.empty(0, dtype=dtype).dtype: scalar_type + for scalar_type, dtype in self._dtypes.items() + } + self._elementwise_cache: dict[str, Callable[..., Any]] = {} + + def __repr__(self) -> str: + return f"{type(self).__name__}({self.xp.__name__})" + + @property + def array_ns(self) -> ModuleType: + """The library's own module, as exposed by `NdArrayField.array_ns`.""" + return self.xp + + def dtype(self, scalar_type: type) -> Any: + try: + return self._dtypes[core_defs.dtype(scalar_type).scalar_type] + except KeyError: + raise TypeError( + f"Array namespace '{self.xp.__name__}' has no dtype for '{scalar_type}'." + ) from None + + def scalar_type(self, dtype: Any) -> type[core_defs.Scalar]: + try: + return self._scalar_types[dtype] + except KeyError: + raise TypeError( + f"Dtype '{dtype}' of array namespace '{self.xp.__name__}' is not a gt4py scalar type." + ) from None + + def device(self, array: core_defs.NDArrayObject) -> Any: + return array_api_compat.device(array) + + def asarray( + self, + data: Any, + *, + dtype: Any = None, + like: core_defs.NDArrayObject | None = None, + ) -> core_defs.NDArrayObject: + """`data` as an array of this namespace, on the device of `like` if given.""" + return self.xp.asarray( + data, + dtype=None if dtype is None else self.dtype(dtype), + device=None if like is None else self.device(like), + ) + + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + """ + `value` as an operand of an elementwise function next to the array `like`. + + Python scalars stay Python scalars, so they keep the weak typing of the + standard. NumPy scalars become 0-d arrays of their dtype, which promotes like + NumPy does with NumPy scalars. + """ + if isinstance(value, np.generic): + return self.asarray(value, dtype=type(value), like=like) + return value + + def elementwise(self, name: str) -> Callable[..., Any]: + """The elementwise function for a gt4py builtin or operator name.""" + try: + return self._elementwise_cache[name] + except KeyError: + func = self._elementwise_cache[name] = self._elementwise(name) + return func + + def _elementwise(self, name: str) -> Callable[..., Any]: + if name == "where": + return self.where + func = getattr(self.xp, STANDARD_NAMES.get(name, name), None) + if func is None: + raise NotImplementedError( + f"'{name}' is not implemented for array namespace '{self.xp.__name__}'." + ) + return func + + def where(self, condition: Any, x: Any, y: Any) -> core_defs.NDArrayObject: + if isinstance(condition, bool | np.bool_): + like = next(a for a in (x, y) if array_api_compat.is_array_api_obj(a)) + condition = self.asarray(condition, dtype=bool, like=like) + return self.xp.where(condition, self.operand(x, condition), self.operand(y, condition)) + + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + """Write `value` into `array[key]`; returns the array holding the result.""" + array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete + return array + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete + + def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: + return common.BufferInfo.from_ndarray(array) + + +_registry: list[tuple[Callable[[ModuleType], bool], Callable[[ModuleType], ArrayOps]]] = [] +_ops_by_namespace: dict[ModuleType, ArrayOps] = {} +_ops_by_array_type: dict[type, ArrayOps] = {} + + +def register( + is_namespace: Callable[[ModuleType], bool], factory: Callable[[ModuleType], ArrayOps] +) -> None: + """ + Use `factory(xp)` for the buffers whose compat namespace `xp` satisfies `is_namespace`. + + Later registrations take precedence. + """ + _registry.insert(0, (is_namespace, factory)) + _ops_by_namespace.clear() + _ops_by_array_type.clear() + + +def for_namespace(xp: ModuleType) -> ArrayOps: + try: + return _ops_by_namespace[xp] + except KeyError: + factory = next((f for is_ns, f in _registry if is_ns(xp)), ArrayOps) + ops = _ops_by_namespace[xp] = factory(xp) + return ops + + +def of(array: Any) -> ArrayOps: + """The `ArrayOps` for the namespace of `array`; raises `TypeError` if it is not an array.""" + try: + return _ops_by_array_type[type(array)] + except KeyError: + ops = _ops_by_array_type[type(array)] = for_namespace( + array_api_compat.array_namespace(array) + ) + return ops + + +def default() -> ArrayOps: + """The `ArrayOps` used for data that is not an array, e.g. nested lists.""" + return for_namespace(compat_numpy) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 730475dd09..d7696adcdf 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -12,17 +12,18 @@ import dataclasses import functools import itertools -import math from collections.abc import Callable, Sequence from types import ModuleType -from typing import Any, ClassVar, Never, Optional, ParamSpec, TypeAlias, TypeVar, cast +from typing import Any, Never, Optional, ParamSpec, TypeAlias, TypeVar, cast +import array_api_compat import numpy as np from numpy import typing as npt from gt4py._core import definitions as core_defs from gt4py.next import common from gt4py.next.embedded import ( + array_ops, common as embedded_common, context as embedded_context, exceptions as embedded_exceptions, @@ -30,23 +31,10 @@ from gt4py.next.ffront import experimental, fbuiltins -try: - import cupy as cp -except ImportError: - cp: Optional[ModuleType] = None # type: ignore[no-redef] - -try: - import jax - from jax import numpy as jnp -except ImportError: - jax: Optional[ModuleType] = None # type: ignore[no-redef] - jnp: Optional[ModuleType] = None # type: ignore[no-redef] - - -def _get_nd_array_class(*fields: common.Field | core_defs.Scalar) -> type[NdArrayField]: - for f in fields: - if isinstance(f, NdArrayField): - return f.__class__ +def _ops_of(*values: Any) -> array_ops.ArrayOps: + for v in values: + if isinstance(v, NdArrayField): + return v._ops raise AssertionError("No 'NdArrayField' found in the arguments.") @@ -54,63 +42,54 @@ def _make_builtin( builtin_name: str, array_builtin_name: str, reverse: bool = False ) -> Callable[..., NdArrayField]: def _builtin_op(*fields: common.Field | core_defs.Scalar) -> NdArrayField: - cls_ = _get_nd_array_class(*fields) - xp = cls_.array_ns - op = _get_builtin(xp, array_builtin_name) + ops = _ops_of(*fields) + op = ops.elementwise(array_builtin_name) domain_intersection = embedded_common.domain_intersection( *[f.domain for f in fields if isinstance(f, common.Field)] ) + arrays: list[core_defs.NDArrayObject] = [] transformed: list[core_defs.NDArrayObject | core_defs.Scalar] = [] for f in fields: if isinstance(f, common.Field): if f.domain == domain_intersection: - transformed.append(xp.asarray(f.ndarray)) + array = ops.asarray(f.ndarray) else: f_broadcasted = _broadcast(f, domain_intersection.dims) f_slices = _get_slices_from_domain_slice( f_broadcasted.domain, domain_intersection ) - transformed.append(xp.asarray(f_broadcasted.ndarray[f_slices])) + array = ops.asarray(f_broadcasted.ndarray[f_slices]) + arrays.append(array) + transformed.append(array) else: assert core_defs.is_scalar_type(f) transformed.append(f) + if len(arrays) < len(transformed): + transformed = [ops.operand(v, arrays[0]) for v in transformed] if reverse: transformed.reverse() new_data = op(*transformed) - return cls_.from_array(new_data, domain=domain_intersection) + return NdArrayField.from_array(new_data, domain=domain_intersection) _builtin_op.__name__ = builtin_name return _builtin_op -try: - from scipy.special import gamma as _np_gamma -except ImportError: - - def _np_gamma(a: core_defs.NDArrayObject) -> core_defs.NDArrayObject: - return np.vectorize(math.gamma, otypes=[a.dtype])(a) - - -def _get_builtin(xp: ModuleType, name: str) -> Callable: - match name: - case "gamma": - if xp is np: - return _np_gamma - if xp is cp: - import cupyx.scipy.special - - return cupyx.scipy.special.gamma - if xp is jnp: - import jax.scipy.special - - return jax.scipy.special.gamma - raise NotImplementedError( - f"'gamma' is not implemented for array namespace '{xp.__name__}'." - ) - case _: - return getattr(xp, name) +def _asarray( + data: npt.ArrayLike | core_defs.NDArrayObject, dtype: Optional[core_defs.DTypeLike] +) -> core_defs.NDArrayObject: + try: + ops = array_ops.of(data) + except TypeError: + ops = array_ops.default() + scalar_type = None if dtype is None else core_defs.dtype(dtype).scalar_type + array = ops.asarray(data, dtype=scalar_type) + assert ops.scalar_type(array.dtype) in ( + core_defs.SCALAR_TYPES if scalar_type is None else (scalar_type,) + ) + return array _Value: TypeAlias = common.Field | core_defs.ScalarT @@ -124,18 +103,23 @@ class NdArrayField( common.FieldBuiltinFuncRegistry, ): """ - Shared field implementation for NumPy-like fields. + Field backed by an array of any Array API compatible library. - Builtin function implementations are registered in a dictionary. - Note: Currently, all concrete NdArray-implementations share - the same implementation, dispatching is handled inside of the registered - function via its namespace. + The array operations are taken from the `array_ops.ArrayOps` of the buffer's + namespace, so one class serves all array libraries. """ _domain: common.Domain _ndarray: core_defs.NDArrayObject - array_ns: ClassVar[ModuleType] # TODO(havogt): introduce a NDArrayNamespace protocol + @property + def _ops(self) -> array_ops.ArrayOps: + return array_ops.of(self._ndarray) + + @property + def array_ns(self) -> ModuleType: + """The module of the array library holding the buffer, e.g. `numpy`.""" + return self._ops.array_ns def __getstate__(self) -> dict[str, Any]: # Serialize only the dataclass fields, excluding cached properties @@ -154,15 +138,7 @@ def from_array( dtype: Optional[core_defs.DTypeLike] = None, ) -> NdArrayField: domain = common.domain(domain) - xp = cls.array_ns - - xp_dtype = None if dtype is None else xp.dtype(core_defs.dtype(dtype).scalar_type) - array = xp.asarray(data, dtype=xp_dtype) - - if dtype is not None: - assert array.dtype.type == core_defs.dtype(dtype).scalar_type - - assert issubclass(array.dtype.type, core_defs.SCALAR_TYPES) + array = _asarray(data, dtype) assert all(isinstance(d, common.Dimension) for d in domain.dims), domain assert len(domain) == array.ndim @@ -187,7 +163,7 @@ def __gt_buffer_info__(self) -> common.BufferInfo: NDArrayField subclasses where the backing ndarray can be replaced should override this and make it a regular property. """ - return common.BufferInfo.from_ndarray(self.ndarray) + return self._ops.buffer_info(self.ndarray) @property def shape(self) -> tuple[int, ...]: @@ -203,17 +179,14 @@ def codomain(self) -> type[core_defs.ScalarT]: @functools.cached_property def dtype(self) -> core_defs.DType[core_defs.ScalarT]: - return core_defs.dtype(self._ndarray.dtype.type) + return core_defs.dtype(self._ops.scalar_type(self._ndarray.dtype)) @property def ndarray(self) -> core_defs.NDArrayObject: return self._ndarray def asnumpy(self) -> np.ndarray: - if self.array_ns == cp: - return cp.asnumpy(self._ndarray) - else: - return np.asarray(self._ndarray) + return self._ops.to_numpy(self._ndarray) def as_scalar(self) -> core_defs.ScalarT: if self.domain.ndim != 0: @@ -363,9 +336,7 @@ def __call__( def restrict(self, index: common.AnyIndexSpec) -> NdArrayField: new_domain, buffer_slice = self._slice(index) - new_buffer = self.ndarray[buffer_slice] - new_buffer = self.__class__.array_ns.asarray(new_buffer) - return self.__class__.from_array(new_buffer, domain=new_domain) + return self.__class__.from_array(self.ndarray[buffer_slice], domain=new_domain) __getitem__ = restrict @@ -383,8 +354,9 @@ def __setitem__( ) value = value.ndarray - assert hasattr(self.ndarray, "__setitem__") - self._ndarray[target_slice] = value # type: ignore[index] # np and cp allow index assignment, jax overrides + new_buffer = self._ops.setitem(self._ndarray, target_slice, value) + if new_buffer is not self._ndarray: + object.__setattr__(self, "_ndarray", new_buffer) __abs__ = _make_builtin("abs", "abs") @@ -484,15 +456,9 @@ def from_array( # type: ignore[override] skip_value: Optional[core_defs.IntegralScalar] = None, ) -> NdArrayConnectivityField: domain = common.domain(domain) - xp = cls.array_ns - - xp_dtype = None if dtype is None else xp.dtype(core_defs.dtype(dtype).scalar_type) - array = xp.asarray(data, dtype=xp_dtype) - - if dtype is not None: - assert array.dtype.type == core_defs.dtype(dtype).scalar_type + array = _asarray(data, dtype) - assert issubclass(array.dtype.type, core_defs.INTEGRAL_TYPES) + assert issubclass(array_ops.of(array).scalar_type(array.dtype), core_defs.INTEGRAL_TYPES) assert all(isinstance(d, common.Dimension) for d in domain.dims), domain assert len(domain) == array.ndim @@ -538,8 +504,7 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co assert isinstance(image_range, common.UnitRange) assert common.UnitRange.is_finite(image_range) - xp = self.array_ns - slices = _hyperslice(self._ndarray, image_range, xp, self.skip_value) + slices = _hyperslice(self._ndarray, image_range, self._ops.xp, self.skip_value) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -552,11 +517,13 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: cache_key = (id(self.ndarray), self.domain, index) if (restricted_connectivity := self._cache.get(cache_key, None)) is None: - cls = self.__class__ - xp = cls.array_ns new_domain, buffer_slice = self._slice(index) - new_buffer = xp.asarray(self.ndarray[buffer_slice]) - restricted_connectivity = cls(new_domain, new_buffer, self.codomain, self.skip_value) + restricted_connectivity = self.__class__( + new_domain, + self._ops.asarray(self.ndarray[buffer_slice]), + self.codomain, + self.skip_value, + ) self._cache[cache_key] = restricted_connectivity return restricted_connectivity @@ -615,7 +582,7 @@ def _gather_output_domain( def _gather_premap(data: NdArrayField, *connectivities: common.GatherConnectivity) -> NdArrayField: """`premap` via a single advanced-index gather (dimension-preserving and -introducing cases).""" - xp = data.array_ns + ops = data._ops new_domain = _gather_output_domain(data.domain, connectivities) conn_by_codomain = {conn.codomain: conn for conn in connectivities} @@ -623,9 +590,9 @@ def _gather_premap(data: NdArrayField, *connectivities: common.GatherConnectivit # the output domain and shifted to 0-based buffer indices, then a single advanced-index gather take_indices = tuple( ( - _connectivity_index_array(conn_by_codomain[dim], new_domain, xp) + _connectivity_index_array(conn_by_codomain[dim], new_domain, ops) if dim in conn_by_codomain - else _identity_index_array(new_domain, dim, xp) + else _identity_index_array(new_domain, dim, ops, like=data._ndarray) ) - data.domain[dim].unit_range.start for dim in data.domain.dims @@ -635,13 +602,14 @@ def _gather_premap(data: NdArrayField, *connectivities: common.GatherConnectivit def _connectivity_index_array( - connectivity: common.GatherConnectivity, domain: common.Domain, xp: ModuleType + connectivity: common.GatherConnectivity, domain: common.Domain, ops: array_ops.ArrayOps ) -> core_defs.NDArrayObject: """`connectivity`'s index table laid out over `domain` (not yet shifted to 0-based).""" # restrict the table to the output ranges of the connectivity's own dimensions sub_domain = common.Domain(*(domain[d] for d in connectivity.domain.dims)) conn = connectivity if sub_domain == connectivity.domain else connectivity.restrict(sub_domain) - arr = xp.asarray(conn.ndarray) + xp = ops.xp + arr = ops.asarray(conn.ndarray) # the axis of `arr` for each output dimension: the connectivity's own axis, or a fresh appended one ndim = conn.domain.ndim fresh_axis = { @@ -652,8 +620,8 @@ def _connectivity_index_array( for dim in domain.dims ) if fresh_axis: # add size-1 axes for output dimensions the connectivity does not span - arr = xp.expand_dims(arr, axis=tuple(fresh_axis.values())) - arr = xp.transpose(arr, transposed_axes) # reorder to the output dimension order + arr = xp.reshape(arr, (*arr.shape, *(1,) * len(fresh_axis))) + arr = xp.permute_dims(arr, transposed_axes) # reorder to the output dimension order if arr.shape != domain.shape: arr = xp.broadcast_to(arr, domain.shape) # broadcast the size-1 axes to the full shape return arr @@ -662,13 +630,21 @@ def _connectivity_index_array( def _identity_index_array( domain: common.Domain, dim: common.Dimension, - xp: ModuleType, - dtype: Optional[npt.DTypeLike] = None, + ops: array_ops.ArrayOps, + *, + like: core_defs.NDArrayObject, + dtype: Optional[type] = None, ) -> core_defs.NDArrayObject: - """Index array selecting `dim` unchanged over `domain`, in the field's index space.""" + """Index array selecting `dim` unchanged over `domain`, in the field's index space, on the device of `like`.""" + xp = ops.xp d_idx = domain.dim_index(dim, allow_missing=False) unit_range = domain[d_idx].unit_range - indices = xp.arange(unit_range.start, unit_range.stop, dtype=dtype) + indices = xp.arange( + unit_range.start, + unit_range.stop, + dtype=None if dtype is None else ops.dtype(dtype), + device=ops.device(like), + ) shape = tuple(len(indices) if i == d_idx else 1 for i in range(len(domain))) return xp.broadcast_to(xp.reshape(indices, shape), domain.shape) @@ -701,13 +677,13 @@ def _hyperslice( nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) slices = tuple( - slice(xp.min(dim_nnz_indices).item(), xp.max(dim_nnz_indices).item() + 1) + slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) for dim_nnz_indices in nnz ) hcube = select_mask[tuple(slices)] if skip_value is not None: ignore_mask = index_array == skip_value - hcube |= ignore_mask[tuple(slices)] + hcube = hcube | ignore_mask[tuple(slices)] if not xp.all(hcube): return None @@ -716,11 +692,22 @@ def _hyperslice( # -- Specialized implementations for builtin operations on array fields -- -NdArrayField.register_builtin_func( + +def _register_builtin(builtin: fbuiltins.BuiltInFunction, impl: Callable[..., Any]) -> None: + """Register `impl` for `builtin`, unless the `ArrayOps` of the first field argument replaces it.""" + + def dispatch(*args: Any, **kwargs: Any) -> Any: + return _ops_of(*args).builtin_overrides.get(builtin, impl)(*args, **kwargs) + + dispatch.__name__ = getattr(impl, "__name__", builtin.name) + NdArrayField.register_builtin_func(builtin, dispatch) + + +_register_builtin( fbuiltins.abs, NdArrayField.__abs__, ) -NdArrayField.register_builtin_func( +_register_builtin( fbuiltins.power, NdArrayField.__pow__, ) @@ -732,32 +719,30 @@ def _hyperslice( ): if name in ["abs", "power"]: continue - NdArrayField.register_builtin_func(getattr(fbuiltins, name), _make_builtin(name, name)) + _register_builtin(getattr(fbuiltins, name), _make_builtin(name, name)) -NdArrayField.register_builtin_func( +_register_builtin( fbuiltins.minimum, _make_builtin("minimum", "minimum"), ) -NdArrayField.register_builtin_func( +_register_builtin( fbuiltins.maximum, _make_builtin("maximum", "maximum"), ) -NdArrayField.register_builtin_func( +_register_builtin( fbuiltins.fmod, _make_builtin("fmod", "fmod"), ) -NdArrayField.register_builtin_func(fbuiltins.where, _make_builtin("where", "where")) +_register_builtin(fbuiltins.where, _make_builtin("where", "where")) -def _to_field( - value: common.Field | core_defs.Scalar, nd_array_field_type: type[NdArrayField] -) -> common.Field: +def _to_field(value: common.Field | core_defs.Scalar, like: NdArrayField) -> common.Field: # TODO(havogt): this function is only to workaround broadcasting of scalars, once we have a ConstantField, we can broadcast to that directly return ( value if isinstance(value, common.Field) - else nd_array_field_type.from_array( - nd_array_field_type.array_ns.asarray(value), domain=common.Domain() + else NdArrayField.from_array( + like._ops.asarray(value, like=like.ndarray), domain=common.Domain() ) ) @@ -768,18 +753,18 @@ def _intersect_fields( ) -> tuple[common.Field, ...]: # TODO(havogt): this function could be moved to common, but then requires a broadcast implementation for all field implementations; # currently blocked, because requiring the `_to_field` function, see comment there. - nd_array_class = _get_nd_array_class(*fields) + like = next(f for f in fields if isinstance(f, NdArrayField)) promoted_dims = common.promote_dims( *(f.domain.dims for f in fields if isinstance(f, common.Field)) ) - broadcasted_fields = [_broadcast(_to_field(f, nd_array_class), promoted_dims) for f in fields] + broadcasted_fields = [_broadcast(_to_field(f, like), promoted_dims) for f in fields] intersected_domains = embedded_common.restrict_to_intersection( *[f.domain for f in broadcasted_fields], ignore_dims=ignore_dims ) return tuple( - nd_array_class.from_array( + NdArrayField.from_array( f.ndarray[_get_slices_from_domain_slice(f.domain, intersected_domain)], domain=intersected_domain, ) @@ -808,13 +793,10 @@ def _concat(*fields: common.Field, dim: common.Dimension) -> common.Field: if left < right: raise embedded_exceptions.NonContiguousDomain(f"Cannot concatenate fields along {dim}.") new_domain = _stack_domains(*[f.domain for f in sorted_fields], dim=dim) - nd_array_class = _get_nd_array_class(*sorted_fields) - return nd_array_class.from_array( - nd_array_class.array_ns.concatenate( - [ - nd_array_class.array_ns.broadcast_to(f.ndarray, f.domain.shape) - for f in sorted_fields - ], + xp = _ops_of(*sorted_fields).xp + return NdArrayField.from_array( + xp.concat( + [xp.broadcast_to(f.ndarray, f.domain.shape) for f in sorted_fields], axis=new_domain.dim_index(dim, allow_missing=False), ), domain=new_domain, @@ -846,10 +828,13 @@ def _invert_domain(domain: common.Domain) -> tuple[common.Domain, ...]: def _size0_field( - nd_array_class: type[NdArrayField], dims: tuple[common.Dimension, ...], dtype: core_defs.DType + like: NdArrayField, dims: tuple[common.Dimension, ...], dtype: core_defs.DType ) -> NdArrayField: - return nd_array_class.from_array( - nd_array_class.array_ns.empty((0,) * len(dims), dtype=dtype.scalar_type), + ops = like._ops + return NdArrayField.from_array( + ops.xp.empty( + (0,) * len(dims), dtype=ops.dtype(dtype.scalar_type), device=ops.device(like.ndarray) + ), domain=common.Domain(dims=dims, ranges=(common.UnitRange(0, 0),) * len(dims)), ) @@ -885,12 +870,12 @@ def _concat_where( if len(t_slices) + len(f_slices) == 0: # no data to concatenate, return an empty field - nd_array_class = _get_nd_array_class(true_field, false_field) - return _size0_field(nd_array_class, dims=t_broadcasted.domain.dims, dtype=true_field.dtype) + like = next(f for f in (true_field, false_field) if isinstance(f, NdArrayField)) + return _size0_field(like, dims=t_broadcasted.domain.dims, dtype=true_field.dtype) return _concat(*f_slices, *t_slices, dim=domain_dim) -NdArrayField.register_builtin_func(experimental.concat_where, _concat_where) # type: ignore[arg-type] +_register_builtin(experimental.concat_where, _concat_where) def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> common.Connectivity: @@ -903,14 +888,18 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> com ) source_dim = offset.source coords = _identity_index_array( - offset_field.domain, source_dim, offset_field.array_ns, dtype=fbuiltins.IndexType + offset_field.domain, + source_dim, + offset_field._ops, + like=offset_field.ndarray, + dtype=fbuiltins.IndexType, ) return common._connectivity( offset_field.ndarray + coords, codomain=source_dim, domain=offset_field.domain ) -NdArrayField.register_builtin_func(experimental.as_offset, _as_offset) # type: ignore[arg-type] +_register_builtin(experimental.as_offset, _as_offset) def _make_reduction( @@ -919,7 +908,7 @@ def _make_reduction( def _builtin_op( field: NdArrayField[common.DimsT, core_defs.ScalarT], axis: common.Dimension ) -> NdArrayField[common.DimsT, core_defs.ScalarT]: - xp = field.array_ns + ops = field._ops if not axis.kind == common.DimensionKind.LOCAL: raise ValueError("Can only reduce local dimensions.") @@ -939,128 +928,67 @@ def _builtin_op( new_domain = common.Domain(*[nr for nr in field.domain if nr.dim != axis]) broadcast_slice = tuple( - slice(None) if d in [axis, offset_definition.domain.dims[0]] else xp.newaxis + slice(None) if d in [axis, offset_definition.domain.dims[0]] else None for d in field.domain.dims ) - masked_array = xp.where( - xp.asarray(offset_definition.ndarray[broadcast_slice]) != common._DEFAULT_SKIP_VALUE, + masked_array = ops.where( + ops.asarray(offset_definition.ndarray[broadcast_slice]) != common._DEFAULT_SKIP_VALUE, field.ndarray, initial_value_op(field), ) - return field.__class__.from_array( - getattr(xp, array_builtin_name)(masked_array, axis=reduce_dim_index), domain=new_domain + return NdArrayField.from_array( + getattr(ops.xp, array_builtin_name)(masked_array, axis=reduce_dim_index), + domain=new_domain, ) _builtin_op.__name__ = builtin_name return _builtin_op -NdArrayField.register_builtin_func( +_register_builtin( fbuiltins.neighbor_sum, _make_reduction("neighbor_sum", "sum", lambda x: x.dtype.scalar_type(0)) ) -NdArrayField.register_builtin_func( - fbuiltins.max_over, _make_reduction("max_over", "max", lambda x: x.array_ns.min(x._ndarray)) +_register_builtin( + fbuiltins.max_over, _make_reduction("max_over", "max", lambda x: x._ops.xp.min(x._ndarray)) ) -NdArrayField.register_builtin_func( - fbuiltins.min_over, _make_reduction("min_over", "min", lambda x: x.array_ns.max(x._ndarray)) +_register_builtin( + fbuiltins.min_over, _make_reduction("min_over", "min", lambda x: x._ops.xp.max(x._ndarray)) ) -# -- Concrete array implementations -- -# NumPy -_nd_array_implementations = [np] - - -@dataclasses.dataclass(frozen=True, eq=False) -class NumPyArrayField(NdArrayField): - array_ns: ClassVar[ModuleType] = np - - -common._field.register(np.ndarray, NumPyArrayField.from_array) - - -@dataclasses.dataclass(frozen=True, eq=False) -class NumPyArrayConnectivityField(NdArrayConnectivityField): - array_ns: ClassVar[ModuleType] = np - - -common._connectivity.register(np.ndarray, NumPyArrayConnectivityField.from_array) - -# CuPy -if cp: - _nd_array_implementations.append(cp) - - @dataclasses.dataclass(frozen=True, eq=False) - class CuPyArrayField(NdArrayField): - array_ns: ClassVar[ModuleType] = cp - - common._field.register(cp.ndarray, CuPyArrayField.from_array) - - @dataclasses.dataclass(frozen=True, eq=False) - class CuPyArrayConnectivityField(NdArrayConnectivityField): - array_ns: ClassVar[ModuleType] = cp - - common._connectivity.register(cp.ndarray, CuPyArrayConnectivityField.from_array) - -# JAX -if jnp: - assert jax is not None - - _nd_array_implementations.append(jnp) - # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config - jax.config.update("jax_enable_x64", True) - - @dataclasses.dataclass(frozen=True, eq=False) - class JaxArrayField(NdArrayField): - array_ns: ClassVar[ModuleType] = jnp - - @property - def __gt_buffer_info__(self) -> common.BufferInfo: - raise NotImplementedError("'__gt_buffer_info__' for JaxArrayField not yet implemented.") +def _field_from_array( + data: Any, + /, + *, + domain: Optional[common.DomainLike] = None, + dtype: Optional[core_defs.DType] = None, +) -> NdArrayField: + if not array_api_compat.is_array_api_obj(data): + raise NotImplementedError(f"Cannot construct a 'Field' from '{type(data)}'.") + assert domain is not None + return NdArrayField.from_array(data, domain=domain, dtype=dtype) + + +def _connectivity_from_array( + data: Any, + /, + codomain: common.Dimension, + *, + domain: Optional[common.DomainLike] = None, + dtype: Optional[core_defs.DType] = None, + skip_value: Optional[core_defs.IntegralScalar] = None, +) -> NdArrayConnectivityField: + if not array_api_compat.is_array_api_obj(data): + raise NotImplementedError(f"Cannot construct a 'Connectivity' from '{type(data)}'.") + assert domain is not None + return NdArrayConnectivityField.from_array( + data, codomain, domain=domain, dtype=dtype, skip_value=skip_value + ) - def __setitem__( - self, - index: common.AnyIndexSpec, - value: common.Field | core_defs.NDArrayObject | core_defs.ScalarT, - ) -> None: - target_domain, target_slice = self._slice(index) - if isinstance(value, common.Field): - if not value.domain == target_domain: - raise ValueError( - f"Incompatible 'Domain' in assignment. Source domain = '{value.domain}', target domain = '{target_domain}'." - ) - value = value.ndarray - - object.__setattr__(self, "_ndarray", self._ndarray.at[target_slice].set(value)) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - - @dataclasses.dataclass(frozen=True, eq=False) - class JaxArrayConnectivityField(NdArrayConnectivityField): - array_ns: ClassVar[ModuleType] = jnp - - common._field.register(jnp.ndarray, JaxArrayField.from_array) - common._connectivity.register(jnp.ndarray, JaxArrayConnectivityField.from_array) - # jax >= 0.11: 'Tracer' is no longer a subclass of 'jax.Array' (only 'isinstance' says so, via - # 'ArrayMeta.__instancecheck__'), and 'singledispatch' resolves on the class hierarchy. - common._field.register(jax.core.Tracer, JaxArrayField.from_array) - common._connectivity.register(jax.core.Tracer, JaxArrayConnectivityField.from_array) - - def _flatten_jax_field( - field: JaxArrayField, - ) -> tuple[tuple[core_defs.NDArrayObject], common.Domain]: - return (field.ndarray,), field.domain - - def _unflatten_jax_field( - domain: common.Domain, children: tuple[core_defs.NDArrayObject] - ) -> JaxArrayField: - return JaxArrayField(domain, children[0]) # type: ignore[abstract] # mypy does not see '__gt_builtin_func__' as implemented by 'FieldBuiltinFuncRegistry' - - jax.tree_util.register_pytree_node( - JaxArrayField, # type: ignore[type-abstract, unused-ignore] # only reported when 'jax' is installed, see '_unflatten_jax_field' - _flatten_jax_field, - _unflatten_jax_field, - ) +common._field.register(object, _field_from_array) +common._connectivity.register(object, _connectivity_from_array) def _broadcast(field: common.Field, new_dimensions: Sequence[common.Dimension]) -> common.Field: @@ -1073,7 +1001,7 @@ def _broadcast(field: common.Field, new_dimensions: Sequence[common.Dimension]) domain_slice.append(slice(None)) named_ranges.append(common.NamedRange(dim, field.domain[pos].unit_range)) else: - domain_slice.append(None) # np.newaxis + domain_slice.append(None) named_ranges.append(common.NamedRange(dim, common.UnitRange.infinite())) return common._field(field.ndarray[tuple(domain_slice)], domain=common.Domain(*named_ranges)) @@ -1086,16 +1014,19 @@ def _builtins_broadcast( raise AssertionError("Scalar case not reachable from 'fbuiltins.broadcast'.") -NdArrayField.register_builtin_func(fbuiltins.broadcast, _builtins_broadcast) +_register_builtin(fbuiltins.broadcast, _builtins_broadcast) def _astype(field: common.Field | core_defs.ScalarT | tuple, type_: type) -> NdArrayField: if isinstance(field, NdArrayField): - return field.__class__.from_array(field.ndarray.astype(type_), domain=field.domain) + ops = field._ops + return NdArrayField.from_array( + ops.xp.astype(field.ndarray, ops.dtype(type_)), domain=field.domain + ) raise AssertionError("This is the NdArrayField implementation of 'fbuiltins.astype'.") -NdArrayField.register_builtin_func(fbuiltins.astype, _astype) # type: ignore[arg-type] # because fbuiltins.astype is overloaded +_register_builtin(fbuiltins.astype, _astype) # type: ignore[arg-type] # because fbuiltins.astype is overloaded def _get_slices_from_domain_slice( diff --git a/src/gt4py/next/field_utils.py b/src/gt4py/next/field_utils.py index 7b9fe7e68b..c0cf06b057 100644 --- a/src/gt4py/next/field_utils.py +++ b/src/gt4py/next/field_utils.py @@ -10,7 +10,7 @@ import numpy as np -from gt4py._core import definitions as core_defs +from gt4py._core import definitions as core_defs, types as core_types from gt4py.eve.xtyping import NestedTuple from gt4py.next import common, named_collections, utils from gt4py.next.type_system import type_specifications as ts, type_translation @@ -39,7 +39,7 @@ def field_from_typespec( >>> field_from_typespec( ... ts.ScalarType(kind=ts.ScalarKind.INT32), common.domain({common.Dimension("I"): 1}), np ... ) # doctest: +ELLIPSIS - NumPyArrayField(... dtype=int32...) + NdArrayField(... dtype=int32...) >>> field_from_typespec( ... ts.TupleType( ... types=[ @@ -50,7 +50,7 @@ def field_from_typespec( ... common.domain({common.Dimension("I"): 1}), ... np, ... ) # doctest: +ELLIPSIS - (NumPyArrayField(... dtype=int32...), NumPyArrayField(... dtype=float32...)) + (NdArrayField(... dtype=int32...), NdArrayField(... dtype=float32...)) """ def _constructor( @@ -67,7 +67,12 @@ def _constructor( ) def impl(type_: ts.ScalarType) -> common.MutableField: res = common._field( - xp.empty(domain.shape, dtype=xp.dtype(type_translation.as_dtype(type_).scalar_type)), + xp.empty( + domain.shape, + dtype=getattr( + xp, core_types.type_to_name[type_translation.as_dtype(type_).scalar_type] + ), + ), domain=domain, ) assert isinstance(res, common.MutableField) diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index 35ca3a8751..147d421f28 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -46,7 +46,7 @@ def _table_digest(table: np.ndarray) -> str: @dataclasses.dataclass(frozen=True, eq=False) -class _CompileTimeConnectivity(nd_array_field.NumPyArrayConnectivityField): +class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): """ Compile-time view of a connectivity: a read-only, C-contiguous host table, memory-mapped from a file named by the digest of its content. diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 86a4229860..7e82bb9183 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -11,10 +11,12 @@ import dataclasses import enum import importlib -from typing import Final +from types import ModuleType +from typing import Final, Optional + +import numpy as np import pytest -from gt4py.next.embedded import nd_array_field from gt4py.next import constructors # Skip definitions @@ -57,9 +59,16 @@ class EmbeddedDummyBackend: executor: Final = None -numpy_execution = EmbeddedDummyBackend("EmbeddedNumPy", nd_array_field.np) -cupy_execution = EmbeddedDummyBackend("EmbeddedCuPy", nd_array_field.cp) -jax_numpy_execution = EmbeddedDummyBackend("EmbeddedJaxNumPy", nd_array_field.jnp) +def _optional_module(name: str) -> Optional[ModuleType]: + try: + return importlib.import_module(name) + except ImportError: + return None + + +numpy_execution = EmbeddedDummyBackend("EmbeddedNumPy", np) +cupy_execution = EmbeddedDummyBackend("EmbeddedCuPy", _optional_module("cupy")) +jax_numpy_execution = EmbeddedDummyBackend("EmbeddedJaxNumPy", _optional_module("jax.numpy")) class EmbeddedIds(_PythonObjectIdMixin, str, enum.Enum): diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index 879094f123..7e5615b239 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -9,14 +9,16 @@ from __future__ import annotations import dataclasses -from typing import TypeAlias +import importlib +from types import ModuleType +from typing import Final, TypeAlias +import numpy as np import pytest import gt4py.next as gtx from gt4py._core import definitions as core_defs from gt4py.next import backend, common -from gt4py.next.embedded import nd_array_field from gt4py.next.iterator import runtime from gt4py.next.program_processors import program_formatter @@ -99,9 +101,27 @@ class DummyConnectivity(common.Connectivity): codomain: gtx.Dimension = gtx.Dimension("dummy_neighbor") +def _optional_module(name: str) -> list[ModuleType]: + try: + return [importlib.import_module(name)] + except ImportError: + return [] + + +ND_ARRAY_IMPLEMENTATIONS: Final[list[ModuleType]] = [ + np, + *_optional_module("cupy"), + *_optional_module("jax.numpy"), +] + + +def is_cupy(xp: ModuleType) -> bool: + return xp.__name__ == "cupy" + + def nd_array_implementation_params(): - for xp in nd_array_field._nd_array_implementations: - if hasattr(nd_array_field, "cp") and xp == nd_array_field.cp: + for xp in ND_ARRAY_IMPLEMENTATIONS: + if is_cupy(xp): yield pytest.param( (xp, core_defs.CUPY_DEVICE_TYPE), id=xp.__name__, marks=pytest.mark.requires_gpu ) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 3546ceaaaa..2e885b6022 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -31,6 +31,7 @@ from gt4py.next.ffront.experimental import as_offset from next_tests.integration_tests.feature_tests.math_builtin_test_data import math_builtin_test_data +from next_tests.unit_tests.conftest import ND_ARRAY_IMPLEMENTATIONS, is_cupy D0 = Dimension("D0") @@ -297,10 +298,10 @@ def test_as_scalar(nd_array_implementation): def product_nd_array_implementation_params(): - for xp1 in nd_array_field._nd_array_implementations: - for xp2 in nd_array_field._nd_array_implementations: + for xp1 in ND_ARRAY_IMPLEMENTATIONS: + for xp2 in ND_ARRAY_IMPLEMENTATIONS: marks = () - if any(hasattr(nd_array_field, "cp") and xp == nd_array_field.cp for xp in (xp1, xp2)): + if any(is_cupy(xp) for xp in (xp1, xp2)): marks = pytest.mark.requires_gpu yield pytest.param((xp1, xp2), id=f"{xp1.__name__}-{xp2.__name__}", marks=marks) @@ -1812,7 +1813,8 @@ def test_jax_traced_array_dispatch(): def loss(arr): field = common._field(arr, domain=domain) - assert isinstance(field, nd_array_field.JaxArrayField) + assert isinstance(field, nd_array_field.NdArrayField) + assert field.array_ns is jax.numpy return jax.numpy.sum((field * field).ndarray) np.testing.assert_allclose(jax.grad(loss)(x), 2.0 * x.__array__()) From bc9b06224ebc6aaeaf65946e7043129f99704c5b Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 20:26:38 +0100 Subject: [PATCH 025/166] test[next]: run the embedded field unit tests on array-api-strict 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. --- pyproject.toml | 1 + src/gt4py/next/constructors.py | 7 ++- tests/next_tests/unit_tests/conftest.py | 10 ++++ .../embedded_tests/test_nd_array_field.py | 36 +++++++++---- .../unit_tests/test_constructors.py | 2 +- uv.lock | 54 ++++++++++++------- 6 files changed, 78 insertions(+), 32 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 692fc24b76..e9d15ea7e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,7 @@ profiling = [ ] scripts = ["pyyaml>=6.0.1", "typer>=0.16.0", "packaging"] test = [ + 'array-api-strict>=2.4', 'black>=25.11', 'clang-format>=18.1', 'factory-boy>=3.3.3', diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index e4320f99d3..e042cceed7 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -19,6 +19,7 @@ import gt4py.eve as eve import gt4py.next.common as common import gt4py.next.custom_layout_allocators as next_allocators +import gt4py.next.embedded.array_ops as array_ops import gt4py.next.embedded.nd_array_field as nd_array_field from gt4py._core import ( definitions as core_defs, @@ -206,7 +207,7 @@ def as_field( raise ValueError(f"Cannot construct 'Field' from array of shape '{data.shape}'.") if dtype is None: - dtype = core_defs.dtype(data.dtype) + dtype = core_defs.dtype(array_ops.of(data).scalar_type(data.dtype)) return self._construct_from_array( actual_domain, @@ -665,7 +666,9 @@ def as_connectivity( """ if skip_value is eve.NOTHING: skip_value = ( - common._DEFAULT_SKIP_VALUE if (data == common._DEFAULT_SKIP_VALUE).any() else None + common._DEFAULT_SKIP_VALUE + if array_api_compat.array_namespace(data).any(data == common._DEFAULT_SKIP_VALUE) + else None ) field = as_field( diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index 7e5615b239..c8bc05e4b1 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -112,6 +112,7 @@ def _optional_module(name: str) -> list[ModuleType]: np, *_optional_module("cupy"), *_optional_module("jax.numpy"), + *_optional_module("array_api_strict"), ] @@ -119,6 +120,15 @@ def is_cupy(xp: ModuleType) -> bool: return xp.__name__ == "cupy" +def is_array_api_strict(xp: ModuleType) -> bool: + return xp.__name__ == "array_api_strict" + + +def asarray(xp: ModuleType, data, dtype=None): + """`xp.asarray` with a NumPy-style `dtype`, translated to the namespace's own dtype object.""" + return xp.asarray(data, dtype=None if dtype is None else getattr(xp, np.dtype(dtype).name)) + + def nd_array_implementation_params(): for xp in ND_ARRAY_IMPLEMENTATIONS: if is_cupy(xp): diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 2e885b6022..9352fc499f 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -31,7 +31,12 @@ from gt4py.next.ffront.experimental import as_offset from next_tests.integration_tests.feature_tests.math_builtin_test_data import math_builtin_test_data -from next_tests.unit_tests.conftest import ND_ARRAY_IMPLEMENTATIONS, is_cupy +from next_tests.unit_tests.conftest import ( + ND_ARRAY_IMPLEMENTATIONS, + asarray, + is_array_api_strict, + is_cupy, +) D0 = Dimension("D0") @@ -83,7 +88,7 @@ def _make_field_or_scalar( dtype = np.float32 if isinstance(lst, core_defs.SCALAR_TYPES): return dtype(lst) - buffer = nd_array_implementation.asarray(lst, dtype=dtype) + buffer = asarray(nd_array_implementation, lst, dtype=dtype) if domain is None: domain = _make_default_domain(buffer.shape) return common._field(buffer, domain=domain) @@ -108,7 +113,7 @@ def are_equal_fields(a: Field, b: Field) -> bool: def test_nd_array_field_buffer_info(nd_array_implementation): import dataclasses - data = nd_array_implementation.asarray([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) + data = asarray(nd_array_implementation, [[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) field = constructors.as_field((D0, D1), data) field_ndarray = field.ndarray @@ -126,6 +131,9 @@ def test_nd_array_field_buffer_info(nd_array_implementation): assert field_ndarray is not field.ndarray +_NOT_IN_ARRAY_API = ("fmod", "cbrt", "gamma") + + @pytest.mark.parametrize("builtin_name, inputs", math_builtin_test_data()) def test_math_function_builtins(builtin_name: str, inputs, nd_array_implementation): if builtin_name == "gamma": @@ -140,6 +148,10 @@ def test_math_function_builtins(builtin_name: str, inputs, nd_array_implementati field_inputs = [_make_field_or_scalar(inp, nd_array_implementation) for inp in inputs] builtin = getattr(fbuiltins, builtin_name) + if is_array_api_strict(nd_array_implementation) and builtin_name in _NOT_IN_ARRAY_API: + with pytest.raises(NotImplementedError, match=builtin_name): + builtin(*field_inputs) + return result = builtin(*field_inputs) assert np.allclose(result.ndarray, expected) @@ -151,7 +163,8 @@ def test_where_builtin(nd_array_implementation): false_ = np.asarray([3.0, 4.0], dtype=np.float32) field_inputs = [ - _make_field_or_scalar(inp, nd_array_implementation) for inp in [cond, true_, false_] + _make_field_or_scalar(cond, nd_array_implementation, dtype=bool), + *(_make_field_or_scalar(inp, nd_array_implementation) for inp in [true_, false_]), ] expected = np.where(cond, true_, false_) @@ -164,13 +177,16 @@ def test_where_builtin_different_domain(nd_array_implementation): true_ = np.asarray([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32) false_ = np.asarray([7.0, 8.0, 9.0, 10.0], dtype=np.float32) - cond_field = common._field(nd_array_implementation.asarray(cond), domain=common.domain({D1: 2})) + cond_field = common._field( + asarray(nd_array_implementation, cond), domain=common.domain({D1: 2}) + ) true_field = common._field( - nd_array_implementation.asarray(true_), + asarray(nd_array_implementation, true_), domain=common.domain({D0: common.UnitRange(0, 2), D1: common.UnitRange(-1, 2)}), ) false_field = common._field( - nd_array_implementation.asarray(false_), domain=common.domain({D1: common.UnitRange(-1, 3)}) + asarray(nd_array_implementation, false_), + domain=common.domain({D1: common.UnitRange(-1, 3)}), ) expected = np.where(cond[np.newaxis, :], true_[:, 1:], false_[np.newaxis, 1:-1]) @@ -289,7 +305,7 @@ def test_binary_operations_with_intersection(binary_arithmetic_op, dims, expecte def test_as_scalar(nd_array_implementation): testee = common._field( - nd_array_implementation.asarray(42.0, dtype=np.float32), domain=common.Domain() + asarray(nd_array_implementation, 42.0, dtype=np.float32), domain=common.Domain() ) result = testee.as_scalar() @@ -313,8 +329,8 @@ def product_nd_array_implementation(request): def test_mixed_fields(product_nd_array_implementation): first_impl, second_impl = product_nd_array_implementation - if "numpy" in first_impl.__name__ and "cupy" in second_impl.__name__: - pytest.skip("Binary operation between NumPy and CuPy requires explicit conversion.") + if not is_cupy(first_impl) and is_cupy(second_impl): + pytest.skip("Binary operation between a CPU library and CuPy requires explicit conversion.") inp_a = [-1.0, 4.2, 42] inp_b = [2.0, 3.0, -3.0] diff --git a/tests/next_tests/unit_tests/test_constructors.py b/tests/next_tests/unit_tests/test_constructors.py index 0d6bbdeb2b..c3aac7afd2 100644 --- a/tests/next_tests/unit_tests/test_constructors.py +++ b/tests/next_tests/unit_tests/test_constructors.py @@ -209,7 +209,7 @@ def test_aligned_index(): [([0, 1, 2], None), ([0, 1, common._DEFAULT_SKIP_VALUE], common._DEFAULT_SKIP_VALUE)], ) def test_as_connectivity(nd_array_implementation, data, skip_value): - testee = gtx.as_connectivity([I], J, nd_array_implementation.array(data)) + testee = gtx.as_connectivity([I], J, nd_array_implementation.asarray(data)) assert testee.skip_value is skip_value diff --git a/uv.lock b/uv.lock index 49f9ed446c..d4fd5bc224 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.12, !=3.13.10, !=3.14.1, <3.15" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -101,6 +101,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/86/16/1a8fd2b19544b84575cf84ef7aa3ad4c173b756d5f087c91f85d1b295777/array_api_compat-1.15.0-py3-none-any.whl", hash = "sha256:7b1b9c53269061403fd5f45a8de349f16e7887653328bfa0c5f2d45299ff0a8e", size = 79113, upload-time = "2026-06-07T20:53:23.621Z" }, ] +[[package]] +name = "array-api-strict" +version = "2.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cd/05/f338cb02b0ce864c567d756b865fd38b522fde9cf3523d02aed270145a0f/array_api_strict-2.6.1.tar.gz", hash = "sha256:27485fd687c678894fb193e8f9f5116651a0bfc19dccea164d7d5df83b4e9a82", size = 91482, upload-time = "2026-07-27T10:46:27.99Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ca/23/0b70060007470e1c3c3f74a2e362e11efdaa68d8d657793014e6a860638b/array_api_strict-2.6.1-py3-none-any.whl", hash = "sha256:84548915c11265f4b87070731bd26edf46b202a04e7491194abcb46f4986c88f", size = 78619, upload-time = "2026-07-27T10:46:26.771Z" }, +] + [[package]] name = "ast-serialize" version = "0.6.0" @@ -403,7 +415,7 @@ name = "cffi" version = "2.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pycparser" }, + { name = "pycparser", marker = "implementation_name != 'PyPy' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } wheels = [ @@ -559,7 +571,7 @@ name = "click" version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } wheels = [ @@ -606,7 +618,7 @@ name = "colorlog" version = "6.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8c/55/ba79756cb90c8d69d599d57785398ac87bba7b19c80e87f4e8a562197c93/colorlog-6.12.0.tar.gz", hash = "sha256:2a7924c1dadf18b22a0eb8b06d1c7b01d5341707ec1641eb6fcc4fde0c3e8e5f", size = 18151, upload-time = "2026-07-23T13:40:40.71Z" } wheels = [ @@ -937,7 +949,7 @@ dependencies = [ { name = "ordered-set" }, { name = "packaging" }, { name = "ply" }, - { name = "pyreadline", marker = "sys_platform == 'win32'" }, + { name = "pyreadline", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "pyyaml" }, { name = "scikit-build" }, { name = "sympy" }, @@ -1127,7 +1139,7 @@ name = "faker" version = "40.36.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "tzdata", marker = "sys_platform == 'win32'" }, + { name = "tzdata", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/98/d2/026af1e002bbc6df534d1f8262b18ec79a974f928e9290bfbfdfe7c7b2af/faker-40.36.0.tar.gz", hash = "sha256:754048c76c03afa7de83eee8f4bcee3cf668cbb7d995f54a4e9678db7f110308", size = 2025903, upload-time = "2026-07-24T21:11:33.088Z" } wheels = [ @@ -1351,6 +1363,7 @@ build = [ { name = "wheel" }, ] dev = [ + { name = "array-api-strict" }, { name = "atlas4py" }, { name = "black" }, { name = "clang-format" }, @@ -1421,6 +1434,7 @@ scripts = [ { name = "typer" }, ] test = [ + { name = "array-api-strict" }, { name = "black" }, { name = "clang-format" }, { name = "factory-boy" }, @@ -1513,6 +1527,7 @@ build = [ { name = "wheel", specifier = ">=0.33.6" }, ] dev = [ + { name = "array-api-strict", specifier = ">=2.4" }, { name = "atlas4py", specifier = ">=0.41", index = "https://test.pypi.org/simple" }, { name = "black", specifier = ">=25.11" }, { name = "clang-format", specifier = ">=18.1" }, @@ -1581,6 +1596,7 @@ scripts = [ { name = "typer", specifier = ">=0.16.0" }, ] test = [ + { name = "array-api-strict", specifier = ">=2.4" }, { name = "black", specifier = ">=25.11" }, { name = "clang-format", specifier = ">=18.1" }, { name = "factory-boy", specifier = ">=3.3.3" }, @@ -1739,7 +1755,7 @@ name = "ipykernel" version = "7.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "appnope", marker = "sys_platform == 'darwin'" }, + { name = "appnope", marker = "sys_platform == 'darwin' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "comm" }, { name = "debugpy" }, { name = "ipython" }, @@ -1763,13 +1779,13 @@ name = "ipython" version = "9.16.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "ipython-pygments-lexers" }, { name = "jedi" }, { name = "matplotlib-inline" }, - { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "pexpect", marker = "(sys_platform != 'emscripten' and sys_platform != 'win32') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "prompt-toolkit" }, - { name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, + { name = "psutil", marker = "(sys_platform != 'cygwin' and sys_platform != 'emscripten') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "pygments" }, { name = "stack-data" }, { name = "traitlets" }, @@ -2442,7 +2458,7 @@ version = "2.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "ast-serialize" }, - { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, + { name = "librt", marker = "platform_python_implementation != 'PyPy' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "mypy-extensions" }, { name = "pathspec" }, { name = "typing-extensions" }, @@ -2826,7 +2842,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, { name = "python-dateutil" }, - { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/be/4f/5f3422a2afec5ffc46308b79e53291365a93748b498ac2e58bead0197916/pandas-3.0.5.tar.gz", hash = "sha256:dca3734d6ab7c906e6730f0788b0a1dbb9f2467731f9711f77995c8e9d62d712", size = 4658219, upload-time = "2026-07-22T22:19:28.819Z" } wheels = [ @@ -2888,7 +2904,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess" }, + { name = "ptyprocess", marker = "(sys_platform != 'emscripten' and sys_platform != 'win32') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } wheels = [ @@ -3137,7 +3153,7 @@ name = "pytest" version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, @@ -3341,7 +3357,7 @@ name = "pyzmq" version = "27.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cffi", marker = "implementation_name == 'pypy'" }, + { name = "cffi", marker = "implementation_name == 'pypy' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/04/0b/3c9baedbdf613ecaa7aa07027780b8867f57b6293b6ee50de316c9f3222b/pyzmq-27.1.0.tar.gz", hash = "sha256:ac0765e3d44455adb6ddbf4417dcce460fc40a05978c08efdf2948072f6db540", size = 281750, upload-time = "2025-09-08T23:10:18.157Z" } wheels = [ @@ -3386,7 +3402,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, { name = "rpds-py" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions", marker = "python_full_version < '3.13' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } wheels = [ @@ -3764,7 +3780,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "alabaster" }, { name = "babel" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "docutils" }, { name = "imagesize" }, { name = "jinja2" }, @@ -3804,7 +3820,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, { name = "markupsafe" }, - { name = "standard-imghdr", marker = "python_full_version >= '3.13'" }, + { name = "standard-imghdr", marker = "python_full_version >= '3.13' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/43/98/43313781f29e8c6c46fec907430310172d6f207e95e4fbea9289990fbbfe/sphinx_jinja2_compat-0.4.1.tar.gz", hash = "sha256:0188f0802d42c3da72997533b55a00815659a78d3f81d4b4747b1fb15a5728e6", size = 5222, upload-time = "2025-08-06T20:06:25.824Z" } wheels = [ @@ -4155,7 +4171,7 @@ version = "0.27.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "annotated-doc" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, { name = "rich" }, { name = "shellingham" }, ] From 41eb666bb4362df925d052560ae9fe34b8f51eba Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 20:27:09 +0100 Subject: [PATCH 026/166] feat[next]: run embedded fields on torch tensors through TorchOps 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. --- src/gt4py/next/embedded/array_libraries.py | 48 ++++++++++++++++++++++ tests/next_tests/unit_tests/conftest.py | 1 + 2 files changed, 49 insertions(+) diff --git a/src/gt4py/next/embedded/array_libraries.py b/src/gt4py/next/embedded/array_libraries.py index d71e167eb2..dfa5f7ce69 100644 --- a/src/gt4py/next/embedded/array_libraries.py +++ b/src/gt4py/next/embedded/array_libraries.py @@ -104,9 +104,57 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") +class TorchOps(array_ops.ArrayOps): + def __init__(self, xp: ModuleType) -> None: + super().__init__(xp) + import torch + + self._torch = torch + + @property + def array_ns(self) -> ModuleType: + return self._torch + + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + # torch functions reject scalar operands; 0-d tensors keep NumPy's promotion + # because a Python float is made float64 here, not torch's default float32 + if isinstance(value, self._torch.Tensor): + return value + scalar_type = ( + type(value) + if isinstance(value, np.generic) + else core_defs.dtype(type(value)).scalar_type + ) + return self.asarray(value, dtype=scalar_type, like=like) + + def _elementwise(self, name: str) -> Callable[..., Any]: + torch = self._torch + if name == "cbrt": + return lambda x: torch.sign(x) * torch.abs(x) ** (1.0 / 3.0) + if name == "gamma": + + def gamma(x: Any) -> Any: + sign = torch.where((x < 0) & (torch.floor(x) % 2 == 1), -1.0, 1.0).to(x.dtype) + return sign * torch.exp(torch.lgamma(x)) + + return gamma + return super()._elementwise(name) + + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + if not isinstance(value, self._torch.Tensor | int | float | bool): + value = self.asarray(value, like=array) + return super().setitem(array, key, value) + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + return array.detach().cpu().numpy() # type: ignore[attr-defined] # `NDArrayObject` typing is not complete + + array_ops.register(array_api_compat.is_numpy_namespace, NumPyOps) array_ops.register(array_api_compat.is_cupy_namespace, CuPyOps) array_ops.register(array_api_compat.is_jax_namespace, JaxOps) +array_ops.register(array_api_compat.is_torch_namespace, TorchOps) if importlib.util.find_spec("jax") is not None: diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index c8bc05e4b1..1e92caafcd 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -112,6 +112,7 @@ def _optional_module(name: str) -> list[ModuleType]: np, *_optional_module("cupy"), *_optional_module("jax.numpy"), + *_optional_module("torch"), *_optional_module("array_api_strict"), ] From 0b398aadfea6705d8e70c9de85ea86647aa74408 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 20:28:01 +0100 Subject: [PATCH 027/166] test[next]: ArrayOps registry and override points --- .../embedded_tests/test_array_ops.py | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 tests/next_tests/unit_tests/embedded_tests/test_array_ops.py diff --git a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py new file mode 100644 index 0000000000..2c87b41816 --- /dev/null +++ b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py @@ -0,0 +1,82 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +import array_api_compat +import numpy as np +import pytest + +from gt4py.next import common +from gt4py.next.embedded import array_libraries, array_ops, nd_array_field +from gt4py.next.ffront import fbuiltins + + +xs = pytest.importorskip("array_api_strict") + +D = common.Dimension("D") + + +@pytest.fixture +def isolated_registry(monkeypatch): + monkeypatch.setattr(array_ops, "_registry", list(array_ops._registry)) + monkeypatch.setattr(array_ops, "_ops_by_namespace", {}) + monkeypatch.setattr(array_ops, "_ops_by_array_type", {}) + + +def _strict_field(values, dtype=xs.float64): + return common._field(xs.asarray(values, dtype=dtype), domain=common.domain({D: len(values)})) + + +def test_unregistered_namespace_uses_standard_ops(): + field = _strict_field([1.0, 2.0]) + + assert type(field._ops) is array_ops.ArrayOps + assert field.array_ns is xs + assert isinstance(field, nd_array_field.NdArrayField) + + +def test_registered_namespaces(): + assert type(array_ops.of(np.empty(1))) is array_libraries.NumPyOps + assert array_ops.of(np.empty(1)).array_ns is np + + +def test_elementwise_override(isolated_registry): + class Ops(array_ops.ArrayOps): + def _elementwise(self, name): + if name == "sin": + return lambda x: x + 100.0 + return super()._elementwise(name) + + array_ops.register(array_api_compat.is_array_api_strict_namespace, Ops) + field = _strict_field([1.0, 2.0]) + + assert np.allclose(fbuiltins.sin(field).asnumpy(), [101.0, 102.0]) + assert np.allclose(fbuiltins.cos(field).asnumpy(), np.cos([1.0, 2.0])) + + +def test_builtin_override(isolated_registry): + def where_override(cond, x, y): + return "overridden" + + class Ops(array_ops.ArrayOps): + builtin_overrides = {fbuiltins.where: where_override} + + array_ops.register(array_api_compat.is_array_api_strict_namespace, Ops) + field = _strict_field([1.0, 2.0]) + cond = _strict_field([True, False], dtype=xs.bool) + + assert fbuiltins.where(cond, field, field) == "overridden" + assert np.allclose(fbuiltins.minimum(field, 1.5).asnumpy(), [1.0, 1.5]) + + +def test_later_registration_takes_precedence(isolated_registry): + class Ops(array_libraries.NumPyOps): + pass + + array_ops.register(array_api_compat.is_numpy_namespace, Ops) + + assert type(array_ops.of(np.empty(1))) is Ops From e633ae48b3e1fc3a28db56387d20131b838ecced Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 20:37:35 +0100 Subject: [PATCH 028/166] refactor[next]: index and assign embedded buffers only as the Array API specifies - slicing a size-1 broadcast axis of a longer range reads its only element instead of relying on NumPy clamping out-of-bounds slices; - a relative index shorter than the buffer gets a trailing ellipsis; - assigned arrays are converted to the target's namespace, device and dtype by the default ArrayOps (NumPy and CuPy assign directly); - the identity index array takes its length from the domain range. --- src/gt4py/next/embedded/array_libraries.py | 19 ++++++++----- src/gt4py/next/embedded/array_ops.py | 5 ++++ src/gt4py/next/embedded/nd_array_field.py | 31 ++++++++++++++++------ 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries.py b/src/gt4py/next/embedded/array_libraries.py index dfa5f7ce69..3778598364 100644 --- a/src/gt4py/next/embedded/array_libraries.py +++ b/src/gt4py/next/embedded/array_libraries.py @@ -54,6 +54,12 @@ def _elementwise(self, name: str) -> Callable[..., Any]: return _np_gamma return super()._elementwise(name) + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete + return array + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.asarray(array) @@ -75,6 +81,12 @@ def _elementwise(self, name: str) -> Callable[..., Any]: return cupyx.scipy.special.gamma return super()._elementwise(name) + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete + return array + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: import cupy as cp @@ -140,13 +152,6 @@ def gamma(x: Any) -> Any: return gamma return super()._elementwise(name) - def setitem( - self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any - ) -> core_defs.NDArrayObject: - if not isinstance(value, self._torch.Tensor | int | float | bool): - value = self.asarray(value, like=array) - return super().setitem(array, key, value) - def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return array.detach().cpu().numpy() # type: ignore[attr-defined] # `NDArrayObject` typing is not complete diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index c703bd5511..5b4762d45d 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -163,6 +163,11 @@ def setitem( self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any ) -> core_defs.NDArrayObject: """Write `value` into `array[key]`; returns the array holding the result.""" + if not isinstance(value, bool | int | float): + # the standard leaves assigning another dtype or device unspecified + value = self.xp.asarray(value, device=self.device(array)) + if value.dtype != array.dtype: + value = self.xp.astype(value, array.dtype) array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index d7696adcdf..93a51ec982 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -427,13 +427,28 @@ def _slice( new_domain = embedded_common.sub_domain(self.domain, index) index_sequence = common.as_any_index_sequence(index) - slice_ = ( - _get_slices_from_domain_slice(self.domain, index_sequence) - if common.is_absolute_index_sequence(index_sequence) - else index_sequence - ) - assert common.is_relative_index_sequence(slice_) - return new_domain, slice_ + if common.is_absolute_index_sequence(index_sequence): + return new_domain, _broadcast_axes_slice( + _get_slices_from_domain_slice(self.domain, index_sequence), + self.domain, + self._ndarray.shape, + ) + assert common.is_relative_index_sequence(index_sequence) + if len(index_sequence) < self._ndarray.ndim and Ellipsis not in index_sequence: + return new_domain, (*index_sequence, Ellipsis) + return new_domain, index_sequence + + +def _broadcast_axes_slice( + slice_: common.RelativeIndexSequence, domain: common.Domain, shape: tuple[int, ...] +) -> common.RelativeIndexSequence: + """`slice_` with every index into a size-1 axis spanning a longer range (a broadcast axis) reading its only element.""" + return tuple( + (slice(None) if isinstance(s, slice) else 0) + if size == 1 and not (common.UnitRange.is_finite(rng) and len(rng) == 1) + else s + for s, size, rng in zip(slice_, shape, domain.ranges, strict=True) + ) @dataclasses.dataclass(frozen=True) @@ -645,7 +660,7 @@ def _identity_index_array( dtype=None if dtype is None else ops.dtype(dtype), device=ops.device(like), ) - shape = tuple(len(indices) if i == d_idx else 1 for i in range(len(domain))) + shape = tuple(len(unit_range) if i == d_idx else 1 for i in range(len(domain))) return xp.broadcast_to(xp.reshape(indices, shape), domain.shape) From ee652c96976dde270b3a104cb8298eb5a9822476 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 20:37:45 +0100 Subject: [PATCH 029/166] test[next]: run the embedded ffront tests on array-api-strict A new 'array_api_strict_execution' embedded descriptor allocates the test fields with array-api-strict. Tests of cbrt and gamma, which the standard does not define, carry the new 'uses_math_outside_array_api' marker and are expected to fail there. Reference values in two tests are computed on NumPy copies instead of indexing the backend arrays the NumPy way. --- pyproject.toml | 1 + tests/next_tests/definitions.py | 9 +++++++++ tests/next_tests/integration_tests/cases_utils.py | 1 + .../feature_tests/ffront_tests/test_cartesian_shifts.py | 2 +- .../ffront_tests/test_math_unary_builtins.py | 2 ++ .../ffront_tests/test_multiple_output_domains.py | 4 ++-- 6 files changed, 16 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e9d15ea7e5..53ec1aea8a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -249,6 +249,7 @@ markers = [ 'uses_dace: tests that exercise the `dace` backend', 'uses_dynamic_offsets: tests that require backend support for dynamic offsets', 'uses_floordiv: tests that require backend support for floor division', + 'uses_math_outside_array_api: tests of math builtins the Array API standard does not define (cbrt, fmod, gamma)', 'uses_if_stmts: tests that require backend support for if-statements', 'uses_index_fields: tests that require backend support for index fields', 'uses_ir_if_stmts', diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 7e82bb9183..40fe02cc25 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -69,12 +69,16 @@ def _optional_module(name: str) -> Optional[ModuleType]: numpy_execution = EmbeddedDummyBackend("EmbeddedNumPy", np) cupy_execution = EmbeddedDummyBackend("EmbeddedCuPy", _optional_module("cupy")) jax_numpy_execution = EmbeddedDummyBackend("EmbeddedJaxNumPy", _optional_module("jax.numpy")) +array_api_strict_execution = EmbeddedDummyBackend( + "EmbeddedArrayAPIStrict", _optional_module("array_api_strict") +) class EmbeddedIds(_PythonObjectIdMixin, str, enum.Enum): NUMPY_EXECUTION = "next_tests.definitions.numpy_execution" CUPY_EXECUTION = "next_tests.definitions.cupy_execution" JAX_NUMPY_EXECUTION = "next_tests.definitions.jax_numpy_execution" + ARRAY_API_STRICT_EXECUTION = "next_tests.definitions.array_api_strict_execution" class OptionalProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): @@ -132,6 +136,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): USES_CARTESIAN_SHIFT = "uses_cartesian_shift" USES_UNSTRUCTURED_SHIFT = "uses_unstructured_shift" USES_MAX_OVER = "uses_max_over" +USES_MATH_OUTSIDE_ARRAY_API = "uses_math_outside_array_api" USES_MESH_WITH_SKIP_VALUES = "uses_mesh_with_skip_values" USES_PROGRAM_METRICS = "uses_program_metrics" USES_SCALAR_IN_DOMAIN_AND_FO = "uses_scalar_in_domain_and_fo" @@ -220,6 +225,9 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): JAX_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_PROGRAM_WITH_SLICED_OUT_ARGUMENTS, XFAIL, UNSUPPORTED_MESSAGE), ] +ARRAY_API_STRICT_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ + (USES_MATH_OUTSIDE_ARRAY_API, XFAIL, "Not in the Array API standard."), +] ROUNDTRIP_SKIP_LIST = DOMAIN_INFERENCE_SKIP_LIST + [ (USES_PROGRAM_METRICS, XFAIL, UNSUPPORTED_MESSAGE), (USES_SPARSE_FIELDS_AS_OUTPUT, XFAIL, UNSUPPORTED_MESSAGE), @@ -260,6 +268,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): EmbeddedIds.NUMPY_EXECUTION: EMBEDDED_SKIP_LIST, EmbeddedIds.CUPY_EXECUTION: EMBEDDED_SKIP_LIST, EmbeddedIds.JAX_NUMPY_EXECUTION: JAX_EMBEDDED_SKIP_LIST, + EmbeddedIds.ARRAY_API_STRICT_EXECUTION: ARRAY_API_STRICT_EMBEDDED_SKIP_LIST, OptionalProgramBackendId.DACE_CPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_GPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_CPU_NO_OPT: DACE_SKIP_TEST_LIST, diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index ea7c898f4d..4512e31306 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -102,6 +102,7 @@ def __gt_allocator__( next_tests.definitions.EmbeddedIds.JAX_NUMPY_EXECUTION, marks=pytest.mark.requires_jax, ), + next_tests.definitions.EmbeddedIds.ARRAY_API_STRICT_EXECUTION, pytest.param( next_tests.definitions.OptionalProgramBackendId.DACE_CPU, marks=pytest.mark.uses_dace, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_cartesian_shifts.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_cartesian_shifts.py index 1e65cd734c..72861f4712 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_cartesian_shifts.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_cartesian_shifts.py @@ -50,7 +50,7 @@ def testee(a: cases.IJKField, b: cases.IJKField) -> cases.IJKField: b = cases.allocate(cartesian_case, testee, "b").extend({cases.IDim: (0, 2)})() out = cases.allocate(cartesian_case, testee, cases.RETURN)() - cases.verify(cartesian_case, testee, a, b, out=out, ref=a.ndarray[1:] + b.ndarray[2:]) + cases.verify(cartesian_case, testee, a, b, out=out, ref=a.asnumpy()[1:] + b.asnumpy()[2:]) @pytest.mark.uses_cartesian_shift diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_unary_builtins.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_unary_builtins.py index 7929cae7cf..e78148e73f 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_unary_builtins.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_unary_builtins.py @@ -214,6 +214,7 @@ def exp_log_fieldop(inp1: cases.IFloatField, inp2: cases.IFloatField) -> cases.I ) +@pytest.mark.uses_math_outside_array_api def test_gamma(cartesian_case): @gtx.field_operator def gamma_fieldop(inp1: cases.IFloatField) -> cases.IFloatField: @@ -224,6 +225,7 @@ def gamma_fieldop(inp1: cases.IFloatField) -> cases.IFloatField: ) +@pytest.mark.uses_math_outside_array_api def test_roots(cartesian_case): @gtx.field_operator def roots_fieldop(inp1: cases.IFloatField, inp2: cases.IFloatField) -> cases.IFloatField: diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py index 0ddb42a521..3a3132d4a8 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py @@ -544,7 +544,7 @@ def test_program_unstructured(unstructured_case): unstructured_case.default_sizes[Cell], unstructured_case.default_sizes[Edge], inout=(out_a_shifted, out_a), - ref=((a.ndarray)[unstructured_case.offset_provider["C2E"].asnumpy()[:, 1]], a), + ref=(a.asnumpy()[unstructured_case.offset_provider["C2E"].asnumpy()[:, 1]], a), ) @@ -598,7 +598,7 @@ def test_program_temporary(unstructured_case): extend={Cell: (-restrict_cell[0], restrict_cell[1])}, )() - e2v = (a.ndarray)[unstructured_case.offset_provider["E2V"].asnumpy()[:, 1]] + e2v = a.asnumpy()[unstructured_case.offset_provider["E2V"].asnumpy()[:, 1]] cases.verify( unstructured_case, prog_temporary, From 607e6bb6b6c0cf2f6168bc1da826a8ce6fe599d0 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 6 Nov 2026 20:41:14 +0100 Subject: [PATCH 030/166] docs[next]: ADR draft for Array API embedded fields --- .../next/0031-Array_API_Embedded_Fields.md | 64 +++++++++++++++++++ docs/development/ADRs/next/README.md | 1 + 2 files changed, 65 insertions(+) create mode 100644 docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md diff --git a/docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md b/docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md new file mode 100644 index 0000000000..60ca54706b --- /dev/null +++ b/docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md @@ -0,0 +1,64 @@ +--- +tags: [embedded, fields, array-api] +--- + +# Array API Embedded Fields + +- **Status**: draft +- **Authors**: Hannes Vogt (@havogt) +- **Created**: 2026-11-06 +- **Updated**: 2026-11-06 + +In the context of the embedded execution of field operators on NumPy, CuPy, JAX and +further array libraries, facing a field class per library that only selects a NumPy-like +module and an implementation written against NumPy names and signatures, we decided to +have one `NdArrayField` written against the Array API standard. It takes its array +operations from a per-namespace `ArrayOps` object that libraries specialise by +inheritance. This achieves support for any standard-conforming library without new +classes, conformance checked with `array-api-strict`, and library-specific behaviour that +the field does not know about. + +## Context + +`NdArrayField` carried the array module as a class variable, and each library had a field +class and a connectivity class that only set it (JAX also changed item assignment). The +implementation called NumPy names (`power`, `transpose(x, axes)`, `concatenate`), +constructors (`xp.dtype(type)`) and methods (`.astype`, `.item()`, `.dtype.type`). A library +whose namespace is only Array API compatible, like torch through `array_api_compat`, needed a +namespace wrapper re-adding the NumPy names and two field classes per device. + +## Decision + +- `NdArrayField` and `NdArrayConnectivityField` are concrete for every library. A field's + operations are `array_ops.of(field.ndarray)`: an `ArrayOps` instance, cached by array type, + for the namespace `array_api_compat.array_namespace` returns. +- `ArrayOps` implements everything the field does to its buffer using only the Array API + standard. Field code calls standard functions on `ops.xp` and the `ArrayOps` methods where a + library may need to differ: elementwise functions by name, scalar operands, `where`, item + assignment, conversion to NumPy, buffer info, dtype translation. +- A library with different needs subclasses `ArrayOps`, overrides only those methods, and is + registered with `array_ops.register(is_namespace, factory)`. Registration does not import the + library. Replacing a whole `fbuiltins` implementation for one namespace goes through + `ArrayOps.builtin_overrides`. +- `common._field` and `common._connectivity` build an `NdArrayField` from any Array API object. +- `NdArrayField.array_ns` remains the library's own module. +- The embedded unit tests and the embedded ffront tests run on `array-api-strict`. + +## Consequences + +- A conforming library works unregistered. NumPy, CuPy, JAX and torch need small `ArrayOps` + subclasses for what the standard leaves open (NumPy scalars, item assignment of immutable + arrays) or lacks (`gamma`, `cbrt`, `fmod`). +- Trace-time behaviour of JAX or torch (domain inference on concrete connectivity tables) plugs + in through `ArrayOps` hooks, without field subclasses. +- The per-library field classes are removed. +- `gamma`, `cbrt` and `fmod` are not available for libraries that do not provide them. + +## Alternatives considered + +- **A field subclass per library** (the previous design): every library needs a class even when + it adds nothing, and the class is the only extension point. +- **A per-operation override table keyed by namespace**: the overrides of one library are + scattered over entries that each need the library's state, and fallbacks need their own chain. + It is kept only for replacing whole builtins (`builtin_overrides`), where an entry per builtin + is the natural unit. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index f19167ef9b..9b08f7e9d4 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -38,6 +38,7 @@ Writing a new ADR is simple: ### Embedded Execution - [0022 - Limitations of embedded concat_where](0022-Limitations-of-embedded-concat_where.md) +- [0031 - Array API Embedded Fields](0031-Array_API_Embedded_Fields.md) ### Transformations From b3550fd17960ca68d1cd623ae282b880ec646657 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 14:10:29 +0100 Subject: [PATCH 031/166] refactor[next]: TODO on NdArrayField.array_ns returning the library module --- src/gt4py/next/embedded/nd_array_field.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 93a51ec982..af5ac2d50c 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -119,6 +119,8 @@ def _ops(self) -> array_ops.ArrayOps: @property def array_ns(self) -> ModuleType: """The module of the array library holding the buffer, e.g. `numpy`.""" + # TODO(havogt): return the Array API namespace (`self._ops.xp`) instead of the library's + # own module; users comparing it to `numpy` should query the device instead. return self._ops.array_ns def __getstate__(self) -> dict[str, Any]: From e283e33afe971f642cad22ed63960c2936cecb0d Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 14:10:29 +0100 Subject: [PATCH 032/166] docs[next]: remove the Array API embedded fields ADR draft --- .../next/0031-Array_API_Embedded_Fields.md | 64 ------------------- docs/development/ADRs/next/README.md | 1 - 2 files changed, 65 deletions(-) delete mode 100644 docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md diff --git a/docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md b/docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md deleted file mode 100644 index 60ca54706b..0000000000 --- a/docs/development/ADRs/next/0031-Array_API_Embedded_Fields.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -tags: [embedded, fields, array-api] ---- - -# Array API Embedded Fields - -- **Status**: draft -- **Authors**: Hannes Vogt (@havogt) -- **Created**: 2026-11-06 -- **Updated**: 2026-11-06 - -In the context of the embedded execution of field operators on NumPy, CuPy, JAX and -further array libraries, facing a field class per library that only selects a NumPy-like -module and an implementation written against NumPy names and signatures, we decided to -have one `NdArrayField` written against the Array API standard. It takes its array -operations from a per-namespace `ArrayOps` object that libraries specialise by -inheritance. This achieves support for any standard-conforming library without new -classes, conformance checked with `array-api-strict`, and library-specific behaviour that -the field does not know about. - -## Context - -`NdArrayField` carried the array module as a class variable, and each library had a field -class and a connectivity class that only set it (JAX also changed item assignment). The -implementation called NumPy names (`power`, `transpose(x, axes)`, `concatenate`), -constructors (`xp.dtype(type)`) and methods (`.astype`, `.item()`, `.dtype.type`). A library -whose namespace is only Array API compatible, like torch through `array_api_compat`, needed a -namespace wrapper re-adding the NumPy names and two field classes per device. - -## Decision - -- `NdArrayField` and `NdArrayConnectivityField` are concrete for every library. A field's - operations are `array_ops.of(field.ndarray)`: an `ArrayOps` instance, cached by array type, - for the namespace `array_api_compat.array_namespace` returns. -- `ArrayOps` implements everything the field does to its buffer using only the Array API - standard. Field code calls standard functions on `ops.xp` and the `ArrayOps` methods where a - library may need to differ: elementwise functions by name, scalar operands, `where`, item - assignment, conversion to NumPy, buffer info, dtype translation. -- A library with different needs subclasses `ArrayOps`, overrides only those methods, and is - registered with `array_ops.register(is_namespace, factory)`. Registration does not import the - library. Replacing a whole `fbuiltins` implementation for one namespace goes through - `ArrayOps.builtin_overrides`. -- `common._field` and `common._connectivity` build an `NdArrayField` from any Array API object. -- `NdArrayField.array_ns` remains the library's own module. -- The embedded unit tests and the embedded ffront tests run on `array-api-strict`. - -## Consequences - -- A conforming library works unregistered. NumPy, CuPy, JAX and torch need small `ArrayOps` - subclasses for what the standard leaves open (NumPy scalars, item assignment of immutable - arrays) or lacks (`gamma`, `cbrt`, `fmod`). -- Trace-time behaviour of JAX or torch (domain inference on concrete connectivity tables) plugs - in through `ArrayOps` hooks, without field subclasses. -- The per-library field classes are removed. -- `gamma`, `cbrt` and `fmod` are not available for libraries that do not provide them. - -## Alternatives considered - -- **A field subclass per library** (the previous design): every library needs a class even when - it adds nothing, and the class is the only extension point. -- **A per-operation override table keyed by namespace**: the overrides of one library are - scattered over entries that each need the library's state, and fallbacks need their own chain. - It is kept only for replacing whole builtins (`builtin_overrides`), where an entry per builtin - is the natural unit. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index 9b08f7e9d4..f19167ef9b 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -38,7 +38,6 @@ Writing a new ADR is simple: ### Embedded Execution - [0022 - Limitations of embedded concat_where](0022-Limitations-of-embedded-concat_where.md) -- [0031 - Array API Embedded Fields](0031-Array_API_Embedded_Fields.md) ### Transformations From becd4ee4eb8b6b390b790cd9c537f67de581304c Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 14:10:46 +0100 Subject: [PATCH 033/166] refactor[next]: drop TorchOps, torch support moves to its own PR --- src/gt4py/next/embedded/array_libraries.py | 41 ---------------------- tests/next_tests/unit_tests/conftest.py | 1 - 2 files changed, 42 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries.py b/src/gt4py/next/embedded/array_libraries.py index 3778598364..a27d1f8b0c 100644 --- a/src/gt4py/next/embedded/array_libraries.py +++ b/src/gt4py/next/embedded/array_libraries.py @@ -116,50 +116,9 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") -class TorchOps(array_ops.ArrayOps): - def __init__(self, xp: ModuleType) -> None: - super().__init__(xp) - import torch - - self._torch = torch - - @property - def array_ns(self) -> ModuleType: - return self._torch - - def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: - # torch functions reject scalar operands; 0-d tensors keep NumPy's promotion - # because a Python float is made float64 here, not torch's default float32 - if isinstance(value, self._torch.Tensor): - return value - scalar_type = ( - type(value) - if isinstance(value, np.generic) - else core_defs.dtype(type(value)).scalar_type - ) - return self.asarray(value, dtype=scalar_type, like=like) - - def _elementwise(self, name: str) -> Callable[..., Any]: - torch = self._torch - if name == "cbrt": - return lambda x: torch.sign(x) * torch.abs(x) ** (1.0 / 3.0) - if name == "gamma": - - def gamma(x: Any) -> Any: - sign = torch.where((x < 0) & (torch.floor(x) % 2 == 1), -1.0, 1.0).to(x.dtype) - return sign * torch.exp(torch.lgamma(x)) - - return gamma - return super()._elementwise(name) - - def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: - return array.detach().cpu().numpy() # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - - array_ops.register(array_api_compat.is_numpy_namespace, NumPyOps) array_ops.register(array_api_compat.is_cupy_namespace, CuPyOps) array_ops.register(array_api_compat.is_jax_namespace, JaxOps) -array_ops.register(array_api_compat.is_torch_namespace, TorchOps) if importlib.util.find_spec("jax") is not None: diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index 1e92caafcd..c8bc05e4b1 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -112,7 +112,6 @@ def _optional_module(name: str) -> list[ModuleType]: np, *_optional_module("cupy"), *_optional_module("jax.numpy"), - *_optional_module("torch"), *_optional_module("array_api_strict"), ] From a4132e35044068fe9b5c73d13b7357fabf9a182f Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 14:28:40 +0100 Subject: [PATCH 034/166] refactor[next]: one module per array library in embedded.array_libraries NumPyOps, CuPyOps and JaxOps move to numpy_ops, cupy_ops and jax_ops. The package imports and registers cupy_ops and jax_ops only if the library is installed. --- src/gt4py/next/embedded/array_libraries.py | 144 ------------------ .../next/embedded/array_libraries/__init__.py | 19 +++ .../next/embedded/array_libraries/cupy_ops.py | 51 +++++++ .../next/embedded/array_libraries/jax_ops.py | 70 +++++++++ .../embedded/array_libraries/numpy_ops.py | 66 ++++++++ .../embedded_tests/test_array_ops.py | 4 +- 6 files changed, 208 insertions(+), 146 deletions(-) delete mode 100644 src/gt4py/next/embedded/array_libraries.py create mode 100644 src/gt4py/next/embedded/array_libraries/__init__.py create mode 100644 src/gt4py/next/embedded/array_libraries/cupy_ops.py create mode 100644 src/gt4py/next/embedded/array_libraries/jax_ops.py create mode 100644 src/gt4py/next/embedded/array_libraries/numpy_ops.py diff --git a/src/gt4py/next/embedded/array_libraries.py b/src/gt4py/next/embedded/array_libraries.py deleted file mode 100644 index a27d1f8b0c..0000000000 --- a/src/gt4py/next/embedded/array_libraries.py +++ /dev/null @@ -1,144 +0,0 @@ -# GT4Py - GridTools Framework -# -# Copyright (c) 2014-2024, ETH Zurich -# All rights reserved. -# -# Please, refer to the LICENSE file in the root directory. -# SPDX-License-Identifier: BSD-3-Clause - -"""`ArrayOps` of the array libraries whose arrays need more than the Array API standard.""" - -from __future__ import annotations - -import importlib.util -import math -from collections.abc import Callable -from types import ModuleType -from typing import Any - -import array_api_compat -import numpy as np - -from gt4py._core import definitions as core_defs -from gt4py.next import common -from gt4py.next.embedded import array_ops, nd_array_field - - -def _np_gamma(a: core_defs.NDArrayObject) -> core_defs.NDArrayObject: - try: - from scipy.special import gamma - except ImportError: - return np.vectorize(math.gamma, otypes=[a.dtype])(a) - return gamma(a) - - -class NumPyOps(array_ops.ArrayOps): - @property - def array_ns(self) -> ModuleType: - return np - - def asarray( - self, - data: Any, - *, - dtype: Any = None, - like: core_defs.NDArrayObject | None = None, - ) -> core_defs.NDArrayObject: - return np.asarray(data, dtype=dtype) # type: ignore[return-value] # `NDArrayObject` typing is not complete - - def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: - return value - - def _elementwise(self, name: str) -> Callable[..., Any]: - if name == "gamma": - return _np_gamma - return super()._elementwise(name) - - def setitem( - self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any - ) -> core_defs.NDArrayObject: - array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete - return array - - def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: - return np.asarray(array) - - -class CuPyOps(array_ops.ArrayOps): - @property - def array_ns(self) -> ModuleType: - import cupy as cp - - return cp - - def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: - return value - - def _elementwise(self, name: str) -> Callable[..., Any]: - if name == "gamma": - import cupyx.scipy.special - - return cupyx.scipy.special.gamma - return super()._elementwise(name) - - def setitem( - self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any - ) -> core_defs.NDArrayObject: - array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete - return array - - def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: - import cupy as cp - - return cp.asnumpy(array) - - -class JaxOps(array_ops.ArrayOps): - def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: - return value - - def _elementwise(self, name: str) -> Callable[..., Any]: - if name == "gamma": - import jax.scipy.special - - return jax.scipy.special.gamma - return super()._elementwise(name) - - def setitem( - self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any - ) -> core_defs.NDArrayObject: - return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - - def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: - return np.asarray(array) - - def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: - raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") - - -array_ops.register(array_api_compat.is_numpy_namespace, NumPyOps) -array_ops.register(array_api_compat.is_cupy_namespace, CuPyOps) -array_ops.register(array_api_compat.is_jax_namespace, JaxOps) - - -if importlib.util.find_spec("jax") is not None: - import jax - - # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config - jax.config.update("jax_enable_x64", True) - - def _flatten_field( - field: nd_array_field.NdArrayField, - ) -> tuple[tuple[core_defs.NDArrayObject], common.Domain]: - return (field.ndarray,), field.domain - - def _unflatten_field( - domain: common.Domain, children: tuple[core_defs.NDArrayObject] - ) -> nd_array_field.NdArrayField: - return nd_array_field.NdArrayField(domain, children[0]) # type: ignore[abstract] # mypy does not see '__gt_builtin_func__' as implemented by 'FieldBuiltinFuncRegistry' - - jax.tree_util.register_pytree_node( - nd_array_field.NdArrayField, # type: ignore[type-abstract, unused-ignore] # only reported when 'jax' is installed, see '_unflatten_field' - _flatten_field, - _unflatten_field, - ) diff --git a/src/gt4py/next/embedded/array_libraries/__init__.py b/src/gt4py/next/embedded/array_libraries/__init__.py new file mode 100644 index 0000000000..52bf52212f --- /dev/null +++ b/src/gt4py/next/embedded/array_libraries/__init__.py @@ -0,0 +1,19 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""`ArrayOps` of the array libraries whose arrays need more than the Array API standard, registered if installed.""" + +import importlib +import importlib.util + +from . import numpy_ops as numpy_ops + + +for _library in ("cupy", "jax"): + if importlib.util.find_spec(_library) is not None: + importlib.import_module(f"{__name__}.{_library}_ops") diff --git a/src/gt4py/next/embedded/array_libraries/cupy_ops.py b/src/gt4py/next/embedded/array_libraries/cupy_ops.py new file mode 100644 index 0000000000..6402397141 --- /dev/null +++ b/src/gt4py/next/embedded/array_libraries/cupy_ops.py @@ -0,0 +1,51 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""`ArrayOps` for CuPy arrays.""" + +from __future__ import annotations + +from collections.abc import Callable +from types import ModuleType +from typing import Any + +import array_api_compat +import cupy as cp +import numpy as np + +from gt4py._core import definitions as core_defs +from gt4py.next import common +from gt4py.next.embedded import array_ops + + +class CuPyOps(array_ops.ArrayOps): + @property + def array_ns(self) -> ModuleType: + return cp + + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + return value + + def _elementwise(self, name: str) -> Callable[..., Any]: + if name == "gamma": + import cupyx.scipy.special + + return cupyx.scipy.special.gamma + return super()._elementwise(name) + + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete + return array + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + return cp.asnumpy(array) + + +array_ops.register(array_api_compat.is_cupy_namespace, CuPyOps) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py new file mode 100644 index 0000000000..14e704b861 --- /dev/null +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -0,0 +1,70 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""`ArrayOps` for JAX arrays, and `NdArrayField` as a JAX pytree.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import array_api_compat +import jax +import numpy as np + +from gt4py._core import definitions as core_defs +from gt4py.next import common +from gt4py.next.embedded import array_ops, nd_array_field + + +class JaxOps(array_ops.ArrayOps): + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + return value + + def _elementwise(self, name: str) -> Callable[..., Any]: + if name == "gamma": + import jax.scipy.special + + return jax.scipy.special.gamma + return super()._elementwise(name) + + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + return np.asarray(array) + + def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: + raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") + + +array_ops.register(array_api_compat.is_jax_namespace, JaxOps) + +# TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config +jax.config.update("jax_enable_x64", True) + + +def _flatten_field( + field: nd_array_field.NdArrayField, +) -> tuple[tuple[core_defs.NDArrayObject], common.Domain]: + return (field.ndarray,), field.domain + + +def _unflatten_field( + domain: common.Domain, children: tuple[core_defs.NDArrayObject] +) -> nd_array_field.NdArrayField: + return nd_array_field.NdArrayField(domain, children[0]) # type: ignore[abstract] # mypy does not see '__gt_builtin_func__' as implemented by 'FieldBuiltinFuncRegistry' + + +jax.tree_util.register_pytree_node( + nd_array_field.NdArrayField, # type: ignore[type-abstract, unused-ignore] # only reported when 'jax' is installed, see '_unflatten_field' + _flatten_field, + _unflatten_field, +) diff --git a/src/gt4py/next/embedded/array_libraries/numpy_ops.py b/src/gt4py/next/embedded/array_libraries/numpy_ops.py new file mode 100644 index 0000000000..dcdbbf736e --- /dev/null +++ b/src/gt4py/next/embedded/array_libraries/numpy_ops.py @@ -0,0 +1,66 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""`ArrayOps` for NumPy arrays.""" + +from __future__ import annotations + +import math +from collections.abc import Callable +from types import ModuleType +from typing import Any + +import array_api_compat +import numpy as np + +from gt4py._core import definitions as core_defs +from gt4py.next import common +from gt4py.next.embedded import array_ops + + +def _np_gamma(a: core_defs.NDArrayObject) -> core_defs.NDArrayObject: + try: + from scipy.special import gamma + except ImportError: + return np.vectorize(math.gamma, otypes=[a.dtype])(a) + return gamma(a) + + +class NumPyOps(array_ops.ArrayOps): + @property + def array_ns(self) -> ModuleType: + return np + + def asarray( + self, + data: Any, + *, + dtype: Any = None, + like: core_defs.NDArrayObject | None = None, + ) -> core_defs.NDArrayObject: + return np.asarray(data, dtype=dtype) # type: ignore[return-value] # `NDArrayObject` typing is not complete + + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: + return value + + def _elementwise(self, name: str) -> Callable[..., Any]: + if name == "gamma": + return _np_gamma + return super()._elementwise(name) + + def setitem( + self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any + ) -> core_defs.NDArrayObject: + array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete + return array + + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: + return np.asarray(array) + + +array_ops.register(array_api_compat.is_numpy_namespace, NumPyOps) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py index 2c87b41816..ff366a1b22 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py @@ -40,7 +40,7 @@ def test_unregistered_namespace_uses_standard_ops(): def test_registered_namespaces(): - assert type(array_ops.of(np.empty(1))) is array_libraries.NumPyOps + assert type(array_ops.of(np.empty(1))) is array_libraries.numpy_ops.NumPyOps assert array_ops.of(np.empty(1)).array_ns is np @@ -74,7 +74,7 @@ class Ops(array_ops.ArrayOps): def test_later_registration_takes_precedence(isolated_registry): - class Ops(array_libraries.NumPyOps): + class Ops(array_libraries.numpy_ops.NumPyOps): pass array_ops.register(array_api_compat.is_numpy_namespace, Ops) From 30dec7adc554b6cd7a4888cf664f76392f5bac7b Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 14:45:43 +0100 Subject: [PATCH 035/166] test[next]: import array-api-strict unconditionally, it is a test dependency --- tests/next_tests/definitions.py | 5 ++--- tests/next_tests/unit_tests/conftest.py | 3 ++- tests/next_tests/unit_tests/embedded_tests/test_array_ops.py | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 40fe02cc25..06d0b6af8e 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -14,6 +14,7 @@ from types import ModuleType from typing import Final, Optional +import array_api_strict import numpy as np import pytest @@ -69,9 +70,7 @@ def _optional_module(name: str) -> Optional[ModuleType]: numpy_execution = EmbeddedDummyBackend("EmbeddedNumPy", np) cupy_execution = EmbeddedDummyBackend("EmbeddedCuPy", _optional_module("cupy")) jax_numpy_execution = EmbeddedDummyBackend("EmbeddedJaxNumPy", _optional_module("jax.numpy")) -array_api_strict_execution = EmbeddedDummyBackend( - "EmbeddedArrayAPIStrict", _optional_module("array_api_strict") -) +array_api_strict_execution = EmbeddedDummyBackend("EmbeddedArrayAPIStrict", array_api_strict) class EmbeddedIds(_PythonObjectIdMixin, str, enum.Enum): diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index c8bc05e4b1..e51a07de4d 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -13,6 +13,7 @@ from types import ModuleType from typing import Final, TypeAlias +import array_api_strict import numpy as np import pytest @@ -112,7 +113,7 @@ def _optional_module(name: str) -> list[ModuleType]: np, *_optional_module("cupy"), *_optional_module("jax.numpy"), - *_optional_module("array_api_strict"), + array_api_strict, ] diff --git a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py index ff366a1b22..8277253b3c 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py @@ -7,6 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause import array_api_compat +import array_api_strict as xs import numpy as np import pytest @@ -15,8 +16,6 @@ from gt4py.next.ffront import fbuiltins -xs = pytest.importorskip("array_api_strict") - D = common.Dimension("D") From 64fd3fa17ee97898efd4b3bc80ea7e2f38ec2e10 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 14:54:34 +0100 Subject: [PATCH 036/166] refactor[next]: dtype translation per array namespace in _core.ndarray_utils The tables between gt4py scalar types and a namespace's dtype objects move from ArrayOps to 'ndarray_utils.namespace_dtype', 'scalar_type' and 'dtype_of', cached per namespace. The field constructors and 'field_from_typespec' use them instead of reaching into the embedded ArrayOps. --- src/gt4py/_core/ndarray_utils.py | 41 ++++++++++++++++++- src/gt4py/next/constructors.py | 11 ++--- src/gt4py/next/embedded/array_ops.py | 26 ++---------- src/gt4py/next/field_utils.py | 6 +-- .../unit_tests/test_nd_array_utils.py | 24 ++++++++++- 5 files changed, 72 insertions(+), 36 deletions(-) diff --git a/src/gt4py/_core/ndarray_utils.py b/src/gt4py/_core/ndarray_utils.py index 3465b9b9ce..acb1083ada 100644 --- a/src/gt4py/_core/ndarray_utils.py +++ b/src/gt4py/_core/ndarray_utils.py @@ -6,13 +6,14 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import functools from collections.abc import Hashable from typing import Any, Callable, Protocol, TypeGuard, cast import array_api_compat import numpy as np -from gt4py._core import definitions as core_defs +from gt4py._core import definitions as core_defs, types as core_types try: @@ -108,6 +109,44 @@ def array_namespace(array: core_defs.NDArrayObject) -> ArrayNamespace: return cast(ArrayNamespace, array_api_compat.array_namespace(array)) +@functools.cache +def _dtype_tables(array_ns: ArrayNamespace) -> tuple[dict[type, Any], dict[Any, type]]: + to_namespace = { + scalar_type: getattr(array_ns, name) + for scalar_type, name in core_types.type_to_name.items() + if hasattr(array_ns, name) + } + # keyed by the dtype of an actual array: e.g. NumPy namespaces expose scalar types as dtypes + to_scalar_type = { + array_ns.empty((0,), dtype=dtype).dtype: scalar_type + for scalar_type, dtype in to_namespace.items() + } + return to_namespace, to_scalar_type + + +def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar]) -> Any: + """The dtype object of `array_ns` for the gt4py scalar type `scalar_type`.""" + try: + return _dtype_tables(array_ns)[0][scalar_type] + except KeyError: + raise TypeError(f"Array namespace '{array_ns}' has no dtype for '{scalar_type}'.") from None + + +def scalar_type(array_ns: ArrayNamespace, dtype: Any) -> type[core_defs.Scalar]: + """The gt4py scalar type of the arrays of `array_ns` with dtype `dtype`.""" + try: + return _dtype_tables(array_ns)[1][dtype] + except KeyError: + raise TypeError( + f"Dtype '{dtype}' of array namespace '{array_ns}' is not a gt4py scalar type." + ) from None + + +def dtype_of(array: core_defs.NDArrayObject) -> core_defs.DType: + """The gt4py dtype of `array`.""" + return core_defs.dtype(scalar_type(array_namespace(array), array.dtype)) + + def _numpy_device_translator(device: core_defs.Device | None) -> Any: if device is None: return None diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index e042cceed7..e9170f74af 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -19,13 +19,8 @@ import gt4py.eve as eve import gt4py.next.common as common import gt4py.next.custom_layout_allocators as next_allocators -import gt4py.next.embedded.array_ops as array_ops import gt4py.next.embedded.nd_array_field as nd_array_field -from gt4py._core import ( - definitions as core_defs, - ndarray_utils as core_ndarray_utils, - types as core_types, -) +from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.eve import xtyping @@ -207,7 +202,7 @@ def as_field( raise ValueError(f"Cannot construct 'Field' from array of shape '{data.shape}'.") if dtype is None: - dtype = core_defs.dtype(array_ops.of(data).scalar_type(data.dtype)) + dtype = core_ndarray_utils.dtype_of(data) return self._construct_from_array( actual_domain, @@ -270,7 +265,7 @@ def __post_init__(self) -> None: ) def _to_array_ns_dtype(self, dtype: core_defs.DType) -> Any: - return getattr(self.array_ns, core_types.type_to_name[dtype.scalar_type]) + return core_ndarray_utils.namespace_dtype(self.array_ns, dtype.scalar_type) def empty( self, diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 5b4762d45d..f6dae4956f 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -29,7 +29,7 @@ import array_api_compat.numpy as compat_numpy import numpy as np -from gt4py._core import definitions as core_defs, types as core_types +from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.next import common @@ -70,16 +70,6 @@ class ArrayOps: def __init__(self, xp: ModuleType) -> None: self.xp = xp - self._dtypes = { - scalar_type: getattr(xp, name) - for scalar_type, name in core_types.type_to_name.items() - if hasattr(xp, name) - } - # keyed by the dtype of an actual array: e.g. NumPy namespaces expose scalar types as dtypes - self._scalar_types = { - xp.empty(0, dtype=dtype).dtype: scalar_type - for scalar_type, dtype in self._dtypes.items() - } self._elementwise_cache: dict[str, Callable[..., Any]] = {} def __repr__(self) -> str: @@ -91,20 +81,10 @@ def array_ns(self) -> ModuleType: return self.xp def dtype(self, scalar_type: type) -> Any: - try: - return self._dtypes[core_defs.dtype(scalar_type).scalar_type] - except KeyError: - raise TypeError( - f"Array namespace '{self.xp.__name__}' has no dtype for '{scalar_type}'." - ) from None + return core_ndarray_utils.namespace_dtype(self.xp, core_defs.dtype(scalar_type).scalar_type) def scalar_type(self, dtype: Any) -> type[core_defs.Scalar]: - try: - return self._scalar_types[dtype] - except KeyError: - raise TypeError( - f"Dtype '{dtype}' of array namespace '{self.xp.__name__}' is not a gt4py scalar type." - ) from None + return core_ndarray_utils.scalar_type(self.xp, dtype) def device(self, array: core_defs.NDArrayObject) -> Any: return array_api_compat.device(array) diff --git a/src/gt4py/next/field_utils.py b/src/gt4py/next/field_utils.py index c0cf06b057..c80dd870ee 100644 --- a/src/gt4py/next/field_utils.py +++ b/src/gt4py/next/field_utils.py @@ -10,7 +10,7 @@ import numpy as np -from gt4py._core import definitions as core_defs, types as core_types +from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.eve.xtyping import NestedTuple from gt4py.next import common, named_collections, utils from gt4py.next.type_system import type_specifications as ts, type_translation @@ -69,8 +69,8 @@ def impl(type_: ts.ScalarType) -> common.MutableField: res = common._field( xp.empty( domain.shape, - dtype=getattr( - xp, core_types.type_to_name[type_translation.as_dtype(type_).scalar_type] + dtype=core_ndarray_utils.namespace_dtype( + xp, type_translation.as_dtype(type_).scalar_type ), ), domain=domain, diff --git a/tests/core_tests/unit_tests/test_nd_array_utils.py b/tests/core_tests/unit_tests/test_nd_array_utils.py index 16a63cc916..68a3c2c5c4 100644 --- a/tests/core_tests/unit_tests/test_nd_array_utils.py +++ b/tests/core_tests/unit_tests/test_nd_array_utils.py @@ -6,10 +6,14 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import importlib from typing import Any -from gt4py._core import ndarray_utils, definitions + +import numpy as np import pytest +from gt4py._core import ndarray_utils, definitions + def cuda_device(id_: int) -> Any: if ndarray_utils.cupy is not None: @@ -45,3 +49,21 @@ def test_get_device_translator(array_ns, gt4py_device, expected_device): ) def test_is_array_namespace(array_ns): assert ndarray_utils.is_array_namespace(array_ns) + + +@pytest.mark.parametrize("array_ns_name", ["numpy", "array_api_strict"]) +@pytest.mark.parametrize( + "scalar_type", [np.bool_, np.int32, np.int64, np.uint8, np.float32, np.float64] +) +def test_dtype_translation(array_ns_name, scalar_type): + array_ns = importlib.import_module(array_ns_name) + name = np.dtype(scalar_type).name + array = array_ns.empty((2,), dtype=getattr(array_ns, name)) + + assert ndarray_utils.namespace_dtype(array_ns, scalar_type) == getattr(array_ns, name) + assert ndarray_utils.dtype_of(array) == definitions.dtype(scalar_type) + + +def test_dtype_of_unsupported_dtype(): + with pytest.raises(TypeError, match="not a gt4py scalar type"): + ndarray_utils.dtype_of(np.empty((2,), dtype=np.complex128)) From 15284726b6b40e3cccf77effa52719be9a51a55c Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 15:19:57 +0100 Subject: [PATCH 037/166] fix[next]: gt4py scalar type of NumPy-style dtypes independent of byte order NumPy, CuPy and JAX dtypes map to their scalar type ('dtype.type'), as before this branch, instead of being looked up by equality in a table of dtypes of freshly created arrays. Non-native byte order is accepted again, and JAX without x64, which creates 32-bit arrays for 64-bit dtypes, no longer reports 64-bit dtypes for 32-bit arrays. Building the tables no longer creates arrays. --- src/gt4py/_core/ndarray_utils.py | 22 +++++++++---------- .../unit_tests/test_nd_array_utils.py | 16 ++++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/gt4py/_core/ndarray_utils.py b/src/gt4py/_core/ndarray_utils.py index acb1083ada..6ea2e798f6 100644 --- a/src/gt4py/_core/ndarray_utils.py +++ b/src/gt4py/_core/ndarray_utils.py @@ -8,7 +8,7 @@ import functools from collections.abc import Hashable -from typing import Any, Callable, Protocol, TypeGuard, cast +from typing import Any, Callable, Final, Protocol, TypeGuard, cast import array_api_compat import numpy as np @@ -109,6 +109,9 @@ def array_namespace(array: core_defs.NDArrayObject) -> ArrayNamespace: return cast(ArrayNamespace, array_api_compat.array_namespace(array)) +_SCALAR_TYPES: Final = frozenset(core_defs.SCALAR_TYPES) + + @functools.cache def _dtype_tables(array_ns: ArrayNamespace) -> tuple[dict[type, Any], dict[Any, type]]: to_namespace = { @@ -116,12 +119,7 @@ def _dtype_tables(array_ns: ArrayNamespace) -> tuple[dict[type, Any], dict[Any, for scalar_type, name in core_types.type_to_name.items() if hasattr(array_ns, name) } - # keyed by the dtype of an actual array: e.g. NumPy namespaces expose scalar types as dtypes - to_scalar_type = { - array_ns.empty((0,), dtype=dtype).dtype: scalar_type - for scalar_type, dtype in to_namespace.items() - } - return to_namespace, to_scalar_type + return to_namespace, {dtype: scalar_type for scalar_type, dtype in to_namespace.items()} def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar]) -> Any: @@ -134,12 +132,14 @@ def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar def scalar_type(array_ns: ArrayNamespace, dtype: Any) -> type[core_defs.Scalar]: """The gt4py scalar type of the arrays of `array_ns` with dtype `dtype`.""" - try: - return _dtype_tables(array_ns)[1][dtype] - except KeyError: + # NumPy, CuPy and JAX describe dtypes as `np.dtype`, whose byte order and whose + # namespace attribute (a scalar type, e.g. `np.float64`) do not compare equal to it + result = dtype.type if isinstance(dtype, np.dtype) else _dtype_tables(array_ns)[1].get(dtype) + if result not in _SCALAR_TYPES: raise TypeError( f"Dtype '{dtype}' of array namespace '{array_ns}' is not a gt4py scalar type." - ) from None + ) + return result def dtype_of(array: core_defs.NDArrayObject) -> core_defs.DType: diff --git a/tests/core_tests/unit_tests/test_nd_array_utils.py b/tests/core_tests/unit_tests/test_nd_array_utils.py index 68a3c2c5c4..a4d3333895 100644 --- a/tests/core_tests/unit_tests/test_nd_array_utils.py +++ b/tests/core_tests/unit_tests/test_nd_array_utils.py @@ -67,3 +67,19 @@ def test_dtype_translation(array_ns_name, scalar_type): def test_dtype_of_unsupported_dtype(): with pytest.raises(TypeError, match="not a gt4py scalar type"): ndarray_utils.dtype_of(np.empty((2,), dtype=np.complex128)) + + +@pytest.mark.parametrize("dtype", [">f8", "i4", " Date: Mon, 9 Nov 2026 15:28:22 +0100 Subject: [PATCH 040/166] fix[next]: reject assignment to part of a broadcast axis of an embedded field A size-1 buffer axis spanning a longer range stores one element for the whole range. Assigning to part of the range used to write nothing (base) or the single element, changing the whole range (previous commit on this branch); it now raises ValueError. Assigning to the whole range and restricting a broadcast axis are unchanged and tested. --- src/gt4py/next/embedded/nd_array_field.py | 20 ++++++++-- .../embedded_tests/test_nd_array_field.py | 38 +++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index af5ac2d50c..a83cb18bfa 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -349,6 +349,17 @@ def __setitem__( ) -> None: target_domain, target_slice = self._slice(index) + # TODO(havogt): a broadcast axis stores one element for its whole range, so a write to + # part of the range cannot be represented without materializing the axis. Remove once + # broadcasting has a representation that is not a size-1 buffer axis. + for dim, rng, size in zip(self.domain.dims, self.domain.ranges, self._ndarray.shape): + if _is_broadcast_axis(size, rng) and ( + dim not in target_domain.dims or target_domain[dim].unit_range != rng + ): + raise ValueError( + f"Cannot assign to part of the broadcast dimension '{dim}' of range '{rng}'." + ) + if isinstance(value, common.Field): if not value.domain == target_domain: raise ValueError( @@ -441,14 +452,17 @@ def _slice( return new_domain, index_sequence +def _is_broadcast_axis(size: int, rng: common.UnitRange) -> bool: + """Whether a buffer axis of `size` stands for every index of the longer range `rng`.""" + return size == 1 and not (common.UnitRange.is_finite(rng) and len(rng) == 1) + + def _broadcast_axes_slice( slice_: common.RelativeIndexSequence, domain: common.Domain, shape: tuple[int, ...] ) -> common.RelativeIndexSequence: """`slice_` with every index into a size-1 axis spanning a longer range (a broadcast axis) reading its only element.""" return tuple( - (slice(None) if isinstance(s, slice) else 0) - if size == 1 and not (common.UnitRange.is_finite(rng) and len(rng) == 1) - else s + (slice(None) if isinstance(s, slice) else 0) if _is_broadcast_axis(size, rng) else s for s, size, rng in zip(slice_, shape, domain.ranges, strict=True) ) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 9352fc499f..e9be39c26b 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1290,6 +1290,44 @@ def test_setitem_wrong_domain(): field[(1, slice(None))] = value_incompatible +def _broadcast_field(): + """A field over D0=[0, 3) x D1=[0, 4) whose D1 axis is broadcast: one stored element per D0 index.""" + return common._field( + np.asarray([[1.0], [2.0], [3.0]]), + domain=common.Domain(dims=(D0, D1), ranges=(UnitRange(0, 3), UnitRange(0, 4))), + ) + + +def test_restrict_broadcast_axis(): + restricted = _broadcast_field()[(NamedRange(D1, UnitRange(1, 3)),)] + + assert restricted.domain == common.Domain( + dims=(D0, D1), ranges=(UnitRange(0, 3), UnitRange(1, 3)) + ) + assert np.array_equal(restricted.asnumpy(), [[1.0], [2.0], [3.0]]) + + +def test_setitem_whole_broadcast_axis(): + field = _broadcast_field() + + field[(NamedIndex(D0, 1),)] = 7.0 + + assert np.array_equal(field.asnumpy(), [[1.0], [7.0], [3.0]]) + + +@pytest.mark.parametrize( + "index", + [(NamedRange(D1, UnitRange(1, 3)),), (NamedIndex(D1, 2),)], + ids=["range", "index"], +) +def test_setitem_part_of_broadcast_axis_raises(index): + field = _broadcast_field() + + with pytest.raises(ValueError, match="broadcast dimension"): + field[index] = 7.0 + assert np.array_equal(field.asnumpy(), [[1.0], [2.0], [3.0]]) + + def test_nd_array_field_getstate_excludes_cached_properties(): """Test that __getstate__ only serializes dataclass fields, excluding cached properties.""" data = np.asarray([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) From 1aa3e71da51dd1535e50227ef26218179e7440e7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 15:28:22 +0100 Subject: [PATCH 041/166] fix[next]: to_numpy of the default ArrayOps on NumPy 2.0 NumPy 2.0's from_dlpack takes no 'device' and 'copy'; it is called without them there, which handles host arrays. --- src/gt4py/next/embedded/array_ops.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index f6dae4956f..ac4b932af0 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -33,6 +33,10 @@ from gt4py.next import common +# TODO(havogt): drop once gt4py requires NumPy >= 2.1, the first version whose `from_dlpack` +# takes `device` and `copy`; NumPy 2.0's `from_dlpack` cannot copy a non-CPU array to the host. +_NUMPY_FROM_DLPACK_TAKES_DEVICE: Final = np.lib.NumpyVersion(np.__version__) >= "2.1.0" + #: gt4py builtin and operator names whose Array API name differs. STANDARD_NAMES: Final[Mapping[str, str]] = { "neg": "negative", @@ -152,7 +156,9 @@ def setitem( return array def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: - return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete + if _NUMPY_FROM_DLPACK_TAKES_DEVICE: + return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete + return np.from_dlpack(array) # type: ignore[arg-type] # `NDArrayObject` typing is not complete def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: return common.BufferInfo.from_ndarray(array) From 9e1c54b4f36eec0262ddcfbb1ea076f097f37c65 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 15:33:50 +0100 Subject: [PATCH 042/166] docs[next]: say that every NdArrayField is a JAX pytree --- src/gt4py/next/embedded/array_libraries/jax_ops.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 14e704b861..e958006db5 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -63,6 +63,9 @@ def _unflatten_field( return nd_array_field.NdArrayField(domain, children[0]) # type: ignore[abstract] # mypy does not see '__gt_builtin_func__' as implemented by 'FieldBuiltinFuncRegistry' +# JAX registers pytrees by type, so fields of every array library are pytrees, not only those +# holding JAX arrays: like a bare NumPy array, a NumPy-backed field passed to `jax.jit` is +# copied to a JAX array on every call. jax.tree_util.register_pytree_node( nd_array_field.NdArrayField, # type: ignore[type-abstract, unused-ignore] # only reported when 'jax' is installed, see '_unflatten_field' _flatten_field, From 46c71930583b466127f48aebf87f19883f1cd7dc Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 9 Nov 2026 15:42:34 +0100 Subject: [PATCH 043/166] fix[next]: accept NumPy dtypes named by C type, e.g. np.longlong 'np.dtype(np.longlong).type' is 'np.longlong', not 'np.int64', on Linux, so the scalar-type lookup rejected such arrays, which 'as_field' accepted before this branch. NumPy-style dtypes are now identified by kind and size. --- src/gt4py/_core/ndarray_utils.py | 15 ++++++++++++--- .../unit_tests/test_nd_array_utils.py | 18 +++++++++++++----- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/gt4py/_core/ndarray_utils.py b/src/gt4py/_core/ndarray_utils.py index 6ea2e798f6..226d3a1afb 100644 --- a/src/gt4py/_core/ndarray_utils.py +++ b/src/gt4py/_core/ndarray_utils.py @@ -112,6 +112,13 @@ def array_namespace(array: core_defs.NDArrayObject) -> ArrayNamespace: _SCALAR_TYPES: Final = frozenset(core_defs.SCALAR_TYPES) +@functools.cache +def _numpy_scalar_type(dtype: np.dtype) -> type: + # NumPy, CuPy and JAX describe dtypes as `np.dtype`, and its `type` depends on byte order + # and C type name (e.g. `np.longlong` is not `np.int64`); kind and size identify it + return np.dtype(f"{dtype.kind}{dtype.itemsize}").type + + @functools.cache def _dtype_tables(array_ns: ArrayNamespace) -> tuple[dict[type, Any], dict[Any, type]]: to_namespace = { @@ -132,9 +139,11 @@ def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar def scalar_type(array_ns: ArrayNamespace, dtype: Any) -> type[core_defs.Scalar]: """The gt4py scalar type of the arrays of `array_ns` with dtype `dtype`.""" - # NumPy, CuPy and JAX describe dtypes as `np.dtype`, whose byte order and whose - # namespace attribute (a scalar type, e.g. `np.float64`) do not compare equal to it - result = dtype.type if isinstance(dtype, np.dtype) else _dtype_tables(array_ns)[1].get(dtype) + result = ( + _numpy_scalar_type(dtype) + if isinstance(dtype, np.dtype) + else _dtype_tables(array_ns)[1].get(dtype) + ) if result not in _SCALAR_TYPES: raise TypeError( f"Dtype '{dtype}' of array namespace '{array_ns}' is not a gt4py scalar type." diff --git a/tests/core_tests/unit_tests/test_nd_array_utils.py b/tests/core_tests/unit_tests/test_nd_array_utils.py index a4d3333895..d315f4c796 100644 --- a/tests/core_tests/unit_tests/test_nd_array_utils.py +++ b/tests/core_tests/unit_tests/test_nd_array_utils.py @@ -64,11 +64,6 @@ def test_dtype_translation(array_ns_name, scalar_type): assert ndarray_utils.dtype_of(array) == definitions.dtype(scalar_type) -def test_dtype_of_unsupported_dtype(): - with pytest.raises(TypeError, match="not a gt4py scalar type"): - ndarray_utils.dtype_of(np.empty((2,), dtype=np.complex128)) - - @pytest.mark.parametrize("dtype", [">f8", "i4", " Date: Mon, 9 Nov 2026 15:44:37 +0100 Subject: [PATCH 044/166] refactor[next]: assign into broadcast axes as on main The check rejecting assignment to part of a broadcast axis fixes behaviour that is already broken on main and moves to its own PR. Assignment indexes the buffer as given again, so it keeps main's behaviour; only reads go through the broadcast-axis normalization. --- src/gt4py/next/embedded/nd_array_field.py | 34 +++++------------ .../embedded_tests/test_nd_array_field.py | 38 ------------------- 2 files changed, 10 insertions(+), 62 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index a83cb18bfa..63b2bff256 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -347,18 +347,7 @@ def __setitem__( index: common.AnyIndexSpec, value: common.Field | core_defs.NDArrayObject | core_defs.ScalarT, ) -> None: - target_domain, target_slice = self._slice(index) - - # TODO(havogt): a broadcast axis stores one element for its whole range, so a write to - # part of the range cannot be represented without materializing the axis. Remove once - # broadcasting has a representation that is not a size-1 buffer axis. - for dim, rng, size in zip(self.domain.dims, self.domain.ranges, self._ndarray.shape): - if _is_broadcast_axis(size, rng) and ( - dim not in target_domain.dims or target_domain[dim].unit_range != rng - ): - raise ValueError( - f"Cannot assign to part of the broadcast dimension '{dim}' of range '{rng}'." - ) + target_domain, target_slice = self._slice(index, for_assignment=True) if isinstance(value, common.Field): if not value.domain == target_domain: @@ -434,35 +423,32 @@ def __invert__(self) -> NdArrayField: raise NotImplementedError("'__invert__' not implemented for non-'bool' fields.") def _slice( - self, index: common.AnyIndexSpec + self, index: common.AnyIndexSpec, *, for_assignment: bool = False ) -> tuple[common.Domain, common.RelativeIndexSequence]: index = embedded_common.canonicalize_any_index_sequence(index) new_domain = embedded_common.sub_domain(self.domain, index) index_sequence = common.as_any_index_sequence(index) if common.is_absolute_index_sequence(index_sequence): - return new_domain, _broadcast_axes_slice( - _get_slices_from_domain_slice(self.domain, index_sequence), - self.domain, - self._ndarray.shape, - ) + buffer_slice = _get_slices_from_domain_slice(self.domain, index_sequence) + if for_assignment: + # writing the only element of a broadcast axis would change its whole range + return new_domain, buffer_slice + return new_domain, _broadcast_axes_slice(buffer_slice, self.domain, self._ndarray.shape) assert common.is_relative_index_sequence(index_sequence) if len(index_sequence) < self._ndarray.ndim and Ellipsis not in index_sequence: return new_domain, (*index_sequence, Ellipsis) return new_domain, index_sequence -def _is_broadcast_axis(size: int, rng: common.UnitRange) -> bool: - """Whether a buffer axis of `size` stands for every index of the longer range `rng`.""" - return size == 1 and not (common.UnitRange.is_finite(rng) and len(rng) == 1) - - def _broadcast_axes_slice( slice_: common.RelativeIndexSequence, domain: common.Domain, shape: tuple[int, ...] ) -> common.RelativeIndexSequence: """`slice_` with every index into a size-1 axis spanning a longer range (a broadcast axis) reading its only element.""" return tuple( - (slice(None) if isinstance(s, slice) else 0) if _is_broadcast_axis(size, rng) else s + (slice(None) if isinstance(s, slice) else 0) + if size == 1 and not (common.UnitRange.is_finite(rng) and len(rng) == 1) + else s for s, size, rng in zip(slice_, shape, domain.ranges, strict=True) ) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index e9be39c26b..9352fc499f 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1290,44 +1290,6 @@ def test_setitem_wrong_domain(): field[(1, slice(None))] = value_incompatible -def _broadcast_field(): - """A field over D0=[0, 3) x D1=[0, 4) whose D1 axis is broadcast: one stored element per D0 index.""" - return common._field( - np.asarray([[1.0], [2.0], [3.0]]), - domain=common.Domain(dims=(D0, D1), ranges=(UnitRange(0, 3), UnitRange(0, 4))), - ) - - -def test_restrict_broadcast_axis(): - restricted = _broadcast_field()[(NamedRange(D1, UnitRange(1, 3)),)] - - assert restricted.domain == common.Domain( - dims=(D0, D1), ranges=(UnitRange(0, 3), UnitRange(1, 3)) - ) - assert np.array_equal(restricted.asnumpy(), [[1.0], [2.0], [3.0]]) - - -def test_setitem_whole_broadcast_axis(): - field = _broadcast_field() - - field[(NamedIndex(D0, 1),)] = 7.0 - - assert np.array_equal(field.asnumpy(), [[1.0], [7.0], [3.0]]) - - -@pytest.mark.parametrize( - "index", - [(NamedRange(D1, UnitRange(1, 3)),), (NamedIndex(D1, 2),)], - ids=["range", "index"], -) -def test_setitem_part_of_broadcast_axis_raises(index): - field = _broadcast_field() - - with pytest.raises(ValueError, match="broadcast dimension"): - field[index] = 7.0 - assert np.array_equal(field.asnumpy(), [[1.0], [2.0], [3.0]]) - - def test_nd_array_field_getstate_excludes_cached_properties(): """Test that __getstate__ only serializes dataclass fields, excluding cached properties.""" data = np.asarray([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) From 08d073b9f92ceaa2b6a1f1029456f0dddcc2015f Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 10 Nov 2026 19:50:54 +0100 Subject: [PATCH 045/166] refactor[next]: decide the tracing case of a connectivity in one place A connectivity under a jax trace is in one of three cases: concrete table, traced table with a concrete twin, or traced table without values. The `_concrete` property names the case, and `_inverse_image`, `restrict` and the gather branch on it. The pytree handle now carries the twin connectivity, so its cached domain lookups survive retraces. Library specifics shrink to `_is_traced` and `_concrete_eval`. --- .../0029-Connectivities_Under_JAX_Tracing.md | 14 +- src/gt4py/next/embedded/nd_array_field.py | 160 +++++++++--------- 2 files changed, 85 insertions(+), 89 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 7b9387b63a..831bfddec9 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -22,17 +22,17 @@ Narrowing is the common case: the field usually covers only part of the connecti ## Decision -`JaxArrayConnectivityField` is a pytree node. The table is the child, and the aux data holds domain, codomain, skip value and a `_TableHandle` to the same buffer. The handle compares by buffer identity, so a new wrapper around the same buffer does not retrace, while a new buffer does. Domain inference reads the table through the handle under `jax.ensure_compile_time_eval()`. +`JaxArrayConnectivityField` is a pytree node. The table is the child, and the aux data holds domain, codomain, skip value and a handle to a concrete connectivity with the same table, its twin. The handle compares by the identity of the twin's table, so a new wrapper around the same buffer does not retrace, while a new buffer does. While the table is traced, domain inference and `restrict` delegate to the twin, which evaluates under `jax.ensure_compile_time_eval()`. One property, `_concrete`, names which of the cases below a connectivity is in, and every operation that differs between them branches on it. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: -- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer, and flattening attached the handle. Domain inference reads the concrete table through the handle, and the gather takes the table as a runtime argument. +- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer, and flattening attached the twin. Domain inference reads the twin's table, and the gather takes the table as a runtime argument. - **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). -- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field). The table is a tracer with no handle, because no concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. +- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field). The table is a tracer with no twin, because no concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. ## Consequences -- Domains under `jit` match eager execution when the table is concrete or has a handle. +- Domains under `jit` match eager execution when the table is concrete or has a twin. - A table computed from traced values behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. - The clamp is only partly redundant with jax's own indexing, which clamps indices past the end but wraps negative ones as NumPy does. It compiles to an extra clamp next to the select jax emits for negative indices. A gather with `mode="clip", wrap_negative_indices=False` clamps both ends with no extra operations; whether that makes jax code faster is still to be investigated. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. @@ -40,9 +40,9 @@ How a `premap` behaves under `jit` depends on how its connectivity reaches the c Open questions, all caused by the handle: -- The handle is a strong reference, so the jit cache keeps every table it has seen alive until `jax.clear_caches()`. Memory stays bounded when a run uses a fixed set of tables. -- A pytree transform of a connectivity (`tree_map`, `vmap`) inside a trace changes the child but not the handle, so domain inference silently uses the old values. This is unsupported, and nothing detects it. -- `shard_map` rejects the handle when the table is sharded, so distributed execution is not supported yet. +- The handle is a strong reference to the twin, so the jit cache keeps every table it has seen, and its cached domain lookups, alive until `jax.clear_caches()`. Memory stays bounded when a run uses a fixed set of tables. +- A pytree transform of a connectivity (`tree_map`, `vmap`) inside a trace changes the child but not the twin, so domain inference silently uses the old values. This is unsupported, and nothing detects it. +- `shard_map` rejects the twin when the table is sharded, so distributed execution is not supported yet. ## Alternatives considered diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 93baea1ef0..3edff22e31 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -9,6 +9,7 @@ from __future__ import annotations import collections +import contextlib import dataclasses import functools import itertools @@ -466,6 +467,10 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] + #: concrete connectivity with the same table, for domain inference while `_ndarray` is traced + _twin: Optional[NdArrayConnectivityField] = dataclasses.field( + default=None, compare=False, repr=False + ) @classmethod def from_array( # type: ignore[override] @@ -516,13 +521,48 @@ def skip_value(self) -> Optional[core_defs.IntegralScalar]: def _cache(self) -> dict: return {} + @property + def _is_traced(self) -> bool: + """Whether `_ndarray` is a placeholder of a trace rather than an array with values.""" + return False + + def _concrete_eval(self) -> contextlib.AbstractContextManager: + """Context in which operations on concrete arrays are evaluated, also inside a trace.""" + return contextlib.nullcontext() + + @property + def _concrete(self) -> Optional[NdArrayConnectivityField]: + """ + The connectivity whose table domain inference reads (the three cases of ADR 0029). + + - `self`: the table is concrete, eagerly or closed over inside a trace. + - The twin: the table is traced and the twin came with it through the pytree. + - `None`: the table is traced and has no concrete values, e.g. `as_offset` of traced + offsets. Domain inference then assumes every target lies inside the field and the + gather clamps. + """ + if not self._is_traced: + return self + return self._twin + + @property + def _gather_clamps(self) -> bool: + return self._concrete is None + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: + concrete = self._concrete + if concrete is None: + return self.domain + if concrete is not self: + return concrete._inverse_image(image_range) + cache_key = hash((id(self.ndarray), self.domain, image_range)) if (new_domain := self._cache.get(cache_key, None)) is None: assert common.UnitRange.is_finite(image_range) - slices = _hyperslice(self._index_table, image_range, self.array_ns, self.skip_value) + with self._concrete_eval(): + slices = _hyperslice(self._ndarray, image_range, self.array_ns, self.skip_value) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -531,18 +571,6 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: return new_domain - @property - def _index_table(self) -> core_defs.NDArrayObject: - # domain inference needs concrete contents, which a traced `_ndarray` does not have; - # the jax subclass answers with the concrete table behind the tracer - return self._ndarray - - def _gather_index( - self, index: core_defs.NDArrayObject, image_range: common.UnitRange - ) -> core_defs.NDArrayObject: - """The 0-based buffer indices the gather reads for `index` from a field on `image_range`.""" - return index - def __setitem__( self, index: common.AnyIndexSpec, @@ -555,18 +583,23 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: if (restricted_connectivity := self._cache.get(cache_key, None)) is None: new_domain, buffer_slice = self._slice(index) - restricted_connectivity = self._restrict_buffer(new_domain, buffer_slice) + concrete = self._concrete + twin = None + if concrete is self: + # stays concrete inside a trace, so domain inference can still read it + with self._concrete_eval(): + new_buffer = self.array_ns.asarray(self._ndarray[buffer_slice]) + else: + new_buffer = self.array_ns.asarray(self._ndarray[buffer_slice]) + if concrete is not None: + twin = concrete.restrict(index) + restricted_connectivity = self.__class__( + new_domain, new_buffer, self.codomain, self.skip_value, twin + ) self._cache[cache_key] = restricted_connectivity return restricted_connectivity - def _restrict_buffer( - self, new_domain: common.Domain, buffer_slice: common.RelativeIndexSequence - ) -> NdArrayConnectivityField: - cls = self.__class__ - new_buffer = cls.array_ns.asarray(self.ndarray[buffer_slice]) - return cls(new_domain, new_buffer, self.codomain, self.skip_value) - __getitem__ = restrict @@ -637,7 +670,10 @@ def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: index = ( _connectivity_index_array(conn, new_domain, xp, skip_value_replacement=start) - start ) - return conn._gather_index(index, data.domain[dim].unit_range) + if conn._gather_clamps: + # the output domain assumed all targets inside the field; out-of-range ones read its boundary + index = xp.clip(index, 0, len(data.domain[dim].unit_range) - 1) + return index new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) @@ -1062,74 +1098,37 @@ def __setitem__( object.__setattr__(self, "_ndarray", self._ndarray.at[target_slice].set(value)) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - class _TableHandle: - """Trace-time reference to a connectivity table, compared by buffer identity.""" + class _TwinHandle: + """Pytree aux data carrying a concrete connectivity, compared by the identity of its table.""" - __slots__ = ("table",) + __slots__ = ("connectivity",) - def __init__(self, table: core_defs.NDArrayObject) -> None: - self.table = table + def __init__(self, connectivity: NdArrayConnectivityField) -> None: + self.connectivity = connectivity def __eq__(self, other: object) -> bool: - return isinstance(other, _TableHandle) and self.table is other.table + return ( + isinstance(other, _TwinHandle) + and self.connectivity._ndarray is other.connectivity._ndarray + ) def __hash__(self) -> int: - return id(self.table) + return id(self.connectivity._ndarray) _JaxConnectivityAuxData: TypeAlias = tuple[ - common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_TableHandle] + common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_TwinHandle] ] @dataclasses.dataclass(frozen=True, eq=False) class JaxArrayConnectivityField(NdArrayConnectivityField): array_ns: ClassVar[ModuleType] = jnp - _table_handle: Optional[_TableHandle] = None @property - def _index_table(self) -> core_defs.NDArrayObject: - if self._table_handle is not None and isinstance(self._ndarray, jax.core.Tracer): - return self._table_handle.table - return self._ndarray + def _is_traced(self) -> bool: + return isinstance(self._ndarray, jax.core.Tracer) - @property - def _image_unknown(self) -> bool: - return self._table_handle is None and isinstance(self._ndarray, jax.core.Tracer) - - def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: - if self._image_unknown: - # values computed inside a trace: assume every target lies in `image_range` - return self.domain - with jax.ensure_compile_time_eval(): - return super()._inverse_image(image_range) - - def _gather_index( - self, index: core_defs.NDArrayObject, image_range: common.UnitRange - ) -> core_defs.NDArrayObject: - if self._image_unknown: - # the output domain assumed all targets inside the field; out-of-range ones read its boundary - return jnp.clip(index, 0, len(image_range) - 1) # type: ignore[arg-type, return-value, unused-ignore] # `NDArrayObject` typing is not complete - return index - - def _restrict_buffer( - self, new_domain: common.Domain, buffer_slice: common.RelativeIndexSequence - ) -> JaxArrayConnectivityField: - handle = None - if isinstance(self._ndarray, jax.core.Tracer): - if self._table_handle is not None: - with jax.ensure_compile_time_eval(): - handle = _TableHandle(self._table_handle.table[buffer_slice]) - new_buffer = jnp.asarray(self._ndarray[buffer_slice]) - else: - # a concrete table must stay concrete under a trace: domain inference reads it - with jax.ensure_compile_time_eval(): - new_buffer = jnp.asarray(self._ndarray[buffer_slice]) - return JaxArrayConnectivityField( - new_domain, - new_buffer, # type: ignore[arg-type, unused-ignore] # `NDArrayObject` typing is not complete - self.codomain, - self.skip_value, - handle, - ) + def _concrete_eval(self) -> contextlib.AbstractContextManager: + return jax.ensure_compile_time_eval() def _jax_as_offset( offset: fbuiltins.FieldOffset, offset_field: NdArrayField @@ -1166,13 +1165,9 @@ def _unflatten_jax_field( def _flatten_jax_connectivity( connectivity: JaxArrayConnectivityField, ) -> tuple[tuple[core_defs.NDArrayObject], _JaxConnectivityAuxData]: - table = connectivity._ndarray - handle = ( - connectivity._table_handle - if isinstance(table, jax.core.Tracer) - else _TableHandle(table) - ) - return (table,), ( + concrete = connectivity._concrete + handle = None if concrete is None else _TwinHandle(concrete) + return (connectivity._ndarray,), ( connectivity.domain, connectivity.codomain, connectivity.skip_value, @@ -1183,7 +1178,8 @@ def _unflatten_jax_connectivity( aux_data: _JaxConnectivityAuxData, children: tuple[core_defs.NDArrayObject] ) -> JaxArrayConnectivityField: domain, codomain, skip_value, handle = aux_data - return JaxArrayConnectivityField(domain, children[0], codomain, skip_value, handle) + twin = None if handle is None else handle.connectivity + return JaxArrayConnectivityField(domain, children[0], codomain, skip_value, twin) jax.tree_util.register_pytree_node( JaxArrayConnectivityField, # type: ignore[type-abstract, unused-ignore] # see '_unflatten_jax_field' From 1f864238205757f8f70933f2f0369671fab95de8 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 10 Nov 2026 20:14:35 +0100 Subject: [PATCH 046/166] refactor[next]: keep jax tracing of connectivities in the jax module The shared connectivity is unaware of tracing again. jax_ops.py builds one connectivity class per case of ADR 0029 (concrete, traced with a concrete twin, traced without values), picked from the table on construction and in a single pytree unflatten. as_offset gets its compile-time evaluation through JaxOps.builtin_overrides. Shared code keeps only a neutral _gather_index hook. --- .../next/embedded/array_libraries/jax_ops.py | 144 +++++++++++++++--- src/gt4py/next/embedded/array_ops.py | 9 -- src/gt4py/next/embedded/nd_array_field.py | 80 +++------- 3 files changed, 147 insertions(+), 86 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 7103885f50..f7723ef720 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -10,9 +10,9 @@ from __future__ import annotations -import contextlib +import dataclasses from collections.abc import Callable -from typing import Any, Optional, TypeAlias +from typing import Any, Optional, TypeAlias, cast import array_api_compat import jax @@ -21,6 +21,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import common from gt4py.next.embedded import array_ops, nd_array_field +from gt4py.next.ffront import experimental, fbuiltins class JaxOps(array_ops.ArrayOps): @@ -39,12 +40,6 @@ def setitem( ) -> core_defs.NDArrayObject: return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - def is_traced(self, array: core_defs.NDArrayObject) -> bool: - return isinstance(array, jax.core.Tracer) - - def concrete_eval(self) -> contextlib.AbstractContextManager: - return jax.ensure_compile_time_eval() - def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.asarray(array) @@ -80,6 +75,102 @@ def _unflatten_field( ) +def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: + # adding the coordinates would stage the table under a trace even for concrete offsets + with jax.ensure_compile_time_eval(): + return nd_array_field._as_offset(offset, offset_field) + + +JaxOps.builtin_overrides = {experimental.as_offset: _as_offset} + + +# Under `jax.jit` a connectivity is in one of three cases (ADR 0029), each its own class: +# its table is concrete, traced with a concrete twin, or traced without values. + + +@dataclasses.dataclass(frozen=True, eq=False) +class _ConcreteConnectivity(nd_array_field.NdArrayConnectivityField): + """A concrete jax table, which stays concrete when used inside a trace.""" + + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: + with jax.ensure_compile_time_eval(): + return super()._inverse_image(image_range) + + def restrict(self, index: common.AnyIndexSpec) -> _ConcreteConnectivity: + with jax.ensure_compile_time_eval(): + return cast(_ConcreteConnectivity, super().restrict(index)) + + __getitem__ = restrict + + +@dataclasses.dataclass(frozen=True, eq=False) +class _TwinnedConnectivity(nd_array_field.NdArrayConnectivityField): + """A traced table whose values are known from a concrete connectivity with the same table.""" + + _twin: nd_array_field.NdArrayConnectivityField + + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: + return self._twin._inverse_image(image_range) + + def restrict(self, index: common.AnyIndexSpec) -> _TwinnedConnectivity: + cache_key = (id(self.ndarray), self.domain, index) + restricted: Optional[_TwinnedConnectivity] + if (restricted := self._cache.get(cache_key, None)) is None: + new_domain, buffer_slice = self._slice(index) + restricted = self._cache[cache_key] = _TwinnedConnectivity( + new_domain, + self._ndarray[buffer_slice], + self.codomain, + self.skip_value, + self._twin.restrict(index), + ) + return restricted + + __getitem__ = restrict + + +@dataclasses.dataclass(frozen=True, eq=False) +class _ValueFreeConnectivity(nd_array_field.NdArrayConnectivityField): + """A traced table without concrete values, e.g. from `as_offset` of traced offsets.""" + + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: + # every target is assumed to lie inside the field; `_gather_index` clamps the others + return self.domain + + def _gather_index( + self, index: core_defs.NDArrayObject, image_range: common.UnitRange + ) -> core_defs.NDArrayObject: + return jax.numpy.clip(index, 0, len(image_range) - 1) # type: ignore[arg-type, return-value, unused-ignore] # `NDArrayObject` typing is not complete + + +def _connectivity_class( + table: core_defs.NDArrayObject, twin: Optional[nd_array_field.NdArrayConnectivityField] +) -> type[nd_array_field.NdArrayConnectivityField]: + if not isinstance(table, jax.core.Tracer): + return _ConcreteConnectivity + return _ValueFreeConnectivity if twin is None else _TwinnedConnectivity + + +def _connectivity_from_array( + data: Any, + /, + codomain: common.Dimension, + *, + domain: Optional[common.DomainLike] = None, + dtype: Optional[core_defs.DType] = None, + skip_value: Optional[core_defs.IntegralScalar] = None, +) -> nd_array_field.NdArrayConnectivityField: + assert domain is not None + return _connectivity_class(data, None).from_array( + data, codomain, domain=domain, dtype=dtype, skip_value=skip_value + ) + + +common._connectivity.register(jax.Array, _connectivity_from_array) +# jax >= 0.11: 'Tracer' is no longer a subclass of 'jax.Array' for 'singledispatch' +common._connectivity.register(jax.core.Tracer, _connectivity_from_array) + + class _TwinHandle: """Pytree aux data carrying a concrete connectivity, compared by the identity of its table.""" @@ -106,8 +197,12 @@ def __hash__(self) -> int: def _flatten_connectivity( connectivity: nd_array_field.NdArrayConnectivityField, ) -> tuple[tuple[core_defs.NDArrayObject], _ConnectivityAuxData]: - concrete = connectivity._concrete - handle = None if concrete is None else _TwinHandle(concrete) + if isinstance(connectivity, _TwinnedConnectivity): + handle: Optional[_TwinHandle] = _TwinHandle(connectivity._twin) + elif isinstance(connectivity, _ValueFreeConnectivity): + handle = None + else: + handle = _TwinHandle(connectivity) return (connectivity._ndarray,), ( connectivity.domain, connectivity.codomain, @@ -119,14 +214,25 @@ def _flatten_connectivity( def _unflatten_connectivity( aux_data: _ConnectivityAuxData, children: tuple[core_defs.NDArrayObject] ) -> nd_array_field.NdArrayConnectivityField: + # one unflatten for all classes: `lax.scan` and `lax.cond` rebuild results through the + # unflatten of the input's class, so the class must follow from the children domain, codomain, skip_value, handle = aux_data + (table,) = children twin = None if handle is None else handle.connectivity - return nd_array_field.NdArrayConnectivityField(domain, children[0], codomain, skip_value, twin) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' - - -# jax registers pytree nodes by exact type, so the connectivity needs its own registration -jax.tree_util.register_pytree_node( - nd_array_field.NdArrayConnectivityField, # type: ignore[type-abstract, unused-ignore] # see 'NdArrayField' above - _flatten_connectivity, - _unflatten_connectivity, -) + if twin is not None and isinstance(table, jax.core.Tracer): + return _TwinnedConnectivity(domain, table, codomain, skip_value, twin) + return _connectivity_class(table, twin)(domain, table, codomain, skip_value) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' + + +# jax registers pytree nodes by exact type +for _cls in ( + nd_array_field.NdArrayConnectivityField, + _ConcreteConnectivity, + _TwinnedConnectivity, + _ValueFreeConnectivity, +): + jax.tree_util.register_pytree_node( + _cls, # type: ignore[type-abstract, unused-ignore] # see 'NdArrayField' above + _flatten_connectivity, + _unflatten_connectivity, + ) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index a0b4682c9d..ac4b932af0 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -21,7 +21,6 @@ from __future__ import annotations -import contextlib from collections.abc import Callable, Mapping from types import ModuleType from typing import Any, ClassVar, Final @@ -156,14 +155,6 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array - def is_traced(self, array: core_defs.NDArrayObject) -> bool: - """Whether `array` is a placeholder of a trace rather than an array with values.""" - return False - - def concrete_eval(self) -> contextlib.AbstractContextManager: - """Context in which operations on concrete arrays are evaluated, also inside a trace.""" - return contextlib.nullcontext() - def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: if _NUMPY_FROM_DLPACK_TAKES_DEVICE: return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index e7cb5586cb..d91a2aef56 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -455,10 +455,6 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: concrete connectivity with the same table, for domain inference while `_ndarray` is traced - _twin: Optional[NdArrayConnectivityField] = dataclasses.field( - default=None, compare=False, repr=False - ) @classmethod def from_array( # type: ignore[override] @@ -503,25 +499,6 @@ def skip_value(self) -> Optional[core_defs.IntegralScalar]: def _cache(self) -> dict: return {} - @property - def _concrete(self) -> Optional[NdArrayConnectivityField]: - """ - The connectivity whose table domain inference reads (the three cases of ADR 0029). - - - `self`: the table is concrete, eagerly or closed over inside a trace. - - The twin: the table is traced and the twin came with it through the pytree. - - `None`: the table is traced and has no concrete values, e.g. `as_offset` of traced - offsets. Domain inference then assumes every target lies inside the field and the - gather clamps. - """ - if not self._ops.is_traced(self._ndarray): - return self - return self._twin - - @property - def _gather_clamps(self) -> bool: - return self._concrete is None - def __setitem__( self, index: common.AnyIndexSpec, @@ -530,19 +507,12 @@ def __setitem__( raise TypeError("'Connectivity' does not support item assignment.") def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: - concrete = self._concrete - if concrete is None: - return self.domain - if concrete is not self: - return concrete._inverse_image(image_range) - cache_key = hash((id(self.ndarray), self.domain, image_range)) if (new_domain := self._cache.get(cache_key, None)) is None: assert common.UnitRange.is_finite(image_range) - with self._ops.concrete_eval(): - slices = _hyperslice(self._ndarray, image_range, self._ops.xp, self.skip_value) + slices = _hyperslice(self._ndarray, image_range, self._ops.xp, self.skip_value) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -556,18 +526,11 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: if (restricted_connectivity := self._cache.get(cache_key, None)) is None: new_domain, buffer_slice = self._slice(index) - concrete = self._concrete - twin = None - if concrete is self: - # stays concrete inside a trace, so domain inference can still read it - with self._ops.concrete_eval(): - new_buffer = self._ops.asarray(self._ndarray[buffer_slice]) - else: - new_buffer = self._ops.asarray(self._ndarray[buffer_slice]) - if concrete is not None: - twin = concrete.restrict(index) restricted_connectivity = self.__class__( - new_domain, new_buffer, self.codomain, self.skip_value, twin + new_domain, + self._ops.asarray(self.ndarray[buffer_slice]), + self.codomain, + self.skip_value, ) self._cache[cache_key] = restricted_connectivity @@ -575,6 +538,12 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: __getitem__ = restrict + def _gather_index( + self, index: core_defs.NDArrayObject, image_range: common.UnitRange + ) -> core_defs.NDArrayObject: + """The 0-based buffer indices the gather reads for `index` from a field on `image_range`.""" + return index + def _domain_premap(data: NdArrayField, *connectivities: common.Connectivity) -> NdArrayField: """`premap` implementation transforming only the field domain not the data (i.e. translation and relocation).""" @@ -643,10 +612,7 @@ def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: index = ( _connectivity_index_array(conn, new_domain, ops, skip_value_replacement=start) - start ) - if conn._gather_clamps: - # the output domain assumed all targets inside the field; out-of-range ones read its boundary - index = ops.xp.clip(index, 0, len(data.domain[dim].unit_range) - 1) - return index + return conn._gather_index(index, data.domain[dim].unit_range) new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) @@ -957,18 +923,16 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> com f"got source '{offset.source.value}' and target ({target_dims})." ) source_dim = offset.source - # without this, adding the coordinates stages the table under a trace even for concrete offsets - with offset_field._ops.concrete_eval(): - coords = _identity_index_array( - offset_field.domain, - source_dim, - offset_field._ops, - like=offset_field.ndarray, - dtype=fbuiltins.IndexType, - ) - return common._connectivity( - offset_field.ndarray + coords, codomain=source_dim, domain=offset_field.domain - ) + coords = _identity_index_array( + offset_field.domain, + source_dim, + offset_field._ops, + like=offset_field.ndarray, + dtype=fbuiltins.IndexType, + ) + return common._connectivity( + offset_field.ndarray + coords, codomain=source_dim, domain=offset_field.domain + ) _register_builtin(experimental.as_offset, _as_offset) From f67c042e4f694a1292469e57d9625693c56f8592 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 10 Nov 2026 20:45:47 +0100 Subject: [PATCH 047/166] refactor[next]: keep the static values of a traced connectivity table with its tracer The value-dependent operations of a connectivity table are ArrayOps methods (hyperslice, restrict_table, gather_index), overridden by JaxOps. The concrete values of a traced table are paired with the tracer they belong to and round-trip unchanged through the pytree aux data, so lax.cond, lax.switch and the carries of lax.scan and lax.while_loop reject a change of table instead of using the values of another one. --- .../next/embedded/array_libraries/jax_ops.py | 273 ++++++++---------- src/gt4py/next/embedded/array_ops.py | 70 ++++- src/gt4py/next/embedded/nd_array_field.py | 72 ++--- .../embedded_tests/test_nd_array_field.py | 118 +++++++- 4 files changed, 329 insertions(+), 204 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index f7723ef720..d90d8621ab 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -6,13 +6,24 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -"""`ArrayOps` for JAX arrays, and `NdArrayField` as a JAX pytree.""" +""" +`ArrayOps` for JAX arrays, and the embedded fields as JAX pytrees. + +Everything gt4py knows about JAX tracing is in this module (ADR 0029). A +connectivity table inside a trace is in one of three cases, told apart by +`_values`: + +- concrete: operations reading its values run under `jax.ensure_compile_time_eval`; +- a tracer standing for a concrete table, which it got as a pytree leaf: the + values are read from that table, kept in a `_StaticTable`; +- a tracer computed inside the trace: there are no values, all its targets are + assumed to be in range and the gather clamps them. +""" from __future__ import annotations -import dataclasses -from collections.abc import Callable -from typing import Any, Optional, TypeAlias, cast +from collections.abc import Callable, Mapping +from typing import Any, ClassVar, Optional, TypeAlias import array_api_compat import jax @@ -24,7 +35,53 @@ from gt4py.next.ffront import experimental, fbuiltins +class _StaticTable: + """ + The concrete array `values` holding the values of `table`, a placeholder of a trace. + + It is also the pytree aux data of a connectivity, without `table`: two are equal + if their values are the same array. + """ + + __slots__ = ("table", "values") + + def __init__(self, values: core_defs.NDArrayObject, table: Any = None) -> None: + self.values = values + self.table = table + + def __eq__(self, other: object) -> bool: + return isinstance(other, _StaticTable) and self.values is other.values + + def __hash__(self) -> int: + return id(self.values) + + def __repr__(self) -> str: + return f"" + + +def _has_values(table: Any) -> bool: + return isinstance(table, np.ndarray | jax.Array) and not isinstance(table, jax.core.Tracer) + + +def _values(table: Any, static: Optional[_StaticTable]) -> Optional[core_defs.NDArrayObject]: + """Return the concrete array with the values of `table`, `None` if they exist only at run time.""" + if _has_values(table): + return table + # a connectivity copied with another table still carries the `static` of the old one + return static.values if static is not None and static.table is table else None + + +def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: + # adding the coordinates would stage the table under a trace even for concrete offsets + with jax.ensure_compile_time_eval(): + return nd_array_field._as_offset(offset, offset_field) + + class JaxOps(array_ops.ArrayOps): + builtin_overrides: ClassVar[Mapping[Any, Callable[..., Any]]] = { + experimental.as_offset: _as_offset + } + def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: return value @@ -40,6 +97,51 @@ def setitem( ) -> core_defs.NDArrayObject: return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete + def hyperslice( + self, + table: core_defs.NDArrayObject, + image_range: common.UnitRange, + skip_value: Optional[core_defs.IntegralScalar] = None, + *, + static: Optional[_StaticTable] = None, + ) -> Optional[tuple[slice, ...]]: + values = _values(table, static) + if values is None: + return (slice(None),) * table.ndim + if values is not table: + return array_ops.of(values).hyperslice(values, image_range, skip_value) + with jax.ensure_compile_time_eval(): + return super().hyperslice(table, image_range, skip_value) + + def restrict_table( + self, + table: core_defs.NDArrayObject, + key: common.RelativeIndexSequence, + *, + static: Optional[_StaticTable] = None, + ) -> tuple[core_defs.NDArrayObject, Optional[_StaticTable]]: + values = _values(table, static) + if values is table: + with jax.ensure_compile_time_eval(): + return super().restrict_table(table, key) + restricted, _ = super().restrict_table(table, key) + if values is None: + return restricted, None + restricted_values, _ = array_ops.of(values).restrict_table(values, key) + return restricted, _StaticTable(restricted_values, restricted) + + def gather_index( + self, + index: core_defs.NDArrayObject, + size: int, + table: core_defs.NDArrayObject, + *, + static: Optional[_StaticTable] = None, + ) -> core_defs.NDArrayObject: + if _values(table, static) is None: + return jax.numpy.clip(index, 0, size - 1) # type: ignore[arg-type, return-value, unused-ignore] # `NDArrayObject` typing is not complete + return index + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.asarray(array) @@ -75,164 +177,39 @@ def _unflatten_field( ) -def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: - # adding the coordinates would stage the table under a trace even for concrete offsets - with jax.ensure_compile_time_eval(): - return nd_array_field._as_offset(offset, offset_field) - - -JaxOps.builtin_overrides = {experimental.as_offset: _as_offset} - - -# Under `jax.jit` a connectivity is in one of three cases (ADR 0029), each its own class: -# its table is concrete, traced with a concrete twin, or traced without values. - - -@dataclasses.dataclass(frozen=True, eq=False) -class _ConcreteConnectivity(nd_array_field.NdArrayConnectivityField): - """A concrete jax table, which stays concrete when used inside a trace.""" - - def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: - with jax.ensure_compile_time_eval(): - return super()._inverse_image(image_range) - - def restrict(self, index: common.AnyIndexSpec) -> _ConcreteConnectivity: - with jax.ensure_compile_time_eval(): - return cast(_ConcreteConnectivity, super().restrict(index)) - - __getitem__ = restrict - - -@dataclasses.dataclass(frozen=True, eq=False) -class _TwinnedConnectivity(nd_array_field.NdArrayConnectivityField): - """A traced table whose values are known from a concrete connectivity with the same table.""" - - _twin: nd_array_field.NdArrayConnectivityField - - def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: - return self._twin._inverse_image(image_range) - - def restrict(self, index: common.AnyIndexSpec) -> _TwinnedConnectivity: - cache_key = (id(self.ndarray), self.domain, index) - restricted: Optional[_TwinnedConnectivity] - if (restricted := self._cache.get(cache_key, None)) is None: - new_domain, buffer_slice = self._slice(index) - restricted = self._cache[cache_key] = _TwinnedConnectivity( - new_domain, - self._ndarray[buffer_slice], - self.codomain, - self.skip_value, - self._twin.restrict(index), - ) - return restricted - - __getitem__ = restrict - - -@dataclasses.dataclass(frozen=True, eq=False) -class _ValueFreeConnectivity(nd_array_field.NdArrayConnectivityField): - """A traced table without concrete values, e.g. from `as_offset` of traced offsets.""" - - def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: - # every target is assumed to lie inside the field; `_gather_index` clamps the others - return self.domain - - def _gather_index( - self, index: core_defs.NDArrayObject, image_range: common.UnitRange - ) -> core_defs.NDArrayObject: - return jax.numpy.clip(index, 0, len(image_range) - 1) # type: ignore[arg-type, return-value, unused-ignore] # `NDArrayObject` typing is not complete - - -def _connectivity_class( - table: core_defs.NDArrayObject, twin: Optional[nd_array_field.NdArrayConnectivityField] -) -> type[nd_array_field.NdArrayConnectivityField]: - if not isinstance(table, jax.core.Tracer): - return _ConcreteConnectivity - return _ValueFreeConnectivity if twin is None else _TwinnedConnectivity - - -def _connectivity_from_array( - data: Any, - /, - codomain: common.Dimension, - *, - domain: Optional[common.DomainLike] = None, - dtype: Optional[core_defs.DType] = None, - skip_value: Optional[core_defs.IntegralScalar] = None, -) -> nd_array_field.NdArrayConnectivityField: - assert domain is not None - return _connectivity_class(data, None).from_array( - data, codomain, domain=domain, dtype=dtype, skip_value=skip_value - ) - - -common._connectivity.register(jax.Array, _connectivity_from_array) -# jax >= 0.11: 'Tracer' is no longer a subclass of 'jax.Array' for 'singledispatch' -common._connectivity.register(jax.core.Tracer, _connectivity_from_array) - - -class _TwinHandle: - """Pytree aux data carrying a concrete connectivity, compared by the identity of its table.""" - - __slots__ = ("connectivity",) - - def __init__(self, connectivity: nd_array_field.NdArrayConnectivityField) -> None: - self.connectivity = connectivity - - def __eq__(self, other: object) -> bool: - return ( - isinstance(other, _TwinHandle) - and self.connectivity._ndarray is other.connectivity._ndarray - ) - - def __hash__(self) -> int: - return id(self.connectivity._ndarray) - - _ConnectivityAuxData: TypeAlias = tuple[ - common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_TwinHandle] + common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_StaticTable] ] def _flatten_connectivity( connectivity: nd_array_field.NdArrayConnectivityField, ) -> tuple[tuple[core_defs.NDArrayObject], _ConnectivityAuxData]: - if isinstance(connectivity, _TwinnedConnectivity): - handle: Optional[_TwinHandle] = _TwinHandle(connectivity._twin) - elif isinstance(connectivity, _ValueFreeConnectivity): - handle = None - else: - handle = _TwinHandle(connectivity) - return (connectivity._ndarray,), ( + table = connectivity._ndarray + values = _values(table, connectivity._static) + return (table,), ( connectivity.domain, connectivity.codomain, connectivity.skip_value, - handle, + None if values is None else _StaticTable(values), ) def _unflatten_connectivity( aux_data: _ConnectivityAuxData, children: tuple[core_defs.NDArrayObject] ) -> nd_array_field.NdArrayConnectivityField: - # one unflatten for all classes: `lax.scan` and `lax.cond` rebuild results through the - # unflatten of the input's class, so the class must follow from the children - domain, codomain, skip_value, handle = aux_data + domain, codomain, skip_value, static = aux_data (table,) = children - twin = None if handle is None else handle.connectivity - if twin is not None and isinstance(table, jax.core.Tracer): - return _TwinnedConnectivity(domain, table, codomain, skip_value, twin) - return _connectivity_class(table, twin)(domain, table, codomain, skip_value) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' - - -# jax registers pytree nodes by exact type -for _cls in ( - nd_array_field.NdArrayConnectivityField, - _ConcreteConnectivity, - _TwinnedConnectivity, - _ValueFreeConnectivity, -): - jax.tree_util.register_pytree_node( - _cls, # type: ignore[type-abstract, unused-ignore] # see 'NdArrayField' above - _flatten_connectivity, - _unflatten_connectivity, - ) + if static is not None: + # jax compares the aux data of the branches of `lax.cond` and of the carry of `lax.scan` + # on trees it rebuilds around placeholders that are not tracers, so they keep it as well + static = None if _has_values(table) else _StaticTable(static.values, table) + return nd_array_field.NdArrayConnectivityField(domain, table, codomain, skip_value, static) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' + + +# jax registers pytree nodes by exact type, so the connectivity needs its own registration +jax.tree_util.register_pytree_node( + nd_array_field.NdArrayConnectivityField, # type: ignore[type-abstract, unused-ignore] # see 'NdArrayField' above + _flatten_connectivity, + _unflatten_connectivity, +) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index ac4b932af0..ce18cfa29e 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -23,7 +23,7 @@ from collections.abc import Callable, Mapping from types import ModuleType -from typing import Any, ClassVar, Final +from typing import Any, ClassVar, Final, Optional import array_api_compat import array_api_compat.numpy as compat_numpy @@ -155,6 +155,74 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array + # The operations on a connectivity table which depend on its values. `static` belongs to + # the library and is stored by the connectivity next to its table: `None`, unless the + # library's arrays can be placeholders without values and it keeps a stand-in for them. + + def hyperslice( + self, + table: core_defs.NDArrayObject, + image_range: common.UnitRange, + skip_value: Optional[core_defs.IntegralScalar] = None, + *, + static: Any = None, + ) -> Optional[tuple[slice, ...]]: + """ + Return the hypercube slice that contains all indices in `table` that are within `image_range`, or `None` if no such hypercube exists. + + If `skip_value` is given, the selected values are ignored. It returns the smallest hypercube. + A bigger hypercube could be constructed by adding lines that contain only `skip_value`s. + + Example: + table = 0 1 -1 + 3 4 -1 + -1 -1 -1 + skip_value = -1 + + would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. + """ + xp = self.xp + select_mask = (table >= image_range.start) & (table < image_range.stop) + + if not xp.any(select_mask): + return None + + nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) + + slices = tuple( + slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) + for dim_nnz_indices in nnz + ) + hcube = select_mask[tuple(slices)] + if skip_value is not None: + ignore_mask = table == skip_value + hcube = hcube | ignore_mask[tuple(slices)] + if not xp.all(hcube): + return None + + return slices + + def restrict_table( + self, + table: core_defs.NDArrayObject, + key: common.RelativeIndexSequence, + *, + static: Any = None, + ) -> tuple[core_defs.NDArrayObject, Any]: + """Return `table[key]` and its `static`.""" + return self.asarray(table[key]), None + + def gather_index( + self, + index: core_defs.NDArrayObject, + size: int, + table: core_defs.NDArrayObject, + *, + static: Any = None, + ) -> core_defs.NDArrayObject: + """Return the indices a gather reads from an axis of `size` elements for `index`, which was computed from `table`.""" + return index + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: if _NUMPY_FROM_DLPACK_TAKES_DEVICE: return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index d91a2aef56..c39bdb58be 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -21,7 +21,7 @@ from numpy import typing as npt from gt4py._core import definitions as core_defs -from gt4py.next import common +from gt4py.next import common, utils from gt4py.next.embedded import ( array_ops, common as embedded_common, @@ -455,6 +455,13 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] + #: stored for the `ArrayOps` of the table, which passes it to its table operations + _static: Any = dataclasses.field( + default=None, + compare=False, + repr=False, + metadata=utils.gt4py_metadata(fingerprint=False), + ) @classmethod def from_array( # type: ignore[override] @@ -512,7 +519,9 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._cache.get(cache_key, None)) is None: assert common.UnitRange.is_finite(image_range) - slices = _hyperslice(self._ndarray, image_range, self._ops.xp, self.skip_value) + slices = self._ops.hyperslice( + self._ndarray, image_range, self.skip_value, static=self._static + ) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -526,11 +535,11 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: if (restricted_connectivity := self._cache.get(cache_key, None)) is None: new_domain, buffer_slice = self._slice(index) + table, static = self._ops.restrict_table( + self._ndarray, buffer_slice, static=self._static + ) restricted_connectivity = self.__class__( - new_domain, - self._ops.asarray(self.ndarray[buffer_slice]), - self.codomain, - self.skip_value, + new_domain, table, self.codomain, self.skip_value, static ) self._cache[cache_key] = restricted_connectivity @@ -538,12 +547,6 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: __getitem__ = restrict - def _gather_index( - self, index: core_defs.NDArrayObject, image_range: common.UnitRange - ) -> core_defs.NDArrayObject: - """The 0-based buffer indices the gather reads for `index` from a field on `image_range`.""" - return index - def _domain_premap(data: NdArrayField, *connectivities: common.Connectivity) -> NdArrayField: """`premap` implementation transforming only the field domain not the data (i.e. translation and relocation).""" @@ -612,7 +615,9 @@ def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: index = ( _connectivity_index_array(conn, new_domain, ops, skip_value_replacement=start) - start ) - return conn._gather_index(index, data.domain[dim].unit_range) + return conn._ops.gather_index( + index, len(data.domain[dim].unit_range), conn._ndarray, static=conn._static + ) new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) @@ -685,47 +690,6 @@ def _identity_index_array( return xp.broadcast_to(xp.reshape(indices, shape), domain.shape) -def _hyperslice( - index_array: core_defs.NDArrayObject, - image_range: common.UnitRange, - xp: ModuleType, - skip_value: Optional[core_defs.IntegralScalar] = None, -) -> Optional[tuple[slice, ...]]: - """ - Return the hypercube slice that contains all indices in `index_array` that are within `image_range`, or `None` if no such hypercube exists. - - If `skip_value` is given, the selected values are ignored. It returns the smallest hypercube. - A bigger hypercube could be constructed by adding lines that contain only `skip_value`s. - - Example: - index_array = 0 1 -1 - 3 4 -1 - -1 -1 -1 - skip_value = -1 - - would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. - """ - select_mask = (index_array >= image_range.start) & (index_array < image_range.stop) - - if not xp.any(select_mask): - return None - - nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) - - slices = tuple( - slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) - for dim_nnz_indices in nnz - ) - hcube = select_mask[tuple(slices)] - if skip_value is not None: - ignore_mask = index_array == skip_value - hcube = hcube | ignore_mask[tuple(slices)] - if not xp.all(hcube): - return None - - return slices - - # -- Specialized implementations for builtin operations on array fields -- diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index c810bceddf..508557e42b 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -6,6 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import dataclasses import math import operator import pickle @@ -27,6 +28,7 @@ UnitRange, ) from gt4py.next.embedded import ( + array_ops, context as embedded_context, exceptions as embedded_exceptions, nd_array_field, @@ -1575,7 +1577,7 @@ def test_hyperslice(index_array, expected): expected = tuple(slice(*e) for e in expected) if expected is not None else None - result = nd_array_field._hyperslice(index_array, image_range, np, skip_value) + result = array_ops.of(index_array).hyperslice(index_array, image_range, skip_value) assert result == expected @@ -2232,3 +2234,117 @@ def premap_first_neighbor(field, conn): assert result.domain == expected.domain np.testing.assert_allclose(result.asnumpy(), expected.asnumpy()) + + +def _jax_narrowing_setup(): + """A field on V:(1,4) and two tables on E:(0,5) mapping into it on E:(1,4) and on E:(0,3).""" + import jax + + V = Dimension("V") + E = Dimension("E") + field = common._field(jax.numpy.asarray([10.0, 20.0, 30.0]), domain=common.domain({V: (1, 4)})) + conn_domain = common.domain({E: (0, 5)}) + conn_a = common._connectivity( + jax.numpy.asarray([0, 1, 2, 3, 5], dtype=np.int32), codomain=V, domain=conn_domain + ) + conn_b = common._connectivity( + jax.numpy.asarray([1, 2, 3, 0, 5], dtype=np.int32), codomain=V, domain=conn_domain + ) + return E, field, conn_a, conn_b + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_connectivity_from_array(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + conn = nd_array_field.NdArrayConnectivityField.from_array( + conn_a.ndarray, conn_a.codomain, domain=conn_a.domain + ) + + for result in ( + jax.jit(lambda field, conn: field.premap(conn))(field, conn), + jax.jit(lambda field: field.premap(conn))(field), + ): + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +@pytest.mark.parametrize("predicate", [True, False]) +def test_jax_jit_premap_with_connectivity_selected_by_cond(predicate): + import jax + + E, field, conn_a, conn_b = _jax_narrowing_setup() + + def premap_selected(predicate, field, conn1, conn2): + return field.premap(jax.lax.cond(predicate, lambda: conn1, lambda: conn2)) + + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(premap_selected)(predicate, field, conn_a, conn_b) + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(lambda predicate, field, conn: premap_selected(predicate, field, conn, conn_b))( + predicate, field, conn_a + ) + + # the same table in both branches + same_table = common._connectivity( + conn_a.ndarray, codomain=conn_a.codomain, domain=conn_a.domain + ) + result = jax.jit(premap_selected)(predicate, field, conn_a, same_table) + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_connectivity_selected_by_switch(): + import jax + + _, field, conn_a, conn_b = _jax_narrowing_setup() + + def premap_selected(index, field, conn1, conn2): + return field.premap(jax.lax.switch(index, [lambda: conn1, lambda: conn2])) + + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(premap_selected)(1, field, conn_a, conn_b) + + +@pytest.mark.requires_jax +def test_jax_scan_with_connectivity_carry(): + import jax + + _, field, conn_a, conn_b = _jax_narrowing_setup() + + def premap_sums(conn, next_conn): + def body(carry, x): + return (carry if next_conn is None else next_conn), x * jax.numpy.sum( + field.premap(carry).ndarray + ) + + return jax.lax.scan(body, conn, jax.numpy.asarray([1.0, 2.0]))[1] + + np.testing.assert_array_equal(premap_sums(conn_a, None), [60.0, 120.0]) + np.testing.assert_array_equal( + jax.jit(lambda conn: premap_sums(conn, None))(conn_a), [60.0, 120.0] + ) + + with pytest.raises(TypeError, match="pytree structure"): + premap_sums(conn_a, conn_b) + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(premap_sums)(conn_a, conn_b) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_replaced_table_has_no_values(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + def premap_next(field, conn): + return field.premap(dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) + + result = jax.jit(premap_next)(field, conn_a) + + # as for every table computed in the trace: not narrowed, out-of-range targets clamped + assert result.domain == common.domain({E: (0, 5)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0, 30.0, 30.0]) From 38c3f371714bafef5eea0dd9e819fc662d3b65c2 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 10 Nov 2026 20:45:47 +0100 Subject: [PATCH 048/166] docs[next]: describe connectivity tracing through ArrayOps in ADR 0029 --- .../0029-Connectivities_Under_JAX_Tracing.md | 50 +++++++++++++++---- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 831bfddec9..8b9264452f 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -7,9 +7,9 @@ tags: [embedded, jax, connectivities] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) - **Created**: 2026-11-06 -- **Updated**: 2026-11-06 +- **Updated**: 2026-11-10 -In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to register jax connectivities as pytree nodes that carry a handle to the concrete table, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime. +In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to pass the concrete table along with its tracer through the pytree aux data of the connectivity, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime. ## Context @@ -22,30 +22,58 @@ Narrowing is the common case: the field usually covers only part of the connecti ## Decision -`JaxArrayConnectivityField` is a pytree node. The table is the child, and the aux data holds domain, codomain, skip value and a handle to a concrete connectivity with the same table, its twin. The handle compares by the identity of the twin's table, so a new wrapper around the same buffer does not retrace, while a new buffer does. While the table is traced, domain inference and `restrict` delegate to the twin, which evaluates under `jax.ensure_compile_time_eval()`. One property, `_concrete`, names which of the cases below a connectivity is in, and every operation that differs between them branches on it. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The three operations that depend on the values of a table are methods of `ArrayOps`: `hyperslice` (domain inference), `restrict_table` and `gather_index`. Their defaults are plain array code. `JaxOps` overrides them, and everything that knows about tracing is in `jax_ops.py`. + +A connectivity stores one opaque value for its `ArrayOps`, `_static`, and hands it to these methods. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, together with the tracer they belong to. A connectivity that got another table, for example through `dataclasses.replace`, does not match its `_static` any more and is treated as having none. + +The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with matching `_static`. Unflattening around anything but a concrete array attaches them. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: -- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer, and flattening attached the twin. Domain inference reads the twin's table, and the gather takes the table as a runtime argument. -- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). -- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field). The table is a tracer with no twin, because no concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. +- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. +- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`, because the operations on it run under `jax.ensure_compile_time_eval()`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). +- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field, or any other table that is a tracer without static values). No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. + +A tracer of any jax transformation counts as traced, not only one of `jit`. In particular a table that depends on a `vmap`ped value has no values even when `vmap` is called eagerly, because it differs per batch element. + +### Control flow + +The aux data claims that the child has the static values. Where jax rebuilds a pytree around new tracers, that claim stays true: + +- At the entry of `jit`, of a nested `jit`, and for the operands of `lax.cond`, the new tracer stands for the flattened table. +- `lax.cond` and `lax.switch` require all branches to return the same aux data, and `lax.scan`, `lax.while_loop` and `lax.fori_loop` require the carry to keep its aux data. Selecting between two tables, changing the table of a carried connectivity, or mixing a table that has static values with one computed in the trace raises jax's `TypeError` about differing pytree structure. The same table on all branches, or an unchanged carry, keeps its static values. + +For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to those as well. ## Consequences -- Domains under `jit` match eager execution when the table is concrete or has a twin. +- Domains under `jit` match eager execution when the table is concrete or has static values. - A table computed from traced values behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. - The clamp is only partly redundant with jax's own indexing, which clamps indices past the end but wraps negative ones as NumPy does. It compiles to an extra clamp next to the select jax emits for negative indices. A gather with `mode="clip", wrap_negative_indices=False` clamps both ends with no extra operations; whether that makes jax code faster is still to be investigated. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached per buffer. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. +- Domain inference on static values is cached on the connectivity object, which is new in every trace, so it is repeated per trace but not per call. -Open questions, all caused by the handle: +Open questions, all caused by the static values in the aux data: -- The handle is a strong reference to the twin, so the jit cache keeps every table it has seen, and its cached domain lookups, alive until `jax.clear_caches()`. Memory stays bounded when a run uses a fixed set of tables. -- A pytree transform of a connectivity (`tree_map`, `vmap`) inside a trace changes the child but not the twin, so domain inference silently uses the old values. This is unsupported, and nothing detects it. -- `shard_map` rejects the twin when the table is sharded, so distributed execution is not supported yet. +- The aux data is a strong reference to the table, so the jit cache keeps every table it has seen alive until `jax.clear_caches()`. Memory stays bounded when a run uses a fixed set of tables. +- Rebuilding a connectivity around another traced table through the pytree API inside a trace (`tree_map` with a function that changes the leaf, `tree_unflatten`) keeps the static values of the old table, so domain inference silently uses them. This is unsupported, and nothing detects it: with jax's public API such a rebuild cannot be told apart from the entry of a `jit`. +- `shard_map` rejects the aux data when the table is sharded, so distributed execution is not supported yet. ## Alternatives considered +### A connectivity subclass per case + +One class each for a concrete table, a traced table with static values and a traced table without, chosen when the connectivity is constructed. This keeps `ArrayOps` free of table operations, but brings back per-library field classes and a second registry next to `ArrayOps`, which a connectivity built with `from_array` bypasses. + +### `is_traced` and `concrete_eval` on `ArrayOps` + +Two small hooks, with the case distinction written out in `NdArrayConnectivityField`. Rejected because tracing then shows in the code shared by all array libraries. + +### Static values that follow the connectivity instead of the table + +Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. + ### Bounds in the aux data instead of the table Storing only `(min, max)` retraces per bounds rather than per buffer and holds no table reference, but cannot answer narrowing ranges. From 15b7897b5825b0cc71f67ebfafae8122757d7378 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 10 Nov 2026 20:46:38 +0100 Subject: [PATCH 049/166] refactor[next]: attach the static values of a connectivity to every unflattened table --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 4 ++-- src/gt4py/next/embedded/array_libraries/jax_ops.py | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 8b9264452f..9a61ac5752 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -26,7 +26,7 @@ There is one connectivity class, `NdArrayConnectivityField`, for all array libra A connectivity stores one opaque value for its `ArrayOps`, `_static`, and hands it to these methods. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, together with the tracer they belong to. A connectivity that got another table, for example through `dataclasses.replace`, does not match its `_static` any more and is treated as having none. -The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with matching `_static`. Unflattening around anything but a concrete array attaches them. +The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with matching `_static`. Unflattening attaches them to the new child, whatever it is; a concrete child does not need them. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: @@ -43,7 +43,7 @@ The aux data claims that the child has the static values. Where jax rebuilds a p - At the entry of `jit`, of a nested `jit`, and for the operands of `lax.cond`, the new tracer stands for the flattened table. - `lax.cond` and `lax.switch` require all branches to return the same aux data, and `lax.scan`, `lax.while_loop` and `lax.fori_loop` require the carry to keep its aux data. Selecting between two tables, changing the table of a carried connectivity, or mixing a table that has static values with one computed in the trace raises jax's `TypeError` about differing pytree structure. The same table on all branches, or an unchanged carry, keeps its static values. -For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to those as well. +For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to every child. ## Consequences diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index d90d8621ab..3f2ee96f7a 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -201,9 +201,9 @@ def _unflatten_connectivity( domain, codomain, skip_value, static = aux_data (table,) = children if static is not None: - # jax compares the aux data of the branches of `lax.cond` and of the carry of `lax.scan` - # on trees it rebuilds around placeholders that are not tracers, so they keep it as well - static = None if _has_values(table) else _StaticTable(static.values, table) + # not only for tracers: jax compares the aux data of the branches of `lax.cond` and of + # the carry of `lax.scan` on trees it rebuilds around other placeholders + static = _StaticTable(static.values, table) return nd_array_field.NdArrayConnectivityField(domain, table, codomain, skip_value, static) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' From 065923a2a289c65871a5b39ce2d019dcfa559232 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 10 Nov 2026 20:53:24 +0100 Subject: [PATCH 050/166] test[next]: cover a replaced connectivity passed on to a nested jit and when the gather clamps --- .../embedded_tests/test_nd_array_field.py | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 508557e42b..66e1c80ac7 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2335,16 +2335,41 @@ def body(carry, x): @pytest.mark.requires_jax -def test_jax_jit_premap_with_replaced_table_has_no_values(): +@pytest.mark.parametrize("nested", [False, True]) +def test_jax_jit_premap_with_replaced_table_has_no_values(nested): import jax E, field, conn_a, _ = _jax_narrowing_setup() + premap = ( + jax.jit(lambda field, conn: field.premap(conn)) + if nested + else nd_array_field.NdArrayField.premap + ) def premap_next(field, conn): - return field.premap(dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) + return premap(field, dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) result = jax.jit(premap_next)(field, conn_a) # as for every table computed in the trace: not narrowed, out-of-range targets clamped assert result.domain == common.domain({E: (0, 5)}) np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0, 30.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_clamps_only_tables_without_values(monkeypatch): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + clip = jax.numpy.clip + clipped = [] + monkeypatch.setattr(jax.numpy, "clip", lambda *args: clipped.append(args) or clip(*args)) + + jax.jit(lambda field, conn: field.premap(conn))(field, conn_a) + jax.jit(lambda field: field.premap(conn_a))(field) + assert not clipped + + jax.jit(lambda field, table: field.premap(dataclasses.replace(conn_a, _ndarray=table)))( + field, conn_a.ndarray + ) + assert len(clipped) == 1 From 8f9022cef49543422ef6f3565388b01597aba552 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 08:51:10 +0100 Subject: [PATCH 051/166] refactor[next]: rename ArrayOps.elementwise to elementwise_function --- src/gt4py/next/embedded/array_libraries/cupy_ops.py | 4 ++-- src/gt4py/next/embedded/array_libraries/jax_ops.py | 4 ++-- src/gt4py/next/embedded/array_libraries/numpy_ops.py | 4 ++-- src/gt4py/next/embedded/array_ops.py | 10 +++++----- src/gt4py/next/embedded/nd_array_field.py | 2 +- .../unit_tests/embedded_tests/test_array_ops.py | 6 +++--- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/cupy_ops.py b/src/gt4py/next/embedded/array_libraries/cupy_ops.py index 6402397141..cec8a5d0d4 100644 --- a/src/gt4py/next/embedded/array_libraries/cupy_ops.py +++ b/src/gt4py/next/embedded/array_libraries/cupy_ops.py @@ -31,12 +31,12 @@ def array_ns(self) -> ModuleType: def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: return value - def _elementwise(self, name: str) -> Callable[..., Any]: + def _elementwise_function(self, name: str) -> Callable[..., Any]: if name == "gamma": import cupyx.scipy.special return cupyx.scipy.special.gamma - return super()._elementwise(name) + return super()._elementwise_function(name) def setitem( self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index e958006db5..e2b87c8b64 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -26,12 +26,12 @@ class JaxOps(array_ops.ArrayOps): def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: return value - def _elementwise(self, name: str) -> Callable[..., Any]: + def _elementwise_function(self, name: str) -> Callable[..., Any]: if name == "gamma": import jax.scipy.special return jax.scipy.special.gamma - return super()._elementwise(name) + return super()._elementwise_function(name) def setitem( self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any diff --git a/src/gt4py/next/embedded/array_libraries/numpy_ops.py b/src/gt4py/next/embedded/array_libraries/numpy_ops.py index 7072f745dd..66dd91e6a3 100644 --- a/src/gt4py/next/embedded/array_libraries/numpy_ops.py +++ b/src/gt4py/next/embedded/array_libraries/numpy_ops.py @@ -48,10 +48,10 @@ def asarray( def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: return value - def _elementwise(self, name: str) -> Callable[..., Any]: + def _elementwise_function(self, name: str) -> Callable[..., Any]: if name == "gamma": return _np_gamma - return super()._elementwise(name) + return super()._elementwise_function(name) def setitem( self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index ac4b932af0..c89b2fdd4f 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -74,7 +74,7 @@ class ArrayOps: def __init__(self, xp: ModuleType) -> None: self.xp = xp - self._elementwise_cache: dict[str, Callable[..., Any]] = {} + self._elementwise_function_cache: dict[str, Callable[..., Any]] = {} def __repr__(self) -> str: return f"{type(self).__name__}({self.xp.__name__})" @@ -119,15 +119,15 @@ def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: return self.asarray(value, dtype=type(value), like=like) return value - def elementwise(self, name: str) -> Callable[..., Any]: + def elementwise_function(self, name: str) -> Callable[..., Any]: """The elementwise function for a gt4py builtin or operator name.""" try: - return self._elementwise_cache[name] + return self._elementwise_function_cache[name] except KeyError: - func = self._elementwise_cache[name] = self._elementwise(name) + func = self._elementwise_function_cache[name] = self._elementwise_function(name) return func - def _elementwise(self, name: str) -> Callable[..., Any]: + def _elementwise_function(self, name: str) -> Callable[..., Any]: if name == "where": return self.where func = getattr(self.xp, STANDARD_NAMES.get(name, name), None) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 63b2bff256..ee31daf370 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -43,7 +43,7 @@ def _make_builtin( ) -> Callable[..., NdArrayField]: def _builtin_op(*fields: common.Field | core_defs.Scalar) -> NdArrayField: ops = _ops_of(*fields) - op = ops.elementwise(array_builtin_name) + op = ops.elementwise_function(array_builtin_name) domain_intersection = embedded_common.domain_intersection( *[f.domain for f in fields if isinstance(f, common.Field)] diff --git a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py index 8277253b3c..543f467090 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py @@ -43,12 +43,12 @@ def test_registered_namespaces(): assert array_ops.of(np.empty(1)).array_ns is np -def test_elementwise_override(isolated_registry): +def test_elementwise_function_override(isolated_registry): class Ops(array_ops.ArrayOps): - def _elementwise(self, name): + def _elementwise_function(self, name): if name == "sin": return lambda x: x + 100.0 - return super()._elementwise(name) + return super()._elementwise_function(name) array_ops.register(array_api_compat.is_array_api_strict_namespace, Ops) field = _strict_field([1.0, 2.0]) From 66996a3abe528e3f6a43881e2ffc4b9eb8d91e11 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 08:51:25 +0100 Subject: [PATCH 052/166] docs[next]: say why ArrayOps.where exists --- src/gt4py/next/embedded/array_ops.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index c89b2fdd4f..99da5b1367 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -138,6 +138,14 @@ def _elementwise_function(self, name: str) -> Callable[..., Any]: return func def where(self, condition: Any, x: Any, y: Any) -> core_defs.NDArrayObject: + """ + `xp.where` for the operands of the `where` builtin. + + The standard requires an array `condition`, but the builtin also receives a + scalar one (e.g. from `broadcast(True)`), which some libraries reject (CuPy, + torch). It becomes a 0-d array on the device of the other operands. `x` and `y` + are converted like the operands of any other elementwise function. + """ if isinstance(condition, bool | np.bool_): like = next(a for a in (x, y) if array_api_compat.is_array_api_obj(a)) condition = self.asarray(condition, dtype=bool, like=like) From 5f148ae8f25404ec7c487f979699cd8a317721fb Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 08:52:03 +0100 Subject: [PATCH 053/166] refactor[next]: precise type hints in the dtype translation of ndarray_utils '_numpy_scalar_type' returns a NumPy scalar type, which the caller checks against the gt4py scalar types; namespace dtypes are typed with the module's '_ArrayDType' protocol instead of 'Any'. --- src/gt4py/_core/ndarray_utils.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/gt4py/_core/ndarray_utils.py b/src/gt4py/_core/ndarray_utils.py index 226d3a1afb..a2aa1cf65b 100644 --- a/src/gt4py/_core/ndarray_utils.py +++ b/src/gt4py/_core/ndarray_utils.py @@ -113,14 +113,16 @@ def array_namespace(array: core_defs.NDArrayObject) -> ArrayNamespace: @functools.cache -def _numpy_scalar_type(dtype: np.dtype) -> type: +def _numpy_scalar_type(dtype: np.dtype) -> type[np.generic]: # NumPy, CuPy and JAX describe dtypes as `np.dtype`, and its `type` depends on byte order # and C type name (e.g. `np.longlong` is not `np.int64`); kind and size identify it return np.dtype(f"{dtype.kind}{dtype.itemsize}").type @functools.cache -def _dtype_tables(array_ns: ArrayNamespace) -> tuple[dict[type, Any], dict[Any, type]]: +def _dtype_tables( + array_ns: ArrayNamespace, +) -> tuple[dict[type, _ArrayDType], dict[_ArrayDType, type]]: to_namespace = { scalar_type: getattr(array_ns, name) for scalar_type, name in core_types.type_to_name.items() @@ -129,7 +131,7 @@ def _dtype_tables(array_ns: ArrayNamespace) -> tuple[dict[type, Any], dict[Any, return to_namespace, {dtype: scalar_type for scalar_type, dtype in to_namespace.items()} -def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar]) -> Any: +def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar]) -> _ArrayDType: """The dtype object of `array_ns` for the gt4py scalar type `scalar_type`.""" try: return _dtype_tables(array_ns)[0][scalar_type] @@ -137,7 +139,7 @@ def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar raise TypeError(f"Array namespace '{array_ns}' has no dtype for '{scalar_type}'.") from None -def scalar_type(array_ns: ArrayNamespace, dtype: Any) -> type[core_defs.Scalar]: +def scalar_type(array_ns: ArrayNamespace, dtype: _ArrayDType) -> type[core_defs.Scalar]: """The gt4py scalar type of the arrays of `array_ns` with dtype `dtype`.""" result = ( _numpy_scalar_type(dtype) From 3a008f02c6ccae6364baec9a196026707601acdc Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 08:53:30 +0100 Subject: [PATCH 054/166] refactor[next]: call array_ops.of directly instead of an NdArrayField._ops property --- src/gt4py/next/embedded/nd_array_field.py | 42 +++++++++---------- .../embedded_tests/test_array_ops.py | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index ee31daf370..68b15790fa 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -34,7 +34,7 @@ def _ops_of(*values: Any) -> array_ops.ArrayOps: for v in values: if isinstance(v, NdArrayField): - return v._ops + return array_ops.of(v._ndarray) raise AssertionError("No 'NdArrayField' found in the arguments.") @@ -112,16 +112,12 @@ class NdArrayField( _domain: common.Domain _ndarray: core_defs.NDArrayObject - @property - def _ops(self) -> array_ops.ArrayOps: - return array_ops.of(self._ndarray) - @property def array_ns(self) -> ModuleType: """The module of the array library holding the buffer, e.g. `numpy`.""" - # TODO(havogt): return the Array API namespace (`self._ops.xp`) instead of the library's + # TODO(havogt): return the Array API namespace (`array_ops.of(self._ndarray).xp`) instead of the library's # own module; users comparing it to `numpy` should query the device instead. - return self._ops.array_ns + return array_ops.of(self._ndarray).array_ns def __getstate__(self) -> dict[str, Any]: # Serialize only the dataclass fields, excluding cached properties @@ -165,7 +161,7 @@ def __gt_buffer_info__(self) -> common.BufferInfo: NDArrayField subclasses where the backing ndarray can be replaced should override this and make it a regular property. """ - return self._ops.buffer_info(self.ndarray) + return array_ops.of(self._ndarray).buffer_info(self.ndarray) @property def shape(self) -> tuple[int, ...]: @@ -181,14 +177,14 @@ def codomain(self) -> type[core_defs.ScalarT]: @functools.cached_property def dtype(self) -> core_defs.DType[core_defs.ScalarT]: - return core_defs.dtype(self._ops.scalar_type(self._ndarray.dtype)) + return core_defs.dtype(array_ops.of(self._ndarray).scalar_type(self._ndarray.dtype)) @property def ndarray(self) -> core_defs.NDArrayObject: return self._ndarray def asnumpy(self) -> np.ndarray: - return self._ops.to_numpy(self._ndarray) + return array_ops.of(self._ndarray).to_numpy(self._ndarray) def as_scalar(self) -> core_defs.ScalarT: if self.domain.ndim != 0: @@ -356,7 +352,7 @@ def __setitem__( ) value = value.ndarray - new_buffer = self._ops.setitem(self._ndarray, target_slice, value) + new_buffer = array_ops.of(self._ndarray).setitem(self._ndarray, target_slice, value) if new_buffer is not self._ndarray: object.__setattr__(self, "_ndarray", new_buffer) @@ -521,7 +517,9 @@ def inverse_image(self, image_range: common.UnitRange | common.NamedRange) -> co assert isinstance(image_range, common.UnitRange) assert common.UnitRange.is_finite(image_range) - slices = _hyperslice(self._ndarray, image_range, self._ops.xp, self.skip_value) + slices = _hyperslice( + self._ndarray, image_range, array_ops.of(self._ndarray).xp, self.skip_value + ) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -537,7 +535,7 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: new_domain, buffer_slice = self._slice(index) restricted_connectivity = self.__class__( new_domain, - self._ops.asarray(self.ndarray[buffer_slice]), + array_ops.of(self._ndarray).asarray(self.ndarray[buffer_slice]), self.codomain, self.skip_value, ) @@ -599,7 +597,7 @@ def _gather_output_domain( def _gather_premap(data: NdArrayField, *connectivities: common.GatherConnectivity) -> NdArrayField: """`premap` via a single advanced-index gather (dimension-preserving and -introducing cases).""" - ops = data._ops + ops = array_ops.of(data._ndarray) new_domain = _gather_output_domain(data.domain, connectivities) conn_by_codomain = {conn.codomain: conn for conn in connectivities} @@ -759,7 +757,7 @@ def _to_field(value: common.Field | core_defs.Scalar, like: NdArrayField) -> com value if isinstance(value, common.Field) else NdArrayField.from_array( - like._ops.asarray(value, like=like.ndarray), domain=common.Domain() + array_ops.of(like._ndarray).asarray(value, like=like.ndarray), domain=common.Domain() ) ) @@ -847,7 +845,7 @@ def _invert_domain(domain: common.Domain) -> tuple[common.Domain, ...]: def _size0_field( like: NdArrayField, dims: tuple[common.Dimension, ...], dtype: core_defs.DType ) -> NdArrayField: - ops = like._ops + ops = array_ops.of(like._ndarray) return NdArrayField.from_array( ops.xp.empty( (0,) * len(dims), dtype=ops.dtype(dtype.scalar_type), device=ops.device(like.ndarray) @@ -907,7 +905,7 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> com coords = _identity_index_array( offset_field.domain, source_dim, - offset_field._ops, + array_ops.of(offset_field._ndarray), like=offset_field.ndarray, dtype=fbuiltins.IndexType, ) @@ -925,7 +923,7 @@ def _make_reduction( def _builtin_op( field: NdArrayField[common.DimsT, core_defs.ScalarT], axis: common.Dimension ) -> NdArrayField[common.DimsT, core_defs.ScalarT]: - ops = field._ops + ops = array_ops.of(field._ndarray) if not axis.kind == common.DimensionKind.LOCAL: raise ValueError("Can only reduce local dimensions.") @@ -967,10 +965,12 @@ def _builtin_op( fbuiltins.neighbor_sum, _make_reduction("neighbor_sum", "sum", lambda x: x.dtype.scalar_type(0)) ) _register_builtin( - fbuiltins.max_over, _make_reduction("max_over", "max", lambda x: x._ops.xp.min(x._ndarray)) + fbuiltins.max_over, + _make_reduction("max_over", "max", lambda x: array_ops.of(x._ndarray).xp.min(x._ndarray)), ) _register_builtin( - fbuiltins.min_over, _make_reduction("min_over", "min", lambda x: x._ops.xp.max(x._ndarray)) + fbuiltins.min_over, + _make_reduction("min_over", "min", lambda x: array_ops.of(x._ndarray).xp.max(x._ndarray)), ) @@ -1036,7 +1036,7 @@ def _builtins_broadcast( def _astype(field: common.Field | core_defs.ScalarT | tuple, type_: type) -> NdArrayField: if isinstance(field, NdArrayField): - ops = field._ops + ops = array_ops.of(field._ndarray) return NdArrayField.from_array( ops.xp.astype(field.ndarray, ops.dtype(type_)), domain=field.domain ) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py index 543f467090..1ef5ed196c 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py @@ -33,7 +33,7 @@ def _strict_field(values, dtype=xs.float64): def test_unregistered_namespace_uses_standard_ops(): field = _strict_field([1.0, 2.0]) - assert type(field._ops) is array_ops.ArrayOps + assert type(array_ops.of(field.ndarray)) is array_ops.ArrayOps assert field.array_ns is xs assert isinstance(field, nd_array_field.NdArrayField) From 54b4c4196a0593d5ff6a8eb1d2360ee7b5a03a10 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 09:24:13 +0100 Subject: [PATCH 055/166] fix[next]: where with two scalar branches on the default ArrayOps The Array API requires one of the branches of 'where' to be an array; with two scalars, the first becomes a 0-d array of its default dtype, which matches NumPy's result. A new ffront test covers 'where' with two scalar branches on every backend. --- src/gt4py/next/embedded/array_ops.py | 9 +++++++-- .../feature_tests/ffront_tests/test_where.py | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 99da5b1367..a7082f1323 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -144,12 +144,17 @@ def where(self, condition: Any, x: Any, y: Any) -> core_defs.NDArrayObject: The standard requires an array `condition`, but the builtin also receives a scalar one (e.g. from `broadcast(True)`), which some libraries reject (CuPy, torch). It becomes a 0-d array on the device of the other operands. `x` and `y` - are converted like the operands of any other elementwise function. + are converted like the operands of any other elementwise function; the standard + also requires one of them to be an array, so if both are scalars, `x` becomes a + 0-d array with the default dtype for its kind, as NumPy promotes it. """ if isinstance(condition, bool | np.bool_): like = next(a for a in (x, y) if array_api_compat.is_array_api_obj(a)) condition = self.asarray(condition, dtype=bool, like=like) - return self.xp.where(condition, self.operand(x, condition), self.operand(y, condition)) + x, y = self.operand(x, condition), self.operand(y, condition) + if not (array_api_compat.is_array_api_obj(x) or array_api_compat.is_array_api_obj(y)): + x = self.asarray(x, like=condition) + return self.xp.where(condition, x, y) def setitem( self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py index 7ea11a7b69..03c714421e 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py @@ -188,6 +188,20 @@ def conditional_promotion(mask: cases.IBoolField, a: cases.IFloatField) -> cases cases.verify(cartesian_case, conditional_promotion, mask, a, out=out, ref=ref) +def test_conditional_scalar_branches(cartesian_case): + @gtx.field_operator + def conditional_scalars(mask: cases.IBoolField) -> cases.IFloatField: + return where(mask, 1.0, 0.0) + + size = cartesian_case.default_sizes[IDim] + mask = cartesian_case.as_field([IDim], np.random.choice(a=[False, True], size=(size))) + out = cases.allocate(cartesian_case, conditional_scalars, cases.RETURN)() + + cases.verify( + cartesian_case, conditional_scalars, mask, out=out, ref=np.where(mask.asnumpy(), 1.0, 0.0) + ) + + def test_conditional_compareop(cartesian_case): @gtx.field_operator def conditional_promotion(a: cases.IFloatField) -> cases.IFloatField: From 74f60d55b9eeaac62d0159d14096e11eeeae2233 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 09:25:06 +0100 Subject: [PATCH 056/166] test[next]: buffer info tests on buffers of each array library The tests built their fields with 'as_field', which copies a CPU array of any library into NumPy, and the connectivity test ignored the library parameter. Fields are now built from the library's own array; JAX raises NotImplementedError, other libraries than NumPy and CuPy are skipped. --- .../embedded_tests/test_nd_array_field.py | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 9352fc499f..5fc9602c3f 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -110,11 +110,28 @@ def are_equal_fields(a: Field, b: Field) -> bool: return (a.domain == b.domain) and (a.asnumpy() == b.asnumpy()).all() +def _skip_or_expect_no_buffer_info(xp) -> bool: + """Whether `xp` arrays have no buffer info; skips libraries for which it is undefined.""" + if xp.__name__ == "jax.numpy": + return True + if xp.__name__ not in ("numpy", "cupy"): + pytest.skip( + "Buffer pointers and strides are outside the Array API standard; " + "'BufferInfo.from_ndarray' knows NumPy and CuPy only." + ) + return False + + def test_nd_array_field_buffer_info(nd_array_implementation): import dataclasses data = asarray(nd_array_implementation, [[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) - field = constructors.as_field((D0, D1), data) + field = common._field(data, domain=common.domain({D0: 2, D1: 2})) + assert field.array_ns is nd_array_implementation + if _skip_or_expect_no_buffer_info(nd_array_implementation): + with pytest.raises(NotImplementedError): + field.__gt_buffer_info__ + return field_ndarray = field.ndarray buffer_info = field.__gt_buffer_info__ @@ -1340,10 +1357,15 @@ def test_nd_array_connectivity_field_buffer_info(nd_array_implementation): E_START, E_STOP = 0, 10 e2v_conn = common._connectivity( - np.roll(np.arange(E_START, E_STOP), 1), + asarray(nd_array_implementation, np.roll(np.arange(E_START, E_STOP), 1), dtype=np.int32), domain=common.domain([common.named_range((E, (E_START, E_STOP)))]), codomain=V, ) + assert e2v_conn.array_ns is nd_array_implementation + if _skip_or_expect_no_buffer_info(nd_array_implementation): + with pytest.raises(NotImplementedError): + e2v_conn.__gt_buffer_info__ + return buffer_info = e2v_conn.__gt_buffer_info__ assert buffer_info == common.BufferInfo.from_ndarray(e2v_conn.ndarray) From 9fc881657b010509c5145ecfc5d659a81ef27bf1 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 09:26:28 +0100 Subject: [PATCH 057/166] test[next]: item assignment on fields of each array library Scalars, NumPy scalars, arrays of the field's library in its dtype and in another one, NumPy arrays and fields are assigned into a float64 field of every library in the test matrix. --- .../embedded_tests/test_nd_array_field.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 5fc9602c3f..e750555c65 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1293,6 +1293,56 @@ def test_setitem(index, value): assert np.allclose(field.ndarray, expected) +_ROW = np.arange(10) * 2.0 + + +@pytest.mark.parametrize( + "index, source, make_value", + [ + ((1, 1), 42.0, lambda xp, v: v), + ((1, 1), 42, lambda xp, v: v), + ((1, 1), np.float32(42.5), lambda xp, v: v), + ((1, slice(None)), _ROW, lambda xp, v: asarray(xp, v, dtype=np.float64)), + ((1, slice(None)), _ROW, lambda xp, v: asarray(xp, v, dtype=np.float32)), + ((1, slice(None)), _ROW, lambda xp, v: v), + ( + (1, slice(None)), + _ROW, + lambda xp, v: common._field( + asarray(xp, v, dtype=np.float64), + domain=common.Domain(NamedRange(D1, UnitRange(0, 10))), + ), + ), + ], + ids=[ + "python-float", + "python-int", + "numpy-scalar", + "array", + "array-other-dtype", + "numpy-array", + "field", + ], +) +def test_setitem_array_libraries(nd_array_implementation, index, source, make_value): + xp = nd_array_implementation + value = make_value(xp, source) + if is_cupy(xp) and isinstance(value, np.ndarray): + pytest.skip("CuPy does not assign a non-scalar NumPy array.") + field = common._field( + asarray(xp, np.arange(100).reshape(10, 10), dtype=np.float64), + domain=common.Domain(dims=(D0, D1), ranges=(UnitRange(0, 10), UnitRange(0, 10))), + ) + expected = np.arange(100, dtype=np.float64).reshape(10, 10) + expected[index] = source + + field[index] = value + + assert field.array_ns is xp + assert field.dtype == core_defs.dtype(np.float64) + assert np.array_equal(field.asnumpy(), expected) + + def test_setitem_wrong_domain(): field = common._field( np.arange(100).reshape(10, 10), From e899fcc5f817e467bad96e513ae101c300330d3e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 09:27:12 +0100 Subject: [PATCH 058/166] build: re-lock uv.lock from main with a current uv The lock was regenerated with an older uv, which rewrote its format revision and unrelated markers; it now differs from main only by array-api-strict. --- uv.lock | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/uv.lock b/uv.lock index d4fd5bc224..5f3409aeab 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.12, !=3.13.10, !=3.14.1, <3.15" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -415,7 +415,7 @@ name = "cffi" version = "2.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pycparser", marker = "implementation_name != 'PyPy' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "pycparser" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } wheels = [ @@ -571,7 +571,7 @@ name = "click" version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } wheels = [ @@ -618,7 +618,7 @@ name = "colorlog" version = "6.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8c/55/ba79756cb90c8d69d599d57785398ac87bba7b19c80e87f4e8a562197c93/colorlog-6.12.0.tar.gz", hash = "sha256:2a7924c1dadf18b22a0eb8b06d1c7b01d5341707ec1641eb6fcc4fde0c3e8e5f", size = 18151, upload-time = "2026-07-23T13:40:40.71Z" } wheels = [ @@ -949,7 +949,7 @@ dependencies = [ { name = "ordered-set" }, { name = "packaging" }, { name = "ply" }, - { name = "pyreadline", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "pyreadline", marker = "sys_platform == 'win32'" }, { name = "pyyaml" }, { name = "scikit-build" }, { name = "sympy" }, @@ -1139,7 +1139,7 @@ name = "faker" version = "40.36.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "tzdata", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "tzdata", marker = "sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/98/d2/026af1e002bbc6df534d1f8262b18ec79a974f928e9290bfbfdfe7c7b2af/faker-40.36.0.tar.gz", hash = "sha256:754048c76c03afa7de83eee8f4bcee3cf668cbb7d995f54a4e9678db7f110308", size = 2025903, upload-time = "2026-07-24T21:11:33.088Z" } wheels = [ @@ -1755,7 +1755,7 @@ name = "ipykernel" version = "7.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "appnope", marker = "sys_platform == 'darwin' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "appnope", marker = "sys_platform == 'darwin'" }, { name = "comm" }, { name = "debugpy" }, { name = "ipython" }, @@ -1779,13 +1779,13 @@ name = "ipython" version = "9.16.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, { name = "ipython-pygments-lexers" }, { name = "jedi" }, { name = "matplotlib-inline" }, - { name = "pexpect", marker = "(sys_platform != 'emscripten' and sys_platform != 'win32') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, { name = "prompt-toolkit" }, - { name = "psutil", marker = "(sys_platform != 'cygwin' and sys_platform != 'emscripten') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'cygwin' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" }, { name = "pygments" }, { name = "stack-data" }, { name = "traitlets" }, @@ -2458,7 +2458,7 @@ version = "2.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "ast-serialize" }, - { name = "librt", marker = "platform_python_implementation != 'PyPy' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, { name = "mypy-extensions" }, { name = "pathspec" }, { name = "typing-extensions" }, @@ -2842,7 +2842,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy" }, { name = "python-dateutil" }, - { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/be/4f/5f3422a2afec5ffc46308b79e53291365a93748b498ac2e58bead0197916/pandas-3.0.5.tar.gz", hash = "sha256:dca3734d6ab7c906e6730f0788b0a1dbb9f2467731f9711f77995c8e9d62d712", size = 4658219, upload-time = "2026-07-22T22:19:28.819Z" } wheels = [ @@ -2904,7 +2904,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess", marker = "(sys_platform != 'emscripten' and sys_platform != 'win32') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'emscripten' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (sys_platform == 'win32' and extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "ptyprocess" }, ] sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" } wheels = [ @@ -3153,7 +3153,7 @@ name = "pytest" version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, @@ -3357,7 +3357,7 @@ name = "pyzmq" version = "27.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cffi", marker = "implementation_name == 'pypy' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "cffi", marker = "implementation_name == 'pypy'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/04/0b/3c9baedbdf613ecaa7aa07027780b8867f57b6293b6ee50de316c9f3222b/pyzmq-27.1.0.tar.gz", hash = "sha256:ac0765e3d44455adb6ddbf4417dcce460fc40a05978c08efdf2948072f6db540", size = 281750, upload-time = "2025-09-08T23:10:18.157Z" } wheels = [ @@ -3402,7 +3402,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, { name = "rpds-py" }, - { name = "typing-extensions", marker = "python_full_version < '3.13' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } wheels = [ @@ -3780,7 +3780,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "alabaster" }, { name = "babel" }, - { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, { name = "docutils" }, { name = "imagesize" }, { name = "jinja2" }, @@ -3820,7 +3820,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, { name = "markupsafe" }, - { name = "standard-imghdr", marker = "python_full_version >= '3.13' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "standard-imghdr", marker = "python_full_version >= '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/43/98/43313781f29e8c6c46fec907430310172d6f207e95e4fbea9289990fbbfe/sphinx_jinja2_compat-0.4.1.tar.gz", hash = "sha256:0188f0802d42c3da72997533b55a00815659a78d3f81d4b4747b1fb15a5728e6", size = 5222, upload-time = "2025-08-06T20:06:25.824Z" } wheels = [ @@ -4171,7 +4171,7 @@ version = "0.27.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "annotated-doc" }, - { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-jax-cuda13') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-jax-cuda13' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, { name = "rich" }, { name = "shellingham" }, ] From 6333ce04b040bc33bccef6a9ac09f8b49e1315e9 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 09:56:03 +0100 Subject: [PATCH 059/166] fix[next]: translate NumPy scalar types named by C type to namespace dtypes 'astype(field, np.longlong)' failed with 'has no dtype for np.longlong' although the namespace has int64: scalar types that are NumPy types are now identified by kind and size in this direction too. --- src/gt4py/_core/ndarray_utils.py | 7 ++++++- tests/core_tests/unit_tests/test_nd_array_utils.py | 10 ++++++++++ .../embedded_tests/test_nd_array_field.py | 13 +++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/gt4py/_core/ndarray_utils.py b/src/gt4py/_core/ndarray_utils.py index a2aa1cf65b..f485d8d123 100644 --- a/src/gt4py/_core/ndarray_utils.py +++ b/src/gt4py/_core/ndarray_utils.py @@ -133,8 +133,13 @@ def _dtype_tables( def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar]) -> _ArrayDType: """The dtype object of `array_ns` for the gt4py scalar type `scalar_type`.""" + key: type = ( + _numpy_scalar_type(np.dtype(scalar_type)) + if issubclass(scalar_type, np.generic) + else scalar_type + ) try: - return _dtype_tables(array_ns)[0][scalar_type] + return _dtype_tables(array_ns)[0][key] except KeyError: raise TypeError(f"Array namespace '{array_ns}' has no dtype for '{scalar_type}'.") from None diff --git a/tests/core_tests/unit_tests/test_nd_array_utils.py b/tests/core_tests/unit_tests/test_nd_array_utils.py index d315f4c796..155a963365 100644 --- a/tests/core_tests/unit_tests/test_nd_array_utils.py +++ b/tests/core_tests/unit_tests/test_nd_array_utils.py @@ -91,3 +91,13 @@ def test_dtype_of_c_type_aliases(c_type, expected): def test_dtype_of_rejects_non_gt4py_types(dtype): with pytest.raises(TypeError, match="not a gt4py scalar type"): ndarray_utils.dtype_of(np.zeros((2,), dtype=dtype)) + + +@pytest.mark.parametrize("array_ns_name", ["numpy", "array_api_strict"]) +@pytest.mark.parametrize( + "c_type, expected", [(np.longlong, "int64"), (np.ulonglong, "uint64"), (np.intc, "int32")] +) +def test_namespace_dtype_of_c_type_aliases(array_ns_name, c_type, expected): + array_ns = importlib.import_module(array_ns_name) + + assert ndarray_utils.namespace_dtype(array_ns, c_type) == getattr(array_ns, expected) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index e750555c65..d64391d730 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1343,6 +1343,19 @@ def test_setitem_array_libraries(nd_array_implementation, index, source, make_va assert np.array_equal(field.asnumpy(), expected) +@pytest.mark.parametrize("c_type, expected", [(np.longlong, np.int64), (np.intc, np.int32)]) +def test_astype_c_type_alias(nd_array_implementation, c_type, expected): + field = common._field( + asarray(nd_array_implementation, [1.0, 2.0], dtype=np.float64), + domain=common.Domain(NamedRange(D0, UnitRange(0, 2))), + ) + + result = fbuiltins.astype(field, c_type) + + assert result.dtype == core_defs.dtype(expected) + assert np.array_equal(result.asnumpy(), np.asarray([1, 2], dtype=expected)) + + def test_setitem_wrong_domain(): field = common._field( np.arange(100).reshape(10, 10), From df9f85251dee839db35a00b1fe6df3e5e672930c Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 11:40:57 +0100 Subject: [PATCH 060/166] fix[next]: concat_where converts fields of other libraries to the first field's As on main, the fields intersected for concat_where are converted to the array library of the first field; mixing e.g. CuPy and NumPy fields raised in concat. A new test covers concat_where for every pair of libraries and checks the library of the result. --- src/gt4py/next/embedded/nd_array_field.py | 3 ++- .../embedded_tests/test_nd_array_field.py | 21 ++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 68b15790fa..51399d2aaa 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -778,9 +778,10 @@ def _intersect_fields( *[f.domain for f in broadcasted_fields], ignore_dims=ignore_dims ) + ops = array_ops.of(like._ndarray) return tuple( NdArrayField.from_array( - f.ndarray[_get_slices_from_domain_slice(f.domain, intersected_domain)], + ops.asarray(f.ndarray[_get_slices_from_domain_slice(f.domain, intersected_domain)]), domain=intersected_domain, ) for f, intersected_domain in zip(broadcasted_fields, intersected_domains, strict=True) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index d64391d730..de3097b44d 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -28,7 +28,7 @@ from gt4py.next.embedded import exceptions as embedded_exceptions, nd_array_field from gt4py.next.embedded.nd_array_field import _get_slices_from_domain_slice from gt4py.next.ffront import fbuiltins -from gt4py.next.ffront.experimental import as_offset +from gt4py.next.ffront.experimental import as_offset, concat_where from next_tests.integration_tests.feature_tests.math_builtin_test_data import math_builtin_test_data from next_tests.unit_tests.conftest import ( @@ -361,6 +361,25 @@ def test_mixed_fields(product_nd_array_implementation): assert np.allclose(result.ndarray, expected) +def test_mixed_fields_concat_where(product_nd_array_implementation): + first_impl, second_impl = product_nd_array_implementation + if not is_cupy(first_impl) and is_cupy(second_impl): + pytest.skip("Converting a CuPy array to a CPU library requires an explicit copy.") + K = Dimension("K") + domain = common.domain({K: 4}) + true_field = common._field( + asarray(first_impl, [1.0, 2.0, 3.0, 4.0], dtype=np.float64), domain=domain + ) + false_field = common._field( + asarray(second_impl, [10.0, 20.0, 30.0, 40.0], dtype=np.float64), domain=domain + ) + + result = concat_where(common.domain({K: (0, 2)}), true_field, false_field) + + assert result.array_ns is first_impl + assert np.array_equal(result.asnumpy(), [1.0, 2.0, 30.0, 40.0]) + + def test_non_dispatched_function(): @fbuiltins.BuiltInFunction def fma(a: common.Field, b: common.Field, c: common.Field, /) -> common.Field: From 7f48c7cbb2d6ba49ca3728ea0740dae250addcdc Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 11:41:39 +0100 Subject: [PATCH 061/166] docs[next]: state the Array API revision the default ArrayOps needs --- src/gt4py/next/embedded/array_ops.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index a7082f1323..428c9a7fa1 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -11,7 +11,9 @@ `ArrayOps` implements everything `NdArrayField` does on its buffer against the Array API standard, through the namespace `array_api_compat` returns for the -buffer. Any standard-conforming array library works without registration. +buffer. Any array library conforming to revision 2024.12 or later of the standard +works without registration; earlier revisions do not take Python scalars as +arguments of elementwise functions, which `ArrayOps` passes for scalar operands. A library that needs different behaviour, or has a faster path outside the standard, subclasses `ArrayOps`, overrides only those methods and is registered From f2d488779f935eaccb424ef22c4fb8d6f6b8c764 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 11:44:06 +0100 Subject: [PATCH 062/166] refactor[next]: register ArrayOps instances by their namespace The registry was a list of namespace predicates with factories, meant to let a library register without being imported; every library module imports its library anyway. 'register' now takes an ArrayOps instance and keys it by its namespace in a dict. --- .../next/embedded/array_libraries/cupy_ops.py | 4 ++-- .../next/embedded/array_libraries/jax_ops.py | 4 ++-- .../embedded/array_libraries/numpy_ops.py | 4 ++-- src/gt4py/next/embedded/array_ops.py | 23 ++++++------------- .../embedded_tests/test_array_ops.py | 11 ++++----- 5 files changed, 18 insertions(+), 28 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/cupy_ops.py b/src/gt4py/next/embedded/array_libraries/cupy_ops.py index cec8a5d0d4..bd68b2ca8c 100644 --- a/src/gt4py/next/embedded/array_libraries/cupy_ops.py +++ b/src/gt4py/next/embedded/array_libraries/cupy_ops.py @@ -14,7 +14,7 @@ from types import ModuleType from typing import Any -import array_api_compat +import array_api_compat.cupy as compat_cupy import cupy as cp import numpy as np @@ -48,4 +48,4 @@ def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return cp.asnumpy(array) -array_ops.register(array_api_compat.is_cupy_namespace, CuPyOps) +array_ops.register(CuPyOps(compat_cupy)) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index e2b87c8b64..7d02f43e27 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -13,8 +13,8 @@ from collections.abc import Callable from typing import Any -import array_api_compat import jax +import jax.numpy as jnp import numpy as np from gt4py._core import definitions as core_defs @@ -45,7 +45,7 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") -array_ops.register(array_api_compat.is_jax_namespace, JaxOps) +array_ops.register(JaxOps(jnp)) # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config jax.config.update("jax_enable_x64", True) diff --git a/src/gt4py/next/embedded/array_libraries/numpy_ops.py b/src/gt4py/next/embedded/array_libraries/numpy_ops.py index 66dd91e6a3..4ea436c9aa 100644 --- a/src/gt4py/next/embedded/array_libraries/numpy_ops.py +++ b/src/gt4py/next/embedded/array_libraries/numpy_ops.py @@ -15,7 +15,7 @@ from types import ModuleType from typing import Any -import array_api_compat +import array_api_compat.numpy as compat_numpy import numpy as np from gt4py._core import definitions as core_defs @@ -63,4 +63,4 @@ def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.asarray(array) -array_ops.register(array_api_compat.is_numpy_namespace, NumPyOps) +array_ops.register(NumPyOps(compat_numpy)) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 428c9a7fa1..3f2109f866 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -16,9 +16,8 @@ arguments of elementwise functions, which `ArrayOps` passes for scalar operands. A library that needs different behaviour, or has a faster path outside the -standard, subclasses `ArrayOps`, overrides only those methods and is registered -with `register`. The registry is keyed by a predicate on the compat namespace and -holds a factory, so registering a library does not import it. +standard, subclasses `ArrayOps`, overrides only those methods and registers an +instance for its compat namespace with `register`. """ from __future__ import annotations @@ -179,30 +178,22 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: return common.BufferInfo.from_ndarray(array) -_registry: list[tuple[Callable[[ModuleType], bool], Callable[[ModuleType], ArrayOps]]] = [] _ops_by_namespace: dict[ModuleType, ArrayOps] = {} _ops_by_array_type: dict[type, ArrayOps] = {} -def register( - is_namespace: Callable[[ModuleType], bool], factory: Callable[[ModuleType], ArrayOps] -) -> None: - """ - Use `factory(xp)` for the buffers whose compat namespace `xp` satisfies `is_namespace`. - - Later registrations take precedence. - """ - _registry.insert(0, (is_namespace, factory)) - _ops_by_namespace.clear() +def register(ops: ArrayOps) -> None: + """Use `ops` for the buffers whose compat namespace is `ops.xp`, replacing an earlier registration.""" + _ops_by_namespace[ops.xp] = ops _ops_by_array_type.clear() def for_namespace(xp: ModuleType) -> ArrayOps: + """The registered `ArrayOps` for the compat namespace `xp`, or the default one.""" try: return _ops_by_namespace[xp] except KeyError: - factory = next((f for is_ns, f in _registry if is_ns(xp)), ArrayOps) - ops = _ops_by_namespace[xp] = factory(xp) + ops = _ops_by_namespace[xp] = ArrayOps(xp) return ops diff --git a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py index 1ef5ed196c..241b39d757 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_array_ops.py @@ -6,7 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import array_api_compat +import array_api_compat.numpy as compat_numpy import array_api_strict as xs import numpy as np import pytest @@ -21,8 +21,7 @@ @pytest.fixture def isolated_registry(monkeypatch): - monkeypatch.setattr(array_ops, "_registry", list(array_ops._registry)) - monkeypatch.setattr(array_ops, "_ops_by_namespace", {}) + monkeypatch.setattr(array_ops, "_ops_by_namespace", dict(array_ops._ops_by_namespace)) monkeypatch.setattr(array_ops, "_ops_by_array_type", {}) @@ -50,7 +49,7 @@ def _elementwise_function(self, name): return lambda x: x + 100.0 return super()._elementwise_function(name) - array_ops.register(array_api_compat.is_array_api_strict_namespace, Ops) + array_ops.register(Ops(xs)) field = _strict_field([1.0, 2.0]) assert np.allclose(fbuiltins.sin(field).asnumpy(), [101.0, 102.0]) @@ -64,7 +63,7 @@ def where_override(cond, x, y): class Ops(array_ops.ArrayOps): builtin_overrides = {fbuiltins.where: where_override} - array_ops.register(array_api_compat.is_array_api_strict_namespace, Ops) + array_ops.register(Ops(xs)) field = _strict_field([1.0, 2.0]) cond = _strict_field([True, False], dtype=xs.bool) @@ -76,6 +75,6 @@ def test_later_registration_takes_precedence(isolated_registry): class Ops(array_libraries.numpy_ops.NumPyOps): pass - array_ops.register(array_api_compat.is_numpy_namespace, Ops) + array_ops.register(Ops(compat_numpy)) assert type(array_ops.of(np.empty(1))) is Ops From bfe5679583857ae0199c5653c3fe6e23e4851fba Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 11:50:12 +0100 Subject: [PATCH 063/166] fix[next]: where with a scalar condition next to a NumPy-scalar branch The device of the condition was taken from the first branch that counts as an array, which can be a NumPy scalar, whose device 'cpu' JAX and CuPy reject. It is now taken from a branch that is a real array. --- src/gt4py/next/embedded/array_ops.py | 6 +++++- .../unit_tests/embedded_tests/test_nd_array_field.py | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 3f2109f866..6b3ba72680 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -150,7 +150,11 @@ def where(self, condition: Any, x: Any, y: Any) -> core_defs.NDArrayObject: 0-d array with the default dtype for its kind, as NumPy promotes it. """ if isinstance(condition, bool | np.bool_): - like = next(a for a in (x, y) if array_api_compat.is_array_api_obj(a)) + like = next( + a + for a in (x, y) + if array_api_compat.is_array_api_obj(a) and not isinstance(a, np.generic) + ) condition = self.asarray(condition, dtype=bool, like=like) x, y = self.operand(x, condition), self.operand(y, condition) if not (array_api_compat.is_array_api_obj(x) or array_api_compat.is_array_api_obj(y)): diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index de3097b44d..cef3982cd6 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -189,6 +189,17 @@ def test_where_builtin(nd_array_implementation): assert np.allclose(result.ndarray, expected) +@pytest.mark.parametrize("condition", [True, False, np.bool_(True)]) +@pytest.mark.parametrize("scalar", [5.0, np.float64(5.0)], ids=["python", "numpy"]) +def test_where_builtin_scalar_condition(nd_array_implementation, condition, scalar): + field = _make_field_or_scalar([1.0, 2.0, 3.0], nd_array_implementation, dtype=np.float64) + + result = fbuiltins.where(condition, scalar, field) + + assert result.array_ns is nd_array_implementation + assert np.array_equal(result.asnumpy(), np.where(condition, 5.0, [1.0, 2.0, 3.0])) + + def test_where_builtin_different_domain(nd_array_implementation): cond = np.asarray([True, False]) true_ = np.asarray([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32) From 1b2ba8f9b8fc0fd71596810c10a84c56a7481901 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 11:52:03 +0100 Subject: [PATCH 064/166] build: require jax>=0.4.32, the first version whose array API namespace is jax.numpy Before 0.4.32, array_api_compat resolves JAX arrays to 'jax.experimental.array_api', for which no ArrayOps is registered: it lacks functions used by the fields on older versions (e.g. 'minimum' on 0.4.26) and makes 'NdArrayField.array_ns' differ from 'jax.numpy'. The x64 test also runs on 0.4.32, where disabling x64 is 'jax.experimental.disable_x64'. --- pyproject.toml | 2 +- tests/core_tests/unit_tests/test_nd_array_utils.py | 6 +++++- uv.lock | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 53ec1aea8a..6bcb6ead22 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -148,7 +148,7 @@ cartesian = ['black>=25.11', 'clang-format>=18.1', 'gt4py[jax,standard,testing]' cuda12 = ['cupy-cuda12x>=12.0'] cuda13 = ['cupy-cuda13x>=14.0'] jax = [ - 'jax>=0.4.26 ; python_version < "3.14"', + 'jax>=0.4.32 ; python_version < "3.14"', # first version whose array API namespace is jax.numpy 'jax>=0.9.1 ; python_version >= "3.14"' # first version with pre-built wheel for Python 3.14 ] jax-cuda12 = ['jax[cuda12-local]>=0.6.0', 'gt4py[cuda12]'] diff --git a/tests/core_tests/unit_tests/test_nd_array_utils.py b/tests/core_tests/unit_tests/test_nd_array_utils.py index 155a963365..1a8da8bced 100644 --- a/tests/core_tests/unit_tests/test_nd_array_utils.py +++ b/tests/core_tests/unit_tests/test_nd_array_utils.py @@ -75,7 +75,11 @@ def test_dtype_of_ignores_byte_order(dtype): def test_dtype_of_jax_without_x64(): import jax - with jax.enable_x64(False): + # `jax.enable_x64` replaced `jax.experimental.disable_x64` in newer JAX versions + disable_x64 = ( + jax.enable_x64(False) if hasattr(jax, "enable_x64") else jax.experimental.disable_x64() + ) + with disable_x64: array = jax.numpy.zeros((2,), dtype=jax.numpy.float32) assert ndarray_utils.dtype_of(array) == definitions.dtype(np.float32) diff --git a/uv.lock b/uv.lock index 5f3409aeab..7d102718aa 100644 --- a/uv.lock +++ b/uv.lock @@ -1495,7 +1495,7 @@ requires-dist = [ { name = "gt4py", extras = ["jax", "standard", "testing"], marker = "extra == 'next'" }, { name = "hypothesis", marker = "extra == 'testing'", specifier = ">=6.93" }, { name = "jax", marker = "python_full_version >= '3.14' and extra == 'jax'", specifier = ">=0.9.1" }, - { name = "jax", marker = "python_full_version < '3.14' and extra == 'jax'", specifier = ">=0.4.26" }, + { name = "jax", marker = "python_full_version < '3.14' and extra == 'jax'", specifier = ">=0.4.32" }, { name = "jax", extras = ["cuda12-local"], marker = "extra == 'jax-cuda12'", specifier = ">=0.6.0" }, { name = "jax", extras = ["cuda13-local"], marker = "extra == 'jax-cuda13'", specifier = ">=0.7.0" }, { name = "jinja2", specifier = ">=3.0.0" }, From 8f6fb4008f19e094e354a3178e37c0ac5fbc68ee Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 13:29:26 +0100 Subject: [PATCH 065/166] fix[next]: reject fields of other array libraries as JAX pytrees A NumPy- or CuPy-backed field passed to e.g. 'jax.jit' was silently copied to a JAX array; flattening it now fails an assertion, as it failed on main. Only arrays of other libraries are rejected, since JAX also flattens fields whose leaves are not arrays, e.g. 'jax.tree.map' results and 'vmap' axis specifications. --- .../next/embedded/array_libraries/jax_ops.py | 9 ++++-- .../embedded_tests/test_nd_array_field.py | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 7d02f43e27..440198cb50 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -13,6 +13,7 @@ from collections.abc import Callable from typing import Any +import array_api_compat import jax import jax.numpy as jnp import numpy as np @@ -54,6 +55,11 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: def _flatten_field( field: nd_array_field.NdArrayField, ) -> tuple[tuple[core_defs.NDArrayObject], common.Domain]: + # JAX also flattens pytrees whose leaves are not arrays (e.g. `jax.tree.map` results or + # `vmap` axis specifications), so only arrays of other libraries are rejected + assert not array_api_compat.is_array_api_obj(field.ndarray) or array_api_compat.is_jax_array( + field.ndarray + ), f"Only fields of JAX arrays are JAX pytrees, got a field of '{type(field.ndarray)}'." return (field.ndarray,), field.domain @@ -63,9 +69,6 @@ def _unflatten_field( return nd_array_field.NdArrayField(domain, children[0]) # type: ignore[abstract] # mypy does not see '__gt_builtin_func__' as implemented by 'FieldBuiltinFuncRegistry' -# JAX registers pytrees by type, so fields of every array library are pytrees, not only those -# holding JAX arrays: like a bare NumPy array, a NumPy-backed field passed to `jax.jit` is -# copied to a JAX array on every call. jax.tree_util.register_pytree_node( nd_array_field.NdArrayField, # type: ignore[type-abstract, unused-ignore] # only reported when 'jax' is installed, see '_unflatten_field' _flatten_field, diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index cef3982cd6..1114bbcba3 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1935,6 +1935,35 @@ def test_jax_pytree_roundtrip(): assert jax.tree_util.tree_structure(other_field) != treedef +@pytest.mark.requires_jax +def test_jax_pytree_rejects_fields_of_other_libraries(): + import jax + + field = common._field(np.ones(3), domain=common.domain({D0: 3})) + + with pytest.raises(AssertionError, match="Only fields of JAX arrays"): + jax.jit(lambda f: f * 2.0)(field) + + +@pytest.mark.requires_jax +def test_jax_pytree_non_array_leaves(): + import jax + + D_BATCH = Dimension("D_BATCH") + field = common._field(jax.numpy.arange(3.0), domain=common.domain({D0: 3})) + batched = common._field(jax.numpy.ones((2, 3)), domain=common.domain({D_BATCH: 2, D0: 3})) + + shapes = jax.tree.map(lambda x: x.shape, field) + assert jax.tree.leaves(shapes) == [3] + assert jax.eval_shape(lambda f: f * 2.0, field).ndarray.shape == (3,) + # a field with an axis index as leaf, as `vmap` prefix for the batched field's buffer + axes = nd_array_field.NdArrayField(common.domain({D0: 3}), 0) + sums = jax.vmap(lambda f: f.ndarray.sum(), in_axes=(axes,))( + nd_array_field.NdArrayField(common.domain({D0: 3}), batched.ndarray) + ) + np.testing.assert_allclose(sums, [3.0, 3.0]) + + @pytest.mark.requires_jax def test_jax_traced_array_dispatch(): import jax From e90ef3b65161a86139b2c2894d2087460a521223 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 13:30:14 +0100 Subject: [PATCH 066/166] docs[next]: TODO on the order dependence of mixed-library operations --- src/gt4py/next/embedded/nd_array_field.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 51399d2aaa..8cbe505365 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -32,6 +32,8 @@ def _ops_of(*values: Any) -> array_ops.ArrayOps: + # TODO(havogt): the first field's array library decides, so mixing libraries depends on the + # order of the operands; reject mixed libraries or define a priority instead. for v in values: if isinstance(v, NdArrayField): return array_ops.of(v._ndarray) From 00c755b07237f11295e9187b5c16099cbf7828b3 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 13:30:14 +0100 Subject: [PATCH 067/166] docs[next]: say why ArrayOps.operand and setitem convert, and which libraries override them Also shorten the cache fill in elementwise_function. --- src/gt4py/next/embedded/array_ops.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 6b3ba72680..bb9b45815f 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -114,7 +114,10 @@ def operand(self, value: Any, like: core_defs.NDArrayObject) -> Any: Python scalars stay Python scalars, so they keep the weak typing of the standard. NumPy scalars become 0-d arrays of their dtype, which promotes like - NumPy does with NumPy scalars. + NumPy does with NumPy scalars. They reach fields of every library, since gt4py's + scalar types are NumPy's, but the standard does not accept them as operands. + Libraries that do (NumPy, CuPy, JAX) override this to keep them as they are, + which spares creating a 0-d array, on the device, per operation. """ if isinstance(value, np.generic): return self.asarray(value, dtype=type(value), like=like) @@ -125,8 +128,9 @@ def elementwise_function(self, name: str) -> Callable[..., Any]: try: return self._elementwise_function_cache[name] except KeyError: - func = self._elementwise_function_cache[name] = self._elementwise_function(name) - return func + return self._elementwise_function_cache.setdefault( + name, self._elementwise_function(name) + ) def _elementwise_function(self, name: str) -> Callable[..., Any]: if name == "where": @@ -164,9 +168,15 @@ def where(self, condition: Any, x: Any, y: Any) -> core_defs.NDArrayObject: def setitem( self, array: core_defs.NDArrayObject, key: common.RelativeIndexSequence, value: Any ) -> core_defs.NDArrayObject: - """Write `value` into `array[key]`; returns the array holding the result.""" + """ + Write `value` into `array[key]`; returns the array holding the result. + + The standard leaves assigning a value of another dtype, device or library + unspecified, so such values are converted to the array's first. Libraries that + cast on assignment (NumPy, CuPy) assign directly; JAX arrays are immutable and + need `.at[key].set(value)`. + """ if not isinstance(value, bool | int | float): - # the standard leaves assigning another dtype or device unspecified value = self.xp.asarray(value, device=self.device(array)) if value.dtype != array.dtype: value = self.xp.astype(value, array.dtype) From 59d5741ea7bf8f6a13433e2f6b81beb042406304 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 14:31:29 +0100 Subject: [PATCH 068/166] build: require numpy>=2.1, the first version whose from_dlpack takes device and copy The default ArrayOps.to_numpy no longer needs a fallback for NumPy 2.0. --- pyproject.toml | 2 +- src/gt4py/next/embedded/array_ops.py | 8 +------- uv.lock | 2 +- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6bcb6ead22..7a6f41aeab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -110,7 +110,7 @@ dependencies = [ 'mako>=1.3', 'nanobind>=1.9.0', 'ninja>=1.11', - 'numpy>=2.0.0 ; python_version < "3.14"', + 'numpy>=2.1.0 ; python_version < "3.14"', # first version whose `from_dlpack` takes `device` and `copy` 'numpy>=2.3.2 ; python_version >= "3.14"', # first version with pre-built wheel for Python 3.14 'ordered-set>=4.1.0', 'packaging>=24.2', diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index bb9b45815f..2d3d7bbf9d 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -34,10 +34,6 @@ from gt4py.next import common -# TODO(havogt): drop once gt4py requires NumPy >= 2.1, the first version whose `from_dlpack` -# takes `device` and `copy`; NumPy 2.0's `from_dlpack` cannot copy a non-CPU array to the host. -_NUMPY_FROM_DLPACK_TAKES_DEVICE: Final = np.lib.NumpyVersion(np.__version__) >= "2.1.0" - #: gt4py builtin and operator names whose Array API name differs. STANDARD_NAMES: Final[Mapping[str, str]] = { "neg": "negative", @@ -184,9 +180,7 @@ def setitem( return array def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: - if _NUMPY_FROM_DLPACK_TAKES_DEVICE: - return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete - return np.from_dlpack(array) # type: ignore[arg-type] # `NDArrayObject` typing is not complete + return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: return common.BufferInfo.from_ndarray(array) diff --git a/uv.lock b/uv.lock index 7d102718aa..c3c2b00305 100644 --- a/uv.lock +++ b/uv.lock @@ -1503,7 +1503,7 @@ requires-dist = [ { name = "mako", specifier = ">=1.3" }, { name = "nanobind", specifier = ">=1.9.0" }, { name = "ninja", specifier = ">=1.11" }, - { name = "numpy", marker = "python_full_version < '3.14'", specifier = ">=2.0.0" }, + { name = "numpy", marker = "python_full_version < '3.14'", specifier = ">=2.1.0" }, { name = "numpy", marker = "python_full_version >= '3.14'", specifier = ">=2.3.2" }, { name = "ordered-set", specifier = ">=4.1.0" }, { name = "packaging", specifier = ">=24.2" }, From 488ed1680bbebd28a8e651f56a06dbd90b3fb52e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 11 Nov 2026 18:09:38 +0100 Subject: [PATCH 069/166] refactor[next]: default ArrayOps.setitem accepts only arrays of its own library Assigning an array of another library into a field of a library without its own ArrayOps raises TypeError instead of converting it; NumPy scalars still become 0-d arrays and the dtype is still cast. NumPy, CuPy and JAX keep main's behaviour. A TODO asks for coherent conversion rules when values of different array libraries meet. --- src/gt4py/next/embedded/array_ops.py | 24 +++++++++++++------ .../embedded_tests/test_nd_array_field.py | 13 ++++++++++ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 2d3d7bbf9d..b8c39a031c 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -55,6 +55,8 @@ } +# TODO(havogt): Redesign coherent conversion rules when arrays/scalars of different array +# libraries are used together. class ArrayOps: """ Operations on the buffers of embedded fields for one array namespace. @@ -167,15 +169,23 @@ def setitem( """ Write `value` into `array[key]`; returns the array holding the result. - The standard leaves assigning a value of another dtype, device or library - unspecified, so such values are converted to the array's first. Libraries that - cast on assignment (NumPy, CuPy) assign directly; JAX arrays are immutable and - need `.at[key].set(value)`. + `value` is a Python scalar, a NumPy scalar (gt4py's scalar types are NumPy's) + or an array of the same library as `array`; arrays of other libraries raise + `TypeError`. The standard leaves assigning a value of another dtype unspecified, + so it is cast to the dtype of `array` first. Libraries that cast on assignment + (NumPy, CuPy) assign directly; JAX arrays are immutable and need + `.at[key].set(value)`. """ - if not isinstance(value, bool | int | float): + if isinstance(value, np.generic): value = self.xp.asarray(value, device=self.device(array)) - if value.dtype != array.dtype: - value = self.xp.astype(value, array.dtype) + elif not isinstance(value, bool | int | float): + if array_api_compat.array_namespace(value) is not self.xp: + raise TypeError( + f"Cannot assign an array of '{type(value).__module__}' to an array of" + f" '{self.xp.__name__}'." + ) + if not isinstance(value, bool | int | float) and value.dtype != array.dtype: + value = self.xp.astype(value, array.dtype) array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 1114bbcba3..2c9238452c 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -11,6 +11,7 @@ import pickle from typing import Callable, Iterable, Optional +import array_api_strict import numpy as np import pytest @@ -1359,6 +1360,8 @@ def test_setitem_array_libraries(nd_array_implementation, index, source, make_va value = make_value(xp, source) if is_cupy(xp) and isinstance(value, np.ndarray): pytest.skip("CuPy does not assign a non-scalar NumPy array.") + if is_array_api_strict(xp) and isinstance(value, np.ndarray): + pytest.skip("Assigning an array of another library is tested separately.") field = common._field( asarray(xp, np.arange(100).reshape(10, 10), dtype=np.float64), domain=common.Domain(dims=(D0, D1), ranges=(UnitRange(0, 10), UnitRange(0, 10))), @@ -1386,6 +1389,16 @@ def test_astype_c_type_alias(nd_array_implementation, c_type, expected): assert np.array_equal(result.asnumpy(), np.asarray([1, 2], dtype=expected)) +def test_setitem_array_of_other_library_raises(): + field = common._field( + asarray(array_api_strict, np.arange(3), dtype=np.float64), + domain=common.Domain(NamedRange(D0, UnitRange(0, 3))), + ) + + with pytest.raises(TypeError, match="Cannot assign an array of 'numpy'"): + field[...] = np.ones(3) + + def test_setitem_wrong_domain(): field = common._field( np.arange(100).reshape(10, 10), From 2fe6c07923b9e544df97716ba38a73a55fbda9a0 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 12 Nov 2026 20:33:58 +0100 Subject: [PATCH 070/166] refactor[next]: drop the identity entry 'pow' from STANDARD_NAMES --- src/gt4py/next/embedded/array_ops.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index b8c39a031c..227263b70a 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -43,7 +43,6 @@ "div": "divide", "floordiv": "floor_divide", "power": "pow", - "pow": "pow", "mod": "remainder", "invert": "logical_not", "arcsin": "asin", From 2f19b7737a4f856da932e312f6bfd783b1a1464b Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 12 Nov 2026 20:37:10 +0100 Subject: [PATCH 071/166] refactor[next]: one table of builtin implementations instead of a per-class registry FieldBuiltinFuncRegistry kept a ChainMap of registries per Field subclass; NdArrayField was its only user and now has no subclasses that register builtins. NdArrayField.__gt_builtin_func__ looks the builtin up in a module-level dict instead, and the mixin is removed from common. --- src/gt4py/next/common.py | 37 ------------------- .../next/embedded/array_libraries/jax_ops.py | 4 +- src/gt4py/next/embedded/nd_array_field.py | 15 +++++--- 3 files changed, 12 insertions(+), 44 deletions(-) diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index 5bc53f6474..2384078271 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -9,7 +9,6 @@ from __future__ import annotations import abc -import collections import dataclasses import enum import functools @@ -1399,42 +1398,6 @@ def promote_dims(*dims_list: Sequence[Dimension]) -> list[Dimension]: return promoted_dims -class FieldBuiltinFuncRegistry: - """ - Mixin for adding `fbuiltins` registry to a `Field`. - - Subclasses of a `Field` with `FieldBuiltinFuncRegistry` get their own registry, - dispatching (via ChainMap) to its parent's registries. - """ - - _builtin_func_map: collections.ChainMap[fbuiltins.BuiltInFunction, Callable] = ( - collections.ChainMap() - ) - - def __init_subclass__(cls, **kwargs: Any) -> None: - cls._builtin_func_map = collections.ChainMap( - {}, # New empty `dict` for new registrations on this class - *[ - c.__dict__["_builtin_func_map"].maps[0] # adding parent `dict`s in mro order - for c in cls.__mro__ - if "_builtin_func_map" in c.__dict__ - ], - ) - - @classmethod - def register_builtin_func( - cls, /, op: fbuiltins.BuiltInFunction[_R, _P], op_func: Optional[Callable[_P, _R]] = None - ) -> Any: - assert op not in cls._builtin_func_map - if op_func is None: # when used as a decorator - return functools.partial(cls.register_builtin_func, op) - return cls._builtin_func_map.setdefault(op, op_func) - - @classmethod - def __gt_builtin_func__(cls, /, func: fbuiltins.BuiltInFunction[_R, _P]) -> Callable[_P, _R]: - return cls._builtin_func_map.get(func, NotImplemented) - - #: Numeric value used to represent missing values in connectivities. #: Equivalent to the `_FillValue` attribute in the UGRID Conventions #: (see: http://ugrid-conventions.github.io/ugrid-conventions/). diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 440198cb50..93aef35b1d 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -66,11 +66,11 @@ def _flatten_field( def _unflatten_field( domain: common.Domain, children: tuple[core_defs.NDArrayObject] ) -> nd_array_field.NdArrayField: - return nd_array_field.NdArrayField(domain, children[0]) # type: ignore[abstract] # mypy does not see '__gt_builtin_func__' as implemented by 'FieldBuiltinFuncRegistry' + return nd_array_field.NdArrayField(domain, children[0]) jax.tree_util.register_pytree_node( - nd_array_field.NdArrayField, # type: ignore[type-abstract, unused-ignore] # only reported when 'jax' is installed, see '_unflatten_field' + nd_array_field.NdArrayField, _flatten_field, _unflatten_field, ) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 8cbe505365..b5f5693040 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -100,10 +100,7 @@ def _asarray( @dataclasses.dataclass(frozen=True) -class NdArrayField( - common.MutableField[common.DimsT, core_defs.ScalarT], - common.FieldBuiltinFuncRegistry, -): +class NdArrayField(common.MutableField[common.DimsT, core_defs.ScalarT]): """ Field backed by an array of any Array API compatible library. @@ -121,6 +118,10 @@ def array_ns(self) -> ModuleType: # own module; users comparing it to `numpy` should query the device instead. return array_ops.of(self._ndarray).array_ns + @classmethod + def __gt_builtin_func__(cls, /, func: fbuiltins.BuiltInFunction[_R, _P]) -> Callable[_P, _R]: + return _builtin_implementations.get(func, NotImplemented) + def __getstate__(self) -> dict[str, Any]: # Serialize only the dataclass fields, excluding cached properties # stored in `__dict__` (which may not be picklable). @@ -710,6 +711,9 @@ def _hyperslice( # -- Specialized implementations for builtin operations on array fields -- +_builtin_implementations: dict[fbuiltins.BuiltInFunction, Callable[..., Any]] = {} + + def _register_builtin(builtin: fbuiltins.BuiltInFunction, impl: Callable[..., Any]) -> None: """Register `impl` for `builtin`, unless the `ArrayOps` of the first field argument replaces it.""" @@ -717,7 +721,8 @@ def dispatch(*args: Any, **kwargs: Any) -> Any: return _ops_of(*args).builtin_overrides.get(builtin, impl)(*args, **kwargs) dispatch.__name__ = getattr(impl, "__name__", builtin.name) - NdArrayField.register_builtin_func(builtin, dispatch) + assert builtin not in _builtin_implementations + _builtin_implementations[builtin] = dispatch _register_builtin( From d619b2bfff7779b4301805f9ed0f44f7491f90eb Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 13 Nov 2026 10:05:51 +0100 Subject: [PATCH 072/166] fix[next]: make the static slot of a connectivity keyword-only A positional slot after the dataclass fields let subclasses take an extra positional argument, e.g. a digest for the compile-time connectivity. --- src/gt4py/next/embedded/array_libraries/jax_ops.py | 4 +++- src/gt4py/next/embedded/nd_array_field.py | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 8681a42547..fdc35e8354 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -204,7 +204,9 @@ def _unflatten_connectivity( # not only for tracers: jax compares the aux data of the branches of `lax.cond` and of # the carry of `lax.scan` on trees it rebuilds around other placeholders static = _StaticTable(static.values, table) - return nd_array_field.NdArrayConnectivityField(domain, table, codomain, skip_value, static) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' + return nd_array_field.NdArrayConnectivityField( + domain, table, codomain, skip_value, _static=static + ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' # jax registers pytree nodes by exact type, so the connectivity needs its own registration diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index a7d8ed5bcb..710c583379 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -454,6 +454,7 @@ class NdArrayConnectivityField( #: stored for the `ArrayOps` of the table, which passes it to its table operations _static: Any = dataclasses.field( default=None, + kw_only=True, compare=False, repr=False, metadata=utils.gt4py_metadata(fingerprint=False), @@ -535,7 +536,7 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: self._ndarray, buffer_slice, static=self._static ) restricted_connectivity = self.__class__( - new_domain, table, self.codomain, self.skip_value, static + new_domain, table, self.codomain, self.skip_value, _static=static ) self._cache[cache_key] = restricted_connectivity From 5897fd1cb5e7721d2f411b1fa099625c64f109bf Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 13 Nov 2026 11:17:00 +0100 Subject: [PATCH 073/166] docs[next]: say why NumPy dtypes are identified by kind and size --- src/gt4py/_core/ndarray_utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gt4py/_core/ndarray_utils.py b/src/gt4py/_core/ndarray_utils.py index f485d8d123..c8b52c9bdb 100644 --- a/src/gt4py/_core/ndarray_utils.py +++ b/src/gt4py/_core/ndarray_utils.py @@ -114,8 +114,8 @@ def array_namespace(array: core_defs.NDArrayObject) -> ArrayNamespace: @functools.cache def _numpy_scalar_type(dtype: np.dtype) -> type[np.generic]: - # NumPy, CuPy and JAX describe dtypes as `np.dtype`, and its `type` depends on byte order - # and C type name (e.g. `np.longlong` is not `np.int64`); kind and size identify it + # `dtype.type` is the scalar type of the dtype's C type, e.g. `np.longlong` for an int64 + # array on Linux, which is not `np.int64`; kind and size identify the gt4py type return np.dtype(f"{dtype.kind}{dtype.itemsize}").type From 881a685315b0fb258504a79bb8a709347c2c1a40 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 13 Nov 2026 12:01:04 +0100 Subject: [PATCH 074/166] refactor[next]: ArrayOps as a frozen dataclass ArrayOps is defined by its namespace 'xp' and only caches looked-up elementwise functions; the cache is a field excluded from init, repr and comparison. The subclasses add no state. --- src/gt4py/next/embedded/array_ops.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 227263b70a..118b005a70 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -22,6 +22,7 @@ from __future__ import annotations +import dataclasses from collections.abc import Callable, Mapping from types import ModuleType from typing import Any, ClassVar, Final @@ -56,6 +57,7 @@ # TODO(havogt): Redesign coherent conversion rules when arrays/scalars of different array # libraries are used together. +@dataclasses.dataclass(frozen=True) class ArrayOps: """ Operations on the buffers of embedded fields for one array namespace. @@ -69,10 +71,9 @@ class ArrayOps: builtin_overrides: ClassVar[Mapping[Any, Callable[..., Any]]] = {} xp: ModuleType - - def __init__(self, xp: ModuleType) -> None: - self.xp = xp - self._elementwise_function_cache: dict[str, Callable[..., Any]] = {} + _elementwise_function_cache: dict[str, Callable[..., Any]] = dataclasses.field( + default_factory=dict, init=False, repr=False, compare=False + ) def __repr__(self) -> str: return f"{type(self).__name__}({self.xp.__name__})" From 309c3ab2fd1e61435b1100470c400cb2504403ce Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 13 Nov 2026 12:14:09 +0100 Subject: [PATCH 075/166] refactor[next]: canonicalize NumPy dtypes separately from taking their scalar type --- src/gt4py/_core/ndarray_utils.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/gt4py/_core/ndarray_utils.py b/src/gt4py/_core/ndarray_utils.py index c8b52c9bdb..30785dac6c 100644 --- a/src/gt4py/_core/ndarray_utils.py +++ b/src/gt4py/_core/ndarray_utils.py @@ -113,10 +113,9 @@ def array_namespace(array: core_defs.NDArrayObject) -> ArrayNamespace: @functools.cache -def _numpy_scalar_type(dtype: np.dtype) -> type[np.generic]: - # `dtype.type` is the scalar type of the dtype's C type, e.g. `np.longlong` for an int64 - # array on Linux, which is not `np.int64`; kind and size identify the gt4py type - return np.dtype(f"{dtype.kind}{dtype.itemsize}").type +def _canonicalize_numpy_dtype(dtype: np.dtype) -> np.dtype: + # dtypes named by C type map to distinct scalar types, e.g. `np.longlong` for int64 on Linux + return np.dtype(f"{dtype.kind}{dtype.itemsize}") @functools.cache @@ -134,7 +133,7 @@ def _dtype_tables( def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar]) -> _ArrayDType: """The dtype object of `array_ns` for the gt4py scalar type `scalar_type`.""" key: type = ( - _numpy_scalar_type(np.dtype(scalar_type)) + _canonicalize_numpy_dtype(np.dtype(scalar_type)).type if issubclass(scalar_type, np.generic) else scalar_type ) @@ -147,7 +146,7 @@ def namespace_dtype(array_ns: ArrayNamespace, scalar_type: type[core_defs.Scalar def scalar_type(array_ns: ArrayNamespace, dtype: _ArrayDType) -> type[core_defs.Scalar]: """The gt4py scalar type of the arrays of `array_ns` with dtype `dtype`.""" result = ( - _numpy_scalar_type(dtype) + _canonicalize_numpy_dtype(dtype).type if isinstance(dtype, np.dtype) else _dtype_tables(array_ns)[1].get(dtype) ) From 4d37585c4d794ed4ee42371671fc92574fd8cdf9 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 13 Nov 2026 14:50:06 +0100 Subject: [PATCH 076/166] refactor[next]: connectivity caches without arrays, clamping gather in ArrayOps A connectivity caches domains and slices only, and 'restrict' builds its result on every call with the cache of its part. A cached restricted connectivity held a tracer of the trace it was first used in, so a traced connectivity closed over by the branches of 'lax.cond', a 'lax.scan' body or an inner 'jit' raised 'UnexpectedTracerError'. 'ArrayOps.gather' replaces 'gather_index'. 'JaxOps' gathers with 'mode="clip", wrap_negative_indices=False', which needs no knowledge of the table an index came from. 'restrict_table' returns the table only: the '_static' of a connectivity is created by the library and passed on by 'restrict', and 'JaxOps' finds the values of a restricted tracer in it. Under JAX, flattening rejects NumPy and CuPy tables, and unflattening no longer attaches static values to a concrete table. --- .../next/embedded/array_libraries/jax_ops.py | 146 ++++++++++++------ src/gt4py/next/embedded/array_ops.py | 27 ++-- src/gt4py/next/embedded/nd_array_field.py | 39 ++--- .../embedded_tests/test_nd_array_field.py | 140 +++++++++++++++-- 4 files changed, 256 insertions(+), 96 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 47cc1a1e6a..6cd8815da7 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -14,14 +14,15 @@ `_values`: - concrete: operations reading its values run under `jax.ensure_compile_time_eval`; -- a tracer standing for a concrete table, which it got as a pytree leaf: the - values are read from that table, kept in a `_StaticTable`; -- a tracer computed inside the trace: there are no values, all its targets are - assumed to be in range and the gather clamps them. +- a tracer standing for a concrete table, which it got as a pytree leaf, or + restricted from such a tracer: the values are read from `_StaticValues`; +- any other tracer: there are no values, all its targets are assumed to be in + range and the gather clamps them. """ from __future__ import annotations +import weakref from collections.abc import Callable, Mapping from typing import Any, ClassVar, Optional, TypeAlias @@ -36,22 +37,33 @@ from gt4py.next.ffront import experimental, fbuiltins -class _StaticTable: - """ - The concrete array `values` holding the values of `table`, a placeholder of a trace. +class _WeakIdDict: + """Values for objects which are found by identity and referenced weakly.""" - It is also the pytree aux data of a connectivity, without `table`: two are equal - if their values are the same array. - """ + __slots__ = ("_items",) + + def __init__(self) -> None: + self._items: dict[int, tuple[weakref.ref, Any]] = {} + + def __setitem__(self, obj: Any, value: Any) -> None: + key = id(obj) + self._items[key] = (weakref.ref(obj, lambda _: self._items.pop(key, None)), value) + + def get(self, obj: Any) -> Any: + ref, value = self._items.get(id(obj), (None, None)) + return value if ref is not None and ref() is obj else None - __slots__ = ("table", "values") - def __init__(self, values: core_defs.NDArrayObject, table: Any = None) -> None: +class _TableIdentity: + """Pytree aux data of a connectivity: equal if `values` is the same array.""" + + __slots__ = ("values",) + + def __init__(self, values: core_defs.NDArrayObject) -> None: self.values = values - self.table = table def __eq__(self, other: object) -> bool: - return isinstance(other, _StaticTable) and self.values is other.values + return isinstance(other, _TableIdentity) and self.values is other.values def __hash__(self) -> int: return id(self.values) @@ -60,16 +72,53 @@ def __repr__(self) -> str: return f"" +class _StaticValues: + """ + The concrete values of `table`, a placeholder of a trace, and of the tables restricted from it. + + Tables are found by identity, so any other table has no values here. + """ + + __slots__ = ("_restricted", "table", "values") + + def __init__(self, values: core_defs.NDArrayObject, table: Any) -> None: + self.values = values + self.table = table + # weak: a restricted table may belong to a trace which ends before the one of `table` + self._restricted = _WeakIdDict() + + def add_restricted(self, table: Any, values: core_defs.NDArrayObject) -> None: + self._restricted[table] = values + + def get(self, table: Any) -> Optional[core_defs.NDArrayObject]: + return self.values if table is self.table else self._restricted.get(table) + + def _has_values(table: Any) -> bool: - return isinstance(table, np.ndarray | jax.Array) and not isinstance(table, jax.core.Tracer) + return isinstance(table, jax.Array) and not isinstance(table, jax.core.Tracer) -def _values(table: Any, static: Optional[_StaticTable]) -> Optional[core_defs.NDArrayObject]: +def _values(table: Any, static: Optional[_StaticValues]) -> Optional[core_defs.NDArrayObject]: """Return the concrete array with the values of `table`, `None` if they exist only at run time.""" if _has_values(table): return table - # a connectivity copied with another table still carries the `static` of the old one - return static.values if static is not None and static.table is table else None + return None if static is None else static.get(table) + + +#: per concrete table, its restrictions by key: restricting the same table again returns the same +#: array, which the pytree aux data identifies +_restricted_values = _WeakIdDict() + + +def _restrict_values( + values: core_defs.NDArrayObject, key: common.RelativeIndexSequence +) -> core_defs.NDArrayObject: + if (by_key := _restricted_values.get(values)) is None: + by_key = _restricted_values[values] = {} + if (restricted := by_key.get(key)) is None: + with jax.ensure_compile_time_eval(): + restricted = by_key[key] = values[key] + return restricted def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: @@ -104,44 +153,37 @@ def hyperslice( image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, *, - static: Optional[_StaticTable] = None, + static: Optional[_StaticValues] = None, ) -> Optional[tuple[slice, ...]]: values = _values(table, static) if values is None: return (slice(None),) * table.ndim - if values is not table: - return array_ops.of(values).hyperslice(values, image_range, skip_value) with jax.ensure_compile_time_eval(): - return super().hyperslice(table, image_range, skip_value) + return super().hyperslice(values, image_range, skip_value) def restrict_table( self, table: core_defs.NDArrayObject, key: common.RelativeIndexSequence, *, - static: Optional[_StaticTable] = None, - ) -> tuple[core_defs.NDArrayObject, Optional[_StaticTable]]: + static: Optional[_StaticValues] = None, + ) -> core_defs.NDArrayObject: values = _values(table, static) - if values is table: - with jax.ensure_compile_time_eval(): - return super().restrict_table(table, key) - restricted, _ = super().restrict_table(table, key) if values is None: - return restricted, None - restricted_values, _ = array_ops.of(values).restrict_table(values, key) - return restricted, _StaticTable(restricted_values, restricted) - - def gather_index( - self, - index: core_defs.NDArrayObject, - size: int, - table: core_defs.NDArrayObject, - *, - static: Optional[_StaticTable] = None, + return super().restrict_table(table, key) + restricted_values = _restrict_values(values, key) + if values is table: + return restricted_values + assert static is not None + restricted = super().restrict_table(table, key) + static.add_restricted(restricted, restricted_values) + return restricted + + def gather( + self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: - if _values(table, static) is None: - return jax.numpy.clip(index, 0, size - 1) # type: ignore[arg-type, return-value, unused-ignore] # `NDArrayObject` typing is not complete - return index + # an index from a table without values may be out of range: it is clamped, at both ends + return array.at[indices].get(mode="clip", wrap_negative_indices=False) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.asarray(array) @@ -181,7 +223,7 @@ def _unflatten_field( _ConnectivityAuxData: TypeAlias = tuple[ - common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_StaticTable] + common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_TableIdentity] ] @@ -189,24 +231,30 @@ def _flatten_connectivity( connectivity: nd_array_field.NdArrayConnectivityField, ) -> tuple[tuple[core_defs.NDArrayObject], _ConnectivityAuxData]: table = connectivity._ndarray + # the aux data identifies the values of a table by its buffer, which a mutable array does not + # allow. The placeholders of JAX are array API objects too, so "not a JAX array" is no test. + assert not (array_api_compat.is_numpy_array(table) or array_api_compat.is_cupy_array(table)), ( + f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(table)}'." + ) values = _values(table, connectivity._static) return (table,), ( connectivity.domain, connectivity.codomain, connectivity.skip_value, - None if values is None else _StaticTable(values), + None if values is None else _TableIdentity(values), ) def _unflatten_connectivity( aux_data: _ConnectivityAuxData, children: tuple[core_defs.NDArrayObject] ) -> nd_array_field.NdArrayConnectivityField: - domain, codomain, skip_value, static = aux_data + domain, codomain, skip_value, identity = aux_data (table,) = children - if static is not None: - # not only for tracers: jax compares the aux data of the branches of `lax.cond` and of - # the carry of `lax.scan` on trees it rebuilds around other placeholders - static = _StaticTable(static.values, table) + # a child without values stands for the flattened table: a tracer, or one of the placeholders + # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around + static = ( + None if identity is None or _has_values(table) else _StaticValues(identity.values, table) + ) return nd_array_field.NdArrayConnectivityField( domain, table, codomain, skip_value, _static=static ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 76addbba65..8be333916a 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -189,9 +189,8 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array - # The operations on a connectivity table which depend on its values. `static` belongs to - # the library and is stored by the connectivity next to its table: `None`, unless the - # library's arrays can be placeholders without values and it keeps a stand-in for them. + # The operations on a connectivity table. `static` is what the connectivity holds for the + # library of its table: `None`, unless the library created the connectivity with one. def hyperslice( self, @@ -214,6 +213,9 @@ def hyperslice( skip_value = -1 would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. + + A library which cannot read the values of `table` returns all of it. What an entry + outside of `image_range` reads is then defined by its `gather`. """ xp = self.xp select_mask = (table >= image_range.start) & (table < image_range.stop) @@ -242,20 +244,15 @@ def restrict_table( key: common.RelativeIndexSequence, *, static: Any = None, - ) -> tuple[core_defs.NDArrayObject, Any]: - """Return `table[key]` and its `static`.""" - return self.asarray(table[key]), None + ) -> core_defs.NDArrayObject: + """Return `table[key]`.""" + return self.asarray(table[key]) - def gather_index( - self, - index: core_defs.NDArrayObject, - size: int, - table: core_defs.NDArrayObject, - *, - static: Any = None, + def gather( + self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: - """Return the indices a gather reads from an axis of `size` elements for `index`, which was computed from `table`.""" - return index + """Return `array[indices]` for one integer index array per axis, all of the same shape.""" + return array[indices] def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 6eececf92e..65844b0102 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -454,7 +454,7 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: stored for the `ArrayOps` of the table, which passes it to its table operations + #: created by the library of the table, for its `ArrayOps`; `restrict` passes it on as it is _static: Any = dataclasses.field( default=None, kw_only=True, @@ -514,7 +514,7 @@ def __setitem__( raise TypeError("'Connectivity' does not support item assignment.") def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: - cache_key = hash((id(self.ndarray), self.domain, image_range)) + cache_key = ("inverse_image", image_range) if (new_domain := self._cache.get(cache_key, None)) is None: assert common.UnitRange.is_finite(image_range) @@ -531,18 +531,18 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: return new_domain def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: - cache_key = (id(self.ndarray), self.domain, index) - - if (restricted_connectivity := self._cache.get(cache_key, None)) is None: - new_domain, buffer_slice = self._slice(index) - table, static = array_ops.of(self._ndarray).restrict_table( - self._ndarray, buffer_slice, static=self._static - ) - restricted_connectivity = self.__class__( - new_domain, table, self.codomain, self.skip_value, _static=static - ) - self._cache[cache_key] = restricted_connectivity - + # no array is cached: whether a restricted table can be used again is up to its library + cache_key = ("restrict", index) + if (cached := self._cache.get(cache_key, None)) is None: + cached = self._cache[cache_key] = (*self._slice(index), {}) + new_domain, buffer_slice, restricted_cache = cached + table = array_ops.of(self._ndarray).restrict_table( + self._ndarray, buffer_slice, static=self._static + ) + restricted_connectivity = self.__class__( + new_domain, table, self.codomain, self.skip_value, _static=self._static + ) + restricted_connectivity.__dict__["_cache"] = restricted_cache return restricted_connectivity __getitem__ = restrict @@ -609,17 +609,12 @@ def take_index(dim: common.Dimension) -> core_defs.NDArrayObject: start = data.domain[dim].unit_range.start if (conn := conn_by_codomain.get(dim)) is None: return _identity_index_array(new_domain, dim, ops, like=data._ndarray) - start - # skip entries read the domain start instead of wrapping around to an arbitrary element; - # what is gathered there, and its cotangent, is left to the reduction mask to discard - assert isinstance(conn, NdArrayConnectivityField) - index = ( + # a skip value is no index of the field: these entries read the domain start + return ( _connectivity_index_array(conn, new_domain, ops, skip_value_replacement=start) - start ) - return array_ops.of(conn._ndarray).gather_index( - index, len(data.domain[dim].unit_range), conn._ndarray, static=conn._static - ) - new_buffer = data._ndarray[tuple(take_index(dim) for dim in data.domain.dims)] + new_buffer = ops.gather(data._ndarray, tuple(take_index(dim) for dim in data.domain.dims)) return data.__class__.from_array(new_buffer, domain=new_domain, dtype=data.dtype) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index d5086721b6..7d0156c946 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2309,6 +2309,10 @@ def premap(field, conn): ) assert traces == 2 + premap(field, conn[NamedIndex(E2VDim, 0)]) + premap(field, conn[NamedIndex(E2VDim, 0)]) + assert traces == 3 + @pytest.mark.requires_jax def test_jax_jit_premap_non_contiguous_inverse_image_raises(): @@ -2513,20 +2517,136 @@ def premap_next(field, conn): np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0, 30.0, 30.0]) +def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + conn = common._connectivity( + np.asarray([[0, 1], [1, 2], [2, 3]]), + codomain=V, + domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + ) + field = common._field(np.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) + calls = 0 + hyperslice = array_ops.ArrayOps.hyperslice + + def counting_hyperslice(*args, **kwargs): + nonlocal calls + calls += 1 + return hyperslice(*args, **kwargs) + + monkeypatch.setattr(array_ops.ArrayOps, "hyperslice", counting_hyperslice) + + for _ in range(3): + result = field.premap(conn[NamedIndex(E2VDim, 0)]) + + assert calls == 1 + assert result.domain == common.domain({E: (0, 2)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_clamps_in_the_gather(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + def premap(field, table): + return field.premap(dataclasses.replace(conn_a, _ndarray=table)) + + # targets -2, -1, 0, 1, 3 of a field on V:(1,4) + table = conn_a.ndarray - 2 + result = jax.jit(premap)(field, table) + + assert result.domain == common.domain({E: (0, 5)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 10.0, 10.0, 30.0]) + for lowered in ( + jax.jit(premap).lower(field, table).as_text(), + jax.jit(lambda field, conn: field.premap(conn)).lower(field, conn_a).as_text(), + ): + assert "stablehlo.gather" in lowered + assert not re.search(r"stablehlo\.(clamp|minimum|maximum|select)", lowered) + + @pytest.mark.requires_jax -def test_jax_jit_premap_clamps_only_tables_without_values(monkeypatch): +@pytest.mark.parametrize("predicate, factor", [(True, 1.0), (False, 2.0)]) +def test_jax_jit_premap_in_cond_branches_closing_over_connectivity(predicate, factor): import jax _, field, conn_a, _ = _jax_narrowing_setup() - clip = jax.numpy.clip - clipped = [] - monkeypatch.setattr(jax.numpy, "clip", lambda *args: clipped.append(args) or clip(*args)) - jax.jit(lambda field, conn: field.premap(conn))(field, conn_a) - jax.jit(lambda field: field.premap(conn_a))(field) - assert not clipped + def premap_in_branches(predicate, field, conn): + return jax.lax.cond( + predicate, + lambda: field.premap(conn).ndarray * 1.0, + lambda: field.premap(conn).ndarray * 2.0, + ) + + result = jax.jit(premap_in_branches)(predicate, field, conn_a) + + np.testing.assert_array_equal(result, np.asarray([10.0, 20.0, 30.0]) * factor) + - jax.jit(lambda field, table: field.premap(dataclasses.replace(conn_a, _ndarray=table)))( - field, conn_a.ndarray +@pytest.mark.requires_jax +def test_jax_jit_premap_in_nested_jit_closing_over_connectivity(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + def premap_twice(field, conn): + inner = jax.jit(lambda field: field.premap(conn))(field) + return inner, field.premap(conn) + + for result in jax.jit(premap_twice)(field, conn_a): + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_in_scan_body_closing_over_connectivity(): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + + def premap_in_scan(field, conn): + def body(carry, _): + return carry + field.premap(conn).ndarray, None + + total, _ = jax.lax.scan(body, jax.numpy.zeros(3), jax.numpy.arange(2)) + return total + field.premap(conn).ndarray + + result = jax.jit(premap_in_scan)(field, conn_a) + + np.testing.assert_array_equal(result, [30.0, 60.0, 90.0]) + + +@pytest.mark.requires_jax +def test_jax_pytree_rejects_connectivities_of_other_libraries(): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + numpy_conn = common._connectivity( + np.asarray([0, 1, 2, 3, 5], dtype=np.int32), codomain=conn_a.codomain, domain=conn_a.domain ) - assert len(clipped) == 1 + + with pytest.raises(AssertionError, match="Only connectivities of JAX arrays"): + jax.jit(lambda field, conn: field.premap(conn))(field, numpy_conn) + + # not a pytree leaf, so it is not flattened + result = jax.jit(lambda field: field.premap(numpy_conn))(field) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_pytree_of_concrete_connectivity_has_no_static(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + rebuilt = jax.tree.map(lambda table: table + 1, conn_a) + + assert rebuilt._static is None + # targets 1, 2, 3, 4, 6 of a field on V:(1,4) + result = field.premap(rebuilt) + assert result.domain == common.domain({E: (0, 3)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) From beed38f438d4536e944e2198c5b0a3dfe9a00ff2 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 13 Nov 2026 14:50:06 +0100 Subject: [PATCH 077/166] docs[next]: ADR 0029 for the gather, the caches and the pytree rules Also states that a neighbor reduction takes its table from the offset provider, which has to be built inside the jitted function for the table to stay a runtime argument. --- .../0029-Connectivities_Under_JAX_Tracing.md | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 9a61ac5752..0841127ebc 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -7,7 +7,7 @@ tags: [embedded, jax, connectivities] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) - **Created**: 2026-11-06 -- **Updated**: 2026-11-10 +- **Updated**: 2026-11-13 In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to pass the concrete table along with its tracer through the pytree aux data of the connectivity, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime. @@ -22,17 +22,21 @@ Narrowing is the common case: the field usually covers only part of the connecti ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The three operations that depend on the values of a table are methods of `ArrayOps`: `hyperslice` (domain inference), `restrict_table` and `gather_index`. Their defaults are plain array code. `JaxOps` overrides them, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations on a table are methods of `ArrayOps`: `hyperslice` (domain inference), `restrict_table` and `gather`. Their defaults are plain array code. `JaxOps` overrides them, and everything that knows about tracing is in `jax_ops.py`. -A connectivity stores one opaque value for its `ArrayOps`, `_static`, and hands it to these methods. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, together with the tracer they belong to. A connectivity that got another table, for example through `dataclasses.replace`, does not match its `_static` any more and is treated as having none. +A connectivity stores one opaque value for its `ArrayOps`, `_static`, and hands it to `hyperslice` and `restrict_table`. Only the library creates it, and `restrict` passes it on unchanged. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, for that tracer and for the tracers restricted from it. Tables are looked up by identity, so a connectivity that got another table, for example through `dataclasses.replace`, has none. -The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with matching `_static`. Unflattening attaches them to the new child, whatever it is; a concrete child does not need them. +`JaxOps.gather` clamps indices to the field at both ends, inside the gather. It does not need to know where an index came from. + +The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with static values. Unflattening attaches them to a child that is not a concrete array; a concrete child has its own values. Because identity only stands for the values of an immutable array, flattening rejects a connectivity with a NumPy or CuPy table: such a connectivity can be closed over, but not passed as a `jit` argument. + +A connectivity caches domains and slices, never tables or restricted connectivities, so nothing cached can belong to a trace that has ended. `JaxOps` returns the same array when the same concrete table is restricted again with the same slice, which keeps a restricted connectivity from retracing. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: -- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. +- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function; a provider set outside inlines the table as a constant for the reduction. - **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`, because the operations on it run under `jax.ensure_compile_time_eval()`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). -- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field, or any other table that is a tracer without static values). No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clips its indices to the field. +- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field, or any other table that is a tracer without static values). No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the clamp of the gather decides what an out-of-range target reads. A tracer of any jax transformation counts as traced, not only one of `jit`. In particular a table that depends on a `vmap`ped value has no values even when `vmap` is called eagerly, because it differs per batch element. @@ -43,15 +47,19 @@ The aux data claims that the child has the static values. Where jax rebuilds a p - At the entry of `jit`, of a nested `jit`, and for the operands of `lax.cond`, the new tracer stands for the flattened table. - `lax.cond` and `lax.switch` require all branches to return the same aux data, and `lax.scan`, `lax.while_loop` and `lax.fori_loop` require the carry to keep its aux data. Selecting between two tables, changing the table of a carried connectivity, or mixing a table that has static values with one computed in the trace raises jax's `TypeError` about differing pytree structure. The same table on all branches, or an unchanged carry, keeps its static values. -For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to every child. +For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to every child that is not a concrete array. + +A traced connectivity can also be closed over by the branches of `lax.cond`, the body of `lax.scan` or an inner `jit`, and used again afterwards. ## Consequences - Domains under `jit` match eager execution when the table is concrete or has static values. - A table computed from traced values behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. -- The clamp is only partly redundant with jax's own indexing, which clamps indices past the end but wraps negative ones as NumPy does. It compiles to an extra clamp next to the select jax emits for negative indices. A gather with `mode="clip", wrap_negative_indices=False` clamps both ends with no extra operations; whether that makes jax code faster is still to be investigated. +- Every gather of a jax field uses `mode="clip", wrap_negative_indices=False`. That clamps both ends with no operation besides the gather, where jax's default indexing clamps past the end but emits a select to wrap negative indices. With a table that has values the clamp never acts. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. -- Connectivities reject item assignment, because their domain lookups are cached per buffer. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. +- Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. +- `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. +- The restrictions of a concrete jax table are kept for as long as the table is alive. - Domain inference on static values is cached on the connectivity object, which is new in every trace, so it is repeated per trace but not per call. Open questions, all caused by the static values in the aux data: From e0956b638dff3810ff90a3d569108a472f08a5ba Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 13 Nov 2026 17:52:02 +0100 Subject: [PATCH 078/166] build: require jax>=0.7.0, the first version whose indexed get takes wrap_negative_indices --- pyproject.toml | 4 ++-- uv.lock | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 7a6f41aeab..5e3c7b8873 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -148,10 +148,10 @@ cartesian = ['black>=25.11', 'clang-format>=18.1', 'gt4py[jax,standard,testing]' cuda12 = ['cupy-cuda12x>=12.0'] cuda13 = ['cupy-cuda13x>=14.0'] jax = [ - 'jax>=0.4.32 ; python_version < "3.14"', # first version whose array API namespace is jax.numpy + 'jax>=0.7.0 ; python_version < "3.14"', # first version whose indexed get takes `wrap_negative_indices` 'jax>=0.9.1 ; python_version >= "3.14"' # first version with pre-built wheel for Python 3.14 ] -jax-cuda12 = ['jax[cuda12-local]>=0.6.0', 'gt4py[cuda12]'] +jax-cuda12 = ['jax[cuda12-local]>=0.7.0', 'gt4py[cuda12]'] jax-cuda13 = ['jax[cuda13-local]>=0.7.0', 'gt4py[cuda13]'] next = ['gt4py[jax,standard,testing]'] rocm6 = ['cupy>=13.4.1,<14.0'] diff --git a/uv.lock b/uv.lock index c3c2b00305..61baacb039 100644 --- a/uv.lock +++ b/uv.lock @@ -1495,8 +1495,8 @@ requires-dist = [ { name = "gt4py", extras = ["jax", "standard", "testing"], marker = "extra == 'next'" }, { name = "hypothesis", marker = "extra == 'testing'", specifier = ">=6.93" }, { name = "jax", marker = "python_full_version >= '3.14' and extra == 'jax'", specifier = ">=0.9.1" }, - { name = "jax", marker = "python_full_version < '3.14' and extra == 'jax'", specifier = ">=0.4.32" }, - { name = "jax", extras = ["cuda12-local"], marker = "extra == 'jax-cuda12'", specifier = ">=0.6.0" }, + { name = "jax", marker = "python_full_version < '3.14' and extra == 'jax'", specifier = ">=0.7.0" }, + { name = "jax", extras = ["cuda12-local"], marker = "extra == 'jax-cuda12'", specifier = ">=0.7.0" }, { name = "jax", extras = ["cuda13-local"], marker = "extra == 'jax-cuda13'", specifier = ">=0.7.0" }, { name = "jinja2", specifier = ">=3.0.0" }, { name = "lark", specifier = ">=1.1.2" }, From e8e269684799c534adf844fc3bbd000bbe339815 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 16 Nov 2026 09:54:13 +0100 Subject: [PATCH 079/166] refactor[next]: name the library slot of a connectivity _array_ops_meta and state its contract --- .../0029-Connectivities_Under_JAX_Tracing.md | 2 +- .../next/embedded/array_libraries/jax_ops.py | 24 +++++++++---------- src/gt4py/next/embedded/array_ops.py | 7 +++--- src/gt4py/next/embedded/nd_array_field.py | 16 ++++++++----- .../embedded_tests/test_nd_array_field.py | 4 ++-- 5 files changed, 27 insertions(+), 26 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 0841127ebc..d4b0cb9aab 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -24,7 +24,7 @@ Narrowing is the common case: the field usually covers only part of the connecti There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations on a table are methods of `ArrayOps`: `hyperslice` (domain inference), `restrict_table` and `gather`. Their defaults are plain array code. `JaxOps` overrides them, and everything that knows about tracing is in `jax_ops.py`. -A connectivity stores one opaque value for its `ArrayOps`, `_static`, and hands it to `hyperslice` and `restrict_table`. Only the library creates it, and `restrict` passes it on unchanged. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, for that tracer and for the tracers restricted from it. Tables are looked up by identity, so a connectivity that got another table, for example through `dataclasses.replace`, has none. +A connectivity stores one opaque value for its `ArrayOps`, `_array_ops_meta`, and hands it as `meta` to `hyperslice` and `restrict_table`. Only the library creates it, and `restrict` passes it on unchanged. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, for that tracer and for the tracers restricted from it. Tables are looked up by identity, so a connectivity that got another table, for example through `dataclasses.replace`, has none. `JaxOps.gather` clamps indices to the field at both ends, inside the gather. It does not need to know where an index came from. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 6cd8815da7..8554bad52d 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -98,11 +98,11 @@ def _has_values(table: Any) -> bool: return isinstance(table, jax.Array) and not isinstance(table, jax.core.Tracer) -def _values(table: Any, static: Optional[_StaticValues]) -> Optional[core_defs.NDArrayObject]: +def _values(table: Any, meta: Optional[_StaticValues]) -> Optional[core_defs.NDArrayObject]: """Return the concrete array with the values of `table`, `None` if they exist only at run time.""" if _has_values(table): return table - return None if static is None else static.get(table) + return None if meta is None else meta.get(table) #: per concrete table, its restrictions by key: restricting the same table again returns the same @@ -153,9 +153,9 @@ def hyperslice( image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, *, - static: Optional[_StaticValues] = None, + meta: Optional[_StaticValues] = None, ) -> Optional[tuple[slice, ...]]: - values = _values(table, static) + values = _values(table, meta) if values is None: return (slice(None),) * table.ndim with jax.ensure_compile_time_eval(): @@ -166,17 +166,17 @@ def restrict_table( table: core_defs.NDArrayObject, key: common.RelativeIndexSequence, *, - static: Optional[_StaticValues] = None, + meta: Optional[_StaticValues] = None, ) -> core_defs.NDArrayObject: - values = _values(table, static) + values = _values(table, meta) if values is None: return super().restrict_table(table, key) restricted_values = _restrict_values(values, key) if values is table: return restricted_values - assert static is not None + assert meta is not None restricted = super().restrict_table(table, key) - static.add_restricted(restricted, restricted_values) + meta.add_restricted(restricted, restricted_values) return restricted def gather( @@ -236,7 +236,7 @@ def _flatten_connectivity( assert not (array_api_compat.is_numpy_array(table) or array_api_compat.is_cupy_array(table)), ( f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(table)}'." ) - values = _values(table, connectivity._static) + values = _values(table, connectivity._array_ops_meta) return (table,), ( connectivity.domain, connectivity.codomain, @@ -252,11 +252,9 @@ def _unflatten_connectivity( (table,) = children # a child without values stands for the flattened table: a tracer, or one of the placeholders # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around - static = ( - None if identity is None or _has_values(table) else _StaticValues(identity.values, table) - ) + meta = None if identity is None or _has_values(table) else _StaticValues(identity.values, table) return nd_array_field.NdArrayConnectivityField( - domain, table, codomain, skip_value, _static=static + domain, table, codomain, skip_value, _array_ops_meta=meta ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 8be333916a..aaf6653242 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -189,8 +189,7 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array - # The operations on a connectivity table. `static` is what the connectivity holds for the - # library of its table: `None`, unless the library created the connectivity with one. + # The operations on a connectivity table. `meta` is the connectivity's `_array_ops_meta`. def hyperslice( self, @@ -198,7 +197,7 @@ def hyperslice( image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, *, - static: Any = None, + meta: Any = None, ) -> Optional[tuple[slice, ...]]: """ Return the hypercube slice that contains all indices in `table` that are within `image_range`, or `None` if no such hypercube exists. @@ -243,7 +242,7 @@ def restrict_table( table: core_defs.NDArrayObject, key: common.RelativeIndexSequence, *, - static: Any = None, + meta: Any = None, ) -> core_defs.NDArrayObject: """Return `table[key]`.""" return self.asarray(table[key]) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 65844b0102..db681b1f38 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -454,8 +454,12 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: created by the library of the table, for its `ArrayOps`; `restrict` passes it on as it is - _static: Any = dataclasses.field( + #: Metadata that the `ArrayOps` of the table attaches to the connectivity. Shared code never + #: creates, reads or changes it: it is `None` unless the library set it when building the + #: connectivity, `restrict` passes it on unchanged, and it is handed as `meta` to + #: `ArrayOps.hyperslice` and `ArrayOps.restrict_table`. It takes no part in equality, `repr` + #: or fingerprinting. + _array_ops_meta: Any = dataclasses.field( default=None, kw_only=True, compare=False, @@ -520,7 +524,7 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: assert common.UnitRange.is_finite(image_range) slices = array_ops.of(self._ndarray).hyperslice( - self._ndarray, image_range, self.skip_value, static=self._static + self._ndarray, image_range, self.skip_value, meta=self._array_ops_meta ) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -531,16 +535,16 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: return new_domain def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: - # no array is cached: whether a restricted table can be used again is up to its library + # Arrays must not be cached: whether a restricted table can be used again is up to its library cache_key = ("restrict", index) if (cached := self._cache.get(cache_key, None)) is None: cached = self._cache[cache_key] = (*self._slice(index), {}) new_domain, buffer_slice, restricted_cache = cached table = array_ops.of(self._ndarray).restrict_table( - self._ndarray, buffer_slice, static=self._static + self._ndarray, buffer_slice, meta=self._array_ops_meta ) restricted_connectivity = self.__class__( - new_domain, table, self.codomain, self.skip_value, _static=self._static + new_domain, table, self.codomain, self.skip_value, _array_ops_meta=self._array_ops_meta ) restricted_connectivity.__dict__["_cache"] = restricted_cache return restricted_connectivity diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 7d0156c946..032c4454c1 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2638,14 +2638,14 @@ def test_jax_pytree_rejects_connectivities_of_other_libraries(): @pytest.mark.requires_jax -def test_jax_pytree_of_concrete_connectivity_has_no_static(): +def test_jax_pytree_of_concrete_connectivity_has_no_array_ops_meta(): import jax E, field, conn_a, _ = _jax_narrowing_setup() rebuilt = jax.tree.map(lambda table: table + 1, conn_a) - assert rebuilt._static is None + assert rebuilt._array_ops_meta is None # targets 1, 2, 3, 4, 6 of a field on V:(1,4) result = field.premap(rebuilt) assert result.domain == common.domain({E: (0, 3)}) From a5e199fe7f7452f5d226601e75a1c192440c7a51 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 16 Nov 2026 09:55:47 +0100 Subject: [PATCH 080/166] test[next]: move the jax tests of embedded fields and connectivities to their own module --- .../embedded_tests/test_nd_array_field.py | 614 ----------------- .../test_nd_array_field_with_array_library.py | 633 ++++++++++++++++++ 2 files changed, 633 insertions(+), 614 deletions(-) create mode 100644 tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_array_library.py diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 032c4454c1..5fd4861b24 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -10,7 +10,6 @@ import math import operator import pickle -import re from typing import Callable, Iterable, Optional import array_api_strict @@ -131,7 +130,6 @@ def _skip_or_expect_no_buffer_info(xp) -> bool: def test_nd_array_field_buffer_info(nd_array_implementation): - import dataclasses data = asarray(nd_array_implementation, [[1.0, 2.0], [3.0, 4.0]], dtype=np.float64) field = common._field(data, domain=common.domain({D0: 2, D1: 2})) @@ -1461,7 +1459,6 @@ def test_nd_array_field_pickle_roundtrip(): def test_nd_array_connectivity_field_buffer_info(nd_array_implementation): - import dataclasses V = Dimension("V") E = Dimension("E") @@ -1934,305 +1931,6 @@ def test_neighbor_sum_after_narrowing_premap(): np.testing.assert_array_equal(result.asnumpy(), [3.0, 3.0]) -@pytest.mark.requires_jax -def test_jax_jit_field_arguments(): - import jax - - domain = common.domain({D0: (1, 3), D1: (2, 5)}) - a = common._field( - jax.numpy.asarray(np.arange(6, dtype=np.float64).reshape(2, 3)), domain=domain - ) - b = common._field(jax.numpy.ones((2, 3), dtype=np.float64), domain=domain) - - @jax.jit - def add(x, y): - return x + y - - result = add(a, b) - - assert isinstance(result, common.Field) - assert result.domain == domain - np.testing.assert_allclose(result.asnumpy(), a.asnumpy() + b.asnumpy()) - - -@pytest.mark.requires_jax -def test_jax_pytree_roundtrip(): - import jax - - domain = common.domain({D0: (1, 3), D1: (2, 5)}) - field = common._field(jax.numpy.ones((2, 3), dtype=np.float64), domain=domain) - - children, treedef = jax.tree_util.tree_flatten(field) - - assert len(children) == 1 - assert children[0] is field.ndarray - - restored = jax.tree_util.tree_unflatten(treedef, children) - assert restored.domain == domain - - other_field = common._field( - jax.numpy.ones((2, 3), dtype=np.float64), domain=common.domain({D0: (0, 2), D1: (2, 5)}) - ) - # the domain is part of the tree structure, hence a domain change forces a 'jax.jit' retrace - assert jax.tree_util.tree_structure(other_field) != treedef - - -@pytest.mark.requires_jax -def test_jax_pytree_rejects_fields_of_other_libraries(): - import jax - - field = common._field(np.ones(3), domain=common.domain({D0: 3})) - - with pytest.raises(AssertionError, match="Only fields of JAX arrays"): - jax.jit(lambda f: f * 2.0)(field) - - -@pytest.mark.requires_jax -def test_jax_pytree_non_array_leaves(): - import jax - - D_BATCH = Dimension("D_BATCH") - field = common._field(jax.numpy.arange(3.0), domain=common.domain({D0: 3})) - batched = common._field(jax.numpy.ones((2, 3)), domain=common.domain({D_BATCH: 2, D0: 3})) - - shapes = jax.tree.map(lambda x: x.shape, field) - assert jax.tree.leaves(shapes) == [3] - assert jax.eval_shape(lambda f: f * 2.0, field).ndarray.shape == (3,) - # a field with an axis index as leaf, as `vmap` prefix for the batched field's buffer - axes = nd_array_field.NdArrayField(common.domain({D0: 3}), 0) - sums = jax.vmap(lambda f: f.ndarray.sum(), in_axes=(axes,))( - nd_array_field.NdArrayField(common.domain({D0: 3}), batched.ndarray) - ) - np.testing.assert_allclose(sums, [3.0, 3.0]) - - -@pytest.mark.requires_jax -def test_jax_traced_array_dispatch(): - import jax - - domain = common.domain({D0: (0, 3)}) - x = jax.numpy.arange(3, dtype=np.float64) - - def loss(arr): - field = common._field(arr, domain=domain) - assert isinstance(field, nd_array_field.NdArrayField) - assert field.array_ns is jax.numpy - return jax.numpy.sum((field * field).ndarray) - - np.testing.assert_allclose(jax.grad(loss)(x), 2.0 * x.__array__()) - np.testing.assert_allclose(jax.jit(loss)(x), loss(x)) - - offsets = jax.numpy.asarray([[2, 0], [1, 2]]) - codomain = common.domain({D0: (0, 2), D1: (0, 2)}) - - def make_connectivity(arr): - return common._connectivity(arr, codomain=D0, domain=codomain).ndarray - - np.testing.assert_array_equal(jax.jit(make_connectivity)(offsets), offsets) - - -@pytest.mark.requires_jax -def test_jax_grad_through_premap_with_skip_values(): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - e2v = common._connectivity( - jax.numpy.asarray([[0, 1], [2, -1]], dtype=np.int32), - codomain=V, - domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), - skip_value=-1, - ) - - def loss(x): - field = common._field(x, domain=common.domain({V: (0, 4)})) - with embedded_context.update(offset_provider={"E2V": e2v}): - result = fbuiltins.neighbor_sum(fbuiltins.sqrt(field.premap(e2v)), axis=E2VDim) - return jax.numpy.sum(result.ndarray) - - x = jax.numpy.asarray([4.0, 9.0, 16.0, -1.0]) - - np.testing.assert_allclose(loss(x), 9.0) - np.testing.assert_allclose(jax.grad(loss)(x), [0.25, 1.0 / 6.0, 0.125, 0.0]) - - -def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: - """Two edges per vertex, both entries equal, every seventh second entry a skip value.""" - vertex = np.arange(4 * num_vertices) // 2 - table = np.stack([vertex, vertex], axis=1).astype(np.int32) - table[::7, 1] = -1 - return table - - -@pytest.mark.requires_jax -@pytest.mark.parametrize("num_field_vertices", [300, 600], ids=["narrowing", "covering"]) -def test_jax_jit_premap_with_connectivity_argument(num_field_vertices): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - table = _skip_value_e2v_table(300) - conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) - field_domain = common.domain({V: (0, num_field_vertices)}) - - def premap_and_reduce(field, conn): - with embedded_context.update(offset_provider={"E2V": conn}): - return fbuiltins.neighbor_sum(field.premap(conn), axis=E2VDim) - - expected = premap_and_reduce( - common._field(np.arange(num_field_vertices, dtype=np.float64), domain=field_domain), - common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1), - ) - - jitted = jax.jit(premap_and_reduce) - field = common._field( - jax.numpy.arange(num_field_vertices, dtype=np.float64), domain=field_domain - ) - conn = common._connectivity( - jax.numpy.asarray(table), codomain=V, domain=conn_domain, skip_value=-1 - ) - result = jitted(field, conn) - - assert result.domain == expected.domain - np.testing.assert_allclose(result.asnumpy(), expected.asnumpy()) - - stablehlo = jitted.lower(field, conn).as_text() - main_arguments = re.search(r"@main\(([^)]*)\)", stablehlo).group(1) - assert f"tensor<{table.shape[0]}x2xi32>" in main_arguments - # large constants print as hex - assert 'dense<"0x' not in stablehlo - assert 'dense<"0x' in jax.jit(lambda field: field.premap(conn)).lower(field).as_text() - - -@pytest.mark.requires_jax -def test_jax_jit_premap_with_closed_over_restricted_connectivity(): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - table = np.asarray([[0, 1], [1, 0], [2, 2]], dtype=np.int32) - conn = common._connectivity( - jax.numpy.asarray(table), - codomain=V, - domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), - ) - field = common._field(jax.numpy.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) - - result = jax.jit(lambda field: field.premap(conn[common.NamedIndex(E2VDim, 1)]))(field) - - assert result.domain == common.domain({E: (0, 2)}) - np.testing.assert_array_equal(result.asnumpy(), [20.0, 10.0]) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_with_as_offset_computed_in_trace(): - import jax - - from gt4py.next.ffront import experimental - - C = Dimension("C") - K = Dimension("K", kind=DimensionKind.VERTICAL) - Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) - domain = common.domain({C: (0, 2), K: (0, 4)}) - values = np.arange(8, dtype=np.float64).reshape(2, 4) - offsets = np.asarray([[1, 1, 0, -1], [0, 2, 1, 0]], dtype=np.int32) - - def shifted(field, offset_field): - return field.premap(experimental.as_offset(Koff, offset_field)) - - field = common._field(jax.numpy.asarray(values), domain=domain) - offset_field = common._field(jax.numpy.asarray(offsets), domain=domain) - expected = shifted(field, offset_field) - - result = jax.jit(shifted)(field, offset_field) - - assert result.domain == domain - np.testing.assert_array_equal(result.asnumpy(), expected.asnumpy()) - np.testing.assert_array_equal( - result.asnumpy(), np.take_along_axis(values, np.arange(4) + offsets, axis=1) - ) - - # out-of-range targets read the boundary value under a trace - beyond = common._field(jax.numpy.asarray(np.full((2, 4), 3, dtype=np.int32)), domain=domain) - np.testing.assert_array_equal( - jax.jit(shifted)(field, beyond).asnumpy(), np.repeat(values[:, -1:], 4, axis=1) - ) - below = common._field(jax.numpy.asarray(np.full((2, 4), -3, dtype=np.int32)), domain=domain) - np.testing.assert_array_equal( - jax.jit(shifted)(field, below).asnumpy(), - np.take_along_axis( - values, np.maximum(np.arange(4) - 3, 0)[None, :].repeat(2, axis=0), axis=1 - ), - ) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_with_closed_over_as_offset_narrows_like_eager(): - import jax - - from gt4py.next.ffront import experimental - - K = Dimension("K", kind=DimensionKind.VERTICAL) - Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) - domain = common.domain({K: (0, 4)}) - field = common._field(jax.numpy.asarray([0.0, 1.0, 2.0, 3.0]), domain=domain) - offset_field = common._field(jax.numpy.ones(4, dtype=np.int32), domain=domain) - - result = jax.jit(lambda field: field.premap(experimental.as_offset(Koff, offset_field)))(field) - - assert result.domain == common.domain({K: (0, 3)}) - np.testing.assert_array_equal(result.asnumpy(), [1.0, 2.0, 3.0]) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_with_field_offset_does_not_leak_tracers(): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - E2V = fbuiltins.FieldOffset("E2V", source=V, target=(E, E2VDim)) - conn = common._connectivity( - jax.numpy.asarray([[0, 1], [2, 3]], dtype=np.int32), - codomain=V, - domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), - ) - field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) - - def shifted(field, conn): - with embedded_context.update(offset_provider={"E2V": conn}): - return field(E2V) - - with jax.checking_leaks(): - result = jax.jit(shifted)(field, conn) - - np.testing.assert_array_equal(result.asnumpy(), [[0.0, 1.0], [2.0, 3.0]]) - - -@pytest.mark.requires_jax -def test_nested_jax_jit_premap_narrows(): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - conn = common._connectivity( - jax.numpy.asarray([[0, 1], [2, 3], [4, 5]], dtype=np.int32), - codomain=V, - domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), - ) - field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) - - inner = jax.jit(lambda field, conn: field.premap(conn)) - result = jax.jit(lambda field, conn: inner(field, conn))(field, conn) - - assert result.domain == common.domain({E: (0, 2), E2VDim: (0, 2)}) - np.testing.assert_array_equal(result.asnumpy(), [[0.0, 1.0], [2.0, 3.0]]) - - def test_neighbor_sum_with_custom_skip_value_and_nonzero_domain_start(): V = Dimension("V") E = Dimension("E") @@ -2275,62 +1973,6 @@ def test_neighbor_sum_over_infinite_range(): np.testing.assert_array_equal(result.ndarray.ravel(), [3.0, 4.0]) -@pytest.mark.requires_jax -def test_jax_jit_retraces_per_connectivity_buffer(): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - table = jax.numpy.asarray(_skip_value_e2v_table(8)) - conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) - field = common._field(jax.numpy.arange(8, dtype=np.float64), domain=common.domain({V: (0, 8)})) - traces = 0 - - @jax.jit - def premap(field, conn): - nonlocal traces - traces += 1 - return field.premap(conn) - - conn = common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1) - premap(field, conn) - premap(field, conn) - assert traces == 1 - - premap(field, common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1)) - assert traces == 1 - - premap( - field, - common._connectivity( - jax.numpy.array(table, copy=True), codomain=V, domain=conn_domain, skip_value=-1 - ), - ) - assert traces == 2 - - premap(field, conn[NamedIndex(E2VDim, 0)]) - premap(field, conn[NamedIndex(E2VDim, 0)]) - assert traces == 3 - - -@pytest.mark.requires_jax -def test_jax_jit_premap_non_contiguous_inverse_image_raises(): - import jax - - V = Dimension("V") - E = Dimension("E") - conn = common._connectivity( - jax.numpy.asarray([0, 5, 1], dtype=np.int32), - codomain=V, - domain=common.domain({E: (0, 3)}), - ) - field = common._field(jax.numpy.arange(3, dtype=np.float64), domain=common.domain({V: (0, 3)})) - - with pytest.raises(ValueError, match="non-contiguous"): - jax.jit(lambda field, conn: field.premap(conn))(field, conn) - - def test_connectivity_field_setitem_raises(): conn = common._connectivity( np.asarray([[0, 1], [-1, -1]]), @@ -2368,155 +2010,6 @@ def test_neighbor_sum_with_transposed_table_dims(): np.testing.assert_allclose(result.asnumpy(), expected) -@pytest.mark.requires_jax -def test_jax_jit_premap_with_restricted_connectivity_argument(): - import jax - - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - table = _skip_value_e2v_table(8) - conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) - field_domain = common.domain({V: (0, 4)}) - - def premap_first_neighbor(field, conn): - return field.premap(conn[NamedIndex(E2VDim, 0)]) - - expected = premap_first_neighbor( - common._field(np.arange(4, dtype=np.float64), domain=field_domain), - common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1), - ) - result = jax.jit(premap_first_neighbor)( - common._field(jax.numpy.arange(4, dtype=np.float64), domain=field_domain), - common._connectivity( - jax.numpy.asarray(table), codomain=V, domain=conn_domain, skip_value=-1 - ), - ) - - assert result.domain == expected.domain - np.testing.assert_allclose(result.asnumpy(), expected.asnumpy()) - - -def _jax_narrowing_setup(): - """A field on V:(1,4) and two tables on E:(0,5) mapping into it on E:(1,4) and on E:(0,3).""" - import jax - - V = Dimension("V") - E = Dimension("E") - field = common._field(jax.numpy.asarray([10.0, 20.0, 30.0]), domain=common.domain({V: (1, 4)})) - conn_domain = common.domain({E: (0, 5)}) - conn_a = common._connectivity( - jax.numpy.asarray([0, 1, 2, 3, 5], dtype=np.int32), codomain=V, domain=conn_domain - ) - conn_b = common._connectivity( - jax.numpy.asarray([1, 2, 3, 0, 5], dtype=np.int32), codomain=V, domain=conn_domain - ) - return E, field, conn_a, conn_b - - -@pytest.mark.requires_jax -def test_jax_jit_premap_with_connectivity_from_array(): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - conn = nd_array_field.NdArrayConnectivityField.from_array( - conn_a.ndarray, conn_a.codomain, domain=conn_a.domain - ) - - for result in ( - jax.jit(lambda field, conn: field.premap(conn))(field, conn), - jax.jit(lambda field: field.premap(conn))(field), - ): - assert result.domain == common.domain({E: (1, 4)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) - - -@pytest.mark.requires_jax -@pytest.mark.parametrize("predicate", [True, False]) -def test_jax_jit_premap_with_connectivity_selected_by_cond(predicate): - import jax - - E, field, conn_a, conn_b = _jax_narrowing_setup() - - def premap_selected(predicate, field, conn1, conn2): - return field.premap(jax.lax.cond(predicate, lambda: conn1, lambda: conn2)) - - with pytest.raises(TypeError, match="pytree structure"): - jax.jit(premap_selected)(predicate, field, conn_a, conn_b) - with pytest.raises(TypeError, match="pytree structure"): - jax.jit(lambda predicate, field, conn: premap_selected(predicate, field, conn, conn_b))( - predicate, field, conn_a - ) - - # the same table in both branches - same_table = common._connectivity( - conn_a.ndarray, codomain=conn_a.codomain, domain=conn_a.domain - ) - result = jax.jit(premap_selected)(predicate, field, conn_a, same_table) - assert result.domain == common.domain({E: (1, 4)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_with_connectivity_selected_by_switch(): - import jax - - _, field, conn_a, conn_b = _jax_narrowing_setup() - - def premap_selected(index, field, conn1, conn2): - return field.premap(jax.lax.switch(index, [lambda: conn1, lambda: conn2])) - - with pytest.raises(TypeError, match="pytree structure"): - jax.jit(premap_selected)(1, field, conn_a, conn_b) - - -@pytest.mark.requires_jax -def test_jax_scan_with_connectivity_carry(): - import jax - - _, field, conn_a, conn_b = _jax_narrowing_setup() - - def premap_sums(conn, next_conn): - def body(carry, x): - return (carry if next_conn is None else next_conn), x * jax.numpy.sum( - field.premap(carry).ndarray - ) - - return jax.lax.scan(body, conn, jax.numpy.asarray([1.0, 2.0]))[1] - - np.testing.assert_array_equal(premap_sums(conn_a, None), [60.0, 120.0]) - np.testing.assert_array_equal( - jax.jit(lambda conn: premap_sums(conn, None))(conn_a), [60.0, 120.0] - ) - - with pytest.raises(TypeError, match="pytree structure"): - premap_sums(conn_a, conn_b) - with pytest.raises(TypeError, match="pytree structure"): - jax.jit(premap_sums)(conn_a, conn_b) - - -@pytest.mark.requires_jax -@pytest.mark.parametrize("nested", [False, True]) -def test_jax_jit_premap_with_replaced_table_has_no_values(nested): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - premap = ( - jax.jit(lambda field, conn: field.premap(conn)) - if nested - else nd_array_field.NdArrayField.premap - ) - - def premap_next(field, conn): - return premap(field, dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) - - result = jax.jit(premap_next)(field, conn_a) - - # as for every table computed in the trace: not narrowed, out-of-range targets clamped - assert result.domain == common.domain({E: (0, 5)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0, 30.0, 30.0]) - - def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): V = Dimension("V") E = Dimension("E") @@ -2543,110 +2036,3 @@ def counting_hyperslice(*args, **kwargs): assert calls == 1 assert result.domain == common.domain({E: (0, 2)}) np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0]) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_clamps_in_the_gather(): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - - def premap(field, table): - return field.premap(dataclasses.replace(conn_a, _ndarray=table)) - - # targets -2, -1, 0, 1, 3 of a field on V:(1,4) - table = conn_a.ndarray - 2 - result = jax.jit(premap)(field, table) - - assert result.domain == common.domain({E: (0, 5)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 10.0, 10.0, 30.0]) - for lowered in ( - jax.jit(premap).lower(field, table).as_text(), - jax.jit(lambda field, conn: field.premap(conn)).lower(field, conn_a).as_text(), - ): - assert "stablehlo.gather" in lowered - assert not re.search(r"stablehlo\.(clamp|minimum|maximum|select)", lowered) - - -@pytest.mark.requires_jax -@pytest.mark.parametrize("predicate, factor", [(True, 1.0), (False, 2.0)]) -def test_jax_jit_premap_in_cond_branches_closing_over_connectivity(predicate, factor): - import jax - - _, field, conn_a, _ = _jax_narrowing_setup() - - def premap_in_branches(predicate, field, conn): - return jax.lax.cond( - predicate, - lambda: field.premap(conn).ndarray * 1.0, - lambda: field.premap(conn).ndarray * 2.0, - ) - - result = jax.jit(premap_in_branches)(predicate, field, conn_a) - - np.testing.assert_array_equal(result, np.asarray([10.0, 20.0, 30.0]) * factor) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_in_nested_jit_closing_over_connectivity(): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - - def premap_twice(field, conn): - inner = jax.jit(lambda field: field.premap(conn))(field) - return inner, field.premap(conn) - - for result in jax.jit(premap_twice)(field, conn_a): - assert result.domain == common.domain({E: (1, 4)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_in_scan_body_closing_over_connectivity(): - import jax - - _, field, conn_a, _ = _jax_narrowing_setup() - - def premap_in_scan(field, conn): - def body(carry, _): - return carry + field.premap(conn).ndarray, None - - total, _ = jax.lax.scan(body, jax.numpy.zeros(3), jax.numpy.arange(2)) - return total + field.premap(conn).ndarray - - result = jax.jit(premap_in_scan)(field, conn_a) - - np.testing.assert_array_equal(result, [30.0, 60.0, 90.0]) - - -@pytest.mark.requires_jax -def test_jax_pytree_rejects_connectivities_of_other_libraries(): - import jax - - _, field, conn_a, _ = _jax_narrowing_setup() - numpy_conn = common._connectivity( - np.asarray([0, 1, 2, 3, 5], dtype=np.int32), codomain=conn_a.codomain, domain=conn_a.domain - ) - - with pytest.raises(AssertionError, match="Only connectivities of JAX arrays"): - jax.jit(lambda field, conn: field.premap(conn))(field, numpy_conn) - - # not a pytree leaf, so it is not flattened - result = jax.jit(lambda field: field.premap(numpy_conn))(field) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) - - -@pytest.mark.requires_jax -def test_jax_pytree_of_concrete_connectivity_has_no_array_ops_meta(): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - - rebuilt = jax.tree.map(lambda table: table + 1, conn_a) - - assert rebuilt._array_ops_meta is None - # targets 1, 2, 3, 4, 6 of a field on V:(1,4) - result = field.premap(rebuilt) - assert result.domain == common.domain({E: (0, 3)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_array_library.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_array_library.py new file mode 100644 index 0000000000..3f9f9902f8 --- /dev/null +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_array_library.py @@ -0,0 +1,633 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +import dataclasses +import re + +import numpy as np +import pytest + +from gt4py.next import common +from gt4py.next.common import Dimension, DimensionKind, NamedIndex +from gt4py.next.embedded import context as embedded_context, nd_array_field +from gt4py.next.ffront import fbuiltins + + +D0 = Dimension("D0") +D1 = Dimension("D1") + + +@pytest.mark.requires_jax +def test_jax_jit_field_arguments(): + import jax + + domain = common.domain({D0: (1, 3), D1: (2, 5)}) + a = common._field( + jax.numpy.asarray(np.arange(6, dtype=np.float64).reshape(2, 3)), domain=domain + ) + b = common._field(jax.numpy.ones((2, 3), dtype=np.float64), domain=domain) + + @jax.jit + def add(x, y): + return x + y + + result = add(a, b) + + assert isinstance(result, common.Field) + assert result.domain == domain + np.testing.assert_allclose(result.asnumpy(), a.asnumpy() + b.asnumpy()) + + +@pytest.mark.requires_jax +def test_jax_pytree_roundtrip(): + import jax + + domain = common.domain({D0: (1, 3), D1: (2, 5)}) + field = common._field(jax.numpy.ones((2, 3), dtype=np.float64), domain=domain) + + children, treedef = jax.tree_util.tree_flatten(field) + + assert len(children) == 1 + assert children[0] is field.ndarray + + restored = jax.tree_util.tree_unflatten(treedef, children) + assert restored.domain == domain + + other_field = common._field( + jax.numpy.ones((2, 3), dtype=np.float64), domain=common.domain({D0: (0, 2), D1: (2, 5)}) + ) + # the domain is part of the tree structure, hence a domain change forces a 'jax.jit' retrace + assert jax.tree_util.tree_structure(other_field) != treedef + + +@pytest.mark.requires_jax +def test_jax_pytree_rejects_fields_of_other_libraries(): + import jax + + field = common._field(np.ones(3), domain=common.domain({D0: 3})) + + with pytest.raises(AssertionError, match="Only fields of JAX arrays"): + jax.jit(lambda f: f * 2.0)(field) + + +@pytest.mark.requires_jax +def test_jax_pytree_non_array_leaves(): + import jax + + D_BATCH = Dimension("D_BATCH") + field = common._field(jax.numpy.arange(3.0), domain=common.domain({D0: 3})) + batched = common._field(jax.numpy.ones((2, 3)), domain=common.domain({D_BATCH: 2, D0: 3})) + + shapes = jax.tree.map(lambda x: x.shape, field) + assert jax.tree.leaves(shapes) == [3] + assert jax.eval_shape(lambda f: f * 2.0, field).ndarray.shape == (3,) + # a field with an axis index as leaf, as `vmap` prefix for the batched field's buffer + axes = nd_array_field.NdArrayField(common.domain({D0: 3}), 0) + sums = jax.vmap(lambda f: f.ndarray.sum(), in_axes=(axes,))( + nd_array_field.NdArrayField(common.domain({D0: 3}), batched.ndarray) + ) + np.testing.assert_allclose(sums, [3.0, 3.0]) + + +@pytest.mark.requires_jax +def test_jax_traced_array_dispatch(): + import jax + + domain = common.domain({D0: (0, 3)}) + x = jax.numpy.arange(3, dtype=np.float64) + + def loss(arr): + field = common._field(arr, domain=domain) + assert isinstance(field, nd_array_field.NdArrayField) + assert field.array_ns is jax.numpy + return jax.numpy.sum((field * field).ndarray) + + np.testing.assert_allclose(jax.grad(loss)(x), 2.0 * x.__array__()) + np.testing.assert_allclose(jax.jit(loss)(x), loss(x)) + + offsets = jax.numpy.asarray([[2, 0], [1, 2]]) + codomain = common.domain({D0: (0, 2), D1: (0, 2)}) + + def make_connectivity(arr): + return common._connectivity(arr, codomain=D0, domain=codomain).ndarray + + np.testing.assert_array_equal(jax.jit(make_connectivity)(offsets), offsets) + + +@pytest.mark.requires_jax +def test_jax_grad_through_premap_with_skip_values(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + e2v = common._connectivity( + jax.numpy.asarray([[0, 1], [2, -1]], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + skip_value=-1, + ) + + def loss(x): + field = common._field(x, domain=common.domain({V: (0, 4)})) + with embedded_context.update(offset_provider={"E2V": e2v}): + result = fbuiltins.neighbor_sum(fbuiltins.sqrt(field.premap(e2v)), axis=E2VDim) + return jax.numpy.sum(result.ndarray) + + x = jax.numpy.asarray([4.0, 9.0, 16.0, -1.0]) + + np.testing.assert_allclose(loss(x), 9.0) + np.testing.assert_allclose(jax.grad(loss)(x), [0.25, 1.0 / 6.0, 0.125, 0.0]) + + +def _skip_value_e2v_table(num_vertices: int) -> np.ndarray: + """Two edges per vertex, both entries equal, every seventh second entry a skip value.""" + vertex = np.arange(4 * num_vertices) // 2 + table = np.stack([vertex, vertex], axis=1).astype(np.int32) + table[::7, 1] = -1 + return table + + +@pytest.mark.requires_jax +@pytest.mark.parametrize("num_field_vertices", [300, 600], ids=["narrowing", "covering"]) +def test_jax_jit_premap_with_connectivity_argument(num_field_vertices): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = _skip_value_e2v_table(300) + conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + field_domain = common.domain({V: (0, num_field_vertices)}) + + def premap_and_reduce(field, conn): + with embedded_context.update(offset_provider={"E2V": conn}): + return fbuiltins.neighbor_sum(field.premap(conn), axis=E2VDim) + + expected = premap_and_reduce( + common._field(np.arange(num_field_vertices, dtype=np.float64), domain=field_domain), + common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1), + ) + + jitted = jax.jit(premap_and_reduce) + field = common._field( + jax.numpy.arange(num_field_vertices, dtype=np.float64), domain=field_domain + ) + conn = common._connectivity( + jax.numpy.asarray(table), codomain=V, domain=conn_domain, skip_value=-1 + ) + result = jitted(field, conn) + + assert result.domain == expected.domain + np.testing.assert_allclose(result.asnumpy(), expected.asnumpy()) + + stablehlo = jitted.lower(field, conn).as_text() + main_arguments = re.search(r"@main\(([^)]*)\)", stablehlo).group(1) + assert f"tensor<{table.shape[0]}x2xi32>" in main_arguments + # large constants print as hex + assert 'dense<"0x' not in stablehlo + assert 'dense<"0x' in jax.jit(lambda field: field.premap(conn)).lower(field).as_text() + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_closed_over_restricted_connectivity(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = np.asarray([[0, 1], [1, 0], [2, 2]], dtype=np.int32) + conn = common._connectivity( + jax.numpy.asarray(table), + codomain=V, + domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + ) + field = common._field(jax.numpy.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) + + result = jax.jit(lambda field: field.premap(conn[common.NamedIndex(E2VDim, 1)]))(field) + + assert result.domain == common.domain({E: (0, 2)}) + np.testing.assert_array_equal(result.asnumpy(), [20.0, 10.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_as_offset_computed_in_trace(): + import jax + + from gt4py.next.ffront import experimental + + C = Dimension("C") + K = Dimension("K", kind=DimensionKind.VERTICAL) + Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) + domain = common.domain({C: (0, 2), K: (0, 4)}) + values = np.arange(8, dtype=np.float64).reshape(2, 4) + offsets = np.asarray([[1, 1, 0, -1], [0, 2, 1, 0]], dtype=np.int32) + + def shifted(field, offset_field): + return field.premap(experimental.as_offset(Koff, offset_field)) + + field = common._field(jax.numpy.asarray(values), domain=domain) + offset_field = common._field(jax.numpy.asarray(offsets), domain=domain) + expected = shifted(field, offset_field) + + result = jax.jit(shifted)(field, offset_field) + + assert result.domain == domain + np.testing.assert_array_equal(result.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal( + result.asnumpy(), np.take_along_axis(values, np.arange(4) + offsets, axis=1) + ) + + # out-of-range targets read the boundary value under a trace + beyond = common._field(jax.numpy.asarray(np.full((2, 4), 3, dtype=np.int32)), domain=domain) + np.testing.assert_array_equal( + jax.jit(shifted)(field, beyond).asnumpy(), np.repeat(values[:, -1:], 4, axis=1) + ) + below = common._field(jax.numpy.asarray(np.full((2, 4), -3, dtype=np.int32)), domain=domain) + np.testing.assert_array_equal( + jax.jit(shifted)(field, below).asnumpy(), + np.take_along_axis( + values, np.maximum(np.arange(4) - 3, 0)[None, :].repeat(2, axis=0), axis=1 + ), + ) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_closed_over_as_offset_narrows_like_eager(): + import jax + + from gt4py.next.ffront import experimental + + K = Dimension("K", kind=DimensionKind.VERTICAL) + Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) + domain = common.domain({K: (0, 4)}) + field = common._field(jax.numpy.asarray([0.0, 1.0, 2.0, 3.0]), domain=domain) + offset_field = common._field(jax.numpy.ones(4, dtype=np.int32), domain=domain) + + result = jax.jit(lambda field: field.premap(experimental.as_offset(Koff, offset_field)))(field) + + assert result.domain == common.domain({K: (0, 3)}) + np.testing.assert_array_equal(result.asnumpy(), [1.0, 2.0, 3.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_field_offset_does_not_leak_tracers(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + E2V = fbuiltins.FieldOffset("E2V", source=V, target=(E, E2VDim)) + conn = common._connectivity( + jax.numpy.asarray([[0, 1], [2, 3]], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 2), E2VDim: (0, 2)}), + ) + field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) + + def shifted(field, conn): + with embedded_context.update(offset_provider={"E2V": conn}): + return field(E2V) + + with jax.checking_leaks(): + result = jax.jit(shifted)(field, conn) + + np.testing.assert_array_equal(result.asnumpy(), [[0.0, 1.0], [2.0, 3.0]]) + + +@pytest.mark.requires_jax +def test_nested_jax_jit_premap_narrows(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + conn = common._connectivity( + jax.numpy.asarray([[0, 1], [2, 3], [4, 5]], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + ) + field = common._field(jax.numpy.arange(4, dtype=np.float64), domain=common.domain({V: (0, 4)})) + + inner = jax.jit(lambda field, conn: field.premap(conn)) + result = jax.jit(lambda field, conn: inner(field, conn))(field, conn) + + assert result.domain == common.domain({E: (0, 2), E2VDim: (0, 2)}) + np.testing.assert_array_equal(result.asnumpy(), [[0.0, 1.0], [2.0, 3.0]]) + + +@pytest.mark.requires_jax +def test_jax_jit_retraces_per_connectivity_buffer(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = jax.numpy.asarray(_skip_value_e2v_table(8)) + conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + field = common._field(jax.numpy.arange(8, dtype=np.float64), domain=common.domain({V: (0, 8)})) + traces = 0 + + @jax.jit + def premap(field, conn): + nonlocal traces + traces += 1 + return field.premap(conn) + + conn = common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1) + premap(field, conn) + premap(field, conn) + assert traces == 1 + + premap(field, common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1)) + assert traces == 1 + + premap( + field, + common._connectivity( + jax.numpy.array(table, copy=True), codomain=V, domain=conn_domain, skip_value=-1 + ), + ) + assert traces == 2 + + premap(field, conn[NamedIndex(E2VDim, 0)]) + premap(field, conn[NamedIndex(E2VDim, 0)]) + assert traces == 3 + + +@pytest.mark.requires_jax +def test_jax_jit_premap_non_contiguous_inverse_image_raises(): + import jax + + V = Dimension("V") + E = Dimension("E") + conn = common._connectivity( + jax.numpy.asarray([0, 5, 1], dtype=np.int32), + codomain=V, + domain=common.domain({E: (0, 3)}), + ) + field = common._field(jax.numpy.arange(3, dtype=np.float64), domain=common.domain({V: (0, 3)})) + + with pytest.raises(ValueError, match="non-contiguous"): + jax.jit(lambda field, conn: field.premap(conn))(field, conn) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_restricted_connectivity_argument(): + import jax + + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + table = _skip_value_e2v_table(8) + conn_domain = common.domain({E: (0, table.shape[0]), E2VDim: (0, 2)}) + field_domain = common.domain({V: (0, 4)}) + + def premap_first_neighbor(field, conn): + return field.premap(conn[NamedIndex(E2VDim, 0)]) + + expected = premap_first_neighbor( + common._field(np.arange(4, dtype=np.float64), domain=field_domain), + common._connectivity(table, codomain=V, domain=conn_domain, skip_value=-1), + ) + result = jax.jit(premap_first_neighbor)( + common._field(jax.numpy.arange(4, dtype=np.float64), domain=field_domain), + common._connectivity( + jax.numpy.asarray(table), codomain=V, domain=conn_domain, skip_value=-1 + ), + ) + + assert result.domain == expected.domain + np.testing.assert_allclose(result.asnumpy(), expected.asnumpy()) + + +def _jax_narrowing_setup(): + """A field on V:(1,4) and two tables on E:(0,5) mapping into it on E:(1,4) and on E:(0,3).""" + import jax + + V = Dimension("V") + E = Dimension("E") + field = common._field(jax.numpy.asarray([10.0, 20.0, 30.0]), domain=common.domain({V: (1, 4)})) + conn_domain = common.domain({E: (0, 5)}) + conn_a = common._connectivity( + jax.numpy.asarray([0, 1, 2, 3, 5], dtype=np.int32), codomain=V, domain=conn_domain + ) + conn_b = common._connectivity( + jax.numpy.asarray([1, 2, 3, 0, 5], dtype=np.int32), codomain=V, domain=conn_domain + ) + return E, field, conn_a, conn_b + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_connectivity_from_array(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + conn = nd_array_field.NdArrayConnectivityField.from_array( + conn_a.ndarray, conn_a.codomain, domain=conn_a.domain + ) + + for result in ( + jax.jit(lambda field, conn: field.premap(conn))(field, conn), + jax.jit(lambda field: field.premap(conn))(field), + ): + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +@pytest.mark.parametrize("predicate", [True, False]) +def test_jax_jit_premap_with_connectivity_selected_by_cond(predicate): + import jax + + E, field, conn_a, conn_b = _jax_narrowing_setup() + + def premap_selected(predicate, field, conn1, conn2): + return field.premap(jax.lax.cond(predicate, lambda: conn1, lambda: conn2)) + + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(premap_selected)(predicate, field, conn_a, conn_b) + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(lambda predicate, field, conn: premap_selected(predicate, field, conn, conn_b))( + predicate, field, conn_a + ) + + # the same table in both branches + same_table = common._connectivity( + conn_a.ndarray, codomain=conn_a.codomain, domain=conn_a.domain + ) + result = jax.jit(premap_selected)(predicate, field, conn_a, same_table) + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_with_connectivity_selected_by_switch(): + import jax + + _, field, conn_a, conn_b = _jax_narrowing_setup() + + def premap_selected(index, field, conn1, conn2): + return field.premap(jax.lax.switch(index, [lambda: conn1, lambda: conn2])) + + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(premap_selected)(1, field, conn_a, conn_b) + + +@pytest.mark.requires_jax +def test_jax_scan_with_connectivity_carry(): + import jax + + _, field, conn_a, conn_b = _jax_narrowing_setup() + + def premap_sums(conn, next_conn): + def body(carry, x): + return (carry if next_conn is None else next_conn), x * jax.numpy.sum( + field.premap(carry).ndarray + ) + + return jax.lax.scan(body, conn, jax.numpy.asarray([1.0, 2.0]))[1] + + np.testing.assert_array_equal(premap_sums(conn_a, None), [60.0, 120.0]) + np.testing.assert_array_equal( + jax.jit(lambda conn: premap_sums(conn, None))(conn_a), [60.0, 120.0] + ) + + with pytest.raises(TypeError, match="pytree structure"): + premap_sums(conn_a, conn_b) + with pytest.raises(TypeError, match="pytree structure"): + jax.jit(premap_sums)(conn_a, conn_b) + + +@pytest.mark.requires_jax +@pytest.mark.parametrize("nested", [False, True]) +def test_jax_jit_premap_with_replaced_table_has_no_values(nested): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + premap = ( + jax.jit(lambda field, conn: field.premap(conn)) + if nested + else nd_array_field.NdArrayField.premap + ) + + def premap_next(field, conn): + return premap(field, dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) + + result = jax.jit(premap_next)(field, conn_a) + + # as for every table computed in the trace: not narrowed, out-of-range targets clamped + assert result.domain == common.domain({E: (0, 5)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0, 30.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_clamps_in_the_gather(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + def premap(field, table): + return field.premap(dataclasses.replace(conn_a, _ndarray=table)) + + # targets -2, -1, 0, 1, 3 of a field on V:(1,4) + table = conn_a.ndarray - 2 + result = jax.jit(premap)(field, table) + + assert result.domain == common.domain({E: (0, 5)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 10.0, 10.0, 30.0]) + for lowered in ( + jax.jit(premap).lower(field, table).as_text(), + jax.jit(lambda field, conn: field.premap(conn)).lower(field, conn_a).as_text(), + ): + assert "stablehlo.gather" in lowered + assert not re.search(r"stablehlo\.(clamp|minimum|maximum|select)", lowered) + + +@pytest.mark.requires_jax +@pytest.mark.parametrize("predicate, factor", [(True, 1.0), (False, 2.0)]) +def test_jax_jit_premap_in_cond_branches_closing_over_connectivity(predicate, factor): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + + def premap_in_branches(predicate, field, conn): + return jax.lax.cond( + predicate, + lambda: field.premap(conn).ndarray * 1.0, + lambda: field.premap(conn).ndarray * 2.0, + ) + + result = jax.jit(premap_in_branches)(predicate, field, conn_a) + + np.testing.assert_array_equal(result, np.asarray([10.0, 20.0, 30.0]) * factor) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_in_nested_jit_closing_over_connectivity(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + def premap_twice(field, conn): + inner = jax.jit(lambda field: field.premap(conn))(field) + return inner, field.premap(conn) + + for result in jax.jit(premap_twice)(field, conn_a): + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_in_scan_body_closing_over_connectivity(): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + + def premap_in_scan(field, conn): + def body(carry, _): + return carry + field.premap(conn).ndarray, None + + total, _ = jax.lax.scan(body, jax.numpy.zeros(3), jax.numpy.arange(2)) + return total + field.premap(conn).ndarray + + result = jax.jit(premap_in_scan)(field, conn_a) + + np.testing.assert_array_equal(result, [30.0, 60.0, 90.0]) + + +@pytest.mark.requires_jax +def test_jax_pytree_rejects_connectivities_of_other_libraries(): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + numpy_conn = common._connectivity( + np.asarray([0, 1, 2, 3, 5], dtype=np.int32), codomain=conn_a.codomain, domain=conn_a.domain + ) + + with pytest.raises(AssertionError, match="Only connectivities of JAX arrays"): + jax.jit(lambda field, conn: field.premap(conn))(field, numpy_conn) + + # not a pytree leaf, so it is not flattened + result = jax.jit(lambda field: field.premap(numpy_conn))(field) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_pytree_of_concrete_connectivity_has_no_array_ops_meta(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + rebuilt = jax.tree.map(lambda table: table + 1, conn_a) + + assert rebuilt._array_ops_meta is None + # targets 1, 2, 3, 4, 6 of a field on V:(1,4) + result = field.premap(rebuilt) + assert result.domain == common.domain({E: (0, 3)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) From ffd17dd6d0d9a019057e06eb3175d2ddbb959bce Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 16 Nov 2026 11:02:28 +0100 Subject: [PATCH 081/166] test[next]: name the jax test module after the library --- ...ield_with_array_library.py => test_nd_array_field_with_jax.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/next_tests/unit_tests/embedded_tests/{test_nd_array_field_with_array_library.py => test_nd_array_field_with_jax.py} (100%) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_array_library.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py similarity index 100% rename from tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_array_library.py rename to tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py From cb1dd903cc6e96d180e25515a6db35b3534a2b25 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 16 Nov 2026 11:13:45 +0100 Subject: [PATCH 082/166] refactor[next]: state the contract of the library state of a connectivity Rename _array_ops_meta to _array_ops_state and state what shared code and an ArrayOps may rely on. JaxOps ignores a state it did not create and attaches none to one element of a vmapped table. Fields, like connectivities, are rejected as JAX pytrees only for arrays of other libraries, so lax.cond can return a field. --- .../0029-Connectivities_Under_JAX_Tracing.md | 2 +- .../next/embedded/array_libraries/jax_ops.py | 41 +++++++++------ src/gt4py/next/embedded/array_ops.py | 14 ++++-- src/gt4py/next/embedded/nd_array_field.py | 23 +++++---- .../test_nd_array_field_with_jax.py | 50 ++++++++++++++++++- 5 files changed, 99 insertions(+), 31 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index d4b0cb9aab..906433fc41 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -24,7 +24,7 @@ Narrowing is the common case: the field usually covers only part of the connecti There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations on a table are methods of `ArrayOps`: `hyperslice` (domain inference), `restrict_table` and `gather`. Their defaults are plain array code. `JaxOps` overrides them, and everything that knows about tracing is in `jax_ops.py`. -A connectivity stores one opaque value for its `ArrayOps`, `_array_ops_meta`, and hands it as `meta` to `hyperslice` and `restrict_table`. Only the library creates it, and `restrict` passes it on unchanged. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, for that tracer and for the tracers restricted from it. Tables are looked up by identity, so a connectivity that got another table, for example through `dataclasses.replace`, has none. +A connectivity stores one opaque value for its `ArrayOps`, `_array_ops_state`, and hands it as `state` to `hyperslice` and `restrict_table`. Only the library creates it, and `restrict` passes it on unchanged. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, for that tracer and for the tracers restricted from it. Tables are looked up by identity, so a connectivity that got another table, for example through `dataclasses.replace`, has none. `JaxOps.gather` clamps indices to the field at both ends, inside the gather. It does not need to know where an index came from. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 8554bad52d..cf715ff934 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -98,11 +98,11 @@ def _has_values(table: Any) -> bool: return isinstance(table, jax.Array) and not isinstance(table, jax.core.Tracer) -def _values(table: Any, meta: Optional[_StaticValues]) -> Optional[core_defs.NDArrayObject]: +def _values(table: Any, state: Any) -> Optional[core_defs.NDArrayObject]: """Return the concrete array with the values of `table`, `None` if they exist only at run time.""" if _has_values(table): return table - return None if meta is None else meta.get(table) + return state.get(table) if isinstance(state, _StaticValues) else None #: per concrete table, its restrictions by key: restricting the same table again returns the same @@ -153,9 +153,9 @@ def hyperslice( image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, *, - meta: Optional[_StaticValues] = None, + state: Any = None, ) -> Optional[tuple[slice, ...]]: - values = _values(table, meta) + values = _values(table, state) if values is None: return (slice(None),) * table.ndim with jax.ensure_compile_time_eval(): @@ -166,17 +166,17 @@ def restrict_table( table: core_defs.NDArrayObject, key: common.RelativeIndexSequence, *, - meta: Optional[_StaticValues] = None, + state: Any = None, ) -> core_defs.NDArrayObject: - values = _values(table, meta) + values = _values(table, state) if values is None: return super().restrict_table(table, key) restricted_values = _restrict_values(values, key) if values is table: return restricted_values - assert meta is not None + assert isinstance(state, _StaticValues) restricted = super().restrict_table(table, key) - meta.add_restricted(restricted, restricted_values) + state.add_restricted(restricted, restricted_values) return restricted def gather( @@ -201,10 +201,12 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: def _flatten_field( field: nd_array_field.NdArrayField, ) -> tuple[tuple[core_defs.NDArrayObject], common.Domain]: - # JAX also flattens pytrees whose leaves are not arrays (e.g. `jax.tree.map` results or - # `vmap` axis specifications), so only arrays of other libraries are rejected - assert not array_api_compat.is_array_api_obj(field.ndarray) or array_api_compat.is_jax_array( - field.ndarray + # JAX also flattens pytrees whose leaves are not arrays (e.g. `jax.tree.map` results, `vmap` + # axis specifications, or the placeholders of `lax.cond` branches, which are array API objects + # too), so only arrays of other libraries are rejected + assert not ( + array_api_compat.is_numpy_array(field.ndarray) + or array_api_compat.is_cupy_array(field.ndarray) ), f"Only fields of JAX arrays are JAX pytrees, got a field of '{type(field.ndarray)}'." return (field.ndarray,), field.domain @@ -236,7 +238,7 @@ def _flatten_connectivity( assert not (array_api_compat.is_numpy_array(table) or array_api_compat.is_cupy_array(table)), ( f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(table)}'." ) - values = _values(table, connectivity._array_ops_meta) + values = _values(table, connectivity._array_ops_state) return (table,), ( connectivity.domain, connectivity.codomain, @@ -251,10 +253,17 @@ def _unflatten_connectivity( domain, codomain, skip_value, identity = aux_data (table,) = children # a child without values stands for the flattened table: a tracer, or one of the placeholders - # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around - meta = None if identity is None or _has_values(table) else _StaticValues(identity.values, table) + # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. Under `vmap` the + # child is one element of the flattened table, whose values the aux data does not have. + state = ( + None + if identity is None + or _has_values(table) + or getattr(table, "shape", identity.values.shape) != identity.values.shape + else _StaticValues(identity.values, table) + ) return nd_array_field.NdArrayConnectivityField( - domain, table, codomain, skip_value, _array_ops_meta=meta + domain, table, codomain, skip_value, _array_ops_state=state ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index aaf6653242..88a2b61878 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -189,7 +189,15 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array - # The operations on a connectivity table. `meta` is the connectivity's `_array_ops_meta`. + # The operations on a connectivity table. `state` is the connectivity's `_array_ops_state`: + # `None`, or the object a library passed when it built a connectivity (for example in + # its pytree unflatten). Only that library reads or changes it. The same object reaches + # every connectivity restricted or copied from that one, also when the table was + # replaced, possibly by an array of another library. So an implementation + # - identifies the table a `state` describes itself and trusts no other pairing, + # - treats a `state` it did not create like `None`, + # - works with `None`: shared code may drop it, and a connectivity built from an array + # never has one. def hyperslice( self, @@ -197,7 +205,7 @@ def hyperslice( image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, *, - meta: Any = None, + state: Any = None, ) -> Optional[tuple[slice, ...]]: """ Return the hypercube slice that contains all indices in `table` that are within `image_range`, or `None` if no such hypercube exists. @@ -242,7 +250,7 @@ def restrict_table( table: core_defs.NDArrayObject, key: common.RelativeIndexSequence, *, - meta: Any = None, + state: Any = None, ) -> core_defs.NDArrayObject: """Return `table[key]`.""" return self.asarray(table[key]) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index db681b1f38..f05844bf7f 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -454,12 +454,13 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: Metadata that the `ArrayOps` of the table attaches to the connectivity. Shared code never - #: creates, reads or changes it: it is `None` unless the library set it when building the - #: connectivity, `restrict` passes it on unchanged, and it is handed as `meta` to - #: `ArrayOps.hyperslice` and `ArrayOps.restrict_table`. It takes no part in equality, `repr` - #: or fingerprinting. - _array_ops_meta: Any = dataclasses.field( + #: Opaque value owned by the `ArrayOps` of the table; its contract is in `ArrayOps`. + #: Shared code only stores it and passes it on: `restrict` gives the restricted + #: connectivity the same object, `dataclasses.replace` and `copy` keep it, and it is + #: passed as `state` to `ArrayOps.hyperslice` and `ArrayOps.restrict_table`. It is `None` + #: unless the library built the connectivity with one. It takes no part in equality, + #: `repr` or fingerprinting. + _array_ops_state: Any = dataclasses.field( default=None, kw_only=True, compare=False, @@ -524,7 +525,7 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: assert common.UnitRange.is_finite(image_range) slices = array_ops.of(self._ndarray).hyperslice( - self._ndarray, image_range, self.skip_value, meta=self._array_ops_meta + self._ndarray, image_range, self.skip_value, state=self._array_ops_state ) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -541,10 +542,14 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: cached = self._cache[cache_key] = (*self._slice(index), {}) new_domain, buffer_slice, restricted_cache = cached table = array_ops.of(self._ndarray).restrict_table( - self._ndarray, buffer_slice, meta=self._array_ops_meta + self._ndarray, buffer_slice, state=self._array_ops_state ) restricted_connectivity = self.__class__( - new_domain, table, self.codomain, self.skip_value, _array_ops_meta=self._array_ops_meta + new_domain, + table, + self.codomain, + self.skip_value, + _array_ops_state=self._array_ops_state, ) restricted_connectivity.__dict__["_cache"] = restricted_cache return restricted_connectivity diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index 3f9f9902f8..6f8550108c 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -619,15 +619,61 @@ def test_jax_pytree_rejects_connectivities_of_other_libraries(): @pytest.mark.requires_jax -def test_jax_pytree_of_concrete_connectivity_has_no_array_ops_meta(): +def test_jax_pytree_of_concrete_connectivity_has_no_array_ops_state(): import jax E, field, conn_a, _ = _jax_narrowing_setup() rebuilt = jax.tree.map(lambda table: table + 1, conn_a) - assert rebuilt._array_ops_meta is None + assert rebuilt._array_ops_state is None # targets 1, 2, 3, 4, 6 of a field on V:(1,4) result = field.premap(rebuilt) assert result.domain == common.domain({E: (0, 3)}) np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_vmap_premap_over_connectivities_has_no_values(): + import jax + + _, field, conn_a, conn_b = _jax_narrowing_setup() + stacked = jax.tree.unflatten( + jax.tree.structure(conn_a), [jax.numpy.stack([conn_a.ndarray, conn_b.ndarray])] + ) + + result = jax.vmap(lambda conn: field.premap(conn).ndarray)(stacked) + + # each element is a table without values: not narrowed, out-of-range targets clamped + np.testing.assert_array_equal( + np.asarray(result), [[10.0, 10.0, 20.0, 30.0, 30.0], [10.0, 20.0, 30.0, 10.0, 30.0]] + ) + + +@pytest.mark.requires_jax +def test_jax_jit_premap_ignores_array_ops_state_of_another_library(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + def premap(field, conn): + return field.premap(dataclasses.replace(conn, _array_ops_state=object())) + + result = jax.jit(premap)(field, conn_a) + + assert result.domain == common.domain({E: (0, 5)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 20.0, 30.0, 30.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_cond_returning_field(): + import jax + + _, field, _, _ = _jax_narrowing_setup() + + result = jax.jit( + lambda predicate, field: jax.lax.cond(predicate, lambda: field, lambda: field * 2.0) + )(False, field) + + assert result.domain == field.domain + np.testing.assert_array_equal(result.asnumpy(), [20.0, 40.0, 60.0]) From a5cafba35642343f0aa10ffbd8e1309c5410c279 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 16 Nov 2026 15:03:56 +0100 Subject: [PATCH 083/166] docs[next]: drop the link to the superseded design proposal from ADR 0029 --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 906433fc41..8428afbbd1 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -92,5 +92,4 @@ Accepting only concrete tables rules out dynamic offsets under `jit`. NaN makes ## References -- [Design proposal](https://github.com/GridTools/gt4py_knowledge/pull/25) - [ADR 0019 - Connectivities](0019-Connectivities.md) From 40fa394e86c72265fa3bf3648aa860d7da853241 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 16 Nov 2026 15:08:30 +0100 Subject: [PATCH 084/166] docs[next]: state the contract of a connectivity's ArrayOps state in the ArrayOps docstring --- src/gt4py/next/embedded/array_ops.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 88a2b61878..d75770eab7 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -65,6 +65,18 @@ class ArrayOps: `xp` is the Array API namespace of the buffers. Field code uses `xp` directly for standard functions and the methods of this class wherever a library may need to differ; those methods are the override points. + + The operations on a connectivity table (`hyperslice`, `restrict_table`) take the + connectivity's `_array_ops_state` as `state`: `None`, or the object a library passed + when it built the connectivity (for example in its pytree unflatten). Only that + library reads or changes it. The same object reaches every connectivity restricted + or copied from that one, also when the table was replaced, possibly by an array of + another library. So an implementation + + - identifies the table a `state` describes itself and trusts no other pairing, + - treats a `state` it did not create like `None`, + - works with `None`: shared code may drop it, and a connectivity built from an + array never has one. """ #: Replacements of whole `fbuiltins` implementations for fields of this namespace. @@ -189,16 +201,6 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array - # The operations on a connectivity table. `state` is the connectivity's `_array_ops_state`: - # `None`, or the object a library passed when it built a connectivity (for example in - # its pytree unflatten). Only that library reads or changes it. The same object reaches - # every connectivity restricted or copied from that one, also when the table was - # replaced, possibly by an array of another library. So an implementation - # - identifies the table a `state` describes itself and trusts no other pairing, - # - treats a `state` it did not create like `None`, - # - works with `None`: shared code may drop it, and a connectivity built from an array - # never has one. - def hyperslice( self, table: core_defs.NDArrayObject, @@ -258,7 +260,7 @@ def restrict_table( def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: - """Return `array[indices]` for one integer index array per axis, all of the same shape.""" + """Return `array[indices]` for one integer index array per axis, broadcast against each other.""" return array[indices] def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: From 2208679105ce933bec7d46378a0bf803b48cd247 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 17 Nov 2026 19:40:36 +0100 Subject: [PATCH 085/166] refactor[next]: separate connectivity caches per operation, build restrictions with dataclasses.replace Also name the array argument of ArrayOps.hyperslice and restrict_table ndarray. --- .../next/embedded/array_libraries/jax_ops.py | 16 ++++---- src/gt4py/next/embedded/array_ops.py | 22 +++++------ src/gt4py/next/embedded/nd_array_field.py | 38 +++++++++---------- .../embedded_tests/test_nd_array_field.py | 8 ++-- 4 files changed, 41 insertions(+), 43 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index cf715ff934..95bd9a0948 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -149,33 +149,33 @@ def setitem( def hyperslice( self, - table: core_defs.NDArrayObject, + ndarray: core_defs.NDArrayObject, image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, *, state: Any = None, ) -> Optional[tuple[slice, ...]]: - values = _values(table, state) + values = _values(ndarray, state) if values is None: - return (slice(None),) * table.ndim + return (slice(None),) * ndarray.ndim with jax.ensure_compile_time_eval(): return super().hyperslice(values, image_range, skip_value) def restrict_table( self, - table: core_defs.NDArrayObject, + ndarray: core_defs.NDArrayObject, key: common.RelativeIndexSequence, *, state: Any = None, ) -> core_defs.NDArrayObject: - values = _values(table, state) + values = _values(ndarray, state) if values is None: - return super().restrict_table(table, key) + return super().restrict_table(ndarray, key) restricted_values = _restrict_values(values, key) - if values is table: + if values is ndarray: return restricted_values assert isinstance(state, _StaticValues) - restricted = super().restrict_table(table, key) + restricted = super().restrict_table(ndarray, key) state.add_restricted(restricted, restricted_values) return restricted diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index d75770eab7..a1456d455e 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -203,31 +203,31 @@ def setitem( def hyperslice( self, - table: core_defs.NDArrayObject, + ndarray: core_defs.NDArrayObject, image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, *, state: Any = None, ) -> Optional[tuple[slice, ...]]: """ - Return the hypercube slice that contains all indices in `table` that are within `image_range`, or `None` if no such hypercube exists. + Return the hypercube slice that contains all indices in `ndarray` that are within `image_range`, or `None` if no such hypercube exists. If `skip_value` is given, the selected values are ignored. It returns the smallest hypercube. A bigger hypercube could be constructed by adding lines that contain only `skip_value`s. Example: - table = 0 1 -1 - 3 4 -1 - -1 -1 -1 + ndarray = 0 1 -1 + 3 4 -1 + -1 -1 -1 skip_value = -1 would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. - A library which cannot read the values of `table` returns all of it. What an entry + A library which cannot read the values of `ndarray` returns all of it. What an entry outside of `image_range` reads is then defined by its `gather`. """ xp = self.xp - select_mask = (table >= image_range.start) & (table < image_range.stop) + select_mask = (ndarray >= image_range.start) & (ndarray < image_range.stop) if not xp.any(select_mask): return None @@ -240,7 +240,7 @@ def hyperslice( ) hcube = select_mask[tuple(slices)] if skip_value is not None: - ignore_mask = table == skip_value + ignore_mask = ndarray == skip_value hcube = hcube | ignore_mask[tuple(slices)] if not xp.all(hcube): return None @@ -249,13 +249,13 @@ def hyperslice( def restrict_table( self, - table: core_defs.NDArrayObject, + ndarray: core_defs.NDArrayObject, key: common.RelativeIndexSequence, *, state: Any = None, ) -> core_defs.NDArrayObject: - """Return `table[key]`.""" - return self.asarray(table[key]) + """Return `ndarray[key]`.""" + return self.asarray(ndarray[key]) def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index ff226a60b0..870a865088 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -504,17 +504,19 @@ def codomain(self) -> common.DimT: # type: ignore[override] # TODO(havogt): ins def skip_value(self) -> Optional[core_defs.IntegralScalar]: return self._skip_value - # This embedded run-time cache is only used to speed up repeated calls to - # `_inverse_image` and `restrict`, and it should not be considered part of - # the connectivity field definition, and therefore it should not be serialized. + # These embedded run-time caches are only used to speed up repeated calls to + # `_inverse_image` and `restrict`, and they should not be considered part of + # the connectivity field definition, and therefore they should not be serialized. @functools.cached_property - def _cache(self) -> dict: + def _inverse_image_cache(self) -> dict[common.UnitRange, common.Domain]: return {} - def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: - cache_key = ("inverse_image", image_range) + @functools.cached_property + def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: + return {} - if (new_domain := self._cache.get(cache_key, None)) is None: + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: + if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: assert common.UnitRange.is_finite(image_range) slices = array_ops.of(self._ndarray).hyperslice( @@ -524,7 +526,7 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: raise ValueError("Restriction generates non-contiguous or empty dimensions.") new_domain = self.domain.slice_at[slices] - self._cache[cache_key] = new_domain + self._inverse_image_cache[image_range] = new_domain return new_domain @@ -537,21 +539,15 @@ def __setitem__( def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: # Arrays must not be cached: whether a restricted table can be used again is up to its library - cache_key = ("restrict", index) - if (cached := self._cache.get(cache_key, None)) is None: - cached = self._cache[cache_key] = (*self._slice(index), {}) - new_domain, buffer_slice, restricted_cache = cached - table = array_ops.of(self._ndarray).restrict_table( + if (cached := self._restrict_cache.get(index, None)) is None: + cached = self._restrict_cache[index] = (*self._slice(index), {}, {}) + new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached + ndarray = array_ops.of(self._ndarray).restrict_table( self._ndarray, buffer_slice, state=self._array_ops_state ) - restricted_connectivity = self.__class__( - new_domain, - table, - self.codomain, - self.skip_value, - _array_ops_state=self._array_ops_state, - ) - restricted_connectivity.__dict__["_cache"] = restricted_cache + restricted_connectivity = dataclasses.replace(self, _domain=new_domain, _ndarray=ndarray) + restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache + restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache return restricted_connectivity __getitem__ = restrict diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 6bde001ce8..a9c9ed5524 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -1900,7 +1900,7 @@ def test_nd_array_connectivity_field_getstate_excludes_runtime_caches(): ) _ = e2v_conn._inverse_image(UnitRange(2, 5)) - assert "_cache" in e2v_conn.__dict__ + assert "_inverse_image_cache" in e2v_conn.__dict__ _ = e2v_conn.__gt_buffer_info__ assert "__gt_buffer_info__" in e2v_conn.__dict__ @@ -1908,7 +1908,8 @@ def test_nd_array_connectivity_field_getstate_excludes_runtime_caches(): state = e2v_conn.__getstate__() assert state["_codomain"] == V assert state["_skip_value"] is None - assert "_cache" not in state + assert "_inverse_image_cache" not in state + assert "_restrict_cache" not in state assert "__gt_buffer_info__" not in state @@ -1933,7 +1934,8 @@ def test_nd_array_connectivity_field_setstate_restores_state_without_caches(): assert restored.codomain == original.codomain assert restored.skip_value == original.skip_value assert np.array_equal(restored.ndarray, original.ndarray) - assert "_cache" not in restored.__dict__ + assert "_inverse_image_cache" not in restored.__dict__ + assert "_restrict_cache" not in restored.__dict__ assert "__gt_buffer_info__" not in restored.__dict__ From ea7f64ac887d107f838b33df86e62f0c4c20e84e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 17 Nov 2026 21:19:27 +0100 Subject: [PATCH 086/166] refactor[next]: move connectivity table operations from ArrayOps to per-connectivity ConnectivityOps --- .../next/embedded/array_libraries/jax_ops.py | 154 ++++++++---------- src/gt4py/next/embedded/array_ops.py | 75 +-------- src/gt4py/next/embedded/connectivity_ops.py | 83 ++++++++++ src/gt4py/next/embedded/nd_array_field.py | 33 ++-- .../embedded_tests/test_nd_array_field.py | 11 +- .../test_nd_array_field_with_jax.py | 18 +- 6 files changed, 177 insertions(+), 197 deletions(-) create mode 100644 src/gt4py/next/embedded/connectivity_ops.py diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 95bd9a0948..043ab0eeda 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -11,17 +11,18 @@ Everything gt4py knows about JAX tracing is in this module (ADR 0029). A connectivity table inside a trace is in one of three cases, told apart by -`_values`: +`JaxConnectivityOps.values`: - concrete: operations reading its values run under `jax.ensure_compile_time_eval`; - a tracer standing for a concrete table, which it got as a pytree leaf, or - restricted from such a tracer: the values are read from `_StaticValues`; + restricted from such a tracer: the values are those of the concrete table; - any other tracer: there are no values, all its targets are assumed to be in range and the gather clamps them. """ from __future__ import annotations +import dataclasses import weakref from collections.abc import Callable, Mapping from typing import Any, ClassVar, Optional, TypeAlias @@ -33,7 +34,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import common -from gt4py.next.embedded import array_ops, nd_array_field +from gt4py.next.embedded import array_ops, connectivity_ops, nd_array_field from gt4py.next.ffront import experimental, fbuiltins @@ -72,55 +73,55 @@ def __repr__(self) -> str: return f"" -class _StaticValues: - """ - The concrete values of `table`, a placeholder of a trace, and of the tables restricted from it. +def _has_values(ndarray: Any) -> bool: + return isinstance(ndarray, jax.Array) and not isinstance(ndarray, jax.core.Tracer) - Tables are found by identity, so any other table has no values here. - """ - __slots__ = ("_restricted", "table", "values") - - def __init__(self, values: core_defs.NDArrayObject, table: Any) -> None: - self.values = values - self.table = table - # weak: a restricted table may belong to a trace which ends before the one of `table` - self._restricted = _WeakIdDict() - - def add_restricted(self, table: Any, values: core_defs.NDArrayObject) -> None: - self._restricted[table] = values - - def get(self, table: Any) -> Optional[core_defs.NDArrayObject]: - return self.values if table is self.table else self._restricted.get(table) - - -def _has_values(table: Any) -> bool: - return isinstance(table, jax.Array) and not isinstance(table, jax.core.Tracer) - - -def _values(table: Any, state: Any) -> Optional[core_defs.NDArrayObject]: - """Return the concrete array with the values of `table`, `None` if they exist only at run time.""" - if _has_values(table): - return table - return state.get(table) if isinstance(state, _StaticValues) else None - - -#: per concrete table, its restrictions by key: restricting the same table again returns the same -#: array, which the pytree aux data identifies +#: per concrete table, its restrictions by buffer slice: restricting the same table again returns +#: the same array, which the pytree aux data identifies _restricted_values = _WeakIdDict() def _restrict_values( - values: core_defs.NDArrayObject, key: common.RelativeIndexSequence + values: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence ) -> core_defs.NDArrayObject: - if (by_key := _restricted_values.get(values)) is None: - by_key = _restricted_values[values] = {} - if (restricted := by_key.get(key)) is None: + if (by_slice := _restricted_values.get(values)) is None: + by_slice = _restricted_values[values] = {} + if (restricted := by_slice.get(buffer_slice)) is None: with jax.ensure_compile_time_eval(): - restricted = by_key[key] = values[key] + restricted = by_slice[buffer_slice] = values[buffer_slice] return restricted +@dataclasses.dataclass(frozen=True) +class JaxConnectivityOps(connectivity_ops.ConnectivityOps): + #: The concrete array with the values of the connectivity's table, `None` if they exist + #: only at run time. The table itself if it is concrete. + values: Optional[core_defs.NDArrayObject] = None + + def hyperslice( + self, + ndarray: core_defs.NDArrayObject, + image_range: common.UnitRange, + skip_value: Optional[core_defs.IntegralScalar] = None, + ) -> Optional[tuple[slice, ...]]: + if self.values is None: + return (slice(None),) * ndarray.ndim + with jax.ensure_compile_time_eval(): + return super().hyperslice(self.values, image_range, skip_value) + + def restrict( + self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence + ) -> tuple[core_defs.NDArrayObject, connectivity_ops.ConnectivityOps]: + if self.values is None: + return super().restrict(ndarray, buffer_slice) + values = _restrict_values(self.values, buffer_slice) + restricted = ( + values if self.values is ndarray else super().restrict(ndarray, buffer_slice)[0] + ) + return restricted, dataclasses.replace(self, values=values) + + def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: # adding the coordinates would stage the table under a trace even for concrete offsets with jax.ensure_compile_time_eval(): @@ -147,37 +148,8 @@ def setitem( ) -> core_defs.NDArrayObject: return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - def hyperslice( - self, - ndarray: core_defs.NDArrayObject, - image_range: common.UnitRange, - skip_value: Optional[core_defs.IntegralScalar] = None, - *, - state: Any = None, - ) -> Optional[tuple[slice, ...]]: - values = _values(ndarray, state) - if values is None: - return (slice(None),) * ndarray.ndim - with jax.ensure_compile_time_eval(): - return super().hyperslice(values, image_range, skip_value) - - def restrict_table( - self, - ndarray: core_defs.NDArrayObject, - key: common.RelativeIndexSequence, - *, - state: Any = None, - ) -> core_defs.NDArrayObject: - values = _values(ndarray, state) - if values is None: - return super().restrict_table(ndarray, key) - restricted_values = _restrict_values(values, key) - if values is ndarray: - return restricted_values - assert isinstance(state, _StaticValues) - restricted = super().restrict_table(ndarray, key) - state.add_restricted(restricted, restricted_values) - return restricted + def connectivity_ops(self, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: + return JaxConnectivityOps(self.xp, ndarray if _has_values(ndarray) else None) def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] @@ -232,14 +204,20 @@ def _unflatten_field( def _flatten_connectivity( connectivity: nd_array_field.NdArrayConnectivityField, ) -> tuple[tuple[core_defs.NDArrayObject], _ConnectivityAuxData]: - table = connectivity._ndarray + ndarray = connectivity._ndarray # the aux data identifies the values of a table by its buffer, which a mutable array does not # allow. The placeholders of JAX are array API objects too, so "not a JAX array" is no test. - assert not (array_api_compat.is_numpy_array(table) or array_api_compat.is_cupy_array(table)), ( - f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(table)}'." + assert not ( + array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) + ), f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." + # a placeholder has no `ArrayOps`, only the ones `_unflatten_connectivity` attached + ops = ( + connectivity._connectivity_ops + if isinstance(ndarray, jax.Array) + else connectivity.__dict__.get("_connectivity_ops") ) - values = _values(table, connectivity._array_ops_state) - return (table,), ( + values = ops.values if isinstance(ops, JaxConnectivityOps) else None + return (ndarray,), ( connectivity.domain, connectivity.codomain, connectivity.skip_value, @@ -251,20 +229,20 @@ def _unflatten_connectivity( aux_data: _ConnectivityAuxData, children: tuple[core_defs.NDArrayObject] ) -> nd_array_field.NdArrayConnectivityField: domain, codomain, skip_value, identity = aux_data - (table,) = children + (ndarray,) = children + connectivity: nd_array_field.NdArrayConnectivityField = nd_array_field.NdArrayConnectivityField( + domain, ndarray, codomain, skip_value + ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' # a child without values stands for the flattened table: a tracer, or one of the placeholders # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. Under `vmap` the # child is one element of the flattened table, whose values the aux data does not have. - state = ( - None - if identity is None - or _has_values(table) - or getattr(table, "shape", identity.values.shape) != identity.values.shape - else _StaticValues(identity.values, table) - ) - return nd_array_field.NdArrayConnectivityField( - domain, table, codomain, skip_value, _array_ops_state=state - ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' + if not ( + identity is None + or _has_values(ndarray) + or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape + ): + connectivity.__dict__["_connectivity_ops"] = JaxConnectivityOps(jnp, identity.values) + return connectivity # jax registers pytree nodes by exact type, so the connectivity needs its own registration diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index a1456d455e..ed02550ec3 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -25,7 +25,7 @@ import dataclasses from collections.abc import Callable, Mapping from types import ModuleType -from typing import Any, ClassVar, Final, Optional +from typing import Any, ClassVar, Final import array_api_compat import array_api_compat.numpy as compat_numpy @@ -33,6 +33,7 @@ from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.next import common +from gt4py.next.embedded import connectivity_ops #: gt4py builtin and operator names whose Array API name differs. @@ -65,18 +66,6 @@ class ArrayOps: `xp` is the Array API namespace of the buffers. Field code uses `xp` directly for standard functions and the methods of this class wherever a library may need to differ; those methods are the override points. - - The operations on a connectivity table (`hyperslice`, `restrict_table`) take the - connectivity's `_array_ops_state` as `state`: `None`, or the object a library passed - when it built the connectivity (for example in its pytree unflatten). Only that - library reads or changes it. The same object reaches every connectivity restricted - or copied from that one, also when the table was replaced, possibly by an array of - another library. So an implementation - - - identifies the table a `state` describes itself and trusts no other pairing, - - treats a `state` it did not create like `None`, - - works with `None`: shared code may drop it, and a connectivity built from an - array never has one. """ #: Replacements of whole `fbuiltins` implementations for fields of this namespace. @@ -201,61 +190,11 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array - def hyperslice( - self, - ndarray: core_defs.NDArrayObject, - image_range: common.UnitRange, - skip_value: Optional[core_defs.IntegralScalar] = None, - *, - state: Any = None, - ) -> Optional[tuple[slice, ...]]: - """ - Return the hypercube slice that contains all indices in `ndarray` that are within `image_range`, or `None` if no such hypercube exists. - - If `skip_value` is given, the selected values are ignored. It returns the smallest hypercube. - A bigger hypercube could be constructed by adding lines that contain only `skip_value`s. - - Example: - ndarray = 0 1 -1 - 3 4 -1 - -1 -1 -1 - skip_value = -1 - - would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. - - A library which cannot read the values of `ndarray` returns all of it. What an entry - outside of `image_range` reads is then defined by its `gather`. - """ - xp = self.xp - select_mask = (ndarray >= image_range.start) & (ndarray < image_range.stop) - - if not xp.any(select_mask): - return None - - nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) - - slices = tuple( - slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) - for dim_nnz_indices in nnz - ) - hcube = select_mask[tuple(slices)] - if skip_value is not None: - ignore_mask = ndarray == skip_value - hcube = hcube | ignore_mask[tuple(slices)] - if not xp.all(hcube): - return None - - return slices - - def restrict_table( - self, - ndarray: core_defs.NDArrayObject, - key: common.RelativeIndexSequence, - *, - state: Any = None, - ) -> core_defs.NDArrayObject: - """Return `ndarray[key]`.""" - return self.asarray(ndarray[key]) + def connectivity_ops( + self, ndarray: core_defs.NDArrayObject + ) -> connectivity_ops.ConnectivityOps: + """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`.""" + return connectivity_ops.ConnectivityOps(self.xp) def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py new file mode 100644 index 0000000000..f74ddaab9b --- /dev/null +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -0,0 +1,83 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""Operations of the embedded connectivities that read the values of their table.""" + +from __future__ import annotations + +import dataclasses +from types import ModuleType +from typing import Optional + +from gt4py._core import definitions as core_defs +from gt4py.next import common + + +@dataclasses.dataclass(frozen=True) +class ConnectivityOps: + """ + Operations on the buffer of one connectivity. + + An instance belongs to one connectivity and is never inherited by a copy of it: + `ArrayOps.connectivity_ops` creates it from the connectivity's buffer, and `restrict` + returns the one of the restricted buffer. A library whose connectivities know more + about their buffer than the buffer itself, e.g. the values of a traced table, + subclasses `ConnectivityOps` and keeps that in its instances. + """ + + xp: ModuleType + + def hyperslice( + self, + ndarray: core_defs.NDArrayObject, + image_range: common.UnitRange, + skip_value: Optional[core_defs.IntegralScalar] = None, + ) -> Optional[tuple[slice, ...]]: + """ + Return the hypercube slice that contains all indices in `ndarray` that are within `image_range`, or `None` if no such hypercube exists. + + If `skip_value` is given, the selected values are ignored. It returns the smallest hypercube. + A bigger hypercube could be constructed by adding lines that contain only `skip_value`s. + + Example: + ndarray = 0 1 -1 + 3 4 -1 + -1 -1 -1 + skip_value = -1 + + would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. + + An implementation which cannot read the values of `ndarray` returns all of it. What an + entry outside of `image_range` reads is then defined by `ArrayOps.gather`. + """ + xp = self.xp + select_mask = (ndarray >= image_range.start) & (ndarray < image_range.stop) + + if not xp.any(select_mask): + return None + + nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) + + slices = tuple( + slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) + for dim_nnz_indices in nnz + ) + hcube = select_mask[tuple(slices)] + if skip_value is not None: + ignore_mask = ndarray == skip_value + hcube = hcube | ignore_mask[tuple(slices)] + if not xp.all(hcube): + return None + + return slices + + def restrict( + self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence + ) -> tuple[core_defs.NDArrayObject, ConnectivityOps]: + """Return `ndarray[buffer_slice]` and the `ConnectivityOps` of the restricted connectivity.""" + return self.xp.asarray(ndarray[buffer_slice]), self diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 870a865088..5a486ae544 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -21,10 +21,11 @@ from numpy import typing as npt from gt4py._core import definitions as core_defs -from gt4py.next import common, utils +from gt4py.next import common from gt4py.next.embedded import ( array_ops, common as embedded_common, + connectivity_ops, context as embedded_context, exceptions as embedded_exceptions, ) @@ -454,19 +455,6 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: Opaque value owned by the `ArrayOps` of the table; its contract is in `ArrayOps`. - #: Shared code only stores it and passes it on: `restrict` gives the restricted - #: connectivity the same object, `dataclasses.replace` and `copy` keep it, and it is - #: passed as `state` to `ArrayOps.hyperslice` and `ArrayOps.restrict_table`. It is `None` - #: unless the library built the connectivity with one. It takes no part in equality, - #: `repr` or fingerprinting. - _array_ops_state: Any = dataclasses.field( - default=None, - kw_only=True, - compare=False, - repr=False, - metadata=utils.gt4py_metadata(fingerprint=False), - ) @classmethod def from_array( # type: ignore[override] @@ -515,13 +503,17 @@ def _inverse_image_cache(self) -> dict[common.UnitRange, common.Domain]: def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: return {} + # Not a field, so that no copy inherits it: `restrict` and a library rebuilding a + # connectivity set it, otherwise it is created from the buffer. + @functools.cached_property + def _connectivity_ops(self) -> connectivity_ops.ConnectivityOps: + return array_ops.of(self._ndarray).connectivity_ops(self._ndarray) + def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: assert common.UnitRange.is_finite(image_range) - slices = array_ops.of(self._ndarray).hyperslice( - self._ndarray, image_range, self.skip_value, state=self._array_ops_state - ) + slices = self._connectivity_ops.hyperslice(self._ndarray, image_range, self.skip_value) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -538,16 +530,15 @@ def __setitem__( raise TypeError("'Connectivity' does not support item assignment.") def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: - # Arrays must not be cached: whether a restricted table can be used again is up to its library + # Arrays and `ConnectivityOps` must not be cached: whether they can be used again is up to their library if (cached := self._restrict_cache.get(index, None)) is None: cached = self._restrict_cache[index] = (*self._slice(index), {}, {}) new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached - ndarray = array_ops.of(self._ndarray).restrict_table( - self._ndarray, buffer_slice, state=self._array_ops_state - ) + ndarray, ops = self._connectivity_ops.restrict(self._ndarray, buffer_slice) restricted_connectivity = dataclasses.replace(self, _domain=new_domain, _ndarray=ndarray) restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache + restricted_connectivity.__dict__["_connectivity_ops"] = ops return restricted_connectivity __getitem__ = restrict diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index a9c9ed5524..b272ebe828 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -29,6 +29,7 @@ ) from gt4py.next.embedded import ( array_ops, + connectivity_ops, context as embedded_context, exceptions as embedded_exceptions, nd_array_field, @@ -2111,7 +2112,11 @@ def test_hyperslice(index_array, expected): expected = tuple(slice(*e) for e in expected) if expected is not None else None - result = array_ops.of(index_array).hyperslice(index_array, image_range, skip_value) + result = ( + array_ops.of(index_array) + .connectivity_ops(index_array) + .hyperslice(index_array, image_range, skip_value) + ) assert result == expected @@ -2344,14 +2349,14 @@ def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): ) field = common._field(np.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) calls = 0 - hyperslice = array_ops.ArrayOps.hyperslice + hyperslice = connectivity_ops.ConnectivityOps.hyperslice def counting_hyperslice(*args, **kwargs): nonlocal calls calls += 1 return hyperslice(*args, **kwargs) - monkeypatch.setattr(array_ops.ArrayOps, "hyperslice", counting_hyperslice) + monkeypatch.setattr(connectivity_ops.ConnectivityOps, "hyperslice", counting_hyperslice) for _ in range(3): result = field.premap(conn[NamedIndex(E2VDim, 0)]) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index 6f8550108c..0b2531be21 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -619,14 +619,13 @@ def test_jax_pytree_rejects_connectivities_of_other_libraries(): @pytest.mark.requires_jax -def test_jax_pytree_of_concrete_connectivity_has_no_array_ops_state(): +def test_jax_pytree_of_concrete_connectivity_reads_its_own_values(): import jax E, field, conn_a, _ = _jax_narrowing_setup() rebuilt = jax.tree.map(lambda table: table + 1, conn_a) - assert rebuilt._array_ops_state is None # targets 1, 2, 3, 4, 6 of a field on V:(1,4) result = field.premap(rebuilt) assert result.domain == common.domain({E: (0, 3)}) @@ -650,21 +649,6 @@ def test_jax_vmap_premap_over_connectivities_has_no_values(): ) -@pytest.mark.requires_jax -def test_jax_jit_premap_ignores_array_ops_state_of_another_library(): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - - def premap(field, conn): - return field.premap(dataclasses.replace(conn, _array_ops_state=object())) - - result = jax.jit(premap)(field, conn_a) - - assert result.domain == common.domain({E: (0, 5)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 20.0, 30.0, 30.0]) - - @pytest.mark.requires_jax def test_jax_jit_cond_returning_field(): import jax From 34d3cf02755d25759caa7626203e7e652644e17b Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 17 Nov 2026 21:20:00 +0100 Subject: [PATCH 087/166] docs[next]: ADR 0029 describes the per-connectivity ConnectivityOps --- .../0029-Connectivities_Under_JAX_Tracing.md | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 8428afbbd1..971b88d2c4 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -7,7 +7,7 @@ tags: [embedded, jax, connectivities] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) - **Created**: 2026-11-06 -- **Updated**: 2026-11-13 +- **Updated**: 2026-11-17 In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to pass the concrete table along with its tracer through the pytree aux data of the connectivity, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime. @@ -22,15 +22,15 @@ Narrowing is the common case: the field usually covers only part of the connecti ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations on a table are methods of `ArrayOps`: `hyperslice` (domain inference), `restrict_table` and `gather`. Their defaults are plain array code. `JaxOps` overrides them, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `hyperslice` (domain inference) and `restrict`, are methods of `ConnectivityOps`. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. -A connectivity stores one opaque value for its `ArrayOps`, `_array_ops_state`, and hands it as `state` to `hyperslice` and `restrict_table`. Only the library creates it, and `restrict` passes it on unchanged. For a table that is a tracer, `JaxOps` keeps there the concrete array with the same values, the static values, for that tracer and for the tracers restricted from it. Tables are looked up by identity, so a connectivity that got another table, for example through `dataclasses.replace`, has none. +Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: `restrict` sets the one returned for the restricted table, a library rebuilding a connectivity, as in its pytree unflatten, sets its own, and otherwise `ArrayOps.connectivity_ops` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. `JaxOps.gather` clamps indices to the field at both ends, inside the gather. It does not need to know where an index came from. -The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with static values. Unflattening attaches them to a child that is not a concrete array; a concrete child has its own values. Because identity only stands for the values of an immutable array, flattening rejects a connectivity with a NumPy or CuPy table: such a connectivity can be closed over, but not passed as a `jit` argument. +The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with static values. Unflattening attaches them, as the connectivity's `JaxConnectivityOps`, to a child that is not a concrete array; a concrete child has its own values. Because identity only stands for the values of an immutable array, flattening rejects a connectivity with a NumPy or CuPy table: such a connectivity can be closed over, but not passed as a `jit` argument. -A connectivity caches domains and slices, never tables or restricted connectivities, so nothing cached can belong to a trace that has ended. `JaxOps` returns the same array when the same concrete table is restricted again with the same slice, which keeps a restricted connectivity from retracing. +A connectivity caches domains and slices, never tables, restricted connectivities or `ConnectivityOps`, so nothing cached can belong to a trace that has ended. `JaxConnectivityOps` returns the same array when the same concrete table is restricted again with the same slice, which keeps a restricted connectivity from retracing. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: @@ -59,6 +59,7 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. - `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. +- A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values: its domain is not narrowed and the gather clamps. - The restrictions of a concrete jax table are kept for as long as the table is alive. - Domain inference on static values is cached on the connectivity object, which is new in every trace, so it is repeated per trace but not per call. @@ -72,7 +73,15 @@ Open questions, all caused by the static values in the aux data: ### A connectivity subclass per case -One class each for a concrete table, a traced table with static values and a traced table without, chosen when the connectivity is constructed. This keeps `ArrayOps` free of table operations, but brings back per-library field classes and a second registry next to `ArrayOps`, which a connectivity built with `from_array` bypasses. +One class each for a concrete table, a traced table with static values and a traced table without, chosen when the connectivity is constructed. This brings back per-library field classes, and the case is fixed at construction although `restrict`, a copy and the pytree API change it. + +### An opaque state passed back to `ArrayOps` + +The table operations were methods of `ArrayOps`, which took a `state` stored on the connectivity. Every copy inherited the state, also with another table, possibly of another library, so each operation had to check that the state described its table, and the static values of restricted tracers were kept in a weak map on the state of the connectivity they were restricted from. + +### Static values found by the table + +A map from table to static values, inside `jax_ops.py`, needs no state on the connectivity. But unflattening attaches static values to placeholders like `None`, integers and `object()`, which cannot be weakly referenced, and `None` is the same object everywhere. ### `is_traced` and `concrete_eval` on `ArrayOps` @@ -80,7 +89,7 @@ Two small hooks, with the case distinction written out in `NdArrayConnectivityFi ### Static values that follow the connectivity instead of the table -Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. +Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. `ConnectivityOps` is not inherited, and a concrete table is its own values. ### Bounds in the aux data instead of the table From 48d366c3ce2e61952119aa51b92cebdf7f990715 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 09:19:43 +0100 Subject: [PATCH 088/166] perf[next]: cache restricted connectivities whose ConnectivityOps allow it --- .../next/embedded/array_libraries/jax_ops.py | 4 ++++ src/gt4py/next/embedded/connectivity_ops.py | 4 ++++ src/gt4py/next/embedded/nd_array_field.py | 20 +++++++++---------- .../embedded_tests/test_nd_array_field.py | 13 ++++++++++++ .../test_nd_array_field_with_jax.py | 4 ---- 5 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 043ab0eeda..de9d5539d5 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -110,6 +110,10 @@ def hyperslice( with jax.ensure_compile_time_eval(): return super().hyperslice(self.values, image_range, skip_value) + def may_cache(self, ndarray: core_defs.NDArrayObject) -> bool: + # a tracer belongs to a trace, which may end before the cache + return _has_values(ndarray) + def restrict( self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence ) -> tuple[core_defs.NDArrayObject, connectivity_ops.ConnectivityOps]: diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py index f74ddaab9b..2871dda7e9 100644 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -76,6 +76,10 @@ def hyperslice( return slices + def may_cache(self, ndarray: core_defs.NDArrayObject) -> bool: + """Whether a connectivity with the buffer `ndarray` may be kept beyond the current call, e.g. in a cache.""" + return True + def restrict( self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence ) -> tuple[core_defs.NDArrayObject, ConnectivityOps]: diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 5a486ae544..9f167ae75f 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -500,7 +500,7 @@ def _inverse_image_cache(self) -> dict[common.UnitRange, common.Domain]: return {} @functools.cached_property - def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: + def _restrict_cache(self) -> dict[Any, NdArrayConnectivityField]: return {} # Not a field, so that no copy inherits it: `restrict` and a library rebuilding a @@ -530,15 +530,15 @@ def __setitem__( raise TypeError("'Connectivity' does not support item assignment.") def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: - # Arrays and `ConnectivityOps` must not be cached: whether they can be used again is up to their library - if (cached := self._restrict_cache.get(index, None)) is None: - cached = self._restrict_cache[index] = (*self._slice(index), {}, {}) - new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached - ndarray, ops = self._connectivity_ops.restrict(self._ndarray, buffer_slice) - restricted_connectivity = dataclasses.replace(self, _domain=new_domain, _ndarray=ndarray) - restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache - restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache - restricted_connectivity.__dict__["_connectivity_ops"] = ops + if (restricted_connectivity := self._restrict_cache.get(index, None)) is None: + new_domain, buffer_slice = self._slice(index) + ndarray, ops = self._connectivity_ops.restrict(self._ndarray, buffer_slice) + restricted_connectivity = dataclasses.replace( + self, _domain=new_domain, _ndarray=ndarray + ) + restricted_connectivity.__dict__["_connectivity_ops"] = ops + if ops.may_cache(ndarray): + self._restrict_cache[index] = restricted_connectivity return restricted_connectivity __getitem__ = restrict diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index b272ebe828..136f5f30de 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2338,6 +2338,19 @@ def test_connectivity_field_setitem_raises(): conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) +def test_connectivity_field_restrict_is_cached(): + V = Dimension("V") + E = Dimension("E") + E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) + conn = common._connectivity( + np.asarray([[0, 1], [1, 2], [2, 3]]), + codomain=V, + domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), + ) + + assert conn[NamedIndex(E2VDim, 0)] is conn[NamedIndex(E2VDim, 0)] + + def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): V = Dimension("V") E = Dimension("E") diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index 0b2531be21..718563d86c 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -613,10 +613,6 @@ def test_jax_pytree_rejects_connectivities_of_other_libraries(): with pytest.raises(AssertionError, match="Only connectivities of JAX arrays"): jax.jit(lambda field, conn: field.premap(conn))(field, numpy_conn) - # not a pytree leaf, so it is not flattened - result = jax.jit(lambda field: field.premap(numpy_conn))(field) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) - @pytest.mark.requires_jax def test_jax_pytree_of_concrete_connectivity_reads_its_own_values(): From c98fad3bfb32688e394ef3b1e461ca488ab35480 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 09:19:46 +0100 Subject: [PATCH 089/166] docs[next]: address review of ADR 0029 --- .../0029-Connectivities_Under_JAX_Tracing.md | 28 +++++++------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 971b88d2c4..d3fef65ea9 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -6,19 +6,17 @@ tags: [embedded, jax, connectivities] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) -- **Created**: 2026-11-06 -- **Updated**: 2026-11-17 +- **Created**: 2026-11-18 +- **Updated**: 2026-11-18 -In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to pass the concrete table along with its tracer through the pytree aux data of the connectivity, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime. +In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to pass the concrete table along with its tracer through the pytree aux data of the connectivity, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime (`as_offset`). ## Context -`premap` uses the table in two ways that pull in opposite directions: +`premap` uses the table twice, and needs it at different times: -- The **output domain** comes from `_inverse_image`, which depends on the table's values. Under a trace it needs concrete values, and Python `slice`s cannot be staged. -- The **gather** should take the table as an argument of the compiled program. A closed-over table is inlined as a constant, which does not scale to large meshes. - -Narrowing is the common case: the field usually covers only part of the connectivity's image, so a solution that handles only covering ranges is not sufficient. +- The **output domain** comes from `_inverse_image`, which depends on the table's values. It is computed at trace time, so it needs concrete values: Python `slice`s cannot be staged. +- The **gather** runs in the compiled program, so it should take the table as a run-time argument. A closed-over table is inlined as a constant, which does not scale to large meshes. ## Decision @@ -26,17 +24,15 @@ There is one connectivity class, `NdArrayConnectivityField`, for all array libra Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: `restrict` sets the one returned for the restricted table, a library rebuilding a connectivity, as in its pytree unflatten, sets its own, and otherwise `ArrayOps.connectivity_ops` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. -`JaxOps.gather` clamps indices to the field at both ends, inside the gather. It does not need to know where an index came from. - -The connectivity is a pytree node. The table is the child. The aux data holds domain, codomain, skip value and the static values, compared by the identity of the array: a new wrapper around the same buffer does not retrace, a new buffer does. Flattening emits them if the table is concrete or a tracer with static values. Unflattening attaches them, as the connectivity's `JaxConnectivityOps`, to a child that is not a concrete array; a concrete child has its own values. Because identity only stands for the values of an immutable array, flattening rejects a connectivity with a NumPy or CuPy table: such a connectivity can be closed over, but not passed as a `jit` argument. +The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values. They are compared by identity, so two connectivities have the same aux data only if they have the same static values. Unflattening gives a child that is not a concrete array the static values from the aux data, in its `JaxConnectivityOps`. -A connectivity caches domains and slices, never tables, restricted connectivities or `ConnectivityOps`, so nothing cached can belong to a trace that has ended. `JaxConnectivityOps` returns the same array when the same concrete table is restricted again with the same slice, which keeps a restricted connectivity from retracing. +Nothing that belongs to a trace may be kept beyond it, so a connectivity caches a restricted connectivity only if its `ConnectivityOps` allows it (`may_cache`), which `JaxConnectivityOps` does for a concrete table only. `JaxConnectivityOps` also returns the same array when the same concrete table is restricted again with the same slice. A restriction then has the same aux data in every call, so it does not cause a retrace. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: - **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function; a provider set outside inlines the table as a constant for the reduction. - **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`, because the operations on it run under `jax.ensure_compile_time_eval()`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). -- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field, or any other table that is a tracer without static values). No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the clamp of the gather decides what an out-of-range target reads. +- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field, or any other table that is a tracer without static values). No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed. `JaxOps.gather` clamps every index to the field at both ends, so an out-of-range target reads the field's boundary value. A tracer of any jax transformation counts as traced, not only one of `jit`. In particular a table that depends on a `vmap`ped value has no values even when `vmap` is called eagerly, because it differs per batch element. @@ -58,7 +54,7 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - Every gather of a jax field uses `mode="clip", wrap_negative_indices=False`. That clamps both ends with no operation besides the gather, where jax's default indexing clamps past the end but emits a select to wrap negative indices. With a table that has values the clamp never acts. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. -- `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. +- `restrict` of a traced table builds a new connectivity on every call, with its own domain lookups. - A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values: its domain is not narrowed and the gather clamps. - The restrictions of a concrete jax table are kept for as long as the table is alive. - Domain inference on static values is cached on the connectivity object, which is new in every trace, so it is repeated per trace but not per call. @@ -71,10 +67,6 @@ Open questions, all caused by the static values in the aux data: ## Alternatives considered -### A connectivity subclass per case - -One class each for a concrete table, a traced table with static values and a traced table without, chosen when the connectivity is constructed. This brings back per-library field classes, and the case is fixed at construction although `restrict`, a copy and the pytree API change it. - ### An opaque state passed back to `ArrayOps` The table operations were methods of `ArrayOps`, which took a `state` stored on the connectivity. Every copy inherited the state, also with another table, possibly of another library, so each operation had to check that the state described its table, and the static values of restricted tracers were kept in a weak map on the state of the connectivity they were restricted from. From ec98eaa6551d0f0f3b576ec75d6abfb5826ef95f Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 11:14:14 +0100 Subject: [PATCH 090/166] refactor[next]: ConnectivityOps get their own registry, ArrayOps no longer know about connectivities --- .../0029-Connectivities_Under_JAX_Tracing.md | 4 +- .../next/embedded/array_libraries/jax_ops.py | 7 +-- src/gt4py/next/embedded/array_ops.py | 7 --- src/gt4py/next/embedded/connectivity_ops.py | 48 +++++++++++++++++-- src/gt4py/next/embedded/nd_array_field.py | 2 +- .../embedded_tests/test_nd_array_field.py | 6 +-- 6 files changed, 52 insertions(+), 22 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index d3fef65ea9..4eb1958123 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -20,9 +20,9 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `hyperslice` (domain inference) and `restrict`, are methods of `ConnectivityOps`. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `hyperslice` (domain inference) and `restrict`, are methods of `ConnectivityOps`, which a library registers for its namespace next to its `ArrayOps`. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. -Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: `restrict` sets the one returned for the restricted table, a library rebuilding a connectivity, as in its pytree unflatten, sets its own, and otherwise `ArrayOps.connectivity_ops` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. +Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: `restrict` sets the one returned for the restricted table, a library rebuilding a connectivity, as in its pytree unflatten, sets its own, and otherwise `connectivity_ops.of` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values. They are compared by identity, so two connectivities have the same aux data only if they have the same static values. Unflattening gives a child that is not a concrete array the static values from the aux data, in its `JaxConnectivityOps`. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index de9d5539d5..0e30c7a394 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -110,6 +110,9 @@ def hyperslice( with jax.ensure_compile_time_eval(): return super().hyperslice(self.values, image_range, skip_value) + def for_ndarray(self, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: + return JaxConnectivityOps(self.xp, ndarray if _has_values(ndarray) else None) + def may_cache(self, ndarray: core_defs.NDArrayObject) -> bool: # a tracer belongs to a trace, which may end before the cache return _has_values(ndarray) @@ -152,9 +155,6 @@ def setitem( ) -> core_defs.NDArrayObject: return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - def connectivity_ops(self, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: - return JaxConnectivityOps(self.xp, ndarray if _has_values(ndarray) else None) - def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: @@ -169,6 +169,7 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: array_ops.register(JaxOps(jnp)) +connectivity_ops.register(JaxConnectivityOps(jnp)) # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config jax.config.update("jax_enable_x64", True) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index ed02550ec3..271be258c2 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -33,7 +33,6 @@ from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.next import common -from gt4py.next.embedded import connectivity_ops #: gt4py builtin and operator names whose Array API name differs. @@ -190,12 +189,6 @@ def setitem( array[key] = value # type: ignore[index] # `NDArrayObject` typing is not complete return array - def connectivity_ops( - self, ndarray: core_defs.NDArrayObject - ) -> connectivity_ops.ConnectivityOps: - """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`.""" - return connectivity_ops.ConnectivityOps(self.xp) - def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py index 2871dda7e9..fa9f19ea34 100644 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -6,13 +6,20 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -"""Operations of the embedded connectivities that read the values of their table.""" +""" +Operations of the embedded connectivities that read the values of their table, per array namespace. + +A library that needs different behaviour subclasses `ConnectivityOps` and registers an +instance for its compat namespace with `register`, as for `array_ops.ArrayOps`. +""" from __future__ import annotations import dataclasses from types import ModuleType -from typing import Optional +from typing import Any, Optional + +import array_api_compat from gt4py._core import definitions as core_defs from gt4py.next import common @@ -24,14 +31,18 @@ class ConnectivityOps: Operations on the buffer of one connectivity. An instance belongs to one connectivity and is never inherited by a copy of it: - `ArrayOps.connectivity_ops` creates it from the connectivity's buffer, and `restrict` - returns the one of the restricted buffer. A library whose connectivities know more + `of` creates it from the connectivity's buffer, and `restrict` returns the one of the + restricted buffer. A library whose connectivities know more about their buffer than the buffer itself, e.g. the values of a traced table, subclasses `ConnectivityOps` and keeps that in its instances. """ xp: ModuleType + def for_ndarray(self, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: + """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`, called on the registered instance.""" + return self + def hyperslice( self, ndarray: core_defs.NDArrayObject, @@ -85,3 +96,32 @@ def restrict( ) -> tuple[core_defs.NDArrayObject, ConnectivityOps]: """Return `ndarray[buffer_slice]` and the `ConnectivityOps` of the restricted connectivity.""" return self.xp.asarray(ndarray[buffer_slice]), self + + +_ops_by_namespace: dict[ModuleType, ConnectivityOps] = {} +_ops_by_array_type: dict[type, ConnectivityOps] = {} + + +def register(ops: ConnectivityOps) -> None: + """Use `ops` for the buffers whose compat namespace is `ops.xp`, replacing an earlier registration.""" + _ops_by_namespace[ops.xp] = ops + _ops_by_array_type.clear() + + +def _for_namespace(xp: ModuleType) -> ConnectivityOps: + try: + return _ops_by_namespace[xp] + except KeyError: + ops = _ops_by_namespace[xp] = ConnectivityOps(xp) + return ops + + +def of(ndarray: Any) -> ConnectivityOps: + """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`; raises `TypeError` if it is not an array.""" + try: + ops = _ops_by_array_type[type(ndarray)] + except KeyError: + ops = _ops_by_array_type[type(ndarray)] = _for_namespace( + array_api_compat.array_namespace(ndarray) + ) + return ops.for_ndarray(ndarray) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 9f167ae75f..fbb012cab7 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -507,7 +507,7 @@ def _restrict_cache(self) -> dict[Any, NdArrayConnectivityField]: # connectivity set it, otherwise it is created from the buffer. @functools.cached_property def _connectivity_ops(self) -> connectivity_ops.ConnectivityOps: - return array_ops.of(self._ndarray).connectivity_ops(self._ndarray) + return connectivity_ops.of(self._ndarray) def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 136f5f30de..cd7e2c06a4 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2112,11 +2112,7 @@ def test_hyperslice(index_array, expected): expected = tuple(slice(*e) for e in expected) if expected is not None else None - result = ( - array_ops.of(index_array) - .connectivity_ops(index_array) - .hyperslice(index_array, image_range, skip_value) - ) + result = connectivity_ops.of(index_array).hyperslice(index_array, image_range, skip_value) assert result == expected From a6b3899a8aadf090605051236356b0656740cf11 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 12:15:48 +0100 Subject: [PATCH 091/166] refactor[next]: ConnectivityOps build on the ArrayOps of their namespace --- .../next/embedded/array_libraries/jax_ops.py | 9 +++-- src/gt4py/next/embedded/connectivity_ops.py | 37 +++++++------------ 2 files changed, 18 insertions(+), 28 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 0e30c7a394..3a5ddc7379 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -111,7 +111,7 @@ def hyperslice( return super().hyperslice(self.values, image_range, skip_value) def for_ndarray(self, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: - return JaxConnectivityOps(self.xp, ndarray if _has_values(ndarray) else None) + return JaxConnectivityOps(self.array_ops, ndarray if _has_values(ndarray) else None) def may_cache(self, ndarray: core_defs.NDArrayObject) -> bool: # a tracer belongs to a trace, which may end before the cache @@ -168,8 +168,9 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") -array_ops.register(JaxOps(jnp)) -connectivity_ops.register(JaxConnectivityOps(jnp)) +_jax_ops = JaxOps(jnp) +array_ops.register(_jax_ops) +connectivity_ops.register(JaxConnectivityOps(_jax_ops)) # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config jax.config.update("jax_enable_x64", True) @@ -246,7 +247,7 @@ def _unflatten_connectivity( or _has_values(ndarray) or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape ): - connectivity.__dict__["_connectivity_ops"] = JaxConnectivityOps(jnp, identity.values) + connectivity.__dict__["_connectivity_ops"] = connectivity_ops.of(identity.values) return connectivity diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py index fa9f19ea34..4b60289b67 100644 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -9,8 +9,9 @@ """ Operations of the embedded connectivities that read the values of their table, per array namespace. -A library that needs different behaviour subclasses `ConnectivityOps` and registers an -instance for its compat namespace with `register`, as for `array_ops.ArrayOps`. +`ConnectivityOps` builds on the `array_ops.ArrayOps` of the buffer's namespace. A library +that needs different behaviour subclasses `ConnectivityOps` and registers an instance, +built with its `ArrayOps`, with `register`. """ from __future__ import annotations @@ -19,10 +20,9 @@ from types import ModuleType from typing import Any, Optional -import array_api_compat - from gt4py._core import definitions as core_defs from gt4py.next import common +from gt4py.next.embedded import array_ops @dataclasses.dataclass(frozen=True) @@ -37,7 +37,7 @@ class ConnectivityOps: subclasses `ConnectivityOps` and keeps that in its instances. """ - xp: ModuleType + array_ops: array_ops.ArrayOps def for_ndarray(self, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`, called on the registered instance.""" @@ -66,7 +66,7 @@ def hyperslice( An implementation which cannot read the values of `ndarray` returns all of it. What an entry outside of `image_range` reads is then defined by `ArrayOps.gather`. """ - xp = self.xp + xp = self.array_ops.xp select_mask = (ndarray >= image_range.start) & (ndarray < image_range.stop) if not xp.any(select_mask): @@ -95,33 +95,22 @@ def restrict( self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence ) -> tuple[core_defs.NDArrayObject, ConnectivityOps]: """Return `ndarray[buffer_slice]` and the `ConnectivityOps` of the restricted connectivity.""" - return self.xp.asarray(ndarray[buffer_slice]), self + return self.array_ops.asarray(ndarray[buffer_slice]), self _ops_by_namespace: dict[ModuleType, ConnectivityOps] = {} -_ops_by_array_type: dict[type, ConnectivityOps] = {} def register(ops: ConnectivityOps) -> None: - """Use `ops` for the buffers whose compat namespace is `ops.xp`, replacing an earlier registration.""" - _ops_by_namespace[ops.xp] = ops - _ops_by_array_type.clear() - - -def _for_namespace(xp: ModuleType) -> ConnectivityOps: - try: - return _ops_by_namespace[xp] - except KeyError: - ops = _ops_by_namespace[xp] = ConnectivityOps(xp) - return ops + """Use `ops` for the buffers whose compat namespace is the one of `ops.array_ops`, replacing an earlier registration.""" + _ops_by_namespace[ops.array_ops.xp] = ops def of(ndarray: Any) -> ConnectivityOps: """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`; raises `TypeError` if it is not an array.""" + ops = array_ops.of(ndarray) try: - ops = _ops_by_array_type[type(ndarray)] + registered = _ops_by_namespace[ops.xp] except KeyError: - ops = _ops_by_array_type[type(ndarray)] = _for_namespace( - array_api_compat.array_namespace(ndarray) - ) - return ops.for_ndarray(ndarray) + registered = _ops_by_namespace[ops.xp] = ConnectivityOps(ops) + return registered.for_ndarray(ndarray) From b6c775fd8c030b866b6a364e6791cf27927df5e3 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 12:44:13 +0100 Subject: [PATCH 092/166] refactor[next]: register ConnectivityOps types, pass a connectivity's ops at construction, name the pytree aux data --- .../next/embedded/array_libraries/jax_ops.py | 61 +++++++++++-------- src/gt4py/next/embedded/connectivity_ops.py | 45 +++++++------- src/gt4py/next/embedded/nd_array_field.py | 17 ++++-- src/gt4py/next/otf/compilation_tasks.py | 6 +- .../embedded_tests/test_nd_array_field.py | 11 ++++ 5 files changed, 85 insertions(+), 55 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 3a5ddc7379..aedcea9742 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -7,7 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause """ -`ArrayOps` for JAX arrays, and the embedded fields as JAX pytrees. +`ArrayOps` and `ConnectivityOps` for JAX arrays, and the embedded fields as JAX pytrees. Everything gt4py knows about JAX tracing is in this module (ADR 0029). A connectivity table inside a trace is in one of three cases, told apart by @@ -25,7 +25,7 @@ import dataclasses import weakref from collections.abc import Callable, Mapping -from typing import Any, ClassVar, Optional, TypeAlias +from typing import Any, ClassVar, NamedTuple, Optional import array_api_compat import jax @@ -93,7 +93,7 @@ def _restrict_values( return restricted -@dataclasses.dataclass(frozen=True) +@dataclasses.dataclass(frozen=True, eq=False) class JaxConnectivityOps(connectivity_ops.ConnectivityOps): #: The concrete array with the values of the connectivity's table, `None` if they exist #: only at run time. The table itself if it is concrete. @@ -110,8 +110,11 @@ def hyperslice( with jax.ensure_compile_time_eval(): return super().hyperslice(self.values, image_range, skip_value) - def for_ndarray(self, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: - return JaxConnectivityOps(self.array_ops, ndarray if _has_values(ndarray) else None) + @classmethod + def from_ndarray( + cls, ops: array_ops.ArrayOps, ndarray: core_defs.NDArrayObject + ) -> JaxConnectivityOps: + return cls(ops, ndarray if _has_values(ndarray) else None) def may_cache(self, ndarray: core_defs.NDArrayObject) -> bool: # a tracer belongs to a trace, which may end before the cache @@ -168,9 +171,8 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: raise NotImplementedError("'__gt_buffer_info__' for JAX arrays not yet implemented.") -_jax_ops = JaxOps(jnp) -array_ops.register(_jax_ops) -connectivity_ops.register(JaxConnectivityOps(_jax_ops)) +array_ops.register(JaxOps(jnp)) +connectivity_ops.register(jnp, JaxConnectivityOps) # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config jax.config.update("jax_enable_x64", True) @@ -202,9 +204,11 @@ def _unflatten_field( ) -_ConnectivityAuxData: TypeAlias = tuple[ - common.Domain, common.Dimension, Optional[core_defs.IntegralScalar], Optional[_TableIdentity] -] +class _ConnectivityAuxData(NamedTuple): + domain: common.Domain + codomain: common.Dimension + skip_value: Optional[core_defs.IntegralScalar] + values: Optional[_TableIdentity] def _flatten_connectivity( @@ -216,14 +220,13 @@ def _flatten_connectivity( assert not ( array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) ), f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." - # a placeholder has no `ArrayOps`, only the ones `_unflatten_connectivity` attached - ops = ( - connectivity._connectivity_ops - if isinstance(ndarray, jax.Array) - else connectivity.__dict__.get("_connectivity_ops") - ) + try: + ops = connectivity._connectivity_ops + except TypeError: + # a placeholder that is no array has `ConnectivityOps` only if unflattening gave it some + ops = None values = ops.values if isinstance(ops, JaxConnectivityOps) else None - return (ndarray,), ( + return (ndarray,), _ConnectivityAuxData( connectivity.domain, connectivity.codomain, connectivity.skip_value, @@ -234,21 +237,25 @@ def _flatten_connectivity( def _unflatten_connectivity( aux_data: _ConnectivityAuxData, children: tuple[core_defs.NDArrayObject] ) -> nd_array_field.NdArrayConnectivityField: - domain, codomain, skip_value, identity = aux_data (ndarray,) = children - connectivity: nd_array_field.NdArrayConnectivityField = nd_array_field.NdArrayConnectivityField( - domain, ndarray, codomain, skip_value - ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' + identity = aux_data.values # a child without values stands for the flattened table: a tracer, or one of the placeholders # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. Under `vmap` the # child is one element of the flattened table, whose values the aux data does not have. - if not ( - identity is None + ops = ( + None + if identity is None or _has_values(ndarray) or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape - ): - connectivity.__dict__["_connectivity_ops"] = connectivity_ops.of(identity.values) - return connectivity + else connectivity_ops.of(identity.values) + ) + return nd_array_field.NdArrayConnectivityField( + aux_data.domain, + ndarray, + aux_data.codomain, + aux_data.skip_value, + connectivity_ops=ops, + ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' # jax registers pytree nodes by exact type, so the connectivity needs its own registration diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py index 4b60289b67..7fee2f462f 100644 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -10,8 +10,8 @@ Operations of the embedded connectivities that read the values of their table, per array namespace. `ConnectivityOps` builds on the `array_ops.ArrayOps` of the buffer's namespace. A library -that needs different behaviour subclasses `ConnectivityOps` and registers an instance, -built with its `ArrayOps`, with `register`. +that needs different behaviour subclasses `ConnectivityOps` and registers the subclass for +its namespace with `register`. """ from __future__ import annotations @@ -23,25 +23,28 @@ from gt4py._core import definitions as core_defs from gt4py.next import common from gt4py.next.embedded import array_ops +from gt4py.next.embedded.array_ops import ArrayOps -@dataclasses.dataclass(frozen=True) +@dataclasses.dataclass(frozen=True, eq=False) class ConnectivityOps: """ Operations on the buffer of one connectivity. - An instance belongs to one connectivity and is never inherited by a copy of it: - `of` creates it from the connectivity's buffer, and `restrict` returns the one of the - restricted buffer. A library whose connectivities know more - about their buffer than the buffer itself, e.g. the values of a traced table, - subclasses `ConnectivityOps` and keeps that in its instances. + An instance belongs to one connectivity and is never inherited by a copy of it: `of` + creates it from the connectivity's buffer, and `restrict` returns the one of the + restricted buffer. The `ndarray` its methods take is the buffer of that connectivity. + A library whose connectivities know more about their buffer than the buffer itself, + e.g. the values of a traced table, subclasses `ConnectivityOps` and keeps that in its + instances. """ - array_ops: array_ops.ArrayOps + array_ops: ArrayOps - def for_ndarray(self, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: - """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`, called on the registered instance.""" - return self + @classmethod + def from_ndarray(cls, ops: ArrayOps, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: + """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`, of the namespace of `ops`.""" + return cls(ops) def hyperslice( self, @@ -98,19 +101,19 @@ def restrict( return self.array_ops.asarray(ndarray[buffer_slice]), self -_ops_by_namespace: dict[ModuleType, ConnectivityOps] = {} +_types_by_namespace: dict[ModuleType, type[ConnectivityOps]] = {} -def register(ops: ConnectivityOps) -> None: - """Use `ops` for the buffers whose compat namespace is the one of `ops.array_ops`, replacing an earlier registration.""" - _ops_by_namespace[ops.array_ops.xp] = ops +def register(xp: ModuleType, ops_type: type[ConnectivityOps]) -> None: + """ + Use `ops_type` for the connectivities whose buffer has the compat namespace `xp`. + + Connectivities which already have their `ConnectivityOps` keep them. + """ + _types_by_namespace[xp] = ops_type def of(ndarray: Any) -> ConnectivityOps: """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`; raises `TypeError` if it is not an array.""" ops = array_ops.of(ndarray) - try: - registered = _ops_by_namespace[ops.xp] - except KeyError: - registered = _ops_by_namespace[ops.xp] = ConnectivityOps(ops) - return registered.for_ndarray(ndarray) + return _types_by_namespace.get(ops.xp, ConnectivityOps).from_ndarray(ops, ndarray) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index fbb012cab7..f184e3e3cb 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -29,6 +29,7 @@ context as embedded_context, exceptions as embedded_exceptions, ) +from gt4py.next.embedded.connectivity_ops import ConnectivityOps from gt4py.next.ffront import experimental, fbuiltins @@ -455,6 +456,15 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] + #: The `ConnectivityOps` of the connectivity if its creator knows them, as `restrict` does. + #: Not a field, so that no copy inherits them; without them, they are created from the buffer. + connectivity_ops: dataclasses.InitVar[Optional[ConnectivityOps]] = dataclasses.field( + default=None, kw_only=True + ) + + def __post_init__(self, connectivity_ops: Optional[ConnectivityOps]) -> None: + if connectivity_ops is not None: + self.__dict__["_connectivity_ops"] = connectivity_ops @classmethod def from_array( # type: ignore[override] @@ -503,10 +513,8 @@ def _inverse_image_cache(self) -> dict[common.UnitRange, common.Domain]: def _restrict_cache(self) -> dict[Any, NdArrayConnectivityField]: return {} - # Not a field, so that no copy inherits it: `restrict` and a library rebuilding a - # connectivity set it, otherwise it is created from the buffer. @functools.cached_property - def _connectivity_ops(self) -> connectivity_ops.ConnectivityOps: + def _connectivity_ops(self) -> ConnectivityOps: return connectivity_ops.of(self._ndarray) def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: @@ -534,9 +542,8 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: new_domain, buffer_slice = self._slice(index) ndarray, ops = self._connectivity_ops.restrict(self._ndarray, buffer_slice) restricted_connectivity = dataclasses.replace( - self, _domain=new_domain, _ndarray=ndarray + self, _domain=new_domain, _ndarray=ndarray, connectivity_ops=ops ) - restricted_connectivity.__dict__["_connectivity_ops"] = ops if ops.may_cache(ndarray): self._restrict_cache[index] = restricted_connectivity return restricted_connectivity diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index 147d421f28..6551653bd6 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -24,7 +24,7 @@ import tempfile import typing import weakref -from typing import Any, Callable +from typing import Any, Callable, Optional import numpy as np import xxhash @@ -32,6 +32,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import backend as gtx_backend, common, utils as next_utils from gt4py.next.embedded import nd_array_field +from gt4py.next.embedded.connectivity_ops import ConnectivityOps from gt4py.next.otf import arguments, artifacts, runners, stages from gt4py.next.otf.compilation import cache as _cache @@ -62,7 +63,8 @@ class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): ) _digest: str = dataclasses.field(init=False) - def __post_init__(self) -> None: + def __post_init__(self, connectivity_ops: Optional[ConnectivityOps]) -> None: + super().__post_init__(connectivity_ops) table = np.ascontiguousarray(np.asarray(self._ndarray)) object.__setattr__(self, "_digest", _table_digest(table)) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index cd7e2c06a4..1b3fda00df 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2334,6 +2334,17 @@ def test_connectivity_field_setitem_raises(): conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) +def test_connectivity_ops_use_the_registered_array_ops(monkeypatch): + table = np.asarray([0, 1, 2]) + numpy_ops = array_ops.of(table) + connectivity_ops.of(table) + replacement = dataclasses.replace(numpy_ops) + monkeypatch.setattr(array_ops, "_ops_by_namespace", {numpy_ops.xp: replacement}) + monkeypatch.setattr(array_ops, "_ops_by_array_type", {}) + + assert connectivity_ops.of(table).array_ops is replacement + + def test_connectivity_field_restrict_is_cached(): V = Dimension("V") E = Dimension("E") From 16866496c5ddd8f70adf9b2a55f2914b713dfaf2 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 12:44:13 +0100 Subject: [PATCH 093/166] docs[next]: ADR 0029 on how a connectivity gets its ConnectivityOps --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 4eb1958123..e742440e63 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -20,9 +20,9 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `hyperslice` (domain inference) and `restrict`, are methods of `ConnectivityOps`, which a library registers for its namespace next to its `ArrayOps`. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `hyperslice` (domain inference) and `restrict`, are methods of `ConnectivityOps`, which builds on the library's `ArrayOps`; a library that needs different table operations registers a subclass for its namespace. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. -Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: `restrict` sets the one returned for the restricted table, a library rebuilding a connectivity, as in its pytree unflatten, sets its own, and otherwise `connectivity_ops.of` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. +Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: a creator that knows it passes it at construction, as `restrict` does with the one returned for the restricted table and the pytree unflatten with the static values, and otherwise `connectivity_ops.of` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values. They are compared by identity, so two connectivities have the same aux data only if they have the same static values. Unflattening gives a child that is not a concrete array the static values from the aux data, in its `JaxConnectivityOps`. From 4cc2f106e582268e0d80425dc474246c46e0099a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 12:53:16 +0100 Subject: [PATCH 094/166] style[next]: import the connectivity_ops and array_ops modules, aliased where a field shadows them --- src/gt4py/next/embedded/connectivity_ops.py | 11 ++++++----- src/gt4py/next/embedded/nd_array_field.py | 15 ++++++++------- src/gt4py/next/otf/compilation_tasks.py | 7 ++++--- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py index 7fee2f462f..bc919247ff 100644 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -22,8 +22,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import common -from gt4py.next.embedded import array_ops -from gt4py.next.embedded.array_ops import ArrayOps +from gt4py.next.embedded import array_ops as embedded_array_ops @dataclasses.dataclass(frozen=True, eq=False) @@ -39,10 +38,12 @@ class ConnectivityOps: instances. """ - array_ops: ArrayOps + array_ops: embedded_array_ops.ArrayOps @classmethod - def from_ndarray(cls, ops: ArrayOps, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: + def from_ndarray( + cls, ops: embedded_array_ops.ArrayOps, ndarray: core_defs.NDArrayObject + ) -> ConnectivityOps: """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`, of the namespace of `ops`.""" return cls(ops) @@ -115,5 +116,5 @@ def register(xp: ModuleType, ops_type: type[ConnectivityOps]) -> None: def of(ndarray: Any) -> ConnectivityOps: """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`; raises `TypeError` if it is not an array.""" - ops = array_ops.of(ndarray) + ops = embedded_array_ops.of(ndarray) return _types_by_namespace.get(ops.xp, ConnectivityOps).from_ndarray(ops, ndarray) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index f184e3e3cb..8007b724e0 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -25,11 +25,10 @@ from gt4py.next.embedded import ( array_ops, common as embedded_common, - connectivity_ops, + connectivity_ops as embedded_connectivity_ops, context as embedded_context, exceptions as embedded_exceptions, ) -from gt4py.next.embedded.connectivity_ops import ConnectivityOps from gt4py.next.ffront import experimental, fbuiltins @@ -458,11 +457,13 @@ class NdArrayConnectivityField( _skip_value: Optional[core_defs.IntegralScalar] #: The `ConnectivityOps` of the connectivity if its creator knows them, as `restrict` does. #: Not a field, so that no copy inherits them; without them, they are created from the buffer. - connectivity_ops: dataclasses.InitVar[Optional[ConnectivityOps]] = dataclasses.field( - default=None, kw_only=True + connectivity_ops: dataclasses.InitVar[Optional[embedded_connectivity_ops.ConnectivityOps]] = ( + dataclasses.field(default=None, kw_only=True) ) - def __post_init__(self, connectivity_ops: Optional[ConnectivityOps]) -> None: + def __post_init__( + self, connectivity_ops: Optional[embedded_connectivity_ops.ConnectivityOps] + ) -> None: if connectivity_ops is not None: self.__dict__["_connectivity_ops"] = connectivity_ops @@ -514,8 +515,8 @@ def _restrict_cache(self) -> dict[Any, NdArrayConnectivityField]: return {} @functools.cached_property - def _connectivity_ops(self) -> ConnectivityOps: - return connectivity_ops.of(self._ndarray) + def _connectivity_ops(self) -> embedded_connectivity_ops.ConnectivityOps: + return embedded_connectivity_ops.of(self._ndarray) def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index 6551653bd6..4430d84c84 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -31,8 +31,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import backend as gtx_backend, common, utils as next_utils -from gt4py.next.embedded import nd_array_field -from gt4py.next.embedded.connectivity_ops import ConnectivityOps +from gt4py.next.embedded import connectivity_ops as embedded_connectivity_ops, nd_array_field from gt4py.next.otf import arguments, artifacts, runners, stages from gt4py.next.otf.compilation import cache as _cache @@ -63,7 +62,9 @@ class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): ) _digest: str = dataclasses.field(init=False) - def __post_init__(self, connectivity_ops: Optional[ConnectivityOps]) -> None: + def __post_init__( + self, connectivity_ops: Optional[embedded_connectivity_ops.ConnectivityOps] + ) -> None: super().__post_init__(connectivity_ops) table = np.ascontiguousarray(np.asarray(self._ndarray)) object.__setattr__(self, "_digest", _table_digest(table)) From 4fc594333885ad4a7747ab34c38e68bd4e93fb1e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 12:56:07 +0100 Subject: [PATCH 095/166] docs[next]: say when a connectivity is given its ConnectivityOps --- src/gt4py/next/embedded/nd_array_field.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 8007b724e0..4ddb6e917f 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -455,8 +455,9 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: The `ConnectivityOps` of the connectivity if its creator knows them, as `restrict` does. - #: Not a field, so that no copy inherits them; without them, they are created from the buffer. + #: The `ConnectivityOps` of a connectivity whose buffer does not determine them, e.g. a tracer + #: standing for a concrete table. Not a field, so that no copy inherits them; without them, + #: they are created from the buffer. connectivity_ops: dataclasses.InitVar[Optional[embedded_connectivity_ops.ConnectivityOps]] = ( dataclasses.field(default=None, kw_only=True) ) From 6e55145a0bbf6d0e3a9c300dc49c067197e96022 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 14:09:40 +0100 Subject: [PATCH 096/166] refactor[next]: drop ConnectivityOps.may_cache, rebuild restrictions sharing their domain lookups; ConnectivityOps.from_ndarray takes only the buffer --- .../0029-Connectivities_Under_JAX_Tracing.md | 4 ++-- .../next/embedded/array_libraries/jax_ops.py | 10 ++------- src/gt4py/next/embedded/connectivity_ops.py | 22 +++++++++---------- src/gt4py/next/embedded/nd_array_field.py | 20 +++++++++-------- .../embedded_tests/test_nd_array_field.py | 13 ----------- 5 files changed, 25 insertions(+), 44 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index e742440e63..0915aa75b3 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -26,7 +26,7 @@ Each connectivity has its own `ConnectivityOps` instance, which can carry what t The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values. They are compared by identity, so two connectivities have the same aux data only if they have the same static values. Unflattening gives a child that is not a concrete array the static values from the aux data, in its `JaxConnectivityOps`. -Nothing that belongs to a trace may be kept beyond it, so a connectivity caches a restricted connectivity only if its `ConnectivityOps` allows it (`may_cache`), which `JaxConnectivityOps` does for a concrete table only. `JaxConnectivityOps` also returns the same array when the same concrete table is restricted again with the same slice. A restriction then has the same aux data in every call, so it does not cause a retrace. +Nothing that belongs to a trace may be kept beyond it, so a connectivity caches domains and slices, never tables or restricted connectivities. `JaxConnectivityOps` returns the same array when the same concrete table is restricted again with the same slice. A restriction then has the same aux data in every call, so it does not cause a retrace. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: @@ -54,7 +54,7 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - Every gather of a jax field uses `mode="clip", wrap_negative_indices=False`. That clamps both ends with no operation besides the gather, where jax's default indexing clamps past the end but emits a select to wrap negative indices. With a table that has values the clamp never acts. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. -- `restrict` of a traced table builds a new connectivity on every call, with its own domain lookups. +- `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. - A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values: its domain is not narrowed and the gather clamps. - The restrictions of a concrete jax table are kept for as long as the table is alive. - Domain inference on static values is cached on the connectivity object, which is new in every trace, so it is repeated per trace but not per call. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index e91cf30761..77ef00cea0 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -111,14 +111,8 @@ def hyperslice( return super().hyperslice(self.values, image_range, skip_value) @classmethod - def from_ndarray( - cls, ops: array_ops.ArrayOps, ndarray: core_defs.NDArrayObject - ) -> JaxConnectivityOps: - return cls(ops, ndarray if _has_values(ndarray) else None) - - def may_cache(self, ndarray: core_defs.NDArrayObject) -> bool: - # a tracer belongs to a trace, which may end before the cache - return _has_values(ndarray) + def from_ndarray(cls, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: + return cls(array_ops.of(ndarray), ndarray if _has_values(ndarray) else None) def restrict( self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py index bc919247ff..37dd52b0c2 100644 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -41,11 +41,9 @@ class ConnectivityOps: array_ops: embedded_array_ops.ArrayOps @classmethod - def from_ndarray( - cls, ops: embedded_array_ops.ArrayOps, ndarray: core_defs.NDArrayObject - ) -> ConnectivityOps: - """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`, of the namespace of `ops`.""" - return cls(ops) + def from_ndarray(cls, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: + """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`.""" + return cls(embedded_array_ops.of(ndarray)) def hyperslice( self, @@ -91,14 +89,14 @@ def hyperslice( return slices - def may_cache(self, ndarray: core_defs.NDArrayObject) -> bool: - """Whether a connectivity with the buffer `ndarray` may be kept beyond the current call, e.g. in a cache.""" - return True - def restrict( self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence ) -> tuple[core_defs.NDArrayObject, ConnectivityOps]: - """Return `ndarray[buffer_slice]` and the `ConnectivityOps` of the restricted connectivity.""" + """ + Return `ndarray[buffer_slice]` and the `ConnectivityOps` of the restricted connectivity. + + `ndarray[buffer_slice]` is returned as an array: indexing with integers only gives a scalar. + """ return self.array_ops.asarray(ndarray[buffer_slice]), self @@ -116,5 +114,5 @@ def register(xp: ModuleType, ops_type: type[ConnectivityOps]) -> None: def of(ndarray: Any) -> ConnectivityOps: """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`; raises `TypeError` if it is not an array.""" - ops = embedded_array_ops.of(ndarray) - return _types_by_namespace.get(ops.xp, ConnectivityOps).from_ndarray(ops, ndarray) + xp = embedded_array_ops.of(ndarray).xp + return _types_by_namespace.get(xp, ConnectivityOps).from_ndarray(ndarray) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 1cb25ced92..c0fcfeab6d 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -521,7 +521,7 @@ def _inverse_image_cache(self) -> dict[common.UnitRange, common.Domain]: return {} @functools.cached_property - def _restrict_cache(self) -> dict[Any, NdArrayConnectivityField]: + def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: return {} @functools.cached_property @@ -549,14 +549,16 @@ def __setitem__( raise TypeError("'Connectivity' does not support item assignment.") def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: - if (restricted_connectivity := self._restrict_cache.get(index, None)) is None: - new_domain, buffer_slice = self._slice(index) - ndarray, ops = self._connectivity_ops.restrict(self._ndarray, buffer_slice) - restricted_connectivity = dataclasses.replace( - self, _domain=new_domain, _ndarray=ndarray, connectivity_ops=ops - ) - if ops.may_cache(ndarray): - self._restrict_cache[index] = restricted_connectivity + # Connectivities and arrays are not cached: they may belong to a trace that ends before the cache + if (cached := self._restrict_cache.get(index, None)) is None: + cached = self._restrict_cache[index] = (*self._slice(index), {}, {}) + new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached + ndarray, ops = self._connectivity_ops.restrict(self._ndarray, buffer_slice) + restricted_connectivity = dataclasses.replace( + self, _domain=new_domain, _ndarray=ndarray, connectivity_ops=ops + ) + restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache + restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache return restricted_connectivity __getitem__ = restrict diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 867feaad00..437b336365 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2364,19 +2364,6 @@ def test_connectivity_ops_use_the_registered_array_ops(monkeypatch): assert connectivity_ops.of(table).array_ops is replacement -def test_connectivity_field_restrict_is_cached(): - V = Dimension("V") - E = Dimension("E") - E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - conn = common._connectivity( - np.asarray([[0, 1], [1, 2], [2, 3]]), - codomain=V, - domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), - ) - - assert conn[NamedIndex(E2VDim, 0)] is conn[NamedIndex(E2VDim, 0)] - - def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): V = Dimension("V") E = Dimension("E") From 1a2eb49415438ee9c5f61f5c454521c71377e03a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 18 Nov 2026 14:58:24 +0100 Subject: [PATCH 097/166] refactor[next]: rename ConnectivityOps.hyperslice to inverse_image_box --- .../0029-Connectivities_Under_JAX_Tracing.md | 2 +- .../next/embedded/array_libraries/jax_ops.py | 4 ++-- src/gt4py/next/embedded/connectivity_ops.py | 8 ++++---- src/gt4py/next/embedded/nd_array_field.py | 4 +++- .../embedded_tests/test_nd_array_field.py | 16 ++++++++++------ 5 files changed, 20 insertions(+), 14 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 0915aa75b3..bab02fd0fe 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -20,7 +20,7 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `hyperslice` (domain inference) and `restrict`, are methods of `ConnectivityOps`, which builds on the library's `ArrayOps`; a library that needs different table operations registers a subclass for its namespace. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `inverse_image_box` (domain inference) and `restrict`, are methods of `ConnectivityOps`, which builds on the library's `ArrayOps`; a library that needs different table operations registers a subclass for its namespace. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: a creator that knows it passes it at construction, as `restrict` does with the one returned for the restricted table and the pytree unflatten with the static values, and otherwise `connectivity_ops.of` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 77ef00cea0..f4d0b8f7e9 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -99,7 +99,7 @@ class JaxConnectivityOps(connectivity_ops.ConnectivityOps): #: only at run time. The table itself if it is concrete. values: Optional[core_defs.NDArrayObject] = None - def hyperslice( + def inverse_image_box( self, ndarray: core_defs.NDArrayObject, image_range: common.UnitRange, @@ -108,7 +108,7 @@ def hyperslice( if self.values is None: return (slice(None),) * ndarray.ndim with jax.ensure_compile_time_eval(): - return super().hyperslice(self.values, image_range, skip_value) + return super().inverse_image_box(self.values, image_range, skip_value) @classmethod def from_ndarray(cls, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py index 37dd52b0c2..d35964a113 100644 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ b/src/gt4py/next/embedded/connectivity_ops.py @@ -45,17 +45,17 @@ def from_ndarray(cls, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`.""" return cls(embedded_array_ops.of(ndarray)) - def hyperslice( + def inverse_image_box( self, ndarray: core_defs.NDArrayObject, image_range: common.UnitRange, skip_value: Optional[core_defs.IntegralScalar] = None, ) -> Optional[tuple[slice, ...]]: """ - Return the hypercube slice that contains all indices in `ndarray` that are within `image_range`, or `None` if no such hypercube exists. + Return the slices of the smallest box of `ndarray` containing all entries within `image_range`, or `None` if that box contains other entries. - If `skip_value` is given, the selected values are ignored. It returns the smallest hypercube. - A bigger hypercube could be constructed by adding lines that contain only `skip_value`s. + If `skip_value` is given, entries equal to it are ignored. A bigger box could be + constructed by adding lines that contain only `skip_value`s. Example: ndarray = 0 1 -1 diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index c0fcfeab6d..1947d19e2d 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -532,7 +532,9 @@ def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: assert common.UnitRange.is_finite(image_range) - slices = self._connectivity_ops.hyperslice(self._ndarray, image_range, self.skip_value) + slices = self._connectivity_ops.inverse_image_box( + self._ndarray, image_range, self.skip_value + ) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 437b336365..fb592407d2 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2124,14 +2124,16 @@ def test_connectivity_field_inverse_image_2d_domain_skip_values(): ([[1, 0, -1], [1, 0, 0]], [(0, 2), (1, 3)]), ], ) -def test_hyperslice(index_array, expected): +def test_inverse_image_box(index_array, expected): index_array = np.asarray(index_array) image_range = common.UnitRange(0, 1) skip_value = -1 expected = tuple(slice(*e) for e in expected) if expected is not None else None - result = connectivity_ops.of(index_array).hyperslice(index_array, image_range, skip_value) + result = connectivity_ops.of(index_array).inverse_image_box( + index_array, image_range, skip_value + ) assert result == expected @@ -2375,14 +2377,16 @@ def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): ) field = common._field(np.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) calls = 0 - hyperslice = connectivity_ops.ConnectivityOps.hyperslice + inverse_image_box = connectivity_ops.ConnectivityOps.inverse_image_box - def counting_hyperslice(*args, **kwargs): + def counting_inverse_image_box(*args, **kwargs): nonlocal calls calls += 1 - return hyperslice(*args, **kwargs) + return inverse_image_box(*args, **kwargs) - monkeypatch.setattr(connectivity_ops.ConnectivityOps, "hyperslice", counting_hyperslice) + monkeypatch.setattr( + connectivity_ops.ConnectivityOps, "inverse_image_box", counting_inverse_image_box + ) for _ in range(3): result = field.premap(conn[NamedIndex(E2VDim, 0)]) From 129b1f4b05f2fe0d9be9d2689154682e5c08dbd3 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 12:49:24 +0100 Subject: [PATCH 098/166] refactor[next]: static values on the connectivity instead of ConnectivityOps; ArrayOps.static_values, plain inverse_image_box --- .../next/embedded/array_libraries/jax_ops.py | 130 ++++++------------ src/gt4py/next/embedded/array_ops.py | 11 +- src/gt4py/next/embedded/connectivity_ops.py | 118 ---------------- src/gt4py/next/embedded/nd_array_field.py | 92 ++++++++++--- src/gt4py/next/otf/compilation_tasks.py | 8 +- .../embedded_tests/test_nd_array_field.py | 22 +-- 6 files changed, 132 insertions(+), 249 deletions(-) delete mode 100644 src/gt4py/next/embedded/connectivity_ops.py diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index f4d0b8f7e9..977c9cad01 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -7,23 +7,21 @@ # SPDX-License-Identifier: BSD-3-Clause """ -`ArrayOps` and `ConnectivityOps` for JAX arrays, and the embedded fields as JAX pytrees. +`ArrayOps` for JAX arrays, and the embedded fields as JAX pytrees. Everything gt4py knows about JAX tracing is in this module (ADR 0029). A -connectivity table inside a trace is in one of three cases, told apart by -`JaxConnectivityOps.values`: +connectivity table inside a trace is in one of three cases, told apart by its +static values: -- concrete: operations reading its values run under `jax.ensure_compile_time_eval`; +- concrete: its static values are a NumPy view of it; - a tracer standing for a concrete table, which it got as a pytree leaf, or - restricted from such a tracer: the values are those of the concrete table; -- any other tracer: there are no values, all its targets are assumed to be in - range and the gather clamps them. + restricted from such a tracer: the static values are those of the concrete table; +- any other tracer: there are no static values, all its targets are assumed to be + in range and the gather clamps them. """ from __future__ import annotations -import dataclasses -import weakref from collections.abc import Callable, Mapping from typing import Any, ClassVar, NamedTuple, Optional @@ -34,98 +32,48 @@ from gt4py._core import definitions as core_defs from gt4py.next import common -from gt4py.next.embedded import array_ops, connectivity_ops, nd_array_field +from gt4py.next.embedded import array_ops, nd_array_field from gt4py.next.ffront import experimental, fbuiltins -class _WeakIdDict: - """Values for objects which are found by identity and referenced weakly.""" - - __slots__ = ("_items",) - - def __init__(self) -> None: - self._items: dict[int, tuple[weakref.ref, Any]] = {} - - def __setitem__(self, obj: Any, value: Any) -> None: - key = id(obj) - self._items[key] = (weakref.ref(obj, lambda _: self._items.pop(key, None)), value) - - def get(self, obj: Any) -> Any: - ref, value = self._items.get(id(obj), (None, None)) - return value if ref is not None and ref() is obj else None +class _TableIdentity: + """ + Pytree aux data of a connectivity: equal if `values` is the same read-only memory. + NumPy returns a new view of a JAX array on every `np.asarray`, so the views of one + buffer, and their restrictions with the same slice, are told apart by their memory. + """ -class _TableIdentity: - """Pytree aux data of a connectivity: equal if `values` is the same array.""" + __slots__ = ("_key", "values") - __slots__ = ("values",) + values: np.ndarray + _key: tuple[int, tuple[int, ...], tuple[int, ...], str] def __init__(self, values: core_defs.NDArrayObject) -> None: + assert isinstance(values, np.ndarray) and not values.flags.writeable + # holding the array keeps its memory alive, so no other array can get its address self.values = values + self._key = ( + values.__array_interface__["data"][0], + values.shape, + values.strides, + values.dtype.str, + ) def __eq__(self, other: object) -> bool: - return isinstance(other, _TableIdentity) and self.values is other.values + return isinstance(other, _TableIdentity) and self._key == other._key def __hash__(self) -> int: - return id(self.values) + return hash(self._key) def __repr__(self) -> str: - return f"" + return f"" def _has_values(ndarray: Any) -> bool: return isinstance(ndarray, jax.Array) and not isinstance(ndarray, jax.core.Tracer) -#: per concrete table, its restrictions by buffer slice: restricting the same table again returns -#: the same array, which the pytree aux data identifies -_restricted_values = _WeakIdDict() - - -def _restrict_values( - values: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence -) -> core_defs.NDArrayObject: - if (by_slice := _restricted_values.get(values)) is None: - by_slice = _restricted_values[values] = {} - if (restricted := by_slice.get(buffer_slice)) is None: - with jax.ensure_compile_time_eval(): - restricted = by_slice[buffer_slice] = values[buffer_slice] - return restricted - - -@dataclasses.dataclass(frozen=True, eq=False) -class JaxConnectivityOps(connectivity_ops.ConnectivityOps): - #: The concrete array with the values of the connectivity's table, `None` if they exist - #: only at run time. The table itself if it is concrete. - values: Optional[core_defs.NDArrayObject] = None - - def inverse_image_box( - self, - ndarray: core_defs.NDArrayObject, - image_range: common.UnitRange, - skip_value: Optional[core_defs.IntegralScalar] = None, - ) -> Optional[tuple[slice, ...]]: - if self.values is None: - return (slice(None),) * ndarray.ndim - with jax.ensure_compile_time_eval(): - return super().inverse_image_box(self.values, image_range, skip_value) - - @classmethod - def from_ndarray(cls, ndarray: core_defs.NDArrayObject) -> JaxConnectivityOps: - return cls(array_ops.of(ndarray), ndarray if _has_values(ndarray) else None) - - def restrict( - self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence - ) -> tuple[core_defs.NDArrayObject, connectivity_ops.ConnectivityOps]: - if self.values is None: - return super().restrict(ndarray, buffer_slice) - values = _restrict_values(self.values, buffer_slice) - restricted = ( - values if self.values is ndarray else super().restrict(ndarray, buffer_slice)[0] - ) - return restricted, dataclasses.replace(self, values=values) - - def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: # adding the coordinates would stage the table under a trace even for concrete offsets with jax.ensure_compile_time_eval(): @@ -153,6 +101,14 @@ def setitem( self.check_assignable(value) return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete + def static_values(self, array: core_defs.NDArrayObject) -> Optional[core_defs.NDArrayObject]: + if isinstance(array, jax.core.Tracer): + return None + # NumPy, so that computing on the values is not staged when a trace closes over the array + values = np.asarray(array) + values.flags.writeable = False + return values # type: ignore[return-value] # `NDArrayObject` typing is not complete + def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: @@ -167,7 +123,6 @@ def buffer_info(self, array: core_defs.NDArrayObject) -> common.BufferInfo: array_ops.register(JaxOps(jnp)) -connectivity_ops.register(jnp, JaxConnectivityOps) # TODO(havogt): we currently enable 64-bit support by default, but we might want to make this configurable via the GT4Py config jax.config.update("jax_enable_x64", True) @@ -216,11 +171,10 @@ def _flatten_connectivity( array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) ), f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." try: - ops = connectivity._connectivity_ops + values = connectivity._static_values except TypeError: - # a placeholder that is no array has `ConnectivityOps` only if unflattening gave it some - ops = None - values = ops.values if isinstance(ops, JaxConnectivityOps) else None + # a placeholder that is no array has static values only if unflattening gave it some + values = None return (ndarray,), _ConnectivityAuxData( connectivity.domain, connectivity.codomain, @@ -237,19 +191,19 @@ def _unflatten_connectivity( # a child without values stands for the flattened table: a tracer, or one of the placeholders # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. Under `vmap` the # child is one element of the flattened table, whose values the aux data does not have. - ops = ( + static_values = ( None if identity is None or _has_values(ndarray) or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape - else connectivity_ops.of(identity.values) + else identity.values ) return nd_array_field.NdArrayConnectivityField( aux_data.domain, ndarray, aux_data.codomain, aux_data.skip_value, - connectivity_ops=ops, + static_values=static_values, # type: ignore[arg-type] # `NDArrayObject` typing is not complete ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 5c8309b98b..5f7aa69b46 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -25,7 +25,7 @@ import dataclasses from collections.abc import Callable, Mapping from types import ModuleType -from typing import Any, ClassVar, Final +from typing import Any, ClassVar, Final, Optional import array_api_compat import array_api_compat.numpy as compat_numpy @@ -198,6 +198,15 @@ def check_assignable(self, value: Any) -> None: f" to an array of '{self.xp.__name__}'." ) + def static_values(self, array: core_defs.NDArrayObject) -> Optional[core_defs.NDArrayObject]: + """ + An array with the values of `array` that can be computed on now, not necessarily of this namespace. + + `None` if the values are known only at run time, e.g. for an array standing for the + argument of a compiled program; `gather` must then accept out-of-range indices. + """ + return array + def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: diff --git a/src/gt4py/next/embedded/connectivity_ops.py b/src/gt4py/next/embedded/connectivity_ops.py deleted file mode 100644 index d35964a113..0000000000 --- a/src/gt4py/next/embedded/connectivity_ops.py +++ /dev/null @@ -1,118 +0,0 @@ -# GT4Py - GridTools Framework -# -# Copyright (c) 2014-2024, ETH Zurich -# All rights reserved. -# -# Please, refer to the LICENSE file in the root directory. -# SPDX-License-Identifier: BSD-3-Clause - -""" -Operations of the embedded connectivities that read the values of their table, per array namespace. - -`ConnectivityOps` builds on the `array_ops.ArrayOps` of the buffer's namespace. A library -that needs different behaviour subclasses `ConnectivityOps` and registers the subclass for -its namespace with `register`. -""" - -from __future__ import annotations - -import dataclasses -from types import ModuleType -from typing import Any, Optional - -from gt4py._core import definitions as core_defs -from gt4py.next import common -from gt4py.next.embedded import array_ops as embedded_array_ops - - -@dataclasses.dataclass(frozen=True, eq=False) -class ConnectivityOps: - """ - Operations on the buffer of one connectivity. - - An instance belongs to one connectivity and is never inherited by a copy of it: `of` - creates it from the connectivity's buffer, and `restrict` returns the one of the - restricted buffer. The `ndarray` its methods take is the buffer of that connectivity. - A library whose connectivities know more about their buffer than the buffer itself, - e.g. the values of a traced table, subclasses `ConnectivityOps` and keeps that in its - instances. - """ - - array_ops: embedded_array_ops.ArrayOps - - @classmethod - def from_ndarray(cls, ndarray: core_defs.NDArrayObject) -> ConnectivityOps: - """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`.""" - return cls(embedded_array_ops.of(ndarray)) - - def inverse_image_box( - self, - ndarray: core_defs.NDArrayObject, - image_range: common.UnitRange, - skip_value: Optional[core_defs.IntegralScalar] = None, - ) -> Optional[tuple[slice, ...]]: - """ - Return the slices of the smallest box of `ndarray` containing all entries within `image_range`, or `None` if that box contains other entries. - - If `skip_value` is given, entries equal to it are ignored. A bigger box could be - constructed by adding lines that contain only `skip_value`s. - - Example: - ndarray = 0 1 -1 - 3 4 -1 - -1 -1 -1 - skip_value = -1 - - would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. - - An implementation which cannot read the values of `ndarray` returns all of it. What an - entry outside of `image_range` reads is then defined by `ArrayOps.gather`. - """ - xp = self.array_ops.xp - select_mask = (ndarray >= image_range.start) & (ndarray < image_range.stop) - - if not xp.any(select_mask): - return None - - nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) - - slices = tuple( - slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) - for dim_nnz_indices in nnz - ) - hcube = select_mask[tuple(slices)] - if skip_value is not None: - ignore_mask = ndarray == skip_value - hcube = hcube | ignore_mask[tuple(slices)] - if not xp.all(hcube): - return None - - return slices - - def restrict( - self, ndarray: core_defs.NDArrayObject, buffer_slice: common.RelativeIndexSequence - ) -> tuple[core_defs.NDArrayObject, ConnectivityOps]: - """ - Return `ndarray[buffer_slice]` and the `ConnectivityOps` of the restricted connectivity. - - `ndarray[buffer_slice]` is returned as an array: indexing with integers only gives a scalar. - """ - return self.array_ops.asarray(ndarray[buffer_slice]), self - - -_types_by_namespace: dict[ModuleType, type[ConnectivityOps]] = {} - - -def register(xp: ModuleType, ops_type: type[ConnectivityOps]) -> None: - """ - Use `ops_type` for the connectivities whose buffer has the compat namespace `xp`. - - Connectivities which already have their `ConnectivityOps` keep them. - """ - _types_by_namespace[xp] = ops_type - - -def of(ndarray: Any) -> ConnectivityOps: - """The `ConnectivityOps` of a connectivity whose buffer is `ndarray`; raises `TypeError` if it is not an array.""" - xp = embedded_array_ops.of(ndarray).xp - return _types_by_namespace.get(xp, ConnectivityOps).from_ndarray(ndarray) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 1947d19e2d..43d3f2b22f 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -25,7 +25,6 @@ from gt4py.next.embedded import ( array_ops, common as embedded_common, - connectivity_ops as embedded_connectivity_ops, context as embedded_context, exceptions as embedded_exceptions, ) @@ -457,6 +456,48 @@ def _broadcast_axes_slice( ) +def _inverse_image_box( + ndarray: core_defs.NDArrayObject, + image_range: common.UnitRange, + xp: ModuleType, + skip_value: Optional[core_defs.IntegralScalar] = None, +) -> Optional[tuple[slice, ...]]: + """ + Return the slices of the smallest box of `ndarray` containing all entries within `image_range`, or `None` if that box contains other entries. + + If `skip_value` is given, entries equal to it are ignored. A bigger box could be + constructed by adding lines that contain only `skip_value`s. + + Example: + ndarray = 0 1 -1 + 3 4 -1 + -1 -1 -1 + skip_value = -1 + + would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. + + """ + select_mask = (ndarray >= image_range.start) & (ndarray < image_range.stop) + + if not xp.any(select_mask): + return None + + nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) + + slices = tuple( + slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) + for dim_nnz_indices in nnz + ) + hcube = select_mask[tuple(slices)] + if skip_value is not None: + ignore_mask = ndarray == skip_value + hcube = hcube | ignore_mask[tuple(slices)] + if not xp.all(hcube): + return None + + return slices + + @dataclasses.dataclass(frozen=True) class NdArrayConnectivityField( common.GatherConnectivity[common.DimsT, common.DimT], @@ -464,18 +505,16 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: The `ConnectivityOps` of a connectivity whose buffer does not determine them, e.g. a tracer - #: standing for a concrete table. Not a field, so that no copy inherits them; without them, - #: they are created from the buffer. - connectivity_ops: dataclasses.InitVar[Optional[embedded_connectivity_ops.ConnectivityOps]] = ( - dataclasses.field(default=None, kw_only=True) + #: The static values of a connectivity whose buffer does not determine them, e.g. a tracer + #: standing for a concrete table (see `ArrayOps.static_values`). Not a field, so that no + #: copy inherits them; without them, they are taken from the buffer. + static_values: dataclasses.InitVar[Optional[core_defs.NDArrayObject]] = dataclasses.field( + default=None, kw_only=True ) - def __post_init__( - self, connectivity_ops: Optional[embedded_connectivity_ops.ConnectivityOps] - ) -> None: - if connectivity_ops is not None: - self.__dict__["_connectivity_ops"] = connectivity_ops + def __post_init__(self, static_values: Optional[core_defs.NDArrayObject]) -> None: + if static_values is not None: + self.__dict__["_static_values"] = static_values @classmethod def from_array( # type: ignore[override] @@ -525,15 +564,22 @@ def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: return {} @functools.cached_property - def _connectivity_ops(self) -> embedded_connectivity_ops.ConnectivityOps: - return embedded_connectivity_ops.of(self._ndarray) + def _static_values(self) -> Optional[core_defs.NDArrayObject]: + return array_ops.of(self._ndarray).static_values(self._ndarray) def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: assert common.UnitRange.is_finite(image_range) - slices = self._connectivity_ops.inverse_image_box( - self._ndarray, image_range, self.skip_value + values = self._static_values + # without static values, all targets are assumed to be in range; the gather decides + # what the others read + slices = ( + (slice(None),) * self._ndarray.ndim + if values is None + else _inverse_image_box( + values, image_range, array_ops.of(values).xp, self.skip_value + ) ) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -553,11 +599,21 @@ def __setitem__( def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: # Connectivities and arrays are not cached: they may belong to a trace that ends before the cache if (cached := self._restrict_cache.get(index, None)) is None: - cached = self._restrict_cache[index] = (*self._slice(index), {}, {}) + new_domain, buffer_slice = self._slice(index) + # the trailing `Ellipsis` makes indexing with integers only return an array, not a scalar + if Ellipsis not in buffer_slice: + buffer_slice = (*buffer_slice, Ellipsis) + cached = self._restrict_cache[index] = (new_domain, buffer_slice, {}, {}) new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached - ndarray, ops = self._connectivity_ops.restrict(self._ndarray, buffer_slice) + values = self._static_values restricted_connectivity = dataclasses.replace( - self, _domain=new_domain, _ndarray=ndarray, connectivity_ops=ops + self, + _domain=new_domain, + _ndarray=self._ndarray[buffer_slice], + # static values that are not the buffer itself are restricted along with it + static_values=( + None if values is None or values is self._ndarray else values[buffer_slice] + ), ) restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index 4430d84c84..d05c1ede1e 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -31,7 +31,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import backend as gtx_backend, common, utils as next_utils -from gt4py.next.embedded import connectivity_ops as embedded_connectivity_ops, nd_array_field +from gt4py.next.embedded import nd_array_field from gt4py.next.otf import arguments, artifacts, runners, stages from gt4py.next.otf.compilation import cache as _cache @@ -62,10 +62,8 @@ class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): ) _digest: str = dataclasses.field(init=False) - def __post_init__( - self, connectivity_ops: Optional[embedded_connectivity_ops.ConnectivityOps] - ) -> None: - super().__post_init__(connectivity_ops) + def __post_init__(self, static_values: Optional[core_defs.NDArrayObject]) -> None: + super().__post_init__(static_values) table = np.ascontiguousarray(np.asarray(self._ndarray)) object.__setattr__(self, "_digest", _table_digest(table)) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index fb592407d2..2bc1d9a0a5 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -29,7 +29,6 @@ ) from gt4py.next.embedded import ( array_ops, - connectivity_ops, context as embedded_context, exceptions as embedded_exceptions, nd_array_field, @@ -2131,9 +2130,7 @@ def test_inverse_image_box(index_array, expected): expected = tuple(slice(*e) for e in expected) if expected is not None else None - result = connectivity_ops.of(index_array).inverse_image_box( - index_array, image_range, skip_value - ) + result = nd_array_field._inverse_image_box(index_array, image_range, np, skip_value) assert result == expected @@ -2355,17 +2352,6 @@ def test_connectivity_field_setitem_raises(): conn[NamedIndex(D1, 1)] = np.asarray([0, 1]) -def test_connectivity_ops_use_the_registered_array_ops(monkeypatch): - table = np.asarray([0, 1, 2]) - numpy_ops = array_ops.of(table) - connectivity_ops.of(table) - replacement = dataclasses.replace(numpy_ops) - monkeypatch.setattr(array_ops, "_ops_by_namespace", {numpy_ops.xp: replacement}) - monkeypatch.setattr(array_ops, "_ops_by_array_type", {}) - - assert connectivity_ops.of(table).array_ops is replacement - - def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): V = Dimension("V") E = Dimension("E") @@ -2377,16 +2363,14 @@ def test_connectivity_field_restrict_keeps_inverse_image_cache(monkeypatch): ) field = common._field(np.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) calls = 0 - inverse_image_box = connectivity_ops.ConnectivityOps.inverse_image_box + inverse_image_box = nd_array_field._inverse_image_box def counting_inverse_image_box(*args, **kwargs): nonlocal calls calls += 1 return inverse_image_box(*args, **kwargs) - monkeypatch.setattr( - connectivity_ops.ConnectivityOps, "inverse_image_box", counting_inverse_image_box - ) + monkeypatch.setattr(nd_array_field, "_inverse_image_box", counting_inverse_image_box) for _ in range(3): result = field.premap(conn[NamedIndex(E2VDim, 0)]) From 4f8f731746077d250ce2e62361a8476933a6084e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 12:50:03 +0100 Subject: [PATCH 099/166] docs[next]: ADR 0029 describes static values on the connectivity --- .../0029-Connectivities_Under_JAX_Tracing.md | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index bab02fd0fe..5de8112364 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -7,7 +7,7 @@ tags: [embedded, jax, connectivities] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) - **Created**: 2026-11-18 -- **Updated**: 2026-11-18 +- **Updated**: 2026-11-19 In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to pass the concrete table along with its tracer through the pytree aux data of the connectivity, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime (`as_offset`). @@ -20,18 +20,18 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. The operations that read the values of a table, `inverse_image_box` (domain inference) and `restrict`, are methods of `ConnectivityOps`, which builds on the library's `ArrayOps`; a library that needs different table operations registers a subclass for its namespace. The gather is `ArrayOps.gather`, an operation on the field's buffer. The defaults are plain array code. `JaxOps` overrides `gather`, `JaxConnectivityOps` the table operations, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. `ArrayOps.static_values` gives them for a buffer: the buffer itself by default, and `None` if the values exist only at run time. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.gather`. `JaxOps` overrides `static_values` and `gather`, and everything that knows about tracing is in `jax_ops.py`. -Each connectivity has its own `ConnectivityOps` instance, which can carry what the library knows about the table beyond the table itself. It is not a dataclass field, so no copy inherits it: a creator that knows it passes it at construction, as `restrict` does with the one returned for the restricted table and the pytree unflatten with the static values, and otherwise `connectivity_ops.of` creates it from the table on first use. For a table that is a tracer, `JaxConnectivityOps` holds the concrete array with the same values, the static values. A connectivity that got another table, for example through `dataclasses.replace` or `copy`, has none. +For a concrete jax table, `JaxOps.static_values` is a read-only NumPy view of it, so domain inference is never staged, also inside a trace. For a tracer it is `None`, and the connectivity then assumes that every target lies in range. A tracer that stands for a concrete table, the case of a connectivity passed to `jit`, gets the static values from its creator: the constructor takes them as a keyword-only init-only argument, which the pytree unflatten passes. They are not a dataclass field, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restricted connectivity keeps them. -The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values. They are compared by identity, so two connectivities have the same aux data only if they have the same static values. Unflattening gives a child that is not a concrete array the static values from the aux data, in its `JaxConnectivityOps`. +The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values. They are compared by their memory, because NumPy returns a new view of a jax array on every call: two connectivities have the same aux data only if their static values are the same read-only memory, which holds for every wrapper of one buffer and for its restrictions with the same slice. Unflattening gives a child that is not a concrete array the static values from the aux data. -Nothing that belongs to a trace may be kept beyond it, so a connectivity caches domains and slices, never tables or restricted connectivities. `JaxConnectivityOps` returns the same array when the same concrete table is restricted again with the same slice. A restriction then has the same aux data in every call, so it does not cause a retrace. +Nothing that belongs to a trace may be kept beyond it, so a connectivity caches domains and slices, never tables or restricted connectivities. How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: - **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function; a provider set outside inlines the table as a constant for the reduction. -- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table stays concrete, also after `restrict`, because the operations on it run under `jax.ensure_compile_time_eval()`. Domain inference reads it directly, but the table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). +- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table is concrete, so domain inference reads its static values, also after a `restrict` inside the trace, which restricts them along with the then staged table. The table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). - **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field, or any other table that is a tracer without static values). No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed. `JaxOps.gather` clamps every index to the field at both ends, so an out-of-range target reads the field's boundary value. A tracer of any jax transformation counts as traced, not only one of `jit`. In particular a table that depends on a `vmap`ped value has no values even when `vmap` is called eagerly, because it differs per batch element. @@ -56,7 +56,7 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. - `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. - A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values: its domain is not narrowed and the gather clamps. -- The restrictions of a concrete jax table are kept for as long as the table is alive. +- The static values of a jax table are NumPy, so on a GPU domain inference reads a host copy of the table. - Domain inference on static values is cached on the connectivity object, which is new in every trace, so it is repeated per trace but not per call. Open questions, all caused by the static values in the aux data: @@ -67,9 +67,13 @@ Open questions, all caused by the static values in the aux data: ## Alternatives considered -### An opaque state passed back to `ArrayOps` +### Table operations on a per-connectivity object -The table operations were methods of `ArrayOps`, which took a `state` stored on the connectivity. Every copy inherited the state, also with another table, possibly of another library, so each operation had to check that the state described its table, and the static values of restricted tracers were kept in a weak map on the state of the connectivity they were restricted from. +Domain inference and `restrict` were methods of a `ConnectivityOps` object, one per connectivity and registered per library, which held the static values and returned its successor from `restrict`. Its methods took plain arrays, but the object carried state about one buffer and the decision what a table without values means, which is the connectivity's. It needed its own registry next to `ArrayOps`. An earlier variant passed an opaque `state` stored on the connectivity back to `ArrayOps`; every copy inherited it, so each operation had to check that the state described its table. + +### Static values in a side table keyed by the connectivity + +A weak map from connectivity to static values in `jax_ops.py` needs no constructor argument, but `restrict` would need a hook to hand the restricted values back, and `ArrayOps` would have to take connectivities. ### Static values found by the table @@ -77,11 +81,11 @@ A map from table to static values, inside `jax_ops.py`, needs no state on the co ### `is_traced` and `concrete_eval` on `ArrayOps` -Two small hooks, with the case distinction written out in `NdArrayConnectivityField`. Rejected because tracing then shows in the code shared by all array libraries. +Two small hooks, with the case distinction written out in `NdArrayConnectivityField`. The connectivity would then have to know when to evaluate concretely. `static_values` instead returns an array that can be computed on now, so the connectivity needs no evaluation mode. ### Static values that follow the connectivity instead of the table -Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. `ConnectivityOps` is not inherited, and a concrete table is its own values. +Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. The static values are not inherited, and a concrete table derives its own. ### Bounds in the aux data instead of the table From 636e294829eb2c64d617124817a9402dc2a7cf8a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 13:00:07 +0100 Subject: [PATCH 100/166] refactor[next]: keep _inverse_image_box where main has _hyperslice, with its text --- src/gt4py/next/embedded/nd_array_field.py | 83 +++++++++++------------ 1 file changed, 41 insertions(+), 42 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 43d3f2b22f..d1bdc14790 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -456,48 +456,6 @@ def _broadcast_axes_slice( ) -def _inverse_image_box( - ndarray: core_defs.NDArrayObject, - image_range: common.UnitRange, - xp: ModuleType, - skip_value: Optional[core_defs.IntegralScalar] = None, -) -> Optional[tuple[slice, ...]]: - """ - Return the slices of the smallest box of `ndarray` containing all entries within `image_range`, or `None` if that box contains other entries. - - If `skip_value` is given, entries equal to it are ignored. A bigger box could be - constructed by adding lines that contain only `skip_value`s. - - Example: - ndarray = 0 1 -1 - 3 4 -1 - -1 -1 -1 - skip_value = -1 - - would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. - - """ - select_mask = (ndarray >= image_range.start) & (ndarray < image_range.stop) - - if not xp.any(select_mask): - return None - - nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) - - slices = tuple( - slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) - for dim_nnz_indices in nnz - ) - hcube = select_mask[tuple(slices)] - if skip_value is not None: - ignore_mask = ndarray == skip_value - hcube = hcube | ignore_mask[tuple(slices)] - if not xp.all(hcube): - return None - - return slices - - @dataclasses.dataclass(frozen=True) class NdArrayConnectivityField( common.GatherConnectivity[common.DimsT, common.DimT], @@ -744,6 +702,47 @@ def _identity_index_array( return xp.broadcast_to(xp.reshape(indices, shape), domain.shape) +def _inverse_image_box( + index_array: core_defs.NDArrayObject, + image_range: common.UnitRange, + xp: ModuleType, + skip_value: Optional[core_defs.IntegralScalar] = None, +) -> Optional[tuple[slice, ...]]: + """ + Return the hypercube slice that contains all indices in `index_array` that are within `image_range`, or `None` if no such hypercube exists. + + If `skip_value` is given, the selected values are ignored. It returns the smallest hypercube. + A bigger hypercube could be constructed by adding lines that contain only `skip_value`s. + + Example: + index_array = 0 1 -1 + 3 4 -1 + -1 -1 -1 + skip_value = -1 + + would currently select the 2x2 range [0,2], [0,2], but could also select the 3x3 range [0,3], [0,3]. + """ + select_mask = (index_array >= image_range.start) & (index_array < image_range.stop) + + if not xp.any(select_mask): + return None + + nnz: tuple[core_defs.NDArrayObject, ...] = xp.nonzero(select_mask) + + slices = tuple( + slice(int(xp.min(dim_nnz_indices)), int(xp.max(dim_nnz_indices)) + 1) + for dim_nnz_indices in nnz + ) + hcube = select_mask[tuple(slices)] + if skip_value is not None: + ignore_mask = index_array == skip_value + hcube = hcube | ignore_mask[tuple(slices)] + if not xp.all(hcube): + return None + + return slices + + # -- Specialized implementations for builtin operations on array fields -- From e97185abaa9d0857e36ffee9ac52e9e64f830780 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 13:58:13 +0100 Subject: [PATCH 101/166] refactor[next]: closed-over connectivities are not supported under jax tracing, drop ArrayOps.static_values --- .../next/embedded/array_libraries/jax_ops.py | 65 +++++++------ src/gt4py/next/embedded/array_ops.py | 11 +-- src/gt4py/next/embedded/nd_array_field.py | 33 +++++-- src/gt4py/next/otf/compilation_tasks.py | 4 +- .../test_nd_array_field_with_jax.py | 95 +++++++++++-------- 5 files changed, 118 insertions(+), 90 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 8a877b6781..793872e3fb 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -10,18 +10,20 @@ `ArrayOps` for JAX arrays, and the embedded fields as JAX pytrees. Everything gt4py knows about JAX tracing is in this module (ADR 0029). A -connectivity table inside a trace is in one of three cases, told apart by its -static values: - -- concrete: its static values are a NumPy view of it; -- a tracer standing for a concrete table, which it got as a pytree leaf, or - restricted from such a tracer: the static values are those of the concrete table; -- any other tracer: there are no static values, all its targets are assumed to be - in range and the gather clamps them. +connectivity table inside a trace is a tracer, and one of two cases: + +- it stands for a concrete table, which it got as a pytree leaf, or it was + restricted from such a tracer: its static values are a NumPy view of the + concrete table, from the pytree aux data; +- it was computed in the trace by `as_offset`: there are no static values, all + its targets are assumed to be in range and the gather clamps them. + +A concrete table closed over by a trace is not supported. """ from __future__ import annotations +import dataclasses from collections.abc import Callable, Mapping from typing import Any, ClassVar, NamedTuple, Optional @@ -74,10 +76,19 @@ def _has_values(ndarray: Any) -> bool: return isinstance(ndarray, jax.Array) and not isinstance(ndarray, jax.core.Tracer) +def _read_only_view(array: jax.Array) -> np.ndarray: + values = np.asarray(array) + values.flags.writeable = False + return values + + def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: - # adding the coordinates would stage the table under a trace even for concrete offsets - with jax.ensure_compile_time_eval(): - return nd_array_field._as_offset(offset, offset_field) + connectivity = nd_array_field._as_offset(offset, offset_field) + assert isinstance(connectivity, nd_array_field.NdArrayConnectivityField) + if isinstance(connectivity.ndarray, jax.core.Tracer): + # computed in the trace: its values exist only at run time + return dataclasses.replace(connectivity, static_values=None) + return connectivity def _layout_strides(array: Any) -> tuple[int, ...]: @@ -115,14 +126,6 @@ def setitem( self.check_assignable(value) return array.at[key].set(value) # type: ignore[attr-defined] # `NDArrayObject` typing is not complete - def static_values(self, array: core_defs.NDArrayObject) -> Optional[core_defs.NDArrayObject]: - if isinstance(array, jax.core.Tracer): - return None - # NumPy, so that computing on the values is not staged when a trace closes over the array - values = np.asarray(array) - values.flags.writeable = False - return values # type: ignore[return-value] # `NDArrayObject` typing is not complete - def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: @@ -191,11 +194,11 @@ def _flatten_connectivity( assert not ( array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) ), f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." - try: - values = connectivity._static_values - except TypeError: - # a placeholder that is no array has static values only if unflattening gave it some - values = None + values: Any = connectivity._static_values + if values is ndarray: + # a placeholder that is no array has no values; NumPy, so that a restriction inside the + # trace is not staged + values = _read_only_view(ndarray) if _has_values(ndarray) else None return (ndarray,), _ConnectivityAuxData( connectivity.domain, connectivity.codomain, @@ -209,13 +212,17 @@ def _unflatten_connectivity( ) -> nd_array_field.NdArrayConnectivityField: (ndarray,) = children identity = aux_data.values - # a child without values stands for the flattened table: a tracer, or one of the placeholders - # jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. Under `vmap` the - # child is one element of the flattened table, whose values the aux data does not have. + # a child that is not a concrete array stands for the flattened table: a tracer, or one of the + # placeholders jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. + # Under `vmap` the child is one element of the flattened table, whose values the aux data + # does not have. static_values = ( - None + nd_array_field._FromBuffer.TOKEN + if _has_values(ndarray) + or array_api_compat.is_numpy_array(ndarray) + or array_api_compat.is_cupy_array(ndarray) + else None if identity is None - or _has_values(ndarray) or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape else identity.values ) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 26d2606035..7f9babfb8e 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -25,7 +25,7 @@ import dataclasses from collections.abc import Callable, Mapping from types import ModuleType -from typing import Any, ClassVar, Final, Optional +from typing import Any, ClassVar, Final import array_api_compat import array_api_compat.numpy as compat_numpy @@ -212,15 +212,6 @@ def check_assignable(self, value: Any) -> None: f" to an array of '{self.xp.__name__}'." ) - def static_values(self, array: core_defs.NDArrayObject) -> Optional[core_defs.NDArrayObject]: - """ - An array with the values of `array` that can be computed on now, not necessarily of this namespace. - - `None` if the values are known only at run time, e.g. for an array standing for the - argument of a compiled program; `gather` must then accept out-of-range indices. - """ - return array - def gather( self, array: core_defs.NDArrayObject, indices: tuple[core_defs.NDArrayObject, ...] ) -> core_defs.NDArrayObject: diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 23777e7718..7b9b6a38e5 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -10,6 +10,7 @@ import collections import dataclasses +import enum import functools import itertools from collections.abc import Callable, Sequence @@ -456,6 +457,15 @@ def _broadcast_axes_slice( ) +class _FromBuffer(enum.Enum): + """The default `static_values` of a connectivity: its buffer holds them itself.""" + + TOKEN = enum.auto() + + +StaticValues: TypeAlias = Optional[core_defs.NDArrayObject] | _FromBuffer + + @dataclasses.dataclass(frozen=True) class NdArrayConnectivityField( common.GatherConnectivity[common.DimsT, common.DimT], @@ -463,15 +473,16 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: The static values of a connectivity whose buffer does not determine them, e.g. a tracer - #: standing for a concrete table (see `ArrayOps.static_values`). Not a field, so that no - #: copy inherits them; without them, they are taken from the buffer. - static_values: dataclasses.InitVar[Optional[core_defs.NDArrayObject]] = dataclasses.field( - default=None, kw_only=True + #: The static values of the table: an array with its values that can be computed on now. + #: By default the buffer itself. A creator gives another array for a buffer that does + #: not hold them, e.g. a tracer standing for a concrete table, or `None` if they exist + #: only at run time. Not a field, so that no copy inherits them. + static_values: dataclasses.InitVar[StaticValues] = dataclasses.field( + default=_FromBuffer.TOKEN, kw_only=True ) - def __post_init__(self, static_values: Optional[core_defs.NDArrayObject]) -> None: - if static_values is not None: + def __post_init__(self, static_values: StaticValues) -> None: + if static_values is not _FromBuffer.TOKEN: self.__dict__["_static_values"] = static_values @classmethod @@ -523,7 +534,7 @@ def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: @functools.cached_property def _static_values(self) -> Optional[core_defs.NDArrayObject]: - return array_ops.of(self._ndarray).static_values(self._ndarray) + return self._ndarray def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: @@ -570,7 +581,11 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: _ndarray=self._ndarray[buffer_slice], # static values that are not the buffer itself are restricted along with it static_values=( - None if values is None or values is self._ndarray else values[buffer_slice] + _FromBuffer.TOKEN + if values is self._ndarray + else None + if values is None + else values[buffer_slice] ), ) restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index d05c1ede1e..aacca51bee 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -24,7 +24,7 @@ import tempfile import typing import weakref -from typing import Any, Callable, Optional +from typing import Any, Callable import numpy as np import xxhash @@ -62,7 +62,7 @@ class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): ) _digest: str = dataclasses.field(init=False) - def __post_init__(self, static_values: Optional[core_defs.NDArrayObject]) -> None: + def __post_init__(self, static_values: nd_array_field.StaticValues) -> None: super().__post_init__(static_values) table = np.ascontiguousarray(np.asarray(self._ndarray)) object.__setattr__(self, "_digest", _table_digest(table)) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index 718563d86c..8b9fc4ab49 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -191,11 +191,10 @@ def premap_and_reduce(field, conn): assert f"tensor<{table.shape[0]}x2xi32>" in main_arguments # large constants print as hex assert 'dense<"0x' not in stablehlo - assert 'dense<"0x' in jax.jit(lambda field: field.premap(conn)).lower(field).as_text() @pytest.mark.requires_jax -def test_jax_jit_premap_with_closed_over_restricted_connectivity(): +def test_jax_jit_premap_with_closed_over_connectivity_raises(): import jax V = Dimension("V") @@ -209,10 +208,12 @@ def test_jax_jit_premap_with_closed_over_restricted_connectivity(): ) field = common._field(jax.numpy.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) - result = jax.jit(lambda field: field.premap(conn[common.NamedIndex(E2VDim, 1)]))(field) - - assert result.domain == common.domain({E: (0, 2)}) - np.testing.assert_array_equal(result.asnumpy(), [20.0, 10.0]) + for premap in ( + lambda field: field.premap(conn), + lambda field: field.premap(conn[common.NamedIndex(E2VDim, 1)]), + ): + with pytest.raises(jax.errors.ConcretizationTypeError): + jax.jit(premap)(field) @pytest.mark.requires_jax @@ -258,7 +259,7 @@ def shifted(field, offset_field): @pytest.mark.requires_jax -def test_jax_jit_premap_with_closed_over_as_offset_narrows_like_eager(): +def test_jax_jit_premap_with_closed_over_as_offset_is_computed_in_trace(): import jax from gt4py.next.ffront import experimental @@ -271,8 +272,9 @@ def test_jax_jit_premap_with_closed_over_as_offset_narrows_like_eager(): result = jax.jit(lambda field: field.premap(experimental.as_offset(Koff, offset_field)))(field) - assert result.domain == common.domain({K: (0, 3)}) - np.testing.assert_array_equal(result.asnumpy(), [1.0, 2.0, 3.0]) + # not narrowed as eagerly, the out-of-range target is clamped + assert result.domain == domain + np.testing.assert_array_equal(result.asnumpy(), [1.0, 2.0, 3.0, 3.0]) @pytest.mark.requires_jax @@ -355,9 +357,13 @@ def premap(field, conn): ) assert traces == 2 - premap(field, conn[NamedIndex(E2VDim, 0)]) - premap(field, conn[NamedIndex(E2VDim, 0)]) + # an eager restriction is a new buffer + restricted = conn[NamedIndex(E2VDim, 0)] + premap(field, restricted) + premap(field, restricted) assert traces == 3 + premap(field, conn[NamedIndex(E2VDim, 0)]) + assert traces == 4 @pytest.mark.requires_jax @@ -432,12 +438,10 @@ def test_jax_jit_premap_with_connectivity_from_array(): conn_a.ndarray, conn_a.codomain, domain=conn_a.domain ) - for result in ( - jax.jit(lambda field, conn: field.premap(conn))(field, conn), - jax.jit(lambda field: field.premap(conn))(field), - ): - assert result.domain == common.domain({E: (1, 4)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + result = jax.jit(lambda field, conn: field.premap(conn))(field, conn) + + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) @pytest.mark.requires_jax @@ -505,44 +509,41 @@ def body(carry, x): @pytest.mark.requires_jax -@pytest.mark.parametrize("nested", [False, True]) -def test_jax_jit_premap_with_replaced_table_has_no_values(nested): +def test_jax_jit_premap_with_table_computed_in_trace_raises(): import jax - E, field, conn_a, _ = _jax_narrowing_setup() - premap = ( - jax.jit(lambda field, conn: field.premap(conn)) - if nested - else nd_array_field.NdArrayField.premap - ) + _, field, conn_a, _ = _jax_narrowing_setup() def premap_next(field, conn): - return premap(field, dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) + return field.premap(dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) - result = jax.jit(premap_next)(field, conn_a) - - # as for every table computed in the trace: not narrowed, out-of-range targets clamped - assert result.domain == common.domain({E: (0, 5)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0, 30.0, 30.0]) + with pytest.raises(jax.errors.ConcretizationTypeError): + jax.jit(premap_next)(field, conn_a) @pytest.mark.requires_jax def test_jax_jit_premap_clamps_in_the_gather(): import jax - E, field, conn_a, _ = _jax_narrowing_setup() + from gt4py.next.ffront import experimental - def premap(field, table): - return field.premap(dataclasses.replace(conn_a, _ndarray=table)) + _, field, conn_a, _ = _jax_narrowing_setup() + K = Dimension("K", kind=DimensionKind.VERTICAL) + Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) + domain = common.domain({K: (0, 5)}) + k_field = common._field(jax.numpy.asarray([10.0, 20.0, 30.0, 40.0, 50.0]), domain=domain) + # targets -2, -1, 1, 4, 6 of a field on K:(0,5) + offsets = common._field(jax.numpy.asarray([-2, -2, -1, 1, 2], dtype=np.int32), domain=domain) + + def shifted(field, offset_field): + return field.premap(experimental.as_offset(Koff, offset_field)) - # targets -2, -1, 0, 1, 3 of a field on V:(1,4) - table = conn_a.ndarray - 2 - result = jax.jit(premap)(field, table) + result = jax.jit(shifted)(k_field, offsets) - assert result.domain == common.domain({E: (0, 5)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 10.0, 10.0, 30.0]) + assert result.domain == domain + np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 20.0, 50.0, 50.0]) for lowered in ( - jax.jit(premap).lower(field, table).as_text(), + jax.jit(shifted).lower(k_field, offsets).as_text(), jax.jit(lambda field, conn: field.premap(conn)).lower(field, conn_a).as_text(), ): assert "stablehlo.gather" in lowered @@ -628,6 +629,20 @@ def test_jax_pytree_of_concrete_connectivity_reads_its_own_values(): np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) +@pytest.mark.requires_jax +def test_jax_pytree_with_numpy_leaf_reads_its_own_values(): + import jax + + E, field, conn_a, _ = _jax_narrowing_setup() + + rebuilt = jax.tree.map(lambda table: np.asarray(table) + 1, conn_a) + + # targets 1, 2, 3, 4, 6 of a field on V:(1,4) + result = field.premap(rebuilt) + assert result.domain == common.domain({E: (0, 3)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + + @pytest.mark.requires_jax def test_jax_vmap_premap_over_connectivities_has_no_values(): import jax From 0f9aae25ad15608dd4e795181c75f24d62854b76 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 13:58:58 +0100 Subject: [PATCH 102/166] docs[next]: ADR 0029 without closed-over connectivities --- .../0029-Connectivities_Under_JAX_Tracing.md | 40 ++++++++++++------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 5de8112364..20bb85ad2b 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -20,19 +20,25 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. `ArrayOps.static_values` gives them for a buffer: the buffer itself by default, and `None` if the values exist only at run time. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.gather`. `JaxOps` overrides `static_values` and `gather`, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.gather`, which `JaxOps` overrides, and everything that knows about tracing is in `jax_ops.py`. -For a concrete jax table, `JaxOps.static_values` is a read-only NumPy view of it, so domain inference is never staged, also inside a trace. For a tracer it is `None`, and the connectivity then assumes that every target lies in range. A tracer that stands for a concrete table, the case of a connectivity passed to `jit`, gets the static values from its creator: the constructor takes them as a keyword-only init-only argument, which the pytree unflatten passes. They are not a dataclass field, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restricted connectivity keeps them. +Under a trace, a connectivity is supported in two cases, and its creator gives it its static values through a keyword-only init-only constructor argument: -The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values. They are compared by their memory, because NumPy returns a new view of a jax array on every call: two connectivities have the same aux data only if their static values are the same read-only memory, which holds for every wrapper of one buffer and for its restrictions with the same slice. Unflattening gives a child that is not a concrete array the static values from the aux data. +- A connectivity passed to `jit` is rebuilt by the pytree unflatten around a tracer, which gets a read-only NumPy view of the concrete table from the aux data. +- A connectivity that `as_offset` computes from traced offsets gets `None`: its values exist only at run time, so the connectivity assumes that every target lies in range. + +The static values are not a dataclass field, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. + +A concrete connectivity closed over by a trace is not supported, nor is any other connectivity built from a tracer. Domain inference then computes on the traced buffer, and jax raises a `ConcretizationTypeError`. + +The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values as a read-only NumPy array. They are compared by their memory, because NumPy returns a new view of a jax array on every call: two connectivities have the same aux data only if their static values are the same memory, which holds for every wrapper of one buffer and for its restrictions inside a trace with the same slice. Unflattening gives a child that is not a concrete array the static values from the aux data if it has their shape, and `None` otherwise, as under `vmap`, where the child is one element of the flattened table. Nothing that belongs to a trace may be kept beyond it, so a connectivity caches domains and slices, never tables or restricted connectivities. -How a `premap` behaves under `jit` depends on how its connectivity reaches the compiled function: +How a `premap` behaves under `jit` in the two supported cases: -- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`), the recommended way. The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function; a provider set outside inlines the table as a constant for the reduction. -- **Closed over** (`jax.jit(lambda f: f.premap(conn))(field)`). The table is concrete, so domain inference reads its static values, also after a `restrict` inside the trace, which restricts them along with the then staged table. The table is inlined into the compiled program as a constant. `as_offset` of a closed-over offset field behaves the same way, but slicing or computing with that field inside the trace makes it traced (next case). -- **Computed from traced values** (`as_offset(Koff, offset_field)` with a traced offset field, or any other table that is a tracer without static values). No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed. `JaxOps.gather` clamps every index to the field at both ends, so an out-of-range target reads the field's boundary value. +- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`). The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function; a provider set outside is closed over. +- **Computed by `as_offset`** in the trace, from a traced offset field or from a closed-over one, whose table the trace computes. No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed. `JaxOps.gather` clamps every index to the field at both ends, so an out-of-range target reads the field's boundary value. A tracer of any jax transformation counts as traced, not only one of `jit`. In particular a table that depends on a `vmap`ped value has no values even when `vmap` is called eagerly, because it differs per batch element. @@ -43,21 +49,23 @@ The aux data claims that the child has the static values. Where jax rebuilds a p - At the entry of `jit`, of a nested `jit`, and for the operands of `lax.cond`, the new tracer stands for the flattened table. - `lax.cond` and `lax.switch` require all branches to return the same aux data, and `lax.scan`, `lax.while_loop` and `lax.fori_loop` require the carry to keep its aux data. Selecting between two tables, changing the table of a carried connectivity, or mixing a table that has static values with one computed in the trace raises jax's `TypeError` about differing pytree structure. The same table on all branches, or an unchanged carry, keeps its static values. -For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to every child that is not a concrete array. +For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to every child that is not a concrete array of jax, NumPy or CuPy. A traced connectivity can also be closed over by the branches of `lax.cond`, the body of `lax.scan` or an inner `jit`, and used again afterwards. ## Consequences -- Domains under `jit` match eager execution when the table is concrete or has static values. -- A table computed from traced values behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. +- Domains under `jit` match eager execution when the connectivity is a `jit` argument. +- A compiled program is specific to the buffers of its connectivities: another buffer, even with equal values, retraces, and an ahead-of-time compiled program rejects it. A connectivity restricted eagerly has a new buffer. +- The tables must not change after they are used. A jax array that shares its memory with a NumPy array, as `jax.device_put` can on a CPU, must not be refilled through that array: the aux data would take the new table for the old one. +- A table computed by `as_offset` behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. - Every gather of a jax field uses `mode="clip", wrap_negative_indices=False`. That clamps both ends with no operation besides the gather, where jax's default indexing clamps past the end but emits a select to wrap negative indices. With a table that has values the clamp never acts. - Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. - `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. -- A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values: its domain is not narrowed and the gather clamps. -- The static values of a jax table are NumPy, so on a GPU domain inference reads a host copy of the table. -- Domain inference on static values is cached on the connectivity object, which is new in every trace, so it is repeated per trace but not per call. +- A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values and raises like one closed over. +- The static values in the aux data are NumPy, so on a GPU a `jit` argument is copied to the host once per table; jax keeps that copy as long as the array, and the jit cache keeps it alive. Eagerly, domain inference runs on the table itself. +- Domain inference is cached on the connectivity object. A connectivity rebuilt in a trace is new in every trace, so its domain inference is repeated per trace but not per call. Open questions, all caused by the static values in the aux data: @@ -71,6 +79,10 @@ Open questions, all caused by the static values in the aux data: Domain inference and `restrict` were methods of a `ConnectivityOps` object, one per connectivity and registered per library, which held the static values and returned its successor from `restrict`. Its methods took plain arrays, but the object carried state about one buffer and the decision what a table without values means, which is the connectivity's. It needed its own registry next to `ArrayOps`. An earlier variant passed an opaque `state` stored on the connectivity back to `ArrayOps`; every copy inherited it, so each operation had to check that the state described its table. +### Supporting closed-over connectivities + +A hook `ArrayOps.static_values` would give the static values of any buffer: for a concrete jax array a NumPy view, so that domain inference on a closed-over table is not staged, and `None` for any tracer. It would also support connectivities built from other tracers, with a clamped gather. icon4py passes its connectivities as `jit` arguments, and a closed-over table is inlined into the program, which is slower; no use case needs the hook. + ### Static values in a side table keyed by the connectivity A weak map from connectivity to static values in `jax_ops.py` needs no constructor argument, but `restrict` would need a hook to hand the restricted values back, and `ArrayOps` would have to take connectivities. @@ -81,7 +93,7 @@ A map from table to static values, inside `jax_ops.py`, needs no state on the co ### `is_traced` and `concrete_eval` on `ArrayOps` -Two small hooks, with the case distinction written out in `NdArrayConnectivityField`. The connectivity would then have to know when to evaluate concretely. `static_values` instead returns an array that can be computed on now, so the connectivity needs no evaluation mode. +Two small hooks, with the case distinction written out in `NdArrayConnectivityField`. The connectivity would then have to know when to evaluate concretely. Its creators instead give it static values that can be computed on, so the connectivity needs no evaluation mode. ### Static values that follow the connectivity instead of the table From a138b14aeeda77534a5acf00d18bd1c04f8ab5a7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 15:23:28 +0100 Subject: [PATCH 103/166] fix[next]: unsupported traced connectivities stay unsupported across pytree boundaries; TypeError for pytrees of other libraries; take from main --- pyproject.toml | 4 +- .../next/embedded/array_libraries/jax_ops.py | 69 +++++---- src/gt4py/next/embedded/nd_array_field.py | 17 ++- .../test_nd_array_field_with_jax.py | 137 ++++++++++++++++-- uv.lock | 4 +- 5 files changed, 178 insertions(+), 53 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 805cd9c316..4800513164 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -148,10 +148,10 @@ cartesian = ['black>=25.11', 'clang-format>=18.1', 'gt4py[jax,standard,testing]' cuda12 = ['cupy-cuda12x>=12.0'] cuda13 = ['cupy-cuda13x>=14.0'] jax = [ - 'jax>=0.7.0 ; python_version < "3.14"', # first version whose indexed get takes `wrap_negative_indices` + 'jax>=0.4.32 ; python_version < "3.14"', # first version whose array API namespace is jax.numpy 'jax>=0.9.1 ; python_version >= "3.14"' # first version with pre-built wheel for Python 3.14 ] -jax-cuda12 = ['jax[cuda12-local]>=0.7.0', 'gt4py[cuda12]'] +jax-cuda12 = ['jax[cuda12-local]>=0.6.0', 'gt4py[cuda12]'] jax-cuda13 = ['jax[cuda13-local]>=0.7.0', 'gt4py[cuda13]'] next = ['gt4py[jax,standard,testing]'] rocm6 = ['cupy>=13.4.1,<14.0'] diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index d164689a14..fada9481e8 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -51,8 +51,8 @@ class _TableIdentity: values: np.ndarray _key: tuple[int, tuple[int, ...], tuple[int, ...], str] - def __init__(self, values: core_defs.NDArrayObject) -> None: - assert isinstance(values, np.ndarray) and not values.flags.writeable + def __init__(self, values: np.ndarray) -> None: + assert not values.flags.writeable # holding the array keeps its memory alive, so no other array can get its address self.values = values self._key = ( @@ -157,10 +157,12 @@ def _flatten_field( # JAX also flattens pytrees whose leaves are not arrays (e.g. `jax.tree.map` results, `vmap` # axis specifications, or the placeholders of `lax.cond` branches, which are array API objects # too), so only arrays of other libraries are rejected - assert not ( - array_api_compat.is_numpy_array(field.ndarray) - or array_api_compat.is_cupy_array(field.ndarray) - ), f"Only fields of JAX arrays are JAX pytrees, got a field of '{type(field.ndarray)}'." + if array_api_compat.is_numpy_array(field.ndarray) or array_api_compat.is_cupy_array( + field.ndarray + ): + raise TypeError( + f"Only fields of JAX arrays are JAX pytrees, got a field of '{type(field.ndarray)}'." + ) return (field.ndarray,), field.domain @@ -181,7 +183,8 @@ class _ConnectivityAuxData(NamedTuple): domain: common.Domain codomain: common.Dimension skip_value: Optional[core_defs.IntegralScalar] - values: Optional[_TableIdentity] + #: `None` if the values exist only at run time + values: Optional[_TableIdentity] | nd_array_field._FromBuffer def _flatten_connectivity( @@ -190,19 +193,26 @@ def _flatten_connectivity( ndarray = connectivity._ndarray # the aux data identifies the values of a table by its buffer, which a mutable array does not # allow. The placeholders of JAX are array API objects too, so "not a JAX array" is no test. - assert not ( - array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) - ), f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." - values: Any = connectivity._static_values - if values is ndarray: - # a placeholder that is no array has no values; NumPy, so that a restriction inside the - # trace is not staged - values = _read_only_view(ndarray) if _has_values(ndarray) else None + if array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray): + raise TypeError( + f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." + ) + values = connectivity._static_values + identity: Optional[_TableIdentity] | nd_array_field._FromBuffer + if values is None: + identity = None + elif values is not ndarray: + # given by the unflattening, or restricted from such values + assert isinstance(values, np.ndarray) + identity = _TableIdentity(values) + elif _has_values(ndarray): + # NumPy, so that a restriction inside the trace is not staged + identity = _TableIdentity(_read_only_view(ndarray)) + else: + # a tracer whose values are its own, i.e. not supported: unflattening keeps it that way + identity = nd_array_field._FromBuffer.TOKEN return (ndarray,), _ConnectivityAuxData( - connectivity.domain, - connectivity.codomain, - connectivity.skip_value, - None if values is None else _TableIdentity(values), + connectivity.domain, connectivity.codomain, connectivity.skip_value, identity ) @@ -215,22 +225,27 @@ def _unflatten_connectivity( # placeholders jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. # Under `vmap` the child is one element of the flattened table, whose values the aux data # does not have. - static_values = ( - nd_array_field._FromBuffer.TOKEN - if _has_values(ndarray) + static_values: Any + if ( + identity is nd_array_field._FromBuffer.TOKEN + or _has_values(ndarray) or array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) - else None - if identity is None + ): + static_values = nd_array_field._FromBuffer.TOKEN + elif ( + identity is None or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape - else identity.values - ) + ): + static_values = None + else: + static_values = identity.values return nd_array_field.NdArrayConnectivityField( aux_data.domain, ndarray, aux_data.codomain, aux_data.skip_value, - static_values=static_values, # type: ignore[arg-type] # `NDArrayObject` typing is not complete + static_values=static_values, ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 4f8a723dee..78ece1d421 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -577,18 +577,19 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: cached = self._restrict_cache[index] = (new_domain, buffer_slice, {}, {}) new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached values = self._static_values + static_values: StaticValues + if values is self._ndarray: + static_values = _FromBuffer.TOKEN + elif values is None: + static_values = None + else: + # static values that are not the buffer itself are restricted along with it + static_values = values[buffer_slice] restricted_connectivity = dataclasses.replace( self, _domain=new_domain, _ndarray=self._ndarray[buffer_slice], - # static values that are not the buffer itself are restricted along with it - static_values=( - _FromBuffer.TOKEN - if values is self._ndarray - else None - if values is None - else values[buffer_slice] - ), + static_values=static_values, ) restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index 8b9fc4ab49..c25be80ae2 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -7,6 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause import dataclasses +import functools import re import numpy as np @@ -71,7 +72,7 @@ def test_jax_pytree_rejects_fields_of_other_libraries(): field = common._field(np.ones(3), domain=common.domain({D0: 3})) - with pytest.raises(AssertionError, match="Only fields of JAX arrays"): + with pytest.raises(TypeError, match="Only fields of JAX arrays"): jax.jit(lambda f: f * 2.0)(field) @@ -244,18 +245,15 @@ def shifted(field, offset_field): result.asnumpy(), np.take_along_axis(values, np.arange(4) + offsets, axis=1) ) - # out-of-range targets read the boundary value under a trace - beyond = common._field(jax.numpy.asarray(np.full((2, 4), 3, dtype=np.int32)), domain=domain) - np.testing.assert_array_equal( - jax.jit(shifted)(field, beyond).asnumpy(), np.repeat(values[:, -1:], 4, axis=1) - ) - below = common._field(jax.numpy.asarray(np.full((2, 4), -3, dtype=np.int32)), domain=domain) - np.testing.assert_array_equal( - jax.jit(shifted)(field, below).asnumpy(), - np.take_along_axis( - values, np.maximum(np.arange(4) - 3, 0)[None, :].repeat(2, axis=0), axis=1 - ), - ) + # out-of-range targets read some element of the field under a trace, without an error + for shift in (3, -3): + result = jax.jit(shifted)( + field, common._field(jax.numpy.full((2, 4), shift, dtype=np.int32), domain=domain) + ).asnumpy() + targets = np.arange(4) + shift + in_range = (targets >= 0) & (targets < 4) + np.testing.assert_array_equal(result[:, in_range], values[:, targets[in_range]]) + assert np.isin(result, values).all() @pytest.mark.requires_jax @@ -611,7 +609,7 @@ def test_jax_pytree_rejects_connectivities_of_other_libraries(): np.asarray([0, 1, 2, 3, 5], dtype=np.int32), codomain=conn_a.codomain, domain=conn_a.domain ) - with pytest.raises(AssertionError, match="Only connectivities of JAX arrays"): + with pytest.raises(TypeError, match="Only connectivities of JAX arrays"): jax.jit(lambda field, conn: field.premap(conn))(field, numpy_conn) @@ -672,3 +670,114 @@ def test_jax_jit_cond_returning_field(): assert result.domain == field.domain np.testing.assert_array_equal(result.asnumpy(), [20.0, 40.0, 60.0]) + + +@pytest.mark.requires_jax +def test_jax_jit_table_computed_in_trace_raises_behind_a_pytree_boundary(): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + + def premap(field, conn): + return field.premap(conn).ndarray + + def nested_jit(field, conn): + return jax.jit(premap)(field, dataclasses.replace(conn, _ndarray=conn.ndarray + 0)) + + def cond_operand(predicate, field, conn): + built = dataclasses.replace(conn, _ndarray=conn.ndarray + 0) + return jax.lax.cond(predicate, premap, premap, field, built) + + with pytest.raises(jax.errors.ConcretizationTypeError): + jax.jit(nested_jit)(field, conn_a) + with pytest.raises(jax.errors.ConcretizationTypeError): + jax.jit(cond_operand)(True, field, conn_a) + + +@pytest.mark.requires_jax +def test_jax_jit_grad_through_premap_with_connectivity_argument(): + import jax + + _, field, conn_a, conn_b = _jax_narrowing_setup() + + def loss(x, conn): + return jax.numpy.sum(common._field(x, domain=field.domain).premap(conn).ndarray ** 2) + + x = field.ndarray + for conn in (conn_a, conn_b): + np.testing.assert_allclose(jax.jit(jax.grad(loss))(x, conn), jax.grad(loss)(x, conn)) + + +@pytest.mark.requires_jax +def test_jax_jit_vmap_over_fields_with_connectivity_argument(): + import jax + + _, field, conn_a, _ = _jax_narrowing_setup() + xs = jax.numpy.stack([field.ndarray, 2.0 * field.ndarray]) + + def premap_each(xs, conn): + return jax.vmap(lambda x: common._field(x, domain=field.domain).premap(conn).ndarray)(xs) + + np.testing.assert_array_equal( + jax.jit(premap_each)(xs, conn_a), [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] + ) + + +@pytest.mark.requires_jax +def test_jax_loop_carry_with_connectivity(): + import jax + + E, field, conn_a, conn_b = _jax_narrowing_setup() + + def fori(conn, next_conn): + carried = jax.lax.fori_loop(0, 2, lambda i, c: c if next_conn is None else next_conn, conn) + return field.premap(carried) + + def while_(conn, next_conn): + def body(state): + i, c = state + return i + 1, (c if next_conn is None else next_conn) + + _, carried = jax.lax.while_loop(lambda state: state[0] < 2, body, (0, conn)) + return field.premap(carried) + + for loop in (fori, while_): + result = jax.jit(functools.partial(loop, next_conn=None))(conn_a) + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + with pytest.raises(TypeError): + jax.jit(loop)(conn_a, conn_b) + + +@pytest.mark.requires_jax +def test_jax_jit_as_offset_connectivity_through_cond_and_scan(): + import jax + + from gt4py.next.ffront import experimental + + K = Dimension("K", kind=DimensionKind.VERTICAL) + Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) + domain = common.domain({K: (0, 4)}) + field = common._field(jax.numpy.asarray([0.0, 1.0, 2.0, 3.0]), domain=domain) + offsets = common._field(jax.numpy.asarray([1, 1, 0, -1], dtype=np.int32), domain=domain) + + def via_cond(predicate, field, offset_field): + conn = experimental.as_offset(Koff, offset_field) + return jax.lax.cond( + predicate, + lambda c: field.premap(c).ndarray, + lambda c: 2.0 * field.premap(c).ndarray, + conn, + ) + + def via_scan(field, offset_field): + conn = experimental.as_offset(Koff, offset_field) + return jax.lax.scan( + lambda c, x: (c, x * field.premap(c).ndarray), conn, jax.numpy.asarray([1.0, 2.0]) + )[1] + + np.testing.assert_array_equal(jax.jit(via_cond)(True, field, offsets), [1.0, 2.0, 2.0, 2.0]) + np.testing.assert_array_equal(jax.jit(via_cond)(False, field, offsets), [2.0, 4.0, 4.0, 4.0]) + np.testing.assert_array_equal( + jax.jit(via_scan)(field, offsets), [[1.0, 2.0, 2.0, 2.0], [2.0, 4.0, 4.0, 4.0]] + ) diff --git a/uv.lock b/uv.lock index 9a1635c493..c16d9f7f8a 100644 --- a/uv.lock +++ b/uv.lock @@ -1495,8 +1495,8 @@ requires-dist = [ { name = "gt4py", extras = ["jax", "standard", "testing"], marker = "extra == 'next'" }, { name = "hypothesis", marker = "extra == 'testing'", specifier = ">=6.93" }, { name = "jax", marker = "python_full_version >= '3.14' and extra == 'jax'", specifier = ">=0.9.1" }, - { name = "jax", marker = "python_full_version < '3.14' and extra == 'jax'", specifier = ">=0.7.0" }, - { name = "jax", extras = ["cuda12-local"], marker = "extra == 'jax-cuda12'", specifier = ">=0.7.0" }, + { name = "jax", marker = "python_full_version < '3.14' and extra == 'jax'", specifier = ">=0.4.32" }, + { name = "jax", extras = ["cuda12-local"], marker = "extra == 'jax-cuda12'", specifier = ">=0.6.0" }, { name = "jax", extras = ["cuda13-local"], marker = "extra == 'jax-cuda13'", specifier = ">=0.7.0" }, { name = "jinja2", specifier = ">=3.0.0" }, { name = "lark", specifier = ">=1.1.2" }, From 3b0c8f18be374129763c4943059e61454a5a2639 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 15:23:59 +0100 Subject: [PATCH 104/166] docs[next]: ADR 0029 with take, unsupported connectivities never compute wrong results --- .../0029-Connectivities_Under_JAX_Tracing.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 20bb85ad2b..85bb4b888c 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -20,7 +20,7 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.gather`, which `JaxOps` overrides, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.take`, and everything that knows about tracing is in `jax_ops.py`. Under a trace, a connectivity is supported in two cases, and its creator gives it its static values through a keyword-only init-only constructor argument: @@ -29,7 +29,7 @@ Under a trace, a connectivity is supported in two cases, and its creator gives i The static values are not a dataclass field, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. -A concrete connectivity closed over by a trace is not supported, nor is any other connectivity built from a tracer. Domain inference then computes on the traced buffer, and jax raises a `ConcretizationTypeError`. +A concrete connectivity closed over by a trace is not supported, nor is any other connectivity built from a tracer, for example by `dataclasses.replace` or `copy` of a traced one. It either raises, usually jax's `ConcretizationTypeError` when domain inference computes on the traced buffer, or works, for example from domain lookups cached by an eager use; it does not compute a wrong result. Flattening keeps such a connectivity unsupported, so that it raises behind a pytree boundary as well. The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values as a read-only NumPy array. They are compared by their memory, because NumPy returns a new view of a jax array on every call: two connectivities have the same aux data only if their static values are the same memory, which holds for every wrapper of one buffer and for its restrictions inside a trace with the same slice. Unflattening gives a child that is not a concrete array the static values from the aux data if it has their shape, and `None` otherwise, as under `vmap`, where the child is one element of the flattened table. @@ -38,7 +38,7 @@ Nothing that belongs to a trace may be kept beyond it, so a connectivity caches How a `premap` behaves under `jit` in the two supported cases: - **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`). The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function; a provider set outside is closed over. -- **Computed by `as_offset`** in the trace, from a traced offset field or from a closed-over one, whose table the trace computes. No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed. `JaxOps.gather` clamps every index to the field at both ends, so an out-of-range target reads the field's boundary value. +- **Computed by `as_offset`** in the trace, from a traced offset field or from a closed-over one, whose table the trace computes. No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed. The gather clamps its indices, so an out-of-range target reads some element of the field. A tracer of any jax transformation counts as traced, not only one of `jit`. In particular a table that depends on a `vmap`ped value has no values even when `vmap` is called eagerly, because it differs per batch element. @@ -58,13 +58,13 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - Domains under `jit` match eager execution when the connectivity is a `jit` argument. - A compiled program is specific to the buffers of its connectivities: another buffer, even with equal values, retraces, and an ahead-of-time compiled program rejects it. A connectivity restricted eagerly has a new buffer. - The tables must not change after they are used. A jax array that shares its memory with a NumPy array, as `jax.device_put` can on a CPU, must not be refilled through that array: the aux data would take the new table for the old one. -- A table computed by `as_offset` behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read the field's boundary value, without an error. -- Every gather of a jax field uses `mode="clip", wrap_negative_indices=False`. That clamps both ends with no operation besides the gather, where jax's default indexing clamps past the end but emits a select to wrap negative indices. With a table that has values the clamp never acts. -- Skip entries read the field's first element, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of a first element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. +- A table computed by `as_offset` behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read some element of the field, without an error. +- The gather of a jax field is `jnp.take` with `mode="clip"`, which clamps both ends with no operation besides the gather. +- Skip entries read some element of the field, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of an element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. - `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. -- A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values and raises like one closed over. -- The static values in the aux data are NumPy, so on a GPU a `jit` argument is copied to the host once per table; jax keeps that copy as long as the array, and the jit cache keeps it alive. Eagerly, domain inference runs on the table itself. +- A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values and is not supported, like one closed over. +- The static values in the aux data are NumPy, so on a GPU every flatten of a concrete connectivity, as a `jit` argument, by `device_put` or by `tree_map`, reads a host copy of the table. jax makes that copy once per array and keeps it as long as the array; the jit cache keeps it alive. Eagerly, domain inference runs on the table itself. On a GPU the aux identity relies on jax keeping that copy, which is not public API. - Domain inference is cached on the connectivity object. A connectivity rebuilt in a trace is new in every trace, so its domain inference is repeated per trace but not per call. Open questions, all caused by the static values in the aux data: From 7a50f36bbe256d3dd3ea4179f91289f2ed6c7800 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 16:11:42 +0100 Subject: [PATCH 105/166] refactor[next]: static values as an attribute set by the connectivity's creators, kinds instead of None and a sentinel --- .../0029-Connectivities_Under_JAX_Tracing.md | 8 +- .../next/embedded/array_libraries/jax_ops.py | 48 +++++------- src/gt4py/next/embedded/nd_array_field.py | 73 +++++++++---------- src/gt4py/next/otf/compilation_tasks.py | 3 +- 4 files changed, 59 insertions(+), 73 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 85bb4b888c..bcee34794d 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -22,12 +22,12 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.take`, and everything that knows about tracing is in `jax_ops.py`. -Under a trace, a connectivity is supported in two cases, and its creator gives it its static values through a keyword-only init-only constructor argument: +Under a trace, a connectivity is supported in two cases, and its creator sets its static values on the new connectivity: - A connectivity passed to `jit` is rebuilt by the pytree unflatten around a tracer, which gets a read-only NumPy view of the concrete table from the aux data. -- A connectivity that `as_offset` computes from traced offsets gets `None`: its values exist only at run time, so the connectivity assumes that every target lies in range. +- A connectivity that `as_offset` computes from traced offsets gets none: its values exist only at run time, so the connectivity assumes that every target lies in range. -The static values are not a dataclass field, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. +The static values are not a dataclass field but an attribute that only these creators set, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. A concrete connectivity closed over by a trace is not supported, nor is any other connectivity built from a tracer, for example by `dataclasses.replace` or `copy` of a traced one. It either raises, usually jax's `ConcretizationTypeError` when domain inference computes on the traced buffer, or works, for example from domain lookups cached by an eager use; it does not compute a wrong result. Flattening keeps such a connectivity unsupported, so that it raises behind a pytree boundary as well. @@ -85,7 +85,7 @@ A hook `ArrayOps.static_values` would give the static values of any buffer: for ### Static values in a side table keyed by the connectivity -A weak map from connectivity to static values in `jax_ops.py` needs no constructor argument, but `restrict` would need a hook to hand the restricted values back, and `ArrayOps` would have to take connectivities. +A weak map from connectivity to static values in `jax_ops.py` needs no attribute on the connectivity, but `restrict` would need a hook to hand the restricted values back, and `ArrayOps` would have to take connectivities. ### Static values found by the table diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index fada9481e8..14977bdf93 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -23,7 +23,6 @@ from __future__ import annotations -import dataclasses from collections.abc import Callable, Mapping from typing import Any, ClassVar, NamedTuple, Optional @@ -87,7 +86,7 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArr assert isinstance(connectivity, nd_array_field.NdArrayConnectivityField) if isinstance(connectivity.ndarray, jax.core.Tracer): # computed in the trace: its values exist only at run time - return dataclasses.replace(connectivity, static_values=None) + return connectivity._with_static_values(nd_array_field._StaticValuesKind.NO_STATIC_VALUES) return connectivity @@ -183,8 +182,7 @@ class _ConnectivityAuxData(NamedTuple): domain: common.Domain codomain: common.Dimension skip_value: Optional[core_defs.IntegralScalar] - #: `None` if the values exist only at run time - values: Optional[_TableIdentity] | nd_array_field._FromBuffer + values: _TableIdentity | nd_array_field._StaticValuesKind def _flatten_connectivity( @@ -198,19 +196,17 @@ def _flatten_connectivity( f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." ) values = connectivity._static_values - identity: Optional[_TableIdentity] | nd_array_field._FromBuffer - if values is None: - identity = None - elif values is not ndarray: - # given by the unflattening, or restricted from such values - assert isinstance(values, np.ndarray) - identity = _TableIdentity(values) - elif _has_values(ndarray): + identity: _TableIdentity | nd_array_field._StaticValuesKind + if values is nd_array_field._StaticValuesKind.FROM_BUFFER and _has_values(ndarray): # NumPy, so that a restriction inside the trace is not staged identity = _TableIdentity(_read_only_view(ndarray)) + elif isinstance(values, nd_array_field._StaticValuesKind): + # of a tracer, `FROM_BUFFER` keeps an unsupported connectivity unsupported + identity = values else: - # a tracer whose values are its own, i.e. not supported: unflattening keeps it that way - identity = nd_array_field._FromBuffer.TOKEN + # given by the unflattening, or restricted from such values + assert isinstance(values, np.ndarray) + identity = _TableIdentity(values) return (ndarray,), _ConnectivityAuxData( connectivity.domain, connectivity.codomain, connectivity.skip_value, identity ) @@ -225,28 +221,22 @@ def _unflatten_connectivity( # placeholders jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. # Under `vmap` the child is one element of the flattened table, whose values the aux data # does not have. - static_values: Any + connectivity: nd_array_field.NdArrayConnectivityField = nd_array_field.NdArrayConnectivityField( + aux_data.domain, ndarray, aux_data.codomain, aux_data.skip_value + ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' if ( - identity is nd_array_field._FromBuffer.TOKEN + identity is nd_array_field._StaticValuesKind.FROM_BUFFER or _has_values(ndarray) or array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) ): - static_values = nd_array_field._FromBuffer.TOKEN - elif ( - identity is None + return connectivity + if ( + identity is nd_array_field._StaticValuesKind.NO_STATIC_VALUES or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape ): - static_values = None - else: - static_values = identity.values - return nd_array_field.NdArrayConnectivityField( - aux_data.domain, - ndarray, - aux_data.codomain, - aux_data.skip_value, - static_values=static_values, - ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' + return connectivity._with_static_values(nd_array_field._StaticValuesKind.NO_STATIC_VALUES) + return connectivity._with_static_values(identity.values) # type: ignore[arg-type] # `NDArrayObject` typing is not complete # jax registers pytree nodes by exact type, so the connectivity needs its own registration diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 78ece1d421..9b2df0ec97 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -459,13 +459,16 @@ def _broadcast_axes_slice( ) -class _FromBuffer(enum.Enum): - """The default `static_values` of a connectivity: its buffer holds them itself.""" +class _StaticValuesKind(enum.Enum): + """The static values of a connectivity when they are not a separate array.""" - TOKEN = enum.auto() + #: the buffer holds them itself + FROM_BUFFER = enum.auto() + #: they exist only at run time + NO_STATIC_VALUES = enum.auto() -StaticValues: TypeAlias = Optional[core_defs.NDArrayObject] | _FromBuffer +StaticValues: TypeAlias = core_defs.NDArrayObject | _StaticValuesKind @dataclasses.dataclass(frozen=True) @@ -475,17 +478,6 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: The static values of the table: an array with its values that can be computed on now. - #: By default the buffer itself. A creator gives another array for a buffer that does - #: not hold them, e.g. a tracer standing for a concrete table, or `None` if they exist - #: only at run time. Not a field, so that no copy inherits them. - static_values: dataclasses.InitVar[StaticValues] = dataclasses.field( - default=_FromBuffer.TOKEN, kw_only=True - ) - - def __post_init__(self, static_values: StaticValues) -> None: - if static_values is not _FromBuffer.TOKEN: - self.__dict__["_static_values"] = static_values @classmethod def from_array( # type: ignore[override] @@ -534,24 +526,35 @@ def _inverse_image_cache(self) -> dict[common.UnitRange, common.Domain]: def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: return {} - @functools.cached_property - def _static_values(self) -> Optional[core_defs.NDArrayObject]: - return self._ndarray + @property + def _static_values(self) -> StaticValues: + """ + The static values of the table: an array with its values that can be computed on now. + + The array may be of another library. By default the buffer holds them itself. A creator + that knows better sets them with `_with_static_values`; no copy inherits them. + """ + return getattr(self, "_given_static_values", _StaticValuesKind.FROM_BUFFER) + + def _with_static_values(self, static_values: StaticValues) -> NdArrayConnectivityField: + """Set the static values of `self`, a connectivity its creator has just built.""" + object.__setattr__(self, "_given_static_values", static_values) + return self def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: assert common.UnitRange.is_finite(image_range) values = self._static_values - # without static values, all targets are assumed to be in range; the gather decides - # what the others read - slices = ( - (slice(None),) * self._ndarray.ndim - if values is None - else _inverse_image_box( + if values is _StaticValuesKind.NO_STATIC_VALUES: + # all targets are assumed to be in range; the gather decides what the others read + slices: Optional[tuple[slice, ...]] = (slice(None),) * self._ndarray.ndim + else: + if values is _StaticValuesKind.FROM_BUFFER: + values = self._ndarray + slices = _inverse_image_box( values, image_range, array_ops.of(values).xp, self.skip_value ) - ) if slices is None: raise ValueError("Restriction generates non-contiguous or empty dimensions.") @@ -576,21 +579,15 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: buffer_slice = (*buffer_slice, Ellipsis) cached = self._restrict_cache[index] = (new_domain, buffer_slice, {}, {}) new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached - values = self._static_values - static_values: StaticValues - if values is self._ndarray: - static_values = _FromBuffer.TOKEN - elif values is None: - static_values = None - else: - # static values that are not the buffer itself are restricted along with it - static_values = values[buffer_slice] restricted_connectivity = dataclasses.replace( - self, - _domain=new_domain, - _ndarray=self._ndarray[buffer_slice], - static_values=static_values, + self, _domain=new_domain, _ndarray=self._ndarray[buffer_slice] ) + values = self._static_values + if not isinstance(values, _StaticValuesKind): + # static values that are not the buffer itself are restricted along with it + values = values[buffer_slice] + if values is not _StaticValuesKind.FROM_BUFFER: + restricted_connectivity._with_static_values(values) restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache return restricted_connectivity diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index aacca51bee..147d421f28 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -62,8 +62,7 @@ class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): ) _digest: str = dataclasses.field(init=False) - def __post_init__(self, static_values: nd_array_field.StaticValues) -> None: - super().__post_init__(static_values) + def __post_init__(self) -> None: table = np.ascontiguousarray(np.asarray(self._ndarray)) object.__setattr__(self, "_digest", _table_digest(table)) From d0a36191a7ef9a540f0a24c16db62a31e96d3f4e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 16:20:53 +0100 Subject: [PATCH 106/166] refactor[next]: static values passed to the constructor, or a _StaticValuesKind --- .../0029-Connectivities_Under_JAX_Tracing.md | 6 ++--- .../next/embedded/array_libraries/jax_ops.py | 25 ++++++++++++------ src/gt4py/next/embedded/nd_array_field.py | 26 ++++++++++--------- src/gt4py/next/otf/compilation_tasks.py | 3 ++- 4 files changed, 36 insertions(+), 24 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index bcee34794d..5e489dd7ff 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -22,12 +22,12 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.take`, and everything that knows about tracing is in `jax_ops.py`. -Under a trace, a connectivity is supported in two cases, and its creator sets its static values on the new connectivity: +Under a trace, a connectivity is supported in two cases, and its creator passes its static values to the constructor, as a keyword-only init-only argument (by default `FROM_BUFFER`: the buffer holds them itself): - A connectivity passed to `jit` is rebuilt by the pytree unflatten around a tracer, which gets a read-only NumPy view of the concrete table from the aux data. -- A connectivity that `as_offset` computes from traced offsets gets none: its values exist only at run time, so the connectivity assumes that every target lies in range. +- A connectivity that `as_offset` computes from traced offsets gets `NO_STATIC_VALUES`: its values exist only at run time, so the connectivity assumes that every target lies in range. -The static values are not a dataclass field but an attribute that only these creators set, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. +The static values are not a dataclass field, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. A concrete connectivity closed over by a trace is not supported, nor is any other connectivity built from a tracer, for example by `dataclasses.replace` or `copy` of a traced one. It either raises, usually jax's `ConcretizationTypeError` when domain inference computes on the traced buffer, or works, for example from domain lookups cached by an eager use; it does not compute a wrong result. Flattening keeps such a connectivity unsupported, so that it raises behind a pytree boundary as well. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 14977bdf93..448ad630ce 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -23,6 +23,7 @@ from __future__ import annotations +import dataclasses from collections.abc import Callable, Mapping from typing import Any, ClassVar, NamedTuple, Optional @@ -86,7 +87,9 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArr assert isinstance(connectivity, nd_array_field.NdArrayConnectivityField) if isinstance(connectivity.ndarray, jax.core.Tracer): # computed in the trace: its values exist only at run time - return connectivity._with_static_values(nd_array_field._StaticValuesKind.NO_STATIC_VALUES) + return dataclasses.replace( + connectivity, static_values=nd_array_field._StaticValuesKind.NO_STATIC_VALUES + ) return connectivity @@ -221,22 +224,28 @@ def _unflatten_connectivity( # placeholders jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. # Under `vmap` the child is one element of the flattened table, whose values the aux data # does not have. - connectivity: nd_array_field.NdArrayConnectivityField = nd_array_field.NdArrayConnectivityField( - aux_data.domain, ndarray, aux_data.codomain, aux_data.skip_value - ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' + static_values: Any if ( identity is nd_array_field._StaticValuesKind.FROM_BUFFER or _has_values(ndarray) or array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) ): - return connectivity - if ( + static_values = nd_array_field._StaticValuesKind.FROM_BUFFER + elif ( identity is nd_array_field._StaticValuesKind.NO_STATIC_VALUES or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape ): - return connectivity._with_static_values(nd_array_field._StaticValuesKind.NO_STATIC_VALUES) - return connectivity._with_static_values(identity.values) # type: ignore[arg-type] # `NDArrayObject` typing is not complete + static_values = nd_array_field._StaticValuesKind.NO_STATIC_VALUES + else: + static_values = identity.values + return nd_array_field.NdArrayConnectivityField( + aux_data.domain, + ndarray, + aux_data.codomain, + aux_data.skip_value, + static_values=static_values, + ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' # jax registers pytree nodes by exact type, so the connectivity needs its own registration diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 9b2df0ec97..7f6571bd75 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -478,6 +478,15 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] + #: The static values of the table, given by a creator that knows better than the buffer, + #: e.g. for a tracer standing for a concrete table. Not a field, so that no copy inherits them. + static_values: dataclasses.InitVar[StaticValues] = dataclasses.field( + default=_StaticValuesKind.FROM_BUFFER, kw_only=True + ) + + def __post_init__(self, static_values: StaticValues) -> None: + if static_values is not _StaticValuesKind.FROM_BUFFER: + object.__setattr__(self, "_given_static_values", static_values) @classmethod def from_array( # type: ignore[override] @@ -531,16 +540,11 @@ def _static_values(self) -> StaticValues: """ The static values of the table: an array with its values that can be computed on now. - The array may be of another library. By default the buffer holds them itself. A creator - that knows better sets them with `_with_static_values`; no copy inherits them. + The array may be of another library. Only given ones are stored, so that the paths + that skip `__post_init__` (pickling, copying) take them from the buffer. """ return getattr(self, "_given_static_values", _StaticValuesKind.FROM_BUFFER) - def _with_static_values(self, static_values: StaticValues) -> NdArrayConnectivityField: - """Set the static values of `self`, a connectivity its creator has just built.""" - object.__setattr__(self, "_given_static_values", static_values) - return self - def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: assert common.UnitRange.is_finite(image_range) @@ -579,15 +583,13 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: buffer_slice = (*buffer_slice, Ellipsis) cached = self._restrict_cache[index] = (new_domain, buffer_slice, {}, {}) new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached - restricted_connectivity = dataclasses.replace( - self, _domain=new_domain, _ndarray=self._ndarray[buffer_slice] - ) values = self._static_values if not isinstance(values, _StaticValuesKind): # static values that are not the buffer itself are restricted along with it values = values[buffer_slice] - if values is not _StaticValuesKind.FROM_BUFFER: - restricted_connectivity._with_static_values(values) + restricted_connectivity = dataclasses.replace( + self, _domain=new_domain, _ndarray=self._ndarray[buffer_slice], static_values=values + ) restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache return restricted_connectivity diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index 147d421f28..aacca51bee 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -62,7 +62,8 @@ class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): ) _digest: str = dataclasses.field(init=False) - def __post_init__(self) -> None: + def __post_init__(self, static_values: nd_array_field.StaticValues) -> None: + super().__post_init__(static_values) table = np.ascontiguousarray(np.asarray(self._ndarray)) object.__setattr__(self, "_digest", _table_digest(table)) From 9262906f9ec8ab80444058797e5e00b864fb8b91 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 16:39:18 +0100 Subject: [PATCH 107/166] refactor[next]: static values as a dataclass field, StaticValues.IN_BUFFER and RUN_TIME_ONLY --- .../next/embedded/array_libraries/jax_ops.py | 63 +++++++++---------- src/gt4py/next/embedded/nd_array_field.py | 62 ++++++++---------- src/gt4py/next/otf/compilation_tasks.py | 3 +- .../test_nd_array_field_with_jax.py | 11 +++- 4 files changed, 64 insertions(+), 75 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 448ad630ce..82c8a6d801 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -38,9 +38,9 @@ from gt4py.next.ffront import experimental, fbuiltins -class _TableIdentity: +class _StaticValuesByMemory: """ - Pytree aux data of a connectivity: equal if `values` is the same read-only memory. + Static values in pytree aux data: equal to others if both are the same read-only memory. NumPy returns a new view of a JAX array on every `np.asarray`, so the views of one buffer, and their restrictions with the same slice, are told apart by their memory. @@ -63,16 +63,16 @@ def __init__(self, values: np.ndarray) -> None: ) def __eq__(self, other: object) -> bool: - return isinstance(other, _TableIdentity) and self._key == other._key + return isinstance(other, _StaticValuesByMemory) and self._key == other._key def __hash__(self) -> int: return hash(self._key) def __repr__(self) -> str: - return f"" + return f"" -def _has_values(ndarray: Any) -> bool: +def _is_concrete(ndarray: Any) -> bool: return isinstance(ndarray, jax.Array) and not isinstance(ndarray, jax.core.Tracer) @@ -88,7 +88,7 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArr if isinstance(connectivity.ndarray, jax.core.Tracer): # computed in the trace: its values exist only at run time return dataclasses.replace( - connectivity, static_values=nd_array_field._StaticValuesKind.NO_STATIC_VALUES + connectivity, _static_values=nd_array_field.StaticValues.RUN_TIME_ONLY ) return connectivity @@ -185,33 +185,29 @@ class _ConnectivityAuxData(NamedTuple): domain: common.Domain codomain: common.Dimension skip_value: Optional[core_defs.IntegralScalar] - values: _TableIdentity | nd_array_field._StaticValuesKind + #: as `NdArrayConnectivityField._static_values`, with an array as NumPy compared by memory + static_values: _StaticValuesByMemory | nd_array_field.StaticValues def _flatten_connectivity( connectivity: nd_array_field.NdArrayConnectivityField, ) -> tuple[tuple[core_defs.NDArrayObject], _ConnectivityAuxData]: ndarray = connectivity._ndarray - # the aux data identifies the values of a table by its buffer, which a mutable array does not + # the aux data identifies the static values by their memory, which a mutable array does not # allow. The placeholders of JAX are array API objects too, so "not a JAX array" is no test. if array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray): raise TypeError( f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." ) - values = connectivity._static_values - identity: _TableIdentity | nd_array_field._StaticValuesKind - if values is nd_array_field._StaticValuesKind.FROM_BUFFER and _has_values(ndarray): + static_values: Any = connectivity._static_values + if static_values is nd_array_field.StaticValues.IN_BUFFER and _is_concrete(ndarray): # NumPy, so that a restriction inside the trace is not staged - identity = _TableIdentity(_read_only_view(ndarray)) - elif isinstance(values, nd_array_field._StaticValuesKind): - # of a tracer, `FROM_BUFFER` keeps an unsupported connectivity unsupported - identity = values - else: - # given by the unflattening, or restricted from such values - assert isinstance(values, np.ndarray) - identity = _TableIdentity(values) + static_values = _StaticValuesByMemory(_read_only_view(ndarray)) + elif not isinstance(static_values, nd_array_field.StaticValues): + static_values = _StaticValuesByMemory(static_values) + # otherwise the kind is kept: `IN_BUFFER` of a tracer keeps an unsupported connectivity unsupported return (ndarray,), _ConnectivityAuxData( - connectivity.domain, connectivity.codomain, connectivity.skip_value, identity + connectivity.domain, connectivity.codomain, connectivity.skip_value, static_values ) @@ -219,32 +215,29 @@ def _unflatten_connectivity( aux_data: _ConnectivityAuxData, children: tuple[core_defs.NDArrayObject] ) -> nd_array_field.NdArrayConnectivityField: (ndarray,) = children - identity = aux_data.values + static_values: Any = aux_data.static_values # a child that is not a concrete array stands for the flattened table: a tracer, or one of the # placeholders jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. - # Under `vmap` the child is one element of the flattened table, whose values the aux data - # does not have. - static_values: Any + # Under `vmap` the child is one element of the flattened table, which has another shape. if ( - identity is nd_array_field._StaticValuesKind.FROM_BUFFER - or _has_values(ndarray) + _is_concrete(ndarray) or array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray) ): - static_values = nd_array_field._StaticValuesKind.FROM_BUFFER - elif ( - identity is nd_array_field._StaticValuesKind.NO_STATIC_VALUES - or getattr(ndarray, "shape", identity.values.shape) != identity.values.shape - ): - static_values = nd_array_field._StaticValuesKind.NO_STATIC_VALUES - else: - static_values = identity.values + static_values = nd_array_field.StaticValues.IN_BUFFER + elif isinstance(static_values, _StaticValuesByMemory): + values = static_values.values + static_values = ( + values + if getattr(ndarray, "shape", values.shape) == values.shape + else nd_array_field.StaticValues.RUN_TIME_ONLY + ) return nd_array_field.NdArrayConnectivityField( aux_data.domain, ndarray, aux_data.codomain, aux_data.skip_value, - static_values=static_values, + _static_values=static_values, ) # type: ignore[abstract, unused-ignore] # see '_unflatten_field' diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 7f6571bd75..157617f8b8 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -24,7 +24,7 @@ from numpy import typing as npt from gt4py._core import definitions as core_defs -from gt4py.next import common +from gt4py.next import common, utils from gt4py.next.embedded import ( array_ops, common as embedded_common, @@ -459,16 +459,13 @@ def _broadcast_axes_slice( ) -class _StaticValuesKind(enum.Enum): +class StaticValues(enum.Enum): """The static values of a connectivity when they are not a separate array.""" - #: the buffer holds them itself - FROM_BUFFER = enum.auto() - #: they exist only at run time - NO_STATIC_VALUES = enum.auto() - - -StaticValues: TypeAlias = core_defs.NDArrayObject | _StaticValuesKind + #: the buffer holds them + IN_BUFFER = enum.auto() + #: there are none: the values exist only at run time + RUN_TIME_ONLY = enum.auto() @dataclasses.dataclass(frozen=True) @@ -478,16 +475,16 @@ class NdArrayConnectivityField( ): _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] - #: The static values of the table, given by a creator that knows better than the buffer, - #: e.g. for a tracer standing for a concrete table. Not a field, so that no copy inherits them. - static_values: dataclasses.InitVar[StaticValues] = dataclasses.field( - default=_StaticValuesKind.FROM_BUFFER, kw_only=True + #: The values of the table as an array that can be computed on now, possibly of another + #: library, for domain inference. A creator sets them for a buffer that is a tracer. + _static_values: core_defs.NDArrayObject | StaticValues = dataclasses.field( + default=StaticValues.IN_BUFFER, + kw_only=True, + compare=False, + repr=False, + metadata=utils.gt4py_metadata(fingerprint=False), ) - def __post_init__(self, static_values: StaticValues) -> None: - if static_values is not _StaticValuesKind.FROM_BUFFER: - object.__setattr__(self, "_given_static_values", static_values) - @classmethod def from_array( # type: ignore[override] cls, @@ -535,27 +532,19 @@ def _inverse_image_cache(self) -> dict[common.UnitRange, common.Domain]: def _restrict_cache(self) -> dict[Any, tuple[common.Domain, Any, dict, dict]]: return {} - @property - def _static_values(self) -> StaticValues: - """ - The static values of the table: an array with its values that can be computed on now. - - The array may be of another library. Only given ones are stored, so that the paths - that skip `__post_init__` (pickling, copying) take them from the buffer. - """ - return getattr(self, "_given_static_values", _StaticValuesKind.FROM_BUFFER) - def _inverse_image(self, image_range: common.UnitRange) -> common.Domain: if (new_domain := self._inverse_image_cache.get(image_range, None)) is None: assert common.UnitRange.is_finite(image_range) - values = self._static_values - if values is _StaticValuesKind.NO_STATIC_VALUES: + values = ( + self._ndarray + if self._static_values is StaticValues.IN_BUFFER + else self._static_values + ) + if isinstance(values, StaticValues): # all targets are assumed to be in range; the gather decides what the others read slices: Optional[tuple[slice, ...]] = (slice(None),) * self._ndarray.ndim else: - if values is _StaticValuesKind.FROM_BUFFER: - values = self._ndarray slices = _inverse_image_box( values, image_range, array_ops.of(values).xp, self.skip_value ) @@ -583,12 +572,15 @@ def restrict(self, index: common.AnyIndexSpec) -> NdArrayConnectivityField: buffer_slice = (*buffer_slice, Ellipsis) cached = self._restrict_cache[index] = (new_domain, buffer_slice, {}, {}) new_domain, buffer_slice, inverse_image_cache, restrict_cache = cached - values = self._static_values - if not isinstance(values, _StaticValuesKind): + static_values = self._static_values + if not isinstance(static_values, StaticValues): # static values that are not the buffer itself are restricted along with it - values = values[buffer_slice] + static_values = static_values[buffer_slice] restricted_connectivity = dataclasses.replace( - self, _domain=new_domain, _ndarray=self._ndarray[buffer_slice], static_values=values + self, + _domain=new_domain, + _ndarray=self._ndarray[buffer_slice], + _static_values=static_values, ) restricted_connectivity.__dict__["_inverse_image_cache"] = inverse_image_cache restricted_connectivity.__dict__["_restrict_cache"] = restrict_cache diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index aacca51bee..147d421f28 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -62,8 +62,7 @@ class _CompileTimeConnectivity(nd_array_field.NdArrayConnectivityField): ) _digest: str = dataclasses.field(init=False) - def __post_init__(self, static_values: nd_array_field.StaticValues) -> None: - super().__post_init__(static_values) + def __post_init__(self) -> None: table = np.ascontiguousarray(np.asarray(self._ndarray)) object.__setattr__(self, "_digest", _table_digest(table)) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index c25be80ae2..3b4f9b0804 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -513,7 +513,9 @@ def test_jax_jit_premap_with_table_computed_in_trace_raises(): _, field, conn_a, _ = _jax_narrowing_setup() def premap_next(field, conn): - return field.premap(dataclasses.replace(conn, _ndarray=conn.ndarray + 1)) + return field.premap( + common._connectivity(conn.ndarray + 1, codomain=conn.codomain, domain=conn.domain) + ) with pytest.raises(jax.errors.ConcretizationTypeError): jax.jit(premap_next)(field, conn_a) @@ -682,10 +684,13 @@ def premap(field, conn): return field.premap(conn).ndarray def nested_jit(field, conn): - return jax.jit(premap)(field, dataclasses.replace(conn, _ndarray=conn.ndarray + 0)) + return jax.jit(premap)( + field, + common._connectivity(conn.ndarray + 0, codomain=conn.codomain, domain=conn.domain), + ) def cond_operand(predicate, field, conn): - built = dataclasses.replace(conn, _ndarray=conn.ndarray + 0) + built = common._connectivity(conn.ndarray + 0, codomain=conn.codomain, domain=conn.domain) return jax.lax.cond(predicate, premap, premap, field, built) with pytest.raises(jax.errors.ConcretizationTypeError): From 5f4dcb0fc128efcde96bf0776e70adad52de2934 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 16:39:35 +0100 Subject: [PATCH 108/166] docs[next]: ADR 0029 on the static values field --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 5e489dd7ff..4bf6601f91 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -22,12 +22,12 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.take`, and everything that knows about tracing is in `jax_ops.py`. -Under a trace, a connectivity is supported in two cases, and its creator passes its static values to the constructor, as a keyword-only init-only argument (by default `FROM_BUFFER`: the buffer holds them itself): +Under a trace, a connectivity is supported in two cases, and its creator sets its static values in the private field `_static_values` (by default `StaticValues.IN_BUFFER`: the buffer holds them itself): - A connectivity passed to `jit` is rebuilt by the pytree unflatten around a tracer, which gets a read-only NumPy view of the concrete table from the aux data. -- A connectivity that `as_offset` computes from traced offsets gets `NO_STATIC_VALUES`: its values exist only at run time, so the connectivity assumes that every target lies in range. +- A connectivity that `as_offset` computes from traced offsets gets `StaticValues.RUN_TIME_ONLY`: its values exist only at run time, so the connectivity assumes that every target lies in range. -The static values are not a dataclass field, so no copy inherits them: a connectivity that got another table, for example through `dataclasses.replace` or `copy`, takes its static values from the new table. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. +The field takes no part in equality, `repr` or fingerprinting. Its default derives the static values from the buffer, so a connectivity built from another table, for example with `common._connectivity` or `from_array`, never carries those of an earlier one. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. Replacing `_ndarray` with `dataclasses.replace` without `_static_values` is a misuse of the interface: it would keep the static values of the old table. A concrete connectivity closed over by a trace is not supported, nor is any other connectivity built from a tracer, for example by `dataclasses.replace` or `copy` of a traced one. It either raises, usually jax's `ConcretizationTypeError` when domain inference computes on the traced buffer, or works, for example from domain lookups cached by an eager use; it does not compute a wrong result. Flattening keeps such a connectivity unsupported, so that it raises behind a pytree boundary as well. @@ -63,7 +63,7 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - Skip entries read some element of the field, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of an element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. - `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. -- A traced connectivity that is copied, or rebuilt with `dataclasses.replace`, loses its static values and is not supported, like one closed over. +- A copy of a connectivity keeps its static values, which belong to the same buffer. - The static values in the aux data are NumPy, so on a GPU every flatten of a concrete connectivity, as a `jit` argument, by `device_put` or by `tree_map`, reads a host copy of the table. jax makes that copy once per array and keeps it as long as the array; the jit cache keeps it alive. Eagerly, domain inference runs on the table itself. On a GPU the aux identity relies on jax keeping that copy, which is not public API. - Domain inference is cached on the connectivity object. A connectivity rebuilt in a trace is new in every trace, so its domain inference is repeated per trace but not per call. @@ -97,7 +97,7 @@ Two small hooks, with the case distinction written out in `NdArrayConnectivityFi ### Static values that follow the connectivity instead of the table -Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. The static values are not inherited, and a concrete table derives its own. +Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. Here the default derives the static values from the buffer, and a concrete table always derives its own. ### Bounds in the aux data instead of the table From 2c8007584fc4bb18842f00cc9abcb62517c83ab9 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 16:43:58 +0100 Subject: [PATCH 109/166] docs[next]: drop the stale gather consequence from ADR 0029 --- .../ADRs/next/0029-Connectivities_Under_JAX_Tracing.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 4bf6601f91..b03ce79653 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -59,7 +59,6 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - A compiled program is specific to the buffers of its connectivities: another buffer, even with equal values, retraces, and an ahead-of-time compiled program rejects it. A connectivity restricted eagerly has a new buffer. - The tables must not change after they are used. A jax array that shares its memory with a NumPy array, as `jax.device_put` can on a CPU, must not be refilled through that array: the aux data would take the new table for the old one. - A table computed by `as_offset` behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read some element of the field, without an error. -- The gather of a jax field is `jnp.take` with `mode="clip"`, which clamps both ends with no operation besides the gather. - Skip entries read some element of the field, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of an element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. - `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. From 89cb86a8e9034d4df14b94fdf2bf03c31d5a275d Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 16:45:00 +0100 Subject: [PATCH 110/166] docs[next]: concise pass over ADR 0029 --- .../0029-Connectivities_Under_JAX_Tracing.md | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index b03ce79653..90489727a0 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -22,16 +22,16 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.take`, and everything that knows about tracing is in `jax_ops.py`. -Under a trace, a connectivity is supported in two cases, and its creator sets its static values in the private field `_static_values` (by default `StaticValues.IN_BUFFER`: the buffer holds them itself): +The static values are the private field `_static_values`, which takes no part in equality, `repr` or fingerprinting. Its default, `StaticValues.IN_BUFFER`, takes them from the buffer, so a connectivity built from a table never carries the static values of another. Under a trace, two connectivities are supported, and their creators set the field: -- A connectivity passed to `jit` is rebuilt by the pytree unflatten around a tracer, which gets a read-only NumPy view of the concrete table from the aux data. +- A connectivity passed to `jit` is rebuilt by the pytree unflatten around a tracer. It gets a read-only NumPy view of the concrete table from the aux data. - A connectivity that `as_offset` computes from traced offsets gets `StaticValues.RUN_TIME_ONLY`: its values exist only at run time, so the connectivity assumes that every target lies in range. -The field takes no part in equality, `repr` or fingerprinting. Its default derives the static values from the buffer, so a connectivity built from another table, for example with `common._connectivity` or `from_array`, never carries those of an earlier one. `restrict` restricts static values that are not the buffer itself along with the buffer, so a restriction inside a trace keeps them. Replacing `_ndarray` with `dataclasses.replace` without `_static_values` is a misuse of the interface: it would keep the static values of the old table. +`restrict` restricts static values that are not the buffer itself along with the buffer. Replacing `_ndarray` with `dataclasses.replace` and keeping `_static_values` is a misuse of the interface. -A concrete connectivity closed over by a trace is not supported, nor is any other connectivity built from a tracer, for example by `dataclasses.replace` or `copy` of a traced one. It either raises, usually jax's `ConcretizationTypeError` when domain inference computes on the traced buffer, or works, for example from domain lookups cached by an eager use; it does not compute a wrong result. Flattening keeps such a connectivity unsupported, so that it raises behind a pytree boundary as well. +A concrete connectivity closed over by a trace is not supported, nor is a connectivity built from another tracer. It either raises, usually jax's `ConcretizationTypeError` from domain inference on the traced buffer, or works, for example from domain lookups cached by an eager use; it does not compute a wrong result. This also holds behind a pytree boundary, because flattening keeps such a connectivity unsupported. -The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and, if the table is concrete or a tracer with static values, the static values as a read-only NumPy array. They are compared by their memory, because NumPy returns a new view of a jax array on every call: two connectivities have the same aux data only if their static values are the same memory, which holds for every wrapper of one buffer and for its restrictions inside a trace with the same slice. Unflattening gives a child that is not a concrete array the static values from the aux data if it has their shape, and `None` otherwise, as under `vmap`, where the child is one element of the flattened table. +The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and the static values: a read-only NumPy array if the table is concrete or a tracer with static values. The arrays are compared by their memory, because NumPy returns a new view of a jax array on every call, so every wrapper of one buffer, and its restrictions with the same slice, have equal aux data. Unflattening gives a child that is not a concrete array the static values from the aux data if it has their shape, and `RUN_TIME_ONLY` otherwise, as under `vmap`, where the child is one element of the flattened table. Nothing that belongs to a trace may be kept beyond it, so a connectivity caches domains and slices, never tables or restricted connectivities. @@ -62,8 +62,7 @@ A traced connectivity can also be closed over by the branches of `lax.cond`, the - Skip entries read some element of the field, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of an element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. - `restrict` builds a new connectivity on every call. It shares the cached domain lookups of the connectivity it was restricted from. -- A copy of a connectivity keeps its static values, which belong to the same buffer. -- The static values in the aux data are NumPy, so on a GPU every flatten of a concrete connectivity, as a `jit` argument, by `device_put` or by `tree_map`, reads a host copy of the table. jax makes that copy once per array and keeps it as long as the array; the jit cache keeps it alive. Eagerly, domain inference runs on the table itself. On a GPU the aux identity relies on jax keeping that copy, which is not public API. +- On a GPU, every flatten of a concrete connectivity (`jit`, `device_put`, `tree_map`) reads a host copy of the table, which jax keeps as long as the array, and the jit cache keeps alive. The aux data's identity relies on jax keeping that copy, which is not public API. Eagerly, domain inference runs on the table itself. - Domain inference is cached on the connectivity object. A connectivity rebuilt in a trace is new in every trace, so its domain inference is repeated per trace but not per call. Open questions, all caused by the static values in the aux data: @@ -76,15 +75,15 @@ Open questions, all caused by the static values in the aux data: ### Table operations on a per-connectivity object -Domain inference and `restrict` were methods of a `ConnectivityOps` object, one per connectivity and registered per library, which held the static values and returned its successor from `restrict`. Its methods took plain arrays, but the object carried state about one buffer and the decision what a table without values means, which is the connectivity's. It needed its own registry next to `ArrayOps`. An earlier variant passed an opaque `state` stored on the connectivity back to `ArrayOps`; every copy inherited it, so each operation had to check that the state described its table. +A `ConnectivityOps` object per connectivity, registered per library, could hold the static values and do domain inference and `restrict` on plain arrays. But it carries state about one buffer and the decision what a table without values means, which is the connectivity's, and needs a second registry next to `ArrayOps`. ### Supporting closed-over connectivities -A hook `ArrayOps.static_values` would give the static values of any buffer: for a concrete jax array a NumPy view, so that domain inference on a closed-over table is not staged, and `None` for any tracer. It would also support connectivities built from other tracers, with a clamped gather. icon4py passes its connectivities as `jit` arguments, and a closed-over table is inlined into the program, which is slower; no use case needs the hook. +A hook `ArrayOps.static_values` could give the static values of any buffer: for a concrete jax array a NumPy view, so that domain inference on a closed-over table is not staged, and none for a tracer, which would also support connectivities built from other tracers. No use case needs it: icon4py passes its connectivities as `jit` arguments, and a closed-over table is inlined into the program, which is slower. ### Static values in a side table keyed by the connectivity -A weak map from connectivity to static values in `jax_ops.py` needs no attribute on the connectivity, but `restrict` would need a hook to hand the restricted values back, and `ArrayOps` would have to take connectivities. +A weak map from connectivity to static values in `jax_ops.py` needs no field, but `restrict` would need a hook to hand the restricted values back, and `ArrayOps` would have to take connectivities. ### Static values found by the table @@ -92,11 +91,11 @@ A map from table to static values, inside `jax_ops.py`, needs no state on the co ### `is_traced` and `concrete_eval` on `ArrayOps` -Two small hooks, with the case distinction written out in `NdArrayConnectivityField`. The connectivity would then have to know when to evaluate concretely. Its creators instead give it static values that can be computed on, so the connectivity needs no evaluation mode. +Two small hooks, with the case distinction written out in `NdArrayConnectivityField`, which would then have to know when to evaluate concretely. With static values that can be computed on, it needs no evaluation mode. -### Static values that follow the connectivity instead of the table +### Aux data from the static values of a concrete connectivity -Earlier versions kept the concrete connectivity in a field that every copy of the connectivity inherits, and derived the aux data of a connectivity with a concrete leaf from that leaf. `dataclasses.replace` then attached the values to another table, and jax's comparison of branches and carries, which runs on trees with a shared placeholder leaf, found nothing to object to: `lax.cond` between two tables silently used the values of the first one. Here the default derives the static values from the buffer, and a concrete table always derives its own. +Deriving the aux data of a connectivity with a concrete leaf from a field that `dataclasses.replace` carries over would attach the values to another table. jax's comparison of branches and carries runs on trees with a shared placeholder leaf, so `lax.cond` between two tables would silently use the values of the first. A concrete table therefore always takes its static values from itself. ### Bounds in the aux data instead of the table From b99ce772bc72bb5bc6fc02f06f6bf6457afbd6cb Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 17:12:15 +0100 Subject: [PATCH 111/166] refactor[next]: address review of ADR 0029 and the jax pytree flattening --- .../0029-Connectivities_Under_JAX_Tracing.md | 43 ++++---------- .../next/embedded/array_libraries/jax_ops.py | 58 +++++++++---------- 2 files changed, 40 insertions(+), 61 deletions(-) diff --git a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md index 90489727a0..954e7db631 100644 --- a/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md +++ b/docs/development/ADRs/next/0029-Connectivities_Under_JAX_Tracing.md @@ -6,7 +6,7 @@ tags: [embedded, jax, connectivities] - **Status**: valid - **Authors**: Hannes Vogt (@havogt) -- **Created**: 2026-11-18 +- **Created**: 2026-11-19 - **Updated**: 2026-11-19 In the context of running embedded `premap` under `jax.jit`, facing a neighbor table that must be a runtime argument for the gather but concrete for domain inference, we decided to pass the concrete table along with its tracer through the pytree aux data of the connectivity, to get the same narrowing as eager execution without compiling tables into the program. We accept a table reference held by jax's jit cache and a silent clamp when the table is only known at runtime (`as_offset`). @@ -20,28 +20,21 @@ In the context of running embedded `premap` under `jax.jit`, facing a neighbor t ## Decision -There is one connectivity class, `NdArrayConnectivityField`, for all array libraries and for all cases below. As for every embedded field, the connectivity does the domain operations, and `ArrayOps` only works on plain arrays. Domain inference reads the table's *static values*: an array with the table's values that can be computed on now, possibly of another library. By default they are the buffer itself. The box of entries that map into an image range is computed on them by one plain function for all libraries. The gather is `ArrayOps.take`, and everything that knows about tracing is in `jax_ops.py`. +There is one connectivity class, `NdArrayConnectivityField`, for all array libraries. As for every embedded field, the connectivity does the domain operations and `ArrayOps` only works on plain arrays; everything that knows about tracing is in `jax_ops.py`. Domain inference reads the connectivity's *static values*: an array with the table's values that can be computed on now, by default the buffer itself. -The static values are the private field `_static_values`, which takes no part in equality, `repr` or fingerprinting. Its default, `StaticValues.IN_BUFFER`, takes them from the buffer, so a connectivity built from a table never carries the static values of another. Under a trace, two connectivities are supported, and their creators set the field: +Under a trace, two connectivities are supported, and their creators give them their static values: -- A connectivity passed to `jit` is rebuilt by the pytree unflatten around a tracer. It gets a read-only NumPy view of the concrete table from the aux data. -- A connectivity that `as_offset` computes from traced offsets gets `StaticValues.RUN_TIME_ONLY`: its values exist only at run time, so the connectivity assumes that every target lies in range. +- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`). The pytree unflatten rebuilds the connectivity around a tracer, with a read-only NumPy view of the concrete table from the aux data as static values. Domain inference and `restrict` read them, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function. +- **Computed by `as_offset`** from a traced offset field. It has no static values: its values exist only at run time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed, and the gather clamps its indices, so an out-of-range target reads some element of the field. -`restrict` restricts static values that are not the buffer itself along with the buffer. Replacing `_ndarray` with `dataclasses.replace` and keeping `_static_values` is a misuse of the interface. +`restrict` restricts static values that are not the buffer itself along with the buffer. -A concrete connectivity closed over by a trace is not supported, nor is a connectivity built from another tracer. It either raises, usually jax's `ConcretizationTypeError` from domain inference on the traced buffer, or works, for example from domain lookups cached by an eager use; it does not compute a wrong result. This also holds behind a pytree boundary, because flattening keeps such a connectivity unsupported. +A concrete connectivity closed over by a trace is not supported, nor is a connectivity built from another tracer. It either raises or works; it does not compute a wrong result. -The connectivity is a pytree node with the table as its child. The aux data holds domain, codomain, skip value and the static values: a read-only NumPy array if the table is concrete or a tracer with static values. The arrays are compared by their memory, because NumPy returns a new view of a jax array on every call, so every wrapper of one buffer, and its restrictions with the same slice, have equal aux data. Unflattening gives a child that is not a concrete array the static values from the aux data if it has their shape, and `RUN_TIME_ONLY` otherwise, as under `vmap`, where the child is one element of the flattened table. +The connectivity is a pytree node with the table as its child and the static values in the aux data, compared by their memory, so every wrapper of one buffer has equal aux data. Nothing that belongs to a trace may be kept beyond it, so a connectivity caches domains and slices, never tables or restricted connectivities. -How a `premap` behaves under `jit` in the two supported cases: - -- **Passed as a jit argument** (`jax.jit(lambda f, c: f.premap(c))(field, conn)`). The table is a tracer with static values. Domain inference and `restrict` read the static values, and the gather takes the table as a runtime argument. A neighbor reduction takes its table from the offset provider, so the provider has to be built from the traced connectivity inside the jitted function; a provider set outside is closed over. -- **Computed by `as_offset`** in the trace, from a traced offset field or from a closed-over one, whose table the trace computes. No concrete values exist at trace time. Domain inference assumes every target lies inside the field, so the output domain is not narrowed. The gather clamps its indices, so an out-of-range target reads some element of the field. - -A tracer of any jax transformation counts as traced, not only one of `jit`. In particular a table that depends on a `vmap`ped value has no values even when `vmap` is called eagerly, because it differs per batch element. - ### Control flow The aux data claims that the child has the static values. Where jax rebuilds a pytree around new tracers, that claim stays true: @@ -49,15 +42,15 @@ The aux data claims that the child has the static values. Where jax rebuilds a p - At the entry of `jit`, of a nested `jit`, and for the operands of `lax.cond`, the new tracer stands for the flattened table. - `lax.cond` and `lax.switch` require all branches to return the same aux data, and `lax.scan`, `lax.while_loop` and `lax.fori_loop` require the carry to keep its aux data. Selecting between two tables, changing the table of a carried connectivity, or mixing a table that has static values with one computed in the trace raises jax's `TypeError` about differing pytree structure. The same table on all branches, or an unchanged carry, keeps its static values. -For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to every child that is not a concrete array of jax, NumPy or CuPy. +For that check jax rebuilds the trees around placeholders that are not tracers, which is why unflattening attaches the static values to every child that is not a concrete array. -A traced connectivity can also be closed over by the branches of `lax.cond`, the body of `lax.scan` or an inner `jit`, and used again afterwards. +A connectivity passed to `jit` can also be used by the branches of `lax.cond`, the body of `lax.scan` or an inner `jit` that close over it, and again afterwards. ## Consequences - Domains under `jit` match eager execution when the connectivity is a `jit` argument. - A compiled program is specific to the buffers of its connectivities: another buffer, even with equal values, retraces, and an ahead-of-time compiled program rejects it. A connectivity restricted eagerly has a new buffer. -- The tables must not change after they are used. A jax array that shares its memory with a NumPy array, as `jax.device_put` can on a CPU, must not be refilled through that array: the aux data would take the new table for the old one. +- The array of a connectivity must not change after it is used. A jax array that shares its memory with a NumPy array, as `jax.device_put` can on a CPU, must not be refilled through that array: the aux data would take the new table for the old one. - A table computed by `as_offset` behaves differently from eager execution when a target is out of range. Eagerly, a uniform offset narrows the domain and a non-contiguous one raises. Under `jit` the domain stays as it is and those targets read some element of the field, without an error. - Skip entries read some element of the field, and reductions mask the result afterwards. A gradient through an operator that is singular at that value is NaN (`0 * inf`), for example `sqrt` of an element that is zero. The gather cannot prevent this, because no replacement value is safe for every operator. - Connectivities reject item assignment, because their domain lookups are cached. Writing into the buffer through `.ndarray` is not detected and leaves those lookups stale, so it is not supported. @@ -79,24 +72,12 @@ A `ConnectivityOps` object per connectivity, registered per library, could hold ### Supporting closed-over connectivities -A hook `ArrayOps.static_values` could give the static values of any buffer: for a concrete jax array a NumPy view, so that domain inference on a closed-over table is not staged, and none for a tracer, which would also support connectivities built from other tracers. No use case needs it: icon4py passes its connectivities as `jit` arguments, and a closed-over table is inlined into the program, which is slower. - -### Static values in a side table keyed by the connectivity - -A weak map from connectivity to static values in `jax_ops.py` needs no field, but `restrict` would need a hook to hand the restricted values back, and `ArrayOps` would have to take connectivities. - -### Static values found by the table - -A map from table to static values, inside `jax_ops.py`, needs no state on the connectivity. But unflattening attaches static values to placeholders like `None`, integers and `object()`, which cannot be weakly referenced, and `None` is the same object everywhere. +A hook `ArrayOps.static_values` could give the static values of any buffer: for a concrete jax array a NumPy view, so that domain inference on a closed-over table is not staged, and none for a tracer, which would also support connectivities built from other tracers. For now we don't have a use case, but this decision can be re-opened when we find one. ### `is_traced` and `concrete_eval` on `ArrayOps` Two small hooks, with the case distinction written out in `NdArrayConnectivityField`, which would then have to know when to evaluate concretely. With static values that can be computed on, it needs no evaluation mode. -### Aux data from the static values of a concrete connectivity - -Deriving the aux data of a connectivity with a concrete leaf from a field that `dataclasses.replace` carries over would attach the values to another table. jax's comparison of branches and carries runs on trees with a shared placeholder leaf, so `lax.cond` between two tables would silently use the values of the first. A concrete table therefore always takes its static values from itself. - ### Bounds in the aux data instead of the table Storing only `(min, max)` retraces per bounds rather than per buffer and holds no table reference, but cannot answer narrowing ranges. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 82c8a6d801..fd3952d95f 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -40,10 +40,10 @@ class _StaticValuesByMemory: """ - Static values in pytree aux data: equal to others if both are the same read-only memory. + Static values in pytree aux data, as a read-only NumPy array: equal if the same memory. NumPy returns a new view of a JAX array on every `np.asarray`, so the views of one - buffer, and their restrictions with the same slice, are told apart by their memory. + buffer, and their restrictions with the same slice, are compared by their memory. """ __slots__ = ("_key", "values") @@ -51,8 +51,10 @@ class _StaticValuesByMemory: values: np.ndarray _key: tuple[int, tuple[int, ...], tuple[int, ...], str] - def __init__(self, values: np.ndarray) -> None: - assert not values.flags.writeable + def __init__(self, array: Any) -> None: + # NumPy, so that restricting the values inside a trace is not staged + values = np.asarray(array) + values.flags.writeable = False # holding the array keeps its memory alive, so no other array can get its address self.values = values self._key = ( @@ -72,14 +74,17 @@ def __repr__(self) -> str: return f"" -def _is_concrete(ndarray: Any) -> bool: - return isinstance(ndarray, jax.Array) and not isinstance(ndarray, jax.core.Tracer) +def _is_concrete(leaf: Any) -> bool: + """Whether `leaf` is an array, of any library, with values; tracers and placeholders have none.""" + # jax rebuilds the trees of `lax.cond` branches and carries around `ShapedArray` placeholders, + # which are array API objects too + return array_api_compat.is_array_api_obj(leaf) and not isinstance( + leaf, (jax.core.Tracer, jax.core.ShapedArray) + ) -def _read_only_view(array: jax.Array) -> np.ndarray: - values = np.asarray(array) - values.flags.writeable = False - return values +def _is_of_other_library(leaf: Any) -> bool: + return _is_concrete(leaf) and not array_api_compat.is_jax_array(leaf) def _as_offset(offset: fbuiltins.FieldOffset, offset_field: nd_array_field.NdArrayField) -> Any: @@ -157,11 +162,8 @@ def _flatten_field( field: nd_array_field.NdArrayField, ) -> tuple[tuple[core_defs.NDArrayObject], common.Domain]: # JAX also flattens pytrees whose leaves are not arrays (e.g. `jax.tree.map` results, `vmap` - # axis specifications, or the placeholders of `lax.cond` branches, which are array API objects - # too), so only arrays of other libraries are rejected - if array_api_compat.is_numpy_array(field.ndarray) or array_api_compat.is_cupy_array( - field.ndarray - ): + # axis specifications, or placeholders), so only arrays of other libraries are rejected + if _is_of_other_library(field.ndarray): raise TypeError( f"Only fields of JAX arrays are JAX pytrees, got a field of '{type(field.ndarray)}'." ) @@ -193,19 +195,18 @@ def _flatten_connectivity( connectivity: nd_array_field.NdArrayConnectivityField, ) -> tuple[tuple[core_defs.NDArrayObject], _ConnectivityAuxData]: ndarray = connectivity._ndarray - # the aux data identifies the static values by their memory, which a mutable array does not - # allow. The placeholders of JAX are array API objects too, so "not a JAX array" is no test. - if array_api_compat.is_numpy_array(ndarray) or array_api_compat.is_cupy_array(ndarray): + # the aux data identifies the static values by their memory, which a mutable array does not allow + if _is_of_other_library(ndarray): raise TypeError( f"Only connectivities of JAX arrays are JAX pytrees, got a table of '{type(ndarray)}'." ) - static_values: Any = connectivity._static_values - if static_values is nd_array_field.StaticValues.IN_BUFFER and _is_concrete(ndarray): - # NumPy, so that a restriction inside the trace is not staged - static_values = _StaticValuesByMemory(_read_only_view(ndarray)) - elif not isinstance(static_values, nd_array_field.StaticValues): - static_values = _StaticValuesByMemory(static_values) - # otherwise the kind is kept: `IN_BUFFER` of a tracer keeps an unsupported connectivity unsupported + values: Any = connectivity._static_values + if values is nd_array_field.StaticValues.IN_BUFFER and _is_concrete(ndarray): + values = ndarray + # `IN_BUFFER` of a tracer keeps an unsupported connectivity unsupported + static_values = ( + values if isinstance(values, nd_array_field.StaticValues) else _StaticValuesByMemory(values) + ) return (ndarray,), _ConnectivityAuxData( connectivity.domain, connectivity.codomain, connectivity.skip_value, static_values ) @@ -219,11 +220,8 @@ def _unflatten_connectivity( # a child that is not a concrete array stands for the flattened table: a tracer, or one of the # placeholders jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. # Under `vmap` the child is one element of the flattened table, which has another shape. - if ( - _is_concrete(ndarray) - or array_api_compat.is_numpy_array(ndarray) - or array_api_compat.is_cupy_array(ndarray) - ): + if _is_concrete(ndarray): + # e.g. a NumPy leaf of an eager `jax.tree.map`: it has values of its own static_values = nd_array_field.StaticValues.IN_BUFFER elif isinstance(static_values, _StaticValuesByMemory): values = static_values.values From 54fe283834a6c01b39aff50974b3570f760e1b43 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 17:19:10 +0100 Subject: [PATCH 112/166] style[next]: drop a comment in the connectivity unflatten --- src/gt4py/next/embedded/array_libraries/jax_ops.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index fd3952d95f..da703e766f 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -221,7 +221,6 @@ def _unflatten_connectivity( # placeholders jax rebuilds the branches of `lax.cond` and the carry of `lax.scan` around. # Under `vmap` the child is one element of the flattened table, which has another shape. if _is_concrete(ndarray): - # e.g. a NumPy leaf of an eager `jax.tree.map`: it has values of its own static_values = nd_array_field.StaticValues.IN_BUFFER elif isinstance(static_values, _StaticValuesByMemory): values = static_values.values From 12119e0d7d7588065fd6b2c061454f9a7c2b8b94 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 17:21:16 +0100 Subject: [PATCH 113/166] docs[next]: the static values of a connectivity must be those of its buffer --- src/gt4py/next/embedded/nd_array_field.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 157617f8b8..2f08b72d2d 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -476,7 +476,8 @@ class NdArrayConnectivityField( _codomain: common.DimT _skip_value: Optional[core_defs.IntegralScalar] #: The values of the table as an array that can be computed on now, possibly of another - #: library, for domain inference. A creator sets them for a buffer that is a tracer. + #: library, for domain inference. A creator sets them for a buffer that is a tracer; they + #: must be the values of `_ndarray`. _static_values: core_defs.NDArrayObject | StaticValues = dataclasses.field( default=StaticValues.IN_BUFFER, kw_only=True, From 48a75a1ab63b1cb174eb4a0c2983421f9d9fb166 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 19 Nov 2026 17:26:03 +0100 Subject: [PATCH 114/166] test[next]: jax connectivity tests check the documented behaviour, not implementation details --- .../test_nd_array_field_with_jax.py | 310 +++++------------- 1 file changed, 84 insertions(+), 226 deletions(-) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py index 3b4f9b0804..00d9e53aef 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_jax.py @@ -6,7 +6,6 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import dataclasses import functools import re @@ -194,27 +193,60 @@ def premap_and_reduce(field, conn): assert 'dense<"0x' not in stablehlo +def _raises_or_equals_eager(traced, eager): + """An unsupported connectivity may raise, but must not compute a wrong result.""" + try: + result = traced() + except Exception: + return + expected = eager() + assert result.domain == expected.domain + np.testing.assert_array_equal(result.asnumpy(), expected.asnumpy()) + + @pytest.mark.requires_jax -def test_jax_jit_premap_with_closed_over_connectivity_raises(): +def test_jax_jit_premap_with_unsupported_connectivity_is_not_wrong(): import jax - V = Dimension("V") - E = Dimension("E") + E, field, conn_a, _ = _jax_narrowing_setup() E2VDim = Dimension("E2V", kind=DimensionKind.LOCAL) - table = np.asarray([[0, 1], [1, 0], [2, 2]], dtype=np.int32) - conn = common._connectivity( - jax.numpy.asarray(table), - codomain=V, + conn_2d = common._connectivity( + jax.numpy.asarray([[0, 1], [1, 2], [3, 3]], dtype=np.int32), + codomain=conn_a.codomain, domain=common.domain({E: (0, 3), E2VDim: (0, 2)}), ) - field = common._field(jax.numpy.asarray([10.0, 20.0]), domain=common.domain({V: (0, 2)})) - for premap in ( - lambda field: field.premap(conn), - lambda field: field.premap(conn[common.NamedIndex(E2VDim, 1)]), - ): - with pytest.raises(jax.errors.ConcretizationTypeError): - jax.jit(premap)(field) + def built_in_trace(conn): + return common._connectivity(conn.ndarray + 1, codomain=conn.codomain, domain=conn.domain) + + def premap(field, conn): + return field.premap(conn) + + cases = [ + # closed over by the trace + (lambda: jax.jit(lambda f: f.premap(conn_a))(field), lambda: field.premap(conn_a)), + ( + lambda: jax.jit(lambda f: f.premap(conn_2d[NamedIndex(E2VDim, 1)]))(field), + lambda: field.premap(conn_2d[NamedIndex(E2VDim, 1)]), + ), + # built from another tracer, directly and behind a pytree boundary + ( + lambda: jax.jit(lambda f, c: f.premap(built_in_trace(c)))(field, conn_a), + lambda: field.premap(built_in_trace(conn_a)), + ), + ( + lambda: jax.jit(lambda f, c: jax.jit(premap)(f, built_in_trace(c)))(field, conn_a), + lambda: field.premap(built_in_trace(conn_a)), + ), + ( + lambda: jax.jit(lambda f, c: jax.lax.cond(True, premap, premap, f, built_in_trace(c)))( + field, conn_a + ), + lambda: field.premap(built_in_trace(conn_a)), + ), + ] + for traced, eager in cases: + _raises_or_equals_eager(traced, eager) @pytest.mark.requires_jax @@ -256,25 +288,6 @@ def shifted(field, offset_field): assert np.isin(result, values).all() -@pytest.mark.requires_jax -def test_jax_jit_premap_with_closed_over_as_offset_is_computed_in_trace(): - import jax - - from gt4py.next.ffront import experimental - - K = Dimension("K", kind=DimensionKind.VERTICAL) - Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) - domain = common.domain({K: (0, 4)}) - field = common._field(jax.numpy.asarray([0.0, 1.0, 2.0, 3.0]), domain=domain) - offset_field = common._field(jax.numpy.ones(4, dtype=np.int32), domain=domain) - - result = jax.jit(lambda field: field.premap(experimental.as_offset(Koff, offset_field)))(field) - - # not narrowed as eagerly, the out-of-range target is clamped - assert result.domain == domain - np.testing.assert_array_equal(result.asnumpy(), [1.0, 2.0, 3.0, 3.0]) - - @pytest.mark.requires_jax def test_jax_jit_premap_with_field_offset_does_not_leak_tracers(): import jax @@ -355,14 +368,6 @@ def premap(field, conn): ) assert traces == 2 - # an eager restriction is a new buffer - restricted = conn[NamedIndex(E2VDim, 0)] - premap(field, restricted) - premap(field, restricted) - assert traces == 3 - premap(field, conn[NamedIndex(E2VDim, 0)]) - assert traces == 4 - @pytest.mark.requires_jax def test_jax_jit_premap_non_contiguous_inverse_image_raises(): @@ -427,21 +432,6 @@ def _jax_narrowing_setup(): return E, field, conn_a, conn_b -@pytest.mark.requires_jax -def test_jax_jit_premap_with_connectivity_from_array(): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - conn = nd_array_field.NdArrayConnectivityField.from_array( - conn_a.ndarray, conn_a.codomain, domain=conn_a.domain - ) - - result = jax.jit(lambda field, conn: field.premap(conn))(field, conn) - - assert result.domain == common.domain({E: (1, 4)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) - - @pytest.mark.requires_jax @pytest.mark.parametrize("predicate", [True, False]) def test_jax_jit_premap_with_connectivity_selected_by_cond(predicate): @@ -459,6 +449,13 @@ def premap_selected(predicate, field, conn1, conn2): predicate, field, conn_a ) + with pytest.raises(TypeError, match="pytree structure"): + jax.jit( + lambda index, field, conn1, conn2: field.premap( + jax.lax.switch(index, [lambda: conn1, lambda: conn2]) + ) + )(1, field, conn_a, conn_b) + # the same table in both branches same_table = common._connectivity( conn_a.ndarray, codomain=conn_a.codomain, domain=conn_a.domain @@ -469,137 +466,31 @@ def premap_selected(predicate, field, conn1, conn2): @pytest.mark.requires_jax -def test_jax_jit_premap_with_connectivity_selected_by_switch(): - import jax - - _, field, conn_a, conn_b = _jax_narrowing_setup() - - def premap_selected(index, field, conn1, conn2): - return field.premap(jax.lax.switch(index, [lambda: conn1, lambda: conn2])) - - with pytest.raises(TypeError, match="pytree structure"): - jax.jit(premap_selected)(1, field, conn_a, conn_b) - - -@pytest.mark.requires_jax -def test_jax_scan_with_connectivity_carry(): - import jax - - _, field, conn_a, conn_b = _jax_narrowing_setup() - - def premap_sums(conn, next_conn): - def body(carry, x): - return (carry if next_conn is None else next_conn), x * jax.numpy.sum( - field.premap(carry).ndarray - ) - - return jax.lax.scan(body, conn, jax.numpy.asarray([1.0, 2.0]))[1] - - np.testing.assert_array_equal(premap_sums(conn_a, None), [60.0, 120.0]) - np.testing.assert_array_equal( - jax.jit(lambda conn: premap_sums(conn, None))(conn_a), [60.0, 120.0] - ) - - with pytest.raises(TypeError, match="pytree structure"): - premap_sums(conn_a, conn_b) - with pytest.raises(TypeError, match="pytree structure"): - jax.jit(premap_sums)(conn_a, conn_b) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_with_table_computed_in_trace_raises(): - import jax - - _, field, conn_a, _ = _jax_narrowing_setup() - - def premap_next(field, conn): - return field.premap( - common._connectivity(conn.ndarray + 1, codomain=conn.codomain, domain=conn.domain) - ) - - with pytest.raises(jax.errors.ConcretizationTypeError): - jax.jit(premap_next)(field, conn_a) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_clamps_in_the_gather(): - import jax - - from gt4py.next.ffront import experimental - - _, field, conn_a, _ = _jax_narrowing_setup() - K = Dimension("K", kind=DimensionKind.VERTICAL) - Koff = fbuiltins.FieldOffset("Koff", source=K, target=(K,)) - domain = common.domain({K: (0, 5)}) - k_field = common._field(jax.numpy.asarray([10.0, 20.0, 30.0, 40.0, 50.0]), domain=domain) - # targets -2, -1, 1, 4, 6 of a field on K:(0,5) - offsets = common._field(jax.numpy.asarray([-2, -2, -1, 1, 2], dtype=np.int32), domain=domain) - - def shifted(field, offset_field): - return field.premap(experimental.as_offset(Koff, offset_field)) - - result = jax.jit(shifted)(k_field, offsets) - - assert result.domain == domain - np.testing.assert_array_equal(result.asnumpy(), [10.0, 10.0, 20.0, 50.0, 50.0]) - for lowered in ( - jax.jit(shifted).lower(k_field, offsets).as_text(), - jax.jit(lambda field, conn: field.premap(conn)).lower(field, conn_a).as_text(), - ): - assert "stablehlo.gather" in lowered - assert not re.search(r"stablehlo\.(clamp|minimum|maximum|select)", lowered) - - -@pytest.mark.requires_jax -@pytest.mark.parametrize("predicate, factor", [(True, 1.0), (False, 2.0)]) -def test_jax_jit_premap_in_cond_branches_closing_over_connectivity(predicate, factor): - import jax - - _, field, conn_a, _ = _jax_narrowing_setup() - - def premap_in_branches(predicate, field, conn): - return jax.lax.cond( - predicate, - lambda: field.premap(conn).ndarray * 1.0, - lambda: field.premap(conn).ndarray * 2.0, - ) - - result = jax.jit(premap_in_branches)(predicate, field, conn_a) - - np.testing.assert_array_equal(result, np.asarray([10.0, 20.0, 30.0]) * factor) - - -@pytest.mark.requires_jax -def test_jax_jit_premap_in_nested_jit_closing_over_connectivity(): +def test_jax_jit_premap_closing_over_connectivity_argument(): import jax E, field, conn_a, _ = _jax_narrowing_setup() - def premap_twice(field, conn): - inner = jax.jit(lambda field: field.premap(conn))(field) - return inner, field.premap(conn) - - for result in jax.jit(premap_twice)(field, conn_a): - assert result.domain == common.domain({E: (1, 4)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) + def in_cond(field, conn): + return jax.lax.cond(True, lambda: field.premap(conn), lambda: field.premap(conn)) + def in_inner_jit(field, conn): + return jax.jit(lambda field: field.premap(conn))(field) -@pytest.mark.requires_jax -def test_jax_jit_premap_in_scan_body_closing_over_connectivity(): - import jax - - _, field, conn_a, _ = _jax_narrowing_setup() - - def premap_in_scan(field, conn): - def body(carry, _): - return carry + field.premap(conn).ndarray, None - - total, _ = jax.lax.scan(body, jax.numpy.zeros(3), jax.numpy.arange(2)) - return total + field.premap(conn).ndarray + def in_scan(field, conn): + result, _ = jax.lax.scan( + lambda carry, _: (field.premap(conn), None), field.premap(conn), None, length=2 + ) + return result - result = jax.jit(premap_in_scan)(field, conn_a) + def and_again_afterwards(closing_over, field, conn): + return closing_over(field, conn), field.premap(conn) - np.testing.assert_array_equal(result, [30.0, 60.0, 90.0]) + for closing_over in (in_cond, in_inner_jit, in_scan): + traced = jax.jit(functools.partial(and_again_afterwards, closing_over)) + for result in traced(field, conn_a): + assert result.domain == common.domain({E: (1, 4)}) + np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) @pytest.mark.requires_jax @@ -616,26 +507,13 @@ def test_jax_pytree_rejects_connectivities_of_other_libraries(): @pytest.mark.requires_jax -def test_jax_pytree_of_concrete_connectivity_reads_its_own_values(): - import jax - - E, field, conn_a, _ = _jax_narrowing_setup() - - rebuilt = jax.tree.map(lambda table: table + 1, conn_a) - - # targets 1, 2, 3, 4, 6 of a field on V:(1,4) - result = field.premap(rebuilt) - assert result.domain == common.domain({E: (0, 3)}) - np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) - - -@pytest.mark.requires_jax -def test_jax_pytree_with_numpy_leaf_reads_its_own_values(): +@pytest.mark.parametrize("to_leaf", [lambda table: table + 1, lambda table: np.asarray(table) + 1]) +def test_jax_pytree_rebuilt_connectivity_reads_its_own_values(to_leaf): import jax E, field, conn_a, _ = _jax_narrowing_setup() - rebuilt = jax.tree.map(lambda table: np.asarray(table) + 1, conn_a) + rebuilt = jax.tree.map(to_leaf, conn_a) # targets 1, 2, 3, 4, 6 of a field on V:(1,4) result = field.premap(rebuilt) @@ -654,10 +532,9 @@ def test_jax_vmap_premap_over_connectivities_has_no_values(): result = jax.vmap(lambda conn: field.premap(conn).ndarray)(stacked) - # each element is a table without values: not narrowed, out-of-range targets clamped - np.testing.assert_array_equal( - np.asarray(result), [[10.0, 10.0, 20.0, 30.0, 30.0], [10.0, 20.0, 30.0, 10.0, 30.0]] - ) + # each element is a table without values: not narrowed, the in-range targets are read + np.testing.assert_array_equal(np.asarray(result)[0, 1:4], [10.0, 20.0, 30.0]) + np.testing.assert_array_equal(np.asarray(result)[1, 0:3], [10.0, 20.0, 30.0]) @pytest.mark.requires_jax @@ -674,31 +551,6 @@ def test_jax_jit_cond_returning_field(): np.testing.assert_array_equal(result.asnumpy(), [20.0, 40.0, 60.0]) -@pytest.mark.requires_jax -def test_jax_jit_table_computed_in_trace_raises_behind_a_pytree_boundary(): - import jax - - _, field, conn_a, _ = _jax_narrowing_setup() - - def premap(field, conn): - return field.premap(conn).ndarray - - def nested_jit(field, conn): - return jax.jit(premap)( - field, - common._connectivity(conn.ndarray + 0, codomain=conn.codomain, domain=conn.domain), - ) - - def cond_operand(predicate, field, conn): - built = common._connectivity(conn.ndarray + 0, codomain=conn.codomain, domain=conn.domain) - return jax.lax.cond(predicate, premap, premap, field, built) - - with pytest.raises(jax.errors.ConcretizationTypeError): - jax.jit(nested_jit)(field, conn_a) - with pytest.raises(jax.errors.ConcretizationTypeError): - jax.jit(cond_operand)(True, field, conn_a) - - @pytest.mark.requires_jax def test_jax_jit_grad_through_premap_with_connectivity_argument(): import jax @@ -734,6 +586,12 @@ def test_jax_loop_carry_with_connectivity(): E, field, conn_a, conn_b = _jax_narrowing_setup() + def scan(conn, next_conn): + carried, _ = jax.lax.scan( + lambda c, x: (c if next_conn is None else next_conn, x), conn, jax.numpy.arange(2.0) + ) + return field.premap(carried) + def fori(conn, next_conn): carried = jax.lax.fori_loop(0, 2, lambda i, c: c if next_conn is None else next_conn, conn) return field.premap(carried) @@ -746,7 +604,7 @@ def body(state): _, carried = jax.lax.while_loop(lambda state: state[0] < 2, body, (0, conn)) return field.premap(carried) - for loop in (fori, while_): + for loop in (scan, fori, while_): result = jax.jit(functools.partial(loop, next_conn=None))(conn_a) assert result.domain == common.domain({E: (1, 4)}) np.testing.assert_array_equal(result.asnumpy(), [10.0, 20.0, 30.0]) From 82012afb536b433724740edd58c11102b46c027a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 08:17:16 +0100 Subject: [PATCH 115/166] feat[next]: jax_jit backend running embedded programs and field operators under jax.jit --- src/gt4py/next/embedded/nd_array_field.py | 15 +- src/gt4py/next/ffront/decorator.py | 76 ++++-- .../program_processors/runners/jax_jit.py | 154 ++++++++++++ .../ffront_tests/test_jax_jit_backend.py | 236 ++++++++++++++++++ 4 files changed, 451 insertions(+), 30 deletions(-) create mode 100644 src/gt4py/next/program_processors/runners/jax_jit.py create mode 100644 tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 9121bb6b47..1908051b12 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -358,13 +358,16 @@ def __setitem__( " 'field.ndarray[...] = ...'." ) - ops = array_ops.of(self._ndarray) - new_buffer = ops.setitem(self._ndarray, target_slice, assigned) + new_buffer = array_ops.of(self._ndarray).setitem(self._ndarray, target_slice, assigned) if new_buffer is not self._ndarray: - object.__setattr__(self, "_ndarray", new_buffer) - # A field whose buffer info was requested is likely exported again. - if "__gt_buffer_info__" in self.__dict__: - self.__dict__["__gt_buffer_info__"] = ops.buffer_info(new_buffer) + self._set_buffer(new_buffer) + + def _set_buffer(self, new_buffer: core_defs.NDArrayObject) -> None: + """Replace the buffer by one of the same shape, for libraries whose arrays are immutable.""" + object.__setattr__(self, "_ndarray", new_buffer) + # A field whose buffer info was requested is likely exported again. + if "__gt_buffer_info__" in self.__dict__: + self.__dict__["__gt_buffer_info__"] = array_ops.of(new_buffer).buffer_info(new_buffer) __abs__ = _make_builtin("abs", "abs") diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 5ed3abbcdb..ffa8e232f4 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -16,6 +16,7 @@ import contextlib import dataclasses import functools +import inspect import types import typing import warnings @@ -47,6 +48,7 @@ from gt4py.next.instrumentation import hook_machinery, metrics from gt4py.next.iterator import ir as itir from gt4py.next.otf import arguments, compiled_program, options, workflow +from gt4py.next.program_processors.runners import jax_jit from gt4py.next.type_system import type_info, type_specifications as ts, type_translation @@ -104,6 +106,9 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): @abc.abstractmethod def __gt_type__(self) -> ts.CallableType: ... + @abc.abstractmethod + def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: ... + def with_backend(self, backend: next_backend.Backend | None) -> Self: return dataclasses.replace(self, backend=backend) @@ -118,7 +123,9 @@ def with_compilation_options( ) @functools.cached_property - def _compiled_programs(self) -> compiled_program.CompiledProgramsPool: + def _compiled_programs(self) -> compiled_program.CompiledProgramsPool | jax_jit.JitRunner: + if isinstance(self.backend, jax_jit.JaxJitBackend): + return self._jax_jit_runner(self.backend) # This cached property initializer is only called when JITting the first # program variant of the pool. If the program is compiled by directly # calling `compile()`, the pool is initialized with the options passed @@ -133,6 +140,10 @@ def _make_compiled_programs_pool( ) -> compiled_program.CompiledProgramsPool: if self.backend is None or self.backend == eve.NOTHING: raise RuntimeError("Cannot compile a program without backend.") + if isinstance(self.backend, jax_jit.JaxJitBackend): + raise RuntimeError( + f"Backend '{self.backend.name}' runs embedded under 'jax.jit'; it does not compile." + ) program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) assert isinstance(program_type, ts_ffront.ProgramType) @@ -204,6 +215,7 @@ def compile( for op in offset_provider ) + assert isinstance(self._compiled_programs, compiled_program.CompiledProgramsPool) self._compiled_programs.compile(offset_providers=offset_provider, **static_args) return self @@ -315,6 +327,12 @@ def gtir(self) -> itir.Program: ) return self._frontend_transforms.past_to_itir(no_args_past).data + def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: + definition = self.definition_stage.definition + return backend.jit( + definition, self.compilation_options.static_params or (), inspect.signature(definition) + ) + def with_grid_type(self, grid_type: common.GridType) -> Program: return dataclasses.replace( self, definition_stage=dataclasses.replace(self.definition_stage, grid_type=grid_type) @@ -514,6 +532,31 @@ def __gt_type__(self) -> ts.CallableType: assert isinstance(type_, ts.CallableType) return type_ + def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: + attributes = ( + self.definition_stage.attributes if self.definition_stage else self.foast_stage.attributes + ) + if attributes is not None and any( + has_scan_op_attribute := [ + attribute in attributes for attribute in ["init", "axis", "forward"] + ] + ): + assert all(has_scan_op_attribute) + return embedded_operators.ScanOperator( + self.definition_stage.definition, + attributes["forward"], + attributes["init"], + attributes["axis"], + ) + return embedded_operators.EmbeddedOperator(self.definition_stage.definition) + + def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: + op = self._embedded_operator() + return backend.jit( + lambda *args, **kwargs: embedded_operators.field_operator_call(op, args, kwargs), + ("domain",), + ) + def with_grid_type(self, grid_type: common.GridType) -> FieldOperator: return dataclasses.replace( self, definition_stage=dataclasses.replace(self.definition_stage, grid_type=grid_type) @@ -541,9 +584,13 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> out = kwargs.pop("out") if "domain" in kwargs: domain = utils.tree_map(common.domain)(kwargs.pop("domain")) - if not isinstance(domain, tuple): - domain = utils.tree_map(lambda _: domain)(out) - out = utils.tree_map(lambda f, dom: f[dom])(out, domain) + if isinstance(self.backend, jax_jit.JaxJitBackend): + # the operator assigns to `out` inside the trace, not to a restricted copy + kwargs["domain"] = domain + else: + if not isinstance(domain, tuple): + domain = utils.tree_map(lambda _: domain)(out) + out = utils.tree_map(lambda f, dom: f[dom])(out, domain) return self._compiled_programs( *args, @@ -558,26 +605,7 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> if not next_embedded.context.within_valid_context(): # field_operator as program kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} - attributes = ( - self.definition_stage.attributes - if self.definition_stage - else self.foast_stage.attributes - ) - if attributes is not None and any( - has_scan_op_attribute := [ - attribute in attributes for attribute in ["init", "axis", "forward"] - ] - ): - assert all(has_scan_op_attribute) - forward = attributes["forward"] - init = attributes["init"] - axis = attributes["axis"] - op: embedded_operators.EmbeddedOperator = embedded_operators.ScanOperator( - self.definition_stage.definition, forward, init, axis - ) - else: - op = embedded_operators.EmbeddedOperator(self.definition_stage.definition) - return embedded_operators.field_operator_call(op, args, kwargs) + return embedded_operators.field_operator_call(self._embedded_operator(), args, kwargs) GTEntryPoint: TypeAlias = Program | FieldOperator diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/jax_jit.py new file mode 100644 index 0000000000..76879ea50b --- /dev/null +++ b/src/gt4py/next/program_processors/runners/jax_jit.py @@ -0,0 +1,154 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +Embedded execution of programs and field operators under `jax.jit`. + +`jax_jit` (created on first access, it requires `jax`) runs the Python definition +on fields of JAX arrays inside `jax.jit`. Fields, connectivities and scalars are +arguments of the jitted function; other offset provider entries (`Dimension`s of +Cartesian offsets) and the parameters named in `static_params` are static. +""" + +from __future__ import annotations + +import dataclasses +import inspect +from collections.abc import Callable, Iterable +from typing import Any, Final + +from gt4py.next import backend as next_backend, common +from gt4py.next.embedded import context as embedded_context, nd_array_field + + +@dataclasses.dataclass(frozen=True) +class JaxJitBackend(next_backend.Backend): + """Runs programs and field operators embedded, under `jax.jit`.""" + + def jit( + self, + function: Callable[..., None], + static_argnames: Iterable[str] = (), + signature: inspect.Signature | None = None, + ) -> JitRunner: + return JitRunner(function, frozenset(static_argnames), signature) + + +def _not_compiled(*args: Any, **kwargs: Any) -> Any: + raise RuntimeError("The 'jax_jit' backend runs embedded under 'jax.jit'; it does not compile.") + + +def _is_field(x: Any) -> bool: + return isinstance(x, common.Field) + + +def _written_fields(tree: Any) -> list[nd_array_field.NdArrayField]: + import jax + + return [ + leaf + for leaf in jax.tree.leaves(tree, is_leaf=_is_field) + if isinstance(leaf, nd_array_field.NdArrayField) and not isinstance(leaf, common.Connectivity) + ] + + +class JitRunner: + """ + One `jax.jit` of an embedded entry point, called like a compiled programs pool. + + The jitted function returns, for each field of the arguments, its new buffer + if the entry point assigned to it and `None` otherwise; the new buffers are + then swapped into the caller's fields. + """ + + def __init__( + self, + function: Callable[..., None], + static_argnames: frozenset[str], + signature: inspect.Signature | None, + ) -> None: + import jax + + self._function = function + self._static_argnames = static_argnames + self._signature = signature + self._jitted = jax.jit(self._traced, static_argnames=("static_kwargs", "static_provider")) + + def _traced( + self, + args: tuple[Any, ...], + kwargs: dict[str, Any], + connectivities: dict[str, common.Connectivity], + *, + static_kwargs: tuple[tuple[str, Any], ...], + static_provider: tuple[tuple[str, Any], ...], + ) -> list[Any]: + fields = _written_fields((args, kwargs)) + buffers = [field.ndarray for field in fields] + with embedded_context.update(offset_provider={**connectivities, **dict(static_provider)}): + self._function(*args, **kwargs, **dict(static_kwargs)) + return [ + field.ndarray if field.ndarray is not buffer else None + for field, buffer in zip(fields, buffers, strict=True) + ] + + def __call__( + self, + *args: Any, + offset_provider: common.OffsetProvider, + enable_jit: bool | None = None, + **kwargs: Any, + ) -> None: + if self._static_argnames: + if self._signature is not None: + bound = self._signature.bind(*args, **kwargs) + args, kwargs = (), dict(bound.arguments) + static_kwargs = tuple( + sorted((name, kwargs.pop(name)) for name in self._static_argnames & kwargs.keys()) + ) + else: + static_kwargs = () + + connectivities = {} + static_provider = [] + for name, entry in offset_provider.items(): + if isinstance(entry, common.Connectivity): + connectivities[name] = entry + else: + static_provider.append((name, entry)) + + new_buffers = self._jitted( + args, + kwargs, + connectivities, + static_kwargs=static_kwargs, + static_provider=tuple(sorted(static_provider)), + ) + for field, buffer in zip(_written_fields((args, kwargs)), new_buffers, strict=True): + if buffer is not None: + field._set_buffer(buffer) + + +def __getattr__(name: str) -> JaxJitBackend: + if name != "jax_jit": + raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") + import jax.numpy as jnp + + from gt4py.next.embedded.array_libraries import jax_ops # noqa: F401 [unused-import] # registers the pytrees + + backend = JaxJitBackend( + name="jax_jit", + executor=_not_compiled, + allocator=jnp, # type: ignore[arg-type] # an array namespace, as accepted by the field constructors + transforms=next_backend.DEFAULT_TRANSFORMS, + ) + globals()[name] = backend + return backend + + +jax_jit: Final[JaxJitBackend] diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py new file mode 100644 index 0000000000..d139c33a99 --- /dev/null +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py @@ -0,0 +1,236 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +import re + +import numpy as np +import pytest + +import gt4py.next as gtx +from gt4py.next import common, int32, neighbor_sum +from gt4py.next.ffront.experimental import as_offset + + +pytestmark = pytest.mark.requires_jax + +IDim = gtx.Dimension("IDim") +Vertex = gtx.Dimension("Vertex") +Edge = gtx.Dimension("Edge") +E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) +E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) +Ioff = gtx.FieldOffset("Ioff", source=IDim, target=(IDim,)) + +E2V_TABLE = np.asarray([[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]], dtype=np.int32) + + +@gtx.field_operator +def edge_sum(f: gtx.Field[[Vertex], gtx.float64]) -> gtx.Field[[Edge], gtx.float64]: + return neighbor_sum(f(E2V), axis=E2VDim) + + +@gtx.program +def edge_sum_program(f: gtx.Field[[Vertex], gtx.float64], out: gtx.Field[[Edge], gtx.float64]): + edge_sum(f, out=out) + + +@gtx.field_operator +def shift_scale( + f: gtx.Field[[IDim], gtx.float64], a: gtx.float64 +) -> gtx.Field[[IDim], gtx.float64]: + return a * f(IDim + 1) + + +@gtx.program +def shift_scale_program( + f: gtx.Field[[IDim], gtx.float64], a: gtx.float64, out: gtx.Field[[IDim], gtx.float64] +): + shift_scale(f, a, out=out) + + +@gtx.program +def shift_scale_bounded( + f: gtx.Field[[IDim], gtx.float64], + a: gtx.float64, + out: gtx.Field[[IDim], gtx.float64], + stop: int32, +): + shift_scale(f, a, out=out, domain={IDim: (0, stop)}) + + +@gtx.field_operator +def dynamic_shift( + f: gtx.Field[[IDim], gtx.float64], offsets: gtx.Field[[IDim], int32] +) -> gtx.Field[[IDim], gtx.float64]: + return f(as_offset(Ioff, offsets)) + + +@gtx.field_operator +def swap( + a: gtx.Field[[IDim], gtx.float64], b: gtx.Field[[IDim], gtx.float64] +) -> tuple[gtx.Field[[IDim], gtx.float64], gtx.Field[[IDim], gtx.float64]]: + return b, a + + +@pytest.fixture( + params=["cpu", pytest.param("gpu", marks=pytest.mark.requires_gpu)], +) +def device(request): + import jax + + try: + return jax.devices(request.param)[0] + except RuntimeError: + pytest.skip(f"no jax '{request.param}' device") + + +@pytest.fixture +def backend(): + from gt4py.next.program_processors.runners import jax_jit + + return jax_jit.jax_jit + + +def _field(device, values, dims): + import jax + + values = np.asarray(values) + return common._field( + jax.device_put(values, device), + domain=common.domain({dim: size for dim, size in zip(dims, values.shape)}), + ) + + +def _e2v(device, table=E2V_TABLE): + import jax + + return common._connectivity( + jax.device_put(table, device), + codomain=Vertex, + domain=common.domain({Edge: table.shape[0], E2VDim: table.shape[1]}), + ) + + +def _runner(entry_point): + return entry_point._compiled_programs._jitted + + +def test_program_with_connectivity(device, backend): + f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) + out = _field(device, np.zeros(5), [Edge]) + expected = _field(device, np.zeros(5), [Edge]) + conn = _e2v(device) + out_object = out + + edge_sum_program.with_backend(backend)(f, out, offset_provider={"E2V": conn}) + edge_sum_program(f, expected, offset_provider={"E2V": conn}) + + assert out is out_object + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), [3.0, 5.0, 7.0, 5.0, 4.0]) + + +def test_table_is_a_runtime_argument(device, backend): + f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) + out = _field(device, np.zeros(5), [Edge]) + prog = edge_sum_program.with_backend(backend) + conn = _e2v(device) + prog(f, out, offset_provider={"E2V": conn}) + + stablehlo = ( + _runner(prog) + .lower((f, out), {}, {"E2V": conn}, static_kwargs=(), static_provider=()) + .as_text() + ) + main_signature = re.search(r"@main\(([^)]*)\)", stablehlo).group(1) + assert "tensor<5x2xi32>" in main_signature + + +def test_retrace_per_table_buffer(device, backend): + f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) + out = _field(device, np.zeros(5), [Edge]) + prog = edge_sum_program.with_backend(backend) + conn = _e2v(device) + + prog(f, out, offset_provider={"E2V": conn}) + prog(_field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), out, offset_provider={"E2V": conn}) + assert _runner(prog)._cache_size() == 1 + np.testing.assert_array_equal(out.asnumpy(), [7.0, 5.0, 3.0, 5.0, 6.0]) + + prog(f, out, offset_provider={"E2V": _e2v(device, E2V_TABLE.copy())}) + assert _runner(prog)._cache_size() == 2 + + +def test_cartesian_offset_and_traced_scalar(device, backend): + f = _field(device, np.arange(6.0), [IDim]) + prog = shift_scale_program.with_backend(backend) + for a in (2.0, 3.0): + out = _field(device, np.zeros(5), [IDim]) + expected = _field(device, np.zeros(5), [IDim]) + prog(f, a, out, offset_provider={}) + shift_scale_program(f, a, expected, offset_provider={}) + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + + assert _runner(prog)._cache_size() == 1 + + +def test_static_param_in_program_domain(device, backend): + f = _field(device, np.arange(6.0), [IDim]) + prog = shift_scale_bounded.with_backend(backend).with_static_params("stop") + out = _field(device, np.full(5, -1.0), [IDim]) + expected = _field(device, np.full(5, -1.0), [IDim]) + + prog(f, 2.0, out, 3, offset_provider={}) + shift_scale_bounded(f, 2.0, expected, 3, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), [2.0, 4.0, 6.0, -1.0, -1.0]) + + +def test_field_operator_out_and_domain(device, backend): + f = _field(device, np.arange(6.0), [IDim]) + out = _field(device, np.full(5, -1.0), [IDim]) + expected = _field(device, np.full(5, -1.0), [IDim]) + + shift_scale.with_backend(backend)( + f, 2.0, out=out, offset_provider={}, domain={IDim: (1, 4)} + ) + shift_scale(f, 2.0, out=expected, offset_provider={}, domain={IDim: (1, 4)}) + + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), [-1.0, 4.0, 6.0, 8.0, -1.0]) + + +def test_dimension_in_offset_provider_is_static(device, backend): + f = _field(device, np.arange(6.0), [IDim]) + offsets = _field(device, np.asarray([1, 0, 2, 1, 0], dtype=np.int32), [IDim]) + out = _field(device, np.zeros(5), [IDim]) + expected = _field(device, np.zeros(5), [IDim]) + + dynamic_shift.with_backend(backend)(f, offsets, out=out, offset_provider={"Ioff": IDim}) + dynamic_shift(f, offsets, out=expected, offset_provider={"Ioff": IDim}) + + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), [1.0, 1.0, 4.0, 4.0, 4.0]) + + +def test_field_operator_tuple_out_leaves_inputs(device, backend): + a = _field(device, np.arange(3.0), [IDim]) + b = _field(device, np.arange(3.0) + 10, [IDim]) + a_buffer, b_buffer = a.ndarray, b.ndarray + out = (_field(device, np.zeros(3), [IDim]), _field(device, np.zeros(3), [IDim])) + + swap.with_backend(backend)(a, b, out=out, offset_provider={}) + + assert a.ndarray is a_buffer and b.ndarray is b_buffer + np.testing.assert_array_equal(out[0].asnumpy(), b.asnumpy()) + np.testing.assert_array_equal(out[1].asnumpy(), a.asnumpy()) + + +def test_compile_is_rejected(backend): + with pytest.raises(RuntimeError, match="does not compile"): + edge_sum_program.with_backend(backend).compile(offset_provider={"E2V": None}) From 19bf2dbc38b2287228d85a346f8832b2dc39145a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 08:31:49 +0100 Subject: [PATCH 116/166] style[next]: lint and typing of the jax_jit backend --- src/gt4py/next/ffront/decorator.py | 4 +++- .../program_processors/runners/jax_jit.py | 19 +++++++++++-------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index ffa8e232f4..279cc4d8cb 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -534,7 +534,9 @@ def __gt_type__(self) -> ts.CallableType: def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: attributes = ( - self.definition_stage.attributes if self.definition_stage else self.foast_stage.attributes + self.definition_stage.attributes + if self.definition_stage + else self.foast_stage.attributes ) if attributes is not None and any( has_scan_op_attribute := [ diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/jax_jit.py index 76879ea50b..ba670c89c0 100644 --- a/src/gt4py/next/program_processors/runners/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/jax_jit.py @@ -20,7 +20,7 @@ import dataclasses import inspect from collections.abc import Callable, Iterable -from typing import Any, Final +from typing import Any from gt4py.next import backend as next_backend, common from gt4py.next.embedded import context as embedded_context, nd_array_field @@ -53,7 +53,8 @@ def _written_fields(tree: Any) -> list[nd_array_field.NdArrayField]: return [ leaf for leaf in jax.tree.leaves(tree, is_leaf=_is_field) - if isinstance(leaf, nd_array_field.NdArrayField) and not isinstance(leaf, common.Connectivity) + if isinstance(leaf, nd_array_field.NdArrayField) + and not isinstance(leaf, common.Connectivity) ] @@ -83,7 +84,7 @@ def _traced( self, args: tuple[Any, ...], kwargs: dict[str, Any], - connectivities: dict[str, common.Connectivity], + connectivities: dict[str, Any], *, static_kwargs: tuple[tuple[str, Any], ...], static_provider: tuple[tuple[str, Any], ...], @@ -114,8 +115,8 @@ def __call__( else: static_kwargs = () - connectivities = {} - static_provider = [] + connectivities: dict[str, Any] = {} + static_provider: list[tuple[str, Any]] = [] for name, entry in offset_provider.items(): if isinstance(entry, common.Connectivity): connectivities[name] = entry @@ -139,16 +140,18 @@ def __getattr__(name: str) -> JaxJitBackend: raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") import jax.numpy as jnp - from gt4py.next.embedded.array_libraries import jax_ops # noqa: F401 [unused-import] # registers the pytrees + from gt4py.next.embedded.array_libraries import ( + jax_ops, # noqa: F401 [unused-import] # registers the pytrees + ) backend = JaxJitBackend( name="jax_jit", executor=_not_compiled, - allocator=jnp, # type: ignore[arg-type] # an array namespace, as accepted by the field constructors + allocator=jnp, transforms=next_backend.DEFAULT_TRANSFORMS, ) globals()[name] = backend return backend -jax_jit: Final[JaxJitBackend] +jax_jit: JaxJitBackend From 1393b110a0f327311acf78b5854907416bc30eba Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 08:31:49 +0100 Subject: [PATCH 117/166] feat[next]: embedded accepts 0-d arrays as scalars, so jax_jit traces scalar arguments --- .../next/embedded/array_libraries/jax_ops.py | 4 ++ src/gt4py/next/embedded/array_ops.py | 11 +++++ src/gt4py/next/embedded/nd_array_field.py | 7 ++- src/gt4py/next/embedded/operators.py | 12 +++--- src/gt4py/next/ffront/fbuiltins.py | 39 +++++++++++------ .../ffront_tests/test_jax_jit_backend.py | 43 +++++++++++++++++-- 6 files changed, 90 insertions(+), 26 deletions(-) diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index da703e766f..7a31329e5c 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -138,6 +138,10 @@ def take( ) -> core_defs.NDArrayObject: return jnp.take(array, indices, axis=axis, mode="clip") + def scalar(self, array: core_defs.NDArrayObject) -> Any: + # a traced element stays a 0-d tracer: its value is only known at run time + return super().scalar(array) if _is_concrete(array) else array + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.asarray(array) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 056c5a650c..9e30b76e3e 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -229,6 +229,10 @@ def check_assignable(self, value: Any) -> None: f" to an array of '{self.xp.__name__}'." ) + def scalar(self, array: core_defs.NDArrayObject) -> Any: + """The element of the 0-d `array`, as a NumPy scalar.""" + return self.to_numpy(array)[()] + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return np.from_dlpack(array, device="cpu", copy=None) # type: ignore[arg-type] # `NDArrayObject` typing is not complete @@ -266,6 +270,13 @@ def of(array: Any) -> ArrayOps: return ops +def is_scalar(value: Any) -> bool: + """A scalar, or a 0-d array (e.g. a traced scalar argument under `jax.jit`).""" + return core_defs.is_scalar_type(value) or ( + getattr(value, "ndim", None) == 0 and array_api_compat.is_array_api_obj(value) + ) + + def default() -> ArrayOps: """The `ArrayOps` used for data that is not an array, e.g. nested lists.""" return for_namespace(compat_numpy) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 1908051b12..c6ffdb2765 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -69,7 +69,7 @@ def _builtin_op(*fields: common.Field | core_defs.Scalar) -> NdArrayField: arrays.append(array) transformed.append(array) else: - assert core_defs.is_scalar_type(f) + assert array_ops.is_scalar(f) transformed.append(f) if len(arrays) < len(transformed): transformed = [ops.operand(v, arrays[0]) for v in transformed] @@ -193,8 +193,7 @@ def as_scalar(self) -> core_defs.ScalarT: raise ValueError( f"'as_scalar' is only valid on 0-dimensional 'Field's, got a {self.domain.ndim}-dimensional 'Field'." ) - # note: `.item()` will return a Python type, therefore we use indexing with an empty tuple - return self.asnumpy()[()] # type: ignore[return-value] # should be ensured by the 0-d check + return array_ops.of(self._ndarray).scalar(self._ndarray) def premap( self: NdArrayField, @@ -349,7 +348,7 @@ def __setitem__( f"Incompatible 'Domain' in assignment. Source domain = '{value.domain}', target domain = '{target_domain}'." ) assigned = value.ndarray - elif isinstance(value, bool | int | float | np.generic): + elif isinstance(value, bool | int | float | np.generic) or array_ops.is_scalar(value): assigned = value else: raise TypeError( diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 46b897feee..f278815bf3 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -13,7 +13,7 @@ from gt4py._core import definitions as core_defs from gt4py.eve import xtyping from gt4py.next import common, errors, field_utils, named_collections, utils -from gt4py.next.embedded import common as embedded_common, context as embedded_context +from gt4py.next.embedded import array_ops, common as embedded_common, context as embedded_context from gt4py.next.otf import arguments from gt4py.next.type_system import type_specifications as ts, type_translation @@ -76,9 +76,11 @@ def scan_loop(hpos: Sequence[common.NamedIndex]) -> None: # convert custom NamedCollections to plain tuples for assignment acc_extracted = arguments.extract(acc) res_extracted = arguments.extract(res) - assert xtyping.is_maybe_nested_in_tuple_of(acc_extracted, core_defs.Scalar) # type: ignore[arg-type] # Scalar is a Union + assert all( + array_ops.is_scalar(a) for a in utils.flatten_nested_tuple((acc_extracted,)) + ) assert xtyping.is_maybe_nested_in_tuple_of(res_extracted, common.MutableField) # type: ignore[type-abstract] # MutableField is abstract/generic - _tuple_assign_value(pos, res_extracted, acc_extracted) + _tuple_assign_value(pos, res_extracted, acc_extracted) # type: ignore[arg-type] # 0-d arrays are scalars too if len(non_scan_domain) == 0: # if we don't have any dimension orthogonal to scan_axis, we need to do one scan_loop @@ -161,7 +163,7 @@ def impl(target: common.MutableField, source: common.Field, domain: common.Domai if isinstance(source, common.Field): target[domain] = source[domain] else: - assert core_defs.is_scalar_type(source) + assert array_ops.is_scalar(source) target[domain] = source if not isinstance(domain, tuple): @@ -196,7 +198,7 @@ def _tuple_at( @named_collections.tree_map_named_collection def impl(field: common.Field | core_defs.Scalar) -> core_defs.Scalar: res = field[pos].as_scalar() if isinstance(field, common.Field) else field - assert core_defs.is_scalar_type(res) + assert array_ops.is_scalar(res) return res return impl(field) # type: ignore[return-value] diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 045098bf76..c91783730a 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -281,13 +281,24 @@ def min_over(field: common.Field, /, axis: common.Dimension) -> common.Field: raise NotImplementedError() +def _is_scalar(value: Any) -> bool: + from gt4py.next.embedded import array_ops # avoid circular import + + return array_ops.is_scalar(value) + + +def _array_ops_of_0d(value: Any) -> Any: + from gt4py.next.embedded import array_ops # avoid circular import + + assert array_ops.is_scalar(value) + return array_ops.of(value) + + @BuiltInFunction def broadcast( field: common.Field | core_defs.ScalarT, dims: tuple[common.Dimension, ...], / ) -> common.Field: - assert core_defs.is_scalar_type( - field - ) # default implementation for scalars, Fields are handled via dispatch + assert _is_scalar(field) # default implementation for scalars, Fields are handled via dispatch # TODO(havogt) implement with FunctionField, the workaround is to ignore broadcasting on scalars as they broadcast automatically, but we lose the check for compatible dimensions return field # type: ignore[return-value] # see comment above @@ -321,8 +332,10 @@ def astype( if isinstance(value, tuple): return tuple(astype(v, type_) for v in value) # default implementation for scalars, Fields are handled via dispatch - assert core_defs.is_scalar_type(value) - return core_defs.dtype(type_).scalar_type(value) + if core_defs.is_scalar_type(value): + return core_defs.dtype(type_).scalar_type(value) + ops = _array_ops_of_0d(value) + return ops.xp.astype(value, ops.dtype(type_)) _UNARY_MATH_NUMBER_BUILTIN_IMPL: Final = {"abs": abs, "neg": operator.neg} @@ -379,11 +392,10 @@ def _make_unary_math_builtin(name: str) -> BuiltInFunction: def impl(value: common.Field | core_defs.ScalarT, /) -> common.Field | core_defs.ScalarT: # TODO(havogt): enable tests in `test_math_builtin_execution.py` - assert core_defs.is_scalar_type( - value - ) # default implementation for scalars, Fields are handled via dispatch - - return cast(common.Field | core_defs.ScalarT, _math_builtin(value)) + # default implementation for scalars, Fields are handled via dispatch + if core_defs.is_scalar_type(value): + return cast(common.Field | core_defs.ScalarT, _math_builtin(value)) + return _array_ops_of_0d(value).elementwise_function(name)(value) impl.__name__ = name return BuiltInFunction(impl) @@ -424,9 +436,10 @@ def impl( lhs: common.Field | core_defs.ScalarT, rhs: common.Field | core_defs.ScalarT, / ) -> common.Field | core_defs.ScalarT: # default implementation for scalars, Fields are handled via dispatch - assert core_defs.is_scalar_type(lhs) - assert core_defs.is_scalar_type(rhs) - return getattr(np, name)(lhs, rhs) + if core_defs.is_scalar_type(lhs) and core_defs.is_scalar_type(rhs): + return getattr(np, name)(lhs, rhs) + ops = _array_ops_of_0d(rhs if core_defs.is_scalar_type(lhs) else lhs) + return ops.elementwise_function(name)(ops.operand(lhs, rhs), ops.operand(rhs, lhs)) impl.__name__ = name return BuiltInFunction(impl) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py index d139c33a99..9e452edf69 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py @@ -12,13 +12,14 @@ import pytest import gt4py.next as gtx -from gt4py.next import common, int32, neighbor_sum +from gt4py.next import astype, common, int32, maximum, neighbor_sum, sqrt from gt4py.next.ffront.experimental import as_offset pytestmark = pytest.mark.requires_jax IDim = gtx.Dimension("IDim") +KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) Vertex = gtx.Dimension("Vertex") Edge = gtx.Dimension("Edge") E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) @@ -69,6 +70,18 @@ def dynamic_shift( return f(as_offset(Ioff, offsets)) +@gtx.field_operator +def scalar_builtins( + f: gtx.Field[[IDim], gtx.float64], a: gtx.float64, n: int32 +) -> gtx.Field[[IDim], gtx.float64]: + return (sqrt(a) + maximum(a, 5.0) + astype(n, gtx.float64)) * f + + +@gtx.scan_operator(axis=KDim, forward=True, init=0.0) +def scaled_cumsum(state: gtx.float64, x: gtx.float64, a: gtx.float64) -> gtx.float64: + return state + a * x + + @gtx.field_operator def swap( a: gtx.Field[[IDim], gtx.float64], b: gtx.Field[[IDim], gtx.float64] @@ -196,9 +209,7 @@ def test_field_operator_out_and_domain(device, backend): out = _field(device, np.full(5, -1.0), [IDim]) expected = _field(device, np.full(5, -1.0), [IDim]) - shift_scale.with_backend(backend)( - f, 2.0, out=out, offset_provider={}, domain={IDim: (1, 4)} - ) + shift_scale.with_backend(backend)(f, 2.0, out=out, offset_provider={}, domain={IDim: (1, 4)}) shift_scale(f, 2.0, out=expected, offset_provider={}, domain={IDim: (1, 4)}) np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) @@ -218,6 +229,30 @@ def test_dimension_in_offset_provider_is_static(device, backend): np.testing.assert_array_equal(out.asnumpy(), [1.0, 1.0, 4.0, 4.0, 4.0]) +def test_scalar_only_builtins_on_traced_scalars(device, backend): + f = _field(device, np.arange(3.0), [IDim]) + out = _field(device, np.zeros(3), [IDim]) + expected = _field(device, np.zeros(3), [IDim]) + + scalar_builtins.with_backend(backend)(f, 4.0, int32(2), out=out, offset_provider={}) + scalar_builtins(f, 4.0, int32(2), out=expected, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), [0.0, 9.0, 18.0]) + + +def test_scan_with_traced_scalar(device, backend): + x = _field(device, np.arange(1.0, 5.0), [KDim]) + out = _field(device, np.zeros(4), [KDim]) + expected = _field(device, np.zeros(4), [KDim]) + + scaled_cumsum.with_backend(backend)(x, 2.0, out=out, offset_provider={}) + scaled_cumsum(x, 2.0, out=expected, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), [2.0, 6.0, 12.0, 20.0]) + + def test_field_operator_tuple_out_leaves_inputs(device, backend): a = _field(device, np.arange(3.0), [IDim]) b = _field(device, np.arange(3.0) + 10, [IDim]) From b621f3c569c69e2fe69a5fa2e7db517db882a3ff Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 09:39:16 +0100 Subject: [PATCH 118/166] feat[next]: jax_jit takes static_params of field operators and dataclass named collections --- src/gt4py/next/ffront/decorator.py | 14 +++++- .../program_processors/runners/jax_jit.py | 46 +++++++++++++++---- .../ffront_tests/test_jax_jit_backend.py | 20 ++++++++ 3 files changed, 69 insertions(+), 11 deletions(-) diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 279cc4d8cb..8d9efa8f68 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -330,7 +330,10 @@ def gtir(self) -> itir.Program: def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: definition = self.definition_stage.definition return backend.jit( - definition, self.compilation_options.static_params or (), inspect.signature(definition) + definition, + self.compilation_options.static_params or (), + param_names=list(inspect.signature(definition).parameters), + param_types=self.__gt_type__().definition.pos_or_kw_args.values(), ) def with_grid_type(self, grid_type: common.GridType) -> Program: @@ -554,9 +557,16 @@ def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: op = self._embedded_operator() + operator_type = self.foast_stage.foast_node.type + assert isinstance(operator_type, ts_ffront.FieldOperatorType | ts_ffront.ScanOperatorType) + param_names = list(inspect.signature(self.definition_stage.definition).parameters) + if isinstance(op, embedded_operators.ScanOperator): + param_names = param_names[1:] # the carry return backend.jit( lambda *args, **kwargs: embedded_operators.field_operator_call(op, args, kwargs), - ("domain",), + ("domain", *(self.compilation_options.static_params or ())), + param_names=param_names, + param_types=operator_type.definition.pos_or_kw_args.values(), ) def with_grid_type(self, grid_type: common.GridType) -> FieldOperator: diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/jax_jit.py index ba670c89c0..432e4bf240 100644 --- a/src/gt4py/next/program_processors/runners/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/jax_jit.py @@ -18,12 +18,13 @@ from __future__ import annotations import dataclasses -import inspect -from collections.abc import Callable, Iterable +import pkgutil +from collections.abc import Callable, Iterable, Sequence from typing import Any from gt4py.next import backend as next_backend, common from gt4py.next.embedded import context as embedded_context, nd_array_field +from gt4py.next.type_system import type_specifications as ts @dataclasses.dataclass(frozen=True) @@ -34,9 +35,35 @@ def jit( self, function: Callable[..., None], static_argnames: Iterable[str] = (), - signature: inspect.Signature | None = None, + param_names: Sequence[str] = (), + param_types: Iterable[ts.TypeSpec] = (), ) -> JitRunner: - return JitRunner(function, frozenset(static_argnames), signature) + for type_ in param_types: + _register_named_collections(type_) + return JitRunner(function, frozenset(static_argnames), tuple(param_names)) + + +_registered_dataclasses: set[type] = set() + + +def _register_named_collections(type_: ts.TypeSpec) -> None: + """Register the dataclass named collections in `type_` as jax pytrees (tuples already are).""" + import jax + + if isinstance(type_, ts.NamedCollectionType): + cls = pkgutil.resolve_name(type_.original_python_type) + if ( + isinstance(cls, type) + and dataclasses.is_dataclass(cls) + and cls not in _registered_dataclasses + ): + jax.tree_util.register_dataclass( + cls, data_fields=[f.name for f in dataclasses.fields(cls)], meta_fields=[] + ) + _registered_dataclasses.add(cls) + if isinstance(type_, ts.TupleType | ts.NamedCollectionType): + for element_type in type_.types: + _register_named_collections(element_type) def _not_compiled(*args: Any, **kwargs: Any) -> Any: @@ -71,13 +98,14 @@ def __init__( self, function: Callable[..., None], static_argnames: frozenset[str], - signature: inspect.Signature | None, + param_names: tuple[str, ...], ) -> None: import jax self._function = function self._static_argnames = static_argnames - self._signature = signature + # static parameters passed positionally are only found by name + self._param_names = param_names if static_argnames & set(param_names) else () self._jitted = jax.jit(self._traced, static_argnames=("static_kwargs", "static_provider")) def _traced( @@ -106,9 +134,9 @@ def __call__( **kwargs: Any, ) -> None: if self._static_argnames: - if self._signature is not None: - bound = self._signature.bind(*args, **kwargs) - args, kwargs = (), dict(bound.arguments) + if self._param_names: + kwargs = {**dict(zip(self._param_names, args)), **kwargs} + args = () static_kwargs = tuple( sorted((name, kwargs.pop(name)) for name in self._static_argnames & kwargs.keys()) ) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py index 9e452edf69..3ac42742a8 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py @@ -82,6 +82,13 @@ def scaled_cumsum(state: gtx.float64, x: gtx.float64, a: gtx.float64) -> gtx.flo return state + a * x +@gtx.field_operator +def scale_if(f: gtx.Field[[IDim], gtx.float64], flag: bool) -> gtx.Field[[IDim], gtx.float64]: + if flag: + return 2.0 * f + return f + + @gtx.field_operator def swap( a: gtx.Field[[IDim], gtx.float64], b: gtx.Field[[IDim], gtx.float64] @@ -253,6 +260,19 @@ def test_scan_with_traced_scalar(device, backend): np.testing.assert_array_equal(out.asnumpy(), [2.0, 6.0, 12.0, 20.0]) +def test_static_param_of_field_operator(device, backend): + f = _field(device, np.arange(3.0), [IDim]) + fo = scale_if.with_backend(backend).with_compilation_options(static_params=("flag",)) + for flag in (True, False): + out = _field(device, np.zeros(3), [IDim]) + expected = _field(device, np.zeros(3), [IDim]) + fo(f, flag, out=out, offset_provider={}) + scale_if(f, flag, out=expected, offset_provider={}) + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + + assert _runner(fo)._cache_size() == 2 + + def test_field_operator_tuple_out_leaves_inputs(device, backend): a = _field(device, np.arange(3.0), [IDim]) b = _field(device, np.arange(3.0) + 10, [IDim]) From 291043a07e62047dc40d80f41bdd258895e5f51d Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 09:39:16 +0100 Subject: [PATCH 119/166] test[next]: jax_jit in the integration test matrix, scalar-dependent tests xfailed for it --- pyproject.toml | 2 + tests/next_tests/definitions.py | 9 +++++ tests/next_tests/integration_tests/cases.py | 7 ++++ .../integration_tests/cases_utils.py | 4 ++ .../ffront_tests/test_compiled_program.py | 38 +++++++++---------- .../ffront_tests/test_concat_where.py | 4 ++ .../ffront_tests/test_conditionals.py | 13 +++++++ .../ffront_tests/test_decorator.py | 2 +- .../feature_tests/ffront_tests/test_domain.py | 5 +++ .../ffront_tests/test_import_from_mod.py | 1 + .../test_math_builtin_execution.py | 2 +- .../ffront_tests/test_named_collections.py | 1 + .../ffront_tests/test_scalar_args.py | 1 + .../feature_tests/ffront_tests/test_scan.py | 1 + .../feature_tests/ffront_tests/test_where.py | 1 + .../test_multiple_output_domains.py | 10 +++++ 16 files changed, 80 insertions(+), 21 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index db8979665e..78f7905d44 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -286,6 +286,8 @@ markers = [ 'embedded_concat_where_non_contiguous_domain: tests with concat_where on non-contiguous domains', 'uses_program_metrics: tests that require backend support for program metrics', 'uses_program_with_sliced_out_arguments: tests that use a sliced argument which is not supported for non-mutable arrays, e.g. JAX', + 'uses_scalar_in_control_flow: tests that branch in Python on a scalar argument', + 'uses_scalar_in_domain: tests that use a scalar argument as a domain bound', 'checks_specific_error: tests that rely on the backend to produce a specific error message' ] norecursedirs = ['dist', 'build', '_local/*', '.*'] diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 819620f942..f501b5f30b 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -115,6 +115,7 @@ class OptionalProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): DACE_CPU = "gt4py.next.program_processors.runners.dace.run_dace_cpu" DACE_GPU = "gt4py.next.program_processors.runners.dace.run_dace_gpu" DACE_CPU_NO_OPT = "gt4py.next.program_processors.runners.dace.run_dace_cpu_noopt" + JAX_JIT = "gt4py.next.program_processors.runners.jax_jit.jax_jit" class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): @@ -174,6 +175,8 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): EMBEDDED_CONCAT_WHERE_INFINITE_DOMAIN = "embedded_concat_where_infinite_domain" EMBEDDED_CONCAT_WHERE_NON_CONTIGUOUS_DOMAIN = "embedded_concat_where_non_contiguous_domain" USES_PROGRAM_WITH_SLICED_OUT_ARGUMENTS = "uses_program_with_sliced_out_arguments" +USES_SCALAR_IN_CONTROL_FLOW = "uses_scalar_in_control_flow" +USES_SCALAR_IN_DOMAIN = "uses_scalar_in_domain" CHECKS_SPECIFIC_ERROR = "checks_specific_error" # Skip messages (available format keys: 'marker', 'backend') @@ -255,6 +258,11 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): JAX_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_PROGRAM_WITH_SLICED_OUT_ARGUMENTS, XFAIL, UNSUPPORTED_MESSAGE), ] +JAX_JIT_SKIP_LIST = JAX_EMBEDDED_SKIP_LIST + [ + # scalar arguments are traced unless they are in `static_params` + (USES_SCALAR_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), + (USES_SCALAR_IN_DOMAIN, XFAIL, UNSUPPORTED_MESSAGE), +] ARRAY_API_STRICT_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_MATH_OUTSIDE_ARRAY_API, XFAIL, "Not in the Array API standard."), ] @@ -304,6 +312,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): OptionalProgramBackendId.DACE_CPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_GPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_CPU_NO_OPT: DACE_SKIP_TEST_LIST, + OptionalProgramBackendId.JAX_JIT: JAX_JIT_SKIP_LIST, ProgramBackendId.GTFN_CPU: GTFN_SKIP_TEST_LIST + [(USES_SCAN_NESTED, XFAIL, UNSUPPORTED_MESSAGE)], ProgramBackendId.GTFN_GPU: GTFN_SKIP_TEST_LIST diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index b5d99e2eb5..2defe75110 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -396,6 +396,13 @@ def allocate( ) +def runs_embedded(case: Case) -> bool: + """Whether the case's programs run embedded, i.e. are not compiled.""" + from gt4py.next.program_processors.runners import jax_jit + + return case.backend is None or isinstance(case.backend, jax_jit.JaxJitBackend) + + def run( case: Case, fieldview_prog: decorator.FieldOperator | decorator.Program, diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index f9c1b5e98e..519cdc9275 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -114,6 +114,10 @@ def __gt_allocator__( pytest.mark.requires_gpu, ), ), + pytest.param( + next_tests.definitions.OptionalProgramBackendId.JAX_JIT, + marks=pytest.mark.requires_jax, + ), pytest.param( next_tests.definitions.OptionalProgramBackendId.DACE_CPU, marks=pytest.mark.uses_dace, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py index c59c57e08f..e669299d66 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py @@ -108,7 +108,7 @@ def testee(a: cases.KField, out: cases.KField): def test_compile(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile(offset_provider=cartesian_case.offset_provider) @@ -127,7 +127,7 @@ def test_compile(cartesian_case, compile_testee): def test_precompile_and_jit_have_same_arg_descr_mapping(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") empty_static_args = {} @@ -146,7 +146,7 @@ def test_precompile_and_jit_have_same_arg_descr_mapping(cartesian_case, compile_ def test_compile_twice_same_program_errors(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") with pytest.raises(ValueError): compile_testee.compile(offset_provider=cartesian_case.offset_provider).compile( @@ -155,7 +155,7 @@ def test_compile_twice_same_program_errors(cartesian_case, compile_testee): def test_compile_kwargs(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile(offset_provider=cartesian_case.offset_provider) @@ -171,7 +171,7 @@ def test_compile_kwargs(cartesian_case, compile_testee): @pytest.mark.uses_scan def test_compile_scan(cartesian_case, compile_testee_scan): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") if isinstance(compile_testee_scan, gtx.ffront.decorator.FieldOperator): @@ -191,7 +191,7 @@ def test_compile_scan(cartesian_case, compile_testee_scan): def test_compile_domain(cartesian_case, compile_testee_domain): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee_domain.compile(offset_provider=cartesian_case.offset_provider) @@ -212,7 +212,7 @@ def test_compile_domain(cartesian_case, compile_testee_domain): @pytest.fixture def compile_testee_unstructured(unstructured_case): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.field_operator @@ -238,7 +238,7 @@ def compile_testee_unstructured_no_jit(compile_testee_unstructured): @pytest.mark.uses_unstructured_shift def test_compile_unstructured(unstructured_case, compile_testee_unstructured): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee_unstructured.compile( @@ -274,7 +274,7 @@ def skip_value_mesh_descriptor(exec_alloc_descriptor): def test_compile_unstructured_wrong_offset_provider( unstructured_case, compile_testee_unstructured_no_jit, skip_value_mesh_descriptor ): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") # compiled for skip_value_mesh @@ -298,7 +298,7 @@ def test_compile_unstructured_wrong_offset_provider( def test_compile_unstructured_for_two_offset_providers( unstructured_case, compile_testee_unstructured_no_jit, skip_value_mesh_descriptor ): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") # compiled for skip_value_mesh and simple_mesh @@ -347,7 +347,7 @@ def compile_variants_field_operator( def compile_variants_testee_not_compiled( cartesian_case, compile_variants_field_operator ) -> Program: - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.program(backend=cartesian_case.backend) @@ -511,7 +511,7 @@ def test_compile_variants_config_default_disable_jit(cartesian_case): """ # One of the 2 cases will be the non-default. The program has to be defined after the config # has been altered in order for the value to take effect. - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") with mock.patch.object(config, "ENABLE_JIT_DEFAULT", True): @@ -760,7 +760,7 @@ def test_compile_variants_with_static_params_jit( def test_compile_variants_decorator_static_params_jit( compile_variants_field_operator, cartesian_case ): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.program( @@ -831,7 +831,7 @@ def test_compile_variants_error_static_field(cartesian_case, compile_variants_te @pytest.fixture def compile_variants_testee_tuple(cartesian_case): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") elif ( cartesian_case.backend.name.startswith("run_dace_gpu") @@ -915,7 +915,7 @@ def test_synchronous_compilation(cartesian_case, compile_testee): @pytest.mark.parametrize("mode", list(config.BuildJobsMode), ids=lambda m: m.name.lower()) def test_wait_for_compilation(cartesian_case, compile_testee, compile_testee_domain, mode): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") with ( @@ -942,7 +942,7 @@ def test_compile_local_program_offloads_to_worker_process(cartesian_case, compil the raw definition function, which is unpicklable for local definitions. A fallback to in-thread compilation would mean the boundary leaked. """ - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") runner = compiled_program.runners.ProcessRunner( @@ -971,7 +971,7 @@ def test_compile_local_program_offloads_to_worker_process(cartesian_case, compil def test_wait_for_compilation_raises_on_failed_compilation(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") # Failing only once the gate opens keeps the future pending until after @@ -1006,7 +1006,7 @@ def compile(self, program, compile_time_args): @pytest.mark.uses_tuple_args @pytest.mark.uses_tuple_returns def test_compile_variants_decorator_static_domains(cartesian_case): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") captured_cargs: Optional[arguments.CompileTimeArgs] = None @@ -1057,7 +1057,7 @@ def testee(inp: tuple[cases.IField, cases.IField, float], out: NamedTupleNamedCo @pytest.fixture def scan_operator_testee(cartesian_case): """A scan operator called directly as a FieldOperator — the only case where _is_generic=True.""" - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.scan_operator(axis=KDim, forward=True, init=0, backend=cartesian_case.backend) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py index 0ed7ed60f0..3c7273123d 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py @@ -81,6 +81,7 @@ def testee(ground: cases.IJKField, air: cases.IJKField) -> cases.IJKField: cases.verify(cartesian_case, testee, ground, air, out=out, ref=ref) +@pytest.mark.uses_scalar_in_domain def test_concat_where_empty_branch(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee(a: cases.IJKField, b: cases.IJKField, N: np.int32) -> cases.IJKField: @@ -239,6 +240,7 @@ def testee(interior: cases.IJKField, boundary: cases.IJKField) -> cases.IJKField ) +@pytest.mark.uses_scalar_in_domain def test_dimension_two_conditions_and(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee(interior: cases.KField, boundary: cases.KField, nlev: np.int32) -> cases.KField: @@ -347,6 +349,7 @@ def testee(interior: cases.KField, boundary: cases.KField) -> cases.KField: ) +@pytest.mark.uses_scalar_in_domain def test_lap_like(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee( @@ -612,6 +615,7 @@ def testee( ) +@pytest.mark.uses_scalar_in_domain def test_nested_conditions_with_empty_branches(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee(interior: cases.IField, boundary: cases.IField, N: gtx.int32) -> cases.IField: diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py index 131dd8dd32..d23cea4d0c 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py @@ -24,6 +24,7 @@ ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_simple_if(condition, cartesian_case): @@ -43,6 +44,7 @@ def simple_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IField # TODO(tehrengruber): test with fields on different domains +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition1, condition2", [[True, False], [True, False]]) @pytest.mark.uses_if_stmts def test_simple_if_conditional(condition1, condition2, cartesian_case): @@ -74,6 +76,7 @@ def simple_if( ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_local_if(cartesian_case, condition): @@ -93,6 +96,7 @@ def local_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IField: cases.verify(cartesian_case, local_if, a, b, condition, out=out, ref=(a if condition else b)) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_temporary_if(cartesian_case, condition): @@ -115,6 +119,7 @@ def temporary_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IFi ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_return(cartesian_case, condition): @@ -137,6 +142,7 @@ def temporary_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IFi ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_stmt_if_branch_returns(cartesian_case, condition): @@ -156,6 +162,7 @@ def if_branch_returns(a: cases.IField, b: cases.IField, condition: bool) -> case ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_stmt_else_branch_returns(cartesian_case, condition): @@ -177,6 +184,7 @@ def else_branch_returns(a: cases.IField, b: cases.IField, condition: bool) -> ca ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_stmt_both_branches_return(cartesian_case, condition): @@ -198,6 +206,7 @@ def both_branches_return(a: cases.IField, b: cases.IField, condition: bool) -> c ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition1, condition2", [[True, False], [True, False]]) @pytest.mark.uses_if_stmts def test_nested_if_stmt_conditional(cartesian_case, condition1, condition2): @@ -235,6 +244,7 @@ def nested_if_conditional_return( ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_nested_if(cartesian_case, condition): @@ -270,6 +280,7 @@ def nested_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IField ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition1, condition2", [[True, False], [True, False]]) @pytest.mark.uses_if_stmts def test_if_without_else(cartesian_case, condition1, condition2): @@ -353,6 +364,7 @@ def if_inconsistent_types( return result +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("left, right", [(2, 3), (3, 2)]) def test_ternary_operator(cartesian_case, left, right): @gtx.field_operator @@ -380,6 +392,7 @@ def testee(left: int32, right: int32) -> cases.IField: ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("left, right", [(2, 3), (3, 2)]) @pytest.mark.uses_tuple_returns def test_ternary_operator_tuple(cartesian_case, left, right): diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py index 89f3842816..7974161504 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py @@ -46,7 +46,7 @@ def testee(a: cases.IField, out: cases.IField): ) @pytest.mark.uses_program_metrics def test_collect_metrics(cartesian_case, metrics_level, expected_names): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Precompiled program with embedded execution is not possible.") @gtx.field_operator diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py index c49f2898aa..3021bdc04f 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py @@ -22,6 +22,7 @@ ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_scalar_in_domain_and_fo def test_scalar_in_domain_spec_and_fo_call(cartesian_case): @gtx.field_operator @@ -56,6 +57,7 @@ def testee_prog(a: cases.IKField): cases.verify(cartesian_case, testee_prog, a, inout=a[1, 3], ref=ref) +@pytest.mark.uses_scalar_in_domain def test_domain(cartesian_case): @gtx.field_operator def fieldop_domain(a: cases.IField) -> cases.IField: @@ -74,6 +76,7 @@ def program_domain(a: cases.IField, size: int32, out: cases.IField): cases.verify(cartesian_case, program_domain, a, size, out, inout=out, ref=ref) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_floordiv def test_domain_input_bounds(cartesian_case): lower_i = 1 @@ -98,6 +101,7 @@ def program_domain( cases.verify(cartesian_case, program_domain, inp, out, lower_i, upper_i, inout=out, ref=ref) +@pytest.mark.uses_scalar_in_domain def test_domain_input_bounds_1(cartesian_case): lower_i = 1 upper_i = cartesian_case.default_sizes[IDim] @@ -143,6 +147,7 @@ def program_domain( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_domain_tuple(cartesian_case): @gtx.field_operator diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py index b41f3a9c89..6c2f0e598f 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py @@ -22,6 +22,7 @@ ) +@pytest.mark.uses_scalar_in_domain def test_import_dims_module(cartesian_case): @gtx.field_operator def mod_op(f: cases.IField) -> cases.IKField: diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py index 9bd7e43273..0f89072e8f 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py @@ -120,7 +120,7 @@ def make_builtin_field_operator(builtin_name: str, backend: Optional[next_backen @pytest.mark.parametrize("builtin_name, inputs", math_builtin_test_data()) def test_math_function_builtins_execution(cartesian_case, builtin_name: str, inputs): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): # TODO(havogt) find a way that works for embedded pytest.xfail("Test does not have a field view program.") if builtin_name == "gamma": diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index 911ace0804..77b793f93b 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -204,6 +204,7 @@ def constructed_inside_dataclass_program_with_domain( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.parametrize( "testee", [ diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py index 3e03f11a36..6d8185d764 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py @@ -39,6 +39,7 @@ def testee(a: int32) -> cases.VField: ) +@pytest.mark.uses_scalar_in_control_flow def test_np_bool_scalar_arg(unstructured_case): """Test scalar argument being turned into 0-dim field.""" diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py index ae9e9b37ef..e1352ffe2a 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py @@ -190,6 +190,7 @@ def expected(a, b, c, d): cases.verify_with_default_data(cartesian_case, solve_tridiag, ref=expected) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.uses_scan def test_ternary_scan(cartesian_case): @gtx.scan_operator(axis=KDim, forward=True, init=0.0) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py index 03c714421e..6cc265c433 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py @@ -20,6 +20,7 @@ ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_cartesian_shift def test_where_k_offset(cartesian_case): @gtx.field_operator diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py index 7c12896fac..5437c45484 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py @@ -56,6 +56,7 @@ def prog_no_tuple( testee_no_tuple(a, b, out=out_a, domain={IDim: (0, i_size)}) +@pytest.mark.uses_scalar_in_domain def test_program_no_tuple(cartesian_case): a = cases.allocate(cartesian_case, prog_no_tuple, "a")() b = cases.allocate(cartesian_case, prog_no_tuple, "b")() @@ -89,6 +90,7 @@ def prog_orig( fop_original(a, b, out=(out_b, out_a), domain={IDim: (0, i_size)}) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_orig(cartesian_case): a = cases.allocate(cartesian_case, prog_orig, "a")() @@ -188,6 +190,7 @@ def prog( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program(cartesian_case): a = cases.allocate(cartesian_case, prog, "a")() @@ -258,6 +261,7 @@ def prog_out_as_tuple( fop_different_fields(a, b, out=out, domain=({JDim: (0, j_size)}, {IDim: (0, i_size)})) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_out_as_tuple( cartesian_case, @@ -302,6 +306,7 @@ def prog_out_as_tuple_different_sizes( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_out_as_tuple_different_sizes( cartesian_case, @@ -372,6 +377,7 @@ def prog_nested_tuples( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_nested_tuples( cartesian_case, @@ -440,6 +446,7 @@ def prog_double_nested_tuples( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_double_nested_tuples( cartesian_case, @@ -491,6 +498,7 @@ def prog_two_vertical_dims( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_two_vertical_dims(cartesian_case): a = cases.allocate(cartesian_case, prog_two_vertical_dims, "a")() @@ -528,6 +536,7 @@ def prog_unstructured( fop_shift_e2c(a, out=(out_a_shifted, out_a), domain=({Cell: (0, c_size)}, {Edge: (0, e_size)})) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns @pytest.mark.uses_unstructured_shift def test_program_unstructured(unstructured_case): @@ -577,6 +586,7 @@ def prog_temporary( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns @pytest.mark.uses_unstructured_shift def test_program_temporary(unstructured_case): From 8eeebce5f0fee22c59737dd0bce04b82a80384fa Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 14:29:10 +0100 Subject: [PATCH 120/166] refactor[next]: EmbeddedJitBackend, the dispatch seam shared by the embedded jit backends --- src/gt4py/next/ffront/decorator.py | 28 +++-- .../runners/embedded_jit.py | 118 ++++++++++++++++++ .../program_processors/runners/jax_jit.py | 86 ++++--------- 3 files changed, 160 insertions(+), 72 deletions(-) create mode 100644 src/gt4py/next/program_processors/runners/embedded_jit.py diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 8d9efa8f68..5fa5bfe8c7 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -48,7 +48,7 @@ from gt4py.next.instrumentation import hook_machinery, metrics from gt4py.next.iterator import ir as itir from gt4py.next.otf import arguments, compiled_program, options, workflow -from gt4py.next.program_processors.runners import jax_jit +from gt4py.next.program_processors.runners import embedded_jit from gt4py.next.type_system import type_info, type_specifications as ts, type_translation @@ -107,7 +107,9 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): def __gt_type__(self) -> ts.CallableType: ... @abc.abstractmethod - def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: ... + def _embedded_jit_runner( + self, backend: embedded_jit.EmbeddedJitBackend + ) -> embedded_jit.EmbeddedJitRunner: ... def with_backend(self, backend: next_backend.Backend | None) -> Self: return dataclasses.replace(self, backend=backend) @@ -123,9 +125,11 @@ def with_compilation_options( ) @functools.cached_property - def _compiled_programs(self) -> compiled_program.CompiledProgramsPool | jax_jit.JitRunner: - if isinstance(self.backend, jax_jit.JaxJitBackend): - return self._jax_jit_runner(self.backend) + def _compiled_programs( + self, + ) -> compiled_program.CompiledProgramsPool | embedded_jit.EmbeddedJitRunner: + if isinstance(self.backend, embedded_jit.EmbeddedJitBackend): + return self._embedded_jit_runner(self.backend) # This cached property initializer is only called when JITting the first # program variant of the pool. If the program is compiled by directly # calling `compile()`, the pool is initialized with the options passed @@ -140,9 +144,9 @@ def _make_compiled_programs_pool( ) -> compiled_program.CompiledProgramsPool: if self.backend is None or self.backend == eve.NOTHING: raise RuntimeError("Cannot compile a program without backend.") - if isinstance(self.backend, jax_jit.JaxJitBackend): + if isinstance(self.backend, embedded_jit.EmbeddedJitBackend): raise RuntimeError( - f"Backend '{self.backend.name}' runs embedded under 'jax.jit'; it does not compile." + f"Backend '{self.backend.name}' runs the program embedded; it does not compile." ) program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) @@ -327,7 +331,9 @@ def gtir(self) -> itir.Program: ) return self._frontend_transforms.past_to_itir(no_args_past).data - def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: + def _embedded_jit_runner( + self, backend: embedded_jit.EmbeddedJitBackend + ) -> embedded_jit.EmbeddedJitRunner: definition = self.definition_stage.definition return backend.jit( definition, @@ -555,7 +561,9 @@ def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: ) return embedded_operators.EmbeddedOperator(self.definition_stage.definition) - def _jax_jit_runner(self, backend: jax_jit.JaxJitBackend) -> jax_jit.JitRunner: + def _embedded_jit_runner( + self, backend: embedded_jit.EmbeddedJitBackend + ) -> embedded_jit.EmbeddedJitRunner: op = self._embedded_operator() operator_type = self.foast_stage.foast_node.type assert isinstance(operator_type, ts_ffront.FieldOperatorType | ts_ffront.ScanOperatorType) @@ -596,7 +604,7 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> out = kwargs.pop("out") if "domain" in kwargs: domain = utils.tree_map(common.domain)(kwargs.pop("domain")) - if isinstance(self.backend, jax_jit.JaxJitBackend): + if isinstance(self.backend, embedded_jit.EmbeddedJitBackend): # the operator assigns to `out` inside the trace, not to a restricted copy kwargs["domain"] = domain else: diff --git a/src/gt4py/next/program_processors/runners/embedded_jit.py b/src/gt4py/next/program_processors/runners/embedded_jit.py new file mode 100644 index 0000000000..2770e6c2d8 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/embedded_jit.py @@ -0,0 +1,118 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +Embedded execution of programs and field operators inside the tracing compiler of an array library. + +The backends (`jax_jit.jax_jit`, `torch_compile.torch_compile`) run the Python +definition on fields of their library, inside `jax.jit` or `torch.compile`. +Fields, connectivities and the other arguments go to the compiled function; the +offset provider entries that are no connectivities (`Dimension`s of Cartesian +offsets) and the parameters named in `static_params` are static. +""" + +from __future__ import annotations + +import abc +import dataclasses +import pkgutil +from collections.abc import Callable, Iterable, Sequence +from typing import Any + +from gt4py.next import backend as next_backend, common +from gt4py.next.type_system import type_specifications as ts + + +StaticItems = tuple[tuple[str, Any], ...] + + +@dataclasses.dataclass(frozen=True) +class EmbeddedJitBackend(next_backend.Backend, abc.ABC): + """Runs programs and field operators embedded, inside the tracing compiler of an array library.""" + + @abc.abstractmethod + def jit( + self, + function: Callable[..., None], + static_argnames: Iterable[str] = (), + param_names: Sequence[str] = (), + param_types: Iterable[ts.TypeSpec] = (), + ) -> EmbeddedJitRunner: ... + + +def not_compiled(*args: Any, **kwargs: Any) -> Any: + raise RuntimeError("An embedded jit backend runs the program embedded; it does not compile.") + + +def named_collection_dataclasses(type_: ts.TypeSpec) -> Iterable[type]: + """The dataclasses of the named collections in `type_`, which are no pytrees by themselves.""" + if isinstance(type_, ts.NamedCollectionType): + cls = pkgutil.resolve_name(type_.original_python_type) + if isinstance(cls, type) and dataclasses.is_dataclass(cls): + yield cls + if isinstance(type_, ts.TupleType | ts.NamedCollectionType): + for element_type in type_.types: + yield from named_collection_dataclasses(element_type) + + +class EmbeddedJitRunner(abc.ABC): + """ + One compiled embedded entry point, called like a compiled programs pool. + + Splits the arguments into the ones the compiled function takes and the static + ones: the parameters in `static_argnames` and the offset provider entries + that are no connectivities, both as sorted `(name, value)` items. + """ + + def __init__( + self, + function: Callable[..., None], + static_argnames: frozenset[str], + param_names: tuple[str, ...], + ) -> None: + self._function = function + self._static_argnames = static_argnames + # static parameters passed positionally are only found by name + self._param_names = param_names if static_argnames & set(param_names) else () + + @abc.abstractmethod + def _run( + self, + args: tuple[Any, ...], + kwargs: dict[str, Any], + connectivities: dict[str, Any], + static_kwargs: StaticItems, + static_provider: StaticItems, + ) -> None: ... + + def __call__( + self, + *args: Any, + offset_provider: common.OffsetProvider, + enable_jit: bool | None = None, + **kwargs: Any, + ) -> None: + if self._static_argnames: + if self._param_names: + kwargs = {**dict(zip(self._param_names, args)), **kwargs} + args = () + static_kwargs = tuple( + sorted((name, kwargs.pop(name)) for name in self._static_argnames & kwargs.keys()) + ) + else: + static_kwargs = () + + connectivities: dict[str, Any] = {} + static_provider: list[tuple[str, Any]] = [] + for name, entry in offset_provider.items(): + if isinstance(entry, common.Connectivity): + connectivities[name] = entry + else: + static_provider.append((name, entry)) + + self._run(args, kwargs, connectivities, static_kwargs, tuple(sorted(static_provider))) diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/jax_jit.py index 432e4bf240..4bd064f740 100644 --- a/src/gt4py/next/program_processors/runners/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/jax_jit.py @@ -11,24 +11,23 @@ `jax_jit` (created on first access, it requires `jax`) runs the Python definition on fields of JAX arrays inside `jax.jit`. Fields, connectivities and scalars are -arguments of the jitted function; other offset provider entries (`Dimension`s of -Cartesian offsets) and the parameters named in `static_params` are static. +arguments of the jitted function (see `embedded_jit` for the static ones). """ from __future__ import annotations import dataclasses -import pkgutil from collections.abc import Callable, Iterable, Sequence from typing import Any from gt4py.next import backend as next_backend, common from gt4py.next.embedded import context as embedded_context, nd_array_field +from gt4py.next.program_processors.runners import embedded_jit from gt4py.next.type_system import type_specifications as ts @dataclasses.dataclass(frozen=True) -class JaxJitBackend(next_backend.Backend): +class JaxJitBackend(embedded_jit.EmbeddedJitBackend): """Runs programs and field operators embedded, under `jax.jit`.""" def jit( @@ -38,38 +37,21 @@ def jit( param_names: Sequence[str] = (), param_types: Iterable[ts.TypeSpec] = (), ) -> JitRunner: + import jax + for type_ in param_types: - _register_named_collections(type_) + for cls in embedded_jit.named_collection_dataclasses(type_): + if cls not in _registered_dataclasses: + jax.tree_util.register_dataclass( + cls, data_fields=[f.name for f in dataclasses.fields(cls)], meta_fields=[] + ) + _registered_dataclasses.add(cls) return JitRunner(function, frozenset(static_argnames), tuple(param_names)) _registered_dataclasses: set[type] = set() -def _register_named_collections(type_: ts.TypeSpec) -> None: - """Register the dataclass named collections in `type_` as jax pytrees (tuples already are).""" - import jax - - if isinstance(type_, ts.NamedCollectionType): - cls = pkgutil.resolve_name(type_.original_python_type) - if ( - isinstance(cls, type) - and dataclasses.is_dataclass(cls) - and cls not in _registered_dataclasses - ): - jax.tree_util.register_dataclass( - cls, data_fields=[f.name for f in dataclasses.fields(cls)], meta_fields=[] - ) - _registered_dataclasses.add(cls) - if isinstance(type_, ts.TupleType | ts.NamedCollectionType): - for element_type in type_.types: - _register_named_collections(element_type) - - -def _not_compiled(*args: Any, **kwargs: Any) -> Any: - raise RuntimeError("The 'jax_jit' backend runs embedded under 'jax.jit'; it does not compile.") - - def _is_field(x: Any) -> bool: return isinstance(x, common.Field) @@ -85,9 +67,9 @@ def _written_fields(tree: Any) -> list[nd_array_field.NdArrayField]: ] -class JitRunner: +class JitRunner(embedded_jit.EmbeddedJitRunner): """ - One `jax.jit` of an embedded entry point, called like a compiled programs pool. + One `jax.jit` of an embedded entry point. The jitted function returns, for each field of the arguments, its new buffer if the entry point assigned to it and `None` otherwise; the new buffers are @@ -102,10 +84,7 @@ def __init__( ) -> None: import jax - self._function = function - self._static_argnames = static_argnames - # static parameters passed positionally are only found by name - self._param_names = param_names if static_argnames & set(param_names) else () + super().__init__(function, static_argnames, param_names) self._jitted = jax.jit(self._traced, static_argnames=("static_kwargs", "static_provider")) def _traced( @@ -114,8 +93,8 @@ def _traced( kwargs: dict[str, Any], connectivities: dict[str, Any], *, - static_kwargs: tuple[tuple[str, Any], ...], - static_provider: tuple[tuple[str, Any], ...], + static_kwargs: embedded_jit.StaticItems, + static_provider: embedded_jit.StaticItems, ) -> list[Any]: fields = _written_fields((args, kwargs)) buffers = [field.ndarray for field in fields] @@ -126,37 +105,20 @@ def _traced( for field, buffer in zip(fields, buffers, strict=True) ] - def __call__( + def _run( self, - *args: Any, - offset_provider: common.OffsetProvider, - enable_jit: bool | None = None, - **kwargs: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + connectivities: dict[str, Any], + static_kwargs: embedded_jit.StaticItems, + static_provider: embedded_jit.StaticItems, ) -> None: - if self._static_argnames: - if self._param_names: - kwargs = {**dict(zip(self._param_names, args)), **kwargs} - args = () - static_kwargs = tuple( - sorted((name, kwargs.pop(name)) for name in self._static_argnames & kwargs.keys()) - ) - else: - static_kwargs = () - - connectivities: dict[str, Any] = {} - static_provider: list[tuple[str, Any]] = [] - for name, entry in offset_provider.items(): - if isinstance(entry, common.Connectivity): - connectivities[name] = entry - else: - static_provider.append((name, entry)) - new_buffers = self._jitted( args, kwargs, connectivities, static_kwargs=static_kwargs, - static_provider=tuple(sorted(static_provider)), + static_provider=static_provider, ) for field, buffer in zip(_written_fields((args, kwargs)), new_buffers, strict=True): if buffer is not None: @@ -174,7 +136,7 @@ def __getattr__(name: str) -> JaxJitBackend: backend = JaxJitBackend( name="jax_jit", - executor=_not_compiled, + executor=embedded_jit.not_compiled, allocator=jnp, transforms=next_backend.DEFAULT_TRANSFORMS, ) From 2a3e23539e331c4f8b6d749822590972a88bf808 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 14:29:10 +0100 Subject: [PATCH 121/166] feat[next]: torch_compile backend running embedded programs and field operators under torch.compile --- .../embedded/array_libraries/torch_ops.py | 4 + .../runners/torch_compile.py | 167 ++++++++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 src/gt4py/next/program_processors/runners/torch_compile.py diff --git a/src/gt4py/next/embedded/array_libraries/torch_ops.py b/src/gt4py/next/embedded/array_libraries/torch_ops.py index 6892aa6a22..f566c92c97 100644 --- a/src/gt4py/next/embedded/array_libraries/torch_ops.py +++ b/src/gt4py/next/embedded/array_libraries/torch_ops.py @@ -121,6 +121,10 @@ def _elementwise_function(self, name: str) -> Callable[..., Any]: return _gamma return super()._elementwise_function(name) + def scalar(self, array: core_defs.NDArrayObject) -> Any: + # an element in a trace stays a 0-d tensor: its value is only known at run time + return super().scalar(array) if _is_concrete(array) else array + def to_numpy(self, array: core_defs.NDArrayObject) -> np.ndarray: return array.detach().cpu().numpy() # type: ignore[attr-defined] # `NDArrayObject` typing is not complete diff --git a/src/gt4py/next/program_processors/runners/torch_compile.py b/src/gt4py/next/program_processors/runners/torch_compile.py new file mode 100644 index 0000000000..fad7f44da6 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/torch_compile.py @@ -0,0 +1,167 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +Embedded execution of programs and field operators under `torch.compile`. + +`torch_compile` (created on first access, it requires `torch`) runs the Python +definition on fields of torch tensors in a `torch.compile` region, through a +`torch.compiler.nonstrict_trace` function, as `torch_ops` describes. Fields and +connectivities are arguments of the region; Dynamo specializes on the other +arguments (see `embedded_jit` for the static ones). +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Callable, Iterable, Sequence +from typing import Any + +from gt4py.next import backend as next_backend +from gt4py.next.embedded import context as embedded_context +from gt4py.next.program_processors.runners import embedded_jit +from gt4py.next.type_system import type_specifications as ts + + +@dataclasses.dataclass(frozen=True) +class TorchCompileBackend(embedded_jit.EmbeddedJitBackend): + """Runs programs and field operators embedded, under `torch.compile`.""" + + def jit( + self, + function: Callable[..., None], + static_argnames: Iterable[str] = (), + param_names: Sequence[str] = (), + param_types: Iterable[ts.TypeSpec] = (), + ) -> CompileRunner: + import torch.utils._pytree as torch_pytree + + for type_ in param_types: + for cls in embedded_jit.named_collection_dataclasses(type_): + if cls not in _registered_dataclasses: + torch_pytree.register_dataclass(cls) + _registered_dataclasses.add(cls) + return CompileRunner(function, frozenset(static_argnames), tuple(param_names)) + + +_registered_dataclasses: set[type] = set() + + +class CompileRunner(embedded_jit.EmbeddedJitRunner): + """ + One `torch.compile` region per combination of static arguments. + + The static arguments are closed over by the non-strictly traced function, + since `nonstrict_trace` only takes tensors, pytrees and constants. The entry + point assigns to its `out` fields in place, which the region applies to the + caller's tensors. + """ + + def __init__( + self, + function: Callable[..., None], + static_argnames: frozenset[str], + param_names: tuple[str, ...], + ) -> None: + super().__init__(function, static_argnames, param_names) + self._embedded_error: BaseException | None = None + self._regions: dict[ + tuple[embedded_jit.StaticItems, embedded_jit.StaticItems], Callable[..., Any] + ] = {} + + def _region( + self, static_kwargs: embedded_jit.StaticItems, static_provider: embedded_jit.StaticItems + ) -> Callable[..., Any]: + import torch + + function = self._function + + @torch.compiler.nonstrict_trace + def run_embedded( + args: tuple[Any, ...], kwargs: dict[str, Any], connectivities: dict[str, Any] + ) -> tuple[()]: + with embedded_context.update( + offset_provider={**connectivities, **dict(static_provider)} + ): + try: + function(*args, **kwargs, **dict(static_kwargs)) + except Exception as error: + # Dynamo reports it as an unsupported output type + self._embedded_error = error + raise + # `nonstrict_trace` does not support a `None` output + return () + + def region( + args: tuple[Any, ...], kwargs: dict[str, Any], connectivities: dict[str, Any] + ) -> tuple[()]: + return run_embedded(args, kwargs, connectivities) + + # Dynamo caches per code object, with a recompile limit: every region needs its own + region.__code__ = region.__code__.replace() + # with dynamic shapes, Dynamo makes domain bounds symbolic, which cannot be in a pytree context + return torch.compile(region, fullgraph=True, dynamic=False) + + def _run( + self, + args: tuple[Any, ...], + kwargs: dict[str, Any], + connectivities: dict[str, Any], + static_kwargs: embedded_jit.StaticItems, + static_provider: embedded_jit.StaticItems, + ) -> None: + import torch + import torch.utils._pytree as torch_pytree + + key = (static_kwargs, static_provider) + if (region := self._regions.get(key)) is None: + region = self._regions[key] = self._region(static_kwargs, static_provider) + args, kwargs = torch_pytree.tree_map(_as_region_argument, (args, kwargs)) + try: + region(args, kwargs, connectivities) + except torch._dynamo.exc.Unsupported as unsupported: + if (error := self._embedded_error) is None: + raise + self._embedded_error = None + raise error from unsupported + + +def _as_region_argument(value: Any) -> Any: + import numpy as np + import torch + + # `nonstrict_trace` takes no NumPy scalars. Dynamo specializes on Python integers and + # booleans, as for domain bounds and conditions; a floating-point scalar becomes a 0-d + # tensor, which keeps its dtype. + if isinstance(value, np.bool_ | np.integer): + return value.item() + if isinstance(value, np.generic): + return torch.as_tensor(value) + return value + + +def __getattr__(name: str) -> TorchCompileBackend: + if name != "torch_compile": + raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") + import torch + + from gt4py.next.embedded.array_libraries import ( + torch_ops, # noqa: F401 [unused-import] # registers the pytrees + ) + + backend = TorchCompileBackend( + name="torch_compile", + executor=embedded_jit.not_compiled, + allocator=torch, + transforms=next_backend.DEFAULT_TRANSFORMS, + ) + globals()[name] = backend + return backend + + +torch_compile: TorchCompileBackend From 2a3a8ba3c3e26b45b4513ddd17eaadc79ff2ca43 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 14:29:10 +0100 Subject: [PATCH 122/166] test[next]: torch_compile in the integration test matrix, the backend tests for both embedded jit backends --- pyproject.toml | 1 + tests/next_tests/definitions.py | 22 ++++- tests/next_tests/integration_tests/cases.py | 4 +- .../integration_tests/cases_utils.py | 12 +++ ...ckend.py => test_embedded_jit_backends.py} | 86 +++++++++++++------ .../ffront_tests/test_reductions.py | 4 +- .../feature_tests/ffront_tests/test_scan.py | 2 +- 7 files changed, 99 insertions(+), 32 deletions(-) rename tests/next_tests/integration_tests/feature_tests/ffront_tests/{test_jax_jit_backend.py => test_embedded_jit_backends.py} (82%) diff --git a/pyproject.toml b/pyproject.toml index 9b48076442..c9a2029eb7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -288,6 +288,7 @@ markers = [ 'uses_program_with_sliced_out_arguments: tests that use a sliced argument which is not supported for non-mutable arrays, e.g. JAX', 'uses_scalar_in_control_flow: tests that branch in Python on a scalar argument', 'uses_scalar_in_domain: tests that use a scalar argument as a domain bound', + 'uses_scan_carry_in_control_flow: tests that branch in Python on the carry of a scan', 'checks_specific_error: tests that rely on the backend to produce a specific error message' ] norecursedirs = ['dist', 'build', '_local/*', '.*'] diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index f501b5f30b..b72ddd09d8 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -13,7 +13,7 @@ import importlib import types from types import ModuleType -from typing import Final, Optional +from typing import Any, Final, Optional import array_api_strict import numpy as np @@ -102,6 +102,17 @@ def __gt_allocate__( torch_cuda_execution = EmbeddedDummyBackend("EmbeddedTorchCUDA", _TorchCUDAAllocator()) +def __getattr__(name: str) -> Any: + if name != "torch_compile_cuda": + raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") + from gt4py.next.program_processors.runners import torch_compile + + backend = globals()[name] = dataclasses.replace( + torch_compile.torch_compile, name="torch_compile_cuda", allocator=_TorchCUDAAllocator() + ) + return backend + + class EmbeddedIds(_PythonObjectIdMixin, str, enum.Enum): NUMPY_EXECUTION = "next_tests.definitions.numpy_execution" CUPY_EXECUTION = "next_tests.definitions.cupy_execution" @@ -116,6 +127,8 @@ class OptionalProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): DACE_GPU = "gt4py.next.program_processors.runners.dace.run_dace_gpu" DACE_CPU_NO_OPT = "gt4py.next.program_processors.runners.dace.run_dace_cpu_noopt" JAX_JIT = "gt4py.next.program_processors.runners.jax_jit.jax_jit" + TORCH_COMPILE = "gt4py.next.program_processors.runners.torch_compile.torch_compile" + TORCH_COMPILE_CUDA = "next_tests.definitions.torch_compile_cuda" class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): @@ -177,6 +190,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): USES_PROGRAM_WITH_SLICED_OUT_ARGUMENTS = "uses_program_with_sliced_out_arguments" USES_SCALAR_IN_CONTROL_FLOW = "uses_scalar_in_control_flow" USES_SCALAR_IN_DOMAIN = "uses_scalar_in_domain" +USES_SCAN_CARRY_IN_CONTROL_FLOW = "uses_scan_carry_in_control_flow" CHECKS_SPECIFIC_ERROR = "checks_specific_error" # Skip messages (available format keys: 'marker', 'backend') @@ -262,6 +276,10 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): # scalar arguments are traced unless they are in `static_params` (USES_SCALAR_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), (USES_SCALAR_IN_DOMAIN, XFAIL, UNSUPPORTED_MESSAGE), + (USES_SCAN_CARRY_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), +] +TORCH_COMPILE_SKIP_LIST = EMBEDDED_SKIP_LIST + [ + (USES_SCAN_CARRY_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), ] ARRAY_API_STRICT_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_MATH_OUTSIDE_ARRAY_API, XFAIL, "Not in the Array API standard."), @@ -313,6 +331,8 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): OptionalProgramBackendId.DACE_GPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_CPU_NO_OPT: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.JAX_JIT: JAX_JIT_SKIP_LIST, + OptionalProgramBackendId.TORCH_COMPILE: TORCH_COMPILE_SKIP_LIST, + OptionalProgramBackendId.TORCH_COMPILE_CUDA: TORCH_COMPILE_SKIP_LIST, ProgramBackendId.GTFN_CPU: GTFN_SKIP_TEST_LIST + [(USES_SCAN_NESTED, XFAIL, UNSUPPORTED_MESSAGE)], ProgramBackendId.GTFN_GPU: GTFN_SKIP_TEST_LIST diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index 2defe75110..0171faeec9 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -398,9 +398,9 @@ def allocate( def runs_embedded(case: Case) -> bool: """Whether the case's programs run embedded, i.e. are not compiled.""" - from gt4py.next.program_processors.runners import jax_jit + from gt4py.next.program_processors.runners import embedded_jit - return case.backend is None or isinstance(case.backend, jax_jit.JaxJitBackend) + return case.backend is None or isinstance(case.backend, embedded_jit.EmbeddedJitBackend) def run( diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index 519cdc9275..afdbc99619 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -118,6 +118,18 @@ def __gt_allocator__( next_tests.definitions.OptionalProgramBackendId.JAX_JIT, marks=pytest.mark.requires_jax, ), + pytest.param( + next_tests.definitions.OptionalProgramBackendId.TORCH_COMPILE, + marks=pytest.mark.requires_torch, + ), + pytest.param( + next_tests.definitions.OptionalProgramBackendId.TORCH_COMPILE_CUDA, + marks=( + pytest.mark.requires_torch, + pytest.mark.requires_torch_cuda, + pytest.mark.requires_gpu, + ), + ), pytest.param( next_tests.definitions.OptionalProgramBackendId.DACE_CPU, marks=pytest.mark.uses_dace, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py similarity index 82% rename from tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py rename to tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py index 3ac42742a8..031237e6d4 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_jax_jit_backend.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py @@ -16,8 +16,6 @@ from gt4py.next.ffront.experimental import as_offset -pytestmark = pytest.mark.requires_jax - IDim = gtx.Dimension("IDim") KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) Vertex = gtx.Dimension("Vertex") @@ -97,39 +95,70 @@ def swap( @pytest.fixture( - params=["cpu", pytest.param("gpu", marks=pytest.mark.requires_gpu)], + params=[ + pytest.param("jax", marks=pytest.mark.requires_jax), + pytest.param("torch", marks=pytest.mark.requires_torch), + ] ) -def device(request): - import jax +def library(request): + return request.param + + +@pytest.fixture(params=["cpu", pytest.param("gpu", marks=pytest.mark.requires_gpu)]) +def device(request, library): + if library == "jax": + import jax - try: - return jax.devices(request.param)[0] - except RuntimeError: - pytest.skip(f"no jax '{request.param}' device") + try: + return jax.devices(request.param)[0] + except RuntimeError: + pytest.skip(f"no jax '{request.param}' device") + import torch + + if request.param == "gpu" and not torch.cuda.is_available(): + pytest.skip("no torch CUDA device") + return torch.device("cuda" if request.param == "gpu" else "cpu") @pytest.fixture -def backend(): - from gt4py.next.program_processors.runners import jax_jit +def backend(library): + if library == "jax": + from gt4py.next.program_processors.runners import jax_jit - return jax_jit.jax_jit + return jax_jit.jax_jit + from gt4py.next.program_processors.runners import torch_compile + return torch_compile.torch_compile -def _field(device, values, dims): + +@pytest.fixture +def jax_only(library): + if library != "jax": + pytest.skip("inspects the 'jax.jit' cache") + + +def _array(device, values): + values = np.asarray(values) + if type(device).__module__.startswith("torch"): + import torch + + return torch.as_tensor(values, device=device) import jax + return jax.device_put(values, device) + + +def _field(device, values, dims): values = np.asarray(values) return common._field( - jax.device_put(values, device), + _array(device, values), domain=common.domain({dim: size for dim, size in zip(dims, values.shape)}), ) def _e2v(device, table=E2V_TABLE): - import jax - return common._connectivity( - jax.device_put(table, device), + _array(device, table), codomain=Vertex, domain=common.domain({Edge: table.shape[0], E2VDim: table.shape[1]}), ) @@ -154,7 +183,7 @@ def test_program_with_connectivity(device, backend): np.testing.assert_array_equal(out.asnumpy(), [3.0, 5.0, 7.0, 5.0, 4.0]) -def test_table_is_a_runtime_argument(device, backend): +def test_table_is_a_runtime_argument(device, backend, jax_only): f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) out = _field(device, np.zeros(5), [Edge]) prog = edge_sum_program.with_backend(backend) @@ -170,7 +199,7 @@ def test_table_is_a_runtime_argument(device, backend): assert "tensor<5x2xi32>" in main_signature -def test_retrace_per_table_buffer(device, backend): +def test_retrace_per_table_buffer(device, backend, jax_only): f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) out = _field(device, np.zeros(5), [Edge]) prog = edge_sum_program.with_backend(backend) @@ -185,7 +214,16 @@ def test_retrace_per_table_buffer(device, backend): assert _runner(prog)._cache_size() == 2 -def test_cartesian_offset_and_traced_scalar(device, backend): +def test_traced_scalar_does_not_retrace(device, backend, jax_only): + f = _field(device, np.arange(6.0), [IDim]) + prog = shift_scale_program.with_backend(backend) + for a in (2.0, 3.0): + prog(f, a, _field(device, np.zeros(5), [IDim]), offset_provider={}) + + assert _runner(prog)._cache_size() == 1 + + +def test_cartesian_offset_and_scalar(device, backend): f = _field(device, np.arange(6.0), [IDim]) prog = shift_scale_program.with_backend(backend) for a in (2.0, 3.0): @@ -195,8 +233,6 @@ def test_cartesian_offset_and_traced_scalar(device, backend): shift_scale_program(f, a, expected, offset_provider={}) np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - assert _runner(prog)._cache_size() == 1 - def test_static_param_in_program_domain(device, backend): f = _field(device, np.arange(6.0), [IDim]) @@ -236,7 +272,7 @@ def test_dimension_in_offset_provider_is_static(device, backend): np.testing.assert_array_equal(out.asnumpy(), [1.0, 1.0, 4.0, 4.0, 4.0]) -def test_scalar_only_builtins_on_traced_scalars(device, backend): +def test_scalar_only_builtins(device, backend): f = _field(device, np.arange(3.0), [IDim]) out = _field(device, np.zeros(3), [IDim]) expected = _field(device, np.zeros(3), [IDim]) @@ -248,7 +284,7 @@ def test_scalar_only_builtins_on_traced_scalars(device, backend): np.testing.assert_array_equal(out.asnumpy(), [0.0, 9.0, 18.0]) -def test_scan_with_traced_scalar(device, backend): +def test_scan_with_scalar(device, backend): x = _field(device, np.arange(1.0, 5.0), [KDim]) out = _field(device, np.zeros(4), [KDim]) expected = _field(device, np.zeros(4), [KDim]) @@ -270,8 +306,6 @@ def test_static_param_of_field_operator(device, backend): scale_if(f, flag, out=expected, offset_provider={}) np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - assert _runner(fo)._cache_size() == 2 - def test_field_operator_tuple_out_leaves_inputs(device, backend): a = _field(device, np.arange(3.0), [IDim]) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py index 311b1870ed..a36dac3625 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py @@ -335,7 +335,7 @@ def test_unstructured_shift_with_non_zero_origin(unstructured_case): # TODO(edopao,havogt): remove the xfail below once the embedded backend supports # non-contiguous field domain, which is generated by the inverse image of the # connectivity used in this test. - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.xfail("Embedded backend only supports contiguous field domains.") @gtx.field_operator @@ -420,7 +420,7 @@ def test_neighbor_sum_with_non_zero_origin(unstructured_case): # TODO(edopao,havogt): remove the xfail below once the embedded backend supports # non-contiguous field domain, which is generated by the inverse image of the # connectivity used in this test. - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.xfail("Embedded backend only supports contiguous field domains.") @gtx.field_operator diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py index e1352ffe2a..7078efcff7 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py @@ -190,7 +190,7 @@ def expected(a, b, c, d): cases.verify_with_default_data(cartesian_case, solve_tridiag, ref=expected) -@pytest.mark.uses_scalar_in_control_flow +@pytest.mark.uses_scan_carry_in_control_flow @pytest.mark.uses_scan def test_ternary_scan(cartesian_case): @gtx.scan_operator(axis=KDim, forward=True, init=0.0) From b269dbae10c55e5699079c21bb38c26a8f4101f5 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 21:12:43 +0100 Subject: [PATCH 123/166] refactor[next]: no import cycle between fbuiltins and embedded, array_ops imported at module level --- src/gt4py/next/__init__.py | 1 + src/gt4py/next/embedded/__init__.py | 6 +++-- src/gt4py/next/ffront/fbuiltins.py | 35 +++++++++-------------------- 3 files changed, 16 insertions(+), 26 deletions(-) diff --git a/src/gt4py/next/__init__.py b/src/gt4py/next/__init__.py index 3b9f97592f..eb16ce131d 100644 --- a/src/gt4py/next/__init__.py +++ b/src/gt4py/next/__init__.py @@ -39,6 +39,7 @@ ) from .constructors import FieldConstructor, as_connectivity, as_field, empty, full, ones, zeros from .embedded import ( # Just for registering field implementations + array_libraries as _array_libraries, nd_array_field as _nd_array_field, ) from .ffront import fbuiltins diff --git a/src/gt4py/next/embedded/__init__.py b/src/gt4py/next/embedded/__init__.py index cf7ed12fdd..df9965da2e 100644 --- a/src/gt4py/next/embedded/__init__.py +++ b/src/gt4py/next/embedded/__init__.py @@ -6,7 +6,9 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -from . import array_libraries, array_ops, common, context, exceptions, nd_array_field +# `nd_array_field` and `array_libraries` import `ffront.fbuiltins`, which imports this package: +# `gt4py.next` imports them after `ffront` +from . import array_ops, common, context, exceptions -__all__ = ["array_libraries", "array_ops", "common", "context", "exceptions", "nd_array_field"] +__all__ = ["array_ops", "common", "context", "exceptions"] diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index c91783730a..1f46d6496a 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -34,6 +34,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import common, named_collections from gt4py.next.common import Dimension, Field # noqa: F401 [unused-import] for TYPE_BUILTINS +from gt4py.next.embedded import array_ops, context as embedded_context from gt4py.next.iterator import runtime from gt4py.next.type_system import type_specifications as ts @@ -281,24 +282,13 @@ def min_over(field: common.Field, /, axis: common.Dimension) -> common.Field: raise NotImplementedError() -def _is_scalar(value: Any) -> bool: - from gt4py.next.embedded import array_ops # avoid circular import - - return array_ops.is_scalar(value) - - -def _array_ops_of_0d(value: Any) -> Any: - from gt4py.next.embedded import array_ops # avoid circular import - - assert array_ops.is_scalar(value) - return array_ops.of(value) - - @BuiltInFunction def broadcast( field: common.Field | core_defs.ScalarT, dims: tuple[common.Dimension, ...], / ) -> common.Field: - assert _is_scalar(field) # default implementation for scalars, Fields are handled via dispatch + assert array_ops.is_scalar( + field + ) # default implementation for scalars, Fields are handled via dispatch # TODO(havogt) implement with FunctionField, the workaround is to ignore broadcasting on scalars as they broadcast automatically, but we lose the check for compatible dimensions return field # type: ignore[return-value] # see comment above @@ -334,7 +324,7 @@ def astype( # default implementation for scalars, Fields are handled via dispatch if core_defs.is_scalar_type(value): return core_defs.dtype(type_).scalar_type(value) - ops = _array_ops_of_0d(value) + ops = array_ops.of(value) return ops.xp.astype(value, ops.dtype(type_)) @@ -395,7 +385,7 @@ def impl(value: common.Field | core_defs.ScalarT, /) -> common.Field | core_defs # default implementation for scalars, Fields are handled via dispatch if core_defs.is_scalar_type(value): return cast(common.Field | core_defs.ScalarT, _math_builtin(value)) - return _array_ops_of_0d(value).elementwise_function(name)(value) + return array_ops.of(value).elementwise_function(name)(value) impl.__name__ = name return BuiltInFunction(impl) @@ -438,8 +428,9 @@ def impl( # default implementation for scalars, Fields are handled via dispatch if core_defs.is_scalar_type(lhs) and core_defs.is_scalar_type(rhs): return getattr(np, name)(lhs, rhs) - ops = _array_ops_of_0d(rhs if core_defs.is_scalar_type(lhs) else lhs) - return ops.elementwise_function(name)(ops.operand(lhs, rhs), ops.operand(rhs, lhs)) + array = cast(core_defs.NDArrayObject, rhs if core_defs.is_scalar_type(lhs) else lhs) + ops = array_ops.of(array) + return ops.elementwise_function(name)(ops.operand(lhs, array), ops.operand(rhs, array)) impl.__name__ = name return BuiltInFunction(impl) @@ -506,10 +497,8 @@ def __gt_type__(self) -> ts.OffsetType: def __getitem__(self, offset: int) -> common.Connectivity: """Serve as a connectivity factory.""" - from gt4py.next import embedded # avoid circular import - assert isinstance(self.value, str) - current_offset_provider = embedded.context.get_offset_provider(None) + current_offset_provider = embedded_context.get_offset_provider(None) assert current_offset_provider is not None offset_definition = common.get_offset(current_offset_provider, self.value) @@ -521,10 +510,8 @@ def __getitem__(self, offset: int) -> common.Connectivity: def as_connectivity_field(self) -> common.Connectivity: """Convert to connectivity field using the offset providers in current embedded execution context.""" - from gt4py.next import embedded # avoid circular import - assert isinstance(self.value, str) - current_offset_provider = embedded.context.get_offset_provider(None) + current_offset_provider = embedded_context.get_offset_provider(None) assert current_offset_provider is not None offset_definition = common.get_offset(current_offset_provider, self.value) From 2b6be0fbf0886fe834fc2691a4a083646218e323 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 21:12:43 +0100 Subject: [PATCH 124/166] refactor[next]: embedded jit backends wrap the embedded entry point, torch_compile traces scalars as jax_jit --- src/gt4py/next/backend.py | 46 +++- .../next/embedded/array_libraries/jax_ops.py | 18 +- .../embedded/array_libraries/torch_ops.py | 18 +- src/gt4py/next/ffront/decorator.py | 120 ++++++---- src/gt4py/next/named_collections.py | 13 +- .../runners/embedded_jit.py | 118 ---------- .../program_processors/runners/jax_jit.py | 154 ++++--------- .../runners/torch_compile.py | 217 +++++++----------- 8 files changed, 294 insertions(+), 410 deletions(-) delete mode 100644 src/gt4py/next/program_processors/runners/embedded_jit.py diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 94f54172f4..02f14d13fe 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -8,8 +8,11 @@ from __future__ import annotations +import abc import dataclasses -from typing import Generic +import inspect +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Generic from gt4py._core import definitions as core_defs from gt4py.next import config, custom_layout_allocators as next_allocators @@ -25,6 +28,7 @@ from gt4py.next.ffront.past_passes import linters as past_linters from gt4py.next.iterator import ir as itir from gt4py.next.otf import arguments, artifacts, stages, toolchain, workflow +from gt4py.next.type_system import type_specifications as ts def jit_to_aot_args( @@ -174,6 +178,46 @@ def __gt_allocator__( return self.allocator +def _not_compiled(*args: Any, **kwargs: Any) -> Any: + raise RuntimeError("An embedded jit backend runs programs embedded; it does not compile them.") + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class EmbeddedJitBackend(Backend, abc.ABC): + """ + Runs programs and field operators embedded, inside the tracing compiler of an array library. + + Instead of compiling, it wraps the embedded entry point of a program or field operator once, + e.g. in `jax.jit`. The allocator is the array namespace of the library. + """ + + executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] = ( + _not_compiled + ) + transforms: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgramDef] = ( + DEFAULT_TRANSFORMS + ) + + @abc.abstractmethod + def jit( + self, + entry: Callable[..., None], + signature: inspect.Signature, + static_params: Sequence[str], + param_types: Iterable[ts.TypeSpec], + ) -> Callable[..., None]: + """ + Wrap `entry`, called as `signature` describes, in the tracing compiler. + + Args: + entry: Runs the program or field operator embedded; it assigns to its `out` fields. + signature: The parameters of `entry`, including the keyword-only `offset_provider`. + static_params: The parameters whose values are compile-time constants. + param_types: The types of the parameters, e.g. to register their named collections. + """ + ... + + @dataclasses.dataclass(frozen=True) class ToolchainConfig: """ diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 7a31329e5c..b3e305351f 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -9,8 +9,9 @@ """ `ArrayOps` for JAX arrays, and the embedded fields as JAX pytrees. -Everything gt4py knows about JAX tracing is in this module (ADR 0029). A -connectivity table inside a trace is a tracer, and one of two cases: +How embedded fields and connectivities behave under JAX tracing is in this module +(ADR 0029); `runners.jax_jit` runs programs under `jax.jit`. A connectivity table +inside a trace is a tracer, and one of two cases: - it stands for a concrete table, which it got as a pytree leaf, or it was restricted from such a tracer: its static values are a NumPy view of the @@ -24,6 +25,7 @@ from __future__ import annotations import dataclasses +import functools from collections.abc import Callable, Mapping from typing import Any, ClassVar, NamedTuple, Optional @@ -248,3 +250,15 @@ def _unflatten_connectivity( _flatten_connectivity, _unflatten_connectivity, ) + +# e.g. the `Dimension`s of an offset provider, or a `domain=` argument, in the arguments of `jax.jit` +jax.tree_util.register_static(common.Dimension) +jax.tree_util.register_static(common.Domain) + + +@functools.cache +def register_named_collection(cls: type) -> None: + """Make the dataclass named collection `cls` a pytree; the other named collections are tuples.""" + jax.tree_util.register_dataclass( + cls, data_fields=[f.name for f in dataclasses.fields(cls)], meta_fields=[] + ) diff --git a/src/gt4py/next/embedded/array_libraries/torch_ops.py b/src/gt4py/next/embedded/array_libraries/torch_ops.py index f566c92c97..6796333aa4 100644 --- a/src/gt4py/next/embedded/array_libraries/torch_ops.py +++ b/src/gt4py/next/embedded/array_libraries/torch_ops.py @@ -9,11 +9,12 @@ """ `ArrayOps` for torch tensors, and the embedded fields as torch pytrees. -Everything gt4py knows about `torch.compile` is in this module (ADR 0029). -Dynamo does not trace embedded code: a region calls it through a -`torch.compiler.nonstrict_trace` function, which gets the fields and connectivities -as pytree nodes and runs the embedded code on the fake tensors of the trace. A -connectivity table inside the trace is one of two cases: +How embedded fields and connectivities behave under `torch.compile` is in this +module (ADR 0029); `runners.torch_compile` runs programs in a region. Dynamo does not +trace embedded code: a region calls it through a `torch.compiler.nonstrict_trace` +function, which gets the fields and connectivities as pytree nodes and runs the +embedded code on the fake tensors of the trace. A connectivity table inside the trace +is one of two cases: - it stands for a concrete table, which it got through the pytree context: its static values are a NumPy array with the values of the concrete table; @@ -38,6 +39,7 @@ from __future__ import annotations import dataclasses +import functools from collections.abc import Callable, Mapping from types import ModuleType from typing import Any, ClassVar, Optional @@ -319,3 +321,9 @@ def _unflatten_connectivity( _flatten_connectivity, _unflatten_connectivity, ) + + +@functools.cache +def register_named_collection(cls: type) -> None: + """Make the dataclass named collection `cls` a pytree; the other named collections are tuples.""" + torch_pytree.register_dataclass(cls) diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 5fa5bfe8c7..a5c042d573 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -48,7 +48,6 @@ from gt4py.next.instrumentation import hook_machinery, metrics from gt4py.next.iterator import ir as itir from gt4py.next.otf import arguments, compiled_program, options, workflow -from gt4py.next.program_processors.runners import embedded_jit from gt4py.next.type_system import type_info, type_specifications as ts, type_translation @@ -102,14 +101,41 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): metadata=utils.gt4py_metadata(fingerprint=False) ) compilation_options: options.CompilationOptions + # an attribute, not a cached property, to cost the call no more than `backend is not None` + _is_compiled: bool = dataclasses.field( + init=False, repr=False, compare=False, metadata=utils.gt4py_metadata(fingerprint=False) + ) + + def __post_init__(self) -> None: + object.__setattr__( + self, + "_is_compiled", + self.backend is not None + and not isinstance(self.backend, next_backend.EmbeddedJitBackend), + ) @abc.abstractmethod def __gt_type__(self) -> ts.CallableType: ... - @abc.abstractmethod - def _embedded_jit_runner( - self, backend: embedded_jit.EmbeddedJitBackend - ) -> embedded_jit.EmbeddedJitRunner: ... + def _jit( + self, entry: Callable[..., None], *keyword_only: inspect.Parameter + ) -> Callable[..., None]: + """`entry`, the embedded execution, wrapped by the embedded jit backend.""" + assert isinstance(self.backend, next_backend.EmbeddedJitBackend) + callable_type = self.__gt_type__() + assert isinstance( + callable_type, + ts_ffront.ProgramType | ts_ffront.FieldOperatorType | ts_ffront.ScanOperatorType, + ) + signature: inspect.Signature = ffront_type_info._signature_from_callable_in_program_context( + callable_type + ) + return self.backend.jit( + entry, + signature.replace(parameters=[*signature.parameters.values(), *keyword_only]), + self.compilation_options.static_params or (), + callable_type.definition.pos_or_kw_args.values(), + ) def with_backend(self, backend: next_backend.Backend | None) -> Self: return dataclasses.replace(self, backend=backend) @@ -125,11 +151,7 @@ def with_compilation_options( ) @functools.cached_property - def _compiled_programs( - self, - ) -> compiled_program.CompiledProgramsPool | embedded_jit.EmbeddedJitRunner: - if isinstance(self.backend, embedded_jit.EmbeddedJitBackend): - return self._embedded_jit_runner(self.backend) + def _compiled_programs(self) -> compiled_program.CompiledProgramsPool: # This cached property initializer is only called when JITting the first # program variant of the pool. If the program is compiled by directly # calling `compile()`, the pool is initialized with the options passed @@ -144,9 +166,9 @@ def _make_compiled_programs_pool( ) -> compiled_program.CompiledProgramsPool: if self.backend is None or self.backend == eve.NOTHING: raise RuntimeError("Cannot compile a program without backend.") - if isinstance(self.backend, embedded_jit.EmbeddedJitBackend): + if not self._is_compiled: raise RuntimeError( - f"Backend '{self.backend.name}' runs the program embedded; it does not compile." + f"Backend '{self.backend.name}' runs programs embedded; it does not compile them." ) program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) @@ -219,7 +241,6 @@ def compile( for op in offset_provider ) - assert isinstance(self._compiled_programs, compiled_program.CompiledProgramsPool) self._compiled_programs.compile(offset_providers=offset_provider, **static_args) return self @@ -278,6 +299,7 @@ def __gt_type__(self) -> ts_ffront.ProgramType: # TODO(ricoh): linting should become optional, up to the backend. def __post_init__(self) -> None: + super().__post_init__() no_args_past = workflow.ConcreteArtifact(self.past_stage, arguments.CompileTimeArgs.empty()) _ = self._frontend_transforms.past_lint(no_args_past).data @@ -331,16 +353,15 @@ def gtir(self) -> itir.Program: ) return self._frontend_transforms.past_to_itir(no_args_past).data - def _embedded_jit_runner( - self, backend: embedded_jit.EmbeddedJitBackend - ) -> embedded_jit.EmbeddedJitRunner: + @functools.cached_property + def _jit_entry(self) -> Callable[..., None]: definition = self.definition_stage.definition - return backend.jit( - definition, - self.compilation_options.static_params or (), - param_names=list(inspect.signature(definition).parameters), - param_types=self.__gt_type__().definition.pos_or_kw_args.values(), - ) + + def run(*args: Any, offset_provider: common.OffsetProvider, **kwargs: Any) -> None: + with next_embedded.context.update(offset_provider=offset_provider): + definition(*args, **kwargs) + + return self._jit(run, inspect.Parameter("offset_provider", inspect.Parameter.KEYWORD_ONLY)) def with_grid_type(self, grid_type: common.GridType) -> Program: return dataclasses.replace( @@ -386,10 +407,13 @@ def __call__( kwarg_types={k: type_translation.from_value(v) for k, v in kwargs.items()}, ) - if self.backend is not None: + if self._is_compiled: self._compiled_programs( *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit ) + elif self.backend is not None: + with embedded_program_call_context(self, args, offset_provider, kwargs): + self._jit_entry(*args, offset_provider=offset_provider, **kwargs) else: # Embedded execution. warnings.warn( @@ -509,6 +533,7 @@ def from_function( # TODO(ricoh): linting should become optional, up to the backend. def __post_init__(self) -> None: """This ensures that DSL linting occurs at decoration time.""" + super().__post_init__() _ = self.foast_stage @functools.cached_property @@ -541,6 +566,7 @@ def __gt_type__(self) -> ts.CallableType: assert isinstance(type_, ts.CallableType) return type_ + @functools.cached_property def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: attributes = ( self.definition_stage.attributes @@ -561,20 +587,17 @@ def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: ) return embedded_operators.EmbeddedOperator(self.definition_stage.definition) - def _embedded_jit_runner( - self, backend: embedded_jit.EmbeddedJitBackend - ) -> embedded_jit.EmbeddedJitRunner: - op = self._embedded_operator() - operator_type = self.foast_stage.foast_node.type - assert isinstance(operator_type, ts_ffront.FieldOperatorType | ts_ffront.ScanOperatorType) - param_names = list(inspect.signature(self.definition_stage.definition).parameters) - if isinstance(op, embedded_operators.ScanOperator): - param_names = param_names[1:] # the carry - return backend.jit( - lambda *args, **kwargs: embedded_operators.field_operator_call(op, args, kwargs), - ("domain", *(self.compilation_options.static_params or ())), - param_names=param_names, - param_types=operator_type.definition.pos_or_kw_args.values(), + @functools.cached_property + def _jit_entry(self) -> Callable[..., None]: + op = self._embedded_operator + + def run(*args: Any, **kwargs: Any) -> None: + embedded_operators.field_operator_call(op, args, kwargs) + + return self._jit( + run, + inspect.Parameter("domain", inspect.Parameter.KEYWORD_ONLY, default=None), + inspect.Parameter("offset_provider", inspect.Parameter.KEYWORD_ONLY), ) def with_grid_type(self, grid_type: common.GridType) -> FieldOperator: @@ -596,7 +619,7 @@ def __gt_closure_vars__(self) -> dict[str, Any]: return self.foast_stage.closure_vars def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> Any: - if not next_embedded.context.within_valid_context() and self.backend is not None: + if not next_embedded.context.within_valid_context() and self._is_compiled: # non embedded execution offset_provider = {**kwargs.pop("offset_provider", {})} if "out" not in kwargs: @@ -604,13 +627,9 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> out = kwargs.pop("out") if "domain" in kwargs: domain = utils.tree_map(common.domain)(kwargs.pop("domain")) - if isinstance(self.backend, embedded_jit.EmbeddedJitBackend): - # the operator assigns to `out` inside the trace, not to a restricted copy - kwargs["domain"] = domain - else: - if not isinstance(domain, tuple): - domain = utils.tree_map(lambda _: domain)(out) - out = utils.tree_map(lambda f, dom: f[dom])(out, domain) + if not isinstance(domain, tuple): + domain = utils.tree_map(lambda _: domain)(out) + out = utils.tree_map(lambda f, dom: f[dom])(out, domain) return self._compiled_programs( *args, @@ -625,7 +644,14 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> if not next_embedded.context.within_valid_context(): # field_operator as program kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} - return embedded_operators.field_operator_call(self._embedded_operator(), args, kwargs) + if self.backend is not None: + if "out" not in kwargs: + raise errors.MissingArgumentError(None, "out", True) + if "domain" in kwargs: + # a `Domain` is static under the tracing compiler, a `dict` is not + kwargs["domain"] = utils.tree_map(common.domain)(kwargs["domain"]) + return self._jit_entry(*args, **kwargs) + return embedded_operators.field_operator_call(self._embedded_operator, args, kwargs) GTEntryPoint: TypeAlias = Program | FieldOperator @@ -764,7 +790,7 @@ def scan_operator( definition: Function from scalars to a scalar. Keyword Arguments: - axis: A :ref:`Dimension` to reduce over. + axis: A `Dimension` to reduce over. forward: Boolean specifying the direction. init: Initial value for the carry argument of the scan pass. diff --git a/src/gt4py/next/named_collections.py b/src/gt4py/next/named_collections.py index e2c7c09a52..50297605fb 100644 --- a/src/gt4py/next/named_collections.py +++ b/src/gt4py/next/named_collections.py @@ -13,7 +13,7 @@ import inspect import pkgutil import typing -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterator, Mapping from typing import Any, Final, TypeAlias, TypeGuard, TypeVar import typing_extensions @@ -394,3 +394,14 @@ def impl( return construct(result) # type: ignore[arg-type] return impl + + +def dataclass_types(type_: ts.TypeSpec) -> Iterator[type]: + """The dataclasses of the named collections in `type_`, e.g. to register them as pytrees.""" + if isinstance(type_, ts.NamedCollectionType): + cls = pkgutil.resolve_name(type_.original_python_type) + if isinstance(cls, type) and dataclasses.is_dataclass(cls): + yield cls + if isinstance(type_, ts.TupleType | ts.NamedCollectionType): + for element_type in type_.types: + yield from dataclass_types(element_type) diff --git a/src/gt4py/next/program_processors/runners/embedded_jit.py b/src/gt4py/next/program_processors/runners/embedded_jit.py deleted file mode 100644 index 2770e6c2d8..0000000000 --- a/src/gt4py/next/program_processors/runners/embedded_jit.py +++ /dev/null @@ -1,118 +0,0 @@ -# GT4Py - GridTools Framework -# -# Copyright (c) 2014-2024, ETH Zurich -# All rights reserved. -# -# Please, refer to the LICENSE file in the root directory. -# SPDX-License-Identifier: BSD-3-Clause - -""" -Embedded execution of programs and field operators inside the tracing compiler of an array library. - -The backends (`jax_jit.jax_jit`, `torch_compile.torch_compile`) run the Python -definition on fields of their library, inside `jax.jit` or `torch.compile`. -Fields, connectivities and the other arguments go to the compiled function; the -offset provider entries that are no connectivities (`Dimension`s of Cartesian -offsets) and the parameters named in `static_params` are static. -""" - -from __future__ import annotations - -import abc -import dataclasses -import pkgutil -from collections.abc import Callable, Iterable, Sequence -from typing import Any - -from gt4py.next import backend as next_backend, common -from gt4py.next.type_system import type_specifications as ts - - -StaticItems = tuple[tuple[str, Any], ...] - - -@dataclasses.dataclass(frozen=True) -class EmbeddedJitBackend(next_backend.Backend, abc.ABC): - """Runs programs and field operators embedded, inside the tracing compiler of an array library.""" - - @abc.abstractmethod - def jit( - self, - function: Callable[..., None], - static_argnames: Iterable[str] = (), - param_names: Sequence[str] = (), - param_types: Iterable[ts.TypeSpec] = (), - ) -> EmbeddedJitRunner: ... - - -def not_compiled(*args: Any, **kwargs: Any) -> Any: - raise RuntimeError("An embedded jit backend runs the program embedded; it does not compile.") - - -def named_collection_dataclasses(type_: ts.TypeSpec) -> Iterable[type]: - """The dataclasses of the named collections in `type_`, which are no pytrees by themselves.""" - if isinstance(type_, ts.NamedCollectionType): - cls = pkgutil.resolve_name(type_.original_python_type) - if isinstance(cls, type) and dataclasses.is_dataclass(cls): - yield cls - if isinstance(type_, ts.TupleType | ts.NamedCollectionType): - for element_type in type_.types: - yield from named_collection_dataclasses(element_type) - - -class EmbeddedJitRunner(abc.ABC): - """ - One compiled embedded entry point, called like a compiled programs pool. - - Splits the arguments into the ones the compiled function takes and the static - ones: the parameters in `static_argnames` and the offset provider entries - that are no connectivities, both as sorted `(name, value)` items. - """ - - def __init__( - self, - function: Callable[..., None], - static_argnames: frozenset[str], - param_names: tuple[str, ...], - ) -> None: - self._function = function - self._static_argnames = static_argnames - # static parameters passed positionally are only found by name - self._param_names = param_names if static_argnames & set(param_names) else () - - @abc.abstractmethod - def _run( - self, - args: tuple[Any, ...], - kwargs: dict[str, Any], - connectivities: dict[str, Any], - static_kwargs: StaticItems, - static_provider: StaticItems, - ) -> None: ... - - def __call__( - self, - *args: Any, - offset_provider: common.OffsetProvider, - enable_jit: bool | None = None, - **kwargs: Any, - ) -> None: - if self._static_argnames: - if self._param_names: - kwargs = {**dict(zip(self._param_names, args)), **kwargs} - args = () - static_kwargs = tuple( - sorted((name, kwargs.pop(name)) for name in self._static_argnames & kwargs.keys()) - ) - else: - static_kwargs = () - - connectivities: dict[str, Any] = {} - static_provider: list[tuple[str, Any]] = [] - for name, entry in offset_provider.items(): - if isinstance(entry, common.Connectivity): - connectivities[name] = entry - else: - static_provider.append((name, entry)) - - self._run(args, kwargs, connectivities, static_kwargs, tuple(sorted(static_provider))) diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/jax_jit.py index 4bd064f740..5e61bf6a22 100644 --- a/src/gt4py/next/program_processors/runners/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/jax_jit.py @@ -9,56 +9,32 @@ """ Embedded execution of programs and field operators under `jax.jit`. -`jax_jit` (created on first access, it requires `jax`) runs the Python definition -on fields of JAX arrays inside `jax.jit`. Fields, connectivities and scalars are -arguments of the jitted function (see `embedded_jit` for the static ones). +Fields, connectivities and scalars are arguments of the jitted function; the +`Dimension`s of the offset provider, a `domain=` argument and the parameters in +`static_params` are static. """ from __future__ import annotations import dataclasses +import inspect from collections.abc import Callable, Iterable, Sequence from typing import Any -from gt4py.next import backend as next_backend, common -from gt4py.next.embedded import context as embedded_context, nd_array_field -from gt4py.next.program_processors.runners import embedded_jit -from gt4py.next.type_system import type_specifications as ts - - -@dataclasses.dataclass(frozen=True) -class JaxJitBackend(embedded_jit.EmbeddedJitBackend): - """Runs programs and field operators embedded, under `jax.jit`.""" - - def jit( - self, - function: Callable[..., None], - static_argnames: Iterable[str] = (), - param_names: Sequence[str] = (), - param_types: Iterable[ts.TypeSpec] = (), - ) -> JitRunner: - import jax - - for type_ in param_types: - for cls in embedded_jit.named_collection_dataclasses(type_): - if cls not in _registered_dataclasses: - jax.tree_util.register_dataclass( - cls, data_fields=[f.name for f in dataclasses.fields(cls)], meta_fields=[] - ) - _registered_dataclasses.add(cls) - return JitRunner(function, frozenset(static_argnames), tuple(param_names)) +import jax +import jax.numpy as jnp - -_registered_dataclasses: set[type] = set() +from gt4py.next import backend as next_backend, common, named_collections +from gt4py.next.embedded import nd_array_field +from gt4py.next.embedded.array_libraries import jax_ops +from gt4py.next.type_system import type_specifications as ts def _is_field(x: Any) -> bool: return isinstance(x, common.Field) -def _written_fields(tree: Any) -> list[nd_array_field.NdArrayField]: - import jax - +def _assignable_fields(tree: Any) -> list[nd_array_field.NdArrayField]: return [ leaf for leaf in jax.tree.leaves(tree, is_leaf=_is_field) @@ -67,81 +43,47 @@ def _written_fields(tree: Any) -> list[nd_array_field.NdArrayField]: ] -class JitRunner(embedded_jit.EmbeddedJitRunner): +@dataclasses.dataclass(frozen=True, kw_only=True) +class JaxJitBackend(next_backend.EmbeddedJitBackend): """ - One `jax.jit` of an embedded entry point. + Runs programs and field operators embedded, under `jax.jit`. - The jitted function returns, for each field of the arguments, its new buffer - if the entry point assigned to it and `None` otherwise; the new buffers are - then swapped into the caller's fields. + JAX arrays are immutable, so an assignment to an `out` field gives it a new + buffer: the jitted function returns the new buffer of each field it assigned + to, and the caller's fields get them. """ - def __init__( + def jit( self, - function: Callable[..., None], - static_argnames: frozenset[str], - param_names: tuple[str, ...], - ) -> None: - import jax + entry: Callable[..., None], + signature: inspect.Signature, + static_params: Sequence[str], + param_types: Iterable[ts.TypeSpec], + ) -> Callable[..., None]: + for type_ in param_types: + for cls in named_collections.dataclass_types(type_): + jax_ops.register_named_collection(cls) - super().__init__(function, static_argnames, param_names) - self._jitted = jax.jit(self._traced, static_argnames=("static_kwargs", "static_provider")) + def traced(*args: Any, **kwargs: Any) -> list[Any]: + fields = _assignable_fields((args, kwargs)) + buffers = [field.ndarray for field in fields] + entry(*args, **kwargs) + return [ + field.ndarray if field.ndarray is not buffer else None + for field, buffer in zip(fields, buffers, strict=True) + ] - def _traced( - self, - args: tuple[Any, ...], - kwargs: dict[str, Any], - connectivities: dict[str, Any], - *, - static_kwargs: embedded_jit.StaticItems, - static_provider: embedded_jit.StaticItems, - ) -> list[Any]: - fields = _written_fields((args, kwargs)) - buffers = [field.ndarray for field in fields] - with embedded_context.update(offset_provider={**connectivities, **dict(static_provider)}): - self._function(*args, **kwargs, **dict(static_kwargs)) - return [ - field.ndarray if field.ndarray is not buffer else None - for field, buffer in zip(fields, buffers, strict=True) - ] - - def _run( - self, - args: tuple[Any, ...], - kwargs: dict[str, Any], - connectivities: dict[str, Any], - static_kwargs: embedded_jit.StaticItems, - static_provider: embedded_jit.StaticItems, - ) -> None: - new_buffers = self._jitted( - args, - kwargs, - connectivities, - static_kwargs=static_kwargs, - static_provider=static_provider, - ) - for field, buffer in zip(_written_fields((args, kwargs)), new_buffers, strict=True): - if buffer is not None: - field._set_buffer(buffer) - - -def __getattr__(name: str) -> JaxJitBackend: - if name != "jax_jit": - raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") - import jax.numpy as jnp - - from gt4py.next.embedded.array_libraries import ( - jax_ops, # noqa: F401 [unused-import] # registers the pytrees - ) - - backend = JaxJitBackend( - name="jax_jit", - executor=embedded_jit.not_compiled, - allocator=jnp, - transforms=next_backend.DEFAULT_TRANSFORMS, - ) - globals()[name] = backend - return backend - - -jax_jit: JaxJitBackend + traced.__signature__ = signature # type: ignore[attr-defined] # for `static_argnames` + jitted = jax.jit(traced, static_argnames=tuple(static_params)) + + def run(*args: Any, **kwargs: Any) -> None: + new_buffers = jitted(*args, **kwargs) + for field, buffer in zip(_assignable_fields((args, kwargs)), new_buffers, strict=True): + if buffer is not None: + field._set_buffer(buffer) + + run.jitted = jitted # type: ignore[attr-defined] # to inspect the traces + return run + + +jax_jit = JaxJitBackend(name="jax_jit", allocator=jnp) diff --git a/src/gt4py/next/program_processors/runners/torch_compile.py b/src/gt4py/next/program_processors/runners/torch_compile.py index fad7f44da6..be41007dd3 100644 --- a/src/gt4py/next/program_processors/runners/torch_compile.py +++ b/src/gt4py/next/program_processors/runners/torch_compile.py @@ -9,159 +9,116 @@ """ Embedded execution of programs and field operators under `torch.compile`. -`torch_compile` (created on first access, it requires `torch`) runs the Python -definition on fields of torch tensors in a `torch.compile` region, through a -`torch.compiler.nonstrict_trace` function, as `torch_ops` describes. Fields and -connectivities are arguments of the region; Dynamo specializes on the other -arguments (see `embedded_jit` for the static ones). +The embedded code runs in a region through a `torch.compiler.nonstrict_trace` +function (see `torch_ops`). Fields, connectivities and scalars are arguments of the +region; the `Dimension`s of the offset provider, a `domain=` argument and the +parameters in `static_params` are static. """ from __future__ import annotations +import contextvars import dataclasses +import inspect from collections.abc import Callable, Iterable, Sequence from typing import Any -from gt4py.next import backend as next_backend -from gt4py.next.embedded import context as embedded_context -from gt4py.next.program_processors.runners import embedded_jit +import numpy as np +import torch + +from gt4py.next import backend as next_backend, common, named_collections +from gt4py.next.embedded.array_libraries import torch_ops from gt4py.next.type_system import type_specifications as ts -@dataclasses.dataclass(frozen=True) -class TorchCompileBackend(embedded_jit.EmbeddedJitBackend): - """Runs programs and field operators embedded, under `torch.compile`.""" +# Dynamo reports an exception of the embedded code as an unsupported output type +_embedded_error: contextvars.ContextVar[Exception | None] = contextvars.ContextVar( + "_embedded_error", default=None +) - def jit( - self, - function: Callable[..., None], - static_argnames: Iterable[str] = (), - param_names: Sequence[str] = (), - param_types: Iterable[ts.TypeSpec] = (), - ) -> CompileRunner: - import torch.utils._pytree as torch_pytree +_Static = tuple[tuple[str, Any], ...] - for type_ in param_types: - for cls in embedded_jit.named_collection_dataclasses(type_): - if cls not in _registered_dataclasses: - torch_pytree.register_dataclass(cls) - _registered_dataclasses.add(cls) - return CompileRunner(function, frozenset(static_argnames), tuple(param_names)) +def _as_region_argument(value: Any) -> Any: + # Dynamo specializes on Python and NumPy scalars, which `nonstrict_trace` does not + # take either: as 0-d tensors they are traced, as by `jax.jit`, and keep their dtype + if isinstance(value, float): + return torch.tensor(value, dtype=torch.float64) + if isinstance(value, bool | int | np.generic): + return torch.as_tensor(value) + return value -_registered_dataclasses: set[type] = set() +def _region(entry: Callable[..., None], static: _Static) -> Callable[..., Any]: + @torch.compiler.nonstrict_trace + def run_embedded(kwargs: dict[str, Any], connectivities: dict[str, Any]) -> tuple[()]: + static_kwargs = dict(static) + offset_provider = {**connectivities, **dict(static_kwargs.pop("offset_provider"))} + try: + entry(**kwargs, **static_kwargs, offset_provider=offset_provider) + except Exception as error: + _embedded_error.set(error) + raise + # `nonstrict_trace` does not support a `None` output + return () -class CompileRunner(embedded_jit.EmbeddedJitRunner): - """ - One `torch.compile` region per combination of static arguments. + def region(kwargs: dict[str, Any], connectivities: dict[str, Any]) -> tuple[()]: + return run_embedded(kwargs, connectivities) - The static arguments are closed over by the non-strictly traced function, - since `nonstrict_trace` only takes tensors, pytrees and constants. The entry - point assigns to its `out` fields in place, which the region applies to the - caller's tensors. - """ + # Dynamo's recompile limit is per code object: each region needs its own + region.__code__ = region.__code__.replace() + # `dynamic=False`: see `torch_ops` + return torch.compile(region, fullgraph=True, dynamic=False) - def __init__( - self, - function: Callable[..., None], - static_argnames: frozenset[str], - param_names: tuple[str, ...], - ) -> None: - super().__init__(function, static_argnames, param_names) - self._embedded_error: BaseException | None = None - self._regions: dict[ - tuple[embedded_jit.StaticItems, embedded_jit.StaticItems], Callable[..., Any] - ] = {} - - def _region( - self, static_kwargs: embedded_jit.StaticItems, static_provider: embedded_jit.StaticItems - ) -> Callable[..., Any]: - import torch - - function = self._function - - @torch.compiler.nonstrict_trace - def run_embedded( - args: tuple[Any, ...], kwargs: dict[str, Any], connectivities: dict[str, Any] - ) -> tuple[()]: - with embedded_context.update( - offset_provider={**connectivities, **dict(static_provider)} - ): - try: - function(*args, **kwargs, **dict(static_kwargs)) - except Exception as error: - # Dynamo reports it as an unsupported output type - self._embedded_error = error - raise - # `nonstrict_trace` does not support a `None` output - return () - def region( - args: tuple[Any, ...], kwargs: dict[str, Any], connectivities: dict[str, Any] - ) -> tuple[()]: - return run_embedded(args, kwargs, connectivities) +@dataclasses.dataclass(frozen=True, kw_only=True) +class TorchCompileBackend(next_backend.EmbeddedJitBackend): + """ + Runs programs and field operators embedded, under `torch.compile`. - # Dynamo caches per code object, with a recompile limit: every region needs its own - region.__code__ = region.__code__.replace() - # with dynamic shapes, Dynamo makes domain bounds symbolic, which cannot be in a pytree context - return torch.compile(region, fullgraph=True, dynamic=False) + Dynamo cannot rebuild frozen dataclasses such as `Dimension` and `Domain` from a + region input, so the static arguments are closed over by one region per + combination of their values. The `out` fields are assigned to in place. + """ - def _run( + def jit( self, - args: tuple[Any, ...], - kwargs: dict[str, Any], - connectivities: dict[str, Any], - static_kwargs: embedded_jit.StaticItems, - static_provider: embedded_jit.StaticItems, - ) -> None: - import torch - import torch.utils._pytree as torch_pytree - - key = (static_kwargs, static_provider) - if (region := self._regions.get(key)) is None: - region = self._regions[key] = self._region(static_kwargs, static_provider) - args, kwargs = torch_pytree.tree_map(_as_region_argument, (args, kwargs)) - try: - region(args, kwargs, connectivities) - except torch._dynamo.exc.Unsupported as unsupported: - if (error := self._embedded_error) is None: - raise - self._embedded_error = None - raise error from unsupported - - -def _as_region_argument(value: Any) -> Any: - import numpy as np - import torch - - # `nonstrict_trace` takes no NumPy scalars. Dynamo specializes on Python integers and - # booleans, as for domain bounds and conditions; a floating-point scalar becomes a 0-d - # tensor, which keeps its dtype. - if isinstance(value, np.bool_ | np.integer): - return value.item() - if isinstance(value, np.generic): - return torch.as_tensor(value) - return value - - -def __getattr__(name: str) -> TorchCompileBackend: - if name != "torch_compile": - raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") - import torch - - from gt4py.next.embedded.array_libraries import ( - torch_ops, # noqa: F401 [unused-import] # registers the pytrees - ) + entry: Callable[..., None], + signature: inspect.Signature, + static_params: Sequence[str], + param_types: Iterable[ts.TypeSpec], + ) -> Callable[..., None]: + for type_ in param_types: + for cls in named_collections.dataclass_types(type_): + torch_ops.register_named_collection(cls) + static_names = frozenset((*static_params, "domain")) + regions: dict[_Static, Callable[..., Any]] = {} + + def run(*args: Any, **kwargs: Any) -> None: + arguments = signature.bind(*args, **kwargs).arguments + connectivities = {} + static_provider = {} + for name, value in arguments.pop("offset_provider").items(): + if isinstance(value, common.Connectivity): + connectivities[name] = value + else: + static_provider[name] = value + static = ( + ("offset_provider", tuple(sorted(static_provider.items()))), + *sorted((name, arguments.pop(name)) for name in static_names & arguments.keys()), + ) + if (region := regions.get(static)) is None: + region = regions[static] = _region(entry, static) + dynamic = torch.utils._pytree.tree_map(_as_region_argument, arguments) + try: + region(dynamic, connectivities) + except torch._dynamo.exc.Unsupported as unsupported: + if (error := _embedded_error.get()) is None: + raise + _embedded_error.set(None) + raise error from unsupported - backend = TorchCompileBackend( - name="torch_compile", - executor=embedded_jit.not_compiled, - allocator=torch, - transforms=next_backend.DEFAULT_TRANSFORMS, - ) - globals()[name] = backend - return backend + return run -torch_compile: TorchCompileBackend +torch_compile = TorchCompileBackend(name="torch_compile", allocator=torch) From 5c8aaef4bedd74255db50919ffa7504d8da43532 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 21:12:43 +0100 Subject: [PATCH 125/166] test[next]: embedded jit backend tests through one seam, the same traced-scalar xfails for both --- tests/next_tests/definitions.py | 26 +++++++++---------- tests/next_tests/integration_tests/cases.py | 4 +-- .../test_embedded_jit_backends.py | 17 +++++++----- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index b72ddd09d8..bcedd321bb 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -13,7 +13,7 @@ import importlib import types from types import ModuleType -from typing import Any, Final, Optional +from typing import Final, Optional import array_api_strict import numpy as np @@ -102,15 +102,14 @@ def __gt_allocate__( torch_cuda_execution = EmbeddedDummyBackend("EmbeddedTorchCUDA", _TorchCUDAAllocator()) -def __getattr__(name: str) -> Any: - if name != "torch_compile_cuda": - raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") - from gt4py.next.program_processors.runners import torch_compile - - backend = globals()[name] = dataclasses.replace( - torch_compile.torch_compile, name="torch_compile_cuda", allocator=_TorchCUDAAllocator() +_torch_compile = _optional_module("gt4py.next.program_processors.runners.torch_compile") +torch_compile_cuda = ( + dataclasses.replace( + _torch_compile.torch_compile, name="torch_compile_cuda", allocator=_TorchCUDAAllocator() ) - return backend + if _torch_compile is not None + else None +) class EmbeddedIds(_PythonObjectIdMixin, str, enum.Enum): @@ -272,15 +271,14 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): JAX_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_PROGRAM_WITH_SLICED_OUT_ARGUMENTS, XFAIL, UNSUPPORTED_MESSAGE), ] -JAX_JIT_SKIP_LIST = JAX_EMBEDDED_SKIP_LIST + [ - # scalar arguments are traced unless they are in `static_params` +#: under a tracing compiler, scalar arguments are traced unless they are in `static_params` +TRACED_SCALARS_SKIP_LIST = [ (USES_SCALAR_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), (USES_SCALAR_IN_DOMAIN, XFAIL, UNSUPPORTED_MESSAGE), (USES_SCAN_CARRY_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), ] -TORCH_COMPILE_SKIP_LIST = EMBEDDED_SKIP_LIST + [ - (USES_SCAN_CARRY_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), -] +JAX_JIT_SKIP_LIST = JAX_EMBEDDED_SKIP_LIST + TRACED_SCALARS_SKIP_LIST +TORCH_COMPILE_SKIP_LIST = EMBEDDED_SKIP_LIST + TRACED_SCALARS_SKIP_LIST ARRAY_API_STRICT_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_MATH_OUTSIDE_ARRAY_API, XFAIL, "Not in the Array API standard."), ] diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index 0171faeec9..cdf282ef79 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -398,9 +398,7 @@ def allocate( def runs_embedded(case: Case) -> bool: """Whether the case's programs run embedded, i.e. are not compiled.""" - from gt4py.next.program_processors.runners import embedded_jit - - return case.backend is None or isinstance(case.backend, embedded_jit.EmbeddedJitBackend) + return case.backend is None or isinstance(case.backend, next_backend.EmbeddedJitBackend) def run( diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py index 031237e6d4..95780d2452 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py @@ -165,7 +165,7 @@ def _e2v(device, table=E2V_TABLE): def _runner(entry_point): - return entry_point._compiled_programs._jitted + return entry_point._jit_entry.jitted def test_program_with_connectivity(device, backend): @@ -190,11 +190,7 @@ def test_table_is_a_runtime_argument(device, backend, jax_only): conn = _e2v(device) prog(f, out, offset_provider={"E2V": conn}) - stablehlo = ( - _runner(prog) - .lower((f, out), {}, {"E2V": conn}, static_kwargs=(), static_provider=()) - .as_text() - ) + stablehlo = _runner(prog).lower(f, out, offset_provider={"E2V": conn}).as_text() main_signature = re.search(r"@main\(([^)]*)\)", stablehlo).group(1) assert "tensor<5x2xi32>" in main_signature @@ -284,6 +280,15 @@ def test_scalar_only_builtins(device, backend): np.testing.assert_array_equal(out.asnumpy(), [0.0, 9.0, 18.0]) +def test_many_int_values_do_not_retrace(device, backend): + f = _field(device, np.arange(3.0), [IDim]) + fo = scalar_builtins.with_backend(backend) + for n in range(10): + out = _field(device, np.zeros(3), [IDim]) + fo(f, 4.0, int32(n), out=out, offset_provider={}) + np.testing.assert_array_equal(out.asnumpy(), (7.0 + n) * np.arange(3.0)) + + def test_scan_with_scalar(device, backend): x = _field(device, np.arange(1.0, 5.0), [KDim]) out = _field(device, np.zeros(4), [KDim]) From 17e58fecc8fd1b19268ca60f90e90883200f12fa Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 21:45:30 +0100 Subject: [PATCH 126/166] refactor[next]: named collections as tuples into the embedded jit backends, aliased fields kept aliased under jax, one rule for static arguments --- src/gt4py/next/backend.py | 8 +- .../next/embedded/array_libraries/jax_ops.py | 12 +- .../embedded/array_libraries/torch_ops.py | 7 -- src/gt4py/next/embedded/array_ops.py | 2 +- src/gt4py/next/embedded/nd_array_field.py | 4 +- src/gt4py/next/embedded/operators.py | 7 +- src/gt4py/next/ffront/decorator.py | 110 ++++++++++++------ src/gt4py/next/ffront/fbuiltins.py | 2 +- src/gt4py/next/ffront/type_info.py | 10 +- src/gt4py/next/named_collections.py | 13 +-- .../program_processors/runners/jax_jit.py | 54 ++++++--- .../runners/torch_compile.py | 20 ++-- 12 files changed, 143 insertions(+), 106 deletions(-) diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 02f14d13fe..b5e97b482a 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -11,7 +11,7 @@ import abc import dataclasses import inspect -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Sequence from typing import Any, Generic from gt4py._core import definitions as core_defs @@ -28,7 +28,6 @@ from gt4py.next.ffront.past_passes import linters as past_linters from gt4py.next.iterator import ir as itir from gt4py.next.otf import arguments, artifacts, stages, toolchain, workflow -from gt4py.next.type_system import type_specifications as ts def jit_to_aot_args( @@ -188,7 +187,7 @@ class EmbeddedJitBackend(Backend, abc.ABC): Runs programs and field operators embedded, inside the tracing compiler of an array library. Instead of compiling, it wraps the embedded entry point of a program or field operator once, - e.g. in `jax.jit`. The allocator is the array namespace of the library. + e.g. in `jax.jit`. The allocator allocates arrays of the library. """ executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] = ( @@ -204,16 +203,15 @@ def jit( entry: Callable[..., None], signature: inspect.Signature, static_params: Sequence[str], - param_types: Iterable[ts.TypeSpec], ) -> Callable[..., None]: """ Wrap `entry`, called as `signature` describes, in the tracing compiler. Args: entry: Runs the program or field operator embedded; it assigns to its `out` fields. + Its arguments are fields, connectivities, scalars and (nested) tuples of them. signature: The parameters of `entry`, including the keyword-only `offset_provider`. static_params: The parameters whose values are compile-time constants. - param_types: The types of the parameters, e.g. to register their named collections. """ ... diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index b3e305351f..7103ad6437 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -25,7 +25,6 @@ from __future__ import annotations import dataclasses -import functools from collections.abc import Callable, Mapping from typing import Any, ClassVar, NamedTuple, Optional @@ -251,14 +250,5 @@ def _unflatten_connectivity( _unflatten_connectivity, ) -# e.g. the `Dimension`s of an offset provider, or a `domain=` argument, in the arguments of `jax.jit` +# e.g. the `Dimension`s of an offset provider in the arguments of `jax.jit` jax.tree_util.register_static(common.Dimension) -jax.tree_util.register_static(common.Domain) - - -@functools.cache -def register_named_collection(cls: type) -> None: - """Make the dataclass named collection `cls` a pytree; the other named collections are tuples.""" - jax.tree_util.register_dataclass( - cls, data_fields=[f.name for f in dataclasses.fields(cls)], meta_fields=[] - ) diff --git a/src/gt4py/next/embedded/array_libraries/torch_ops.py b/src/gt4py/next/embedded/array_libraries/torch_ops.py index 6796333aa4..2a22dbdce4 100644 --- a/src/gt4py/next/embedded/array_libraries/torch_ops.py +++ b/src/gt4py/next/embedded/array_libraries/torch_ops.py @@ -39,7 +39,6 @@ from __future__ import annotations import dataclasses -import functools from collections.abc import Callable, Mapping from types import ModuleType from typing import Any, ClassVar, Optional @@ -321,9 +320,3 @@ def _unflatten_connectivity( _flatten_connectivity, _unflatten_connectivity, ) - - -@functools.cache -def register_named_collection(cls: type) -> None: - """Make the dataclass named collection `cls` a pytree; the other named collections are tuples.""" - torch_pytree.register_dataclass(cls) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 9e30b76e3e..15efec3693 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -270,7 +270,7 @@ def of(array: Any) -> ArrayOps: return ops -def is_scalar(value: Any) -> bool: +def is_scalar_or_0d(value: Any) -> bool: """A scalar, or a 0-d array (e.g. a traced scalar argument under `jax.jit`).""" return core_defs.is_scalar_type(value) or ( getattr(value, "ndim", None) == 0 and array_api_compat.is_array_api_obj(value) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index c6ffdb2765..4c45733ef7 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -69,7 +69,7 @@ def _builtin_op(*fields: common.Field | core_defs.Scalar) -> NdArrayField: arrays.append(array) transformed.append(array) else: - assert array_ops.is_scalar(f) + assert array_ops.is_scalar_or_0d(f) transformed.append(f) if len(arrays) < len(transformed): transformed = [ops.operand(v, arrays[0]) for v in transformed] @@ -348,7 +348,7 @@ def __setitem__( f"Incompatible 'Domain' in assignment. Source domain = '{value.domain}', target domain = '{target_domain}'." ) assigned = value.ndarray - elif isinstance(value, bool | int | float | np.generic) or array_ops.is_scalar(value): + elif isinstance(value, bool | int | float | np.generic) or array_ops.is_scalar_or_0d(value): assigned = value else: raise TypeError( diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index f278815bf3..992f7eda04 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -77,7 +77,8 @@ def scan_loop(hpos: Sequence[common.NamedIndex]) -> None: acc_extracted = arguments.extract(acc) res_extracted = arguments.extract(res) assert all( - array_ops.is_scalar(a) for a in utils.flatten_nested_tuple((acc_extracted,)) + array_ops.is_scalar_or_0d(a) + for a in utils.flatten_nested_tuple((acc_extracted,)) ) assert xtyping.is_maybe_nested_in_tuple_of(res_extracted, common.MutableField) # type: ignore[type-abstract] # MutableField is abstract/generic _tuple_assign_value(pos, res_extracted, acc_extracted) # type: ignore[arg-type] # 0-d arrays are scalars too @@ -163,7 +164,7 @@ def impl(target: common.MutableField, source: common.Field, domain: common.Domai if isinstance(source, common.Field): target[domain] = source[domain] else: - assert array_ops.is_scalar(source) + assert array_ops.is_scalar_or_0d(source) target[domain] = source if not isinstance(domain, tuple): @@ -198,7 +199,7 @@ def _tuple_at( @named_collections.tree_map_named_collection def impl(field: common.Field | core_defs.Scalar) -> core_defs.Scalar: res = field[pos].as_scalar() if isinstance(field, common.Field) else field - assert array_ops.is_scalar(res) + assert array_ops.is_scalar_or_0d(res) return res return impl(field) # type: ignore[return-value] diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index a5c042d573..612f2a66c1 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -32,6 +32,7 @@ custom_layout_allocators as next_allocators, embedded as next_embedded, errors, + named_collections, utils, ) from gt4py.next.embedded import operators as embedded_operators @@ -118,24 +119,50 @@ def __post_init__(self) -> None: def __gt_type__(self) -> ts.CallableType: ... def _jit( - self, entry: Callable[..., None], *keyword_only: inspect.Parameter + self, + entry: Callable[..., None], + *keyword_only: inspect.Parameter, + static_params: Sequence[str] = (), ) -> Callable[..., None]: - """`entry`, the embedded execution, wrapped by the embedded jit backend.""" + """ + `entry`, the embedded execution, wrapped by the embedded jit backend. + + Named collections reach the backend as tuples, which are pytrees in every + library, and `entry` gets them rebuilt. + """ assert isinstance(self.backend, next_backend.EmbeddedJitBackend) - callable_type = self.__gt_type__() - assert isinstance( - callable_type, - ts_ffront.ProgramType | ts_ffront.FieldOperatorType | ts_ffront.ScanOperatorType, - ) - signature: inspect.Signature = ffront_type_info._signature_from_callable_in_program_context( - callable_type - ) - return self.backend.jit( - entry, - signature.replace(parameters=[*signature.parameters.values(), *keyword_only]), - self.compilation_options.static_params or (), - callable_type.definition.pos_or_kw_args.values(), - ) + program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) + assert isinstance(program_type, ts_ffront.ProgramType) + signature: inspect.Signature = ffront_type_info.signature_in_program_context(program_type) + signature = signature.replace(parameters=[*signature.parameters.values(), *keyword_only]) + static_params = (*(self.compilation_options.static_params or ()), *static_params) + params = program_type.definition.pos_or_kw_args | program_type.definition.kw_only_args + constructors = { + name: _named_collection_constructor(type_) + for name, type_ in params.items() + if type_info.needs_value_extraction(type_) + } + if not constructors: + return self.backend.jit(entry, signature, static_params) + + def with_named_collections(**kwargs: Any) -> None: + entry( + **{name: constructors.get(name, _identity)(value) for name, value in kwargs.items()} + ) + + jitted = self.backend.jit(with_named_collections, signature, static_params) + param_names = tuple(program_type.definition.pos_or_kw_args) + + def run(*args: Any, **kwargs: Any) -> None: + kwargs = {**dict(zip(param_names, args)), **kwargs} + jitted( + **{ + name: arguments.extract(value) if name in constructors else value + for name, value in kwargs.items() + } + ) + + return run def with_backend(self, backend: next_backend.Backend | None) -> Self: return dataclasses.replace(self, backend=backend) @@ -353,15 +380,18 @@ def gtir(self) -> itir.Program: ) return self._frontend_transforms.past_to_itir(no_args_past).data + def _run_embedded( + self, *args: Any, offset_provider: common.OffsetProvider, **kwargs: Any + ) -> None: + with next_embedded.context.update(offset_provider=offset_provider): + self.definition_stage.definition(*args, **kwargs) + @functools.cached_property def _jit_entry(self) -> Callable[..., None]: - definition = self.definition_stage.definition - - def run(*args: Any, offset_provider: common.OffsetProvider, **kwargs: Any) -> None: - with next_embedded.context.update(offset_provider=offset_provider): - definition(*args, **kwargs) - - return self._jit(run, inspect.Parameter("offset_provider", inspect.Parameter.KEYWORD_ONLY)) + return self._jit( + self._run_embedded, + inspect.Parameter("offset_provider", inspect.Parameter.KEYWORD_ONLY), + ) def with_grid_type(self, grid_type: common.GridType) -> Program: return dataclasses.replace( @@ -423,9 +453,8 @@ def __call__( stacklevel=2, ) - with next_embedded.context.update(offset_provider=offset_provider): - with embedded_program_call_context(self, args, offset_provider, kwargs): - self.definition_stage.definition(*args, **kwargs) + with embedded_program_call_context(self, args, offset_provider, kwargs): + self._run_embedded(*args, offset_provider=offset_provider, **kwargs) @typing.overload @@ -587,17 +616,16 @@ def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: ) return embedded_operators.EmbeddedOperator(self.definition_stage.definition) + def _run_embedded(self, *args: Any, **kwargs: Any) -> Any: + return embedded_operators.field_operator_call(self._embedded_operator, args, kwargs) + @functools.cached_property def _jit_entry(self) -> Callable[..., None]: - op = self._embedded_operator - - def run(*args: Any, **kwargs: Any) -> None: - embedded_operators.field_operator_call(op, args, kwargs) - return self._jit( - run, + self._run_embedded, inspect.Parameter("domain", inspect.Parameter.KEYWORD_ONLY, default=None), inspect.Parameter("offset_provider", inspect.Parameter.KEYWORD_ONLY), + static_params=("domain",), ) def with_grid_type(self, grid_type: common.GridType) -> FieldOperator: @@ -651,12 +679,28 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> # a `Domain` is static under the tracing compiler, a `dict` is not kwargs["domain"] = utils.tree_map(common.domain)(kwargs["domain"]) return self._jit_entry(*args, **kwargs) - return embedded_operators.field_operator_call(self._embedded_operator, args, kwargs) + return self._run_embedded(*args, **kwargs) GTEntryPoint: TypeAlias = Program | FieldOperator +def _identity(value: Any) -> Any: + return value + + +def _named_collection_constructor(type_: ts.TypeSpec) -> Callable[[Any], Any]: + """Rebuild the named collections of a value of `type_` from the tuples of `arguments.extract`.""" + if isinstance(type_, ts.NamedCollectionType): + return named_collections.make_named_collection_constructor_from_type_spec(type_) + if isinstance(type_, ts.TupleType) and type_info.needs_value_extraction(type_): + constructors = [_named_collection_constructor(element) for element in type_.types] + return lambda values: tuple( + constructor(value) for constructor, value in zip(constructors, values, strict=True) + ) + return _identity + + # TODO(tehrengruber): This class does not follow the Liskov-Substitution principle as it doesn't # have a field operator definition. Currently implementation is merely a hack to keep the only # test relying on this working. Revisit. diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 1f46d6496a..6e74768322 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -286,7 +286,7 @@ def min_over(field: common.Field, /, axis: common.Dimension) -> common.Field: def broadcast( field: common.Field | core_defs.ScalarT, dims: tuple[common.Dimension, ...], / ) -> common.Field: - assert array_ops.is_scalar( + assert array_ops.is_scalar_or_0d( field ) # default implementation for scalars, Fields are handled via dispatch # TODO(havogt) implement with FunctionField, the workaround is to ignore broadcasting on scalars as they broadcast automatically, but we lose the check for compatible dimensions diff --git a/src/gt4py/next/ffront/type_info.py b/src/gt4py/next/ffront/type_info.py index cfe1a51abb..0959524ea3 100644 --- a/src/gt4py/next/ffront/type_info.py +++ b/src/gt4py/next/ffront/type_info.py @@ -391,13 +391,13 @@ def identity(a: IField, *, out: IField) -> None: ... return callable_type -def _signature_from_callable_in_program_context( +def signature_in_program_context( callable_type: ts.CallableType, ) -> inspect.Signature: if isinstance(callable_type, ts_ffront.ProgramType): - return _signature_from_callable_in_program_context(callable_type.definition) + return signature_in_program_context(callable_type.definition) elif isinstance(callable_type, ts_ffront.FieldOperatorType | ts_ffront.ScanOperatorType): - operator_signature = _signature_from_callable_in_program_context(callable_type.definition) + operator_signature = signature_in_program_context(callable_type.definition) params = list(operator_signature.parameters.values()) if isinstance(callable_type, ts_ffront.ScanOperatorType): params = params[1:] # Remove the carry state arg @@ -435,6 +435,4 @@ def make_args_canonicalizer( See :ref:`utils.make_args_canonicalizer`. """ - return utils.make_args_canonicalizer( - _signature_from_callable_in_program_context(callable_type), **kwargs - ) + return utils.make_args_canonicalizer(signature_in_program_context(callable_type), **kwargs) diff --git a/src/gt4py/next/named_collections.py b/src/gt4py/next/named_collections.py index 50297605fb..e2c7c09a52 100644 --- a/src/gt4py/next/named_collections.py +++ b/src/gt4py/next/named_collections.py @@ -13,7 +13,7 @@ import inspect import pkgutil import typing -from collections.abc import Callable, Iterator, Mapping +from collections.abc import Callable, Mapping from typing import Any, Final, TypeAlias, TypeGuard, TypeVar import typing_extensions @@ -394,14 +394,3 @@ def impl( return construct(result) # type: ignore[arg-type] return impl - - -def dataclass_types(type_: ts.TypeSpec) -> Iterator[type]: - """The dataclasses of the named collections in `type_`, e.g. to register them as pytrees.""" - if isinstance(type_, ts.NamedCollectionType): - cls = pkgutil.resolve_name(type_.original_python_type) - if isinstance(cls, type) and dataclasses.is_dataclass(cls): - yield cls - if isinstance(type_, ts.TupleType | ts.NamedCollectionType): - for element_type in type_.types: - yield from dataclass_types(element_type) diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/jax_jit.py index 5e61bf6a22..abaea8bc7c 100644 --- a/src/gt4py/next/program_processors/runners/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/jax_jit.py @@ -10,30 +10,59 @@ Embedded execution of programs and field operators under `jax.jit`. Fields, connectivities and scalars are arguments of the jitted function; the -`Dimension`s of the offset provider, a `domain=` argument and the parameters in -`static_params` are static. +`Dimension`s of the offset provider and the parameters in `static_params` are static. """ from __future__ import annotations import dataclasses import inspect -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Sequence from typing import Any import jax import jax.numpy as jnp -from gt4py.next import backend as next_backend, common, named_collections +from gt4py.next import backend as next_backend, common from gt4py.next.embedded import nd_array_field -from gt4py.next.embedded.array_libraries import jax_ops -from gt4py.next.type_system import type_specifications as ts def _is_field(x: Any) -> bool: return isinstance(x, common.Field) +@dataclasses.dataclass(frozen=True) +class _Alias: + """A field that was passed before, at leaf `index` of the arguments.""" + + index: int + + +jax.tree_util.register_static(_Alias) + + +def _is_field_or_alias(x: Any) -> bool: + return isinstance(x, common.Field | _Alias) + + +def _mark_aliases(tree: Any) -> Any: + leaves, treedef = jax.tree.flatten(tree, is_leaf=_is_field) + first: dict[int, int] = {} + aliased = False + for i, leaf in enumerate(leaves): + if isinstance(leaf, common.Field) and (index := first.setdefault(id(leaf), i)) != i: + leaves[i] = _Alias(index) + aliased = True + return treedef.unflatten(leaves) if aliased else tree + + +def _resolve_aliases(tree: Any) -> Any: + leaves, treedef = jax.tree.flatten(tree, is_leaf=_is_field_or_alias) + return treedef.unflatten( + [leaves[leaf.index] if isinstance(leaf, _Alias) else leaf for leaf in leaves] + ) + + def _assignable_fields(tree: Any) -> list[nd_array_field.NdArrayField]: return [ leaf @@ -50,7 +79,9 @@ class JaxJitBackend(next_backend.EmbeddedJitBackend): JAX arrays are immutable, so an assignment to an `out` field gives it a new buffer: the jitted function returns the new buffer of each field it assigned - to, and the caller's fields get them. + to, and the caller's fields get them. A field passed more than once is one + field in the trace, so its aliases see the assignment. The returned callable has the + `jax.jit` object as its `jitted` attribute, to inspect its traces. """ def jit( @@ -58,15 +89,11 @@ def jit( entry: Callable[..., None], signature: inspect.Signature, static_params: Sequence[str], - param_types: Iterable[ts.TypeSpec], ) -> Callable[..., None]: - for type_ in param_types: - for cls in named_collections.dataclass_types(type_): - jax_ops.register_named_collection(cls) - def traced(*args: Any, **kwargs: Any) -> list[Any]: fields = _assignable_fields((args, kwargs)) buffers = [field.ndarray for field in fields] + args, kwargs = _resolve_aliases((args, kwargs)) entry(*args, **kwargs) return [ field.ndarray if field.ndarray is not buffer else None @@ -77,12 +104,13 @@ def traced(*args: Any, **kwargs: Any) -> list[Any]: jitted = jax.jit(traced, static_argnames=tuple(static_params)) def run(*args: Any, **kwargs: Any) -> None: + args, kwargs = _mark_aliases((args, kwargs)) new_buffers = jitted(*args, **kwargs) for field, buffer in zip(_assignable_fields((args, kwargs)), new_buffers, strict=True): if buffer is not None: field._set_buffer(buffer) - run.jitted = jitted # type: ignore[attr-defined] # to inspect the traces + run.jitted = jitted # type: ignore[attr-defined] return run diff --git a/src/gt4py/next/program_processors/runners/torch_compile.py b/src/gt4py/next/program_processors/runners/torch_compile.py index be41007dd3..84c5bffcb7 100644 --- a/src/gt4py/next/program_processors/runners/torch_compile.py +++ b/src/gt4py/next/program_processors/runners/torch_compile.py @@ -11,8 +11,8 @@ The embedded code runs in a region through a `torch.compiler.nonstrict_trace` function (see `torch_ops`). Fields, connectivities and scalars are arguments of the -region; the `Dimension`s of the offset provider, a `domain=` argument and the -parameters in `static_params` are static. +region; the `Dimension`s of the offset provider and the parameters in +`static_params` are static. """ from __future__ import annotations @@ -20,15 +20,13 @@ import contextvars import dataclasses import inspect -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Sequence from typing import Any import numpy as np import torch -from gt4py.next import backend as next_backend, common, named_collections -from gt4py.next.embedded.array_libraries import torch_ops -from gt4py.next.type_system import type_specifications as ts +from gt4py.next import backend as next_backend, common # Dynamo reports an exception of the embedded code as an unsupported output type @@ -86,12 +84,8 @@ def jit( entry: Callable[..., None], signature: inspect.Signature, static_params: Sequence[str], - param_types: Iterable[ts.TypeSpec], ) -> Callable[..., None]: - for type_ in param_types: - for cls in named_collections.dataclass_types(type_): - torch_ops.register_named_collection(cls) - static_names = frozenset((*static_params, "domain")) + static_names = frozenset(static_params) regions: dict[_Static, Callable[..., Any]] = {} def run(*args: Any, **kwargs: Any) -> None: @@ -110,13 +104,15 @@ def run(*args: Any, **kwargs: Any) -> None: if (region := regions.get(static)) is None: region = regions[static] = _region(entry, static) dynamic = torch.utils._pytree.tree_map(_as_region_argument, arguments) + token = _embedded_error.set(None) try: region(dynamic, connectivities) except torch._dynamo.exc.Unsupported as unsupported: if (error := _embedded_error.get()) is None: raise - _embedded_error.set(None) raise error from unsupported + finally: + _embedded_error.reset(token) return run From 9eed5d982d10ad23bac74972c3f7d21095f884df Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 21:45:30 +0100 Subject: [PATCH 127/166] test[next]: embedded jit backend unit tests next to the other runners, no recompiles checked for torch --- .../test_embedded_jit_backends.py | 330 ------------------ .../runners_tests/test_embedded_jit.py | 305 ++++++++++++++++ 2 files changed, 305 insertions(+), 330 deletions(-) delete mode 100644 tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py create mode 100644 tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py deleted file mode 100644 index 95780d2452..0000000000 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_embedded_jit_backends.py +++ /dev/null @@ -1,330 +0,0 @@ -# GT4Py - GridTools Framework -# -# Copyright (c) 2014-2024, ETH Zurich -# All rights reserved. -# -# Please, refer to the LICENSE file in the root directory. -# SPDX-License-Identifier: BSD-3-Clause - -import re - -import numpy as np -import pytest - -import gt4py.next as gtx -from gt4py.next import astype, common, int32, maximum, neighbor_sum, sqrt -from gt4py.next.ffront.experimental import as_offset - - -IDim = gtx.Dimension("IDim") -KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) -Vertex = gtx.Dimension("Vertex") -Edge = gtx.Dimension("Edge") -E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) -E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) -Ioff = gtx.FieldOffset("Ioff", source=IDim, target=(IDim,)) - -E2V_TABLE = np.asarray([[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]], dtype=np.int32) - - -@gtx.field_operator -def edge_sum(f: gtx.Field[[Vertex], gtx.float64]) -> gtx.Field[[Edge], gtx.float64]: - return neighbor_sum(f(E2V), axis=E2VDim) - - -@gtx.program -def edge_sum_program(f: gtx.Field[[Vertex], gtx.float64], out: gtx.Field[[Edge], gtx.float64]): - edge_sum(f, out=out) - - -@gtx.field_operator -def shift_scale( - f: gtx.Field[[IDim], gtx.float64], a: gtx.float64 -) -> gtx.Field[[IDim], gtx.float64]: - return a * f(IDim + 1) - - -@gtx.program -def shift_scale_program( - f: gtx.Field[[IDim], gtx.float64], a: gtx.float64, out: gtx.Field[[IDim], gtx.float64] -): - shift_scale(f, a, out=out) - - -@gtx.program -def shift_scale_bounded( - f: gtx.Field[[IDim], gtx.float64], - a: gtx.float64, - out: gtx.Field[[IDim], gtx.float64], - stop: int32, -): - shift_scale(f, a, out=out, domain={IDim: (0, stop)}) - - -@gtx.field_operator -def dynamic_shift( - f: gtx.Field[[IDim], gtx.float64], offsets: gtx.Field[[IDim], int32] -) -> gtx.Field[[IDim], gtx.float64]: - return f(as_offset(Ioff, offsets)) - - -@gtx.field_operator -def scalar_builtins( - f: gtx.Field[[IDim], gtx.float64], a: gtx.float64, n: int32 -) -> gtx.Field[[IDim], gtx.float64]: - return (sqrt(a) + maximum(a, 5.0) + astype(n, gtx.float64)) * f - - -@gtx.scan_operator(axis=KDim, forward=True, init=0.0) -def scaled_cumsum(state: gtx.float64, x: gtx.float64, a: gtx.float64) -> gtx.float64: - return state + a * x - - -@gtx.field_operator -def scale_if(f: gtx.Field[[IDim], gtx.float64], flag: bool) -> gtx.Field[[IDim], gtx.float64]: - if flag: - return 2.0 * f - return f - - -@gtx.field_operator -def swap( - a: gtx.Field[[IDim], gtx.float64], b: gtx.Field[[IDim], gtx.float64] -) -> tuple[gtx.Field[[IDim], gtx.float64], gtx.Field[[IDim], gtx.float64]]: - return b, a - - -@pytest.fixture( - params=[ - pytest.param("jax", marks=pytest.mark.requires_jax), - pytest.param("torch", marks=pytest.mark.requires_torch), - ] -) -def library(request): - return request.param - - -@pytest.fixture(params=["cpu", pytest.param("gpu", marks=pytest.mark.requires_gpu)]) -def device(request, library): - if library == "jax": - import jax - - try: - return jax.devices(request.param)[0] - except RuntimeError: - pytest.skip(f"no jax '{request.param}' device") - import torch - - if request.param == "gpu" and not torch.cuda.is_available(): - pytest.skip("no torch CUDA device") - return torch.device("cuda" if request.param == "gpu" else "cpu") - - -@pytest.fixture -def backend(library): - if library == "jax": - from gt4py.next.program_processors.runners import jax_jit - - return jax_jit.jax_jit - from gt4py.next.program_processors.runners import torch_compile - - return torch_compile.torch_compile - - -@pytest.fixture -def jax_only(library): - if library != "jax": - pytest.skip("inspects the 'jax.jit' cache") - - -def _array(device, values): - values = np.asarray(values) - if type(device).__module__.startswith("torch"): - import torch - - return torch.as_tensor(values, device=device) - import jax - - return jax.device_put(values, device) - - -def _field(device, values, dims): - values = np.asarray(values) - return common._field( - _array(device, values), - domain=common.domain({dim: size for dim, size in zip(dims, values.shape)}), - ) - - -def _e2v(device, table=E2V_TABLE): - return common._connectivity( - _array(device, table), - codomain=Vertex, - domain=common.domain({Edge: table.shape[0], E2VDim: table.shape[1]}), - ) - - -def _runner(entry_point): - return entry_point._jit_entry.jitted - - -def test_program_with_connectivity(device, backend): - f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) - out = _field(device, np.zeros(5), [Edge]) - expected = _field(device, np.zeros(5), [Edge]) - conn = _e2v(device) - out_object = out - - edge_sum_program.with_backend(backend)(f, out, offset_provider={"E2V": conn}) - edge_sum_program(f, expected, offset_provider={"E2V": conn}) - - assert out is out_object - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - np.testing.assert_array_equal(out.asnumpy(), [3.0, 5.0, 7.0, 5.0, 4.0]) - - -def test_table_is_a_runtime_argument(device, backend, jax_only): - f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) - out = _field(device, np.zeros(5), [Edge]) - prog = edge_sum_program.with_backend(backend) - conn = _e2v(device) - prog(f, out, offset_provider={"E2V": conn}) - - stablehlo = _runner(prog).lower(f, out, offset_provider={"E2V": conn}).as_text() - main_signature = re.search(r"@main\(([^)]*)\)", stablehlo).group(1) - assert "tensor<5x2xi32>" in main_signature - - -def test_retrace_per_table_buffer(device, backend, jax_only): - f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) - out = _field(device, np.zeros(5), [Edge]) - prog = edge_sum_program.with_backend(backend) - conn = _e2v(device) - - prog(f, out, offset_provider={"E2V": conn}) - prog(_field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), out, offset_provider={"E2V": conn}) - assert _runner(prog)._cache_size() == 1 - np.testing.assert_array_equal(out.asnumpy(), [7.0, 5.0, 3.0, 5.0, 6.0]) - - prog(f, out, offset_provider={"E2V": _e2v(device, E2V_TABLE.copy())}) - assert _runner(prog)._cache_size() == 2 - - -def test_traced_scalar_does_not_retrace(device, backend, jax_only): - f = _field(device, np.arange(6.0), [IDim]) - prog = shift_scale_program.with_backend(backend) - for a in (2.0, 3.0): - prog(f, a, _field(device, np.zeros(5), [IDim]), offset_provider={}) - - assert _runner(prog)._cache_size() == 1 - - -def test_cartesian_offset_and_scalar(device, backend): - f = _field(device, np.arange(6.0), [IDim]) - prog = shift_scale_program.with_backend(backend) - for a in (2.0, 3.0): - out = _field(device, np.zeros(5), [IDim]) - expected = _field(device, np.zeros(5), [IDim]) - prog(f, a, out, offset_provider={}) - shift_scale_program(f, a, expected, offset_provider={}) - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - - -def test_static_param_in_program_domain(device, backend): - f = _field(device, np.arange(6.0), [IDim]) - prog = shift_scale_bounded.with_backend(backend).with_static_params("stop") - out = _field(device, np.full(5, -1.0), [IDim]) - expected = _field(device, np.full(5, -1.0), [IDim]) - - prog(f, 2.0, out, 3, offset_provider={}) - shift_scale_bounded(f, 2.0, expected, 3, offset_provider={}) - - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - np.testing.assert_array_equal(out.asnumpy(), [2.0, 4.0, 6.0, -1.0, -1.0]) - - -def test_field_operator_out_and_domain(device, backend): - f = _field(device, np.arange(6.0), [IDim]) - out = _field(device, np.full(5, -1.0), [IDim]) - expected = _field(device, np.full(5, -1.0), [IDim]) - - shift_scale.with_backend(backend)(f, 2.0, out=out, offset_provider={}, domain={IDim: (1, 4)}) - shift_scale(f, 2.0, out=expected, offset_provider={}, domain={IDim: (1, 4)}) - - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - np.testing.assert_array_equal(out.asnumpy(), [-1.0, 4.0, 6.0, 8.0, -1.0]) - - -def test_dimension_in_offset_provider_is_static(device, backend): - f = _field(device, np.arange(6.0), [IDim]) - offsets = _field(device, np.asarray([1, 0, 2, 1, 0], dtype=np.int32), [IDim]) - out = _field(device, np.zeros(5), [IDim]) - expected = _field(device, np.zeros(5), [IDim]) - - dynamic_shift.with_backend(backend)(f, offsets, out=out, offset_provider={"Ioff": IDim}) - dynamic_shift(f, offsets, out=expected, offset_provider={"Ioff": IDim}) - - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - np.testing.assert_array_equal(out.asnumpy(), [1.0, 1.0, 4.0, 4.0, 4.0]) - - -def test_scalar_only_builtins(device, backend): - f = _field(device, np.arange(3.0), [IDim]) - out = _field(device, np.zeros(3), [IDim]) - expected = _field(device, np.zeros(3), [IDim]) - - scalar_builtins.with_backend(backend)(f, 4.0, int32(2), out=out, offset_provider={}) - scalar_builtins(f, 4.0, int32(2), out=expected, offset_provider={}) - - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - np.testing.assert_array_equal(out.asnumpy(), [0.0, 9.0, 18.0]) - - -def test_many_int_values_do_not_retrace(device, backend): - f = _field(device, np.arange(3.0), [IDim]) - fo = scalar_builtins.with_backend(backend) - for n in range(10): - out = _field(device, np.zeros(3), [IDim]) - fo(f, 4.0, int32(n), out=out, offset_provider={}) - np.testing.assert_array_equal(out.asnumpy(), (7.0 + n) * np.arange(3.0)) - - -def test_scan_with_scalar(device, backend): - x = _field(device, np.arange(1.0, 5.0), [KDim]) - out = _field(device, np.zeros(4), [KDim]) - expected = _field(device, np.zeros(4), [KDim]) - - scaled_cumsum.with_backend(backend)(x, 2.0, out=out, offset_provider={}) - scaled_cumsum(x, 2.0, out=expected, offset_provider={}) - - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - np.testing.assert_array_equal(out.asnumpy(), [2.0, 6.0, 12.0, 20.0]) - - -def test_static_param_of_field_operator(device, backend): - f = _field(device, np.arange(3.0), [IDim]) - fo = scale_if.with_backend(backend).with_compilation_options(static_params=("flag",)) - for flag in (True, False): - out = _field(device, np.zeros(3), [IDim]) - expected = _field(device, np.zeros(3), [IDim]) - fo(f, flag, out=out, offset_provider={}) - scale_if(f, flag, out=expected, offset_provider={}) - np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) - - -def test_field_operator_tuple_out_leaves_inputs(device, backend): - a = _field(device, np.arange(3.0), [IDim]) - b = _field(device, np.arange(3.0) + 10, [IDim]) - a_buffer, b_buffer = a.ndarray, b.ndarray - out = (_field(device, np.zeros(3), [IDim]), _field(device, np.zeros(3), [IDim])) - - swap.with_backend(backend)(a, b, out=out, offset_provider={}) - - assert a.ndarray is a_buffer and b.ndarray is b_buffer - np.testing.assert_array_equal(out[0].asnumpy(), b.asnumpy()) - np.testing.assert_array_equal(out[1].asnumpy(), a.asnumpy()) - - -def test_compile_is_rejected(backend): - with pytest.raises(RuntimeError, match="does not compile"): - edge_sum_program.with_backend(backend).compile(offset_provider={"E2V": None}) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py new file mode 100644 index 0000000000..b3f3c6184b --- /dev/null +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py @@ -0,0 +1,305 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""What the embedded jit backends add to embedded execution; the integration matrix runs the features.""" + +import dataclasses +import re + +import numpy as np +import pytest + +import gt4py.next as gtx +from gt4py.next import astype, broadcast, common, int32, neighbor_sum + + +IDim = gtx.Dimension("IDim") +Vertex = gtx.Dimension("Vertex") +Edge = gtx.Dimension("Edge") +E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) +E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) + +E2V_TABLE = np.asarray([[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]], dtype=np.int32) + + +@dataclasses.dataclass +class Pair: + first: gtx.Field[[IDim], gtx.float64] + second: gtx.Field[[IDim], gtx.float64] + + +@gtx.field_operator +def edge_sum(f: gtx.Field[[Vertex], gtx.float64]) -> gtx.Field[[Edge], gtx.float64]: + return neighbor_sum(f(E2V), axis=E2VDim) + + +@gtx.program +def edge_sum_program(f: gtx.Field[[Vertex], gtx.float64], out: gtx.Field[[Edge], gtx.float64]): + edge_sum(f, out=out) + + +@gtx.field_operator +def scale(f: gtx.Field[[IDim], gtx.float64], n: int32) -> gtx.Field[[IDim], gtx.float64]: + return astype(n, gtx.float64) * f + + +@gtx.program +def scale_bounded( + f: gtx.Field[[IDim], gtx.float64], out: gtx.Field[[IDim], gtx.float64], stop: int32 +): + scale(f, 2, out=out, domain={IDim: (0, stop)}) + + +@gtx.field_operator +def scale_if(f: gtx.Field[[IDim], gtx.float64], flag: bool) -> gtx.Field[[IDim], gtx.float64]: + if flag: + return 2.0 * f + return f + + +@gtx.field_operator +def split(f: gtx.Field[[IDim], gtx.float64]) -> Pair: + return Pair(first=f, second=2.0 * f) + + +@gtx.field_operator +def plus_one(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + 1.0 + + +@gtx.field_operator +def identity(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + + +@gtx.program +def write_then_read( + a: gtx.Field[[IDim], gtx.float64], + b: gtx.Field[[IDim], gtx.float64], + out: gtx.Field[[IDim], gtx.float64], +): + plus_one(a, out=a) + identity(b, out=out) + + +@gtx.field_operator +def infinity() -> gtx.Field[[IDim], gtx.float64]: + return broadcast(1.0 / 0.0, (IDim,)) + + +@pytest.fixture( + params=[ + pytest.param("jax", marks=pytest.mark.requires_jax), + pytest.param("torch", marks=pytest.mark.requires_torch), + ] +) +def library(request): + return request.param + + +@pytest.fixture(params=["cpu", pytest.param("gpu", marks=pytest.mark.requires_gpu)]) +def device(request, library): + if library == "jax": + import jax + + try: + return jax.devices(request.param)[0] + except RuntimeError: + pytest.skip(f"no jax '{request.param}' device") + import torch + + if request.param == "gpu" and not torch.cuda.is_available(): + pytest.skip("no torch CUDA device") + return torch.device("cuda" if request.param == "gpu" else "cpu") + + +@pytest.fixture +def backend(library): + if library == "jax": + from gt4py.next.program_processors.runners import jax_jit + + return jax_jit.jax_jit + from gt4py.next.program_processors.runners import torch_compile + + return torch_compile.torch_compile + + +@pytest.fixture +def no_recompiles(library): + """Fail on a second trace of the same entry point.""" + if library == "jax": + yield + return + import torch + + with torch._dynamo.config.patch(recompile_limit=1, fail_on_recompile_limit_hit=True): + yield + + +def _array(device, values): + values = np.asarray(values) + if type(device).__module__.startswith("torch"): + import torch + + return torch.as_tensor(values, device=device) + import jax + + return jax.device_put(values, device) + + +def _field(device, values, dims): + values = np.asarray(values) + return common._field( + _array(device, values), + domain=common.domain({dim: size for dim, size in zip(dims, values.shape)}), + ) + + +def _e2v(device, table=E2V_TABLE): + return common._connectivity( + _array(device, table), + codomain=Vertex, + domain=common.domain({Edge: table.shape[0], E2VDim: table.shape[1]}), + ) + + +def _jitted(entry_point): + return entry_point._jit_entry.jitted + + +def test_out_assigned_in_the_callers_field(device, backend): + f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) + f_buffer = f.ndarray + out = _field(device, np.zeros(5), [Edge]) + out_object = out + + edge_sum_program.with_backend(backend)(f, out, offset_provider={"E2V": _e2v(device)}) + + assert out is out_object and f.ndarray is f_buffer + np.testing.assert_array_equal(out.asnumpy(), [3.0, 5.0, 7.0, 5.0, 4.0]) + + +@pytest.mark.requires_jax +def test_table_is_a_runtime_argument(): + import jax + + device = jax.devices("cpu")[0] + f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) + out = _field(device, np.zeros(5), [Edge]) + from gt4py.next.program_processors.runners import jax_jit + + prog = edge_sum_program.with_backend(jax_jit.jax_jit) + conn = _e2v(device) + prog(f, out, offset_provider={"E2V": conn}) + + stablehlo = _jitted(prog).lower(f, out, offset_provider={"E2V": conn}).as_text() + assert "tensor<5x2xi32>" in re.search(r"@main\(([^)]*)\)", stablehlo).group(1) + + +@pytest.mark.requires_jax +def test_retrace_per_table_buffer(): + import jax + + from gt4py.next.program_processors.runners import jax_jit + + device = jax.devices("cpu")[0] + out = _field(device, np.zeros(5), [Edge]) + prog = edge_sum_program.with_backend(jax_jit.jax_jit) + conn = _e2v(device) + + prog(_field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]), out, offset_provider={"E2V": conn}) + prog(_field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), out, offset_provider={"E2V": conn}) + assert _jitted(prog)._cache_size() == 1 + + prog( + _field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), + out, + offset_provider={"E2V": _e2v(device, E2V_TABLE.copy())}, + ) + assert _jitted(prog)._cache_size() == 2 + + +def test_scalar_values_do_not_retrace(device, backend, no_recompiles): + f = _field(device, np.arange(3.0), [IDim]) + fo = scale.with_backend(backend) + for n in range(10): + out = _field(device, np.zeros(3), [IDim]) + fo(f, int32(n), out=out, offset_provider={}) + np.testing.assert_array_equal(out.asnumpy(), n * np.arange(3.0)) + + +def test_static_param_of_program(device, backend): + f = _field(device, np.arange(5.0), [IDim]) + out = _field(device, np.full(5, -1.0), [IDim]) + + scale_bounded.with_backend(backend).with_static_params("stop")(f, out, 3, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), [0.0, 2.0, 4.0, -1.0, -1.0]) + + +def test_static_param_of_field_operator(device, backend): + f = _field(device, np.arange(3.0), [IDim]) + fo = scale_if.with_backend(backend).with_compilation_options(static_params=("flag",)) + for flag, factor in ((True, 2.0), (False, 1.0)): + out = _field(device, np.zeros(3), [IDim]) + fo(f, flag, out=out, offset_provider={}) + np.testing.assert_array_equal(out.asnumpy(), factor * np.arange(3.0)) + + +def test_domain_of_field_operator_writes_into_out(device, backend): + f = _field(device, np.arange(5.0), [IDim]) + out = _field(device, np.full(5, -1.0), [IDim]) + + scale.with_backend(backend)(f, int32(3), out=out, domain={IDim: (1, 4)}, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), [-1.0, 3.0, 6.0, 9.0, -1.0]) + + +def test_dataclass_only_as_out(device, backend): + f = _field(device, np.arange(3.0), [IDim]) + out = Pair( + first=_field(device, np.zeros(3), [IDim]), second=_field(device, np.zeros(3), [IDim]) + ) + + split.with_backend(backend)(f, out=out, offset_provider={}) + + np.testing.assert_array_equal(out.first.asnumpy(), np.arange(3.0)) + np.testing.assert_array_equal(out.second.asnumpy(), 2.0 * np.arange(3.0)) + + +def test_aliases_see_the_assignment(device, backend): + a = _field(device, np.arange(3.0), [IDim]) + out = _field(device, np.zeros(3), [IDim]) + expected_a = _field(device, np.arange(3.0), [IDim]) + expected = _field(device, np.zeros(3), [IDim]) + + write_then_read.with_backend(backend)(a, a, out, offset_provider={}) + write_then_read(expected_a, expected_a, expected, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(a.asnumpy(), expected_a.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), np.arange(3.0) + 1.0) + + +def test_error_of_the_embedded_code_is_raised(device, backend): + out = _field(device, np.zeros(3), [IDim]) + + with pytest.raises(ZeroDivisionError): + infinity.with_backend(backend)(out=out, offset_provider={}) + + +def test_missing_out_is_rejected(device, backend): + with pytest.raises(gtx.errors.MissingArgumentError, match="'out'"): + scale.with_backend(backend)( + _field(device, np.arange(3.0), [IDim]), int32(1), offset_provider={} + ) + + +def test_compile_is_rejected(backend): + with pytest.raises(RuntimeError, match="does not compile"): + edge_sum_program.with_backend(backend).compile(offset_provider={"E2V": None}) From 2048a3d0d02c31c555c0fee50b5089c32ab7cdcf Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Fri, 20 Nov 2026 21:45:30 +0100 Subject: [PATCH 128/166] docs[next]: ADR 0030 on the embedded jit backends --- .../ADRs/next/0030-Embedded-Jit-Backends.md | 50 +++++++++++++++++++ docs/development/ADRs/next/README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 docs/development/ADRs/next/0030-Embedded-Jit-Backends.md diff --git a/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md b/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md new file mode 100644 index 0000000000..6c93ae9d50 --- /dev/null +++ b/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md @@ -0,0 +1,50 @@ +--- +tags: [embedded, backend, jax, torch] +--- + +# Embedded Jit Backends + +- **Status**: valid +- **Authors**: Hannes Vogt (@havogt) +- **Created**: 2026-11-20 +- **Updated**: 2026-11-20 + +In the context of running programs and field operators on JAX arrays or torch tensors with the speed of the library's compiler, facing that embedded execution is plain Python and compiled backends do not take these arrays, we decided to add backends that wrap the embedded execution of an entry point in the library's tracing compiler (`jax.jit`, `torch.compile`), to get compiled programs without writing jax or torch code. We accept that scalar arguments are traced, so Python control flow or a domain bound on one needs `static_params`. + +## Context + +Embedded execution runs the definition of a program on fields of any array library. Under `jax.jit` or `torch.compile` it traces into a single compiled function, and ADR 0029 makes connectivities runtime arguments of it. The user had to write the jit wrapper by hand: split the offset provider, return the new `out` buffers (JAX arrays are immutable), and keep the wrapper cached. + +## Decision + +`EmbeddedJitBackend` (in `gt4py.next.backend`) is a `Backend` that does not compile: its `jit(entry, signature, static_params)` wraps the embedded entry point once. There are two instances, `runners.jax_jit.jax_jit` and `runners.torch_compile.torch_compile`. + +- **Dispatch**: an entry point with such a backend takes the embedded path and calls its cached jitted entry. Whether an entry point is compiled is an attribute set at creation, so the call of a compiled backend costs what it did. `.compile()` raises. +- **Arguments**: fields and connectivities (pytrees, ADR 0029) and scalars are traced. The `Dimension`s of the offset provider and the parameters in `static_params` are static; for a field operator called with `out=`, so is `domain`. +- **Named collections** reach the backend as tuples and are rebuilt inside, as the compiled path extracts them: no user type is registered as a pytree. +- **`out`**: under jax the jitted function returns the new buffers of the fields it assigned to, which the caller's fields get; a field passed twice and assigned to is rejected. Under torch the assignment is in place. +- **Embedded changes**: a traced scalar is a 0-d array, so embedded accepts 0-d arrays where it accepts scalars, and the element of a 0-d traced array stays an array (`ArrayOps.scalar`). + +torch specifics, all from Dynamo: the embedded code runs through `nonstrict_trace`, which takes neither NumPy scalars nor frozen dataclasses, so scalars become 0-d tensors and the static arguments are closed over by one region per combination of their values. Each region gets its own code object, since Dynamo's recompile limit counts per code object. An exception of the embedded code is re-raised as itself. + +## Consequences + +- A program on jax or torch fields is compiled by `with_backend(jax_jit)` or `with_backend(torch_compile)`. +- A scalar that the embedded code needs concretely (an `if`, a domain bound, a scan carry in a condition) fails under tracing unless it is in `static_params`; the test matrix marks such tests (`uses_scalar_in_control_flow`, `uses_scalar_in_domain`, `uses_scan_carry_in_control_flow`). +- Retracing: per field domain and per table buffer (ADR 0029), per value of a static parameter. torch allows 8 recompiles per region. +- Embedded scans loop per column and level, so their trace grows with the size of the domain. +- The embedded-program hook wraps the jitted call, so it runs per call, not per trace. + +## Alternatives considered + +### Jit backends as compiled backends + +Entering through the compiled programs pool needs the embedded context set up again, a special case for `domain=` on the compiled path, and skips the embedded hook. + +### Registering named collections as pytrees + +Mutates the global pytree registry for user types, conflicts with a user's own registration, and misses types that appear only as `out`. + +### Specialized scalars under torch + +Dynamo's default: every new value of an integer recompiles, and the recompile limit is reached by, e.g., a time-step counter. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index 9132ffe478..e23185378b 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -39,6 +39,7 @@ Writing a new ADR is simple: - [0022 - Limitations of embedded concat_where](0022-Limitations-of-embedded-concat_where.md) - [0029 - Connectivities in Tracing Embedded Backends](0029-Connectivities_in_Tracing_Embedded_Backends.md) +- [0030 - Embedded Jit Backends](0030-Embedded-Jit-Backends.md) ### Transformations From 6ffadaf3835a5bf205f85cdbb4719cb00189a1c7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Sun, 22 Nov 2026 19:21:30 +0100 Subject: [PATCH 129/166] refactor[next]: a single dispatch hook for embedded jit backends in the decorator, the shared part in runners.embedded_jit --- src/gt4py/next/backend.py | 29 ++-- src/gt4py/next/ffront/decorator.py | 153 ++++-------------- .../runners/embedded_jit.py | 120 ++++++++++++++ .../program_processors/runners/jax_jit.py | 17 +- .../runners/torch_compile.py | 12 +- 5 files changed, 186 insertions(+), 145 deletions(-) create mode 100644 src/gt4py/next/program_processors/runners/embedded_jit.py diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index b5e97b482a..ab38db8ac4 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -10,9 +10,8 @@ import abc import dataclasses -import inspect -from collections.abc import Callable, Sequence -from typing import Any, Generic +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, Generic from gt4py._core import definitions as core_defs from gt4py.next import config, custom_layout_allocators as next_allocators @@ -30,6 +29,10 @@ from gt4py.next.otf import arguments, artifacts, stages, toolchain, workflow +if TYPE_CHECKING: + from gt4py.next.ffront import decorator as ffront_decorator + + def jit_to_aot_args( inp: arguments.JITArgs, ) -> arguments.CompileTimeArgs: @@ -186,8 +189,9 @@ class EmbeddedJitBackend(Backend, abc.ABC): """ Runs programs and field operators embedded, inside the tracing compiler of an array library. - Instead of compiling, it wraps the embedded entry point of a program or field operator once, - e.g. in `jax.jit`. The allocator allocates arrays of the library. + Instead of compiling, it wraps the embedded execution of a program or field operator once, + e.g. in `jax.jit`. The allocator allocates arrays of the library. A stopgap until embedded + execution is represented by backends (ADR 0030). """ executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] = ( @@ -198,20 +202,11 @@ class EmbeddedJitBackend(Backend, abc.ABC): ) @abc.abstractmethod - def jit( - self, - entry: Callable[..., None], - signature: inspect.Signature, - static_params: Sequence[str], - ) -> Callable[..., None]: + def jit(self, entry_point: ffront_decorator.GTEntryPoint) -> Callable[..., None]: """ - Wrap `entry`, called as `signature` describes, in the tracing compiler. + `entry_point` run embedded inside the tracing compiler, called as the entry point is. - Args: - entry: Runs the program or field operator embedded; it assigns to its `out` fields. - Its arguments are fields, connectivities, scalars and (nested) tuples of them. - signature: The parameters of `entry`, including the keyword-only `offset_provider`. - static_params: The parameters whose values are compile-time constants. + Called once per entry point: the result is cached by it. """ ... diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 612f2a66c1..890e084827 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -16,7 +16,6 @@ import contextlib import dataclasses import functools -import inspect import types import typing import warnings @@ -32,7 +31,6 @@ custom_layout_allocators as next_allocators, embedded as next_embedded, errors, - named_collections, utils, ) from gt4py.next.embedded import operators as embedded_operators @@ -102,7 +100,7 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): metadata=utils.gt4py_metadata(fingerprint=False) ) compilation_options: options.CompilationOptions - # an attribute, not a cached property, to cost the call no more than `backend is not None` + # an attribute, not a property, to cost the call no more than `backend is not None` _is_compiled: bool = dataclasses.field( init=False, repr=False, compare=False, metadata=utils.gt4py_metadata(fingerprint=False) ) @@ -115,54 +113,14 @@ def __post_init__(self) -> None: and not isinstance(self.backend, next_backend.EmbeddedJitBackend), ) - @abc.abstractmethod - def __gt_type__(self) -> ts.CallableType: ... - - def _jit( - self, - entry: Callable[..., None], - *keyword_only: inspect.Parameter, - static_params: Sequence[str] = (), - ) -> Callable[..., None]: - """ - `entry`, the embedded execution, wrapped by the embedded jit backend. - - Named collections reach the backend as tuples, which are pytrees in every - library, and `entry` gets them rebuilt. - """ + @functools.cached_property + def _embedded_jit(self) -> Callable[..., None]: + """This entry point run embedded inside the tracing compiler of its embedded jit backend.""" assert isinstance(self.backend, next_backend.EmbeddedJitBackend) - program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) - assert isinstance(program_type, ts_ffront.ProgramType) - signature: inspect.Signature = ffront_type_info.signature_in_program_context(program_type) - signature = signature.replace(parameters=[*signature.parameters.values(), *keyword_only]) - static_params = (*(self.compilation_options.static_params or ()), *static_params) - params = program_type.definition.pos_or_kw_args | program_type.definition.kw_only_args - constructors = { - name: _named_collection_constructor(type_) - for name, type_ in params.items() - if type_info.needs_value_extraction(type_) - } - if not constructors: - return self.backend.jit(entry, signature, static_params) - - def with_named_collections(**kwargs: Any) -> None: - entry( - **{name: constructors.get(name, _identity)(value) for name, value in kwargs.items()} - ) - - jitted = self.backend.jit(with_named_collections, signature, static_params) - param_names = tuple(program_type.definition.pos_or_kw_args) + return self.backend.jit(typing.cast(GTEntryPoint, self)) - def run(*args: Any, **kwargs: Any) -> None: - kwargs = {**dict(zip(param_names, args)), **kwargs} - jitted( - **{ - name: arguments.extract(value) if name in constructors else value - for name, value in kwargs.items() - } - ) - - return run + @abc.abstractmethod + def __gt_type__(self) -> ts.CallableType: ... def with_backend(self, backend: next_backend.Backend | None) -> Self: return dataclasses.replace(self, backend=backend) @@ -380,19 +338,6 @@ def gtir(self) -> itir.Program: ) return self._frontend_transforms.past_to_itir(no_args_past).data - def _run_embedded( - self, *args: Any, offset_provider: common.OffsetProvider, **kwargs: Any - ) -> None: - with next_embedded.context.update(offset_provider=offset_provider): - self.definition_stage.definition(*args, **kwargs) - - @functools.cached_property - def _jit_entry(self) -> Callable[..., None]: - return self._jit( - self._run_embedded, - inspect.Parameter("offset_provider", inspect.Parameter.KEYWORD_ONLY), - ) - def with_grid_type(self, grid_type: common.GridType) -> Program: return dataclasses.replace( self, definition_stage=dataclasses.replace(self.definition_stage, grid_type=grid_type) @@ -443,7 +388,7 @@ def __call__( ) elif self.backend is not None: with embedded_program_call_context(self, args, offset_provider, kwargs): - self._jit_entry(*args, offset_provider=offset_provider, **kwargs) + self._embedded_jit(*args, offset_provider=offset_provider, **kwargs) else: # Embedded execution. warnings.warn( @@ -453,8 +398,9 @@ def __call__( stacklevel=2, ) - with embedded_program_call_context(self, args, offset_provider, kwargs): - self._run_embedded(*args, offset_provider=offset_provider, **kwargs) + with next_embedded.context.update(offset_provider=offset_provider): + with embedded_program_call_context(self, args, offset_provider, kwargs): + self.definition_stage.definition(*args, **kwargs) @typing.overload @@ -595,39 +541,6 @@ def __gt_type__(self) -> ts.CallableType: assert isinstance(type_, ts.CallableType) return type_ - @functools.cached_property - def _embedded_operator(self) -> embedded_operators.EmbeddedOperator: - attributes = ( - self.definition_stage.attributes - if self.definition_stage - else self.foast_stage.attributes - ) - if attributes is not None and any( - has_scan_op_attribute := [ - attribute in attributes for attribute in ["init", "axis", "forward"] - ] - ): - assert all(has_scan_op_attribute) - return embedded_operators.ScanOperator( - self.definition_stage.definition, - attributes["forward"], - attributes["init"], - attributes["axis"], - ) - return embedded_operators.EmbeddedOperator(self.definition_stage.definition) - - def _run_embedded(self, *args: Any, **kwargs: Any) -> Any: - return embedded_operators.field_operator_call(self._embedded_operator, args, kwargs) - - @functools.cached_property - def _jit_entry(self) -> Callable[..., None]: - return self._jit( - self._run_embedded, - inspect.Parameter("domain", inspect.Parameter.KEYWORD_ONLY, default=None), - inspect.Parameter("offset_provider", inspect.Parameter.KEYWORD_ONLY), - static_params=("domain",), - ) - def with_grid_type(self, grid_type: common.GridType) -> FieldOperator: return dataclasses.replace( self, definition_stage=dataclasses.replace(self.definition_stage, grid_type=grid_type) @@ -673,34 +586,32 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> # field_operator as program kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} if self.backend is not None: - if "out" not in kwargs: - raise errors.MissingArgumentError(None, "out", True) - if "domain" in kwargs: - # a `Domain` is static under the tracing compiler, a `dict` is not - kwargs["domain"] = utils.tree_map(common.domain)(kwargs["domain"]) - return self._jit_entry(*args, **kwargs) - return self._run_embedded(*args, **kwargs) + return self._embedded_jit(*args, **kwargs) + attributes = ( + self.definition_stage.attributes + if self.definition_stage + else self.foast_stage.attributes + ) + if attributes is not None and any( + has_scan_op_attribute := [ + attribute in attributes for attribute in ["init", "axis", "forward"] + ] + ): + assert all(has_scan_op_attribute) + forward = attributes["forward"] + init = attributes["init"] + axis = attributes["axis"] + op: embedded_operators.EmbeddedOperator = embedded_operators.ScanOperator( + self.definition_stage.definition, forward, init, axis + ) + else: + op = embedded_operators.EmbeddedOperator(self.definition_stage.definition) + return embedded_operators.field_operator_call(op, args, kwargs) GTEntryPoint: TypeAlias = Program | FieldOperator -def _identity(value: Any) -> Any: - return value - - -def _named_collection_constructor(type_: ts.TypeSpec) -> Callable[[Any], Any]: - """Rebuild the named collections of a value of `type_` from the tuples of `arguments.extract`.""" - if isinstance(type_, ts.NamedCollectionType): - return named_collections.make_named_collection_constructor_from_type_spec(type_) - if isinstance(type_, ts.TupleType) and type_info.needs_value_extraction(type_): - constructors = [_named_collection_constructor(element) for element in type_.types] - return lambda values: tuple( - constructor(value) for constructor, value in zip(constructors, values, strict=True) - ) - return _identity - - # TODO(tehrengruber): This class does not follow the Liskov-Substitution principle as it doesn't # have a field operator definition. Currently implementation is merely a hack to keep the only # test relying on this working. Revisit. diff --git a/src/gt4py/next/program_processors/runners/embedded_jit.py b/src/gt4py/next/program_processors/runners/embedded_jit.py new file mode 100644 index 0000000000..813ace56fe --- /dev/null +++ b/src/gt4py/next/program_processors/runners/embedded_jit.py @@ -0,0 +1,120 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +What the embedded jit backends share: the embedded execution of an entry point, as they wrap it. + +A stopgap until embedded execution is represented by backends (ADR 0030). +""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any, TypeAlias + +from gt4py.next import common, errors, named_collections, utils +from gt4py.next.embedded import context as embedded_context +from gt4py.next.ffront import type_info as ffront_type_info, type_specifications as ts_ffront +from gt4py.next.otf import arguments +from gt4py.next.type_system import type_info, type_specifications as ts + + +if TYPE_CHECKING: + from gt4py.next.ffront import decorator + + +#: Wraps the embedded execution, called as the signature describes, in a tracing compiler, with +#: the named parameters static. The arguments are fields, connectivities, scalars and (nested) +#: tuples of them. +Wrap: TypeAlias = Callable[ + [Callable[..., None], inspect.Signature, Sequence[str]], Callable[..., None] +] + + +def jit(entry_point: decorator.GTEntryPoint, wrap: Wrap) -> Callable[..., None]: + """`entry_point` run embedded in the tracing compiler of `wrap`, called as the entry point is.""" + callable_type = entry_point.__gt_type__() + program_type = ffront_type_info.type_in_program_context(callable_type) + assert isinstance(program_type, ts_ffront.ProgramType) + is_program = isinstance(callable_type, ts_ffront.ProgramType) + + signature = ffront_type_info.signature_in_program_context(program_type) + keyword_only = [ + *([] if is_program else [_keyword_only("domain", default=None)]), + _keyword_only("offset_provider"), + ] + signature = signature.replace(parameters=[*signature.parameters.values(), *keyword_only]) + static_params = ( + *(entry_point.compilation_options.static_params or ()), + *([] if is_program else ["domain"]), + ) + + # a field operator called in an embedded context runs embedded + run = entry_point.definition_stage.definition if is_program else entry_point + + def run_embedded(*args: Any, offset_provider: common.OffsetProvider, **kwargs: Any) -> None: + with embedded_context.update(offset_provider=offset_provider): + run(*args, **kwargs) + + # named collections reach the tracing compiler as tuples, which are pytrees in every library + params = program_type.definition.pos_or_kw_args | program_type.definition.kw_only_args + constructors = { + name: _named_collection_constructor(type_) + for name, type_ in params.items() + if type_info.needs_value_extraction(type_) + } + + def with_named_collections(**kwargs: Any) -> None: + run_embedded( + **{name: constructors.get(name, _identity)(value) for name, value in kwargs.items()} + ) + + jitted = wrap( + with_named_collections if constructors else run_embedded, signature, static_params + ) + param_names = tuple(program_type.definition.pos_or_kw_args) + + def call(*args: Any, **kwargs: Any) -> None: + if not is_program: + if "out" not in kwargs: + raise errors.MissingArgumentError(None, "out", True) + if "domain" in kwargs: + # a `Domain` is static in the tracing compiler, a `dict` is not + kwargs["domain"] = utils.tree_map(common.domain)(kwargs["domain"]) + if constructors: + kwargs = {**dict(zip(param_names, args)), **kwargs} + args = () + kwargs = { + name: arguments.extract(value) if name in constructors else value + for name, value in kwargs.items() + } + jitted(*args, **kwargs) + + call.__wrapped__ = jitted # type: ignore[attr-defined] + return call + + +def _keyword_only(name: str, **kwargs: Any) -> inspect.Parameter: + return inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, **kwargs) + + +def _identity(value: Any) -> Any: + return value + + +def _named_collection_constructor(type_: ts.TypeSpec) -> Callable[[Any], Any]: + """Rebuild the named collections of a value of `type_` from the tuples of `arguments.extract`.""" + if isinstance(type_, ts.NamedCollectionType): + return named_collections.make_named_collection_constructor_from_type_spec(type_) + if isinstance(type_, ts.TupleType) and type_info.needs_value_extraction(type_): + constructors = [_named_collection_constructor(element) for element in type_.types] + return lambda values: tuple( + constructor(value) for constructor, value in zip(constructors, values, strict=True) + ) + return _identity diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/jax_jit.py index abaea8bc7c..e98127b0f8 100644 --- a/src/gt4py/next/program_processors/runners/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/jax_jit.py @@ -18,13 +18,18 @@ import dataclasses import inspect from collections.abc import Callable, Sequence -from typing import Any +from typing import TYPE_CHECKING, Any import jax import jax.numpy as jnp from gt4py.next import backend as next_backend, common from gt4py.next.embedded import nd_array_field +from gt4py.next.program_processors.runners import embedded_jit + + +if TYPE_CHECKING: + from gt4py.next.ffront import decorator def _is_field(x: Any) -> bool: @@ -80,11 +85,13 @@ class JaxJitBackend(next_backend.EmbeddedJitBackend): JAX arrays are immutable, so an assignment to an `out` field gives it a new buffer: the jitted function returns the new buffer of each field it assigned to, and the caller's fields get them. A field passed more than once is one - field in the trace, so its aliases see the assignment. The returned callable has the - `jax.jit` object as its `jitted` attribute, to inspect its traces. + field in the trace, so its aliases see the assignment. """ - def jit( + def jit(self, entry_point: decorator.GTEntryPoint) -> Callable[..., None]: + return embedded_jit.jit(entry_point, self._wrap) + + def _wrap( self, entry: Callable[..., None], signature: inspect.Signature, @@ -110,7 +117,7 @@ def run(*args: Any, **kwargs: Any) -> None: if buffer is not None: field._set_buffer(buffer) - run.jitted = jitted # type: ignore[attr-defined] + run.__wrapped__ = jitted # type: ignore[attr-defined] return run diff --git a/src/gt4py/next/program_processors/runners/torch_compile.py b/src/gt4py/next/program_processors/runners/torch_compile.py index 84c5bffcb7..5dad29cd9f 100644 --- a/src/gt4py/next/program_processors/runners/torch_compile.py +++ b/src/gt4py/next/program_processors/runners/torch_compile.py @@ -21,12 +21,17 @@ import dataclasses import inspect from collections.abc import Callable, Sequence -from typing import Any +from typing import TYPE_CHECKING, Any import numpy as np import torch from gt4py.next import backend as next_backend, common +from gt4py.next.program_processors.runners import embedded_jit + + +if TYPE_CHECKING: + from gt4py.next.ffront import decorator # Dynamo reports an exception of the embedded code as an unsupported output type @@ -79,7 +84,10 @@ class TorchCompileBackend(next_backend.EmbeddedJitBackend): combination of their values. The `out` fields are assigned to in place. """ - def jit( + def jit(self, entry_point: decorator.GTEntryPoint) -> Callable[..., None]: + return embedded_jit.jit(entry_point, self._wrap) + + def _wrap( self, entry: Callable[..., None], signature: inspect.Signature, From ee88bc98bb546adb6f7582aaaa00773b6e2fffa7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Sun, 22 Nov 2026 19:21:30 +0100 Subject: [PATCH 130/166] test[next]: embedded jit tests reach the jax.jit object through __wrapped__ --- .../program_processor_tests/runners_tests/test_embedded_jit.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py index b3f3c6184b..eef6f9ab1e 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py @@ -169,7 +169,8 @@ def _e2v(device, table=E2V_TABLE): def _jitted(entry_point): - return entry_point._jit_entry.jitted + """The `jax.jit` object, under the call adapter of `embedded_jit` and the write-back of `jax_jit`.""" + return entry_point._embedded_jit.__wrapped__.__wrapped__ def test_out_assigned_in_the_callers_field(device, backend): From 1f46a3b89597351455e581f0248739e1441b11a2 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Sun, 22 Nov 2026 19:21:30 +0100 Subject: [PATCH 131/166] docs[next]: ADR 0030 describes the single dispatch hook --- docs/development/ADRs/next/0030-Embedded-Jit-Backends.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md b/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md index 6c93ae9d50..88ef2f63bd 100644 --- a/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md +++ b/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md @@ -17,9 +17,9 @@ Embedded execution runs the definition of a program on fields of any array libra ## Decision -`EmbeddedJitBackend` (in `gt4py.next.backend`) is a `Backend` that does not compile: its `jit(entry, signature, static_params)` wraps the embedded entry point once. There are two instances, `runners.jax_jit.jax_jit` and `runners.torch_compile.torch_compile`. +`EmbeddedJitBackend` (in `gt4py.next.backend`) is a `Backend` that does not compile: its `jit(entry_point)` returns the entry point run embedded inside the tracing compiler. There are two instances, `runners.jax_jit.jax_jit` and `runners.torch_compile.torch_compile`. What they share (the embedded execution, its signature and static parameters, the named collections) is in `runners.embedded_jit`; each backend only wraps it in its compiler. -- **Dispatch**: an entry point with such a backend takes the embedded path and calls its cached jitted entry. Whether an entry point is compiled is an attribute set at creation, so the call of a compiled backend costs what it did. `.compile()` raises. +- **Dispatch**: this is a stopgap until embedded execution is represented by backends, so the decorator has a single hook. An entry point with such a backend takes the embedded path and calls `backend.jit(entry_point)`, cached on the entry point. Whether an entry point is compiled is an attribute set at creation, so the call of a compiled backend costs what it did. `.compile()` raises. - **Arguments**: fields and connectivities (pytrees, ADR 0029) and scalars are traced. The `Dimension`s of the offset provider and the parameters in `static_params` are static; for a field operator called with `out=`, so is `domain`. - **Named collections** reach the backend as tuples and are rebuilt inside, as the compiled path extracts them: no user type is registered as a pytree. - **`out`**: under jax the jitted function returns the new buffers of the fields it assigned to, which the caller's fields get; a field passed twice and assigned to is rejected. Under torch the assignment is in place. From 70d736b9257197403ddedfd3d7793da9bea9db11 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 11:32:35 +0000 Subject: [PATCH 132/166] docs[next]: select the SWM target by backend, allocator and device, refresh the halo by field assignment --- examples/swm.ipynb | 163 +++++++++++++++++++++++++++++---------------- 1 file changed, 106 insertions(+), 57 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 6f851ea438..1ee1716410 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -57,9 +57,13 @@ "metadata": {}, "outputs": [], "source": [ + "import dataclasses\n", + "from typing import Any\n", + "\n", "import numpy as np\n", "\n", "import gt4py.next as gtx\n", + "from gt4py._core import definitions as core_defs\n", "\n", "import swm_numpy" ] @@ -72,7 +76,12 @@ "\n", "Fields carry **one halo cell on every side**, so the domain runs from `-1` to `M+1`. All\n", "three prognostic fields share this one index space; the C-grid staggering is expressed by\n", - "the shifts inside the operators rather than by different array shapes." + "the shifts inside the operators rather than by different array shapes.\n", + "\n", + "A `Target` names where the model runs: the `backend` that executes the field operator\n", + "(`None` runs it embedded, in Python) and the `allocator` and `device` of its fields. An\n", + "allocator is either a backend or an array namespace such as `numpy`, `cupy`, `jax.numpy`\n", + "or `torch`; embedded execution runs on whichever library holds the fields." ] }, { @@ -94,9 +103,17 @@ "DT = swm_numpy.DT # 90 s\n", "ALPHA = swm_numpy.ALPHA # Robert-Asselin filter coefficient\n", "\n", - "backend = None\n", - "# backend = gtx.gtfn_cpu\n", - "# backend = gtx.gtfn_gpu" + "\n", + "@dataclasses.dataclass(frozen=True)\n", + "class Target:\n", + " backend: Any = None\n", + " allocator: Any = None\n", + " device: core_defs.Device | None = None\n", + "\n", + "\n", + "target = Target()\n", + "# target = Target(gtx.gtfn_cpu, gtx.gtfn_cpu)\n", + "# target = Target(gtx.gtfn_gpu, gtx.gtfn_gpu)" ] }, { @@ -225,9 +242,10 @@ "source": [ "## Periodicity\n", "\n", - "The domain wraps in both directions. Here the halo is refreshed **outside** GT4Py, in\n", - "NumPy, after each step: the operator computes the interior only, and the halo is then\n", - "overwritten with the opposite edge.\n", + "The domain wraps in both directions. Here the halo is refreshed **outside** the field\n", + "operator, after each step: the operator computes the interior only, and the halo is then\n", + "overwritten with the opposite edge by assigning to the field. Field assignment works for\n", + "every array library, including JAX, whose arrays are immutable and get a new buffer.\n", "\n", "Rows are copied before columns, which is what fills the corners correctly.\n", "\n", @@ -243,12 +261,19 @@ "outputs": [], "source": [ "def apply_periodic(field: gtx.Field, m: int = M, n: int = N) -> None:\n", - " \"\"\"Refresh the one-cell halo of `field` in place from the opposite edge.\"\"\"\n", - " a = field.ndarray\n", - " a[0, :] = a[m, :]\n", - " a[m + 1, :] = a[1, :]\n", - " a[:, 0] = a[:, n]\n", - " a[:, n + 1] = a[:, 1]" + " \"\"\"Refresh the one-cell halo of `field` from the opposite edge.\"\"\"\n", + "\n", + " def copy(dst: dict, src: dict) -> None:\n", + " dst_domain = gtx.domain(dst)\n", + " src_buffer = field[gtx.domain(src)].ndarray\n", + " field[dst_domain] = type(field).from_array(src_buffer, domain=dst_domain)\n", + "\n", + " all_j = (-1, n + 1)\n", + " copy({I: (-1, 0), J: all_j}, {I: (m - 1, m), J: all_j})\n", + " copy({I: (m, m + 1), J: all_j}, {I: (0, 1), J: all_j})\n", + " all_i = (-1, m + 1)\n", + " copy({I: all_i, J: (-1, 0)}, {I: all_i, J: (n - 1, n)})\n", + " copy({I: all_i, J: (n, n + 1)}, {I: all_i, J: (0, 1)})" ] }, { @@ -259,7 +284,12 @@ "\n", "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", - "with the filter switched off, which is how the leapfrog scheme is started." + "with the filter switched off, which is how the leapfrog scheme is started.\n", + "\n", + "A `Model` holds the fields of one integration and the field operator bound to its target,\n", + "so that repeated calls of `advance` continue the same integration with the same compiled\n", + "or traced operator. `advance(..., periodic=False)` skips the halo refresh: the results are\n", + "wrong, but the steps then run back to back without host work in between." ] }, { @@ -268,48 +298,67 @@ "metadata": {}, "outputs": [], "source": [ - "def run(itmax: int, m: int = M, n: int = N) -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", + "class Model:\n", + " def __init__(self, m: int = M, n: int = N, target: Target = target):\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(target.backend)\n", + " self.cycle = 0\n", + "\n", + " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", + " return gtx.as_field(\n", + " self.domain,\n", + " np.pad(a, 1, mode=\"wrap\"),\n", + " allocator=target.allocator,\n", + " device=target.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", + "\n", + "\n", + "def run(\n", + " itmax: int, m: int = M, n: int = N, target: Target = target\n", + ") -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", - " domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", - " interior = gtx.domain({I: (0, m), J: (0, n)})\n", - "\n", - " u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n", - "\n", - " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", - " return gtx.as_field(domain, np.pad(a, 1, mode=\"wrap\"), allocator=backend)\n", - "\n", - " u, v, p = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", - " uold, vold, pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", - " unew, vnew, pnew = (gtx.zeros(domain, dtype=gtx.float64, allocator=backend) for _ in range(3))\n", - "\n", - " for cycle in range(itmax):\n", - " tdt = DT if cycle == 0 else 2.0 * DT\n", - " alpha = 0.0 if cycle == 0 else ALPHA\n", - "\n", - " timestep(\n", - " u,\n", - " v,\n", - " p,\n", - " uold,\n", - " vold,\n", - " pold,\n", - " DX,\n", - " DY,\n", - " tdt,\n", - " alpha,\n", - " out=(unew, vnew, pnew, uold, vold, pold),\n", - " domain=interior,\n", - " offset_provider={},\n", - " )\n", - "\n", - " for field in (unew, vnew, pnew):\n", - " apply_periodic(field, m, n)\n", - "\n", - " u, unew = unew, u\n", - " v, vnew = vnew, v\n", - " p, pnew = pnew, p\n", - "\n", - " return u, v, p\n", + " model = Model(m, n, target)\n", + " model.advance(itmax)\n", + " return model.u, model.v, model.p\n", "\n", "\n", "def interior_of(field: gtx.Field, m: int = M, n: int = N) -> np.ndarray:\n", @@ -341,8 +390,8 @@ "ATOL_P = 1e-8 # peak |p| ~ 5e4\n", "\n", "\n", - "def test_matches_numpy():\n", - " u, v, p = run(STEPS)\n", + "def test_matches_numpy(target: Target = target):\n", + " u, v, p = run(STEPS, target=target)\n", " u_ref, v_ref, p_ref = swm_numpy.run(STEPS)\n", "\n", " np.testing.assert_allclose(interior_of(u), u_ref, atol=ATOL_UV)\n", From 532070d073da7dccef1c7deb0b1354823901f16a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 11:32:36 +0000 Subject: [PATCH 133/166] docs[next]: run the SWM time step under an explicit jax.jit or torch.compile --- examples/swm.ipynb | 133 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 119 insertions(+), 14 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 1ee1716410..384f4d7ef6 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -58,6 +58,7 @@ "outputs": [], "source": [ "import dataclasses\n", + "from collections.abc import Callable\n", "from typing import Any\n", "\n", "import numpy as np\n", @@ -81,7 +82,9 @@ "A `Target` names where the model runs: the `backend` that executes the field operator\n", "(`None` runs it embedded, in Python) and the `allocator` and `device` of its fields. An\n", "allocator is either a backend or an array namespace such as `numpy`, `cupy`, `jax.numpy`\n", - "or `torch`; embedded execution runs on whichever library holds the fields." + "or `torch`; embedded execution runs on whichever library holds the fields. An embedded\n", + "target can also name a `jit`, which compiles the time step with the compiler of its array\n", + "library." ] }, { @@ -109,11 +112,92 @@ " backend: Any = None\n", " allocator: Any = None\n", " device: core_defs.Device | None = None\n", + " jit: Callable[[Callable], Callable] | None = None" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Explicit jit\n", + "\n", + "Embedded execution runs the Python of the field operator on every call. JAX and torch can\n", + "instead trace that Python once and compile the operations it records. A `jit` gets the\n", + "model's time step\n", + "\n", + "```python\n", + "step(u, v, p, uold, vold, pold, unew, vnew, pnew, tdt, alpha)\n", + "```\n", + "\n", + "(see `Model` below), which writes the interior of the last six fields and returns them, and\n", + "gives back a compiled function with the same signature.\n", + "\n", + "`jax.jit` takes fields as JAX pytrees, whose structure includes the domain, so each grid\n", + "size is traced once. `tdt` and `alpha` are static arguments, since embedded field\n", + "operators take Python scalars but not traced ones: the forward first step and the leapfrog\n", + "steps are two traces. The six fields the step overwrites are donated, so XLA writes the\n", + "results into their buffers instead of allocating new ones.\n", + "\n", + "`torch.compile` does not trace embedded GT4Py code itself. A `torch.compiler.nonstrict_trace`\n", + "function is called opaquely by Dynamo and runs on the fake tensors of the trace, so the\n", + "graph it records is what gets compiled. `fullgraph=True` turns a graph break into an error\n", + "and `dynamic=False` keeps the domain bounds static, which they have to be in the pytree of\n", + "a field. Dynamo also guards on which of the arguments share their domain objects, and the\n", + "fields a compiled call returns have domains of their own, so the first few steps compile\n", + "again until that sharing settles. All models share Dynamo's cache, which holds a limited\n", + "number of graphs per compiled function, so each model starts with an empty one." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def jax_jit(step: Callable) -> Callable:\n", + " import jax\n", + "\n", + " return jax.jit(step, static_argnums=(9, 10), donate_argnums=(3, 4, 5, 6, 7, 8))\n", + "\n", + "\n", + "def torch_compile(step: Callable) -> Callable:\n", + " import torch\n", + "\n", + " torch.compiler.reset()\n", + " traced = torch.compiler.nonstrict_trace(step)\n", + " return torch.compile(lambda *args: traced(*args), fullgraph=True, dynamic=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Choosing a target\n", "\n", + "Uncomment one of the targets below. Each needs its library imported first:\n", + "`from gt4py.next.program_processors.runners import dace`, `import cupy`, `import jax` or\n", + "`import torch`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "CUDA = core_defs.Device(core_defs.DeviceType.CUDA, 0)\n", "\n", - "target = Target()\n", + "target = Target() # embedded on NumPy\n", "# target = Target(gtx.gtfn_cpu, gtx.gtfn_cpu)\n", - "# target = Target(gtx.gtfn_gpu, gtx.gtfn_gpu)" + "# target = Target(gtx.gtfn_gpu, gtx.gtfn_gpu)\n", + "# target = Target(dace.run_dace_cpu, dace.run_dace_cpu)\n", + "# target = Target(dace.run_dace_gpu, dace.run_dace_gpu)\n", + "# target = Target(None, cupy)\n", + "# target = Target(None, jax.numpy)\n", + "# target = Target(None, jax.numpy, jit=jax_jit)\n", + "# target = Target(None, torch)\n", + "# target = Target(None, torch, CUDA)\n", + "# target = Target(None, torch, CUDA, jit=torch_compile)" ] }, { @@ -286,9 +370,11 @@ "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", "with the filter switched off, which is how the leapfrog scheme is started.\n", "\n", - "A `Model` holds the fields of one integration and the field operator bound to its target,\n", - "so that repeated calls of `advance` continue the same integration with the same compiled\n", - "or traced operator. `advance(..., periodic=False)` skips the halo refresh: the results are\n", + "A `Model` holds the fields of one integration and the time step bound to its target, so\n", + "that repeated calls of `advance` continue the same integration with the same compiled or\n", + "traced operator. The step returns the fields it wrote and `advance` rebinds them: a\n", + "jit-compiled step returns new fields rather than writing into its arguments. The halo\n", + "refresh runs outside the step. `advance(..., periodic=False)` skips it: the results are\n", "wrong, but the steps then run back to back without host work in between." ] }, @@ -302,8 +388,29 @@ " def __init__(self, m: int = M, n: int = N, target: Target = target):\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(target.backend)\n", + " interior = gtx.domain({I: (0, m), J: (0, n)})\n", + " operator = timestep.with_backend(target.backend)\n", + "\n", + " def step(u, v, p, uold, vold, pold, unew, vnew, pnew, tdt, alpha):\n", + " out = (unew, vnew, pnew, uold, vold, pold)\n", + " operator(\n", + " u,\n", + " v,\n", + " p,\n", + " uold,\n", + " vold,\n", + " pold,\n", + " DX,\n", + " DY,\n", + " tdt,\n", + " alpha,\n", + " out=out,\n", + " domain=interior,\n", + " offset_provider={},\n", + " )\n", + " return out\n", + "\n", + " self.step = step if target.jit is None else target.jit(step)\n", " self.cycle = 0\n", "\n", " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", @@ -326,20 +433,18 @@ " 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.unew, self.vnew, self.pnew, self.uold, self.vold, self.pold = 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", + " self.unew,\n", + " self.vnew,\n", + " self.pnew,\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", From c1716be2b66c9abf074a5f91cab3f101045a03a3 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 11:36:08 +0000 Subject: [PATCH 134/166] docs[next]: select the SWM DaCe targets through gtx.dace_cpu and gtx.dace_gpu --- examples/swm.ipynb | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 384f4d7ef6..f8f8eb418b 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -174,9 +174,8 @@ "source": [ "### Choosing a target\n", "\n", - "Uncomment one of the targets below. Each needs its library imported first:\n", - "`from gt4py.next.program_processors.runners import dace`, `import cupy`, `import jax` or\n", - "`import torch`." + "Uncomment one of the targets below. The embedded ones need their array library imported\n", + "first: `import cupy`, `import jax` or `import torch`." ] }, { @@ -190,8 +189,8 @@ "target = Target() # embedded on NumPy\n", "# target = Target(gtx.gtfn_cpu, gtx.gtfn_cpu)\n", "# target = Target(gtx.gtfn_gpu, gtx.gtfn_gpu)\n", - "# target = Target(dace.run_dace_cpu, dace.run_dace_cpu)\n", - "# target = Target(dace.run_dace_gpu, dace.run_dace_gpu)\n", + "# target = Target(gtx.dace_cpu, gtx.dace_cpu)\n", + "# target = Target(gtx.dace_gpu, gtx.dace_gpu)\n", "# target = Target(None, cupy)\n", "# target = Target(None, jax.numpy)\n", "# target = Target(None, jax.numpy, jit=jax_jit)\n", From 48bf008e4423bb6925ad2975e1f0140c5f165736 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 16:49:14 +0000 Subject: [PATCH 135/166] docs[next]: SWM introduction without the provenance paragraph --- examples/swm.ipynb | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index f8f8eb418b..57fc0fd2d7 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -20,9 +20,9 @@ "# Shallow Water Model\n", "\n", "A doubly periodic shallow water model on an Arakawa C-grid, integrated with a leapfrog\n", - "scheme and a Robert-Asselin time filter. It is the NCAR\n", + "scheme and a Robert-Asselin time filter, ported from the NCAR\n", "[SWM](https://github.com/NCAR/SWM) mini-app, a long-standing benchmark for comparing\n", - "programming models, written here as a single `gt4py.next` field operator.\n", + "programming models.\n", "\n", "The prognostic equations are\n", "\n", @@ -42,13 +42,7 @@ "\\eta = \\frac{\\delta_x v - \\delta_y u}{\\overline{P}^{\\,xy}} ,\n", "$$\n", "\n", - "named `cu`, `cv`, `h` and `z` here.\n", - "\n", - "**Provenance.** The *scheme* is Sadourny's. The *configuration* --- grid size, spacing,\n", - "time step, filter coefficient and initial condition --- comes from the\n", - "[NCAR/SWM](https://github.com/NCAR/SWM) benchmark rather than from the paper; Sadourny\n", - "damps the leapfrog scheme by averaging odd and even time levels every $N$ steps, not with\n", - "the per-step Robert-Asselin filter used here." + "named `cu`, `cv`, `h` and `z` here." ] }, { From 0a0e6d8a6f1eb753db4517f16d785a1cc0433927 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 16:49:17 +0000 Subject: [PATCH 136/166] docs[next]: SWM plot without an interpretation of the flow --- examples/swm.ipynb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 57fc0fd2d7..50b45f57a6 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -545,9 +545,7 @@ "source": [ "## The flow\n", "\n", - "The initial stream function sets up a pair of counter-rotating vortices; after a few\n", - "hundred steps the pressure field has developed the finer structure the scheme is meant to\n", - "handle without spurious accumulation of energy at the grid scale." + "`u`, `v` and `p` after `STEPS` steps." ] }, { From a621b922ed31c99e538de1ebeb8634072fd04f23 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:05:57 +0000 Subject: [PATCH 137/166] docs[next]: SWM operators section without the announced staggered-dimensions follow-up --- examples/swm.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 50b45f57a6..7cf2edf7b9 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -204,9 +204,9 @@ "maps back. Which one a term needs is fixed by where its operands live: `p` and `h` sit at\n", "cell centres, `u` and `cu` on $x$-faces, `v` and `cv` on $y$-faces, and `z` on corners.\n", "\n", - "Keeping the two variants apart by hand is exactly the bookkeeping that\n", + "Keeping the two variants apart by hand is the bookkeeping that\n", "[staggered dimensions](../docs/development/ADRs/next/0026-Staggered_Dimensions.md) are\n", - "designed to remove; a follow-up rewrites these eight operators as four." + "designed to remove." ] }, { From 35d6494fe02437b194493fb6b4e3391b33c25c5f Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:06:00 +0000 Subject: [PATCH 138/166] docs[next]: check the SWM example against the NCAR reference by default --- examples/swm.ipynb | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 7cf2edf7b9..cc111b040a 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -509,8 +509,7 @@ "\n", "`swm_reference.npz` holds `u`, `v`, `p` after the full 4000-step benchmark, taken from\n", "[NCAR/SWM](https://github.com/NCAR/SWM) `ref/16x16` (Apache-2.0). Reproducing it end to\n", - "end is the real correctness check, but it takes far longer than a notebook should in CI,\n", - "so it is opt-in." + "end is the real correctness check." ] }, { @@ -519,9 +518,6 @@ "metadata": {}, "outputs": [], "source": [ - "RUN_FULL_BENCHMARK = False\n", - "\n", - "\n", "def test_matches_reference():\n", " u, v, p = run(swm_numpy.ITMAX)\n", " u_out, v_out, p_out = swm_numpy.to_reference_layout(\n", @@ -534,9 +530,8 @@ " np.testing.assert_allclose(p_out, reference[\"p\"], atol=ATOL_P)\n", "\n", "\n", - "if RUN_FULL_BENCHMARK:\n", - " test_matches_reference()\n", - " print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" + "test_matches_reference()\n", + "print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" ] }, { From 988af2da7ef3327a31f338067dbb911e718b5c0a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:06:03 +0000 Subject: [PATCH 139/166] docs[next]: tighten the SWM tolerances to about three times the largest error of any target --- examples/swm.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index cc111b040a..3adb0f13d8 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -484,8 +484,8 @@ "\n", "# The two implementations sum the same terms in a different order, so they agree to\n", "# rounding rather than bit-for-bit. Tolerances are absolute because u and v cross zero.\n", - "ATOL_UV = 1e-11 # peak |u|, |v| ~ 4\n", - "ATOL_P = 1e-8 # peak |p| ~ 5e4\n", + "ATOL_UV = 3e-12 # peak |u|, |v| ~ 4\n", + "ATOL_P = 1e-9 # peak |p| ~ 5e4\n", "\n", "\n", "def test_matches_numpy(target: Target = target):\n", From 356bc15396a7ea1730d5f617f6ac5569dcdd4108 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:39:59 +0000 Subject: [PATCH 140/166] docs[next]: an opt-in performance comparison of all SWM targets at the end of the notebook --- examples/swm.ipynb | 161 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 3adb0f13d8..c7aea34d8b 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -562,6 +562,167 @@ "fig.tight_layout()" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Performance comparison\n", + "\n", + "The same model on every target installed here: the compiled `gtfn` and `dace` backends on\n", + "CPU and GPU, and embedded execution on NumPy, CuPy, JAX and torch arrays, eagerly and\n", + "under `jax.jit` and `torch.compile`. Each target is first checked against the NumPy\n", + "implementation, then timed on a sweep of grid sizes.\n", + "\n", + "The timed steps skip the halo refresh, which runs on the host between two steps. Their\n", + "results are therefore wrong, but the steps run back to back: GPU work is launched\n", + "asynchronously and the host's dispatch of the next step overlaps with the device's\n", + "execution of the previous one.\n", + "\n", + "The first steps include compilation and the first leapfrog step uses different scalars, so\n", + "`WARMUP_STEPS` run before any timing; the first step is reported separately. Then\n", + "`REPEATS` blocks of `TIMED_STEPS` steps are timed, each between two waits for the device,\n", + "and the median time per step over the blocks is reported. The comparison takes minutes, so\n", + "it is opt-in. Start the kernel with `PYTHONOPTIMIZE=1` to time without GT4Py's runtime\n", + "checks." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import importlib.util\n", + "import json\n", + "import statistics\n", + "import time\n", + "\n", + "RUN_PERFORMANCE_COMPARISON = False\n", + "\n", + "GRID_SIZES = (64, 256, 1024, 2048, 4096)\n", + "WARMUP_STEPS = 5\n", + "TIMED_STEPS = 20\n", + "REPEATS = 5\n", + "\n", + "\n", + "def installed(module: str) -> bool:\n", + " return importlib.util.find_spec(module) is not None\n", + "\n", + "\n", + "def comparison_targets() -> dict[str, Target]:\n", + " \"\"\"Every target whose libraries and devices are available here.\"\"\"\n", + " try:\n", + " import cupy\n", + "\n", + " gpu = cupy.cuda.runtime.getDeviceCount() > 0\n", + " except (ImportError, RuntimeError):\n", + " gpu = False\n", + "\n", + " targets = {\"dace_cpu\": Target(gtx.dace_cpu, gtx.dace_cpu)}\n", + " if gpu:\n", + " targets[\"dace_gpu\"] = Target(gtx.dace_gpu, gtx.dace_gpu)\n", + " targets[\"gtfn_cpu\"] = Target(gtx.gtfn_cpu, gtx.gtfn_cpu)\n", + " if gpu:\n", + " targets[\"gtfn_gpu\"] = Target(gtx.gtfn_gpu, gtx.gtfn_gpu)\n", + " targets[\"numpy\"] = Target(None, np)\n", + " if gpu:\n", + " targets[\"cupy\"] = Target(None, cupy)\n", + " if installed(\"jax\"):\n", + " import jax\n", + "\n", + " label = jax.default_backend()\n", + " targets[f\"jax [{label}]\"] = Target(None, jax.numpy)\n", + " targets[f\"jax.jit [{label}]\"] = Target(None, jax.numpy, jit=jax_jit)\n", + " if installed(\"torch\"):\n", + " import torch\n", + "\n", + " device = CUDA if torch.cuda.is_available() else None\n", + " label = \"cuda\" if device else \"cpu\"\n", + " targets[f\"torch [{label}]\"] = Target(None, torch, device)\n", + " targets[f\"torch.compile [{label}]\"] = Target(None, torch, device, jit=torch_compile)\n", + " return targets\n", + "\n", + "\n", + "def wait(model: Model) -> None:\n", + " \"\"\"Block until the device has finished every step launched so far.\"\"\"\n", + " for field in (model.u, model.v, model.p, model.uold, model.vold, model.pold):\n", + " buffer = field.ndarray\n", + " library = type(buffer).__module__.split(\".\")[0]\n", + " if hasattr(buffer, \"block_until_ready\"):\n", + " buffer.block_until_ready()\n", + " elif library == \"cupy\":\n", + " buffer.device.synchronize()\n", + " elif library == \"torch\" and buffer.is_cuda:\n", + " import torch\n", + "\n", + " torch.cuda.synchronize(buffer.device)\n", + "\n", + "\n", + "def time_steps(size: int, target: Target) -> dict[str, Any]:\n", + " \"\"\"Return the time of the first step and the time per step of each timed block.\"\"\"\n", + " model = Model(size, size, target)\n", + "\n", + " start = time.perf_counter()\n", + " model.advance(1, periodic=False)\n", + " wait(model)\n", + " first_step = time.perf_counter() - start\n", + " model.advance(WARMUP_STEPS - 1, periodic=False)\n", + "\n", + " per_step = []\n", + " for _ in range(REPEATS):\n", + " wait(model)\n", + " start = time.perf_counter()\n", + " model.advance(TIMED_STEPS, periodic=False)\n", + " wait(model)\n", + " per_step.append((time.perf_counter() - start) / TIMED_STEPS)\n", + "\n", + " if not all(np.isfinite(field.asnumpy()).all() for field in (model.u, model.v, model.p)):\n", + " raise FloatingPointError(\"non-finite fields after the timed steps\")\n", + " return {\"first_step\": first_step, \"per_step\": per_step}\n", + "\n", + "\n", + "def compare(grid_sizes=GRID_SIZES) -> dict[str, dict[int, dict[str, Any]]]:\n", + " \"\"\"Validate every target, then time it on every grid size.\"\"\"\n", + " timings = {}\n", + " for name, comparison_target in comparison_targets().items():\n", + " test_matches_numpy(comparison_target)\n", + " timings[name] = {}\n", + " for size in grid_sizes:\n", + " timings[name][size] = time_steps(size, comparison_target)\n", + " median = 1e3 * statistics.median(timings[name][size][\"per_step\"])\n", + " print(f\"{name:24} {size:5}^2 {median:10.3f} ms/step\", flush=True)\n", + " return timings\n", + "\n", + "\n", + "def report(timings: dict[str, dict[int, dict[str, Any]]]) -> None:\n", + " sizes = list(next(iter(timings.values())))\n", + " header = \"\".join(f\"{f'{size}^2':>12}\" for size in sizes)\n", + " print(f\"{'median ms/step':24}{header} {'first step [s]':>16}\")\n", + " for name, by_size in timings.items():\n", + " steady = \"\".join(\n", + " f\"{1e3 * statistics.median(result['per_step']):12.3f}\" for result in by_size.values()\n", + " )\n", + " first = \"/\".join(f\"{result['first_step']:.2f}\" for result in by_size.values())\n", + " print(f\"{name:24}{steady} {first:>16}\")\n", + "\n", + " fig, ax = plt.subplots(figsize=(7, 4.5))\n", + " for name, by_size in timings.items():\n", + " points = [size * size for size in by_size]\n", + " medians = [1e3 * statistics.median(result[\"per_step\"]) for result in by_size.values()]\n", + " ax.loglog(points, medians, marker=\"o\", label=name)\n", + " ax.set_xlabel(\"grid points\")\n", + " ax.set_ylabel(\"median time per step [ms]\")\n", + " ax.legend(fontsize=\"small\")\n", + " fig.tight_layout()\n", + "\n", + "\n", + "if RUN_PERFORMANCE_COMPARISON:\n", + " timings = compare()\n", + " with open(\"swm_timings.json\", \"w\") as file:\n", + " json.dump(timings, file)\n", + " report(timings)" + ] + }, { "cell_type": "markdown", "metadata": {}, From 5f067b5fb15d3d43dcd3f86c711385ca3eb35c72 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:40:02 +0000 Subject: [PATCH 141/166] docs[next]: SWM operators section names generic operators beside staggered dimensions, without the ADR link --- examples/swm.ipynb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index c7aea34d8b..9edddbeab7 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -204,9 +204,8 @@ "maps back. Which one a term needs is fixed by where its operands live: `p` and `h` sit at\n", "cell centres, `u` and `cu` on $x$-faces, `v` and `cv` on $y$-faces, and `z` on corners.\n", "\n", - "Keeping the two variants apart by hand is the bookkeeping that\n", - "[staggered dimensions](../docs/development/ADRs/next/0026-Staggered_Dimensions.md) are\n", - "designed to remove." + "Staggered dimensions would remove the need for the two shift directions, and operators\n", + "generic over the dimension would remove the separate $x$ and $y$ variants." ] }, { From 3fac77fd1d7ff9356f150985898f9e47a9783d68 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:40:05 +0000 Subject: [PATCH 142/166] docs[next]: the SWM old levels are rebound, not updated in place --- examples/swm.ipynb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 9edddbeab7..ae8fda506c 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -358,8 +358,7 @@ "source": [ "## Time loop\n", "\n", - "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", - "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", + "`uold`, `vold` and `pold` are never swapped; only the prognostic fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", "with the filter switched off, which is how the leapfrog scheme is started.\n", "\n", "A `Model` holds the fields of one integration and the time step bound to its target, so\n", From 171f99e62cceee61d812440d05c162b22c4ac84e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:40:09 +0000 Subject: [PATCH 143/166] docs[next]: SWM equations without the Coriolis term the model does not have --- examples/swm.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index ae8fda506c..a1b52ba4dd 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -27,13 +27,13 @@ "The prognostic equations are\n", "\n", "$$\n", - "\\frac{\\partial \\mathbf{V}}{\\partial t} + (\\zeta + f)\\,\\mathbf{k} \\times \\mathbf{V}\n", + "\\frac{\\partial \\mathbf{V}}{\\partial t} + \\zeta\\,\\mathbf{k} \\times \\mathbf{V}\n", " + \\nabla\\left(P + \\tfrac{1}{2}\\mathbf{V}\\cdot\\mathbf{V}\\right) = 0,\n", "\\qquad\n", "\\frac{\\partial P}{\\partial t} + \\nabla\\cdot(P\\mathbf{V}) = 0 ,\n", "$$\n", "\n", - "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975,\n", + "without rotation (the Coriolis parameter $f$ is zero, as in NCAR/SWM), discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975,\n", "his Eq. 4). The four intermediates below are his mass fluxes and diagnostics,\n", "\n", "$$\n", From 63af7c22e9cb2644f413cd1db2de43e24a233fbb Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:40:12 +0000 Subject: [PATCH 144/166] docs[next]: SWM periodicity section without the announced concat_where follow-up --- examples/swm.ipynb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index a1b52ba4dd..756c24cd11 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -323,11 +323,7 @@ "overwritten with the opposite edge by assigning to the field. Field assignment works for\n", "every array library, including JAX, whose arrays are immutable and get a new buffer.\n", "\n", - "Rows are copied before columns, which is what fills the corners correctly.\n", - "\n", - "Expressing the wrap *inside* the field operator instead --- with `concat_where` over a\n", - "domain boundary --- is the subject of a follow-up; it needs shift offsets that are only\n", - "known at compile time rather than when the operator is traced." + "Rows are copied before columns, which is what fills the corners correctly." ] }, { From 87a0b1623139a10ab77320658512745a50c9b401 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:40:15 +0000 Subject: [PATCH 145/166] docs[next]: pass the SWM target explicitly instead of binding it at definition time --- examples/swm.ipynb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 756c24cd11..f5c00f9368 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -372,7 +372,7 @@ "outputs": [], "source": [ "class Model:\n", - " def __init__(self, m: int = M, n: int = N, target: Target = target):\n", + " def __init__(self, m: int = M, n: int = N, *, target: Target):\n", " self.m, self.n = m, n\n", " self.domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", " interior = gtx.domain({I: (0, m), J: (0, n)})\n", @@ -445,10 +445,10 @@ "\n", "\n", "def run(\n", - " itmax: int, m: int = M, n: int = N, target: Target = target\n", + " itmax: int, m: int = M, n: int = N, *, target: Target\n", ") -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", - " model = Model(m, n, target)\n", + " model = Model(m, n, target=target)\n", " model.advance(itmax)\n", " return model.u, model.v, model.p\n", "\n", @@ -482,7 +482,7 @@ "ATOL_P = 1e-9 # peak |p| ~ 5e4\n", "\n", "\n", - "def test_matches_numpy(target: Target = target):\n", + "def test_matches_numpy(target: Target):\n", " u, v, p = run(STEPS, target=target)\n", " u_ref, v_ref, p_ref = swm_numpy.run(STEPS)\n", "\n", @@ -491,7 +491,7 @@ " np.testing.assert_allclose(interior_of(p), p_ref, atol=ATOL_P)\n", "\n", "\n", - "test_matches_numpy()\n", + "test_matches_numpy(target)\n", "print(\"GT4Py and NumPy agree after\", STEPS, \"steps\")" ] }, @@ -512,8 +512,8 @@ "metadata": {}, "outputs": [], "source": [ - "def test_matches_reference():\n", - " u, v, p = run(swm_numpy.ITMAX)\n", + "def test_matches_reference(target: Target):\n", + " u, v, p = run(swm_numpy.ITMAX, target=target)\n", " u_out, v_out, p_out = swm_numpy.to_reference_layout(\n", " interior_of(u), interior_of(v), interior_of(p)\n", " )\n", @@ -524,7 +524,7 @@ " np.testing.assert_allclose(p_out, reference[\"p\"], atol=ATOL_P)\n", "\n", "\n", - "test_matches_reference()\n", + "test_matches_reference(target)\n", "print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" ] }, @@ -545,7 +545,7 @@ "source": [ "import matplotlib.pyplot as plt\n", "\n", - "u, v, p = run(STEPS)\n", + "u, v, p = run(STEPS, target=target)\n", "\n", "fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))\n", "for ax, field, name in zip(axes, (u, v, p), (\"u\", \"v\", \"p\")):\n", @@ -654,7 +654,7 @@ "\n", "def time_steps(size: int, target: Target) -> dict[str, Any]:\n", " \"\"\"Return the time of the first step and the time per step of each timed block.\"\"\"\n", - " model = Model(size, size, target)\n", + " model = Model(size, size, target=target)\n", "\n", " start = time.perf_counter()\n", " model.advance(1, periodic=False)\n", From 1332651787c51852e0588ec4f06e0c574a41a27e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 17:40:18 +0000 Subject: [PATCH 146/166] docs[next]: say that torch.compiler.reset clears all of Dynamo's compiled state --- examples/swm.ipynb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index f5c00f9368..8198a698c0 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -139,7 +139,9 @@ "a field. Dynamo also guards on which of the arguments share their domain objects, and the\n", "fields a compiled call returns have domains of their own, so the first few steps compile\n", "again until that sharing settles. All models share Dynamo's cache, which holds a limited\n", - "number of graphs per compiled function, so each model starts with an empty one." + "number of graphs per compiled function, so each model starts with an empty one.\n", + "`torch.compiler.reset()` clears everything Dynamo has compiled in the process, not only the\n", + "previous model's step." ] }, { From 60546c93d82ccb64b74345310f3b243b5c33816f Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 19:39:33 +0000 Subject: [PATCH 147/166] refactor[next]: embedded jit backends in runners.experimental, exported from gt4py.next.experimental; explicit EmbeddedJitBackend checks in the decorator (review) --- .../ADRs/next/0030-Embedded-Jit-Backends.md | 2 +- .../next/embedded/array_libraries/jax_ops.py | 2 +- .../embedded/array_libraries/torch_ops.py | 2 +- src/gt4py/next/experimental/__init__.py | 21 +++++++++++++++++++ src/gt4py/next/ffront/decorator.py | 4 ++-- .../runners/experimental/__init__.py | 10 +++++++++ .../{ => experimental}/embedded_jit.py | 0 .../runners/{ => experimental}/jax_jit.py | 2 +- .../{ => experimental}/torch_compile.py | 2 +- 9 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 src/gt4py/next/program_processors/runners/experimental/__init__.py rename src/gt4py/next/program_processors/runners/{ => experimental}/embedded_jit.py (100%) rename src/gt4py/next/program_processors/runners/{ => experimental}/jax_jit.py (98%) rename src/gt4py/next/program_processors/runners/{ => experimental}/torch_compile.py (98%) diff --git a/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md b/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md index 88ef2f63bd..ad99181f93 100644 --- a/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md +++ b/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md @@ -17,7 +17,7 @@ Embedded execution runs the definition of a program on fields of any array libra ## Decision -`EmbeddedJitBackend` (in `gt4py.next.backend`) is a `Backend` that does not compile: its `jit(entry_point)` returns the entry point run embedded inside the tracing compiler. There are two instances, `runners.jax_jit.jax_jit` and `runners.torch_compile.torch_compile`. What they share (the embedded execution, its signature and static parameters, the named collections) is in `runners.embedded_jit`; each backend only wraps it in its compiler. +`EmbeddedJitBackend` (in `gt4py.next.backend`) is a `Backend` that does not compile: its `jit(entry_point)` returns the entry point run embedded inside the tracing compiler. There are two instances, `runners.experimental.jax_jit.jax_jit` and `runners.experimental.torch_compile.torch_compile`, exported as `gt4py.next.experimental.jax_jit` and `gt4py.next.experimental.torch_compile`. What they share (the embedded execution, its signature and static parameters, the named collections) is in `runners.experimental.embedded_jit`; each backend only wraps it in its compiler. - **Dispatch**: this is a stopgap until embedded execution is represented by backends, so the decorator has a single hook. An entry point with such a backend takes the embedded path and calls `backend.jit(entry_point)`, cached on the entry point. Whether an entry point is compiled is an attribute set at creation, so the call of a compiled backend costs what it did. `.compile()` raises. - **Arguments**: fields and connectivities (pytrees, ADR 0029) and scalars are traced. The `Dimension`s of the offset provider and the parameters in `static_params` are static; for a field operator called with `out=`, so is `domain`. diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 7103ad6437..4826c3f31a 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -10,7 +10,7 @@ `ArrayOps` for JAX arrays, and the embedded fields as JAX pytrees. How embedded fields and connectivities behave under JAX tracing is in this module -(ADR 0029); `runners.jax_jit` runs programs under `jax.jit`. A connectivity table +(ADR 0029); `runners.experimental.jax_jit` runs programs under `jax.jit`. A connectivity table inside a trace is a tracer, and one of two cases: - it stands for a concrete table, which it got as a pytree leaf, or it was diff --git a/src/gt4py/next/embedded/array_libraries/torch_ops.py b/src/gt4py/next/embedded/array_libraries/torch_ops.py index 2a22dbdce4..e700fb2cd4 100644 --- a/src/gt4py/next/embedded/array_libraries/torch_ops.py +++ b/src/gt4py/next/embedded/array_libraries/torch_ops.py @@ -10,7 +10,7 @@ `ArrayOps` for torch tensors, and the embedded fields as torch pytrees. How embedded fields and connectivities behave under `torch.compile` is in this -module (ADR 0029); `runners.torch_compile` runs programs in a region. Dynamo does not +module (ADR 0029); `runners.experimental.torch_compile` runs programs in a region. Dynamo does not trace embedded code: a region calls it through a `torch.compiler.nonstrict_trace` function, which gets the fields and connectivities as pytree nodes and runs the embedded code on the fake tensors of the trace. A connectivity table inside the trace diff --git a/src/gt4py/next/experimental/__init__.py b/src/gt4py/next/experimental/__init__.py index 6378821989..3aeb012683 100644 --- a/src/gt4py/next/experimental/__init__.py +++ b/src/gt4py/next/experimental/__init__.py @@ -6,6 +6,9 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import importlib +from typing import Any, Final + from gt4py.next.ffront.experimental import as_offset, concat_where @@ -13,3 +16,21 @@ "as_offset", "concat_where", ] + +# the embedded jit backends, created on first access: they need an optional package +_EMBEDDED_JIT_BACKENDS: Final = {"jax_jit": "jax", "torch_compile": "torch"} + + +def __getattr__(name: str) -> Any: + if name not in _EMBEDDED_JIT_BACKENDS: + raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") + try: + module = importlib.import_module( + f"gt4py.next.program_processors.runners.experimental.{name}" + ) + except ImportError as error: + raise AttributeError( + f"'{name}' requires the optional '{_EMBEDDED_JIT_BACKENDS[name]}' package." + ) from error + backend = globals()[name] = getattr(module, name) + return backend diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 890e084827..6fb154fa1b 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -386,7 +386,7 @@ def __call__( self._compiled_programs( *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit ) - elif self.backend is not None: + elif isinstance(self.backend, next_backend.EmbeddedJitBackend): with embedded_program_call_context(self, args, offset_provider, kwargs): self._embedded_jit(*args, offset_provider=offset_provider, **kwargs) else: @@ -585,7 +585,7 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> if not next_embedded.context.within_valid_context(): # field_operator as program kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} - if self.backend is not None: + if isinstance(self.backend, next_backend.EmbeddedJitBackend): return self._embedded_jit(*args, **kwargs) attributes = ( self.definition_stage.attributes diff --git a/src/gt4py/next/program_processors/runners/experimental/__init__.py b/src/gt4py/next/program_processors/runners/experimental/__init__.py new file mode 100644 index 0000000000..c2291e97e3 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/experimental/__init__.py @@ -0,0 +1,10 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + + +"""Experimental backends: embedded execution inside the tracing compiler of an array library.""" diff --git a/src/gt4py/next/program_processors/runners/embedded_jit.py b/src/gt4py/next/program_processors/runners/experimental/embedded_jit.py similarity index 100% rename from src/gt4py/next/program_processors/runners/embedded_jit.py rename to src/gt4py/next/program_processors/runners/experimental/embedded_jit.py diff --git a/src/gt4py/next/program_processors/runners/jax_jit.py b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py similarity index 98% rename from src/gt4py/next/program_processors/runners/jax_jit.py rename to src/gt4py/next/program_processors/runners/experimental/jax_jit.py index e98127b0f8..74d1efa5c5 100644 --- a/src/gt4py/next/program_processors/runners/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py @@ -25,7 +25,7 @@ from gt4py.next import backend as next_backend, common from gt4py.next.embedded import nd_array_field -from gt4py.next.program_processors.runners import embedded_jit +from gt4py.next.program_processors.runners.experimental import embedded_jit if TYPE_CHECKING: diff --git a/src/gt4py/next/program_processors/runners/torch_compile.py b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py similarity index 98% rename from src/gt4py/next/program_processors/runners/torch_compile.py rename to src/gt4py/next/program_processors/runners/experimental/torch_compile.py index 5dad29cd9f..1a6a8073fb 100644 --- a/src/gt4py/next/program_processors/runners/torch_compile.py +++ b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py @@ -27,7 +27,7 @@ import torch from gt4py.next import backend as next_backend, common -from gt4py.next.program_processors.runners import embedded_jit +from gt4py.next.program_processors.runners.experimental import embedded_jit if TYPE_CHECKING: From 5f714df3786f52be9beffd56da80205bb27bea93 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 19:39:33 +0000 Subject: [PATCH 148/166] test[next]: embedded jit backends from their new location, and their export (review) --- tests/next_tests/definitions.py | 8 +++++--- .../runners_tests/test_embedded_jit.py | 14 ++++++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index bcedd321bb..1840992b80 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -102,7 +102,9 @@ def __gt_allocate__( torch_cuda_execution = EmbeddedDummyBackend("EmbeddedTorchCUDA", _TorchCUDAAllocator()) -_torch_compile = _optional_module("gt4py.next.program_processors.runners.torch_compile") +_torch_compile = _optional_module( + "gt4py.next.program_processors.runners.experimental.torch_compile" +) torch_compile_cuda = ( dataclasses.replace( _torch_compile.torch_compile, name="torch_compile_cuda", allocator=_TorchCUDAAllocator() @@ -125,8 +127,8 @@ class OptionalProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): DACE_CPU = "gt4py.next.program_processors.runners.dace.run_dace_cpu" DACE_GPU = "gt4py.next.program_processors.runners.dace.run_dace_gpu" DACE_CPU_NO_OPT = "gt4py.next.program_processors.runners.dace.run_dace_cpu_noopt" - JAX_JIT = "gt4py.next.program_processors.runners.jax_jit.jax_jit" - TORCH_COMPILE = "gt4py.next.program_processors.runners.torch_compile.torch_compile" + JAX_JIT = "gt4py.next.program_processors.runners.experimental.jax_jit.jax_jit" + TORCH_COMPILE = "gt4py.next.program_processors.runners.experimental.torch_compile.torch_compile" TORCH_COMPILE_CUDA = "next_tests.definitions.torch_compile_cuda" diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py index eef6f9ab1e..33390eda27 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py @@ -121,10 +121,10 @@ def device(request, library): @pytest.fixture def backend(library): if library == "jax": - from gt4py.next.program_processors.runners import jax_jit + from gt4py.next.program_processors.runners.experimental import jax_jit return jax_jit.jax_jit - from gt4py.next.program_processors.runners import torch_compile + from gt4py.next.program_processors.runners.experimental import torch_compile return torch_compile.torch_compile @@ -192,7 +192,7 @@ def test_table_is_a_runtime_argument(): device = jax.devices("cpu")[0] f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) out = _field(device, np.zeros(5), [Edge]) - from gt4py.next.program_processors.runners import jax_jit + from gt4py.next.program_processors.runners.experimental import jax_jit prog = edge_sum_program.with_backend(jax_jit.jax_jit) conn = _e2v(device) @@ -206,7 +206,7 @@ def test_table_is_a_runtime_argument(): def test_retrace_per_table_buffer(): import jax - from gt4py.next.program_processors.runners import jax_jit + from gt4py.next.program_processors.runners.experimental import jax_jit device = jax.devices("cpu")[0] out = _field(device, np.zeros(5), [Edge]) @@ -301,6 +301,12 @@ def test_missing_out_is_rejected(device, backend): ) +def test_exported_from_experimental(library, backend): + from gt4py.next import experimental + + assert getattr(experimental, {"jax": "jax_jit", "torch": "torch_compile"}[library]) is backend + + def test_compile_is_rejected(backend): with pytest.raises(RuntimeError, match="does not compile"): edge_sum_program.with_backend(backend).compile(offset_provider={"E2V": None}) From ab54012771baf1c3e0b3f3008afd14feefe0ecef Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 20:29:32 +0000 Subject: [PATCH 149/166] test[next]: the new compile-without-offset-provider tests skip the embedded jit backends, as embedded --- .../feature_tests/ffront_tests/test_compiled_program.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py index 0cd4693cb7..820bb86903 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py @@ -170,7 +170,7 @@ def test_compile_kwargs(cartesian_case, compile_testee): def test_compile_without_offset_provider(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile() @@ -190,7 +190,7 @@ def test_compile_without_offset_provider(cartesian_case, compile_testee): @pytest.mark.uses_cartesian_shift def test_compile_cartesian_shift_without_offset_provider(cartesian_case): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.field_operator From 6f0e8cbe16bbffd8f250002d5a3c8470f719e037 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 23:04:02 +0000 Subject: [PATCH 150/166] refactor[next]: embedded/__init__ imports no submodules; the decorator and context import what they use (review of #3030) --- src/gt4py/next/embedded/__init__.py | 7 ------- src/gt4py/next/embedded/context.py | 9 ++++----- src/gt4py/next/ffront/decorator.py | 9 ++++----- 3 files changed, 8 insertions(+), 17 deletions(-) diff --git a/src/gt4py/next/embedded/__init__.py b/src/gt4py/next/embedded/__init__.py index 0fdbacd655..c9075cc89d 100644 --- a/src/gt4py/next/embedded/__init__.py +++ b/src/gt4py/next/embedded/__init__.py @@ -5,10 +5,3 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause - -# not `nd_array_field` and `array_libraries`: they import `ffront.fbuiltins`, which imports -# this package -from . import array_ops, common, context, exceptions - - -__all__ = ["array_ops", "common", "context", "exceptions"] diff --git a/src/gt4py/next/embedded/context.py b/src/gt4py/next/embedded/context.py index 8183a3292c..1b44e90453 100644 --- a/src/gt4py/next/embedded/context.py +++ b/src/gt4py/next/embedded/context.py @@ -15,7 +15,6 @@ import gt4py.eve as eve import gt4py.next.common as common -import gt4py.next.embedded as gtx_embedded import gt4py.next.errors.exceptions as exceptions @@ -80,20 +79,20 @@ def update( closure_token, offset_provider_token = None, None if closure_column_range is not eve.NOTHING: assert not isinstance(closure_column_range, eve.NothingType) - closure_token = gtx_embedded.context._closure_column_range.set(closure_column_range) + closure_token = _closure_column_range.set(closure_column_range) if offset_provider is not eve.NOTHING: assert not isinstance(offset_provider, eve.NothingType) - offset_provider_token = gtx_embedded.context._offset_provider.set(offset_provider) + offset_provider_token = _offset_provider.set(offset_provider) try: yield None finally: if closure_column_range is not eve.NOTHING: assert closure_token is not None - gtx_embedded.context._closure_column_range.reset(closure_token) + _closure_column_range.reset(closure_token) if offset_provider is not eve.NOTHING: assert offset_provider_token is not None - gtx_embedded.context._offset_provider.reset(offset_provider_token) + _offset_provider.reset(offset_provider_token) def within_valid_context() -> bool: diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index be445822be..c3970cc080 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -29,11 +29,10 @@ backend as next_backend, common, custom_layout_allocators as next_allocators, - embedded as next_embedded, errors, utils, ) -from gt4py.next.embedded import operators as embedded_operators +from gt4py.next.embedded import context as embedded_context, operators as embedded_operators from gt4py.next.ffront import ( field_operator_ast as foast, foast_to_gtir, @@ -396,7 +395,7 @@ def __call__( stacklevel=2, ) - with next_embedded.context.update(offset_provider=offset_provider): + with embedded_context.update(offset_provider=offset_provider): with embedded_program_call_context(self, args, offset_provider, kwargs): self.definition_stage.definition(*args, **kwargs) @@ -558,7 +557,7 @@ def __gt_closure_vars__(self) -> dict[str, Any]: return self.foast_stage.closure_vars def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> Any: - if not next_embedded.context.within_valid_context() and self._is_compiled: + if not embedded_context.within_valid_context() and self._is_compiled: # non embedded execution offset_provider = {**kwargs.pop("offset_provider", {})} if "out" not in kwargs: @@ -580,7 +579,7 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> else enable_jit, ) else: - if not next_embedded.context.within_valid_context(): + if not embedded_context.within_valid_context(): # field_operator as program kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} if isinstance(self.backend, next_backend.EmbeddedJitBackend): From a4e7c27d1b225ab2e36fe2984027389fecb9f528 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Mon, 23 Nov 2026 23:04:02 +0000 Subject: [PATCH 151/166] refactor[next]: array_ops.ScalarLike is TensorLike: it admits any array (review of #3030) --- src/gt4py/next/embedded/array_ops.py | 6 +++--- src/gt4py/next/embedded/operators.py | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 4209146a05..3dd1756e5f 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -285,11 +285,11 @@ def is_0d_array(value: Any) -> bool: ) -#: What embedded accepts where it accepts a scalar: a scalar, or a 0-d array (`is_scalar_like`) -ScalarLike: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject +#: A scalar or an array; `is_scalar_like` narrows to it, since typing has no 0-d arrays +TensorLike: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject -def is_scalar_like(value: Any) -> TypeIs[ScalarLike]: +def is_scalar_like(value: Any) -> TypeIs[TensorLike]: """A scalar, or a 0-d array.""" return core_defs.is_scalar_type(value) or is_0d_array(value) diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 8bc520fd8e..9bb51948b5 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -181,7 +181,7 @@ def _intersect_scan_args( def _is_maybe_nested_in_tuple_of_scalars( value: object, -) -> TypeIs[xtyping.MaybeNestedInTuple[array_ops.ScalarLike]]: +) -> TypeIs[xtyping.MaybeNestedInTuple[array_ops.TensorLike]]: """Scalars or 0-d arrays, or (nested) tuples of them.""" return all(array_ops.is_scalar_like(v) for v in utils.flatten_nested_tuple((value,))) @@ -189,10 +189,10 @@ def _is_maybe_nested_in_tuple_of_scalars( def _tuple_assign_value( pos: Sequence[common.NamedIndex], target: xtyping.MaybeNestedInTuple[common.MutableField], - source: xtyping.MaybeNestedInTuple[array_ops.ScalarLike], + source: xtyping.MaybeNestedInTuple[array_ops.TensorLike], ) -> None: @utils.tree_map - def impl(target: common.MutableField, source: array_ops.ScalarLike) -> None: + def impl(target: common.MutableField, source: array_ops.TensorLike) -> None: target[pos] = source impl(target, source) @@ -200,10 +200,10 @@ def impl(target: common.MutableField, source: array_ops.ScalarLike) -> None: def _tuple_at( pos: Sequence[common.NamedIndex], - field: xtyping.MaybeNestedInTuple[common.Field | array_ops.ScalarLike], -) -> array_ops.ScalarLike | tuple[array_ops.ScalarLike | tuple, ...]: + field: xtyping.MaybeNestedInTuple[common.Field | array_ops.TensorLike], +) -> array_ops.TensorLike | tuple[array_ops.TensorLike | tuple, ...]: @named_collections.tree_map_named_collection - def impl(field: common.Field | array_ops.ScalarLike) -> array_ops.ScalarLike: + def impl(field: common.Field | array_ops.TensorLike) -> array_ops.TensorLike: res = field[pos].as_scalar() if isinstance(field, common.Field) else field assert array_ops.is_scalar_like(res) return res From 9d8b35425400aa6f9f68b6ffb8c66309f1eee0fd Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 00:16:55 +0000 Subject: [PATCH 152/166] docs[next]: no ADR for the embedded jit backends (review) --- .../ADRs/next/0030-Embedded-Jit-Backends.md | 50 ------------------- docs/development/ADRs/next/README.md | 1 - src/gt4py/next/backend.py | 2 +- .../runners/experimental/embedded_jit.py | 2 +- 4 files changed, 2 insertions(+), 53 deletions(-) delete mode 100644 docs/development/ADRs/next/0030-Embedded-Jit-Backends.md diff --git a/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md b/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md deleted file mode 100644 index ad99181f93..0000000000 --- a/docs/development/ADRs/next/0030-Embedded-Jit-Backends.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -tags: [embedded, backend, jax, torch] ---- - -# Embedded Jit Backends - -- **Status**: valid -- **Authors**: Hannes Vogt (@havogt) -- **Created**: 2026-11-20 -- **Updated**: 2026-11-20 - -In the context of running programs and field operators on JAX arrays or torch tensors with the speed of the library's compiler, facing that embedded execution is plain Python and compiled backends do not take these arrays, we decided to add backends that wrap the embedded execution of an entry point in the library's tracing compiler (`jax.jit`, `torch.compile`), to get compiled programs without writing jax or torch code. We accept that scalar arguments are traced, so Python control flow or a domain bound on one needs `static_params`. - -## Context - -Embedded execution runs the definition of a program on fields of any array library. Under `jax.jit` or `torch.compile` it traces into a single compiled function, and ADR 0029 makes connectivities runtime arguments of it. The user had to write the jit wrapper by hand: split the offset provider, return the new `out` buffers (JAX arrays are immutable), and keep the wrapper cached. - -## Decision - -`EmbeddedJitBackend` (in `gt4py.next.backend`) is a `Backend` that does not compile: its `jit(entry_point)` returns the entry point run embedded inside the tracing compiler. There are two instances, `runners.experimental.jax_jit.jax_jit` and `runners.experimental.torch_compile.torch_compile`, exported as `gt4py.next.experimental.jax_jit` and `gt4py.next.experimental.torch_compile`. What they share (the embedded execution, its signature and static parameters, the named collections) is in `runners.experimental.embedded_jit`; each backend only wraps it in its compiler. - -- **Dispatch**: this is a stopgap until embedded execution is represented by backends, so the decorator has a single hook. An entry point with such a backend takes the embedded path and calls `backend.jit(entry_point)`, cached on the entry point. Whether an entry point is compiled is an attribute set at creation, so the call of a compiled backend costs what it did. `.compile()` raises. -- **Arguments**: fields and connectivities (pytrees, ADR 0029) and scalars are traced. The `Dimension`s of the offset provider and the parameters in `static_params` are static; for a field operator called with `out=`, so is `domain`. -- **Named collections** reach the backend as tuples and are rebuilt inside, as the compiled path extracts them: no user type is registered as a pytree. -- **`out`**: under jax the jitted function returns the new buffers of the fields it assigned to, which the caller's fields get; a field passed twice and assigned to is rejected. Under torch the assignment is in place. -- **Embedded changes**: a traced scalar is a 0-d array, so embedded accepts 0-d arrays where it accepts scalars, and the element of a 0-d traced array stays an array (`ArrayOps.scalar`). - -torch specifics, all from Dynamo: the embedded code runs through `nonstrict_trace`, which takes neither NumPy scalars nor frozen dataclasses, so scalars become 0-d tensors and the static arguments are closed over by one region per combination of their values. Each region gets its own code object, since Dynamo's recompile limit counts per code object. An exception of the embedded code is re-raised as itself. - -## Consequences - -- A program on jax or torch fields is compiled by `with_backend(jax_jit)` or `with_backend(torch_compile)`. -- A scalar that the embedded code needs concretely (an `if`, a domain bound, a scan carry in a condition) fails under tracing unless it is in `static_params`; the test matrix marks such tests (`uses_scalar_in_control_flow`, `uses_scalar_in_domain`, `uses_scan_carry_in_control_flow`). -- Retracing: per field domain and per table buffer (ADR 0029), per value of a static parameter. torch allows 8 recompiles per region. -- Embedded scans loop per column and level, so their trace grows with the size of the domain. -- The embedded-program hook wraps the jitted call, so it runs per call, not per trace. - -## Alternatives considered - -### Jit backends as compiled backends - -Entering through the compiled programs pool needs the embedded context set up again, a special case for `domain=` on the compiled path, and skips the embedded hook. - -### Registering named collections as pytrees - -Mutates the global pytree registry for user types, conflicts with a user's own registration, and misses types that appear only as `out`. - -### Specialized scalars under torch - -Dynamo's default: every new value of an integer recompiles, and the recompile limit is reached by, e.g., a time-step counter. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index e23185378b..9132ffe478 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -39,7 +39,6 @@ Writing a new ADR is simple: - [0022 - Limitations of embedded concat_where](0022-Limitations-of-embedded-concat_where.md) - [0029 - Connectivities in Tracing Embedded Backends](0029-Connectivities_in_Tracing_Embedded_Backends.md) -- [0030 - Embedded Jit Backends](0030-Embedded-Jit-Backends.md) ### Transformations diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index ab38db8ac4..bd4ad84617 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -191,7 +191,7 @@ class EmbeddedJitBackend(Backend, abc.ABC): Instead of compiling, it wraps the embedded execution of a program or field operator once, e.g. in `jax.jit`. The allocator allocates arrays of the library. A stopgap until embedded - execution is represented by backends (ADR 0030). + execution is represented by backends. """ executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] = ( diff --git a/src/gt4py/next/program_processors/runners/experimental/embedded_jit.py b/src/gt4py/next/program_processors/runners/experimental/embedded_jit.py index 813ace56fe..e67c74a997 100644 --- a/src/gt4py/next/program_processors/runners/experimental/embedded_jit.py +++ b/src/gt4py/next/program_processors/runners/experimental/embedded_jit.py @@ -9,7 +9,7 @@ """ What the embedded jit backends share: the embedded execution of an entry point, as they wrap it. -A stopgap until embedded execution is represented by backends (ADR 0030). +A stopgap until embedded execution is represented by backends. """ from __future__ import annotations From db6bccca603a8d782fb7009ae7bbf5c4820a45d1 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 00:16:55 +0000 Subject: [PATCH 153/166] refactor[next]: _has_compiled_backend, a cached_property instead of a field set in __post_init__ (review) --- src/gt4py/next/ffront/decorator.py | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index c3970cc080..6e00b94f00 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -99,17 +99,11 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): metadata=utils.gt4py_metadata(fingerprint=False) ) compilation_options: options.CompilationOptions - # an attribute, not a property, to cost the call no more than `backend is not None` - _is_compiled: bool = dataclasses.field( - init=False, repr=False, compare=False, metadata=utils.gt4py_metadata(fingerprint=False) - ) - def __post_init__(self) -> None: - object.__setattr__( - self, - "_is_compiled", - self.backend is not None - and not isinstance(self.backend, next_backend.EmbeddedJitBackend), + @functools.cached_property + def _has_compiled_backend(self) -> bool: + return self.backend is not None and not isinstance( + self.backend, next_backend.EmbeddedJitBackend ) @functools.cached_property @@ -150,7 +144,7 @@ def _make_compiled_programs_pool( ) -> compiled_program.CompiledProgramsPool: if self.backend is None or self.backend == eve.NOTHING: raise RuntimeError("Cannot compile a program without backend.") - if not self._is_compiled: + if not self._has_compiled_backend: raise RuntimeError( f"Backend '{self.backend.name}' runs programs embedded; it does not compile them." ) @@ -281,7 +275,6 @@ def __gt_type__(self) -> ts_ffront.ProgramType: # TODO(ricoh): linting should become optional, up to the backend. def __post_init__(self) -> None: - super().__post_init__() no_args_past = workflow.ConcreteArtifact(self.past_stage, arguments.CompileTimeArgs.empty()) _ = self._frontend_transforms.past_lint(no_args_past).data @@ -379,7 +372,7 @@ def __call__( kwarg_types={k: type_translation.from_value(v) for k, v in kwargs.items()}, ) - if self._is_compiled: + if self._has_compiled_backend: self._compiled_programs( *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit ) @@ -505,7 +498,6 @@ def from_function( # TODO(ricoh): linting should become optional, up to the backend. def __post_init__(self) -> None: """This ensures that DSL linting occurs at decoration time.""" - super().__post_init__() _ = self.foast_stage @functools.cached_property @@ -557,7 +549,7 @@ def __gt_closure_vars__(self) -> dict[str, Any]: return self.foast_stage.closure_vars def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> Any: - if not embedded_context.within_valid_context() and self._is_compiled: + if not embedded_context.within_valid_context() and self._has_compiled_backend: # non embedded execution offset_provider = {**kwargs.pop("offset_provider", {})} if "out" not in kwargs: From 18993f0a7b601eb06ec4a20348ab1d6713ce714e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 00:16:55 +0000 Subject: [PATCH 154/166] refactor[next]: array_ops.TensorLike is NDValue (review) --- src/gt4py/next/embedded/array_ops.py | 4 ++-- src/gt4py/next/embedded/operators.py | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 3dd1756e5f..429310354b 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -286,10 +286,10 @@ def is_0d_array(value: Any) -> bool: #: A scalar or an array; `is_scalar_like` narrows to it, since typing has no 0-d arrays -TensorLike: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject +NDValue: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject -def is_scalar_like(value: Any) -> TypeIs[TensorLike]: +def is_scalar_like(value: Any) -> TypeIs[NDValue]: """A scalar, or a 0-d array.""" return core_defs.is_scalar_type(value) or is_0d_array(value) diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 9bb51948b5..05e8e7a46a 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -181,7 +181,7 @@ def _intersect_scan_args( def _is_maybe_nested_in_tuple_of_scalars( value: object, -) -> TypeIs[xtyping.MaybeNestedInTuple[array_ops.TensorLike]]: +) -> TypeIs[xtyping.MaybeNestedInTuple[array_ops.NDValue]]: """Scalars or 0-d arrays, or (nested) tuples of them.""" return all(array_ops.is_scalar_like(v) for v in utils.flatten_nested_tuple((value,))) @@ -189,10 +189,10 @@ def _is_maybe_nested_in_tuple_of_scalars( def _tuple_assign_value( pos: Sequence[common.NamedIndex], target: xtyping.MaybeNestedInTuple[common.MutableField], - source: xtyping.MaybeNestedInTuple[array_ops.TensorLike], + source: xtyping.MaybeNestedInTuple[array_ops.NDValue], ) -> None: @utils.tree_map - def impl(target: common.MutableField, source: array_ops.TensorLike) -> None: + def impl(target: common.MutableField, source: array_ops.NDValue) -> None: target[pos] = source impl(target, source) @@ -200,10 +200,10 @@ def impl(target: common.MutableField, source: array_ops.TensorLike) -> None: def _tuple_at( pos: Sequence[common.NamedIndex], - field: xtyping.MaybeNestedInTuple[common.Field | array_ops.TensorLike], -) -> array_ops.TensorLike | tuple[array_ops.TensorLike | tuple, ...]: + field: xtyping.MaybeNestedInTuple[common.Field | array_ops.NDValue], +) -> array_ops.NDValue | tuple[array_ops.NDValue | tuple, ...]: @named_collections.tree_map_named_collection - def impl(field: common.Field | array_ops.TensorLike) -> array_ops.TensorLike: + def impl(field: common.Field | array_ops.NDValue) -> array_ops.NDValue: res = field[pos].as_scalar() if isinstance(field, common.Field) else field assert array_ops.is_scalar_like(res) return res From f6d6dc1b4b4918ead094e46cd20d68c39162f626 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 01:28:31 +0000 Subject: [PATCH 155/166] fix[next]: a backend whose allocator is an array namespace allocates fields with it --- src/gt4py/next/constructors.py | 6 ++-- .../runners_tests/test_embedded_jit.py | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index e9170f74af..940b550f92 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -76,6 +76,8 @@ def __init__( device = DEFAULT_DEVICE # Currently we use optimized CPU layout, but possibly we could also use standard numpy allocation allocator = next_allocators.device_allocators[device.device_type] + if next_allocators.is_field_allocator_factory(allocator): + allocator = allocator.__gt_allocator__ if core_ndarray_utils.is_array_namespace(allocator): if aligned_index is not None: @@ -93,9 +95,7 @@ def __init__( self._array_constructor = _ArrayAPIArrayConstructor( array_ns=allocator, device=translated_device ) - elif next_allocators.is_field_allocation_tool(allocator): - if next_allocators.is_field_allocator_factory(allocator): - allocator = allocator.__gt_allocator__ + elif next_allocators.is_field_allocator(allocator): if device is not None and allocator.__gt_device_type__ != device.device_type: raise ValueError( f"Allocator {allocator} is for device type {allocator.__gt_device_type__}, but device type {device.device_type} was specified." diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py index 33390eda27..ab250c6ca5 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py @@ -301,6 +301,34 @@ def test_missing_out_is_rejected(device, backend): ) +def test_backend_allocates_arrays_of_its_library(library, backend): + field = gtx.zeros(gtx.domain({IDim: 3}), allocator=backend) + + if library == "jax": + import jax + + assert isinstance(field.ndarray, jax.Array) + else: + import torch + + assert isinstance(field.ndarray, torch.Tensor) + + +@pytest.mark.requires_torch +@pytest.mark.requires_gpu +def test_torch_compile_allocates_on_the_given_device(): + from gt4py._core import definitions as core_defs + from gt4py.next.program_processors.runners.experimental import torch_compile + + field = gtx.zeros( + gtx.domain({IDim: 3}), + allocator=torch_compile.torch_compile, + device=core_defs.Device(core_defs.DeviceType.CUDA, 0), + ) + + assert field.ndarray.is_cuda + + def test_exported_from_experimental(library, backend): from gt4py.next import experimental From 2aad236d86b948521ee2c43d273c570a3663ff6b Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 01:29:26 +0000 Subject: [PATCH 156/166] docs[next]: run the SWM jit targets on the experimental jax_jit and torch_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. --- examples/swm.ipynb | 121 +++++++++++---------------------------------- 1 file changed, 30 insertions(+), 91 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 8198a698c0..6078d7dfae 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -52,12 +52,12 @@ "outputs": [], "source": [ "import dataclasses\n", - "from collections.abc import Callable\n", "from typing import Any\n", "\n", "import numpy as np\n", "\n", "import gt4py.next as gtx\n", + "from gt4py.next import experimental as gtx_experimental\n", "from gt4py._core import definitions as core_defs\n", "\n", "import swm_numpy" @@ -76,9 +76,7 @@ "A `Target` names where the model runs: the `backend` that executes the field operator\n", "(`None` runs it embedded, in Python) and the `allocator` and `device` of its fields. An\n", "allocator is either a backend or an array namespace such as `numpy`, `cupy`, `jax.numpy`\n", - "or `torch`; embedded execution runs on whichever library holds the fields. An embedded\n", - "target can also name a `jit`, which compiles the time step with the compiler of its array\n", - "library." + "or `torch`; embedded execution runs on whichever library holds the fields." ] }, { @@ -105,63 +103,23 @@ "class Target:\n", " backend: Any = None\n", " allocator: Any = None\n", - " device: core_defs.Device | None = None\n", - " jit: Callable[[Callable], Callable] | None = None" + " device: core_defs.Device | None = None" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### Explicit jit\n", - "\n", - "Embedded execution runs the Python of the field operator on every call. JAX and torch can\n", - "instead trace that Python once and compile the operations it records. A `jit` gets the\n", - "model's time step\n", - "\n", - "```python\n", - "step(u, v, p, uold, vold, pold, unew, vnew, pnew, tdt, alpha)\n", - "```\n", - "\n", - "(see `Model` below), which writes the interior of the last six fields and returns them, and\n", - "gives back a compiled function with the same signature.\n", - "\n", - "`jax.jit` takes fields as JAX pytrees, whose structure includes the domain, so each grid\n", - "size is traced once. `tdt` and `alpha` are static arguments, since embedded field\n", - "operators take Python scalars but not traced ones: the forward first step and the leapfrog\n", - "steps are two traces. The six fields the step overwrites are donated, so XLA writes the\n", - "results into their buffers instead of allocating new ones.\n", - "\n", - "`torch.compile` does not trace embedded GT4Py code itself. A `torch.compiler.nonstrict_trace`\n", - "function is called opaquely by Dynamo and runs on the fake tensors of the trace, so the\n", - "graph it records is what gets compiled. `fullgraph=True` turns a graph break into an error\n", - "and `dynamic=False` keeps the domain bounds static, which they have to be in the pytree of\n", - "a field. Dynamo also guards on which of the arguments share their domain objects, and the\n", - "fields a compiled call returns have domains of their own, so the first few steps compile\n", - "again until that sharing settles. All models share Dynamo's cache, which holds a limited\n", - "number of graphs per compiled function, so each model starts with an empty one.\n", - "`torch.compiler.reset()` clears everything Dynamo has compiled in the process, not only the\n", - "previous model's step." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def jax_jit(step: Callable) -> Callable:\n", - " import jax\n", - "\n", - " return jax.jit(step, static_argnums=(9, 10), donate_argnums=(3, 4, 5, 6, 7, 8))\n", - "\n", + "### jax.jit and torch.compile\n", "\n", - "def torch_compile(step: Callable) -> Callable:\n", - " import torch\n", + "Embedded execution runs the Python of the field operator on every call. The experimental\n", + "backends `gtx_experimental.jax_jit` and `gtx_experimental.torch_compile` instead run it\n", + "once under `jax.jit` or `torch.compile`, on fields of JAX arrays or torch tensors, and call\n", + "the compiled function from then on. They write `out=` like any other backend.\n", "\n", - " torch.compiler.reset()\n", - " traced = torch.compiler.nonstrict_trace(step)\n", - " return torch.compile(lambda *args: traced(*args), fullgraph=True, dynamic=False)" + "A program is traced again for every new field domain, so each grid size compiles once. The\n", + "scalars are traced, so `tdt` and `alpha` changing after the first step do not compile\n", + "again." ] }, { @@ -189,10 +147,10 @@ "# target = Target(gtx.dace_gpu, gtx.dace_gpu)\n", "# target = Target(None, cupy)\n", "# target = Target(None, jax.numpy)\n", - "# target = Target(None, jax.numpy, jit=jax_jit)\n", + "# target = Target(gtx_experimental.jax_jit, jax.numpy)\n", "# target = Target(None, torch)\n", "# target = Target(None, torch, CUDA)\n", - "# target = Target(None, torch, CUDA, jit=torch_compile)" + "# target = Target(gtx_experimental.torch_compile, torch, CUDA)" ] }, { @@ -356,15 +314,15 @@ "source": [ "## Time loop\n", "\n", - "`uold`, `vold` and `pold` are never swapped; only the prognostic fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", + "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", + "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", "with the filter switched off, which is how the leapfrog scheme is started.\n", "\n", - "A `Model` holds the fields of one integration and the time step bound to its target, so\n", - "that repeated calls of `advance` continue the same integration with the same compiled or\n", - "traced operator. The step returns the fields it wrote and `advance` rebinds them: a\n", - "jit-compiled step returns new fields rather than writing into its arguments. The halo\n", - "refresh runs outside the step. `advance(..., periodic=False)` skips it: the results are\n", - "wrong, but the steps then run back to back without host work in between." + "A `Model` holds the fields of one integration and the field operator bound to its target,\n", + "so that repeated calls of `advance` continue the same integration with the same compiled\n", + "or traced operator. The halo refresh runs outside the field operator.\n", + "`advance(..., periodic=False)` skips it: the results are wrong, but the steps then run back\n", + "to back without host work in between." ] }, { @@ -377,29 +335,8 @@ " def __init__(self, m: int = M, n: int = N, *, target: Target):\n", " self.m, self.n = m, n\n", " self.domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", - " interior = gtx.domain({I: (0, m), J: (0, n)})\n", - " operator = timestep.with_backend(target.backend)\n", - "\n", - " def step(u, v, p, uold, vold, pold, unew, vnew, pnew, tdt, alpha):\n", - " out = (unew, vnew, pnew, uold, vold, pold)\n", - " operator(\n", - " u,\n", - " v,\n", - " p,\n", - " uold,\n", - " vold,\n", - " pold,\n", - " DX,\n", - " DY,\n", - " tdt,\n", - " alpha,\n", - " out=out,\n", - " domain=interior,\n", - " offset_provider={},\n", - " )\n", - " return out\n", - "\n", - " self.step = step if target.jit is None else target.jit(step)\n", + " self.interior = gtx.domain({I: (0, m), J: (0, n)})\n", + " self.step = timestep.with_backend(target.backend)\n", " self.cycle = 0\n", "\n", " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", @@ -422,18 +359,20 @@ " tdt = DT if self.cycle == 0 else 2.0 * DT\n", " alpha = 0.0 if self.cycle == 0 else ALPHA\n", "\n", - " self.unew, self.vnew, self.pnew, self.uold, self.vold, self.pold = self.step(\n", + " self.step(\n", " self.u,\n", " self.v,\n", " self.p,\n", " self.uold,\n", " self.vold,\n", " self.pold,\n", - " self.unew,\n", - " self.vnew,\n", - " self.pnew,\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", @@ -628,14 +567,14 @@ "\n", " label = jax.default_backend()\n", " targets[f\"jax [{label}]\"] = Target(None, jax.numpy)\n", - " targets[f\"jax.jit [{label}]\"] = Target(None, jax.numpy, jit=jax_jit)\n", + " targets[f\"jax.jit [{label}]\"] = Target(gtx_experimental.jax_jit, jax.numpy)\n", " if installed(\"torch\"):\n", " import torch\n", "\n", " device = CUDA if torch.cuda.is_available() else None\n", " label = \"cuda\" if device else \"cpu\"\n", " targets[f\"torch [{label}]\"] = Target(None, torch, device)\n", - " targets[f\"torch.compile [{label}]\"] = Target(None, torch, device, jit=torch_compile)\n", + " targets[f\"torch.compile [{label}]\"] = Target(gtx_experimental.torch_compile, torch, device)\n", " return targets\n", "\n", "\n", From 6d5458433f4e38089d5a8de728b7c97fc9d57b90 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 01:29:26 +0000 Subject: [PATCH 157/166] docs[next]: write the SWM differences as in the NumPy reference (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. --- examples/swm.ipynb | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 6078d7dfae..905538337a 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -201,25 +201,25 @@ "@gtx.field_operator\n", "def delta_x(dx: gtx.float64, f: IJField) -> IJField:\n", " \"\"\"Forward difference in x.\"\"\"\n", - " return (1.0 / dx) * (f(I + 1) - f)\n", + " return (f(I + 1) - f) / dx\n", "\n", "\n", "@gtx.field_operator\n", "def delta_y(dy: gtx.float64, f: IJField) -> IJField:\n", " \"\"\"Forward difference in y.\"\"\"\n", - " return (1.0 / dy) * (f(J + 1) - f)\n", + " return (f(J + 1) - f) / dy\n", "\n", "\n", "@gtx.field_operator\n", "def delta_x_staggered(dx: gtx.float64, f: IJField) -> IJField:\n", " \"\"\"Backward difference in x, for an x-staggered field.\"\"\"\n", - " return (1.0 / dx) * (f - f(I - 1))\n", + " return (f - f(I - 1)) / dx\n", "\n", "\n", "@gtx.field_operator\n", "def delta_y_staggered(dy: gtx.float64, f: IJField) -> IJField:\n", " \"\"\"Backward difference in y, for a y-staggered field.\"\"\"\n", - " return (1.0 / dy) * (f - f(J - 1))" + " return (f - f(J - 1)) / dy" ] }, { @@ -417,8 +417,9 @@ "source": [ "STEPS = 100\n", "\n", - "# The two implementations sum the same terms in a different order, so they agree to\n", - "# rounding rather than bit-for-bit. Tolerances are absolute because u and v cross zero.\n", + "# Both implementations evaluate the same expressions, but compiled backends and the JIT\n", + "# compilers may reorder or fuse operations, so agreement is to rounding, not bit-for-bit.\n", + "# Tolerances are absolute because u and v cross zero.\n", "ATOL_UV = 3e-12 # peak |u|, |v| ~ 4\n", "ATOL_P = 1e-9 # peak |p| ~ 5e4\n", "\n", From d236c5fe1defcab4b42174fd14e9d4fa82750dc7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 01:32:19 +0000 Subject: [PATCH 158/166] feat[next]: EmbeddedBackend runs embedded on the arrays it allocates, with eager backends for numpy, cupy, jax and torch; the jit backends override its wrap --- src/gt4py/next/backend.py | 36 ++++++++++------ src/gt4py/next/experimental/__init__.py | 42 ++++++++++++++----- src/gt4py/next/ffront/decorator.py | 18 ++++---- .../{embedded_jit.py => embedded.py} | 23 ++++------ .../runners/experimental/jax_jit.py | 14 ++----- .../runners/experimental/torch_compile.py | 14 ++----- ...{test_embedded_jit.py => test_embedded.py} | 0 7 files changed, 77 insertions(+), 70 deletions(-) rename src/gt4py/next/program_processors/runners/experimental/{embedded_jit.py => embedded.py} (84%) rename tests/next_tests/unit_tests/program_processor_tests/runners_tests/{test_embedded_jit.py => test_embedded.py} (100%) diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index bd4ad84617..f477c1b77e 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -8,9 +8,9 @@ from __future__ import annotations -import abc import dataclasses -from collections.abc import Callable +import inspect +from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any, Generic from gt4py._core import definitions as core_defs @@ -181,17 +181,17 @@ def __gt_allocator__( def _not_compiled(*args: Any, **kwargs: Any) -> Any: - raise RuntimeError("An embedded jit backend runs programs embedded; it does not compile them.") + raise RuntimeError("An embedded backend runs programs embedded; it does not compile them.") @dataclasses.dataclass(frozen=True, kw_only=True) -class EmbeddedJitBackend(Backend, abc.ABC): +class EmbeddedBackend(Backend): """ - Runs programs and field operators embedded, inside the tracing compiler of an array library. + Runs programs and field operators embedded, on the arrays its allocator allocates. - Instead of compiling, it wraps the embedded execution of a program or field operator once, - e.g. in `jax.jit`. The allocator allocates arrays of the library. A stopgap until embedded - execution is represented by backends. + It does not compile. Subclasses run the embedded execution inside the tracing compiler of + the array library, e.g. `jax.jit`, by overriding `wrap`. A stopgap until embedded execution + is represented by backends. """ executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] = ( @@ -201,14 +201,26 @@ class EmbeddedJitBackend(Backend, abc.ABC): DEFAULT_TRANSFORMS ) - @abc.abstractmethod - def jit(self, entry_point: ffront_decorator.GTEntryPoint) -> Callable[..., None]: + def runner(self, entry_point: ffront_decorator.GTEntryPoint) -> Callable[..., None]: """ - `entry_point` run embedded inside the tracing compiler, called as the entry point is. + `entry_point` run embedded, wrapped by `wrap`, called as the entry point is. Called once per entry point: the result is cached by it. """ - ... + from gt4py.next.program_processors.runners.experimental import embedded + + return embedded.runner(entry_point, self.wrap) + + def wrap( + self, entry: Callable[..., None], signature: inspect.Signature, static_params: Sequence[str] + ) -> Callable[..., None]: + """ + `entry`, the embedded execution called as `signature` describes, in a tracing compiler. + + The parameters `static_params` are static. The arguments are fields, connectivities, + scalars and (nested) tuples of them. + """ + return entry @dataclasses.dataclass(frozen=True) diff --git a/src/gt4py/next/experimental/__init__.py b/src/gt4py/next/experimental/__init__.py index 3aeb012683..bb492a0ca3 100644 --- a/src/gt4py/next/experimental/__init__.py +++ b/src/gt4py/next/experimental/__init__.py @@ -17,20 +17,40 @@ "concat_where", ] -# the embedded jit backends, created on first access: they need an optional package +# the embedded backends, created on first access: they need an optional package _EMBEDDED_JIT_BACKENDS: Final = {"jax_jit": "jax", "torch_compile": "torch"} +#: The array namespace each eager embedded backend allocates with +_EMBEDDED_BACKENDS: Final = { + "embedded_numpy": "numpy", + "embedded_cupy": "cupy", + "embedded_jax": "jax.numpy", + "embedded_torch": "torch", +} def __getattr__(name: str) -> Any: - if name not in _EMBEDDED_JIT_BACKENDS: + if name in _EMBEDDED_BACKENDS: + from gt4py.next import backend as next_backend + + namespace = _EMBEDDED_BACKENDS[name] + try: + allocator = importlib.import_module(namespace) + except ImportError as error: + raise AttributeError( + f"'{name}' requires the optional '{namespace}' package." + ) from error + backend = next_backend.EmbeddedBackend(name=name, allocator=allocator) + elif name in _EMBEDDED_JIT_BACKENDS: + try: + module = importlib.import_module( + f"gt4py.next.program_processors.runners.experimental.{name}" + ) + except ImportError as error: + raise AttributeError( + f"'{name}' requires the optional '{_EMBEDDED_JIT_BACKENDS[name]}' package." + ) from error + backend = getattr(module, name) + else: raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") - try: - module = importlib.import_module( - f"gt4py.next.program_processors.runners.experimental.{name}" - ) - except ImportError as error: - raise AttributeError( - f"'{name}' requires the optional '{_EMBEDDED_JIT_BACKENDS[name]}' package." - ) from error - backend = globals()[name] = getattr(module, name) + globals()[name] = backend return backend diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 6e00b94f00..7c55253991 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -103,14 +103,14 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): @functools.cached_property def _has_compiled_backend(self) -> bool: return self.backend is not None and not isinstance( - self.backend, next_backend.EmbeddedJitBackend + self.backend, next_backend.EmbeddedBackend ) @functools.cached_property - def _embedded_jit(self) -> Callable[..., None]: - """This entry point run embedded inside the tracing compiler of its embedded jit backend.""" - assert isinstance(self.backend, next_backend.EmbeddedJitBackend) - return self.backend.jit(typing.cast(GTEntryPoint, self)) + def _embedded_runner(self) -> Callable[..., None]: + """This entry point run by its embedded backend.""" + assert isinstance(self.backend, next_backend.EmbeddedBackend) + return self.backend.runner(typing.cast(GTEntryPoint, self)) @abc.abstractmethod def __gt_type__(self) -> ts.CallableType: ... @@ -376,9 +376,9 @@ def __call__( self._compiled_programs( *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit ) - elif isinstance(self.backend, next_backend.EmbeddedJitBackend): + elif isinstance(self.backend, next_backend.EmbeddedBackend): with embedded_program_call_context(self, args, offset_provider, kwargs): - self._embedded_jit(*args, offset_provider=offset_provider, **kwargs) + self._embedded_runner(*args, offset_provider=offset_provider, **kwargs) else: # Embedded execution. warnings.warn( @@ -574,8 +574,8 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> if not embedded_context.within_valid_context(): # field_operator as program kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} - if isinstance(self.backend, next_backend.EmbeddedJitBackend): - return self._embedded_jit(*args, **kwargs) + if isinstance(self.backend, next_backend.EmbeddedBackend): + return self._embedded_runner(*args, **kwargs) attributes = ( self.definition_stage.attributes if self.definition_stage diff --git a/src/gt4py/next/program_processors/runners/experimental/embedded_jit.py b/src/gt4py/next/program_processors/runners/experimental/embedded.py similarity index 84% rename from src/gt4py/next/program_processors/runners/experimental/embedded_jit.py rename to src/gt4py/next/program_processors/runners/experimental/embedded.py index e67c74a997..db6a2a456e 100644 --- a/src/gt4py/next/program_processors/runners/experimental/embedded_jit.py +++ b/src/gt4py/next/program_processors/runners/experimental/embedded.py @@ -6,17 +6,13 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -""" -What the embedded jit backends share: the embedded execution of an entry point, as they wrap it. - -A stopgap until embedded execution is represented by backends. -""" +"""The embedded execution of an entry point, as the embedded backends run it.""" from __future__ import annotations import inspect from collections.abc import Callable, Sequence -from typing import TYPE_CHECKING, Any, TypeAlias +from typing import TYPE_CHECKING, Any from gt4py.next import common, errors, named_collections, utils from gt4py.next.embedded import context as embedded_context @@ -29,16 +25,11 @@ from gt4py.next.ffront import decorator -#: Wraps the embedded execution, called as the signature describes, in a tracing compiler, with -#: the named parameters static. The arguments are fields, connectivities, scalars and (nested) -#: tuples of them. -Wrap: TypeAlias = Callable[ - [Callable[..., None], inspect.Signature, Sequence[str]], Callable[..., None] -] - - -def jit(entry_point: decorator.GTEntryPoint, wrap: Wrap) -> Callable[..., None]: - """`entry_point` run embedded in the tracing compiler of `wrap`, called as the entry point is.""" +def runner( + entry_point: decorator.GTEntryPoint, + wrap: Callable[[Callable[..., None], inspect.Signature, Sequence[str]], Callable[..., None]], +) -> Callable[..., None]: + """`entry_point` run embedded, wrapped by `wrap`, called as the entry point is.""" callable_type = entry_point.__gt_type__() program_type = ffront_type_info.type_in_program_context(callable_type) assert isinstance(program_type, ts_ffront.ProgramType) diff --git a/src/gt4py/next/program_processors/runners/experimental/jax_jit.py b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py index 74d1efa5c5..4564bb4900 100644 --- a/src/gt4py/next/program_processors/runners/experimental/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py @@ -18,18 +18,13 @@ import dataclasses import inspect from collections.abc import Callable, Sequence -from typing import TYPE_CHECKING, Any +from typing import Any import jax import jax.numpy as jnp from gt4py.next import backend as next_backend, common from gt4py.next.embedded import nd_array_field -from gt4py.next.program_processors.runners.experimental import embedded_jit - - -if TYPE_CHECKING: - from gt4py.next.ffront import decorator def _is_field(x: Any) -> bool: @@ -78,7 +73,7 @@ def _assignable_fields(tree: Any) -> list[nd_array_field.NdArrayField]: @dataclasses.dataclass(frozen=True, kw_only=True) -class JaxJitBackend(next_backend.EmbeddedJitBackend): +class JaxJitBackend(next_backend.EmbeddedBackend): """ Runs programs and field operators embedded, under `jax.jit`. @@ -88,10 +83,7 @@ class JaxJitBackend(next_backend.EmbeddedJitBackend): field in the trace, so its aliases see the assignment. """ - def jit(self, entry_point: decorator.GTEntryPoint) -> Callable[..., None]: - return embedded_jit.jit(entry_point, self._wrap) - - def _wrap( + def wrap( self, entry: Callable[..., None], signature: inspect.Signature, diff --git a/src/gt4py/next/program_processors/runners/experimental/torch_compile.py b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py index 1a6a8073fb..8e59d4c8d4 100644 --- a/src/gt4py/next/program_processors/runners/experimental/torch_compile.py +++ b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py @@ -21,17 +21,12 @@ import dataclasses import inspect from collections.abc import Callable, Sequence -from typing import TYPE_CHECKING, Any +from typing import Any import numpy as np import torch from gt4py.next import backend as next_backend, common -from gt4py.next.program_processors.runners.experimental import embedded_jit - - -if TYPE_CHECKING: - from gt4py.next.ffront import decorator # Dynamo reports an exception of the embedded code as an unsupported output type @@ -75,7 +70,7 @@ def region(kwargs: dict[str, Any], connectivities: dict[str, Any]) -> tuple[()]: @dataclasses.dataclass(frozen=True, kw_only=True) -class TorchCompileBackend(next_backend.EmbeddedJitBackend): +class TorchCompileBackend(next_backend.EmbeddedBackend): """ Runs programs and field operators embedded, under `torch.compile`. @@ -84,10 +79,7 @@ class TorchCompileBackend(next_backend.EmbeddedJitBackend): combination of their values. The `out` fields are assigned to in place. """ - def jit(self, entry_point: decorator.GTEntryPoint) -> Callable[..., None]: - return embedded_jit.jit(entry_point, self._wrap) - - def _wrap( + def wrap( self, entry: Callable[..., None], signature: inspect.Signature, diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py similarity index 100% rename from tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded_jit.py rename to tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py From 6a8861b5f0a55f60e0411935e0d835459674b8e5 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 01:32:19 +0000 Subject: [PATCH 159/166] test[next]: eager embedded backends: programs, field operators, allocation, no compile --- tests/next_tests/integration_tests/cases.py | 2 +- .../runners_tests/test_embedded.py | 48 +++++++++++++++++-- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index cdf282ef79..0452bbd82e 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -398,7 +398,7 @@ def allocate( def runs_embedded(case: Case) -> bool: """Whether the case's programs run embedded, i.e. are not compiled.""" - return case.backend is None or isinstance(case.backend, next_backend.EmbeddedJitBackend) + return case.backend is None or isinstance(case.backend, next_backend.EmbeddedBackend) def run( diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py index ab250c6ca5..8abdc8e52c 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py @@ -6,7 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -"""What the embedded jit backends add to embedded execution; the integration matrix runs the features.""" +"""What the embedded backends add to embedded execution; the integration matrix runs the features.""" import dataclasses import re @@ -169,8 +169,8 @@ def _e2v(device, table=E2V_TABLE): def _jitted(entry_point): - """The `jax.jit` object, under the call adapter of `embedded_jit` and the write-back of `jax_jit`.""" - return entry_point._embedded_jit.__wrapped__.__wrapped__ + """The `jax.jit` object, under the call adapter of `embedded` and the write-back of `jax_jit`.""" + return entry_point._embedded_runner.__wrapped__.__wrapped__ def test_out_assigned_in_the_callers_field(device, backend): @@ -329,6 +329,48 @@ def test_torch_compile_allocates_on_the_given_device(): assert field.ndarray.is_cuda +@pytest.fixture( + params=[ + "numpy", + pytest.param("cupy", marks=pytest.mark.requires_gpu), + pytest.param("jax", marks=pytest.mark.requires_jax), + pytest.param("torch", marks=pytest.mark.requires_torch), + ] +) +def eager_backend(request): + from gt4py.next import experimental + + return getattr(experimental, f"embedded_{request.param}") + + +def test_eager_backend_runs_on_the_arrays_it_allocates(eager_backend): + domain = gtx.domain({IDim: 3}) + a = gtx.as_field(domain, np.arange(3.0), allocator=eager_backend) + b = gtx.as_field(domain, np.zeros(3), allocator=eager_backend) + out = gtx.zeros(domain, allocator=eager_backend) + + write_then_read.with_backend(eager_backend)(a, b, out, offset_provider={}) + + assert type(out.ndarray) is type(eager_backend.allocator.zeros(1)) + np.testing.assert_array_equal(a.asnumpy(), np.arange(3.0) + 1.0) + np.testing.assert_array_equal(out.asnumpy(), np.zeros(3)) + + +def test_eager_backend_runs_field_operators(eager_backend): + domain = gtx.domain({IDim: 3}) + f = gtx.as_field(domain, np.arange(3.0), allocator=eager_backend) + out = gtx.zeros(domain, allocator=eager_backend) + + plus_one.with_backend(eager_backend)(f, out=out, domain={IDim: (1, 3)}, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), [0.0, 2.0, 3.0]) + + +def test_eager_backend_does_not_compile(eager_backend): + with pytest.raises(RuntimeError, match="does not compile"): + edge_sum_program.with_backend(eager_backend).compile(offset_provider={"E2V": None}) + + def test_exported_from_experimental(library, backend): from gt4py.next import experimental From 592a9053eaf76a05ce8f178fe17025ac30625cc5 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 01:46:29 +0000 Subject: [PATCH 160/166] docs[next]: select the SWM backend and device instead of a Target With the embedded and embedded-jit backends of #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=. --- examples/swm.ipynb | 133 +++++++++++++++++++++++---------------------- 1 file changed, 68 insertions(+), 65 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 905538337a..fd98522dda 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -51,13 +51,12 @@ "metadata": {}, "outputs": [], "source": [ - "import dataclasses\n", "from typing import Any\n", "\n", "import numpy as np\n", "\n", "import gt4py.next as gtx\n", - "from gt4py.next import experimental as gtx_experimental\n", + "from gt4py.next import backend as next_backend, experimental as gtx_experimental\n", "from gt4py._core import definitions as core_defs\n", "\n", "import swm_numpy" @@ -73,10 +72,11 @@ "three prognostic fields share this one index space; the C-grid staggering is expressed by\n", "the shifts inside the operators rather than by different array shapes.\n", "\n", - "A `Target` names where the model runs: the `backend` that executes the field operator\n", - "(`None` runs it embedded, in Python) and the `allocator` and `device` of its fields. An\n", - "allocator is either a backend or an array namespace such as `numpy`, `cupy`, `jax.numpy`\n", - "or `torch`; embedded execution runs on whichever library holds the fields." + "The backend that executes the field operator also allocates its fields. The compiled\n", + "`gtfn` and `dace` backends generate C++ or CUDA. The experimental embedded backends run the\n", + "Python of the field operator on the arrays of one library: `embedded_numpy`,\n", + "`embedded_cupy`, `embedded_jax` and `embedded_torch`. Only torch needs a `device` to put\n", + "its tensors on the GPU." ] }, { @@ -96,14 +96,7 @@ "DX = swm_numpy.DX # 100 km\n", "DY = swm_numpy.DY\n", "DT = swm_numpy.DT # 90 s\n", - "ALPHA = swm_numpy.ALPHA # Robert-Asselin filter coefficient\n", - "\n", - "\n", - "@dataclasses.dataclass(frozen=True)\n", - "class Target:\n", - " backend: Any = None\n", - " allocator: Any = None\n", - " device: core_defs.Device | None = None" + "ALPHA = swm_numpy.ALPHA # Robert-Asselin filter coefficient" ] }, { @@ -126,10 +119,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Choosing a target\n", + "### Choosing a backend\n", "\n", - "Uncomment one of the targets below. The embedded ones need their array library imported\n", - "first: `import cupy`, `import jax` or `import torch`." + "Uncomment one of the backends below." ] }, { @@ -140,17 +132,17 @@ "source": [ "CUDA = core_defs.Device(core_defs.DeviceType.CUDA, 0)\n", "\n", - "target = Target() # embedded on NumPy\n", - "# target = Target(gtx.gtfn_cpu, gtx.gtfn_cpu)\n", - "# target = Target(gtx.gtfn_gpu, gtx.gtfn_gpu)\n", - "# target = Target(gtx.dace_cpu, gtx.dace_cpu)\n", - "# target = Target(gtx.dace_gpu, gtx.dace_gpu)\n", - "# target = Target(None, cupy)\n", - "# target = Target(None, jax.numpy)\n", - "# target = Target(gtx_experimental.jax_jit, jax.numpy)\n", - "# target = Target(None, torch)\n", - "# target = Target(None, torch, CUDA)\n", - "# target = Target(gtx_experimental.torch_compile, torch, CUDA)" + "backend, device = gtx_experimental.embedded_numpy, None\n", + "# backend, device = gtx.gtfn_cpu, None\n", + "# backend, device = gtx.gtfn_gpu, None\n", + "# backend, device = gtx.dace_cpu, None\n", + "# backend, device = gtx.dace_gpu, None\n", + "# backend, device = gtx_experimental.embedded_cupy, None\n", + "# backend, device = gtx_experimental.embedded_jax, None\n", + "# backend, device = gtx_experimental.jax_jit, None\n", + "# backend, device = gtx_experimental.embedded_torch, None\n", + "# backend, device = gtx_experimental.embedded_torch, CUDA\n", + "# backend, device = gtx_experimental.torch_compile, CUDA" ] }, { @@ -318,7 +310,7 @@ "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", "with the filter switched off, which is how the leapfrog scheme is started.\n", "\n", - "A `Model` holds the fields of one integration and the field operator bound to its target,\n", + "A `Model` holds the fields of one integration and the field operator bound to its backend,\n", "so that repeated calls of `advance` continue the same integration with the same compiled\n", "or traced operator. The halo refresh runs outside the field operator.\n", "`advance(..., periodic=False)` skips it: the results are wrong, but the steps then run back\n", @@ -332,19 +324,23 @@ "outputs": [], "source": [ "class Model:\n", - " def __init__(self, m: int = M, n: int = N, *, target: Target):\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(target.backend)\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,\n", - " np.pad(a, 1, mode=\"wrap\"),\n", - " allocator=target.allocator,\n", - " device=target.device,\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", @@ -386,10 +382,15 @@ "\n", "\n", "def run(\n", - " itmax: int, m: int = M, n: int = N, *, target: Target\n", + " itmax: int,\n", + " m: int = M,\n", + " n: int = N,\n", + " *,\n", + " backend: next_backend.Backend,\n", + " device: core_defs.Device | None = None,\n", ") -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", - " model = Model(m, n, target=target)\n", + " model = Model(m, n, backend=backend, device=device)\n", " model.advance(itmax)\n", " return model.u, model.v, model.p\n", "\n", @@ -424,8 +425,8 @@ "ATOL_P = 1e-9 # peak |p| ~ 5e4\n", "\n", "\n", - "def test_matches_numpy(target: Target):\n", - " u, v, p = run(STEPS, target=target)\n", + "def test_matches_numpy(backend: next_backend.Backend, device: core_defs.Device | None = None):\n", + " u, v, p = run(STEPS, backend=backend, device=device)\n", " u_ref, v_ref, p_ref = swm_numpy.run(STEPS)\n", "\n", " np.testing.assert_allclose(interior_of(u), u_ref, atol=ATOL_UV)\n", @@ -433,7 +434,7 @@ " np.testing.assert_allclose(interior_of(p), p_ref, atol=ATOL_P)\n", "\n", "\n", - "test_matches_numpy(target)\n", + "test_matches_numpy(backend, device)\n", "print(\"GT4Py and NumPy agree after\", STEPS, \"steps\")" ] }, @@ -454,8 +455,8 @@ "metadata": {}, "outputs": [], "source": [ - "def test_matches_reference(target: Target):\n", - " u, v, p = run(swm_numpy.ITMAX, target=target)\n", + "def test_matches_reference(backend: next_backend.Backend, device: core_defs.Device | None = None):\n", + " u, v, p = run(swm_numpy.ITMAX, backend=backend, device=device)\n", " u_out, v_out, p_out = swm_numpy.to_reference_layout(\n", " interior_of(u), interior_of(v), interior_of(p)\n", " )\n", @@ -466,7 +467,7 @@ " np.testing.assert_allclose(p_out, reference[\"p\"], atol=ATOL_P)\n", "\n", "\n", - "test_matches_reference(target)\n", + "test_matches_reference(backend, device)\n", "print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" ] }, @@ -487,7 +488,7 @@ "source": [ "import matplotlib.pyplot as plt\n", "\n", - "u, v, p = run(STEPS, target=target)\n", + "u, v, p = run(STEPS, backend=backend, device=device)\n", "\n", "fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))\n", "for ax, field, name in zip(axes, (u, v, p), (\"u\", \"v\", \"p\")):\n", @@ -504,9 +505,9 @@ "source": [ "## Performance comparison\n", "\n", - "The same model on every target installed here: the compiled `gtfn` and `dace` backends on\n", + "The same model on every backend installed here: the compiled `gtfn` and `dace` backends on\n", "CPU and GPU, and embedded execution on NumPy, CuPy, JAX and torch arrays, eagerly and\n", - "under `jax.jit` and `torch.compile`. Each target is first checked against the NumPy\n", + "under `jax.jit` and `torch.compile`. Each backend is first checked against the NumPy\n", "implementation, then timed on a sweep of grid sizes.\n", "\n", "The timed steps skip the halo refresh, which runs on the host between two steps. Their\n", @@ -545,8 +546,8 @@ " return importlib.util.find_spec(module) is not None\n", "\n", "\n", - "def comparison_targets() -> dict[str, Target]:\n", - " \"\"\"Every target whose libraries and devices are available here.\"\"\"\n", + "def comparison_backends() -> dict[str, tuple[next_backend.Backend, core_defs.Device | None]]:\n", + " \"\"\"Every backend whose libraries and devices are available here, with its device.\"\"\"\n", " try:\n", " import cupy\n", "\n", @@ -554,29 +555,29 @@ " except (ImportError, RuntimeError):\n", " gpu = False\n", "\n", - " targets = {\"dace_cpu\": Target(gtx.dace_cpu, gtx.dace_cpu)}\n", + " backends = {\"dace_cpu\": (gtx.dace_cpu, None)}\n", " if gpu:\n", - " targets[\"dace_gpu\"] = Target(gtx.dace_gpu, gtx.dace_gpu)\n", - " targets[\"gtfn_cpu\"] = Target(gtx.gtfn_cpu, gtx.gtfn_cpu)\n", + " backends[\"dace_gpu\"] = (gtx.dace_gpu, None)\n", + " backends[\"gtfn_cpu\"] = (gtx.gtfn_cpu, None)\n", " if gpu:\n", - " targets[\"gtfn_gpu\"] = Target(gtx.gtfn_gpu, gtx.gtfn_gpu)\n", - " targets[\"numpy\"] = Target(None, np)\n", + " backends[\"gtfn_gpu\"] = (gtx.gtfn_gpu, None)\n", + " backends[\"numpy\"] = (gtx_experimental.embedded_numpy, None)\n", " if gpu:\n", - " targets[\"cupy\"] = Target(None, cupy)\n", + " backends[\"cupy\"] = (gtx_experimental.embedded_cupy, None)\n", " if installed(\"jax\"):\n", " import jax\n", "\n", " label = jax.default_backend()\n", - " targets[f\"jax [{label}]\"] = Target(None, jax.numpy)\n", - " targets[f\"jax.jit [{label}]\"] = Target(gtx_experimental.jax_jit, jax.numpy)\n", + " backends[f\"jax [{label}]\"] = (gtx_experimental.embedded_jax, None)\n", + " backends[f\"jax.jit [{label}]\"] = (gtx_experimental.jax_jit, None)\n", " if installed(\"torch\"):\n", " import torch\n", "\n", " device = CUDA if torch.cuda.is_available() else None\n", " label = \"cuda\" if device else \"cpu\"\n", - " targets[f\"torch [{label}]\"] = Target(None, torch, device)\n", - " targets[f\"torch.compile [{label}]\"] = Target(gtx_experimental.torch_compile, torch, device)\n", - " return targets\n", + " backends[f\"torch [{label}]\"] = (gtx_experimental.embedded_torch, device)\n", + " backends[f\"torch.compile [{label}]\"] = (gtx_experimental.torch_compile, device)\n", + " return backends\n", "\n", "\n", "def wait(model: Model) -> None:\n", @@ -594,9 +595,11 @@ " torch.cuda.synchronize(buffer.device)\n", "\n", "\n", - "def time_steps(size: int, target: Target) -> dict[str, Any]:\n", + "def time_steps(\n", + " size: int, backend: next_backend.Backend, device: core_defs.Device | None\n", + ") -> dict[str, Any]:\n", " \"\"\"Return the time of the first step and the time per step of each timed block.\"\"\"\n", - " model = Model(size, size, target=target)\n", + " model = Model(size, size, backend=backend, device=device)\n", "\n", " start = time.perf_counter()\n", " model.advance(1, periodic=False)\n", @@ -618,13 +621,13 @@ "\n", "\n", "def compare(grid_sizes=GRID_SIZES) -> dict[str, dict[int, dict[str, Any]]]:\n", - " \"\"\"Validate every target, then time it on every grid size.\"\"\"\n", + " \"\"\"Validate every backend, then time it on every grid size.\"\"\"\n", " timings = {}\n", - " for name, comparison_target in comparison_targets().items():\n", - " test_matches_numpy(comparison_target)\n", + " for name, (comparison_backend, comparison_device) in comparison_backends().items():\n", + " test_matches_numpy(comparison_backend, comparison_device)\n", " timings[name] = {}\n", " for size in grid_sizes:\n", - " timings[name][size] = time_steps(size, comparison_target)\n", + " timings[name][size] = time_steps(size, comparison_backend, comparison_device)\n", " median = 1e3 * statistics.median(timings[name][size][\"per_step\"])\n", " print(f\"{name:24} {size:5}^2 {median:10.3f} ms/step\", flush=True)\n", " return timings\n", From 8747db4dbd5d72143b7d7f7c2356a20dcab557e6 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 01:47:43 +0000 Subject: [PATCH 161/166] docs[next]: move the SWM example into examples/swm with a README --- examples/swm/README.md | 11 +++++++++++ examples/{ => swm}/swm.ipynb | 0 examples/{ => swm}/swm_numpy.py | 0 examples/{ => swm}/swm_reference.npz | Bin 4 files changed, 11 insertions(+) create mode 100644 examples/swm/README.md rename examples/{ => swm}/swm.ipynb (100%) rename examples/{ => swm}/swm_numpy.py (100%) rename examples/{ => swm}/swm_reference.npz (100%) diff --git a/examples/swm/README.md b/examples/swm/README.md new file mode 100644 index 0000000000..e7b544f3e5 --- /dev/null +++ b/examples/swm/README.md @@ -0,0 +1,11 @@ +# Shallow water model + +The NCAR [SWM](https://github.com/NCAR/SWM) shallow water benchmark written with `gt4py.next`. +Start with the notebook; the other two files only support it. + +- `swm.ipynb`: the model, a choice of backends, its validation, and an opt-in performance + comparison across all backends. +- `swm_numpy.py`: a NumPy implementation of the same scheme, which the notebook validates + against. +- `swm_reference.npz`: `u`, `v` and `p` after the full 4000-step benchmark on the 16x16 grid, + from NCAR/SWM `ref/16x16`. diff --git a/examples/swm.ipynb b/examples/swm/swm.ipynb similarity index 100% rename from examples/swm.ipynb rename to examples/swm/swm.ipynb diff --git a/examples/swm_numpy.py b/examples/swm/swm_numpy.py similarity index 100% rename from examples/swm_numpy.py rename to examples/swm/swm_numpy.py diff --git a/examples/swm_reference.npz b/examples/swm/swm_reference.npz similarity index 100% rename from examples/swm_reference.npz rename to examples/swm/swm_reference.npz From 957a0451e5ac9081c3d97f3664199979ed51590a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 10:02:57 +0000 Subject: [PATCH 162/166] fix[next]: embedded backends reject fields of another array library, bind named-collection arguments, check static_params; backend allocators can be array namespaces (review) --- src/gt4py/next/backend.py | 28 +++++---- src/gt4py/next/constructors.py | 3 +- src/gt4py/next/custom_layout_allocators.py | 9 ++- src/gt4py/next/experimental/__init__.py | 46 +++++++------- src/gt4py/next/ffront/decorator.py | 7 ++- .../runners/experimental/__init__.py | 2 +- .../runners/experimental/embedded.py | 63 ++++++++++++++----- .../runners/experimental/jax_jit.py | 11 ++-- .../runners/experimental/torch_compile.py | 7 ++- 9 files changed, 116 insertions(+), 60 deletions(-) diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index f477c1b77e..11774edce1 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -13,7 +13,7 @@ from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any, Generic -from gt4py._core import definitions as core_defs +from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.next import config, custom_layout_allocators as next_allocators from gt4py.next.ffront import ( foast_to_gtir, @@ -154,7 +154,10 @@ def step_order(self, inp: stages.ConcreteProgramDef) -> list[str]: class Backend(Generic[core_defs.DeviceTypeT]): name: str executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] - allocator: next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + allocator: ( + next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + | core_ndarray_utils.ArrayNamespace + ) transforms: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgramDef] def compile( @@ -176,7 +179,10 @@ def load_artifact(self, artifact: artifacts.CompilationArtifact) -> artifacts.Ex @property def __gt_allocator__( self, - ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: + ) -> ( + next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + | core_ndarray_utils.ArrayNamespace + ): return self.allocator @@ -187,11 +193,11 @@ def _not_compiled(*args: Any, **kwargs: Any) -> Any: @dataclasses.dataclass(frozen=True, kw_only=True) class EmbeddedBackend(Backend): """ - Runs programs and field operators embedded, on the arrays its allocator allocates. + Runs programs and field operators embedded, on arrays of its allocator's array namespace. - It does not compile. Subclasses run the embedded execution inside the tracing compiler of - the array library, e.g. `jax.jit`, by overriding `wrap`. A stopgap until embedded execution - is represented by backends. + It does not compile, and it raises for fields of another array library. Subclasses run the + embedded execution inside the tracing compiler of the library, e.g. `jax.jit`, by + overriding `wrap`. """ executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] = ( @@ -209,16 +215,16 @@ def runner(self, entry_point: ffront_decorator.GTEntryPoint) -> Callable[..., No """ from gt4py.next.program_processors.runners.experimental import embedded - return embedded.runner(entry_point, self.wrap) + return embedded.runner(entry_point, self.wrap, self.allocator) def wrap( self, entry: Callable[..., None], signature: inspect.Signature, static_params: Sequence[str] ) -> Callable[..., None]: """ - `entry`, the embedded execution called as `signature` describes, in a tracing compiler. + `entry`, the embedded execution called as `signature` describes, as the backend runs it. - The parameters `static_params` are static. The arguments are fields, connectivities, - scalars and (nested) tuples of them. + Subclasses wrap it in a tracing compiler, with the parameters `static_params` static. The + arguments are fields, connectivities, scalars and (nested) tuples of them. """ return entry diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index 940b550f92..11453d5138 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -76,6 +76,7 @@ def __init__( device = DEFAULT_DEVICE # Currently we use optimized CPU layout, but possibly we could also use standard numpy allocation allocator = next_allocators.device_allocators[device.device_type] + requested = allocator if next_allocators.is_field_allocator_factory(allocator): allocator = allocator.__gt_allocator__ @@ -106,7 +107,7 @@ def __init__( aligned_index=aligned_index, ) else: - raise ValueError(f"Invalid field allocator: {allocator}.") + raise ValueError(f"Invalid field allocator: {requested}.") def _construct_from_array( self, diff --git a/src/gt4py/next/custom_layout_allocators.py b/src/gt4py/next/custom_layout_allocators.py index 8451863cc3..5ae3844c77 100644 --- a/src/gt4py/next/custom_layout_allocators.py +++ b/src/gt4py/next/custom_layout_allocators.py @@ -15,6 +15,7 @@ from typing_extensions import Protocol, TypeIs import gt4py._core.definitions as core_defs +import gt4py._core.ndarray_utils as core_ndarray_utils import gt4py.next.common as common import gt4py.storage.allocators as core_allocators @@ -56,7 +57,11 @@ class FieldBufferAllocatorFactoryProtocol(Protocol[core_defs.DeviceTypeT]): @property @abc.abstractmethod - def __gt_allocator__(self) -> FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: ... + def __gt_allocator__( + self, + ) -> ( + FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] | core_ndarray_utils.ArrayNamespace + ): ... def is_field_allocator_factory(obj: Any) -> TypeIs[FieldBufferAllocatorFactoryProtocol]: @@ -66,7 +71,7 @@ def is_field_allocator_factory(obj: Any) -> TypeIs[FieldBufferAllocatorFactoryPr def is_field_allocator_factory_for( obj: Any, device: core_defs.DeviceTypeT ) -> TypeIs[FieldBufferAllocatorFactoryProtocol[core_defs.DeviceTypeT]]: - return is_field_allocator_factory(obj) and obj.__gt_allocator__.__gt_device_type__ is device + return is_field_allocator_factory(obj) and is_field_allocator_for(obj.__gt_allocator__, device) FieldBufferAllocationUtil = ( diff --git a/src/gt4py/next/experimental/__init__.py b/src/gt4py/next/experimental/__init__.py index bb492a0ca3..0e0ed99912 100644 --- a/src/gt4py/next/experimental/__init__.py +++ b/src/gt4py/next/experimental/__init__.py @@ -17,40 +17,44 @@ "concat_where", ] -# the embedded backends, created on first access: they need an optional package -_EMBEDDED_JIT_BACKENDS: Final = {"jax_jit": "jax", "torch_compile": "torch"} -#: The array namespace each eager embedded backend allocates with -_EMBEDDED_BACKENDS: Final = { +#: The eager embedded backends, and the array namespace each allocates with +_EAGER_BACKENDS: Final = { "embedded_numpy": "numpy", "embedded_cupy": "cupy", "embedded_jax": "jax.numpy", "embedded_torch": "torch", } +#: The embedded jit backends, and the optional package each needs +_JIT_BACKENDS: Final = {"jax_jit": "jax", "torch_compile": "torch"} +# the backends are created on first access, since most of them need an optional package def __getattr__(name: str) -> Any: - if name in _EMBEDDED_BACKENDS: + if name in _EAGER_BACKENDS: from gt4py.next import backend as next_backend - namespace = _EMBEDDED_BACKENDS[name] - try: - allocator = importlib.import_module(namespace) - except ImportError as error: - raise AttributeError( - f"'{name}' requires the optional '{namespace}' package." - ) from error + namespace = _EAGER_BACKENDS[name] + allocator = _import(name, namespace, namespace.partition(".")[0]) backend = next_backend.EmbeddedBackend(name=name, allocator=allocator) - elif name in _EMBEDDED_JIT_BACKENDS: - try: - module = importlib.import_module( - f"gt4py.next.program_processors.runners.experimental.{name}" - ) - except ImportError as error: - raise AttributeError( - f"'{name}' requires the optional '{_EMBEDDED_JIT_BACKENDS[name]}' package." - ) from error + elif name in _JIT_BACKENDS: + module = _import( + name, f"gt4py.next.program_processors.runners.experimental.{name}", _JIT_BACKENDS[name] + ) backend = getattr(module, name) else: raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") globals()[name] = backend return backend + + +def __dir__() -> list[str]: + return [*globals(), *_EAGER_BACKENDS, *_JIT_BACKENDS] + + +def _import(backend: str, module: str, package: str) -> Any: + try: + return importlib.import_module(module) + except ModuleNotFoundError as error: + if (error.name or "").partition(".")[0] != package: + raise + raise AttributeError(f"'{backend}' requires the optional '{package}' package.") from error diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 7c55253991..8affea5d47 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -23,7 +23,7 @@ from typing import Any, Generic, Optional, Self, Sequence, TypeAlias, Unpack, override from gt4py import eve -from gt4py._core import definitions as core_defs +from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.eve import xtyping from gt4py.next import ( backend as next_backend, @@ -285,7 +285,10 @@ def __name__(self) -> str: @functools.cached_property def __gt_allocator__( self, - ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: + ) -> ( + next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + | core_ndarray_utils.ArrayNamespace + ): if self.backend: return self.backend.__gt_allocator__ else: diff --git a/src/gt4py/next/program_processors/runners/experimental/__init__.py b/src/gt4py/next/program_processors/runners/experimental/__init__.py index c2291e97e3..91b29f7772 100644 --- a/src/gt4py/next/program_processors/runners/experimental/__init__.py +++ b/src/gt4py/next/program_processors/runners/experimental/__init__.py @@ -7,4 +7,4 @@ # SPDX-License-Identifier: BSD-3-Clause -"""Experimental backends: embedded execution inside the tracing compiler of an array library.""" +"""Experimental backends: embedded execution, eager or inside the tracing compiler of an array library.""" diff --git a/src/gt4py/next/program_processors/runners/experimental/embedded.py b/src/gt4py/next/program_processors/runners/experimental/embedded.py index db6a2a456e..efa3c9e288 100644 --- a/src/gt4py/next/program_processors/runners/experimental/embedded.py +++ b/src/gt4py/next/program_processors/runners/experimental/embedded.py @@ -14,8 +14,9 @@ from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any +from gt4py._core import ndarray_utils as core_ndarray_utils from gt4py.next import common, errors, named_collections, utils -from gt4py.next.embedded import context as embedded_context +from gt4py.next.embedded import array_ops, context as embedded_context, nd_array_field from gt4py.next.ffront import type_info as ffront_type_info, type_specifications as ts_ffront from gt4py.next.otf import arguments from gt4py.next.type_system import type_info, type_specifications as ts @@ -28,8 +29,14 @@ def runner( entry_point: decorator.GTEntryPoint, wrap: Callable[[Callable[..., None], inspect.Signature, Sequence[str]], Callable[..., None]], + allocator: Any, ) -> Callable[..., None]: - """`entry_point` run embedded, wrapped by `wrap`, called as the entry point is.""" + """ + `entry_point` run embedded, wrapped by `wrap`, called as the entry point is. + + It raises for fields and connectivities of another array library than `allocator`, if that + is an array namespace. + """ callable_type = entry_point.__gt_type__() program_type = ffront_type_info.type_in_program_context(callable_type) assert isinstance(program_type, ts_ffront.ProgramType) @@ -45,6 +52,15 @@ def runner( *(entry_point.compilation_options.static_params or ()), *([] if is_program else ["domain"]), ) + if unknown := set(static_params) - signature.parameters.keys(): + raise ValueError( + f"Static parameters {sorted(unknown)} are not parameters of the entry point." + ) + expected = ( + array_ops.of(allocator.empty((0,))) + if core_ndarray_utils.is_array_namespace(allocator) + else None + ) # a field operator called in an embedded context runs embedded run = entry_point.definition_stage.definition if is_program else entry_point @@ -53,7 +69,7 @@ def run_embedded(*args: Any, offset_provider: common.OffsetProvider, **kwargs: A with embedded_context.update(offset_provider=offset_provider): run(*args, **kwargs) - # named collections reach the tracing compiler as tuples, which are pytrees in every library + # named collections reach `wrap` as tuples, which are pytrees in every array library params = program_type.definition.pos_or_kw_args | program_type.definition.kw_only_args constructors = { name: _named_collection_constructor(type_) @@ -66,31 +82,48 @@ def with_named_collections(**kwargs: Any) -> None: **{name: constructors.get(name, _identity)(value) for name, value in kwargs.items()} ) - jitted = wrap( + wrapped = wrap( with_named_collections if constructors else run_embedded, signature, static_params ) - param_names = tuple(program_type.definition.pos_or_kw_args) def call(*args: Any, **kwargs: Any) -> None: if not is_program: if "out" not in kwargs: raise errors.MissingArgumentError(None, "out", True) if "domain" in kwargs: - # a `Domain` is static in the tracing compiler, a `dict` is not + # a `Domain` can be a static argument of a tracing compiler, a `dict` cannot kwargs["domain"] = utils.tree_map(common.domain)(kwargs["domain"]) if constructors: - kwargs = {**dict(zip(param_names, args)), **kwargs} - args = () - kwargs = { - name: arguments.extract(value) if name in constructors else value - for name, value in kwargs.items() - } - jitted(*args, **kwargs) - - call.__wrapped__ = jitted # type: ignore[attr-defined] + args, kwargs = ( + (), + { + name: arguments.extract(value) if name in constructors else value + for name, value in signature.bind(*args, **kwargs).arguments.items() + }, + ) + if expected is not None: + _check_array_library(expected, (args, kwargs)) + wrapped(*args, **kwargs) + + call.__wrapped__ = wrapped # type: ignore[attr-defined] return call +def _check_array_library(expected: array_ops.ArrayOps, value: Any) -> None: + if isinstance(value, nd_array_field.NdArrayField): + if array_ops.of(value._ndarray) is not expected: + raise TypeError( + f"A field of '{type(value._ndarray).__module__}.{type(value._ndarray).__name__}'" + f" arrays, but the backend runs on '{expected.xp.__name__}' arrays." + ) + elif isinstance(value, tuple | list): + for element in value: + _check_array_library(expected, element) + elif isinstance(value, dict): + for element in value.values(): + _check_array_library(expected, element) + + def _keyword_only(name: str, **kwargs: Any) -> inspect.Parameter: return inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, **kwargs) diff --git a/src/gt4py/next/program_processors/runners/experimental/jax_jit.py b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py index 4564bb4900..c5c0ca6d59 100644 --- a/src/gt4py/next/program_processors/runners/experimental/jax_jit.py +++ b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py @@ -18,11 +18,12 @@ import dataclasses import inspect from collections.abc import Callable, Sequence -from typing import Any +from typing import Any, cast import jax import jax.numpy as jnp +from gt4py._core import ndarray_utils as core_ndarray_utils from gt4py.next import backend as next_backend, common from gt4py.next.embedded import nd_array_field @@ -53,13 +54,13 @@ def _mark_aliases(tree: Any) -> Any: if isinstance(leaf, common.Field) and (index := first.setdefault(id(leaf), i)) != i: leaves[i] = _Alias(index) aliased = True - return treedef.unflatten(leaves) if aliased else tree + return jax.tree.unflatten(treedef, leaves) if aliased else tree def _resolve_aliases(tree: Any) -> Any: leaves, treedef = jax.tree.flatten(tree, is_leaf=_is_field_or_alias) - return treedef.unflatten( - [leaves[leaf.index] if isinstance(leaf, _Alias) else leaf for leaf in leaves] + return jax.tree.unflatten( + treedef, [leaves[leaf.index] if isinstance(leaf, _Alias) else leaf for leaf in leaves] ) @@ -113,4 +114,4 @@ def run(*args: Any, **kwargs: Any) -> None: return run -jax_jit = JaxJitBackend(name="jax_jit", allocator=jnp) +jax_jit = JaxJitBackend(name="jax_jit", allocator=cast(core_ndarray_utils.ArrayNamespace, jnp)) diff --git a/src/gt4py/next/program_processors/runners/experimental/torch_compile.py b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py index 8e59d4c8d4..7d6eceea77 100644 --- a/src/gt4py/next/program_processors/runners/experimental/torch_compile.py +++ b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py @@ -21,11 +21,12 @@ import dataclasses import inspect from collections.abc import Callable, Sequence -from typing import Any +from typing import Any, cast import numpy as np import torch +from gt4py._core import ndarray_utils as core_ndarray_utils from gt4py.next import backend as next_backend, common @@ -117,4 +118,6 @@ def run(*args: Any, **kwargs: Any) -> None: return run -torch_compile = TorchCompileBackend(name="torch_compile", allocator=torch) +torch_compile = TorchCompileBackend( + name="torch_compile", allocator=cast(core_ndarray_utils.ArrayNamespace, torch) +) From dd9bd463171f83e46c3148373e9a9444444169db Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 10:02:57 +0000 Subject: [PATCH 163/166] ci: torch.compile on CPU skipped for now, 16 xdist workers for the gh200 next internal cuda13 jobs --- .cscs-ci/default.yml | 5 +++++ tests/next_tests/definitions.py | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.cscs-ci/default.yml b/.cscs-ci/default.yml index c97a85bc82..6145017c92 100644 --- a/.cscs-ci/default.yml +++ b/.cscs-ci/default.yml @@ -103,6 +103,11 @@ test_cscs_gh200: - if: $SUBPACKAGE == 'next' && $VARIANT == 'dace' && $DETAIL == 'nomesh' variables: SLURM_TIMELIMIT: "00:15:00" + - if: $SUBPACKAGE == 'next' && $VARIANT == 'internal' && $SUBVARIANT == 'cuda13' + variables: + # 32 workers run the node out of host memory + PYTEST_XDIST_AUTO_NUM_WORKERS: 16 + SLURM_TIMELIMIT: "00:15:00" - if: $SUBPACKAGE == 'next' && $VARIANT == 'internal' && $DETAIL == 'nomesh' variables: SLURM_TIMELIMIT: "00:10:00" diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 1840992b80..efd4560823 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -281,6 +281,8 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): ] JAX_JIT_SKIP_LIST = JAX_EMBEDDED_SKIP_LIST + TRACED_SCALARS_SKIP_LIST TORCH_COMPILE_SKIP_LIST = EMBEDDED_SKIP_LIST + TRACED_SCALARS_SKIP_LIST +# TODO(havogt): inductor builds CPU code with `$CXX`, which is `hipcc` on the ROCm CI and fails +TORCH_COMPILE_CPU_MESSAGE = "'torch.compile' on CPU is skipped for now." ARRAY_API_STRICT_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_MATH_OUTSIDE_ARRAY_API, XFAIL, "Not in the Array API standard."), ] @@ -331,7 +333,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): OptionalProgramBackendId.DACE_GPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_CPU_NO_OPT: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.JAX_JIT: JAX_JIT_SKIP_LIST, - OptionalProgramBackendId.TORCH_COMPILE: TORCH_COMPILE_SKIP_LIST, + OptionalProgramBackendId.TORCH_COMPILE: [(ALL, SKIP, TORCH_COMPILE_CPU_MESSAGE)], OptionalProgramBackendId.TORCH_COMPILE_CUDA: TORCH_COMPILE_SKIP_LIST, ProgramBackendId.GTFN_CPU: GTFN_SKIP_TEST_LIST + [(USES_SCAN_NESTED, XFAIL, UNSUPPORTED_MESSAGE)], From e18797b3bbfc019b36a742fcae6a948fd810bcfc Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 10:02:57 +0000 Subject: [PATCH 164/166] test[next]: embedded backends: library check, argument binding, static_params, lazy creation; one compile test for all --- .../runners_tests/test_embedded.py | 105 ++++++++++++++++-- 1 file changed, 98 insertions(+), 7 deletions(-) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py index 8abdc8e52c..630cf321b3 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py @@ -17,6 +17,8 @@ import gt4py.next as gtx from gt4py.next import astype, broadcast, common, int32, neighbor_sum +from next_tests import definitions + IDim = gtx.Dimension("IDim") Vertex = gtx.Dimension("Vertex") @@ -115,6 +117,8 @@ def device(request, library): if request.param == "gpu" and not torch.cuda.is_available(): pytest.skip("no torch CUDA device") + if request.param == "cpu": + pytest.skip(definitions.TORCH_COMPILE_CPU_MESSAGE) return torch.device("cuda" if request.param == "gpu" else "cpu") @@ -343,7 +347,7 @@ def eager_backend(request): return getattr(experimental, f"embedded_{request.param}") -def test_eager_backend_runs_on_the_arrays_it_allocates(eager_backend): +def test_eager_backend_runs_programs(eager_backend): domain = gtx.domain({IDim: 3}) a = gtx.as_field(domain, np.arange(3.0), allocator=eager_backend) b = gtx.as_field(domain, np.zeros(3), allocator=eager_backend) @@ -351,7 +355,6 @@ def test_eager_backend_runs_on_the_arrays_it_allocates(eager_backend): write_then_read.with_backend(eager_backend)(a, b, out, offset_provider={}) - assert type(out.ndarray) is type(eager_backend.allocator.zeros(1)) np.testing.assert_array_equal(a.asnumpy(), np.arange(3.0) + 1.0) np.testing.assert_array_equal(out.asnumpy(), np.zeros(3)) @@ -366,9 +369,63 @@ def test_eager_backend_runs_field_operators(eager_backend): np.testing.assert_array_equal(out.asnumpy(), [0.0, 2.0, 3.0]) -def test_eager_backend_does_not_compile(eager_backend): - with pytest.raises(RuntimeError, match="does not compile"): - edge_sum_program.with_backend(eager_backend).compile(offset_provider={"E2V": None}) +@pytest.fixture( + params=[ + pytest.param("embedded_jax", marks=pytest.mark.requires_jax), + pytest.param("embedded_torch", marks=pytest.mark.requires_torch), + pytest.param("jax_jit", marks=pytest.mark.requires_jax), + pytest.param("torch_compile", marks=pytest.mark.requires_torch), + ] +) +def non_numpy_backend(request): + from gt4py.next import experimental + + return getattr(experimental, request.param) + + +def test_fields_of_another_library_are_rejected(non_numpy_backend): + domain = gtx.domain({IDim: 3}) + f = gtx.as_field(domain, np.arange(3.0), allocator=non_numpy_backend) + numpy_out = gtx.zeros(domain, allocator=np) + + with pytest.raises(TypeError, match="numpy.ndarray"): + plus_one.with_backend(non_numpy_backend)(f, out=numpy_out, offset_provider={}) + + +def test_connectivities_of_another_library_are_rejected(non_numpy_backend): + f = gtx.as_field([Vertex], np.arange(4.0), allocator=non_numpy_backend) + out = gtx.zeros(gtx.domain({Edge: 5}), allocator=non_numpy_backend) + numpy_e2v = common._connectivity( + E2V_TABLE, codomain=Vertex, domain=common.domain({Edge: 5, E2VDim: 2}) + ) + + with pytest.raises(TypeError, match="numpy.ndarray"): + edge_sum_program.with_backend(non_numpy_backend)(f, out, offset_provider={"E2V": numpy_e2v}) + + +@gtx.field_operator +def first(p: Pair) -> gtx.Field[[IDim], gtx.float64]: + return p.first + + +def test_arguments_are_bound_as_by_the_entry_point(eager_backend): + domain = gtx.domain({IDim: 3}) + f = gtx.as_field(domain, np.arange(3.0), allocator=eager_backend) + out = gtx.zeros(domain, allocator=eager_backend) + fo = first.with_backend(eager_backend) + + with pytest.raises(TypeError): + fo(Pair(first=f, second=f), f, out=out, offset_provider={}) + with pytest.raises(TypeError): + fo(Pair(first=f, second=f), p=Pair(first=out, second=out), out=out, offset_provider={}) + + +def test_unknown_static_params_are_rejected(eager_backend): + fo = scale.with_backend(eager_backend).with_compilation_options(static_params=("m",)) + f = gtx.as_field(gtx.domain({IDim: 3}), np.arange(3.0), allocator=eager_backend) + + with pytest.raises(ValueError, match="'m'"): + fo(f, int32(1), out=f, offset_provider={}) def test_exported_from_experimental(library, backend): @@ -377,6 +434,40 @@ def test_exported_from_experimental(library, backend): assert getattr(experimental, {"jax": "jax_jit", "torch": "torch_compile"}[library]) is backend -def test_compile_is_rejected(backend): +def test_eager_backend_is_created_once(eager_backend): + from gt4py.next import backend as next_backend, experimental + + assert isinstance(eager_backend, next_backend.EmbeddedBackend) + assert getattr(experimental, eager_backend.name) is eager_backend + + +def test_missing_optional_package_is_reported(monkeypatch): + import sys + + from gt4py.next import experimental + + monkeypatch.delitem(vars(experimental), "embedded_cupy", raising=False) + monkeypatch.setitem(sys.modules, "cupy", None) + + with pytest.raises(AttributeError, match="optional 'cupy' package"): + experimental.embedded_cupy + + +@pytest.mark.parametrize( + "name", + [ + "embedded_numpy", + pytest.param("embedded_cupy", marks=pytest.mark.requires_gpu), + pytest.param("embedded_jax", marks=pytest.mark.requires_jax), + pytest.param("embedded_torch", marks=pytest.mark.requires_torch), + pytest.param("jax_jit", marks=pytest.mark.requires_jax), + pytest.param("torch_compile", marks=pytest.mark.requires_torch), + ], +) +def test_compile_is_rejected(name): + from gt4py.next import experimental + with pytest.raises(RuntimeError, match="does not compile"): - edge_sum_program.with_backend(backend).compile(offset_provider={"E2V": None}) + edge_sum_program.with_backend(getattr(experimental, name)).compile( + offset_provider={"E2V": None} + ) From 4ba3a855d4e6ff7e0a497c49597d6eff0d7a44b4 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 10:25:42 +0000 Subject: [PATCH 165/166] docs[next]: SWM notes on features being worked on and on the dispatch overhead real models hide (review) --- examples/swm/swm.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/swm/swm.ipynb b/examples/swm/swm.ipynb index fd98522dda..6e69a4a5b9 100644 --- a/examples/swm/swm.ipynb +++ b/examples/swm/swm.ipynb @@ -157,7 +157,7 @@ "cell centres, `u` and `cu` on $x$-faces, `v` and `cv` on $y$-faces, and `z` on corners.\n", "\n", "Staggered dimensions would remove the need for the two shift directions, and operators\n", - "generic over the dimension would remove the separate $x$ and $y$ variants." + "generic over the dimension would remove the separate $x$ and $y$ variants, which are features currently being worked on." ] }, { @@ -513,7 +513,7 @@ "The timed steps skip the halo refresh, which runs on the host between two steps. Their\n", "results are therefore wrong, but the steps run back to back: GPU work is launched\n", "asynchronously and the host's dispatch of the next step overlaps with the device's\n", - "execution of the previous one.\n", + "execution of the previous one. This emulates real-world use cases: in more complex models the Python dispatch overhead is hidden even on smaller grids.\n", "\n", "The first steps include compilation and the first leapfrog step uses different scalars, so\n", "`WARMUP_STEPS` run before any timing; the first step is reported separately. Then\n", From b561a5bddc70ba5d473cebd1bed8a5e0e8f9a36a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 12:04:47 +0000 Subject: [PATCH 166/166] docs[next]: select the device of the SWM JAX backends, as for torch --- examples/swm/swm.ipynb | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/examples/swm/swm.ipynb b/examples/swm/swm.ipynb index 6e69a4a5b9..b30704e716 100644 --- a/examples/swm/swm.ipynb +++ b/examples/swm/swm.ipynb @@ -75,8 +75,8 @@ "The backend that executes the field operator also allocates its fields. The compiled\n", "`gtfn` and `dace` backends generate C++ or CUDA. The experimental embedded backends run the\n", "Python of the field operator on the arrays of one library: `embedded_numpy`,\n", - "`embedded_cupy`, `embedded_jax` and `embedded_torch`. Only torch needs a `device` to put\n", - "its tensors on the GPU." + "`embedded_cupy`, `embedded_jax` and `embedded_torch`. JAX and torch take a `device` to choose\n", + "between CPU and GPU; without one, JAX uses its default device and torch the CPU." ] }, { @@ -130,6 +130,7 @@ "metadata": {}, "outputs": [], "source": [ + "CPU = core_defs.Device(core_defs.DeviceType.CPU, 0)\n", "CUDA = core_defs.Device(core_defs.DeviceType.CUDA, 0)\n", "\n", "backend, device = gtx_experimental.embedded_numpy, None\n", @@ -138,9 +139,11 @@ "# backend, device = gtx.dace_cpu, None\n", "# backend, device = gtx.dace_gpu, None\n", "# backend, device = gtx_experimental.embedded_cupy, None\n", - "# backend, device = gtx_experimental.embedded_jax, None\n", - "# backend, device = gtx_experimental.jax_jit, None\n", - "# backend, device = gtx_experimental.embedded_torch, None\n", + "# backend, device = gtx_experimental.embedded_jax, CPU\n", + "# backend, device = gtx_experimental.embedded_jax, CUDA\n", + "# backend, device = gtx_experimental.jax_jit, CPU\n", + "# backend, device = gtx_experimental.jax_jit, CUDA\n", + "# backend, device = gtx_experimental.embedded_torch, CPU\n", "# backend, device = gtx_experimental.embedded_torch, CUDA\n", "# backend, device = gtx_experimental.torch_compile, CUDA" ] @@ -567,9 +570,10 @@ " if installed(\"jax\"):\n", " import jax\n", "\n", - " label = jax.default_backend()\n", - " backends[f\"jax [{label}]\"] = (gtx_experimental.embedded_jax, None)\n", - " backends[f\"jax.jit [{label}]\"] = (gtx_experimental.jax_jit, None)\n", + " device = CUDA if jax.default_backend() == \"gpu\" else CPU\n", + " label = \"cuda\" if device is CUDA else \"cpu\"\n", + " backends[f\"jax [{label}]\"] = (gtx_experimental.embedded_jax, device)\n", + " backends[f\"jax.jit [{label}]\"] = (gtx_experimental.jax_jit, device)\n", " if installed(\"torch\"):\n", " import torch\n", "\n",