Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
cf17293
fix[next-dace]: replace unit stride on fields in tuple arguments
edopao Dec 1, 2026
7701f71
test[next-dace]: cover multiple horizontal dims in tuple arguments
edopao Dec 1, 2026
81e8108
set unit stride on horizontal dimensions only for unstructured domain
edopao Nov 26, 2026
8a1da79
add test coverage
edopao Nov 26, 2026
732875e
fix[next]: set unit stride on horizontal dimensions only for unstruct…
edopao Nov 26, 2026
2190e9d
test[next]: check grid_type emitted by gtfn and dace translation steps
edopao Nov 26, 2026
42073c7
refactor[next]: keep the grid type out of the generic build infrastru…
edopao Nov 26, 2026
f3feea3
fix dace test
edopao Nov 26, 2026
a60a27b
feat[next]: configure the unit-stride assumption by dimension or dime…
edopao Dec 1, 2026
5873f10
feat[next]: configure the DaCe auto-optimize pipeline with the unit-s…
edopao Dec 1, 2026
2271f9c
test[next]: configure the unit-stride assumption with JDim in the dac…
edopao Dec 1, 2026
e85e06f
refactor[next]: configure the unit-stride assumption by dimension kin…
edopao Dec 1, 2026
0c6a404
test[next-dace]: check that arguments violating the unit-stride assum…
edopao Dec 1, 2026
55aaf1f
ci[next-dace]: assume unit stride on the horizontal dimension in CSCS CI
edopao Dec 1, 2026
b29eca7
test[next]: allocate the laplacian input with the backend allocator
edopao Dec 1, 2026
85ef49c
undo CI-config change
edopao Dec 1, 2026
8932ce7
test[next-dace]: adapt the test for multiple horizontal dimensions
edopao Dec 1, 2026
855f5ba
refactor[next-dace]: use order_dimensions() in MapIterationOrder
edopao Dec 1, 2026
2435176
Merge branch 'main' into pass-unit-stride-dims-cartesian
edopao Dec 2, 2026
bcbc2e4
feat[next]: allocators report their layout mapper for unit-stride det…
edopao Dec 2, 2026
374bcaf
feat[next]: add use_backend_allocator_layout toolchain option
edopao Dec 2, 2026
f99b461
feat[next-gtfn]: derive static unit strides from the backend allocato…
edopao Dec 2, 2026
f2704c8
feat[next-dace]: derive constant unit strides from the backend alloca…
edopao Dec 2, 2026
378e181
refactor[next]: remove the unit_stride_kind option
edopao Dec 2, 2026
ddcd13d
remove metion of the gridtools issue
edopao Dec 2, 2026
e73578d
edit
edopao Dec 2, 2026
dcb3b20
fix dace tests
edopao Dec 2, 2026
9dc8e44
edit
edopao Dec 2, 2026
6d139a8
Merge remote-tracking branch 'origin/main' into pass-unit-stride-dims…
edopao Dec 2, 2026
d444f34
ci: test with GridTools signed static strides and backend allocator l…
edopao Dec 2, 2026
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 .cscs-ci/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ build_cscs_amd_rocm:
USE_MPI: 0 # TODO(havogt): to workaround the libfabric hook injecting incompatible libraries
SLURM_JOB_NUM_NODES: 1
SLURM_TIMELIMIT: 5
# Static unit strides from the backend allocator layout, see `config.USE_BACKEND_ALLOCATOR_LAYOUT`.
GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT: '1'
parallel:
matrix:
- SUBPACKAGE: [cartesian]
Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,10 @@ url = 'https://gridtools.github.io/pypi/'
# dace = {index = "gridtools"}
[tool.uv.sources]
atlas4py = { index = "test.pypi" }
# TODO(edopao): switch back to PyPI once a gridtools-cpp release has signed static strides in the
# nanobind adapter, see https://github.com/GridTools/gt4py/issues/3071.
# Wheel built from https://github.com/edopao/gridtools/tree/fix/nanobind-signed-static-strides
gridtools-cpp = { url = "https://github.com/edopao/gridtools/releases/download/gt4py-3071-signed-strides/gridtools_cpp-2.4.0-py3-none-any.whl" }

