From 9cf30a3824a81ba388cfe9d9bb82ea21b84d59fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Thu, 30 Jul 2026 12:49:04 +0200 Subject: [PATCH 01/10] refactor[next]: rename Backend to Toolchain and restructure artifact loading Adopt the vocabulary ADR 0017 already defines: the root object that carries a program from DSL source to a runnable callable is the *toolchain*, not the *backend* (which is one of its two halves). Renamed: - `next.backend.Backend` -> `next.backend.Toolchain` - `Toolchain.transforms` -> `Toolchain.frontend` - `Toolchain.executor` -> `Toolchain.backend` - `otf.workflow.ConcreteArtifact` -> `otf.workflow.ProgramWithArgs` - `ProgramWithArgs.data` -> `ProgramWithArgs.definition` - `otf.stages.CompilableProgramDef` -> `otf.stages.CompilableProgram` - `gtx.typing.Backend` -> `gtx.typing.Toolchain` - `ffront.foast_to_past.ItirShim.definition` -> `ItirShim.operator_def`, freeing the name for the renamed `ProgramWithArgs` field it now wraps Beyond the renames, this restructures how artifacts are loaded. `Backend.load_artifact()` was an overridable method, so a toolchain needing backend-specific runtime data in the loaded program subclassed the root object (ADR 0027's dace external-workspace path did exactly that). It becomes `Toolchain.loading`, a plain step field defaulting to `artifacts.load_artifact`, so customization is composition-time like the other three fields. The `DaCeBackend` subclass is therefore deleted and `run_dace_*` are plain `Toolchain` instances carrying a `DaCeLoadingStep`; the public path to the workspace moves from `backend.external_workspace` to `backend.loading.external_workspace`. This also keeps subclassing off the load path, which matters because per ADR 0024 a toolchain that customizes `compile` is opaque to the process-pool runner. These are hard renames: no deprecation aliases are kept, so downstream has to move in this release rather than drift on a compatibility layer. An alias would have been partial anyway -- constructing with the old keyword names cannot be aliased on a dataclass without hand-writing `__init__` -- and a half-working compatibility layer is harder to act on than one loud break. Also resolves the `TODO(tehrengruber)` in `backend.py` asking for exactly this rename, and records the decision in a new ADR 0029, which partially supersedes ADR 0011 and refines ADR 0017. Programs compile and run exactly as before. Fingerprints embed qualified class and field names, so the `ProgramWithArgs` rename rotates the two persistent translation-cache keys (gtfn, dace); this is the second such rotation in the stack, after the module move that created `otf.workflow.ConcreteArtifact`. Each is a cold rebuild rather than a stale hit because the key itself changes -- entries written under the old name are simply never looked up. On top of that, `BUILD_CACHE_VERSION_ID` (the gt4py version) already rotates these keys at every release, so the cost is nothing extra for anyone crossing a release boundary. The two rotations collapse into one if the stack lands in a single release. --- .../ADRs/next/0011-On_The_Fly_Compilation.md | 2 + .../ADRs/next/0017-Toolchain-Configuration.md | 2 + .../next/0027-External_Workspace_Memory.md | 2 + ...hain-Naming-and-Pipeline-Simplification.md | 176 ++++++++++++++++++ docs/development/ADRs/next/README.md | 1 + docs/user/next/advanced/HackTheToolchain.md | 4 +- docs/user/next/advanced/WorkflowPatterns.md | 2 +- src/gt4py/next/AGENTS.md | 3 + src/gt4py/next/backend.py | 48 ++--- src/gt4py/next/config.py | 4 +- src/gt4py/next/ffront/decorator.py | 67 +++---- src/gt4py/next/ffront/foast_to_past.py | 51 ++--- src/gt4py/next/ffront/past_process_args.py | 6 +- src/gt4py/next/ffront/past_to_itir.py | 20 +- src/gt4py/next/ffront/stages.py | 8 +- src/gt4py/next/iterator/runtime.py | 8 +- src/gt4py/next/otf/artifacts.py | 19 +- src/gt4py/next/otf/compilation_tasks.py | 16 +- src/gt4py/next/otf/compiled_program.py | 6 +- src/gt4py/next/otf/recipes.py | 2 +- src/gt4py/next/otf/stages.py | 6 +- src/gt4py/next/otf/toolchain.py | 22 +-- src/gt4py/next/otf/workflow.py | 4 +- .../codegens/gtfn/gtfn_module.py | 8 +- .../runners/dace/program.py | 12 +- .../runners/dace/workflow/backend.py | 27 +-- .../runners/dace/workflow/translation.py | 8 +- .../runners/double_roundtrip.py | 6 +- .../next/program_processors/runners/gtfn.py | 8 +- .../program_processors/runners/roundtrip.py | 34 ++-- src/gt4py/next/typing.py | 7 +- .../benchmarks/benchmark_program_call.py | 10 +- tests/next_tests/definitions.py | 2 +- tests/next_tests/integration_tests/cases.py | 10 +- .../integration_tests/cases_utils.py | 6 +- ..._write_back_buffer_elimination_lowering.py | 6 +- .../test_math_builtin_execution.py | 2 +- .../instrumentation_tests/test_hooks.py | 6 +- .../ffront_tests/test_ffront_fvm_nabla.py | 4 +- .../iterator_tests/test_vertical_advection.py | 2 +- tests/next_tests/unit_tests/conftest.py | 2 +- .../otf_tests/test_compiled_program.py | 18 +- .../unit_tests/otf_tests/test_runners.py | 20 +- .../gtfn_tests/test_gtfn_module.py | 14 +- .../dace_tests/test_dace_backend.py | 48 ++--- .../dace_tests/test_dace_translation.py | 6 +- .../runners_tests/test_gtfn.py | 34 ++-- typing_tests/test_next.yaml | 6 +- 48 files changed, 502 insertions(+), 283 deletions(-) create mode 100644 docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md diff --git a/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md b/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md index 3050b1b450..7cde4775f7 100644 --- a/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md +++ b/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md @@ -14,6 +14,8 @@ This supersedes [0009 - Compiled Backend Integration](0009-Compiled-Backend-Inte > [!NOTE] > The stage and step names introduced below have since been renamed and redistributed over two modules: `ProgramCall` is now `otf.stages.CompilableProgramDef`; `ProgramSource`, `CompilableSource` and `CompiledProgram` are now `otf.artifacts.ProgramSource`, `otf.artifacts.ExtensionSource` and `otf.artifacts.CompilationArtifact` (whose `load()` returns an `otf.artifacts.ExecutableProgram`); and `otf.step_types` was merged into `otf.stages`, where `BindingStep` no longer exists. The architecture described here — composable, statically typed workflows — is unchanged. +Partially superseded by [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) (workflow combinators and step-type naming). + ## Context The on-the-fly compilation (OTFC) in gt4py encompasses everything necessary to go from an IR representation of a GT4Py program to an executable Python function. Depending on the chosen route, this may include: diff --git a/docs/development/ADRs/next/0017-Toolchain-Configuration.md b/docs/development/ADRs/next/0017-Toolchain-Configuration.md index 4fc17fcb4e..367f69ad88 100644 --- a/docs/development/ADRs/next/0017-Toolchain-Configuration.md +++ b/docs/development/ADRs/next/0017-Toolchain-Configuration.md @@ -11,6 +11,8 @@ tags: [backend, otf, workflows, toolchain] In order to provide a streamlined user experience, we attempt to standardize how users of GT4Py stencils can configure how those stencils are optimized without editing GT4Py code. This describes the design of the first minimal implementation. +Refined by [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) (the term *toolchain* becomes the name of the root object). + ## Context In this document the word toolchain is used to mean all the code components that work together to go from DSL code to an optimized, runnable python callable. diff --git a/docs/development/ADRs/next/0027-External_Workspace_Memory.md b/docs/development/ADRs/next/0027-External_Workspace_Memory.md index c2d90458ed..7807acb7bf 100644 --- a/docs/development/ADRs/next/0027-External_Workspace_Memory.md +++ b/docs/development/ADRs/next/0027-External_Workspace_Memory.md @@ -9,6 +9,8 @@ tags: [] - **Created**: 2026-07-27 - **Updated**: 2026-08-03 +Partially superseded by [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) (the workspace is carried by an explicit `Toolchain.loading` step instead of a `DaCeBackend` subclass overriding `Backend.load_artifact`; the decision to inject the workspace at load time is unchanged). + In the context of `gt4py.next` DaCe backends that run the same compiled SDFG many times (e.g. inside a time loop), facing per-call GPU transient allocation overhead and the desire to bound workspace memory to one SDFG's transient diff --git a/docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md b/docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md new file mode 100644 index 0000000000..937d94e295 --- /dev/null +++ b/docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md @@ -0,0 +1,176 @@ +--- +tags: [backend, otf, toolchain, workflows, naming, observability] +--- + +# Toolchain Naming and Pipeline Simplification + +- **Status**: valid +- **Authors**: Enrique González Paredes (@egparedes) +- **Created**: 2026-07-30 +- **Updated**: 2026-07-30 + +In the context of the on-the-fly compilation toolchain, facing a root object +whose names (`Backend`, `transforms`, `executor`) no longer match the +established *toolchain* vocabulary and a workflow-combinator framework whose +reading cost exceeds its value, we decided to rename the root object to +`Toolchain` (with `frontend` / `backend` halves), rename the envelope and +stage types accordingly, replace the combinator tower with explicit, fully +typed pipelines, and add a sanctioned stage-observability seam. We considered +keeping the combinators and trimming only the dead ones, and accept that the +renames break the old names outright, rotate the persistent translation-cache +keys (the second such rotation in this stack), and impose a migration burden +on downstream code that subclassed the combinators. + +This partially supersedes [0011 - On The Fly Compilation](0011-On_The_Fly_Compilation.md) +(the workflow-combinator framework and the `otf.step_types` naming — its stage +vocabulary and build-system decisions remain valid) and refines +[0017 - Toolchain Configuration](0017-Toolchain-Configuration.md) (whose term +*toolchain* becomes the name of the root object; its configuration decisions +remain valid). + +This builds on [0028 - Plain Builders Instead of factory-boy Factories](0028-Plain-Builders-Instead-of-Factories.md), +which replaced the factory classes that constructed these objects, so the +renames below land in plain, type-checked builder code. + +## Context + +ADR 0017 already defines **toolchain** as "all the code components that work +together to go from DSL code to an optimized, runnable python callable" — +JIT/OTF pipelines, transformation passes, lowerings, parsers. The code grew +into exactly that shape while keeping older names: the root object is called +`Backend`, its frontend half `transforms`, its backend half `executor`, and +the pipeline pieces are spread over five vaguely-named modules (`workflow`, +`toolchain`, `definitions`, `stages`, `recipes`). + +Separately, the workflow-combinator framework introduced by ADR 0011 had grown +to thirteen abstractions (`Workflow`, two mixins, `NamedStepSequence`, +`MultiWorkflow`, `StepSequence`, `CachedStep`, `SkippableStep`, `make_step`, +the `ConcreteArtifact` envelope and three adapters) to express function +composition (some of them already deleted as dead code in the preparatory +cleanup PRs). Measured against actual use, only `CachedStep` is a deep module; +the others are shallow wrappers around `Callable[[S], T]`, and the +`NamedStepSequence.__call__` reflection loop is `Any`-typed, defeating the +static typing ADR 0011 prized. + +Finally, the seam between the toolchain and its consumers has no sanctioned +interface for observing or running intermediate stages: the one consumer that +needs an intermediate stage (the dace `__sdfg__` path) duck-types into the +default pipeline and mutates its stages. + +## Decision + +### Naming + +| Old | New | +| ---------------------------- | --------------------------------- | +| `Backend` | `Toolchain` | +| `Backend.transforms` | `Toolchain.frontend` | +| `Backend.executor` | `Toolchain.backend` | +| `Backend.load_artifact()` | `Toolchain.loading` | +| `OTFCompileWorkflow` | `CompilePipeline` | +| `ConcreteArtifact` / `.data` | `ProgramWithArgs` / `.definition` | +| `CompilableProgramDef` | `CompilableProgram` | + +These are hard renames: no deprecation aliases are kept, so the old names stop +resolving in the same release. The public `gtx.*` names (`gtx.gtfn_cpu`, +`gtx.wait_for_compilation`, ...) are unchanged, with one exception — +`gtx.typing.Backend` becomes `gtx.typing.Toolchain`. + +We considered shipping one-release read aliases for the renamed attributes and +re-export shims for the moved modules. We rejected that: an alias that silently +keeps working is exactly what lets a downstream stay on the old vocabulary past +the release where it was supposed to migrate, and the aliases would have been +partial anyway (constructing with the old keyword names could not be aliased +without hand-writing `__init__`, so `Backend(executor=...)` would have raised +`TypeError` regardless). A single loud break at a known release is easier to +act on than a half-working compatibility layer. `CompilableProgram` stays a type +alias (of the parameterized envelope) for now. + +The last row is not a pure rename. `Backend.load_artifact()` was an overridable +method, and a toolchain that needed backend-specific runtime data in the loaded +program subclassed `Toolchain` to override it (see +[0027 - External Workspace Memory for DaCe Transients](0027-External_Workspace_Memory.md)). +`Toolchain.loading` makes that seam a field like the other three — a plain step +defaulting to `artifacts.load_artifact` — so customization stays +composition-time, consistent with the rest of this ADR. It also keeps +subclassing off the load path: per +[0024 - Compilation Runners](0024-Compilation-Runners.md), a toolchain that +customizes `compile` is opaque to the process-pool runner, and a +customization mechanism built on subclassing invites exactly that. The step +lives on `Toolchain` rather than inside `CompilePipeline` because loading also +happens off the pipeline — `CompiledProgramsPool` loads artifacts straight from +a compilation future — and because monolithic backends have no `CompilePipeline` +to hang it on. + +### Pipeline, not combinators + +Named pipelines become frozen dataclasses with an explicit, fully typed +`__call__`; steps are plain callables (`Step[S, T] = Callable[[S], T]`); +customization stays composition-time via `dataclasses.replace`. The +combinator framework (both mixins, `NamedStepSequence`, `MultiWorkflow`, +`StepSequence`, `make_step`, `.chain`, the three adapters) is deleted; +`CachedStep` is kept unchanged. + +What ADR 0011's decisions become: + +| ADR 0011 requirement | Kept by | +| ------------------------------------------- | ----------------------------------------------------------------------- | +| Named steps, order visible | dataclass fields + explicit `__call__` (order literally visible) | +| Statically typed composition | explicit `__call__` — checked end-to-end, unlike the reflection loop | +| Customization at composition, not via flags | `dataclasses.replace` on frozen pipelines | +| Steps compose across backends | `Step[S, T]` is a `Callable` — every existing step already satisfies it | +| Linear workflows | unchanged (`Transforms` keeps its input-dependent step *selection*) | + +### Stage observability + +A `stage_hook(name, artifact)` event hook (on the existing +`instrumentation.hook_machinery`) is emitted by `CompilePipeline` and +`Transforms` after each step; artifacts are treated opaquely. +`GT4PY_DUMP_STAGES=` registers a subscriber that writes each stage +artifact per program. `Toolchain.translate(definition, compile_time_args)` is +the sanctioned partial run (frontend + translation only); it narrows to the +standard `CompilePipeline` shape and raises a clear error on monolithic +backends. Per-call step options are deliberately not offered — a caller +needing a variant step builds a variant pipeline with `dataclasses.replace`. + +### Phasing + +The decisions in this ADR land as a stack of PRs. The naming decisions above +land first, except the `OTFCompileWorkflow` → `CompilePipeline` rename, which +lands with the pipeline PR; the "Pipeline, not combinators" and "Stage +observability" decisions are implemented in follow-up PRs of the same stack. + +## Consequences + +- The dace `__sdfg__` reach-in (duck-typing through `executor.translation` + and mutating frozen stages) will be replaced by a dace-owned translate-only + step built with `dataclasses.replace`. +- Downstream code subclassing the deleted combinators or overriding + `Transforms.step_order` must migrate to explicit `__call__` composition. +- Downstream code must migrate to the new names in the same release: the old + ones are removed, not aliased. That includes the modules dissolved along the + way — `otf.definitions`, `otf.code_specs`, `otf.recipes` and `otf.toolchain` + cease to exist, and `gtx.typing.Backend` becomes `gtx.typing.Toolchain`. +- ADR 0011's `otf.step_types` naming section no longer describes the code. +- Cache keys rotate: fingerprints embed the qualified class and field names, + so the `ProgramWithArgs` / `definition` rename changes the keys of the + persistent translation caches (gtfn and dace). This is the *second* of two + rotations in this stack — moving the same class from `otf.toolchain` to + `otf.workflow` already rotated them once, since the qualified name alone + is enough. What makes each a cold rebuild rather than a stale hit is that + the key itself changes, so entries written under the old name are never + looked up; `BUILD_CACHE_VERSION_ID` (the gt4py version) is a separate salt + on top, which means the rotation costs nothing extra to anyone who crosses + a release — or, for a source install, any commit — boundary anyway. The two + collapse into a single cold rebuild if the whole stack lands in one + release, which is the concrete argument for not spreading it across + releases. + +## Alternatives considered + +- **Keep the combinators but trim dead ones**: rejected — the tower is a + shallow-module archetype and every recorded ADR 0011 requirement survives + its removal; trimming keeps the reading cost and the `Any`-typed + composition. +- **A per-call options API on `translate()`**: rejected — reconfiguration + stays composition-time, ADR 0011's own rule. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index f19167ef9b..29fe79fac5 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -53,6 +53,7 @@ Writing a new ADR is simple: - [0017 - Toolchain Configuration](0017-Toolchain-Configuration.md) - [0027 - External Workspace Memory for DaCe Transients](0027-External_Workspace_Memory.md) - [0028 - Plain Builders Instead of factory-boy Factories](0028-Plain-Builders-Instead-of-Factories.md) +- [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) ### Python Integration diff --git a/docs/user/next/advanced/HackTheToolchain.md b/docs/user/next/advanced/HackTheToolchain.md index 773070130b..e87396da9f 100644 --- a/docs/user/next/advanced/HackTheToolchain.md +++ b/docs/user/next/advanced/HackTheToolchain.md @@ -22,8 +22,8 @@ cached_lowering_toolchain = gtx.backend.DEFAULT_TRANSFORMS.replace( ## Skip Steps / Change Order ```python -DUMMY_FOP = workflow.ConcreteArtifact( - data=ff_stages.DSLFieldOperatorDef(definition=None), args=None +DUMMY_FOP = workflow.ProgramWithArgs( + definition=ff_stages.DSLFieldOperatorDef(definition=None), args=None ) ``` diff --git a/docs/user/next/advanced/WorkflowPatterns.md b/docs/user/next/advanced/WorkflowPatterns.md index b8ce74a9be..d2556b2bc0 100644 --- a/docs/user/next/advanced/WorkflowPatterns.md +++ b/docs/user/next/advanced/WorkflowPatterns.md @@ -399,7 +399,7 @@ gtx.backend.DEFAULT_PROG_TRANSFORMS?? ``` ```python -gtx.program_processors.runners.gtfn.run_gtfn_gpu.executor.otf_workflow?? +gtx.program_processors.runners.gtfn.run_gtfn_gpu.backend?? ``` ```python diff --git a/src/gt4py/next/AGENTS.md b/src/gt4py/next/AGENTS.md index f0a2bfc342..ea94beaf17 100644 --- a/src/gt4py/next/AGENTS.md +++ b/src/gt4py/next/AGENTS.md @@ -31,6 +31,9 @@ field operators / programs (ffront) Distinct from `iterator/embedded.py`, which runs one level lower. - `otf/` — on-the-fly compilation toolchain (workflow steps, caching, argument descriptors). +- `backend.py` — the toolchain root object `Toolchain` (formerly `Backend`): + `frontend` (definition transforms) + `backend` (compile pipeline) + + allocator. - `program_processors/runners/` — the backends: `gtfn` (GridTools C++), `dace` (DaCe SDFG), `roundtrip` / `double_roundtrip` (pure Python). - `type_system/` — `next` type specifications and the type inference the diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 94f54172f4..fb649bf28f 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -9,7 +9,7 @@ from __future__ import annotations import dataclasses -from typing import Generic +from typing import Callable, Generic from gt4py._core import definitions as core_defs from gt4py.next import config, custom_layout_allocators as next_allocators @@ -45,7 +45,7 @@ def adapted_jit_to_aot_args_factory() -> workflow.Workflow[ class Transforms( workflow.MultiWorkflow[ stages.ConcreteProgramDef[stages.IRDefinitionT, stages.ArgsDefinitionT], - stages.CompilableProgramDef, + stages.CompilableProgram, ] ): """ @@ -92,14 +92,14 @@ class Transforms( ] = dataclasses.field(default_factory=past_process_args.transform_program_args_factory) past_to_itir: workflow.Workflow[ - ffront_stages.ConcretePASTProgramDef, stages.CompilableProgramDef + ffront_stages.ConcretePASTProgramDef, stages.CompilableProgram ] = dataclasses.field(default_factory=past_to_itir.past_to_gtir_factory) def step_order(self, inp: stages.ConcreteProgramDef) -> list[str]: steps: list[str] = [] if isinstance(inp.args, arguments.JITArgs): steps.append("aotify_args") - match inp.data: + match inp.definition: case ffront_stages.DSLFieldOperatorDef(): steps.extend( [ @@ -140,32 +140,36 @@ def step_order(self, inp: stages.ConcreteProgramDef) -> list[str]: DEFAULT_TRANSFORMS: Transforms = Transforms() -# TODO(tehrengruber): Rename class and `executor` & `transforms` attribute. Maybe: -# `Backend` -> `Toolchain` -# `transforms` -> `frontend_transforms` -# `executor` -> `backend_transforms` @dataclasses.dataclass(frozen=True) -class Backend(Generic[core_defs.DeviceTypeT]): +class Toolchain(Generic[core_defs.DeviceTypeT]): + """ + Complete pipeline from a program definition to an executable program. + + The `frontend` workflow transforms any supported program definition into a + `CompilableProgram`, which the `backend` workflow then compiles into a + loadable compilation artifact. The `loading` step turns that artifact into a + directly-callable program; toolchains needing to inject backend-specific + runtime data supply their own step here. The `allocator` describes the + device the compiled program expects its buffers on. + """ + name: str - executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] + backend: workflow.Workflow[stages.CompilableProgram, artifacts.CompilationArtifact] allocator: next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] - transforms: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgramDef] + frontend: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgram] + # A plain `Callable`, not `workflow.Workflow`: the protocol names its + # parameter `inp`, which would force every loading step to use that name. + loading: Callable[[artifacts.CompilationArtifact], artifacts.ExecutableProgram] = ( + dataclasses.field(default=artifacts.load_artifact) + ) def compile( self, program: stages.IRDefinitionT, compile_time_args: arguments.CompileTimeArgs ) -> artifacts.ExecutableProgram: - artifact = self.executor( - self.transforms(stages.ConcreteProgramDef(data=program, args=compile_time_args)) + artifact = self.backend( + self.frontend(stages.ConcreteProgramDef(definition=program, args=compile_time_args)) ) - return self.load_artifact(artifact) - - def load_artifact(self, artifact: artifacts.CompilationArtifact) -> artifacts.ExecutableProgram: - """Load an artifact into an executable program. - - Backends may override this method to inject backend-specific runtime data - into the loaded program. - """ - return artifact.load() + return self.loading(artifact) @property def __gt_allocator__( diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index 7700074e19..25ebddb744 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -48,10 +48,10 @@ class BuildJobsMode(enum.Enum): #: Run compilation in a ``ThreadPoolExecutor``. THREAD = "thread" #: Run compilation in a ``ProcessPoolExecutor`` with the ``spawn`` start - #: method. Requires the backend's ``executor`` to be stdlib-picklable + #: method. Requires the toolchain's ``backend`` pipeline to be stdlib-picklable #: (standard runners and factory-constructed variants are) and to return a #: picklable ``CompilationArtifact``; backends that don't qualify (or that - #: customize ``Backend.compile``) are compiled in the calling thread + #: customize ``Toolchain.compile``) are compiled in the calling thread #: instead, with a warning. PROCESS = "process" diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index bf63aa692a..92f3ceabc0 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -50,7 +50,7 @@ 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.Toolchain | None = None ProgramCallMetricsCollector = metrics.make_collector( @@ -96,7 +96,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: Optional[next_backend.Toolchain] = dataclasses.field( metadata=utils.gt4py_metadata(fingerprint=False) ) compilation_options: options.CompilationOptions @@ -104,7 +104,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.Toolchain | None) -> Self: return dataclasses.replace(self, backend=backend) def with_compilation_options( @@ -246,7 +246,7 @@ class Program(_CompilableGTEntryPointMixin[ffront_stages.DSLProgramDef]): def from_function( cls, definition: types.FunctionType, - backend: next_backend.Backend | None, + backend: next_backend.Toolchain | None, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Program: @@ -263,8 +263,8 @@ def __gt_type__(self) -> ts_ffront.ProgramType: # TODO(ricoh): linting should become optional, up to the backend. def __post_init__(self) -> None: - no_args_past = workflow.ConcreteArtifact(self.past_stage, arguments.CompileTimeArgs.empty()) - _ = self._frontend_transforms.past_lint(no_args_past).data + no_args_past = workflow.ProgramWithArgs(self.past_stage, arguments.CompileTimeArgs.empty()) + _ = self._frontend_transforms.past_lint(no_args_past).definition @property def __name__(self) -> str: @@ -286,19 +286,19 @@ def definition(self) -> types.FunctionType: @functools.cached_property def past_stage(self) -> ffront_stages.PASTProgramDef: # backwards compatibility for backends that do not support the full toolchain - no_args_def = workflow.ConcreteArtifact( + no_args_def = workflow.ProgramWithArgs( self.definition_stage, arguments.CompileTimeArgs.empty() ) - return self._frontend_transforms.func_to_past(no_args_def).data + return self._frontend_transforms.func_to_past(no_args_def).definition @property def _frontend_transforms(self) -> next_backend.Transforms: if self.backend is None: return next_backend.DEFAULT_TRANSFORMS - # TODO(tehrengruber): This class relies heavily on `self.backend.transforms` being + # TODO(tehrengruber): This class relies heavily on `self.backend.frontend` being # a `next_backend.Transforms`, but the backend type annotation does not reflect that. - assert isinstance(self.backend.transforms, next_backend.Transforms) - return self.backend.transforms + assert isinstance(self.backend.frontend, next_backend.Transforms) + return self.backend.frontend @functools.cached_property def _all_closure_vars(self) -> dict[str, Any]: @@ -306,15 +306,15 @@ def _all_closure_vars(self) -> dict[str, Any]: @functools.cached_property def gtir(self) -> itir.Program: - no_args_past = workflow.ConcreteArtifact( - data=ffront_stages.PASTProgramDef( + no_args_past = workflow.ProgramWithArgs( + definition=ffront_stages.PASTProgramDef( past_node=self.past_stage.past_node, closure_vars=self.past_stage.closure_vars, grid_type=self.definition_stage.grid_type, ), args=arguments.CompileTimeArgs.empty(), ) - return self._frontend_transforms.past_to_itir(no_args_past).data + return self._frontend_transforms.past_to_itir(no_args_past).definition def with_grid_type(self, grid_type: common.GridType) -> Program: return dataclasses.replace( @@ -503,7 +503,7 @@ def program(definition: Callable) -> Program: ... @typing.overload def program( *, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Callable[[Callable], Program]: ... @@ -513,7 +513,7 @@ def program( definition: Callable | None = None, *, # `NOTHING` -> default backend, `None` -> no backend (embedded execution) - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Program | Callable[[Callable], Program]: @@ -544,7 +544,8 @@ def program_inner(definition: Callable) -> Program: program = Program.from_function( definition, backend=typing.cast( - next_backend.Backend | None, DEFAULT_BACKEND if backend is eve.NOTHING else backend + next_backend.Toolchain | None, + DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type=grid_type, **compilation_options, @@ -580,7 +581,7 @@ class FieldOperator(_CompilableGTEntryPointMixin[ffront_stages.DSLFieldOperatorD def from_function( cls, definition: types.FunctionType, - backend: Optional[next_backend.Backend], + backend: Optional[next_backend.Toolchain], grid_type: Optional[common.GridType] = None, *, operator_node_cls: type[foast.OperatorNode] = foast.FieldOperator, @@ -606,10 +607,10 @@ def __post_init__(self) -> None: @functools.cached_property def foast_stage(self) -> ffront_stages.FOASTOperatorDef: return self._frontend_transforms.func_to_foast( - workflow.ConcreteArtifact( - data=self.definition_stage, args=arguments.CompileTimeArgs.empty() + workflow.ProgramWithArgs( + definition=self.definition_stage, args=arguments.CompileTimeArgs.empty() ) - ).data + ).definition @property def __name__(self) -> str: @@ -623,10 +624,10 @@ def definition(self) -> types.FunctionType: def _frontend_transforms(self) -> next_backend.Transforms: if self.backend is None: return next_backend.DEFAULT_TRANSFORMS - # TODO(tehrengruber): This class relies heavily on `self.backend.transforms` being + # TODO(tehrengruber): This class relies heavily on `self.backend.frontend` being # a `next_backend.Transforms`, but the backend type annotation does not reflect that. - assert isinstance(self.backend.transforms, next_backend.Transforms) - return self.backend.transforms + assert isinstance(self.backend.frontend, next_backend.Transforms) + return self.backend.frontend def __gt_type__(self) -> ts.CallableType: type_ = self.foast_stage.foast_node.type @@ -730,7 +731,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.Toolchain | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, ) -> FieldOperator: ... @@ -738,7 +739,7 @@ def field_operator( @typing.overload def field_operator( *, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, ) -> Callable[[Callable], FieldOperator]: ... @@ -746,7 +747,7 @@ def field_operator( def field_operator( definition: Callable | None = None, *, - backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> FieldOperator | Callable[[types.FunctionType], FieldOperator]: @@ -771,7 +772,8 @@ def field_operator_inner(definition: Callable) -> FieldOperator: return FieldOperator.from_function( definition, typing.cast( - next_backend.Backend | None, DEFAULT_BACKEND if backend is eve.NOTHING else backend + next_backend.Toolchain | None, + DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type, **compilation_options, @@ -787,7 +789,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.Toolchain | eve.NothingType | None, grid_type: common.GridType | None, ) -> FieldOperator: ... @@ -814,7 +816,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.Toolchain | eve.NothingType | None, grid_type: common.GridType | None, ) -> Callable[[Callable], FieldOperator]: ... @@ -825,7 +827,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.Toolchain | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, ) -> FieldOperator | Callable[[Callable], FieldOperator]: """ @@ -862,7 +864,8 @@ def scan_operator_inner(definition: Callable) -> FieldOperator: return FieldOperator.from_function( definition, typing.cast( - next_backend.Backend | None, DEFAULT_BACKEND if backend is eve.NOTHING else backend + next_backend.Toolchain | None, + DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type, operator_node_cls=foast.ScanOperator, diff --git a/src/gt4py/next/ffront/foast_to_past.py b/src/gt4py/next/ffront/foast_to_past.py index beabe53c71..488aa2a253 100644 --- a/src/gt4py/next/ffront/foast_to_past.py +++ b/src/gt4py/next/ffront/foast_to_past.py @@ -33,23 +33,23 @@ class ItirShim: lowering has access to the relevant information. """ - definition: ConcreteFOASTOperatorDef + operator_def: ConcreteFOASTOperatorDef foast_to_itir: workflow.Workflow[ConcreteFOASTOperatorDef, itir.FunctionDefinition] def __gt_closure_vars__(self) -> Optional[dict[str, Any]]: - return self.definition.data.closure_vars + return self.operator_def.definition.closure_vars def __gt_type__(self) -> ts.CallableType: - assert isinstance(self.definition.data.foast_node.type, ts.CallableType) - return self.definition.data.foast_node.type + assert isinstance(self.operator_def.definition.foast_node.type, ts.CallableType) + return self.operator_def.definition.foast_node.type def __gt_itir__(self) -> itir.FunctionDefinition: - return self.foast_to_itir(self.definition) + return self.foast_to_itir(self.operator_def) # FIXME[#1582](tehrengruber): remove after refactoring to GTIR def __gt_gtir__(self) -> itir.FunctionDefinition: # backend should have self.foast_to_itir set to foast_to_gtir - return self.foast_to_itir(self.definition) + return self.foast_to_itir(self.operator_def) @dataclasses.dataclass(frozen=True) @@ -82,14 +82,15 @@ class OperatorToProgram(workflow.Workflow[ConcreteFOASTOperatorDef, ConcretePAST ... argument_descriptor_contexts={}, ... ) - >>> copy_program = op_to_prog( - ... workflow.ConcreteArtifact(copy.foast_stage, compile_time_args) - ... ) + >>> copy_program = op_to_prog(workflow.ProgramWithArgs(copy.foast_stage, compile_time_args)) - >>> print(copy_program.data.past_node.id) + >>> print(copy_program.definition.past_node.id) __field_operator_copy - >>> assert copy_program.data.closure_vars["copy"].definition.data is copy.foast_stage + >>> assert ( + ... copy_program.definition.closure_vars["copy"].operator_def.definition + ... is copy.foast_stage + ... ) """ foast_to_itir: workflow.Workflow[ConcreteFOASTOperatorDef, itir.FunctionDefinition] @@ -102,10 +103,12 @@ def __call__(self, inp: ConcreteFOASTOperatorDef) -> ConcretePASTProgramDef: arg_types, kwarg_types = inp.args.args, inp.args.kwargs assert not kwarg_types - type_ = inp.data.foast_node.type - loc = inp.data.foast_node.location - assert isinstance(inp.data.foast_node.type, ts.CallableType) - partial_program_type = ffront_type_info.type_in_program_context(inp.data.foast_node.type) + type_ = inp.definition.foast_node.type + loc = inp.definition.foast_node.location + assert isinstance(inp.definition.foast_node.type, ts.CallableType) + partial_program_type = ffront_type_info.type_in_program_context( + inp.definition.foast_node.type + ) assert isinstance(partial_program_type, ts_ffront.ProgramType) args_names = [ *partial_program_type.definition.pos_only_args, @@ -134,27 +137,29 @@ def __call__(self, inp: ConcreteFOASTOperatorDef) -> ConcretePASTProgramDef: params_ref = [past.Name(id=pdecl.id, location=loc) for pdecl in params_decl[:-1]] out_ref = past.Name(id="out", location=loc) - if inp.data.foast_node.id in inp.data.closure_vars: + if inp.definition.foast_node.id in inp.definition.closure_vars: raise RuntimeError("A closure variable has the same name as the field operator itself.") closure_symbols: list[past.Symbol] = [ past.Symbol( - id=inp.data.foast_node.id, + id=inp.definition.foast_node.id, type=ts.DeferredType(constraint=None), namespace=dialect_ast_enums.Namespace.CLOSURE, location=loc, ), ] - fieldop_itir_closure_vars = {inp.data.foast_node.id: ItirShim(inp, self.foast_to_itir)} + fieldop_itir_closure_vars = { + inp.definition.foast_node.id: ItirShim(inp, self.foast_to_itir) + } untyped_past_node = past.Program( - id=f"__field_operator_{inp.data.foast_node.id}", + id=f"__field_operator_{inp.definition.foast_node.id}", type=ts.DeferredType(constraint=ts_ffront.ProgramType), params=params_decl, body=[ past.Call( - func=past.Name(id=inp.data.foast_node.id, location=loc), + func=past.Name(id=inp.definition.foast_node.id, location=loc), args=params_ref, kwargs={"out": out_ref}, location=loc, @@ -169,11 +174,11 @@ def __call__(self, inp: ConcreteFOASTOperatorDef) -> ConcretePASTProgramDef: ) past_node = type_deduction.ProgramTypeDeduction.apply(untyped_past_node) - return workflow.ConcreteArtifact( - data=ffront_stages.PASTProgramDef( + return workflow.ProgramWithArgs( + definition=ffront_stages.PASTProgramDef( past_node=past_node, closure_vars=fieldop_itir_closure_vars, # type: ignore[arg-type] - grid_type=inp.data.grid_type, + grid_type=inp.definition.grid_type, ), args=inp.args, ) diff --git a/src/gt4py/next/ffront/past_process_args.py b/src/gt4py/next/ffront/past_process_args.py index 859776ccc7..ced8cf7dd8 100644 --- a/src/gt4py/next/ffront/past_process_args.py +++ b/src/gt4py/next/ffront/past_process_args.py @@ -22,10 +22,10 @@ def transform_program_args( inp: ffront_stages.ConcretePASTProgramDef, ) -> ffront_stages.ConcretePASTProgramDef: rewritten_args, rewritten_kwargs = _process_args( - past_node=inp.data.past_node, args=inp.args.args, kwargs=inp.args.kwargs + past_node=inp.definition.past_node, args=inp.args.args, kwargs=inp.args.kwargs ) - return workflow.ConcreteArtifact( - data=inp.data, + return workflow.ProgramWithArgs( + definition=inp.definition, args=arguments.CompileTimeArgs( args=rewritten_args, kwargs=rewritten_kwargs, diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index cd908fca14..5182918488 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -35,7 +35,7 @@ # FIXME[#1582](tehrengruber): This should only depend on the program not the arguments. Remove # dependency as soon as column axis can be deduced from ITIR in consumers of the CompilableProgram. -def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: +def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgram: """ Lower a PAST program definition to Iterator IR. @@ -63,21 +63,21 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: ... ) >>> itir_copy = past_to_gtir( - ... workflow.ConcreteArtifact(copy_program.past_stage, compile_time_args) + ... workflow.ProgramWithArgs(copy_program.past_stage, compile_time_args) ... ) - >>> print(itir_copy.data.id) + >>> print(itir_copy.definition.id) copy_program - >>> print(type(itir_copy.data)) + >>> print(type(itir_copy.definition)) """ - all_closure_vars = transform_utils._get_closure_vars_recursively(inp.data.closure_vars) + all_closure_vars = transform_utils._get_closure_vars_recursively(inp.definition.closure_vars) offsets_and_dimensions = transform_utils._filter_closure_vars_by_type( all_closure_vars, fbuiltins.FieldOffset, common.Dimension ) grid_type = transform_utils._deduce_grid_type( - inp.data.grid_type, offsets_and_dimensions.values() + inp.definition.grid_type, offsets_and_dimensions.values() ) gt_callables = transform_utils._filter_closure_vars_by_type( @@ -94,7 +94,7 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: lowered_funcs.append(gt_callable.__gt_gtir__()) itir_program = ProgramLowering.apply( - inp.data.past_node, function_definitions=lowered_funcs, grid_type=grid_type + inp.definition.past_node, function_definitions=lowered_funcs, grid_type=grid_type ) # TODO(tehrengruber): Put this in a dedicated transformation step. @@ -141,15 +141,15 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: inp.args, args=args, kwargs=kwargs, column_axis=_column_axis(all_closure_vars) ) - if config.DEBUG or inp.data.debug: + if config.DEBUG or inp.definition.debug: devtools.debug(itir_program) - return stages.CompilableProgramDef(data=itir_program, args=compile_time_args) + return stages.CompilableProgram(definition=itir_program, args=compile_time_args) def past_to_gtir_factory( cached: bool = True, -) -> workflow.Workflow[ConcretePASTProgramDef, stages.CompilableProgramDef]: +) -> workflow.Workflow[ConcretePASTProgramDef, stages.CompilableProgram]: wf = workflow.make_step(past_to_gtir) if cached: wf = workflow.CachedStep.in_memory( diff --git a/src/gt4py/next/ffront/stages.py b/src/gt4py/next/ffront/stages.py index b7a817bea9..b47ac349bc 100644 --- a/src/gt4py/next/ffront/stages.py +++ b/src/gt4py/next/ffront/stages.py @@ -83,7 +83,7 @@ class DSLFieldOperatorDef(BaseStage): debug: bool = False -ConcreteDSLFieldOperatorDef: typing.TypeAlias = workflow.ConcreteArtifact[ +ConcreteDSLFieldOperatorDef: typing.TypeAlias = workflow.ProgramWithArgs[ DSLFieldOperatorDef, arguments.CompileTimeArgs ] @@ -97,7 +97,7 @@ class FOASTOperatorDef(BaseStage): debug: bool = False -ConcreteFOASTOperatorDef: typing.TypeAlias = workflow.ConcreteArtifact[ +ConcreteFOASTOperatorDef: typing.TypeAlias = workflow.ProgramWithArgs[ FOASTOperatorDef, arguments.CompileTimeArgs ] @@ -109,7 +109,7 @@ class DSLProgramDef(BaseStage): debug: bool = False -ConcreteDSLProgramDef: typing.TypeAlias = workflow.ConcreteArtifact[ +ConcreteDSLProgramDef: typing.TypeAlias = workflow.ProgramWithArgs[ DSLProgramDef, arguments.CompileTimeArgs ] @@ -122,7 +122,7 @@ class PASTProgramDef(BaseStage): debug: bool = False -ConcretePASTProgramDef: typing.TypeAlias = workflow.ConcreteArtifact[ +ConcretePASTProgramDef: typing.TypeAlias = workflow.ProgramWithArgs[ PASTProgramDef, arguments.CompileTimeArgs ] diff --git a/src/gt4py/next/iterator/runtime.py b/src/gt4py/next/iterator/runtime.py index 88a466229f..4907f1d7f4 100644 --- a/src/gt4py/next/iterator/runtime.py +++ b/src/gt4py/next/iterator/runtime.py @@ -74,7 +74,7 @@ def itir(self, *args): def __call__( self, *args, - backend: Optional[next_backend.Backend | program_formatter.ProgramFormatter] = None, + backend: Optional[next_backend.Toolchain | program_formatter.ProgramFormatter] = None, offset_provider=None, column_axis=None, ): @@ -87,8 +87,8 @@ def __call__( # 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.Backend): - assert isinstance(backend, next_backend.Backend) + if isinstance(backend, next_backend.Toolchain): + assert isinstance(backend, next_backend.Toolchain) compiled_program = backend.compile( itir_node, arguments.CompileTimeArgs.from_concrete( @@ -102,7 +102,7 @@ def __call__( ) else: raise ValueError( - "Backend must be a 'gt4py.next.backend.Backend' or " + "Backend must be a 'gt4py.next.backend.Toolchain' or " "'gt4py.next.program_formatter.ProgramFormatter'." ) else: diff --git a/src/gt4py/next/otf/artifacts.py b/src/gt4py/next/otf/artifacts.py index fa3226153b..5ee89a989f 100644 --- a/src/gt4py/next/otf/artifacts.py +++ b/src/gt4py/next/otf/artifacts.py @@ -179,7 +179,7 @@ class CompilationArtifact(Protocol): arguments. The one current exception is ``RoundtripArtifact`` when it is configured - with a ``dispatch_backend``: that field holds a ``Backend`` reference + with a ``dispatch_backend``: that field holds a ``Toolchain`` reference whose role belongs at the runner / load-time seam, not in the artifact itself. """ @@ -187,6 +187,23 @@ class CompilationArtifact(Protocol): def load(self) -> ExecutableProgram: ... +def load_artifact(artifact: CompilationArtifact) -> ExecutableProgram: + """ + Load a compilation artifact into a directly-callable program. + + This is the default loading step of a `Toolchain`. Toolchains that need to + inject backend-specific runtime data into the loaded program supply their + own step instead of overriding a method. + + Args: + artifact: The artifact produced by the toolchain's compile pipeline. + + Returns: + The loaded, directly-callable program. + """ + return artifact.load() + + def _unique_libs(*args: interface.LibraryDependency) -> tuple[interface.LibraryDependency, ...]: """ Filter out multiple occurrences of the same ``interface.LibraryDependency``. diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index ace3127501..0a59c39792 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -134,15 +134,15 @@ def load(self) -> artifacts.ExecutableProgram: def make_compilation_task( - backend: gtx_backend.Backend, + backend: gtx_backend.Toolchain, definition_stage: Any, compile_time_args: arguments.CompileTimeArgs, ) -> runners.CompilationTask: """Prepare the compilation of `definition_stage` with `backend` as a task for a runner.""" name = getattr(backend, "name", type(backend).__name__) - if getattr(type(backend), "compile", None) is not gtx_backend.Backend.compile: + if getattr(type(backend), "compile", None) is not gtx_backend.Toolchain.compile: # A customized `compile` is opaque: it cannot be decomposed into the - # standard transforms/executor workflow (and yields an already-loaded + # standard frontend/backend workflow (and yields an already-loaded # program instead of an artifact), so the executor closes over # everything and ignores the compilable. return runners.CompilationTask( @@ -156,12 +156,12 @@ def make_compilation_task( ) # Frontend lowering happens here, main-side: decorators rebind the user's # function module attribute, so the raw `types.FunctionType` must not cross - # a process boundary; the lowered `CompilableProgramDef` is pickle-safe. - compilable = backend.transforms( - stages.ConcreteProgramDef(data=definition_stage, args=compile_time_args) + # a process boundary; the lowered `CompilableProgram` is pickle-safe. + compilable = backend.frontend( + stages.ConcreteProgramDef(definition=definition_stage, args=compile_time_args) ) - def construct_compilable(with_refs: bool) -> stages.CompilableProgramDef: + def construct_compilable(with_refs: bool) -> stages.CompilableProgram: if not with_refs or not compilable.args.offset_provider: return compilable # The shipped copy must not carry the connectivity buffers: they may @@ -176,5 +176,5 @@ def construct_compilable(with_refs: bool) -> stages.CompilableProgramDef: ) return runners.CompilationTask( - name=name, construct_compilable=construct_compilable, executor=backend.executor + name=name, construct_compilable=construct_compilable, executor=backend.backend ) diff --git a/src/gt4py/next/otf/compiled_program.py b/src/gt4py/next/otf/compiled_program.py index b71fdd9df9..96a7d39308 100644 --- a/src/gt4py/next/otf/compiled_program.py +++ b/src/gt4py/next/otf/compiled_program.py @@ -89,7 +89,7 @@ def metrics_source_key(pool: CompiledProgramsPool, key: CompiledProgramsKey) -> def compile_variant_hook( program_pool: CompiledProgramsPool, key: CompiledProgramsKey, - backend: gtx_backend.Backend, + backend: gtx_backend.Toolchain, argument_descriptors: ArgStaticDescriptorsByType, offset_provider: common.OffsetProviderType | common.OffsetProvider, ) -> None: @@ -350,7 +350,7 @@ class CompiledProgramsPool(Generic[ffront_stages.DSLDefinitionT]): to `compile` before it can be used. """ - backend: gtx_backend.Backend + backend: gtx_backend.Toolchain definition_stage: ffront_stages.DSLDefinitionT # Note: This type can be incomplete, i.e. contain DeferredType, whenever the operator is a # scan operator. In the future it could also be the type of a generic program. @@ -491,7 +491,7 @@ def _load_artifact( ) -> artifacts.ExecutableProgram: artifact = artifact_future.result() # re-raises errors from the compilation worker try: - return self.backend.load_artifact(artifact) + return self.backend.loading(artifact) except Exception as e: raise RuntimeError( f"Failed to load the compiled program '{self.definition.__name__}'." diff --git a/src/gt4py/next/otf/recipes.py b/src/gt4py/next/otf/recipes.py index b905ee0bd3..a515fd5a98 100644 --- a/src/gt4py/next/otf/recipes.py +++ b/src/gt4py/next/otf/recipes.py @@ -15,7 +15,7 @@ @dataclasses.dataclass(frozen=True) class OTFCompileWorkflow( - workflow.NamedStepSequence[stages.CompilableProgramDef, artifacts.CompilationArtifact] + workflow.NamedStepSequence[stages.CompilableProgram, artifacts.CompilationArtifact] ): """The typical compiled backend steps composed into a workflow.""" diff --git a/src/gt4py/next/otf/stages.py b/src/gt4py/next/otf/stages.py index 4781907c1b..2d1962b4b1 100644 --- a/src/gt4py/next/otf/stages.py +++ b/src/gt4py/next/otf/stages.py @@ -39,12 +39,12 @@ ) ArgsDefinitionT = TypeVar("ArgsDefinitionT", arguments.JITArgs, arguments.CompileTimeArgs) -ConcreteProgramDef: TypeAlias = workflow.ConcreteArtifact[IRDefinitionT, ArgsDefinitionT] -CompilableProgramDef: TypeAlias = ConcreteProgramDef[itir.Program, arguments.CompileTimeArgs] +ConcreteProgramDef: TypeAlias = workflow.ProgramWithArgs[IRDefinitionT, ArgsDefinitionT] +CompilableProgram: TypeAlias = ConcreteProgramDef[itir.Program, arguments.CompileTimeArgs] class TranslationStep( - workflow.ReplaceEnabledWorkflowMixin[CompilableProgramDef, artifacts.ProgramSource[CodeSpecT]], + workflow.ReplaceEnabledWorkflowMixin[CompilableProgram, artifacts.ProgramSource[CodeSpecT]], Protocol[CodeSpecT], ): """Translate a GT4Py program to source code (ProgramCall -> ProgramSource).""" diff --git a/src/gt4py/next/otf/toolchain.py b/src/gt4py/next/otf/toolchain.py index 14d1b1cdf8..752c6e4fd9 100644 --- a/src/gt4py/next/otf/toolchain.py +++ b/src/gt4py/next/otf/toolchain.py @@ -25,40 +25,38 @@ class DataOnlyAdapter( workflow.ChainableWorkflowMixin, workflow.ReplaceEnabledWorkflowMixin, - workflow.Workflow[workflow.ConcreteArtifact[S, ArgsT], workflow.ConcreteArtifact[T, ArgsT]], + workflow.Workflow[workflow.ProgramWithArgs[S, ArgsT], workflow.ProgramWithArgs[T, ArgsT]], Generic[ArgsT, S, T], ): step: workflow.Workflow[S, T] def __call__( - self, inp: workflow.ConcreteArtifact[S, ArgsT] - ) -> workflow.ConcreteArtifact[T, ArgsT]: - return workflow.ConcreteArtifact(data=self.step(inp.data), args=inp.args) + self, inp: workflow.ProgramWithArgs[S, ArgsT] + ) -> workflow.ProgramWithArgs[T, ArgsT]: + return workflow.ProgramWithArgs(definition=self.step(inp.definition), args=inp.args) @dataclasses.dataclass(frozen=True) class ArgsOnlyAdapter( workflow.ChainableWorkflowMixin, workflow.ReplaceEnabledWorkflowMixin, - workflow.Workflow[workflow.ConcreteArtifact[DefT, S], workflow.ConcreteArtifact[DefT, T]], + workflow.Workflow[workflow.ProgramWithArgs[DefT, S], workflow.ProgramWithArgs[DefT, T]], Generic[DefT, S, T], ): step: workflow.Workflow[S, T] - def __call__( - self, inp: workflow.ConcreteArtifact[DefT, S] - ) -> workflow.ConcreteArtifact[DefT, T]: - return workflow.ConcreteArtifact(data=inp.data, args=self.step(inp.args)) + def __call__(self, inp: workflow.ProgramWithArgs[DefT, S]) -> workflow.ProgramWithArgs[DefT, T]: + return workflow.ProgramWithArgs(definition=inp.definition, args=self.step(inp.args)) @dataclasses.dataclass(frozen=True) class StripArgsAdapter( workflow.ChainableWorkflowMixin, workflow.ReplaceEnabledWorkflowMixin, - workflow.Workflow[workflow.ConcreteArtifact[S, ArgsT], T], + workflow.Workflow[workflow.ProgramWithArgs[S, ArgsT], T], Generic[ArgsT, S, T], ): step: workflow.Workflow[S, T] - def __call__(self, inp: workflow.ConcreteArtifact[S, ArgsT]) -> T: - return self.step(inp.data) + def __call__(self, inp: workflow.ProgramWithArgs[S, ArgsT]) -> T: + return self.step(inp.definition) diff --git a/src/gt4py/next/otf/workflow.py b/src/gt4py/next/otf/workflow.py index fa57a9ac7f..8d4c2fdec0 100644 --- a/src/gt4py/next/otf/workflow.py +++ b/src/gt4py/next/otf/workflow.py @@ -34,7 +34,7 @@ @dataclasses.dataclass -class ConcreteArtifact(Generic[DefT, ArgsT]): +class ProgramWithArgs(Generic[DefT, ArgsT]): """Pair of a program definition in any stage with the arguments it is compiled for. This is the envelope threaded through the definition-transforming half of @@ -47,7 +47,7 @@ class ConcreteArtifact(Generic[DefT, ArgsT]): test in `tests/next_tests/unit_tests/otf_tests/`. """ - data: DefT + definition: DefT args: ArgsT diff --git a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py index f1c6978791..6f09b7d30c 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -35,11 +35,11 @@ def get_param_description(name: str, type_: Any) -> interface.Parameter: @dataclasses.dataclass(frozen=True) class GTFNTranslationStep( workflow.ReplaceEnabledWorkflowMixin[ - stages.CompilableProgramDef, + stages.CompilableProgram, artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec], ], workflow.ChainableWorkflowMixin[ - stages.CompilableProgramDef, + stages.CompilableProgram, artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec], ], ): @@ -174,10 +174,10 @@ def generate_stencil_source( return GTFNCodegen.apply(gtfn_ir) def __call__( - self, inp: stages.CompilableProgramDef + self, inp: stages.CompilableProgram ) -> artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec]: """Generate GTFN C++ code from the ITIR definition.""" - program: itir.Program = inp.data + program: itir.Program = inp.definition # handle regular parameters and arguments of the program (i.e. what the user defined in # the program) diff --git a/src/gt4py/next/program_processors/runners/dace/program.py b/src/gt4py/next/program_processors/runners/dace/program.py index f8f8c7e1a4..abd88a7dad 100644 --- a/src/gt4py/next/program_processors/runners/dace/program.py +++ b/src/gt4py/next/program_processors/runners/dace/program.py @@ -43,9 +43,9 @@ def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: column_axis = kwargs.get("column_axis", None) # TODO(ricoh): connectivity tables required here for now. - gtir_stage = typing.cast(gtx_backend.Transforms, self.backend.transforms).past_to_itir( - workflow.ConcreteArtifact( - data=self.past_stage, + gtir_stage = typing.cast(gtx_backend.Transforms, self.backend.frontend).past_to_itir( + workflow.ProgramWithArgs( + definition=self.past_stage, args=arguments.CompileTimeArgs( args=tuple(p.type for p in self.past_stage.past_node.params), kwargs={}, @@ -55,13 +55,13 @@ def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: ), ) ) - program = gtir_stage.data + program = gtir_stage.definition program = itir_transforms.apply_fieldview_transforms( # run the transforms separately because they require the runtime info program, offset_provider=offset_provider ) object.__setattr__( gtir_stage, - "data", + "definition", program, ) object.__setattr__( @@ -76,7 +76,7 @@ def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: gt4py_program_args=[p.type for p in program.params], ) - otf_workflow = self.backend.executor + otf_workflow = self.backend.backend assert hasattr(otf_workflow, "translation") otf_workflow_translation = ( otf_workflow.translation.step diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py index 98149f20c4..079ea0a9ae 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -23,15 +23,20 @@ @dataclasses.dataclass(frozen=True) -class DaCeBackend(backend.Backend[Any]): - """DaCe backend with support for injecting an external workspace at load time.""" +class DaCeLoadingStep: + """ + Loading step that injects an external workspace into the loaded program. + + The workspace is owned by the caller, not by the toolchain; it is installed + onto the program wrapper before its first call, so that it is used when the + SDFG argument vector is constructed. + """ external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None - def load_artifact(self, artifact: artifacts.CompilationArtifact) -> artifacts.ExecutableProgram: - program = super().load_artifact(artifact) + def __call__(self, artifact: artifacts.CompilationArtifact) -> artifacts.ExecutableProgram: + program = artifacts.load_artifact(artifact) assert isinstance(program, gtx_wfddecoration.DaCeDecoratedProgram) - # Inject the backend-level workspace so it is used when arguments are constructed. program.set_external_workspace(self.external_workspace or {}) return program @@ -44,7 +49,7 @@ def make_dace_toolchain( translation: gtx_wfdfactory.DaCeTranslationBuilder = gtx_wfdfactory.make_dace_translator, bindings: gtx_wfdfactory.DaCeBindingsBuilder = gtx_wfdfactory.make_dace_bindings, compilation: gtx_wfdfactory.DaCeCompilationBuilder = gtx_wfdfactory.make_dace_compiler, -) -> DaCeBackend: +) -> backend.Toolchain: """ Build a DaCe toolchain. @@ -62,14 +67,14 @@ def make_dace_toolchain( if cfg is None: cfg = gtx_wfdfactory.DaCeConfig() - return DaCeBackend( + return backend.Toolchain( name=f"run_dace_{cfg.device_name}{'_opt' if cfg.auto_optimize else ''}{name_postfix}", - executor=gtx_wfdfactory.make_dace_compile_workflow( + backend=gtx_wfdfactory.make_dace_compile_workflow( cfg, translation=translation, bindings=bindings, compilation=compilation ), allocator=cfg.make_allocator(), - transforms=backend.DEFAULT_TRANSFORMS, - external_workspace=cfg.external_workspace, + frontend=backend.DEFAULT_TRANSFORMS, + loading=DaCeLoadingStep(cfg.external_workspace), ) @@ -83,7 +88,7 @@ def make_dace_backend( use_metrics: bool = True, use_zero_origin: bool = False, use_max_domain_range_on_unstructured_shift: bool | None = None, -) -> DaCeBackend: +) -> backend.Toolchain: """Customize the dace backend with the given configuration parameters. Deprecated: use `make_dace_toolchain` with a `DaCeConfig` for the shared diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py index ee96fbeff2..e83c33e5ab 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -349,11 +349,11 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: @dataclasses.dataclass(frozen=True) class DaCeTranslator( workflow.ChainableWorkflowMixin[ - stages.CompilableProgramDef, + stages.CompilableProgram, artifacts.ProgramSource[artifacts.SDFGCodeSpec], ], workflow.ReplaceEnabledWorkflowMixin[ - stages.CompilableProgramDef, + stages.CompilableProgram, artifacts.ProgramSource[artifacts.SDFGCodeSpec], ], ): @@ -460,10 +460,10 @@ def _generate_sdfg_without_configuring_dace( return sdfg def __call__( - self, inp: stages.CompilableProgramDef + self, inp: stages.CompilableProgram ) -> artifacts.ProgramSource[artifacts.SDFGCodeSpec]: """Generate DaCe SDFG file from the GTIR definition.""" - program: itir.Program = inp.data + program: itir.Program = inp.definition assert isinstance(program, itir.Program) sdfg = self.generate_sdfg( diff --git a/src/gt4py/next/program_processors/runners/double_roundtrip.py b/src/gt4py/next/program_processors/runners/double_roundtrip.py index 3e96b30c60..ef7681f685 100644 --- a/src/gt4py/next/program_processors/runners/double_roundtrip.py +++ b/src/gt4py/next/program_processors/runners/double_roundtrip.py @@ -12,9 +12,9 @@ from gt4py.next.program_processors.runners import roundtrip -backend = next_backend.Backend( +backend = next_backend.Toolchain( name="double_roundtrip", - transforms=next_backend.DEFAULT_TRANSFORMS, - executor=roundtrip.Roundtrip(dispatch_backend=roundtrip.default, use_embedded=False), + frontend=next_backend.DEFAULT_TRANSFORMS, + backend=roundtrip.Roundtrip(dispatch_backend=roundtrip.default, use_embedded=False), allocator=roundtrip.default.allocator, ) diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index f73f4e0cd6..2d80dcbe66 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -287,7 +287,7 @@ def make_gtfn_toolchain( translation: GTFNTranslationBuilder = make_gtfn_translation, bindings: GTFNBindingsBuilder = make_gtfn_bindings, compilation: GTFNCompilationBuilder = make_gtfn_compiler, -) -> backend.Backend: +) -> backend.Toolchain: """ Build a GTFN toolchain. @@ -305,13 +305,13 @@ def make_gtfn_toolchain( if cfg is None: cfg = GTFNConfig() - return backend.Backend( + return backend.Toolchain( name=f"run_gtfn_{cfg.device_name}{name_postfix}", - executor=make_gtfn_compile_workflow( + backend=make_gtfn_compile_workflow( cfg, translation=translation, bindings=bindings, compilation=compilation ), allocator=cfg.make_allocator(), - transforms=backend.DEFAULT_TRANSFORMS, + frontend=backend.DEFAULT_TRANSFORMS, ) diff --git a/src/gt4py/next/program_processors/runners/roundtrip.py b/src/gt4py/next/program_processors/runners/roundtrip.py index 29afc3535a..4108eebbc7 100644 --- a/src/gt4py/next/program_processors/runners/roundtrip.py +++ b/src/gt4py/next/program_processors/runners/roundtrip.py @@ -216,7 +216,7 @@ class RoundtripArtifact: source_code: str entry_point_name: str column_axis: common.Dimension | None - dispatch_backend: next_backend.Backend | None + dispatch_backend: next_backend.Toolchain | None debug: bool def load(self) -> artifacts.ExecutableProgram: @@ -248,17 +248,17 @@ def decorated_fencil( @dataclasses.dataclass(frozen=True) -class Roundtrip(workflow.Workflow[stages.CompilableProgramDef, RoundtripArtifact]): +class Roundtrip(workflow.Workflow[stages.CompilableProgram, RoundtripArtifact]): debug: Optional[bool] = None use_embedded: bool = True - dispatch_backend: Optional[next_backend.Backend] = None + dispatch_backend: Optional[next_backend.Toolchain] = None transforms: itir_transforms.GTIRTransform = itir_transforms.apply_common_transforms # type: ignore[assignment] # TODO(havogt): cleanup interface of `apply_common_transforms` - def __call__(self, inp: stages.CompilableProgramDef) -> RoundtripArtifact: + def __call__(self, inp: stages.CompilableProgram) -> RoundtripArtifact: debug = config.DEBUG if self.debug is None else self.debug source_code, entry_point_name = _generate_source( - inp.data, + inp.definition, offset_provider=inp.args.offset_provider, debug=debug, use_embedded=self.use_embedded, @@ -275,41 +275,41 @@ def __call__(self, inp: stages.CompilableProgramDef) -> RoundtripArtifact: # TODO(tehrengruber): introduce factory -default = next_backend.Backend( +default = next_backend.Toolchain( name="roundtrip", - executor=Roundtrip( + backend=Roundtrip( transforms=functools.partial( itir_transforms.apply_common_transforms, extract_temporaries=False, ) ), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - transforms=next_backend.DEFAULT_TRANSFORMS, + frontend=next_backend.DEFAULT_TRANSFORMS, ) -with_temporaries = next_backend.Backend( +with_temporaries = next_backend.Toolchain( name="roundtrip_with_temporaries", - executor=Roundtrip( + backend=Roundtrip( transforms=functools.partial( itir_transforms.apply_common_transforms, extract_temporaries=True, ) ), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - transforms=next_backend.DEFAULT_TRANSFORMS, + frontend=next_backend.DEFAULT_TRANSFORMS, ) -no_transforms = next_backend.Backend( +no_transforms = next_backend.Toolchain( name="roundtrip", - executor=Roundtrip(transforms=lambda o, *, offset_provider: o), + backend=Roundtrip(transforms=lambda o, *, offset_provider: o), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - transforms=next_backend.DEFAULT_TRANSFORMS, + frontend=next_backend.DEFAULT_TRANSFORMS, ) -gtir = next_backend.Backend( +gtir = next_backend.Toolchain( name="roundtrip_gtir", - executor=Roundtrip(transforms=itir_transforms.apply_fieldview_transforms), # type: ignore[arg-type] # don't understand why mypy complains + backend=Roundtrip(transforms=itir_transforms.apply_fieldview_transforms), # type: ignore[arg-type] # don't understand why mypy complains allocator=next_allocators.StandardCPUFieldBufferAllocator(), - transforms=next_backend.Transforms( + frontend=next_backend.Transforms( past_to_itir=past_to_itir.past_to_gtir_factory(), foast_to_itir=foast_to_gtir.adapted_foast_to_gtir_factory(cached=True), field_view_op_to_prog=foast_to_past.operator_to_program_factory( diff --git a/src/gt4py/next/typing.py b/src/gt4py/next/typing.py index 1c75458862..9fccb71595 100644 --- a/src/gt4py/next/typing.py +++ b/src/gt4py/next/typing.py @@ -25,7 +25,7 @@ CompiledProgramsKey: TypeAlias = Annotated[compiled_program.CompiledProgramsKey, _ONLY_FOR_TYPING] -Backend: TypeAlias = Annotated[backend.Backend, _ONLY_FOR_TYPING] +Toolchain: TypeAlias = Annotated[backend.Toolchain, _ONLY_FOR_TYPING] Allocator: TypeAlias = Annotated[constructors.Allocator, _ONLY_FOR_TYPING] @@ -34,10 +34,9 @@ __all__ = [ "Allocator", - "Backend", "FieldOperator", "OffsetProvider", "Program", - # from _core.definitions for convenience - "Scalar", + "Scalar", # from _core.definitions for convenience + "Toolchain", ] diff --git a/tests/next_tests/benchmarks/benchmark_program_call.py b/tests/next_tests/benchmarks/benchmark_program_call.py index 166509e8f3..ce0d05229b 100644 --- a/tests/next_tests/benchmarks/benchmark_program_call.py +++ b/tests/next_tests/benchmarks/benchmark_program_call.py @@ -47,7 +47,7 @@ @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_const_no_args_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain ): @gtx.field_operator def const() -> gtx.Field[Dims[IDim], gtx.float64]: @@ -69,7 +69,7 @@ def const_no_args(out: gtx.Field[Dims[IDim], gtx.float64]): @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_copy_01_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain ): @gtx.field_operator def identity_fop( @@ -96,7 +96,7 @@ def copy_01_arg( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_horizontal_copy_01_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain ): @gtx.field_operator def identity_01_fop( @@ -143,7 +143,7 @@ def horizontal_copy_01_arg_program( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_horizontal_copy_05_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain ): @gtx.field_operator def identity_05_fop( @@ -202,7 +202,7 @@ def horizontal_copy_05_arg_program( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_horizontal_copy_25_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain ): @gtx.field_operator def identity_25_fop( diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 86a4229860..0f30cb6038 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -54,7 +54,7 @@ class ProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): class EmbeddedDummyBackend: name: str allocator: constructors.Allocator - executor: Final = None + backend: Final = None numpy_execution = EmbeddedDummyBackend("EmbeddedNumPy", nd_array_field.np) diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index b5d99e2eb5..ac8435ce17 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -545,7 +545,7 @@ def cartesian_case_no_backend(): @pytest.fixture def cartesian_case( - exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Backend, + exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Toolchain, ): return Case.from_cartesian_grid_descriptor( simple_cartesian_grid(), @@ -566,7 +566,7 @@ def unstructured_case_no_backend(mesh_descriptor: MeshDescriptor): @pytest.fixture def unstructured_case( mesh_descriptor: MeshDescriptor, - exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Backend, + exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Toolchain, ): return Case.from_mesh_descriptor( mesh_descriptor, @@ -712,7 +712,7 @@ def get_default_data( class Case: """Parametrizable components for single feature integration tests.""" - backend: Optional[next_backend.Backend] + backend: Optional[next_backend.Toolchain] offset_provider: dict[str, common.Connectivity | gtx.Dimension] default_sizes: dict[gtx.Dimension, int] grid_type: common.GridType @@ -726,7 +726,7 @@ def as_field(self): def from_cartesian_grid_descriptor( cls, grid_descriptor: CartesianGridDescriptor, - backend: Optional[next_backend.Backend] = None, + backend: Optional[next_backend.Toolchain] = None, allocator: Optional[next_allocators.FieldBufferAllocatorFactoryProtocol] = None, ) -> Case: return cls( @@ -748,7 +748,7 @@ def from_cartesian_grid_descriptor( def from_mesh_descriptor( cls, mesh_descriptor: MeshDescriptor, - backend: Optional[next_backend.Backend] = None, + backend: Optional[next_backend.Toolchain] = None, allocator: Optional[next_allocators.FieldBufferAllocatorFactoryProtocol] = None, ) -> Case: return cls( diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index ea7c898f4d..3a0fc519bd 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -59,7 +59,7 @@ def _no_backend_allocator(*args: Any, **kwargs: Any) -> None: raise ValueError("No backend selected! Backend selection is mandatory in tests.") -class NoBackend(next_backend.Backend): +class NoBackend(next_backend.Toolchain): """Temporary default backend to not accidentally test the wrong backend.""" def __call__(self, program, *args, **kwargs) -> None: @@ -76,12 +76,12 @@ def __gt_allocator__( no_backend = NoBackend( name="no_backend", - executor=_no_backend_executor, + backend=_no_backend_executor, allocator=_no_backend_allocator, # TODO(tehrengruber): We don't want any transformations, but since `decorator.FieldOperator` # and `decorator.Program` unconditionally do linting on construction we need the # transformations. When this is up to the backend we can remove this again. - transforms=next_backend.DEFAULT_TRANSFORMS, + frontend=next_backend.DEFAULT_TRANSFORMS, ) diff --git a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py index e613e3db92..741d8efff9 100644 --- a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py +++ b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py @@ -119,10 +119,12 @@ def uncached_dace_cpu(): The cache stores the optimized SDFG, so a second run of these tests would replay it and never call the transformation. """ - executor = gtx_dace.run_dace_cpu.executor + compile_pipeline = gtx_dace.run_dace_cpu.backend return dataclasses.replace( gtx_dace.run_dace_cpu, - executor=dataclasses.replace(executor, translation=executor.translation.step), + backend=dataclasses.replace( + compile_pipeline, translation=compile_pipeline.translation.step + ), ) 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..1f1ee9c740 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 @@ -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: Optional[next_backend.Toolchain]): # 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 9f51689d77..c7ef03a844 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 @@ -126,7 +126,7 @@ def custom_compiled_program_callback( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: getattr(b, "name", str(b))) -def test_program_call_hooks(backend: gtx_typing.Backend): +def test_program_call_hooks(backend: gtx_typing.Toolchain): size = 10 a_field = gtx.full([(IDim, size)], 1, dtype=gtx.float64) b_field = gtx.full([(IDim, size)], 1, dtype=gtx.float64) @@ -208,11 +208,11 @@ 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)) ) -def test_compile_variant_hook(backend: gtx_typing.Backend): +def test_compile_variant_hook(backend: gtx_typing.Toolchain): def custom_compile_variant_hook( program_pool: "CompiledProgramsPool", key: gtx_typing.CompiledProgramsKey, - backend: gtx_typing.Backend, + backend: gtx_typing.Toolchain, argument_descriptors: dict[type, dict[str, Any]], offset_provider: common.OffsetProviderType | common.OffsetProvider, ) -> None: 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 2b4847d3c3..760c2b01e3 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 @@ -83,7 +83,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 exec_alloc_descriptor.executor is None else exec_alloc_descriptor + None if exec_alloc_descriptor.backend is None else exec_alloc_descriptor )( setup.input_field, setup.S_fields[0], @@ -106,7 +106,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 exec_alloc_descriptor.executor is None else exec_alloc_descriptor)( + pnabla.with_backend(None if exec_alloc_descriptor.backend is None else exec_alloc_descriptor)( setup.input_field, setup.S_fields, setup.sign_field, diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py index f9b2060621..283f134876 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py @@ -100,7 +100,7 @@ def fen_solve_tridiag2(i_size, j_size, k_size, a, b, c, d, x): def test_tridiag(fencil, tridiag_reference, program_processor): program_processor, validate = program_processor - if isinstance(program_processor, backend.Backend) and "dace" in program_processor.name: + if isinstance(program_processor, backend.Toolchain) and "dace" in program_processor.name: pytest.xfail("Dace ITIR backend doesn't support the IR format used in this test.") a, b, c, d, x = tridiag_reference diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index 879094f123..5d21882c42 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -23,7 +23,7 @@ import next_tests -ProgramProcessor: TypeAlias = backend.Backend | program_formatter.ProgramFormatter +ProgramProcessor: TypeAlias = backend.Toolchain | program_formatter.ProgramFormatter def _program_processor(request) -> tuple[ProgramProcessor, bool]: diff --git a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py index 3d9fcaa834..498a363760 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py +++ b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py @@ -90,8 +90,8 @@ def _verify_program_has_expected_true_value(program: itir.Program): def test_inlining_of_scalars_works(testee_prog): - input_pair = workflow.ConcreteArtifact( - data=testee_prog.definition_stage, + input_pair = workflow.ProgramWithArgs( + definition=testee_prog.definition_stage, args=arguments.CompileTimeArgs( args=list(testee_prog.past_stage.past_node.type.definition.pos_or_kw_args.values()), kwargs={}, @@ -103,7 +103,7 @@ def test_inlining_of_scalars_works(testee_prog): ), ) - transformed = backend.DEFAULT_TRANSFORMS(input_pair).data + transformed = backend.DEFAULT_TRANSFORMS(input_pair).definition _verify_program_has_expected_true_value(transformed) @@ -123,7 +123,7 @@ class _NoOpArtifact: def load(self): return lambda *args, **kwargs: None - def pirate(program: workflow.ConcreteArtifact): + def pirate(program: workflow.ProgramWithArgs): # Replaces the gtfn otf_workflow: steals the compilable program, then # returns a dummy artifact whose materialization is a no-op callable. nonlocal hijacked_program @@ -131,7 +131,7 @@ def pirate(program: workflow.ConcreteArtifact): return _NoOpArtifact() hacked_gtfn_backend = dataclasses.replace( - gtfn.make_gtfn_toolchain(name_postfix="_custom"), executor=pirate + gtfn.make_gtfn_toolchain(name_postfix="_custom"), backend=pirate ) testee = testee_prog.with_backend(hacked_gtfn_backend).compile(cond=[True], offset_provider={}) @@ -141,7 +141,7 @@ def pirate(program: workflow.ConcreteArtifact): offset_provider={}, ) - _verify_program_has_expected_true_value(hijacked_program.data) + _verify_program_has_expected_true_value(hijacked_program.definition) def test_different_static_args_work_after_backend_change(testee_prog): @@ -300,8 +300,8 @@ def _verify_program_has_expected_domain( def test_inlining_of_static_domain_works(testee_prog, uids: utils.IDGeneratorPool): domain = gtx.Domain(dims=(TDim,), ranges=(gtx.UnitRange(0, 1),)) - input_pair = workflow.ConcreteArtifact( - data=testee_prog.definition_stage, + input_pair = workflow.ProgramWithArgs( + definition=testee_prog.definition_stage, args=arguments.CompileTimeArgs( args=list(testee_prog.past_stage.past_node.type.definition.pos_or_kw_args.values()), kwargs={}, @@ -313,7 +313,7 @@ def test_inlining_of_static_domain_works(testee_prog, uids: utils.IDGeneratorPoo ), ) - transformed = backend.DEFAULT_TRANSFORMS(input_pair).data + transformed = backend.DEFAULT_TRANSFORMS(input_pair).definition _verify_program_has_expected_domain(transformed, domain, uids) diff --git a/tests/next_tests/unit_tests/otf_tests/test_runners.py b/tests/next_tests/unit_tests/otf_tests/test_runners.py index dfe0d5b5f6..5597a5b27c 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_runners.py +++ b/tests/next_tests/unit_tests/otf_tests/test_runners.py @@ -100,11 +100,11 @@ def test_process_runner_falls_back_on_non_offloadable_task(process_runner): def test_make_compilation_task_decomposes_standard_backend(): - backend = next_backend.Backend( + backend = next_backend.Toolchain( name="test_backend", - executor=lambda compilable: _NoOpArtifact(), + backend=lambda compilable: _NoOpArtifact(), allocator=None, - transforms=lambda inp: inp, + frontend=lambda inp: inp, ) task = compilation_tasks.make_compilation_task( @@ -112,7 +112,7 @@ def test_make_compilation_task_decomposes_standard_backend(): ) assert task.no_offload_reason is None - assert task.executor is backend.executor + assert task.executor is backend.backend assert callable(task.compile().load()) @@ -129,11 +129,11 @@ def compile(self, program, compile_time_args): return self._wrapped.compile(program, compile_time_args=compile_time_args) backend = _WrapperBackend( - next_backend.Backend( + next_backend.Toolchain( name="test_backend", - executor=lambda compilable: _NoOpArtifact(), + backend=lambda compilable: _NoOpArtifact(), allocator=None, - transforms=lambda inp: inp, + frontend=lambda inp: inp, ) ) @@ -154,11 +154,11 @@ def test_offloaded_task_ships_connectivities_as_file_refs(): compile_time_args = dataclasses.replace( arguments.CompileTimeArgs.empty(), offset_provider={"V2E": conn} ) - backend = next_backend.Backend( + backend = next_backend.Toolchain( name="test_backend", - executor=lambda compilable: _NoOpArtifact(), + backend=lambda compilable: _NoOpArtifact(), allocator=None, - transforms=lambda inp: inp, + frontend=lambda inp: inp, ) task = compilation_tasks.make_compilation_task( diff --git a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py index af958b84d9..03cd77c2f8 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py +++ b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py @@ -76,8 +76,8 @@ def program_example(): def test_codegen(program_example): fencil, parameters = program_example module = gtfn_module.translate_program_cpu( - stages.CompilableProgramDef( - data=fencil, + stages.CompilableProgram( + definition=fencil, args=arguments.CompileTimeArgs.from_concrete(*parameters, **{"offset_provider": {}}), ) ) @@ -88,8 +88,8 @@ def test_codegen(program_example): def test_hash_and_diskcache(program_example, tmp_path): fencil, parameters = program_example - compilable_program = stages.CompilableProgramDef( - data=fencil, + compilable_program = stages.CompilableProgram( + definition=fencil, args=arguments.CompileTimeArgs.from_concrete(*parameters, **{"offset_provider": {}}), ) hash = fingerprinting.strict_fingerprinter(compilable_program) @@ -110,7 +110,7 @@ def test_hash_and_diskcache(program_example, tmp_path): # hash is different if program changes altered_program_id = copy.deepcopy(compilable_program) - altered_program_id.data.id = "example2" + altered_program_id.definition.id = "example2" assert fingerprinting.strict_fingerprinter( compilable_program ) != fingerprinting.strict_fingerprinter(altered_program_id) @@ -130,8 +130,8 @@ def test_hash_and_diskcache(program_example, tmp_path): def test_gtfn_file_cache(program_example): fencil, parameters = program_example - compilable_program = stages.CompilableProgramDef( - data=fencil, + compilable_program = stages.CompilableProgram( + definition=fencil, args=arguments.CompileTimeArgs.from_concrete(*parameters, **{"offset_provider": {}}), ) cached_gtfn_translation_step = gtfn.make_gtfn_compile_workflow( 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 13abf117de..f3cc628a84 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 @@ -203,7 +203,7 @@ def test_make_backend_accepts_external_workspace_with_external_mode(): ), ) - assert backend.external_workspace[core_defs.DeviceType.CPU] is workspace + assert backend.loading.external_workspace[core_defs.DeviceType.CPU] is workspace def test_make_backend_infers_external_mode_when_workspace_is_provided(): @@ -214,10 +214,10 @@ def test_make_backend_infers_external_mode_when_workspace_is_provided(): ) assert ( - backend.executor.translation.step.auto_optimize_args["transient_memory_mode"] + backend.backend.translation.step.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.EXTERNAL ) - assert backend.external_workspace[core_defs.DeviceType.CPU] is workspace + assert backend.loading.external_workspace[core_defs.DeviceType.CPU] is workspace def test_make_backend_warns_external_workspace_without_external_mode(): @@ -236,10 +236,10 @@ def test_make_backend_warns_external_workspace_without_external_mode(): # Explicit mode stays as requested by the caller; backend only warns. assert ( - backend.executor.translation.step.auto_optimize_args["transient_memory_mode"] + backend.backend.translation.step.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.POOL ) - assert backend.external_workspace[core_defs.DeviceType.CPU] is workspace + assert backend.loading.external_workspace[core_defs.DeviceType.CPU] is workspace def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): @@ -251,14 +251,14 @@ def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): cfg, translation=functools.partial(dace_wf_factory.make_dace_translator, use_metrics=False) ) - translator = backend.executor.translation.step + translator = backend.backend.translation.step assert translator.use_metrics is False assert ( translator.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.EXTERNAL ) - assert backend.external_workspace is cfg.external_workspace - assert backend.executor.compilation.bind_func_name == cfg.bind_func_name + assert backend.loading.external_workspace is cfg.external_workspace + assert backend.backend.compilation.bind_func_name == cfg.bind_func_name def test_make_toolchain_rejects_derived_optimization_args(): @@ -272,11 +272,11 @@ def test_make_toolchain_rejects_derived_optimization_args(): def test_make_toolchain_uncached_translation(): - backend = dace_wf_backend.make_dace_toolchain( + toolchain = dace_wf_backend.make_dace_toolchain( dace_wf_factory.DaCeConfig(cached_translation=False) ) - assert isinstance(backend.executor.translation, dace_wf_translation.DaCeTranslator) + assert isinstance(toolchain.backend.translation, dace_wf_translation.DaCeTranslator) def test_make_dace_backend_is_deprecated(): @@ -310,12 +310,12 @@ def test_make_dace_backend_is_deprecated(): # distinct `functools.partial` objects, so compare what they wrap. assert deprecated.name == toolchain.name assert deprecated.allocator == toolchain.allocator - assert deprecated.external_workspace is toolchain.external_workspace - assert deprecated.executor.translation.step == toolchain.executor.translation.step - assert deprecated.executor.translation.cache.path == toolchain.executor.translation.cache.path - assert deprecated.executor.bindings.func is toolchain.executor.bindings.func - assert deprecated.executor.bindings.keywords == toolchain.executor.bindings.keywords - assert deprecated.executor.compilation == toolchain.executor.compilation + assert deprecated.loading.external_workspace is toolchain.loading.external_workspace + assert deprecated.backend.translation.step == toolchain.backend.translation.step + assert deprecated.backend.translation.cache.path == toolchain.backend.translation.cache.path + assert deprecated.backend.bindings.func is toolchain.backend.bindings.func + assert deprecated.backend.bindings.keywords == toolchain.backend.bindings.keywords + assert deprecated.backend.compilation == toolchain.backend.compilation def test_translator_rejects_derived_optimization_args_on_every_route(): @@ -328,7 +328,7 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) - translator = dace_wf_backend.run_dace_cpu.executor.translation.step + translator = dace_wf_backend.run_dace_cpu.backend.translation.step with pytest.raises(ValueError, match="cannot be overridden"): dataclasses.replace(translator, auto_optimize_args={"constant_symbols": {}}) @@ -343,8 +343,8 @@ def test_step_builders_reach_all_step_settings(): ), ) - assert toolchain.executor.translation.step.disable_itir_transforms is True - assert toolchain.executor.compilation.add_gpu_trace_markers is True + assert toolchain.backend.translation.step.disable_itir_transforms is True + assert toolchain.backend.compilation.add_gpu_trace_markers is True def test_unused_optimization_args_warning_points_at_the_caller(): @@ -449,9 +449,9 @@ def testee(a: cases.IField, b: cases.IField, out: cases.IField): out = cases.allocate(test_case, testee, "out")() captured_sdfg: dace.SDFG | None = None - translation_step = custom_backend.executor.translation.step + translation_step = custom_backend.backend.translation.step - def mocked_translator(inp: stages.CompilableProgramDef) -> dace.SDFG: + def mocked_translator(inp: stages.CompilableProgram) -> dace.SDFG: nonlocal captured_sdfg result = translation_step(inp) captured_sdfg = dace.SDFG.from_json(result.source_code) @@ -459,8 +459,8 @@ def mocked_translator(inp: stages.CompilableProgramDef) -> dace.SDFG: custom_backend = dataclasses.replace( custom_backend, - executor=dataclasses.replace( - custom_backend.executor, + backend=dataclasses.replace( + custom_backend.backend, translation=mocked_translator, ), ) @@ -499,7 +499,7 @@ def no_op_top_level_map_processing(*, sdfg: dace.SDFG, **kwargs) -> dace.SDFG: assert all( tdesc.lifetime == dace.AllocationLifetime.External for _, tdesc in transient_arrays ) - # load_artifact injected the backend-level workspace onto the program wrapper. + # The loading step injected the toolchain-level workspace onto the program wrapper. assert ( decorated_program._fun.external_workspace[device_type] is external_workspace[device_type] diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py index 87e212afc9..7fa373f665 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_translation.py @@ -425,7 +425,7 @@ def test_generate_sdfg_async_call_multi_state( assert not _are_streams_synchronized(sdfg) -def _make_simple_field_operator_compilable_program() -> otf_workflow.ConcreteArtifact: +def _make_simple_field_operator_compilable_program() -> otf_workflow.ProgramWithArgs: """Return a compilable program wrapping a minimal GTIR field operator.""" ir = itir.Program( id="simple_field_operator", @@ -443,8 +443,8 @@ def _make_simple_field_operator_compilable_program() -> otf_workflow.ConcreteArt ), ], ) - return otf_workflow.ConcreteArtifact( - data=ir, + return otf_workflow.ProgramWithArgs( + definition=ir, args=otf_arguments.CompileTimeArgs( args=tuple(param.type for param in ir.params), kwargs={}, diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py index 70ef246bce..3265af0841 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py @@ -38,15 +38,15 @@ def test_make_gtfn_toolchain_device(): gpu_version = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(gpu=True)) assert cpu_version.name == "run_gtfn_cpu" - assert isinstance(cpu_version.executor.translation, workflow.CachedStep) - assert cpu_version.executor.translation.step.device_type is core_defs.DeviceType.CPU + assert isinstance(cpu_version.backend.translation, workflow.CachedStep) + assert cpu_version.backend.translation.step.device_type is core_defs.DeviceType.CPU assert gpu_version.name == "run_gtfn_gpu" - assert isinstance(gpu_version.executor.translation, workflow.CachedStep) - assert gpu_version.executor.translation.step.device_type is core_defs.DeviceType.CUDA + assert isinstance(gpu_version.backend.translation, workflow.CachedStep) + assert gpu_version.backend.translation.step.device_type is core_defs.DeviceType.CUDA # The compilation step now also carries device_type so it can stamp the artifact. - assert cpu_version.executor.compilation.device_type is core_defs.DeviceType.CPU - assert gpu_version.executor.compilation.device_type is core_defs.DeviceType.CUDA + assert cpu_version.backend.compilation.device_type is core_defs.DeviceType.CPU + assert gpu_version.backend.compilation.device_type is core_defs.DeviceType.CUDA assert custom_layout_allocators.is_field_allocator_for( cpu_version.allocator, core_defs.DeviceType.CPU @@ -62,9 +62,9 @@ def test_make_gtfn_toolchain_build_cache_config(monkeypatch): monkeypatch.setattr(config, "BUILD_CACHE_LIFETIME", config.BuildCacheLifetime.PERSISTENT) persistent_version = gtfn.make_gtfn_toolchain() - assert session_version.executor.compilation.cache_lifetime is config.BuildCacheLifetime.SESSION + assert session_version.backend.compilation.cache_lifetime is config.BuildCacheLifetime.SESSION assert ( - persistent_version.executor.compilation.cache_lifetime + persistent_version.backend.compilation.cache_lifetime is config.BuildCacheLifetime.PERSISTENT ) @@ -76,11 +76,11 @@ def test_make_gtfn_toolchain_build_type_config(monkeypatch): min_size_version = gtfn.make_gtfn_toolchain() assert ( - release_version.executor.compilation.builder_factory.cmake_build_type + release_version.backend.compilation.builder_factory.cmake_build_type is config.CMakeBuildType.RELEASE ) assert ( - min_size_version.executor.compilation.builder_factory.cmake_build_type + min_size_version.backend.compilation.builder_factory.cmake_build_type is config.CMakeBuildType.MIN_SIZE_REL ) @@ -98,8 +98,8 @@ def test_cmake_build_type_changes_build_folder(monkeypatch, tmp_path): monkeypatch.setattr(config, "CMAKE_BUILD_TYPE", config.CMakeBuildType.DEBUG) debug_version = gtfn.make_gtfn_toolchain() - release_compiler = release_version.executor.compilation - debug_compiler = debug_version.executor.compilation + release_compiler = release_version.backend.compilation + debug_compiler = debug_version.backend.compilation build_context_ids: list[str] = [] @@ -147,11 +147,11 @@ def test_step_builder_partial_keeps_config_settings(): ), ) - translation = toolchain.executor.translation + translation = toolchain.backend.translation assert isinstance(translation, workflow.CachedStep) assert translation.step.enable_itir_transforms is False assert translation.step.device_type is cfg.device_type - compilation = toolchain.executor.compilation + compilation = toolchain.backend.compilation assert compilation.device_type is cfg.device_type assert compilation.builder_factory.cmake_extra_flags == ["-DEXTRA=ON"] assert compilation.builder_factory.cmake_build_type is config.CMakeBuildType.DEBUG @@ -165,14 +165,14 @@ def test_custom_step_builder_output_is_cached(): toolchain = gtfn.make_gtfn_toolchain(translation=lambda cfg: custom_step) - assert isinstance(toolchain.executor.translation, workflow.CachedStep) - assert toolchain.executor.translation.step is custom_step + assert isinstance(toolchain.backend.translation, workflow.CachedStep) + assert toolchain.backend.translation.step is custom_step def test_uncached_translation(): toolchain = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(cached_translation=False)) - assert isinstance(toolchain.executor.translation, gtfn_module.GTFNTranslationStep) + assert isinstance(toolchain.backend.translation, gtfn_module.GTFNTranslationStep) def test_step_builder_cannot_override_config_setting(): diff --git a/typing_tests/test_next.yaml b/typing_tests/test_next.yaml index 5db040f8df..a743f0401f 100644 --- a/typing_tests/test_next.yaml +++ b/typing_tests/test_next.yaml @@ -211,7 +211,7 @@ 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.Toolchain | None) -> None: _ = foo.with_backend(backend) - case: with_backend_scanop @@ -227,7 +227,7 @@ ) -> float: return carry + val - def somescanop_with_backend(backend: gtx.typing.Backend | None) -> None: + def somescanop_with_backend(backend: gtx.typing.Toolchain | None) -> None: _ = somescanop.with_backend(backend) - case: with_backend_program @@ -251,7 +251,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.Toolchain | None) -> None: _ = foo_prg.with_backend(backend) - case: astype_return_type From 1a1abd99af382a1e63843a8d89aa3fb0bb5ee580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 18:28:46 +0100 Subject: [PATCH 02/10] refactor[next]: make Backend abstract with a CompiledBackend kind and an internal Toolchain Rework the root object after review: the user-facing object keeps the name `Backend` (`gtx.typing.Backend` again), but it no longer carries the frontend transforms. - `backend.Backend` is an abstract base with `name` and `allocator` (instantiating it raises `TypeError`). - `backend.CompiledBackend(Backend)` adds `compiler` (formerly `Toolchain.backend` / `Backend.executor`) and `loader` (formerly `Toolchain.loading`), and provides `__gt_allocator__`. - `backend.Toolchain` becomes internal: the global frontend (`DEFAULT_TRANSFORMS`) composed with a `CompiledBackend`. The compiled-programs pool holds one, `FieldOperatorFromFoast` and the iterator runtime build one for their one-shot compiles. - Programs and operators dispatch on the backend kind in one helper; objects that are not backends are rejected when they are created. - The frontend is global, so `Program`/`FieldOperator` always lower with `DEFAULT_TRANSFORMS`; `roundtrip.gtir` drops its own, identical `Transforms`. - `compile` is no longer a backend method, so the opaque "customized compile" path of `make_compilation_task` is deleted. Tests: the compilation guards in `test_compiled_program.py` swapped `program.backend` after the pool was created and therefore guarded nothing; they now replace the pool's toolchain (`_forbid_compilation`), with a test proving the guard raises. Test doubles wrap `compiler` instead of overriding `compile`. --- src/gt4py/next/backend.py | 101 +++++++++++---- src/gt4py/next/config.py | 9 +- src/gt4py/next/ffront/decorator.py | 113 ++++++++++------- src/gt4py/next/iterator/runtime.py | 9 +- src/gt4py/next/otf/artifacts.py | 10 +- src/gt4py/next/otf/compilation_tasks.py | 39 ++---- src/gt4py/next/otf/compiled_program.py | 16 ++- .../runners/dace/program.py | 9 +- .../runners/dace/workflow/backend.py | 11 +- .../runners/double_roundtrip.py | 5 +- .../next/program_processors/runners/gtfn.py | 7 +- .../program_processors/runners/roundtrip.py | 32 ++--- src/gt4py/next/typing.py | 4 +- .../benchmarks/benchmark_program_call.py | 10 +- tests/next_tests/definitions.py | 1 - tests/next_tests/integration_tests/cases.py | 10 +- .../integration_tests/cases_utils.py | 34 ++---- ..._write_back_buffer_elimination_lowering.py | 4 +- .../ffront_tests/test_compiled_program.py | 106 ++++++++++------ .../ffront_tests/test_decorator.py | 6 +- .../test_math_builtin_execution.py | 2 +- .../instrumentation_tests/test_hooks.py | 6 +- .../ffront_tests/test_ffront_fvm_nabla.py | 10 +- .../iterator_tests/test_vertical_advection.py | 2 +- tests/next_tests/unit_tests/conftest.py | 2 +- .../ffront_tests/test_decorator_dispatch.py | 115 ++++++++++++++++++ .../otf_tests/test_compiled_program.py | 2 +- .../unit_tests/otf_tests/test_runners.py | 54 ++------ .../dace_tests/test_dace_backend.py | 42 +++---- .../runners_tests/test_gtfn.py | 34 +++--- tests/next_tests/unit_tests/test_backend.py | 111 +++++++++++++++++ typing_tests/test_next.yaml | 6 +- 32 files changed, 598 insertions(+), 324 deletions(-) create mode 100644 tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py create mode 100644 tests/next_tests/unit_tests/test_backend.py diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index fb649bf28f..e2152c37a3 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -9,10 +9,10 @@ from __future__ import annotations import dataclasses -from typing import Callable, Generic +from typing import Callable from gt4py._core import definitions as core_defs -from gt4py.next import config, custom_layout_allocators as next_allocators +from gt4py.next import config, constructors, custom_layout_allocators as next_allocators from gt4py.next.ffront import ( foast_to_gtir, foast_to_past, @@ -141,41 +141,90 @@ def step_order(self, inp: stages.ConcreteProgramDef) -> list[str]: @dataclasses.dataclass(frozen=True) -class Toolchain(Generic[core_defs.DeviceTypeT]): +class Backend: """ - Complete pipeline from a program definition to an executable program. - - The `frontend` workflow transforms any supported program definition into a - `CompilableProgram`, which the `backend` workflow then compiles into a - loadable compilation artifact. The `loading` step turns that artifact into a - directly-callable program; toolchains needing to inject backend-specific - runtime data supply their own step here. The `allocator` describes the - device the compiled program expects its buffers on. + Abstract base of the objects passed as `backend=` to programs and operators. + + 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`. + + Attributes: + name: Human-readable label used in metrics, logs and diagnostics. It is + expected to be unique among the backends used in a process; backends + sharing a name are reported under the same label. gt4py does not use + it to identify a backend: not as a cache key and not in fingerprints. + Code that needs the kind of a backend should check its type, not its + name. + allocator: Allocates the buffers of fields used with this backend. """ name: str - backend: workflow.Workflow[stages.CompilableProgram, artifacts.CompilationArtifact] - allocator: next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] - frontend: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgram] + allocator: constructors.Allocator + + def __post_init__(self) -> None: + if type(self) is Backend: + raise TypeError( + "'Backend' is abstract: instantiate a concrete kind such as 'CompiledBackend'." + ) + + +@dataclasses.dataclass(frozen=True) +class CompiledBackend(Backend): + """ + A backend that compiles programs before running them. + + Programs are lowered by the (global) frontend to a `CompilableProgram`, turned + into a loadable `CompilationArtifact` by `compiler` (possibly in a worker + process, see `config.BuildJobsMode`), and made directly callable by `loader` + (always in the calling process). Backends needing backend-specific runtime + data in the loaded program supply their own `loader`. Customize either step + with `dataclasses.replace`. + + Attributes: + allocator: The field buffer allocator for the device the compiled + programs expect their buffers on. + compiler: Compiles a lowered program into a loadable artifact. + loader: Loads an artifact into a directly-callable program. + """ + + allocator: next_allocators.FieldBufferAllocatorProtocol + compiler: workflow.Workflow[stages.CompilableProgram, artifacts.CompilationArtifact] # A plain `Callable`, not `workflow.Workflow`: the protocol names its - # parameter `inp`, which would force every loading step to use that name. - loading: Callable[[artifacts.CompilationArtifact], artifacts.ExecutableProgram] = ( + # parameter `inp`, which would force every loader to use that name. + loader: Callable[[artifacts.CompilationArtifact], artifacts.ExecutableProgram] = ( dataclasses.field(default=artifacts.load_artifact) ) + @property + def __gt_allocator__(self) -> next_allocators.FieldBufferAllocatorProtocol: + return self.allocator + + +@dataclasses.dataclass(frozen=True) +class Toolchain: + """ + Internal: the complete route from a program definition to an executable program. + + Composes the frontend, which transforms any supported program definition into + a `CompilableProgram`, with a compiled backend, whose `compiler` turns it into + a compilation artifact and whose `loader` makes that callable. Not part of the + public API: gt4py builds it where a compilation happens. + """ + + backend: CompiledBackend + frontend: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgram] = ( + DEFAULT_TRANSFORMS + ) + def compile( - self, program: stages.IRDefinitionT, compile_time_args: arguments.CompileTimeArgs + self, definition: stages.IRDefinitionT, compile_time_args: arguments.CompileTimeArgs ) -> artifacts.ExecutableProgram: - artifact = self.backend( - self.frontend(stages.ConcreteProgramDef(definition=program, args=compile_time_args)) + """Lower, compile and load `definition` in the calling thread.""" + compilable = self.frontend( + stages.ConcreteProgramDef(definition=definition, args=compile_time_args) ) - return self.loading(artifact) - - @property - def __gt_allocator__( - self, - ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: - return self.allocator + return self.backend.loader(self.backend.compiler(compilable)) @dataclasses.dataclass(frozen=True) diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index 25ebddb744..1b4e04cf77 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -48,11 +48,10 @@ class BuildJobsMode(enum.Enum): #: Run compilation in a ``ThreadPoolExecutor``. THREAD = "thread" #: Run compilation in a ``ProcessPoolExecutor`` with the ``spawn`` start - #: method. Requires the toolchain's ``backend`` pipeline to be stdlib-picklable - #: (standard runners and factory-constructed variants are) and to return a - #: picklable ``CompilationArtifact``; backends that don't qualify (or that - #: customize ``Toolchain.compile``) are compiled in the calling thread - #: instead, with a warning. + #: method. Requires the backend's ``compiler`` to be stdlib-picklable + #: (standard runners and builder-constructed variants are) and to return a + #: picklable ``CompilationArtifact``; backends that don't qualify are + #: compiled in the calling thread instead, with a warning. PROCESS = "process" diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 92f3ceabc0..978a120ca8 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -50,7 +50,40 @@ from gt4py.next.type_system import type_info, type_specifications as ts, type_translation -DEFAULT_BACKEND: next_backend.Toolchain | None = None +DEFAULT_BACKEND: next_backend.Backend | None = None + + +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): + raise TypeError( + f"Expected a 'gt4py.next.backend.Backend' (or None for embedded execution)," + f" got '{type(backend).__name__}'." + ) + + +def _compiled_backend_or_none( + backend: next_backend.Backend | None, +) -> next_backend.CompiledBackend | None: + """ + Dispatch on the kind of `backend`. + + Returns: + The compiled backend to run on, or `None` for embedded execution. + + Raises: + TypeError: If `backend` is a `Backend` of a kind that cannot run programs. + """ + match backend: + case next_backend.CompiledBackend(): + return backend + case 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." + ) ProgramCallMetricsCollector = metrics.make_collector( @@ -96,7 +129,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.Toolchain] = dataclasses.field( + backend: Optional[next_backend.Backend] = dataclasses.field( metadata=utils.gt4py_metadata(fingerprint=False) ) compilation_options: options.CompilationOptions @@ -104,7 +137,7 @@ class _CompilableGTEntryPointMixin(Generic[ffront_stages.DSLDefinitionT]): @abc.abstractmethod def __gt_type__(self) -> ts.CallableType: ... - def with_backend(self, backend: next_backend.Toolchain | None) -> Self: + def with_backend(self, backend: next_backend.Backend | None) -> Self: return dataclasses.replace(self, backend=backend) def with_compilation_options( @@ -131,7 +164,8 @@ def _compiled_programs(self) -> compiled_program.CompiledProgramsPool: def _make_compiled_programs_pool( self, static_params: Sequence[str], static_domains: bool ) -> compiled_program.CompiledProgramsPool: - if self.backend is None or self.backend == eve.NOTHING: + compiled_backend = _compiled_backend_or_none(self.backend) + if compiled_backend is None: raise RuntimeError("Cannot compile a program without backend.") program_type = ffront_type_info.type_in_program_context(self.__gt_type__()) @@ -151,7 +185,7 @@ def _make_compiled_programs_pool( ) return compiled_program.CompiledProgramsPool( - backend=self.backend, + toolchain=next_backend.Toolchain(compiled_backend), definition_stage=self.definition_stage, program_type=program_type, argument_descriptor_mapping=argument_descriptor_mapping, @@ -233,7 +267,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 to be used for code generation. + backend: The backend the program runs on (`None` for embedded execution). 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. @@ -246,7 +280,7 @@ class Program(_CompilableGTEntryPointMixin[ffront_stages.DSLProgramDef]): def from_function( cls, definition: types.FunctionType, - backend: next_backend.Toolchain | None, + backend: next_backend.Backend | None, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Program: @@ -263,6 +297,7 @@ def __gt_type__(self) -> ts_ffront.ProgramType: # TODO(ricoh): linting should become optional, up to the backend. def __post_init__(self) -> None: + _check_backend(self.backend) no_args_past = workflow.ProgramWithArgs(self.past_stage, arguments.CompileTimeArgs.empty()) _ = self._frontend_transforms.past_lint(no_args_past).definition @@ -274,10 +309,10 @@ def __name__(self) -> str: def __gt_allocator__( self, ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: - if self.backend: - return self.backend.__gt_allocator__ - else: + compiled_backend = _compiled_backend_or_none(self.backend) + if compiled_backend is None: raise RuntimeError(f"Program '{self}' does not have a backend set.") + return compiled_backend.__gt_allocator__ @property def definition(self) -> types.FunctionType: @@ -293,12 +328,8 @@ def past_stage(self) -> ffront_stages.PASTProgramDef: @property def _frontend_transforms(self) -> next_backend.Transforms: - if self.backend is None: - return next_backend.DEFAULT_TRANSFORMS - # TODO(tehrengruber): This class relies heavily on `self.backend.frontend` being - # a `next_backend.Transforms`, but the backend type annotation does not reflect that. - assert isinstance(self.backend.frontend, next_backend.Transforms) - return self.backend.frontend + # The frontend is global: it is not part of any backend (ADR 0029). + return next_backend.DEFAULT_TRANSFORMS @functools.cached_property def _all_closure_vars(self) -> dict[str, Any]: @@ -398,7 +429,7 @@ def __call__( kwarg_types={k: type_translation.from_value(v) for k, v in kwargs.items()}, ) - if self.backend is not None: + if _compiled_backend_or_none(self.backend) is not None: self._compiled_programs( *args, **kwargs, offset_provider=offset_provider, enable_jit=enable_jit ) @@ -503,7 +534,7 @@ def program(definition: Callable) -> Program: ... @typing.overload def program( *, - backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Callable[[Callable], Program]: ... @@ -513,7 +544,7 @@ def program( definition: Callable | None = None, *, # `NOTHING` -> default backend, `None` -> no backend (embedded execution) - backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> Program | Callable[[Callable], Program]: @@ -544,7 +575,7 @@ def program_inner(definition: Callable) -> Program: program = Program.from_function( definition, backend=typing.cast( - next_backend.Toolchain | None, + next_backend.Backend | None, DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type=grid_type, @@ -581,7 +612,7 @@ class FieldOperator(_CompilableGTEntryPointMixin[ffront_stages.DSLFieldOperatorD def from_function( cls, definition: types.FunctionType, - backend: Optional[next_backend.Toolchain], + backend: Optional[next_backend.Backend], grid_type: Optional[common.GridType] = None, *, operator_node_cls: type[foast.OperatorNode] = foast.FieldOperator, @@ -602,6 +633,7 @@ def from_function( # TODO(ricoh): linting should become optional, up to the backend. def __post_init__(self) -> None: """This ensures that DSL linting occurs at decoration time.""" + _check_backend(self.backend) _ = self.foast_stage @functools.cached_property @@ -622,12 +654,8 @@ def definition(self) -> types.FunctionType: @property def _frontend_transforms(self) -> next_backend.Transforms: - if self.backend is None: - return next_backend.DEFAULT_TRANSFORMS - # TODO(tehrengruber): This class relies heavily on `self.backend.frontend` being - # a `next_backend.Transforms`, but the backend type annotation does not reflect that. - assert isinstance(self.backend.frontend, next_backend.Transforms) - return self.backend.frontend + # The frontend is global: it is not part of any backend (ADR 0029). + return next_backend.DEFAULT_TRANSFORMS def __gt_type__(self) -> ts.CallableType: type_ = self.foast_stage.foast_node.type @@ -639,9 +667,7 @@ def with_grid_type(self, grid_type: common.GridType) -> FieldOperator: self, definition_stage=dataclasses.replace(self.definition_stage, grid_type=grid_type) ) - # TODO(tehrengruber): We can not use transforms from `self.backend` since this can be - # a different backend than the one of the program that calls this field operator. Just use - # the hard-coded lowering until this is cleaned up. + # The lowering does not depend on the backend: the frontend is global (ADR 0029). def __gt_itir__(self) -> itir.FunctionDefinition: return foast_to_gtir.foast_to_gtir(self.foast_stage) @@ -653,7 +679,10 @@ 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 next_embedded.context.within_valid_context() + and _compiled_backend_or_none(self.backend) is not None + ): # non embedded execution offset_provider = {**kwargs.pop("offset_provider", {})} if "out" not in kwargs: @@ -720,8 +749,10 @@ class FieldOperatorFromFoast(FieldOperator): @override def __call__(self, *args: Any, **kwargs: Any) -> Any: - assert self.backend is not None - compiled_fo = self.backend.compile( + compiled_backend = _compiled_backend_or_none(self.backend) + if compiled_backend is None: + raise RuntimeError("Cannot compile a field operator without backend.") + compiled_fo = next_backend.Toolchain(compiled_backend).compile( self.foast_stage, arguments.CompileTimeArgs.from_concrete(*args, **kwargs) ) return compiled_fo(*args, **kwargs) @@ -731,7 +762,7 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any: def field_operator( definition: Callable, *, - backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, ) -> FieldOperator: ... @@ -739,7 +770,7 @@ def field_operator( @typing.overload def field_operator( *, - backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, ) -> Callable[[Callable], FieldOperator]: ... @@ -747,7 +778,7 @@ def field_operator( def field_operator( definition: Callable | None = None, *, - backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, **compilation_options: Unpack[options.CompilationOptionsArgs], ) -> FieldOperator | Callable[[types.FunctionType], FieldOperator]: @@ -772,7 +803,7 @@ def field_operator_inner(definition: Callable) -> FieldOperator: return FieldOperator.from_function( definition, typing.cast( - next_backend.Toolchain | None, + next_backend.Backend | None, DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type, @@ -789,7 +820,7 @@ def scan_operator( axis: common.Dimension, forward: bool = True, init: core_defs.Scalar = 0.0, - backend: next_backend.Toolchain | eve.NothingType | None, + backend: next_backend.Backend | eve.NothingType | None, grid_type: common.GridType | None, ) -> FieldOperator: ... @@ -816,7 +847,7 @@ def scan_operator( axis: common.Dimension, forward: bool = True, init: core_defs.Scalar = 0.0, - backend: next_backend.Toolchain | eve.NothingType | None, + backend: next_backend.Backend | eve.NothingType | None, grid_type: common.GridType | None, ) -> Callable[[Callable], FieldOperator]: ... @@ -827,7 +858,7 @@ def scan_operator( axis: common.Dimension, forward: bool = True, init: core_defs.Scalar = 0.0, - backend: next_backend.Toolchain | eve.NothingType | None = eve.NOTHING, + backend: next_backend.Backend | eve.NothingType | None = eve.NOTHING, grid_type: common.GridType | None = None, ) -> FieldOperator | Callable[[Callable], FieldOperator]: """ @@ -864,7 +895,7 @@ def scan_operator_inner(definition: Callable) -> FieldOperator: return FieldOperator.from_function( definition, typing.cast( - next_backend.Toolchain | None, + next_backend.Backend | None, 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 4907f1d7f4..2cf5be6528 100644 --- a/src/gt4py/next/iterator/runtime.py +++ b/src/gt4py/next/iterator/runtime.py @@ -74,7 +74,7 @@ def itir(self, *args): def __call__( self, *args, - backend: Optional[next_backend.Toolchain | program_formatter.ProgramFormatter] = None, + backend: Optional[next_backend.CompiledBackend | program_formatter.ProgramFormatter] = None, offset_provider=None, column_axis=None, ): @@ -87,9 +87,8 @@ def __call__( # 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.Toolchain): - assert isinstance(backend, next_backend.Toolchain) - compiled_program = backend.compile( + if isinstance(backend, next_backend.CompiledBackend): + compiled_program = next_backend.Toolchain(backend).compile( itir_node, arguments.CompileTimeArgs.from_concrete( *args, offset_provider=offset_provider, column_axis=column_axis @@ -102,7 +101,7 @@ def __call__( ) else: raise ValueError( - "Backend must be a 'gt4py.next.backend.Toolchain' or " + "Backend must be a 'gt4py.next.backend.CompiledBackend' or " "'gt4py.next.program_formatter.ProgramFormatter'." ) else: diff --git a/src/gt4py/next/otf/artifacts.py b/src/gt4py/next/otf/artifacts.py index 5ee89a989f..f3f647f365 100644 --- a/src/gt4py/next/otf/artifacts.py +++ b/src/gt4py/next/otf/artifacts.py @@ -179,7 +179,7 @@ class CompilationArtifact(Protocol): arguments. The one current exception is ``RoundtripArtifact`` when it is configured - with a ``dispatch_backend``: that field holds a ``Toolchain`` reference + with a ``dispatch_backend``: that field holds a ``CompiledBackend`` reference whose role belongs at the runner / load-time seam, not in the artifact itself. """ @@ -191,12 +191,12 @@ def load_artifact(artifact: CompilationArtifact) -> ExecutableProgram: """ Load a compilation artifact into a directly-callable program. - This is the default loading step of a `Toolchain`. Toolchains that need to - inject backend-specific runtime data into the loaded program supply their - own step instead of overriding a method. + This is the default `CompiledBackend.loader`. Backends that need to inject + backend-specific runtime data into the loaded program supply their own + loader instead of overriding a method. Args: - artifact: The artifact produced by the toolchain's compile pipeline. + artifact: The artifact produced by the backend's compiler. Returns: The loaded, directly-callable program. diff --git a/src/gt4py/next/otf/compilation_tasks.py b/src/gt4py/next/otf/compilation_tasks.py index 0a59c39792..1c45bf987b 100644 --- a/src/gt4py/next/otf/compilation_tasks.py +++ b/src/gt4py/next/otf/compilation_tasks.py @@ -6,7 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -"""Preparation of runner-ready compilation tasks from a backend and a program definition. +"""Preparation of runner-ready compilation tasks from a toolchain and a program definition. This is the layer between the compiled-programs pool and the compilation runners: it decides what runs main-side (frontend lowering, since the raw @@ -29,7 +29,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import backend as gtx_backend, common, constructors -from gt4py.next.otf import arguments, artifacts, runners, stages +from gt4py.next.otf import arguments, runners, stages def _connectivity_from_file( @@ -123,41 +123,16 @@ def _offset_provider_with_file_refs( } -@dataclasses.dataclass(frozen=True) -class _PreloadedArtifact: - """Wraps the already-loaded program of a backend with a customized ``compile``.""" - - program: artifacts.ExecutableProgram - - def load(self) -> artifacts.ExecutableProgram: - return self.program - - def make_compilation_task( - backend: gtx_backend.Toolchain, + toolchain: gtx_backend.Toolchain, definition_stage: Any, compile_time_args: arguments.CompileTimeArgs, ) -> runners.CompilationTask: - """Prepare the compilation of `definition_stage` with `backend` as a task for a runner.""" - name = getattr(backend, "name", type(backend).__name__) - if getattr(type(backend), "compile", None) is not gtx_backend.Toolchain.compile: - # A customized `compile` is opaque: it cannot be decomposed into the - # standard frontend/backend workflow (and yields an already-loaded - # program instead of an artifact), so the executor closes over - # everything and ignores the compilable. - return runners.CompilationTask( - name=name, - construct_compilable=lambda with_refs: None, - executor=lambda _: _PreloadedArtifact( - backend.compile(definition_stage, compile_time_args=compile_time_args) - ), - no_offload_reason="it does not use the standard compilation workflow" - " (customized 'compile')", - ) + """Prepare the compilation of `definition_stage` with `toolchain` as a task for a runner.""" # Frontend lowering happens here, main-side: decorators rebind the user's # function module attribute, so the raw `types.FunctionType` must not cross # a process boundary; the lowered `CompilableProgram` is pickle-safe. - compilable = backend.frontend( + compilable = toolchain.frontend( stages.ConcreteProgramDef(definition=definition_stage, args=compile_time_args) ) @@ -176,5 +151,7 @@ def construct_compilable(with_refs: bool) -> stages.CompilableProgram: ) return runners.CompilationTask( - name=name, construct_compilable=construct_compilable, executor=backend.backend + name=toolchain.backend.name, + construct_compilable=construct_compilable, + executor=toolchain.backend.compiler, ) diff --git a/src/gt4py/next/otf/compiled_program.py b/src/gt4py/next/otf/compiled_program.py index 96a7d39308..936894ae0e 100644 --- a/src/gt4py/next/otf/compiled_program.py +++ b/src/gt4py/next/otf/compiled_program.py @@ -89,7 +89,7 @@ def metrics_source_key(pool: CompiledProgramsPool, key: CompiledProgramsKey) -> def compile_variant_hook( program_pool: CompiledProgramsPool, key: CompiledProgramsKey, - backend: gtx_backend.Toolchain, + backend: gtx_backend.CompiledBackend, argument_descriptors: ArgStaticDescriptorsByType, offset_provider: common.OffsetProviderType | common.OffsetProvider, ) -> None: @@ -350,7 +350,9 @@ class CompiledProgramsPool(Generic[ffront_stages.DSLDefinitionT]): to `compile` before it can be used. """ - backend: gtx_backend.Toolchain + #: The route used to compile the variants: the global frontend and the + #: program's compiled backend. + toolchain: gtx_backend.Toolchain definition_stage: ffront_stages.DSLDefinitionT # Note: This type can be incomplete, i.e. contain DeferredType, whenever the operator is a # scan operator. In the future it could also be the type of a generic program. @@ -368,6 +370,10 @@ class CompiledProgramsPool(Generic[ffront_stages.DSLDefinitionT]): CompiledProgramsKey, concurrent.futures.Future[artifacts.CompilationArtifact] ] = dataclasses.field(default_factory=dict, init=False) + @property + def backend(self) -> gtx_backend.CompiledBackend: + return self.toolchain.backend + @functools.cached_property def root(self) -> tuple[str, str]: result = (self.definition_stage.definition.__name__, self.backend.name) @@ -491,7 +497,7 @@ def _load_artifact( ) -> artifacts.ExecutableProgram: artifact = artifact_future.result() # re-raises errors from the compilation worker try: - return self.backend.loading(artifact) + return self.backend.loader(artifact) except Exception as e: raise RuntimeError( f"Failed to load the compiled program '{self.definition.__name__}'." @@ -692,7 +698,7 @@ def _compile_variant( runner = runners.get_default_runner() future = runner.submit( compilation_tasks.make_compilation_task( - self.backend, self.definition_stage, compile_time_args + self.toolchain, self.definition_stage, compile_time_args ) ) if future.done(): @@ -702,7 +708,7 @@ def _compile_variant( else: self._compilation_jobs[key] = future _ongoing_compilations[future] = ( - f"{self.definition_stage.definition.__name__} ({getattr(self.backend, 'name', type(self.backend).__name__)})" + f"{self.definition_stage.definition.__name__} ({self.backend.name})" ) # TODO(tehrengruber): Rework the interface to allow precompilation with compile time diff --git a/src/gt4py/next/program_processors/runners/dace/program.py b/src/gt4py/next/program_processors/runners/dace/program.py index abd88a7dad..2b9347e8f9 100644 --- a/src/gt4py/next/program_processors/runners/dace/program.py +++ b/src/gt4py/next/program_processors/runners/dace/program.py @@ -36,14 +36,17 @@ class Program(decorator.Program, dace.frontend.python.common.SDFGConvertible): ] = {} # symbolically defined def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: - if (self.backend is None) or "dace" not in self.backend.name.lower(): + if not ( + isinstance(self.backend, gtx_backend.CompiledBackend) + and "dace" in self.backend.name.lower() + ): raise ValueError("The SDFG can be generated only for the DaCe backend.") offset_provider: gtx_common.OffsetProvider = self.compilation_options.connectivities or {} column_axis = kwargs.get("column_axis", None) # TODO(ricoh): connectivity tables required here for now. - gtir_stage = typing.cast(gtx_backend.Transforms, self.backend.frontend).past_to_itir( + gtir_stage = self._frontend_transforms.past_to_itir( workflow.ProgramWithArgs( definition=self.past_stage, args=arguments.CompileTimeArgs( @@ -76,7 +79,7 @@ def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: gt4py_program_args=[p.type for p in program.params], ) - otf_workflow = self.backend.backend + otf_workflow = self.backend.compiler assert hasattr(otf_workflow, "translation") otf_workflow_translation = ( otf_workflow.translation.step diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py index 079ea0a9ae..5049a7f735 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -49,7 +49,7 @@ def make_dace_toolchain( translation: gtx_wfdfactory.DaCeTranslationBuilder = gtx_wfdfactory.make_dace_translator, bindings: gtx_wfdfactory.DaCeBindingsBuilder = gtx_wfdfactory.make_dace_bindings, compilation: gtx_wfdfactory.DaCeCompilationBuilder = gtx_wfdfactory.make_dace_compiler, -) -> backend.Toolchain: +) -> backend.CompiledBackend: """ Build a DaCe toolchain. @@ -67,14 +67,13 @@ def make_dace_toolchain( if cfg is None: cfg = gtx_wfdfactory.DaCeConfig() - return backend.Toolchain( + return backend.CompiledBackend( name=f"run_dace_{cfg.device_name}{'_opt' if cfg.auto_optimize else ''}{name_postfix}", - backend=gtx_wfdfactory.make_dace_compile_workflow( + compiler=gtx_wfdfactory.make_dace_compile_workflow( cfg, translation=translation, bindings=bindings, compilation=compilation ), allocator=cfg.make_allocator(), - frontend=backend.DEFAULT_TRANSFORMS, - loading=DaCeLoadingStep(cfg.external_workspace), + loader=DaCeLoadingStep(cfg.external_workspace), ) @@ -88,7 +87,7 @@ def make_dace_backend( use_metrics: bool = True, use_zero_origin: bool = False, use_max_domain_range_on_unstructured_shift: bool | None = None, -) -> backend.Toolchain: +) -> backend.CompiledBackend: """Customize the dace backend with the given configuration parameters. Deprecated: use `make_dace_toolchain` with a `DaCeConfig` for the shared diff --git a/src/gt4py/next/program_processors/runners/double_roundtrip.py b/src/gt4py/next/program_processors/runners/double_roundtrip.py index ef7681f685..ecb6917780 100644 --- a/src/gt4py/next/program_processors/runners/double_roundtrip.py +++ b/src/gt4py/next/program_processors/runners/double_roundtrip.py @@ -12,9 +12,8 @@ from gt4py.next.program_processors.runners import roundtrip -backend = next_backend.Toolchain( +backend = next_backend.CompiledBackend( name="double_roundtrip", - frontend=next_backend.DEFAULT_TRANSFORMS, - backend=roundtrip.Roundtrip(dispatch_backend=roundtrip.default, use_embedded=False), + compiler=roundtrip.Roundtrip(dispatch_backend=roundtrip.default, use_embedded=False), allocator=roundtrip.default.allocator, ) diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index 2d80dcbe66..2f00d16a64 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -287,7 +287,7 @@ def make_gtfn_toolchain( translation: GTFNTranslationBuilder = make_gtfn_translation, bindings: GTFNBindingsBuilder = make_gtfn_bindings, compilation: GTFNCompilationBuilder = make_gtfn_compiler, -) -> backend.Toolchain: +) -> backend.CompiledBackend: """ Build a GTFN toolchain. @@ -305,13 +305,12 @@ def make_gtfn_toolchain( if cfg is None: cfg = GTFNConfig() - return backend.Toolchain( + return backend.CompiledBackend( name=f"run_gtfn_{cfg.device_name}{name_postfix}", - backend=make_gtfn_compile_workflow( + compiler=make_gtfn_compile_workflow( cfg, translation=translation, bindings=bindings, compilation=compilation ), allocator=cfg.make_allocator(), - frontend=backend.DEFAULT_TRANSFORMS, ) diff --git a/src/gt4py/next/program_processors/runners/roundtrip.py b/src/gt4py/next/program_processors/runners/roundtrip.py index 4108eebbc7..7c84018c3d 100644 --- a/src/gt4py/next/program_processors/runners/roundtrip.py +++ b/src/gt4py/next/program_processors/runners/roundtrip.py @@ -25,7 +25,7 @@ config, custom_layout_allocators as next_allocators, ) -from gt4py.next.ffront import foast_to_gtir, foast_to_past, past_to_itir +from gt4py.next.ffront import foast_to_gtir from gt4py.next.iterator import ir as itir, transforms as itir_transforms from gt4py.next.otf import artifacts, stages, workflow from gt4py.next.type_system import type_info, type_specifications as ts @@ -216,7 +216,7 @@ class RoundtripArtifact: source_code: str entry_point_name: str column_axis: common.Dimension | None - dispatch_backend: next_backend.Toolchain | None + dispatch_backend: next_backend.CompiledBackend | None debug: bool def load(self) -> artifacts.ExecutableProgram: @@ -251,7 +251,7 @@ def decorated_fencil( class Roundtrip(workflow.Workflow[stages.CompilableProgram, RoundtripArtifact]): debug: Optional[bool] = None use_embedded: bool = True - dispatch_backend: Optional[next_backend.Toolchain] = None + dispatch_backend: Optional[next_backend.CompiledBackend] = None transforms: itir_transforms.GTIRTransform = itir_transforms.apply_common_transforms # type: ignore[assignment] # TODO(havogt): cleanup interface of `apply_common_transforms` def __call__(self, inp: stages.CompilableProgram) -> RoundtripArtifact: @@ -275,46 +275,36 @@ def __call__(self, inp: stages.CompilableProgram) -> RoundtripArtifact: # TODO(tehrengruber): introduce factory -default = next_backend.Toolchain( +default = next_backend.CompiledBackend( name="roundtrip", - backend=Roundtrip( + compiler=Roundtrip( transforms=functools.partial( itir_transforms.apply_common_transforms, extract_temporaries=False, ) ), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - frontend=next_backend.DEFAULT_TRANSFORMS, ) -with_temporaries = next_backend.Toolchain( +with_temporaries = next_backend.CompiledBackend( name="roundtrip_with_temporaries", - backend=Roundtrip( + compiler=Roundtrip( transforms=functools.partial( itir_transforms.apply_common_transforms, extract_temporaries=True, ) ), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - frontend=next_backend.DEFAULT_TRANSFORMS, ) -no_transforms = next_backend.Toolchain( +no_transforms = next_backend.CompiledBackend( name="roundtrip", - backend=Roundtrip(transforms=lambda o, *, offset_provider: o), + compiler=Roundtrip(transforms=lambda o, *, offset_provider: o), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - frontend=next_backend.DEFAULT_TRANSFORMS, ) -gtir = next_backend.Toolchain( +gtir = next_backend.CompiledBackend( name="roundtrip_gtir", - backend=Roundtrip(transforms=itir_transforms.apply_fieldview_transforms), # type: ignore[arg-type] # don't understand why mypy complains + compiler=Roundtrip(transforms=itir_transforms.apply_fieldview_transforms), # type: ignore[arg-type] # don't understand why mypy complains allocator=next_allocators.StandardCPUFieldBufferAllocator(), - frontend=next_backend.Transforms( - past_to_itir=past_to_itir.past_to_gtir_factory(), - foast_to_itir=foast_to_gtir.adapted_foast_to_gtir_factory(cached=True), - field_view_op_to_prog=foast_to_past.operator_to_program_factory( - foast_to_itir_step=foast_to_gtir.adapted_foast_to_gtir_factory() - ), - ), ) foast_to_gtir_step = foast_to_gtir.adapted_foast_to_gtir_factory(cached=True) diff --git a/src/gt4py/next/typing.py b/src/gt4py/next/typing.py index 9fccb71595..c8367bd64e 100644 --- a/src/gt4py/next/typing.py +++ b/src/gt4py/next/typing.py @@ -25,7 +25,7 @@ CompiledProgramsKey: TypeAlias = Annotated[compiled_program.CompiledProgramsKey, _ONLY_FOR_TYPING] -Toolchain: TypeAlias = Annotated[backend.Toolchain, _ONLY_FOR_TYPING] +Backend: TypeAlias = Annotated[backend.Backend, _ONLY_FOR_TYPING] Allocator: TypeAlias = Annotated[constructors.Allocator, _ONLY_FOR_TYPING] @@ -34,9 +34,9 @@ __all__ = [ "Allocator", + "Backend", "FieldOperator", "OffsetProvider", "Program", "Scalar", # from _core.definitions for convenience - "Toolchain", ] diff --git a/tests/next_tests/benchmarks/benchmark_program_call.py b/tests/next_tests/benchmarks/benchmark_program_call.py index ce0d05229b..166509e8f3 100644 --- a/tests/next_tests/benchmarks/benchmark_program_call.py +++ b/tests/next_tests/benchmarks/benchmark_program_call.py @@ -47,7 +47,7 @@ @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_const_no_args_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend ): @gtx.field_operator def const() -> gtx.Field[Dims[IDim], gtx.float64]: @@ -69,7 +69,7 @@ def const_no_args(out: gtx.Field[Dims[IDim], gtx.float64]): @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_copy_01_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend ): @gtx.field_operator def identity_fop( @@ -96,7 +96,7 @@ def copy_01_arg( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_horizontal_copy_01_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend ): @gtx.field_operator def identity_01_fop( @@ -143,7 +143,7 @@ def horizontal_copy_01_arg_program( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_horizontal_copy_05_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend ): @gtx.field_operator def identity_05_fop( @@ -202,7 +202,7 @@ def horizontal_copy_05_arg_program( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: b.name) def benchmark_horizontal_copy_25_arg_program( - benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Toolchain + benchmark: ptb_fixture.BenchmarkFixture, backend: gtx_typing.Backend ): @gtx.field_operator def identity_25_fop( diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 0f30cb6038..adf8aa6887 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -54,7 +54,6 @@ class ProgramBackendId(_PythonObjectIdMixin, str, enum.Enum): class EmbeddedDummyBackend: name: str allocator: constructors.Allocator - backend: Final = None numpy_execution = EmbeddedDummyBackend("EmbeddedNumPy", nd_array_field.np) diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index ac8435ce17..b5d99e2eb5 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -545,7 +545,7 @@ def cartesian_case_no_backend(): @pytest.fixture def cartesian_case( - exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Toolchain, + exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Backend, ): return Case.from_cartesian_grid_descriptor( simple_cartesian_grid(), @@ -566,7 +566,7 @@ def unstructured_case_no_backend(mesh_descriptor: MeshDescriptor): @pytest.fixture def unstructured_case( mesh_descriptor: MeshDescriptor, - exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Toolchain, + exec_alloc_descriptor: test_definitions.EmbeddedDummyBackend | next_backend.Backend, ): return Case.from_mesh_descriptor( mesh_descriptor, @@ -712,7 +712,7 @@ def get_default_data( class Case: """Parametrizable components for single feature integration tests.""" - backend: Optional[next_backend.Toolchain] + backend: Optional[next_backend.Backend] offset_provider: dict[str, common.Connectivity | gtx.Dimension] default_sizes: dict[gtx.Dimension, int] grid_type: common.GridType @@ -726,7 +726,7 @@ def as_field(self): def from_cartesian_grid_descriptor( cls, grid_descriptor: CartesianGridDescriptor, - backend: Optional[next_backend.Toolchain] = None, + backend: Optional[next_backend.Backend] = None, allocator: Optional[next_allocators.FieldBufferAllocatorFactoryProtocol] = None, ) -> Case: return cls( @@ -748,7 +748,7 @@ def from_cartesian_grid_descriptor( def from_mesh_descriptor( cls, mesh_descriptor: MeshDescriptor, - backend: Optional[next_backend.Toolchain] = None, + backend: Optional[next_backend.Backend] = None, allocator: Optional[next_allocators.FieldBufferAllocatorFactoryProtocol] = None, ) -> Case: return cls( diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index 3a0fc519bd..d996e9f309 100644 --- a/tests/next_tests/integration_tests/cases_utils.py +++ b/tests/next_tests/integration_tests/cases_utils.py @@ -13,6 +13,7 @@ regression tests. The ``cases`` framework builds on these; see ``cases.py``. """ +import dataclasses import types from typing import Any, Protocol, TypeVar @@ -51,38 +52,21 @@ ] -def _no_backend_executor(*args: Any, **kwargs: Any) -> None: - raise ValueError("No backend selected! Backend selection is mandatory in tests.") - - def _no_backend_allocator(*args: Any, **kwargs: Any) -> None: raise ValueError("No backend selected! Backend selection is mandatory in tests.") -class NoBackend(next_backend.Toolchain): - """Temporary default backend to not accidentally test the wrong backend.""" - - def __call__(self, program, *args, **kwargs) -> None: - raise ValueError("No backend selected! Backend selection is mandatory in tests.") - - def compile(self, program, compile_time_args): - raise ValueError("No backend selected! Backend selection is mandatory in tests.") +@dataclasses.dataclass(frozen=True) +class NoBackend(next_backend.Backend): + """ + Default backend in tests, to not accidentally test the wrong backend. - def __gt_allocator__( - self, - ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: - raise ValueError("No backend selected! Backend selection is mandatory in tests.") + It is neither a compiled nor an embedded backend, so programs and operators + can be created with it, but calling them raises a `TypeError`. + """ -no_backend = NoBackend( - name="no_backend", - backend=_no_backend_executor, - allocator=_no_backend_allocator, - # TODO(tehrengruber): We don't want any transformations, but since `decorator.FieldOperator` - # and `decorator.Program` unconditionally do linting on construction we need the - # transformations. When this is up to the backend we can remove this again. - frontend=next_backend.DEFAULT_TRANSFORMS, -) +no_backend = NoBackend(name="no_backend", allocator=_no_backend_allocator) @pytest.fixture( diff --git a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py index 741d8efff9..b163610b91 100644 --- a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py +++ b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_write_back_buffer_elimination_lowering.py @@ -119,10 +119,10 @@ def uncached_dace_cpu(): The cache stores the optimized SDFG, so a second run of these tests would replay it and never call the transformation. """ - compile_pipeline = gtx_dace.run_dace_cpu.backend + compile_pipeline = gtx_dace.run_dace_cpu.compiler return dataclasses.replace( gtx_dace.run_dace_cpu, - backend=dataclasses.replace( + compiler=dataclasses.replace( compile_pipeline, translation=compile_pipeline.translation.step ), ) 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 4a642f5cc4..e77f6aa41a 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 @@ -5,6 +5,7 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import dataclasses import inspect import threading import warnings @@ -18,7 +19,7 @@ from gt4py import next as gtx from gt4py._core import definitions as core_defs -from gt4py.next import errors, config +from gt4py.next import backend as next_backend, config, errors from gt4py.next.otf import compiled_program, options, arguments from gt4py.next.otf.compilation import cache as compilation_cache from gt4py.next.ffront.decorator import Program @@ -41,8 +42,24 @@ from gt4py.next.otf import arguments -_raise_on_compile = mock.Mock() -_raise_on_compile.compile.side_effect = AssertionError("This function should never be called.") + +def _never_called(*args, **kwargs): + raise AssertionError("This function should never be called.") + + +def _forbid_compilation(program) -> None: + """ + Make every new compilation of `program` fail. + + Replaces the toolchain of the program's compiled-programs pool by one whose + frontend and compiler raise. Variants that are already compiled, or still in + flight, keep loading and running; `program.backend` is left untouched. + """ + pool = program._compiled_programs + pool.toolchain = next_backend.Toolchain( + dataclasses.replace(pool.toolchain.backend, compiler=_never_called), + frontend=_never_called, + ) class NamedTupleNamedCollection(NamedTuple): @@ -116,7 +133,7 @@ def test_compile(cartesian_case, compile_testee): args, kwargs = cases.get_default_data(cartesian_case, compile_testee) # make sure the backend is never called - object.__setattr__(compile_testee, "backend", _raise_on_compile) + _forbid_compilation(compile_testee) compile_testee(*args, offset_provider=cartesian_case.offset_provider, **kwargs) assert np.allclose(kwargs["out"].ndarray, args[0].ndarray + args[1].ndarray) @@ -163,7 +180,7 @@ def test_compile_kwargs(cartesian_case, compile_testee): (a, b), kwargs = cases.get_default_data(cartesian_case, compile_testee) # make sure the backend is never called - object.__setattr__(compile_testee, "backend", _raise_on_compile) + _forbid_compilation(compile_testee) compile_testee(offset_provider=cartesian_case.offset_provider, b=b, a=a, **kwargs) assert np.allclose(kwargs["out"].ndarray, a.ndarray + b.ndarray) @@ -184,7 +201,7 @@ def test_compile_scan(cartesian_case, compile_testee_scan): out = cartesian_case.as_field([KDim], np.zeros(k_size, dtype=np.int32)) # make sure the backend is never called - object.__setattr__(compile_testee_scan, "backend", _raise_on_compile) + _forbid_compilation(compile_testee_scan) compile_testee_scan(inp, out=out, offset_provider=cartesian_case.offset_provider) assert np.allclose(out.ndarray, np.cumsum(inp.ndarray)) @@ -199,7 +216,7 @@ def test_compile_domain(cartesian_case, compile_testee_domain): args, kwargs = cases.get_default_data(cartesian_case, compile_testee_domain) # make sure the backend is never called - object.__setattr__(compile_testee_domain, "backend", _raise_on_compile) + _forbid_compilation(compile_testee_domain) compile_testee_domain( *args[:-1], @@ -248,7 +265,7 @@ def test_compile_unstructured(unstructured_case, compile_testee_unstructured): args, kwargs = cases.get_default_data(unstructured_case, compile_testee_unstructured) # make sure the backend is never called - object.__setattr__(compile_testee_unstructured, "backend", _raise_on_compile) + _forbid_compilation(compile_testee_unstructured) compile_testee_unstructured(*args, offset_provider=unstructured_case.offset_provider, **kwargs) @@ -286,7 +303,7 @@ def test_compile_unstructured_wrong_offset_provider( args, kwargs = cases.get_default_data(unstructured_case, compile_testee_unstructured_no_jit) # make sure the backend is never called - object.__setattr__(compile_testee_unstructured_no_jit, "backend", _raise_on_compile) + _forbid_compilation(compile_testee_unstructured_no_jit) with pytest.raises(RuntimeError, match="No program.*static.*arg.*"): compile_testee_unstructured_no_jit( @@ -310,7 +327,7 @@ def test_compile_unstructured_for_two_offset_providers( ) # make sure the backend is never called - object.__setattr__(compile_testee_unstructured_no_jit, "backend", _raise_on_compile) + _forbid_compilation(compile_testee_unstructured_no_jit) args, kwargs = cases.get_default_data(unstructured_case, compile_testee_unstructured_no_jit) compile_testee_unstructured_no_jit( @@ -386,7 +403,7 @@ def compile_variants_testee(cartesian_case, compile_variants_testee_not_compiled @pytest.mark.uses_tuple_returns def test_compile_variants(cartesian_case, compile_variants_testee): # make sure the backend is never called - object.__setattr__(compile_variants_testee, "backend", _raise_on_compile) + _forbid_compilation(compile_variants_testee) assert compile_variants_testee._compiled_programs.argument_descriptor_mapping[ arguments.StaticArg @@ -429,7 +446,7 @@ def test_compile_variants(cartesian_case, compile_variants_testee): @pytest.mark.uses_tuple_returns def test_compile_variants_args_and_kwargs(cartesian_case, compile_variants_testee): # make sure the backend is never called - object.__setattr__(compile_variants_testee, "backend", _raise_on_compile) + _forbid_compilation(compile_variants_testee) field_a = cases.allocate(cartesian_case, compile_variants_testee, "field_a")() field_b = cases.allocate(cartesian_case, compile_variants_testee, "field_b")() @@ -601,7 +618,7 @@ def test_compile_variants_not_compiled_then_reset_static_params( assert np.allclose(out[1].ndarray, field_b.ndarray - 4.0) # make sure the backend is never called form here on - object.__setattr__(compile_variants_testee, "backend", _raise_on_compile) + _forbid_compilation(testee_static_float_static_bool) # calling it again will not recompile out = cases.allocate(cartesian_case, testee_static_float_static_bool, "out")() @@ -651,7 +668,8 @@ def test_compile_variants_not_compiled_then_set_new_static_params( ) # make sure the backend is never called form here on - object.__setattr__(compile_variants_testee, "backend", _raise_on_compile) + _forbid_compilation(compile_variants_testee) + _forbid_compilation(testee_static_float_static_bool) out = cases.allocate(cartesian_case, testee_static_float_static_bool, "out")() testee_static_float_static_bool( @@ -699,7 +717,7 @@ def test_compile_variants_jit(cartesian_case, compile_variants_testee): assert np.allclose(out[1].ndarray, field_b.ndarray - 4.0) # make sure on the second call the backend is not called - object.__setattr__(compile_variants_testee, "backend", _raise_on_compile) + _forbid_compilation(compile_variants_testee) out = cases.allocate(cartesian_case, compile_variants_testee, "out")() compile_variants_testee( field_a, @@ -740,7 +758,7 @@ def test_compile_variants_with_static_params_jit( assert np.allclose(out[1].ndarray, field_b.ndarray + 3.0) # make sure the backend is not called on the second call - object.__setattr__(testee_with_static_params, "backend", _raise_on_compile) + _forbid_compilation(testee_with_static_params) out = cases.allocate(cartesian_case, testee_with_static_params, "out")() testee_with_static_params( @@ -797,7 +815,7 @@ def testee( assert np.allclose(out[1].ndarray, field_b.ndarray + 3.0) # make sure the backend is not called on the second call - object.__setattr__(testee, "backend", _raise_on_compile) + _forbid_compilation(testee) out = cases.allocate(cartesian_case, testee, "out")() testee( @@ -867,7 +885,7 @@ def testee( @pytest.mark.uses_tuple_args def test_compile_variants_tuple(cartesian_case, compile_variants_testee_tuple): # make sure the backend is never called - object.__setattr__(compile_variants_testee_tuple, "backend", _raise_on_compile) + _forbid_compilation(compile_variants_testee_tuple) field_a = cases.allocate(cartesian_case, compile_variants_testee_tuple, "field_a")() field_b = cases.allocate(cartesian_case, compile_variants_testee_tuple, "field_b")() @@ -978,13 +996,11 @@ def test_wait_for_compilation_raises_on_failed_compilation(cartesian_case, compi # submission; an instant failure would raise eagerly at `compile()` already. gate = threading.Event() - class FailingBackend: - def __getattr__(self, name): - return getattr(cartesian_case.backend, name) + def failing_compiler(compilable): + gate.wait() + raise ValueError("compilation went boom") - def compile(self, program, compile_time_args): - gate.wait() - raise ValueError("compilation went boom") + failing_backend = dataclasses.replace(cartesian_case.backend, compiler=failing_compiler) runner = compiled_program.runners.ThreadRunner(max_workers=1) try: @@ -992,7 +1008,7 @@ def compile(self, program, compile_time_args): get_runner.return_value = runner # The program must stay referenced: failure tracking is weak, so the # failed future of a garbage-collected program is not reported. - testee = compile_testee.with_backend(FailingBackend()) + testee = compile_testee.with_backend(failing_backend) testee.compile(offset_provider=cartesian_case.offset_provider) gate.set() with pytest.raises(ValueError, match="compilation went boom"): @@ -1011,15 +1027,12 @@ def test_compile_variants_decorator_static_domains(cartesian_case): captured_cargs: Optional[arguments.CompileTimeArgs] = None - class CaptureCompileTimeArgsBackend: - def __getattr__(self, name): - return getattr(cartesian_case.backend, name) + def capturing_compiler(compilable): + nonlocal captured_cargs + captured_cargs = compilable.args + return cartesian_case.backend.compiler(compilable) - def compile(self, program, compile_time_args): - nonlocal captured_cargs - captured_cargs = compile_time_args - - return cartesian_case.backend.compile(program, compile_time_args) + capturing_backend = dataclasses.replace(cartesian_case.backend, compiler=capturing_compiler) @gtx.field_operator def identity_like(inp: tuple[cases.IField, cases.IField, float]): @@ -1027,7 +1040,7 @@ def identity_like(inp: tuple[cases.IField, cases.IField, float]): # the float argument here is merely to test that static domains work for tuple arguments # of inhomogeneous types - @gtx.program(backend=CaptureCompileTimeArgsBackend(), static_domains=True) + @gtx.program(backend=capturing_backend, static_domains=True) def testee(inp: tuple[cases.IField, cases.IField, float], out: NamedTupleNamedCollection): identity_like(inp, out=out) @@ -1088,3 +1101,28 @@ def test_warn_on_direct_scan_operator_call(cartesian_case, scan_operator_testee) w = generic_warnings[0] assert w.filename == __file__ assert w.lineno == call_lineno + + +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: + pytest.skip("Embedded execution does not compile.") + + @gtx.field_operator + def scale(a: cases.IField, factor: int32) -> cases.IField: + return a * factor + + @gtx.program(backend=cartesian_case.backend, static_params=("factor",)) + def testee(a: cases.IField, factor: int32, out: cases.IField): + scale(a, factor, out=out) + + a = cases.allocate(cartesian_case, testee, "a")() + out = cases.allocate(cartesian_case, testee, "out")() + testee.compile(factor=[int32(2)], offset_provider=cartesian_case.offset_provider) + _forbid_compilation(testee) + + testee(a, int32(2), out, offset_provider=cartesian_case.offset_provider, enable_jit=True) + assert np.allclose(out.ndarray, 2 * a.ndarray) + + with pytest.raises(AssertionError, match="should never be called"): + testee(a, int32(3), out, offset_provider=cartesian_case.offset_provider, enable_jit=True) 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..2e49f61a6e 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 @@ -103,7 +103,7 @@ def copy(a: IField) -> IField: a = cases.allocate(cartesian_case, copy, "a")() - with pytest.raises(ValueError, match="No backend selected!"): + with pytest.raises(TypeError, match="no_backend"): # Calling this should fail if the default backend is respected # due to `exec_alloc_descriptor` fixture (dependency of `cartesian_case`) # setting the default backend to something invalid. @@ -121,7 +121,7 @@ def sum(state: float, a: float) -> float: a = gtx.ones({KDim: 10}, allocator=cartesian_case.allocator) - with pytest.raises(ValueError, match="No backend selected!"): + with pytest.raises(TypeError, match="no_backend"): # see comment in field_operator test _ = sum(a, out=a, offset_provider={}) @@ -141,6 +141,6 @@ def copy_program(a: IField, b: IField) -> IField: a = cases.allocate(cartesian_case, copy_program, "a")() b = cases.allocate(cartesian_case, copy_program, "b")() - with pytest.raises(ValueError, match="No backend selected!"): + with pytest.raises(TypeError, match="no_backend"): # see comment in field_operator test _ = copy_program(a, b, offset_provider={}) 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 1f1ee9c740..9bd7e43273 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 @@ -39,7 +39,7 @@ # becomes easier. -def make_builtin_field_operator(builtin_name: str, backend: Optional[next_backend.Toolchain]): +def make_builtin_field_operator(builtin_name: str, backend: Optional[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 c7ef03a844..9f51689d77 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 @@ -126,7 +126,7 @@ def custom_compiled_program_callback( @pytest.mark.parametrize("backend", BACKENDS, ids=lambda b: getattr(b, "name", str(b))) -def test_program_call_hooks(backend: gtx_typing.Toolchain): +def test_program_call_hooks(backend: gtx_typing.Backend): size = 10 a_field = gtx.full([(IDim, size)], 1, dtype=gtx.float64) b_field = gtx.full([(IDim, size)], 1, dtype=gtx.float64) @@ -208,11 +208,11 @@ def test_program_call_hooks(backend: gtx_typing.Toolchain): @pytest.mark.parametrize( "backend", [b for b in BACKENDS if b is not None], ids=lambda b: getattr(b, "name", str(b)) ) -def test_compile_variant_hook(backend: gtx_typing.Toolchain): +def test_compile_variant_hook(backend: gtx_typing.Backend): def custom_compile_variant_hook( program_pool: "CompiledProgramsPool", key: gtx_typing.CompiledProgramsKey, - backend: gtx_typing.Toolchain, + backend: gtx_typing.Backend, argument_descriptors: dict[type, dict[str, Any]], offset_provider: common.OffsetProviderType | common.OffsetProvider, ) -> None: 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 760c2b01e3..216448db1d 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 @@ -83,7 +83,9 @@ 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 exec_alloc_descriptor.backend is None else exec_alloc_descriptor + None + if isinstance(exec_alloc_descriptor, test_definitions.EmbeddedDummyBackend) + else exec_alloc_descriptor )( setup.input_field, setup.S_fields[0], @@ -106,7 +108,11 @@ 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 exec_alloc_descriptor.backend is None else exec_alloc_descriptor)( + pnabla.with_backend( + None + if isinstance(exec_alloc_descriptor, test_definitions.EmbeddedDummyBackend) + else exec_alloc_descriptor + )( setup.input_field, setup.S_fields, setup.sign_field, diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py index 283f134876..004120c89c 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py @@ -100,7 +100,7 @@ def fen_solve_tridiag2(i_size, j_size, k_size, a, b, c, d, x): def test_tridiag(fencil, tridiag_reference, program_processor): program_processor, validate = program_processor - if isinstance(program_processor, backend.Toolchain) and "dace" in program_processor.name: + if isinstance(program_processor, backend.CompiledBackend) and "dace" in program_processor.name: pytest.xfail("Dace ITIR backend doesn't support the IR format used in this test.") a, b, c, d, x = tridiag_reference diff --git a/tests/next_tests/unit_tests/conftest.py b/tests/next_tests/unit_tests/conftest.py index 5d21882c42..f521ca593b 100644 --- a/tests/next_tests/unit_tests/conftest.py +++ b/tests/next_tests/unit_tests/conftest.py @@ -23,7 +23,7 @@ import next_tests -ProgramProcessor: TypeAlias = backend.Toolchain | program_formatter.ProgramFormatter +ProgramProcessor: TypeAlias = backend.CompiledBackend | program_formatter.ProgramFormatter def _program_processor(request) -> tuple[ProgramProcessor, bool]: 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 new file mode 100644 index 0000000000..3e77a08c30 --- /dev/null +++ b/tests/next_tests/unit_tests/ffront_tests/test_decorator_dispatch.py @@ -0,0 +1,115 @@ +# 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 + +"""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.program_processors.runners import roundtrip + + +IDim = gtx.Dimension("IDim") +KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + + +@dataclasses.dataclass(frozen=True) +class _OtherBackend(next_backend.Backend): + """A backend that is neither compiled nor embedded.""" + + +_other_backend = _OtherBackend(name="other_backend", allocator=None) + + +def _copy_def(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + + +def _sum_def(state: float, a: float) -> float: + return state + a + + +def _make_testees(backend): + @gtx.field_operator(backend=backend) + def copy(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]): + copy(a, out=out) + + @gtx.scan_operator(axis=KDim, forward=True, init=0.0, backend=backend) + def scan(state: float, a: float) -> float: + return state + a + + return copy, copy_program, scan + + +@pytest.mark.parametrize("not_a_backend", [object(), "roundtrip", roundtrip.default.compiler]) +def test_construction_rejects_non_backends(not_a_backend): + with pytest.raises(TypeError, match="Expected a 'gt4py.next.backend.Backend'"): + gtx.field_operator(_copy_def, backend=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) + 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'"): + copy_program.with_backend(not_a_backend) + + +def test_unsupported_backend_kind_raises_on_use(): + # Creating programs and operators with such a backend works ... + copy, copy_program, scan = _make_testees(_other_backend) + a = gtx.as_field([IDim], np.ones(3)) + out = gtx.zeros({IDim: 3}) + k_field = gtx.as_field([KDim], np.ones(3)) + + # ... but using them does not. + with pytest.raises(TypeError, match="other_backend"): + copy_program(a, out, offset_provider={}) + with pytest.raises(TypeError, match="other_backend"): + copy(a, out=out, offset_provider={}) + with pytest.raises(TypeError, match="other_backend"): + scan(k_field, out=k_field, offset_provider={}) + with pytest.raises(TypeError, match="other_backend"): + copy_program.compile(offset_provider={}) + with pytest.raises(TypeError, match="other_backend"): + gtx.zeros({IDim: 3}, allocator=copy_program) + + +def test_none_backend_runs_embedded(): + copy, copy_program, _ = _make_testees(None) + 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 + 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={}) + + +def test_compiled_backend_allocator_and_toolchain(): + _, copy_program, _ = _make_testees(roundtrip.default) + + assert copy_program.__gt_allocator__ is roundtrip.default.allocator + + copy_program.compile(offset_provider={}) + toolchain = copy_program._compiled_programs.toolchain + assert toolchain.backend is roundtrip.default + assert toolchain.frontend is next_backend.DEFAULT_TRANSFORMS + assert copy_program._compiled_programs.backend is roundtrip.default diff --git a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py index 498a363760..a7c2ec094d 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py +++ b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py @@ -131,7 +131,7 @@ def pirate(program: workflow.ProgramWithArgs): return _NoOpArtifact() hacked_gtfn_backend = dataclasses.replace( - gtfn.make_gtfn_toolchain(name_postfix="_custom"), backend=pirate + gtfn.make_gtfn_toolchain(name_postfix="_custom"), compiler=pirate ) testee = testee_prog.with_backend(hacked_gtfn_backend).compile(cond=[True], offset_provider={}) diff --git a/tests/next_tests/unit_tests/otf_tests/test_runners.py b/tests/next_tests/unit_tests/otf_tests/test_runners.py index 5597a5b27c..50ad95277f 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_runners.py +++ b/tests/next_tests/unit_tests/otf_tests/test_runners.py @@ -100,52 +100,22 @@ def test_process_runner_falls_back_on_non_offloadable_task(process_runner): def test_make_compilation_task_decomposes_standard_backend(): - backend = next_backend.Toolchain( - name="test_backend", - backend=lambda compilable: _NoOpArtifact(), - allocator=None, + toolchain = next_backend.Toolchain( + next_backend.CompiledBackend( + name="test_backend", compiler=lambda compilable: _NoOpArtifact(), allocator=None + ), frontend=lambda inp: inp, ) task = compilation_tasks.make_compilation_task( - backend, definition_stage=None, compile_time_args=arguments.CompileTimeArgs.empty() + toolchain, definition_stage=None, compile_time_args=arguments.CompileTimeArgs.empty() ) assert task.no_offload_reason is None - assert task.executor is backend.backend + assert task.executor is toolchain.backend.compiler assert callable(task.compile().load()) -def test_make_compilation_task_is_opaque_for_customized_compile(): - class _WrapperBackend: - def __init__(self, wrapped): - self._wrapped = wrapped - - def __getattr__(self, name): - return getattr(self._wrapped, name) - - def compile(self, program, compile_time_args): - self.compile_called = True - return self._wrapped.compile(program, compile_time_args=compile_time_args) - - backend = _WrapperBackend( - next_backend.Toolchain( - name="test_backend", - backend=lambda compilable: _NoOpArtifact(), - allocator=None, - frontend=lambda inp: inp, - ) - ) - - task = compilation_tasks.make_compilation_task( - backend, definition_stage=None, compile_time_args=arguments.CompileTimeArgs.empty() - ) - - assert task.no_offload_reason is not None - assert callable(task.compile().load()) - assert backend.compile_called - - def test_offloaded_task_ships_connectivities_as_file_refs(): Vertex = gtx.Dimension("Vertex") Edge = gtx.Dimension("Edge") @@ -154,15 +124,15 @@ def test_offloaded_task_ships_connectivities_as_file_refs(): compile_time_args = dataclasses.replace( arguments.CompileTimeArgs.empty(), offset_provider={"V2E": conn} ) - backend = next_backend.Toolchain( - name="test_backend", - backend=lambda compilable: _NoOpArtifact(), - allocator=None, + toolchain = next_backend.Toolchain( + next_backend.CompiledBackend( + name="test_backend", compiler=lambda compilable: _NoOpArtifact(), allocator=None + ), frontend=lambda inp: inp, ) task = compilation_tasks.make_compilation_task( - backend, definition_stage=None, compile_time_args=compile_time_args + toolchain, definition_stage=None, compile_time_args=compile_time_args ) # without refs the original compilable is used as is @@ -181,7 +151,7 @@ def test_offloaded_task_ships_connectivities_as_file_refs(): # the same connectivity is dumped only once across tasks path = compilation_tasks._connectivity_files[id(conn)][1] task2 = compilation_tasks.make_compilation_task( - backend, definition_stage=None, compile_time_args=compile_time_args + toolchain, definition_stage=None, compile_time_args=compile_time_args ) pickle.dumps(task2.construct_compilable(True).args.offset_provider["V2E"]) assert compilation_tasks._connectivity_files[id(conn)][1] == path 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 f3cc628a84..569b385eb8 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 @@ -203,7 +203,7 @@ def test_make_backend_accepts_external_workspace_with_external_mode(): ), ) - assert backend.loading.external_workspace[core_defs.DeviceType.CPU] is workspace + assert backend.loader.external_workspace[core_defs.DeviceType.CPU] is workspace def test_make_backend_infers_external_mode_when_workspace_is_provided(): @@ -214,10 +214,10 @@ def test_make_backend_infers_external_mode_when_workspace_is_provided(): ) assert ( - backend.backend.translation.step.auto_optimize_args["transient_memory_mode"] + backend.compiler.translation.step.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.EXTERNAL ) - assert backend.loading.external_workspace[core_defs.DeviceType.CPU] is workspace + assert backend.loader.external_workspace[core_defs.DeviceType.CPU] is workspace def test_make_backend_warns_external_workspace_without_external_mode(): @@ -236,10 +236,10 @@ def test_make_backend_warns_external_workspace_without_external_mode(): # Explicit mode stays as requested by the caller; backend only warns. assert ( - backend.backend.translation.step.auto_optimize_args["transient_memory_mode"] + backend.compiler.translation.step.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.POOL ) - assert backend.loading.external_workspace[core_defs.DeviceType.CPU] is workspace + assert backend.loader.external_workspace[core_defs.DeviceType.CPU] is workspace def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): @@ -251,14 +251,14 @@ def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): cfg, translation=functools.partial(dace_wf_factory.make_dace_translator, use_metrics=False) ) - translator = backend.backend.translation.step + translator = backend.compiler.translation.step assert translator.use_metrics is False assert ( translator.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.EXTERNAL ) - assert backend.loading.external_workspace is cfg.external_workspace - assert backend.backend.compilation.bind_func_name == cfg.bind_func_name + assert backend.loader.external_workspace is cfg.external_workspace + assert backend.compiler.compilation.bind_func_name == cfg.bind_func_name def test_make_toolchain_rejects_derived_optimization_args(): @@ -276,7 +276,7 @@ def test_make_toolchain_uncached_translation(): dace_wf_factory.DaCeConfig(cached_translation=False) ) - assert isinstance(toolchain.backend.translation, dace_wf_translation.DaCeTranslator) + assert isinstance(toolchain.compiler.translation, dace_wf_translation.DaCeTranslator) def test_make_dace_backend_is_deprecated(): @@ -310,12 +310,12 @@ def test_make_dace_backend_is_deprecated(): # distinct `functools.partial` objects, so compare what they wrap. assert deprecated.name == toolchain.name assert deprecated.allocator == toolchain.allocator - assert deprecated.loading.external_workspace is toolchain.loading.external_workspace - assert deprecated.backend.translation.step == toolchain.backend.translation.step - assert deprecated.backend.translation.cache.path == toolchain.backend.translation.cache.path - assert deprecated.backend.bindings.func is toolchain.backend.bindings.func - assert deprecated.backend.bindings.keywords == toolchain.backend.bindings.keywords - assert deprecated.backend.compilation == toolchain.backend.compilation + assert deprecated.loader.external_workspace is toolchain.loader.external_workspace + assert deprecated.compiler.translation.step == toolchain.compiler.translation.step + assert deprecated.compiler.translation.cache.path == toolchain.compiler.translation.cache.path + assert deprecated.compiler.bindings.func is toolchain.compiler.bindings.func + assert deprecated.compiler.bindings.keywords == toolchain.compiler.bindings.keywords + assert deprecated.compiler.compilation == toolchain.compiler.compilation def test_translator_rejects_derived_optimization_args_on_every_route(): @@ -328,7 +328,7 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) - translator = dace_wf_backend.run_dace_cpu.backend.translation.step + translator = dace_wf_backend.run_dace_cpu.compiler.translation.step with pytest.raises(ValueError, match="cannot be overridden"): dataclasses.replace(translator, auto_optimize_args={"constant_symbols": {}}) @@ -343,8 +343,8 @@ def test_step_builders_reach_all_step_settings(): ), ) - assert toolchain.backend.translation.step.disable_itir_transforms is True - assert toolchain.backend.compilation.add_gpu_trace_markers is True + assert toolchain.compiler.translation.step.disable_itir_transforms is True + assert toolchain.compiler.compilation.add_gpu_trace_markers is True def test_unused_optimization_args_warning_points_at_the_caller(): @@ -449,7 +449,7 @@ def testee(a: cases.IField, b: cases.IField, out: cases.IField): out = cases.allocate(test_case, testee, "out")() captured_sdfg: dace.SDFG | None = None - translation_step = custom_backend.backend.translation.step + translation_step = custom_backend.compiler.translation.step def mocked_translator(inp: stages.CompilableProgram) -> dace.SDFG: nonlocal captured_sdfg @@ -459,8 +459,8 @@ def mocked_translator(inp: stages.CompilableProgram) -> dace.SDFG: custom_backend = dataclasses.replace( custom_backend, - backend=dataclasses.replace( - custom_backend.backend, + compiler=dataclasses.replace( + custom_backend.compiler, translation=mocked_translator, ), ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py index 3265af0841..58b69d3a19 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py @@ -38,15 +38,15 @@ def test_make_gtfn_toolchain_device(): gpu_version = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(gpu=True)) assert cpu_version.name == "run_gtfn_cpu" - assert isinstance(cpu_version.backend.translation, workflow.CachedStep) - assert cpu_version.backend.translation.step.device_type is core_defs.DeviceType.CPU + assert isinstance(cpu_version.compiler.translation, workflow.CachedStep) + assert cpu_version.compiler.translation.step.device_type is core_defs.DeviceType.CPU assert gpu_version.name == "run_gtfn_gpu" - assert isinstance(gpu_version.backend.translation, workflow.CachedStep) - assert gpu_version.backend.translation.step.device_type is core_defs.DeviceType.CUDA + assert isinstance(gpu_version.compiler.translation, workflow.CachedStep) + assert gpu_version.compiler.translation.step.device_type is core_defs.DeviceType.CUDA # The compilation step now also carries device_type so it can stamp the artifact. - assert cpu_version.backend.compilation.device_type is core_defs.DeviceType.CPU - assert gpu_version.backend.compilation.device_type is core_defs.DeviceType.CUDA + assert cpu_version.compiler.compilation.device_type is core_defs.DeviceType.CPU + assert gpu_version.compiler.compilation.device_type is core_defs.DeviceType.CUDA assert custom_layout_allocators.is_field_allocator_for( cpu_version.allocator, core_defs.DeviceType.CPU @@ -62,9 +62,9 @@ def test_make_gtfn_toolchain_build_cache_config(monkeypatch): monkeypatch.setattr(config, "BUILD_CACHE_LIFETIME", config.BuildCacheLifetime.PERSISTENT) persistent_version = gtfn.make_gtfn_toolchain() - assert session_version.backend.compilation.cache_lifetime is config.BuildCacheLifetime.SESSION + assert session_version.compiler.compilation.cache_lifetime is config.BuildCacheLifetime.SESSION assert ( - persistent_version.backend.compilation.cache_lifetime + persistent_version.compiler.compilation.cache_lifetime is config.BuildCacheLifetime.PERSISTENT ) @@ -76,11 +76,11 @@ def test_make_gtfn_toolchain_build_type_config(monkeypatch): min_size_version = gtfn.make_gtfn_toolchain() assert ( - release_version.backend.compilation.builder_factory.cmake_build_type + release_version.compiler.compilation.builder_factory.cmake_build_type is config.CMakeBuildType.RELEASE ) assert ( - min_size_version.backend.compilation.builder_factory.cmake_build_type + min_size_version.compiler.compilation.builder_factory.cmake_build_type is config.CMakeBuildType.MIN_SIZE_REL ) @@ -98,8 +98,8 @@ def test_cmake_build_type_changes_build_folder(monkeypatch, tmp_path): monkeypatch.setattr(config, "CMAKE_BUILD_TYPE", config.CMakeBuildType.DEBUG) debug_version = gtfn.make_gtfn_toolchain() - release_compiler = release_version.backend.compilation - debug_compiler = debug_version.backend.compilation + release_compiler = release_version.compiler.compilation + debug_compiler = debug_version.compiler.compilation build_context_ids: list[str] = [] @@ -147,11 +147,11 @@ def test_step_builder_partial_keeps_config_settings(): ), ) - translation = toolchain.backend.translation + translation = toolchain.compiler.translation assert isinstance(translation, workflow.CachedStep) assert translation.step.enable_itir_transforms is False assert translation.step.device_type is cfg.device_type - compilation = toolchain.backend.compilation + compilation = toolchain.compiler.compilation assert compilation.device_type is cfg.device_type assert compilation.builder_factory.cmake_extra_flags == ["-DEXTRA=ON"] assert compilation.builder_factory.cmake_build_type is config.CMakeBuildType.DEBUG @@ -165,14 +165,14 @@ def test_custom_step_builder_output_is_cached(): toolchain = gtfn.make_gtfn_toolchain(translation=lambda cfg: custom_step) - assert isinstance(toolchain.backend.translation, workflow.CachedStep) - assert toolchain.backend.translation.step is custom_step + assert isinstance(toolchain.compiler.translation, workflow.CachedStep) + assert toolchain.compiler.translation.step is custom_step def test_uncached_translation(): toolchain = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(cached_translation=False)) - assert isinstance(toolchain.backend.translation, gtfn_module.GTFNTranslationStep) + assert isinstance(toolchain.compiler.translation, gtfn_module.GTFNTranslationStep) def test_step_builder_cannot_override_config_setting(): diff --git a/tests/next_tests/unit_tests/test_backend.py b/tests/next_tests/unit_tests/test_backend.py new file mode 100644 index 0000000000..7c8f6dc7a8 --- /dev/null +++ b/tests/next_tests/unit_tests/test_backend.py @@ -0,0 +1,111 @@ +# 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 + +"""Tests for the backend kinds and the internal toolchain in `gt4py.next.backend`.""" + +import dataclasses + +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 + + +@dataclasses.dataclass(frozen=True) +class _OtherBackend(next_backend.Backend): + """A backend that is neither compiled nor embedded.""" + + +def _make_compiled_backend(**kwargs) -> next_backend.CompiledBackend: + return next_backend.CompiledBackend( + name=kwargs.pop("name", "test_backend"), + allocator=kwargs.pop("allocator", next_allocators.StandardCPUFieldBufferAllocator()), + compiler=kwargs.pop("compiler", lambda compilable: compilable), + **kwargs, + ) + + +def test_backend_is_abstract(): + with pytest.raises(TypeError, match="abstract"): + next_backend.Backend(name="backend", allocator=None) + + +def test_backend_subclass_can_be_instantiated(): + backend = _OtherBackend(name="other", allocator=None) + + assert backend.name == "other" + + +def test_compiled_backend_defaults(): + allocator = next_allocators.StandardCPUFieldBufferAllocator() + backend = _make_compiled_backend(allocator=allocator) + + assert isinstance(backend, next_backend.Backend) + assert backend.loader is artifacts.load_artifact + assert backend.__gt_allocator__ is allocator + assert [field.name for field in dataclasses.fields(backend)] == [ + "name", + "allocator", + "compiler", + "loader", + ] + + +def test_compiled_backend_replace_keeps_other_fields(): + def other_compiler(compilable): + return compilable + + backend = _make_compiled_backend() + variant = dataclasses.replace(backend, compiler=other_compiler) + + assert variant.compiler is other_compiler + assert variant.name == backend.name + assert variant.allocator is backend.allocator + assert variant.loader is backend.loader + + +def test_toolchain_compile_runs_frontend_compiler_and_loader_in_order(): + calls = [] + compile_time_args = arguments.CompileTimeArgs.empty() + + def frontend(program_with_args): + calls.append(("frontend", program_with_args.definition, program_with_args.args)) + return "compilable" + + def compiler(compilable): + calls.append(("compiler", compilable)) + return "artifact" + + def loader(artifact): + calls.append(("loader", artifact)) + return "executable" + + backend = _make_compiled_backend(compiler=compiler, loader=loader) + result = next_backend.Toolchain(backend, frontend=frontend).compile( + "definition", compile_time_args + ) + + assert result == "executable" + assert calls == [ + ("frontend", "definition", compile_time_args), + ("compiler", "compilable"), + ("loader", "artifact"), + ] + + +def test_toolchain_default_frontend_is_the_global_one(): + assert next_backend.Toolchain(_make_compiled_backend()).frontend is ( + next_backend.DEFAULT_TRANSFORMS + ) + + +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__ diff --git a/typing_tests/test_next.yaml b/typing_tests/test_next.yaml index a743f0401f..5db040f8df 100644 --- a/typing_tests/test_next.yaml +++ b/typing_tests/test_next.yaml @@ -211,7 +211,7 @@ 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.Toolchain | None) -> None: + def foo_with_backend(backend: gtx.typing.Backend | None) -> None: _ = foo.with_backend(backend) - case: with_backend_scanop @@ -227,7 +227,7 @@ ) -> float: return carry + val - def somescanop_with_backend(backend: gtx.typing.Toolchain | None) -> None: + def somescanop_with_backend(backend: gtx.typing.Backend | None) -> None: _ = somescanop.with_backend(backend) - case: with_backend_program @@ -251,7 +251,7 @@ ) -> None: foo(a, out=b, domain={KDim: (start, end)}) - def foo_prg_with_backend(backend: gtx.typing.Toolchain | None) -> None: + def foo_prg_with_backend(backend: gtx.typing.Backend | None) -> None: _ = foo_prg.with_backend(backend) - case: astype_return_type From a0d796aacbbd2d200aed149a2a758a7e36b23375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 18:32:38 +0100 Subject: [PATCH 03/10] test[next]: pin that roundtrip.gtir lowers exactly as with its former frontend roundtrip.gtir now uses the global default frontend; its former private Transforms used the same factories with the same caching flags and only owned separate in-memory caches. The test compares both lowerings of a program and of a field operator. --- .../runners_tests/test_roundtrip.py | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py index 510aa1ef1d..f6fb36e7b4 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py @@ -10,8 +10,12 @@ import pytest +import gt4py.next as gtx +from gt4py.next import backend as next_backend +from gt4py.next.ffront import foast_to_gtir, foast_to_past, past_to_itir from gt4py.next.iterator import ir as itir from gt4py.next.iterator.ir_utils import ir_makers as im +from gt4py.next.otf import arguments, stages from gt4py.next.program_processors.runners import roundtrip @@ -70,3 +74,39 @@ def test_load_module_caches_by_debug_flag(debug_order, monkeypatch): assert roundtrip._load_module(source_code, debug) is modules[debug] finally: os.remove(modules[True].__file__) + + +def _former_gtir_frontend() -> next_backend.Transforms: + """The frontend `roundtrip.gtir` used to build for itself (before ADR 0029).""" + return next_backend.Transforms( + past_to_itir=past_to_itir.past_to_gtir_factory(), + foast_to_itir=foast_to_gtir.adapted_foast_to_gtir_factory(cached=True), + field_view_op_to_prog=foast_to_past.operator_to_program_factory( + foast_to_itir_step=foast_to_gtir.adapted_foast_to_gtir_factory() + ), + ) + + +def test_gtir_uses_the_default_frontend_without_changing_the_lowering(): + IDim = gtx.Dimension("IDim") + + @gtx.field_operator + def double(a: gtx.Field[[IDim], gtx.float64]) -> gtx.Field[[IDim], gtx.float64]: + return a + a + + @gtx.program + def double_program(a: gtx.Field[[IDim], gtx.float64], out: gtx.Field[[IDim], gtx.float64]): + double(a, out=out) + + a = gtx.zeros({IDim: 4}) + out = gtx.zeros({IDim: 4}) + default_frontend = next_backend.Toolchain(roundtrip.gtir).frontend + assert default_frontend is next_backend.DEFAULT_TRANSFORMS + + # A field operator is lowered as the program wrapping it, so `out` is positional. + compile_time_args = arguments.CompileTimeArgs.from_concrete(a, out, offset_provider={}) + for definition_stage in [double_program.definition_stage, double.definition_stage]: + inp = stages.ConcreteProgramDef(definition=definition_stage, args=compile_time_args) + lowered = default_frontend(inp).definition + assert isinstance(lowered, itir.Program) + assert lowered == _former_gtir_frontend()(inp).definition From 7324127178b2ec41f611f9a4ff37f634deca40ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 18:38:28 +0100 Subject: [PATCH 04/10] refactor[next]: drop CompilationTask.no_offload_reason Its only producer was the opaque 'customized compile' path of make_compilation_task, deleted with the backend restructuring. Tasks still fall back to the calling thread when their executor cannot be pickled; a new test covers that for a backend with a closure compiler. --- src/gt4py/next/otf/runners.py | 20 +++++-------- .../unit_tests/otf_tests/test_runners.py | 29 ++++++++++++++----- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/src/gt4py/next/otf/runners.py b/src/gt4py/next/otf/runners.py index f260a33061..ab5311b3c7 100644 --- a/src/gt4py/next/otf/runners.py +++ b/src/gt4py/next/otf/runners.py @@ -43,8 +43,6 @@ class CompilationTask: #: The artifact-producing step. A runner may execute it anywhere, including #: another process; its picklability is the runner's concern. executor: Callable[[Any], artifacts.CompilationArtifact] - #: Reason this task is known not to be shippable to another process, if any. - no_offload_reason: str | None = None def compile(self, with_refs: bool = False) -> artifacts.CompilationArtifact: return self.executor(self.construct_compilable(with_refs)) @@ -186,9 +184,9 @@ class ProcessRunner: The worker runs the task's executor (post-lowering compile) and returns the picklable ``CompilationArtifact``. - Tasks that cannot be offloaded — a known ``no_offload_reason`` or an executor - that stdlib ``pickle`` cannot serialize — are compiled in the calling thread - instead (with a warning), so they behave as under ``SerialRunner``. + Tasks whose executor stdlib ``pickle`` cannot serialize are compiled in the + calling thread instead (with a warning), so they behave as under + ``SerialRunner``. """ def __init__(self, max_workers: int, shared_session_cache_dir: str) -> None: @@ -211,14 +209,10 @@ def __init__(self, max_workers: int, shared_session_cache_dir: str) -> None: def submit( self, task: CompilationTask ) -> concurrent.futures.Future[artifacts.CompilationArtifact]: - reason = task.no_offload_reason - executor_blob: bytes | None = None - if reason is None: - try: - executor_blob = pickle.dumps(task.executor) - except Exception as error: # pickling arbitrary object graphs raises arbitrary errors - reason = f"its executor is not picklable ({error!s})" - if executor_blob is None: + try: + executor_blob = pickle.dumps(task.executor) + except Exception as error: # pickling arbitrary object graphs raises arbitrary errors + reason = f"its executor is not picklable ({error!s})" warnings.warn( f"Compiling '{task.name}' in the calling thread instead of a worker process " f"because {reason}.", diff --git a/tests/next_tests/unit_tests/otf_tests/test_runners.py b/tests/next_tests/unit_tests/otf_tests/test_runners.py index 50ad95277f..375f6dd3c7 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_runners.py +++ b/tests/next_tests/unit_tests/otf_tests/test_runners.py @@ -84,19 +84,33 @@ def test_process_runner_propagates_recursion_limit(process_runner): sys.setrecursionlimit(old_limit) -def test_process_runner_falls_back_on_non_offloadable_task(process_runner): - task = runners.CompilationTask( - name="opaque", - construct_compilable=lambda with_refs: None, - executor=lambda _: _NoOpArtifact(), - no_offload_reason="it does not use the standard compilation workflow", +def test_process_runner_runs_unpicklable_compiler_in_calling_thread(process_runner): + """A backend whose compiler cannot be pickled still compiles, in the calling thread. + + This is the generic fallback that replaced the opaque "customized compile" path. + """ + calls = [] + + def closure_compiler(compilable): + calls.append(compilable) + return _NoOpArtifact() + + toolchain = next_backend.Toolchain( + next_backend.CompiledBackend( + name="closure_backend", compiler=closure_compiler, allocator=None + ), + frontend=lambda inp: inp, + ) + task = compilation_tasks.make_compilation_task( + toolchain, definition_stage=None, compile_time_args=arguments.CompileTimeArgs.empty() ) - with pytest.warns(UserWarning, match="standard compilation workflow"): + with pytest.warns(UserWarning, match="not picklable"): future = process_runner.submit(task) assert future.done() assert callable(future.result().load()) + assert len(calls) == 1 def test_make_compilation_task_decomposes_standard_backend(): @@ -111,7 +125,6 @@ def test_make_compilation_task_decomposes_standard_backend(): toolchain, definition_stage=None, compile_time_args=arguments.CompileTimeArgs.empty() ) - assert task.no_offload_reason is None assert task.executor is toolchain.backend.compiler assert callable(task.compile().load()) From e9f2cf5b19f77efb41a9c75e120a89f605167b1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 18:42:49 +0100 Subject: [PATCH 05/10] refactor[next-dace]: rename DaCeLoadingStep to DaCeLoader and identify DaCe backends by type - DaCeLoadingStep -> DaCeLoader (the external workspace stays reachable as backend.loader.external_workspace); both are exported from runners.dace. - New is_dace_backend(backend): a CompiledBackend whose compiler is the standard compile pipeline with a DaCeTranslator translation step (looking through CachedStep). Program.__sdfg__ uses it instead of checking that the backend name contains 'dace', so renamed DaCe backends convert too; the orchestration and vertical-advection tests use it as well. --- .../runners/dace/__init__.py | 4 ++ .../runners/dace/program.py | 7 ++-- .../runners/dace/workflow/backend.py | 37 ++++++++++++++++--- .../dace_tests/test_orchestration.py | 5 ++- .../feature_tests/dace_tests/test_program.py | 30 ++++++++++++++- .../iterator_tests/test_vertical_advection.py | 13 ++++++- .../dace_tests/test_dace_backend.py | 34 +++++++++++++++++ 7 files changed, 116 insertions(+), 14 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/__init__.py b/src/gt4py/next/program_processors/runners/dace/__init__.py index 2e06493bd0..6199a96e3b 100644 --- a/src/gt4py/next/program_processors/runners/dace/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace/__init__.py @@ -9,6 +9,8 @@ from gt4py.next.program_processors.runners.dace.sdfg_callable import get_sdfg_args from gt4py.next.program_processors.runners.dace.workflow.backend import ( + DaCeLoader, + is_dace_backend, make_dace_backend, make_dace_toolchain, run_dace_cpu, @@ -32,8 +34,10 @@ "DaCeBindingsBuilder", "DaCeCompilationBuilder", "DaCeConfig", + "DaCeLoader", "DaCeTranslationBuilder", "get_sdfg_args", + "is_dace_backend", "make_dace_backend", "make_dace_bindings", "make_dace_compile_workflow", diff --git a/src/gt4py/next/program_processors/runners/dace/program.py b/src/gt4py/next/program_processors/runners/dace/program.py index 2b9347e8f9..b11454c25e 100644 --- a/src/gt4py/next/program_processors/runners/dace/program.py +++ b/src/gt4py/next/program_processors/runners/dace/program.py @@ -20,6 +20,7 @@ from gt4py.next.iterator.transforms import extractors as extractors from gt4py.next.otf import arguments, workflow from gt4py.next.program_processors.runners.dace import sdfg_args as gtx_dace_args +from gt4py.next.program_processors.runners.dace.workflow import backend as gtx_dace_backend from gt4py.next.type_system import type_specifications as ts @@ -36,16 +37,14 @@ class Program(decorator.Program, dace.frontend.python.common.SDFGConvertible): ] = {} # symbolically defined def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: - if not ( - isinstance(self.backend, gtx_backend.CompiledBackend) - and "dace" in self.backend.name.lower() - ): + if not gtx_dace_backend.is_dace_backend(self.backend): raise ValueError("The SDFG can be generated only for the DaCe backend.") offset_provider: gtx_common.OffsetProvider = self.compilation_options.connectivities or {} column_axis = kwargs.get("column_axis", None) # TODO(ricoh): connectivity tables required here for now. + assert isinstance(self.backend, gtx_backend.CompiledBackend) gtir_stage = self._frontend_transforms.past_to_itir( workflow.ProgramWithArgs( definition=self.past_stage, diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py index 5049a7f735..fd087497bf 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -14,20 +14,21 @@ from typing import Any from gt4py.next import backend, config -from gt4py.next.otf import artifacts +from gt4py.next.otf import artifacts, recipes, workflow from gt4py.next.program_processors.runners.dace.workflow import ( common as gtx_wfdcommon, decoration as gtx_wfddecoration, factory as gtx_wfdfactory, + translation as gtx_wfdtranslation, ) @dataclasses.dataclass(frozen=True) -class DaCeLoadingStep: +class DaCeLoader: """ - Loading step that injects an external workspace into the loaded program. + Loader that injects an external workspace into the loaded program. - The workspace is owned by the caller, not by the toolchain; it is installed + The workspace is owned by the caller, not by the backend; it is installed onto the program wrapper before its first call, so that it is used when the SDFG argument vector is constructed. """ @@ -41,6 +42,32 @@ def __call__(self, artifact: artifacts.CompilationArtifact) -> artifacts.Executa return program +def is_dace_backend(backend_: Any) -> bool: + """ + Check whether `backend_` is a compiled backend translating programs to SDFGs. + + The check looks at the translation step of the standard compile pipeline + (through a `CachedStep`), not at the backend name, so renamed and customized + DaCe backends are recognized too. + + Args: + backend_: Any object, typically a `Backend`. + + Returns: + `True` if `backend_` is a `CompiledBackend` whose compiler is the standard + compile pipeline with a `DaCeTranslator` translation step. + """ + if not isinstance(backend_, backend.CompiledBackend): + return False + compiler = backend_.compiler + if not isinstance(compiler, recipes.OTFCompileWorkflow): + return False + translation: Any = compiler.translation + if isinstance(translation, workflow.CachedStep): + translation = translation.step + return isinstance(translation, gtx_wfdtranslation.DaCeTranslator) + + def make_dace_toolchain( cfg: gtx_wfdfactory.DaCeConfig | None = None, /, @@ -73,7 +100,7 @@ def make_dace_toolchain( cfg, translation=translation, bindings=bindings, compilation=compilation ), allocator=cfg.make_allocator(), - loader=DaCeLoadingStep(cfg.external_workspace), + loader=DaCeLoader(cfg.external_workspace), ) diff --git a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_orchestration.py b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_orchestration.py index e984140038..c0f1bfee0d 100644 --- a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_orchestration.py +++ b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_orchestration.py @@ -14,6 +14,7 @@ from gt4py.next import common as gtx_common, custom_layout_allocators as gtx_allocators from gt4py._core import definitions as core_defs +from gt4py.next.program_processors.runners import dace as dace_backends from next_tests.integration_tests import cases from next_tests.integration_tests.cases import cartesian_case, unstructured_case # noqa: F401 from next_tests.integration_tests.cases_utils import ( @@ -33,7 +34,7 @@ @pytest.mark.uses_cartesian_shift def test_sdfgConvertible_laplap(cartesian_case): # noqa: F811 - if not cartesian_case.backend or "dace" not in cartesian_case.backend.name: + if not dace_backends.is_dace_backend(cartesian_case.backend): pytest.skip("DaCe-related test: Test SDFGConvertible interface for GT4Py programs") backend = cartesian_case.backend @@ -80,7 +81,7 @@ def testee(a: gtx.Field[gtx.Dims[Vertex], gtx.float64], b: gtx.Field[gtx.Dims[Ed @pytest.mark.uses_unstructured_shift def test_sdfgConvertible_connectivities(unstructured_case): # noqa: F811 - if not unstructured_case.backend or "dace" not in unstructured_case.backend.name: + if not dace_backends.is_dace_backend(unstructured_case.backend): pytest.skip("DaCe-related test: Test SDFGConvertible interface for GT4Py programs") allocator, backend = unstructured_case.allocator, unstructured_case.backend diff --git a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py index 7221f33ad6..227aac2143 100644 --- a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py +++ b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py @@ -6,6 +6,8 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import dataclasses + import dace import pytest @@ -23,7 +25,7 @@ mesh_descriptor, # noqa: F401 ) -from gt4py.next.program_processors.runners import dace as dace_backends +from gt4py.next.program_processors.runners import dace as dace_backends, gtfn # Override the exec_alloc_descriptor with a custom Backend, @@ -100,3 +102,29 @@ def testee_dace( assert testee.gt4py_program_input_fields == {"a": Vertex, "b": Vertex} assert testee.gt4py_program_output_fields == {"b": Vertex, "c": Vertex} + + +def test_sdfg_conversion_requires_a_dace_backend(): + @gtx.program(backend=gtfn.run_gtfn) + def testee(a: gtx.Field[[Vertex], gtx.int], out: gtx.Field[[Vertex], gtx.int]): + _copy(a, out=out) + + with pytest.raises(ValueError, match="only for the DaCe backend"): + testee.__sdfg__() + + +def test_sdfg_conversion_does_not_depend_on_the_backend_name(exec_alloc_descriptor): + renamed = dataclasses.replace(exec_alloc_descriptor, name="custom") + + @gtx.program(backend=renamed) + def testee(a: gtx.Field[[Vertex], gtx.int], out: gtx.Field[[Vertex], gtx.int]): + _copy(a, out=out) + + sdfg = testee.__sdfg__() + + assert isinstance(sdfg, dace.SDFG) + + +@gtx.field_operator +def _copy(a: gtx.Field[[Vertex], gtx.int]) -> gtx.Field[[Vertex], gtx.int]: + return a diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py index 004120c89c..ebaeffe41f 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py @@ -10,13 +10,22 @@ import pytest import gt4py.next as gtx -from gt4py.next import backend from gt4py.next.iterator.builtins import * from gt4py.next.iterator.runtime import set_at, fendef, fundef from gt4py.next.program_processors.formatters import gtfn as gtfn_formatters from gt4py.next.program_processors.runners import gtfn from next_tests.integration_tests.cases import IDim, JDim, KDim + + +try: + from gt4py.next.program_processors.runners.dace import is_dace_backend +except ImportError: # dace is an optional dependency + + def is_dace_backend(backend: object) -> bool: + return False + + from next_tests.unit_tests.conftest import program_processor, run_processor @@ -100,7 +109,7 @@ def fen_solve_tridiag2(i_size, j_size, k_size, a, b, c, d, x): def test_tridiag(fencil, tridiag_reference, program_processor): program_processor, validate = program_processor - if isinstance(program_processor, backend.CompiledBackend) and "dace" in program_processor.name: + if is_dace_backend(program_processor): pytest.xfail("Dace ITIR backend doesn't support the IR format used in this test.") a, b, c, d, x = tridiag_reference 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 569b385eb8..4a58d2e8bf 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 @@ -22,6 +22,7 @@ from gt4py._core import definitions as core_defs from gt4py.next import config from gt4py.next.otf import runners, stages +from gt4py.next.program_processors.runners import gtfn, roundtrip from gt4py.next.otf import workflow as gtx_workflow from gt4py.next.program_processors.runners.dace import transformations as gtx_transformations from gt4py.next.program_processors.runners.dace.transformations import ( @@ -279,6 +280,39 @@ def test_make_toolchain_uncached_translation(): assert isinstance(toolchain.compiler.translation, dace_wf_translation.DaCeTranslator) +def test_backend_carries_its_workspace_in_a_dace_loader(): + workspace: dict = {} + backend = dace_wf_backend.make_dace_toolchain( + dace_wf_factory.DaCeConfig(external_workspace=workspace) + ) + + assert isinstance(backend.loader, dace_wf_backend.DaCeLoader) + assert backend.loader.external_workspace is workspace + + +@pytest.mark.parametrize( + "backend", + [ + dace_wf_backend.run_dace_cpu, + dace_wf_backend.make_dace_toolchain(name_postfix="_custom"), + dace_wf_backend.make_dace_toolchain(dace_wf_factory.DaCeConfig(cached_translation=False)), + dataclasses.replace(dace_wf_backend.run_dace_cpu, name="renamed"), + ], + ids=["run_dace_cpu", "postfix", "uncached", "renamed"], +) +def test_is_dace_backend_recognizes_dace_backends(backend): + assert dace_wf_backend.is_dace_backend(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"], +) +def test_is_dace_backend_rejects_other_objects(backend): + assert not dace_wf_backend.is_dace_backend(backend) + + def test_make_dace_backend_is_deprecated(): workspace = {core_defs.DeviceType.CPU: _RecordingWorkspace()} with pytest.warns(DeprecationWarning, match="make_dace_toolchain"): From 59825fc06de9628df0908b665ed41b102e25b551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 18:49:19 +0100 Subject: [PATCH 06/10] refactor[next]!: rename the compiled-backend builders and config The builders return a `CompiledBackend` and `Toolchain` is now internal, so the public names follow the backend vocabulary: - `gtfn.make_gtfn_toolchain` -> `gtfn.make_gtfn_backend` - `dace.make_dace_toolchain` -> `dace.make_dace_backend` - `backend.ToolchainConfig` -> `backend.CompiledBackendConfig` The flat-keyword `make_dace_backend(gpu, auto_optimize=..., ...)`, deprecated in the previous release, is removed; its name now belongs to the config-based builder. Calls in the removed shape (`make_dace_backend(gpu=...)` or `make_dace_backend(True)`) fail at the call with a `TypeError` that explains the new signature and where each old argument goes. The `name_postfix` docstrings now say what the generated name encodes instead of claiming the name "must stay unique". --- src/gt4py/next/backend.py | 10 +- .../runners/dace/__init__.py | 2 - .../runners/dace/workflow/__init__.py | 2 +- .../runners/dace/workflow/backend.py | 147 ++++++++---------- .../runners/dace/workflow/factory.py | 14 +- .../next/program_processors/runners/gtfn.py | 32 ++-- .../test_temporaries_with_sizes.py | 2 +- .../otf_tests/test_compiled_program.py | 2 +- .../dace_tests/test_dace_backend.py | 75 +++------ .../dace_tests/test_dace_bindings.py | 4 +- .../runners_tests/test_gtfn.py | 30 ++-- 11 files changed, 136 insertions(+), 184 deletions(-) diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index e2152c37a3..85ad846df7 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -228,18 +228,18 @@ def compile( @dataclasses.dataclass(frozen=True) -class ToolchainConfig: +class CompiledBackendConfig: """ - Settings that describe what a compiled toolchain builds for. + Settings that describe what a compiled backend builds for. - A toolchain builder creates every step from one config, so steps that must + A backend builder creates every step from one config, so steps that must agree on a setting (the target device, the build type, the cache lifetime, the data layout) read it from the same place and cannot drift apart. Settings that only tune how a single step does its job are not part of the config: they are keyword arguments of that step's builder. Defaults are read from `gt4py.next.config` when the config is created, not - when this module is imported, so the toolchains built from a default config + when this module is imported, so the backends built from a default config follow the current user configuration. """ @@ -266,7 +266,7 @@ def device_type(self) -> core_defs.DeviceType: @property def device_name(self) -> str: - """Device part of the toolchain name.""" + """Device part of the backend name.""" return "gpu" if self.gpu else "cpu" def make_allocator(self) -> next_allocators.FieldBufferAllocatorProtocol: diff --git a/src/gt4py/next/program_processors/runners/dace/__init__.py b/src/gt4py/next/program_processors/runners/dace/__init__.py index 6199a96e3b..a5d2f8e335 100644 --- a/src/gt4py/next/program_processors/runners/dace/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace/__init__.py @@ -12,7 +12,6 @@ DaCeLoader, is_dace_backend, make_dace_backend, - make_dace_toolchain, run_dace_cpu, run_dace_cpu_noopt, run_dace_gpu, @@ -42,7 +41,6 @@ "make_dace_bindings", "make_dace_compile_workflow", "make_dace_compiler", - "make_dace_toolchain", "make_dace_translator", "run_dace_cpu", "run_dace_cpu_noopt", diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/__init__.py b/src/gt4py/next/program_processors/runners/dace/workflow/__init__.py index 2159bcc0a3..ab4b334545 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/__init__.py @@ -15,7 +15,7 @@ - `compilation` for compiling the SDFG into a program - `decoration` to parse the program arguments and pass them to the program call -The toolchain builders create every step from one `DaCeConfig`, and wrap the +The backend builders create every step from one `DaCeConfig`, and wrap the translation step in a persistent `CachedStep` unless the config disables it, thus they provide caching of the GTIR program. """ diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py index fd087497bf..3150d82d1e 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -10,10 +10,10 @@ import dataclasses import functools -import warnings -from typing import Any +from collections.abc import Callable +from typing import Any, Final, ParamSpec -from gt4py.next import backend, config +from gt4py.next import backend from gt4py.next.otf import artifacts, recipes, workflow from gt4py.next.program_processors.runners.dace.workflow import ( common as gtx_wfdcommon, @@ -68,7 +68,53 @@ def is_dace_backend(backend_: Any) -> bool: return isinstance(translation, gtx_wfdtranslation.DaCeTranslator) -def make_dace_toolchain( +#: Keyword arguments of the flat-keyword `make_dace_backend` removed in ADR 0029, +#: mapped to where the setting lives now. +_REMOVED_MAKE_DACE_BACKEND_KEYWORDS: Final[dict[str, str]] = { + "gpu": "DaCeConfig(gpu=...)", + "auto_optimize": "DaCeConfig(auto_optimize=...)", + "external_workspace": "DaCeConfig(external_workspace=...)", + "unstructured_horizontal_has_unit_stride": ( + "DaCeConfig(unstructured_horizontal_has_unit_stride=...)" + ), + "optimization_args": "make_dace_translator(auto_optimize_args=...)", + "async_sdfg_call": "make_dace_translator(async_sdfg_call=...)", + "use_metrics": "make_dace_translator(use_metrics=...)", + "use_zero_origin": "make_dace_translator(disable_field_origin_on_program_arguments=...)", + "use_max_domain_range_on_unstructured_shift": ( + "make_dace_translator(use_max_domain_range_on_unstructured_shift=...)" + ), +} + +_P = ParamSpec("_P") + + +def _reject_removed_make_dace_backend_call( + builder: Callable[_P, backend.CompiledBackend], +) -> Callable[_P, backend.CompiledBackend]: + """Turn calls in the shape of the removed flat-keyword `make_dace_backend` into a clear error.""" + + @functools.wraps(builder) + def checked_builder(*args: _P.args, **kwargs: _P.kwargs) -> backend.CompiledBackend: + removed = [name for name in kwargs if name in _REMOVED_MAKE_DACE_BACKEND_KEYWORDS] + if removed or (args and not isinstance(args[0], gtx_wfdfactory.DaCeConfig | None)): + moved = "".join( + f"\n - '{name}' -> {_REMOVED_MAKE_DACE_BACKEND_KEYWORDS[name]}" for name in removed + ) + raise TypeError( + "'make_dace_backend' takes a 'DaCeConfig' and step builders; the flat-keyword" + " signature 'make_dace_backend(gpu, auto_optimize=..., ...)' was removed (ADR 0029)." + " Call 'make_dace_backend(DaCeConfig(gpu=..., auto_optimize=...)," + " translation=functools.partial(make_dace_translator, ...))' instead." + + (f" Where the given arguments go:{moved}" if moved else "") + ) + return builder(*args, **kwargs) + + return checked_builder + + +@_reject_removed_make_dace_backend_call +def make_dace_backend( cfg: gtx_wfdfactory.DaCeConfig | None = None, /, *, @@ -78,18 +124,24 @@ def make_dace_toolchain( compilation: gtx_wfdfactory.DaCeCompilationBuilder = gtx_wfdfactory.make_dace_compiler, ) -> backend.CompiledBackend: """ - Build a DaCe toolchain. + Build a compiled DaCe backend. Args: - cfg: The toolchain configuration. Defaults to `DaCeConfig()`. - name_postfix: Appended to the toolchain name, which must stay unique. + cfg: The backend configuration. Defaults to `DaCeConfig()`. + name_postfix: Appended to the generated name. The generated name encodes + only the device and whether auto-optimization is on; pass a postfix + to tell other variants apart in metrics and logs. translation: Builder of the translation step, see `make_dace_compile_workflow`. bindings: Builder of the bindings step. compilation: Builder of the compilation step. Returns: - The configured toolchain. + The configured backend. + + Raises: + TypeError: If called with the arguments of the removed flat-keyword + signature (`make_dace_backend(gpu, auto_optimize=..., ...)`). """ if cfg is None: cfg = gtx_wfdfactory.DaCeConfig() @@ -104,79 +156,8 @@ def make_dace_toolchain( ) -def make_dace_backend( - gpu: bool, - auto_optimize: bool = True, - async_sdfg_call: bool = True, - optimization_args: dict[str, Any] | None = None, - external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None, - unstructured_horizontal_has_unit_stride: bool = config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE, - use_metrics: bool = True, - use_zero_origin: bool = False, - use_max_domain_range_on_unstructured_shift: bool | None = None, -) -> backend.CompiledBackend: - """Customize the dace backend with the given configuration parameters. - - Deprecated: use `make_dace_toolchain` with a `DaCeConfig` for the shared - settings and `functools.partial(make_dace_translator, ...)` for the - translation settings. This flat-keyword front end builds exactly that from - its arguments. - - Args: - gpu: Enable GPU transformations and code generation. - auto_optimize: Enable the SDFG auto-optimize pipeline. - async_sdfg_call: Make an asynchronous SDFG call on GPU to allow overlapping - of GPU kernel execution with the Python driver code. - optimization_args: A `dict` containing configuration parameters for - the SDFG auto-optimize pipeline, see `gt_auto_optimize()`. - external_workspace: Workspace memory externally allocated, which is used - for SDFG's transient arrays when `transient_memory_mode` is `EXTERNAL`. - unstructured_horizontal_has_unit_stride: When the memory layout has unit stride - in the horizontal dimension, replace the field stride symbol with '1'. - use_metrics: Add SDFG instrumentation to collect the metric for stencil - compute time. - use_zero_origin: Can be set to `True` when all fields passed as program - arguments have zero-based origin. This setting will skip generation - of range start-symbols `_range_0` since they can be assumed to be zero. - use_max_domain_range_on_unstructured_shift: See `DaCeTranslator`. - - Note that `gt_auto_optimize()` parameters that are derived from GT4Py configuration - cannot be overridden, and therefore cannot appear in `optimization_args`. - - Returns: - A dace backend with custom configuration for the target device. - - Raises: - ValueError: If `optimization_args` sets a parameter derived from the - configuration, or requests the `EXTERNAL` transient memory mode - without an `external_workspace`. - """ - warnings.warn( - "'make_dace_backend' is deprecated, use 'make_dace_toolchain' with a 'DaCeConfig' and" - " 'functools.partial(make_dace_translator, ...)' instead.", - DeprecationWarning, - stacklevel=2, - ) - return make_dace_toolchain( - gtx_wfdfactory.DaCeConfig( - gpu=gpu, - auto_optimize=auto_optimize, - external_workspace=external_workspace, - unstructured_horizontal_has_unit_stride=unstructured_horizontal_has_unit_stride, - ), - translation=functools.partial( - gtx_wfdfactory.make_dace_translator, - auto_optimize_args=optimization_args, - async_sdfg_call=async_sdfg_call, - use_metrics=use_metrics, - disable_field_origin_on_program_arguments=use_zero_origin, - use_max_domain_range_on_unstructured_shift=use_max_domain_range_on_unstructured_shift, - ), - ) - - -run_dace_cpu = make_dace_toolchain(gtx_wfdfactory.DaCeConfig(auto_optimize=True)) -run_dace_cpu_noopt = make_dace_toolchain(gtx_wfdfactory.DaCeConfig(auto_optimize=False)) +run_dace_cpu = make_dace_backend(gtx_wfdfactory.DaCeConfig(auto_optimize=True)) +run_dace_cpu_noopt = make_dace_backend(gtx_wfdfactory.DaCeConfig(auto_optimize=False)) -run_dace_gpu = make_dace_toolchain(gtx_wfdfactory.DaCeConfig(gpu=True, auto_optimize=True)) -run_dace_gpu_noopt = make_dace_toolchain(gtx_wfdfactory.DaCeConfig(gpu=True, auto_optimize=False)) +run_dace_gpu = make_dace_backend(gtx_wfdfactory.DaCeConfig(gpu=True, auto_optimize=True)) +run_dace_gpu_noopt = make_dace_backend(gtx_wfdfactory.DaCeConfig(gpu=True, auto_optimize=False)) diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py index 6b3d52dba6..66c131213d 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -33,12 +33,12 @@ @dataclasses.dataclass(frozen=True) -class DaCeConfig(next_backend.ToolchainConfig): - """Settings shared by the steps of a DaCe toolchain, see `ToolchainConfig`.""" +class DaCeConfig(next_backend.CompiledBackendConfig): + """Settings shared by the steps of a DaCe backend, see `CompiledBackendConfig`.""" #: Run the SDFG auto-optimize pipeline. auto_optimize: bool = True - #: Workspace memory allocated outside the SDFG. The toolchain injects it into + #: Workspace memory allocated outside the SDFG. The backend's loader injects it into #: the loaded programs, and the translation step then defaults to the #: `EXTERNAL` transient memory mode, which stores the transients in it. The #: workspace is a dict, so a config holding one is not hashable. @@ -66,7 +66,7 @@ def make_dace_translator( The keyword arguments are the step-local fields of `DaCeTranslator`. Args: - cfg: The toolchain configuration. + cfg: The backend configuration. auto_optimize_args: Configuration for the SDFG auto-optimize pipeline, see `gt_auto_optimize()`. The parameters `DaCeTranslator` derives itself cannot be set here. With an external workspace in `cfg`, the @@ -141,7 +141,7 @@ def make_dace_compiler( Build the compilation step, targeting `cfg.device_type`. Args: - cfg: The toolchain configuration. + cfg: The backend configuration. add_gpu_trace_markers: Add GPU trace markers to the generated code. Defaults to the value in `config`. @@ -159,7 +159,7 @@ def make_dace_compiler( ) -#: Step builders: callables creating a step from the toolchain configuration. +#: Step builders: callables creating a step from the backend configuration. DaCeTranslationBuilder: TypeAlias = Callable[[DaCeConfig], stages.TranslationStep] DaCeBindingsBuilder: TypeAlias = Callable[ [DaCeConfig], workflow.Workflow[artifacts.ProgramSource, artifacts.ExtensionSource] @@ -190,7 +190,7 @@ def make_dace_compile_workflow( responsible for configuring its step from `cfg`. Args: - cfg: The toolchain configuration. Defaults to `DaCeConfig()`. + cfg: The backend configuration. Defaults to `DaCeConfig()`. translation: Builder of the translation step. bindings: Builder of the bindings step. compilation: Builder of the compilation step. diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index 2f00d16a64..7ec5fe2a99 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -124,11 +124,11 @@ def _make_artifact( @dataclasses.dataclass(frozen=True) -class GTFNConfig(backend.ToolchainConfig): - """Settings shared by the steps of a GTFN toolchain, see `ToolchainConfig`.""" +class GTFNConfig(backend.CompiledBackendConfig): + """Settings shared by the steps of a GTFN backend, see `CompiledBackendConfig`.""" -#: Step builders: callables creating a step from the toolchain configuration. +#: Step builders: callables creating a step from the backend configuration. GTFNTranslationBuilder: TypeAlias = Callable[[GTFNConfig], stages.TranslationStep] GTFNBindingsBuilder: TypeAlias = Callable[ [GTFNConfig], workflow.Workflow[artifacts.ProgramSource, artifacts.ExtensionSource] @@ -150,7 +150,7 @@ def make_gtfn_translation( Build the GTIR -> C++ translation step. Args: - cfg: The toolchain configuration. + cfg: The backend configuration. enable_itir_transforms: Run the GTIR transformation passes before code generation. symbolic_domain_sizes: Symbolic sizes of the domains, by dimension name. @@ -191,7 +191,7 @@ def make_gtfn_build_system( Build the build-system project generator used by the GTFN compiler. Args: - cfg: The toolchain configuration. + cfg: The backend configuration. cmake_extra_flags: Extra flags passed to CMake. renew_compiledb: Regenerate the compilation database even if one exists. @@ -218,7 +218,7 @@ def make_gtfn_compiler( Build the compilation step. Args: - cfg: The toolchain configuration. + cfg: The backend configuration. build_system: Builder of the build-system project generator. force_recompile: Recompile even if a cached build exists. @@ -255,7 +255,7 @@ def make_gtfn_compile_workflow( responsible for configuring its step from `cfg`. Args: - cfg: The toolchain configuration. Defaults to `GTFNConfig()`. + cfg: The backend configuration. Defaults to `GTFNConfig()`. translation: Builder of the translation step. bindings: Builder of the bindings step. compilation: Builder of the compilation step. @@ -279,7 +279,7 @@ def make_gtfn_compile_workflow( ) -def make_gtfn_toolchain( +def make_gtfn_backend( cfg: GTFNConfig | None = None, /, *, @@ -289,18 +289,20 @@ def make_gtfn_toolchain( compilation: GTFNCompilationBuilder = make_gtfn_compiler, ) -> backend.CompiledBackend: """ - Build a GTFN toolchain. + Build a compiled GTFN backend. Args: - cfg: The toolchain configuration. Defaults to `GTFNConfig()`. - name_postfix: Appended to the toolchain name, which must stay unique. + cfg: The backend configuration. Defaults to `GTFNConfig()`. + name_postfix: Appended to the generated name. The generated name encodes + only the device; pass a postfix to tell other variants apart in + metrics and logs. translation: Builder of the translation step, see `make_gtfn_compile_workflow`. bindings: Builder of the bindings step. compilation: Builder of the compilation step. Returns: - The configured toolchain. + The configured backend. """ if cfg is None: cfg = GTFNConfig() @@ -314,11 +316,11 @@ def make_gtfn_toolchain( ) -run_gtfn = make_gtfn_toolchain() +run_gtfn = make_gtfn_backend() -run_gtfn_gpu = make_gtfn_toolchain(GTFNConfig(gpu=True)) +run_gtfn_gpu = make_gtfn_backend(GTFNConfig(gpu=True)) -run_gtfn_no_transforms = make_gtfn_toolchain( +run_gtfn_no_transforms = make_gtfn_backend( name_postfix="_no_transforms", translation=functools.partial(make_gtfn_translation, enable_itir_transforms=False), ) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py index 8900154140..5ee3e31037 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_temporaries_with_sizes.py @@ -32,7 +32,7 @@ # see https://docs.pytest.org/en/latest/how-to/fixtures.html#override-a-fixture-on-a-test-module-level @pytest.fixture def exec_alloc_descriptor(): - return gtfn.make_gtfn_toolchain( + return gtfn.make_gtfn_backend( gtfn.GTFNConfig(cached_translation=False), name_postfix="_with_temporaries_and_sizes", translation=functools.partial( diff --git a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py index a7c2ec094d..77dd465664 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py +++ b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py @@ -131,7 +131,7 @@ def pirate(program: workflow.ProgramWithArgs): return _NoOpArtifact() hacked_gtfn_backend = dataclasses.replace( - gtfn.make_gtfn_toolchain(name_postfix="_custom"), compiler=pirate + gtfn.make_gtfn_backend(name_postfix="_custom"), compiler=pirate ) testee = testee_prog.with_backend(hacked_gtfn_backend).compile(cond=[True], offset_provider={}) 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 4a58d2e8bf..574c64145b 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 @@ -106,7 +106,7 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: monkeypatch.setattr(gtx_transformations, "gt_auto_optimize", mocked_auto_optimize) monkeypatch.setattr(gtx_transformations, "gt_gpu_transformation", mocked_gpu_transformation) - custom_backend = dace_wf_backend.make_dace_toolchain( + custom_backend = dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig( gpu=on_gpu, auto_optimize=auto_optimize, @@ -194,7 +194,7 @@ class _RecordingWorkspace: def test_make_backend_accepts_external_workspace_with_external_mode(): workspace = _RecordingWorkspace() - backend = dace_wf_backend.make_dace_toolchain( + backend = dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig(external_workspace={core_defs.DeviceType.CPU: workspace}), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -210,7 +210,7 @@ def test_make_backend_accepts_external_workspace_with_external_mode(): def test_make_backend_infers_external_mode_when_workspace_is_provided(): workspace = _RecordingWorkspace() - backend = dace_wf_backend.make_dace_toolchain( + backend = dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig(external_workspace={core_defs.DeviceType.CPU: workspace}) ) @@ -225,7 +225,7 @@ def test_make_backend_warns_external_workspace_without_external_mode(): workspace = _RecordingWorkspace() with pytest.warns(UserWarning, match="External memory workspace provided"): - backend = dace_wf_backend.make_dace_toolchain( + backend = dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig(external_workspace={core_defs.DeviceType.CPU: workspace}), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -243,12 +243,12 @@ def test_make_backend_warns_external_workspace_without_external_mode(): assert backend.loader.external_workspace[core_defs.DeviceType.CPU] is workspace -def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): +def test_make_backend_derives_workspace_and_memory_mode_from_one_config(): """The toolchain and its translation step read the workspace from one config.""" workspace = _RecordingWorkspace() cfg = dace_wf_factory.DaCeConfig(external_workspace={core_defs.DeviceType.CPU: workspace}) - backend = dace_wf_backend.make_dace_toolchain( + backend = dace_wf_backend.make_dace_backend( cfg, translation=functools.partial(dace_wf_factory.make_dace_translator, use_metrics=False) ) @@ -262,9 +262,9 @@ def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): assert backend.compiler.compilation.bind_func_name == cfg.bind_func_name -def test_make_toolchain_rejects_derived_optimization_args(): +def test_make_backend_rejects_derived_optimization_args(): with pytest.raises(ValueError, match="cannot be overridden"): - dace_wf_backend.make_dace_toolchain( + dace_wf_backend.make_dace_backend( translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args={"unit_strides_kind": None}, @@ -272,8 +272,8 @@ def test_make_toolchain_rejects_derived_optimization_args(): ) -def test_make_toolchain_uncached_translation(): - toolchain = dace_wf_backend.make_dace_toolchain( +def test_make_backend_uncached_translation(): + toolchain = dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig(cached_translation=False) ) @@ -282,7 +282,7 @@ def test_make_toolchain_uncached_translation(): def test_backend_carries_its_workspace_in_a_dace_loader(): workspace: dict = {} - backend = dace_wf_backend.make_dace_toolchain( + backend = dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig(external_workspace=workspace) ) @@ -294,8 +294,8 @@ def test_backend_carries_its_workspace_in_a_dace_loader(): "backend", [ dace_wf_backend.run_dace_cpu, - dace_wf_backend.make_dace_toolchain(name_postfix="_custom"), - dace_wf_backend.make_dace_toolchain(dace_wf_factory.DaCeConfig(cached_translation=False)), + dace_wf_backend.make_dace_backend(name_postfix="_custom"), + dace_wf_backend.make_dace_backend(dace_wf_factory.DaCeConfig(cached_translation=False)), dataclasses.replace(dace_wf_backend.run_dace_cpu, name="renamed"), ], ids=["run_dace_cpu", "postfix", "uncached", "renamed"], @@ -313,43 +313,14 @@ def test_is_dace_backend_rejects_other_objects(backend): assert not dace_wf_backend.is_dace_backend(backend) -def test_make_dace_backend_is_deprecated(): - workspace = {core_defs.DeviceType.CPU: _RecordingWorkspace()} - with pytest.warns(DeprecationWarning, match="make_dace_toolchain"): - deprecated = dace_wf_backend.make_dace_backend( - gpu=False, - async_sdfg_call=False, - optimization_args={"blocking_size": 10}, - external_workspace=workspace, - unstructured_horizontal_has_unit_stride=True, - use_metrics=False, - use_zero_origin=True, - use_max_domain_range_on_unstructured_shift=True, - ) - toolchain = dace_wf_backend.make_dace_toolchain( - dace_wf_factory.DaCeConfig( - external_workspace=workspace, unstructured_horizontal_has_unit_stride=True - ), - translation=functools.partial( - dace_wf_factory.make_dace_translator, - auto_optimize_args={"blocking_size": 10}, - async_sdfg_call=False, - use_metrics=False, - disable_field_origin_on_program_arguments=True, - use_max_domain_range_on_unstructured_shift=True, - ), - ) +def test_make_dace_backend_rejects_the_removed_flat_keyword_signature(): + with pytest.raises(TypeError, match=r"'gpu' -> DaCeConfig\(gpu=...\)") as keyword_call: + dace_wf_backend.make_dace_backend(gpu=False, use_metrics=False) + assert "make_dace_translator(use_metrics=...)" in str(keyword_call.value) + assert "flat-keyword signature" in str(keyword_call.value) - # The cached steps own distinct `FileCache` objects and the bindings are - # distinct `functools.partial` objects, so compare what they wrap. - assert deprecated.name == toolchain.name - assert deprecated.allocator == toolchain.allocator - assert deprecated.loader.external_workspace is toolchain.loader.external_workspace - assert deprecated.compiler.translation.step == toolchain.compiler.translation.step - assert deprecated.compiler.translation.cache.path == toolchain.compiler.translation.cache.path - assert deprecated.compiler.bindings.func is toolchain.compiler.bindings.func - assert deprecated.compiler.bindings.keywords == toolchain.compiler.bindings.keywords - assert deprecated.compiler.compilation == toolchain.compiler.compilation + with pytest.raises(TypeError, match="takes a 'DaCeConfig'"): + dace_wf_backend.make_dace_backend(True) def test_translator_rejects_derived_optimization_args_on_every_route(): @@ -368,7 +339,7 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): def test_step_builders_reach_all_step_settings(): - toolchain = dace_wf_backend.make_dace_toolchain( + toolchain = dace_wf_backend.make_dace_backend( translation=functools.partial( dace_wf_factory.make_dace_translator, disable_itir_transforms=True ), @@ -383,7 +354,7 @@ def test_step_builders_reach_all_step_settings(): def test_unused_optimization_args_warning_points_at_the_caller(): with pytest.warns(UserWarning, match="auto-optimize is disabled") as record: - dace_wf_backend.make_dace_toolchain( + dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig(auto_optimize=False), translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args={"blocking_size": 10} @@ -453,7 +424,7 @@ def test_transient_memory_mode(device_type, transient_memory_mode, monkeypatch): else None ) - custom_backend = dace_wf_backend.make_dace_toolchain( + custom_backend = dace_wf_backend.make_dace_backend( dace_wf_factory.DaCeConfig(gpu=on_gpu, external_workspace=external_workspace), translation=functools.partial( dace_wf_factory.make_dace_translator, diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py index 2eb9d87172..9ce0e1adb7 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_bindings.py @@ -294,7 +294,7 @@ def testee( ): testee_op(a, b, out=out, domain={IDim: (1, M - 1), JDim: (2, N - 2), KDim: (3, K - 3)}) - backend = dace_runner.make_dace_toolchain( + backend = dace_runner.make_dace_backend( translation=functools.partial( dace_runner.make_dace_translator, use_metrics=use_metrics, @@ -350,7 +350,7 @@ def testee_op(a: cases.VField) -> cases.VField: def testee(a: cases.VField, b: cases.VField): testee_op(a, out=b) - backend = dace_runner.make_dace_toolchain( + backend = dace_runner.make_dace_backend( translation=functools.partial( dace_runner.make_dace_translator, use_metrics=use_metrics, diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py index 58b69d3a19..00bcc0ea2c 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_gtfn.py @@ -33,9 +33,9 @@ from gt4py.next.program_processors.runners import gtfn -def test_make_gtfn_toolchain_device(): - cpu_version = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(gpu=False)) - gpu_version = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(gpu=True)) +def test_make_gtfn_backend_device(): + cpu_version = gtfn.make_gtfn_backend(gtfn.GTFNConfig(gpu=False)) + gpu_version = gtfn.make_gtfn_backend(gtfn.GTFNConfig(gpu=True)) assert cpu_version.name == "run_gtfn_cpu" assert isinstance(cpu_version.compiler.translation, workflow.CachedStep) @@ -56,11 +56,11 @@ def test_make_gtfn_toolchain_device(): ) -def test_make_gtfn_toolchain_build_cache_config(monkeypatch): +def test_make_gtfn_backend_build_cache_config(monkeypatch): monkeypatch.setattr(config, "BUILD_CACHE_LIFETIME", config.BuildCacheLifetime.SESSION) - session_version = gtfn.make_gtfn_toolchain() + session_version = gtfn.make_gtfn_backend() monkeypatch.setattr(config, "BUILD_CACHE_LIFETIME", config.BuildCacheLifetime.PERSISTENT) - persistent_version = gtfn.make_gtfn_toolchain() + persistent_version = gtfn.make_gtfn_backend() assert session_version.compiler.compilation.cache_lifetime is config.BuildCacheLifetime.SESSION assert ( @@ -69,11 +69,11 @@ def test_make_gtfn_toolchain_build_cache_config(monkeypatch): ) -def test_make_gtfn_toolchain_build_type_config(monkeypatch): +def test_make_gtfn_backend_build_type_config(monkeypatch): monkeypatch.setattr(config, "CMAKE_BUILD_TYPE", config.CMakeBuildType.RELEASE) - release_version = gtfn.make_gtfn_toolchain() + release_version = gtfn.make_gtfn_backend() monkeypatch.setattr(config, "CMAKE_BUILD_TYPE", config.CMakeBuildType.MIN_SIZE_REL) - min_size_version = gtfn.make_gtfn_toolchain() + min_size_version = gtfn.make_gtfn_backend() assert ( release_version.compiler.compilation.builder_factory.cmake_build_type @@ -94,9 +94,9 @@ def test_cmake_build_type_changes_build_folder(monkeypatch, tmp_path): land in different cache folders. """ monkeypatch.setattr(config, "CMAKE_BUILD_TYPE", config.CMakeBuildType.RELEASE) - release_version = gtfn.make_gtfn_toolchain() + release_version = gtfn.make_gtfn_backend() monkeypatch.setattr(config, "CMAKE_BUILD_TYPE", config.CMakeBuildType.DEBUG) - debug_version = gtfn.make_gtfn_toolchain() + debug_version = gtfn.make_gtfn_backend() release_compiler = release_version.compiler.compilation debug_compiler = debug_version.compiler.compilation @@ -136,7 +136,7 @@ def test_step_builder_partial_keeps_config_settings(): """A partial of a default step builder changes a step-local setting only.""" cfg = gtfn.GTFNConfig(gpu=True, cmake_build_type=config.CMakeBuildType.DEBUG) - toolchain = gtfn.make_gtfn_toolchain( + toolchain = gtfn.make_gtfn_backend( cfg, translation=functools.partial(gtfn.make_gtfn_translation, enable_itir_transforms=False), compilation=functools.partial( @@ -163,21 +163,21 @@ def test_custom_step_builder_output_is_cached(): device_type=core_defs.DeviceType.CPU, use_max_domain_range_on_unstructured_shift=True ) - toolchain = gtfn.make_gtfn_toolchain(translation=lambda cfg: custom_step) + toolchain = gtfn.make_gtfn_backend(translation=lambda cfg: custom_step) assert isinstance(toolchain.compiler.translation, workflow.CachedStep) assert toolchain.compiler.translation.step is custom_step def test_uncached_translation(): - toolchain = gtfn.make_gtfn_toolchain(gtfn.GTFNConfig(cached_translation=False)) + toolchain = gtfn.make_gtfn_backend(gtfn.GTFNConfig(cached_translation=False)) assert isinstance(toolchain.compiler.translation, gtfn_module.GTFNTranslationStep) def test_step_builder_cannot_override_config_setting(): with pytest.raises(TypeError, match="device_type"): - gtfn.make_gtfn_toolchain( + gtfn.make_gtfn_backend( gtfn.GTFNConfig(gpu=True), translation=functools.partial( gtfn.make_gtfn_translation, device_type=core_defs.DeviceType.CPU From b5e3b1510494369cec53be4225e346b0b627c09a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Wed, 28 Oct 2026 18:50:41 +0100 Subject: [PATCH 07/10] docs[next]: rewrite ADR 0029 as Backend Structure and Pipeline Simplification ADR 0029 (introduced by this PR, not yet on main) is rewritten for the reworked design: the user-facing Backend stays, as an abstract base with a CompiledBackend kind; the frontend is global and composed with a compiled backend by an internal Toolchain; dispatch on the backend kind; no overridable compile; Backend.name is a label; builder/config renames. The 'Pipeline, not combinators', 'Stage observability' and 'Phasing' sections of the later stack PRs are kept in the new vocabulary. The file is renamed accordingly. Also: notes in ADRs 0011, 0017, 0024, 0027 and 0028; HackTheToolchain.md says the frontend is not a user customization point; WorkflowPatterns.md and the next AGENTS.md module map use the new names. --- .../ADRs/next/0011-On_The_Fly_Compilation.md | 2 +- .../ADRs/next/0017-Toolchain-Configuration.md | 2 +- .../ADRs/next/0024-Compilation-Runners.md | 2 + .../next/0027-External_Workspace_Memory.md | 2 +- ...028-Plain-Builders-Instead-of-Factories.md | 2 + ...d-Structure-and-Pipeline-Simplification.md | 297 ++++++++++++++++++ ...hain-Naming-and-Pipeline-Simplification.md | 176 ----------- docs/development/ADRs/next/README.md | 2 +- docs/user/next/advanced/HackTheToolchain.md | 11 +- docs/user/next/advanced/WorkflowPatterns.md | 8 +- src/gt4py/next/AGENTS.md | 7 +- 11 files changed, 322 insertions(+), 189 deletions(-) create mode 100644 docs/development/ADRs/next/0029-Backend-Structure-and-Pipeline-Simplification.md delete mode 100644 docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md diff --git a/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md b/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md index 7cde4775f7..7647ebcc8f 100644 --- a/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md +++ b/docs/development/ADRs/next/0011-On_The_Fly_Compilation.md @@ -14,7 +14,7 @@ This supersedes [0009 - Compiled Backend Integration](0009-Compiled-Backend-Inte > [!NOTE] > The stage and step names introduced below have since been renamed and redistributed over two modules: `ProgramCall` is now `otf.stages.CompilableProgramDef`; `ProgramSource`, `CompilableSource` and `CompiledProgram` are now `otf.artifacts.ProgramSource`, `otf.artifacts.ExtensionSource` and `otf.artifacts.CompilationArtifact` (whose `load()` returns an `otf.artifacts.ExecutableProgram`); and `otf.step_types` was merged into `otf.stages`, where `BindingStep` no longer exists. The architecture described here — composable, statically typed workflows — is unchanged. -Partially superseded by [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) (workflow combinators and step-type naming). +Partially superseded by [0029 - Backend Structure and Pipeline Simplification](0029-Backend-Structure-and-Pipeline-Simplification.md) (workflow combinators and step-type naming). ## Context diff --git a/docs/development/ADRs/next/0017-Toolchain-Configuration.md b/docs/development/ADRs/next/0017-Toolchain-Configuration.md index 367f69ad88..4a72f49eb4 100644 --- a/docs/development/ADRs/next/0017-Toolchain-Configuration.md +++ b/docs/development/ADRs/next/0017-Toolchain-Configuration.md @@ -11,7 +11,7 @@ tags: [backend, otf, workflows, toolchain] In order to provide a streamlined user experience, we attempt to standardize how users of GT4Py stencils can configure how those stencils are optimized without editing GT4Py code. This describes the design of the first minimal implementation. -Refined by [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) (the term *toolchain* becomes the name of the root object). +Refined by [0029 - Backend Structure and Pipeline Simplification](0029-Backend-Structure-and-Pipeline-Simplification.md) (the term *toolchain* names the internal composition of the frontend with a compiled backend; the user-facing object stays `Backend`). ## Context diff --git a/docs/development/ADRs/next/0024-Compilation-Runners.md b/docs/development/ADRs/next/0024-Compilation-Runners.md index ed94ffc194..e76571043b 100644 --- a/docs/development/ADRs/next/0024-Compilation-Runners.md +++ b/docs/development/ADRs/next/0024-Compilation-Runners.md @@ -9,6 +9,8 @@ tags: [] - **Created**: 2026-07-08 - **Updated**: 2026-07-08 +Partially superseded by [0029 - Backend Structure and Pipeline Simplification](0029-Backend-Structure-and-Pipeline-Simplification.md) (`compile` is no longer a backend method, so the fallback for backends that customize it no longer exists; a compiler that cannot be pickled still compiles in the calling thread). + In the context of ahead-of-time compilation of many program variants (`CompiledProgramsPool`), facing a thread pool that can neither hide the CPython-bound cost of translation and optimization (GIL) nor parallelize the diff --git a/docs/development/ADRs/next/0027-External_Workspace_Memory.md b/docs/development/ADRs/next/0027-External_Workspace_Memory.md index 7807acb7bf..e28e5d7ba5 100644 --- a/docs/development/ADRs/next/0027-External_Workspace_Memory.md +++ b/docs/development/ADRs/next/0027-External_Workspace_Memory.md @@ -9,7 +9,7 @@ tags: [] - **Created**: 2026-07-27 - **Updated**: 2026-08-03 -Partially superseded by [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) (the workspace is carried by an explicit `Toolchain.loading` step instead of a `DaCeBackend` subclass overriding `Backend.load_artifact`; the decision to inject the workspace at load time is unchanged). +Partially superseded by [0029 - Backend Structure and Pipeline Simplification](0029-Backend-Structure-and-Pipeline-Simplification.md) (the workspace is carried by a `DaCeLoader`, the `CompiledBackend.loader` of the DaCe backends, instead of a `DaCeBackend` subclass overriding `Backend.load_artifact`; the decision to inject the workspace at load time is unchanged). In the context of `gt4py.next` DaCe backends that run the same compiled SDFG many times (e.g. inside a time loop), facing per-call GPU transient allocation diff --git a/docs/development/ADRs/next/0028-Plain-Builders-Instead-of-Factories.md b/docs/development/ADRs/next/0028-Plain-Builders-Instead-of-Factories.md index e5f4fbd0d0..53668a2cf9 100644 --- a/docs/development/ADRs/next/0028-Plain-Builders-Instead-of-Factories.md +++ b/docs/development/ADRs/next/0028-Plain-Builders-Instead-of-Factories.md @@ -9,6 +9,8 @@ tags: [backend, otf, toolchain, workflows, dependencies] - **Created**: 2026-08-20 - **Updated**: 2026-09-30 +Partially superseded by [0029 - Backend Structure and Pipeline Simplification](0029-Backend-Structure-and-Pipeline-Simplification.md) (the builders are renamed `make_gtfn_backend` / `make_dace_backend` and the config base `CompiledBackendConfig`; the deprecated flat-keyword `make_dace_backend` is removed and its name reused; the composition rules are unchanged). + In the context of composing the GTFN and DaCe toolchains and their OTF compile workflows, facing a production dependency on `factory-boy` — a test-data library — whose `Trait` / `SubFactory` / `SelfAttribute` / `LazyAttribute` 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 new file mode 100644 index 0000000000..fc454dd8c4 --- /dev/null +++ b/docs/development/ADRs/next/0029-Backend-Structure-and-Pipeline-Simplification.md @@ -0,0 +1,297 @@ +--- +tags: [backend, otf, toolchain, workflows, naming, observability] +--- + +# Backend Structure and Pipeline Simplification + +- **Status**: valid +- **Authors**: Enrique González Paredes (@egparedes) +- **Created**: 2026-07-30 +- **Updated**: 2026-10-28 + +In the context of the object users pass as `backend=` and the on-the-fly compilation route behind +it, facing a root object that mixes a user-facing concept (where and how a program runs) with +internal composition (which frontend lowers it, which steps compile it), and a workflow-combinator +framework whose reading cost exceeds its value, we decided to keep the established name `Backend` +for the user-facing object but make it an abstract base with a `name` and an `allocator`, with a +concrete `CompiledBackend` kind that carries a `compiler` and a `loader`; to take the frontend out +of the backend into a single global default composed with a compiled backend by an internal +`Toolchain`; to dispatch on the backend kind in one place; to rename the envelope and stage types; +to replace the combinator tower with explicit, fully typed pipelines; and to add a sanctioned +stage-observability seam. We accept that the changes break the old names outright (no aliases), +that a backend can no longer customize `compile` or its frontend, that the persistent +translation-cache keys rotate once more, and that downstream code that subclassed `Backend` or the +combinators must migrate. + +This partially supersedes [0011 - On The Fly Compilation](0011-On_The_Fly_Compilation.md) (the +workflow-combinator framework and the `otf.step_types` naming; its stage vocabulary and +build-system decisions remain valid), [0024 - Compilation Runners](0024-Compilation-Runners.md) +(the fallback for backends that customize `compile` no longer exists; the rest is unchanged), +[0027 - External Workspace Memory for DaCe Transients](0027-External_Workspace_Memory.md) (the +workspace is injected by a `CompiledBackend.loader`, not a `DaCeBackend` subclass) and +[0028 - Plain Builders Instead of factory-boy Factories](0028-Plain-Builders-Instead-of-Factories.md) +(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). + +## Context + +ADR 0017 defines **toolchain** as "all the code components that work together to go from DSL code +to an optimized, runnable python callable". The root object users pass as `backend=` had grown +into a toolchain in that sense: `Backend(name, executor, allocator, transforms)` held the frontend +transforms, the compile workflow, the loading logic (an overridable `load_artifact()` method) and +the allocator. Users, however, regard **backend** as the established name for "where and how my +program runs", covering both halves; renaming the user-facing object to `Toolchain` (the first +version of this ADR) was rejected in review for that reason, and because a complete rename would +have reached every `backend=` keyword, `with_backend`, `Program.backend` and the test framework. + +Looking at what the fields are actually used for: + +- **The frontend is not a per-backend choice.** Every in-tree backend uses the same + `DEFAULT_TRANSFORMS`; the one that built its own (`roundtrip.gtir`, a leftover of #1569) built an + identical one, differing only in owning separate in-memory caches. `Program` and `FieldOperator` + lower with `DEFAULT_TRANSFORMS` whenever they have no backend, and `FieldOperator.__gt_itir__` + ignores the backend's frontend on purpose (an operator called from a program must lower the same + way regardless of the operator's own backend). A per-backend frontend was a configuration point + that was not honoured consistently. +- **The allocator is the one thing every kind of execution needs.** Embedded execution has no + frontend, compiler or loader, but it allocates fields (tests and applications allocate with + `allocator=backend`); it is represented today by `backend=None`, which has no allocator, no name + and cannot be distinguished from "not configured". +- **`compile` and `load_artifact` were overridable methods.** A backend needing runtime data in the + loaded program subclassed the root object (ADR 0027's `DaCeBackend`), and ADR 0024 had to add an + "opaque" fallback for backends overriding `compile`, which cannot be decomposed for the process + pool. Test doubles relied on duck-typing `compile`. +- **`name` had no stated meaning.** It is used as a label in metrics, logs and diagnostics, while + builder docstrings claimed it "must stay unique" without anything enforcing or relying on it. + +Separately, the workflow-combinator framework introduced by ADR 0011 had grown to thirteen +abstractions (`Workflow`, two mixins, `NamedStepSequence`, `MultiWorkflow`, `StepSequence`, +`CachedStep`, `SkippableStep`, `make_step`, the `ConcreteArtifact` envelope and three adapters) to +express function composition (some of them already deleted as dead code in the preparatory +cleanup PRs). Measured against actual use, only `CachedStep` is a deep module; the others are +shallow wrappers around `Callable[[S], T]`, and the `NamedStepSequence.__call__` reflection loop is +`Any`-typed, defeating the static typing ADR 0011 prized. + +Finally, the seam between the compile route and its consumers has no sanctioned interface for +observing or running intermediate stages: the one consumer that needs an intermediate stage (the +dace `__sdfg__` path) duck-types into the default pipeline and mutates its stages. + +## Decision + +### Backend structure + +Sketch (step types as of the pipeline PR; until then `compiler` and `frontend` are typed +`workflow.Workflow[...]`): + +```python +@dataclasses.dataclass(frozen=True) +class Backend: # abstract: __post_init__ rejects `type(self) is Backend` + name: str + allocator: Allocator # array namespace or field-buffer allocator (factory) + + +@dataclasses.dataclass(frozen=True) +class CompiledBackend(Backend): + allocator: FieldBufferAllocatorProtocol + compiler: Step[CompilableProgram, CompilationArtifact] + loader: Callable[[CompilationArtifact], ExecutableProgram] = artifacts.load_artifact + + +@dataclasses.dataclass(frozen=True) +class Toolchain: # internal + backend: CompiledBackend + frontend: Step[ConcreteProgramDef, CompilableProgram] = DEFAULT_TRANSFORMS +``` + +- **`Backend` stays the user-facing name** (`gtx.typing.Backend`, `backend=`, `with_backend`, + `Program.backend`). It is an abstract base with two fields. Abstractness is enforced in + `__post_init__` rather than with abstract methods: there are none, and a required dataclass field + cannot implement an inherited abstract property. +- **`CompiledBackend`** is the kind that compiles. `compiler` turns the lowered program into a + loadable artifact and may run in a worker process; `loader` turns the artifact into a callable + and always runs in the calling process. Both are plain fields: customization is + composition-time (`dataclasses.replace(backend, compiler=...)`), never subclassing. `compile` is + 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 + 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 + happens (the compiled-programs pool, one-shot compiles, partial runs). `Toolchain` is not + exported from `gt4py.next` or `gtx.typing`; its `frontend` field exists for gt4py's own tests + and future internal use, not as a user customization point. +- **Dispatch on the backend kind lives in one helper** used by `Program`, `FieldOperator` and scan + operators: a `CompiledBackend` goes through the compiled-programs pool, embedded execution runs + the definition, anything else raises `TypeError`. Construction (`@program`, `with_backend`, + `dataclasses.replace`) additionally rejects objects that are not `Backend`s at all. +- **No opaque compile path.** With `compile` gone from the user-facing object, the + compilation-task layer always decomposes a compile into frontend (main process), compiler + (possibly offloaded) and loader (main process). A `compiler` that cannot be pickled still falls + back to the calling thread, as ADR 0024 describes. +- **`name` is a label.** It identifies the backend in metrics, logs and diagnostics. It is expected + to be unique among the backends used in a process; backends sharing a name are reported under the + same label. gt4py does not use it to identify a backend: not as a cache key and not in + fingerprints (`Program.backend` is excluded from fingerprints; translation caches are keyed on + the program and the step). Uniqueness is documented, not enforced. Generated builder names encode + only the device (and for DaCe the optimization level); callers distinguish other variants with + `name_postfix`. Code must not infer a backend's kind from its name: the dace SDFG conversion + checks the type of the translation step inside `compiler` instead, and other code should do the + same (`isinstance`, `is_dace_backend`). + +### Loading is a field + +`Backend.load_artifact()` was an overridable method, and a backend that needed backend-specific +runtime data in the loaded program subclassed the root object to override it (ADR 0027). +`CompiledBackend.loader` makes that seam a field — a plain callable defaulting to +`artifacts.load_artifact` — so customization stays composition-time, consistent with the rest of +this ADR, and the `DaCeBackend` subclass is replaced by a `DaCeLoader` holding the external +workspace (`backend.loader.external_workspace`). The loader lives on the backend rather than +inside the compile pipeline because loading also happens off the pipeline — the compiled-programs +pool loads artifacts straight from a compilation future — and because monolithic compilers have no +pipeline to hang it on. + +### Naming + +| Old (`main`) | New | +| ---------------------------------------------- | ------------------------------------------- | +| `Backend` (concrete) | `Backend` (abstract), `CompiledBackend` | +| `Backend.executor` | `CompiledBackend.compiler` | +| `Backend.transforms` | removed; internal `Toolchain.frontend` | +| `Backend.load_artifact()` | `CompiledBackend.loader` | +| `Backend.compile()` | internal `Toolchain.compile()` | +| `DaCeBackend` / `.external_workspace` | `DaCeLoader` / `.loader.external_workspace` | +| `make_gtfn_toolchain` / `make_dace_toolchain` | `make_gtfn_backend` / `make_dace_backend` | +| `make_dace_backend(gpu=..., ...)` (deprecated) | removed (its name is reused) | +| `ToolchainConfig` | `CompiledBackendConfig` | +| `OTFCompileWorkflow` | `CompilePipeline` | +| `ConcreteArtifact` / `.data` | `ProgramWithArgs` / `.definition` | +| `CompilableProgramDef` | `CompilableProgram` | +| `ItirShim.definition` | `ItirShim.operator_def` | + +The builders and their config base follow the new vocabulary, since they build a `CompiledBackend`. +The flat-keyword `make_dace_backend` was deprecated one release earlier (ADR 0028); it is removed +rather than kept because the config-based builder takes its name, and two builders with one name +cannot coexist. A call in the removed shape fails with a `TypeError` that explains the new +signature. + +These are hard renames: no deprecation aliases are kept, so the old names stop resolving in the +same release. The public `gtx.*` names (`gtx.gtfn_cpu`, `gtx.wait_for_compilation`, +`gtx.typing.Backend`, ...) are unchanged. + +We considered shipping one-release read aliases for the renamed attributes and re-export shims for +the moved modules. We rejected that: an alias that silently keeps working is exactly what lets a +downstream stay on the old vocabulary past the release where it was supposed to migrate, and the +aliases would have been partial anyway (constructing with the old keyword names could not be +aliased without hand-writing `__init__`, so `Backend(executor=...)` would have raised `TypeError` +regardless). A single loud break at a known release is easier to act on than a half-working +compatibility layer. `CompilableProgram` stays a type alias (of the parameterized envelope) for +now. + +### Pipeline, not combinators + +Named pipelines become frozen dataclasses with an explicit, fully typed `__call__`; steps are +plain callables (`Step[S, T] = Callable[[S], T]`); customization stays composition-time via +`dataclasses.replace`. The combinator framework (both mixins, `NamedStepSequence`, +`MultiWorkflow`, `StepSequence`, `make_step`, `.chain`, the three adapters) is deleted; +`CachedStep` is kept unchanged. The standard three-step `compiler` of the compiled backends +becomes `CompilePipeline` (translation, bindings, compilation); the frontend `Transforms` keeps its +input-dependent step selection. + +What ADR 0011's decisions become: + +| ADR 0011 requirement | Kept by | +| ------------------------------------------- | ----------------------------------------------------------------------- | +| Named steps, order visible | dataclass fields + explicit `__call__` (order literally visible) | +| Statically typed composition | explicit `__call__` — checked end-to-end, unlike the reflection loop | +| Customization at composition, not via flags | `dataclasses.replace` on frozen pipelines and backends | +| Steps compose across backends | `Step[S, T]` is a `Callable` — every existing step already satisfies it | +| Linear workflows | unchanged (`Transforms` keeps its input-dependent step *selection*) | + +### Stage observability + +A `stage_hook(name, artifact)` event hook (on the existing `instrumentation.hook_machinery`) is +emitted by `CompilePipeline` and `Transforms` after each step; artifacts are treated opaquely. +`GT4PY_DUMP_STAGES=` registers a subscriber that writes each stage artifact per program. +`Toolchain.translate(definition, compile_time_args)` is the sanctioned partial run (frontend + +translation only) for gt4py's own consumers, such as the dace SDFG conversion; it narrows to the +standard `CompilePipeline` shape of `backend.compiler` and raises a clear error on monolithic +compilers. Per-call step options are deliberately not offered — a caller needing a variant step +builds a variant backend with `dataclasses.replace(backend, compiler=dataclasses.replace(...))`. + +### Phasing + +The decisions in this ADR land as a stack of PRs. The backend structure, loader, naming (except +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. + +## Consequences + +- `gtx.typing.Backend`, `backend=`, `with_backend` and `Program.backend` keep their names; code + that only passes backend instances around (`gtx.gtfn_cpu`, `run_dace_cpu`, ...) is unaffected. +- Code that constructs or introspects backends must migrate: `CompiledBackend(name=..., allocator=..., compiler=..., loader=...)`, `.compiler` instead of `.executor`, `.loader` + instead of `load_artifact()`, `make_*_backend` instead of `make_*_toolchain` and + `CompiledBackendConfig` instead of `ToolchainConfig`. The old names are removed, not aliased; that includes `Backend` being instantiable (it is now abstract) and the + dissolved modules of the pipeline PR (`otf.definitions`, `otf.code_specs`, `otf.recipes`, + `otf.toolchain`). +- A backend can no longer change the frontend or override `compile`/`load_artifact`. Behaviour is + customized by replacing `compiler` or `loader`; duck-typed backend objects are rejected when the + program is constructed. +- Every compile is decomposable, so the process-pool runner never needs an opaque path; the only + remaining reason to compile in the calling thread is an unpicklable `compiler`. +- The dace `__sdfg__` reach-in (duck-typing through the compile pipeline's `translation` and + mutating frozen stages) is replaced by a dace-owned translate-only variant built with + `dataclasses.replace`, used through `Toolchain.translate`. +- Downstream code subclassing the deleted combinators or overriding `Transforms.step_order` must + migrate to explicit `__call__` composition. +- ADR 0011's `otf.step_types` naming section no longer describes the code. +- Cache keys rotate: fingerprints embed the qualified class and field names, so the + `ProgramWithArgs` / `definition` rename changes the keys of the persistent translation caches + (gtfn and dace). This is the *second* of two rotations in this stack — moving the same class from + `otf.toolchain` to `otf.workflow` already rotated them once, since the qualified name alone is + enough. What makes each a cold rebuild rather than a stale hit is that the key itself changes, so + entries written under the old name are never looked up; `BUILD_CACHE_VERSION_ID` (the gt4py + version) is a separate salt on top, which means the rotation costs nothing extra to anyone who + crosses a release — or, for a source install, any commit — boundary anyway. The two collapse into + a single cold rebuild if the whole stack lands in one release, which is the concrete argument for + not spreading it across releases. The backend restructuring itself rotates nothing: + `Program.backend` is excluded from fingerprints and no fingerprinted class gains or loses a field. + +## Alternatives considered + +- **Rename the user-facing `Backend` to `Toolchain`** (the first version of this ADR): rejected in + review. "Backend" is how users name the choice of execution, frontend included; the rename would + have had to reach every `backend=` keyword, `with_backend`, `Program.backend` and the test + framework to be consistent, and a partial rename produced code like `self.backend.backend`. +- **One concrete `Backend` with an optional `compiler`** (embedded = no compiler): rejected; every + consumer would branch on `compiler is None`, the type would not tell the two kinds apart, and an + embedded-specific behaviour (e.g. a future `jax.jit` execution) would have nowhere to go. +- **Keep the frontend as a field of `CompiledBackend`**: rejected; it was not honoured + consistently (see Context), embedded execution has none, and no backend uses a different one. +- **`allocator` as an abstract property on `Backend`**: does not work with dataclasses — a + required field in a subclass does not implement an inherited abstract property, and `dataclass` + re-runs `abc.update_abstractmethods`, so the subclass stays abstract. +- **Enforce name uniqueness** (registry or check at construction): rejected; nothing in gt4py relies + on uniqueness, test doubles and `dataclasses.replace` variants legitimately share names, and a + global registry would be process state for a label. +- **Keep overridable `compile` with the opaque process-pool fallback**: rejected; it made the + process pool's behaviour depend on how a backend was written, and every known override (test + doubles) is expressible by wrapping `compiler`. +- **Dispatch by polymorphism** (a method on `Backend`, e.g. `backend.run(program, args)` or + `backend.make_pool(...)`, instead of one `isinstance` helper): rejected; what happens per kind + (lowering with the global frontend, the compiled-programs pool, the embedded context and its + hooks) belongs to the `ffront` program objects, which import `backend.py` — moving it onto + `Backend` would invert that dependency, and an overridable method would reopen the "customized + `compile`" problem this ADR removes. The set of kinds is closed and small. +- **Keep `make_*_toolchain` / `ToolchainConfig`**: rejected; public builders named after an + internal class but returning a `CompiledBackend` would keep the vocabulary split this ADR + removes. +- **Keep the combinators but trim dead ones**: rejected — the tower is a shallow-module archetype + and every recorded ADR 0011 requirement survives its removal; trimming keeps the reading cost and + the `Any`-typed composition. +- **A per-call options API on `translate()`**: rejected — reconfiguration stays composition-time, + ADR 0011's own rule. diff --git a/docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md b/docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md deleted file mode 100644 index 937d94e295..0000000000 --- a/docs/development/ADRs/next/0029-Toolchain-Naming-and-Pipeline-Simplification.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -tags: [backend, otf, toolchain, workflows, naming, observability] ---- - -# Toolchain Naming and Pipeline Simplification - -- **Status**: valid -- **Authors**: Enrique González Paredes (@egparedes) -- **Created**: 2026-07-30 -- **Updated**: 2026-07-30 - -In the context of the on-the-fly compilation toolchain, facing a root object -whose names (`Backend`, `transforms`, `executor`) no longer match the -established *toolchain* vocabulary and a workflow-combinator framework whose -reading cost exceeds its value, we decided to rename the root object to -`Toolchain` (with `frontend` / `backend` halves), rename the envelope and -stage types accordingly, replace the combinator tower with explicit, fully -typed pipelines, and add a sanctioned stage-observability seam. We considered -keeping the combinators and trimming only the dead ones, and accept that the -renames break the old names outright, rotate the persistent translation-cache -keys (the second such rotation in this stack), and impose a migration burden -on downstream code that subclassed the combinators. - -This partially supersedes [0011 - On The Fly Compilation](0011-On_The_Fly_Compilation.md) -(the workflow-combinator framework and the `otf.step_types` naming — its stage -vocabulary and build-system decisions remain valid) and refines -[0017 - Toolchain Configuration](0017-Toolchain-Configuration.md) (whose term -*toolchain* becomes the name of the root object; its configuration decisions -remain valid). - -This builds on [0028 - Plain Builders Instead of factory-boy Factories](0028-Plain-Builders-Instead-of-Factories.md), -which replaced the factory classes that constructed these objects, so the -renames below land in plain, type-checked builder code. - -## Context - -ADR 0017 already defines **toolchain** as "all the code components that work -together to go from DSL code to an optimized, runnable python callable" — -JIT/OTF pipelines, transformation passes, lowerings, parsers. The code grew -into exactly that shape while keeping older names: the root object is called -`Backend`, its frontend half `transforms`, its backend half `executor`, and -the pipeline pieces are spread over five vaguely-named modules (`workflow`, -`toolchain`, `definitions`, `stages`, `recipes`). - -Separately, the workflow-combinator framework introduced by ADR 0011 had grown -to thirteen abstractions (`Workflow`, two mixins, `NamedStepSequence`, -`MultiWorkflow`, `StepSequence`, `CachedStep`, `SkippableStep`, `make_step`, -the `ConcreteArtifact` envelope and three adapters) to express function -composition (some of them already deleted as dead code in the preparatory -cleanup PRs). Measured against actual use, only `CachedStep` is a deep module; -the others are shallow wrappers around `Callable[[S], T]`, and the -`NamedStepSequence.__call__` reflection loop is `Any`-typed, defeating the -static typing ADR 0011 prized. - -Finally, the seam between the toolchain and its consumers has no sanctioned -interface for observing or running intermediate stages: the one consumer that -needs an intermediate stage (the dace `__sdfg__` path) duck-types into the -default pipeline and mutates its stages. - -## Decision - -### Naming - -| Old | New | -| ---------------------------- | --------------------------------- | -| `Backend` | `Toolchain` | -| `Backend.transforms` | `Toolchain.frontend` | -| `Backend.executor` | `Toolchain.backend` | -| `Backend.load_artifact()` | `Toolchain.loading` | -| `OTFCompileWorkflow` | `CompilePipeline` | -| `ConcreteArtifact` / `.data` | `ProgramWithArgs` / `.definition` | -| `CompilableProgramDef` | `CompilableProgram` | - -These are hard renames: no deprecation aliases are kept, so the old names stop -resolving in the same release. The public `gtx.*` names (`gtx.gtfn_cpu`, -`gtx.wait_for_compilation`, ...) are unchanged, with one exception — -`gtx.typing.Backend` becomes `gtx.typing.Toolchain`. - -We considered shipping one-release read aliases for the renamed attributes and -re-export shims for the moved modules. We rejected that: an alias that silently -keeps working is exactly what lets a downstream stay on the old vocabulary past -the release where it was supposed to migrate, and the aliases would have been -partial anyway (constructing with the old keyword names could not be aliased -without hand-writing `__init__`, so `Backend(executor=...)` would have raised -`TypeError` regardless). A single loud break at a known release is easier to -act on than a half-working compatibility layer. `CompilableProgram` stays a type -alias (of the parameterized envelope) for now. - -The last row is not a pure rename. `Backend.load_artifact()` was an overridable -method, and a toolchain that needed backend-specific runtime data in the loaded -program subclassed `Toolchain` to override it (see -[0027 - External Workspace Memory for DaCe Transients](0027-External_Workspace_Memory.md)). -`Toolchain.loading` makes that seam a field like the other three — a plain step -defaulting to `artifacts.load_artifact` — so customization stays -composition-time, consistent with the rest of this ADR. It also keeps -subclassing off the load path: per -[0024 - Compilation Runners](0024-Compilation-Runners.md), a toolchain that -customizes `compile` is opaque to the process-pool runner, and a -customization mechanism built on subclassing invites exactly that. The step -lives on `Toolchain` rather than inside `CompilePipeline` because loading also -happens off the pipeline — `CompiledProgramsPool` loads artifacts straight from -a compilation future — and because monolithic backends have no `CompilePipeline` -to hang it on. - -### Pipeline, not combinators - -Named pipelines become frozen dataclasses with an explicit, fully typed -`__call__`; steps are plain callables (`Step[S, T] = Callable[[S], T]`); -customization stays composition-time via `dataclasses.replace`. The -combinator framework (both mixins, `NamedStepSequence`, `MultiWorkflow`, -`StepSequence`, `make_step`, `.chain`, the three adapters) is deleted; -`CachedStep` is kept unchanged. - -What ADR 0011's decisions become: - -| ADR 0011 requirement | Kept by | -| ------------------------------------------- | ----------------------------------------------------------------------- | -| Named steps, order visible | dataclass fields + explicit `__call__` (order literally visible) | -| Statically typed composition | explicit `__call__` — checked end-to-end, unlike the reflection loop | -| Customization at composition, not via flags | `dataclasses.replace` on frozen pipelines | -| Steps compose across backends | `Step[S, T]` is a `Callable` — every existing step already satisfies it | -| Linear workflows | unchanged (`Transforms` keeps its input-dependent step *selection*) | - -### Stage observability - -A `stage_hook(name, artifact)` event hook (on the existing -`instrumentation.hook_machinery`) is emitted by `CompilePipeline` and -`Transforms` after each step; artifacts are treated opaquely. -`GT4PY_DUMP_STAGES=` registers a subscriber that writes each stage -artifact per program. `Toolchain.translate(definition, compile_time_args)` is -the sanctioned partial run (frontend + translation only); it narrows to the -standard `CompilePipeline` shape and raises a clear error on monolithic -backends. Per-call step options are deliberately not offered — a caller -needing a variant step builds a variant pipeline with `dataclasses.replace`. - -### Phasing - -The decisions in this ADR land as a stack of PRs. The naming decisions above -land first, except the `OTFCompileWorkflow` → `CompilePipeline` rename, which -lands with the pipeline PR; the "Pipeline, not combinators" and "Stage -observability" decisions are implemented in follow-up PRs of the same stack. - -## Consequences - -- The dace `__sdfg__` reach-in (duck-typing through `executor.translation` - and mutating frozen stages) will be replaced by a dace-owned translate-only - step built with `dataclasses.replace`. -- Downstream code subclassing the deleted combinators or overriding - `Transforms.step_order` must migrate to explicit `__call__` composition. -- Downstream code must migrate to the new names in the same release: the old - ones are removed, not aliased. That includes the modules dissolved along the - way — `otf.definitions`, `otf.code_specs`, `otf.recipes` and `otf.toolchain` - cease to exist, and `gtx.typing.Backend` becomes `gtx.typing.Toolchain`. -- ADR 0011's `otf.step_types` naming section no longer describes the code. -- Cache keys rotate: fingerprints embed the qualified class and field names, - so the `ProgramWithArgs` / `definition` rename changes the keys of the - persistent translation caches (gtfn and dace). This is the *second* of two - rotations in this stack — moving the same class from `otf.toolchain` to - `otf.workflow` already rotated them once, since the qualified name alone - is enough. What makes each a cold rebuild rather than a stale hit is that - the key itself changes, so entries written under the old name are never - looked up; `BUILD_CACHE_VERSION_ID` (the gt4py version) is a separate salt - on top, which means the rotation costs nothing extra to anyone who crosses - a release — or, for a source install, any commit — boundary anyway. The two - collapse into a single cold rebuild if the whole stack lands in one - release, which is the concrete argument for not spreading it across - releases. - -## Alternatives considered - -- **Keep the combinators but trim dead ones**: rejected — the tower is a - shallow-module archetype and every recorded ADR 0011 requirement survives - its removal; trimming keeps the reading cost and the `Any`-typed - composition. -- **A per-call options API on `translate()`**: rejected — reconfiguration - stays composition-time, ADR 0011's own rule. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index 29fe79fac5..40f77597ed 100644 --- a/docs/development/ADRs/next/README.md +++ b/docs/development/ADRs/next/README.md @@ -53,7 +53,7 @@ Writing a new ADR is simple: - [0017 - Toolchain Configuration](0017-Toolchain-Configuration.md) - [0027 - External Workspace Memory for DaCe Transients](0027-External_Workspace_Memory.md) - [0028 - Plain Builders Instead of factory-boy Factories](0028-Plain-Builders-Instead-of-Factories.md) -- [0029 - Toolchain Naming and Pipeline Simplification](0029-Toolchain-Naming-and-Pipeline-Simplification.md) +- [0029 - Backend Structure and Pipeline Simplification](0029-Backend-Structure-and-Pipeline-Simplification.md) ### Python Integration diff --git a/docs/user/next/advanced/HackTheToolchain.md b/docs/user/next/advanced/HackTheToolchain.md index e87396da9f..37f73f65c0 100644 --- a/docs/user/next/advanced/HackTheToolchain.md +++ b/docs/user/next/advanced/HackTheToolchain.md @@ -11,6 +11,13 @@ from gt4py import eve +> [!NOTE] +> The frontend (`gtx.backend.Transforms`, the definition transformations shown in the next two +> sections) is global and not a user customization point: a backend does not carry a frontend +> (ADR 0029). A modified `Transforms` can only be used through the internal +> `gtx.backend.Toolchain`, e.g. in gt4py's own tests. What a backend does is customized through +> its `compiler` and `loader`, see "Alternative Workflow" below. + ## Replace Steps ```python @@ -48,7 +55,7 @@ skip_linting_transforms.step_order(DUMMY_FOP) ## Alternative Workflow -A toolchain is built from one configuration, `GTFNConfig` (or `DaCeConfig`), +A compiled backend is built from one configuration, `GTFNConfig` (or `DaCeConfig`), which holds the settings all steps must agree on: the device, the build type, the cache lifetime, the data layout. Each step is created by a step builder that receives that configuration. To change a single setting of one step, pass @@ -60,7 +67,7 @@ import functools gtfn = gtx.program_processors.runners.gtfn -debug_gpu_no_transforms = gtfn.make_gtfn_toolchain( +debug_gpu_no_transforms = gtfn.make_gtfn_backend( gtfn.GTFNConfig(gpu=True, cmake_build_type=gtx.config.CMakeBuildType.DEBUG), name_postfix="_debug_no_transforms", translation=functools.partial(gtfn.make_gtfn_translation, enable_itir_transforms=False), diff --git a/docs/user/next/advanced/WorkflowPatterns.md b/docs/user/next/advanced/WorkflowPatterns.md index d2556b2bc0..73be1cbd43 100644 --- a/docs/user/next/advanced/WorkflowPatterns.md +++ b/docs/user/next/advanced/WorkflowPatterns.md @@ -185,7 +185,7 @@ cached_calc(1) ### Example in the Wild ```python -gtx.backend.DEFAULT_PROG_TRANSFORMS.past_lint?? +gtx.backend.DEFAULT_TRANSFORMS.past_lint?? ``` @@ -395,13 +395,13 @@ proc.hexify_colors("blue") ### Example in the Wild ```python editable=true slideshow={"slide_type": ""} -gtx.backend.DEFAULT_PROG_TRANSFORMS?? +gtx.backend.DEFAULT_TRANSFORMS?? ``` ```python -gtx.program_processors.runners.gtfn.run_gtfn_gpu.backend?? +gtx.program_processors.runners.gtfn.run_gtfn_gpu.compiler?? ``` ```python -gtx.program_processors.runners.gtfn.make_gtfn_toolchain?? +gtx.program_processors.runners.gtfn.make_gtfn_backend?? ``` diff --git a/src/gt4py/next/AGENTS.md b/src/gt4py/next/AGENTS.md index ea94beaf17..22fe51bfb9 100644 --- a/src/gt4py/next/AGENTS.md +++ b/src/gt4py/next/AGENTS.md @@ -31,9 +31,10 @@ field operators / programs (ffront) Distinct from `iterator/embedded.py`, which runs one level lower. - `otf/` — on-the-fly compilation toolchain (workflow steps, caching, argument descriptors). -- `backend.py` — the toolchain root object `Toolchain` (formerly `Backend`): - `frontend` (definition transforms) + `backend` (compile pipeline) + - allocator. +- `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). - `type_system/` — `next` type specifications and the type inference the From 49dadf2a6a857ec007cc300f39e0990828485f20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Thu, 29 Oct 2026 09:11:43 +0100 Subject: [PATCH 08/10] fix[next-dace]: do not mutate the cached frontend result in Program.__sdfg__ `__sdfg__` lowers through the shared frontend and then overwrote the cached `past_to_itir` result in place (transformed definition, offset provider types instead of tables). Every later compilation of the same program reused the corrupted stage, so running it on another backend failed (an assertion in domain inference, or `'NeighborConnectivityType' object has no attribute 'asnumpy'` when offloading the compilation). Build a new stage instead. The bug exists on main for the backends sharing the default frontend; the previous commits extended it to `roundtrip.gtir`, which now shares it too. Found in an adversarial review of #2741. --- .../runners/dace/program.py | 25 +++++++++------ .../feature_tests/dace_tests/test_program.py | 32 ++++++++++++++++++- 2 files changed, 47 insertions(+), 10 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/program.py b/src/gt4py/next/program_processors/runners/dace/program.py index b11454c25e..2270d03912 100644 --- a/src/gt4py/next/program_processors/runners/dace/program.py +++ b/src/gt4py/next/program_processors/runners/dace/program.py @@ -61,17 +61,24 @@ def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: program = itir_transforms.apply_fieldview_transforms( # run the transforms separately because they require the runtime info program, offset_provider=offset_provider ) - object.__setattr__( + # `gtir_stage` is the cached result of the shared frontend: build a new stage + # instead of mutating it, otherwise every later compilation of this program + # (on any backend) would get the transformed definition and offset provider types. + # TODO(ricoh): the offset provider types isolate DaCe from the runtime tables in + # connectivities.offset_provider, which are needed at the time of writing for + # mandatory GTIR passes. Remove this as soon as Program does not expect + # connectivity tables anymore. + gtir_stage = dataclasses.replace( gtir_stage, - "definition", - program, + definition=program, + args=dataclasses.replace( + gtir_stage.args, + # `CompileTimeArgs.offset_provider` is still typed as the runtime + # mapping, even though the mandatory GTIR passes are the only + # consumers needing the tables and they already ran above. + offset_provider=gtir_stage.args.offset_provider_type, # type: ignore[arg-type] + ), ) - object.__setattr__( - gtir_stage.args, "offset_provider", gtir_stage.args.offset_provider_type - ) # TODO(ricoh): currently this is circumventing the frozenness of CompileTimeArgs - # in order to isolate DaCe from the runtime tables in connectivities.offset_provider. - # These are needed at the time of writing for mandatory GTIR passes. - # Remove this as soon as Program does not expect connectivity tables anymore. _crosscheck_dace_parsing( dace_parsed_args=[*args, *kwargs.values()], diff --git a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py index 227aac2143..bb76bdabe0 100644 --- a/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py +++ b/tests/next_tests/integration_tests/feature_tests/dace_tests/test_program.py @@ -9,6 +9,7 @@ import dataclasses import dace +import numpy as np import pytest from gt4py import next as gtx @@ -17,6 +18,8 @@ from next_tests.integration_tests import cases from next_tests.integration_tests.cases_utils import ( Cell, + E2V, + E2VDim, Edge, IDim, JDim, @@ -25,7 +28,7 @@ mesh_descriptor, # noqa: F401 ) -from gt4py.next.program_processors.runners import dace as dace_backends, gtfn +from gt4py.next.program_processors.runners import dace as dace_backends, gtfn, roundtrip # Override the exec_alloc_descriptor with a custom Backend, @@ -125,6 +128,33 @@ def testee(a: gtx.Field[[Vertex], gtx.int], out: gtx.Field[[Vertex], gtx.int]): assert isinstance(sdfg, dace.SDFG) +def test_sdfg_conversion_does_not_alter_the_cached_lowering(exec_alloc_descriptor): + # `__sdfg__` lowers through the shared frontend, whose results are cached: it must + # not change the cached result, which later compilations on any backend reuse. + e2v = gtx.as_connectivity( + [Edge, E2VDim], Vertex, np.array([[0, 1], [1, 2], [2, 0]], dtype=gtx.IndexType) + ) + offset_provider = {"E2V": e2v} + + @gtx.program(backend=exec_alloc_descriptor) + def testee(a: gtx.Field[[Vertex], gtx.float64], out: gtx.Field[[Edge], gtx.float64]): + _first_vertex(a, out=out) + + testee = testee.with_compilation_options(connectivities=offset_provider) + testee.__sdfg__() + + a = gtx.as_field([Vertex], np.arange(3.0)) + out = gtx.zeros({Edge: 3}) + testee.with_backend(roundtrip.default)(a, out, offset_provider=offset_provider) + + np.testing.assert_array_equal(out.asnumpy(), a.asnumpy()) + + @gtx.field_operator def _copy(a: gtx.Field[[Vertex], gtx.int]) -> gtx.Field[[Vertex], gtx.int]: return a + + +@gtx.field_operator +def _first_vertex(a: gtx.Field[[Vertex], gtx.float64]) -> gtx.Field[[Edge], gtx.float64]: + return a(E2V[0]) From f8c23ad70b3dd3b810820e0b4b65f2bec1d137a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Thu, 29 Oct 2026 09:27:53 +0100 Subject: [PATCH 09/10] docs[next]: restructure ADR 0029 around the final design Present the backend structure first on its own terms (concepts, the route from definition to callable, customization, pipelines, observability) and move the transition from the old structure (name mapping, removed mechanisms, no-alias policy, cache-key rotation, phasing, earlier ADRs) into a later section. No decision changes. Also corrects claims that did not match the code: compiling in the calling thread is not only the unpicklable-compiler fallback (serial mode), the cache version salt does not change on every source commit, `__sdfg__` no longer mutates the cached stage, and DaCe names encode whether auto-optimization is on. --- ...d-Structure-and-Pipeline-Simplification.md | 450 +++++++++--------- 1 file changed, 214 insertions(+), 236 deletions(-) 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..9a9a116974 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 @@ -7,89 +7,40 @@ tags: [backend, otf, toolchain, workflows, naming, observability] - **Status**: valid - **Authors**: Enrique González Paredes (@egparedes) - **Created**: 2026-07-30 -- **Updated**: 2026-10-28 - -In the context of the object users pass as `backend=` and the on-the-fly compilation route behind -it, facing a root object that mixes a user-facing concept (where and how a program runs) with -internal composition (which frontend lowers it, which steps compile it), and a workflow-combinator -framework whose reading cost exceeds its value, we decided to keep the established name `Backend` -for the user-facing object but make it an abstract base with a `name` and an `allocator`, with a -concrete `CompiledBackend` kind that carries a `compiler` and a `loader`; to take the frontend out -of the backend into a single global default composed with a compiled backend by an internal -`Toolchain`; to dispatch on the backend kind in one place; to rename the envelope and stage types; -to replace the combinator tower with explicit, fully typed pipelines; and to add a sanctioned -stage-observability seam. We accept that the changes break the old names outright (no aliases), -that a backend can no longer customize `compile` or its frontend, that the persistent -translation-cache keys rotate once more, and that downstream code that subclassed `Backend` or the -combinators must migrate. +- **Updated**: 2026-10-29 -This partially supersedes [0011 - On The Fly Compilation](0011-On_The_Fly_Compilation.md) (the -workflow-combinator framework and the `otf.step_types` naming; its stage vocabulary and -build-system decisions remain valid), [0024 - Compilation Runners](0024-Compilation-Runners.md) -(the fallback for backends that customize `compile` no longer exists; the rest is unchanged), -[0027 - External Workspace Memory for DaCe Transients](0027-External_Workspace_Memory.md) (the -workspace is injected by a `CompiledBackend.loader`, not a `DaCeBackend` subclass) and -[0028 - Plain Builders Instead of factory-boy Factories](0028-Plain-Builders-Instead-of-Factories.md) -(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). - -## Context - -ADR 0017 defines **toolchain** as "all the code components that work together to go from DSL code -to an optimized, runnable python callable". The root object users pass as `backend=` had grown -into a toolchain in that sense: `Backend(name, executor, allocator, transforms)` held the frontend -transforms, the compile workflow, the loading logic (an overridable `load_artifact()` method) and -the allocator. Users, however, regard **backend** as the established name for "where and how my -program runs", covering both halves; renaming the user-facing object to `Toolchain` (the first -version of this ADR) was rejected in review for that reason, and because a complete rename would -have reached every `backend=` keyword, `with_backend`, `Program.backend` and the test framework. - -Looking at what the fields are actually used for: - -- **The frontend is not a per-backend choice.** Every in-tree backend uses the same - `DEFAULT_TRANSFORMS`; the one that built its own (`roundtrip.gtir`, a leftover of #1569) built an - identical one, differing only in owning separate in-memory caches. `Program` and `FieldOperator` - lower with `DEFAULT_TRANSFORMS` whenever they have no backend, and `FieldOperator.__gt_itir__` - ignores the backend's frontend on purpose (an operator called from a program must lower the same - way regardless of the operator's own backend). A per-backend frontend was a configuration point - that was not honoured consistently. -- **The allocator is the one thing every kind of execution needs.** Embedded execution has no - frontend, compiler or loader, but it allocates fields (tests and applications allocate with - `allocator=backend`); it is represented today by `backend=None`, which has no allocator, no name - and cannot be distinguished from "not configured". -- **`compile` and `load_artifact` were overridable methods.** A backend needing runtime data in the - loaded program subclassed the root object (ADR 0027's `DaCeBackend`), and ADR 0024 had to add an - "opaque" fallback for backends overriding `compile`, which cannot be decomposed for the process - pool. Test doubles relied on duck-typing `compile`. -- **`name` had no stated meaning.** It is used as a label in metrics, logs and diagnostics, while - builder docstrings claimed it "must stay unique" without anything enforcing or relying on it. - -Separately, the workflow-combinator framework introduced by ADR 0011 had grown to thirteen -abstractions (`Workflow`, two mixins, `NamedStepSequence`, `MultiWorkflow`, `StepSequence`, -`CachedStep`, `SkippableStep`, `make_step`, the `ConcreteArtifact` envelope and three adapters) to -express function composition (some of them already deleted as dead code in the preparatory -cleanup PRs). Measured against actual use, only `CachedStep` is a deep module; the others are -shallow wrappers around `Callable[[S], T]`, and the `NamedStepSequence.__call__` reflection loop is -`Any`-typed, defeating the static typing ADR 0011 prized. - -Finally, the seam between the compile route and its consumers has no sanctioned interface for -observing or running intermediate stages: the one consumer that needs an intermediate stage (the -dace `__sdfg__` path) duck-types into the default pipeline and mutates its stages. +In the context of the compilation route behind `backend=`, we decided to keep a public, +abstract `Backend` describing execution and allocation, with `CompiledBackend` carrying a compiler +and loader, and an internal `Toolchain` composing it with the global frontend. We use explicit, +fully typed pipelines and a sanctioned interface for observing and running intermediate stages. +We accept hard breaks in internal names, removal of backend-specific frontends and overridable +compilation/loading methods, a persistent translation-cache rotation, and downstream subclass migration. ## Decision -### Backend structure +### Concepts and composition + +A **toolchain** is the complete route from DSL code to an optimized, runnable Python callable. + +| Concept | Responsibility and interface | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Backend` | Public abstract execution choice: a `name` and an `allocator`. Used by `gtx.typing.Backend`, `backend=`, `with_backend` and `Program.backend`. | +| Allocator | Provides field buffers; the base accepts an array namespace or a field-buffer allocator (factory), while compiled backends require `FieldBufferAllocatorProtocol`. | +| `CompiledBackend` | The backend kind that compiles: owns `compiler`, `loader` and the allocator for the target device. | +| Frontend | Lowers a program definition and its arguments into a `CompilableProgram`. | +| Global frontend | `DEFAULT_TRANSFORMS`, shared by all backends; no backend owns or selects a frontend. | +| Compiler | Turns a `CompilableProgram` into a loadable `CompilationArtifact`, possibly in a worker process. | +| Loader | Turns that artifact into an `ExecutableProgram` in the calling process; defaults to `artifacts.load_artifact`. | +| `Toolchain` | Internal composition of the global frontend with a `CompiledBackend`, created where compilation happens. | -Sketch (step types as of the pipeline PR; until then `compiler` and `frontend` are typed -`workflow.Workflow[...]`): +The objects are frozen dataclasses. This sketch uses the target pipeline types; in #2741, +`compiler` and `frontend` still use `workflow.Workflow[...]`: ```python @dataclasses.dataclass(frozen=True) -class Backend: # abstract: __post_init__ rejects `type(self) is Backend` +class Backend: # __post_init__ rejects type(self) is Backend name: str - allocator: Allocator # array namespace or field-buffer allocator (factory) + allocator: Allocator @dataclasses.dataclass(frozen=True) @@ -105,55 +56,112 @@ class Toolchain: # internal frontend: Step[ConcreteProgramDef, CompilableProgram] = DEFAULT_TRANSFORMS ``` -- **`Backend` stays the user-facing name** (`gtx.typing.Backend`, `backend=`, `with_backend`, - `Program.backend`). It is an abstract base with two fields. Abstractness is enforced in - `__post_init__` rather than with abstract methods: there are none, and a required dataclass field - cannot implement an inherited abstract property. -- **`CompiledBackend`** is the kind that compiles. `compiler` turns the lowered program into a - loadable artifact and may run in a worker process; `loader` turns the artifact into a callable - and always runs in the calling process. Both are plain fields: customization is - composition-time (`dataclasses.replace(backend, compiler=...)`), never subclassing. `compile` is - 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 - 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 - happens (the compiled-programs pool, one-shot compiles, partial runs). `Toolchain` is not - exported from `gt4py.next` or `gtx.typing`; its `frontend` field exists for gt4py's own tests - and future internal use, not as a user customization point. -- **Dispatch on the backend kind lives in one helper** used by `Program`, `FieldOperator` and scan - operators: a `CompiledBackend` goes through the compiled-programs pool, embedded execution runs - the definition, anything else raises `TypeError`. Construction (`@program`, `with_backend`, - `dataclasses.replace`) additionally rejects objects that are not `Backend`s at all. -- **No opaque compile path.** With `compile` gone from the user-facing object, the - compilation-task layer always decomposes a compile into frontend (main process), compiler - (possibly offloaded) and loader (main process). A `compiler` that cannot be pickled still falls - back to the calling thread, as ADR 0024 describes. -- **`name` is a label.** It identifies the backend in metrics, logs and diagnostics. It is expected - to be unique among the backends used in a process; backends sharing a name are reported under the - same label. gt4py does not use it to identify a backend: not as a cache key and not in - fingerprints (`Program.backend` is excluded from fingerprints; translation caches are keyed on - the program and the step). Uniqueness is documented, not enforced. Generated builder names encode - only the device (and for DaCe the optimization level); callers distinguish other variants with - `name_postfix`. Code must not infer a backend's kind from its name: the dace SDFG conversion - checks the type of the translation step inside `compiler` instead, and other code should do the - same (`isinstance`, `is_dace_backend`). - -### Loading is a field - -`Backend.load_artifact()` was an overridable method, and a backend that needed backend-specific -runtime data in the loaded program subclassed the root object to override it (ADR 0027). -`CompiledBackend.loader` makes that seam a field — a plain callable defaulting to -`artifacts.load_artifact` — so customization stays composition-time, consistent with the rest of -this ADR, and the `DaCeBackend` subclass is replaced by a `DaCeLoader` holding the external -workspace (`backend.loader.external_workspace`). The loader lives on the backend rather than -inside the compile pipeline because loading also happens off the pipeline — the compiled-programs -pool loads artifacts straight from a compilation future — and because monolithic compilers have no -pipeline to hang it on. - -### Naming +`Backend` has no abstract methods; `__post_init__` enforces abstractness. `Toolchain` is not exported from +`gt4py.next` or `gtx.typing`; its frontend field is for GT4Py tests and future internal use, not +user customization. Embedded execution remains `backend=None` in this PR. A sibling +`EmbeddedBackend(Backend)`, rather than a mode of `CompiledBackend`, and retirement of `None` +are decided separately in ADR 0030 (follow-up #2956). + +### From definition to callable + +```text +program definition + compile-time arguments + -> global frontend [calling process] + -> CompilableProgram + -> backend.compiler [runner: possibly a worker process] + -> CompilationArtifact + -> backend.loader [calling process] + -> ExecutableProgram [callable] +``` + +One helper dispatches on backend kind for `Program`, `FieldOperator` and scan operators: +a `CompiledBackend` uses the compiled-programs pool; `None` runs the definition in embedded +execution; unsupported kinds raise `TypeError`. Construction (`@program`, `with_backend`, +`dataclasses.replace`) rejects objects that are neither a `Backend` nor `None`. + +The pool uses an internal `Toolchain`. The compilation-task layer runs its frontend main-side, +then submits the compiler and lowered program to the compilation runner. The process runner +returns an artifact through a future; the pool loads it on first use in the calling process. +A compiler that cannot be pickled falls back to the calling thread, with a warning. Serial and +thread runners remain available as specified in ADR 0024. Every task is decomposable; there is +no opaque compilation path. For one-shot compilation, internal `Toolchain.compile()` runs +frontend, compiler and loader synchronously in the calling thread. No `Backend` has a `compile` +method. + +The loader belongs to the backend, outside its compiler: the pool loads directly from compilation +futures, and a monolithic compiler has no pipeline on which to place loading. DaCe supplies a +`DaCeLoader` carrying the caller's external workspace at `backend.loader.external_workspace` and +injecting it into the loaded program. + +### Customization and names + +Customize by composition, not subclassing: replace `compiler` or `loader` with +`dataclasses.replace(backend, compiler=...)`, or replace steps inside a pipeline. +`make_gtfn_backend` and `make_dace_backend` build compiled +backends, with family configs based on `CompiledBackendConfig`; ADR 0028's composition rules remain. + +`name` is a label for metrics, logs and diagnostics. Uniqueness among backends in a process is +expected and documented, not enforced; shared names are reported under the same label. Names +identify neither cache entries nor fingerprints: `Program.backend` is excluded from fingerprints, +and translation caches key on the program and step. Generated names encode the device and, for +DaCe, whether auto-optimization is enabled; callers distinguish other variants with `name_postfix`. +Determine backend kind by types, never names (`isinstance`, `is_dace_backend`). The DaCe check +inspects the standard compiler's translation step, through a `CachedStep` if present. + +### Explicit typed pipelines + +In the target design, named pipelines are frozen dataclasses with explicit, fully typed `__call__` +methods and callable steps (`Step[S, T] = Callable[[S], T]`). The standard compiler becomes +`CompilePipeline`: translation, bindings, compilation. + +| ADR 0011 requirement | Kept by | +| ------------------------------------------- | ----------------------------------------------------------------------- | +| Named steps, order visible | dataclass fields + explicit `__call__` (order literally visible) | +| Statically typed composition | explicit `__call__` — checked end-to-end, unlike the reflection loop | +| Customization at composition, not via flags | `dataclasses.replace` on frozen pipelines and backends | +| Steps compose across backends | `Step[S, T]` is a `Callable` — every existing step already satisfies it | +| Linear workflows | unchanged (`Transforms` keeps its input-dependent step *selection*) | + +### Stage observability + +In the target design, a `stage_hook(name, artifact)` event hook on `instrumentation.hook_machinery` is +emitted by `CompilePipeline` and `Transforms` after each step; artifacts are treated opaquely. +`GT4PY_DUMP_STAGES=` registers a subscriber that writes each stage artifact per program. +`Toolchain.translate(definition, compile_time_args)` is the sanctioned partial run (frontend + +translation only) for gt4py's own consumers, such as the dace SDFG conversion; it narrows to the +standard `CompilePipeline` shape of `backend.compiler` and raises a clear error on monolithic +compilers. Per-call step options are deliberately not offered — a caller needing a variant step +builds a variant backend with `dataclasses.replace(backend, compiler=dataclasses.replace(...))`. +In #2742, DaCe's `__sdfg__` reach-in becomes a DaCe-owned translate-only variant built this way +and run through `Toolchain.translate`. + +## Context and transition + +The previous `Backend(name, executor, allocator, transforms)` combined frontend transforms, +compilation, overridable loading and allocation. Users call the execution choice a backend, +including the frontend, but its internal composition is a toolchain in ADR 0017's sense. + +- Every backend used `DEFAULT_TRANSFORMS`, except `roundtrip.gtir` (a #1569 leftover), which + built identical transforms with separate in-memory caches. `Program` and `FieldOperator` used + the default without a backend; `FieldOperator.__gt_itir__` ignored its backend's frontend to + lower consistently inside programs. Per-backend frontend settings were inconsistently honoured. +- All execution kinds allocate: tests and applications use `allocator=backend`. Embedded execution + needs no frontend, compiler or loader, but its `None` representation has neither allocator nor + name and is indistinguishable from “not configured”. +- Overridable `compile` and `load_artifact` led to ADR 0027's `DaCeBackend` subclass and ADR 0024's + opaque fallback for compilation that cannot be decomposed for the process pool. + Test doubles duck-typed `compile`. +- Builder docstrings said names “must stay unique”, though nothing enforced or relied on it. +- ADR 0011's framework grew to thirteen abstractions: `Workflow`, two mixins, + `NamedStepSequence`, `MultiWorkflow`, `StepSequence`, `CachedStep`, `SkippableStep`, `make_step`, + `ConcreteArtifact` and three adapters. Some were already removed as dead code in preparatory + PRs. Only `CachedStep` is a deep module; the rest wrap `Callable[[S], T]`, and the + `NamedStepSequence.__call__` reflection loop is `Any`-typed, defeating static composition. +- Intermediate stages had no sanctioned interface. DaCe's `__sdfg__` historically mutated frozen + stages; #2741 copies the cached frontend stage with `dataclasses.replace`, but still reaches + into the translation step until #2742. + +### Names and removed mechanisms | Old (`main`) | New | | ---------------------------------------------- | ------------------------------------------- | @@ -166,132 +174,102 @@ pipeline to hang it on. | `make_gtfn_toolchain` / `make_dace_toolchain` | `make_gtfn_backend` / `make_dace_backend` | | `make_dace_backend(gpu=..., ...)` (deprecated) | removed (its name is reused) | | `ToolchainConfig` | `CompiledBackendConfig` | -| `OTFCompileWorkflow` | `CompilePipeline` | +| `OTFCompileWorkflow` | `CompilePipeline` (in #2743) | | `ConcreteArtifact` / `.data` | `ProgramWithArgs` / `.definition` | | `CompilableProgramDef` | `CompilableProgram` | | `ItirShim.definition` | `ItirShim.operator_def` | -The builders and their config base follow the new vocabulary, since they build a `CompiledBackend`. -The flat-keyword `make_dace_backend` was deprecated one release earlier (ADR 0028); it is removed -rather than kept because the config-based builder takes its name, and two builders with one name -cannot coexist. A call in the removed shape fails with a `TypeError` that explains the new -signature. +The builders and config base are named for the `CompiledBackend` they build. The flat-keyword +`make_dace_backend`, deprecated one release earlier (ADR 0028), is removed because the config-based +builder takes its name: two builders cannot share it. Old-style calls raise `TypeError` explaining +the new signature. These are hard renames: no deprecation aliases are kept, so the old names stop resolving in the same release. The public `gtx.*` names (`gtx.gtfn_cpu`, `gtx.wait_for_compilation`, `gtx.typing.Backend`, ...) are unchanged. -We considered shipping one-release read aliases for the renamed attributes and re-export shims for -the moved modules. We rejected that: an alias that silently keeps working is exactly what lets a -downstream stay on the old vocabulary past the release where it was supposed to migrate, and the -aliases would have been partial anyway (constructing with the old keyword names could not be -aliased without hand-writing `__init__`, so `Backend(executor=...)` would have raised `TypeError` -regardless). A single loud break at a known release is easier to act on than a half-working -compatibility layer. `CompilableProgram` stays a type alias (of the parameterized envelope) for -now. +One-release attribute aliases and module re-export shims were rejected: they let downstream code +postpone migration and provide only partial compatibility. Old constructor keywords still require +a handwritten `__init__`; otherwise `Backend(executor=...)` raises `TypeError`. One explicit break +at a known release is easier to act on. `CompilableProgram` remains a parameterized-envelope type alias. + +The overridable `compile`/`load_artifact` methods, `DaCeBackend` subclass, opaque “customized +compile” path and `CompilationTask.no_offload_reason` are removed. The pipeline PR removes the +combinator framework (both mixins, `NamedStepSequence`, `MultiWorkflow`, `StepSequence`, +`make_step`, `.chain` and the three adapters), and dissolves `otf.definitions`, `otf.code_specs`, +`otf.recipes` and `otf.toolchain`. `CachedStep` remains unchanged. + +### Cache-key rotation + +Fingerprints include qualified class and field names. Renaming `ConcreteArtifact.data` to +`ProgramWithArgs.definition` changes persistent translation-cache keys for GTFN and DaCe. This +is the second rotation in the stack: moving the envelope from `otf.toolchain` to `otf.workflow` +already changed its qualified name. Old entries are never looked up under new keys, so each +rotation causes a cold rebuild, not a stale hit. + +`BUILD_CACHE_VERSION_ID` is a separate salt, defaulting to the GT4Py version (and overridable via +`GT4PY_BUILD_CACHE_VERSION_ID`). When a release or source-install version change already changes +that salt, the rename adds no further rebuild. A source commit does not unconditionally change +the salt: version discovery can fall back to installed metadata, and an explicit override can +hold it constant. Users upgrading across the entire stack in one release see one cold rebuild; +this argues against spreading it across releases. Backend restructuring itself rotates nothing: +`Program.backend` is excluded and no fingerprinted class gains or loses a field from that change. + +### Phasing and earlier decisions + +#2741 lands the backend structure, loader, naming except `CompilePipeline`, and removal of the +opaque compile path. #2742 adds stage observability, including `Toolchain.translate`; #2743 +replaces the combinators and renames `OTFCompileWorkflow` to `CompilePipeline`. Thus the pipeline +and observability sections describe the target design, not APIs already available at #2741. +Embedded backends follow separately under ADR 0030 (#2956). -### Pipeline, not combinators - -Named pipelines become frozen dataclasses with an explicit, fully typed `__call__`; steps are -plain callables (`Step[S, T] = Callable[[S], T]`); customization stays composition-time via -`dataclasses.replace`. The combinator framework (both mixins, `NamedStepSequence`, -`MultiWorkflow`, `StepSequence`, `make_step`, `.chain`, the three adapters) is deleted; -`CachedStep` is kept unchanged. The standard three-step `compiler` of the compiled backends -becomes `CompilePipeline` (translation, bindings, compilation); the frontend `Transforms` keeps its -input-dependent step selection. - -What ADR 0011's decisions become: - -| ADR 0011 requirement | Kept by | -| ------------------------------------------- | ----------------------------------------------------------------------- | -| Named steps, order visible | dataclass fields + explicit `__call__` (order literally visible) | -| Statically typed composition | explicit `__call__` — checked end-to-end, unlike the reflection loop | -| Customization at composition, not via flags | `dataclasses.replace` on frozen pipelines and backends | -| Steps compose across backends | `Step[S, T]` is a `Callable` — every existing step already satisfies it | -| Linear workflows | unchanged (`Transforms` keeps its input-dependent step *selection*) | - -### Stage observability - -A `stage_hook(name, artifact)` event hook (on the existing `instrumentation.hook_machinery`) is -emitted by `CompilePipeline` and `Transforms` after each step; artifacts are treated opaquely. -`GT4PY_DUMP_STAGES=` registers a subscriber that writes each stage artifact per program. -`Toolchain.translate(definition, compile_time_args)` is the sanctioned partial run (frontend + -translation only) for gt4py's own consumers, such as the dace SDFG conversion; it narrows to the -standard `CompilePipeline` shape of `backend.compiler` and raises a clear error on monolithic -compilers. Per-call step options are deliberately not offered — a caller needing a variant step -builds a variant backend with `dataclasses.replace(backend, compiler=dataclasses.replace(...))`. - -### Phasing - -The decisions in this ADR land as a stack of PRs. The backend structure, loader, naming (except -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. +This partially supersedes [0011 - On The Fly Compilation](0011-On_The_Fly_Compilation.md) (the +workflow-combinator framework and the `otf.step_types` naming; its stage vocabulary and +build-system decisions remain valid), [0024 - Compilation Runners](0024-Compilation-Runners.md) +(the fallback for backends that customize `compile` no longer exists; the rest is unchanged), +[0027 - External Workspace Memory for DaCe Transients](0027-External_Workspace_Memory.md) (the +workspace is injected by a `CompiledBackend.loader`, not a `DaCeBackend` subclass) and +[0028 - Plain Builders Instead of factory-boy Factories](0028-Plain-Builders-Instead-of-Factories.md) +(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). ## Consequences -- `gtx.typing.Backend`, `backend=`, `with_backend` and `Program.backend` keep their names; code - that only passes backend instances around (`gtx.gtfn_cpu`, `run_dace_cpu`, ...) is unaffected. -- Code that constructs or introspects backends must migrate: `CompiledBackend(name=..., allocator=..., compiler=..., loader=...)`, `.compiler` instead of `.executor`, `.loader` - instead of `load_artifact()`, `make_*_backend` instead of `make_*_toolchain` and - `CompiledBackendConfig` instead of `ToolchainConfig`. The old names are removed, not aliased; that includes `Backend` being instantiable (it is now abstract) and the - dissolved modules of the pipeline PR (`otf.definitions`, `otf.code_specs`, `otf.recipes`, - `otf.toolchain`). -- A backend can no longer change the frontend or override `compile`/`load_artifact`. Behaviour is - customized by replacing `compiler` or `loader`; duck-typed backend objects are rejected when the - program is constructed. -- Every compile is decomposable, so the process-pool runner never needs an opaque path; the only - remaining reason to compile in the calling thread is an unpicklable `compiler`. -- The dace `__sdfg__` reach-in (duck-typing through the compile pipeline's `translation` and - mutating frozen stages) is replaced by a dace-owned translate-only variant built with - `dataclasses.replace`, used through `Toolchain.translate`. -- Downstream code subclassing the deleted combinators or overriding `Transforms.step_order` must - migrate to explicit `__call__` composition. -- ADR 0011's `otf.step_types` naming section no longer describes the code. -- Cache keys rotate: fingerprints embed the qualified class and field names, so the - `ProgramWithArgs` / `definition` rename changes the keys of the persistent translation caches - (gtfn and dace). This is the *second* of two rotations in this stack — moving the same class from - `otf.toolchain` to `otf.workflow` already rotated them once, since the qualified name alone is - enough. What makes each a cold rebuild rather than a stale hit is that the key itself changes, so - entries written under the old name are never looked up; `BUILD_CACHE_VERSION_ID` (the gt4py - version) is a separate salt on top, which means the rotation costs nothing extra to anyone who - crosses a release — or, for a source install, any commit — boundary anyway. The two collapse into - a single cold rebuild if the whole stack lands in one release, which is the concrete argument for - not spreading it across releases. The backend restructuring itself rotates nothing: - `Program.backend` is excluded from fingerprints and no fingerprinted class gains or loses a field. +- Code only passing backend instances (`gtx.gtfn_cpu`, `run_dace_cpu`, ...) is unaffected. +- Construction and introspection must use `CompiledBackend(name=..., allocator=..., compiler=..., loader=...)` and the new names; `Backend` itself is no longer instantiable. +- Custom backend behavior moves to compiler/loader fields. Duck-typed backends fail at construction. +- Compile tasks are decomposable; process-mode fallback is limited to unpicklable compilers. + Explicit serial execution remains supported. +- Subclasses of deleted combinators and overrides of `Transforms.step_order` must migrate to + explicit `__call__` composition. +- Persistent translation caches rebuild under the changed keys, as described above. ## Alternatives considered -- **Rename the user-facing `Backend` to `Toolchain`** (the first version of this ADR): rejected in - review. "Backend" is how users name the choice of execution, frontend included; the rename would - have had to reach every `backend=` keyword, `with_backend`, `Program.backend` and the test - framework to be consistent, and a partial rename produced code like `self.backend.backend`. -- **One concrete `Backend` with an optional `compiler`** (embedded = no compiler): rejected; every - consumer would branch on `compiler is None`, the type would not tell the two kinds apart, and an - embedded-specific behaviour (e.g. a future `jax.jit` execution) would have nowhere to go. -- **Keep the frontend as a field of `CompiledBackend`**: rejected; it was not honoured - consistently (see Context), embedded execution has none, and no backend uses a different one. -- **`allocator` as an abstract property on `Backend`**: does not work with dataclasses — a - required field in a subclass does not implement an inherited abstract property, and `dataclass` - re-runs `abc.update_abstractmethods`, so the subclass stays abstract. -- **Enforce name uniqueness** (registry or check at construction): rejected; nothing in gt4py relies - on uniqueness, test doubles and `dataclasses.replace` variants legitimately share names, and a - global registry would be process state for a label. -- **Keep overridable `compile` with the opaque process-pool fallback**: rejected; it made the - process pool's behaviour depend on how a backend was written, and every known override (test - doubles) is expressible by wrapping `compiler`. -- **Dispatch by polymorphism** (a method on `Backend`, e.g. `backend.run(program, args)` or - `backend.make_pool(...)`, instead of one `isinstance` helper): rejected; what happens per kind - (lowering with the global frontend, the compiled-programs pool, the embedded context and its - hooks) belongs to the `ffront` program objects, which import `backend.py` — moving it onto - `Backend` would invert that dependency, and an overridable method would reopen the "customized - `compile`" problem this ADR removes. The set of kinds is closed and small. -- **Keep `make_*_toolchain` / `ToolchainConfig`**: rejected; public builders named after an - internal class but returning a `CompiledBackend` would keep the vocabulary split this ADR - removes. -- **Keep the combinators but trim dead ones**: rejected — the tower is a shallow-module archetype - and every recorded ADR 0011 requirement survives its removal; trimming keeps the reading cost and - the `Any`-typed composition. -- **A per-call options API on `translate()`**: rejected — reconfiguration stays composition-time, - ADR 0011's own rule. +- **Rename public `Backend` to `Toolchain`** (this ADR's first version): rejected in review. + Users call execution, including the frontend, a backend. Consistency would require renaming + every `backend=`, `with_backend`, `Program.backend` and the test framework; a partial rename + produced `self.backend.backend`. +- **One concrete `Backend` with optional `compiler`**: consumers must branch on `compiler is None`, + types cannot distinguish execution kinds, and embedded-specific behavior (e.g. future `jax.jit` + execution) has nowhere to go. +- **Frontend on `CompiledBackend`**: inconsistently honoured, absent in embedded execution, + and identical across backends. +- **Abstract `allocator` property**: a required dataclass field cannot implement an inherited + abstract property; `dataclass` reruns `abc.update_abstractmethods`, leaving subclasses abstract. +- **Enforce unique names** (registry or construction check): nothing relies on uniqueness; + test doubles and `dataclasses.replace` variants legitimately share names. A global registry + adds process state for a label. +- **Overridable `compile` with opaque fallback**: process-pool behavior depends on how a backend + is written; all known overrides (test doubles) can wrap `compiler` instead. +- **Polymorphic dispatch** (`Backend.run(program, args)` or `Backend.make_pool(...)`): global + lowering, the compiled-programs pool, embedded context and hooks belong to `ffront` program + objects, which import `backend.py`. Moving them onto `Backend` inverts that dependency; + overridable methods reopen the customized-compile problem. The set of kinds is closed and small. +- **Keep `make_*_toolchain` / `ToolchainConfig`**: naming public builders after an internal class + while returning `CompiledBackend` perpetuates the vocabulary split. +- **Trim only dead combinators**: keeps shallow wrappers, reading cost and `Any`-typed composition; + every ADR 0011 requirement survives full removal. +- **Per-call `translate()` options**: violates ADR 0011's composition-time reconfiguration rule. From e9f4113b2897ec2dad88f8afc19beaf3b9ed5d7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enrique=20Gonz=C3=A1lez=20Paredes?= Date: Thu, 29 Oct 2026 10:55:00 +0100 Subject: [PATCH 10/10] refactor[next]: address review of the backend structure - `CompiledBackend` and `Toolchain` are generic on the device type again, as `Backend` was on main, so the allocator keeps its device type. - Rename `DEFAULT_TRANSFORMS` to `DEFAULT_FRONTEND`: it is the global frontend, not a backend's default transforms. - Drop the `_frontend_transforms` properties of `Program` and `FieldOperator`; they only returned the global frontend. - Reword the linting TODO: backends no longer own the frontend. --- ...d-Structure-and-Pipeline-Simplification.md | 7 +++--- docs/user/next/advanced/HackTheToolchain.md | 6 ++--- docs/user/next/advanced/WorkflowPatterns.md | 4 ++-- src/gt4py/next/AGENTS.md | 2 +- src/gt4py/next/backend.py | 18 ++++++++------- src/gt4py/next/ffront/decorator.py | 22 +++++-------------- .../runners/dace/program.py | 2 +- .../ffront_tests/test_decorator_dispatch.py | 2 +- .../otf_tests/test_compiled_program.py | 4 ++-- .../runners_tests/test_roundtrip.py | 2 +- tests/next_tests/unit_tests/test_backend.py | 2 +- 11 files changed, 32 insertions(+), 39 deletions(-) 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 9a9a116974..b0fe4452d8 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 @@ -28,7 +28,7 @@ A **toolchain** is the complete route from DSL code to an optimized, runnable Py | Allocator | Provides field buffers; the base accepts an array namespace or a field-buffer allocator (factory), while compiled backends require `FieldBufferAllocatorProtocol`. | | `CompiledBackend` | The backend kind that compiles: owns `compiler`, `loader` and the allocator for the target device. | | Frontend | Lowers a program definition and its arguments into a `CompilableProgram`. | -| Global frontend | `DEFAULT_TRANSFORMS`, shared by all backends; no backend owns or selects a frontend. | +| Global frontend | `DEFAULT_FRONTEND`, shared by all backends; no backend owns or selects a frontend. | | Compiler | Turns a `CompilableProgram` into a loadable `CompilationArtifact`, possibly in a worker process. | | Loader | Turns that artifact into an `ExecutableProgram` in the calling process; defaults to `artifacts.load_artifact`. | | `Toolchain` | Internal composition of the global frontend with a `CompiledBackend`, created where compilation happens. | @@ -53,7 +53,7 @@ class CompiledBackend(Backend): @dataclasses.dataclass(frozen=True) class Toolchain: # internal backend: CompiledBackend - frontend: Step[ConcreteProgramDef, CompilableProgram] = DEFAULT_TRANSFORMS + frontend: Step[ConcreteProgramDef, CompilableProgram] = DEFAULT_FRONTEND ``` `Backend` has no abstract methods; `__post_init__` enforces abstractness. `Toolchain` is not exported from @@ -141,7 +141,7 @@ The previous `Backend(name, executor, allocator, transforms)` combined frontend compilation, overridable loading and allocation. Users call the execution choice a backend, including the frontend, but its internal composition is a toolchain in ADR 0017's sense. -- Every backend used `DEFAULT_TRANSFORMS`, except `roundtrip.gtir` (a #1569 leftover), which +- Every backend used the default `Transforms`, except `roundtrip.gtir` (a #1569 leftover), which built identical transforms with separate in-memory caches. `Program` and `FieldOperator` used the default without a backend; `FieldOperator.__gt_itir__` ignored its backend's frontend to lower consistently inside programs. Per-backend frontend settings were inconsistently honoured. @@ -178,6 +178,7 @@ including the frontend, but its internal composition is a toolchain in ADR 0017' | `ConcreteArtifact` / `.data` | `ProgramWithArgs` / `.definition` | | `CompilableProgramDef` | `CompilableProgram` | | `ItirShim.definition` | `ItirShim.operator_def` | +| `DEFAULT_TRANSFORMS` | `DEFAULT_FRONTEND` | The builders and config base are named for the `CompiledBackend` they build. The flat-keyword `make_dace_backend`, deprecated one release earlier (ADR 0028), is removed because the config-based diff --git a/docs/user/next/advanced/HackTheToolchain.md b/docs/user/next/advanced/HackTheToolchain.md index 37f73f65c0..4a298ba982 100644 --- a/docs/user/next/advanced/HackTheToolchain.md +++ b/docs/user/next/advanced/HackTheToolchain.md @@ -21,7 +21,7 @@ from gt4py import eve ## Replace Steps ```python -cached_lowering_toolchain = gtx.backend.DEFAULT_TRANSFORMS.replace( +cached_lowering_toolchain = gtx.backend.DEFAULT_FRONTEND.replace( past_to_itir=gtx.ffront.past_to_itir.past_to_gtir_factory(cached=False) ) ``` @@ -35,7 +35,7 @@ DUMMY_FOP = workflow.ProgramWithArgs( ``` ```python -gtx.backend.DEFAULT_TRANSFORMS.step_order(DUMMY_FOP) +gtx.backend.DEFAULT_FRONTEND.step_order(DUMMY_FOP) ``` ```python @@ -48,7 +48,7 @@ class SkipLinting(gtx.backend.Transforms): return order -same_steps = dataclasses.asdict(gtx.backend.DEFAULT_TRANSFORMS) +same_steps = dataclasses.asdict(gtx.backend.DEFAULT_FRONTEND) skip_linting_transforms = SkipLinting(**same_steps) skip_linting_transforms.step_order(DUMMY_FOP) ``` diff --git a/docs/user/next/advanced/WorkflowPatterns.md b/docs/user/next/advanced/WorkflowPatterns.md index 73be1cbd43..d2ebcb5eef 100644 --- a/docs/user/next/advanced/WorkflowPatterns.md +++ b/docs/user/next/advanced/WorkflowPatterns.md @@ -185,7 +185,7 @@ cached_calc(1) ### Example in the Wild ```python -gtx.backend.DEFAULT_TRANSFORMS.past_lint?? +gtx.backend.DEFAULT_FRONTEND.past_lint?? ``` @@ -395,7 +395,7 @@ proc.hexify_colors("blue") ### Example in the Wild ```python editable=true slideshow={"slide_type": ""} -gtx.backend.DEFAULT_TRANSFORMS?? +gtx.backend.DEFAULT_FRONTEND?? ``` ```python diff --git a/src/gt4py/next/AGENTS.md b/src/gt4py/next/AGENTS.md index 22fe51bfb9..1068fcf9a9 100644 --- a/src/gt4py/next/AGENTS.md +++ b/src/gt4py/next/AGENTS.md @@ -33,7 +33,7 @@ field operators / programs (ffront) argument descriptors). - `backend.py` — `Backend` (abstract: `name`, `allocator`), its concrete kind `CompiledBackend` (+ `compiler`, `loader`), the global frontend - (`Transforms` / `DEFAULT_TRANSFORMS`) and the internal `Toolchain` + (`Transforms` / `DEFAULT_FRONTEND`) and the internal `Toolchain` composing the two. - `program_processors/runners/` — the backends: `gtfn` (GridTools C++), `dace` (DaCe SDFG), `roundtrip` / `double_roundtrip` (pure Python). diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 85ad846df7..429fc6f051 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -9,7 +9,7 @@ from __future__ import annotations import dataclasses -from typing import Callable +from typing import Callable, Generic from gt4py._core import definitions as core_defs from gt4py.next import config, constructors, custom_layout_allocators as next_allocators @@ -137,7 +137,7 @@ def step_order(self, inp: stages.ConcreteProgramDef) -> list[str]: return steps -DEFAULT_TRANSFORMS: Transforms = Transforms() +DEFAULT_FRONTEND: Transforms = Transforms() @dataclasses.dataclass(frozen=True) @@ -170,7 +170,7 @@ def __post_init__(self) -> None: @dataclasses.dataclass(frozen=True) -class CompiledBackend(Backend): +class CompiledBackend(Backend, Generic[core_defs.DeviceTypeT]): """ A backend that compiles programs before running them. @@ -188,7 +188,7 @@ class CompiledBackend(Backend): loader: Loads an artifact into a directly-callable program. """ - allocator: next_allocators.FieldBufferAllocatorProtocol + allocator: next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] compiler: workflow.Workflow[stages.CompilableProgram, artifacts.CompilationArtifact] # A plain `Callable`, not `workflow.Workflow`: the protocol names its # parameter `inp`, which would force every loader to use that name. @@ -197,12 +197,14 @@ class CompiledBackend(Backend): ) @property - def __gt_allocator__(self) -> next_allocators.FieldBufferAllocatorProtocol: + def __gt_allocator__( + self, + ) -> next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT]: return self.allocator @dataclasses.dataclass(frozen=True) -class Toolchain: +class Toolchain(Generic[core_defs.DeviceTypeT]): """ Internal: the complete route from a program definition to an executable program. @@ -212,9 +214,9 @@ class Toolchain: public API: gt4py builds it where a compilation happens. """ - backend: CompiledBackend + backend: CompiledBackend[core_defs.DeviceTypeT] frontend: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgram] = ( - DEFAULT_TRANSFORMS + DEFAULT_FRONTEND ) def compile( diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index 978a120ca8..ae713032d5 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -295,11 +295,11 @@ def __gt_type__(self) -> ts_ffront.ProgramType: assert isinstance(self.past_stage.past_node.type, ts_ffront.ProgramType) return self.past_stage.past_node.type - # TODO(ricoh): linting should become optional, up to the backend. + # TODO(ricoh): linting should become optional. def __post_init__(self) -> None: _check_backend(self.backend) no_args_past = workflow.ProgramWithArgs(self.past_stage, arguments.CompileTimeArgs.empty()) - _ = self._frontend_transforms.past_lint(no_args_past).definition + _ = next_backend.DEFAULT_FRONTEND.past_lint(no_args_past).definition @property def __name__(self) -> str: @@ -324,12 +324,7 @@ def past_stage(self) -> ffront_stages.PASTProgramDef: no_args_def = workflow.ProgramWithArgs( self.definition_stage, arguments.CompileTimeArgs.empty() ) - return self._frontend_transforms.func_to_past(no_args_def).definition - - @property - def _frontend_transforms(self) -> next_backend.Transforms: - # The frontend is global: it is not part of any backend (ADR 0029). - return next_backend.DEFAULT_TRANSFORMS + return next_backend.DEFAULT_FRONTEND.func_to_past(no_args_def).definition @functools.cached_property def _all_closure_vars(self) -> dict[str, Any]: @@ -345,7 +340,7 @@ def gtir(self) -> itir.Program: ), args=arguments.CompileTimeArgs.empty(), ) - return self._frontend_transforms.past_to_itir(no_args_past).definition + return next_backend.DEFAULT_FRONTEND.past_to_itir(no_args_past).definition def with_grid_type(self, grid_type: common.GridType) -> Program: return dataclasses.replace( @@ -630,7 +625,7 @@ def from_function( compilation_options=options.CompilationOptions(**compilation_options), ) - # TODO(ricoh): linting should become optional, up to the backend. + # TODO(ricoh): linting should become optional. def __post_init__(self) -> None: """This ensures that DSL linting occurs at decoration time.""" _check_backend(self.backend) @@ -638,7 +633,7 @@ def __post_init__(self) -> None: @functools.cached_property def foast_stage(self) -> ffront_stages.FOASTOperatorDef: - return self._frontend_transforms.func_to_foast( + return next_backend.DEFAULT_FRONTEND.func_to_foast( workflow.ProgramWithArgs( definition=self.definition_stage, args=arguments.CompileTimeArgs.empty() ) @@ -652,11 +647,6 @@ def __name__(self) -> str: def definition(self) -> types.FunctionType: return self.definition_stage.definition - @property - def _frontend_transforms(self) -> next_backend.Transforms: - # The frontend is global: it is not part of any backend (ADR 0029). - return next_backend.DEFAULT_TRANSFORMS - def __gt_type__(self) -> ts.CallableType: type_ = self.foast_stage.foast_node.type assert isinstance(type_, ts.CallableType) diff --git a/src/gt4py/next/program_processors/runners/dace/program.py b/src/gt4py/next/program_processors/runners/dace/program.py index 2270d03912..3e66af5647 100644 --- a/src/gt4py/next/program_processors/runners/dace/program.py +++ b/src/gt4py/next/program_processors/runners/dace/program.py @@ -45,7 +45,7 @@ def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: # TODO(ricoh): connectivity tables required here for now. assert isinstance(self.backend, gtx_backend.CompiledBackend) - gtir_stage = self._frontend_transforms.past_to_itir( + gtir_stage = gtx_backend.DEFAULT_FRONTEND.past_to_itir( workflow.ProgramWithArgs( definition=self.past_stage, args=arguments.CompileTimeArgs( 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..9c556ad691 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 @@ -111,5 +111,5 @@ def test_compiled_backend_allocator_and_toolchain(): copy_program.compile(offset_provider={}) toolchain = copy_program._compiled_programs.toolchain assert toolchain.backend is roundtrip.default - assert toolchain.frontend is next_backend.DEFAULT_TRANSFORMS + assert toolchain.frontend is next_backend.DEFAULT_FRONTEND assert copy_program._compiled_programs.backend is roundtrip.default diff --git a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py index 77dd465664..48af12dddc 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py +++ b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py @@ -103,7 +103,7 @@ def test_inlining_of_scalars_works(testee_prog): ), ) - transformed = backend.DEFAULT_TRANSFORMS(input_pair).definition + transformed = backend.DEFAULT_FRONTEND(input_pair).definition _verify_program_has_expected_true_value(transformed) @@ -313,7 +313,7 @@ def test_inlining_of_static_domain_works(testee_prog, uids: utils.IDGeneratorPoo ), ) - transformed = backend.DEFAULT_TRANSFORMS(input_pair).definition + transformed = backend.DEFAULT_FRONTEND(input_pair).definition _verify_program_has_expected_domain(transformed, domain, uids) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py index f6fb36e7b4..48c5ccf4c0 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/test_roundtrip.py @@ -101,7 +101,7 @@ def double_program(a: gtx.Field[[IDim], gtx.float64], out: gtx.Field[[IDim], gtx a = gtx.zeros({IDim: 4}) out = gtx.zeros({IDim: 4}) default_frontend = next_backend.Toolchain(roundtrip.gtir).frontend - assert default_frontend is next_backend.DEFAULT_TRANSFORMS + assert default_frontend is next_backend.DEFAULT_FRONTEND # A field operator is lowered as the program wrapping it, so `out` is positional. compile_time_args = arguments.CompileTimeArgs.from_concrete(a, out, offset_provider={}) diff --git a/tests/next_tests/unit_tests/test_backend.py b/tests/next_tests/unit_tests/test_backend.py index 7c8f6dc7a8..8793228781 100644 --- a/tests/next_tests/unit_tests/test_backend.py +++ b/tests/next_tests/unit_tests/test_backend.py @@ -101,7 +101,7 @@ def loader(artifact): def test_toolchain_default_frontend_is_the_global_one(): assert next_backend.Toolchain(_make_compiled_backend()).frontend is ( - next_backend.DEFAULT_TRANSFORMS + next_backend.DEFAULT_FRONTEND )