Skip to content

feat[next]: derive static unit strides from the backend allocator layout - #3063

Open
edopao wants to merge 30 commits into
GridTools:mainfrom
edopao:pass-unit-stride-dims-cartesian
Open

edopao wants to merge 30 commits into
GridTools:mainfrom
edopao:pass-unit-stride-dims-cartesian

Conversation

@edopao

@edopao edopao commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Compiled toolchains can assume that all field and connectivity arguments have the memory layout of the backend allocator, and specialize the generated code with a static unit stride on the innermost dimension. The layout belongs to the allocator; the toolchain only reads it.

ToolchainConfig.use_backend_allocator_layout     # env GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT, default False
  layout_mapper = get_layout_mapper(make_allocator())   # allocator.__gt_layout_mapper__, a plain picklable function
    GTFN:  nanobind.create_bindings(..., layout_mapper)
             static stride 1 on unit_stride_dimension(layout_mapper, dims)   # fields and connectivities
    DaCe:  find_constant_symbols(..., layout_mapper)
             stride symbol of unit_stride_dimension(...) := 1               # fields and connectivities
           gt_auto_optimize(unit_strides_kind = kind of the unit-stride dimension shared by most field arguments)
 custom_layout_allocators
+  LayoutAwareFieldBufferAllocatorProtocol    # optional: __gt_layout_mapper__
+  get_layout_mapper(allocator_or_backend)
+  unit_stride_dimension(layout_mapper, dims) # raises ValueError on an invalid layout map
 BaseFieldBufferAllocator
+  __gt_layout_mapper__ -> self.layout_mapper
 ToolchainConfig
+  use_backend_allocator_layout: bool
+  layout_mapper -> FieldLayoutMapper | None
  • With horizontal_first_layout_mapper (default CPU/GPU allocators) the unit-stride dimension is the first horizontal one, e.g. Cell in (Cell, K), IDim in (IDim, JDim, KDim), so the same assumption works on Cartesian and unstructured grids.
  • The layout mapper, not the allocator, is stored in the toolchain steps: allocators hold unpicklable state (array modules), while the steps must stay picklable and hashable for process-pool builds and cache keys.
  • DaCe: gt_auto_optimize() is configured with a single unit_strides_kind, so the translator passes the kind of the unit-stride dimension shared by most field arguments. When the layout is assumed this argument cannot be overridden; when it is not, it can be set in auto_optimize_args as before. Passing the layout mapper itself to the optimizer, to order each map by its own dimensions, is left as a follow-up.
  • Arguments whose layout differs from the allocator's are rejected at call time. In the DaCe fast-call path this check is still an assert, so it is skipped under python -O.

Why the flag is off by default

With the flag on, GTFN fails to compile Cartesian programs that apply a negative shift on the unit-stride dimension (e.g. IDim - 1), see #3071: GridTools' nanobind_adapter.hpp represents static strides as integral_constant<std::size_t, ...>, so the offset computation is unsigned. The default should be flipped once the signed-stride fix lands in GridTools and gridtools-cpp is bumped.

Evidence

  • Before: generated code uses runtime strides for every dimension.
    After: with GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT=1, GTFN bindings and DaCe SDFGs use a static unit stride on the innermost dimension of each field and connectivity; mismatched layouts are rejected.
  • GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT=1 uv run pytest tests/next_tests -k "gtfn or dace": TODO results.
  • Not tested on GPU.

Merge Danger

Door: two-way

Opt-in and off by default; with the flag off the generated code does not change.

Blast Radius: opt-in

  • New optional allocator interface (__gt_layout_mapper__): custom allocators that do not implement it simply get no layout assumption.
  • With the flag on, user code passing fields or connectivities not allocated with the backend allocator (e.g. plain C-ordered NumPy arrays) is rejected at call time.

