diff --git a/.cscs-ci/default.yml b/.cscs-ci/default.yml index c97a85bc82..6145017c92 100644 --- a/.cscs-ci/default.yml +++ b/.cscs-ci/default.yml @@ -103,6 +103,11 @@ test_cscs_gh200: - if: $SUBPACKAGE == 'next' && $VARIANT == 'dace' && $DETAIL == 'nomesh' variables: SLURM_TIMELIMIT: "00:15:00" + - if: $SUBPACKAGE == 'next' && $VARIANT == 'internal' && $SUBVARIANT == 'cuda13' + variables: + # 32 workers run the node out of host memory + PYTEST_XDIST_AUTO_NUM_WORKERS: 16 + SLURM_TIMELIMIT: "00:15:00" - if: $SUBPACKAGE == 'next' && $VARIANT == 'internal' && $DETAIL == 'nomesh' variables: SLURM_TIMELIMIT: "00:10:00" diff --git a/pyproject.toml b/pyproject.toml index e3bda29021..9a9c13e7a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -289,6 +289,9 @@ markers = [ 'embedded_concat_where_non_contiguous_domain: tests with concat_where on non-contiguous domains', 'uses_program_metrics: tests that require backend support for program metrics', 'uses_program_with_sliced_out_arguments: tests that use a sliced argument which is not supported for non-mutable arrays, e.g. JAX', + 'uses_scalar_in_control_flow: tests that branch in Python on a scalar argument', + 'uses_scalar_in_domain: tests that use a scalar argument as a domain bound', + 'uses_scan_carry_in_control_flow: tests that branch in Python on the carry of a scan', 'checks_specific_error: tests that rely on the backend to produce a specific error message' ] norecursedirs = ['dist', 'build', '_local/*', '.*'] diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 94f54172f4..11774edce1 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -9,9 +9,11 @@ from __future__ import annotations import dataclasses -from typing import Generic +import inspect +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any, Generic -from gt4py._core import definitions as core_defs +from gt4py._core import definitions as core_defs, ndarray_utils as core_ndarray_utils from gt4py.next import config, custom_layout_allocators as next_allocators from gt4py.next.ffront import ( foast_to_gtir, @@ -27,6 +29,10 @@ from gt4py.next.otf import arguments, artifacts, stages, toolchain, workflow +if TYPE_CHECKING: + from gt4py.next.ffront import decorator as ffront_decorator + + def jit_to_aot_args( inp: arguments.JITArgs, ) -> arguments.CompileTimeArgs: @@ -148,7 +154,10 @@ def step_order(self, inp: stages.ConcreteProgramDef) -> list[str]: class Backend(Generic[core_defs.DeviceTypeT]): name: str executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] - allocator: next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + allocator: ( + next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + | core_ndarray_utils.ArrayNamespace + ) transforms: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgramDef] def compile( @@ -170,10 +179,56 @@ def load_artifact(self, artifact: artifacts.CompilationArtifact) -> artifacts.Ex @property def __gt_allocator__( self, - ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: + ) -> ( + next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + | core_ndarray_utils.ArrayNamespace + ): return self.allocator +def _not_compiled(*args: Any, **kwargs: Any) -> Any: + raise RuntimeError("An embedded backend runs programs embedded; it does not compile them.") + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class EmbeddedBackend(Backend): + """ + Runs programs and field operators embedded, on arrays of its allocator's array namespace. + + It does not compile, and it raises for fields of another array library. Subclasses run the + embedded execution inside the tracing compiler of the library, e.g. `jax.jit`, by + overriding `wrap`. + """ + + executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] = ( + _not_compiled + ) + transforms: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgramDef] = ( + DEFAULT_TRANSFORMS + ) + + def runner(self, entry_point: ffront_decorator.GTEntryPoint) -> Callable[..., None]: + """ + `entry_point` run embedded, wrapped by `wrap`, called as the entry point is. + + Called once per entry point: the result is cached by it. + """ + from gt4py.next.program_processors.runners.experimental import embedded + + return embedded.runner(entry_point, self.wrap, self.allocator) + + def wrap( + self, entry: Callable[..., None], signature: inspect.Signature, static_params: Sequence[str] + ) -> Callable[..., None]: + """ + `entry`, the embedded execution called as `signature` describes, as the backend runs it. + + Subclasses wrap it in a tracing compiler, with the parameters `static_params` static. The + arguments are fields, connectivities, scalars and (nested) tuples of them. + """ + return entry + + @dataclasses.dataclass(frozen=True) class ToolchainConfig: """ diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index e9170f74af..11453d5138 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -76,6 +76,9 @@ def __init__( device = DEFAULT_DEVICE # Currently we use optimized CPU layout, but possibly we could also use standard numpy allocation allocator = next_allocators.device_allocators[device.device_type] + requested = allocator + if next_allocators.is_field_allocator_factory(allocator): + allocator = allocator.__gt_allocator__ if core_ndarray_utils.is_array_namespace(allocator): if aligned_index is not None: @@ -93,9 +96,7 @@ def __init__( self._array_constructor = _ArrayAPIArrayConstructor( array_ns=allocator, device=translated_device ) - elif next_allocators.is_field_allocation_tool(allocator): - if next_allocators.is_field_allocator_factory(allocator): - allocator = allocator.__gt_allocator__ + elif next_allocators.is_field_allocator(allocator): if device is not None and allocator.__gt_device_type__ != device.device_type: raise ValueError( f"Allocator {allocator} is for device type {allocator.__gt_device_type__}, but device type {device.device_type} was specified." @@ -106,7 +107,7 @@ def __init__( aligned_index=aligned_index, ) else: - raise ValueError(f"Invalid field allocator: {allocator}.") + raise ValueError(f"Invalid field allocator: {requested}.") def _construct_from_array( self, diff --git a/src/gt4py/next/custom_layout_allocators.py b/src/gt4py/next/custom_layout_allocators.py index 8451863cc3..5ae3844c77 100644 --- a/src/gt4py/next/custom_layout_allocators.py +++ b/src/gt4py/next/custom_layout_allocators.py @@ -15,6 +15,7 @@ from typing_extensions import Protocol, TypeIs import gt4py._core.definitions as core_defs +import gt4py._core.ndarray_utils as core_ndarray_utils import gt4py.next.common as common import gt4py.storage.allocators as core_allocators @@ -56,7 +57,11 @@ class FieldBufferAllocatorFactoryProtocol(Protocol[core_defs.DeviceTypeT]): @property @abc.abstractmethod - def __gt_allocator__(self) -> FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: ... + def __gt_allocator__( + self, + ) -> ( + FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] | core_ndarray_utils.ArrayNamespace + ): ... def is_field_allocator_factory(obj: Any) -> TypeIs[FieldBufferAllocatorFactoryProtocol]: @@ -66,7 +71,7 @@ def is_field_allocator_factory(obj: Any) -> TypeIs[FieldBufferAllocatorFactoryPr def is_field_allocator_factory_for( obj: Any, device: core_defs.DeviceTypeT ) -> TypeIs[FieldBufferAllocatorFactoryProtocol[core_defs.DeviceTypeT]]: - return is_field_allocator_factory(obj) and obj.__gt_allocator__.__gt_device_type__ is device + return is_field_allocator_factory(obj) and is_field_allocator_for(obj.__gt_allocator__, device) FieldBufferAllocationUtil = ( diff --git a/src/gt4py/next/embedded/__init__.py b/src/gt4py/next/embedded/__init__.py index 0fdbacd655..c9075cc89d 100644 --- a/src/gt4py/next/embedded/__init__.py +++ b/src/gt4py/next/embedded/__init__.py @@ -5,10 +5,3 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause - -# not `nd_array_field` and `array_libraries`: they import `ffront.fbuiltins`, which imports -# this package -from . import array_ops, common, context, exceptions - - -__all__ = ["array_ops", "common", "context", "exceptions"] diff --git a/src/gt4py/next/embedded/array_libraries/jax_ops.py b/src/gt4py/next/embedded/array_libraries/jax_ops.py index 7a31329e5c..4826c3f31a 100644 --- a/src/gt4py/next/embedded/array_libraries/jax_ops.py +++ b/src/gt4py/next/embedded/array_libraries/jax_ops.py @@ -9,8 +9,9 @@ """ `ArrayOps` for JAX arrays, and the embedded fields as JAX pytrees. -Everything gt4py knows about JAX tracing is in this module (ADR 0029). A -connectivity table inside a trace is a tracer, and one of two cases: +How embedded fields and connectivities behave under JAX tracing is in this module +(ADR 0029); `runners.experimental.jax_jit` runs programs under `jax.jit`. A connectivity table +inside a trace is a tracer, and one of two cases: - it stands for a concrete table, which it got as a pytree leaf, or it was restricted from such a tracer: its static values are a NumPy view of the @@ -248,3 +249,6 @@ def _unflatten_connectivity( _flatten_connectivity, _unflatten_connectivity, ) + +# e.g. the `Dimension`s of an offset provider in the arguments of `jax.jit` +jax.tree_util.register_static(common.Dimension) diff --git a/src/gt4py/next/embedded/array_libraries/torch_ops.py b/src/gt4py/next/embedded/array_libraries/torch_ops.py index f566c92c97..e700fb2cd4 100644 --- a/src/gt4py/next/embedded/array_libraries/torch_ops.py +++ b/src/gt4py/next/embedded/array_libraries/torch_ops.py @@ -9,11 +9,12 @@ """ `ArrayOps` for torch tensors, and the embedded fields as torch pytrees. -Everything gt4py knows about `torch.compile` is in this module (ADR 0029). -Dynamo does not trace embedded code: a region calls it through a -`torch.compiler.nonstrict_trace` function, which gets the fields and connectivities -as pytree nodes and runs the embedded code on the fake tensors of the trace. A -connectivity table inside the trace is one of two cases: +How embedded fields and connectivities behave under `torch.compile` is in this +module (ADR 0029); `runners.experimental.torch_compile` runs programs in a region. Dynamo does not +trace embedded code: a region calls it through a `torch.compiler.nonstrict_trace` +function, which gets the fields and connectivities as pytree nodes and runs the +embedded code on the fake tensors of the trace. A connectivity table inside the trace +is one of two cases: - it stands for a concrete table, which it got through the pytree context: its static values are a NumPy array with the values of the concrete table; diff --git a/src/gt4py/next/embedded/array_ops.py b/src/gt4py/next/embedded/array_ops.py index 4209146a05..429310354b 100644 --- a/src/gt4py/next/embedded/array_ops.py +++ b/src/gt4py/next/embedded/array_ops.py @@ -285,11 +285,11 @@ def is_0d_array(value: Any) -> bool: ) -#: What embedded accepts where it accepts a scalar: a scalar, or a 0-d array (`is_scalar_like`) -ScalarLike: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject +#: A scalar or an array; `is_scalar_like` narrows to it, since typing has no 0-d arrays +NDValue: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject -def is_scalar_like(value: Any) -> TypeIs[ScalarLike]: +def is_scalar_like(value: Any) -> TypeIs[NDValue]: """A scalar, or a 0-d array.""" return core_defs.is_scalar_type(value) or is_0d_array(value) diff --git a/src/gt4py/next/embedded/context.py b/src/gt4py/next/embedded/context.py index 8183a3292c..1b44e90453 100644 --- a/src/gt4py/next/embedded/context.py +++ b/src/gt4py/next/embedded/context.py @@ -15,7 +15,6 @@ import gt4py.eve as eve import gt4py.next.common as common -import gt4py.next.embedded as gtx_embedded import gt4py.next.errors.exceptions as exceptions @@ -80,20 +79,20 @@ def update( closure_token, offset_provider_token = None, None if closure_column_range is not eve.NOTHING: assert not isinstance(closure_column_range, eve.NothingType) - closure_token = gtx_embedded.context._closure_column_range.set(closure_column_range) + closure_token = _closure_column_range.set(closure_column_range) if offset_provider is not eve.NOTHING: assert not isinstance(offset_provider, eve.NothingType) - offset_provider_token = gtx_embedded.context._offset_provider.set(offset_provider) + offset_provider_token = _offset_provider.set(offset_provider) try: yield None finally: if closure_column_range is not eve.NOTHING: assert closure_token is not None - gtx_embedded.context._closure_column_range.reset(closure_token) + _closure_column_range.reset(closure_token) if offset_provider is not eve.NOTHING: assert offset_provider_token is not None - gtx_embedded.context._offset_provider.reset(offset_provider_token) + _offset_provider.reset(offset_provider_token) def within_valid_context() -> bool: diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index a4dc029ba8..2be6dcd62a 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -357,13 +357,16 @@ def __setitem__( " 'field.ndarray[...] = ...'." ) - ops = array_ops.of(self._ndarray) - new_buffer = ops.setitem(self._ndarray, target_slice, assigned) + new_buffer = array_ops.of(self._ndarray).setitem(self._ndarray, target_slice, assigned) if new_buffer is not self._ndarray: - object.__setattr__(self, "_ndarray", new_buffer) - # A field whose buffer info was requested is likely exported again. - if "__gt_buffer_info__" in self.__dict__: - self.__dict__["__gt_buffer_info__"] = ops.buffer_info(new_buffer) + self._set_buffer(new_buffer) + + def _set_buffer(self, new_buffer: core_defs.NDArrayObject) -> None: + """Replace the buffer by one of the same shape, for libraries whose arrays are immutable.""" + object.__setattr__(self, "_ndarray", new_buffer) + # A field whose buffer info was requested is likely exported again. + if "__gt_buffer_info__" in self.__dict__: + self.__dict__["__gt_buffer_info__"] = array_ops.of(new_buffer).buffer_info(new_buffer) __abs__ = _make_builtin("abs", "abs") diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 8bc520fd8e..05e8e7a46a 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -181,7 +181,7 @@ def _intersect_scan_args( def _is_maybe_nested_in_tuple_of_scalars( value: object, -) -> TypeIs[xtyping.MaybeNestedInTuple[array_ops.ScalarLike]]: +) -> TypeIs[xtyping.MaybeNestedInTuple[array_ops.NDValue]]: """Scalars or 0-d arrays, or (nested) tuples of them.""" return all(array_ops.is_scalar_like(v) for v in utils.flatten_nested_tuple((value,))) @@ -189,10 +189,10 @@ def _is_maybe_nested_in_tuple_of_scalars( def _tuple_assign_value( pos: Sequence[common.NamedIndex], target: xtyping.MaybeNestedInTuple[common.MutableField], - source: xtyping.MaybeNestedInTuple[array_ops.ScalarLike], + source: xtyping.MaybeNestedInTuple[array_ops.NDValue], ) -> None: @utils.tree_map - def impl(target: common.MutableField, source: array_ops.ScalarLike) -> None: + def impl(target: common.MutableField, source: array_ops.NDValue) -> None: target[pos] = source impl(target, source) @@ -200,10 +200,10 @@ def impl(target: common.MutableField, source: array_ops.ScalarLike) -> None: def _tuple_at( pos: Sequence[common.NamedIndex], - field: xtyping.MaybeNestedInTuple[common.Field | array_ops.ScalarLike], -) -> array_ops.ScalarLike | tuple[array_ops.ScalarLike | tuple, ...]: + field: xtyping.MaybeNestedInTuple[common.Field | array_ops.NDValue], +) -> array_ops.NDValue | tuple[array_ops.NDValue | tuple, ...]: @named_collections.tree_map_named_collection - def impl(field: common.Field | array_ops.ScalarLike) -> array_ops.ScalarLike: + def impl(field: common.Field | array_ops.NDValue) -> array_ops.NDValue: res = field[pos].as_scalar() if isinstance(field, common.Field) else field assert array_ops.is_scalar_like(res) return res diff --git a/src/gt4py/next/experimental/__init__.py b/src/gt4py/next/experimental/__init__.py index 6378821989..0e0ed99912 100644 --- a/src/gt4py/next/experimental/__init__.py +++ b/src/gt4py/next/experimental/__init__.py @@ -6,6 +6,9 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import importlib +from typing import Any, Final + from gt4py.next.ffront.experimental import as_offset, concat_where @@ -13,3 +16,45 @@ "as_offset", "concat_where", ] + +#: The eager embedded backends, and the array namespace each allocates with +_EAGER_BACKENDS: Final = { + "embedded_numpy": "numpy", + "embedded_cupy": "cupy", + "embedded_jax": "jax.numpy", + "embedded_torch": "torch", +} +#: The embedded jit backends, and the optional package each needs +_JIT_BACKENDS: Final = {"jax_jit": "jax", "torch_compile": "torch"} + + +# the backends are created on first access, since most of them need an optional package +def __getattr__(name: str) -> Any: + if name in _EAGER_BACKENDS: + from gt4py.next import backend as next_backend + + namespace = _EAGER_BACKENDS[name] + allocator = _import(name, namespace, namespace.partition(".")[0]) + backend = next_backend.EmbeddedBackend(name=name, allocator=allocator) + elif name in _JIT_BACKENDS: + module = _import( + name, f"gt4py.next.program_processors.runners.experimental.{name}", _JIT_BACKENDS[name] + ) + backend = getattr(module, name) + else: + raise AttributeError(f"Module '{__name__}' has no attribute '{name}'.") + globals()[name] = backend + return backend + + +def __dir__() -> list[str]: + return [*globals(), *_EAGER_BACKENDS, *_JIT_BACKENDS] + + +def _import(backend: str, module: str, package: str) -> Any: + try: + return importlib.import_module(module) + except ModuleNotFoundError as error: + if (error.name or "").partition(".")[0] != package: + raise + raise AttributeError(f"'{backend}' requires the optional '{package}' package.") from error diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 6ba80d6b22..8affea5d47 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -23,17 +23,16 @@ 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, common, custom_layout_allocators as next_allocators, - embedded as next_embedded, errors, utils, ) -from gt4py.next.embedded import operators as embedded_operators +from gt4py.next.embedded import context as embedded_context, operators as embedded_operators from gt4py.next.ffront import ( field_operator_ast as foast, foast_to_gtir, @@ -101,6 +100,18 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): ) compilation_options: options.CompilationOptions + @functools.cached_property + def _has_compiled_backend(self) -> bool: + return self.backend is not None and not isinstance( + self.backend, next_backend.EmbeddedBackend + ) + + @functools.cached_property + def _embedded_runner(self) -> Callable[..., None]: + """This entry point run by its embedded backend.""" + assert isinstance(self.backend, next_backend.EmbeddedBackend) + return self.backend.runner(typing.cast(GTEntryPoint, self)) + @abc.abstractmethod def __gt_type__(self) -> ts.CallableType: ... @@ -133,6 +144,10 @@ def _make_compiled_programs_pool( ) -> compiled_program.CompiledProgramsPool: if self.backend is None or self.backend == eve.NOTHING: raise RuntimeError("Cannot compile a program without backend.") + if not self._has_compiled_backend: + raise RuntimeError( + f"Backend '{self.backend.name}' runs programs embedded; it does not compile them." + ) program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) assert isinstance(program_type, ts_ffront.ProgramType) @@ -270,7 +285,10 @@ def __name__(self) -> str: @functools.cached_property def __gt_allocator__( self, - ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: + ) -> ( + next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] + | core_ndarray_utils.ArrayNamespace + ): if self.backend: return self.backend.__gt_allocator__ else: @@ -357,10 +375,13 @@ def __call__( kwarg_types={k: type_translation.from_value(v) for k, v in kwargs.items()}, ) - if self.backend is not None: + if self._has_compiled_backend: self._compiled_programs( *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit ) + elif isinstance(self.backend, next_backend.EmbeddedBackend): + with embedded_program_call_context(self, args, offset_provider, kwargs): + self._embedded_runner(*args, offset_provider=offset_provider, **kwargs) else: # Embedded execution. warnings.warn( @@ -370,7 +391,7 @@ def __call__( stacklevel=2, ) - with next_embedded.context.update(offset_provider=offset_provider): + with embedded_context.update(offset_provider=offset_provider): with embedded_program_call_context(self, args, offset_provider, kwargs): self.definition_stage.definition(*args, **kwargs) @@ -531,7 +552,7 @@ def __gt_closure_vars__(self) -> dict[str, Any]: return self.foast_stage.closure_vars def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> Any: - if not next_embedded.context.within_valid_context() and self.backend is not None: + if not embedded_context.within_valid_context() and self._has_compiled_backend: # non embedded execution offset_provider = {**kwargs.pop("offset_provider", {})} if "out" not in kwargs: @@ -553,9 +574,11 @@ def __call__(self, *args: Any, enable_jit: bool | None = None, **kwargs: Any) -> else enable_jit, ) else: - if not next_embedded.context.within_valid_context(): + if not embedded_context.within_valid_context(): # field_operator as program kwargs["offset_provider"] = {**kwargs.pop("offset_provider", {})} + if isinstance(self.backend, next_backend.EmbeddedBackend): + return self._embedded_runner(*args, **kwargs) attributes = ( self.definition_stage.attributes if self.definition_stage diff --git a/src/gt4py/next/ffront/type_info.py b/src/gt4py/next/ffront/type_info.py index cfe1a51abb..0959524ea3 100644 --- a/src/gt4py/next/ffront/type_info.py +++ b/src/gt4py/next/ffront/type_info.py @@ -391,13 +391,13 @@ def identity(a: IField, *, out: IField) -> None: ... return callable_type -def _signature_from_callable_in_program_context( +def signature_in_program_context( callable_type: ts.CallableType, ) -> inspect.Signature: if isinstance(callable_type, ts_ffront.ProgramType): - return _signature_from_callable_in_program_context(callable_type.definition) + return signature_in_program_context(callable_type.definition) elif isinstance(callable_type, ts_ffront.FieldOperatorType | ts_ffront.ScanOperatorType): - operator_signature = _signature_from_callable_in_program_context(callable_type.definition) + operator_signature = signature_in_program_context(callable_type.definition) params = list(operator_signature.parameters.values()) if isinstance(callable_type, ts_ffront.ScanOperatorType): params = params[1:] # Remove the carry state arg @@ -435,6 +435,4 @@ def make_args_canonicalizer( See :ref:`utils.make_args_canonicalizer`. """ - return utils.make_args_canonicalizer( - _signature_from_callable_in_program_context(callable_type), **kwargs - ) + return utils.make_args_canonicalizer(signature_in_program_context(callable_type), **kwargs) diff --git a/src/gt4py/next/program_processors/runners/experimental/__init__.py b/src/gt4py/next/program_processors/runners/experimental/__init__.py new file mode 100644 index 0000000000..91b29f7772 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/experimental/__init__.py @@ -0,0 +1,10 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + + +"""Experimental backends: embedded execution, eager or inside the tracing compiler of an array library.""" diff --git a/src/gt4py/next/program_processors/runners/experimental/embedded.py b/src/gt4py/next/program_processors/runners/experimental/embedded.py new file mode 100644 index 0000000000..efa3c9e288 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/experimental/embedded.py @@ -0,0 +1,144 @@ +# 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 + +"""The embedded execution of an entry point, as the embedded backends run it.""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any + +from gt4py._core import ndarray_utils as core_ndarray_utils +from gt4py.next import common, errors, named_collections, utils +from gt4py.next.embedded import array_ops, context as embedded_context, nd_array_field +from gt4py.next.ffront import type_info as ffront_type_info, type_specifications as ts_ffront +from gt4py.next.otf import arguments +from gt4py.next.type_system import type_info, type_specifications as ts + + +if TYPE_CHECKING: + from gt4py.next.ffront import decorator + + +def runner( + entry_point: decorator.GTEntryPoint, + wrap: Callable[[Callable[..., None], inspect.Signature, Sequence[str]], Callable[..., None]], + allocator: Any, +) -> Callable[..., None]: + """ + `entry_point` run embedded, wrapped by `wrap`, called as the entry point is. + + It raises for fields and connectivities of another array library than `allocator`, if that + is an array namespace. + """ + callable_type = entry_point.__gt_type__() + program_type = ffront_type_info.type_in_program_context(callable_type) + assert isinstance(program_type, ts_ffront.ProgramType) + is_program = isinstance(callable_type, ts_ffront.ProgramType) + + signature = ffront_type_info.signature_in_program_context(program_type) + keyword_only = [ + *([] if is_program else [_keyword_only("domain", default=None)]), + _keyword_only("offset_provider"), + ] + signature = signature.replace(parameters=[*signature.parameters.values(), *keyword_only]) + static_params = ( + *(entry_point.compilation_options.static_params or ()), + *([] if is_program else ["domain"]), + ) + if unknown := set(static_params) - signature.parameters.keys(): + raise ValueError( + f"Static parameters {sorted(unknown)} are not parameters of the entry point." + ) + expected = ( + array_ops.of(allocator.empty((0,))) + if core_ndarray_utils.is_array_namespace(allocator) + else None + ) + + # a field operator called in an embedded context runs embedded + run = entry_point.definition_stage.definition if is_program else entry_point + + def run_embedded(*args: Any, offset_provider: common.OffsetProvider, **kwargs: Any) -> None: + with embedded_context.update(offset_provider=offset_provider): + run(*args, **kwargs) + + # named collections reach `wrap` as tuples, which are pytrees in every array library + params = program_type.definition.pos_or_kw_args | program_type.definition.kw_only_args + constructors = { + name: _named_collection_constructor(type_) + for name, type_ in params.items() + if type_info.needs_value_extraction(type_) + } + + def with_named_collections(**kwargs: Any) -> None: + run_embedded( + **{name: constructors.get(name, _identity)(value) for name, value in kwargs.items()} + ) + + wrapped = wrap( + with_named_collections if constructors else run_embedded, signature, static_params + ) + + def call(*args: Any, **kwargs: Any) -> None: + if not is_program: + if "out" not in kwargs: + raise errors.MissingArgumentError(None, "out", True) + if "domain" in kwargs: + # a `Domain` can be a static argument of a tracing compiler, a `dict` cannot + kwargs["domain"] = utils.tree_map(common.domain)(kwargs["domain"]) + if constructors: + args, kwargs = ( + (), + { + name: arguments.extract(value) if name in constructors else value + for name, value in signature.bind(*args, **kwargs).arguments.items() + }, + ) + if expected is not None: + _check_array_library(expected, (args, kwargs)) + wrapped(*args, **kwargs) + + call.__wrapped__ = wrapped # type: ignore[attr-defined] + return call + + +def _check_array_library(expected: array_ops.ArrayOps, value: Any) -> None: + if isinstance(value, nd_array_field.NdArrayField): + if array_ops.of(value._ndarray) is not expected: + raise TypeError( + f"A field of '{type(value._ndarray).__module__}.{type(value._ndarray).__name__}'" + f" arrays, but the backend runs on '{expected.xp.__name__}' arrays." + ) + elif isinstance(value, tuple | list): + for element in value: + _check_array_library(expected, element) + elif isinstance(value, dict): + for element in value.values(): + _check_array_library(expected, element) + + +def _keyword_only(name: str, **kwargs: Any) -> inspect.Parameter: + return inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, **kwargs) + + +def _identity(value: Any) -> Any: + return value + + +def _named_collection_constructor(type_: ts.TypeSpec) -> Callable[[Any], Any]: + """Rebuild the named collections of a value of `type_` from the tuples of `arguments.extract`.""" + if isinstance(type_, ts.NamedCollectionType): + return named_collections.make_named_collection_constructor_from_type_spec(type_) + if isinstance(type_, ts.TupleType) and type_info.needs_value_extraction(type_): + constructors = [_named_collection_constructor(element) for element in type_.types] + return lambda values: tuple( + constructor(value) for constructor, value in zip(constructors, values, strict=True) + ) + return _identity diff --git a/src/gt4py/next/program_processors/runners/experimental/jax_jit.py b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py new file mode 100644 index 0000000000..c5c0ca6d59 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/experimental/jax_jit.py @@ -0,0 +1,117 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +Embedded execution of programs and field operators under `jax.jit`. + +Fields, connectivities and scalars are arguments of the jitted function; the +`Dimension`s of the offset provider and the parameters in `static_params` are static. +""" + +from __future__ import annotations + +import dataclasses +import inspect +from collections.abc import Callable, Sequence +from typing import Any, cast + +import jax +import jax.numpy as jnp + +from gt4py._core import ndarray_utils as core_ndarray_utils +from gt4py.next import backend as next_backend, common +from gt4py.next.embedded import nd_array_field + + +def _is_field(x: Any) -> bool: + return isinstance(x, common.Field) + + +@dataclasses.dataclass(frozen=True) +class _Alias: + """A field that was passed before, at leaf `index` of the arguments.""" + + index: int + + +jax.tree_util.register_static(_Alias) + + +def _is_field_or_alias(x: Any) -> bool: + return isinstance(x, common.Field | _Alias) + + +def _mark_aliases(tree: Any) -> Any: + leaves, treedef = jax.tree.flatten(tree, is_leaf=_is_field) + first: dict[int, int] = {} + aliased = False + for i, leaf in enumerate(leaves): + if isinstance(leaf, common.Field) and (index := first.setdefault(id(leaf), i)) != i: + leaves[i] = _Alias(index) + aliased = True + return jax.tree.unflatten(treedef, leaves) if aliased else tree + + +def _resolve_aliases(tree: Any) -> Any: + leaves, treedef = jax.tree.flatten(tree, is_leaf=_is_field_or_alias) + return jax.tree.unflatten( + treedef, [leaves[leaf.index] if isinstance(leaf, _Alias) else leaf for leaf in leaves] + ) + + +def _assignable_fields(tree: Any) -> list[nd_array_field.NdArrayField]: + return [ + leaf + for leaf in jax.tree.leaves(tree, is_leaf=_is_field) + if isinstance(leaf, nd_array_field.NdArrayField) + and not isinstance(leaf, common.Connectivity) + ] + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class JaxJitBackend(next_backend.EmbeddedBackend): + """ + Runs programs and field operators embedded, under `jax.jit`. + + JAX arrays are immutable, so an assignment to an `out` field gives it a new + buffer: the jitted function returns the new buffer of each field it assigned + to, and the caller's fields get them. A field passed more than once is one + field in the trace, so its aliases see the assignment. + """ + + def wrap( + self, + entry: Callable[..., None], + signature: inspect.Signature, + static_params: Sequence[str], + ) -> Callable[..., None]: + def traced(*args: Any, **kwargs: Any) -> list[Any]: + fields = _assignable_fields((args, kwargs)) + buffers = [field.ndarray for field in fields] + args, kwargs = _resolve_aliases((args, kwargs)) + entry(*args, **kwargs) + return [ + field.ndarray if field.ndarray is not buffer else None + for field, buffer in zip(fields, buffers, strict=True) + ] + + traced.__signature__ = signature # type: ignore[attr-defined] # for `static_argnames` + jitted = jax.jit(traced, static_argnames=tuple(static_params)) + + def run(*args: Any, **kwargs: Any) -> None: + args, kwargs = _mark_aliases((args, kwargs)) + new_buffers = jitted(*args, **kwargs) + for field, buffer in zip(_assignable_fields((args, kwargs)), new_buffers, strict=True): + if buffer is not None: + field._set_buffer(buffer) + + run.__wrapped__ = jitted # type: ignore[attr-defined] + return run + + +jax_jit = JaxJitBackend(name="jax_jit", allocator=cast(core_ndarray_utils.ArrayNamespace, jnp)) diff --git a/src/gt4py/next/program_processors/runners/experimental/torch_compile.py b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py new file mode 100644 index 0000000000..7d6eceea77 --- /dev/null +++ b/src/gt4py/next/program_processors/runners/experimental/torch_compile.py @@ -0,0 +1,123 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +Embedded execution of programs and field operators under `torch.compile`. + +The embedded code runs in a region through a `torch.compiler.nonstrict_trace` +function (see `torch_ops`). Fields, connectivities and scalars are arguments of the +region; the `Dimension`s of the offset provider and the parameters in +`static_params` are static. +""" + +from __future__ import annotations + +import contextvars +import dataclasses +import inspect +from collections.abc import Callable, Sequence +from typing import Any, cast + +import numpy as np +import torch + +from gt4py._core import ndarray_utils as core_ndarray_utils +from gt4py.next import backend as next_backend, common + + +# Dynamo reports an exception of the embedded code as an unsupported output type +_embedded_error: contextvars.ContextVar[Exception | None] = contextvars.ContextVar( + "_embedded_error", default=None +) + +_Static = tuple[tuple[str, Any], ...] + + +def _as_region_argument(value: Any) -> Any: + # Dynamo specializes on Python and NumPy scalars, which `nonstrict_trace` does not + # take either: as 0-d tensors they are traced, as by `jax.jit`, and keep their dtype + if isinstance(value, float): + return torch.tensor(value, dtype=torch.float64) + if isinstance(value, bool | int | np.generic): + return torch.as_tensor(value) + return value + + +def _region(entry: Callable[..., None], static: _Static) -> Callable[..., Any]: + @torch.compiler.nonstrict_trace + def run_embedded(kwargs: dict[str, Any], connectivities: dict[str, Any]) -> tuple[()]: + static_kwargs = dict(static) + offset_provider = {**connectivities, **dict(static_kwargs.pop("offset_provider"))} + try: + entry(**kwargs, **static_kwargs, offset_provider=offset_provider) + except Exception as error: + _embedded_error.set(error) + raise + # `nonstrict_trace` does not support a `None` output + return () + + def region(kwargs: dict[str, Any], connectivities: dict[str, Any]) -> tuple[()]: + return run_embedded(kwargs, connectivities) + + # Dynamo's recompile limit is per code object: each region needs its own + region.__code__ = region.__code__.replace() + # `dynamic=False`: see `torch_ops` + return torch.compile(region, fullgraph=True, dynamic=False) + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class TorchCompileBackend(next_backend.EmbeddedBackend): + """ + Runs programs and field operators embedded, under `torch.compile`. + + Dynamo cannot rebuild frozen dataclasses such as `Dimension` and `Domain` from a + region input, so the static arguments are closed over by one region per + combination of their values. The `out` fields are assigned to in place. + """ + + def wrap( + self, + entry: Callable[..., None], + signature: inspect.Signature, + static_params: Sequence[str], + ) -> Callable[..., None]: + static_names = frozenset(static_params) + regions: dict[_Static, Callable[..., Any]] = {} + + def run(*args: Any, **kwargs: Any) -> None: + arguments = signature.bind(*args, **kwargs).arguments + connectivities = {} + static_provider = {} + for name, value in arguments.pop("offset_provider").items(): + if isinstance(value, common.Connectivity): + connectivities[name] = value + else: + static_provider[name] = value + static = ( + ("offset_provider", tuple(sorted(static_provider.items()))), + *sorted((name, arguments.pop(name)) for name in static_names & arguments.keys()), + ) + if (region := regions.get(static)) is None: + region = regions[static] = _region(entry, static) + dynamic = torch.utils._pytree.tree_map(_as_region_argument, arguments) + token = _embedded_error.set(None) + try: + region(dynamic, connectivities) + except torch._dynamo.exc.Unsupported as unsupported: + if (error := _embedded_error.get()) is None: + raise + raise error from unsupported + finally: + _embedded_error.reset(token) + + return run + + +torch_compile = TorchCompileBackend( + name="torch_compile", allocator=cast(core_ndarray_utils.ArrayNamespace, torch) +) diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 819620f942..efd4560823 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -102,6 +102,18 @@ def __gt_allocate__( torch_cuda_execution = EmbeddedDummyBackend("EmbeddedTorchCUDA", _TorchCUDAAllocator()) +_torch_compile = _optional_module( + "gt4py.next.program_processors.runners.experimental.torch_compile" +) +torch_compile_cuda = ( + dataclasses.replace( + _torch_compile.torch_compile, name="torch_compile_cuda", allocator=_TorchCUDAAllocator() + ) + if _torch_compile is not None + else None +) + + class EmbeddedIds(_PythonObjectIdMixin, str, enum.Enum): NUMPY_EXECUTION = "next_tests.definitions.numpy_execution" CUPY_EXECUTION = "next_tests.definitions.cupy_execution" @@ -115,6 +127,9 @@ class OptionalProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): DACE_CPU = "gt4py.next.program_processors.runners.dace.run_dace_cpu" DACE_GPU = "gt4py.next.program_processors.runners.dace.run_dace_gpu" DACE_CPU_NO_OPT = "gt4py.next.program_processors.runners.dace.run_dace_cpu_noopt" + JAX_JIT = "gt4py.next.program_processors.runners.experimental.jax_jit.jax_jit" + TORCH_COMPILE = "gt4py.next.program_processors.runners.experimental.torch_compile.torch_compile" + TORCH_COMPILE_CUDA = "next_tests.definitions.torch_compile_cuda" class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): @@ -174,6 +189,9 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): EMBEDDED_CONCAT_WHERE_INFINITE_DOMAIN = "embedded_concat_where_infinite_domain" EMBEDDED_CONCAT_WHERE_NON_CONTIGUOUS_DOMAIN = "embedded_concat_where_non_contiguous_domain" USES_PROGRAM_WITH_SLICED_OUT_ARGUMENTS = "uses_program_with_sliced_out_arguments" +USES_SCALAR_IN_CONTROL_FLOW = "uses_scalar_in_control_flow" +USES_SCALAR_IN_DOMAIN = "uses_scalar_in_domain" +USES_SCAN_CARRY_IN_CONTROL_FLOW = "uses_scan_carry_in_control_flow" CHECKS_SPECIFIC_ERROR = "checks_specific_error" # Skip messages (available format keys: 'marker', 'backend') @@ -255,6 +273,16 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): JAX_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_PROGRAM_WITH_SLICED_OUT_ARGUMENTS, XFAIL, UNSUPPORTED_MESSAGE), ] +#: under a tracing compiler, scalar arguments are traced unless they are in `static_params` +TRACED_SCALARS_SKIP_LIST = [ + (USES_SCALAR_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), + (USES_SCALAR_IN_DOMAIN, XFAIL, UNSUPPORTED_MESSAGE), + (USES_SCAN_CARRY_IN_CONTROL_FLOW, XFAIL, UNSUPPORTED_MESSAGE), +] +JAX_JIT_SKIP_LIST = JAX_EMBEDDED_SKIP_LIST + TRACED_SCALARS_SKIP_LIST +TORCH_COMPILE_SKIP_LIST = EMBEDDED_SKIP_LIST + TRACED_SCALARS_SKIP_LIST +# TODO(havogt): inductor builds CPU code with `$CXX`, which is `hipcc` on the ROCm CI and fails +TORCH_COMPILE_CPU_MESSAGE = "'torch.compile' on CPU is skipped for now." ARRAY_API_STRICT_EMBEDDED_SKIP_LIST = EMBEDDED_SKIP_LIST + [ (USES_MATH_OUTSIDE_ARRAY_API, XFAIL, "Not in the Array API standard."), ] @@ -304,6 +332,9 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): OptionalProgramBackendId.DACE_CPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_GPU: DACE_SKIP_TEST_LIST, OptionalProgramBackendId.DACE_CPU_NO_OPT: DACE_SKIP_TEST_LIST, + OptionalProgramBackendId.JAX_JIT: JAX_JIT_SKIP_LIST, + OptionalProgramBackendId.TORCH_COMPILE: [(ALL, SKIP, TORCH_COMPILE_CPU_MESSAGE)], + OptionalProgramBackendId.TORCH_COMPILE_CUDA: TORCH_COMPILE_SKIP_LIST, ProgramBackendId.GTFN_CPU: GTFN_SKIP_TEST_LIST + [(USES_SCAN_NESTED, XFAIL, UNSUPPORTED_MESSAGE)], ProgramBackendId.GTFN_GPU: GTFN_SKIP_TEST_LIST diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index b5d99e2eb5..0452bbd82e 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -396,6 +396,11 @@ def allocate( ) +def runs_embedded(case: Case) -> bool: + """Whether the case's programs run embedded, i.e. are not compiled.""" + return case.backend is None or isinstance(case.backend, next_backend.EmbeddedBackend) + + def run( case: Case, fieldview_prog: decorator.FieldOperator | decorator.Program, diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index f9c1b5e98e..afdbc99619 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -114,6 +114,22 @@ def __gt_allocator__( pytest.mark.requires_gpu, ), ), + pytest.param( + next_tests.definitions.OptionalProgramBackendId.JAX_JIT, + marks=pytest.mark.requires_jax, + ), + pytest.param( + next_tests.definitions.OptionalProgramBackendId.TORCH_COMPILE, + marks=pytest.mark.requires_torch, + ), + pytest.param( + next_tests.definitions.OptionalProgramBackendId.TORCH_COMPILE_CUDA, + marks=( + pytest.mark.requires_torch, + pytest.mark.requires_torch_cuda, + pytest.mark.requires_gpu, + ), + ), pytest.param( next_tests.definitions.OptionalProgramBackendId.DACE_CPU, marks=pytest.mark.uses_dace, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py index d1ef34c76d..820bb86903 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_compiled_program.py @@ -108,7 +108,7 @@ def testee(a: cases.KField, out: cases.KField): def test_compile(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile(offset_provider=cartesian_case.offset_provider) @@ -127,7 +127,7 @@ def test_compile(cartesian_case, compile_testee): def test_precompile_and_jit_have_same_arg_descr_mapping(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") empty_static_args = {} @@ -146,7 +146,7 @@ def test_precompile_and_jit_have_same_arg_descr_mapping(cartesian_case, compile_ def test_compile_twice_same_program_errors(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") with pytest.raises(ValueError): compile_testee.compile(offset_provider=cartesian_case.offset_provider).compile( @@ -155,7 +155,7 @@ def test_compile_twice_same_program_errors(cartesian_case, compile_testee): def test_compile_kwargs(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile(offset_provider=cartesian_case.offset_provider) @@ -170,7 +170,7 @@ def test_compile_kwargs(cartesian_case, compile_testee): def test_compile_without_offset_provider(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee.compile() @@ -190,7 +190,7 @@ def test_compile_without_offset_provider(cartesian_case, compile_testee): @pytest.mark.uses_cartesian_shift def test_compile_cartesian_shift_without_offset_provider(cartesian_case): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.field_operator @@ -215,7 +215,7 @@ def testee(a: cases.IField, out: cases.IField): @pytest.mark.uses_scan def test_compile_scan(cartesian_case, compile_testee_scan): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") if isinstance(compile_testee_scan, gtx.ffront.decorator.FieldOperator): @@ -235,7 +235,7 @@ def test_compile_scan(cartesian_case, compile_testee_scan): def test_compile_domain(cartesian_case, compile_testee_domain): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee_domain.compile(offset_provider=cartesian_case.offset_provider) @@ -256,7 +256,7 @@ def test_compile_domain(cartesian_case, compile_testee_domain): @pytest.fixture def compile_testee_unstructured(unstructured_case): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.field_operator @@ -282,7 +282,7 @@ def compile_testee_unstructured_no_jit(compile_testee_unstructured): @pytest.mark.uses_unstructured_shift def test_compile_unstructured(unstructured_case, compile_testee_unstructured): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") compile_testee_unstructured.compile( @@ -330,7 +330,7 @@ def skip_value_mesh_descriptor(exec_alloc_descriptor): def test_compile_unstructured_wrong_offset_provider( unstructured_case, compile_testee_unstructured_no_jit, skip_value_mesh_descriptor ): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") # compiled for skip_value_mesh @@ -354,7 +354,7 @@ def test_compile_unstructured_wrong_offset_provider( def test_compile_unstructured_for_two_offset_providers( unstructured_case, compile_testee_unstructured_no_jit, skip_value_mesh_descriptor ): - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.skip("Embedded compiled program doesn't make sense.") # compiled for skip_value_mesh and simple_mesh @@ -403,7 +403,7 @@ def compile_variants_field_operator( def compile_variants_testee_not_compiled( cartesian_case, compile_variants_field_operator ) -> Program: - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.program(backend=cartesian_case.backend) @@ -567,7 +567,7 @@ def test_compile_variants_config_default_disable_jit(cartesian_case): """ # One of the 2 cases will be the non-default. The program has to be defined after the config # has been altered in order for the value to take effect. - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") with mock.patch.object(config, "ENABLE_JIT_DEFAULT", True): @@ -816,7 +816,7 @@ def test_compile_variants_with_static_params_jit( def test_compile_variants_decorator_static_params_jit( compile_variants_field_operator, cartesian_case ): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.program( @@ -887,7 +887,7 @@ def test_compile_variants_error_static_field(cartesian_case, compile_variants_te @pytest.fixture def compile_variants_testee_tuple(cartesian_case): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") elif ( cartesian_case.backend.name.startswith("run_dace_gpu") @@ -971,7 +971,7 @@ def test_synchronous_compilation(cartesian_case, compile_testee): @pytest.mark.parametrize("mode", list(config.BuildJobsMode), ids=lambda m: m.name.lower()) def test_wait_for_compilation(cartesian_case, compile_testee, compile_testee_domain, mode): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") with ( @@ -998,7 +998,7 @@ def test_compile_local_program_offloads_to_worker_process(cartesian_case, compil the raw definition function, which is unpicklable for local definitions. A fallback to in-thread compilation would mean the boundary leaked. """ - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") runner = compiled_program.runners.ProcessRunner( @@ -1027,7 +1027,7 @@ def test_compile_local_program_offloads_to_worker_process(cartesian_case, compil def test_wait_for_compilation_raises_on_failed_compilation(cartesian_case, compile_testee): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") # Failing only once the gate opens keeps the future pending until after @@ -1062,7 +1062,7 @@ def compile(self, program, compile_time_args): @pytest.mark.uses_tuple_args @pytest.mark.uses_tuple_returns def test_compile_variants_decorator_static_domains(cartesian_case): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") captured_cargs: Optional[arguments.CompileTimeArgs] = None @@ -1113,7 +1113,7 @@ def testee(inp: tuple[cases.IField, cases.IField, float], out: NamedTupleNamedCo @pytest.fixture def scan_operator_testee(cartesian_case): """A scan operator called directly as a FieldOperator — the only case where _is_generic=True.""" - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Embedded compiled program doesn't make sense.") @gtx.scan_operator(axis=KDim, forward=True, init=0, backend=cartesian_case.backend) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py index 0ed7ed60f0..3c7273123d 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py @@ -81,6 +81,7 @@ def testee(ground: cases.IJKField, air: cases.IJKField) -> cases.IJKField: cases.verify(cartesian_case, testee, ground, air, out=out, ref=ref) +@pytest.mark.uses_scalar_in_domain def test_concat_where_empty_branch(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee(a: cases.IJKField, b: cases.IJKField, N: np.int32) -> cases.IJKField: @@ -239,6 +240,7 @@ def testee(interior: cases.IJKField, boundary: cases.IJKField) -> cases.IJKField ) +@pytest.mark.uses_scalar_in_domain def test_dimension_two_conditions_and(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee(interior: cases.KField, boundary: cases.KField, nlev: np.int32) -> cases.KField: @@ -347,6 +349,7 @@ def testee(interior: cases.KField, boundary: cases.KField) -> cases.KField: ) +@pytest.mark.uses_scalar_in_domain def test_lap_like(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee( @@ -612,6 +615,7 @@ def testee( ) +@pytest.mark.uses_scalar_in_domain def test_nested_conditions_with_empty_branches(cartesian_case, static_domains: bool): @gtx.field_operator(static_domains=static_domains) def testee(interior: cases.IField, boundary: cases.IField, N: gtx.int32) -> cases.IField: diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py index 131dd8dd32..d23cea4d0c 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_conditionals.py @@ -24,6 +24,7 @@ ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_simple_if(condition, cartesian_case): @@ -43,6 +44,7 @@ def simple_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IField # TODO(tehrengruber): test with fields on different domains +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition1, condition2", [[True, False], [True, False]]) @pytest.mark.uses_if_stmts def test_simple_if_conditional(condition1, condition2, cartesian_case): @@ -74,6 +76,7 @@ def simple_if( ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_local_if(cartesian_case, condition): @@ -93,6 +96,7 @@ def local_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IField: cases.verify(cartesian_case, local_if, a, b, condition, out=out, ref=(a if condition else b)) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_temporary_if(cartesian_case, condition): @@ -115,6 +119,7 @@ def temporary_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IFi ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_return(cartesian_case, condition): @@ -137,6 +142,7 @@ def temporary_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IFi ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_stmt_if_branch_returns(cartesian_case, condition): @@ -156,6 +162,7 @@ def if_branch_returns(a: cases.IField, b: cases.IField, condition: bool) -> case ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_stmt_else_branch_returns(cartesian_case, condition): @@ -177,6 +184,7 @@ def else_branch_returns(a: cases.IField, b: cases.IField, condition: bool) -> ca ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_if_stmt_both_branches_return(cartesian_case, condition): @@ -198,6 +206,7 @@ def both_branches_return(a: cases.IField, b: cases.IField, condition: bool) -> c ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition1, condition2", [[True, False], [True, False]]) @pytest.mark.uses_if_stmts def test_nested_if_stmt_conditional(cartesian_case, condition1, condition2): @@ -235,6 +244,7 @@ def nested_if_conditional_return( ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition", [True, False]) @pytest.mark.uses_if_stmts def test_nested_if(cartesian_case, condition): @@ -270,6 +280,7 @@ def nested_if(a: cases.IField, b: cases.IField, condition: bool) -> cases.IField ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("condition1, condition2", [[True, False], [True, False]]) @pytest.mark.uses_if_stmts def test_if_without_else(cartesian_case, condition1, condition2): @@ -353,6 +364,7 @@ def if_inconsistent_types( return result +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("left, right", [(2, 3), (3, 2)]) def test_ternary_operator(cartesian_case, left, right): @gtx.field_operator @@ -380,6 +392,7 @@ def testee(left: int32, right: int32) -> cases.IField: ) +@pytest.mark.uses_scalar_in_control_flow @pytest.mark.parametrize("left, right", [(2, 3), (3, 2)]) @pytest.mark.uses_tuple_returns def test_ternary_operator_tuple(cartesian_case, left, right): diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py index 89f3842816..7974161504 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_decorator.py @@ -46,7 +46,7 @@ def testee(a: cases.IField, out: cases.IField): ) @pytest.mark.uses_program_metrics def test_collect_metrics(cartesian_case, metrics_level, expected_names): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): pytest.skip("Precompiled program with embedded execution is not possible.") @gtx.field_operator diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py index c49f2898aa..3021bdc04f 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_domain.py @@ -22,6 +22,7 @@ ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_scalar_in_domain_and_fo def test_scalar_in_domain_spec_and_fo_call(cartesian_case): @gtx.field_operator @@ -56,6 +57,7 @@ def testee_prog(a: cases.IKField): cases.verify(cartesian_case, testee_prog, a, inout=a[1, 3], ref=ref) +@pytest.mark.uses_scalar_in_domain def test_domain(cartesian_case): @gtx.field_operator def fieldop_domain(a: cases.IField) -> cases.IField: @@ -74,6 +76,7 @@ def program_domain(a: cases.IField, size: int32, out: cases.IField): cases.verify(cartesian_case, program_domain, a, size, out, inout=out, ref=ref) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_floordiv def test_domain_input_bounds(cartesian_case): lower_i = 1 @@ -98,6 +101,7 @@ def program_domain( cases.verify(cartesian_case, program_domain, inp, out, lower_i, upper_i, inout=out, ref=ref) +@pytest.mark.uses_scalar_in_domain def test_domain_input_bounds_1(cartesian_case): lower_i = 1 upper_i = cartesian_case.default_sizes[IDim] @@ -143,6 +147,7 @@ def program_domain( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_domain_tuple(cartesian_case): @gtx.field_operator diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py index b41f3a9c89..6c2f0e598f 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_import_from_mod.py @@ -22,6 +22,7 @@ ) +@pytest.mark.uses_scalar_in_domain def test_import_dims_module(cartesian_case): @gtx.field_operator def mod_op(f: cases.IField) -> cases.IKField: diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py index 9bd7e43273..0f89072e8f 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_math_builtin_execution.py @@ -120,7 +120,7 @@ def make_builtin_field_operator(builtin_name: str, backend: Optional[next_backen @pytest.mark.parametrize("builtin_name, inputs", math_builtin_test_data()) def test_math_function_builtins_execution(cartesian_case, builtin_name: str, inputs): - if cartesian_case.backend is None: + if cases.runs_embedded(cartesian_case): # TODO(havogt) find a way that works for embedded pytest.xfail("Test does not have a field view program.") if builtin_name == "gamma": diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index 911ace0804..77b793f93b 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -204,6 +204,7 @@ def constructed_inside_dataclass_program_with_domain( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.parametrize( "testee", [ diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py index 311b1870ed..a36dac3625 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_reductions.py @@ -335,7 +335,7 @@ def test_unstructured_shift_with_non_zero_origin(unstructured_case): # TODO(edopao,havogt): remove the xfail below once the embedded backend supports # non-contiguous field domain, which is generated by the inverse image of the # connectivity used in this test. - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.xfail("Embedded backend only supports contiguous field domains.") @gtx.field_operator @@ -420,7 +420,7 @@ def test_neighbor_sum_with_non_zero_origin(unstructured_case): # TODO(edopao,havogt): remove the xfail below once the embedded backend supports # non-contiguous field domain, which is generated by the inverse image of the # connectivity used in this test. - if unstructured_case.backend is None: + if cases.runs_embedded(unstructured_case): pytest.xfail("Embedded backend only supports contiguous field domains.") @gtx.field_operator diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py index 3e03f11a36..6d8185d764 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scalar_args.py @@ -39,6 +39,7 @@ def testee(a: int32) -> cases.VField: ) +@pytest.mark.uses_scalar_in_control_flow def test_np_bool_scalar_arg(unstructured_case): """Test scalar argument being turned into 0-dim field.""" diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py index ae9e9b37ef..7078efcff7 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py @@ -190,6 +190,7 @@ def expected(a, b, c, d): cases.verify_with_default_data(cartesian_case, solve_tridiag, ref=expected) +@pytest.mark.uses_scan_carry_in_control_flow @pytest.mark.uses_scan def test_ternary_scan(cartesian_case): @gtx.scan_operator(axis=KDim, forward=True, init=0.0) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py index 03c714421e..6cc265c433 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_where.py @@ -20,6 +20,7 @@ ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_cartesian_shift def test_where_k_offset(cartesian_case): @gtx.field_operator diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py index 7c12896fac..5437c45484 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_multiple_output_domains.py @@ -56,6 +56,7 @@ def prog_no_tuple( testee_no_tuple(a, b, out=out_a, domain={IDim: (0, i_size)}) +@pytest.mark.uses_scalar_in_domain def test_program_no_tuple(cartesian_case): a = cases.allocate(cartesian_case, prog_no_tuple, "a")() b = cases.allocate(cartesian_case, prog_no_tuple, "b")() @@ -89,6 +90,7 @@ def prog_orig( fop_original(a, b, out=(out_b, out_a), domain={IDim: (0, i_size)}) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_orig(cartesian_case): a = cases.allocate(cartesian_case, prog_orig, "a")() @@ -188,6 +190,7 @@ def prog( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program(cartesian_case): a = cases.allocate(cartesian_case, prog, "a")() @@ -258,6 +261,7 @@ def prog_out_as_tuple( fop_different_fields(a, b, out=out, domain=({JDim: (0, j_size)}, {IDim: (0, i_size)})) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_out_as_tuple( cartesian_case, @@ -302,6 +306,7 @@ def prog_out_as_tuple_different_sizes( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_out_as_tuple_different_sizes( cartesian_case, @@ -372,6 +377,7 @@ def prog_nested_tuples( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_nested_tuples( cartesian_case, @@ -440,6 +446,7 @@ def prog_double_nested_tuples( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_double_nested_tuples( cartesian_case, @@ -491,6 +498,7 @@ def prog_two_vertical_dims( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns def test_program_two_vertical_dims(cartesian_case): a = cases.allocate(cartesian_case, prog_two_vertical_dims, "a")() @@ -528,6 +536,7 @@ def prog_unstructured( fop_shift_e2c(a, out=(out_a_shifted, out_a), domain=({Cell: (0, c_size)}, {Edge: (0, e_size)})) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns @pytest.mark.uses_unstructured_shift def test_program_unstructured(unstructured_case): @@ -577,6 +586,7 @@ def prog_temporary( ) +@pytest.mark.uses_scalar_in_domain @pytest.mark.uses_tuple_returns @pytest.mark.uses_unstructured_shift def test_program_temporary(unstructured_case): diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py new file mode 100644 index 0000000000..630cf321b3 --- /dev/null +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_embedded.py @@ -0,0 +1,473 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +"""What the embedded backends add to embedded execution; the integration matrix runs the features.""" + +import dataclasses +import re + +import numpy as np +import pytest + +import gt4py.next as gtx +from gt4py.next import astype, broadcast, common, int32, neighbor_sum + +from next_tests import definitions + + +IDim = gtx.Dimension("IDim") +Vertex = gtx.Dimension("Vertex") +Edge = gtx.Dimension("Edge") +E2VDim = gtx.Dimension("E2V", kind=gtx.DimensionKind.LOCAL) +E2V = gtx.FieldOffset("E2V", source=Vertex, target=(Edge, E2VDim)) + +E2V_TABLE = np.asarray([[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]], dtype=np.int32) + + +@dataclasses.dataclass +class Pair: + first: gtx.Field[[IDim], gtx.float64] + second: gtx.Field[[IDim], gtx.float64] + + +@gtx.field_operator +def edge_sum(f: gtx.Field[[Vertex], gtx.float64]) -> gtx.Field[[Edge], gtx.float64]: + return neighbor_sum(f(E2V), axis=E2VDim) + + +@gtx.program +def edge_sum_program(f: gtx.Field[[Vertex], gtx.float64], out: gtx.Field[[Edge], gtx.float64]): + edge_sum(f, out=out) + + +@gtx.field_operator +def scale(f: gtx.Field[[IDim], gtx.float64], n: int32) -> gtx.Field[[IDim], gtx.float64]: + return astype(n, gtx.float64) * f + + +@gtx.program +def scale_bounded( + f: gtx.Field[[IDim], gtx.float64], out: gtx.Field[[IDim], gtx.float64], stop: int32 +): + scale(f, 2, out=out, domain={IDim: (0, stop)}) + + +@gtx.field_operator +def scale_if(f: gtx.Field[[IDim], gtx.float64], flag: bool) -> gtx.Field[[IDim], gtx.float64]: + if flag: + return 2.0 * f + return f + + +@gtx.field_operator +def split(f: gtx.Field[[IDim], gtx.float64]) -> Pair: + return Pair(first=f, second=2.0 * f) + + +@gtx.field_operator +def plus_one(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + 1.0 + + +@gtx.field_operator +def identity(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + + +@gtx.program +def write_then_read( + a: gtx.Field[[IDim], gtx.float64], + b: gtx.Field[[IDim], gtx.float64], + out: gtx.Field[[IDim], gtx.float64], +): + plus_one(a, out=a) + identity(b, out=out) + + +@gtx.field_operator +def infinity() -> gtx.Field[[IDim], gtx.float64]: + return broadcast(1.0 / 0.0, (IDim,)) + + +@pytest.fixture( + params=[ + pytest.param("jax", marks=pytest.mark.requires_jax), + pytest.param("torch", marks=pytest.mark.requires_torch), + ] +) +def library(request): + return request.param + + +@pytest.fixture(params=["cpu", pytest.param("gpu", marks=pytest.mark.requires_gpu)]) +def device(request, library): + if library == "jax": + import jax + + try: + return jax.devices(request.param)[0] + except RuntimeError: + pytest.skip(f"no jax '{request.param}' device") + import torch + + if request.param == "gpu" and not torch.cuda.is_available(): + pytest.skip("no torch CUDA device") + if request.param == "cpu": + pytest.skip(definitions.TORCH_COMPILE_CPU_MESSAGE) + return torch.device("cuda" if request.param == "gpu" else "cpu") + + +@pytest.fixture +def backend(library): + if library == "jax": + from gt4py.next.program_processors.runners.experimental import jax_jit + + return jax_jit.jax_jit + from gt4py.next.program_processors.runners.experimental import torch_compile + + return torch_compile.torch_compile + + +@pytest.fixture +def no_recompiles(library): + """Fail on a second trace of the same entry point.""" + if library == "jax": + yield + return + import torch + + with torch._dynamo.config.patch(recompile_limit=1, fail_on_recompile_limit_hit=True): + yield + + +def _array(device, values): + values = np.asarray(values) + if type(device).__module__.startswith("torch"): + import torch + + return torch.as_tensor(values, device=device) + import jax + + return jax.device_put(values, device) + + +def _field(device, values, dims): + values = np.asarray(values) + return common._field( + _array(device, values), + domain=common.domain({dim: size for dim, size in zip(dims, values.shape)}), + ) + + +def _e2v(device, table=E2V_TABLE): + return common._connectivity( + _array(device, table), + codomain=Vertex, + domain=common.domain({Edge: table.shape[0], E2VDim: table.shape[1]}), + ) + + +def _jitted(entry_point): + """The `jax.jit` object, under the call adapter of `embedded` and the write-back of `jax_jit`.""" + return entry_point._embedded_runner.__wrapped__.__wrapped__ + + +def test_out_assigned_in_the_callers_field(device, backend): + f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) + f_buffer = f.ndarray + out = _field(device, np.zeros(5), [Edge]) + out_object = out + + edge_sum_program.with_backend(backend)(f, out, offset_provider={"E2V": _e2v(device)}) + + assert out is out_object and f.ndarray is f_buffer + np.testing.assert_array_equal(out.asnumpy(), [3.0, 5.0, 7.0, 5.0, 4.0]) + + +@pytest.mark.requires_jax +def test_table_is_a_runtime_argument(): + import jax + + device = jax.devices("cpu")[0] + f = _field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]) + out = _field(device, np.zeros(5), [Edge]) + from gt4py.next.program_processors.runners.experimental import jax_jit + + prog = edge_sum_program.with_backend(jax_jit.jax_jit) + conn = _e2v(device) + prog(f, out, offset_provider={"E2V": conn}) + + stablehlo = _jitted(prog).lower(f, out, offset_provider={"E2V": conn}).as_text() + assert "tensor<5x2xi32>" in re.search(r"@main\(([^)]*)\)", stablehlo).group(1) + + +@pytest.mark.requires_jax +def test_retrace_per_table_buffer(): + import jax + + from gt4py.next.program_processors.runners.experimental import jax_jit + + device = jax.devices("cpu")[0] + out = _field(device, np.zeros(5), [Edge]) + prog = edge_sum_program.with_backend(jax_jit.jax_jit) + conn = _e2v(device) + + prog(_field(device, [1.0, 2.0, 3.0, 4.0], [Vertex]), out, offset_provider={"E2V": conn}) + prog(_field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), out, offset_provider={"E2V": conn}) + assert _jitted(prog)._cache_size() == 1 + + prog( + _field(device, [4.0, 3.0, 2.0, 1.0], [Vertex]), + out, + offset_provider={"E2V": _e2v(device, E2V_TABLE.copy())}, + ) + assert _jitted(prog)._cache_size() == 2 + + +def test_scalar_values_do_not_retrace(device, backend, no_recompiles): + f = _field(device, np.arange(3.0), [IDim]) + fo = scale.with_backend(backend) + for n in range(10): + out = _field(device, np.zeros(3), [IDim]) + fo(f, int32(n), out=out, offset_provider={}) + np.testing.assert_array_equal(out.asnumpy(), n * np.arange(3.0)) + + +def test_static_param_of_program(device, backend): + f = _field(device, np.arange(5.0), [IDim]) + out = _field(device, np.full(5, -1.0), [IDim]) + + scale_bounded.with_backend(backend).with_static_params("stop")(f, out, 3, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), [0.0, 2.0, 4.0, -1.0, -1.0]) + + +def test_static_param_of_field_operator(device, backend): + f = _field(device, np.arange(3.0), [IDim]) + fo = scale_if.with_backend(backend).with_compilation_options(static_params=("flag",)) + for flag, factor in ((True, 2.0), (False, 1.0)): + out = _field(device, np.zeros(3), [IDim]) + fo(f, flag, out=out, offset_provider={}) + np.testing.assert_array_equal(out.asnumpy(), factor * np.arange(3.0)) + + +def test_domain_of_field_operator_writes_into_out(device, backend): + f = _field(device, np.arange(5.0), [IDim]) + out = _field(device, np.full(5, -1.0), [IDim]) + + scale.with_backend(backend)(f, int32(3), out=out, domain={IDim: (1, 4)}, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), [-1.0, 3.0, 6.0, 9.0, -1.0]) + + +def test_dataclass_only_as_out(device, backend): + f = _field(device, np.arange(3.0), [IDim]) + out = Pair( + first=_field(device, np.zeros(3), [IDim]), second=_field(device, np.zeros(3), [IDim]) + ) + + split.with_backend(backend)(f, out=out, offset_provider={}) + + np.testing.assert_array_equal(out.first.asnumpy(), np.arange(3.0)) + np.testing.assert_array_equal(out.second.asnumpy(), 2.0 * np.arange(3.0)) + + +def test_aliases_see_the_assignment(device, backend): + a = _field(device, np.arange(3.0), [IDim]) + out = _field(device, np.zeros(3), [IDim]) + expected_a = _field(device, np.arange(3.0), [IDim]) + expected = _field(device, np.zeros(3), [IDim]) + + write_then_read.with_backend(backend)(a, a, out, offset_provider={}) + write_then_read(expected_a, expected_a, expected, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), expected.asnumpy()) + np.testing.assert_array_equal(a.asnumpy(), expected_a.asnumpy()) + np.testing.assert_array_equal(out.asnumpy(), np.arange(3.0) + 1.0) + + +def test_error_of_the_embedded_code_is_raised(device, backend): + out = _field(device, np.zeros(3), [IDim]) + + with pytest.raises(ZeroDivisionError): + infinity.with_backend(backend)(out=out, offset_provider={}) + + +def test_missing_out_is_rejected(device, backend): + with pytest.raises(gtx.errors.MissingArgumentError, match="'out'"): + scale.with_backend(backend)( + _field(device, np.arange(3.0), [IDim]), int32(1), offset_provider={} + ) + + +def test_backend_allocates_arrays_of_its_library(library, backend): + field = gtx.zeros(gtx.domain({IDim: 3}), allocator=backend) + + if library == "jax": + import jax + + assert isinstance(field.ndarray, jax.Array) + else: + import torch + + assert isinstance(field.ndarray, torch.Tensor) + + +@pytest.mark.requires_torch +@pytest.mark.requires_gpu +def test_torch_compile_allocates_on_the_given_device(): + from gt4py._core import definitions as core_defs + from gt4py.next.program_processors.runners.experimental import torch_compile + + field = gtx.zeros( + gtx.domain({IDim: 3}), + allocator=torch_compile.torch_compile, + device=core_defs.Device(core_defs.DeviceType.CUDA, 0), + ) + + assert field.ndarray.is_cuda + + +@pytest.fixture( + params=[ + "numpy", + pytest.param("cupy", marks=pytest.mark.requires_gpu), + pytest.param("jax", marks=pytest.mark.requires_jax), + pytest.param("torch", marks=pytest.mark.requires_torch), + ] +) +def eager_backend(request): + from gt4py.next import experimental + + return getattr(experimental, f"embedded_{request.param}") + + +def test_eager_backend_runs_programs(eager_backend): + domain = gtx.domain({IDim: 3}) + a = gtx.as_field(domain, np.arange(3.0), allocator=eager_backend) + b = gtx.as_field(domain, np.zeros(3), allocator=eager_backend) + out = gtx.zeros(domain, allocator=eager_backend) + + write_then_read.with_backend(eager_backend)(a, b, out, offset_provider={}) + + np.testing.assert_array_equal(a.asnumpy(), np.arange(3.0) + 1.0) + np.testing.assert_array_equal(out.asnumpy(), np.zeros(3)) + + +def test_eager_backend_runs_field_operators(eager_backend): + domain = gtx.domain({IDim: 3}) + f = gtx.as_field(domain, np.arange(3.0), allocator=eager_backend) + out = gtx.zeros(domain, allocator=eager_backend) + + plus_one.with_backend(eager_backend)(f, out=out, domain={IDim: (1, 3)}, offset_provider={}) + + np.testing.assert_array_equal(out.asnumpy(), [0.0, 2.0, 3.0]) + + +@pytest.fixture( + params=[ + pytest.param("embedded_jax", marks=pytest.mark.requires_jax), + pytest.param("embedded_torch", marks=pytest.mark.requires_torch), + pytest.param("jax_jit", marks=pytest.mark.requires_jax), + pytest.param("torch_compile", marks=pytest.mark.requires_torch), + ] +) +def non_numpy_backend(request): + from gt4py.next import experimental + + return getattr(experimental, request.param) + + +def test_fields_of_another_library_are_rejected(non_numpy_backend): + domain = gtx.domain({IDim: 3}) + f = gtx.as_field(domain, np.arange(3.0), allocator=non_numpy_backend) + numpy_out = gtx.zeros(domain, allocator=np) + + with pytest.raises(TypeError, match="numpy.ndarray"): + plus_one.with_backend(non_numpy_backend)(f, out=numpy_out, offset_provider={}) + + +def test_connectivities_of_another_library_are_rejected(non_numpy_backend): + f = gtx.as_field([Vertex], np.arange(4.0), allocator=non_numpy_backend) + out = gtx.zeros(gtx.domain({Edge: 5}), allocator=non_numpy_backend) + numpy_e2v = common._connectivity( + E2V_TABLE, codomain=Vertex, domain=common.domain({Edge: 5, E2VDim: 2}) + ) + + with pytest.raises(TypeError, match="numpy.ndarray"): + edge_sum_program.with_backend(non_numpy_backend)(f, out, offset_provider={"E2V": numpy_e2v}) + + +@gtx.field_operator +def first(p: Pair) -> gtx.Field[[IDim], gtx.float64]: + return p.first + + +def test_arguments_are_bound_as_by_the_entry_point(eager_backend): + domain = gtx.domain({IDim: 3}) + f = gtx.as_field(domain, np.arange(3.0), allocator=eager_backend) + out = gtx.zeros(domain, allocator=eager_backend) + fo = first.with_backend(eager_backend) + + with pytest.raises(TypeError): + fo(Pair(first=f, second=f), f, out=out, offset_provider={}) + with pytest.raises(TypeError): + fo(Pair(first=f, second=f), p=Pair(first=out, second=out), out=out, offset_provider={}) + + +def test_unknown_static_params_are_rejected(eager_backend): + fo = scale.with_backend(eager_backend).with_compilation_options(static_params=("m",)) + f = gtx.as_field(gtx.domain({IDim: 3}), np.arange(3.0), allocator=eager_backend) + + with pytest.raises(ValueError, match="'m'"): + fo(f, int32(1), out=f, offset_provider={}) + + +def test_exported_from_experimental(library, backend): + from gt4py.next import experimental + + assert getattr(experimental, {"jax": "jax_jit", "torch": "torch_compile"}[library]) is backend + + +def test_eager_backend_is_created_once(eager_backend): + from gt4py.next import backend as next_backend, experimental + + assert isinstance(eager_backend, next_backend.EmbeddedBackend) + assert getattr(experimental, eager_backend.name) is eager_backend + + +def test_missing_optional_package_is_reported(monkeypatch): + import sys + + from gt4py.next import experimental + + monkeypatch.delitem(vars(experimental), "embedded_cupy", raising=False) + monkeypatch.setitem(sys.modules, "cupy", None) + + with pytest.raises(AttributeError, match="optional 'cupy' package"): + experimental.embedded_cupy + + +@pytest.mark.parametrize( + "name", + [ + "embedded_numpy", + pytest.param("embedded_cupy", marks=pytest.mark.requires_gpu), + pytest.param("embedded_jax", marks=pytest.mark.requires_jax), + pytest.param("embedded_torch", marks=pytest.mark.requires_torch), + pytest.param("jax_jit", marks=pytest.mark.requires_jax), + pytest.param("torch_compile", marks=pytest.mark.requires_torch), + ], +) +def test_compile_is_rejected(name): + from gt4py.next import experimental + + with pytest.raises(RuntimeError, match="does not compile"): + edge_sum_program.with_backend(getattr(experimental, name)).compile( + offset_provider={"E2V": None} + )