Skip to content

feat[next]: embedded jit backends for jax.jit and torch.compile - #3027

Open
havogt wants to merge 161 commits into
GridTools:mainfrom
havogt:jax-jit
Open

havogt wants to merge 161 commits into
GridTools:mainfrom
havogt:jax-jit

Conversation

@havogt

@havogt havogt commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Adds experimental jax.jit and torch.compile backends. A proper implementation will come after a planned backend refactoring, see #2956.

  • gt4py.next.experimental.jax_jit: under jax.jit.
  • gt4py.next.experimental.torch_compile: under torch.compile, through torch.compiler.nonstrict_trace.
  • gt4py.next.experimental.embedded_numpy, embedded_cupy, embedded_jax, embedded_torch: eager embedded execution.
prog.with_backend(experimental.jax_jit)(*fields, offset_provider=...)
  • EmbeddedBackend (gt4py.next.backend) is a Backend that does not compile: runner(entry_point) runs the entry point embedded, through wrap, and the result is cached on the entry point. The eager backends are instances of it. The jit backends override wrap. Calls on compiled backends take the same path as before; .compile() raises.
  • The backends allocate: gtx.zeros(domain, allocator=experimental.jax_jit), and device= for cupy and torch on CUDA. A backend whose allocator is an array namespace now allocates with it.
  • Fields, connectivities and scalars are traced. static_params, a field operator's domain=, and the offset provider's Dimensions are static.
  • out: jax returns the new buffers and the caller's fields take them; torch assigns in place.
  • Integration test matrix: new jax_jit, torch_compile and torch_compile_cuda entries. Tests that need a concrete scalar are xfailed with uses_scalar_in_control_flow, uses_scalar_in_domain or uses_scan_carry_in_control_flow.

A skip entry wrapped around to a real element of the buffer, which is
masked later but still receives a cotangent under jax.grad.

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

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

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

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

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

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

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

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

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

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

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

The constructors read the dtype of the given array through ArrayOps and
test for skip values with the namespace's 'any' instead of the NumPy
method.
torch tensors work through array_api_compat with one ArrayOps subclass
and no field class: scalar operands of elementwise functions become 0-d
tensors (Python floats as float64, as NumPy promotes them), cbrt and
gamma have torch implementations, assigned values become tensors and
conversion to NumPy detaches and copies to the host. The embedded unit
tests run on torch when it is installed.
…PI 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.
Comment thread src/gt4py/next/ffront/decorator.py Outdated
self._compiled_programs(
*args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit
)
elif self.backend is not None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Suggested change
elif self.backend is not None:
elif isinstance(self.backend, next_backend.EmbeddedJitBackend):

would that make sense?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 60546c9: both entry points check isinstance(self.backend, next_backend.EmbeddedJitBackend).

🤖 Written by an agent on behalf of @havogt

@@ -0,0 +1,120 @@
# GT4Py - GridTools Framework
#

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Let's move this and the concrete implementations into an experimental subdirectory.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

and then export it from next/experiment/__init__.py.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 60546c9 and 5f714df: program_processors/runners/experimental/{embedded_jit,jax_jit,torch_compile}.py, and gt4py.next.experimental exports jax_jit and torch_compile, lazily since they import jax and torch.

🤖 Written by an agent on behalf of @havogt

@@ -0,0 +1,50 @@
---

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Let's remove the ADR for now

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed, with its README entry and the references in backend.py and embedded_jit.py; it comes with the next push. The torch specifics it described are already in comments in torch_compile.py.

🤖 Written by an agent on behalf of @havogt

# Conflicts:
#	src/gt4py/next/__init__.py
#	src/gt4py/next/embedded/__init__.py
#	src/gt4py/next/embedded/array_ops.py
#	src/gt4py/next/embedded/nd_array_field.py
#	src/gt4py/next/embedded/operators.py
#	src/gt4py/next/ffront/fbuiltins.py
Comment thread src/gt4py/next/ffront/decorator.py Outdated
)

def __post_init__(self) -> None:
object.__setattr__(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

could we do this with a cached_property? then we wouldn't need the extra postinits and it's cleaner.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It was a cached_property at first: 43–58 ns per call, against ~30 ns for backend is not None on main, which is why it became a field. That is negligible next to a compiled call, so it is a cached_property again, _has_compiled_backend, and the __post_init__s are gone (next push).

🤖 Written by an agent on behalf of @havogt

Comment thread src/gt4py/next/ffront/decorator.py Outdated
Comment on lines +115 to +119
@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))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

do we need this cached property? Why? Is the call expensive on every call otherwise?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes. backend.jit builds a new jax.jit/torch.compile wrapper, and the trace cache belongs to the wrapper. Without the cached property, every call would rebuild the signature and retrace. It is cached per entry point, like _compiled_programs.

🤖 Written by an agent on behalf of @havogt

"""
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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

make sure all references to the ADR are removed in the end

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done; nothing refers to the ADR any more (next push).

🤖 Written by an agent on behalf of @havogt

@egparedes egparedes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

First round of comments

Comment thread src/gt4py/next/embedded/array_ops.py Outdated
Comment on lines +288 to +289
#: 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What would you think about using NDValue here as name for the type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fine: renamed to NDValue (next push).

🤖 Written by an agent on behalf of @havogt

Comment thread src/gt4py/next/ffront/decorator.py Outdated
Comment on lines +103 to +105
_is_compiled: bool = dataclasses.field(
init=False, repr=False, compare=False, metadata=utils.gt4py_metadata(fingerprint=False)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why not using a cached_property? Is it required for this to be a dataclass.field?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Also, I think the name is misleading since this only refers to a embedded jitting backend and not an actual gt4py internal compiled backend

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No, it isn't required: it was a field only to save ~20 ns per call over a cached_property. It is a cached_property again (next push). Renamed to _has_compiled_backend: it is true for gt4py's compiled backends, and false both without a backend and for the embedded jit ones.

🤖 Written by an agent on behalf of @havogt

Comment thread src/gt4py/next/ffront/decorator.py Outdated
self._compiled_programs(
*args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit
)
elif isinstance(self.backend, next_backend.EmbeddedJitBackend):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It looks like the difference between the two branches is mostly the warning, so we could drop it here and we would only need one embedded_program_call_context context handler, right? That would simplify the code quite a lot.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

They differ in more than the warning. The jit path passes offset_provider to the jitted function, which splits it into traced tables and static dimensions and sets the embedded context inside the trace. Plain embedded sets the context here and calls the definition. With one embedded_program_call_context, the branch would still need an inner if for both the context and the callee, so it comes out the same length and one level deeper. I'd keep the two branches.

🤖 Written by an agent on behalf of @havogt

@egparedes
egparedes marked this pull request as ready for review November 24, 2026 00:44
Comment on lines +90 to +96
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()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Argument handling

When named-collection constructors are present, call rewrites positional
arguments with dict(zip(param_names, args)) and then discards args.
zip silently drops extra positional arguments, and keyword arguments
override positional ones without raising TypeError. This can mask user
errors and invoke the jitted function with a silently modified argument list.
Use signature.bind or explicit validation before rewriting arguments.

Comment thread src/gt4py/next/experimental/__init__.py Outdated
Comment on lines +27 to +34
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Error handling

__getattr__ catches every ImportError while importing the backend module
and converts it into an AttributeError saying the optional package is required.
If jax or torch is installed but the backend module itself fails to import
because of an incompatible version, missing subdependency, or bug, the user gets
a misleading missing-optional-package error. Distinguish the missing optional
package from other import failures, or re-raise the original import error.

Comment on lines +108 to +111
static = (
("offset_provider", tuple(sorted(static_provider.items()))),
*sorted((name, arguments.pop(name)) for name in static_names & arguments.keys()),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Static params

The region cache key is built from static_names & arguments.keys(), so unknown
or misspelled static parameters are silently ignored. In addition, static values
must be hashable because they become part of the dict key; marking a list, dict,
or array-valued parameter static raises TypeError late. Validate that static
parameters exist in the signature and are hashable.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

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

What: A field operator with a named-collection argument can silently drop extra positional arguments or ignore positional arguments overridden by keywords.
Where: src/gt4py/next/program_processors/runners/experimental/embedded_jit.py:call
Trigger: A field operator with a named-collection `out` is called with too many positional arguments, or with the same argument both positionally and by keyword.
Detected by: nothing
Covered in this PR: No

What: A broken backend module import is reported as a missing optional package.
Where: src/gt4py/next/experimental/__init__.py:__getattr__
Trigger: `jax` or `torch` is installed, but importing the corresponding experimental backend module fails for another reason, e.g. an incompatible version.
Detected by: nothing
Covered in this PR: No

What: A misspelled or unsupported static parameter is silently ignored by the torch backend, changing tracing behavior unexpectedly.
Where: src/gt4py/next/program_processors/runners/experimental/torch_compile.py:TorchCompileBackend.run
Trigger: `static_params` contains a name that is not present in the bound call arguments, or an unhashable value is marked static.
Detected by: nothing
Covered in this PR: No

🏅 Score: 85
🧪 PR contains tests
🔒 No security concerns identified
🔀 No multiple PR themes

⚙️ Agent run details
  • Model: openai/Qwen/Qwen3.8-Flash-Next-FP8 (fallback)
  • Tokens: 43,227 in / 40,350 out / 83,577 total
  • Time cost: 1044.7s
  • AI calls: 1

havogt added a commit to havogt/gt4py that referenced this pull request Nov 24, 2026
With the embedded and embedded-jit backends of GridTools#3027 as their own
allocators, every selection is a backend plus, for torch, a device. The
Target dataclass is gone; Model, run and the validation take backend= and
device=.

This branch was successfully deployed

1 active (outdated) deployment
pr-agent — 18993f0a Deployed Nov 24, 2026 by egparedes via pr-agent / pr-agent #185
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants