From cf1729374ce58b664dfb14b6411e29ce446bcdaf Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 14:55:42 +0100 Subject: [PATCH 01/28] fix[next-dace]: replace unit stride on fields in tuple arguments `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. --- .../runners/dace/workflow/translation.py | 65 +++++++++---------- .../dace_tests/test_dace_translation.py | 63 ++++++++++++++++++ 2 files changed, 92 insertions(+), 36 deletions(-) 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 2909e1a651..77c0b79b53 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -39,21 +39,32 @@ def find_constant_symbols( """Helper function to find symbols to replace with constant values.""" constant_symbols: dict[str, int] = {} + # Collect all fields in the program arguments, including the elements of tuples + field_params: list[tuple[str, ts.FieldType]] = [] + for p in ir.params: + psymbols = ( + gtx_dace_lowering.flatten_tuple_fields(p.id, p.type) + if isinstance(p.type, ts.TupleType) + else [p] + ) + field_params.extend( + (str(sym.id), sym.type) for sym in psymbols if isinstance(sym.type, ts.FieldType) + ) + if unstructured_horizontal_has_unit_stride: # Search the stride symbols corresponding to the horizontal dimension - for p in ir.params: - if isinstance(p.type, ts.FieldType): - h_dims = [dim for dim in p.type.dims if dim.kind == common.DimensionKind.HORIZONTAL] - if len(h_dims) == 0: - continue - elif len(h_dims) == 1: - dim = h_dims[0] - else: - raise NotImplementedError( - f"Unsupported field with multiple horizontal dimensions '{p}'." - ) - sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(str(p.id), dim) - constant_symbols[sdfg_stride_symbol.name] = 1 + for name, field_type in field_params: + h_dims = [dim for dim in field_type.dims if dim.kind == common.DimensionKind.HORIZONTAL] + if len(h_dims) == 0: + continue + elif len(h_dims) == 1: + dim = h_dims[0] + else: + raise NotImplementedError( + f"Unsupported field with multiple horizontal dimensions '{name}'." + ) + sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, dim) + constant_symbols[sdfg_stride_symbol.name] = 1 # Same for connectivity tables, for which the first dimension is always horizontal for offset, conn_type in offset_provider_type.items(): if ( @@ -68,29 +79,11 @@ def find_constant_symbols( constant_symbols[sdfg_stride_symbol.name] = 1 if disable_field_origin_on_program_arguments: - # collect symbols used as range start for all program arguments - for p in ir.params: - if isinstance(p.type, ts.TupleType): - psymbols = [ - sym - for sym in gtx_dace_lowering.flatten_tuple_fields(p.id, p.type) - if isinstance(sym.type, ts.FieldType) - ] - elif isinstance(p.type, ts.FieldType): - psymbols = [p] - else: - psymbols = [] - for psymbol in psymbols: - assert isinstance(psymbol.type, ts.FieldType) - if len(psymbol.type.dims) == 0: - # zero-dimensional field - continue - # set all range start symbols to constant value 0 - sdfg_origin_symbols = [ - gtx_dace_args.range_start_symbol(str(psymbol.id), dim) - for dim in psymbol.type.dims - ] - constant_symbols |= {sdfg_symbol.name: 0 for sdfg_symbol in sdfg_origin_symbols} + # set all range start symbols of the program arguments to constant value 0 + for name, field_type in field_params: + constant_symbols |= { + gtx_dace_args.range_start_symbol(name, dim).name: 0 for dim in field_type.dims + } return constant_symbols 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 8174c37190..a275530f16 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 @@ -132,6 +132,69 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): assert constant_symbols == expected +@pytest.mark.parametrize("has_unit_stride", [False, True]) +@pytest.mark.parametrize("disable_field_origin", [False, True]) +def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin): + """Fields nested in tuple arguments, both inputs and targets, are also considered.""" + domain = im.get_field_domain( + gtx_common.GridType.UNSTRUCTURED, im.tuple_get(0, "y"), VFTYPE.dims + ) + ir = itir.Program( + id="find_constant_symbols_tuple_args_sdfg", + function_definitions=[], + params=[ + # the scalar element has no field symbols + itir.Sym(id="x", type=ts.TupleType(types=[VFTYPE, FLOAT_TYPE])), + itir.Sym( + id="y", type=ts.TupleType(types=[VFTYPE, ts.TupleType(types=[VFTYPE, VFTYPE])]) + ), + ], + declarations=[], + body=[ + itir.SetAt( + expr=im.make_tuple( + im.op_as_fieldop("plus")(im.tuple_get(0, "x"), im.tuple_get(1, "x")), + im.make_tuple(im.tuple_get(0, "x"), im.tuple_get(0, "x")), + ), + # the domain has the same tuple structure as the target + domain=im.make_tuple(domain, im.make_tuple(domain, domain)), + target=itir.SymRef(id="y"), + ) + ], + ) + + sdfg = dace_wf_translation.DaCeTranslator( + device_type=core_defs.DeviceType.CPU, + auto_optimize=False, + auto_optimize_args=None, + async_sdfg_call=False, + unstructured_horizontal_has_unit_stride=has_unit_stride, + use_metrics=False, + disable_field_origin_on_program_arguments=disable_field_origin, + ).generate_sdfg(ir, offset_provider={}, column_axis=None) + + constant_symbols = dace_wf_translation.find_constant_symbols( + ir=ir, + sdfg=sdfg, + offset_provider_type={}, + disable_field_origin_on_program_arguments=disable_field_origin, + unstructured_horizontal_has_unit_stride=has_unit_stride, + ) + + field_names = ["x_0", "y_0", "y_1_0", "y_1_1"] + expected = {} + if has_unit_stride: + expected |= {f"__{name}_Vertex_stride": 1 for name in field_names} + if disable_field_origin: + expected |= {f"__{name}_Vertex_range_0": 0 for name in field_names} + assert constant_symbols == expected + + # check that the symbols have been replaced in the translated SDFG + for name in field_names: + expected_stride = "1" if has_unit_stride else f"__{name}_Vertex_stride" + assert [str(stride) for stride in sdfg.arrays[name].strides] == [expected_stride] + + def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. return False From 7701f718a96acba083c06f5feb9ba7747102c68a Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 15:24:01 +0100 Subject: [PATCH 02/28] test[next-dace]: cover multiple horizontal dims in tuple arguments --- .../dace_tests/test_dace_translation.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) 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 a275530f16..44aa1fe913 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 @@ -32,6 +32,7 @@ V2E, Edge, IDim, + JDim, Vertex, skip_value_mesh, ) @@ -41,6 +42,7 @@ FLOAT_TYPE = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) IFTYPE = ts.FieldType(dims=[IDim], dtype=FLOAT_TYPE) +IJFTYPE = ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE) EFTYPE = ts.FieldType(dims=[Edge], dtype=FLOAT_TYPE) VFTYPE = ts.FieldType(dims=[Vertex], dtype=FLOAT_TYPE) @@ -195,6 +197,50 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) assert [str(stride) for stride in sdfg.arrays[name].strides] == [expected_stride] +@pytest.mark.parametrize( + "param_type, field_name", + [ + pytest.param(IJFTYPE, "x", id="field"), + pytest.param(ts.TupleType(types=[IFTYPE, IJFTYPE]), "x_1", id="tuple"), + pytest.param( + ts.TupleType(types=[IFTYPE, ts.TupleType(types=[IFTYPE, IJFTYPE])]), + "x_1_1", + id="nested_tuple", + ), + ], +) +def test_find_constant_symbols_multiple_horizontal_dims(param_type, field_name): + """Unit stride is ambiguous on a field with multiple horizontal dimensions.""" + ir = itir.Program( + id="find_constant_symbols_multiple_horizontal_dims", + function_definitions=[], + params=[itir.Sym(id="x", type=param_type)], + declarations=[], + body=[], + ) + kwargs = { + "ir": ir, + "sdfg": dace.SDFG("find_constant_symbols_multiple_horizontal_dims"), + "offset_provider_type": {}, + "disable_field_origin_on_program_arguments": False, + } + + with pytest.raises( + NotImplementedError, match=rf"multiple horizontal dimensions '{field_name}'" + ): + dace_wf_translation.find_constant_symbols( + **kwargs, unstructured_horizontal_has_unit_stride=True + ) + + # the same field is supported when the unit-stride option is disabled + assert ( + dace_wf_translation.find_constant_symbols( + **kwargs, unstructured_horizontal_has_unit_stride=False + ) + == {} + ) + + def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. return False From 81e810804fc1397a32f14e7c3ae5a7d7f31ac5f3 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 26 Nov 2026 10:06:25 +0100 Subject: [PATCH 03/28] set unit stride on horizontal dimensions only for unstructured domain --- .../program_processors/runners/dace/workflow/translation.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 77c0b79b53..6110e55c60 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -17,6 +17,7 @@ from gt4py.next import common from gt4py.next.instrumentation import metrics from gt4py.next.iterator import ir as itir, transforms as itir_transforms +from gt4py.next.iterator.ir_utils import misc as ir_misc from gt4py.next.iterator.transforms import scan_fusion as gtx_scan_fusion from gt4py.next.otf import artifacts, stages, workflow from gt4py.next.otf.binding import interface @@ -51,7 +52,8 @@ def find_constant_symbols( (str(sym.id), sym.type) for sym in psymbols if isinstance(sym.type, ts.FieldType) ) - if unstructured_horizontal_has_unit_stride: + grid_type = ir_misc.grid_type_from_program(ir) + if (grid_type == common.GridType.UNSTRUCTURED) and unstructured_horizontal_has_unit_stride: # Search the stride symbols corresponding to the horizontal dimension for name, field_type in field_params: h_dims = [dim for dim in field_type.dims if dim.kind == common.DimensionKind.HORIZONTAL] From 8a1da79387fe5cd8c60bb7101cd4485f8e7eaf1d Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 26 Nov 2026 10:21:02 +0100 Subject: [PATCH 04/28] add test coverage --- .../dace_tests/test_dace_translation.py | 65 +++++++++++++++---- 1 file changed, 54 insertions(+), 11 deletions(-) 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 44aa1fe913..f99ce176a9 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 @@ -33,6 +33,7 @@ Edge, IDim, JDim, + KDim, Vertex, skip_value_mesh, ) @@ -42,9 +43,6 @@ FLOAT_TYPE = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) IFTYPE = ts.FieldType(dims=[IDim], dtype=FLOAT_TYPE) -IJFTYPE = ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE) -EFTYPE = ts.FieldType(dims=[Edge], dtype=FLOAT_TYPE) -VFTYPE = ts.FieldType(dims=[Vertex], dtype=FLOAT_TYPE) @pytest.fixture( @@ -81,15 +79,18 @@ def _translate_gtir_to_sdfg( @pytest.mark.parametrize("has_unit_stride", [False, True]) @pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols(has_unit_stride, disable_field_origin): +def test_find_constant_symbols_unstructured(has_unit_stride, disable_field_origin): + """Unit stride must only be set on the horizontal dimension, not on the vertical one.""" SKIP_VALUE_MESH = skip_value_mesh(None) + ekftype = ts.FieldType(dims=[Edge, KDim], dtype=FLOAT_TYPE) + vkftype = ts.FieldType(dims=[Vertex, KDim], dtype=FLOAT_TYPE) ir = itir.Program( - id="find_constant_symbols_sdfg", + id="find_constant_symbols_unstructured_sdfg", function_definitions=[], params=[ - itir.Sym(id="x", type=EFTYPE), - itir.Sym(id="y", type=VFTYPE), + itir.Sym(id="x", type=ekftype), + itir.Sym(id="y", type=vkftype), ], declarations=[], body=[ @@ -97,7 +98,7 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): expr=im.as_fieldop( im.lambda_("it")(im.reduce("plus", im.literal_from_value(1.0))(im.deref("it"))) )(im.as_fieldop_neighbors(V2E.value, "x")), - domain=im.get_field_domain(gtx_common.GridType.UNSTRUCTURED, "y", VFTYPE.dims), + domain=im.get_field_domain(gtx_common.GridType.UNSTRUCTURED, "y", vkftype.dims), target=itir.SymRef(id="y"), ) ], @@ -121,6 +122,7 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): expected = {} if has_unit_stride: + # The vertical dimension stride symbols must not be set to 1. expected |= { "__x_Edge_stride": 1, "__y_Vertex_stride": 1, @@ -129,26 +131,67 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): if disable_field_origin: expected |= { "__x_Edge_range_0": 0, + "__x_KDim_range_0": 0, "__y_Vertex_range_0": 0, + "__y_KDim_range_0": 0, } assert constant_symbols == expected +def test_find_constant_symbols_cartesian(): + """Unit stride must not be set on fields of a cartesian program.""" + ir = itir.Program( + id="find_constant_symbols_cartesian_sdfg", + declarations=[], + function_definitions=[], + params=[ + itir.Sym(id="x", type=ts.FieldType(dims=[IDim], dtype=FLOAT_TYPE)), + itir.Sym(id="y", type=ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE)), + ], + body=[ + itir.SetAt( + expr=im.op_as_fieldop("plus")("x", 1.0), + domain=im.get_field_domain(gtx_common.GridType.CARTESIAN, "y", [IDim, JDim]), + target=itir.SymRef(id="y"), + ), + ], + ) + + sdfg = _translate_gtir_to_sdfg( + ir=ir, + offset_provider={}, + device_type=core_defs.DeviceType.CPU, + auto_optimize=False, + async_sdfg_call=False, + ) + + constant_symbols = dace_wf_translation.find_constant_symbols( + ir=ir, + sdfg=sdfg, + offset_provider_type={}, + disable_field_origin_on_program_arguments=False, + unstructured_horizontal_has_unit_stride=True, + ) + + assert constant_symbols == {} + + @pytest.mark.parametrize("has_unit_stride", [False, True]) @pytest.mark.parametrize("disable_field_origin", [False, True]) def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin): """Fields nested in tuple arguments, both inputs and targets, are also considered.""" + vftype = ts.FieldType(dims=[Vertex], dtype=FLOAT_TYPE) domain = im.get_field_domain( - gtx_common.GridType.UNSTRUCTURED, im.tuple_get(0, "y"), VFTYPE.dims + gtx_common.GridType.UNSTRUCTURED, im.tuple_get(0, "y"), vftype.dims ) ir = itir.Program( id="find_constant_symbols_tuple_args_sdfg", function_definitions=[], params=[ # the scalar element has no field symbols - itir.Sym(id="x", type=ts.TupleType(types=[VFTYPE, FLOAT_TYPE])), + itir.Sym(id="x", type=ts.TupleType(types=[vftype, FLOAT_TYPE])), itir.Sym( - id="y", type=ts.TupleType(types=[VFTYPE, ts.TupleType(types=[VFTYPE, VFTYPE])]) + id="y", type=ts.TupleType(types=[vftype, ts.TupleType(types=[vftype, vftype])]) ), ], declarations=[], From 732875e56668676f2951a63addadbc76721cb900 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 26 Nov 2026 10:50:30 +0100 Subject: [PATCH 05/28] fix[next]: set unit stride on horizontal dimensions only for unstructured 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. --- src/gt4py/next/otf/artifacts.py | 4 ++ src/gt4py/next/otf/binding/nanobind.py | 11 +++- .../compilation/build_systems/compiledb.py | 4 +- .../codegens/gtfn/gtfn_module.py | 2 + .../runners/dace/workflow/translation.py | 1 + .../otf_tests/binding_tests/test_nanobind.py | 59 ++++++++++++++++++- .../build_systems_tests/conftest.py | 3 +- .../unit_tests/otf_tests/test_languages.py | 2 + .../dace_tests/test_dace_cache_consistency.py | 3 +- .../dace_tests/test_dace_compilation.py | 3 +- .../dace_tests/test_dace_translation.py | 2 +- 11 files changed, 84 insertions(+), 10 deletions(-) diff --git a/src/gt4py/next/otf/artifacts.py b/src/gt4py/next/otf/artifacts.py index fa3226153b..5870855c52 100644 --- a/src/gt4py/next/otf/artifacts.py +++ b/src/gt4py/next/otf/artifacts.py @@ -28,6 +28,7 @@ from collections.abc import Callable from typing import Generic, Optional, Protocol, TypeAlias, TypeVar, runtime_checkable +from gt4py.next import common from gt4py.next.otf.binding import interface @@ -107,12 +108,15 @@ class ProgramSource(Generic[CodeSpecT]): - implementation language and language conventions - dependencies on implementation language libraries - how to call the program + - the grid type of the program (e.g. bindings use it to decide whether the + horizontal dimensions can be assumed to have unit stride) """ entry_point: interface.Function source_code: str library_deps: tuple[interface.LibraryDependency, ...] code_spec: CodeSpecT + grid_type: common.GridType @dataclasses.dataclass(frozen=True) diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index f67b3383a6..0a903745e3 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -253,6 +253,13 @@ def create_bindings( ) wrapper_name = program_source.entry_point.name + "_wrapper" + # Unit stride on horizontal dimensions is only assumed for unstructured programs: + # on a cartesian grid, a field can have more than one horizontal dimension. + has_unit_stride = ( + unstructured_horizontal_has_unit_stride + and program_source.grid_type == common.GridType.UNSTRUCTURED + ) + Stmt = ReturnStmt if program_source.entry_point.returns else ExprStmt file_binding = BindingFile( callee_header_file=f"{program_source.entry_point.name}.{program_source.code_spec.header_extension}", @@ -283,9 +290,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_, has_unit_stride) for param in program_source.entry_point.parameters ], ) diff --git a/src/gt4py/next/otf/compilation/build_systems/compiledb.py b/src/gt4py/next/otf/compilation/build_systems/compiledb.py index 92a9facb08..d90de86b5b 100644 --- a/src/gt4py/next/otf/compilation/build_systems/compiledb.py +++ b/src/gt4py/next/otf/compilation/build_systems/compiledb.py @@ -17,7 +17,7 @@ from typing import Final, Optional, TypeVar from gt4py._core import file_utils, locking -from gt4py.next import config, errors, fingerprinting +from gt4py.next import common, config, errors, fingerprinting from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface from gt4py.next.otf.compilation import build_data, cache, compiler @@ -263,6 +263,8 @@ def _cc_prototype_program_source( source_code="", library_deps=deps, code_spec=code_spec, + # The prototype program is empty, it has no grid: any grid type will do. + grid_type=common.GridType.CARTESIAN, ) 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..6e8adaa375 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -17,6 +17,7 @@ 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 @@ -223,6 +224,7 @@ def __call__( 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), ) ) return module 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 6110e55c60..137c1eb7c1 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -534,5 +534,6 @@ def __call__( source_code=gtx_wfdcommon.serialize_sdfg_as_json(sdfg), # type: ignore[arg-type] # The source code is typed as a `str`, but we assign a JSON dictionary. library_deps=tuple(), code_spec=artifacts.SDFGCodeSpec(), + grid_type=ir_misc.grid_type_from_program(program), ) return module diff --git a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py index 50a82692ba..52acb73025 100644 --- a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py +++ b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py @@ -6,8 +6,13 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -from gt4py.next import config -from gt4py.next.otf.binding import nanobind +import pytest + +import gt4py.next as gtx +import gt4py.next.type_system.type_specifications as ts +from gt4py.next import common, config +from gt4py.next.otf import artifacts +from gt4py.next.otf.binding import interface, nanobind from next_tests.unit_tests.otf_tests.compilation_tests.build_systems_tests.conftest import ( program_source_example, @@ -19,3 +24,53 @@ def test_bindings(program_source_example): program_source_example, config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE ) assert module.library_deps[0].name == "nanobind" + + +_DYN = "gridtools::nanobind::dynamic_size" + + +@pytest.mark.parametrize( + "grid_type, dims, has_unit_stride, expected_stride_spec", + [ + # unstructured: unit stride on the horizontal dimension only, not on the vertical one + ( + common.GridType.UNSTRUCTURED, + [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], + True, + f"1, {_DYN}", + ), + ( + common.GridType.UNSTRUCTURED, + [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], + False, + f"{_DYN}, {_DYN}", + ), + # cartesian: never unit stride, although both dimensions are horizontal + ( + common.GridType.CARTESIAN, + [gtx.Dimension("I"), gtx.Dimension("J")], + True, + f"{_DYN}, {_DYN}", + ), + ], +) +def test_bindings_static_strides(grid_type, dims, has_unit_stride, expected_stride_spec): + program_source = artifacts.ProgramSource( + entry_point=interface.Function( + "stencil", + parameters=( + interface.Parameter( + name="buf", + type_=ts.FieldType(dims=dims, dtype=ts.ScalarType(ts.ScalarKind.FLOAT64)), + ), + ), + ), + source_code="", + library_deps=(), + code_spec=artifacts.CPPCodeSpec(), + grid_type=grid_type, + ) + + bindings = nanobind.create_bindings(program_source, has_unit_stride) + + assert f"gridtools::nanobind::stride_spec<{expected_stride_spec}>{{}}" in bindings.source_code diff --git a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py index ba83a07b2d..fccef0f3aa 100644 --- a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py +++ b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py @@ -13,7 +13,7 @@ import gt4py.next as gtx import gt4py.next.type_system.type_specifications as ts -from gt4py.next import config +from gt4py.next import common, config from gt4py.next.otf import artifacts from gt4py.next.otf.binding import cpp_interface, interface, nanobind from gt4py.next.otf.compilation import cache @@ -74,6 +74,7 @@ def make_program_source(name: str) -> artifacts.ProgramSource: source_code=src, library_deps=(interface.LibraryDependency("gridtools_cpu", "master"),), code_spec=artifacts.CPPCodeSpec(), + grid_type=common.GridType.CARTESIAN, ) diff --git a/tests/next_tests/unit_tests/otf_tests/test_languages.py b/tests/next_tests/unit_tests/otf_tests/test_languages.py index 08a738d017..ae1d091903 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_languages.py +++ b/tests/next_tests/unit_tests/otf_tests/test_languages.py @@ -8,6 +8,7 @@ import pytest +from gt4py.next import common from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface @@ -18,4 +19,5 @@ def test_header_files_settings_with_cpp_accepted(): source_code="", library_deps=(), code_spec=artifacts.CPPCodeSpec(), + grid_type=common.GridType.CARTESIAN, ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py index becf9ee9f6..87dba54653 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py @@ -31,7 +31,7 @@ import pytest from gt4py._core import definitions as core_defs, locking -from gt4py.next import config, fingerprinting +from gt4py.next import common, config, fingerprinting from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface from gt4py.next.otf.compilation import cache as gtx_cache @@ -64,6 +64,7 @@ def _make_input(name: str) -> artifacts.ExtensionSource: source_code=sdfg.to_json(), library_deps=(), code_spec=artifacts.SDFGCodeSpec(), + grid_type=common.GridType.CARTESIAN, ) return artifacts.ExtensionSource( program_source=program_source, diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py index 35478779e4..0c8bf68ba0 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py @@ -24,7 +24,7 @@ from dace.sdfg import nodes as dace_nodes from gt4py._core import definitions as core_defs -from gt4py.next import config +from gt4py.next import common, config from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface from gt4py.next.program_processors.runners.dace.workflow import ( @@ -93,6 +93,7 @@ def program_source() -> dace_wf_compilation.SDFGExtensionSource: source_code=_make_sdfg_with_gpu_map().to_json(), library_deps=(), code_spec=artifacts.SDFGCodeSpec(), + grid_type=common.GridType.CARTESIAN, ) binding_source = artifacts.BindingSource(source_code="", library_deps=()) return artifacts.ExtensionSource(program_source=program_source, binding_source=binding_source) 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 f99ce176a9..2f1e7f1858 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 @@ -145,7 +145,7 @@ def test_find_constant_symbols_cartesian(): declarations=[], function_definitions=[], params=[ - itir.Sym(id="x", type=ts.FieldType(dims=[IDim], dtype=FLOAT_TYPE)), + itir.Sym(id="x", type=ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE)), itir.Sym(id="y", type=ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE)), ], body=[ From 2190e9d00aa160f8582a501ce66898c75e07351a Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 26 Nov 2026 11:30:00 +0100 Subject: [PATCH 06/28] test[next]: check grid_type emitted by gtfn and dace translation steps 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. --- .../gtfn_tests/test_gtfn_module.py | 96 +++++++++++++------ .../dace_tests/test_dace_translation.py | 87 ++++++++++++----- 2 files changed, 131 insertions(+), 52 deletions(-) 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..78eb16a1be 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 @@ -9,32 +9,34 @@ import copy from gt4py._core import filecache -import numpy as np import pytest import gt4py.next as gtx from gt4py.next.iterator import builtins, ir as itir from gt4py.next.iterator.ir_utils import ir_makers as im -from gt4py.next import fingerprinting +from gt4py.next import common, fingerprinting from gt4py.next.otf import arguments, artifacts, stages from gt4py.next.program_processors.codegens.gtfn import gtfn_module from gt4py.next.program_processors.runners import gtfn -from gt4py.next.type_system import type_translation +from gt4py.next.type_system import type_specifications as ts from gt4py.next import custom_layout_allocators as next_allocators from next_tests.integration_tests import cases from next_tests.integration_tests.cases import cartesian_case, cartesian_case_no_backend from next_tests.integration_tests.cases_utils import ( + V2E, + Edge, KDim, + Vertex, exec_alloc_descriptor, + skip_value_mesh, ) -@pytest.fixture -def program_example(): - IDim = gtx.Dimension("I") - params = [gtx.as_field([IDim], np.empty((1,), dtype=np.float32)), np.float32(3.14)] - param_types = [type_translation.from_value(param) for param in params] +def _make_cartesian_program() -> itir.Program: + """Point-wise operation on a 1D cartesian field.""" + float_type = ts.ScalarType(kind=ts.ScalarKind.FLOAT32) + param_types = [ts.FieldType(dims=[gtx.Dimension("I")], dtype=float_type), float_type] domain = itir.FunCall( fun=itir.SymRef(id="cartesian_domain"), @@ -49,7 +51,7 @@ def program_example(): ) ], ) - program = itir.Program( + return itir.Program( id="example", params=[im.sym(name, type_) for name, type_ in zip(("buf", "sc"), param_types)], function_definitions=[ @@ -70,28 +72,66 @@ def program_example(): ) ], ) - return program, params -def test_codegen(program_example): - fencil, parameters = program_example - module = gtfn_module.translate_program_cpu( - stages.CompilableProgramDef( - data=fencil, - args=arguments.CompileTimeArgs.from_concrete(*parameters, **{"offset_provider": {}}), - ) +def _make_unstructured_program() -> itir.Program: + """Neighbor reduction over 'V2E'.""" + float_type = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) + vftype = ts.FieldType(dims=[Vertex], dtype=float_type) + return itir.Program( + id="example_unstructured", + function_definitions=[], + params=[ + im.sym("x", ts.FieldType(dims=[Edge], dtype=float_type)), + im.sym("y", vftype), + ], + declarations=[], + body=[ + itir.SetAt( + expr=im.as_fieldop( + im.lambda_("it")(im.reduce("plus", im.literal_from_value(1.0))(im.deref("it"))) + )(im.as_fieldop_neighbors(V2E.value, "x")), + domain=im.get_field_domain(common.GridType.UNSTRUCTURED, "y", vftype.dims), + target=itir.SymRef(id="y"), + ) + ], ) - assert module.entry_point.name == fencil.id + + +def _make_compilable_program( + program: itir.Program, offset_provider: common.OffsetProvider +) -> stages.CompilableProgramDef: + return stages.CompilableProgramDef( + data=program, + args=arguments.CompileTimeArgs( + args=tuple(param.type for param in program.params), + kwargs={}, + offset_provider=offset_provider, + column_axis=None, + argument_descriptor_contexts={}, + ), + ) + + +@pytest.mark.parametrize("grid_type", [common.GridType.CARTESIAN, common.GridType.UNSTRUCTURED]) +def test_codegen(grid_type): + if grid_type == common.GridType.CARTESIAN: + program = _make_cartesian_program() + offset_provider = {} + else: + program = _make_unstructured_program() + offset_provider = skip_value_mesh(None).offset_provider + + module = gtfn_module.translate_program_cpu(_make_compilable_program(program, offset_provider)) + + assert module.entry_point.name == program.id assert any(d.name == "gridtools_cpu" for d in module.library_deps) assert isinstance(module.code_spec, artifacts.CPPCodeSpec) + assert module.grid_type == grid_type -def test_hash_and_diskcache(program_example, tmp_path): - fencil, parameters = program_example - compilable_program = stages.CompilableProgramDef( - data=fencil, - args=arguments.CompileTimeArgs.from_concrete(*parameters, **{"offset_provider": {}}), - ) +def test_hash_and_diskcache(tmp_path): + compilable_program = _make_compilable_program(_make_cartesian_program(), offset_provider={}) hash = fingerprinting.strict_fingerprinter(compilable_program) cache = filecache.FileCache(tmp_path) @@ -128,12 +168,8 @@ def test_hash_and_diskcache(program_example, tmp_path): ) != fingerprinting.strict_fingerprinter(altered_program_column_axis) -def test_gtfn_file_cache(program_example): - fencil, parameters = program_example - compilable_program = stages.CompilableProgramDef( - data=fencil, - args=arguments.CompileTimeArgs.from_concrete(*parameters, **{"offset_provider": {}}), - ) +def test_gtfn_file_cache(): + compilable_program = _make_compilable_program(_make_cartesian_program(), offset_provider={}) cached_gtfn_translation_step = gtfn.make_gtfn_compile_workflow( gtfn.GTFNConfig(cached_translation=True) ).translation 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 2f1e7f1858..aec8a4f784 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 @@ -77,16 +77,13 @@ def _translate_gtir_to_sdfg( ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) -@pytest.mark.parametrize("has_unit_stride", [False, True]) -@pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols_unstructured(has_unit_stride, disable_field_origin): - """Unit stride must only be set on the horizontal dimension, not on the vertical one.""" - SKIP_VALUE_MESH = skip_value_mesh(None) +def _make_unstructured_program(program_id: str) -> itir.Program: + """Neighbor reduction over 'V2E' on fields with a vertical dimension.""" ekftype = ts.FieldType(dims=[Edge, KDim], dtype=FLOAT_TYPE) vkftype = ts.FieldType(dims=[Vertex, KDim], dtype=FLOAT_TYPE) - ir = itir.Program( - id="find_constant_symbols_unstructured_sdfg", + return itir.Program( + id=program_id, function_definitions=[], params=[ itir.Sym(id="x", type=ekftype), @@ -104,6 +101,14 @@ def test_find_constant_symbols_unstructured(has_unit_stride, disable_field_origi ], ) + +@pytest.mark.parametrize("has_unit_stride", [False, True]) +@pytest.mark.parametrize("disable_field_origin", [False, True]) +def test_find_constant_symbols(has_unit_stride, disable_field_origin): + """Unit stride must only be set on the horizontal dimension, not on the vertical one.""" + SKIP_VALUE_MESH = skip_value_mesh(None) + ir = _make_unstructured_program("find_constant_symbols_sdfg") + sdfg = _translate_gtir_to_sdfg( ir=ir, offset_provider=SKIP_VALUE_MESH.offset_provider, @@ -138,10 +143,10 @@ def test_find_constant_symbols_unstructured(has_unit_stride, disable_field_origi assert constant_symbols == expected -def test_find_constant_symbols_cartesian(): - """Unit stride must not be set on fields of a cartesian program.""" - ir = itir.Program( - id="find_constant_symbols_cartesian_sdfg", +def _make_cartesian_program(program_id: str) -> itir.Program: + """Point-wise operation on fields with two horizontal dimensions.""" + return itir.Program( + id=program_id, declarations=[], function_definitions=[], params=[ @@ -157,23 +162,61 @@ def test_find_constant_symbols_cartesian(): ], ) - sdfg = _translate_gtir_to_sdfg( - ir=ir, - offset_provider={}, + +@pytest.mark.parametrize( + "grid_type", [gtx_common.GridType.CARTESIAN, gtx_common.GridType.UNSTRUCTURED] +) +def test_translation_grid_type(grid_type): + """ + The translator records the grid type of the program on its output, and the + emitted SDFG has unit stride on the horizontal dimension only for unstructured + programs. + """ + if grid_type == gtx_common.GridType.UNSTRUCTURED: + ir = _make_unstructured_program("translation_grid_type_unstructured") + offset_provider = skip_value_mesh(None).offset_provider + expected_strides = { + "x": ("1", "__x_KDim_stride"), + "y": ("1", "__y_KDim_stride"), + "gt_conn_V2E": ("1", "__gt_conn_V2E_neighbor_stride"), + } + else: + ir = _make_cartesian_program("translation_grid_type_cartesian") + offset_provider = {} + expected_strides = { + "x": ("__x_IDim_stride", "__x_JDim_stride"), + "y": ("__y_IDim_stride", "__y_JDim_stride"), + } + + compilable_program = otf_workflow.ConcreteArtifact( + data=ir, + args=otf_arguments.CompileTimeArgs( + args=tuple(param.type for param in ir.params), + kwargs={}, + offset_provider=offset_provider, + column_axis=None, + argument_descriptor_contexts={}, + ), + ) + translator = dace_wf_translation.DaCeTranslator( device_type=core_defs.DeviceType.CPU, auto_optimize=False, + auto_optimize_args=None, async_sdfg_call=False, - ) - - constant_symbols = dace_wf_translation.find_constant_symbols( - ir=ir, - sdfg=sdfg, - offset_provider_type={}, - disable_field_origin_on_program_arguments=False, unstructured_horizontal_has_unit_stride=True, + use_metrics=False, ) - assert constant_symbols == {} + program_source = translator(compilable_program) + + assert program_source.grid_type == grid_type + sdfg = dace.SDFG.from_json(program_source.source_code) + strides = { + name: tuple(str(stride) for stride in desc.strides) + for name, desc in sdfg.arrays.items() + if not desc.transient + } + assert strides == expected_strides @pytest.mark.parametrize("has_unit_stride", [False, True]) From 42073c70ffa5e9e7fd8e1f49af4a29d17871fbe2 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 26 Nov 2026 13:19:19 +0100 Subject: [PATCH 07/28] refactor[next]: keep the grid type out of the generic build infrastructure 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. --- src/gt4py/next/otf/artifacts.py | 4 -- src/gt4py/next/otf/binding/nanobind.py | 11 +--- .../compilation/build_systems/compiledb.py | 4 +- .../codegens/gtfn/gtfn_module.py | 32 ++++++---- .../runners/dace/workflow/translation.py | 1 - .../next/program_processors/runners/gtfn.py | 36 +++++++++-- .../otf_tests/binding_tests/test_nanobind.py | 59 +---------------- .../build_systems_tests/conftest.py | 3 +- .../unit_tests/otf_tests/test_languages.py | 2 - .../gtfn_tests/test_gtfn_module.py | 3 +- .../dace_tests/test_dace_cache_consistency.py | 3 +- .../dace_tests/test_dace_compilation.py | 3 +- .../dace_tests/test_dace_translation.py | 7 +- .../runners_tests/test_gtfn.py | 64 ++++++++++++++++++- 14 files changed, 125 insertions(+), 107 deletions(-) diff --git a/src/gt4py/next/otf/artifacts.py b/src/gt4py/next/otf/artifacts.py index 5870855c52..fa3226153b 100644 --- a/src/gt4py/next/otf/artifacts.py +++ b/src/gt4py/next/otf/artifacts.py @@ -28,7 +28,6 @@ from collections.abc import Callable from typing import Generic, Optional, Protocol, TypeAlias, TypeVar, runtime_checkable -from gt4py.next import common from gt4py.next.otf.binding import interface @@ -108,15 +107,12 @@ class ProgramSource(Generic[CodeSpecT]): - implementation language and language conventions - dependencies on implementation language libraries - how to call the program - - the grid type of the program (e.g. bindings use it to decide whether the - horizontal dimensions can be assumed to have unit stride) """ entry_point: interface.Function source_code: str library_deps: tuple[interface.LibraryDependency, ...] code_spec: CodeSpecT - grid_type: common.GridType @dataclasses.dataclass(frozen=True) diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index 0a903745e3..f67b3383a6 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -253,13 +253,6 @@ def create_bindings( ) wrapper_name = program_source.entry_point.name + "_wrapper" - # Unit stride on horizontal dimensions is only assumed for unstructured programs: - # on a cartesian grid, a field can have more than one horizontal dimension. - has_unit_stride = ( - unstructured_horizontal_has_unit_stride - and program_source.grid_type == common.GridType.UNSTRUCTURED - ) - Stmt = ReturnStmt if program_source.entry_point.returns else ExprStmt file_binding = BindingFile( callee_header_file=f"{program_source.entry_point.name}.{program_source.code_spec.header_extension}", @@ -290,7 +283,9 @@ def create_bindings( expr=FunctionCall( target=program_source.entry_point, args=[ - make_argument(param.name, param.type_, has_unit_stride) + make_argument( + param.name, param.type_, unstructured_horizontal_has_unit_stride + ) for param in program_source.entry_point.parameters ], ) diff --git a/src/gt4py/next/otf/compilation/build_systems/compiledb.py b/src/gt4py/next/otf/compilation/build_systems/compiledb.py index d90de86b5b..92a9facb08 100644 --- a/src/gt4py/next/otf/compilation/build_systems/compiledb.py +++ b/src/gt4py/next/otf/compilation/build_systems/compiledb.py @@ -17,7 +17,7 @@ from typing import Final, Optional, TypeVar from gt4py._core import file_utils, locking -from gt4py.next import common, config, errors, fingerprinting +from gt4py.next import config, errors, fingerprinting from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface from gt4py.next.otf.compilation import build_data, cache, compiler @@ -263,8 +263,6 @@ def _cc_prototype_program_source( source_code="", library_deps=deps, code_spec=code_spec, - # The prototype program is empty, it has no grid: any grid type will do. - grid_type=common.GridType.CARTESIAN, ) 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 6e8adaa375..bb07317b87 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -33,6 +33,19 @@ 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. + """ + + grid_type: common.GridType + + @dataclasses.dataclass(frozen=True) class GTFNTranslationStep( workflow.ReplaceEnabledWorkflowMixin[ @@ -174,9 +187,7 @@ def generate_stencil_source( return GTFNCodegen.apply(gtfn_ir) - def __call__( - self, inp: stages.CompilableProgramDef - ) -> artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec]: + def __call__(self, inp: stages.CompilableProgramDef) -> GTFNProgramSource: """Generate GTFN C++ code from the ITIR definition.""" program: itir.Program = inp.data @@ -218,16 +229,13 @@ def __call__( ] ) - 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(), - grid_type=ir_misc.grid_type_from_program(program), - ) + 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), ) - return module def _backend_header(self) -> str: match self.device_type: 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 137c1eb7c1..6110e55c60 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -534,6 +534,5 @@ def __call__( source_code=gtx_wfdcommon.serialize_sdfg_as_json(sdfg), # type: ignore[arg-type] # The source code is typed as a `str`, but we assign a JSON dictionary. library_deps=tuple(), code_spec=artifacts.SDFGCodeSpec(), - grid_type=ir_misc.grid_type_from_program(program), ) return module diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index f73f4e0cd6..a65bd67786 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -167,15 +167,41 @@ def make_gtfn_translation( ) +@dataclasses.dataclass(frozen=True) +class GTFNBindings: + """ + Generate the nanobind bindings of a program translated by `GTFNTranslationStep`. + + Unit stride on the horizontal dimensions is assumed only for unstructured + programs: on a cartesian grid, a field can have more than one horizontal + dimension. + """ + + unstructured_horizontal_has_unit_stride: bool + + def __call__( + self, program_source: gtfn_module.GTFNProgramSource + ) -> artifacts.ExtensionSource[artifacts.HeaderAndSourceCodeSpec, artifacts.PythonCodeSpec]: + has_unit_stride = ( + self.unstructured_horizontal_has_unit_stride + and program_source.grid_type == common.GridType.UNSTRUCTURED + ) + # `GTFNTranslationStep` types its code spec as `HeaderAndSourceCodeSpec`, while + # `ExtensionGenerator` accepts only C++-like specs, the only ones the step emits. + return nanobind.ExtensionGenerator( # type: ignore[type-var] # see comment above + unstructured_horizontal_has_unit_stride=has_unit_stride + )(program_source) + + def make_gtfn_bindings( cfg: GTFNConfig, / ) -> workflow.Workflow[artifacts.ProgramSource, artifacts.ExtensionSource]: """Build the step generating the nanobind bindings of the translated program.""" - # `OTFCompileWorkflow` is not parameterized over the code spec, so its - # `bindings` field is typed for `ProgramSource[Any]` while - # `ExtensionGenerator` accepts only C++-like specs. Parameterizing the - # pipeline is the real fix and belongs with the pipeline rework. - return nanobind.ExtensionGenerator( # type: ignore[return-value] # see comment above + # `OTFCompileWorkflow` is not parameterized over the program source, so its + # `bindings` field is typed for `ProgramSource[Any]` while `GTFNBindings` + # accepts only the `GTFNProgramSource` emitted by `GTFNTranslationStep`. + # Parameterizing the pipeline is the real fix and belongs with the pipeline rework. + return GTFNBindings( # type: ignore[return-value] # see comment above unstructured_horizontal_has_unit_stride=cfg.unstructured_horizontal_has_unit_stride ) diff --git a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py index 52acb73025..50a82692ba 100644 --- a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py +++ b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py @@ -6,13 +6,8 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import pytest - -import gt4py.next as gtx -import gt4py.next.type_system.type_specifications as ts -from gt4py.next import common, config -from gt4py.next.otf import artifacts -from gt4py.next.otf.binding import interface, nanobind +from gt4py.next import config +from gt4py.next.otf.binding import nanobind from next_tests.unit_tests.otf_tests.compilation_tests.build_systems_tests.conftest import ( program_source_example, @@ -24,53 +19,3 @@ def test_bindings(program_source_example): program_source_example, config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE ) assert module.library_deps[0].name == "nanobind" - - -_DYN = "gridtools::nanobind::dynamic_size" - - -@pytest.mark.parametrize( - "grid_type, dims, has_unit_stride, expected_stride_spec", - [ - # unstructured: unit stride on the horizontal dimension only, not on the vertical one - ( - common.GridType.UNSTRUCTURED, - [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], - True, - f"1, {_DYN}", - ), - ( - common.GridType.UNSTRUCTURED, - [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], - False, - f"{_DYN}, {_DYN}", - ), - # cartesian: never unit stride, although both dimensions are horizontal - ( - common.GridType.CARTESIAN, - [gtx.Dimension("I"), gtx.Dimension("J")], - True, - f"{_DYN}, {_DYN}", - ), - ], -) -def test_bindings_static_strides(grid_type, dims, has_unit_stride, expected_stride_spec): - program_source = artifacts.ProgramSource( - entry_point=interface.Function( - "stencil", - parameters=( - interface.Parameter( - name="buf", - type_=ts.FieldType(dims=dims, dtype=ts.ScalarType(ts.ScalarKind.FLOAT64)), - ), - ), - ), - source_code="", - library_deps=(), - code_spec=artifacts.CPPCodeSpec(), - grid_type=grid_type, - ) - - bindings = nanobind.create_bindings(program_source, has_unit_stride) - - assert f"gridtools::nanobind::stride_spec<{expected_stride_spec}>{{}}" in bindings.source_code diff --git a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py index fccef0f3aa..ba83a07b2d 100644 --- a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py +++ b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py @@ -13,7 +13,7 @@ import gt4py.next as gtx import gt4py.next.type_system.type_specifications as ts -from gt4py.next import common, config +from gt4py.next import config from gt4py.next.otf import artifacts from gt4py.next.otf.binding import cpp_interface, interface, nanobind from gt4py.next.otf.compilation import cache @@ -74,7 +74,6 @@ def make_program_source(name: str) -> artifacts.ProgramSource: source_code=src, library_deps=(interface.LibraryDependency("gridtools_cpu", "master"),), code_spec=artifacts.CPPCodeSpec(), - grid_type=common.GridType.CARTESIAN, ) diff --git a/tests/next_tests/unit_tests/otf_tests/test_languages.py b/tests/next_tests/unit_tests/otf_tests/test_languages.py index ae1d091903..08a738d017 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_languages.py +++ b/tests/next_tests/unit_tests/otf_tests/test_languages.py @@ -8,7 +8,6 @@ import pytest -from gt4py.next import common from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface @@ -19,5 +18,4 @@ def test_header_files_settings_with_cpp_accepted(): source_code="", library_deps=(), code_spec=artifacts.CPPCodeSpec(), - grid_type=common.GridType.CARTESIAN, ) 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 78eb16a1be..af51efc596 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 @@ -124,10 +124,11 @@ def test_codegen(grid_type): module = gtfn_module.translate_program_cpu(_make_compilable_program(program, offset_provider)) + assert isinstance(module, gtfn_module.GTFNProgramSource) + assert module.grid_type == grid_type assert module.entry_point.name == program.id assert any(d.name == "gridtools_cpu" for d in module.library_deps) assert isinstance(module.code_spec, artifacts.CPPCodeSpec) - assert module.grid_type == grid_type def test_hash_and_diskcache(tmp_path): diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py index 87dba54653..becf9ee9f6 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_cache_consistency.py @@ -31,7 +31,7 @@ import pytest from gt4py._core import definitions as core_defs, locking -from gt4py.next import common, config, fingerprinting +from gt4py.next import config, fingerprinting from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface from gt4py.next.otf.compilation import cache as gtx_cache @@ -64,7 +64,6 @@ def _make_input(name: str) -> artifacts.ExtensionSource: source_code=sdfg.to_json(), library_deps=(), code_spec=artifacts.SDFGCodeSpec(), - grid_type=common.GridType.CARTESIAN, ) return artifacts.ExtensionSource( program_source=program_source, diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py index 0c8bf68ba0..35478779e4 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_compilation.py @@ -24,7 +24,7 @@ from dace.sdfg import nodes as dace_nodes from gt4py._core import definitions as core_defs -from gt4py.next import common, config +from gt4py.next import config from gt4py.next.otf import artifacts from gt4py.next.otf.binding import interface from gt4py.next.program_processors.runners.dace.workflow import ( @@ -93,7 +93,6 @@ def program_source() -> dace_wf_compilation.SDFGExtensionSource: source_code=_make_sdfg_with_gpu_map().to_json(), library_deps=(), code_spec=artifacts.SDFGCodeSpec(), - grid_type=common.GridType.CARTESIAN, ) binding_source = artifacts.BindingSource(source_code="", library_deps=()) return artifacts.ExtensionSource(program_source=program_source, binding_source=binding_source) 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 aec8a4f784..07c56ea41f 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 @@ -167,11 +167,7 @@ def _make_cartesian_program(program_id: str) -> itir.Program: "grid_type", [gtx_common.GridType.CARTESIAN, gtx_common.GridType.UNSTRUCTURED] ) def test_translation_grid_type(grid_type): - """ - The translator records the grid type of the program on its output, and the - emitted SDFG has unit stride on the horizontal dimension only for unstructured - programs. - """ + """The emitted SDFG has unit stride on the horizontal dimension only for unstructured programs.""" if grid_type == gtx_common.GridType.UNSTRUCTURED: ir = _make_unstructured_program("translation_grid_type_unstructured") offset_provider = skip_value_mesh(None).offset_provider @@ -209,7 +205,6 @@ def test_translation_grid_type(grid_type): program_source = translator(compilable_program) - assert program_source.grid_type == grid_type sdfg = dace.SDFG.from_json(program_source.source_code) strides = { name: tuple(str(stride) for stride in desc.strides) 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..b93f637cb0 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 @@ -26,11 +26,14 @@ import pytest import gt4py._core.definitions as core_defs -from gt4py.next import config, custom_layout_allocators -from gt4py.next.otf import workflow +import gt4py.next as gtx +from gt4py.next import common, config, custom_layout_allocators +from gt4py.next.otf import artifacts, workflow +from gt4py.next.otf.binding import interface from gt4py.next.otf.compilation import build_data, cache, compiler, importer from gt4py.next.program_processors.codegens.gtfn import gtfn_module from gt4py.next.program_processors.runners import gtfn +from gt4py.next.type_system import type_specifications as ts def test_make_gtfn_toolchain_device(): @@ -204,3 +207,60 @@ def test_compile_workflow_without_config_caches_translation(): assert isinstance(workflow_.translation, workflow.CachedStep) assert isinstance(workflow_.translation.step, gtfn_module.GTFNTranslationStep) + + +_DYN = "gridtools::nanobind::dynamic_size" + + +@pytest.mark.parametrize( + "grid_type, dims, has_unit_stride, expected_stride_spec", + [ + # unstructured: unit stride on the horizontal dimension only, not on the vertical one + ( + common.GridType.UNSTRUCTURED, + [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], + True, + f"1, {_DYN}", + ), + ( + common.GridType.UNSTRUCTURED, + [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], + False, + f"{_DYN}, {_DYN}", + ), + # cartesian: never unit stride, although both dimensions are horizontal + ( + common.GridType.CARTESIAN, + [gtx.Dimension("I"), gtx.Dimension("J")], + True, + f"{_DYN}, {_DYN}", + ), + ], +) +def test_bindings_static_strides(grid_type, dims, has_unit_stride, expected_stride_spec): + program_source = gtfn_module.GTFNProgramSource( + entry_point=interface.Function( + "stencil", + parameters=( + interface.Parameter( + name="buf", + type_=ts.FieldType(dims=dims, dtype=ts.ScalarType(ts.ScalarKind.FLOAT64)), + ), + ), + ), + source_code="", + library_deps=(), + code_spec=artifacts.CPPCodeSpec(), + grid_type=grid_type, + ) + bindings = gtfn.make_gtfn_bindings( + gtfn.GTFNConfig(unstructured_horizontal_has_unit_stride=has_unit_stride) + ) + + extension = bindings(program_source) + + assert extension.binding_source is not None + assert ( + f"gridtools::nanobind::stride_spec<{expected_stride_spec}>{{}}" + in extension.binding_source.source_code + ) From f3feea3a104adf2c596797f04be74e853e216837 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 26 Nov 2026 13:36:45 +0100 Subject: [PATCH 08/28] fix dace test --- .../runners_tests/dace_tests/test_dace_backend.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) 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 cbabcb94aa..990870bcd1 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 @@ -136,11 +136,9 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: mock_auto_optimize.assert_called_once_with( sdfg, gpu=on_gpu, - constant_symbols={ - "__a_IDim_stride": 1, - "__b_IDim_stride": 1, - "__out_IDim_stride": 1, - }, + # `testee` is a cartesian program: the horizontal strides are not set + # to 1, although `unstructured_horizontal_has_unit_stride` is enabled. + constant_symbols={}, transient_memory_mode=optimization_args["transient_memory_mode"], gpu_block_size=optimization_args["gpu_block_size"], gpu_block_size_2d=optimization_args["gpu_block_size_2d"], From a60a27b49c156d33c79661483aa5b6d9e266ff90 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 11:13:03 +0100 Subject: [PATCH 09/28] feat[next]: configure the unit-stride assumption by dimension or dimension 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. --- src/gt4py/next/backend.py | 10 +- src/gt4py/next/common.py | 27 +++++ src/gt4py/next/config.py | 14 ++- src/gt4py/next/otf/binding/nanobind.py | 38 +++--- .../codegens/gtfn/gtfn_module.py | 21 +--- .../runners/dace/workflow/backend.py | 11 +- .../runners/dace/workflow/factory.py | 2 +- .../runners/dace/workflow/translation.py | 61 +++++----- .../next/program_processors/runners/gtfn.py | 38 +----- .../otf_tests/test_gtfn_workflow.py | 61 ++++++++++ .../otf_tests/binding_tests/test_nanobind.py | 4 +- .../build_systems_tests/conftest.py | 2 +- .../gtfn_tests/test_gtfn_module.py | 3 +- .../dace_tests/test_dace_backend.py | 19 +-- .../dace_tests/test_dace_translation.py | 109 +++++++++++++----- .../dace_tests/test_scan_fusion.py | 6 +- .../runners_tests/test_gtfn.py | 54 ++++++--- 17 files changed, 317 insertions(+), 163 deletions(-) diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 11774edce1..0ad9230c84 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -30,6 +30,7 @@ if TYPE_CHECKING: + from gt4py.next import common from gt4py.next.ffront import decorator as ffront_decorator @@ -255,9 +256,12 @@ 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 + #: Dimension or dimension kind that is assumed to have unit stride in the + #: memory layout of the field arguments, see `common.has_unit_stride()`. + #: E.g. `DimensionKind.HORIZONTAL` for an unstructured mesh, or a single + #: dimension like `IDim` on a cartesian grid; `None` disables the assumption. + unit_stride_dimension: common.UnitStrideDimension = dataclasses.field( + default_factory=lambda: config.UNIT_STRIDE_DIMENSION ) @property diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index cf42e74093..37784e2098 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -130,6 +130,33 @@ def __ne__(self, value: Dimension | core_defs.IntegralScalar) -> bool | Domain: return NotImplemented +#: A dimension or a dimension kind that a toolchain may assume to have unit +#: stride in the memory layout of the field arguments, or `None` for no +#: assumption. +UnitStrideDimension: TypeAlias = Dimension | DimensionKind | None + + +def has_unit_stride(dim: Dimension, unit_stride_dimension: UnitStrideDimension, /) -> bool: + """ + Check if a dimension is covered by a unit-stride assumption. + + Args: + dim: The dimension to check. + unit_stride_dimension: A `Dimension` matched by value and kind, or a + `DimensionKind` matched against the kind of `dim`, or `None`. + + Returns: + Whether `dim` is assumed to have unit stride. + """ + match unit_stride_dimension: + case DimensionKind() as kind: + return dim.kind == kind + case Dimension(): + return dim == unit_stride_dimension + case None: + return False + + if TYPE_CHECKING: # These exist as on-the fly replacements for Dimension instances # (which are not types) during typechecking (with mypy). We can diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index 3076d4a1b8..5ecdd42dee 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -14,7 +14,11 @@ import pathlib import sys import warnings -from typing import Final +from typing import TYPE_CHECKING, Final + + +if TYPE_CHECKING: + from gt4py.next import common # Module-level UPPERCASE values are snapshotted and shipped verbatim to @@ -140,10 +144,10 @@ 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 -) +#: Dimension or dimension kind that compiled toolchains may assume to have +#: unit stride in the memory layout of the field arguments, see +#: `common.has_unit_stride()`. `None` disables the assumption. +UNIT_STRIDE_DIMENSION: common.UnitStrideDimension = None #: Add GPU trace markers (NVTX, ROC-TX) to the generated code, at compile time. diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index f67b3383a6..7aea71e772 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -204,20 +204,25 @@ 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, unit_stride_dimension: common.UnitStrideDimension ) -> str | BufferSID | Tuple: if isinstance(type_, ts.FieldType): + unit_stride_dims = [ + dim for dim in type_.dims if common.has_unit_stride(dim, unit_stride_dimension) + ] + if len(unit_stride_dims) > 1: + raise ValueError( + f"Invalid unit-stride assumption: field '{name}' with dimensions " + f"'{type_.dims}' has more than one dimension with unit stride " + f"('{unit_stride_dimension}'). Configure a single dimension instead of a " + "dimension 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 in unit_stride_dims else None, ) for dim in type_.dims ], @@ -225,7 +230,7 @@ def make_argument( ) elif isinstance(type_, ts.TupleType): elements = [ - make_argument(_tuple_get(i, name), t, unstructured_horizontal_has_unit_stride) + make_argument(_tuple_get(i, name), t, unit_stride_dimension) for i, t in enumerate(type_.types) ] return Tuple(elems=elements) @@ -237,7 +242,7 @@ def make_argument( def create_bindings( program_source: artifacts.ProgramSource[CodeSpecT], - unstructured_horizontal_has_unit_stride: bool, + unit_stride_dimension: common.UnitStrideDimension, ) -> artifacts.BindingSource[CodeSpecT, artifacts.PythonCodeSpec]: """ Generate Python bindings through which a C++ function can be called. @@ -246,6 +251,9 @@ def create_bindings( ---------- program_source The program source for which the bindings are created + unit_stride_dimension + Dimension or dimension kind that is assumed to have unit stride in the + memory layout of the field arguments, see `common.has_unit_stride()`. """ if not isinstance(program_source.code_spec, artifacts.CPPLikeCodeSpec): raise ValueError( @@ -283,9 +291,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_, unit_stride_dimension) for param in program_source.entry_point.parameters ], ) @@ -321,14 +327,14 @@ 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 + unit_stride_dimension: common.UnitStrideDimension = dataclasses.field( + default_factory=lambda: config.UNIT_STRIDE_DIMENSION + ) 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.unit_stride_dimension) return artifacts.ExtensionSource( program_source=program_source, binding_source=binding_source ) 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 bb07317b87..e5bd424a54 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -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 @@ -33,19 +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. - """ - - grid_type: common.GridType - - @dataclasses.dataclass(frozen=True) class GTFNTranslationStep( workflow.ReplaceEnabledWorkflowMixin[ @@ -187,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 @@ -229,12 +217,11 @@ def __call__(self, inp: stages.CompilableProgramDef) -> GTFNProgramSource: ] ) - return GTFNProgramSource( + return artifacts.ProgramSource( 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), ) def _backend_header(self) -> str: 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 2665354f91..696b4c314f 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -13,7 +13,7 @@ import warnings from typing import Any -from gt4py.next import backend, config +from gt4py.next import backend, common, config from gt4py.next.otf import artifacts from gt4py.next.program_processors.runners.dace.workflow import ( common as gtx_wfdcommon, @@ -80,7 +80,7 @@ def make_dace_backend( 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, + unit_stride_dimension: common.UnitStrideDimension = config.UNIT_STRIDE_DIMENSION, use_metrics: bool = True, use_zero_origin: bool = False, use_max_domain_range_on_unstructured_shift: bool | None = None, @@ -102,8 +102,9 @@ def make_dace_backend( accepts the scan-fusion options `fuse_scan_inputs` and `scan_fusion_scope`. 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'. + unit_stride_dimension: Dimension or dimension kind that is assumed to have + unit stride in the memory layout of the field arguments; its stride + symbols are replaced by '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 @@ -133,7 +134,7 @@ def make_dace_backend( gpu=gpu, auto_optimize=auto_optimize, external_workspace=external_workspace, - unstructured_horizontal_has_unit_stride=unstructured_horizontal_has_unit_stride, + unit_stride_dimension=unit_stride_dimension, ), translation=functools.partial( gtx_wfdfactory.make_dace_translator, 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 0295940a68..b074520a9b 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -135,7 +135,7 @@ def make_dace_translator( auto_optimize=cfg.auto_optimize, auto_optimize_args=optimization_args, async_sdfg_call=async_sdfg_call and cfg.gpu, - unstructured_horizontal_has_unit_stride=cfg.unstructured_horizontal_has_unit_stride, + unit_stride_dimension=cfg.unit_stride_dimension, use_metrics=use_metrics, disable_field_origin_on_program_arguments=disable_field_origin_on_program_arguments, use_max_domain_range_on_unstructured_shift=use_max_domain_range_on_unstructured_shift, 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 6110e55c60..4e1f895ba0 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -17,7 +17,6 @@ from gt4py.next import common from gt4py.next.instrumentation import metrics from gt4py.next.iterator import ir as itir, transforms as itir_transforms -from gt4py.next.iterator.ir_utils import misc as ir_misc from gt4py.next.iterator.transforms import scan_fusion as gtx_scan_fusion from gt4py.next.otf import artifacts, stages, workflow from gt4py.next.otf.binding import interface @@ -35,7 +34,7 @@ def find_constant_symbols( sdfg: dace.SDFG, offset_provider_type: common.OffsetProviderType, disable_field_origin_on_program_arguments: bool, - unstructured_horizontal_has_unit_stride: bool, + unit_stride_dimension: common.UnitStrideDimension, ) -> dict[str, int]: """Helper function to find symbols to replace with constant values.""" constant_symbols: dict[str, int] = {} @@ -52,21 +51,22 @@ def find_constant_symbols( (str(sym.id), sym.type) for sym in psymbols if isinstance(sym.type, ts.FieldType) ) - grid_type = ir_misc.grid_type_from_program(ir) - if (grid_type == common.GridType.UNSTRUCTURED) and unstructured_horizontal_has_unit_stride: - # Search the stride symbols corresponding to the horizontal dimension + if unit_stride_dimension is not None: + # Search the stride symbols of the dimensions with unit stride for name, field_type in field_params: - h_dims = [dim for dim in field_type.dims if dim.kind == common.DimensionKind.HORIZONTAL] - if len(h_dims) == 0: - continue - elif len(h_dims) == 1: - dim = h_dims[0] - else: - raise NotImplementedError( - f"Unsupported field with multiple horizontal dimensions '{name}'." + unit_stride_dims = [ + dim for dim in field_type.dims if common.has_unit_stride(dim, unit_stride_dimension) + ] + if len(unit_stride_dims) > 1: + raise ValueError( + f"Invalid unit-stride assumption: field '{p.id}' with dimensions " + f"'{field_type.dims}' has more than one dimension with unit stride " + f"('{unit_stride_dimension}'). Configure a single dimension instead " + "of a dimension kind." ) - sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, dim) - constant_symbols[sdfg_stride_symbol.name] = 1 + for dim in unit_stride_dims: + sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, dim) + constant_symbols[sdfg_stride_symbol.name] = 1 # Same for connectivity tables, for which the first dimension is always horizontal for offset, conn_type in offset_provider_type.items(): if ( @@ -75,10 +75,11 @@ def find_constant_symbols( ): assert not sdfg.arrays[conn_id].transient assert conn_type.source_dim.kind == common.DimensionKind.HORIZONTAL - sdfg_stride_symbol = gtx_dace_args.field_stride_symbol( - conn_id, conn_type.source_dim, offset_provider_type - ) - constant_symbols[sdfg_stride_symbol.name] = 1 + if common.has_unit_stride(conn_type.source_dim, unit_stride_dimension): + sdfg_stride_symbol = gtx_dace_args.field_stride_symbol( + conn_id, conn_type.source_dim, offset_provider_type + ) + constant_symbols[sdfg_stride_symbol.name] = 1 if disable_field_origin_on_program_arguments: # set all range start symbols of the program arguments to constant value 0 @@ -403,7 +404,7 @@ class DaCeTranslator( auto_optimize: bool auto_optimize_args: dict[str, Any] | None async_sdfg_call: bool - unstructured_horizontal_has_unit_stride: bool + unit_stride_dimension: common.UnitStrideDimension use_metrics: bool disable_field_origin_on_program_arguments: bool = False @@ -465,19 +466,27 @@ def _generate_sdfg_without_configuring_dace( sdfg, offset_provider_type, self.disable_field_origin_on_program_arguments, - self.unstructured_horizontal_has_unit_stride, + self.unit_stride_dimension, ) + # `gt_auto_optimize()` reasons in terms of dimension kinds, not dimensions: + # it can exploit the unit-stride assumption only if the assumed dimension, + # or the kind covering it, is horizontal. + match self.unit_stride_dimension: + case ( + common.DimensionKind.HORIZONTAL + | common.Dimension(kind=common.DimensionKind.HORIZONTAL) + ): + unit_strides_kind: common.DimensionKind | None = common.DimensionKind.HORIZONTAL + case _: + unit_strides_kind = None + if self.auto_optimize: gtx_transformations.gt_auto_optimize( sdfg, gpu=on_gpu, constant_symbols=constant_symbols, - unit_strides_kind=( - common.DimensionKind.HORIZONTAL - if self.unstructured_horizontal_has_unit_stride - else None - ), + unit_strides_kind=unit_strides_kind, **auto_optimize_args, ) elif on_gpu: diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index a65bd67786..4e4107f99b 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -167,42 +167,16 @@ def make_gtfn_translation( ) -@dataclasses.dataclass(frozen=True) -class GTFNBindings: - """ - Generate the nanobind bindings of a program translated by `GTFNTranslationStep`. - - Unit stride on the horizontal dimensions is assumed only for unstructured - programs: on a cartesian grid, a field can have more than one horizontal - dimension. - """ - - unstructured_horizontal_has_unit_stride: bool - - def __call__( - self, program_source: gtfn_module.GTFNProgramSource - ) -> artifacts.ExtensionSource[artifacts.HeaderAndSourceCodeSpec, artifacts.PythonCodeSpec]: - has_unit_stride = ( - self.unstructured_horizontal_has_unit_stride - and program_source.grid_type == common.GridType.UNSTRUCTURED - ) - # `GTFNTranslationStep` types its code spec as `HeaderAndSourceCodeSpec`, while - # `ExtensionGenerator` accepts only C++-like specs, the only ones the step emits. - return nanobind.ExtensionGenerator( # type: ignore[type-var] # see comment above - unstructured_horizontal_has_unit_stride=has_unit_stride - )(program_source) - - def make_gtfn_bindings( cfg: GTFNConfig, / ) -> workflow.Workflow[artifacts.ProgramSource, artifacts.ExtensionSource]: """Build the step generating the nanobind bindings of the translated program.""" - # `OTFCompileWorkflow` is not parameterized over the program source, so its - # `bindings` field is typed for `ProgramSource[Any]` while `GTFNBindings` - # accepts only the `GTFNProgramSource` emitted by `GTFNTranslationStep`. - # Parameterizing the pipeline is the real fix and belongs with the pipeline rework. - return GTFNBindings( # type: ignore[return-value] # see comment above - unstructured_horizontal_has_unit_stride=cfg.unstructured_horizontal_has_unit_stride + # `OTFCompileWorkflow` is not parameterized over the code spec, so its + # `bindings` field is typed for `ProgramSource[Any]` while + # `ExtensionGenerator` accepts only C++-like specs. Parameterizing the + # pipeline is the real fix and belongs with the pipeline rework. + return nanobind.ExtensionGenerator( # type: ignore[return-value] # see comment above + unit_stride_dimension=cfg.unit_stride_dimension ) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py b/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py index d27989c18a..df8043fadd 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py @@ -7,8 +7,11 @@ # SPDX-License-Identifier: BSD-3-Clause import numpy as np +import pytest import gt4py.next as gtx +from gt4py.next import common +from gt4py.next.embedded import nd_array_field from gt4py.next.program_processors.runners import gtfn from next_tests.integration_tests.cases import IDim, JDim @@ -37,3 +40,61 @@ def copy(inp: gtx.Field[[IDim, JDim], gtx.int32]) -> gtx.Field[[IDim, JDim], gtx copy(inp, out=out, offset_provider={}) assert np.allclose(inp[:out_nx, :out_ny].asnumpy(), out.asnumpy()) + + +def test_unit_stride_dimension_cartesian(): + """ + A cartesian program can assume unit stride on a single horizontal dimension. + + The unit-stride dimension must match the memory layout of the arguments, + which the nanobind adapter checks at runtime. + """ + nx = 6 + ny = 7 + backend = gtfn.make_gtfn_toolchain( + gtfn.GTFNConfig(unit_stride_dimension=IDim), name_postfix="_unit_stride_idim" + ) + + # column-major buffers have unit stride on the first dimension + inp = nd_array_field.NdArrayField.from_array( + np.asfortranarray(np.arange(nx * ny, dtype=np.int32).reshape((nx, ny))), + domain=common.domain({IDim: range(nx), JDim: range(ny)}), + ) + out = nd_array_field.NdArrayField.from_array( + np.zeros((nx, ny), dtype=np.int32, order="F"), + domain=common.domain({IDim: range(nx), JDim: range(ny)}), + ) + + @gtx.field_operator(backend=backend) + def copy(inp: gtx.Field[[IDim, JDim], gtx.int32]) -> gtx.Field[[IDim, JDim], gtx.int32]: + return inp + + copy(inp, out=out, offset_provider={}) + + assert np.array_equal(inp.ndarray, out.ndarray) + + +def test_unit_stride_dimension_cartesian_mismatch(): + """The nanobind adapter rejects arguments whose layout does not match the assumption.""" + nx = 6 + ny = 7 + backend = gtfn.make_gtfn_toolchain( + gtfn.GTFNConfig(unit_stride_dimension=IDim), name_postfix="_unit_stride_idim_mismatch" + ) + + # row-major buffers have unit stride on the last dimension + inp = nd_array_field.NdArrayField.from_array( + np.arange(nx * ny, dtype=np.int32).reshape((nx, ny)), + domain=common.domain({IDim: range(nx), JDim: range(ny)}), + ) + out = nd_array_field.NdArrayField.from_array( + np.zeros((nx, ny), dtype=np.int32), + domain=common.domain({IDim: range(nx), JDim: range(ny)}), + ) + + @gtx.field_operator(backend=backend) + def copy(inp: gtx.Field[[IDim, JDim], gtx.int32]) -> gtx.Field[[IDim, JDim], gtx.int32]: + return inp + + with pytest.raises(ValueError, match="doesn't match dynamic stride"): + copy(inp, out=out, offset_provider={}) diff --git a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py index 50a82692ba..5d1b68bb00 100644 --- a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py +++ b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py @@ -15,7 +15,5 @@ def test_bindings(program_source_example): - module = nanobind.create_bindings( - program_source_example, config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE - ) + module = nanobind.create_bindings(program_source_example, config.UNIT_STRIDE_DIMENSION) assert module.library_deps[0].name == "nanobind" diff --git a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py index ba83a07b2d..4eb718b23a 100644 --- a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py +++ b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py @@ -92,6 +92,6 @@ def extension_source_example(program_source_example): return artifacts.ExtensionSource( program_source=program_source_example, binding_source=nanobind.create_bindings( - program_source_example, config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE + program_source_example, config.UNIT_STRIDE_DIMENSION ), ) 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 af51efc596..ccc1eac7d6 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 @@ -124,8 +124,7 @@ def test_codegen(grid_type): module = gtfn_module.translate_program_cpu(_make_compilable_program(program, offset_provider)) - assert isinstance(module, gtfn_module.GTFNProgramSource) - assert module.grid_type == grid_type + assert isinstance(module, artifacts.ProgramSource) assert module.entry_point.name == program.id assert any(d.name == "gridtools_cpu" for d in module.library_deps) assert isinstance(module.code_spec, artifacts.CPPCodeSpec) 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 990870bcd1..eb1220b570 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 @@ -109,7 +109,7 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: dace_wf_factory.DaCeConfig( gpu=on_gpu, auto_optimize=auto_optimize, - unstructured_horizontal_has_unit_stride=on_gpu, + unit_stride_dimension=(gtx.common.DimensionKind.HORIZONTAL if on_gpu else None), ), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -136,9 +136,13 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: mock_auto_optimize.assert_called_once_with( sdfg, gpu=on_gpu, - # `testee` is a cartesian program: the horizontal strides are not set - # to 1, although `unstructured_horizontal_has_unit_stride` is enabled. - constant_symbols={}, + # `testee` is a cartesian program, but its fields have a single + # horizontal dimension, so the unit-stride assumption applies. + constant_symbols={ + "__a_IDim_stride": 1, + "__b_IDim_stride": 1, + "__out_IDim_stride": 1, + }, transient_memory_mode=optimization_args["transient_memory_mode"], gpu_block_size=optimization_args["gpu_block_size"], gpu_block_size_2d=optimization_args["gpu_block_size_2d"], @@ -318,14 +322,15 @@ def test_make_dace_backend_is_deprecated(): async_sdfg_call=False, optimization_args={"blocking_size": 10}, external_workspace=workspace, - unstructured_horizontal_has_unit_stride=True, + unit_stride_dimension=gtx.common.DimensionKind.HORIZONTAL, 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 + external_workspace=workspace, + unit_stride_dimension=gtx.common.DimensionKind.HORIZONTAL, ), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -356,7 +361,7 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): auto_optimize=False, auto_optimize_args={"gpu": True}, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=False, + unit_stride_dimension=None, use_metrics=False, ) translator = dace_wf_backend.run_dace_cpu.executor.translation.step 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 07c56ea41f..1a665f3f50 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 @@ -72,7 +72,7 @@ def _translate_gtir_to_sdfg( auto_optimize=auto_optimize, auto_optimize_args=None, async_sdfg_call=async_sdfg_call, - unstructured_horizontal_has_unit_stride=False, + unit_stride_dimension=None, use_metrics=use_metrics, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -102,9 +102,11 @@ def _make_unstructured_program(program_id: str) -> itir.Program: ) -@pytest.mark.parametrize("has_unit_stride", [False, True]) +@pytest.mark.parametrize( + "unit_stride_dimension", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] +) @pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols(has_unit_stride, disable_field_origin): +def test_find_constant_symbols(unit_stride_dimension, disable_field_origin): """Unit stride must only be set on the horizontal dimension, not on the vertical one.""" SKIP_VALUE_MESH = skip_value_mesh(None) ir = _make_unstructured_program("find_constant_symbols_sdfg") @@ -122,11 +124,11 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): sdfg=sdfg, offset_provider_type=SKIP_VALUE_MESH.offset_provider_type, disable_field_origin_on_program_arguments=disable_field_origin, - unstructured_horizontal_has_unit_stride=has_unit_stride, + unit_stride_dimension=unit_stride_dimension, ) expected = {} - if has_unit_stride: + if unit_stride_dimension is not None: # The vertical dimension stride symbols must not be set to 1. expected |= { "__x_Edge_stride": 1, @@ -164,25 +166,47 @@ def _make_cartesian_program(program_id: str) -> itir.Program: @pytest.mark.parametrize( - "grid_type", [gtx_common.GridType.CARTESIAN, gtx_common.GridType.UNSTRUCTURED] + "grid_type, unit_stride_dimension, expected_horizontal_unit_stride", + [ + (gtx_common.GridType.UNSTRUCTURED, gtx_common.DimensionKind.HORIZONTAL, True), + (gtx_common.GridType.UNSTRUCTURED, None, False), + # cartesian: unit stride on the configured dimension only + (gtx_common.GridType.CARTESIAN, IDim, True), + (gtx_common.GridType.CARTESIAN, None, False), + ], ) -def test_translation_grid_type(grid_type): - """The emitted SDFG has unit stride on the horizontal dimension only for unstructured programs.""" +def test_translation_unit_strides( + grid_type, unit_stride_dimension, expected_horizontal_unit_stride +): + """The emitted SDFG has unit stride on the dimensions configured in the translator.""" if grid_type == gtx_common.GridType.UNSTRUCTURED: - ir = _make_unstructured_program("translation_grid_type_unstructured") + ir = _make_unstructured_program("translation_unit_strides_unstructured") offset_provider = skip_value_mesh(None).offset_provider - expected_strides = { - "x": ("1", "__x_KDim_stride"), - "y": ("1", "__y_KDim_stride"), - "gt_conn_V2E": ("1", "__gt_conn_V2E_neighbor_stride"), - } + if expected_horizontal_unit_stride: + expected_strides = { + "x": ("1", "__x_KDim_stride"), + "y": ("1", "__y_KDim_stride"), + "gt_conn_V2E": ("1", "__gt_conn_V2E_neighbor_stride"), + } + else: + expected_strides = { + "x": ("__x_Edge_stride", "__x_KDim_stride"), + "y": ("__y_Vertex_stride", "__y_KDim_stride"), + "gt_conn_V2E": ("__gt_conn_V2E_source_stride", "__gt_conn_V2E_neighbor_stride"), + } else: - ir = _make_cartesian_program("translation_grid_type_cartesian") + ir = _make_cartesian_program("translation_unit_strides_cartesian") offset_provider = {} - expected_strides = { - "x": ("__x_IDim_stride", "__x_JDim_stride"), - "y": ("__y_IDim_stride", "__y_JDim_stride"), - } + if expected_horizontal_unit_stride: + expected_strides = { + "x": ("1", "__x_JDim_stride"), + "y": ("1", "__y_JDim_stride"), + } + else: + expected_strides = { + "x": ("__x_IDim_stride", "__x_JDim_stride"), + "y": ("__y_IDim_stride", "__y_JDim_stride"), + } compilable_program = otf_workflow.ConcreteArtifact( data=ir, @@ -199,7 +223,7 @@ def test_translation_grid_type(grid_type): auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=True, + unit_stride_dimension=unit_stride_dimension, use_metrics=False, ) @@ -214,9 +238,40 @@ def test_translation_grid_type(grid_type): assert strides == expected_strides -@pytest.mark.parametrize("has_unit_stride", [False, True]) +def test_translation_unit_strides_invalid_assumption(): + """A cartesian program with two horizontal dimensions per field cannot assume + unit stride for all horizontal dimensions.""" + ir = _make_cartesian_program("translation_unit_strides_invalid") + offset_provider = {} + + compilable_program = otf_workflow.ConcreteArtifact( + data=ir, + args=otf_arguments.CompileTimeArgs( + args=tuple(param.type for param in ir.params), + kwargs={}, + offset_provider=offset_provider, + column_axis=None, + argument_descriptor_contexts={}, + ), + ) + translator = dace_wf_translation.DaCeTranslator( + device_type=core_defs.DeviceType.CPU, + auto_optimize=False, + auto_optimize_args=None, + async_sdfg_call=False, + unit_stride_dimension=gtx_common.DimensionKind.HORIZONTAL, + use_metrics=False, + ) + + with pytest.raises(ValueError, match="more than one dimension with unit stride"): + translator(compilable_program) + + +@pytest.mark.parametrize( + "unit_stride_dimension", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] +) @pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin): +def test_find_constant_symbols_tuple_args(unit_stride_dimension, disable_field_origin): """Fields nested in tuple arguments, both inputs and targets, are also considered.""" vftype = ts.FieldType(dims=[Vertex], dtype=FLOAT_TYPE) domain = im.get_field_domain( @@ -251,7 +306,7 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=has_unit_stride, + unit_stride_dimension=unit_stride_dimension, use_metrics=False, disable_field_origin_on_program_arguments=disable_field_origin, ).generate_sdfg(ir, offset_provider={}, column_axis=None) @@ -261,12 +316,12 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) sdfg=sdfg, offset_provider_type={}, disable_field_origin_on_program_arguments=disable_field_origin, - unstructured_horizontal_has_unit_stride=has_unit_stride, + unit_stride_dimension=unit_stride_dimension, ) field_names = ["x_0", "y_0", "y_1_0", "y_1_1"] expected = {} - if has_unit_stride: + if unit_stride_dimension is not None: expected |= {f"__{name}_Vertex_stride": 1 for name in field_names} if disable_field_origin: expected |= {f"__{name}_Vertex_range_0": 0 for name in field_names} @@ -274,7 +329,7 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) # check that the symbols have been replaced in the translated SDFG for name in field_names: - expected_stride = "1" if has_unit_stride else f"__{name}_Vertex_stride" + expected_stride = "1" if unit_stride_dimension is not None else f"__{name}_Vertex_stride" assert [str(stride) for stride in sdfg.arrays[name].strides] == [expected_stride] @@ -676,7 +731,7 @@ def test_translation_source_code_invariant_under_guid_change(): auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=False, + unit_stride_dimension=None, use_metrics=False, ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py index 4da343b7e5..af2dfb4828 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py @@ -75,7 +75,7 @@ def translate(program, enabled, **extra_options): auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": enabled, **extra_options}, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=False, + unit_stride_dimension=None, use_metrics=False, ) return translator.generate_sdfg(program, offset_provider={}, column_axis=K) @@ -227,7 +227,7 @@ def test_compiled_staggered_scan_fusion(tmp_path, input_dim, forward, mixed, lev auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True}, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=False, + unit_stride_dimension=None, use_metrics=False, ).generate_sdfg(program, offset_provider={}, column_axis=scan_dim) graph.validate() @@ -586,7 +586,7 @@ def test_invalid_scan_fusion_scope_is_rejected(): auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True, "scan_fusion_scope": "field_operators"}, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=False, + unit_stride_dimension=None, use_metrics=False, ) 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 b93f637cb0..a2d36e27a3 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 @@ -27,7 +27,7 @@ import gt4py._core.definitions as core_defs import gt4py.next as gtx -from gt4py.next import common, config, custom_layout_allocators +from gt4py.next import config, custom_layout_allocators from gt4py.next.otf import artifacts, workflow from gt4py.next.otf.binding import interface from gt4py.next.otf.compilation import build_data, cache, compiler, importer @@ -213,32 +213,34 @@ def test_compile_workflow_without_config_caches_translation(): @pytest.mark.parametrize( - "grid_type, dims, has_unit_stride, expected_stride_spec", + "dims, unit_stride_dimension, expected_stride_spec", [ # unstructured: unit stride on the horizontal dimension only, not on the vertical one ( - common.GridType.UNSTRUCTURED, [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], - True, + gtx.DimensionKind.HORIZONTAL, f"1, {_DYN}", ), ( - common.GridType.UNSTRUCTURED, [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], - False, + None, f"{_DYN}, {_DYN}", ), - # cartesian: never unit stride, although both dimensions are horizontal + # cartesian: unit stride on the configured dimension only ( - common.GridType.CARTESIAN, [gtx.Dimension("I"), gtx.Dimension("J")], - True, + gtx.Dimension("I"), + f"1, {_DYN}", + ), + ( + [gtx.Dimension("I"), gtx.Dimension("J")], + None, f"{_DYN}, {_DYN}", ), ], ) -def test_bindings_static_strides(grid_type, dims, has_unit_stride, expected_stride_spec): - program_source = gtfn_module.GTFNProgramSource( +def test_bindings_static_strides(dims, unit_stride_dimension, expected_stride_spec): + program_source = artifacts.ProgramSource( entry_point=interface.Function( "stencil", parameters=( @@ -251,11 +253,8 @@ def test_bindings_static_strides(grid_type, dims, has_unit_stride, expected_stri source_code="", library_deps=(), code_spec=artifacts.CPPCodeSpec(), - grid_type=grid_type, - ) - bindings = gtfn.make_gtfn_bindings( - gtfn.GTFNConfig(unstructured_horizontal_has_unit_stride=has_unit_stride) ) + bindings = gtfn.make_gtfn_bindings(gtfn.GTFNConfig(unit_stride_dimension=unit_stride_dimension)) extension = bindings(program_source) @@ -264,3 +263,28 @@ def test_bindings_static_strides(grid_type, dims, has_unit_stride, expected_stri f"gridtools::nanobind::stride_spec<{expected_stride_spec}>{{}}" in extension.binding_source.source_code ) + + +def test_bindings_static_strides_invalid_assumption(): + """A field cannot have more than one dimension with unit stride.""" + dims = [gtx.Dimension("I"), gtx.Dimension("J")] + program_source = artifacts.ProgramSource( + entry_point=interface.Function( + "stencil", + parameters=( + interface.Parameter( + name="buf", + type_=ts.FieldType(dims=dims, dtype=ts.ScalarType(ts.ScalarKind.FLOAT64)), + ), + ), + ), + source_code="", + library_deps=(), + code_spec=artifacts.CPPCodeSpec(), + ) + bindings = gtfn.make_gtfn_bindings( + gtfn.GTFNConfig(unit_stride_dimension=gtx.DimensionKind.HORIZONTAL) + ) + + with pytest.raises(ValueError, match="more than one dimension with unit stride"): + bindings(program_source) From 5873f10557bb4e2ff5bd4dda70e37035eb42cd7b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 11:40:16 +0100 Subject: [PATCH 10/28] feat[next]: configure the DaCe auto-optimize pipeline with the unit-stride 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. --- src/gt4py/next/backend.py | 7 +- src/gt4py/next/common.py | 27 ++-- src/gt4py/next/config.py | 2 +- src/gt4py/next/otf/binding/nanobind.py | 16 +- .../dace/transformations/auto_optimize.py | 114 ++++++++----- .../runners/dace/transformations/strides.py | 152 +++++++++++++++++- .../runners/dace/workflow/translation.py | 45 +++--- .../dace_tests/test_dace_backend.py | 4 +- .../dace_tests/test_dace_translation.py | 31 +++- .../test_change_strides.py | 134 +++++++++++++++ .../runners_tests/test_gtfn.py | 32 +--- tests/next_tests/unit_tests/test_common.py | 26 +++ 12 files changed, 462 insertions(+), 128 deletions(-) create mode 100644 tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 0ad9230c84..1436113af4 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -257,9 +257,10 @@ class ToolchainConfig: default_factory=lambda: config.BUILD_CACHE_LIFETIME ) #: Dimension or dimension kind that is assumed to have unit stride in the - #: memory layout of the field arguments, see `common.has_unit_stride()`. - #: E.g. `DimensionKind.HORIZONTAL` for an unstructured mesh, or a single - #: dimension like `IDim` on a cartesian grid; `None` disables the assumption. + #: memory layout of the field arguments, see + #: `common.resolve_unit_stride_dimension()`. E.g. `DimensionKind.HORIZONTAL` + #: for an unstructured mesh, or a single dimension like `IDim` on a + #: cartesian grid; `None` disables the assumption. unit_stride_dimension: common.UnitStrideDimension = dataclasses.field( default_factory=lambda: config.UNIT_STRIDE_DIMENSION ) diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index 37784e2098..89965d734b 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -136,25 +136,34 @@ def __ne__(self, value: Dimension | core_defs.IntegralScalar) -> bool | Domain: UnitStrideDimension: TypeAlias = Dimension | DimensionKind | None -def has_unit_stride(dim: Dimension, unit_stride_dimension: UnitStrideDimension, /) -> bool: +def resolve_unit_stride_dimension( + dims: Iterable[Dimension], unit_stride_dimension: UnitStrideDimension, / +) -> Optional[Dimension]: """ - Check if a dimension is covered by a unit-stride assumption. + Resolve the dimension of a field that is assumed to have unit stride. + + A `Dimension` argument selects exactly this dimension, while a + `DimensionKind` argument selects the first dimension of that kind in + `dims`: in a field with several dimensions of the same kind, e.g. a + cartesian ``IJ`` field, only the leading one can have unit stride. This + is also the memory layout the standard GT4Py allocators produce. `None` + disables the assumption. Args: - dim: The dimension to check. - unit_stride_dimension: A `Dimension` matched by value and kind, or a - `DimensionKind` matched against the kind of `dim`, or `None`. + dims: The dimensions of a field, in the order given by its type. + unit_stride_dimension: The configured unit-stride assumption. Returns: - Whether `dim` is assumed to have unit stride. + The dimension assumed to have unit stride, or `None` if the + assumption does not apply to `dims`. """ match unit_stride_dimension: case DimensionKind() as kind: - return dim.kind == kind + return next((dim for dim in dims if dim.kind == kind), None) case Dimension(): - return dim == unit_stride_dimension + return unit_stride_dimension if unit_stride_dimension in dims else None case None: - return False + return None if TYPE_CHECKING: diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index 5ecdd42dee..8d14ed9360 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -146,7 +146,7 @@ def _get_build_cache_version_id() -> str: #: Dimension or dimension kind that compiled toolchains may assume to have #: unit stride in the memory layout of the field arguments, see -#: `common.has_unit_stride()`. `None` disables the assumption. +#: `common.resolve_unit_stride_dimension()`. `None` disables the assumption. UNIT_STRIDE_DIMENSION: common.UnitStrideDimension = None diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index 7aea71e772..57aa6b6809 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -207,22 +207,13 @@ def make_argument( name: str, type_: ts.TypeSpec, unit_stride_dimension: common.UnitStrideDimension ) -> str | BufferSID | Tuple: if isinstance(type_, ts.FieldType): - unit_stride_dims = [ - dim for dim in type_.dims if common.has_unit_stride(dim, unit_stride_dimension) - ] - if len(unit_stride_dims) > 1: - raise ValueError( - f"Invalid unit-stride assumption: field '{name}' with dimensions " - f"'{type_.dims}' has more than one dimension with unit stride " - f"('{unit_stride_dimension}'). Configure a single dimension instead of a " - "dimension kind." - ) + unit_stride_dim = common.resolve_unit_stride_dimension(type_.dims, unit_stride_dimension) return BufferSID( source_buffer=name, dimensions=[ DimensionSpec( name=dim.value, - static_stride=1 if dim in unit_stride_dims else None, + static_stride=1 if dim == unit_stride_dim else None, ) for dim in type_.dims ], @@ -253,7 +244,8 @@ def create_bindings( The program source for which the bindings are created unit_stride_dimension Dimension or dimension kind that is assumed to have unit stride in the - memory layout of the field arguments, see `common.has_unit_stride()`. + memory layout of the field arguments, see + `common.resolve_unit_stride_dimension()`. """ if not isinstance(program_source.code_spec, artifacts.CPPLikeCodeSpec): raise ValueError( diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py b/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py index 0ac28e96cc..b504f894ea 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py @@ -147,6 +147,7 @@ def gt_auto_optimize( sdfg: dace.SDFG, gpu: bool, unit_strides_kind: Optional[gtx_common.DimensionKind] = None, + unit_strides_dimension: Optional[gtx_common.UnitStrideDimension] = None, transient_memory_mode: TransientMemoryMode = TransientMemoryMode.POOL, gpu_block_size: Optional[Sequence[int | str] | str] = (32, 8, 1), gpu_block_size_1d: Optional[Sequence[int | str] | str] = (64, 1, 1), @@ -210,7 +211,14 @@ def gt_auto_optimize( sdfg: The SDFG that should be optimized in place. gpu: Optimize for GPU or CPU. unit_strides_kind: All dimensions of this kind are considered to have unit - strides, see `gt_set_iteration_order()` for more. + strides, see `gt_set_iteration_order()` for more. Mutually exclusive + with `unit_strides_dimension`. + unit_strides_dimension: The dimension(s) that have unit stride: a GT4Py + `Dimension`, which is used to set the Map order and the strides of the + transients such that this dimension is the fastest varying one, see + `gt_set_iteration_order()` and `gt_change_strides()`; or a + `DimensionKind`, which behaves like `unit_strides_kind`. Mutually + exclusive with `unit_strides_kind`. transient_memory_mode: Lifetime for transient arrays. gpu_block_size: This is used as default thread block size for GPU Maps. See also the `gpu_block_size_*d` arguments @@ -286,6 +294,9 @@ def gt_auto_optimize( device = dace.DeviceType.GPU if gpu else dace.DeviceType.CPU optimization_hooks = optimization_hooks or {} + if unit_strides_kind is not None and unit_strides_dimension is not None: + raise ValueError("Specified both 'unit_strides_kind' and 'unit_strides_dimension'.") + with dace.config.temporary_config(): # Do not store which transformations were applied inside the SDFG. dace.Config.set("store_history", value=False) @@ -441,6 +452,7 @@ def gt_auto_optimize( sdfg=sdfg, gpu=gpu, unit_strides_kind=unit_strides_kind, + unit_strides_dimension=unit_strides_dimension, gpu_block_size=gpu_block_size, gpu_launch_factor=gpu_launch_factor, gpu_launch_bounds=gpu_launch_bounds, @@ -923,6 +935,7 @@ def _gt_auto_configure_maps_and_strides( sdfg: dace.SDFG, gpu: bool, unit_strides_kind: Optional[gtx_common.DimensionKind], + unit_strides_dimension: Optional[gtx_common.UnitStrideDimension], gpu_block_size: Optional[Sequence[int | str] | str], gpu_launch_bounds: Optional[int | str], gpu_launch_factor: Optional[int], @@ -942,53 +955,70 @@ def _gt_auto_configure_maps_and_strides( For a description of the arguments see the `gt_auto_optimize()` function. """ - # If `unit_strides_kind` is unknown we will not modify the Map order nor the - # strides, except if we are on GPU. The reason for this is that the maximal - # number of blocks is different for each dimension. If the largest dimension - # is for example associated with the `z` dimension, we would get launch errors - # at some point. Thus in that case we pretend that it is horizontal. Which is - # a valid assumption for any ICON-like code or if the GT4Py allocator is used. - # TODO(phimuell): Make this selection more intelligent. - if unit_strides_kind is None and gpu: - prefered_direction_kind: Optional[gtx_common.DimensionKind] = ( - gtx_common.DimensionKind.HORIZONTAL - ) - else: - prefered_direction_kind = unit_strides_kind - - # We should actually use a `gtx.Dimension` here and not a `gtx.DimensionKind`, - # since they are unique. However at this stage, especially after the expansion - # of non standard Memlets (which happens in the GPU transformation) associating - # Map parameters with GT4Py dimension is very hard to impossible. At this stage - # the kind is the most reliable indicator we have. - # NOTE: This is not the only location where we manipulate the Map order, we also - # do it in the GPU transformation, where we have to set the order of the - # expanded Memlets. - if prefered_direction_kind is not None: - gtx_transformations.gt_set_iteration_order( - sdfg=sdfg, - unit_strides_kind=prefered_direction_kind, - validate=False, - validate_all=validate_all, - ) + match unit_strides_dimension: + case gtx_common.Dimension(): + # The concrete unit-stride dimension is known, so the Map order and the + # strides can be set based on it, without relying on dimension kinds. + gtx_transformations.gt_set_iteration_order( + sdfg=sdfg, + unit_strides_dim=unit_strides_dimension, + validate=False, + validate_all=validate_all, + ) + gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=unit_strides_dimension) + prefered_direction_kind: Optional[gtx_common.DimensionKind] = ( + unit_strides_dimension.kind + ) + case _: + # If `unit_strides_kind` is unknown we will not modify the Map order nor the + # strides, except if we are on GPU. The reason for this is that the maximal + # number of blocks is different for each dimension. If the largest dimension + # is for example associated with the `z` dimension, we would get launch errors + # at some point. Thus in that case we pretend that it is horizontal. Which is + # a valid assumption for any ICON-like code or if the GT4Py allocator is used. + # TODO(phimuell): Make this selection more intelligent. + kind: Optional[gtx_common.DimensionKind] = unit_strides_kind + if kind is None and isinstance(unit_strides_dimension, gtx_common.DimensionKind): + kind = unit_strides_dimension + if kind is None and gpu: + kind = gtx_common.DimensionKind.HORIZONTAL + prefered_direction_kind = kind + + # We should actually use a `gtx.Dimension` here and not a `gtx.DimensionKind`, + # since they are unique. However at this stage, especially after the expansion + # of non standard Memlets (which happens in the GPU transformation) associating + # Map parameters with GT4Py dimension is very hard to impossible. At this stage + # the kind is the most reliable indicator we have. + # NOTE: This is not the only location where we manipulate the Map order, we also + # do it in the GPU transformation, where we have to set the order of the + # expanded Memlets. + if prefered_direction_kind is not None: + gtx_transformations.gt_set_iteration_order( + sdfg=sdfg, + unit_strides_kind=prefered_direction_kind, + validate=False, + validate_all=validate_all, + ) - # NOTE: We have to set the strides of transients before the non-standard Memlets - # get expanded, i.e. turned into Maps because no matching `cudaMemcpy*()` call - # exists, which requires that the final strides are there. Furthermore, Memlet - # expansion has to happen before the GPU block size is set. There are several - # possible solutions for that, of which none is really good. The least bad one - # is to set the strides of the transients here. The main downside is that we - # slightly modify the SDFG in the GPU transformation after we have set the - # strides. - if prefered_direction_kind is not None: - gtx_transformations.gt_change_strides(sdfg, prefered_direction_kind=prefered_direction_kind) + # NOTE: We have to set the strides of transients before the non-standard Memlets + # get expanded, i.e. turned into Maps because no matching `cudaMemcpy*()` call + # exists, which requires that the final strides are there. Furthermore, Memlet + # expansion has to happen before the GPU block size is set. There are several + # possible solutions for that, of which none is really good. The least bad one + # is to set the strides of the transients here. The main downside is that we + # slightly modify the SDFG in the GPU transformation after we have set the + # strides. + if prefered_direction_kind is not None: + gtx_transformations.gt_change_strides( + sdfg, prefered_direction_kind=prefered_direction_kind + ) if gpu: - if unit_strides_kind != gtx_common.DimensionKind.HORIZONTAL: + if prefered_direction_kind != gtx_common.DimensionKind.HORIZONTAL: warnings.warn( "The GT4Py DaCe GPU backend assumes that the leading dimension, i.e." " where stride is 1, is of kind 'HORIZONTAL', however it was" - f" '{unit_strides_kind}'. Furthermore, it should be the last dimension." + f" '{prefered_direction_kind}'. Furthermore, it should be the last dimension." " Other configurations might lead to suboptimal performance.", stacklevel=2, ) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/strides.py b/src/gt4py/next/program_processors/runners/dace/transformations/strides.py index 0635639543..35204901dc 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/strides.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/strides.py @@ -6,6 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import warnings from typing import Optional, TypeAlias import dace @@ -34,7 +35,9 @@ def gt_change_strides( sdfg: dace.SDFG, - prefered_direction_kind: gtx_common.DimensionKind, + prefered_direction_kind: Optional[gtx_common.DimensionKind] = None, + *, + unit_strides_dim: Optional[gtx_common.Dimension] = None, ) -> dace.SDFG: """Modifies the strides of transients. @@ -47,12 +50,17 @@ def gt_change_strides( Args: sdfg: The SDFG to process. prefered_direction_kind: `DimensionKind` of the dimension with stride 1. + unit_strides_dim: The GT4Py `Dimension` with stride 1. The strides of the + transients are set such that this dimension is the fastest varying one, + determined from the access pattern of each transient, see + `_gt_set_strides_from_unit_strides_dim()`. Mutually exclusive with + `prefered_direction_kind`. Note: - This function should be run after `gt_set_iteration_order()` has been run. - Currently the function will not scan the access pattern. Instead it relies on the default behaviour of the lowering and how the GT4Py allocator works. - - The current implementation assumes that there is only one dimension of the + - The kind-based variant assumes that there is only one dimension of the given kind. """ # TODO(phimeull): Implement this function correctly, such that it decides the @@ -72,6 +80,16 @@ def gt_change_strides( # `_gt_change_strides_non_recursive_impl()` does. This is very brittle but at # this point the best thing we can do. + if (prefered_direction_kind is None) == (unit_strides_dim is None): + raise ValueError( + "Specify either 'prefered_direction_kind' or 'unit_strides_dim', not both." + ) + + if unit_strides_dim is not None: + for nsdfg in sdfg.all_sdfgs_recursive(): + _gt_change_strides_dims_impl(nsdfg, unit_strides_dim) + return sdfg + match prefered_direction_kind: case gtx_common.DimensionKind.VERTICAL: return # Nothing to do in that case. Maybe run Memlet propagation here? @@ -86,6 +104,136 @@ def gt_change_strides( ) +def _gt_find_axis_of_map_variable( + sdfg: dace.SDFG, + data_name: str, + ndim: int, + map_variable: str, +) -> Optional[int]: + """Find the array axis of `data_name` that is indexed by `map_variable`. + + The function scans all memlets that access `data_name` inside Maps and + determines, for every array axis, the Map parameter that indexes it: either + because the Memlet subset range refers to the parameter, or, if the range is + a constant expression, because the parameter is at the same positional order + (the lowering creates Maps and array axes in the same canonical order). + + Args: + sdfg: The SDFG to scan. + data_name: Name of the data container whose axes should be resolved. + ndim: Number of dimensions of `data_name`. + map_variable: The Map parameter to look for, e.g. `get_map_variable(dim)`. + + Returns: + The axis indexed by `map_variable`, or `None` if no Memlet refers to it. + If different accesses associate `map_variable` with different axes, also + `None` is returned and a warning is emitted. + """ + votes: dict[int, int] = {} + for state in sdfg.states(): + scope_dict = state.scope_dict() + for edge in state.edges(): + src_scope = scope_dict.get(edge.src) + if src_scope is None or not isinstance(src_scope, dace_nodes.MapEntry): + continue + if edge.data is None or edge.data.data != data_name: + continue + subset = edge.data.subset + if subset is None or len(subset.ranges) != ndim: + # squeezed or expanded access, does not provide axis information + continue + map_params: list[str] = src_scope.map.params + for axis, axis_range in enumerate(subset.ranges): + referenced_params = { + str(sym) + for bound in (axis_range[0], axis_range[1]) + if dace.symbolic.issymbolic(bound) + for sym in bound.free_symbols + } + if map_variable in referenced_params: + votes[axis] = votes.get(axis, 0) + 1 + elif ( + not referenced_params + and axis < len(map_params) + and map_params[axis] == map_variable + ): + # the range does not refer to a Map parameter, e.g. the full + # extent of the array axis; fall back to the positional order + votes[axis] = votes.get(axis, 0) + 1 + + if not votes: + return None + if len(votes) > 1: + warnings.warn( + f"Found inconsistent accesses of '{data_name}' for map variable '{map_variable}'" + f" (axes {sorted(votes)}), keeping the current strides.", + stacklevel=2, + ) + return None + return next(iter(votes)) + + +def _gt_change_strides_dims_impl( + sdfg: dace.SDFG, + unit_strides_dim: gtx_common.Dimension, +) -> None: + """Set the strides of the transients such that `unit_strides_dim` is the fastest varying. + + For every top level transient array the function determines the array axis that + corresponds to `unit_strides_dim` from the access pattern, see + `_gt_find_axis_of_map_variable()`, and reorders the strides such that this axis + becomes the fastest varying one, preserving the relative order of the other axes. + + Transients that are not accessed along `unit_strides_dim` are left unchanged; + if the accesses do not allow to determine the axis, the function falls back to + the kind-based heuristic of `_gt_change_strides_non_recursive_impl()` if the + dimension is horizontal. + """ + map_variable = gtx_dace_lowering.get_map_variable(unit_strides_dim) + top_level_transients_and_their_accesses = _gt_find_toplevel_data_accesses( + sdfg=sdfg, + only_transients=True, + only_arrays=True, + ) + for top_level_transient, accesses in top_level_transients_and_their_accesses.items(): + desc: dace_data.Array = sdfg.arrays[top_level_transient] + ndim = len(desc.shape) + if ndim <= 1: + continue + + stride_order: Optional[list[int]] = None + axis = _gt_find_axis_of_map_variable( + sdfg=sdfg, + data_name=top_level_transient, + ndim=ndim, + map_variable=map_variable, + ) + if axis is not None: + # layout value 0 means stride 1 (fastest varying); the other axes keep + # their relative order + stride_order = [0] * ndim + for position, other_axis in enumerate((a for a in range(ndim) if a != axis), start=1): + stride_order[other_axis] = position + elif unit_strides_dim.kind == gtx_common.DimensionKind.HORIZONTAL: + # fall back to the kind-based heuristic: reversing to Fortran order + # puts the first horizontal dimension at stride 1 + stride_order = list(range(ndim)) + + if stride_order is not None: + desc.set_strides_from_layout(*stride_order) + + processed_nsdfgs: set[dace_nodes.NestedSDFG] = set() + for state, access_node in accesses: + gt_propagate_strides_from_access_node( + sdfg=sdfg, + state=state, + outer_node=access_node, + processed_nsdfgs=processed_nsdfgs, + ) + + _gt_modify_strides_of_views_non_recursive(sdfg) + + def _gt_change_strides_non_recursive_impl( sdfg: dace.SDFG, ) -> None: 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 4e1f895ba0..d753145aca 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -54,18 +54,12 @@ def find_constant_symbols( if unit_stride_dimension is not None: # Search the stride symbols of the dimensions with unit stride for name, field_type in field_params: - unit_stride_dims = [ - dim for dim in field_type.dims if common.has_unit_stride(dim, unit_stride_dimension) - ] - if len(unit_stride_dims) > 1: - raise ValueError( - f"Invalid unit-stride assumption: field '{p.id}' with dimensions " - f"'{field_type.dims}' has more than one dimension with unit stride " - f"('{unit_stride_dimension}'). Configure a single dimension instead " - "of a dimension kind." + if ( + unit_stride_dim := common.resolve_unit_stride_dimension( + field_type.dims, unit_stride_dimension ) - for dim in unit_stride_dims: - sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, dim) + ) is not None: + sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, unit_stride_dim) constant_symbols[sdfg_stride_symbol.name] = 1 # Same for connectivity tables, for which the first dimension is always horizontal for offset, conn_type in offset_provider_type.items(): @@ -75,7 +69,12 @@ def find_constant_symbols( ): assert not sdfg.arrays[conn_id].transient assert conn_type.source_dim.kind == common.DimensionKind.HORIZONTAL - if common.has_unit_stride(conn_type.source_dim, unit_stride_dimension): + if ( + common.resolve_unit_stride_dimension( + (conn_type.source_dim,), unit_stride_dimension + ) + is not None + ): sdfg_stride_symbol = gtx_dace_args.field_stride_symbol( conn_id, conn_type.source_dim, offset_provider_type ) @@ -339,7 +338,7 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: #: The parameters of `gt_auto_optimize()` that the translation step derives from #: its own configuration, and which therefore cannot be customized. _DERIVED_OPTIMIZATION_ARGS: Final[frozenset[str]] = frozenset( - {"gpu", "constant_symbols", "unit_strides_kind"} + {"gpu", "constant_symbols", "unit_strides_kind", "unit_strides_dimension"} ) #: The accepted values of the `scan_fusion_scope` option in `auto_optimize_args`. @@ -469,24 +468,22 @@ def _generate_sdfg_without_configuring_dace( self.unit_stride_dimension, ) - # `gt_auto_optimize()` reasons in terms of dimension kinds, not dimensions: - # it can exploit the unit-stride assumption only if the assumed dimension, - # or the kind covering it, is horizontal. + # `gt_auto_optimize()` distinguishes between dimension kinds and concrete + # dimensions: forward the configured unit-stride assumption in the form + # it expects. + unit_strides_kwargs: dict[str, Any] = {} match self.unit_stride_dimension: - case ( - common.DimensionKind.HORIZONTAL - | common.Dimension(kind=common.DimensionKind.HORIZONTAL) - ): - unit_strides_kind: common.DimensionKind | None = common.DimensionKind.HORIZONTAL - case _: - unit_strides_kind = None + case common.Dimension(): + unit_strides_kwargs["unit_strides_dimension"] = self.unit_stride_dimension + case common.DimensionKind() | None as kind: + unit_strides_kwargs["unit_strides_kind"] = kind if self.auto_optimize: gtx_transformations.gt_auto_optimize( sdfg, gpu=on_gpu, constant_symbols=constant_symbols, - unit_strides_kind=unit_strides_kind, + **unit_strides_kwargs, **auto_optimize_args, ) elif on_gpu: 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 eb1220b570..0a30fc2892 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 @@ -136,8 +136,8 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: mock_auto_optimize.assert_called_once_with( sdfg, gpu=on_gpu, - # `testee` is a cartesian program, but its fields have a single - # horizontal dimension, so the unit-stride assumption applies. + # `testee` is a cartesian program; the unit-stride assumption + # applies to the leading horizontal dimension of its fields. constant_symbols={ "__a_IDim_stride": 1, "__b_IDim_stride": 1, 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 1a665f3f50..7af064d21b 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 @@ -173,6 +173,9 @@ def _make_cartesian_program(program_id: str) -> itir.Program: # cartesian: unit stride on the configured dimension only (gtx_common.GridType.CARTESIAN, IDim, True), (gtx_common.GridType.CARTESIAN, None, False), + # cartesian with several horizontal dimensions: a dimension kind applies + # to the leading dimension of that kind, as the standard allocator lays out + (gtx_common.GridType.CARTESIAN, gtx_common.DimensionKind.HORIZONTAL, True), ], ) def test_translation_unit_strides( @@ -238,10 +241,10 @@ def test_translation_unit_strides( assert strides == expected_strides -def test_translation_unit_strides_invalid_assumption(): - """A cartesian program with two horizontal dimensions per field cannot assume - unit stride for all horizontal dimensions.""" - ir = _make_cartesian_program("translation_unit_strides_invalid") +def test_translation_unit_strides_auto_optimize(): + """With auto-optimization, the Maps are ordered such that the unit-stride + dimension is associated to the innermost loop.""" + ir = _make_cartesian_program("translation_unit_strides_auto_optimize") offset_provider = {} compilable_program = otf_workflow.ConcreteArtifact( @@ -256,15 +259,27 @@ def test_translation_unit_strides_invalid_assumption(): ) translator = dace_wf_translation.DaCeTranslator( device_type=core_defs.DeviceType.CPU, - auto_optimize=False, + auto_optimize=True, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_dimension=gtx_common.DimensionKind.HORIZONTAL, + unit_stride_dimension=IDim, use_metrics=False, ) - with pytest.raises(ValueError, match="more than one dimension with unit stride"): - translator(compilable_program) + program_source = translator(compilable_program) + + sdfg = dace.SDFG.from_json(program_source.source_code) + idim_map_variable = gtx_dace_lowering.get_map_variable(IDim) + map_params = [ + map_entry.map.params + for state in sdfg.states() + for map_entry in state.nodes() + if isinstance(map_entry, dace_nodes.MapEntry) + ] + assert map_params, "expected at least one Map" + for params in map_params: + if idim_map_variable in params: + assert params[-1] == idim_map_variable @pytest.mark.parametrize( diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py new file mode 100644 index 0000000000..21676dfc4a --- /dev/null +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py @@ -0,0 +1,134 @@ +# 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 + +from __future__ import annotations + +import itertools + +import dace +import pytest + +from gt4py.next import common as gtx_common +from gt4py.next.program_processors.runners.dace import ( + lowering as gtx_dace_lowering, + transformations as gtx_transformations, +) + + +IDim = gtx_common.Dimension("IDim") +JDim = gtx_common.Dimension("JDim") +KDim = gtx_common.Dimension("KDim", kind=gtx_common.DimensionKind.VERTICAL) + +_sdfg_counter = itertools.count() + + +def _make_transient_access_sdfg( + shape: tuple[int, ...], + dims: list[gtx_common.Dimension], +) -> tuple[dace.SDFG, str]: + """Create an SDFG with a transient array accessed by a Map over `dims`. + + The Map parameters and the Memlet subsets follow the GT4Py naming + conventions, so they look like the output of the lowering. + """ + sdfg = dace.SDFG(f"change_strides_sdfg_{next(_sdfg_counter)}") + state = sdfg.add_state("state", is_start_block=True) + sdfg.add_array("tmp", shape=shape, dtype=dace.float64, transient=True) + + map_ranges = [ + (gtx_dace_lowering.get_map_variable(dim), f"0:{size}") for dim, size in zip(dims, shape) + ] + memlet_idx = ",".join(var for var, _ in map_ranges) + state.add_mapped_tasklet( + "compute", + map_ranges=map_ranges, + inputs={"__in": dace.Memlet(f"tmp[{memlet_idx}]")}, + code="__out = __in + 1", + outputs={"__out": dace.Memlet(f"tmp[{memlet_idx}]")}, + external_edges=True, + ) + sdfg.validate() + return sdfg, "tmp" + + +def _strides_of(sdfg: dace.SDFG, name: str) -> tuple[int, ...]: + return tuple(int(stride) for stride in sdfg.arrays[name].strides) + + +def test_change_strides_unit_strides_dim(): + """The axis of the given dimension becomes the fastest varying one.""" + sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5, 6), dims=[IDim, JDim, KDim]) + + gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=JDim) + + # JDim (axis 1) has stride 1, the other axes keep their relative order + assert _strides_of(sdfg, tmp) == (5, 1, 20) + sdfg.validate() + + +def test_change_strides_unit_strides_dim_not_accessed(): + """A transient that is not accessed along the given dimension keeps its strides.""" + # the Map only ranges over IDim and JDim, so KDim does not appear + sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) + strides_before = _strides_of(sdfg, tmp) + + gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=KDim) + + # KDim is vertical: without access information the strides stay unchanged + assert _strides_of(sdfg, tmp) == strides_before + sdfg.validate() + + +def test_change_strides_unit_strides_dim_horizontal_fallback(): + """A horizontal dimension falls back to the kind-based layout without access information.""" + sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) + + # no access refers to the connectivity-like dimension 'CDim' + c_dim = gtx_common.Dimension("CDim") + gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=c_dim) + + # fallback for horizontal dimensions: Fortran order, IDim is the first horizontal + assert _strides_of(sdfg, tmp) == (1, 4) + sdfg.validate() + + +def test_change_strides_prefered_direction_kind_horizontal(): + """The kind-based variant keeps its behaviour: transients are flipped to Fortran order.""" + sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5, 6), dims=[IDim, JDim, KDim]) + + gtx_transformations.gt_change_strides( + sdfg, prefered_direction_kind=gtx_common.DimensionKind.HORIZONTAL + ) + + assert _strides_of(sdfg, tmp) == (1, 4, 20) + sdfg.validate() + + +def test_change_strides_mutually_exclusive(): + sdfg, _ = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) + + with pytest.raises(ValueError, match="Specify either"): + gtx_transformations.gt_change_strides( + sdfg, + prefered_direction_kind=gtx_common.DimensionKind.HORIZONTAL, + unit_strides_dim=IDim, + ) + with pytest.raises(ValueError, match="Specify either"): + gtx_transformations.gt_change_strides(sdfg) + + +def test_gt_auto_optimize_mutually_exclusive(): + sdfg, _ = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) + + with pytest.raises(ValueError, match="Specified both"): + gtx_transformations.gt_auto_optimize( + sdfg, + gpu=False, + unit_strides_kind=gtx_common.DimensionKind.HORIZONTAL, + unit_strides_dimension=IDim, + ) 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 a2d36e27a3..a3a0f093f1 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 @@ -237,6 +237,13 @@ def test_compile_workflow_without_config_caches_translation(): None, f"{_DYN}, {_DYN}", ), + # cartesian with several horizontal dimensions: a dimension kind applies + # to the leading dimension of that kind, as the standard allocator lays out + ( + [gtx.Dimension("I"), gtx.Dimension("J")], + gtx.DimensionKind.HORIZONTAL, + f"1, {_DYN}", + ), ], ) def test_bindings_static_strides(dims, unit_stride_dimension, expected_stride_spec): @@ -263,28 +270,3 @@ def test_bindings_static_strides(dims, unit_stride_dimension, expected_stride_sp f"gridtools::nanobind::stride_spec<{expected_stride_spec}>{{}}" in extension.binding_source.source_code ) - - -def test_bindings_static_strides_invalid_assumption(): - """A field cannot have more than one dimension with unit stride.""" - dims = [gtx.Dimension("I"), gtx.Dimension("J")] - program_source = artifacts.ProgramSource( - entry_point=interface.Function( - "stencil", - parameters=( - interface.Parameter( - name="buf", - type_=ts.FieldType(dims=dims, dtype=ts.ScalarType(ts.ScalarKind.FLOAT64)), - ), - ), - ), - source_code="", - library_deps=(), - code_spec=artifacts.CPPCodeSpec(), - ) - bindings = gtfn.make_gtfn_bindings( - gtfn.GTFNConfig(unit_stride_dimension=gtx.DimensionKind.HORIZONTAL) - ) - - with pytest.raises(ValueError, match="more than one dimension with unit stride"): - bindings(program_source) diff --git a/tests/next_tests/unit_tests/test_common.py b/tests/next_tests/unit_tests/test_common.py index 89dfaa88cb..516a60ae97 100644 --- a/tests/next_tests/unit_tests/test_common.py +++ b/tests/next_tests/unit_tests/test_common.py @@ -633,6 +633,32 @@ def test_dimension_promotion_repeated_calls(): common.check_dims([K, I]) +@pytest.mark.parametrize( + "dims, unit_stride_dimension, expected", + [ + # a dimension kind applies to the leading dimension of that kind + ((Dimension("I"), Dimension("J")), DimensionKind.HORIZONTAL, Dimension("I")), + ( + (Dimension("K", kind=DimensionKind.VERTICAL), Dimension("J")), + DimensionKind.HORIZONTAL, + Dimension("J"), + ), + ((Dimension("K", kind=DimensionKind.VERTICAL),), DimensionKind.HORIZONTAL, None), + # a dimension applies only if the field actually has it + ((Dimension("I"), Dimension("J")), Dimension("I"), Dimension("I")), + ((Dimension("I"), Dimension("J")), Dimension("K"), None), + # no assumption + ((Dimension("I"),), None, None), + ], +) +def test_resolve_unit_stride_dimension( + dims: tuple[Dimension, ...], + unit_stride_dimension: common.UnitStrideDimension, + expected: Optional[Dimension], +): + assert common.resolve_unit_stride_dimension(dims, unit_stride_dimension) == expected + + def _read_only(array): array = array.copy() array.flags.writeable = False From 2271f9c5366fd63212818d4fac5c15731846fc59 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 12:00:21 +0100 Subject: [PATCH 11/28] test[next]: configure the unit-stride assumption with JDim in the dace 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`. --- .../runners/dace/workflow/translation.py | 7 +++-- .../dace_tests/test_dace_backend.py | 28 +++++++++++-------- 2 files changed, 22 insertions(+), 13 deletions(-) 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 d753145aca..21d51aa1f9 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -470,8 +470,11 @@ def _generate_sdfg_without_configuring_dace( # `gt_auto_optimize()` distinguishes between dimension kinds and concrete # dimensions: forward the configured unit-stride assumption in the form - # it expects. - unit_strides_kwargs: dict[str, Any] = {} + # it expects, and explicitly disable the other one. + unit_strides_kwargs: dict[str, Any] = { + "unit_strides_kind": None, + "unit_strides_dimension": None, + } match self.unit_stride_dimension: case common.Dimension(): unit_strides_kwargs["unit_strides_dimension"] = self.unit_stride_dimension 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 0a30fc2892..00f3ebf3ae 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 @@ -36,7 +36,7 @@ ) from next_tests.integration_tests import cases, cases_utils -from next_tests.integration_tests.cases_utils import KDim +from next_tests.integration_tests.cases_utils import JDim, KDim @pytest.fixture( @@ -55,11 +55,11 @@ def test_make_backend(auto_optimize, device_type, monkeypatch): on_gpu = device_type == core_defs.CUPY_DEVICE_TYPE @gtx.field_operator - def testee_op(a: cases.IField, b: cases.IField) -> cases.IField: + def testee_op(a: cases.IJField, b: cases.IJField) -> cases.IJField: return a + b @gtx.program - def testee(a: cases.IField, b: cases.IField, out: cases.IField): + def testee(a: cases.IJField, b: cases.IJField, out: cases.IJField): testee_op(a, b, out=out) mock_top_level_dataflow_hook1 = mock.create_autospec(gtx_transformations.GT4PyAutoOptHookStage) @@ -105,11 +105,12 @@ 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) + # the unit-stride is configured with the concrete dimension custom_backend = dace_wf_backend.make_dace_toolchain( dace_wf_factory.DaCeConfig( gpu=on_gpu, auto_optimize=auto_optimize, - unit_stride_dimension=(gtx.common.DimensionKind.HORIZONTAL if on_gpu else None), + unit_stride_dimension=JDim, ), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -131,23 +132,23 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: mock_gpu_transformation.assert_not_called() # check call to `gt_auto_optimize()` + # the configured unit-stride dimension is forwarded to `gt_auto_optimize()` if auto_optimize: if on_gpu: mock_auto_optimize.assert_called_once_with( sdfg, gpu=on_gpu, - # `testee` is a cartesian program; the unit-stride assumption - # applies to the leading horizontal dimension of its fields. constant_symbols={ - "__a_IDim_stride": 1, - "__b_IDim_stride": 1, - "__out_IDim_stride": 1, + "__a_JDim_stride": 1, + "__b_JDim_stride": 1, + "__out_JDim_stride": 1, }, transient_memory_mode=optimization_args["transient_memory_mode"], gpu_block_size=optimization_args["gpu_block_size"], gpu_block_size_2d=optimization_args["gpu_block_size_2d"], optimization_hooks=optimization_args["optimization_hooks"], - unit_strides_kind=gtx.common.DimensionKind.HORIZONTAL, + unit_strides_kind=None, + unit_strides_dimension=JDim, ) mock_top_level_dataflow_hook1.assert_called_once_with(sdfg) mock_top_level_dataflow_hook2.assert_not_called() @@ -155,12 +156,17 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: mock_auto_optimize.assert_called_once_with( sdfg, gpu=on_gpu, - constant_symbols={}, + constant_symbols={ + "__a_JDim_stride": 1, + "__b_JDim_stride": 1, + "__out_JDim_stride": 1, + }, transient_memory_mode=optimization_args["transient_memory_mode"], blocking_dim=optimization_args["blocking_dim"], blocking_size=optimization_args["blocking_size"], optimization_hooks=optimization_args["optimization_hooks"], unit_strides_kind=None, + unit_strides_dimension=JDim, ) mock_top_level_dataflow_hook1.assert_not_called() mock_top_level_dataflow_hook2.assert_called_once_with(sdfg) From e85e06f152f87d618d998c0b2345482eb5cc226a Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 13:28:08 +0100 Subject: [PATCH 12/28] refactor[next]: configure the unit-stride assumption by dimension kind 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. --- src/gt4py/next/backend.py | 12 +- src/gt4py/next/common.py | 38 ++--- src/gt4py/next/config.py | 27 +++- src/gt4py/next/otf/binding/nanobind.py | 24 +-- .../codegens/gtfn/gtfn_module.py | 13 +- .../dace/transformations/auto_optimize.py | 114 +++++-------- .../dace/transformations/map_orderer.py | 23 ++- .../runners/dace/transformations/strides.py | 152 +----------------- .../runners/dace/workflow/backend.py | 10 +- .../runners/dace/workflow/factory.py | 2 +- .../runners/dace/workflow/translation.py | 36 +---- .../next/program_processors/runners/gtfn.py | 2 +- .../otf_tests/test_gtfn_workflow.py | 14 +- .../otf_tests/binding_tests/test_nanobind.py | 2 +- .../build_systems_tests/conftest.py | 4 +- .../dace_tests/test_dace_backend.py | 31 ++-- .../dace_tests/test_dace_translation.py | 40 ++--- .../dace_tests/test_scan_fusion.py | 6 +- .../test_change_strides.py | 134 --------------- .../transformation_tests/test_map_order.py | 95 ++++++++++- .../runners_tests/test_gtfn.py | 12 +- tests/next_tests/unit_tests/test_common.py | 11 +- tests/next_tests/unit_tests/test_config.py | 24 ++- 23 files changed, 299 insertions(+), 527 deletions(-) delete mode 100644 tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 1436113af4..dc8cf02f6d 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -256,13 +256,11 @@ class ToolchainConfig: cache_lifetime: config.BuildCacheLifetime = dataclasses.field( default_factory=lambda: config.BUILD_CACHE_LIFETIME ) - #: Dimension or dimension kind that is assumed to have unit stride in the - #: memory layout of the field arguments, see - #: `common.resolve_unit_stride_dimension()`. E.g. `DimensionKind.HORIZONTAL` - #: for an unstructured mesh, or a single dimension like `IDim` on a - #: cartesian grid; `None` disables the assumption. - unit_stride_dimension: common.UnitStrideDimension = dataclasses.field( - default_factory=lambda: config.UNIT_STRIDE_DIMENSION + #: Assume unit stride in the first dimension of this kind in the memory + #: layout of the field arguments, see `common.unit_stride_dimension()`. + #: `None` disables the assumption. + unit_stride_kind: common.DimensionKind | None = dataclasses.field( + default_factory=lambda: config.UNIT_STRIDE_KIND ) @property diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index 89965d734b..864fafdea4 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -130,40 +130,28 @@ def __ne__(self, value: Dimension | core_defs.IntegralScalar) -> bool | Domain: return NotImplemented -#: A dimension or a dimension kind that a toolchain may assume to have unit -#: stride in the memory layout of the field arguments, or `None` for no -#: assumption. -UnitStrideDimension: TypeAlias = Dimension | DimensionKind | None - - -def resolve_unit_stride_dimension( - dims: Iterable[Dimension], unit_stride_dimension: UnitStrideDimension, / +def unit_stride_dimension( + dims: Iterable[Dimension], kind: Optional[DimensionKind], / ) -> Optional[Dimension]: """ - Resolve the dimension of a field that is assumed to have unit stride. + Find the dimension of a field that is assumed to have unit stride. - A `Dimension` argument selects exactly this dimension, while a - `DimensionKind` argument selects the first dimension of that kind in - `dims`: in a field with several dimensions of the same kind, e.g. a - cartesian ``IJ`` field, only the leading one can have unit stride. This - is also the memory layout the standard GT4Py allocators produce. `None` - disables the assumption. + This is the first dimension of the given kind, because within each kind the + dimensions appearing earlier in `dims` get smaller strides, see + `custom_layout_allocators.horizontal_first_layout_mapper()`. Args: dims: The dimensions of a field, in the order given by its type. - unit_stride_dimension: The configured unit-stride assumption. + kind: The dimension kind assumed to have unit stride, or `None` for no + assumption. Returns: - The dimension assumed to have unit stride, or `None` if the - assumption does not apply to `dims`. + The dimension assumed to have unit stride, or `None` if the assumption + does not apply to `dims`. """ - match unit_stride_dimension: - case DimensionKind() as kind: - return next((dim for dim in dims if dim.kind == kind), None) - case Dimension(): - return unit_stride_dimension if unit_stride_dimension in dims else None - case None: - return None + if kind is None: + return None + return next((dim for dim in dims if dim.kind == kind), None) if TYPE_CHECKING: diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index 8d14ed9360..a788de999d 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -14,11 +14,9 @@ import pathlib import sys import warnings -from typing import TYPE_CHECKING, Final +from typing import Final - -if TYPE_CHECKING: - from gt4py.next import common +from gt4py.next import common # Module-level UPPERCASE values are snapshotted and shipped verbatim to @@ -144,10 +142,23 @@ def _get_build_cache_version_id() -> str: ] -#: Dimension or dimension kind that compiled toolchains may assume to have -#: unit stride in the memory layout of the field arguments, see -#: `common.resolve_unit_stride_dimension()`. `None` disables the assumption. -UNIT_STRIDE_DIMENSION: common.UnitStrideDimension = None +def _unit_stride_kind_from_env() -> common.DimensionKind | None: + value = os.environ.get("GT4PY_UNIT_STRIDE_KIND", "none") + if value.lower() in ("", "none"): + return None + try: + return common.DimensionKind(value.lower()) + except ValueError: + raise ValueError( + f"Invalid 'GT4PY_UNIT_STRIDE_KIND' value '{value}': use 'none' or one of" + f" {[str(kind) for kind in common.DimensionKind]}." + ) from None + + +#: Experimental, use at your own risk: dimension kind for which compiled +#: toolchains assume that the first dimension of this kind has unit stride in +#: the memory layout of the field arguments. `None` disables the assumption. +UNIT_STRIDE_KIND: common.DimensionKind | None = _unit_stride_kind_from_env() #: Add GPU trace markers (NVTX, ROC-TX) to the generated code, at compile time. diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index 57aa6b6809..9c153a7e8c 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -204,10 +204,10 @@ def _tuple_get(index: int, var: str) -> str: def make_argument( - name: str, type_: ts.TypeSpec, unit_stride_dimension: common.UnitStrideDimension + name: str, type_: ts.TypeSpec, unit_stride_kind: common.DimensionKind | None ) -> str | BufferSID | Tuple: if isinstance(type_, ts.FieldType): - unit_stride_dim = common.resolve_unit_stride_dimension(type_.dims, unit_stride_dimension) + unit_stride_dim = common.unit_stride_dimension(type_.dims, unit_stride_kind) return BufferSID( source_buffer=name, dimensions=[ @@ -221,7 +221,7 @@ def make_argument( ) elif isinstance(type_, ts.TupleType): elements = [ - make_argument(_tuple_get(i, name), t, unit_stride_dimension) + make_argument(_tuple_get(i, name), t, unit_stride_kind) for i, t in enumerate(type_.types) ] return Tuple(elems=elements) @@ -233,7 +233,7 @@ def make_argument( def create_bindings( program_source: artifacts.ProgramSource[CodeSpecT], - unit_stride_dimension: common.UnitStrideDimension, + unit_stride_kind: common.DimensionKind | None, ) -> artifacts.BindingSource[CodeSpecT, artifacts.PythonCodeSpec]: """ Generate Python bindings through which a C++ function can be called. @@ -242,10 +242,10 @@ def create_bindings( ---------- program_source The program source for which the bindings are created - unit_stride_dimension - Dimension or dimension kind that is assumed to have unit stride in the - memory layout of the field arguments, see - `common.resolve_unit_stride_dimension()`. + unit_stride_kind + Dimension kind for which the first dimension is assumed to have unit + stride in the memory layout of the field arguments, see + `common.unit_stride_dimension()`. """ if not isinstance(program_source.code_spec, artifacts.CPPLikeCodeSpec): raise ValueError( @@ -283,7 +283,7 @@ def create_bindings( expr=FunctionCall( target=program_source.entry_point, args=[ - make_argument(param.name, param.type_, unit_stride_dimension) + make_argument(param.name, param.type_, unit_stride_kind) for param in program_source.entry_point.parameters ], ) @@ -319,14 +319,14 @@ class ExtensionGenerator: Generate a Python extension module that contains the bindings for a C++ function. """ - unit_stride_dimension: common.UnitStrideDimension = dataclasses.field( - default_factory=lambda: config.UNIT_STRIDE_DIMENSION + unit_stride_kind: common.DimensionKind | None = dataclasses.field( + default_factory=lambda: config.UNIT_STRIDE_KIND ) def __call__( self, program_source: artifacts.ProgramSource[CodeSpecT] ) -> artifacts.ExtensionSource[CodeSpecT, artifacts.PythonCodeSpec]: - binding_source = create_bindings(program_source, self.unit_stride_dimension) + binding_source = create_bindings(program_source, self.unit_stride_kind) return artifacts.ExtensionSource( program_source=program_source, binding_source=binding_source ) 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 e5bd424a54..f1c6978791 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -217,12 +217,15 @@ def __call__( ] ) - return artifacts.ProgramSource( - entry_point=function, - library_deps=(interface.LibraryDependency(self._library_name(), "master"),), - source_code=source_code, - code_spec=self._code_spec(), + 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: diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py b/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py index b504f894ea..0ac28e96cc 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/auto_optimize.py @@ -147,7 +147,6 @@ def gt_auto_optimize( sdfg: dace.SDFG, gpu: bool, unit_strides_kind: Optional[gtx_common.DimensionKind] = None, - unit_strides_dimension: Optional[gtx_common.UnitStrideDimension] = None, transient_memory_mode: TransientMemoryMode = TransientMemoryMode.POOL, gpu_block_size: Optional[Sequence[int | str] | str] = (32, 8, 1), gpu_block_size_1d: Optional[Sequence[int | str] | str] = (64, 1, 1), @@ -211,14 +210,7 @@ def gt_auto_optimize( sdfg: The SDFG that should be optimized in place. gpu: Optimize for GPU or CPU. unit_strides_kind: All dimensions of this kind are considered to have unit - strides, see `gt_set_iteration_order()` for more. Mutually exclusive - with `unit_strides_dimension`. - unit_strides_dimension: The dimension(s) that have unit stride: a GT4Py - `Dimension`, which is used to set the Map order and the strides of the - transients such that this dimension is the fastest varying one, see - `gt_set_iteration_order()` and `gt_change_strides()`; or a - `DimensionKind`, which behaves like `unit_strides_kind`. Mutually - exclusive with `unit_strides_kind`. + strides, see `gt_set_iteration_order()` for more. transient_memory_mode: Lifetime for transient arrays. gpu_block_size: This is used as default thread block size for GPU Maps. See also the `gpu_block_size_*d` arguments @@ -294,9 +286,6 @@ def gt_auto_optimize( device = dace.DeviceType.GPU if gpu else dace.DeviceType.CPU optimization_hooks = optimization_hooks or {} - if unit_strides_kind is not None and unit_strides_dimension is not None: - raise ValueError("Specified both 'unit_strides_kind' and 'unit_strides_dimension'.") - with dace.config.temporary_config(): # Do not store which transformations were applied inside the SDFG. dace.Config.set("store_history", value=False) @@ -452,7 +441,6 @@ def gt_auto_optimize( sdfg=sdfg, gpu=gpu, unit_strides_kind=unit_strides_kind, - unit_strides_dimension=unit_strides_dimension, gpu_block_size=gpu_block_size, gpu_launch_factor=gpu_launch_factor, gpu_launch_bounds=gpu_launch_bounds, @@ -935,7 +923,6 @@ def _gt_auto_configure_maps_and_strides( sdfg: dace.SDFG, gpu: bool, unit_strides_kind: Optional[gtx_common.DimensionKind], - unit_strides_dimension: Optional[gtx_common.UnitStrideDimension], gpu_block_size: Optional[Sequence[int | str] | str], gpu_launch_bounds: Optional[int | str], gpu_launch_factor: Optional[int], @@ -955,70 +942,53 @@ def _gt_auto_configure_maps_and_strides( For a description of the arguments see the `gt_auto_optimize()` function. """ - match unit_strides_dimension: - case gtx_common.Dimension(): - # The concrete unit-stride dimension is known, so the Map order and the - # strides can be set based on it, without relying on dimension kinds. - gtx_transformations.gt_set_iteration_order( - sdfg=sdfg, - unit_strides_dim=unit_strides_dimension, - validate=False, - validate_all=validate_all, - ) - gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=unit_strides_dimension) - prefered_direction_kind: Optional[gtx_common.DimensionKind] = ( - unit_strides_dimension.kind - ) - case _: - # If `unit_strides_kind` is unknown we will not modify the Map order nor the - # strides, except if we are on GPU. The reason for this is that the maximal - # number of blocks is different for each dimension. If the largest dimension - # is for example associated with the `z` dimension, we would get launch errors - # at some point. Thus in that case we pretend that it is horizontal. Which is - # a valid assumption for any ICON-like code or if the GT4Py allocator is used. - # TODO(phimuell): Make this selection more intelligent. - kind: Optional[gtx_common.DimensionKind] = unit_strides_kind - if kind is None and isinstance(unit_strides_dimension, gtx_common.DimensionKind): - kind = unit_strides_dimension - if kind is None and gpu: - kind = gtx_common.DimensionKind.HORIZONTAL - prefered_direction_kind = kind - - # We should actually use a `gtx.Dimension` here and not a `gtx.DimensionKind`, - # since they are unique. However at this stage, especially after the expansion - # of non standard Memlets (which happens in the GPU transformation) associating - # Map parameters with GT4Py dimension is very hard to impossible. At this stage - # the kind is the most reliable indicator we have. - # NOTE: This is not the only location where we manipulate the Map order, we also - # do it in the GPU transformation, where we have to set the order of the - # expanded Memlets. - if prefered_direction_kind is not None: - gtx_transformations.gt_set_iteration_order( - sdfg=sdfg, - unit_strides_kind=prefered_direction_kind, - validate=False, - validate_all=validate_all, - ) + # If `unit_strides_kind` is unknown we will not modify the Map order nor the + # strides, except if we are on GPU. The reason for this is that the maximal + # number of blocks is different for each dimension. If the largest dimension + # is for example associated with the `z` dimension, we would get launch errors + # at some point. Thus in that case we pretend that it is horizontal. Which is + # a valid assumption for any ICON-like code or if the GT4Py allocator is used. + # TODO(phimuell): Make this selection more intelligent. + if unit_strides_kind is None and gpu: + prefered_direction_kind: Optional[gtx_common.DimensionKind] = ( + gtx_common.DimensionKind.HORIZONTAL + ) + else: + prefered_direction_kind = unit_strides_kind + + # We should actually use a `gtx.Dimension` here and not a `gtx.DimensionKind`, + # since they are unique. However at this stage, especially after the expansion + # of non standard Memlets (which happens in the GPU transformation) associating + # Map parameters with GT4Py dimension is very hard to impossible. At this stage + # the kind is the most reliable indicator we have. + # NOTE: This is not the only location where we manipulate the Map order, we also + # do it in the GPU transformation, where we have to set the order of the + # expanded Memlets. + if prefered_direction_kind is not None: + gtx_transformations.gt_set_iteration_order( + sdfg=sdfg, + unit_strides_kind=prefered_direction_kind, + validate=False, + validate_all=validate_all, + ) - # NOTE: We have to set the strides of transients before the non-standard Memlets - # get expanded, i.e. turned into Maps because no matching `cudaMemcpy*()` call - # exists, which requires that the final strides are there. Furthermore, Memlet - # expansion has to happen before the GPU block size is set. There are several - # possible solutions for that, of which none is really good. The least bad one - # is to set the strides of the transients here. The main downside is that we - # slightly modify the SDFG in the GPU transformation after we have set the - # strides. - if prefered_direction_kind is not None: - gtx_transformations.gt_change_strides( - sdfg, prefered_direction_kind=prefered_direction_kind - ) + # NOTE: We have to set the strides of transients before the non-standard Memlets + # get expanded, i.e. turned into Maps because no matching `cudaMemcpy*()` call + # exists, which requires that the final strides are there. Furthermore, Memlet + # expansion has to happen before the GPU block size is set. There are several + # possible solutions for that, of which none is really good. The least bad one + # is to set the strides of the transients here. The main downside is that we + # slightly modify the SDFG in the GPU transformation after we have set the + # strides. + if prefered_direction_kind is not None: + gtx_transformations.gt_change_strides(sdfg, prefered_direction_kind=prefered_direction_kind) if gpu: - if prefered_direction_kind != gtx_common.DimensionKind.HORIZONTAL: + if unit_strides_kind != gtx_common.DimensionKind.HORIZONTAL: warnings.warn( "The GT4Py DaCe GPU backend assumes that the leading dimension, i.e." " where stride is 1, is of kind 'HORIZONTAL', however it was" - f" '{prefered_direction_kind}'. Furthermore, it should be the last dimension." + f" '{unit_strides_kind}'. Furthermore, it should be the last dimension." " Other configurations might lead to suboptimal performance.", stacklevel=2, ) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py b/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py index 2f56671da8..f1e414d6d3 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py @@ -77,7 +77,10 @@ class MapIterationOrder(dace_transformation.SingleStateTransformation): The second way is to specify `unit_strides_kind`, which is a GT4Py `DimensionKind` enum value. In that case the all dimensions that are associated to this kind will be ordered such that they are the inner most. If a Map has multiple - dimensions of the same kind, then their relative order is undefined. + dimensions of the same kind, then the first one, according to the canonical + order of `gtx_common.order_dimensions()`, is the inner most. This matches the + memory layout, where the first dimension of a kind has the smallest stride, + e.g. `Map[IDim, JDim, KDim]` -> `Map[KDim, JDim, IDim]` for `HORIZONTAL`. In any case the order of the non matches dimensions is unspecific. @@ -217,8 +220,22 @@ def _compute_map_param_order_unit_strides_kind(self) -> Optional[list[str]]: if not map_params_to_order: return None - # The final parameter order is that the "leading ones" are right most. - # However, their order, if there are multiple of the same kind, is unspecific. + # The final parameter order is that the "leading ones" are right most. Since + # the first dimension of a kind has the smallest stride, it must be last. The + # order must not depend on the current one, otherwise the transformation + # would not be idempotent. + # NOTE: We have to compare the dimension names, i.e. without the decoration added + # by `get_map_variable()` and `LoopBlocking`, to obtain the same order as + # `gtx_common.order_dimensions()`. + map_params_to_order.sort( + key=lambda map_param: ( + map_param.removeprefix("__gtx_coarse_") + .removeprefix("i_") + .removesuffix(kind_to_look_for) + .removesuffix("_gtx") + ), + reverse=True, + ) new_map_params: list[str] = [ map_param for map_param in map_params if map_param not in map_params_to_order ] diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/strides.py b/src/gt4py/next/program_processors/runners/dace/transformations/strides.py index 35204901dc..0635639543 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/strides.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/strides.py @@ -6,7 +6,6 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import warnings from typing import Optional, TypeAlias import dace @@ -35,9 +34,7 @@ def gt_change_strides( sdfg: dace.SDFG, - prefered_direction_kind: Optional[gtx_common.DimensionKind] = None, - *, - unit_strides_dim: Optional[gtx_common.Dimension] = None, + prefered_direction_kind: gtx_common.DimensionKind, ) -> dace.SDFG: """Modifies the strides of transients. @@ -50,17 +47,12 @@ def gt_change_strides( Args: sdfg: The SDFG to process. prefered_direction_kind: `DimensionKind` of the dimension with stride 1. - unit_strides_dim: The GT4Py `Dimension` with stride 1. The strides of the - transients are set such that this dimension is the fastest varying one, - determined from the access pattern of each transient, see - `_gt_set_strides_from_unit_strides_dim()`. Mutually exclusive with - `prefered_direction_kind`. Note: - This function should be run after `gt_set_iteration_order()` has been run. - Currently the function will not scan the access pattern. Instead it relies on the default behaviour of the lowering and how the GT4Py allocator works. - - The kind-based variant assumes that there is only one dimension of the + - The current implementation assumes that there is only one dimension of the given kind. """ # TODO(phimeull): Implement this function correctly, such that it decides the @@ -80,16 +72,6 @@ def gt_change_strides( # `_gt_change_strides_non_recursive_impl()` does. This is very brittle but at # this point the best thing we can do. - if (prefered_direction_kind is None) == (unit_strides_dim is None): - raise ValueError( - "Specify either 'prefered_direction_kind' or 'unit_strides_dim', not both." - ) - - if unit_strides_dim is not None: - for nsdfg in sdfg.all_sdfgs_recursive(): - _gt_change_strides_dims_impl(nsdfg, unit_strides_dim) - return sdfg - match prefered_direction_kind: case gtx_common.DimensionKind.VERTICAL: return # Nothing to do in that case. Maybe run Memlet propagation here? @@ -104,136 +86,6 @@ def gt_change_strides( ) -def _gt_find_axis_of_map_variable( - sdfg: dace.SDFG, - data_name: str, - ndim: int, - map_variable: str, -) -> Optional[int]: - """Find the array axis of `data_name` that is indexed by `map_variable`. - - The function scans all memlets that access `data_name` inside Maps and - determines, for every array axis, the Map parameter that indexes it: either - because the Memlet subset range refers to the parameter, or, if the range is - a constant expression, because the parameter is at the same positional order - (the lowering creates Maps and array axes in the same canonical order). - - Args: - sdfg: The SDFG to scan. - data_name: Name of the data container whose axes should be resolved. - ndim: Number of dimensions of `data_name`. - map_variable: The Map parameter to look for, e.g. `get_map_variable(dim)`. - - Returns: - The axis indexed by `map_variable`, or `None` if no Memlet refers to it. - If different accesses associate `map_variable` with different axes, also - `None` is returned and a warning is emitted. - """ - votes: dict[int, int] = {} - for state in sdfg.states(): - scope_dict = state.scope_dict() - for edge in state.edges(): - src_scope = scope_dict.get(edge.src) - if src_scope is None or not isinstance(src_scope, dace_nodes.MapEntry): - continue - if edge.data is None or edge.data.data != data_name: - continue - subset = edge.data.subset - if subset is None or len(subset.ranges) != ndim: - # squeezed or expanded access, does not provide axis information - continue - map_params: list[str] = src_scope.map.params - for axis, axis_range in enumerate(subset.ranges): - referenced_params = { - str(sym) - for bound in (axis_range[0], axis_range[1]) - if dace.symbolic.issymbolic(bound) - for sym in bound.free_symbols - } - if map_variable in referenced_params: - votes[axis] = votes.get(axis, 0) + 1 - elif ( - not referenced_params - and axis < len(map_params) - and map_params[axis] == map_variable - ): - # the range does not refer to a Map parameter, e.g. the full - # extent of the array axis; fall back to the positional order - votes[axis] = votes.get(axis, 0) + 1 - - if not votes: - return None - if len(votes) > 1: - warnings.warn( - f"Found inconsistent accesses of '{data_name}' for map variable '{map_variable}'" - f" (axes {sorted(votes)}), keeping the current strides.", - stacklevel=2, - ) - return None - return next(iter(votes)) - - -def _gt_change_strides_dims_impl( - sdfg: dace.SDFG, - unit_strides_dim: gtx_common.Dimension, -) -> None: - """Set the strides of the transients such that `unit_strides_dim` is the fastest varying. - - For every top level transient array the function determines the array axis that - corresponds to `unit_strides_dim` from the access pattern, see - `_gt_find_axis_of_map_variable()`, and reorders the strides such that this axis - becomes the fastest varying one, preserving the relative order of the other axes. - - Transients that are not accessed along `unit_strides_dim` are left unchanged; - if the accesses do not allow to determine the axis, the function falls back to - the kind-based heuristic of `_gt_change_strides_non_recursive_impl()` if the - dimension is horizontal. - """ - map_variable = gtx_dace_lowering.get_map_variable(unit_strides_dim) - top_level_transients_and_their_accesses = _gt_find_toplevel_data_accesses( - sdfg=sdfg, - only_transients=True, - only_arrays=True, - ) - for top_level_transient, accesses in top_level_transients_and_their_accesses.items(): - desc: dace_data.Array = sdfg.arrays[top_level_transient] - ndim = len(desc.shape) - if ndim <= 1: - continue - - stride_order: Optional[list[int]] = None - axis = _gt_find_axis_of_map_variable( - sdfg=sdfg, - data_name=top_level_transient, - ndim=ndim, - map_variable=map_variable, - ) - if axis is not None: - # layout value 0 means stride 1 (fastest varying); the other axes keep - # their relative order - stride_order = [0] * ndim - for position, other_axis in enumerate((a for a in range(ndim) if a != axis), start=1): - stride_order[other_axis] = position - elif unit_strides_dim.kind == gtx_common.DimensionKind.HORIZONTAL: - # fall back to the kind-based heuristic: reversing to Fortran order - # puts the first horizontal dimension at stride 1 - stride_order = list(range(ndim)) - - if stride_order is not None: - desc.set_strides_from_layout(*stride_order) - - processed_nsdfgs: set[dace_nodes.NestedSDFG] = set() - for state, access_node in accesses: - gt_propagate_strides_from_access_node( - sdfg=sdfg, - state=state, - outer_node=access_node, - processed_nsdfgs=processed_nsdfgs, - ) - - _gt_modify_strides_of_views_non_recursive(sdfg) - - def _gt_change_strides_non_recursive_impl( sdfg: dace.SDFG, ) -> None: 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 696b4c314f..120e77fbee 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -80,7 +80,7 @@ def make_dace_backend( async_sdfg_call: bool = True, optimization_args: dict[str, Any] | None = None, external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None, - unit_stride_dimension: common.UnitStrideDimension = config.UNIT_STRIDE_DIMENSION, + unit_stride_kind: common.DimensionKind | None = config.UNIT_STRIDE_KIND, use_metrics: bool = True, use_zero_origin: bool = False, use_max_domain_range_on_unstructured_shift: bool | None = None, @@ -102,9 +102,9 @@ def make_dace_backend( accepts the scan-fusion options `fuse_scan_inputs` and `scan_fusion_scope`. external_workspace: Workspace memory externally allocated, which is used for SDFG's transient arrays when `transient_memory_mode` is `EXTERNAL`. - unit_stride_dimension: Dimension or dimension kind that is assumed to have - unit stride in the memory layout of the field arguments; its stride - symbols are replaced by '1'. + unit_stride_kind: Dimension kind for which the first dimension is assumed + to have unit stride in the memory layout of the field arguments; its + stride symbols are replaced by '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 @@ -134,7 +134,7 @@ def make_dace_backend( gpu=gpu, auto_optimize=auto_optimize, external_workspace=external_workspace, - unit_stride_dimension=unit_stride_dimension, + unit_stride_kind=unit_stride_kind, ), translation=functools.partial( gtx_wfdfactory.make_dace_translator, 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 b074520a9b..00cabd450c 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -135,7 +135,7 @@ def make_dace_translator( auto_optimize=cfg.auto_optimize, auto_optimize_args=optimization_args, async_sdfg_call=async_sdfg_call and cfg.gpu, - unit_stride_dimension=cfg.unit_stride_dimension, + unit_stride_kind=cfg.unit_stride_kind, use_metrics=use_metrics, disable_field_origin_on_program_arguments=disable_field_origin_on_program_arguments, use_max_domain_range_on_unstructured_shift=use_max_domain_range_on_unstructured_shift, 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 21d51aa1f9..1d958d1445 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -34,7 +34,7 @@ def find_constant_symbols( sdfg: dace.SDFG, offset_provider_type: common.OffsetProviderType, disable_field_origin_on_program_arguments: bool, - unit_stride_dimension: common.UnitStrideDimension, + unit_stride_kind: common.DimensionKind | None, ) -> dict[str, int]: """Helper function to find symbols to replace with constant values.""" constant_symbols: dict[str, int] = {} @@ -51,13 +51,11 @@ def find_constant_symbols( (str(sym.id), sym.type) for sym in psymbols if isinstance(sym.type, ts.FieldType) ) - if unit_stride_dimension is not None: + if unit_stride_kind is not None: # Search the stride symbols of the dimensions with unit stride for name, field_type in field_params: if ( - unit_stride_dim := common.resolve_unit_stride_dimension( - field_type.dims, unit_stride_dimension - ) + unit_stride_dim := common.unit_stride_dimension(field_type.dims, unit_stride_kind) ) is not None: sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, unit_stride_dim) constant_symbols[sdfg_stride_symbol.name] = 1 @@ -69,12 +67,7 @@ def find_constant_symbols( ): assert not sdfg.arrays[conn_id].transient assert conn_type.source_dim.kind == common.DimensionKind.HORIZONTAL - if ( - common.resolve_unit_stride_dimension( - (conn_type.source_dim,), unit_stride_dimension - ) - is not None - ): + if conn_type.source_dim.kind == unit_stride_kind: sdfg_stride_symbol = gtx_dace_args.field_stride_symbol( conn_id, conn_type.source_dim, offset_provider_type ) @@ -338,7 +331,7 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: #: The parameters of `gt_auto_optimize()` that the translation step derives from #: its own configuration, and which therefore cannot be customized. _DERIVED_OPTIMIZATION_ARGS: Final[frozenset[str]] = frozenset( - {"gpu", "constant_symbols", "unit_strides_kind", "unit_strides_dimension"} + {"gpu", "constant_symbols", "unit_strides_kind"} ) #: The accepted values of the `scan_fusion_scope` option in `auto_optimize_args`. @@ -403,7 +396,7 @@ class DaCeTranslator( auto_optimize: bool auto_optimize_args: dict[str, Any] | None async_sdfg_call: bool - unit_stride_dimension: common.UnitStrideDimension + unit_stride_kind: common.DimensionKind | None use_metrics: bool disable_field_origin_on_program_arguments: bool = False @@ -465,28 +458,15 @@ def _generate_sdfg_without_configuring_dace( sdfg, offset_provider_type, self.disable_field_origin_on_program_arguments, - self.unit_stride_dimension, + self.unit_stride_kind, ) - # `gt_auto_optimize()` distinguishes between dimension kinds and concrete - # dimensions: forward the configured unit-stride assumption in the form - # it expects, and explicitly disable the other one. - unit_strides_kwargs: dict[str, Any] = { - "unit_strides_kind": None, - "unit_strides_dimension": None, - } - match self.unit_stride_dimension: - case common.Dimension(): - unit_strides_kwargs["unit_strides_dimension"] = self.unit_stride_dimension - case common.DimensionKind() | None as kind: - unit_strides_kwargs["unit_strides_kind"] = kind - if self.auto_optimize: gtx_transformations.gt_auto_optimize( sdfg, gpu=on_gpu, constant_symbols=constant_symbols, - **unit_strides_kwargs, + unit_strides_kind=self.unit_stride_kind, **auto_optimize_args, ) elif on_gpu: diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index 4e4107f99b..e9584d95d3 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -176,7 +176,7 @@ def make_gtfn_bindings( # `ExtensionGenerator` accepts only C++-like specs. Parameterizing the # pipeline is the real fix and belongs with the pipeline rework. return nanobind.ExtensionGenerator( # type: ignore[return-value] # see comment above - unit_stride_dimension=cfg.unit_stride_dimension + unit_stride_kind=cfg.unit_stride_kind ) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py b/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py index df8043fadd..fb7967f730 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py @@ -42,17 +42,18 @@ def copy(inp: gtx.Field[[IDim, JDim], gtx.int32]) -> gtx.Field[[IDim, JDim], gtx assert np.allclose(inp[:out_nx, :out_ny].asnumpy(), out.asnumpy()) -def test_unit_stride_dimension_cartesian(): +def test_unit_stride_kind_cartesian(): """ - A cartesian program can assume unit stride on a single horizontal dimension. + On a cartesian grid, unit stride is assumed on the first horizontal dimension only. - The unit-stride dimension must match the memory layout of the arguments, + The assumption must match the memory layout of the arguments, which the nanobind adapter checks at runtime. """ nx = 6 ny = 7 backend = gtfn.make_gtfn_toolchain( - gtfn.GTFNConfig(unit_stride_dimension=IDim), name_postfix="_unit_stride_idim" + gtfn.GTFNConfig(unit_stride_kind=common.DimensionKind.HORIZONTAL), + name_postfix="_unit_stride_horizontal", ) # column-major buffers have unit stride on the first dimension @@ -74,12 +75,13 @@ def copy(inp: gtx.Field[[IDim, JDim], gtx.int32]) -> gtx.Field[[IDim, JDim], gtx assert np.array_equal(inp.ndarray, out.ndarray) -def test_unit_stride_dimension_cartesian_mismatch(): +def test_unit_stride_kind_cartesian_mismatch(): """The nanobind adapter rejects arguments whose layout does not match the assumption.""" nx = 6 ny = 7 backend = gtfn.make_gtfn_toolchain( - gtfn.GTFNConfig(unit_stride_dimension=IDim), name_postfix="_unit_stride_idim_mismatch" + gtfn.GTFNConfig(unit_stride_kind=common.DimensionKind.HORIZONTAL), + name_postfix="_unit_stride_horizontal_mismatch", ) # row-major buffers have unit stride on the last dimension diff --git a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py index 5d1b68bb00..c9f699c8b7 100644 --- a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py +++ b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py @@ -15,5 +15,5 @@ def test_bindings(program_source_example): - module = nanobind.create_bindings(program_source_example, config.UNIT_STRIDE_DIMENSION) + module = nanobind.create_bindings(program_source_example, config.UNIT_STRIDE_KIND) assert module.library_deps[0].name == "nanobind" diff --git a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py index 4eb718b23a..7d59d16502 100644 --- a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py +++ b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py @@ -91,7 +91,5 @@ def program_source_example(): def extension_source_example(program_source_example): return artifacts.ExtensionSource( program_source=program_source_example, - binding_source=nanobind.create_bindings( - program_source_example, config.UNIT_STRIDE_DIMENSION - ), + binding_source=nanobind.create_bindings(program_source_example, config.UNIT_STRIDE_KIND), ) 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 00f3ebf3ae..7713f2135d 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 @@ -36,7 +36,7 @@ ) from next_tests.integration_tests import cases, cases_utils -from next_tests.integration_tests.cases_utils import JDim, KDim +from next_tests.integration_tests.cases_utils import KDim @pytest.fixture( @@ -105,12 +105,12 @@ 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) - # the unit-stride is configured with the concrete dimension + # unit stride applies to the first horizontal dimension, i.e. `IDim` custom_backend = dace_wf_backend.make_dace_toolchain( dace_wf_factory.DaCeConfig( gpu=on_gpu, auto_optimize=auto_optimize, - unit_stride_dimension=JDim, + unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, ), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -132,23 +132,21 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: mock_gpu_transformation.assert_not_called() # check call to `gt_auto_optimize()` - # the configured unit-stride dimension is forwarded to `gt_auto_optimize()` if auto_optimize: if on_gpu: mock_auto_optimize.assert_called_once_with( sdfg, gpu=on_gpu, constant_symbols={ - "__a_JDim_stride": 1, - "__b_JDim_stride": 1, - "__out_JDim_stride": 1, + "__a_IDim_stride": 1, + "__b_IDim_stride": 1, + "__out_IDim_stride": 1, }, transient_memory_mode=optimization_args["transient_memory_mode"], gpu_block_size=optimization_args["gpu_block_size"], gpu_block_size_2d=optimization_args["gpu_block_size_2d"], optimization_hooks=optimization_args["optimization_hooks"], - unit_strides_kind=None, - unit_strides_dimension=JDim, + unit_strides_kind=gtx.common.DimensionKind.HORIZONTAL, ) mock_top_level_dataflow_hook1.assert_called_once_with(sdfg) mock_top_level_dataflow_hook2.assert_not_called() @@ -157,16 +155,15 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: sdfg, gpu=on_gpu, constant_symbols={ - "__a_JDim_stride": 1, - "__b_JDim_stride": 1, - "__out_JDim_stride": 1, + "__a_IDim_stride": 1, + "__b_IDim_stride": 1, + "__out_IDim_stride": 1, }, transient_memory_mode=optimization_args["transient_memory_mode"], blocking_dim=optimization_args["blocking_dim"], blocking_size=optimization_args["blocking_size"], optimization_hooks=optimization_args["optimization_hooks"], - unit_strides_kind=None, - unit_strides_dimension=JDim, + unit_strides_kind=gtx.common.DimensionKind.HORIZONTAL, ) mock_top_level_dataflow_hook1.assert_not_called() mock_top_level_dataflow_hook2.assert_called_once_with(sdfg) @@ -328,7 +325,7 @@ def test_make_dace_backend_is_deprecated(): async_sdfg_call=False, optimization_args={"blocking_size": 10}, external_workspace=workspace, - unit_stride_dimension=gtx.common.DimensionKind.HORIZONTAL, + unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, use_metrics=False, use_zero_origin=True, use_max_domain_range_on_unstructured_shift=True, @@ -336,7 +333,7 @@ def test_make_dace_backend_is_deprecated(): toolchain = dace_wf_backend.make_dace_toolchain( dace_wf_factory.DaCeConfig( external_workspace=workspace, - unit_stride_dimension=gtx.common.DimensionKind.HORIZONTAL, + unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, ), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -367,7 +364,7 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): auto_optimize=False, auto_optimize_args={"gpu": True}, async_sdfg_call=False, - unit_stride_dimension=None, + unit_stride_kind=None, use_metrics=False, ) translator = dace_wf_backend.run_dace_cpu.executor.translation.step 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 7af064d21b..ffff48c9ff 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 @@ -72,7 +72,7 @@ def _translate_gtir_to_sdfg( auto_optimize=auto_optimize, auto_optimize_args=None, async_sdfg_call=async_sdfg_call, - unit_stride_dimension=None, + unit_stride_kind=None, use_metrics=use_metrics, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -103,10 +103,10 @@ def _make_unstructured_program(program_id: str) -> itir.Program: @pytest.mark.parametrize( - "unit_stride_dimension", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] + "unit_stride_kind", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] ) @pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols(unit_stride_dimension, disable_field_origin): +def test_find_constant_symbols(unit_stride_kind, disable_field_origin): """Unit stride must only be set on the horizontal dimension, not on the vertical one.""" SKIP_VALUE_MESH = skip_value_mesh(None) ir = _make_unstructured_program("find_constant_symbols_sdfg") @@ -124,11 +124,11 @@ def test_find_constant_symbols(unit_stride_dimension, disable_field_origin): sdfg=sdfg, offset_provider_type=SKIP_VALUE_MESH.offset_provider_type, disable_field_origin_on_program_arguments=disable_field_origin, - unit_stride_dimension=unit_stride_dimension, + unit_stride_kind=unit_stride_kind, ) expected = {} - if unit_stride_dimension is not None: + if unit_stride_kind is not None: # The vertical dimension stride symbols must not be set to 1. expected |= { "__x_Edge_stride": 1, @@ -166,21 +166,17 @@ def _make_cartesian_program(program_id: str) -> itir.Program: @pytest.mark.parametrize( - "grid_type, unit_stride_dimension, expected_horizontal_unit_stride", + "grid_type, unit_stride_kind, expected_horizontal_unit_stride", [ (gtx_common.GridType.UNSTRUCTURED, gtx_common.DimensionKind.HORIZONTAL, True), (gtx_common.GridType.UNSTRUCTURED, None, False), - # cartesian: unit stride on the configured dimension only - (gtx_common.GridType.CARTESIAN, IDim, True), (gtx_common.GridType.CARTESIAN, None, False), # cartesian with several horizontal dimensions: a dimension kind applies # to the leading dimension of that kind, as the standard allocator lays out (gtx_common.GridType.CARTESIAN, gtx_common.DimensionKind.HORIZONTAL, True), ], ) -def test_translation_unit_strides( - grid_type, unit_stride_dimension, expected_horizontal_unit_stride -): +def test_translation_unit_strides(grid_type, unit_stride_kind, expected_horizontal_unit_stride): """The emitted SDFG has unit stride on the dimensions configured in the translator.""" if grid_type == gtx_common.GridType.UNSTRUCTURED: ir = _make_unstructured_program("translation_unit_strides_unstructured") @@ -226,7 +222,7 @@ def test_translation_unit_strides( auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_dimension=unit_stride_dimension, + unit_stride_kind=unit_stride_kind, use_metrics=False, ) @@ -262,7 +258,7 @@ def test_translation_unit_strides_auto_optimize(): auto_optimize=True, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_dimension=IDim, + unit_stride_kind=gtx_common.DimensionKind.HORIZONTAL, use_metrics=False, ) @@ -277,16 +273,14 @@ def test_translation_unit_strides_auto_optimize(): if isinstance(map_entry, dace_nodes.MapEntry) ] assert map_params, "expected at least one Map" - for params in map_params: - if idim_map_variable in params: - assert params[-1] == idim_map_variable + assert all(params[-1] == idim_map_variable for params in map_params) @pytest.mark.parametrize( - "unit_stride_dimension", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] + "unit_stride_kind", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] ) @pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols_tuple_args(unit_stride_dimension, disable_field_origin): +def test_find_constant_symbols_tuple_args(unit_stride_kind, disable_field_origin): """Fields nested in tuple arguments, both inputs and targets, are also considered.""" vftype = ts.FieldType(dims=[Vertex], dtype=FLOAT_TYPE) domain = im.get_field_domain( @@ -321,7 +315,7 @@ def test_find_constant_symbols_tuple_args(unit_stride_dimension, disable_field_o auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_dimension=unit_stride_dimension, + unit_stride_kind=unit_stride_kind, use_metrics=False, disable_field_origin_on_program_arguments=disable_field_origin, ).generate_sdfg(ir, offset_provider={}, column_axis=None) @@ -331,12 +325,12 @@ def test_find_constant_symbols_tuple_args(unit_stride_dimension, disable_field_o sdfg=sdfg, offset_provider_type={}, disable_field_origin_on_program_arguments=disable_field_origin, - unit_stride_dimension=unit_stride_dimension, + unit_stride_kind=unit_stride_kind, ) field_names = ["x_0", "y_0", "y_1_0", "y_1_1"] expected = {} - if unit_stride_dimension is not None: + if unit_stride_kind is not None: expected |= {f"__{name}_Vertex_stride": 1 for name in field_names} if disable_field_origin: expected |= {f"__{name}_Vertex_range_0": 0 for name in field_names} @@ -344,7 +338,7 @@ def test_find_constant_symbols_tuple_args(unit_stride_dimension, disable_field_o # check that the symbols have been replaced in the translated SDFG for name in field_names: - expected_stride = "1" if unit_stride_dimension is not None else f"__{name}_Vertex_stride" + expected_stride = "1" if unit_stride_kind is not None else f"__{name}_Vertex_stride" assert [str(stride) for stride in sdfg.arrays[name].strides] == [expected_stride] @@ -746,7 +740,7 @@ def test_translation_source_code_invariant_under_guid_change(): auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_dimension=None, + unit_stride_kind=None, use_metrics=False, ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py index af2dfb4828..8dd63e6ab5 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py @@ -75,7 +75,7 @@ def translate(program, enabled, **extra_options): auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": enabled, **extra_options}, async_sdfg_call=False, - unit_stride_dimension=None, + unit_stride_kind=None, use_metrics=False, ) return translator.generate_sdfg(program, offset_provider={}, column_axis=K) @@ -227,7 +227,7 @@ def test_compiled_staggered_scan_fusion(tmp_path, input_dim, forward, mixed, lev auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True}, async_sdfg_call=False, - unit_stride_dimension=None, + unit_stride_kind=None, use_metrics=False, ).generate_sdfg(program, offset_provider={}, column_axis=scan_dim) graph.validate() @@ -586,7 +586,7 @@ def test_invalid_scan_fusion_scope_is_rejected(): auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True, "scan_fusion_scope": "field_operators"}, async_sdfg_call=False, - unit_stride_dimension=None, + unit_stride_kind=None, use_metrics=False, ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py deleted file mode 100644 index 21676dfc4a..0000000000 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_change_strides.py +++ /dev/null @@ -1,134 +0,0 @@ -# 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 - -from __future__ import annotations - -import itertools - -import dace -import pytest - -from gt4py.next import common as gtx_common -from gt4py.next.program_processors.runners.dace import ( - lowering as gtx_dace_lowering, - transformations as gtx_transformations, -) - - -IDim = gtx_common.Dimension("IDim") -JDim = gtx_common.Dimension("JDim") -KDim = gtx_common.Dimension("KDim", kind=gtx_common.DimensionKind.VERTICAL) - -_sdfg_counter = itertools.count() - - -def _make_transient_access_sdfg( - shape: tuple[int, ...], - dims: list[gtx_common.Dimension], -) -> tuple[dace.SDFG, str]: - """Create an SDFG with a transient array accessed by a Map over `dims`. - - The Map parameters and the Memlet subsets follow the GT4Py naming - conventions, so they look like the output of the lowering. - """ - sdfg = dace.SDFG(f"change_strides_sdfg_{next(_sdfg_counter)}") - state = sdfg.add_state("state", is_start_block=True) - sdfg.add_array("tmp", shape=shape, dtype=dace.float64, transient=True) - - map_ranges = [ - (gtx_dace_lowering.get_map_variable(dim), f"0:{size}") for dim, size in zip(dims, shape) - ] - memlet_idx = ",".join(var for var, _ in map_ranges) - state.add_mapped_tasklet( - "compute", - map_ranges=map_ranges, - inputs={"__in": dace.Memlet(f"tmp[{memlet_idx}]")}, - code="__out = __in + 1", - outputs={"__out": dace.Memlet(f"tmp[{memlet_idx}]")}, - external_edges=True, - ) - sdfg.validate() - return sdfg, "tmp" - - -def _strides_of(sdfg: dace.SDFG, name: str) -> tuple[int, ...]: - return tuple(int(stride) for stride in sdfg.arrays[name].strides) - - -def test_change_strides_unit_strides_dim(): - """The axis of the given dimension becomes the fastest varying one.""" - sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5, 6), dims=[IDim, JDim, KDim]) - - gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=JDim) - - # JDim (axis 1) has stride 1, the other axes keep their relative order - assert _strides_of(sdfg, tmp) == (5, 1, 20) - sdfg.validate() - - -def test_change_strides_unit_strides_dim_not_accessed(): - """A transient that is not accessed along the given dimension keeps its strides.""" - # the Map only ranges over IDim and JDim, so KDim does not appear - sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) - strides_before = _strides_of(sdfg, tmp) - - gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=KDim) - - # KDim is vertical: without access information the strides stay unchanged - assert _strides_of(sdfg, tmp) == strides_before - sdfg.validate() - - -def test_change_strides_unit_strides_dim_horizontal_fallback(): - """A horizontal dimension falls back to the kind-based layout without access information.""" - sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) - - # no access refers to the connectivity-like dimension 'CDim' - c_dim = gtx_common.Dimension("CDim") - gtx_transformations.gt_change_strides(sdfg, unit_strides_dim=c_dim) - - # fallback for horizontal dimensions: Fortran order, IDim is the first horizontal - assert _strides_of(sdfg, tmp) == (1, 4) - sdfg.validate() - - -def test_change_strides_prefered_direction_kind_horizontal(): - """The kind-based variant keeps its behaviour: transients are flipped to Fortran order.""" - sdfg, tmp = _make_transient_access_sdfg(shape=(4, 5, 6), dims=[IDim, JDim, KDim]) - - gtx_transformations.gt_change_strides( - sdfg, prefered_direction_kind=gtx_common.DimensionKind.HORIZONTAL - ) - - assert _strides_of(sdfg, tmp) == (1, 4, 20) - sdfg.validate() - - -def test_change_strides_mutually_exclusive(): - sdfg, _ = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) - - with pytest.raises(ValueError, match="Specify either"): - gtx_transformations.gt_change_strides( - sdfg, - prefered_direction_kind=gtx_common.DimensionKind.HORIZONTAL, - unit_strides_dim=IDim, - ) - with pytest.raises(ValueError, match="Specify either"): - gtx_transformations.gt_change_strides(sdfg) - - -def test_gt_auto_optimize_mutually_exclusive(): - sdfg, _ = _make_transient_access_sdfg(shape=(4, 5), dims=[IDim, JDim]) - - with pytest.raises(ValueError, match="Specified both"): - gtx_transformations.gt_auto_optimize( - sdfg, - gpu=False, - unit_strides_kind=gtx_common.DimensionKind.HORIZONTAL, - unit_strides_dimension=IDim, - ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py index 985fe28bfb..106d444cbf 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py @@ -8,18 +8,28 @@ from __future__ import annotations +import itertools + import dace import pytest import numpy as np from gt4py.next import common as gtx_common from gt4py.next.program_processors.runners.dace import ( + lowering as gtx_dace_lowering, transformations as gtx_transformations, ) +from gt4py.next.program_processors.runners.dace.transformations import auto_optimize + from . import util +IDim = gtx_common.Dimension("IDim") +JDim = gtx_common.Dimension("JDim") +KDim = gtx_common.Dimension("KDim", kind=gtx_common.DimensionKind.VERTICAL) + + def _perform_reorder_test( sdfg: dace.SDFG, unit_strides_dim: list[str], @@ -92,12 +102,39 @@ def test_map_order_unit_strides_kind_1(): ) new_map_order = map_entrie.map.params.copy() - # The order of the horizontal is unspecific, but vertical must be at - # position 0, because position 1 and 2 are occupied by the other two. - assert new_map_order[0].endswith("_vertical") - assert all(map_param.endswith("_horizontal") for map_param in new_map_order[1:]) - assert set(original_map_order) == set(new_map_order) - assert len(new_map_order) == len(original_map_order) + # The first horizontal dimension has the smallest stride, so it must be innermost. + assert new_map_order == ["KDim_vertical", "VDim_horizontal", "EDim_horizontal"] + + +@pytest.mark.parametrize("dims", itertools.permutations([IDim, JDim, KDim])) +def test_map_order_unit_strides_kind_first_dimension(dims): + """The first dimension of the kind is innermost, independent of the initial order.""" + sdfg = _make_test_sdfg([gtx_dace_lowering.get_map_variable(dim) for dim in dims]) + map_entry: dace.nodes.MapEntry = util.count_nodes(sdfg, dace.nodes.MapEntry, True)[0] + + # Also ensures that the transformation is idempotent. + for _ in range(2): + gtx_transformations.gt_set_iteration_order( + sdfg=sdfg, unit_strides_kind=gtx_common.DimensionKind.HORIZONTAL + ) + assert map_entry.map.params == [ + gtx_dace_lowering.get_map_variable(dim) for dim in (KDim, JDim, IDim) + ] + + +def test_map_order_unit_strides_kind_matches_canonical_order(): + """The order is given by the dimension names, also if one is the prefix of another.""" + dims = gtx_common.order_dimensions([gtx_common.Dimension("XY"), gtx_common.Dimension("X")]) + sdfg = _make_test_sdfg([gtx_dace_lowering.get_map_variable(dim) for dim in dims]) + map_entry: dace.nodes.MapEntry = util.count_nodes(sdfg, dace.nodes.MapEntry, True)[0] + + gtx_transformations.gt_set_iteration_order( + sdfg=sdfg, unit_strides_kind=gtx_common.DimensionKind.HORIZONTAL + ) + + assert map_entry.map.params == [ + gtx_dace_lowering.get_map_variable(dim) for dim in reversed(dims) + ] def test_map_order_unit_strides_kind_2(): @@ -135,3 +172,49 @@ def test_map_order_unit_strides_dim_3(): def test_map_order_unit_strides_dim_4(): sdfg = _make_test_sdfg(["CDim", "KDim"]) _perform_reorder_test(sdfg, ["EDim", "VDim"], []) + + +@pytest.mark.parametrize("gpu", [False, True]) +def test_unit_strides_kind_map_order_matches_transient_strides(gpu, monkeypatch): + """The inner most Map parameter indexes the axis of the transient with stride 1.""" + monkeypatch.setattr(gtx_transformations, "gt_gpu_transformation", lambda *_, **__: None) + dims = (IDim, JDim, KDim) + shape = (4, 5, 6) + params = [gtx_dace_lowering.get_map_variable(dim) for dim in dims] + index = ",".join(params) + map_ranges = [(param, f"0:{size}") for param, size in zip(params, shape)] + + sdfg = dace.SDFG(util.unique_name("unit_strides_kind")) + for name in ["a", "b", "t"]: + sdfg.add_array(name, shape=shape, dtype=dace.float64, transient=(name == "t")) + state = sdfg.add_state(is_start_block=True) + for i, (src, dst) in enumerate([("a", "t"), ("t", "b")]): + if i > 0: + state = sdfg.add_state_after(state) + state.add_mapped_tasklet( + f"copy_{i}", + map_ranges=map_ranges, + inputs={"__in": dace.Memlet(f"{src}[{index}]")}, + code="__out = __in", + outputs={"__out": dace.Memlet(f"{dst}[{index}]")}, + external_edges=True, + ) + sdfg.validate() + + auto_optimize._gt_auto_configure_maps_and_strides( + sdfg=sdfg, + gpu=gpu, + unit_strides_kind=gtx_common.DimensionKind.HORIZONTAL, + gpu_block_size=None, + gpu_launch_bounds=None, + gpu_launch_factor=None, + gpu_maxnreg=None, + optimization_hooks={}, + gpu_block_size_spec=None, + validate_all=False, + ) + + map_entries = util.count_nodes(sdfg, dace.nodes.MapEntry, True) + assert len(map_entries) == 2 + assert all(me.map.params == [params[2], params[1], params[0]] for me in map_entries) + assert sdfg.arrays["t"].strides == (1, 4, 20) 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 a3a0f093f1..89c5b446a7 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 @@ -213,7 +213,7 @@ def test_compile_workflow_without_config_caches_translation(): @pytest.mark.parametrize( - "dims, unit_stride_dimension, expected_stride_spec", + "dims, unit_stride_kind, expected_stride_spec", [ # unstructured: unit stride on the horizontal dimension only, not on the vertical one ( @@ -226,12 +226,6 @@ def test_compile_workflow_without_config_caches_translation(): None, f"{_DYN}, {_DYN}", ), - # cartesian: unit stride on the configured dimension only - ( - [gtx.Dimension("I"), gtx.Dimension("J")], - gtx.Dimension("I"), - f"1, {_DYN}", - ), ( [gtx.Dimension("I"), gtx.Dimension("J")], None, @@ -246,7 +240,7 @@ def test_compile_workflow_without_config_caches_translation(): ), ], ) -def test_bindings_static_strides(dims, unit_stride_dimension, expected_stride_spec): +def test_bindings_static_strides(dims, unit_stride_kind, expected_stride_spec): program_source = artifacts.ProgramSource( entry_point=interface.Function( "stencil", @@ -261,7 +255,7 @@ def test_bindings_static_strides(dims, unit_stride_dimension, expected_stride_sp library_deps=(), code_spec=artifacts.CPPCodeSpec(), ) - bindings = gtfn.make_gtfn_bindings(gtfn.GTFNConfig(unit_stride_dimension=unit_stride_dimension)) + bindings = gtfn.make_gtfn_bindings(gtfn.GTFNConfig(unit_stride_kind=unit_stride_kind)) extension = bindings(program_source) diff --git a/tests/next_tests/unit_tests/test_common.py b/tests/next_tests/unit_tests/test_common.py index 516a60ae97..fb1eca5378 100644 --- a/tests/next_tests/unit_tests/test_common.py +++ b/tests/next_tests/unit_tests/test_common.py @@ -634,7 +634,7 @@ def test_dimension_promotion_repeated_calls(): @pytest.mark.parametrize( - "dims, unit_stride_dimension, expected", + "dims, unit_stride_kind, expected", [ # a dimension kind applies to the leading dimension of that kind ((Dimension("I"), Dimension("J")), DimensionKind.HORIZONTAL, Dimension("I")), @@ -644,19 +644,16 @@ def test_dimension_promotion_repeated_calls(): Dimension("J"), ), ((Dimension("K", kind=DimensionKind.VERTICAL),), DimensionKind.HORIZONTAL, None), - # a dimension applies only if the field actually has it - ((Dimension("I"), Dimension("J")), Dimension("I"), Dimension("I")), - ((Dimension("I"), Dimension("J")), Dimension("K"), None), # no assumption ((Dimension("I"),), None, None), ], ) -def test_resolve_unit_stride_dimension( +def test_unit_stride_dimension( dims: tuple[Dimension, ...], - unit_stride_dimension: common.UnitStrideDimension, + unit_stride_kind: Optional[DimensionKind], expected: Optional[Dimension], ): - assert common.resolve_unit_stride_dimension(dims, unit_stride_dimension) == expected + assert common.unit_stride_dimension(dims, unit_stride_kind) == expected def _read_only(array): diff --git a/tests/next_tests/unit_tests/test_config.py b/tests/next_tests/unit_tests/test_config.py index f353086309..7535e19f02 100644 --- a/tests/next_tests/unit_tests/test_config.py +++ b/tests/next_tests/unit_tests/test_config.py @@ -12,7 +12,7 @@ import pytest -from gt4py.next import config +from gt4py.next import common, config @pytest.fixture @@ -50,6 +50,28 @@ def test_env_flag_to_bool_unset(env_var): assert config.env_flag_to_bool(env_var, default=False) is False +@pytest.mark.parametrize( + "value, expected", + [ + (None, None), + ("none", None), + ("horizontal", common.DimensionKind.HORIZONTAL), + ("VERTICAL", common.DimensionKind.VERTICAL), + ], +) +def test_unit_stride_kind_from_env(monkeypatch, value, expected): + monkeypatch.delenv("GT4PY_UNIT_STRIDE_KIND", raising=False) + if value is not None: + monkeypatch.setenv("GT4PY_UNIT_STRIDE_KIND", value) + assert config._unit_stride_kind_from_env() == expected + + +def test_unit_stride_kind_from_env_invalid(monkeypatch): + monkeypatch.setenv("GT4PY_UNIT_STRIDE_KIND", "IDim") + with pytest.raises(ValueError, match="GT4PY_UNIT_STRIDE_KIND"): + config._unit_stride_kind_from_env() + + def test_python_debug_mode_warning_is_off_by_default(): """The `python -O` hint is opt-in: an unset environment variable must disable it.""" env = {k: v for k, v in os.environ.items() if k != "GT4PY_WARN_PYTHON_DEBUG_MODE"} From 0c6a404619ca38a0ff1baace4f60d1699859195e Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 13:50:37 +0100 Subject: [PATCH 13/28] test[next-dace]: check that arguments violating the unit-stride assumption 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. --- .../dace_tests/test_dace_backend.py | 70 ++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) 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 7713f2135d..b41f668590 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 @@ -21,6 +21,7 @@ from gt4py import next as gtx from gt4py._core import definitions as core_defs from gt4py.next import config +from gt4py.next.embedded import nd_array_field from gt4py.next.otf import runners, stages from gt4py.next.otf import workflow as gtx_workflow from gt4py.next.program_processors.runners.dace import transformations as gtx_transformations @@ -36,7 +37,7 @@ ) from next_tests.integration_tests import cases, cases_utils -from next_tests.integration_tests.cases_utils import KDim +from next_tests.integration_tests.cases_utils import IDim, JDim, KDim @pytest.fixture( @@ -609,3 +610,70 @@ def no_op_top_level_map_processing(*, sdfg: dace.SDFG, **kwargs) -> dace.SDFG: assert any(marker in generated_code for marker in ("delete ", "free")) assert np.allclose(out.asnumpy(), a.asnumpy() + b.asnumpy() + 1) + + +def _make_unit_stride_copy(auto_optimize: bool): + backend = dace_wf_backend.make_dace_toolchain( + dace_wf_factory.DaCeConfig( + auto_optimize=auto_optimize, + unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, + ), + name_postfix=f"_unit_stride_horizontal_{auto_optimize}", + ) + + @gtx.field_operator(backend=backend) + def copy(inp: cases.IJField) -> cases.IJField: + return inp + + return copy + + +def _make_unit_stride_copy_args(order: str) -> tuple[gtx.Field, gtx.Field]: + """Input and output fields with unit stride on 'IDim' ('F') or 'JDim' ('C').""" + shape = (6, 7) + domain = gtx.common.domain({IDim: shape[0], JDim: shape[1]}) + # `from_array()` wraps the array, while `gtx.as_field()` would change the layout + inp, out = ( + nd_array_field.NdArrayField.from_array(np.array(array, order=order), domain=domain) + for array in ( + np.arange(np.prod(shape), dtype=np.int32).reshape(shape), + np.zeros(shape, dtype=np.int32), + ) + ) + return inp, out + + +@pytest.mark.parametrize("auto_optimize", [False, True], ids=["NO_AUTO_OPT", "AUTO_OPT"]) +def test_unit_stride_kind_cartesian(auto_optimize): + """On a cartesian grid, unit stride is assumed on the first horizontal dimension only.""" + copy = _make_unit_stride_copy(auto_optimize) + + for _ in range(2): # the second call is a fast call + inp, out = _make_unit_stride_copy_args("F") + copy(inp, out=out, offset_provider={}) + assert np.array_equal(inp.ndarray, out.ndarray) + + +@pytest.mark.parametrize("auto_optimize", [False, True], ids=["NO_AUTO_OPT", "AUTO_OPT"]) +def test_unit_stride_kind_cartesian_mismatch_first_call(auto_optimize): + """The first call rejects arguments whose layout does not match the assumption.""" + copy = _make_unit_stride_copy(auto_optimize) + + inp, out = _make_unit_stride_copy_args("C") + with pytest.raises(RuntimeError, match="Array stride mismatch: expected 1, got 7."): + copy(inp, out=out, offset_provider={}) + + +@pytest.mark.skipif(not __debug__, reason="The fast call checks the strides with 'assert'.") +@pytest.mark.parametrize("auto_optimize", [False, True], ids=["NO_AUTO_OPT", "AUTO_OPT"]) +def test_unit_stride_kind_cartesian_mismatch_fast_call(auto_optimize): + """The calls after the first one reject arguments whose layout does not match, too.""" + copy = _make_unit_stride_copy(auto_optimize) + + inp, out = _make_unit_stride_copy_args("F") + copy(inp, out=out, offset_provider={}) + + inp, out = _make_unit_stride_copy_args("C") + with pytest.raises(AssertionError): + copy(inp, out=out, offset_provider={}) + assert np.all(out.ndarray == 0) # the program did not run From 55aaf1fb81529c2ec3a95ed3684e469ac19df18e Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 14:20:39 +0100 Subject: [PATCH 14/28] ci[next-dace]: assume unit stride on the horizontal dimension in CSCS CI 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. --- .cscs-ci/default.yml | 5 +++++ .../runners_tests/dace_tests/test_dace_bindings.py | 8 ++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.cscs-ci/default.yml b/.cscs-ci/default.yml index 6145017c92..c3349c3466 100644 --- a/.cscs-ci/default.yml +++ b/.cscs-ci/default.yml @@ -77,6 +77,11 @@ build_cscs_amd_rocm: - mkdir -p "${WORKDIR}/gt4py" && git clone --depth 1 "${CSCS_CI_ORIG_CLONE_URL}" "${WORKDIR}/gt4py" - cd "${WORKDIR}/gt4py" && git fetch --depth 1 origin "${CI_COMMIT_SHA}" && git checkout "${CI_COMMIT_SHA}" - export NOX_SESSION_ARGS="${VARIANT:+($VARIANT}${SUBVARIANT:+, $SUBVARIANT}${DETAIL:+, $DETAIL}${VARIANT:+)}" + # Set here rather than in `rules`, because only the variables of the first matching rule apply. + - | + if [ "${SUBPACKAGE}" = "next" ] && [ "${VARIANT}" = "dace" ]; then + export GT4PY_UNIT_STRIDE_KIND=horizontal + fi - cd "${WORKDIR}/gt4py" && ./noxfile.py -s "test_${SUBPACKAGE}-${PY_VERSION}${NOX_SESSION_ARGS}" test_cscs_gh200: 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..5921c52b9b 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,12 +294,14 @@ def testee( ): testee_op(a, b, out=out, domain={IDim: (1, M - 1), JDim: (2, N - 2), KDim: (3, K - 3)}) + # the expected bindings have symbolic strides, independent of the environment backend = dace_runner.make_dace_toolchain( + dace_runner.DaCeConfig(unit_stride_kind=None), translation=functools.partial( dace_runner.make_dace_translator, use_metrics=use_metrics, disable_field_origin_on_program_arguments=use_zero_origin, - ) + ), ) monkeypatch.setattr( dace_workflow.compilation.DaCeCompiler, @@ -350,12 +352,14 @@ def testee_op(a: cases.VField) -> cases.VField: def testee(a: cases.VField, b: cases.VField): testee_op(a, out=b) + # the expected bindings have symbolic strides, independent of the environment backend = dace_runner.make_dace_toolchain( + dace_runner.DaCeConfig(unit_stride_kind=None), translation=functools.partial( dace_runner.make_dace_translator, use_metrics=use_metrics, disable_field_origin_on_program_arguments=use_zero_origin, - ) + ), ) monkeypatch.setattr( dace_workflow.compilation.DaCeCompiler, From b29eca745a74cf8d9f5f4fbdc9266e10a4961288 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 14:45:04 +0100 Subject: [PATCH 15/28] test[next]: allocate the laplacian input with the backend allocator 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. --- .../ffront_tests/test_laplacian.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_laplacian.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_laplacian.py index d9dcc0d5a8..3dc63aa286 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_laplacian.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_laplacian.py @@ -69,9 +69,12 @@ def laplap_program( laplap(in_field, out=out_field[2:-2, 2:-2]) -def square(inp): +def square(case, inp): """Compute the square of the field entries""" - return inp[:, :] * inp[:, :] + result = inp[:, :] * inp[:, :] + # The memory layout of the result of an embedded operation is chosen by the array library, + # so use the allocator to obtain the layout that the backend might rely on. + return case.as_field(result.domain, result.ndarray) def lap_ref(inp): @@ -87,7 +90,7 @@ def skewedlap_ref(inp): @pytest.mark.uses_program_with_sliced_out_arguments def test_ffront_lap(cartesian_case): in_field = cases.allocate(cartesian_case, lap_program, "in_field")() - in_field = square(in_field) + in_field = square(cartesian_case, in_field) out_field = cases.allocate(cartesian_case, lap_program, "out_field")() cases.verify( @@ -103,7 +106,7 @@ def test_ffront_lap(cartesian_case): @pytest.mark.uses_program_with_sliced_out_arguments def test_ffront_skewedlap(cartesian_case): in_field = cases.allocate(cartesian_case, skewedlap_program, "in_field")() - in_field = square(in_field) + in_field = square(cartesian_case, in_field) out_field = cases.allocate(cartesian_case, skewedlap_program, "out_field")() cases.verify( @@ -119,7 +122,7 @@ def test_ffront_skewedlap(cartesian_case): @pytest.mark.uses_program_with_sliced_out_arguments def test_ffront_laplap(cartesian_case): in_field = cases.allocate(cartesian_case, laplap_program, "in_field")() - in_field = square(in_field) + in_field = square(cartesian_case, in_field) out_field = cases.allocate(cartesian_case, laplap_program, "out_field")() cases.verify( From 85ef49c2ced603f8e48d62708939fedc775a0066 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 15:45:44 +0100 Subject: [PATCH 16/28] undo CI-config change --- .cscs-ci/default.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.cscs-ci/default.yml b/.cscs-ci/default.yml index c3349c3466..6145017c92 100644 --- a/.cscs-ci/default.yml +++ b/.cscs-ci/default.yml @@ -77,11 +77,6 @@ build_cscs_amd_rocm: - mkdir -p "${WORKDIR}/gt4py" && git clone --depth 1 "${CSCS_CI_ORIG_CLONE_URL}" "${WORKDIR}/gt4py" - cd "${WORKDIR}/gt4py" && git fetch --depth 1 origin "${CI_COMMIT_SHA}" && git checkout "${CI_COMMIT_SHA}" - export NOX_SESSION_ARGS="${VARIANT:+($VARIANT}${SUBVARIANT:+, $SUBVARIANT}${DETAIL:+, $DETAIL}${VARIANT:+)}" - # Set here rather than in `rules`, because only the variables of the first matching rule apply. - - | - if [ "${SUBPACKAGE}" = "next" ] && [ "${VARIANT}" = "dace" ]; then - export GT4PY_UNIT_STRIDE_KIND=horizontal - fi - cd "${WORKDIR}/gt4py" && ./noxfile.py -s "test_${SUBPACKAGE}-${PY_VERSION}${NOX_SESSION_ARGS}" test_cscs_gh200: From 8932ce71ecfd4cd5da45b5e1fe13e3d0f655e993 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 15:55:13 +0100 Subject: [PATCH 17/28] test[next-dace]: adapt the test for multiple horizontal dimensions Restore the definition of IJFTYPE, lost in the rebase, and check that unit stride is set on the first horizontal dimension only. --- .../dace_tests/test_dace_translation.py | 31 +++++++------------ 1 file changed, 12 insertions(+), 19 deletions(-) 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 ffff48c9ff..f18102bdfc 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 @@ -43,6 +43,7 @@ FLOAT_TYPE = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) IFTYPE = ts.FieldType(dims=[IDim], dtype=FLOAT_TYPE) +IJFTYPE = ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE) @pytest.fixture( @@ -343,19 +344,19 @@ def test_find_constant_symbols_tuple_args(unit_stride_kind, disable_field_origin @pytest.mark.parametrize( - "param_type, field_name", + "param_type, field_names", [ - pytest.param(IJFTYPE, "x", id="field"), - pytest.param(ts.TupleType(types=[IFTYPE, IJFTYPE]), "x_1", id="tuple"), + pytest.param(IJFTYPE, ["x"], id="field"), + pytest.param(ts.TupleType(types=[IFTYPE, IJFTYPE]), ["x_0", "x_1"], id="tuple"), pytest.param( ts.TupleType(types=[IFTYPE, ts.TupleType(types=[IFTYPE, IJFTYPE])]), - "x_1_1", + ["x_0", "x_1_0", "x_1_1"], id="nested_tuple", ), ], ) -def test_find_constant_symbols_multiple_horizontal_dims(param_type, field_name): - """Unit stride is ambiguous on a field with multiple horizontal dimensions.""" +def test_find_constant_symbols_multiple_horizontal_dims(param_type, field_names): + """Unit stride is set on the first one of multiple horizontal dimensions only.""" ir = itir.Program( id="find_constant_symbols_multiple_horizontal_dims", function_definitions=[], @@ -370,20 +371,12 @@ def test_find_constant_symbols_multiple_horizontal_dims(param_type, field_name): "disable_field_origin_on_program_arguments": False, } - with pytest.raises( - NotImplementedError, match=rf"multiple horizontal dimensions '{field_name}'" - ): - dace_wf_translation.find_constant_symbols( - **kwargs, unstructured_horizontal_has_unit_stride=True - ) + assert dace_wf_translation.find_constant_symbols( + **kwargs, unit_stride_kind=gtx_common.DimensionKind.HORIZONTAL + ) == {f"__{name}_IDim_stride": 1 for name in field_names} - # the same field is supported when the unit-stride option is disabled - assert ( - dace_wf_translation.find_constant_symbols( - **kwargs, unstructured_horizontal_has_unit_stride=False - ) - == {} - ) + # no symbol is replaced when the unit-stride option is disabled + assert dace_wf_translation.find_constant_symbols(**kwargs, unit_stride_kind=None) == {} def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: From 855f5bad728e8de9674932076fce78295c71aa63 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 1 Dec 2026 16:31:50 +0100 Subject: [PATCH 18/28] refactor[next-dace]: use order_dimensions() in MapIterationOrder 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. --- .../runners/dace/lowering/__init__.py | 2 ++ .../dace/lowering/gtir_to_sdfg_utils.py | 19 +++++++++++++++ .../dace/transformations/map_orderer.py | 19 +++++++-------- .../transformation_tests/test_map_order.py | 24 +++++++++++++++++++ 4 files changed, 54 insertions(+), 10 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py b/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py index b96538a0c1..405a211d49 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py @@ -10,6 +10,7 @@ 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, ) @@ -17,6 +18,7 @@ __all__ = [ "flatten_tuple_fields", + "get_dimension_from_map_variable", "get_map_variable", "lower_program_to_sdfg", "safe_replace_symbolic", diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py index 9b5fbdbbc2..40f83be812 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_utils.py @@ -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. diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py b/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py index f1e414d6d3..044facd1b3 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/map_orderer.py @@ -224,17 +224,16 @@ def _compute_map_param_order_unit_strides_kind(self) -> Optional[list[str]]: # the first dimension of a kind has the smallest stride, it must be last. The # order must not depend on the current one, otherwise the transformation # would not be idempotent. - # NOTE: We have to compare the dimension names, i.e. without the decoration added - # by `get_map_variable()` and `LoopBlocking`, to obtain the same order as - # `gtx_common.order_dimensions()`. + dims = { + # `LoopBlocking` adds a prefix to the name of the map parameter. + map_param: gtx_dace_lowering.get_dimension_from_map_variable( + map_param.removeprefix("__gtx_coarse_"), self.unit_strides_kind + ) + for map_param in map_params_to_order + } + ordered_dims = gtx_common.order_dimensions(dims.values()) map_params_to_order.sort( - key=lambda map_param: ( - map_param.removeprefix("__gtx_coarse_") - .removeprefix("i_") - .removesuffix(kind_to_look_for) - .removesuffix("_gtx") - ), - reverse=True, + key=lambda map_param: ordered_dims.index(dims[map_param]), reverse=True ) new_map_params: list[str] = [ map_param for map_param in map_params if map_param not in map_params_to_order diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py index 106d444cbf..b74d110d9c 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_order.py @@ -154,6 +154,30 @@ def test_map_order_unit_strides_kind_2(): assert original_map_order == new_map_order +@pytest.mark.parametrize( + "dim", [IDim, KDim, gtx_common.Dimension("X_Y"), gtx_common.Dimension("i_")] +) +def test_get_dimension_from_map_variable(dim): + map_variable = gtx_dace_lowering.get_map_variable(dim) + assert gtx_dace_lowering.get_dimension_from_map_variable(map_variable, dim.kind) == dim + + +def test_map_order_unit_strides_kind_blocked_dimension(): + """The prefix added by `LoopBlocking` does not change the order.""" + sdfg = _make_test_sdfg( + ["__gtx_coarse_" + gtx_dace_lowering.get_map_variable(IDim)] + + [gtx_dace_lowering.get_map_variable(dim) for dim in (JDim, KDim)] + ) + map_entry: dace.nodes.MapEntry = util.count_nodes(sdfg, dace.nodes.MapEntry, True)[0] + i_param, j_param, k_param = map_entry.map.params + + gtx_transformations.gt_set_iteration_order( + sdfg=sdfg, unit_strides_kind=gtx_common.DimensionKind.HORIZONTAL + ) + + assert map_entry.map.params == [k_param, j_param, i_param] + + def test_map_order_unit_strides_dim_1(): sdfg = _make_test_sdfg(["EDim", "KDim", "VDim"]) _perform_reorder_test(sdfg, ["EDim", "VDim"], ["KDim", "VDim", "EDim"]) From bcbc2e4efb4e8d7c675326788fce887728773cf7 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 13:12:43 +0100 Subject: [PATCH 19/28] feat[next]: allocators report their layout mapper for unit-stride detection Add LayoutAwareFieldBufferAllocatorProtocol (__gt_layout_mapper__), get_layout_mapper() and unit_stride_dimension(layout_mapper, dims). --- src/gt4py/next/custom_layout_allocators.py | 60 +++++++++++++++ .../test_custom_layout_allocators.py | 74 +++++++++++++++++++ 2 files changed, 134 insertions(+) diff --git a/src/gt4py/next/custom_layout_allocators.py b/src/gt4py/next/custom_layout_allocators.py index e0d9644b66..8283f5f0d9 100644 --- a/src/gt4py/next/custom_layout_allocators.py +++ b/src/gt4py/next/custom_layout_allocators.py @@ -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.""" @@ -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, @@ -153,6 +190,9 @@ def __gt_allocate__( __TensorFieldAllocatorAsFieldAllocatorInterfaceT: type[FieldBufferAllocatorProtocol] = ( BaseFieldBufferAllocator ) + __TensorFieldAllocatorAsLayoutAwareInterfaceT: type[LayoutAwareFieldBufferAllocatorProtocol] = ( + BaseFieldBufferAllocator + ) def horizontal_first_layout_mapper( @@ -186,6 +226,26 @@ 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. + """ + if layout_mapper is None or not dims: + return None + innermost = len(dims) - 1 + return next(dim for dim, pos in zip(dims, layout_mapper(dims)) if pos == innermost) + + #: Registry of default allocators for each device type. device_allocators: dict[core_defs.DeviceType, FieldBufferAllocatorProtocol] = {} diff --git a/tests/next_tests/unit_tests/test_custom_layout_allocators.py b/tests/next_tests/unit_tests/test_custom_layout_allocators.py index 6f54a5d930..9aececf4b0 100644 --- a/tests/next_tests/unit_tests/test_custom_layout_allocators.py +++ b/tests/next_tests/unit_tests/test_custom_layout_allocators.py @@ -254,3 +254,77 @@ def test_aligned_index_outside_domain_raises(self): core_defs.dtype(float), aligned_index=[common.NamedIndex(Cell, 110)], ) + + +IDim = common.Dimension("IDim", common.DimensionKind.HORIZONTAL) +JDim = common.Dimension("JDim", common.DimensionKind.HORIZONTAL) +C2E = common.Dimension("C2E", common.DimensionKind.LOCAL) + +_UNIT_STRIDE_CASES = [ + ((Cell, K), Cell), + ((K, Cell), Cell), + ((IDim, JDim, K), IDim), + ((JDim, IDim, K), JDim), + ((K,), K), + ((Cell, C2E), Cell), + ((K, C2E), K), +] + + +def test_is_layout_aware_field_allocator(): + assert next_allocators.is_layout_aware_field_allocator( + next_allocators.StandardCPUFieldBufferAllocator() + ) + assert not next_allocators.is_layout_aware_field_allocator(DummyAllocator()) + assert not next_allocators.is_layout_aware_field_allocator("not an allocator") + + +def test_get_layout_mapper(): + allocator = next_allocators.StandardCPUFieldBufferAllocator() + expected = next_allocators.horizontal_first_layout_mapper + assert next_allocators.get_layout_mapper(allocator) is expected + + class Factory: # e.g. a backend + __gt_allocator__ = allocator + + assert next_allocators.get_layout_mapper(Factory()) is expected + + +@pytest.mark.parametrize( + "obj", [None, DummyAllocator(), DummyAllocatorFactory(), "not an allocator"] +) +def test_get_layout_mapper_unknown_layout(obj): + assert next_allocators.get_layout_mapper(obj) is None + + +def test_layout_mapper_is_picklable(): + # The layout mapper is stored in the toolchain configuration, which must be picklable. + import pickle + + mapper = next_allocators.get_layout_mapper(next_allocators.StandardCPUFieldBufferAllocator()) + assert pickle.loads(pickle.dumps(mapper)) is mapper + + +@pytest.mark.parametrize("dims, expected", _UNIT_STRIDE_CASES) +def test_unit_stride_dimension(dims, expected): + mapper = next_allocators.horizontal_first_layout_mapper + assert next_allocators.unit_stride_dimension(mapper, dims) == expected + + +@pytest.mark.parametrize("dims, expected", _UNIT_STRIDE_CASES) +def test_unit_stride_dimension_matches_allocated_strides(dims, expected): + allocator = next_allocators.StandardCPUFieldBufferAllocator() + domain = common.Domain( + dims=dims, ranges=tuple(common.UnitRange(0, 3 + i) for i in range(len(dims))) + ) + buffer = allocator.__gt_allocate__(domain, core_defs.dtype(float)) + unit_stride_dim = next_allocators.unit_stride_dimension( + next_allocators.get_layout_mapper(allocator), dims + ) + assert buffer.strides[dims.index(unit_stride_dim)] == buffer.dtype.byte_size + + +def test_unit_stride_dimension_unknown_layout_or_no_dims(): + assert next_allocators.unit_stride_dimension(None, (Cell, K)) is None + mapper = next_allocators.horizontal_first_layout_mapper + assert next_allocators.unit_stride_dimension(mapper, ()) is None From 374bcafb94d04a4e3c4655627139b01ecf2d59d9 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 13:14:06 +0100 Subject: [PATCH 20/28] feat[next]: add use_backend_allocator_layout toolchain option ToolchainConfig.layout_mapper exposes the layout mapper of the toolchain's allocator when GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT is set (default off). --- src/gt4py/next/backend.py | 19 +++++++++++++++++++ src/gt4py/next/config.py | 12 ++++++++++++ .../runners_tests/test_gtfn.py | 18 ++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index dc8cf02f6d..c7b7fbe4e6 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -262,6 +262,25 @@ class ToolchainConfig: unit_stride_kind: common.DimensionKind | None = dataclasses.field( default_factory=lambda: config.UNIT_STRIDE_KIND ) + #: 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: diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index a788de999d..44a9ec22b9 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -161,6 +161,18 @@ def _unit_stride_kind_from_env() -> common.DimensionKind | None: UNIT_STRIDE_KIND: common.DimensionKind | None = _unit_stride_kind_from_env() +#: Experimental, use at your own risk: 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. +#: Known issue: the GTFN backend fails to compile Cartesian programs with a +#: negative shift in the unit-stride dimension, because of a GridTools bug +#: (unsigned static strides in `nanobind_adapter.hpp`). +USE_BACKEND_ALLOCATOR_LAYOUT: bool = env_flag_to_bool( + "GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT", default=False +) + + #: Add GPU trace markers (NVTX, ROC-TX) to the generated code, at compile time. ADD_GPU_TRACE_MARKERS: bool = env_flag_to_bool("GT4PY_ADD_GPU_TRACE_MARKERS", default=False) 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 89c5b446a7..caf5e27d20 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 @@ -88,6 +88,24 @@ def test_make_gtfn_toolchain_build_type_config(monkeypatch): ) +def test_use_backend_allocator_layout_config(monkeypatch): + monkeypatch.setattr(config, "USE_BACKEND_ALLOCATOR_LAYOUT", True) + assert gtfn.GTFNConfig().use_backend_allocator_layout is True + monkeypatch.setattr(config, "USE_BACKEND_ALLOCATOR_LAYOUT", False) + assert gtfn.GTFNConfig().use_backend_allocator_layout is False + + +def test_layout_mapper(): + cfg_off = gtfn.GTFNConfig(use_backend_allocator_layout=False) + cfg_on = gtfn.GTFNConfig(use_backend_allocator_layout=True) + + assert cfg_off.layout_mapper is None + assert cfg_on.layout_mapper is custom_layout_allocators.get_layout_mapper( + cfg_on.make_allocator() + ) + assert cfg_on.layout_mapper is custom_layout_allocators.horizontal_first_layout_mapper + + def test_cmake_build_type_changes_build_folder(monkeypatch, tmp_path): """Different cmake build types must yield different build folders. From f99b461c79e3a3ac82e53673666bcd2b2cf1f23c Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 13:18:58 +0100 Subject: [PATCH 21/28] feat[next-gtfn]: derive static unit strides from the backend allocator 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. --- src/gt4py/next/otf/binding/nanobind.py | 31 +++++----- .../next/program_processors/runners/gtfn.py | 2 +- .../otf_tests/test_gtfn_workflow.py | 17 +++--- .../otf_tests/binding_tests/test_nanobind.py | 3 +- .../build_systems_tests/conftest.py | 3 +- .../runners_tests/test_gtfn.py | 57 ++++++++++--------- 6 files changed, 59 insertions(+), 54 deletions(-) diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index 9c153a7e8c..6503800989 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -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 @@ -204,10 +204,12 @@ def _tuple_get(index: int, var: str) -> str: def make_argument( - name: str, type_: ts.TypeSpec, unit_stride_kind: common.DimensionKind | None + name: str, + type_: ts.TypeSpec, + layout_mapper: next_allocators.FieldLayoutMapper | None, ) -> str | BufferSID | Tuple: if isinstance(type_, ts.FieldType): - unit_stride_dim = common.unit_stride_dimension(type_.dims, unit_stride_kind) + unit_stride_dim = next_allocators.unit_stride_dimension(layout_mapper, type_.dims) return BufferSID( source_buffer=name, dimensions=[ @@ -221,8 +223,7 @@ def make_argument( ) elif isinstance(type_, ts.TupleType): elements = [ - make_argument(_tuple_get(i, name), t, unit_stride_kind) - 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): @@ -233,7 +234,7 @@ def make_argument( def create_bindings( program_source: artifacts.ProgramSource[CodeSpecT], - unit_stride_kind: common.DimensionKind | None, + layout_mapper: next_allocators.FieldLayoutMapper | None, ) -> artifacts.BindingSource[CodeSpecT, artifacts.PythonCodeSpec]: """ Generate Python bindings through which a C++ function can be called. @@ -242,10 +243,11 @@ def create_bindings( ---------- program_source The program source for which the bindings are created - unit_stride_kind - Dimension kind for which the first dimension is assumed to have unit - stride in the memory layout of the field arguments, see - `common.unit_stride_dimension()`. + 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. """ if not isinstance(program_source.code_spec, artifacts.CPPLikeCodeSpec): raise ValueError( @@ -283,7 +285,7 @@ def create_bindings( expr=FunctionCall( target=program_source.entry_point, args=[ - make_argument(param.name, param.type_, unit_stride_kind) + make_argument(param.name, param.type_, layout_mapper) for param in program_source.entry_point.parameters ], ) @@ -319,14 +321,13 @@ class ExtensionGenerator: Generate a Python extension module that contains the bindings for a C++ function. """ - unit_stride_kind: common.DimensionKind | None = dataclasses.field( - default_factory=lambda: config.UNIT_STRIDE_KIND - ) + #: 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.unit_stride_kind) + binding_source = create_bindings(program_source, self.layout_mapper) return artifacts.ExtensionSource( program_source=program_source, binding_source=binding_source ) diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index e9584d95d3..e6bda8125e 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -176,7 +176,7 @@ def make_gtfn_bindings( # `ExtensionGenerator` accepts only C++-like specs. Parameterizing the # pipeline is the real fix and belongs with the pipeline rework. return nanobind.ExtensionGenerator( # type: ignore[return-value] # see comment above - unit_stride_kind=cfg.unit_stride_kind + layout_mapper=cfg.layout_mapper ) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py b/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py index fb7967f730..5a4981c464 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/otf_tests/test_gtfn_workflow.py @@ -42,9 +42,10 @@ def copy(inp: gtx.Field[[IDim, JDim], gtx.int32]) -> gtx.Field[[IDim, JDim], gtx assert np.allclose(inp[:out_nx, :out_ny].asnumpy(), out.asnumpy()) -def test_unit_stride_kind_cartesian(): +def test_backend_allocator_layout_cartesian(): """ - On a cartesian grid, unit stride is assumed on the first horizontal dimension only. + On a cartesian grid, the backend allocator gives unit stride to the first + horizontal dimension only. The assumption must match the memory layout of the arguments, which the nanobind adapter checks at runtime. @@ -52,11 +53,11 @@ def test_unit_stride_kind_cartesian(): nx = 6 ny = 7 backend = gtfn.make_gtfn_toolchain( - gtfn.GTFNConfig(unit_stride_kind=common.DimensionKind.HORIZONTAL), - name_postfix="_unit_stride_horizontal", + gtfn.GTFNConfig(use_backend_allocator_layout=True), + name_postfix="_backend_allocator_layout", ) - # column-major buffers have unit stride on the first dimension + # column-major buffers have unit stride on the first dimension, like the backend allocator inp = nd_array_field.NdArrayField.from_array( np.asfortranarray(np.arange(nx * ny, dtype=np.int32).reshape((nx, ny))), domain=common.domain({IDim: range(nx), JDim: range(ny)}), @@ -75,13 +76,13 @@ def copy(inp: gtx.Field[[IDim, JDim], gtx.int32]) -> gtx.Field[[IDim, JDim], gtx assert np.array_equal(inp.ndarray, out.ndarray) -def test_unit_stride_kind_cartesian_mismatch(): +def test_backend_allocator_layout_cartesian_mismatch(): """The nanobind adapter rejects arguments whose layout does not match the assumption.""" nx = 6 ny = 7 backend = gtfn.make_gtfn_toolchain( - gtfn.GTFNConfig(unit_stride_kind=common.DimensionKind.HORIZONTAL), - name_postfix="_unit_stride_horizontal_mismatch", + gtfn.GTFNConfig(use_backend_allocator_layout=True), + name_postfix="_backend_allocator_layout_mismatch", ) # row-major buffers have unit stride on the last dimension diff --git a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py index c9f699c8b7..5719a2cbbc 100644 --- a/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py +++ b/tests/next_tests/unit_tests/otf_tests/binding_tests/test_nanobind.py @@ -6,7 +6,6 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -from gt4py.next import config from gt4py.next.otf.binding import nanobind from next_tests.unit_tests.otf_tests.compilation_tests.build_systems_tests.conftest import ( @@ -15,5 +14,5 @@ def test_bindings(program_source_example): - module = nanobind.create_bindings(program_source_example, config.UNIT_STRIDE_KIND) + module = nanobind.create_bindings(program_source_example, None) assert module.library_deps[0].name == "nanobind" diff --git a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py index 7d59d16502..4e49fa48ea 100644 --- a/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py +++ b/tests/next_tests/unit_tests/otf_tests/compilation_tests/build_systems_tests/conftest.py @@ -13,7 +13,6 @@ import gt4py.next as gtx import gt4py.next.type_system.type_specifications as ts -from gt4py.next import config from gt4py.next.otf import artifacts from gt4py.next.otf.binding import cpp_interface, interface, nanobind from gt4py.next.otf.compilation import cache @@ -91,5 +90,5 @@ def program_source_example(): def extension_source_example(program_source_example): return artifacts.ExtensionSource( program_source=program_source_example, - binding_source=nanobind.create_bindings(program_source_example, config.UNIT_STRIDE_KIND), + binding_source=nanobind.create_bindings(program_source_example, None), ) 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 caf5e27d20..409f81b276 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 @@ -230,35 +230,38 @@ def test_compile_workflow_without_config_caches_translation(): _DYN = "gridtools::nanobind::dynamic_size" +def test_bindings_with_backend_allocator_layout_are_picklable(): + # Required to compile in a process pool, see `config.BUILD_JOBS_MODE`. + import pickle + + bindings = gtfn.make_gtfn_bindings(gtfn.GTFNConfig(use_backend_allocator_layout=True)) + + assert pickle.loads(pickle.dumps(bindings)) == bindings + + +_Vertex = gtx.Dimension("Vertex") +_K = gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL) +_V2E = gtx.Dimension("V2E", kind=gtx.DimensionKind.LOCAL) + + @pytest.mark.parametrize( - "dims, unit_stride_kind, expected_stride_spec", + "dims, use_backend_allocator_layout, expected_stride_spec", [ - # unstructured: unit stride on the horizontal dimension only, not on the vertical one - ( - [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], - gtx.DimensionKind.HORIZONTAL, - f"1, {_DYN}", - ), - ( - [gtx.Dimension("Vertex"), gtx.Dimension("K", kind=gtx.DimensionKind.VERTICAL)], - None, - f"{_DYN}, {_DYN}", - ), - ( - [gtx.Dimension("I"), gtx.Dimension("J")], - None, - f"{_DYN}, {_DYN}", - ), - # cartesian with several horizontal dimensions: a dimension kind applies - # to the leading dimension of that kind, as the standard allocator lays out - ( - [gtx.Dimension("I"), gtx.Dimension("J")], - gtx.DimensionKind.HORIZONTAL, - f"1, {_DYN}", - ), + # no assumption: all strides are dynamic + ([_Vertex, _K], False, f"{_DYN}, {_DYN}"), + ([gtx.Dimension("I"), gtx.Dimension("J")], False, f"{_DYN}, {_DYN}"), + # the CPU allocator lays out horizontal dimensions innermost + ([_Vertex, _K], True, f"1, {_DYN}"), + ([_K, _Vertex], True, f"{_DYN}, 1"), + # cartesian with several horizontal dimensions: the first one is innermost + ([gtx.Dimension("I"), gtx.Dimension("J")], True, f"1, {_DYN}"), + # fields without horizontal dimension have unit stride too + ([_K], True, "1"), + # connectivity tables are passed as fields with a local dimension + ([_Vertex, _V2E], True, f"1, {_DYN}"), ], ) -def test_bindings_static_strides(dims, unit_stride_kind, expected_stride_spec): +def test_bindings_static_strides(dims, use_backend_allocator_layout, expected_stride_spec): program_source = artifacts.ProgramSource( entry_point=interface.Function( "stencil", @@ -273,7 +276,9 @@ def test_bindings_static_strides(dims, unit_stride_kind, expected_stride_spec): library_deps=(), code_spec=artifacts.CPPCodeSpec(), ) - bindings = gtfn.make_gtfn_bindings(gtfn.GTFNConfig(unit_stride_kind=unit_stride_kind)) + bindings = gtfn.make_gtfn_bindings( + gtfn.GTFNConfig(use_backend_allocator_layout=use_backend_allocator_layout) + ) extension = bindings(program_source) From f2704c88e0cbdc2c44a80ae8b057a8fc5a067393 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 13:23:13 +0100 Subject: [PATCH 22/28] feat[next-dace]: derive constant unit strides from the backend allocator layout find_constant_symbols takes the toolchain's layout mapper instead of a dimension kind, for both fields and connectivity tables. --- .../runners/dace/workflow/factory.py | 1 + .../runners/dace/workflow/translation.py | 38 ++++++---- .../dace_tests/test_find_constant_symbols.py | 74 +++++++++++++++++++ 3 files changed, 100 insertions(+), 13 deletions(-) create mode 100644 tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py 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 00cabd450c..8200b8a66e 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -139,6 +139,7 @@ def make_dace_translator( use_metrics=use_metrics, disable_field_origin_on_program_arguments=disable_field_origin_on_program_arguments, use_max_domain_range_on_unstructured_shift=use_max_domain_range_on_unstructured_shift, + layout_mapper=cfg.layout_mapper, ) 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 1d958d1445..e965000645 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -14,7 +14,7 @@ import dace from gt4py._core import definitions as core_defs -from gt4py.next import common +from gt4py.next import common, custom_layout_allocators as next_allocators from gt4py.next.instrumentation import metrics from gt4py.next.iterator import ir as itir, transforms as itir_transforms from gt4py.next.iterator.transforms import scan_fusion as gtx_scan_fusion @@ -34,9 +34,15 @@ def find_constant_symbols( sdfg: dace.SDFG, offset_provider_type: common.OffsetProviderType, disable_field_origin_on_program_arguments: bool, - unit_stride_kind: common.DimensionKind | None, + layout_mapper: next_allocators.FieldLayoutMapper | None, ) -> dict[str, int]: - """Helper function to find symbols to replace with constant values.""" + """ + Helper function to find symbols to replace with constant values. + + If `layout_mapper` is given, the fields and connectivity tables passed as + program arguments are assumed to have that memory layout: the stride of + their innermost dimension is set to 1. + """ constant_symbols: dict[str, int] = {} # Collect all fields in the program arguments, including the elements of tuples @@ -51,27 +57,31 @@ def find_constant_symbols( (str(sym.id), sym.type) for sym in psymbols if isinstance(sym.type, ts.FieldType) ) - if unit_stride_kind is not None: + if layout_mapper is not None: # Search the stride symbols of the dimensions with unit stride for name, field_type in field_params: if ( - unit_stride_dim := common.unit_stride_dimension(field_type.dims, unit_stride_kind) + unit_stride_dim := next_allocators.unit_stride_dimension( + layout_mapper, field_type.dims + ) ) is not None: sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, unit_stride_dim) constant_symbols[sdfg_stride_symbol.name] = 1 - # Same for connectivity tables, for which the first dimension is always horizontal + # Same for connectivity tables, whose dimensions are `(source_dim, neighbor_dim)` for offset, conn_type in offset_provider_type.items(): if ( isinstance(conn_type, common.NeighborConnectivityType) and (conn_id := gtx_dace_args.connectivity_identifier(offset)) in sdfg.arrays ): assert not sdfg.arrays[conn_id].transient - assert conn_type.source_dim.kind == common.DimensionKind.HORIZONTAL - if conn_type.source_dim.kind == unit_stride_kind: - sdfg_stride_symbol = gtx_dace_args.field_stride_symbol( - conn_id, conn_type.source_dim, offset_provider_type - ) - constant_symbols[sdfg_stride_symbol.name] = 1 + unit_stride_dim = next_allocators.unit_stride_dimension( + layout_mapper, conn_type.domain + ) + assert unit_stride_dim is not None + sdfg_stride_symbol = gtx_dace_args.field_stride_symbol( + conn_id, unit_stride_dim, offset_provider_type + ) + constant_symbols[sdfg_stride_symbol.name] = 1 if disable_field_origin_on_program_arguments: # set all range start symbols of the program arguments to constant value 0 @@ -401,6 +411,8 @@ class DaCeTranslator( disable_field_origin_on_program_arguments: bool = False use_max_domain_range_on_unstructured_shift: bool | None = None + #: Memory layout assumed for the program arguments, see `find_constant_symbols()`. + layout_mapper: next_allocators.FieldLayoutMapper | None = None def __post_init__(self) -> None: if self.auto_optimize_args and ( @@ -458,7 +470,7 @@ def _generate_sdfg_without_configuring_dace( sdfg, offset_provider_type, self.disable_field_origin_on_program_arguments, - self.unit_stride_kind, + self.layout_mapper, ) if self.auto_optimize: diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py new file mode 100644 index 0000000000..921e055f3c --- /dev/null +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py @@ -0,0 +1,74 @@ +# 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 + +import types + +import dace +import numpy as np + +from gt4py._core import definitions as core_defs +from gt4py.next import common, custom_layout_allocators +from gt4py.next.iterator import ir as itir +from gt4py.next.program_processors.runners.dace.workflow import translation +from gt4py.next.type_system import type_specifications as ts + + +Vertex = common.Dimension("Vertex") +Edge = common.Dimension("Edge") +K = common.Dimension("K", kind=common.DimensionKind.VERTICAL) +V2E = common.Dimension("V2E", kind=common.DimensionKind.LOCAL) + +_FLOAT = ts.ScalarType(ts.ScalarKind.FLOAT64) + + +def _find_constant_symbols(layout_mapper): + # `find_constant_symbols()` only reads the program parameters and the SDFG arrays + ir = types.SimpleNamespace( + params=[ + itir.Sym(id="a", type=ts.FieldType(dims=[Vertex, K], dtype=_FLOAT)), + itir.Sym(id="b", type=ts.FieldType(dims=[K, Edge], dtype=_FLOAT)), + itir.Sym(id="c", type=ts.FieldType(dims=[K], dtype=_FLOAT)), + itir.Sym(id="s", type=_FLOAT), + ] + ) + offset_provider_type = { + "V2E": common.NeighborConnectivityType( + domain=(Vertex, V2E), + codomain=Edge, + skip_value=None, + dtype=core_defs.dtype(np.int32), + max_neighbors=4, + ) + } + sdfg = dace.SDFG("find_constant_symbols") + sdfg.add_array("gt_conn_V2E", (10, 4), dace.int32, transient=False) + + return translation.find_constant_symbols( + ir, + sdfg, + offset_provider_type, + disable_field_origin_on_program_arguments=False, + layout_mapper=layout_mapper, + ) + + +def test_find_constant_symbols_without_layout(): + assert _find_constant_symbols(None) == {} + + +def test_find_constant_symbols_with_backend_allocator_layout(): + constant_symbols = _find_constant_symbols( + custom_layout_allocators.horizontal_first_layout_mapper + ) + + assert constant_symbols == { + "__a_Vertex_stride": 1, + "__b_Edge_stride": 1, + "__c_K_stride": 1, + "__gt_conn_V2E_source_stride": 1, + } From 378e181dd09a5d22bef7c933a567e934ef712c6d Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 13:34:57 +0100 Subject: [PATCH 23/28] refactor[next]: remove the unit_stride_kind option 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. --- src/gt4py/next/backend.py | 7 -- src/gt4py/next/common.py | 24 ----- src/gt4py/next/config.py | 21 ----- .../runners/dace/workflow/backend.py | 7 +- .../runners/dace/workflow/factory.py | 1 - .../runners/dace/workflow/translation.py | 24 ++++- .../dace_tests/test_dace_backend.py | 24 ++--- .../dace_tests/test_dace_bindings.py | 4 +- .../dace_tests/test_dace_translation.py | 94 +++++++++++++------ .../dace_tests/test_find_constant_symbols.py | 74 --------------- .../dace_tests/test_scan_fusion.py | 3 - .../runners_tests/test_gtfn.py | 1 - tests/next_tests/unit_tests/test_common.py | 23 ----- tests/next_tests/unit_tests/test_config.py | 37 ++++---- 14 files changed, 118 insertions(+), 226 deletions(-) delete mode 100644 tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py diff --git a/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index c7b7fbe4e6..368db4136e 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -30,7 +30,6 @@ if TYPE_CHECKING: - from gt4py.next import common from gt4py.next.ffront import decorator as ffront_decorator @@ -256,12 +255,6 @@ class ToolchainConfig: cache_lifetime: config.BuildCacheLifetime = dataclasses.field( default_factory=lambda: config.BUILD_CACHE_LIFETIME ) - #: Assume unit stride in the first dimension of this kind in the memory - #: layout of the field arguments, see `common.unit_stride_dimension()`. - #: `None` disables the assumption. - unit_stride_kind: common.DimensionKind | None = dataclasses.field( - default_factory=lambda: config.UNIT_STRIDE_KIND - ) #: 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( diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index 864fafdea4..cf42e74093 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -130,30 +130,6 @@ def __ne__(self, value: Dimension | core_defs.IntegralScalar) -> bool | Domain: return NotImplemented -def unit_stride_dimension( - dims: Iterable[Dimension], kind: Optional[DimensionKind], / -) -> Optional[Dimension]: - """ - Find the dimension of a field that is assumed to have unit stride. - - This is the first dimension of the given kind, because within each kind the - dimensions appearing earlier in `dims` get smaller strides, see - `custom_layout_allocators.horizontal_first_layout_mapper()`. - - Args: - dims: The dimensions of a field, in the order given by its type. - kind: The dimension kind assumed to have unit stride, or `None` for no - assumption. - - Returns: - The dimension assumed to have unit stride, or `None` if the assumption - does not apply to `dims`. - """ - if kind is None: - return None - return next((dim for dim in dims if dim.kind == kind), None) - - if TYPE_CHECKING: # These exist as on-the fly replacements for Dimension instances # (which are not types) during typechecking (with mypy). We can diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index 44a9ec22b9..a9e2db0edf 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -16,8 +16,6 @@ import warnings from typing import Final -from gt4py.next import common - # Module-level UPPERCASE values are snapshotted and shipped verbatim to # compilation worker processes (see `gt4py.next.otf.runners`); keep them @@ -142,25 +140,6 @@ def _get_build_cache_version_id() -> str: ] -def _unit_stride_kind_from_env() -> common.DimensionKind | None: - value = os.environ.get("GT4PY_UNIT_STRIDE_KIND", "none") - if value.lower() in ("", "none"): - return None - try: - return common.DimensionKind(value.lower()) - except ValueError: - raise ValueError( - f"Invalid 'GT4PY_UNIT_STRIDE_KIND' value '{value}': use 'none' or one of" - f" {[str(kind) for kind in common.DimensionKind]}." - ) from None - - -#: Experimental, use at your own risk: dimension kind for which compiled -#: toolchains assume that the first dimension of this kind has unit stride in -#: the memory layout of the field arguments. `None` disables the assumption. -UNIT_STRIDE_KIND: common.DimensionKind | None = _unit_stride_kind_from_env() - - #: Experimental, use at your own risk: 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 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 120e77fbee..14d80a2502 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -13,7 +13,7 @@ import warnings from typing import Any -from gt4py.next import backend, common, config +from gt4py.next import backend from gt4py.next.otf import artifacts from gt4py.next.program_processors.runners.dace.workflow import ( common as gtx_wfdcommon, @@ -80,7 +80,6 @@ def make_dace_backend( async_sdfg_call: bool = True, optimization_args: dict[str, Any] | None = None, external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None, - unit_stride_kind: common.DimensionKind | None = config.UNIT_STRIDE_KIND, use_metrics: bool = True, use_zero_origin: bool = False, use_max_domain_range_on_unstructured_shift: bool | None = None, @@ -102,9 +101,6 @@ def make_dace_backend( accepts the scan-fusion options `fuse_scan_inputs` and `scan_fusion_scope`. external_workspace: Workspace memory externally allocated, which is used for SDFG's transient arrays when `transient_memory_mode` is `EXTERNAL`. - unit_stride_kind: Dimension kind for which the first dimension is assumed - to have unit stride in the memory layout of the field arguments; its - stride symbols are replaced by '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 @@ -134,7 +130,6 @@ def make_dace_backend( gpu=gpu, auto_optimize=auto_optimize, external_workspace=external_workspace, - unit_stride_kind=unit_stride_kind, ), translation=functools.partial( gtx_wfdfactory.make_dace_translator, 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 8200b8a66e..4713f291cf 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -135,7 +135,6 @@ def make_dace_translator( auto_optimize=cfg.auto_optimize, auto_optimize_args=optimization_args, async_sdfg_call=async_sdfg_call and cfg.gpu, - unit_stride_kind=cfg.unit_stride_kind, use_metrics=use_metrics, disable_field_origin_on_program_arguments=disable_field_origin_on_program_arguments, use_max_domain_range_on_unstructured_shift=use_max_domain_range_on_unstructured_shift, 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 e965000645..5e0568b7dc 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -93,6 +93,27 @@ def find_constant_symbols( return constant_symbols +def unit_stride_kind( + layout_mapper: next_allocators.FieldLayoutMapper | None, +) -> common.DimensionKind | None: + """ + Find the dimension kind that is innermost in the memory layout given by `layout_mapper`. + + The DaCe optimizer orders the maps and sets the strides of the transients by + dimension kind, see `gt_auto_optimize()`, because at that stage the map + parameters can only be associated with a dimension kind. Within a kind, it + assumes that the first dimension is innermost, as in the layout of + `custom_layout_allocators.horizontal_first_layout_mapper()`. + + Returns: + The kind of the innermost dimension in a field with one dimension of each + kind, or `None` if the layout is unknown. + """ + probe_dims = [common.Dimension(f"_{kind}", kind) for kind in common.DimensionKind] + unit_stride_dim = next_allocators.unit_stride_dimension(layout_mapper, probe_dims) + return None if unit_stride_dim is None else unit_stride_dim.kind + + def make_sdfg_call_async(sdfg: dace.SDFG, gpu: bool) -> None: """Configure an SDFG to immediately return once all work has been scheduled. @@ -406,7 +427,6 @@ class DaCeTranslator( auto_optimize: bool auto_optimize_args: dict[str, Any] | None async_sdfg_call: bool - unit_stride_kind: common.DimensionKind | None use_metrics: bool disable_field_origin_on_program_arguments: bool = False @@ -478,7 +498,7 @@ def _generate_sdfg_without_configuring_dace( sdfg, gpu=on_gpu, constant_symbols=constant_symbols, - unit_strides_kind=self.unit_stride_kind, + unit_strides_kind=unit_stride_kind(self.layout_mapper), **auto_optimize_args, ) elif on_gpu: 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 b41f668590..a0b59f4ba6 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_dace_backend.py @@ -106,12 +106,12 @@ 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) - # unit stride applies to the first horizontal dimension, i.e. `IDim` + # the backend allocator gives unit stride to the first horizontal dimension, i.e. `IDim` custom_backend = dace_wf_backend.make_dace_toolchain( dace_wf_factory.DaCeConfig( gpu=on_gpu, auto_optimize=auto_optimize, - unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, + use_backend_allocator_layout=True, ), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -326,16 +326,12 @@ def test_make_dace_backend_is_deprecated(): async_sdfg_call=False, optimization_args={"blocking_size": 10}, external_workspace=workspace, - unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, 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, - unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, - ), + dace_wf_factory.DaCeConfig(external_workspace=workspace), translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args={"blocking_size": 10}, @@ -365,7 +361,6 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): auto_optimize=False, auto_optimize_args={"gpu": True}, async_sdfg_call=False, - unit_stride_kind=None, use_metrics=False, ) translator = dace_wf_backend.run_dace_cpu.executor.translation.step @@ -616,9 +611,9 @@ def _make_unit_stride_copy(auto_optimize: bool): backend = dace_wf_backend.make_dace_toolchain( dace_wf_factory.DaCeConfig( auto_optimize=auto_optimize, - unit_stride_kind=gtx.common.DimensionKind.HORIZONTAL, + use_backend_allocator_layout=True, ), - name_postfix=f"_unit_stride_horizontal_{auto_optimize}", + name_postfix=f"_backend_allocator_layout_{auto_optimize}", ) @gtx.field_operator(backend=backend) @@ -644,8 +639,9 @@ def _make_unit_stride_copy_args(order: str) -> tuple[gtx.Field, gtx.Field]: @pytest.mark.parametrize("auto_optimize", [False, True], ids=["NO_AUTO_OPT", "AUTO_OPT"]) -def test_unit_stride_kind_cartesian(auto_optimize): - """On a cartesian grid, unit stride is assumed on the first horizontal dimension only.""" +def test_backend_allocator_layout_cartesian(auto_optimize): + """On a cartesian grid, the backend allocator gives unit stride to the first + horizontal dimension only.""" copy = _make_unit_stride_copy(auto_optimize) for _ in range(2): # the second call is a fast call @@ -655,7 +651,7 @@ def test_unit_stride_kind_cartesian(auto_optimize): @pytest.mark.parametrize("auto_optimize", [False, True], ids=["NO_AUTO_OPT", "AUTO_OPT"]) -def test_unit_stride_kind_cartesian_mismatch_first_call(auto_optimize): +def test_backend_allocator_layout_cartesian_mismatch_first_call(auto_optimize): """The first call rejects arguments whose layout does not match the assumption.""" copy = _make_unit_stride_copy(auto_optimize) @@ -666,7 +662,7 @@ def test_unit_stride_kind_cartesian_mismatch_first_call(auto_optimize): @pytest.mark.skipif(not __debug__, reason="The fast call checks the strides with 'assert'.") @pytest.mark.parametrize("auto_optimize", [False, True], ids=["NO_AUTO_OPT", "AUTO_OPT"]) -def test_unit_stride_kind_cartesian_mismatch_fast_call(auto_optimize): +def test_backend_allocator_layout_cartesian_mismatch_fast_call(auto_optimize): """The calls after the first one reject arguments whose layout does not match, too.""" copy = _make_unit_stride_copy(auto_optimize) 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 5921c52b9b..bb24ce0da0 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 @@ -296,7 +296,7 @@ def testee( # the expected bindings have symbolic strides, independent of the environment backend = dace_runner.make_dace_toolchain( - dace_runner.DaCeConfig(unit_stride_kind=None), + dace_runner.DaCeConfig(use_backend_allocator_layout=False), translation=functools.partial( dace_runner.make_dace_translator, use_metrics=use_metrics, @@ -354,7 +354,7 @@ def testee(a: cases.VField, b: cases.VField): # the expected bindings have symbolic strides, independent of the environment backend = dace_runner.make_dace_toolchain( - dace_runner.DaCeConfig(unit_stride_kind=None), + dace_runner.DaCeConfig(use_backend_allocator_layout=False), 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 f18102bdfc..d3858885b1 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 @@ -17,7 +17,7 @@ from unittest import mock from gt4py._core import definitions as core_defs -from gt4py.next import common as gtx_common, fingerprinting +from gt4py.next import common as gtx_common, custom_layout_allocators, fingerprinting 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 as otf_arguments, workflow as otf_workflow @@ -41,6 +41,8 @@ from dace import nodes as dace_nodes +HORIZONTAL_FIRST = custom_layout_allocators.horizontal_first_layout_mapper + FLOAT_TYPE = ts.ScalarType(kind=ts.ScalarKind.FLOAT64) IFTYPE = ts.FieldType(dims=[IDim], dtype=FLOAT_TYPE) IJFTYPE = ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE) @@ -73,7 +75,6 @@ def _translate_gtir_to_sdfg( auto_optimize=auto_optimize, auto_optimize_args=None, async_sdfg_call=async_sdfg_call, - unit_stride_kind=None, use_metrics=use_metrics, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -103,11 +104,9 @@ def _make_unstructured_program(program_id: str) -> itir.Program: ) -@pytest.mark.parametrize( - "unit_stride_kind", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] -) +@pytest.mark.parametrize("layout_mapper", [None, HORIZONTAL_FIRST], ids=["none", "horizontal"]) @pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols(unit_stride_kind, disable_field_origin): +def test_find_constant_symbols(layout_mapper, disable_field_origin): """Unit stride must only be set on the horizontal dimension, not on the vertical one.""" SKIP_VALUE_MESH = skip_value_mesh(None) ir = _make_unstructured_program("find_constant_symbols_sdfg") @@ -125,11 +124,11 @@ def test_find_constant_symbols(unit_stride_kind, disable_field_origin): sdfg=sdfg, offset_provider_type=SKIP_VALUE_MESH.offset_provider_type, disable_field_origin_on_program_arguments=disable_field_origin, - unit_stride_kind=unit_stride_kind, + layout_mapper=layout_mapper, ) expected = {} - if unit_stride_kind is not None: + if layout_mapper is not None: # The vertical dimension stride symbols must not be set to 1. expected |= { "__x_Edge_stride": 1, @@ -167,17 +166,17 @@ def _make_cartesian_program(program_id: str) -> itir.Program: @pytest.mark.parametrize( - "grid_type, unit_stride_kind, expected_horizontal_unit_stride", + "grid_type, layout_mapper, expected_horizontal_unit_stride", [ - (gtx_common.GridType.UNSTRUCTURED, gtx_common.DimensionKind.HORIZONTAL, True), + (gtx_common.GridType.UNSTRUCTURED, HORIZONTAL_FIRST, True), (gtx_common.GridType.UNSTRUCTURED, None, False), (gtx_common.GridType.CARTESIAN, None, False), - # cartesian with several horizontal dimensions: a dimension kind applies - # to the leading dimension of that kind, as the standard allocator lays out - (gtx_common.GridType.CARTESIAN, gtx_common.DimensionKind.HORIZONTAL, True), + # cartesian with several horizontal dimensions: the standard allocator + # gives unit stride to the first one + (gtx_common.GridType.CARTESIAN, HORIZONTAL_FIRST, True), ], ) -def test_translation_unit_strides(grid_type, unit_stride_kind, expected_horizontal_unit_stride): +def test_translation_unit_strides(grid_type, layout_mapper, expected_horizontal_unit_stride): """The emitted SDFG has unit stride on the dimensions configured in the translator.""" if grid_type == gtx_common.GridType.UNSTRUCTURED: ir = _make_unstructured_program("translation_unit_strides_unstructured") @@ -223,8 +222,8 @@ def test_translation_unit_strides(grid_type, unit_stride_kind, expected_horizont auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_kind=unit_stride_kind, use_metrics=False, + layout_mapper=layout_mapper, ) program_source = translator(compilable_program) @@ -259,8 +258,8 @@ def test_translation_unit_strides_auto_optimize(): auto_optimize=True, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_kind=gtx_common.DimensionKind.HORIZONTAL, use_metrics=False, + layout_mapper=HORIZONTAL_FIRST, ) program_source = translator(compilable_program) @@ -277,11 +276,9 @@ def test_translation_unit_strides_auto_optimize(): assert all(params[-1] == idim_map_variable for params in map_params) -@pytest.mark.parametrize( - "unit_stride_kind", [None, gtx_common.DimensionKind.HORIZONTAL], ids=["none", "horizontal"] -) +@pytest.mark.parametrize("layout_mapper", [None, HORIZONTAL_FIRST], ids=["none", "horizontal"]) @pytest.mark.parametrize("disable_field_origin", [False, True]) -def test_find_constant_symbols_tuple_args(unit_stride_kind, disable_field_origin): +def test_find_constant_symbols_tuple_args(layout_mapper, disable_field_origin): """Fields nested in tuple arguments, both inputs and targets, are also considered.""" vftype = ts.FieldType(dims=[Vertex], dtype=FLOAT_TYPE) domain = im.get_field_domain( @@ -316,9 +313,9 @@ def test_find_constant_symbols_tuple_args(unit_stride_kind, disable_field_origin auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_kind=unit_stride_kind, use_metrics=False, disable_field_origin_on_program_arguments=disable_field_origin, + layout_mapper=layout_mapper, ).generate_sdfg(ir, offset_provider={}, column_axis=None) constant_symbols = dace_wf_translation.find_constant_symbols( @@ -326,12 +323,12 @@ def test_find_constant_symbols_tuple_args(unit_stride_kind, disable_field_origin sdfg=sdfg, offset_provider_type={}, disable_field_origin_on_program_arguments=disable_field_origin, - unit_stride_kind=unit_stride_kind, + layout_mapper=layout_mapper, ) field_names = ["x_0", "y_0", "y_1_0", "y_1_1"] expected = {} - if unit_stride_kind is not None: + if layout_mapper is not None: expected |= {f"__{name}_Vertex_stride": 1 for name in field_names} if disable_field_origin: expected |= {f"__{name}_Vertex_range_0": 0 for name in field_names} @@ -339,7 +336,7 @@ def test_find_constant_symbols_tuple_args(unit_stride_kind, disable_field_origin # check that the symbols have been replaced in the translated SDFG for name in field_names: - expected_stride = "1" if unit_stride_kind is not None else f"__{name}_Vertex_stride" + expected_stride = "1" if layout_mapper is not None else f"__{name}_Vertex_stride" assert [str(stride) for stride in sdfg.arrays[name].strides] == [expected_stride] @@ -371,12 +368,52 @@ def test_find_constant_symbols_multiple_horizontal_dims(param_type, field_names) "disable_field_origin_on_program_arguments": False, } + assert dace_wf_translation.find_constant_symbols(**kwargs, layout_mapper=HORIZONTAL_FIRST) == { + f"__{name}_IDim_stride": 1 for name in field_names + } + + # no symbol is replaced when the memory layout is unknown + assert dace_wf_translation.find_constant_symbols(**kwargs, layout_mapper=None) == {} + + +def test_find_constant_symbols_without_horizontal_dim(): + """The innermost dimension of the layout gets unit stride, whatever its kind.""" + ir = itir.Program( + id="find_constant_symbols_without_horizontal_dim", + function_definitions=[], + params=[itir.Sym(id="x", type=ts.FieldType(dims=[KDim], dtype=FLOAT_TYPE))], + declarations=[], + body=[], + ) + assert dace_wf_translation.find_constant_symbols( - **kwargs, unit_stride_kind=gtx_common.DimensionKind.HORIZONTAL - ) == {f"__{name}_IDim_stride": 1 for name in field_names} + ir=ir, + sdfg=dace.SDFG("find_constant_symbols_without_horizontal_dim"), + offset_provider_type={}, + disable_field_origin_on_program_arguments=False, + layout_mapper=HORIZONTAL_FIRST, + ) == {"__x_KDim_stride": 1} + - # no symbol is replaced when the unit-stride option is disabled - assert dace_wf_translation.find_constant_symbols(**kwargs, unit_stride_kind=None) == {} +def test_unit_stride_kind(): + assert dace_wf_translation.unit_stride_kind(None) is None + assert dace_wf_translation.unit_stride_kind(HORIZONTAL_FIRST) is ( + gtx_common.DimensionKind.HORIZONTAL + ) + + def vertical_innermost_layout_mapper(dims): + is_vertical = [dim.kind is gtx_common.DimensionKind.VERTICAL for dim in dims] + order = [i for i, v in enumerate(is_vertical) if not v] + [ + i for i, v in enumerate(is_vertical) if v + ] + layout_map = [0] * len(dims) + for pos, i in enumerate(order): + layout_map[i] = pos + return tuple(layout_map) + + assert dace_wf_translation.unit_stride_kind(vertical_innermost_layout_mapper) is ( + gtx_common.DimensionKind.VERTICAL + ) def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: @@ -733,7 +770,6 @@ def test_translation_source_code_invariant_under_guid_change(): auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unit_stride_kind=None, use_metrics=False, ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py deleted file mode 100644 index 921e055f3c..0000000000 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_find_constant_symbols.py +++ /dev/null @@ -1,74 +0,0 @@ -# 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 - -import types - -import dace -import numpy as np - -from gt4py._core import definitions as core_defs -from gt4py.next import common, custom_layout_allocators -from gt4py.next.iterator import ir as itir -from gt4py.next.program_processors.runners.dace.workflow import translation -from gt4py.next.type_system import type_specifications as ts - - -Vertex = common.Dimension("Vertex") -Edge = common.Dimension("Edge") -K = common.Dimension("K", kind=common.DimensionKind.VERTICAL) -V2E = common.Dimension("V2E", kind=common.DimensionKind.LOCAL) - -_FLOAT = ts.ScalarType(ts.ScalarKind.FLOAT64) - - -def _find_constant_symbols(layout_mapper): - # `find_constant_symbols()` only reads the program parameters and the SDFG arrays - ir = types.SimpleNamespace( - params=[ - itir.Sym(id="a", type=ts.FieldType(dims=[Vertex, K], dtype=_FLOAT)), - itir.Sym(id="b", type=ts.FieldType(dims=[K, Edge], dtype=_FLOAT)), - itir.Sym(id="c", type=ts.FieldType(dims=[K], dtype=_FLOAT)), - itir.Sym(id="s", type=_FLOAT), - ] - ) - offset_provider_type = { - "V2E": common.NeighborConnectivityType( - domain=(Vertex, V2E), - codomain=Edge, - skip_value=None, - dtype=core_defs.dtype(np.int32), - max_neighbors=4, - ) - } - sdfg = dace.SDFG("find_constant_symbols") - sdfg.add_array("gt_conn_V2E", (10, 4), dace.int32, transient=False) - - return translation.find_constant_symbols( - ir, - sdfg, - offset_provider_type, - disable_field_origin_on_program_arguments=False, - layout_mapper=layout_mapper, - ) - - -def test_find_constant_symbols_without_layout(): - assert _find_constant_symbols(None) == {} - - -def test_find_constant_symbols_with_backend_allocator_layout(): - constant_symbols = _find_constant_symbols( - custom_layout_allocators.horizontal_first_layout_mapper - ) - - assert constant_symbols == { - "__a_Vertex_stride": 1, - "__b_Edge_stride": 1, - "__c_K_stride": 1, - "__gt_conn_V2E_source_stride": 1, - } diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py index 8dd63e6ab5..3102cb7a83 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py @@ -75,7 +75,6 @@ def translate(program, enabled, **extra_options): auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": enabled, **extra_options}, async_sdfg_call=False, - unit_stride_kind=None, use_metrics=False, ) return translator.generate_sdfg(program, offset_provider={}, column_axis=K) @@ -227,7 +226,6 @@ def test_compiled_staggered_scan_fusion(tmp_path, input_dim, forward, mixed, lev auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True}, async_sdfg_call=False, - unit_stride_kind=None, use_metrics=False, ).generate_sdfg(program, offset_provider={}, column_axis=scan_dim) graph.validate() @@ -586,7 +584,6 @@ def test_invalid_scan_fusion_scope_is_rejected(): auto_optimize=True, auto_optimize_args={"fuse_scan_inputs": True, "scan_fusion_scope": "field_operators"}, async_sdfg_call=False, - unit_stride_kind=None, use_metrics=False, ) 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 409f81b276..d98798b2fc 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 @@ -252,7 +252,6 @@ def test_bindings_with_backend_allocator_layout_are_picklable(): ([gtx.Dimension("I"), gtx.Dimension("J")], False, f"{_DYN}, {_DYN}"), # the CPU allocator lays out horizontal dimensions innermost ([_Vertex, _K], True, f"1, {_DYN}"), - ([_K, _Vertex], True, f"{_DYN}, 1"), # cartesian with several horizontal dimensions: the first one is innermost ([gtx.Dimension("I"), gtx.Dimension("J")], True, f"1, {_DYN}"), # fields without horizontal dimension have unit stride too diff --git a/tests/next_tests/unit_tests/test_common.py b/tests/next_tests/unit_tests/test_common.py index fb1eca5378..89dfaa88cb 100644 --- a/tests/next_tests/unit_tests/test_common.py +++ b/tests/next_tests/unit_tests/test_common.py @@ -633,29 +633,6 @@ def test_dimension_promotion_repeated_calls(): common.check_dims([K, I]) -@pytest.mark.parametrize( - "dims, unit_stride_kind, expected", - [ - # a dimension kind applies to the leading dimension of that kind - ((Dimension("I"), Dimension("J")), DimensionKind.HORIZONTAL, Dimension("I")), - ( - (Dimension("K", kind=DimensionKind.VERTICAL), Dimension("J")), - DimensionKind.HORIZONTAL, - Dimension("J"), - ), - ((Dimension("K", kind=DimensionKind.VERTICAL),), DimensionKind.HORIZONTAL, None), - # no assumption - ((Dimension("I"),), None, None), - ], -) -def test_unit_stride_dimension( - dims: tuple[Dimension, ...], - unit_stride_kind: Optional[DimensionKind], - expected: Optional[Dimension], -): - assert common.unit_stride_dimension(dims, unit_stride_kind) == expected - - def _read_only(array): array = array.copy() array.flags.writeable = False diff --git a/tests/next_tests/unit_tests/test_config.py b/tests/next_tests/unit_tests/test_config.py index 7535e19f02..8d0dfcd20e 100644 --- a/tests/next_tests/unit_tests/test_config.py +++ b/tests/next_tests/unit_tests/test_config.py @@ -12,7 +12,7 @@ import pytest -from gt4py.next import common, config +from gt4py.next import config @pytest.fixture @@ -50,26 +50,25 @@ def test_env_flag_to_bool_unset(env_var): assert config.env_flag_to_bool(env_var, default=False) is False -@pytest.mark.parametrize( - "value, expected", - [ - (None, None), - ("none", None), - ("horizontal", common.DimensionKind.HORIZONTAL), - ("VERTICAL", common.DimensionKind.VERTICAL), - ], -) -def test_unit_stride_kind_from_env(monkeypatch, value, expected): - monkeypatch.delenv("GT4PY_UNIT_STRIDE_KIND", raising=False) +@pytest.mark.parametrize("value, expected", [(None, "False"), ("1", "True"), ("0", "False")]) +def test_use_backend_allocator_layout_from_env(value, expected): + """The layout assumption is opt-in, until GTFN supports it on all cartesian programs.""" + env = {k: v for k, v in os.environ.items() if k != "GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT"} if value is not None: - monkeypatch.setenv("GT4PY_UNIT_STRIDE_KIND", value) - assert config._unit_stride_kind_from_env() == expected - + env["GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT"] = value + result = subprocess.run( + [ + sys.executable, + "-c", + "from gt4py.next import config; print(config.USE_BACKEND_ALLOCATOR_LAYOUT)", + ], + env=env, + capture_output=True, + text=True, + check=True, + ) -def test_unit_stride_kind_from_env_invalid(monkeypatch): - monkeypatch.setenv("GT4PY_UNIT_STRIDE_KIND", "IDim") - with pytest.raises(ValueError, match="GT4PY_UNIT_STRIDE_KIND"): - config._unit_stride_kind_from_env() + assert result.stdout.strip() == expected def test_python_debug_mode_warning_is_off_by_default(): From ddcd13dccc01705fbee47d433c49058d3aec6646 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 13:46:40 +0100 Subject: [PATCH 24/28] remove metion of the gridtools issue --- src/gt4py/next/config.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index a9e2db0edf..b3b86bb300 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -144,9 +144,6 @@ def _get_build_cache_version_id() -> str: #: 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. -#: Known issue: the GTFN backend fails to compile Cartesian programs with a -#: negative shift in the unit-stride dimension, because of a GridTools bug -#: (unsigned static strides in `nanobind_adapter.hpp`). USE_BACKEND_ALLOCATOR_LAYOUT: bool = env_flag_to_bool( "GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT", default=False ) From e73578d2937495e37c59590e374a33533b14fa51 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 13:55:38 +0100 Subject: [PATCH 25/28] edit --- src/gt4py/next/custom_layout_allocators.py | 12 ++- src/gt4py/next/otf/binding/nanobind.py | 21 +++--- .../runners/dace/workflow/translation.py | 75 +++++++++++++------ 3 files changed, 76 insertions(+), 32 deletions(-) diff --git a/src/gt4py/next/custom_layout_allocators.py b/src/gt4py/next/custom_layout_allocators.py index 8283f5f0d9..cf0cb01cda 100644 --- a/src/gt4py/next/custom_layout_allocators.py +++ b/src/gt4py/next/custom_layout_allocators.py @@ -239,11 +239,21 @@ def unit_stride_dimension( 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 - return next(dim for dim, pos in zip(dims, layout_mapper(dims)) if pos == innermost) + # 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. diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index 6503800989..adc4ad14ed 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -239,15 +239,18 @@ def create_bindings( """ Generate Python bindings through which a C++ function can be called. - Parameters - ---------- - 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. + 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( 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 5e0568b7dc..417c0d9fbf 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -8,6 +8,7 @@ from __future__ import annotations +import collections import dataclasses from typing import Any, Final, Literal, Optional @@ -29,6 +30,21 @@ from gt4py.next.type_system import type_specifications as ts +def _field_params(ir: itir.Program) -> list[tuple[str, ts.FieldType]]: + """Collect all fields in the program arguments, including the elements of tuples.""" + field_params: list[tuple[str, ts.FieldType]] = [] + for p in ir.params: + psymbols = ( + gtx_dace_lowering.flatten_tuple_fields(p.id, p.type) + if isinstance(p.type, ts.TupleType) + else [p] + ) + field_params.extend( + (str(sym.id), sym.type) for sym in psymbols if isinstance(sym.type, ts.FieldType) + ) + return field_params + + def find_constant_symbols( ir: itir.Program, sdfg: dace.SDFG, @@ -44,18 +60,7 @@ def find_constant_symbols( their innermost dimension is set to 1. """ constant_symbols: dict[str, int] = {} - - # Collect all fields in the program arguments, including the elements of tuples - field_params: list[tuple[str, ts.FieldType]] = [] - for p in ir.params: - psymbols = ( - gtx_dace_lowering.flatten_tuple_fields(p.id, p.type) - if isinstance(p.type, ts.TupleType) - else [p] - ) - field_params.extend( - (str(sym.id), sym.type) for sym in psymbols if isinstance(sym.type, ts.FieldType) - ) + field_params = _field_params(ir) if layout_mapper is not None: # Search the stride symbols of the dimensions with unit stride @@ -94,10 +99,11 @@ def find_constant_symbols( def unit_stride_kind( + ir: itir.Program, layout_mapper: next_allocators.FieldLayoutMapper | None, ) -> common.DimensionKind | None: """ - Find the dimension kind that is innermost in the memory layout given by `layout_mapper`. + Find the dimension kind with unit stride in the fields passed to the program. The DaCe optimizer orders the maps and sets the strides of the transients by dimension kind, see `gt_auto_optimize()`, because at that stage the map @@ -105,13 +111,26 @@ def unit_stride_kind( assumes that the first dimension is innermost, as in the layout of `custom_layout_allocators.horizontal_first_layout_mapper()`. + The kind is derived from the unit-stride dimension of each field argument, + the same one `find_constant_symbols()` sets a constant stride for, so it + does not depend on how `layout_mapper` orders the dimensions. If the fields + disagree, the most common kind is chosen. + Returns: - The kind of the innermost dimension in a field with one dimension of each - kind, or `None` if the layout is unknown. + The most common kind of the unit-stride dimension of the field arguments, + or `None` if the layout is unknown or the program has no field arguments. """ - probe_dims = [common.Dimension(f"_{kind}", kind) for kind in common.DimensionKind] - unit_stride_dim = next_allocators.unit_stride_dimension(layout_mapper, probe_dims) - return None if unit_stride_dim is None else unit_stride_dim.kind + if layout_mapper is None: + return None + kinds = collections.Counter( + unit_stride_dim.kind + for _, field_type in _field_params(ir) + if ( + unit_stride_dim := next_allocators.unit_stride_dimension(layout_mapper, field_type.dims) + ) + is not None + ) + return kinds.most_common(1)[0][0] if kinds else None def make_sdfg_call_async(sdfg: dace.SDFG, gpu: bool) -> None: @@ -361,9 +380,11 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: #: The parameters of `gt_auto_optimize()` that the translation step derives from #: its own configuration, and which therefore cannot be customized. -_DERIVED_OPTIMIZATION_ARGS: Final[frozenset[str]] = frozenset( - {"gpu", "constant_symbols", "unit_strides_kind"} -) +_DERIVED_OPTIMIZATION_ARGS: Final[frozenset[str]] = frozenset({"gpu", "constant_symbols"}) + +#: The parameters of `gt_auto_optimize()` that the translation step derives from +#: its configuration only when it assumes a memory layout (`layout_mapper` is set). +_LAYOUT_DERIVED_OPTIMIZATION_ARGS: Final[frozenset[str]] = frozenset({"unit_strides_kind"}) #: The accepted values of the `scan_fusion_scope` option in `auto_optimize_args`. _SCAN_FUSION_SCOPES: Final[frozenset[str]] = frozenset({"immediate", "field_operator"}) @@ -441,6 +462,15 @@ def __post_init__(self) -> None: raise ValueError( f"The following optimization arguments cannot be overridden: {derived_args}." ) + if ( + self.auto_optimize_args + and self.layout_mapper is not None + and (derived_args := self.auto_optimize_args.keys() & _LAYOUT_DERIVED_OPTIMIZATION_ARGS) + ): + raise ValueError( + f"The following optimization arguments cannot be overridden when the" + f" backend allocator layout is assumed: {derived_args}." + ) if ( self.auto_optimize_args and (scope := self.auto_optimize_args.get("scan_fusion_scope", "immediate")) @@ -494,11 +524,12 @@ def _generate_sdfg_without_configuring_dace( ) if self.auto_optimize: + if self.layout_mapper is not None: + auto_optimize_args["unit_strides_kind"] = unit_stride_kind(ir, self.layout_mapper) gtx_transformations.gt_auto_optimize( sdfg, gpu=on_gpu, constant_symbols=constant_symbols, - unit_strides_kind=unit_stride_kind(self.layout_mapper), **auto_optimize_args, ) elif on_gpu: From dcb3b209ae77cb26336d32a5b9afa26694bd0f80 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 14:22:00 +0100 Subject: [PATCH 26/28] fix dace tests --- .../dace_tests/test_dace_backend.py | 19 ++++++- .../dace_tests/test_dace_translation.py | 50 +++++++++++++++++-- 2 files changed, 65 insertions(+), 4 deletions(-) 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 a0b59f4ba6..64dee0c343 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 @@ -301,15 +301,32 @@ def test_translator_keeps_explicit_transient_memory_mode(gpu, transient_memory_m def test_make_toolchain_rejects_derived_optimization_args(): + """`unit_strides_kind` is derived from the layout when the allocator layout is assumed.""" with pytest.raises(ValueError, match="cannot be overridden"): dace_wf_backend.make_dace_toolchain( + dace_wf_factory.DaCeConfig(use_backend_allocator_layout=True), translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args={"unit_strides_kind": None}, - ) + ), ) +def test_make_toolchain_accepts_unit_strides_kind_without_layout_assumption(): + toolchain = dace_wf_backend.make_dace_toolchain( + dace_wf_factory.DaCeConfig(use_backend_allocator_layout=False), + translation=functools.partial( + dace_wf_factory.make_dace_translator, + auto_optimize_args={"unit_strides_kind": gtx.common.DimensionKind.HORIZONTAL}, + ), + ) + + assert ( + toolchain.executor.translation.step.auto_optimize_args["unit_strides_kind"] + is gtx.common.DimensionKind.HORIZONTAL + ) + + def test_make_toolchain_uncached_translation(): backend = dace_wf_backend.make_dace_toolchain( dace_wf_factory.DaCeConfig(cached_translation=False) 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 d3858885b1..1d1046dc80 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 @@ -395,9 +395,22 @@ def test_find_constant_symbols_without_horizontal_dim(): ) == {"__x_KDim_stride": 1} +def _make_program_with_params(*param_types: ts.TypeSpec) -> itir.Program: + return itir.Program( + id="unit_stride_kind", + function_definitions=[], + params=[itir.Sym(id=f"x{i}", type=t) for i, t in enumerate(param_types)], + declarations=[], + body=[], + ) + + def test_unit_stride_kind(): - assert dace_wf_translation.unit_stride_kind(None) is None - assert dace_wf_translation.unit_stride_kind(HORIZONTAL_FIRST) is ( + ikftype = ts.FieldType(dims=[IDim, KDim], dtype=FLOAT_TYPE) + ir = _make_program_with_params(ikftype, ts.TupleType(types=[ikftype, FLOAT_TYPE])) + + assert dace_wf_translation.unit_stride_kind(ir, None) is None + assert dace_wf_translation.unit_stride_kind(ir, HORIZONTAL_FIRST) is ( gtx_common.DimensionKind.HORIZONTAL ) @@ -411,9 +424,40 @@ def vertical_innermost_layout_mapper(dims): layout_map[i] = pos return tuple(layout_map) - assert dace_wf_translation.unit_stride_kind(vertical_innermost_layout_mapper) is ( + assert dace_wf_translation.unit_stride_kind(ir, vertical_innermost_layout_mapper) is ( + gtx_common.DimensionKind.VERTICAL + ) + + # without field arguments there is no unit-stride dimension + assert ( + dace_wf_translation.unit_stride_kind( + _make_program_with_params(FLOAT_TYPE), HORIZONTAL_FIRST + ) + is None + ) + + +def test_unit_stride_kind_position_based_layout(): + """The kind follows the unit-stride dimension of the fields, also for a layout + mapper that does not order the dimensions by kind.""" + + def c_order_layout_mapper(dims): + return tuple(range(len(dims))) + + kftype = ts.FieldType(dims=[KDim], dtype=FLOAT_TYPE) + ikftype = ts.FieldType(dims=[IDim, KDim], dtype=FLOAT_TYPE) + ir = _make_program_with_params(ikftype, ikftype, IFTYPE) + + # the last dimension is innermost: `KDim` in two fields, `IDim` in one + assert dace_wf_translation.unit_stride_kind(ir, c_order_layout_mapper) is ( gtx_common.DimensionKind.VERTICAL ) + assert ( + dace_wf_translation.unit_stride_kind( + _make_program_with_params(kftype), c_order_layout_mapper + ) + is gtx_common.DimensionKind.VERTICAL + ) def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: From 9dc8e44baa3e523a1f0d4218bc058343ebe194db Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 14:24:05 +0100 Subject: [PATCH 27/28] edit --- src/gt4py/next/config.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index b3b86bb300..b85b66a99d 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -140,10 +140,10 @@ def _get_build_cache_version_id() -> str: ] -#: Experimental, use at your own risk: 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. +#: 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 ) From d444f3440ce68371e33ce044749d5dab0a170ee3 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 2 Dec 2026 22:42:28 +0100 Subject: [PATCH 28/28] ci: test with GridTools signed static strides and backend allocator layout --- .cscs-ci/default.yml | 2 ++ pyproject.toml | 4 ++++ uv.lock | 10 +++++----- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.cscs-ci/default.yml b/.cscs-ci/default.yml index 6145017c92..fcaa373195 100644 --- a/.cscs-ci/default.yml +++ b/.cscs-ci/default.yml @@ -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] diff --git a/pyproject.toml b/pyproject.toml index 01dff97bc1..81c6087e0c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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] diff --git a/uv.lock b/uv.lock index 863f5e47ed..bde9a5d92c 100644 --- a/uv.lock +++ b/uv.lock @@ -1372,10 +1372,10 @@ wheels = [ [[package]] name = "gridtools-cpp" -version = "2.3.9" -source = { registry = "https://pypi.org/simple" } +version = "2.4.0" +source = { url = "https://github.com/edopao/gridtools/releases/download/gt4py-3071-signed-strides/gridtools_cpp-2.4.0-py3-none-any.whl" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/8f/08ae062f2b7714c2753faeeead091fc5aa6344ec919ff63d242b95990573/gridtools_cpp-2.3.9-py3-none-any.whl", hash = "sha256:e4deefd804670e101083df9eb27d6b454e3d39ae903b4f7b043846a181452286", size = 1044245, upload-time = "2025-04-11T13:55:39.966Z" }, + { url = "https://github.com/edopao/gridtools/releases/download/gt4py-3071-signed-strides/gridtools_cpp-2.4.0-py3-none-any.whl", hash = "sha256:a5d88541c667c89707f44cc5936b17ba77545434f6d8f0856f6b7fcba7a62614" }, ] [[package]] @@ -1436,7 +1436,7 @@ jax-cuda12 = [ ] jax-cuda13 = [ { name = "cupy-cuda13x" }, - { name = "jax", extra = ["cuda13-local"], marker = "extra == 'extra-5-gt4py-jax-cuda13' or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm6') or (extra == 'extra-5-gt4py-cuda12' and extra == 'extra-5-gt4py-rocm7') or (extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7')" }, + { name = "jax", extra = ["cuda13-local"], marker = "extra == 'extra-5-gt4py-jax-cuda13' or extra == 'extra-5-gt4py-cuda12' and (extra == 'extra-5-gt4py-rocm6' or extra == 'extra-5-gt4py-rocm7') or extra == 'extra-5-gt4py-rocm6' and extra == 'extra-5-gt4py-rocm7'" }, ] next = [ { name = "hypothesis" }, @@ -1600,7 +1600,7 @@ requires-dist = [ { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, { name = "frozendict", specifier = ">=2.3" }, - { name = "gridtools-cpp", specifier = "==2.*,>=2.3.9" }, + { name = "gridtools-cpp", url = "https://github.com/edopao/gridtools/releases/download/gt4py-3071-signed-strides/gridtools_cpp-2.4.0-py3-none-any.whl" }, { name = "gt4py", extras = ["cuda12"], marker = "extra == 'jax-cuda12'" }, { name = "gt4py", extras = ["cuda13"], marker = "extra == 'jax-cuda13'" }, { name = "gt4py", extras = ["jax", "standard", "testing"], marker = "extra == 'cartesian'" },