Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/development/ADRs/next/0011-On_The_Fly_Compilation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions docs/development/ADRs/next/0017-Toolchain-Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions docs/development/ADRs/next/0024-Compilation-Runners.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions docs/development/ADRs/next/0027-External_Workspace_Memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions docs/development/ADRs/next/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
21 changes: 14 additions & 7 deletions docs/user/next/advanced/HackTheToolchain.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,31 @@ from gt4py import eve
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"><script src="https://spcl.github.io/dace/webclient2/dist/sdfv.js"></script>
<link href="https://spcl.github.io/dace/webclient2/sdfv.css" rel="stylesheet">

> [!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.

Comment on lines +14 to +20

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
> [!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)
)
```

## 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
Expand All @@ -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
Expand All @@ -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),
Expand Down
8 changes: 4 additions & 4 deletions docs/user/next/advanced/WorkflowPatterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -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??
```

<!-- #region editable=true slideshow={"slide_type": ""} -->
Expand Down Expand Up @@ -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??
```
4 changes: 4 additions & 0 deletions src/gt4py/next/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
119 changes: 87 additions & 32 deletions src/gt4py/next/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
]
):
"""
Expand Down Expand Up @@ -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(
[
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not __gt_allocator__ in the abstract interface?


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] = (
Comment thread
egparedes marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The custom loader was introduced with the dace external workspace in #2719. It's to my knowledge the only stateful aspect of any backend, wondering if we should provide the workspace at execution time instead of binding it to the program via backend. That approach would also have downsides, because the workspace is clearly coupled to a dace backend (unless we generalize it).

dataclasses.field(default=artifacts.load_artifact)
)

@property
def __gt_allocator__(
Expand All @@ -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.
"""

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


Expand Down
Loading
Loading