@edopao edopao changed the title feat[next]: unit-stride configuration by dimension kind for both cartesian and next feat[next]: unit-stride configuration by dimension kind for both cartesian and unstructured grids Dec 1, 2026
Comment thread src/gt4py/next/otf/binding/nanobind.py Outdated
Comment on lines 210 to 217
unit_stride_dim = common.unit_stride_dimension(type_.dims, unit_stride_kind)
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,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Compile failure

With the unit-stride assumption enabled on cartesian grids, GTFN fails to compile programs applying a negative shift in the unit-stride dimension (e.g. IDim - 1), as documented in the PR description. The failure manifests as an opaque GridTools C++ error at JIT time. Since the setting is experimental and None by default this is not a regression for default users, but the limitation should be tracked (or surfaced as a documented restriction / clearer error) before the feature is promoted out of experimental status.

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
✅ Merge recommendation: Needs review
🔎 Failure modes

What: GTFN fails to compile cartesian programs that apply a negative shift in the unit-stride dimension (the known issue documented in the PR description), so enabling the new setting breaks such programs with an opaque GridTools C++ compiler error at JIT time instead of a clear DSL-level diagnostic.
Where: src/gt4py/next/otf/binding/nanobind.py:make_argument
Trigger: unit_stride_kind=HORIZONTAL (or GT4PY_UNIT_STRIDE_KIND=horizontal) combined with a cartesian program applying e.g. IDim - 1.
Detected by: Runtime JIT compile error (gridtools/fn/cartesian.hpp); no test in this PR exercises this scenario.
Covered in this PR: No

What: The DaCe path replaces the stride symbol of the first dimension of the configured kind with the constant 1 without a visible runtime check that the passed argument layout actually matches the assumption, so a wrongly-laid-out argument could be read/written with wrong addresses and silently produce wrong results. It remains uncertain whether the dace runner validates argument strides elsewhere in the execution path.
Where: src/gt4py/next/program_processors/runners/dace/workflow/translation.py:find_constant_symbols
Trigger: unit_stride_kind=HORIZONTAL with a program argument whose memory layout does not have unit stride on the first dimension of that kind (e.g. a C-order (IDim, JDim) array).
Detected by: Nothing in this PR; the gtfn path has a mismatch test (test_unit_stride_kind_cartesian_mismatch) but there is no dace equivalent.
Covered in this PR: No

What: The old GT4PY_UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE environment variable is silently ignored after this change, so environments that relied on it lose the unit-stride optimization without any deprecation warning.
Where: src/gt4py/next/config.py:_unit_stride_kind_from_env
Trigger: Upgrading with GT4PY_UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE=1 still set in the environment.
Detected by: Nothing automated; would only surface as a performance regression.
Covered in this PR: No

🏅 Score: 84
🧪 PR contains tests
🔒 No security concerns identified
🔀 No multiple PR themes

⚙️ Agent run details
  • Model: openai/zai-org/GLM-5.3-Flash
  • Tokens: 28,440 in / 25,901 out / 54,341 total
  • Time cost: 430.6s
  • AI calls: 1

`find_constant_symbols` only considered plain field arguments when collecting
the horizontal stride symbols, so the fields inside tuple arguments (inputs and
targets) kept symbolic strides. Flatten the tuple arguments, as already done
for the field origin symbols.
@edopao
edopao force-pushed the pass-unit-stride-dims-cartesian branch from b09b782 to 15bf569 Compare December 1, 2026 14:04
edopao added 14 commits December 1, 2026 15:24
…ured programs in gtfn

Add a required grid_type field to ProgramSource, filled by the gtfn and dace
translation steps, and use it in the nanobind bindings to apply
unstructured_horizontal_has_unit_stride only to unstructured programs.
Parametrize test_codegen (gtfn) and test_translation_grid_type (dace) over
cartesian and unstructured programs. The dace test also checks the strides
of the emitted SDFG, which makes the cartesian find_constant_symbols test
redundant.
…cture

Address review: revert grid_type on ProgramSource, compiledb and nanobind.
GTFNTranslationStep now emits a GTFNProgramSource, a ProgramSource subclass
with the grid type, and make_gtfn_bindings returns a GTFNBindings step that
enables unstructured_horizontal_has_unit_stride only for unstructured
programs before calling the unchanged nanobind.ExtensionGenerator.
…nsion kind

Replace `unstructured_horizontal_has_unit_stride` with `unit_stride_dimension`,
a `Dimension | DimensionKind | None` setting that names the dimension(s)
assumed to have unit stride in the memory layout of the field arguments:
a `DimensionKind` (e.g. `HORIZONTAL`) covers every dimension of that kind,
as for the unstructured case; a single `Dimension` (e.g. `IDim`) covers only
that dimension, which makes the assumption usable on cartesian grids too.

The nanobind bindings and the DaCe `find_constant_symbols` apply the setting
by dimension membership, so the grid-type plumbing of the previous commits
(`GTFNProgramSource`, `GTFNBindings`) is reverted. A field with more than one
matching dimension is rejected as an impossible layout. The DaCe auto-optimize
pipeline still reasons in terms of dimension kinds and receives `HORIZONTAL`
if the setting covers a horizontal dimension.

The `GT4PY_UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE` environment variable is
removed: it cannot express dimensions.

The nanobind adapter already validates static strides against the actual
buffer layout at call time, so a wrong assumption raises instead of producing
wrong results.
…tride dimension

`gt_auto_optimize()` now accepts `unit_strides_dimension`, a concrete GT4Py
`Dimension` with unit stride, next to the existing `unit_strides_kind`:

- `gt_set_iteration_order()` reorders the Maps such that the configured
  dimension is the innermost loop (the `MapIterationOrder` transformation
  already supported concrete dimensions).
- `gt_change_strides()` sets the strides of the transients such that the
  configured dimension is the fastest varying one. The axis is determined
  from the access pattern of each transient, using the Map parameter naming
  convention of the lowering. Transients that are not accessed along the
  dimension keep their strides, and horizontal dimensions fall back to the
  kind-based Fortran-order layout.

The DaCe translator forwards the configured unit-stride assumption in the
form `gt_auto_optimize()` expects: dimension kinds as `unit_strides_kind`,
concrete dimensions as `unit_strides_dimension`.

Also, the unit-stride assumption is resolved per field with
`common.resolve_unit_stride_dimension()`: a `DimensionKind` selects the
leading dimension of that kind, which is the dimension the standard GT4Py
allocators lay out with stride 1, so the assumption is also valid for
cartesian fields with more than one horizontal dimension.
…e backend test

`test_make_backend` now compiles a cartesian program with `IJ` fields and
configures `unit_stride_dimension=JDim` for both the CPU and the GPU
variant, instead of `DimensionKind.HORIZONTAL` on GPU and no assumption
on CPU. The configured dimension is forwarded to `gt_auto_optimize()` and
yields the constant stride symbols `__a/b/out_JDim_stride = 1` in both
variants.

To match the explicit assertions, the DaCe translator forwards both
`unit_strides_kind` and `unit_strides_dimension` to `gt_auto_optimize()`,
with the form not used by the configuration set to `None`.
…d only

Replace `unit_stride_dimension` with `unit_stride_kind`. The first dimension
of the given kind has unit stride, as laid out by
`horizontal_first_layout_mapper()`, so a concrete dimension is not needed.

- Remove the dimension-based code path from `gt_auto_optimize()` and
  `gt_change_strides()`.
- `MapIterationOrder`: make the first dimension of the kind the innermost
  one, consistent with the strides of the transients.
- Add `GT4PY_UNIT_STRIDE_KIND`, which replaces
  `GT4PY_UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE`.

Known limitation: with the assumption enabled, gtfn fails to compile cartesian
programs with a negative shift in the unit-stride dimension, because the
GridTools nanobind adapter uses an unsigned type for static strides.
…ption are rejected

