From 710d8039a6dc09594148f58028af70c7525abab0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 22:04:50 +0100 Subject: [PATCH 1/7] feat[next]: let allocator factories provide an array namespace `FieldConstructor` now unwraps `__gt_allocator__` factories before choosing between the array-API path and the custom-layout path, so a factory whose allocator is an array namespace (e.g. NumPy) allocates like that namespace instead of being pushed into the `TensorBuffer` path. - `FieldBufferAllocatorFactoryProtocol.__gt_allocator__` may return an array namespace as well as a field buffer allocator. - `is_field_allocator_factory_for(obj, device)` is true only for factories providing a field buffer allocator for that device type (it raised `AttributeError` for an array namespace). Prepares embedded backends (ADR 0030), whose allocator is an array namespace. --- src/gt4py/next/constructors.py | 15 +++-- src/gt4py/next/custom_layout_allocators.py | 23 ++++++- .../unit_tests/test_constructors.py | 60 +++++++++++++++++++ .../test_custom_layout_allocators.py | 16 +++++ 4 files changed, 106 insertions(+), 8 deletions(-) diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index e4320f99d3..0efa117bf8 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -52,8 +52,10 @@ Accepts either: - An array namespace following the Array API standard (e.g. ``numpy``, ``cupy``, ``jax.numpy``), which will be used directly for array creation. -- A GT4Py field buffer allocator or allocator factory (e.g. a backend), which controls - memory layout and alignment. +- A GT4Py field buffer allocator, which controls memory layout and alignment. +- An allocator factory (e.g. a backend or a program), which provides one of the above + through its ``__gt_allocator__`` property: a field buffer allocator for compiled + backends, an array namespace for embedded backends. """ DEFAULT_DEVICE: Final[core_defs.Device] = core_defs.Device(core_defs.DeviceType.CPU, 0) @@ -81,6 +83,11 @@ def __init__( # Currently we use optimized CPU layout, but possibly we could also use standard numpy allocation allocator = next_allocators.device_allocators[device.device_type] + # Unwrap factories first: a factory (e.g. a backend or a program) may provide + # an array namespace as well as a field buffer 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: import warnings @@ -97,9 +104,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/src/gt4py/next/custom_layout_allocators.py b/src/gt4py/next/custom_layout_allocators.py index 8451863cc3..6fe19ce5dc 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 @@ -52,11 +53,21 @@ def is_field_allocator_for( class FieldBufferAllocatorFactoryProtocol(Protocol[core_defs.DeviceTypeT]): - """Protocol for device-specific buffer allocator factories for fields.""" + """ + Protocol for objects that provide the allocator for their fields (e.g. backends, programs). + + The provided allocator is either a field buffer allocator, which controls the + device and the memory layout, or an array namespace (e.g. `numpy`), which + allocates with its standard layout (e.g. embedded backends). + """ @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 +77,13 @@ 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 + """ + Check whether `obj` is an allocator factory providing a field buffer allocator for `device`. + + A factory providing an array namespace is not specific to any device type, + so it is never a factory for `device`. + """ + return is_field_allocator_factory(obj) and is_field_allocator_for(obj.__gt_allocator__, device) FieldBufferAllocationUtil = ( diff --git a/tests/next_tests/unit_tests/test_constructors.py b/tests/next_tests/unit_tests/test_constructors.py index 0d6bbdeb2b..b508fcf2bb 100644 --- a/tests/next_tests/unit_tests/test_constructors.py +++ b/tests/next_tests/unit_tests/test_constructors.py @@ -31,6 +31,17 @@ cp = core_defs.cp +@dataclasses.dataclass(frozen=True) +class ArrayNamespaceFactory: + """An allocator factory providing an array namespace, like an embedded backend.""" + + array_ns: ModuleType + + @property + def __gt_allocator__(self) -> ModuleType: + return self.array_ns + + @dataclasses.dataclass class ConstructorTestSetup: allocator: gtx_typing.Allocator @@ -55,6 +66,11 @@ def _constructor_test_cases(): device=None, expected_xp=np, ), + ConstructorTestSetup( + allocator=ArrayNamespaceFactory(np), + device=None, + expected_xp=np, + ), pytest.param( ConstructorTestSetup( allocator=next_allocators.StandardGPUFieldBufferAllocator(), @@ -160,6 +176,13 @@ def test_as_field(): assert np.array_equal(a.ndarray, ref) +def test_as_field_with_array_namespace_factory(): + ref = np.random.rand(sizes[I]).astype(gtx.float32) + a = gtx.as_field([I], ref, allocator=ArrayNamespaceFactory(np)) + assert isinstance(a.ndarray, np.ndarray) + assert np.array_equal(a.ndarray, ref) + + def test_as_field_domain(): ref = np.random.rand(sizes[I] - 1, sizes[J] - 1).astype(gtx.float32) domain = common.Domain( @@ -292,6 +315,43 @@ def __gt_allocator__(self): assert isinstance(field.ndarray, np.ndarray) assert not field.ndarray.flags["C_CONTIGUOUS"] # custom layout + def test_array_namespace_factory(self): + """allocator=factory providing numpy → unwraps and uses array-API standard allocation.""" + fc = constructors.FieldConstructor(allocator=ArrayNamespaceFactory(np)) + field = fc.zeros(self._domain) + assert isinstance(field.ndarray, np.ndarray) + assert field.ndarray.flags["C_CONTIGUOUS"] # standard array-API allocation + + def test_array_namespace_factory_aligned_index_warns(self): + """allocator=factory providing numpy with aligned_index → warns as for numpy.""" + aligned_index = [common.NamedIndex(I, 0)] + with pytest.warns(UserWarning, match="aligned_index"): + fc = constructors.FieldConstructor( + allocator=ArrayNamespaceFactory(np), aligned_index=aligned_index + ) + field = fc.zeros(self._domain) + assert field.ndarray.flags["C_CONTIGUOUS"] + + def test_array_namespace_factory_device_mismatch_raises(self): + """allocator=factory providing numpy, device=CUDA → raises ValueError as for numpy.""" + device = core_defs.Device(core_defs.DeviceType.CUDA, 0) + with pytest.raises(ValueError, match="NumPy does not support device type"): + constructors.FieldConstructor(allocator=np, device=device) + with pytest.raises(ValueError, match="NumPy does not support device type"): + constructors.FieldConstructor(allocator=ArrayNamespaceFactory(np), device=device) + + def test_field_buffer_allocator_factory_device_mismatch_raises(self): + """allocator=factory providing a CPU allocator, device=CUDA → raises ValueError.""" + + class FakeFactory: + @property + def __gt_allocator__(self): + return next_allocators.StandardCPUFieldBufferAllocator() + + device = core_defs.Device(core_defs.DeviceType.CUDA, 0) + with pytest.raises(ValueError, match="device type"): + constructors.FieldConstructor(allocator=FakeFactory(), device=device) + def test_field_buffer_allocator_device_mismatch_raises(self): """allocator=CPU allocator, device=CUDA → raises ValueError.""" allocator = next_allocators.StandardCPUFieldBufferAllocator() diff --git a/tests/next_tests/unit_tests/test_custom_layout_allocators.py b/tests/next_tests/unit_tests/test_custom_layout_allocators.py index 6f54a5d930..443dbc2073 100644 --- a/tests/next_tests/unit_tests/test_custom_layout_allocators.py +++ b/tests/next_tests/unit_tests/test_custom_layout_allocators.py @@ -9,6 +9,7 @@ from collections.abc import Sequence from typing import Optional +import numpy as np import pytest import gt4py._core.definitions as core_defs @@ -34,6 +35,12 @@ class DummyAllocatorFactory(next_allocators.FieldBufferAllocatorFactoryProtocol) __gt_allocator__ = DummyAllocator() +class ArrayNamespaceFactory: + """A factory providing an array namespace instead of a field buffer allocator.""" + + __gt_allocator__ = np + + def test_is_field_allocator(): # Test with a field allocator allocator = DummyAllocator() @@ -92,6 +99,15 @@ def test_is_field_allocator_factory_for(test_function): invalid_obj = "not an allocator factory" assert not test_function(invalid_obj, core_defs.DeviceType.CPU) + # A factory providing an array namespace is not specific to any device type + assert not test_function(ArrayNamespaceFactory(), core_defs.DeviceType.CPU) + + +def test_array_namespace_factory_is_field_allocator_factory(): + assert next_allocators.is_field_allocator_factory(ArrayNamespaceFactory()) + assert next_allocators.is_field_allocation_tool(ArrayNamespaceFactory()) + assert not next_allocators.is_field_allocator(ArrayNamespaceFactory()) + def test_horizontal_first_layout_mapper(): from gt4py.next.custom_layout_allocators import horizontal_first_layout_mapper From 2d24b6875e74d316a37eeba21210debee9a8434a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 22:09:42 +0100 Subject: [PATCH 2/7] feat[next]: add EmbeddedBackend and the embedded backend instances - `Backend.__gt_allocator__` moves to the base class and returns the backend's allocator, unwrapping an allocator factory; `CompiledBackend` keeps its narrower override. - `EmbeddedBackend(Backend)`, a sibling of `CompiledBackend`, runs the Python definition directly on fields; its allocator is an array namespace (validated, NumPy by default). - New module `program_processors.runners.embedded` with `embedded_numpy` (also exported as `gtx.embedded_numpy`) and the lazily created `embedded_cupy` / `embedded_jax`, which raise `AttributeError` naming the missing optional package. - `Backend.__deepcopy__` returns the backend itself (immutable configuration; the NumPy module it holds cannot be copied), and `Program.__gt_allocator__` is a plain property, so a program used as `allocator=` does not cache a module and stays deep-copyable. Copies share the backend. Programs do not dispatch to `EmbeddedBackend` yet; that is the next step. --- src/gt4py/next/__init__.py | 2 + src/gt4py/next/backend.py | 65 ++++++++++- src/gt4py/next/ffront/decorator.py | 4 +- .../program_processors/runners/embedded.py | 67 +++++++++++ tests/next_tests/unit_tests/test_backend.py | 104 ++++++++++++++++++ 5 files changed, 237 insertions(+), 5 deletions(-) create mode 100644 src/gt4py/next/program_processors/runners/embedded.py diff --git a/src/gt4py/next/__init__.py b/src/gt4py/next/__init__.py index 3b9f97592f..cad7c9a207 100644 --- a/src/gt4py/next/__init__.py +++ b/src/gt4py/next/__init__.py @@ -97,6 +97,7 @@ where, ) from .otf.compiled_program import wait_for_compilation +from .program_processors.runners.embedded import embedded_numpy from .program_processors.runners.gtfn import run_gtfn as gtfn_cpu, run_gtfn_gpu as gtfn_gpu from .program_processors.runners.roundtrip import default as itir_python @@ -144,6 +145,7 @@ # from otf "wait_for_compilation", # from program_processor + "embedded_numpy", "gtfn_cpu", "gtfn_gpu", "itir_python", diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 85ad846df7..838dc24fa3 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -9,9 +9,12 @@ from __future__ import annotations import dataclasses -from typing import Callable +import typing +from typing import Any, Callable, Final, Self -from gt4py._core import definitions as core_defs +import numpy as np + +from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.next import config, constructors, custom_layout_allocators as next_allocators from gt4py.next.ffront import ( foast_to_gtir, @@ -147,7 +150,11 @@ class Backend: A backend decides how a program runs and where the buffers of its fields are allocated. This class is abstract: instantiate a concrete kind, such as - `CompiledBackend`. + `CompiledBackend` or `EmbeddedBackend`. + + Backends are immutable configuration objects: a deep copy of a backend is the + backend itself, so deep copies of programs share their backend, including any + caller-owned state it holds (e.g. a DaCe external workspace). Attributes: name: Human-readable label used in metrics, logs and diagnostics. It is @@ -165,9 +172,25 @@ class Backend: def __post_init__(self) -> None: if type(self) is Backend: raise TypeError( - "'Backend' is abstract: instantiate a concrete kind such as 'CompiledBackend'." + "'Backend' is abstract: instantiate a concrete kind such as 'CompiledBackend'" + " or 'EmbeddedBackend'." ) + def __deepcopy__(self, memo: dict[int, Any]) -> Self: + # Immutable configuration object: share its fields (array namespaces, + # compile pipelines with caches, caller-owned buffers) instead of copying them. + return self + + @property + def __gt_allocator__( + self, + ) -> next_allocators.FieldBufferAllocatorProtocol | core_ndarray_utils.ArrayNamespace: + """The allocator for fields used with this backend (unwrapping an allocator factory).""" + allocator = self.allocator + if next_allocators.is_field_allocator_factory(allocator): + return allocator.__gt_allocator__ + return allocator + @dataclasses.dataclass(frozen=True) class CompiledBackend(Backend): @@ -201,6 +224,40 @@ def __gt_allocator__(self) -> next_allocators.FieldBufferAllocatorProtocol: return self.allocator +_NUMPY_NAMESPACE: Final = typing.cast(core_ndarray_utils.ArrayNamespace, np) + + +@dataclasses.dataclass(frozen=True) +class EmbeddedBackend(Backend): + """ + A backend that runs the Python definition directly on fields, without lowering. + + Execution is the same for every instance: embedded operators dispatch on the + array types of their arguments. The allocator only decides where gt4py + allocates the buffers of fields for this backend, e.g. in + `gtx.zeros(..., allocator=program)`. The instances live in + `gt4py.next.program_processors.runners.embedded`. + + Attributes: + allocator: The array namespace (e.g. `numpy`, `cupy`, `jax.numpy`) used + to allocate field buffers. Defaults to NumPy. + """ + + allocator: core_ndarray_utils.ArrayNamespace = _NUMPY_NAMESPACE + + def __post_init__(self) -> None: + super().__post_init__() + if not core_ndarray_utils.is_array_namespace(self.allocator): + raise TypeError( + f"The allocator of embedded backend '{self.name}' must be an array namespace" + f" (e.g. 'numpy'), got '{self.allocator}'." + ) + + @property + def __gt_allocator__(self) -> core_ndarray_utils.ArrayNamespace: + return self.allocator + + @dataclasses.dataclass(frozen=True) class Toolchain: """ diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 978a120ca8..76cec44b93 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -305,7 +305,9 @@ def __post_init__(self) -> None: def __name__(self) -> str: return self.definition_stage.definition.__name__ - @functools.cached_property + # A plain property, not a cached one: caching would store the allocator (which + # may hold a module) in the program, and the program could not be deep-copied. + @property def __gt_allocator__( self, ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: diff --git a/src/gt4py/next/program_processors/runners/embedded.py b/src/gt4py/next/program_processors/runners/embedded.py new file mode 100644 index 0000000000..77780802d1 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/embedded.py @@ -0,0 +1,67 @@ +# 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 backends: run programs and operators directly in Python on fields. + +- `embedded_numpy` allocates with NumPy. It is the default backend and is also + exported as `gt4py.next.embedded_numpy`. +- `embedded_cupy` allocates with CuPy and `embedded_jax` with `jax.numpy`. They + are created on first access and require the optional package; accessing them + without it raises `AttributeError`. +""" + +from __future__ import annotations + +import typing +from typing import Final + +import numpy as np + +from gt4py._core import ndarray_utils as core_ndarray_utils +from gt4py.next import backend as next_backend + + +embedded_numpy: Final = next_backend.EmbeddedBackend( + name="embedded_numpy", allocator=typing.cast(core_ndarray_utils.ArrayNamespace, np) +) + + +def _import_cupy() -> core_ndarray_utils.ArrayNamespace: + import cupy + + return typing.cast(core_ndarray_utils.ArrayNamespace, cupy) + + +def _import_jax_numpy() -> core_ndarray_utils.ArrayNamespace: + import jax.numpy + + return typing.cast(core_ndarray_utils.ArrayNamespace, jax.numpy) + + +# Backends needing an optional package: name -> (package, namespace importer) +_OPTIONAL_BACKENDS: Final[ + dict[str, tuple[str, typing.Callable[[], core_ndarray_utils.ArrayNamespace]]] +] = { + "embedded_cupy": ("cupy", _import_cupy), + "embedded_jax": ("jax", _import_jax_numpy), +} + + +def __getattr__(name: str) -> next_backend.EmbeddedBackend: + if name not in _OPTIONAL_BACKENDS: + raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") + package, import_namespace = _OPTIONAL_BACKENDS[name] + try: + array_ns = import_namespace() + except ImportError as error: + raise AttributeError(f"'{name}' requires the optional '{package}' package.") from error + backend = next_backend.EmbeddedBackend(name=name, allocator=array_ns) + # Cache it, so that every access returns the same instance. + globals()[name] = backend + return backend diff --git a/tests/next_tests/unit_tests/test_backend.py b/tests/next_tests/unit_tests/test_backend.py index 7c8f6dc7a8..e3740f7fa2 100644 --- a/tests/next_tests/unit_tests/test_backend.py +++ b/tests/next_tests/unit_tests/test_backend.py @@ -8,13 +8,20 @@ """Tests for the backend kinds and the internal toolchain in `gt4py.next.backend`.""" +import copy import dataclasses +import importlib.util +import numpy as np import pytest import gt4py.next as gtx from gt4py.next import backend as next_backend, custom_layout_allocators as next_allocators from gt4py.next.otf import arguments, artifacts +from gt4py.next.program_processors.runners import embedded as embedded_runners, gtfn + + +IDim = gtx.Dimension("IDim") @dataclasses.dataclass(frozen=True) @@ -109,3 +116,100 @@ def test_toolchain_is_not_public(): assert "Toolchain" not in gtx.__all__ assert "Toolchain" not in gtx.typing.__all__ assert "Backend" in gtx.typing.__all__ + + +def test_backend_allocator_unwraps_a_factory(): + inner = next_allocators.StandardCPUFieldBufferAllocator() + + class Factory: + __gt_allocator__ = inner + + assert _OtherBackend(name="other", allocator=Factory()).__gt_allocator__ is inner + assert _OtherBackend(name="other", allocator=inner).__gt_allocator__ is inner + assert _OtherBackend(name="other", allocator=np).__gt_allocator__ is np + + +def test_embedded_backend_defaults_to_numpy(): + backend = next_backend.EmbeddedBackend(name="my_embedded") + + assert isinstance(backend, next_backend.Backend) + assert not isinstance(backend, next_backend.CompiledBackend) + assert backend.allocator is np + assert backend.__gt_allocator__ is np + assert [field.name for field in dataclasses.fields(backend)] == ["name", "allocator"] + + +def test_embedded_backend_rejects_a_non_namespace_allocator(): + with pytest.raises(TypeError, match="must be an array namespace"): + next_backend.EmbeddedBackend( + name="bad", allocator=next_allocators.StandardCPUFieldBufferAllocator() + ) + + +def test_embedded_backend_instances(): + assert gtx.embedded_numpy is embedded_runners.embedded_numpy + assert isinstance(gtx.embedded_numpy, next_backend.EmbeddedBackend) + assert gtx.embedded_numpy.name == "embedded_numpy" + assert gtx.embedded_numpy.allocator is np + assert "embedded_numpy" in gtx.__all__ + + +@pytest.mark.parametrize("name, package", [("embedded_cupy", "cupy"), ("embedded_jax", "jax")]) +def test_optional_embedded_backend(name, package): + if importlib.util.find_spec(package) is None: + with pytest.raises(AttributeError, match=f"requires the optional '{package}' package"): + getattr(embedded_runners, name) + else: + backend = getattr(embedded_runners, name) + assert isinstance(backend, next_backend.EmbeddedBackend) + assert backend.name == name + assert getattr(embedded_runners, name) is backend + + +def test_embedded_runners_unknown_attribute(): + with pytest.raises(AttributeError, match="no attribute 'embedded_foo'"): + embedded_runners.embedded_foo # noqa: B018 [useless-expression] + + +@pytest.mark.parametrize( + "backend", + [gtx.embedded_numpy, gtfn.run_gtfn, _make_compiled_backend()], + ids=lambda backend: backend.name, +) +def test_deepcopy_of_a_backend_is_the_backend(backend): + assert copy.deepcopy(backend) is backend + + +def _make_copy_program(backend): + @gtx.field_operator(backend=backend) + def identity(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + + @gtx.program(backend=backend) + def copy_program(a: gtx.Field[[IDim], gtx.float64], out: gtx.Field[[IDim], gtx.float64]): + identity(a, out=out) + + return copy_program + + +@pytest.mark.parametrize( + "backend", [gtx.embedded_numpy, gtfn.run_gtfn], ids=lambda backend: backend.name +) +def test_deepcopy_of_a_program_shares_the_backend(backend): + program = _make_copy_program(backend) + + program_copy = copy.deepcopy(program) + + assert program_copy is not program + assert program_copy.backend is backend + + +def test_deepcopy_of_a_compiled_program_after_allocation(): + program = _make_copy_program(gtfn.run_gtfn) + field = gtx.zeros({IDim: 3}, allocator=program) + assert isinstance(field.ndarray, np.ndarray) + + program_copy = copy.deepcopy(program) + + assert program_copy.backend is gtfn.run_gtfn + assert "__gt_allocator__" not in program.__dict__ From dbdbf7f8cd5ed38fe4028aace11d3e8896cdd544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 22:13:54 +0100 Subject: [PATCH 3/7] feat[next]: run programs and operators on EmbeddedBackend objects The dispatch helper treats an `EmbeddedBackend` like `None` (embedded execution); `None` keeps working until it becomes an error. - `Program.__gt_allocator__` returns the backend's allocator for every backend kind, so `gtx.zeros(..., allocator=program)` allocates with the array namespace of an embedded program. - Embedded calls report metrics under `prog` (e.g. `prog`); `None` still reports `prog<'embedded'>`. - `.compile()` on a program or operator with an embedded backend says that embedded programs are not compiled. --- src/gt4py/next/ffront/decorator.py | 30 +++++++++----- .../ffront_tests/test_decorator.py | 29 ++++++++++++++ .../instrumentation_tests/test_hooks.py | 12 +++--- .../ffront_tests/test_decorator_dispatch.py | 39 +++++++++++++++++++ tests/next_tests/unit_tests/test_backend.py | 9 +++-- 5 files changed, 101 insertions(+), 18 deletions(-) diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 76cec44b93..61563480cf 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, @@ -77,15 +77,21 @@ def _compiled_backend_or_none( match backend: case next_backend.CompiledBackend(): return backend - case None: + case next_backend.EmbeddedBackend() | None: return None case _: raise TypeError( f"Backend '{backend.name}' of type '{type(backend).__name__}' is not supported:" - " expected a 'CompiledBackend', or None for embedded execution." + " expected a 'CompiledBackend' or an 'EmbeddedBackend'." ) +def _not_compilable_message(backend: next_backend.Backend | None, what: str) -> str: + if backend is None: + return f"Cannot compile a {what} without backend." + return f"Backend '{backend.name}' is an embedded backend; embedded programs are not compiled." + + ProgramCallMetricsCollector = metrics.make_collector( level=metrics.MINIMAL, metric_name=metrics.TOTAL_METRIC ) @@ -111,7 +117,8 @@ def embedded_program_call_context( kwargs: dict[str, Any], ) -> contextlib.AbstractContextManager: """Hook called at the beginning and end of an embedded program call.""" - return metrics.metrics_source_key_setter(f"{program.__name__}<'embedded'>") + backend_name = "'embedded'" if program.backend is None else program.backend.name + return metrics.metrics_source_key_setter(f"{program.__name__}<{backend_name}>") @dataclasses.dataclass(frozen=True) @@ -166,7 +173,7 @@ def _make_compiled_programs_pool( ) -> compiled_program.CompiledProgramsPool: compiled_backend = _compiled_backend_or_none(self.backend) if compiled_backend is None: - raise RuntimeError("Cannot compile a program without backend.") + raise RuntimeError(_not_compilable_message(self.backend, "program")) program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) assert isinstance(program_type, ts_ffront.ProgramType) @@ -310,11 +317,14 @@ def __name__(self) -> str: @property def __gt_allocator__( self, - ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: - compiled_backend = _compiled_backend_or_none(self.backend) - if compiled_backend is None: + ) -> ( + next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + | core_ndarray_utils.ArrayNamespace + ): + _compiled_backend_or_none(self.backend) # rejects unsupported backend kinds + if self.backend is None: raise RuntimeError(f"Program '{self}' does not have a backend set.") - return compiled_backend.__gt_allocator__ + return self.backend.__gt_allocator__ @property def definition(self) -> types.FunctionType: @@ -753,7 +763,7 @@ class FieldOperatorFromFoast(FieldOperator): def __call__(self, *args: Any, **kwargs: Any) -> Any: compiled_backend = _compiled_backend_or_none(self.backend) if compiled_backend is None: - raise RuntimeError("Cannot compile a field operator without backend.") + raise RuntimeError(_not_compilable_message(self.backend, "field operator")) compiled_fo = next_backend.Toolchain(compiled_backend).compile( self.foast_stage, arguments.CompileTimeArgs.from_concrete(*args, **kwargs) ) 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 2e49f61a6e..9f989c82ea 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 @@ -77,6 +77,35 @@ def testee(a: cases.IField, out: cases.IField): assert set(source.metrics.keys()) == set(expected_names) +@pytest.mark.parametrize( + "metrics_level", + [metrics.MINIMAL, metrics.PERFORMANCE, metrics.ALL], +) +def test_collect_metrics_embedded(metrics_level): + @gtx.field_operator(backend=gtx.embedded_numpy) + def testee_op(a: cases.IField, b: cases.IField) -> cases.IField: + return a + b + + @gtx.program(backend=gtx.embedded_numpy) + def testee(a: cases.IField, out: cases.IField): + testee_op(a, a, out=out) + + a = gtx.ones({cases.IDim: 5}, dtype=gtx.int32) + out = gtx.zeros({cases.IDim: 5}, dtype=gtx.int32) + with ( + mock.patch("gt4py.next.config.COLLECT_METRICS_LEVEL", metrics_level), + mock.patch( + "gt4py.next.instrumentation.metrics.sources", collections.defaultdict(metrics.Source) + ), + pytest.warns(UserWarning, match="Using Python execution"), + ): + testee(a, out, offset_provider={}) + + # Embedded calls are reported under the name of their backend. + assert set(metrics.sources.keys()) == {"testee"} + assert "total" in metrics.sources["testee"].metrics + + def test_docstring(cartesian_case): @gtx.field_operator def fieldop_with_docstring(a: cases.IField) -> cases.IField: diff --git a/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py b/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py index 9f51689d77..b566623a4e 100644 --- a/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py +++ b/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py @@ -15,15 +15,15 @@ import pytest import gt4py.next as gtx -from gt4py.next import common, Dims, gtfn_cpu, typing as gtx_typing +from gt4py.next import backend as next_backend, common, Dims, gtfn_cpu, typing as gtx_typing from gt4py.next.instrumentation import gpu_profiler, hooks try: from gt4py.next.program_processors.runners import dace as dace_backends - BACKENDS = [None, gtfn_cpu, dace_backends.run_dace_cpu] + BACKENDS = [None, gtx.embedded_numpy, gtfn_cpu, dace_backends.run_dace_cpu] except ImportError: - BACKENDS = [None, gtfn_cpu] + BACKENDS = [None, gtx.embedded_numpy, gtfn_cpu] IDim = gtx.Dimension("IDim") @@ -161,7 +161,7 @@ def test_program_call_hooks(backend: gtx_typing.Backend): assert hook_name == "custom_program_callback" assert hook_call_info["program"] == test_program.__name__ - if backend is None: + if backend is None or isinstance(backend, next_backend.EmbeddedBackend): # The embedded program call hook should have also been called # with the embedded backend assert len(embedded_callback_results) == 2 @@ -206,7 +206,9 @@ def test_program_call_hooks(backend: gtx_typing.Backend): @pytest.mark.parametrize( - "backend", [b for b in BACKENDS if b is not None], ids=lambda b: getattr(b, "name", str(b)) + "backend", + [b for b in BACKENDS if isinstance(b, next_backend.CompiledBackend)], + ids=lambda b: getattr(b, "name", str(b)), ) def test_compile_variant_hook(backend: gtx_typing.Backend): def custom_compile_variant_hook( diff --git a/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py b/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py index 3e77a08c30..554a337450 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py @@ -103,6 +103,45 @@ def test_none_backend_runs_embedded(): copy_program.compile(offset_provider={}) +def test_embedded_backend_runs_embedded(): + copy, copy_program, scan = _make_testees(gtx.embedded_numpy) + a = gtx.as_field([IDim], np.arange(3.0)) + out = gtx.zeros({IDim: 3}) + k_field = gtx.as_field([KDim], np.ones(3)) + k_out = gtx.zeros({KDim: 3}) + + with pytest.warns(UserWarning, match="Using Python execution"): + copy_program(a, out, offset_provider={}) + assert np.allclose(out.asnumpy(), a.asnumpy()) + + out = gtx.zeros({IDim: 3}) + copy(a, out=out, offset_provider={}) + assert np.allclose(out.asnumpy(), a.asnumpy()) + + scan(k_field, out=k_out, offset_provider={}) + assert np.allclose(k_out.asnumpy(), [1.0, 2.0, 3.0]) + + with pytest.raises(RuntimeError, match="'embedded_numpy' is an embedded backend"): + copy_program.compile(offset_provider={}) + with pytest.raises(RuntimeError, match="'embedded_numpy' is an embedded backend"): + copy.compile(offset_provider={}) + + +@pytest.mark.parametrize( + "backend", + [gtx.embedded_numpy, next_backend.EmbeddedBackend(name="other_numpy")], + ids=lambda backend: backend.name, +) +def test_embedded_backend_allocator(backend): + _, copy_program, _ = _make_testees(backend) + + assert copy_program.__gt_allocator__ is np + field = gtx.zeros({IDim: 3}, allocator=copy_program) + assert isinstance(field.ndarray, np.ndarray) + field = gtx.ones({IDim: 3}, allocator=backend) + assert isinstance(field.ndarray, np.ndarray) + + def test_compiled_backend_allocator_and_toolchain(): _, copy_program, _ = _make_testees(roundtrip.default) diff --git a/tests/next_tests/unit_tests/test_backend.py b/tests/next_tests/unit_tests/test_backend.py index e3740f7fa2..193d2b908f 100644 --- a/tests/next_tests/unit_tests/test_backend.py +++ b/tests/next_tests/unit_tests/test_backend.py @@ -204,12 +204,15 @@ def test_deepcopy_of_a_program_shares_the_backend(backend): assert program_copy.backend is backend -def test_deepcopy_of_a_compiled_program_after_allocation(): - program = _make_copy_program(gtfn.run_gtfn) +@pytest.mark.parametrize( + "backend", [gtx.embedded_numpy, gtfn.run_gtfn], ids=lambda backend: backend.name +) +def test_deepcopy_of_a_program_after_allocation(backend): + program = _make_copy_program(backend) field = gtx.zeros({IDim: 3}, allocator=program) assert isinstance(field.ndarray, np.ndarray) program_copy = copy.deepcopy(program) - assert program_copy.backend is gtfn.run_gtfn + assert program_copy.backend is backend assert "__gt_allocator__" not in program.__dict__ From 27b314b114f7ff2714a130a30ff131ff22a4b60f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 22:27:12 +0100 Subject: [PATCH 4/7] test[next]: run the embedded test matrix on the real embedded backends - `EmbeddedDummyBackend` and `numpy_execution` / `cupy_execution` / `jax_numpy_execution` are deleted; the `EmbeddedIds` parameters load `runners.embedded.embedded_{numpy,cupy,jax}`. - `cartesian_case` / `unstructured_case` always use the backend of `exec_alloc_descriptor`; `Case.backend` is a `Backend`, never `None`, and `Case.is_embedded` replaces the `backend is None` checks. The `*_no_backend` cases use `cases_utils.no_backend`. - Tests that mapped the dummy to `None` pass the embedded backend directly. --- tests/next_tests/definitions.py | 21 ++-------- tests/next_tests/integration_tests/cases.py | 41 ++++++++----------- .../integration_tests/cases_utils.py | 2 +- .../ffront_tests/test_compiled_program.py | 40 +++++++++--------- .../ffront_tests/test_decorator.py | 2 +- .../test_math_builtin_execution.py | 2 +- .../ffront_tests/test_reductions.py | 4 +- .../ffront_tests/test_ffront_fvm_nabla.py | 24 +++++------ .../ffront_tests/test_icon_like_scan.py | 4 +- .../test_offset_dimensions_names.py | 7 +--- tests/next_tests/unit_tests/test_cases.py | 25 ++++++++++- 11 files changed, 82 insertions(+), 90 deletions(-) diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index adf8aa6887..05a96a03d0 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -8,15 +8,11 @@ """Contains definition of test-exclusion matrices, see ADR 15.""" -import dataclasses import enum import importlib from typing import Final import pytest -from gt4py.next.embedded import nd_array_field -from gt4py.next import constructors - # Skip definitions XFAIL = pytest.xfail SKIP = pytest.skip @@ -50,21 +46,10 @@ class ProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): DOUBLE_ROUNDTRIP = "gt4py.next.program_processors.runners.double_roundtrip.backend" -@dataclasses.dataclass(frozen=True) -class EmbeddedDummyBackend: - name: str - allocator: constructors.Allocator - - -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) - - 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" + NUMPY_EXECUTION = "gt4py.next.program_processors.runners.embedded.embedded_numpy" + CUPY_EXECUTION = "gt4py.next.program_processors.runners.embedded.embedded_cupy" + JAX_NUMPY_EXECUTION = "gt4py.next.program_processors.runners.embedded.embedded_jax" class OptionalProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index b5d99e2eb5..eee6207b20 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -45,7 +45,6 @@ from gt4py.next.type_system import type_specifications as ts, type_translation from gt4py.next.otf import arguments -from next_tests import definitions as test_definitions from next_tests.integration_tests.cases_utils import ( # noqa: F401 [unused-import] C2E, C2V, @@ -67,6 +66,7 @@ exec_alloc_descriptor, mesh_descriptor, MeshDescriptor, + no_backend, simple_cartesian_grid, CartesianGridDescriptor, ) @@ -540,41 +540,31 @@ def verify_with_default_data( @pytest.fixture def cartesian_case_no_backend(): - return Case.from_cartesian_grid_descriptor(simple_cartesian_grid()) + return Case.from_cartesian_grid_descriptor(simple_cartesian_grid(), backend=no_backend) @pytest.fixture -def cartesian_case( - exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Backend, -): +def cartesian_case(exec_alloc_descriptor: next_backend.Backend): return Case.from_cartesian_grid_descriptor( simple_cartesian_grid(), - backend=( - None - if isinstance(exec_alloc_descriptor, test_definitions.EmbeddedDummyBackend) - else exec_alloc_descriptor - ), + backend=exec_alloc_descriptor, allocator=exec_alloc_descriptor.allocator, ) @pytest.fixture def unstructured_case_no_backend(mesh_descriptor: MeshDescriptor): - return Case.from_mesh_descriptor(mesh_descriptor) + return Case.from_mesh_descriptor(mesh_descriptor, backend=no_backend) @pytest.fixture def unstructured_case( mesh_descriptor: MeshDescriptor, - exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Backend, + exec_alloc_descriptor: next_backend.Backend, ): return Case.from_mesh_descriptor( mesh_descriptor, - backend=( - None - if isinstance(exec_alloc_descriptor, test_definitions.EmbeddedDummyBackend) - else exec_alloc_descriptor - ), + backend=exec_alloc_descriptor, allocator=exec_alloc_descriptor.allocator, ) @@ -712,11 +702,16 @@ def get_default_data( class Case: """Parametrizable components for single feature integration tests.""" - backend: Optional[next_backend.Backend] + backend: next_backend.Backend offset_provider: dict[str, common.Connectivity | gtx.Dimension] default_sizes: dict[gtx.Dimension, int] grid_type: common.GridType - allocator: next_allocators.FieldBufferAllocatorFactoryProtocol + allocator: constructors.Allocator + + @property + def is_embedded(self) -> bool: + """Whether the case runs programs and operators embedded (in Python).""" + return isinstance(self.backend, next_backend.EmbeddedBackend) @property def as_field(self): @@ -726,8 +721,8 @@ def as_field(self): def from_cartesian_grid_descriptor( cls, grid_descriptor: CartesianGridDescriptor, - backend: Optional[next_backend.Backend] = None, - allocator: Optional[next_allocators.FieldBufferAllocatorFactoryProtocol] = None, + backend: next_backend.Backend = no_backend, + allocator: Optional[constructors.Allocator] = None, ) -> Case: return cls( backend=backend, @@ -748,8 +743,8 @@ def from_cartesian_grid_descriptor( def from_mesh_descriptor( cls, mesh_descriptor: MeshDescriptor, - backend: Optional[next_backend.Backend] = None, - allocator: Optional[next_allocators.FieldBufferAllocatorFactoryProtocol] = None, + backend: next_backend.Backend = no_backend, + allocator: Optional[constructors.Allocator] = None, ) -> Case: return cls( backend=backend, diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index d996e9f309..ea48a90cf8 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -77,7 +77,7 @@ class NoBackend(next_backend.Backend): pytest.param( next_tests.definitions.ProgramBackendId.GTFN_GPU, marks=pytest.mark.requires_gpu ), - # will use the default (embedded) execution, but input/output allocated with the provided allocator + # embedded execution: the embedded backends differ only in their allocator next_tests.definitions.EmbeddedIds.NUMPY_EXECUTION, pytest.param( next_tests.definitions.EmbeddedIds.CUPY_EXECUTION, marks=pytest.mark.requires_gpu 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 e77f6aa41a..729a8f2e11 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 @@ -125,7 +125,7 @@ def testee(a: cases.KField, out: cases.KField): def test_compile(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile(offset_provider=cartesian_case.offset_provider) @@ -144,7 +144,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") empty_static_args = {} @@ -163,7 +163,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") with pytest.raises(ValueError): compile_testee.compile(offset_provider=cartesian_case.offset_provider).compile( @@ -172,7 +172,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile(offset_provider=cartesian_case.offset_provider) @@ -188,7 +188,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") if isinstance(compile_testee_scan, gtx.ffront.decorator.FieldOperator): @@ -208,7 +208,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") compile_testee_domain.compile(offset_provider=cartesian_case.offset_provider) @@ -229,7 +229,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 unstructured_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") @gtx.field_operator @@ -255,7 +255,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 unstructured_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") compile_testee_unstructured.compile( @@ -291,7 +291,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 unstructured_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") # compiled for skip_value_mesh @@ -315,7 +315,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 unstructured_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") # compiled for skip_value_mesh and simple_mesh @@ -364,7 +364,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") @gtx.program(backend=cartesian_case.backend) @@ -528,7 +528,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") with mock.patch.object(config, "ENABLE_JIT_DEFAULT", True): @@ -778,7 +778,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") @gtx.program( @@ -849,7 +849,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") elif ( cartesian_case.backend.name.startswith("run_dace_gpu") @@ -933,7 +933,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") with ( @@ -960,7 +960,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") runner = compiled_program.runners.ProcessRunner( @@ -989,7 +989,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") # Failing only once the gate opens keeps the future pending until after @@ -1022,7 +1022,7 @@ def failing_compiler(compilable): @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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") captured_cargs: Optional[arguments.CompileTimeArgs] = None @@ -1070,7 +1070,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 cartesian_case.is_embedded: pytest.skip("Embedded compiled program doesn't make sense.") @gtx.scan_operator(axis=KDim, forward=True, init=0, backend=cartesian_case.backend) @@ -1105,7 +1105,7 @@ def test_warn_on_direct_scan_operator_call(cartesian_case, scan_operator_testee) def test_forbid_compilation_guard_is_effective(cartesian_case): """`_forbid_compilation` lets compiled variants run and makes any new compilation fail.""" - if cartesian_case.backend is None: + if cartesian_case.is_embedded: pytest.skip("Embedded execution does not compile.") @gtx.field_operator 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 9f989c82ea..623d697a62 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 cartesian_case.is_embedded: 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_math_builtin_execution.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py index 9bd7e43273..b13cabecc6 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 cartesian_case.is_embedded: # 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_reductions.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py index 311b1870ed..d9ae31013e 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 unstructured_case.is_embedded: 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 unstructured_case.is_embedded: pytest.xfail("Embedded backend only supports contiguous field domains.") @gtx.field_operator diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py index 216448db1d..72b43a2f46 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_ffront_fvm_nabla.py @@ -13,9 +13,9 @@ from packaging import version from gt4py import next as gtx -from gt4py.next import neighbor_sum +from gt4py._core import definitions as core_defs +from gt4py.next import backend as next_backend, neighbor_sum -from next_tests import definitions as test_definitions from next_tests.integration_tests.cases_utils import ( exec_alloc_descriptor, ) @@ -32,8 +32,12 @@ def _skip_if_cupy_14_0_1_hip(exec_alloc_descriptor) -> None: - if exec_alloc_descriptor is test_definitions.cupy_execution: - cp = test_definitions.cupy_execution.allocator + if ( + isinstance(exec_alloc_descriptor, next_backend.EmbeddedBackend) + and core_defs.cp is not None + and exec_alloc_descriptor.allocator is core_defs.cp + ): + cp = core_defs.cp if cp.cuda.runtime.is_hip: cp_version = version.parse(cp.__version__) if cp_version.major == 14 and cp_version.minor == 0 and cp_version.micro < 2: @@ -82,11 +86,7 @@ def test_ffront_compute_zavgS(exec_alloc_descriptor): zavgS = gtx.zeros({Edge: setup.edges_size}, allocator=exec_alloc_descriptor.allocator) - compute_zavgS.with_backend( - None - if isinstance(exec_alloc_descriptor, test_definitions.EmbeddedDummyBackend) - else exec_alloc_descriptor - )( + compute_zavgS.with_backend(exec_alloc_descriptor)( setup.input_field, setup.S_fields[0], out=zavgS, @@ -108,11 +108,7 @@ def test_ffront_nabla(exec_alloc_descriptor): pnabla_MXX = gtx.zeros({Vertex: setup.nodes_size}, allocator=exec_alloc_descriptor.allocator) pnabla_MYY = gtx.zeros({Vertex: setup.nodes_size}, allocator=exec_alloc_descriptor.allocator) - pnabla.with_backend( - None - if isinstance(exec_alloc_descriptor, test_definitions.EmbeddedDummyBackend) - else exec_alloc_descriptor - )( + pnabla.with_backend(exec_alloc_descriptor)( setup.input_field, setup.S_fields, setup.sign_field, diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py index 234b8f4d02..2dda107a00 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_icon_like_scan.py @@ -183,9 +183,7 @@ def reference( @pytest.fixture def test_setup(exec_alloc_descriptor): test_case = cases.Case( - None - if isinstance(exec_alloc_descriptor, test_definitions.EmbeddedDummyBackend) - else exec_alloc_descriptor, + exec_alloc_descriptor, offset_provider={}, default_sizes={Cell: 14, KDim: 10}, grid_type=common.GridType.UNSTRUCTURED, diff --git a/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py b/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py index 89a72b428f..79237df059 100644 --- a/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py +++ b/tests/next_tests/regression_tests/ffront_tests/test_offset_dimensions_names.py @@ -28,7 +28,6 @@ from gt4py import next as gtx from gt4py.next import Dims, Field, common, constructors, neighbor_sum -from next_tests import definitions as test_defs from next_tests.integration_tests import cases from next_tests.integration_tests import cases_utils from next_tests.integration_tests.cases_utils import ( # noqa: F401 [unused-import] # fixture @@ -63,11 +62,7 @@ def _case(exec_alloc_descriptor, tag: str, local_dim: common.Dimension) -> cases # array, and `simple_mesh` builds the table from NumPy anyway. v2e_arr = mesh.offset_provider["V2E"].asnumpy() return cases.Case( - ( - None - if isinstance(exec_alloc_descriptor, test_defs.EmbeddedDummyBackend) - else exec_alloc_descriptor - ), + exec_alloc_descriptor, offset_provider={ tag: constructors.as_connectivity( domain={V: v2e_arr.shape[0], local_dim: v2e_arr.shape[1]}, diff --git a/tests/next_tests/unit_tests/test_cases.py b/tests/next_tests/unit_tests/test_cases.py index e5c5182b81..0a26cd8014 100644 --- a/tests/next_tests/unit_tests/test_cases.py +++ b/tests/next_tests/unit_tests/test_cases.py @@ -10,12 +10,13 @@ import pytest import gt4py.next as gtx -from gt4py.next import errors +from gt4py.next import backend as next_backend, errors from next_tests import definitions from next_tests.integration_tests import cases from next_tests.integration_tests.cases import ( # noqa: F401 [unused-import] cartesian_case, + cartesian_case_no_backend, exec_alloc_descriptor, tree_mapped_np_allclose, ) @@ -130,3 +131,25 @@ def wrong_ref(a, b): with pytest.raises(AssertionError): cases.verify_with_default_data(cartesian_case, addition, ref=wrong_ref) + + +def test_case_backend_is_the_exec_alloc_descriptor(cartesian_case, exec_alloc_descriptor): + assert cartesian_case.backend is exec_alloc_descriptor + assert cartesian_case.allocator is exec_alloc_descriptor.allocator + assert cartesian_case.is_embedded == isinstance( + exec_alloc_descriptor, next_backend.EmbeddedBackend + ) + + +@pytest.mark.parametrize("embedded_id", list(definitions.EmbeddedIds)) +def test_embedded_ids_load_the_embedded_backends(embedded_id): + try: + backend = embedded_id.load() + except AttributeError as error: + pytest.skip(str(error)) # the optional array library is not installed + assert isinstance(backend, next_backend.EmbeddedBackend) + + +def test_no_backend_cases(cartesian_case_no_backend): + assert cartesian_case_no_backend.backend is cases.no_backend + assert not cartesian_case_no_backend.is_embedded From 1d3fc05b22a7482ecda31f18542e9bd80a417bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 22:34:57 +0100 Subject: [PATCH 5/7] feat[next]!: make embedded_numpy the default backend and reject backend=None - `decorator.DEFAULT_BACKEND` is `gtx.embedded_numpy`: programs and operators decorated without `backend=` still run embedded on NumPy. - `backend=None` raises `TypeError` when a program or operator is created (decorators, `from_function`, `with_backend`, `dataclasses.replace`), and the message names the replacement. No deprecation aliases. - The dispatch helper accepts `CompiledBackend` and `EmbeddedBackend` only; `backend` is typed `Backend` (no `None`) everywhere in the decorators. - Embedded metrics keys always use the backend name. - `iterator.runtime`: `fendef(..., backend=None)` keeps meaning iterator-level embedded execution; an `EmbeddedBackend` is rejected with a message pointing to it. Tests: `backend=None` is rejected everywhere it can be passed, the default is `embedded_numpy`, `with_backend(None)` is a mypy error, and the remaining `None`-as-embedded uses are gone. --- src/gt4py/next/ffront/decorator.py | 63 +++++++++---------- src/gt4py/next/iterator/runtime.py | 10 ++- .../ffront_tests/test_decorator.py | 6 +- .../test_math_builtin_execution.py | 4 +- .../instrumentation_tests/test_hooks.py | 10 +-- .../ffront_tests/test_decorator_dispatch.py | 56 ++++++++++++++--- .../unit_tests/ffront_tests/test_stages.py | 8 +-- .../iterator_tests/test_runtime_domain.py | 17 ++++- .../dace_tests/test_dace_backend.py | 11 +++- tests/next_tests/unit_tests/test_backend.py | 15 +++++ typing_tests/test_next.yaml | 24 +++++-- 11 files changed, 158 insertions(+), 66 deletions(-) diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 61563480cf..2a60e6879b 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -47,23 +47,27 @@ 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 as embedded_runners from gt4py.next.type_system import type_info, type_specifications as ts, type_translation -DEFAULT_BACKEND: next_backend.Backend | None = None +DEFAULT_BACKEND: next_backend.Backend = embedded_runners.embedded_numpy def _check_backend(backend: Any) -> None: """Reject, when a program or operator is created, anything that is not a backend.""" - if backend is not None and not isinstance(backend, next_backend.Backend): + if backend is None: raise TypeError( - f"Expected a 'gt4py.next.backend.Backend' (or None for embedded execution)," - f" got '{type(backend).__name__}'." + "'backend=None' is not supported: embedded execution is selected by an" + " 'EmbeddedBackend'. Omit 'backend' to use the default, or pass one such as" + " 'gtx.embedded_numpy'." ) + if not isinstance(backend, next_backend.Backend): + raise TypeError(f"Expected a 'gt4py.next.backend.Backend', got '{type(backend).__name__}'.") def _compiled_backend_or_none( - backend: next_backend.Backend | None, + backend: next_backend.Backend, ) -> next_backend.CompiledBackend | None: """ Dispatch on the kind of `backend`. @@ -77,7 +81,7 @@ def _compiled_backend_or_none( match backend: case next_backend.CompiledBackend(): return backend - case next_backend.EmbeddedBackend() | None: + case next_backend.EmbeddedBackend(): return None case _: raise TypeError( @@ -86,9 +90,7 @@ def _compiled_backend_or_none( ) -def _not_compilable_message(backend: next_backend.Backend | None, what: str) -> str: - if backend is None: - return f"Cannot compile a {what} without backend." +def _not_compilable_message(backend: next_backend.Backend) -> str: return f"Backend '{backend.name}' is an embedded backend; embedded programs are not compiled." @@ -117,8 +119,7 @@ def embedded_program_call_context( kwargs: dict[str, Any], ) -> contextlib.AbstractContextManager: """Hook called at the beginning and end of an embedded program call.""" - backend_name = "'embedded'" if program.backend is None else program.backend.name - return metrics.metrics_source_key_setter(f"{program.__name__}<{backend_name}>") + return metrics.metrics_source_key_setter(f"{program.__name__}<{program.backend.name}>") @dataclasses.dataclass(frozen=True) @@ -136,7 +137,7 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): # backend-specific compilation is keyed separately in the backend's own # caches, and fingerprinting the whole backend object graph is both wasteful # and fragile (it may hold non-importable callables, see also test doubles). - backend: Optional[next_backend.Backend] = dataclasses.field( + backend: next_backend.Backend = dataclasses.field( metadata=utils.gt4py_metadata(fingerprint=False) ) compilation_options: options.CompilationOptions @@ -144,7 +145,7 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): @abc.abstractmethod def __gt_type__(self) -> ts.CallableType: ... - def with_backend(self, backend: next_backend.Backend | None) -> Self: + def with_backend(self, backend: next_backend.Backend) -> Self: return dataclasses.replace(self, backend=backend) def with_compilation_options( @@ -173,7 +174,7 @@ def _make_compiled_programs_pool( ) -> compiled_program.CompiledProgramsPool: compiled_backend = _compiled_backend_or_none(self.backend) if compiled_backend is None: - raise RuntimeError(_not_compilable_message(self.backend, "program")) + raise RuntimeError(_not_compilable_message(self.backend)) program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) assert isinstance(program_type, ts_ffront.ProgramType) @@ -274,7 +275,7 @@ class Program(_CompilableGTEntryPointMixin[ffront_stages.DSLProgramDef]): past_node: The node representing the program. closure_vars: Mapping of externally defined symbols to their respective values. For example, referenced global and nonlocal variables. - backend: The backend the program runs on (`None` for embedded execution). + backend: The backend the program runs on. definition: The Python function object corresponding to the PAST node. grid_type: The grid type (cartesian or unstructured) to be used. If not explicitly given it will be deduced from actually occurring dimensions. @@ -287,7 +288,7 @@ class Program(_CompilableGTEntryPointMixin[ffront_stages.DSLProgramDef]): def from_function( cls, definition: types.FunctionType, - backend: next_backend.Backend | None, + backend: next_backend.Backend, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Program: @@ -322,8 +323,6 @@ def __gt_allocator__( | core_ndarray_utils.ArrayNamespace ): _compiled_backend_or_none(self.backend) # rejects unsupported backend kinds - if self.backend is None: - raise RuntimeError(f"Program '{self}' does not have a backend set.") return self.backend.__gt_allocator__ @property @@ -546,7 +545,7 @@ def program(definition: Callable) -> Program: ... @typing.overload def program( *, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Callable[[Callable], Program]: ... @@ -555,8 +554,8 @@ def program( def program( definition: Callable | None = None, *, - # `NOTHING` -> default backend, `None` -> no backend (embedded execution) - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + # `NOTHING` -> default backend (`DEFAULT_BACKEND`, embedded execution on NumPy) + backend: next_backend.Backend | eve.NothingType = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Program | Callable[[Callable], Program]: @@ -587,7 +586,7 @@ def program_inner(definition: Callable) -> Program: program = Program.from_function( definition, backend=typing.cast( - next_backend.Backend | None, + next_backend.Backend, DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type=grid_type, @@ -624,7 +623,7 @@ class FieldOperator(_CompilableGTEntryPointMixin[ffront_stages.DSLFieldOperatorD def from_function( cls, definition: types.FunctionType, - backend: Optional[next_backend.Backend], + backend: next_backend.Backend, grid_type: Optional[common.GridType] = None, *, operator_node_cls: type[foast.OperatorNode] = foast.FieldOperator, @@ -763,7 +762,7 @@ class FieldOperatorFromFoast(FieldOperator): def __call__(self, *args: Any, **kwargs: Any) -> Any: compiled_backend = _compiled_backend_or_none(self.backend) if compiled_backend is None: - raise RuntimeError(_not_compilable_message(self.backend, "field operator")) + raise RuntimeError(_not_compilable_message(self.backend)) compiled_fo = next_backend.Toolchain(compiled_backend).compile( self.foast_stage, arguments.CompileTimeArgs.from_concrete(*args, **kwargs) ) @@ -774,7 +773,7 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any: def field_operator( definition: Callable, *, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType = eve.NOTHING, grid_type: common.GridType | None = None, ) -> FieldOperator: ... @@ -782,7 +781,7 @@ def field_operator( @typing.overload def field_operator( *, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType = eve.NOTHING, grid_type: common.GridType | None = None, ) -> Callable[[Callable], FieldOperator]: ... @@ -790,7 +789,7 @@ def field_operator( def field_operator( definition: Callable | None = None, *, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> FieldOperator | Callable[[types.FunctionType], FieldOperator]: @@ -815,7 +814,7 @@ def field_operator_inner(definition: Callable) -> FieldOperator: return FieldOperator.from_function( definition, typing.cast( - next_backend.Backend | None, + next_backend.Backend, DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type, @@ -832,7 +831,7 @@ def scan_operator( axis: common.Dimension, forward: bool = True, init: core_defs.Scalar = 0.0, - backend: next_backend.Backend | eve.NothingType | None, + backend: next_backend.Backend | eve.NothingType, grid_type: common.GridType | None, ) -> FieldOperator: ... @@ -859,7 +858,7 @@ def scan_operator( axis: common.Dimension, forward: bool = True, init: core_defs.Scalar = 0.0, - backend: next_backend.Backend | eve.NothingType | None, + backend: next_backend.Backend | eve.NothingType, grid_type: common.GridType | None, ) -> Callable[[Callable], FieldOperator]: ... @@ -870,7 +869,7 @@ def scan_operator( axis: common.Dimension, forward: bool = True, init: core_defs.Scalar = 0.0, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType = eve.NOTHING, grid_type: common.GridType | None = None, ) -> FieldOperator | Callable[[Callable], FieldOperator]: """ @@ -907,7 +906,7 @@ def scan_operator_inner(definition: Callable) -> FieldOperator: return FieldOperator.from_function( definition, typing.cast( - next_backend.Backend | None, + next_backend.Backend, DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type, diff --git a/src/gt4py/next/iterator/runtime.py b/src/gt4py/next/iterator/runtime.py index 2cf5be6528..f1d06740c7 100644 --- a/src/gt4py/next/iterator/runtime.py +++ b/src/gt4py/next/iterator/runtime.py @@ -82,11 +82,17 @@ def __call__( column_axis = column_axis or self.column_axis if backend is not None: - itir_node = self.itir(*args) - # TODO(tehrengruber): remove cirular dependency and place import at the top of the file from gt4py.next import backend as next_backend + if isinstance(backend, next_backend.EmbeddedBackend): + raise ValueError( + f"Embedded backend '{backend.name}' runs field-view programs only:" + " iterator-level embedded execution is selected with 'backend=None'." + ) + + itir_node = self.itir(*args) + if isinstance(backend, next_backend.CompiledBackend): compiled_program = next_backend.Toolchain(backend).compile( itir_node, 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 623d697a62..3b14f8d8bd 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 @@ -23,11 +23,11 @@ def test_program_gtir_regression(cartesian_case): - @gtx.field_operator(backend=None) + @gtx.field_operator(backend=gtx.embedded_numpy) def testee_op(a: cases.IField) -> cases.IField: return a - @gtx.program(backend=None) + @gtx.program(backend=gtx.embedded_numpy) def testee(a: cases.IField, out: cases.IField): testee_op(a, out=out) @@ -53,7 +53,7 @@ def test_collect_metrics(cartesian_case, metrics_level, expected_names): def testee_op(a: cases.IField, b: cases.IField) -> cases.IField: return a + b - @gtx.program(backend=None) + @gtx.program(backend=gtx.embedded_numpy) def testee(a: cases.IField, out: cases.IField): testee_op(a, a, out=out) 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 b13cabecc6..c7ad01e30f 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 @@ -7,7 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause import math -from typing import Callable, Optional +from typing import Callable import numpy as np import pytest @@ -39,7 +39,7 @@ # becomes easier. -def make_builtin_field_operator(builtin_name: str, backend: Optional[next_backend.Backend]): +def make_builtin_field_operator(builtin_name: str, backend: next_backend.Backend): # TODO(tehrengruber): creating a field operator programmatically should be # easier than what we need to do here. # construct annotation dictionary containing the input argument and return diff --git a/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py b/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py index b566623a4e..7bed4f0b7a 100644 --- a/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py +++ b/tests/next_tests/integration_tests/feature_tests/instrumentation_tests/test_hooks.py @@ -21,9 +21,9 @@ try: from gt4py.next.program_processors.runners import dace as dace_backends - BACKENDS = [None, gtx.embedded_numpy, gtfn_cpu, dace_backends.run_dace_cpu] + BACKENDS = [gtx.embedded_numpy, gtfn_cpu, dace_backends.run_dace_cpu] except ImportError: - BACKENDS = [None, gtx.embedded_numpy, gtfn_cpu] + BACKENDS = [gtx.embedded_numpy, gtfn_cpu] IDim = gtx.Dimension("IDim") @@ -125,7 +125,7 @@ def custom_compiled_program_callback( ) -@pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: getattr(b, "name", str(b))) +@pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def test_program_call_hooks(backend: gtx_typing.Backend): size = 10 a_field = gtx.full([(IDim, size)], 1, dtype=gtx.float64) @@ -161,7 +161,7 @@ def test_program_call_hooks(backend: gtx_typing.Backend): assert hook_name == "custom_program_callback" assert hook_call_info["program"] == test_program.__name__ - if backend is None or isinstance(backend, next_backend.EmbeddedBackend): + if isinstance(backend, next_backend.EmbeddedBackend): # The embedded program call hook should have also been called # with the embedded backend assert len(embedded_callback_results) == 2 @@ -208,7 +208,7 @@ def test_program_call_hooks(backend: gtx_typing.Backend): @pytest.mark.parametrize( "backend", [b for b in BACKENDS if isinstance(b, next_backend.CompiledBackend)], - ids=lambda b: getattr(b, "name", str(b)), + ids=lambda b: b.name, ) def test_compile_variant_hook(backend: gtx_typing.Backend): def custom_compile_variant_hook( diff --git a/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py b/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py index 554a337450..a18a1d8761 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py @@ -9,13 +9,13 @@ """Tests for how programs and operators dispatch on the kind of their backend.""" import dataclasses -import warnings import numpy as np import pytest import gt4py.next as gtx from gt4py.next import backend as next_backend +from gt4py.next.ffront import decorator from gt4py.next.program_processors.runners import roundtrip @@ -39,6 +39,15 @@ def _sum_def(state: float, a: float) -> float: return state + a +@gtx.field_operator +def _copy_op(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + + +def _copy_program_def(a: gtx.Field[[IDim], gtx.float64], out: gtx.Field[[IDim], gtx.float64]): + _copy_op(a, out=out) + + def _make_testees(backend): @gtx.field_operator(backend=backend) def copy(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: @@ -62,7 +71,7 @@ def test_construction_rejects_non_backends(not_a_backend): with pytest.raises(TypeError, match="Expected a 'gt4py.next.backend.Backend'"): gtx.scan_operator(axis=KDim, forward=True, init=0.0, backend=not_a_backend)(_sum_def) - copy, copy_program, _ = _make_testees(None) + copy, copy_program, _ = _make_testees(gtx.embedded_numpy) with pytest.raises(TypeError, match="Expected a 'gt4py.next.backend.Backend'"): copy.with_backend(not_a_backend) with pytest.raises(TypeError, match="Expected a 'gt4py.next.backend.Backend'"): @@ -89,18 +98,45 @@ def test_unsupported_backend_kind_raises_on_use(): gtx.zeros({IDim: 3}, allocator=copy_program) -def test_none_backend_runs_embedded(): - copy, copy_program, _ = _make_testees(None) +_NONE_MESSAGE = "'backend=None' is not supported.*'gtx.embedded_numpy'" + + +def test_none_backend_is_rejected(): + with pytest.raises(TypeError, match=_NONE_MESSAGE): + gtx.program(backend=None)(_copy_program_def) + with pytest.raises(TypeError, match=_NONE_MESSAGE): + gtx.field_operator(_copy_def, backend=None) + with pytest.raises(TypeError, match=_NONE_MESSAGE): + gtx.scan_operator(axis=KDim, forward=True, init=0.0, backend=None)(_sum_def) + with pytest.raises(TypeError, match=_NONE_MESSAGE): + decorator.Program.from_function(_copy_program_def, backend=None) + with pytest.raises(TypeError, match=_NONE_MESSAGE): + decorator.FieldOperator.from_function(_copy_def, backend=None) + + copy, copy_program, scan = _make_testees(gtx.embedded_numpy) + for testee in (copy, copy_program, scan): + with pytest.raises(TypeError, match=_NONE_MESSAGE): + testee.with_backend(None) + with pytest.raises(TypeError, match=_NONE_MESSAGE): + dataclasses.replace(testee, backend=None) + + +def test_default_backend_is_embedded_numpy(): + assert decorator.DEFAULT_BACKEND is gtx.embedded_numpy + + copy = gtx.field_operator(_copy_def) + copy_program = gtx.program(_copy_program_def) + scan = gtx.scan_operator(axis=KDim, forward=True, init=0.0)(_sum_def) + assert copy.backend is gtx.embedded_numpy + assert copy_program.backend is gtx.embedded_numpy + assert scan.backend is gtx.embedded_numpy + a = gtx.as_field([IDim], np.arange(3.0)) out = gtx.zeros({IDim: 3}) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", UserWarning) # "Using Python execution" warning + with pytest.warns(UserWarning, match="Using Python execution"): copy_program(a, out, offset_provider={}) assert np.allclose(out.asnumpy(), a.asnumpy()) - - with pytest.raises(RuntimeError, match="without backend"): - copy_program.compile(offset_provider={}) + assert gtx.zeros({IDim: 3}, allocator=copy_program).ndarray.flags["C_CONTIGUOUS"] def test_embedded_backend_runs_embedded(): diff --git a/tests/next_tests/unit_tests/ffront_tests/test_stages.py b/tests/next_tests/unit_tests/ffront_tests/test_stages.py index 3c14182655..068b056fb1 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_stages.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_stages.py @@ -183,10 +183,10 @@ def test_fingerprint_excludes_backend(): def copy(a: gtx.Field[[IDim], gtx.int32]) -> gtx.Field[[IDim], gtx.int32]: return a - without_backend = stages.fingerprinter(copy.with_backend(None)) - with_backend = stages.fingerprinter(copy.with_backend(gtx.gtfn_cpu)) - assert without_backend == with_backend + embedded = stages.fingerprinter(copy.with_backend(gtx.embedded_numpy)) + compiled = stages.fingerprinter(copy.with_backend(gtx.gtfn_cpu)) + assert embedded == compiled # A non-fingerprintable backend (here a `Mock`) must not crash fingerprinting. object.__setattr__(copy, "backend", mock.Mock()) - assert stages.fingerprinter(copy) == without_backend + assert stages.fingerprinter(copy) == embedded diff --git a/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py b/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py index bf2df06bf2..592027d2ba 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_runtime_domain.py @@ -12,7 +12,13 @@ import gt4py.next as gtx from gt4py.next import common from gt4py.next.iterator.builtins import deref -from gt4py.next.iterator.runtime import CartesianDomain, UnstructuredDomain, _deduce_domain, fundef +from gt4py.next.iterator.runtime import ( + CartesianDomain, + UnstructuredDomain, + _deduce_domain, + fendef, + fundef, +) @fundef @@ -45,3 +51,12 @@ def test_embedded_error_on_wrong_domain(): out = gtx.as_field([I], np.zeros(1)) with pytest.raises(RuntimeError, match="expected 'UnstructuredDomain'"): foo[dom](gtx.as_field([I], np.zeros((1,))), out=out, offset_provider={"bar": connectivity}) + + +def test_embedded_backend_is_rejected_by_iterator_programs(): + @fendef + def fencil(): + pass + + with pytest.raises(ValueError, match="iterator-level embedded execution.*'backend=None'"): + fencil(backend=gtx.embedded_numpy) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py index 574c64145b..991fed3c08 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py @@ -306,8 +306,15 @@ def test_is_dace_backend_recognizes_dace_backends(backend): @pytest.mark.parametrize( "backend", - [gtfn.run_gtfn, roundtrip.default, cases_utils.no_backend, None, "run_dace_cpu"], - ids=["gtfn", "roundtrip", "no_backend", "None", "name"], + [ + gtfn.run_gtfn, + roundtrip.default, + gtx.embedded_numpy, + cases_utils.no_backend, + None, + "run_dace_cpu", + ], + ids=["gtfn", "roundtrip", "embedded_numpy", "no_backend", "None", "name"], ) def test_is_dace_backend_rejects_other_objects(backend): assert not dace_wf_backend.is_dace_backend(backend) diff --git a/tests/next_tests/unit_tests/test_backend.py b/tests/next_tests/unit_tests/test_backend.py index 193d2b908f..073159cd73 100644 --- a/tests/next_tests/unit_tests/test_backend.py +++ b/tests/next_tests/unit_tests/test_backend.py @@ -216,3 +216,18 @@ def test_deepcopy_of_a_program_after_allocation(backend): assert program_copy.backend is backend assert "__gt_allocator__" not in program.__dict__ + + +def test_deepcopy_of_a_default_program(): + @gtx.field_operator + def identity(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + + @gtx.program + def copy_program(a: gtx.Field[[IDim], gtx.float64], out: gtx.Field[[IDim], gtx.float64]): + identity(a, out=out) + + assert copy_program.backend is gtx.embedded_numpy + assert copy.deepcopy(copy_program).backend is gtx.embedded_numpy + gtx.zeros({IDim: 3}, allocator=copy_program) + assert copy.deepcopy(copy_program).backend is gtx.embedded_numpy diff --git a/typing_tests/test_next.yaml b/typing_tests/test_next.yaml index 5db040f8df..0eac9652bd 100644 --- a/typing_tests/test_next.yaml +++ b/typing_tests/test_next.yaml @@ -18,7 +18,7 @@ KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) - @gtx.field_operator(grid_type=None, backend=None) + @gtx.field_operator(grid_type=None, backend=gtx.embedded_numpy) def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: return a @@ -91,7 +91,7 @@ def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: return a - @gtx.program(backend=None, grid_type=gtx.common.GridType.UNSTRUCTURED) + @gtx.program(backend=gtx.embedded_numpy, grid_type=gtx.common.GridType.UNSTRUCTURED) def foo_prg( a: gtx.Field[gtx.Dims[KDim], gtx.int32], b: gtx.Field[gtx.Dims[KDim], gtx.int32], @@ -211,9 +211,23 @@ def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: return a - def foo_with_backend(backend: gtx.typing.Backend | None) -> None: + def foo_with_backend(backend: gtx.typing.Backend) -> None: _ = foo.with_backend(backend) + - case: with_backend_none_is_rejected + main: | + from gt4py import next as gtx + + KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + + @gtx.field_operator + def foo(a: gtx.Field[gtx.Dims[KDim], gtx.int32]) -> gtx.Field[gtx.Dims[KDim], gtx.int32]: + return a + + _ = foo.with_backend(None) + out: | + main:9:22: error: Argument 1 to "with_backend" of "_CompilableGTEntryPointMixin" has incompatible type "None"; expected "Backend" [arg-type] + - case: with_backend_scanop main: | from gt4py import next as gtx @@ -227,7 +241,7 @@ ) -> float: return carry + val - def somescanop_with_backend(backend: gtx.typing.Backend | None) -> None: + def somescanop_with_backend(backend: gtx.typing.Backend) -> None: _ = somescanop.with_backend(backend) - case: with_backend_program @@ -251,7 +265,7 @@ ) -> None: foo(a, out=b, domain={KDim: (start, end)}) - def foo_prg_with_backend(backend: gtx.typing.Backend | None) -> None: + def foo_prg_with_backend(backend: gtx.typing.Backend) -> None: _ = foo_prg.with_backend(backend) - case: astype_return_type From 19cc1883f386a6891454eab957cd84b283c061c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 22:37:15 +0100 Subject: [PATCH 6/7] docs[next]: add ADR 0030 (Embedded Backends) and use gtx.embedded_numpy - New ADR 0030, listed under "Embedded Execution" in the ADR index; the plain-text "ADR 0030" mentions in ADR 0029 become links. - Workshop exercises and slides use `gtx.embedded_numpy` instead of `backend = None`. - `src/gt4py/next/AGENTS.md`: embedded execution is an `EmbeddedBackend`. --- ...d-Structure-and-Pipeline-Simplification.md | 7 +- .../ADRs/next/0030-Embedded-Backends.md | 152 ++++++++++++++++++ docs/development/ADRs/next/README.md | 1 + .../exercises/1_simple_addition.ipynb | 2 +- .../1_simple_addition_solution.ipynb | 2 +- .../exercises/2_divergence_exercise.ipynb | 2 +- .../2_divergence_exercise_solution.ipynb | 2 +- .../exercises/3_gradient_exercise.ipynb | 2 +- .../3_gradient_exercise_solution.ipynb | 2 +- .../workshop/exercises/4_curl_exercise.ipynb | 2 +- .../exercises/4_curl_exercise_solution.ipynb | 2 +- .../exercises/5_vector_laplace_exercise.ipynb | 2 +- .../5_vector_laplace_exercise_solution.ipynb | 2 +- .../workshop/exercises/6_where_domain.ipynb | 2 +- .../exercises/6_where_domain_solution.ipynb | 2 +- .../workshop/exercises/7_scan_operator.ipynb | 2 +- .../exercises/7_scan_operator_solution.ipynb | 2 +- .../8_diffusion_exercise_solution.ipynb | 2 +- docs/user/next/workshop/slides/slides_1.ipynb | 2 +- src/gt4py/next/AGENTS.md | 17 +- 20 files changed, 183 insertions(+), 26 deletions(-) create mode 100644 docs/development/ADRs/next/0030-Embedded-Backends.md diff --git a/docs/development/ADRs/next/0029-Backend-Structure-and-Pipeline-Simplification.md b/docs/development/ADRs/next/0029-Backend-Structure-and-Pipeline-Simplification.md index fc454dd8c4..c5a9113e91 100644 --- a/docs/development/ADRs/next/0029-Backend-Structure-and-Pipeline-Simplification.md +++ b/docs/development/ADRs/next/0029-Backend-Structure-and-Pipeline-Simplification.md @@ -33,7 +33,8 @@ workspace is injected by a `CompiledBackend.loader`, not a `DaCeBackend` subclas (builder and config names, and the deprecated flat-keyword `make_dace_backend`), and refines [0017 - Toolchain Configuration](0017-Toolchain-Configuration.md) (its term *toolchain* names the internal composition of the frontend with a compiled backend; its configuration decisions remain -valid). Embedded execution as `Backend` objects is decided separately, in ADR 0030 (follow-up). +valid). Embedded execution as `Backend` objects is decided separately, in +[ADR 0030](0030-Embedded-Backends.md) (follow-up). ## Context @@ -116,7 +117,7 @@ class Toolchain: # internal not a method of any `Backend`. - **Embedded execution gets its own kind**, `EmbeddedBackend(Backend)`, a sibling of `CompiledBackend` rather than a mode of it. Introducing it, together with retiring - `backend=None`, is decided in ADR 0030 and lands separately; until + `backend=None`, is decided in [ADR 0030](0030-Embedded-Backends.md) and lands separately; until then embedded execution is still `backend=None`. - **The frontend is global.** `DEFAULT_TRANSFORMS` is the only frontend; it is not a field of any `Backend`. The internal `Toolchain` composes it with a `CompiledBackend` where a compilation @@ -227,7 +228,7 @@ The decisions in this ADR land as a stack of PRs. The backend structure, loader, the `OTFCompileWorkflow` → `CompilePipeline` rename) and the removal of the opaque compile path land first (#2741); stage observability follows (#2742); the pipeline simplification lands last, together with the deferred `CompilePipeline` rename (#2743). `EmbeddedBackend` and the retirement -of `backend=None` follow separately under ADR 0030. +of `backend=None` follow separately under [ADR 0030](0030-Embedded-Backends.md). ## Consequences diff --git a/docs/development/ADRs/next/0030-Embedded-Backends.md b/docs/development/ADRs/next/0030-Embedded-Backends.md new file mode 100644 index 0000000000..3113cf1ba7 --- /dev/null +++ b/docs/development/ADRs/next/0030-Embedded-Backends.md @@ -0,0 +1,152 @@ +--- +tags: [backend, embedded, allocators] +--- + +# Embedded Backends + +- **Status**: valid +- **Authors**: Enrique González Paredes (@egparedes) +- **Created**: 2026-10-28 +- **Updated**: 2026-10-28 + +In the context of selecting embedded execution for programs and operators, facing `backend=None` +as its only representation — which has no allocator and no name, cannot tell embedded execution +apart from "not configured", and forces every consumer to special-case `None` — we decided to +represent embedded execution by `EmbeddedBackend` objects, a concrete kind of the abstract +`Backend` of [ADR 0029](0029-Backend-Structure-and-Pipeline-Simplification.md), with one instance +per array namespace (NumPy, CuPy, JAX), to make the NumPy instance the default backend, and to make +`backend=None` an error, to achieve one representation for every way a program can run and +working allocation (`allocator=program`) for embedded programs. We accept a loud break for code +that passes `backend=None`, a widened allocator-factory protocol, and a changed metrics key for +embedded calls. + +## Context + +Before this ADR, `backend=None` meant embedded execution and `DEFAULT_BACKEND` was `None`. This +has several consequences: + +- **No allocator.** Embedded execution allocates with an array namespace (NumPy, CuPy, JAX), but + `None` cannot say which. `Program.__gt_allocator__` raises for embedded programs, so + `gtx.zeros(..., allocator=program)` does not work for them, and test suites carry their own + stand-ins: gt4py's `EmbeddedDummyBackend` (name + array namespace, plus a fake attribute to look + like a compiled backend), icon4py's "testing infrastructure doesn't allow to specify embedded + backend aka `None` for cupy" note. +- **No name.** Embedded calls are reported in metrics under a hardcoded `'embedded'` label. +- **`None` is ambiguous.** It reads as "no backend configured", and every consumer special-cases + it (`backend is None` checks in the decorators, in tests, in applications). +- **Allocation by factory assumes a field-buffer allocator.** `FieldConstructor` only unwraps + `__gt_allocator__` inside its custom-layout branch, after checking for an array namespace. An + allocator factory whose `__gt_allocator__` is an array namespace would be pushed into the + `TensorBuffer` path. + +ADR 0029 made `Backend` an abstract base with `name` and `allocator`, a `CompiledBackend` kind, and +a single dispatch on the kind, anticipating an embedded kind. + +## Decision + +### `EmbeddedBackend` + +```python +@dataclasses.dataclass(frozen=True) +class EmbeddedBackend(Backend): + allocator: ArrayNamespace = numpy # validated to be an array namespace +``` + +- A sibling of `CompiledBackend`, not a configuration of it: it has no frontend, compiler or + loader. Execution is identical for every instance — embedded operators dispatch on the array + types of their arguments — so `allocator` only decides where gt4py allocates buffers for this + backend. +- Instances, in `gt4py.next.program_processors.runners.embedded`: `embedded_numpy` (also exported + as `gtx.embedded_numpy`), `embedded_cupy` and `embedded_jax`. The latter two require the optional + packages; accessing them without the package raises an `AttributeError` that names it. +- CuPy and JAX are **instances**, not subclasses. A subclass with its own execution behaviour (for + example JAX execution under `jax.jit`) is possible later and would plug into the same dispatch. + +### `backend=None` is an error; the default is `embedded_numpy` + +- `decorator.DEFAULT_BACKEND` becomes `embedded_numpy`. `@gtx.program`, `@gtx.field_operator` and + `@gtx.scan_operator` without `backend=` therefore still run embedded on NumPy. +- `backend=None` raises `TypeError` at construction — in the decorators, `from_function`, + `with_backend` and `dataclasses.replace` — with a message naming the replacement: omit `backend` + or pass an `EmbeddedBackend` such as `gtx.embedded_numpy`. There is no deprecation period, in + line with ADR 0029's no-alias policy: a `None` that silently kept working would hide the new + objects from exactly the code that should adopt them. +- Scope: this concerns the field-view decorators (`gt4py.next.ffront`). The iterator-level + `fendef(..., backend=None)` keeps meaning *iterator* embedded execution (`iterator/embedded.py`), + a different execution model used internally by the roundtrip backend and the iterator tests; an + `EmbeddedBackend` is not accepted there. +- The dispatch helper of ADR 0029 replaces its `None` case by `EmbeddedBackend`; any other + `Backend` still raises `TypeError`. + +### Allocation + +- `Backend.__gt_allocator__` moves to the base class and returns the backend's allocator (unwrapping + a factory); `CompiledBackend` keeps its narrower return type. `Program.__gt_allocator__` returns + its backend's, for every kind. +- `FieldBufferAllocatorFactoryProtocol.__gt_allocator__` may return an array namespace as well as a + field-buffer allocator. `FieldConstructor` unwraps factories *before* deciding between the + array-API path and the custom-layout path, so `gtx.zeros(..., allocator=program)` allocates with + NumPy/CuPy/JAX for an embedded program and with the backend's layout for a compiled one. + `is_field_allocator_factory_for(obj, device)` is true only when the factory yields a field-buffer + allocator for that device type. + +### Name + +Embedded calls report metrics under `f"{program}<{backend.name}>"`, the format of compiled calls, +instead of the hardcoded `'embedded'`. + +### Copying + +Backends are immutable configuration objects: `Backend.__deepcopy__` returns the backend itself, +and `Program.__gt_allocator__` is a plain property rather than a cached one. Without these, every +program using the default backend would stop being deep-copyable — the NumPy module held by +`embedded_numpy` cannot be copied (`TypeError: cannot pickle 'module' object`), and the cached +allocator would put it into the program. With them, programs can be deep-copied whatever their +backend, also after being used as `allocator=`. A copy shares the backend, including caller-owned +state such as a DaCe external workspace; copies are not isolated from each other, exactly like two +programs on the same backend. A program that already holds compiled variants still copies its +compiled-programs pool, which fails for DaCe-compiled programs; that limitation predates this ADR +and is not addressed here. Backends are not picklable (compiled backends never were, and programs +are not picklable either); this ADR does not change that. + +### Compiling an embedded program + +`.compile()` on a program or operator with an `EmbeddedBackend` raises `RuntimeError` saying that +embedded programs are not compiled (it used to say "Cannot compile a program without backend"). + +## Consequences + +- Every way to run a program is a `Backend` object with a name and an allocator; code that needs + to know the kind uses `isinstance(backend, EmbeddedBackend | CompiledBackend)` instead of + `backend is None`. +- Code passing `backend=None` (notebooks, applications, tests) fails loudly and must pass + `gtx.embedded_numpy` or omit `backend`. Code mapping "embedded" to `None` in its own + configuration (icon4py's backend table) must map it to an `EmbeddedBackend`. Code that reads + `backend.allocator.device_type` for any `Backend` must handle an array-namespace allocator. +- `gtx.zeros(..., allocator=program)` and `allocator=backend` work for embedded programs; the + test suite drops `EmbeddedDummyBackend` and uses the real instances. +- `copy.deepcopy` of programs keeps working for embedded programs and also works for compiled + ones that hold no compiled variants yet; the copy shares the backend object (and its + caller-owned state). Deep-copying a program with DaCe-compiled variants still fails, as before. +- Code that classifies backends by name (e.g. `backend.name.startswith("run_dace_")`, + `"embedded" if backend is None else backend.name`) should switch to types + (`isinstance(backend, EmbeddedBackend)`); the default backend's name is `embedded_numpy`. +- The metrics key of embedded calls changes from `prog<'embedded'>` to `prog` + (and similar for CuPy/JAX), so dashboards keyed on the old string need updating. +- Third-party allocator-factory implementations keep working; code that *consumes* + `__gt_allocator__` must accept an array namespace. + +## Alternatives considered + +- **Keep `None` as an alias of `embedded_numpy`**: rejected; it keeps the ambiguity and the special + cases alive and would silently pick NumPy for code that meant "whatever the arrays are". +- **Deprecate `None` for one release**: rejected for consistency with ADR 0029's no-alias policy; + the break is at decoration time and its message names the fix. +- **One `EmbeddedBackend` without an allocator** (allocation decided elsewhere): rejected; the + allocator is exactly what the embedded case was missing, and per-namespace instances are what + test matrices and applications already model by hand. +- **Subclasses per namespace (`NumPyBackend`, `CuPyBackend`, ...)**: rejected for now; they would + differ only in a default value. Subclasses are reserved for differences in execution behaviour. +- **Unwrap `__gt_allocator__` only for programs**: rejected; any factory can legitimately yield an + array namespace once embedded backends are factories, so the constructor must handle it + generally. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index 40f77597ed..eb84bbb20c 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) +- [0030 - Embedded Backends](0030-Embedded-Backends.md) ### Transformations diff --git a/docs/user/next/workshop/exercises/1_simple_addition.ipynb b/docs/user/next/workshop/exercises/1_simple_addition.ipynb index 7f42f2b9d8..b8b731287b 100644 --- a/docs/user/next/workshop/exercises/1_simple_addition.ipynb +++ b/docs/user/next/workshop/exercises/1_simple_addition.ipynb @@ -70,7 +70,7 @@ "metadata": {}, "outputs": [], "source": [ - "def test_addition(backend=None):\n", + "def test_addition(backend=gtx.embedded_numpy):\n", " domain = gtx.domain({I: size, J: size})\n", "\n", " a_data = np.fromfunction(lambda xx, yy: xx, domain.shape, dtype=float)\n", diff --git a/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb b/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb index dd1a30cc6b..82361f9cee 100644 --- a/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb +++ b/docs/user/next/workshop/exercises/1_simple_addition_solution.ipynb @@ -101,7 +101,7 @@ "metadata": {}, "outputs": [], "source": [ - "def test_addition(backend=None):\n", + "def test_addition(backend=gtx.embedded_numpy):\n", " domain = gtx.domain({I: size, J: size})\n", "\n", " a_data = np.fromfunction(lambda xx, yy: xx, domain.shape, dtype=float)\n", diff --git a/docs/user/next/workshop/exercises/2_divergence_exercise.ipynb b/docs/user/next/workshop/exercises/2_divergence_exercise.ipynb index b0a1980d0f..9a7fcee2b9 100644 --- a/docs/user/next/workshop/exercises/2_divergence_exercise.ipynb +++ b/docs/user/next/workshop/exercises/2_divergence_exercise.ipynb @@ -87,7 +87,7 @@ "outputs": [], "source": [ "def test_divergence():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/2_divergence_exercise_solution.ipynb b/docs/user/next/workshop/exercises/2_divergence_exercise_solution.ipynb index 573ee6a44e..5cc4cc8171 100644 --- a/docs/user/next/workshop/exercises/2_divergence_exercise_solution.ipynb +++ b/docs/user/next/workshop/exercises/2_divergence_exercise_solution.ipynb @@ -92,7 +92,7 @@ "outputs": [], "source": [ "def test_divergence():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/3_gradient_exercise.ipynb b/docs/user/next/workshop/exercises/3_gradient_exercise.ipynb index 2b422b1823..0a4ebaf5b4 100644 --- a/docs/user/next/workshop/exercises/3_gradient_exercise.ipynb +++ b/docs/user/next/workshop/exercises/3_gradient_exercise.ipynb @@ -86,7 +86,7 @@ "outputs": [], "source": [ "def test_gradient():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/3_gradient_exercise_solution.ipynb b/docs/user/next/workshop/exercises/3_gradient_exercise_solution.ipynb index 85044b989f..397ec698f4 100644 --- a/docs/user/next/workshop/exercises/3_gradient_exercise_solution.ipynb +++ b/docs/user/next/workshop/exercises/3_gradient_exercise_solution.ipynb @@ -99,7 +99,7 @@ "outputs": [], "source": [ "def test_gradient():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/4_curl_exercise.ipynb b/docs/user/next/workshop/exercises/4_curl_exercise.ipynb index dc321f1bdd..8569d867ee 100644 --- a/docs/user/next/workshop/exercises/4_curl_exercise.ipynb +++ b/docs/user/next/workshop/exercises/4_curl_exercise.ipynb @@ -108,7 +108,7 @@ "outputs": [], "source": [ "def test_curl():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/4_curl_exercise_solution.ipynb b/docs/user/next/workshop/exercises/4_curl_exercise_solution.ipynb index 251fe8239a..0393491a60 100644 --- a/docs/user/next/workshop/exercises/4_curl_exercise_solution.ipynb +++ b/docs/user/next/workshop/exercises/4_curl_exercise_solution.ipynb @@ -113,7 +113,7 @@ "outputs": [], "source": [ "def test_curl():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/5_vector_laplace_exercise.ipynb b/docs/user/next/workshop/exercises/5_vector_laplace_exercise.ipynb index 30f568de6f..f95467b11a 100644 --- a/docs/user/next/workshop/exercises/5_vector_laplace_exercise.ipynb +++ b/docs/user/next/workshop/exercises/5_vector_laplace_exercise.ipynb @@ -234,7 +234,7 @@ "outputs": [], "source": [ "def test_laplacian():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/5_vector_laplace_exercise_solution.ipynb b/docs/user/next/workshop/exercises/5_vector_laplace_exercise_solution.ipynb index eaeb8c7b02..3d56b6234a 100644 --- a/docs/user/next/workshop/exercises/5_vector_laplace_exercise_solution.ipynb +++ b/docs/user/next/workshop/exercises/5_vector_laplace_exercise_solution.ipynb @@ -255,7 +255,7 @@ "outputs": [], "source": [ "def test_laplacian():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/exercises/6_where_domain.ipynb b/docs/user/next/workshop/exercises/6_where_domain.ipynb index ff59b32436..2939acaf5f 100644 --- a/docs/user/next/workshop/exercises/6_where_domain.ipynb +++ b/docs/user/next/workshop/exercises/6_where_domain.ipynb @@ -62,7 +62,7 @@ "\n", "import gt4py.next as gtx\n", "\n", - "backend = None\n", + "backend = gtx.embedded_numpy\n", "# backend = gtfn_cpu\n", "# backend = gtfn_gpu" ] diff --git a/docs/user/next/workshop/exercises/6_where_domain_solution.ipynb b/docs/user/next/workshop/exercises/6_where_domain_solution.ipynb index 5514c1b4f7..9419357c1f 100644 --- a/docs/user/next/workshop/exercises/6_where_domain_solution.ipynb +++ b/docs/user/next/workshop/exercises/6_where_domain_solution.ipynb @@ -62,7 +62,7 @@ "\n", "import gt4py.next as gtx\n", "\n", - "backend = None\n", + "backend = gtx.embedded_numpy\n", "# backend = gtfn_cpu\n", "# backend = gtfn_gpu" ] diff --git a/docs/user/next/workshop/exercises/7_scan_operator.ipynb b/docs/user/next/workshop/exercises/7_scan_operator.ipynb index 626fd4ecd9..59bbd9e492 100644 --- a/docs/user/next/workshop/exercises/7_scan_operator.ipynb +++ b/docs/user/next/workshop/exercises/7_scan_operator.ipynb @@ -115,7 +115,7 @@ "\n", "import gt4py.next as gtx\n", "\n", - "backend = None\n", + "backend = gtx.embedded_numpy\n", "# backend = gtfn_cpu\n", "# backend = gtfn_gpu" ] diff --git a/docs/user/next/workshop/exercises/7_scan_operator_solution.ipynb b/docs/user/next/workshop/exercises/7_scan_operator_solution.ipynb index 335c26a2a2..99334a243f 100644 --- a/docs/user/next/workshop/exercises/7_scan_operator_solution.ipynb +++ b/docs/user/next/workshop/exercises/7_scan_operator_solution.ipynb @@ -115,7 +115,7 @@ "\n", "import gt4py.next as gtx\n", "\n", - "backend = None\n", + "backend = gtx.embedded_numpy\n", "# backend = gtfn_cpu\n", "# backend = gtfn_gpu" ] diff --git a/docs/user/next/workshop/exercises/8_diffusion_exercise_solution.ipynb b/docs/user/next/workshop/exercises/8_diffusion_exercise_solution.ipynb index b278cee26d..50dc098e74 100644 --- a/docs/user/next/workshop/exercises/8_diffusion_exercise_solution.ipynb +++ b/docs/user/next/workshop/exercises/8_diffusion_exercise_solution.ipynb @@ -124,7 +124,7 @@ "outputs": [], "source": [ "def test_diffusion_step():\n", - " backend = None\n", + " backend = gtx.embedded_numpy\n", " # backend = gtfn_cpu\n", " # backend = gtfn_gpu\n", "\n", diff --git a/docs/user/next/workshop/slides/slides_1.ipynb b/docs/user/next/workshop/slides/slides_1.ipynb index f1e0229d4f..8804521d49 100644 --- a/docs/user/next/workshop/slides/slides_1.ipynb +++ b/docs/user/next/workshop/slides/slides_1.ipynb @@ -40,7 +40,7 @@ "\n", "The following backends are supported:\n", "\n", - "- `None` aka _embedded_: runs the DSL code directly via the Python interpreter (experimental)\n", + "- `gtx.embedded_numpy` (the default) aka _embedded_: runs the DSL code directly via the Python interpreter (experimental)\n", "- `gtfn_cpu` and `gtfn_gpu`: transpiles the DSL to C++ code using the GridTools library\n", "- `dace`: uses the DaCe library to generate optimized code (experimental)\n", "\n", diff --git a/src/gt4py/next/AGENTS.md b/src/gt4py/next/AGENTS.md index 22fe51bfb9..8bd1fa3c2b 100644 --- a/src/gt4py/next/AGENTS.md +++ b/src/gt4py/next/AGENTS.md @@ -6,8 +6,9 @@ the repo-wide [root `AGENTS.md`](../../../AGENTS.md). `gt4py.next` is the successor to `gt4py.cartesian`, targeting both structured and unstructured grids. Field operators and programs run in one of two modes: **embedded** — executed directly in Python on `Field`s (backed by NumPy / -CuPy / JAX), with no lowering to the IR — or **compiled**, lowered through a -fixed toolchain to a backend: +CuPy / JAX), with no lowering to the IR, by an `EmbeddedBackend` (the default +is `gtx.embedded_numpy`; `backend=None` is an error) — or **compiled**, lowered +through a fixed toolchain to a `CompiledBackend`: ``` field operators / programs (ffront) @@ -32,11 +33,13 @@ field operators / programs (ffront) - `otf/` — on-the-fly compilation toolchain (workflow steps, caching, argument descriptors). - `backend.py` — `Backend` (abstract: `name`, `allocator`), its concrete - kind `CompiledBackend` (+ `compiler`, `loader`), the global frontend - (`Transforms` / `DEFAULT_TRANSFORMS`) and the internal `Toolchain` - composing the two. -- `program_processors/runners/` — the backends: `gtfn` (GridTools C++), - `dace` (DaCe SDFG), `roundtrip` / `double_roundtrip` (pure Python). + kinds `CompiledBackend` (+ `compiler`, `loader`) and `EmbeddedBackend` + (allocator = array namespace), the global frontend (`Transforms` / + `DEFAULT_TRANSFORMS`) and the internal `Toolchain` composing the frontend + with a compiled backend. +- `program_processors/runners/` — the backends: `embedded` + (`embedded_numpy` / `embedded_cupy` / `embedded_jax`), `gtfn` (GridTools + C++), `dace` (DaCe SDFG), `roundtrip` / `double_roundtrip` (pure Python). - `type_system/` — `next` type specifications and the type inference the frontend runs. - `errors/` — user-facing DSL error formatting. When raising or improving a From d507e3ba759d5c7a705de36bf0ea9609e9dc5ba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 22:53:45 +0100 Subject: [PATCH 7/7] ci[next]: exclude requires_jax from the dace test sessions The dace sessions run with `--require-optional-deps` but do not install the `jax` extra. Their selection includes the embedded JAX parameter of the backend matrix (dace tests skip non-dace backends in the test body), and that parameter now loads the real `embedded_jax` backend, which needs `jax`. Exclude the marker, as the noxfile prescribes for unmet `requires_*` markers. --- noxfile.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/noxfile.py b/noxfile.py index c8091de09e..5b47a0aaf9 100755 --- a/noxfile.py +++ b/noxfile.py @@ -94,7 +94,10 @@ "internal": {"extras": ["jax"], "markers": ["not uses_dace"]} } CodeGenDaceTestSettings = CodeGenTestSettings | { - "dace": {"extras": [], "markers": ["uses_dace"]}, + # No `jax` extra here, so exclude `requires_jax`: the only such items in the dace + # selection are the embedded JAX parameters of the backend matrix, which dace + # tests skip anyway, and which need `jax` to load the `embedded_jax` backend. + "dace": {"extras": [], "markers": ["uses_dace", "not requires_jax"]}, }