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..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,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 - Backend Structure and Pipeline Simplification](0029-Backend-Structure-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..4a72f49eb4 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 - 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 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/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 c2d90458ed..e28e5d7ba5 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 - 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 overhead and the desire to bound workspace memory to one SDFG's transient 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..b0fe4452d8 --- /dev/null +++ b/docs/development/ADRs/next/0029-Backend-Structure-and-Pipeline-Simplification.md @@ -0,0 +1,276 @@ +--- +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-29 + +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 + +### 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_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. | + +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: # __post_init__ rejects type(self) is Backend + name: str + allocator: Allocator + + +@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_FRONTEND +``` + +`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 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. +- 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 | +| ---------------------------------------------- | ------------------------------------------- | +| `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` (in #2743) | +| `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 +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. + +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). + +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 + +- 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 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. diff --git a/docs/development/ADRs/next/README.md b/docs/development/ADRs/next/README.md index f19167ef9b..40f77597ed 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 - 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 773070130b..4a298ba982 100644 --- a/docs/user/next/advanced/HackTheToolchain.md +++ b/docs/user/next/advanced/HackTheToolchain.md @@ -11,10 +11,17 @@ 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 -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) ) ``` @@ -22,13 +29,13 @@ 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 ) ``` ```python -gtx.backend.DEFAULT_TRANSFORMS.step_order(DUMMY_FOP) +gtx.backend.DEFAULT_FRONTEND.step_order(DUMMY_FOP) ``` ```python @@ -41,14 +48,14 @@ 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) ``` ## 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 b8ce74a9be..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_PROG_TRANSFORMS.past_lint?? +gtx.backend.DEFAULT_FRONTEND.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_FRONTEND?? ``` ```python -gtx.program_processors.runners.gtfn.run_gtfn_gpu.executor.otf_workflow?? +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 f0a2bfc342..1068fcf9a9 100644 --- a/src/gt4py/next/AGENTS.md +++ b/src/gt4py/next/AGENTS.md @@ -31,6 +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` — `Backend` (abstract: `name`, `allocator`), its concrete + kind `CompiledBackend` (+ `compiler`, `loader`), the global frontend + (`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). - `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..429fc6f051 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 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 +from gt4py.next import config, constructors, custom_layout_allocators as next_allocators from gt4py.next.ffront import ( foast_to_gtir, foast_to_past, @@ -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( [ @@ -137,35 +137,64 @@ def step_order(self, inp: stages.ConcreteProgramDef) -> list[str]: return steps -DEFAULT_TRANSFORMS: Transforms = Transforms() +DEFAULT_FRONTEND: 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 Backend: + """ + 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 - executor: workflow.Workflow[stages.CompilableProgramDef, artifacts.CompilationArtifact] - allocator: next_allocators.FieldBufferAllocatorProtocol[core_defs.DeviceTypeT] - transforms: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgramDef] + allocator: constructors.Allocator - 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)) - ) - return self.load_artifact(artifact) + def __post_init__(self) -> None: + if type(self) is Backend: + raise TypeError( + "'Backend' is abstract: instantiate a concrete kind such as 'CompiledBackend'." + ) - 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() +@dataclasses.dataclass(frozen=True) +class CompiledBackend(Backend, Generic[core_defs.DeviceTypeT]): + """ + 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[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. + loader: Callable[[artifacts.CompilationArtifact], artifacts.ExecutableProgram] = ( + dataclasses.field(default=artifacts.load_artifact) + ) @property def __gt_allocator__( @@ -175,18 +204,44 @@ def __gt_allocator__( @dataclasses.dataclass(frozen=True) -class ToolchainConfig: +class Toolchain(Generic[core_defs.DeviceTypeT]): + """ + 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[core_defs.DeviceTypeT] + frontend: workflow.Workflow[stages.ConcreteProgramDef, stages.CompilableProgram] = ( + DEFAULT_FRONTEND + ) + + def compile( + self, definition: stages.IRDefinitionT, compile_time_args: arguments.CompileTimeArgs + ) -> artifacts.ExecutableProgram: + """Lower, compile and load `definition` in the calling thread.""" + compilable = self.frontend( + stages.ConcreteProgramDef(definition=definition, args=compile_time_args) + ) + return self.backend.loader(self.backend.compiler(compilable)) + + +@dataclasses.dataclass(frozen=True) +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. """ @@ -213,7 +268,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/config.py b/src/gt4py/next/config.py index 7700074e19..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 backend's ``executor`` 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 - #: 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 bf63aa692a..ae713032d5 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -53,6 +53,39 @@ 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( level=metrics.MINIMAL, metric_name=metrics.TOTAL_METRIC ) @@ -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. @@ -261,10 +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: - no_args_past = workflow.ConcreteArtifact(self.past_stage, arguments.CompileTimeArgs.empty()) - _ = self._frontend_transforms.past_lint(no_args_past).data + _check_backend(self.backend) + no_args_past = workflow.ProgramWithArgs(self.past_stage, arguments.CompileTimeArgs.empty()) + _ = next_backend.DEFAULT_FRONTEND.past_lint(no_args_past).definition @property def __name__(self) -> str: @@ -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: @@ -286,19 +321,10 @@ 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 - - @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 - # 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 + return next_backend.DEFAULT_FRONTEND.func_to_past(no_args_def).definition @functools.cached_property def _all_closure_vars(self) -> dict[str, Any]: @@ -306,15 +332,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 next_backend.DEFAULT_FRONTEND.past_to_itir(no_args_past).definition def with_grid_type(self, grid_type: common.GridType) -> Program: return dataclasses.replace( @@ -398,7 +424,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 ) @@ -544,7 +570,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.Backend | None, + DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type=grid_type, **compilation_options, @@ -598,18 +625,19 @@ 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) _ = self.foast_stage @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() + return next_backend.DEFAULT_FRONTEND.func_to_foast( + workflow.ProgramWithArgs( + definition=self.definition_stage, args=arguments.CompileTimeArgs.empty() ) - ).data + ).definition @property def __name__(self) -> str: @@ -619,15 +647,6 @@ def __name__(self) -> str: def definition(self) -> types.FunctionType: return self.definition_stage.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 - # 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 - def __gt_type__(self) -> ts.CallableType: type_ = self.foast_stage.foast_node.type assert isinstance(type_, ts.CallableType) @@ -638,9 +657,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) @@ -652,7 +669,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: @@ -719,8 +739,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) @@ -771,7 +793,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.Backend | None, + DEFAULT_BACKEND if backend is eve.NOTHING else backend, ), grid_type, **compilation_options, @@ -862,7 +885,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.Backend | 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..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.Backend | 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.Backend): - assert isinstance(backend, next_backend.Backend) - 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.Backend' 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 fa3226153b..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 ``Backend`` 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. """ @@ -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 `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 backend's compiler. + + 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..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,45 +123,20 @@ 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.Backend, + 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.Backend.compile: - # A customized `compile` is opaque: it cannot be decomposed into the - # standard transforms/executor 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 `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 = toolchain.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 +151,7 @@ def construct_compilable(with_refs: bool) -> stages.CompilableProgramDef: ) return runners.CompilationTask( - name=name, construct_compilable=construct_compilable, executor=backend.executor + 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 b71fdd9df9..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.Backend, + 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.Backend + #: 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.load_artifact(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/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/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/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/__init__.py b/src/gt4py/next/program_processors/runners/dace/__init__.py index 2e06493bd0..a5d2f8e335 100644 --- a/src/gt4py/next/program_processors/runners/dace/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace/__init__.py @@ -9,8 +9,9 @@ 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, run_dace_cpu_noopt, run_dace_gpu, @@ -32,13 +33,14 @@ "DaCeBindingsBuilder", "DaCeCompilationBuilder", "DaCeConfig", + "DaCeLoader", "DaCeTranslationBuilder", "get_sdfg_args", + "is_dace_backend", "make_dace_backend", "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/program.py b/src/gt4py/next/program_processors/runners/dace/program.py index f8f8c7e1a4..3e66af5647 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,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 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. - gtir_stage = typing.cast(gtx_backend.Transforms, self.backend.transforms).past_to_itir( - workflow.ConcreteArtifact( - data=self.past_stage, + assert isinstance(self.backend, gtx_backend.CompiledBackend) + gtir_stage = gtx_backend.DEFAULT_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,28 +57,35 @@ 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` 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, - "data", - 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()], gt4py_program_args=[p.type for p in program.params], ) - otf_workflow = self.backend.executor + 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/__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 98149f20c4..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,33 +10,111 @@ 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.otf import artifacts +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, decoration as gtx_wfddecoration, factory as gtx_wfdfactory, + translation as gtx_wfdtranslation, ) @dataclasses.dataclass(frozen=True) -class DaCeBackend(backend.Backend[Any]): - """DaCe backend with support for injecting an external workspace at load time.""" +class DaCeLoader: + """ + Loader that injects an external workspace into the loaded program. + + 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. + """ 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 -def make_dace_toolchain( +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) + + +#: 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, /, *, @@ -44,108 +122,42 @@ 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.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() - return DaCeBackend( + return backend.CompiledBackend( name=f"run_dace_{cfg.device_name}{'_opt' if cfg.auto_optimize else ''}{name_postfix}", - executor=gtx_wfdfactory.make_dace_compile_workflow( + compiler=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, - ) - - -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, -) -> DaCeBackend: - """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, - ), + loader=DaCeLoader(cfg.external_workspace), ) -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/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..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.Backend( +backend = next_backend.CompiledBackend( name="double_roundtrip", - transforms=next_backend.DEFAULT_TRANSFORMS, - executor=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 f73f4e0cd6..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, /, *, @@ -287,39 +287,40 @@ def make_gtfn_toolchain( translation: GTFNTranslationBuilder = make_gtfn_translation, bindings: GTFNBindingsBuilder = make_gtfn_bindings, compilation: GTFNCompilationBuilder = make_gtfn_compiler, -) -> backend.Backend: +) -> 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() - return backend.Backend( + return backend.CompiledBackend( name=f"run_gtfn_{cfg.device_name}{name_postfix}", - executor=make_gtfn_compile_workflow( + compiler=make_gtfn_compile_workflow( cfg, translation=translation, bindings=bindings, compilation=compilation ), allocator=cfg.make_allocator(), - transforms=backend.DEFAULT_TRANSFORMS, ) -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/src/gt4py/next/program_processors/runners/roundtrip.py b/src/gt4py/next/program_processors/runners/roundtrip.py index 29afc3535a..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.Backend | None + dispatch_backend: next_backend.CompiledBackend | 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.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.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,46 +275,36 @@ def __call__(self, inp: stages.CompilableProgramDef) -> RoundtripArtifact: # TODO(tehrengruber): introduce factory -default = next_backend.Backend( +default = next_backend.CompiledBackend( name="roundtrip", - executor=Roundtrip( + compiler=Roundtrip( transforms=functools.partial( itir_transforms.apply_common_transforms, extract_temporaries=False, ) ), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - transforms=next_backend.DEFAULT_TRANSFORMS, ) -with_temporaries = next_backend.Backend( +with_temporaries = next_backend.CompiledBackend( name="roundtrip_with_temporaries", - executor=Roundtrip( + compiler=Roundtrip( transforms=functools.partial( itir_transforms.apply_common_transforms, extract_temporaries=True, ) ), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - transforms=next_backend.DEFAULT_TRANSFORMS, ) -no_transforms = next_backend.Backend( +no_transforms = next_backend.CompiledBackend( name="roundtrip", - executor=Roundtrip(transforms=lambda o, *, offset_provider: o), + compiler=Roundtrip(transforms=lambda o, *, offset_provider: o), allocator=next_allocators.StandardCPUFieldBufferAllocator(), - transforms=next_backend.DEFAULT_TRANSFORMS, ) -gtir = next_backend.Backend( +gtir = next_backend.CompiledBackend( name="roundtrip_gtir", - executor=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(), - transforms=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 1c75458862..c8367bd64e 100644 --- a/src/gt4py/next/typing.py +++ b/src/gt4py/next/typing.py @@ -38,6 +38,5 @@ "FieldOperator", "OffsetProvider", "Program", - # from _core.definitions for convenience - "Scalar", + "Scalar", # from _core.definitions for convenience ] diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 86a4229860..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 - executor: Final = None numpy_execution = EmbeddedDummyBackend("EmbeddedNumPy", nd_array_field.np) diff --git a/tests/next_tests/integration_tests/cases_utils.py b/tests/next_tests/integration_tests/cases_utils.py index ea7c898f4d..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.") +@dataclasses.dataclass(frozen=True) class NoBackend(next_backend.Backend): - """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.") + """ + 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", - executor=_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, -) +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_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..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 @@ -6,7 +6,10 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import dataclasses + import dace +import numpy as np import pytest from gt4py import next as gtx @@ -15,6 +18,8 @@ from next_tests.integration_tests import cases from next_tests.integration_tests.cases_utils import ( Cell, + E2V, + E2VDim, Edge, IDim, JDim, @@ -23,7 +28,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, roundtrip # Override the exec_alloc_descriptor with a custom Backend, @@ -100,3 +105,56 @@ 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) + + +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]) 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..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,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.compiler return dataclasses.replace( gtx_dace.run_dace_cpu, - executor=dataclasses.replace(executor, translation=executor.translation.step), + 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_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/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..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.executor 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.executor 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 f9b2060621..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.Backend) 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/conftest.py b/tests/next_tests/unit_tests/conftest.py index 879094f123..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.Backend | 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..9c556ad691 --- /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_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 3d9fcaa834..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 @@ -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_FRONTEND(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_backend(name_postfix="_custom"), compiler=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_FRONTEND(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..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,66 +84,49 @@ 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", - ) - - with pytest.warns(UserWarning, match="standard compilation workflow"): - future = process_runner.submit(task) +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. - assert future.done() - assert callable(future.result().load()) + This is the generic fallback that replaced the opaque "customized compile" path. + """ + calls = [] + def closure_compiler(compilable): + calls.append(compilable) + return _NoOpArtifact() -def test_make_compilation_task_decomposes_standard_backend(): - backend = next_backend.Backend( - name="test_backend", - executor=lambda compilable: _NoOpArtifact(), - allocator=None, - transforms=lambda inp: inp, + 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( - 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.executor - assert callable(task.compile().load()) - - -def test_make_compilation_task_is_opaque_for_customized_compile(): - class _WrapperBackend: - def __init__(self, wrapped): - self._wrapped = wrapped + with pytest.warns(UserWarning, match="not picklable"): + future = process_runner.submit(task) - def __getattr__(self, name): - return getattr(self._wrapped, name) + assert future.done() + assert callable(future.result().load()) + assert len(calls) == 1 - 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.Backend( - name="test_backend", - executor=lambda compilable: _NoOpArtifact(), - allocator=None, - transforms=lambda inp: inp, - ) +def test_make_compilation_task_decomposes_standard_backend(): + 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 not None + assert task.executor is toolchain.backend.compiler assert callable(task.compile().load()) - assert backend.compile_called def test_offloaded_task_ships_connectivities_as_file_refs(): @@ -154,15 +137,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.Backend( - name="test_backend", - executor=lambda compilable: _NoOpArtifact(), - allocator=None, - transforms=lambda inp: inp, + 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 +164,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/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..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 @@ -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 ( @@ -105,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, @@ -193,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, @@ -203,28 +204,28 @@ def test_make_backend_accepts_external_workspace_with_external_mode(): ), ) - assert backend.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(): 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}) ) assert ( - backend.executor.translation.step.auto_optimize_args["transient_memory_mode"] + backend.compiler.translation.step.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.EXTERNAL ) - assert backend.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(): 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, @@ -236,34 +237,34 @@ 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.compiler.translation.step.auto_optimize_args["transient_memory_mode"] == gtx_transformations.TransientMemoryMode.POOL ) - assert backend.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(): +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) ) - translator = backend.executor.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.external_workspace is cfg.external_workspace - assert backend.executor.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(): +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}, @@ -271,51 +272,55 @@ def test_make_toolchain_rejects_derived_optimization_args(): ) -def test_make_toolchain_uncached_translation(): - backend = 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) ) - assert isinstance(backend.executor.translation, dace_wf_translation.DaCeTranslator) + assert isinstance(toolchain.compiler.translation, dace_wf_translation.DaCeTranslator) -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_backend_carries_its_workspace_in_a_dace_loader(): + workspace: dict = {} + backend = dace_wf_backend.make_dace_backend( + dace_wf_factory.DaCeConfig(external_workspace=workspace) ) - # 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.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 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_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"], +) +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_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) + + 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(): @@ -328,13 +333,13 @@ 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.compiler.translation.step with pytest.raises(ValueError, match="cannot be overridden"): dataclasses.replace(translator, auto_optimize_args={"constant_symbols": {}}) 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 ), @@ -343,13 +348,13 @@ 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.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(): 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} @@ -419,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, @@ -449,9 +454,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.compiler.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 +464,8 @@ def mocked_translator(inp: stages.CompilableProgramDef) -> dace.SDFG: custom_backend = dataclasses.replace( custom_backend, - executor=dataclasses.replace( - custom_backend.executor, + compiler=dataclasses.replace( + custom_backend.compiler, translation=mocked_translator, ), ) @@ -499,7 +504,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_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/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..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,20 +33,20 @@ 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.executor.translation, workflow.CachedStep) - assert cpu_version.executor.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.executor.translation, workflow.CachedStep) - assert gpu_version.executor.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.executor.compilation.device_type is core_defs.DeviceType.CPU - assert gpu_version.executor.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 @@ -56,31 +56,31 @@ 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.executor.compilation.cache_lifetime is config.BuildCacheLifetime.SESSION + assert session_version.compiler.compilation.cache_lifetime is config.BuildCacheLifetime.SESSION assert ( - persistent_version.executor.compilation.cache_lifetime + persistent_version.compiler.compilation.cache_lifetime is config.BuildCacheLifetime.PERSISTENT ) -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.executor.compilation.builder_factory.cmake_build_type + release_version.compiler.compilation.builder_factory.cmake_build_type is config.CMakeBuildType.RELEASE ) assert ( - min_size_version.executor.compilation.builder_factory.cmake_build_type + min_size_version.compiler.compilation.builder_factory.cmake_build_type is config.CMakeBuildType.MIN_SIZE_REL ) @@ -94,12 +94,12 @@ 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.executor.compilation - debug_compiler = debug_version.executor.compilation + release_compiler = release_version.compiler.compilation + debug_compiler = debug_version.compiler.compilation build_context_ids: list[str] = [] @@ -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( @@ -147,11 +147,11 @@ def test_step_builder_partial_keeps_config_settings(): ), ) - translation = toolchain.executor.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.executor.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 @@ -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.executor.translation, workflow.CachedStep) - assert toolchain.executor.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)) + toolchain = gtfn.make_gtfn_backend(gtfn.GTFNConfig(cached_translation=False)) - assert isinstance(toolchain.executor.translation, gtfn_module.GTFNTranslationStep) + 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 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..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 @@ -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_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={}) + 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 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..8793228781 --- /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_FRONTEND + ) + + +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__