Run a cartesian program with unit stride on the first horizontal dimension,
and check that a mismatching layout is rejected both on the first call and on
the following fast calls.
Set GT4PY_UNIT_STRIDE_KIND=horizontal in the test jobs of the dace backends.
The bindings tests compare against code with symbolic strides, therefore they
explicitly disable the assumption.
The input is the result of an embedded operation, whose memory layout is
chosen by the array library. On GPU it does not have unit stride on the first
horizontal dimension, which violates the unit-stride assumption.
@edopao
edopao force-pushed the pass-unit-stride-dims-cartesian branch from 15bf569 to b29eca7 Compare December 1, 2026 14:44
@edopao
edopao requested a review from havogt December 1, 2026 14:47
Restore the definition of IJFTYPE, lost in the rebase, and check that unit
stride is set on the first horizontal dimension only.
Recover the dimensions from the names of the map parameters, by means of the
new function get_dimension_from_map_variable(), instead of replicating the
canonical order of the dimensions.

@havogt havogt left a comment

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.

I'd propose we discuss this later today. My comments are ideas, not suggestions to do it now.

Comment thread src/gt4py/next/common.py Outdated
return NotImplemented


def unit_stride_dimension(

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.

I think we should ask the backend to provide this information, because the allocation strategy is a propery of the backend not of gt4py.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I agree, we should ask the (backend) allocator.

Comment thread src/gt4py/next/otf/binding/nanobind.py Outdated

def make_argument(
name: str, type_: ts.TypeSpec, unstructured_horizontal_has_unit_stride: bool
name: str, type_: ts.TypeSpec, unit_stride_kind: common.DimensionKind | None

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.

Possible alternative strategy could be to pass a function has_unit_stride: Callable[[Dimension], bool] to make this more customizable. Then the env flag would probably be assume_backend_allocator_layout.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I see. I would call the config option use_backend_allocator_layout and I would make it default True.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We need to keep the default False until the GridTools fix is merged.

@edopao edopao left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I like your suggestions, and I will draft an implementation. My proposal would be to merge #3048 as a fix, and work on this PR for the solution based on backend allocators.

Comment thread src/gt4py/next/otf/binding/nanobind.py Outdated

def make_argument(
name: str, type_: ts.TypeSpec, unstructured_horizontal_has_unit_stride: bool
name: str, type_: ts.TypeSpec, unit_stride_kind: common.DimensionKind | None

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We need to keep the default False until the GridTools fix is merged.

…ection

Add LayoutAwareFieldBufferAllocatorProtocol (__gt_layout_mapper__),
get_layout_mapper() and unit_stride_dimension(layout_mapper, dims).
ToolchainConfig.layout_mapper exposes the layout mapper of the toolchain's
allocator when GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT is set (default off).
…r layout

The nanobind bindings take the toolchain's layout mapper instead of a
dimension kind; the innermost dimension of fields and connectivity tables
gets a static unit stride.
…tor layout

find_constant_symbols takes the toolchain's layout mapper instead of a
dimension kind, for both fields and connectivity tables.
The DaCe optimizer's unit-stride kind is derived from the backend allocator
layout; GT4PY_UNIT_STRIDE_KIND and ToolchainConfig.unit_stride_kind are removed.
@edopao edopao changed the title feat[next]: unit-stride configuration by dimension kind for both cartesian and unstructured grids feat[next]: derive static unit strides from the backend allocator layout Dec 2, 2026
@edopao
edopao force-pushed the pass-unit-stride-dims-cartesian branch from 0da4fe5 to aadd9d0 Compare December 2, 2026 13:02
@edopao
edopao force-pushed the pass-unit-stride-dims-cartesian branch from aadd9d0 to e73578d Compare December 2, 2026 13:08
@edopao

edopao commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

With the fix GridTools/gridtools#1833 the GTFN pass.

There is one failure in dace tests, which seems related to #3046:
FAILED tests/next_tests/integration_tests/feature_tests/ffront_tests/test_concat_where.py::test_lap_like[dynamic_domains-dace.run_dace_gpu] - AssertionError: Verification failed:

This branch was previously deployed

1 inactive (outdated) deployment
pr-agent — 71e330de Deployed Dec 1, 2026 by edopao via pr-agent / pr-agent #243
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants