Repository navigation
Conversation
A skip entry wrapped around to a real element of the buffer, which is masked later but still receives a cotangent under jax.grad. Claude-Session: https://claude.ai/code/session_013m5PzT4FxbaKPxfXqiQLr5
A reduction after a narrowing premap broadcast the full table against the narrowed field. The mask now uses the connectivity's own skip value. Claude-Session: https://claude.ai/code/session_013m5PzT4FxbaKPxfXqiQLr5
The neighbor table travels as the traced child, so it is a runtime argument of the compiled program rather than an inlined constant. The aux data carries a handle to the same buffer, compared by identity, through which `inverse_image` reads the concrete table at trace time, so domain inference narrows under `jax.jit` exactly as it does eagerly. `inverse_image` also answers covering image ranges from eagerly computed table bounds instead of scanning the table. Claude-Session: https://claude.ai/code/session_013m5PzT4FxbaKPxfXqiQLr5
… bounds on write Also reuse the gather's index-array layout for the reduction mask, which handles transposed table dimensions, sanitise skip indices before the broadcast, and treat an empty table as an empty image.
…ax trace Restricting a concrete jax connectivity inside jax.jit (e.g. for field(E2C2V[0])) produced a traced buffer, so the later domain inference on it failed with a ConcretizationTypeError. Slice concrete tables with jax.ensure_compile_time_eval.
A connectivity whose table is computed inside a jax trace (e.g. from as_offset) has no concrete values for domain inference. Assume all its targets lie in the field and clip the gather indices, so out-of-range targets read the boundary value. Eager execution is unchanged.
jax.jit does not need it: domain inference already reads concrete tables through `_hyperslice`. On tables with skip values computing the bounds costs more than a covering scan, and under jit they are recomputed per trace.
…ivity base class The jax connectivity overrides `inverse_image` instead of an `_image_slices` indirection, and adjusts gather indices through a `_gather_index` hook, so shared code no longer knows about values computed in a trace. Test the clamp on negative targets: positive ones are already clamped by jax indexing.
It is an implementation detail of premap: nothing outside the embedded implementations calls it.
All callers pass a UnitRange, so the NamedRange branch and its dimension check were unreachable.
- Drop the cache in FieldOffset.as_connectivity_field: it returned its input, and kept traced connectivities alive after the trace. - Align the table for skip masks without broadcasting, so reductions work on fields with an infinite range again. - Keep as_offset of concrete offsets concrete under a trace, so jit narrows like eager. Allow subclasses to override a registered builtin for this. - Cover the f89 fix with a narrowing case, custom skip values, non-zero domain starts and nested jit, and fix the check that a table is not inlined.
…ient limit in the ADR
…ssert in the inverse-image test Also state in the ADR that writing into a connectivity buffer through `.ndarray` is not supported.
Also date the ADR to the current state.
…with a no-wrap gather
…via ArrayOps NdArrayField and NdArrayConnectivityField no longer carry the array namespace as a class variable. Each field takes its array operations from an 'ArrayOps' object resolved from the type of its buffer: the namespace array_api_compat returns for the buffer selects a registered ArrayOps subclass, or the default one, which is written against the Array API standard only. The per-library field classes (NumPyArrayField, CuPyArrayField, JaxArrayField and their connectivity counterparts) are removed; NumPy, CuPy and JAX differ only in NumPyOps, CuPyOps and JaxOps (gamma, scalar operands, item assignment for JAX, conversion to NumPy). 'common._field' and 'common._connectivity' construct an NdArrayField from any Array API object instead of a per-type registration. 'NdArrayField.array_ns' stays the library's own module (numpy, cupy, jax.numpy). An ArrayOps can replace a whole fbuiltins implementation via 'builtin_overrides'.
array-api-strict is added to the namespace matrix of the embedded unit tests, which shows that NdArrayField uses only the Array API standard. Test inputs are built with each namespace's own dtype objects. The non-standard builtins fmod, cbrt and gamma raise NotImplementedError on strict. The constructors read the dtype of the given array through ArrayOps and test for skip values with the namespace's 'any' instead of the NumPy method.
torch tensors work through array_api_compat with one ArrayOps subclass and no field class: scalar operands of elementwise functions become 0-d tensors (Python floats as float64, as NumPy promotes them), cbrt and gamma have torch implementations, assigned values become tensors and conversion to NumPy detaches and copies to the host. The embedded unit tests run on torch when it is installed.
…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.
…he decorator, the shared part in runners.embedded_jit
| self._compiled_programs( | ||
| *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit | ||
| ) | ||
| elif self.backend is not None: |
There was a problem hiding this comment.
| elif self.backend is not None: | |
| elif isinstance(self.backend, next_backend.EmbeddedJitBackend): |
would that make sense?
| @@ -0,0 +1,120 @@ | |||
| # GT4Py - GridTools Framework | |||
| # | |||
There was a problem hiding this comment.
Let's move this and the concrete implementations into an experimental subdirectory.
There was a problem hiding this comment.
and then export it from next/experiment/__init__.py.
…ed from gt4py.next.experimental; explicit EmbeddedJitBackend checks in the decorator (review)
…bedded jit backends, as embedded
| @@ -0,0 +1,50 @@ | |||
| --- | |||
There was a problem hiding this comment.
Let's remove the ADR for now
There was a problem hiding this comment.
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
…r and context import what they use (review of GridTools#3030)
| ) | ||
|
|
||
| def __post_init__(self) -> None: | ||
| object.__setattr__( |
There was a problem hiding this comment.
could we do this with a cached_property? then we wouldn't need the extra postinits and it's cleaner.
There was a problem hiding this comment.
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
| @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)) |
There was a problem hiding this comment.
do we need this cached property? Why? Is the call expensive on every call otherwise?
There was a problem hiding this comment.
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). |
There was a problem hiding this comment.
make sure all references to the ADR are removed in the end
There was a problem hiding this comment.
Done; nothing refers to the ADR any more (next push).
🤖 Written by an agent on behalf of @havogt
egparedes
left a comment
There was a problem hiding this comment.
First round of comments
| #: 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 |
There was a problem hiding this comment.
What would you think about using NDValue here as name for the type?
There was a problem hiding this comment.
Fine: renamed to NDValue (next push).
🤖 Written by an agent on behalf of @havogt
| _is_compiled: bool = dataclasses.field( | ||
| init=False, repr=False, compare=False, metadata=utils.gt4py_metadata(fingerprint=False) | ||
| ) |
There was a problem hiding this comment.
Why not using a cached_property? Is it required for this to be a dataclass.field?
There was a problem hiding this comment.
Also, I think the name is misleading since this only refers to a embedded jitting backend and not an actual gt4py internal compiled backend
There was a problem hiding this comment.
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
| self._compiled_programs( | ||
| *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit | ||
| ) | ||
| elif isinstance(self.backend, next_backend.EmbeddedJitBackend): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| 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() | ||
| } |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| static = ( | ||
| ("offset_provider", tuple(sorted(static_provider.items()))), | ||
| *sorted((name, arguments.pop(name)) for name in static_names & arguments.keys()), | ||
| ) |
There was a problem hiding this comment.
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.
PR Reviewer Guide 🔍Here are some key observations to aid the review process:
⚙️ Agent run details
|
… with eager backends for numpy, cupy, jax and torch; the jit backends override its wrap
…ation, no compile
With the embedded and embedded-jit backends of GridTools#3027 as their own allocators, every selection is a backend plus, for torch, a device. The Target dataclass is gone; Model, run and the validation take backend= and device=.
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: underjax.jit.gt4py.next.experimental.torch_compile: undertorch.compile, throughtorch.compiler.nonstrict_trace.gt4py.next.experimental.embedded_numpy,embedded_cupy,embedded_jax,embedded_torch: eager embedded execution.EmbeddedBackend(gt4py.next.backend) is aBackendthat does not compile:runner(entry_point)runs the entry point embedded, throughwrap, and the result is cached on the entry point. The eager backends are instances of it. The jit backends overridewrap. Calls on compiled backends take the same path as before;.compile()raises.gtx.zeros(domain, allocator=experimental.jax_jit), anddevice=for cupy and torch on CUDA. A backend whose allocator is an array namespace now allocates with it.static_params, a field operator'sdomain=, and the offset provider'sDimensions are static.out: jax returns the new buffers and the caller's fields take them; torch assigns in place.jax_jit,torch_compileandtorch_compile_cudaentries. Tests that need a concrete scalar are xfailed withuses_scalar_in_control_flow,uses_scalar_in_domainoruses_scan_carry_in_control_flow.