# -- versioningit --
[tool.versioningit]
Expand Down
21 changes: 18 additions & 3 deletions src/gt4py/next/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,26 @@ class ToolchainConfig:
cache_lifetime: config.BuildCacheLifetime = dataclasses.field(
default_factory=lambda: config.BUILD_CACHE_LIFETIME
)
#: Assume unit stride in the horizontal dimension of unstructured fields.
unstructured_horizontal_has_unit_stride: bool = dataclasses.field(
default_factory=lambda: config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE
#: Assume that all field and connectivity arguments have the memory layout
#: of the toolchain's allocator, see `layout_mapper`.
use_backend_allocator_layout: bool = dataclasses.field(
default_factory=lambda: config.USE_BACKEND_ALLOCATOR_LAYOUT
)

@property
def layout_mapper(self) -> next_allocators.FieldLayoutMapper | None:
"""
Memory layout the compiled code can assume for its arguments.

This is the layout mapper of the allocator returned by `make_allocator()`
if `use_backend_allocator_layout` is set, otherwise `None` (no assumption).
It is a plain function, so the toolchain steps can store it and stay
picklable and hashable.
"""
if not self.use_backend_allocator_layout:
return None
return next_allocators.get_layout_mapper(self.make_allocator())

@property
def device_type(self) -> core_defs.DeviceType:
if self.gpu:
Expand Down
9 changes: 6 additions & 3 deletions src/gt4py/next/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,12 @@ def _get_build_cache_version_id() -> str:
]


#: Experimental, use at your own risk: assume horizontal dimension has stride 1
UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE: bool = env_flag_to_bool(
"GT4PY_UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE", default=False
#: Compiled toolchains assume that all field and connectivity arguments have the
#: memory layout of the backend's allocator, and specialize the generated code
#: for it (e.g. static unit strides). Arguments with a different layout are
#: rejected at call time.
USE_BACKEND_ALLOCATOR_LAYOUT: bool = env_flag_to_bool(
"GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT", default=False
)


Expand Down
70 changes: 70 additions & 0 deletions src/gt4py/next/custom_layout_allocators.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,39 @@ def is_field_allocator_for(
return is_field_allocator(obj) and obj.__gt_device_type__ is device


class LayoutAwareFieldBufferAllocatorProtocol(
FieldBufferAllocatorProtocol[core_defs.DeviceTypeT], Protocol[core_defs.DeviceTypeT]
):
"""Protocol for field buffer allocators that can report the memory layout they use.

Implementing this protocol is optional. Compiled toolchains can use the
reported layout to specialize the generated code for the strides of the
fields allocated by this allocator, see `unit_stride_dimension()`.

The layout is reported as a `FieldLayoutMapper` rather than through a method
of the allocator, because toolchains store it in their (picklable and hashable)
configuration, while allocators may hold unpicklable state (e.g. modules).
"""

@property
@abc.abstractmethod
def __gt_layout_mapper__(self) -> FieldLayoutMapper: ...


def is_layout_aware_field_allocator(obj: Any) -> TypeIs[LayoutAwareFieldBufferAllocatorProtocol]:
return is_field_allocator(obj) and hasattr(obj, "__gt_layout_mapper__")


def get_layout_mapper(obj: Any) -> Optional[FieldLayoutMapper]:
"""Return the layout mapper of an allocator or allocator factory (e.g. a backend).

Returns `None` if `obj` does not report its layout.
"""
if is_field_allocator_factory(obj):
obj = obj.__gt_allocator__
return obj.__gt_layout_mapper__ if is_layout_aware_field_allocator(obj) else None


class FieldBufferAllocatorFactoryProtocol(Protocol[core_defs.DeviceTypeT]):
"""Protocol for device-specific buffer allocator factories for fields."""

Expand Down Expand Up @@ -130,6 +163,10 @@ def buffer_allocator(self) -> core_allocators.BufferAllocator:
def __gt_device_type__(self) -> core_defs.DeviceTypeT:
return self.device_type

@property
def __gt_layout_mapper__(self) -> FieldLayoutMapper:
return self.layout_mapper

def __gt_allocate__(
self,
domain: common.Domain,
Expand All @@ -153,6 +190,9 @@ def __gt_allocate__(
__TensorFieldAllocatorAsFieldAllocatorInterfaceT: type[FieldBufferAllocatorProtocol] = (
BaseFieldBufferAllocator
)
__TensorFieldAllocatorAsLayoutAwareInterfaceT: type[LayoutAwareFieldBufferAllocatorProtocol] = (
BaseFieldBufferAllocator
)


def horizontal_first_layout_mapper(
Expand Down Expand Up @@ -186,6 +226,36 @@ def pos_of_kind(kind: common.DimensionKind) -> list[int]:
__horizontal_first_layout_mapper: FieldLayoutMapper = horizontal_first_layout_mapper


def unit_stride_dimension(
layout_mapper: Optional[FieldLayoutMapper], dims: Sequence[common.Dimension], /
) -> Optional[common.Dimension]:
"""Find the dimension with unit stride in the layout given by `layout_mapper`.

Args:
layout_mapper: The layout mapper of an allocator, see `get_layout_mapper()`,
or `None` if the layout is unknown.
dims: The dimensions of a field, in the order given by its type.

Returns:
The innermost dimension of the layout of `dims`, or `None` if `dims` is
empty or the layout is unknown.

Raises:
ValueError: If `layout_mapper` does not return a valid layout map for `dims`.
"""
if layout_mapper is None or not dims:
return None
layout_map = layout_mapper(dims)
if len(layout_map) != len(dims) or not core_allocators.is_valid_layout_map(layout_map):
raise ValueError(
f"Layout mapper '{layout_mapper}' returned an invalid layout map {tuple(layout_map)}"
f" for dimensions {list(dims)}: expected a permutation of 0..{len(dims) - 1}."
)
innermost = len(dims) - 1
# The layout map is a valid permutation, so exactly one dimension is innermost.
return next(dim for dim, pos in zip(dims, layout_map) if pos == innermost)


#: Registry of default allocators for each device type.
device_allocators: dict[core_defs.DeviceType, FieldBufferAllocatorProtocol] = {}

Expand Down
46 changes: 24 additions & 22 deletions src/gt4py/next/otf/binding/nanobind.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import gt4py.eve as eve
from gt4py.eve.codegen import JinjaTemplate as as_jinja, TemplatedGenerator
from gt4py.next import common, config
from gt4py.next import custom_layout_allocators as next_allocators
from gt4py.next.otf import artifacts, cpp_utils
from gt4py.next.otf.binding import cpp_interface, interface
from gt4py.next.type_system import type_specifications as ts
Expand Down Expand Up @@ -204,29 +204,26 @@ def _tuple_get(index: int, var: str) -> str:


def make_argument(
name: str, type_: ts.TypeSpec, unstructured_horizontal_has_unit_stride: bool
name: str,
type_: ts.TypeSpec,
layout_mapper: next_allocators.FieldLayoutMapper | None,
) -> str | BufferSID | Tuple:
if isinstance(type_, ts.FieldType):
unit_stride_dim = next_allocators.unit_stride_dimension(layout_mapper, type_.dims)
return BufferSID(
source_buffer=name,
dimensions=[
DimensionSpec(
name=dim.value,
static_stride=1
if (
unstructured_horizontal_has_unit_stride
and dim.kind == common.DimensionKind.HORIZONTAL
)
else None,
static_stride=1 if dim == unit_stride_dim else None,
)
for dim in type_.dims
],
scalar_type=type_.dtype,
)
elif isinstance(type_, ts.TupleType):
elements = [
make_argument(_tuple_get(i, name), t, unstructured_horizontal_has_unit_stride)
for i, t in enumerate(type_.types)
make_argument(_tuple_get(i, name), t, layout_mapper) for i, t in enumerate(type_.types)
]
return Tuple(elems=elements)
elif isinstance(type_, ts.ScalarType):
Expand All @@ -237,15 +234,23 @@ def make_argument(

def create_bindings(
program_source: artifacts.ProgramSource[CodeSpecT],
unstructured_horizontal_has_unit_stride: bool,
layout_mapper: next_allocators.FieldLayoutMapper | None,
) -> artifacts.BindingSource[CodeSpecT, artifacts.PythonCodeSpec]:
"""
Generate Python bindings through which a C++ function can be called.

Parameters
----------
program_source
The program source for which the bindings are created
Args:
program_source: The program source for which the bindings are created.
layout_mapper: Memory layout assumed for the field and connectivity
arguments: the innermost dimension gets a static unit stride, see
`custom_layout_allocators.unit_stride_dimension()`. `None` makes no
assumption.

Returns:
The binding source wrapping the program source.

Raises:
ValueError: If `program_source` is not a C++-like program source.
"""
if not isinstance(program_source.code_spec, artifacts.CPPLikeCodeSpec):
raise ValueError(
Expand Down Expand Up @@ -283,9 +288,7 @@ def create_bindings(
expr=FunctionCall(
target=program_source.entry_point,
args=[
make_argument(
param.name, param.type_, unstructured_horizontal_has_unit_stride
)
make_argument(param.name, param.type_, layout_mapper)
for param in program_source.entry_point.parameters
],
)
Expand Down Expand Up @@ -321,14 +324,13 @@ class ExtensionGenerator:
Generate a Python extension module that contains the bindings for a C++ function.
"""

unstructured_horizontal_has_unit_stride: bool = config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE
#: Memory layout assumed for the arguments, see `create_bindings()`.
layout_mapper: next_allocators.FieldLayoutMapper | None = None

def __call__(
self, program_source: artifacts.ProgramSource[CodeSpecT]
) -> artifacts.ExtensionSource[CodeSpecT, artifacts.PythonCodeSpec]:
binding_source = create_bindings(
program_source, self.unstructured_horizontal_has_unit_stride
)
binding_source = create_bindings(program_source, self.layout_mapper)
return artifacts.ExtensionSource(
program_source=program_source, binding_source=binding_source
)
35 changes: 11 additions & 24 deletions src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from gt4py.next import common
from gt4py.next.ffront import fbuiltins
from gt4py.next.iterator import ir as itir
from gt4py.next.iterator.ir_utils import misc as ir_misc
from gt4py.next.iterator.transforms import pass_manager
from gt4py.next.otf import artifacts, stages, workflow
from gt4py.next.otf.binding import cpp_interface, interface
Expand All @@ -33,22 +32,6 @@ def get_param_description(name: str, type_: Any) -> interface.Parameter:
return interface.Parameter(name, type_)


@dataclasses.dataclass(frozen=True)
class GTFNProgramSource(artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec]):
"""
Program source emitted by the GTFN translation step.

It extends the generic `ProgramSource` with properties of the translated program
that only the GTFN toolchain needs, e.g. the grid type, which the GTFN bindings
step uses to decide whether the horizontal dimensions have unit stride.

TODO(edopao): This subclass should be removed once the unit-stride dimensions
are derived from the backend allocator layout, which is the long-term solution.
"""

grid_type: common.GridType


@dataclasses.dataclass(frozen=True)
class GTFNTranslationStep(
workflow.ReplaceEnabledWorkflowMixin[
Expand Down Expand Up @@ -190,7 +173,9 @@ def generate_stencil_source(

return GTFNCodegen.apply(gtfn_ir)

def __call__(self, inp: stages.CompilableProgramDef) -> GTFNProgramSource:
def __call__(
self, inp: stages.CompilableProgramDef
) -> artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec]:
"""Generate GTFN C++ code from the ITIR definition."""
program: itir.Program = inp.data

Expand Down Expand Up @@ -232,13 +217,15 @@ def __call__(self, inp: stages.CompilableProgramDef) -> GTFNProgramSource:
]
)

return GTFNProgramSource(
entry_point=function,
library_deps=(interface.LibraryDependency(self._library_name(), "master"),),
source_code=source_code,
code_spec=self._code_spec(),
grid_type=ir_misc.grid_type_from_program(program),
module: artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec] = (
artifacts.ProgramSource(
entry_point=function,
library_deps=(interface.LibraryDependency(self._library_name(), "master"),),
source_code=source_code,
code_spec=self._code_spec(),
)
)
return module

def _backend_header(self) -> str:
match self.device_type:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg import lower_program_to_sdfg
from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_utils import (
flatten_tuple_fields,
get_dimension_from_map_variable,
get_map_variable,
safe_replace_symbolic,
)


__all__ = [
"flatten_tuple_fields",
"get_dimension_from_map_variable",
"get_map_variable",
"lower_program_to_sdfg",
"safe_replace_symbolic",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,25 @@ def get_map_variable(dim: gtx_common.Dimension) -> str:
return f"i_{dim.value}_gtx_{dim.kind}{suffix}"


def get_dimension_from_map_variable(
map_variable: str, kind: gtx_common.DimensionKind
) -> gtx_common.Dimension:
"""
Recover the dimension of a map variable, see `get_map_variable()`.

Note that the map variable does not distinguish a staggered dimension from its base
dimension, therefore the result is always the base dimension.

Args:
map_variable: Name of the map variable.
kind: The kind of the dimension, has to be horizontal or vertical.
"""
assert kind != gtx_common.DimensionKind.LOCAL
return gtx_common.Dimension(
map_variable.removeprefix("i_").removesuffix(f"_{kind}").removesuffix("_gtx"), kind
)


def make_tasklet_connector_for(name: str) -> str:
"""
Format tasklet connector name based on the naming convention to avoid conflicts with GTIR program symbols.
Expand Down
Loading
Loading