Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
164 commits
Select commit Hold shift + click to select a range
d10e2e5
fix[next]: sanitise skip-value indices before the premap gather
havogt Sep 10, 2026
57f3ae0
fix[next]: restrict the neighbor table to the field domain in reductions
havogt Sep 10, 2026
3982769
feat[next]: register jax connectivities as pytree nodes
havogt Sep 10, 2026
82d0032
test[next]: assert the inverse-image bounds shortcut bypasses the tab…
havogt Sep 10, 2026
a8bcd95
fix[next]: carry the table handle through restrict, invalidate cached…
havogt Sep 16, 2026
c118ca2
refactor[next]: forbid item assignment on connectivity fields
havogt Sep 16, 2026
9882efe
docs[next]: say why domain inference reads the table through a property
havogt Sep 16, 2026
c654d8b
Merge remote-tracking branch 'upstream/main' into jax-connectivities
havogt Sep 16, 2026
3709b85
fix[next]: keep restricted concrete connectivities concrete under a j…
havogt Sep 25, 2026
7aeff15
fix[next]: clamp value-dependent jax connectivities under a trace
havogt Sep 26, 2026
2ce6a92
Merge remote-tracking branch 'upstream/main' into jax-connectivities
havogt Oct 30, 2026
25d3cc1
refactor[next]: remove the inverse-image bounds shortcut
havogt Oct 30, 2026
db939ba
docs[next]: add ADR for connectivities under JAX tracing
havogt Oct 30, 2026
3bbca26
Merge remote-tracking branch 'upstream/main' into jax-connectivities
havogt Oct 30, 2026
f7f60f1
refactor[next]: move jax domain inference handling out of the connect…
havogt Oct 30, 2026
f7b443a
refactor[next]: make Connectivity.inverse_image private
havogt Oct 30, 2026
865944c
refactor[next]: restrict Connectivity._inverse_image to UnitRange
havogt Nov 2, 2026
7d69dd8
fix[next]: address review findings on jax connectivities
havogt Nov 2, 2026
2ee7af1
docs[next]: correct as_offset behaviour and state the skip-value grad…
havogt Nov 2, 2026
a8198a1
docs[next]: say when a closed-over as_offset field stops being concrete
havogt Nov 2, 2026
4179b9e
fix[next]: type-check the jax connectivity code with jax installed, a…
havogt Nov 6, 2026
db4bf55
fix[next]: keep the jax type ignores valid when jax is not installed
havogt Nov 6, 2026
38fb4cd
Merge remote-tracking branch 'upstream/main' into jax-connectivities
havogt Nov 6, 2026
fa98551
test[next]: drop tests of removed shortcut code and pytree internals
havogt Nov 6, 2026
3ad1c75
docs[next]: note in the ADR that the jax gather clamp may be cheaper …
havogt Nov 6, 2026
2571afb
refactor[next]: one NdArrayField for all array libraries, operations …
havogt Nov 6, 2026
bc9b062
test[next]: run the embedded field unit tests on array-api-strict
havogt Nov 6, 2026
41eb666
feat[next]: run embedded fields on torch tensors through TorchOps
havogt Nov 6, 2026
0b398aa
test[next]: ArrayOps registry and override points
havogt Nov 6, 2026
e633ae4
refactor[next]: index and assign embedded buffers only as the Array A…
havogt Nov 6, 2026
ee652c9
test[next]: run the embedded ffront tests on array-api-strict
havogt Nov 6, 2026
607e6bb
docs[next]: ADR draft for Array API embedded fields
havogt Nov 6, 2026
b3550fd
refactor[next]: TODO on NdArrayField.array_ns returning the library m…
havogt Nov 9, 2026
e283e33
docs[next]: remove the Array API embedded fields ADR draft
havogt Nov 9, 2026
becd4ee
refactor[next]: drop TorchOps, torch support moves to its own PR
havogt Nov 9, 2026
a4132e3
refactor[next]: one module per array library in embedded.array_libraries
havogt Nov 9, 2026
30dec7a
test[next]: import array-api-strict unconditionally, it is a test dep…
havogt Nov 9, 2026
64fd3fa
refactor[next]: dtype translation per array namespace in _core.ndarra…
havogt Nov 9, 2026
1528472
fix[next]: gt4py scalar type of NumPy-style dtypes independent of byt…
havogt Nov 9, 2026
d25796b
refactor[next]: import scipy's gamma once, at module level
havogt Nov 9, 2026
b90c3c9
fix[next]: skip an installed array library that fails to import, as b…
havogt Nov 9, 2026
414110f
fix[next]: reject assignment to part of a broadcast axis of an embedd…
havogt Nov 9, 2026
1aa3e71
fix[next]: to_numpy of the default ArrayOps on NumPy 2.0
havogt Nov 9, 2026
9e1c54b
docs[next]: say that every NdArrayField is a JAX pytree
havogt Nov 9, 2026
46c7193
fix[next]: accept NumPy dtypes named by C type, e.g. np.longlong
havogt Nov 9, 2026
e6d431b
refactor[next]: assign into broadcast axes as on main
havogt Nov 9, 2026
08d073b
refactor[next]: decide the tracing case of a connectivity in one place
havogt Nov 10, 2026
a3eb843
Merge jax-connectivities into #2976: connectivity tracing support on …
havogt Nov 10, 2026
1f86423
refactor[next]: keep jax tracing of connectivities in the jax module
havogt Nov 10, 2026
f67c042
refactor[next]: keep the static values of a traced connectivity table…
havogt Nov 10, 2026
38c3f37
docs[next]: describe connectivity tracing through ArrayOps in ADR 0029
havogt Nov 10, 2026
15b7897
refactor[next]: attach the static values of a connectivity to every u…
havogt Nov 10, 2026
065923a
test[next]: cover a replaced connectivity passed on to a nested jit a…
havogt Nov 10, 2026
8f9022c
refactor[next]: rename ArrayOps.elementwise to elementwise_function
havogt Nov 11, 2026
66996a3
docs[next]: say why ArrayOps.where exists
havogt Nov 11, 2026
5f148ae
refactor[next]: precise type hints in the dtype translation of ndarra…
havogt Nov 11, 2026
3a008f0
refactor[next]: call array_ops.of directly instead of an NdArrayField…
havogt Nov 11, 2026
54b4c41
fix[next]: where with two scalar branches on the default ArrayOps
havogt Nov 11, 2026
74f60d5
test[next]: buffer info tests on buffers of each array library
havogt Nov 11, 2026
9fc8816
test[next]: item assignment on fields of each array library
havogt Nov 11, 2026
e899fcc
build: re-lock uv.lock from main with a current uv
havogt Nov 11, 2026
6333ce0
fix[next]: translate NumPy scalar types named by C type to namespace …
havogt Nov 11, 2026
df9f852
fix[next]: concat_where converts fields of other libraries to the fir…
havogt Nov 11, 2026
7f48c7c
docs[next]: state the Array API revision the default ArrayOps needs
havogt Nov 11, 2026
f2d4887
refactor[next]: register ArrayOps instances by their namespace
havogt Nov 11, 2026
bfe5679
fix[next]: where with a scalar condition next to a NumPy-scalar branch
havogt Nov 11, 2026
1b2ba8f
build: require jax>=0.4.32, the first version whose array API namespa…
havogt Nov 11, 2026
77e6f98
Merge remote-tracking branch 'upstream/main' into array-api-field
havogt Nov 11, 2026
a02c6e0
Merge remote-tracking branch 'upstream/pr-2976' into jax-connectiviti…
havogt Nov 11, 2026
8f6fb40
fix[next]: reject fields of other array libraries as JAX pytrees
havogt Nov 11, 2026
e90ef3b
docs[next]: TODO on the order dependence of mixed-library operations
havogt Nov 11, 2026
00c755b
docs[next]: say why ArrayOps.operand and setitem convert, and which l…
havogt Nov 11, 2026
59d5741
build: require numpy>=2.1, the first version whose from_dlpack takes …
havogt Nov 11, 2026
488ed16
refactor[next]: default ArrayOps.setitem accepts only arrays of its o…
havogt Nov 11, 2026
2fe6c07
refactor[next]: drop the identity entry 'pow' from STANDARD_NAMES
havogt Nov 12, 2026
2f19b77
refactor[next]: one table of builtin implementations instead of a per…
havogt Nov 12, 2026
d619b2b
fix[next]: make the static slot of a connectivity keyword-only
havogt Nov 13, 2026
5897fd1
docs[next]: say why NumPy dtypes are identified by kind and size
havogt Nov 13, 2026
881a685
refactor[next]: ArrayOps as a frozen dataclass
havogt Nov 13, 2026
309c3ab
refactor[next]: canonicalize NumPy dtypes separately from taking thei…
havogt Nov 13, 2026
821c385
Merge remote-tracking branch 'upstream/pr-2976' into jax-connectiviti…
havogt Nov 13, 2026
0e0edfa
Merge remote-tracking branch 'upstream/main' into jax-connectivities-…
havogt Nov 13, 2026
4d37585
refactor[next]: connectivity caches without arrays, clamping gather i…
havogt Nov 13, 2026
beed38f
docs[next]: ADR 0029 for the gather, the caches and the pytree rules
havogt Nov 13, 2026
e0956b6
build: require jax>=0.7.0, the first version whose indexed get takes …
havogt Nov 13, 2026
e8e2696
refactor[next]: name the library slot of a connectivity _array_ops_me…
havogt Nov 16, 2026
a5e199f
test[next]: move the jax tests of embedded fields and connectivities …
havogt Nov 16, 2026
ffd17dd
test[next]: name the jax test module after the library
havogt Nov 16, 2026
cb1dd90
refactor[next]: state the contract of the library state of a connecti…
havogt Nov 16, 2026
f00b04e
Merge remote-tracking branch 'upstream/main' into jax-connectivities-…
havogt Nov 16, 2026
a5cafba
docs[next]: drop the link to the superseded design proposal from ADR …
havogt Nov 16, 2026
40fa394
docs[next]: state the contract of a connectivity's ArrayOps state in …
havogt Nov 16, 2026
2208679
refactor[next]: separate connectivity caches per operation, build res…
havogt Nov 17, 2026
ea7f64a
refactor[next]: move connectivity table operations from ArrayOps to p…
havogt Nov 17, 2026
34d3cf0
docs[next]: ADR 0029 describes the per-connectivity ConnectivityOps
havogt Nov 17, 2026
88fb9dc
Merge remote-tracking branch 'upstream/main' into jax-connectivities-…
havogt Nov 18, 2026
48d366c
perf[next]: cache restricted connectivities whose ConnectivityOps all…
havogt Nov 18, 2026
c98fad3
docs[next]: address review of ADR 0029
havogt Nov 18, 2026
ec98eaa
refactor[next]: ConnectivityOps get their own registry, ArrayOps no l…
havogt Nov 18, 2026
a6b3899
refactor[next]: ConnectivityOps build on the ArrayOps of their namespace
havogt Nov 18, 2026
b6c775f
refactor[next]: register ConnectivityOps types, pass a connectivity's…
havogt Nov 18, 2026
1686649
docs[next]: ADR 0029 on how a connectivity gets its ConnectivityOps
havogt Nov 18, 2026
4cc2f10
style[next]: import the connectivity_ops and array_ops modules, alias…
havogt Nov 18, 2026
4fc5943
docs[next]: say when a connectivity is given its ConnectivityOps
havogt Nov 18, 2026
54ad9d8
Merge remote-tracking branch 'upstream/main' into jax-connectivities-…
havogt Nov 18, 2026
6e55145
refactor[next]: drop ConnectivityOps.may_cache, rebuild restrictions …
havogt Nov 18, 2026
1a2eb49
refactor[next]: rename ConnectivityOps.hyperslice to inverse_image_box
havogt Nov 18, 2026
129b1f4
refactor[next]: static values on the connectivity instead of Connecti…
havogt Nov 19, 2026
4f8f731
docs[next]: ADR 0029 describes static values on the connectivity
havogt Nov 19, 2026
636e294
refactor[next]: keep _inverse_image_box where main has _hyperslice, w…
havogt Nov 19, 2026
1806038
Merge remote-tracking branch 'upstream/main' into jax-connectivities-…
havogt Nov 19, 2026
e97185a
refactor[next]: closed-over connectivities are not supported under ja…
havogt Nov 19, 2026
0f9aae2
docs[next]: ADR 0029 without closed-over connectivities
havogt Nov 19, 2026
7cb5a7e
Merge remote-tracking branch 'upstream/main' into jax-connectivities-…
havogt Nov 19, 2026
a138b14
fix[next]: unsupported traced connectivities stay unsupported across …
havogt Nov 19, 2026
3b0c8f1
docs[next]: ADR 0029 with take, unsupported connectivities never comp…
havogt Nov 19, 2026
7a50f36
refactor[next]: static values as an attribute set by the connectivity…
havogt Nov 19, 2026
d0a3619
refactor[next]: static values passed to the constructor, or a _Static…
havogt Nov 19, 2026
9262906
refactor[next]: static values as a dataclass field, StaticValues.IN_B…
havogt Nov 19, 2026
5f4dcb0
docs[next]: ADR 0029 on the static values field
havogt Nov 19, 2026
fde4552
Merge remote-tracking branch 'upstream/main' into jax-connectivities-…
havogt Nov 19, 2026
2c80075
docs[next]: drop the stale gather consequence from ADR 0029
havogt Nov 19, 2026
89cb86a
docs[next]: concise pass over ADR 0029
havogt Nov 19, 2026
b99ce77
refactor[next]: address review of ADR 0029 and the jax pytree flattening
havogt Nov 19, 2026
54fe283
style[next]: drop a comment in the connectivity unflatten
havogt Nov 19, 2026
12119e0
docs[next]: the static values of a connectivity must be those of its …
havogt Nov 19, 2026
48a75a1
test[next]: jax connectivity tests check the documented behaviour, no…
havogt Nov 19, 2026
41bc371
Merge remote-tracking branch 'upstream/main' into jax-jit
havogt Nov 20, 2026
82012af
feat[next]: jax_jit backend running embedded programs and field opera…
havogt Nov 20, 2026
19bf2db
style[next]: lint and typing of the jax_jit backend
havogt Nov 20, 2026
1393b11
feat[next]: embedded accepts 0-d arrays as scalars, so jax_jit traces…
havogt Nov 20, 2026
b621f3c
feat[next]: jax_jit takes static_params of field operators and datacl…
havogt Nov 20, 2026
291043a
test[next]: jax_jit in the integration test matrix, scalar-dependent …
havogt Nov 20, 2026
347c98f
Merge remote-tracking branch 'upstream/main' into jax-jit
havogt Nov 20, 2026
8eeebce
refactor[next]: EmbeddedJitBackend, the dispatch seam shared by the e…
havogt Nov 20, 2026
2a3e235
feat[next]: torch_compile backend running embedded programs and field…
havogt Nov 20, 2026
2a3a8ba
test[next]: torch_compile in the integration test matrix, the backend…
havogt Nov 20, 2026
ae02879
Merge remote-tracking branch 'upstream/main' into jax-jit
havogt Nov 20, 2026
b269dba
refactor[next]: no import cycle between fbuiltins and embedded, array…
havogt Nov 20, 2026
2b6be0f
refactor[next]: embedded jit backends wrap the embedded entry point, …
havogt Nov 20, 2026
5c8aaef
test[next]: embedded jit backend tests through one seam, the same tra…
havogt Nov 20, 2026
17e58fe
refactor[next]: named collections as tuples into the embedded jit bac…
havogt Nov 20, 2026
9eed5d9
test[next]: embedded jit backend unit tests next to the other runners…
havogt Nov 20, 2026
2048a3d
docs[next]: ADR 0030 on the embedded jit backends
havogt Nov 20, 2026
8080cdf
Merge remote-tracking branch 'upstream/main' into jax-jit
havogt Nov 22, 2026
6ffadaf
refactor[next]: a single dispatch hook for embedded jit backends in t…
havogt Nov 22, 2026
ee88bc9
test[next]: embedded jit tests reach the jax.jit object through __wra…
havogt Nov 22, 2026
1f46a3b
docs[next]: ADR 0030 describes the single dispatch hook
havogt Nov 22, 2026
60546c9
refactor[next]: embedded jit backends in runners.experimental, export…
havogt Nov 23, 2026
5f714df
test[next]: embedded jit backends from their new location, and their …
havogt Nov 23, 2026
6f7e602
Merge remote-tracking branch 'upstream/main' into jax-jit
havogt Nov 23, 2026
ab54012
test[next]: the new compile-without-offset-provider tests skip the em…
havogt Nov 23, 2026
b1573cb
Merge remote-tracking branch 'upstream/main' into jax-jit
havogt Nov 23, 2026
6f0e8cb
refactor[next]: embedded/__init__ imports no submodules; the decorato…
havogt Nov 23, 2026
a4e7c27
refactor[next]: array_ops.ScalarLike is TensorLike: it admits any arr…
havogt Nov 23, 2026
9d8b354
docs[next]: no ADR for the embedded jit backends (review)
havogt Nov 24, 2026
db6bccc
refactor[next]: _has_compiled_backend, a cached_property instead of a…
havogt Nov 24, 2026
18993f0
refactor[next]: array_ops.TensorLike is NDValue (review)
havogt Nov 24, 2026
f6d6dc1
fix[next]: a backend whose allocator is an array namespace allocates …
havogt Nov 24, 2026
d236c5f
feat[next]: EmbeddedBackend runs embedded on the arrays it allocates,…
havogt Nov 24, 2026
6a8861b
test[next]: eager embedded backends: programs, field operators, alloc…
havogt Nov 24, 2026
957a045
fix[next]: embedded backends reject fields of another array library, …
havogt Nov 24, 2026
dd9bd46
ci: torch.compile on CPU skipped for now, 16 xdist workers for the gh…
havogt Nov 24, 2026
e18797b
test[next]: embedded backends: library check, argument binding, stati…
havogt Nov 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .cscs-ci/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,9 @@ 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',
'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/*', '.*']
Expand Down
63 changes: 59 additions & 4 deletions src/gt4py/next/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
from __future__ import annotations

import dataclasses
from typing import Generic
import inspect
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,
Expand All @@ -27,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:
Expand Down Expand Up @@ -148,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(
Expand All @@ -170,10 +179,56 @@ 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


def _not_compiled(*args: Any, **kwargs: Any) -> Any:
raise RuntimeError("An embedded backend runs programs embedded; it does not compile them.")


@dataclasses.dataclass(frozen=True, kw_only=True)
class EmbeddedBackend(Backend):
"""
Runs programs and field operators embedded, on arrays of its allocator's array namespace.

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] = (
_not_compiled
)
transforms: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgramDef] = (
DEFAULT_TRANSFORMS
)

def runner(self, entry_point: ffront_decorator.GTEntryPoint) -> Callable[..., None]:
"""
`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, 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, as the backend runs it.

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


@dataclasses.dataclass(frozen=True)
class ToolchainConfig:
"""
Expand Down
9 changes: 5 additions & 4 deletions src/gt4py/next/constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ 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__

if core_ndarray_utils.is_array_namespace(allocator):
if aligned_index is not None:
Expand All @@ -93,9 +96,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."
Expand All @@ -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,
Expand Down
9 changes: 7 additions & 2 deletions src/gt4py/next/custom_layout_allocators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]:
Expand All @@ -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 = (
Expand Down
7 changes: 0 additions & 7 deletions src/gt4py/next/embedded/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
8 changes: 6 additions & 2 deletions src/gt4py/next/embedded/array_libraries/jax_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.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
restricted from such a tracer: its static values are a NumPy view of the
Expand Down Expand Up @@ -248,3 +249,6 @@ def _unflatten_connectivity(
_flatten_connectivity,
_unflatten_connectivity,
)

# e.g. the `Dimension`s of an offset provider in the arguments of `jax.jit`
jax.tree_util.register_static(common.Dimension)
11 changes: 6 additions & 5 deletions src/gt4py/next/embedded/array_libraries/torch_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.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
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;
Expand Down
6 changes: 3 additions & 3 deletions src/gt4py/next/embedded/array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
NDValue: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject


def is_scalar_like(value: Any) -> TypeIs[ScalarLike]:
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)

Expand Down
9 changes: 4 additions & 5 deletions src/gt4py/next/embedded/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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:
Expand Down
15 changes: 9 additions & 6 deletions src/gt4py/next/embedded/nd_array_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,13 +357,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")

Expand Down
12 changes: 6 additions & 6 deletions src/gt4py/next/embedded/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,29 +181,29 @@ 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.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,)))


def _tuple_assign_value(
pos: Sequence[common.NamedIndex],
target: xtyping.MaybeNestedInTuple[common.MutableField],
source: xtyping.MaybeNestedInTuple[array_ops.ScalarLike],
source: xtyping.MaybeNestedInTuple[array_ops.NDValue],
) -> None:
@utils.tree_map
def impl(target: common.MutableField, source: array_ops.ScalarLike) -> None:
def impl(target: common.MutableField, source: array_ops.NDValue) -> None:
target[pos] = source

impl(target, source)


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.NDValue],
) -> array_ops.NDValue | tuple[array_ops.NDValue | 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.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
Expand Down
45 changes: 45 additions & 0 deletions src/gt4py/next/experimental/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,55 @@
# 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


__all__ = [
"as_offset",
"concat_where",
]

#: 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 _EAGER_BACKENDS:
from gt4py.next import backend as next_backend

namespace = _EAGER_BACKENDS[name]
allocator = _import(name, namespace, namespace.partition(".")[0])
backend = next_backend.EmbeddedBackend(name=name, allocator=allocator)
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
Loading