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/src/gt4py/next/backend.py b/src/gt4py/next/backend.py index 11774edce1..368db4136e 100644 --- a/src/gt4py/next/backend.py +++ b/src/gt4py/next/backend.py @@ -255,11 +255,26 @@ class ToolchainConfig: cache_lifetime: config.BuildCacheLifetime = dataclasses.field( default_factory=lambda: config.BUILD_CACHE_LIFETIME ) - #: Assume unit stride in the horizontal dimension of unstructured fields. - unstructured_horizontal_has_unit_stride: bool = dataclasses.field( - default_factory=lambda: config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE + #: Assume that all field and connectivity arguments have the memory layout + #: of the toolchain's allocator, see `layout_mapper`. + use_backend_allocator_layout: bool = dataclasses.field( + default_factory=lambda: config.USE_BACKEND_ALLOCATOR_LAYOUT ) + @property + def layout_mapper(self) -> next_allocators.FieldLayoutMapper | None: + """ + Memory layout the compiled code can assume for its arguments. + + This is the layout mapper of the allocator returned by `make_allocator()` + if `use_backend_allocator_layout` is set, otherwise `None` (no assumption). + It is a plain function, so the toolchain steps can store it and stay + picklable and hashable. + """ + if not self.use_backend_allocator_layout: + return None + return next_allocators.get_layout_mapper(self.make_allocator()) + @property def device_type(self) -> core_defs.DeviceType: if self.gpu: diff --git a/src/gt4py/next/config.py b/src/gt4py/next/config.py index 3076d4a1b8..b85b66a99d 100644 --- a/src/gt4py/next/config.py +++ b/src/gt4py/next/config.py @@ -140,9 +140,12 @@ def _get_build_cache_version_id() -> str: ] -#: Experimental, use at your own risk: assume horizontal dimension has stride 1 -UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE: bool = env_flag_to_bool( - "GT4PY_UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE", default=False +#: Compiled toolchains assume that all field and connectivity arguments have the +#: memory layout of the backend's allocator, and specialize the generated code +#: for it (e.g. static unit strides). Arguments with a different layout are +#: rejected at call time. +USE_BACKEND_ALLOCATOR_LAYOUT: bool = env_flag_to_bool( + "GT4PY_USE_BACKEND_ALLOCATOR_LAYOUT", default=False ) diff --git a/src/gt4py/next/custom_layout_allocators.py b/src/gt4py/next/custom_layout_allocators.py index e0d9644b66..cf0cb01cda 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,36 @@ def pos_of_kind(kind: common.DimensionKind) -> list[int]: __horizontal_first_layout_mapper: FieldLayoutMapper = horizontal_first_layout_mapper +def unit_stride_dimension( + layout_mapper: Optional[FieldLayoutMapper], dims: Sequence[common.Dimension], / +) -> Optional[common.Dimension]: + """Find the dimension with unit stride in the layout given by `layout_mapper`. + + Args: + layout_mapper: The layout mapper of an allocator, see `get_layout_mapper()`, + or `None` if the layout is unknown. + dims: The dimensions of a field, in the order given by its type. + + Returns: + The innermost dimension of the layout of `dims`, or `None` if `dims` is + empty or the layout is unknown. + + Raises: + ValueError: If `layout_mapper` does not return a valid layout map for `dims`. + """ + if layout_mapper is None or not dims: + return None + layout_map = layout_mapper(dims) + if len(layout_map) != len(dims) or not core_allocators.is_valid_layout_map(layout_map): + raise ValueError( + f"Layout mapper '{layout_mapper}' returned an invalid layout map {tuple(layout_map)}" + f" for dimensions {list(dims)}: expected a permutation of 0..{len(dims) - 1}." + ) + innermost = len(dims) - 1 + # The layout map is a valid permutation, so exactly one dimension is innermost. + return next(dim for dim, pos in zip(dims, layout_map) if pos == innermost) + + #: Registry of default allocators for each device type. device_allocators: dict[core_defs.DeviceType, FieldBufferAllocatorProtocol] = {} diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index f67b3383a6..adc4ad14ed 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,20 +204,18 @@ def _tuple_get(index: int, var: str) -> str: def make_argument( - name: str, type_: ts.TypeSpec, unstructured_horizontal_has_unit_stride: bool + name: str, + type_: ts.TypeSpec, + layout_mapper: next_allocators.FieldLayoutMapper | None, ) -> str | BufferSID | Tuple: if isinstance(type_, ts.FieldType): + unit_stride_dim = next_allocators.unit_stride_dimension(layout_mapper, type_.dims) return BufferSID( source_buffer=name, dimensions=[ DimensionSpec( name=dim.value, - static_stride=1 - if ( - unstructured_horizontal_has_unit_stride - and dim.kind == common.DimensionKind.HORIZONTAL - ) - else None, + static_stride=1 if dim == unit_stride_dim else None, ) for dim in type_.dims ], @@ -225,8 +223,7 @@ def make_argument( ) elif isinstance(type_, ts.TupleType): elements = [ - make_argument(_tuple_get(i, name), t, unstructured_horizontal_has_unit_stride) - for i, t in enumerate(type_.types) + make_argument(_tuple_get(i, name), t, layout_mapper) for i, t in enumerate(type_.types) ] return Tuple(elems=elements) elif isinstance(type_, ts.ScalarType): @@ -237,15 +234,23 @@ def make_argument( def create_bindings( program_source: artifacts.ProgramSource[CodeSpecT], - unstructured_horizontal_has_unit_stride: bool, + layout_mapper: next_allocators.FieldLayoutMapper | None, ) -> artifacts.BindingSource[CodeSpecT, artifacts.PythonCodeSpec]: """ Generate Python bindings through which a C++ function can be called. - Parameters - ---------- - program_source - The program source for which the bindings are created + Args: + program_source: The program source for which the bindings are created. + layout_mapper: Memory layout assumed for the field and connectivity + arguments: the innermost dimension gets a static unit stride, see + `custom_layout_allocators.unit_stride_dimension()`. `None` makes no + assumption. + + Returns: + The binding source wrapping the program source. + + Raises: + ValueError: If `program_source` is not a C++-like program source. """ if not isinstance(program_source.code_spec, artifacts.CPPLikeCodeSpec): raise ValueError( @@ -283,9 +288,7 @@ def create_bindings( expr=FunctionCall( target=program_source.entry_point, args=[ - make_argument( - param.name, param.type_, unstructured_horizontal_has_unit_stride - ) + make_argument(param.name, param.type_, layout_mapper) for param in program_source.entry_point.parameters ], ) @@ -321,14 +324,13 @@ class ExtensionGenerator: Generate a Python extension module that contains the bindings for a C++ function. """ - unstructured_horizontal_has_unit_stride: bool = config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE + #: Memory layout assumed for the arguments, see `create_bindings()`. + layout_mapper: next_allocators.FieldLayoutMapper | None = None def __call__( self, program_source: artifacts.ProgramSource[CodeSpecT] ) -> artifacts.ExtensionSource[CodeSpecT, artifacts.PythonCodeSpec]: - binding_source = create_bindings( - program_source, self.unstructured_horizontal_has_unit_stride - ) + binding_source = create_bindings(program_source, self.layout_mapper) return artifacts.ExtensionSource( program_source=program_source, binding_source=binding_source ) 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 aebcfdb5f3..f1c6978791 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,22 +32,6 @@ def get_param_description(name: str, type_: Any) -> interface.Parameter: return interface.Parameter(name, type_) -@dataclasses.dataclass(frozen=True) -class GTFNProgramSource(artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec]): - """ - Program source emitted by the GTFN translation step. - - It extends the generic `ProgramSource` with properties of the translated program - that only the GTFN toolchain needs, e.g. the grid type, which the GTFN bindings - step uses to decide whether the horizontal dimensions have unit stride. - - TODO(edopao): This subclass should be removed once the unit-stride dimensions - are derived from the backend allocator layout, which is the long-term solution. - """ - - grid_type: common.GridType - - @dataclasses.dataclass(frozen=True) class GTFNTranslationStep( workflow.ReplaceEnabledWorkflowMixin[ @@ -190,7 +173,9 @@ def generate_stencil_source( return GTFNCodegen.apply(gtfn_ir) - def __call__(self, inp: stages.CompilableProgramDef) -> GTFNProgramSource: + def __call__( + self, inp: stages.CompilableProgramDef + ) -> artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec]: """Generate GTFN C++ code from the ITIR definition.""" program: itir.Program = inp.data @@ -232,13 +217,15 @@ def __call__(self, inp: stages.CompilableProgramDef) -> GTFNProgramSource: ] ) - return GTFNProgramSource( - entry_point=function, - library_deps=(interface.LibraryDependency(self._library_name(), "master"),), - source_code=source_code, - code_spec=self._code_spec(), - grid_type=ir_misc.grid_type_from_program(program), + module: artifacts.ProgramSource[artifacts.HeaderAndSourceCodeSpec] = ( + artifacts.ProgramSource( + entry_point=function, + library_deps=(interface.LibraryDependency(self._library_name(), "master"),), + source_code=source_code, + code_spec=self._code_spec(), + ) ) + return module def _backend_header(self) -> str: match self.device_type: 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 2f56671da8..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 @@ -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,21 @@ 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. + 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: 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/src/gt4py/next/program_processors/runners/dace/workflow/backend.py b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py index 2665354f91..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, 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, - unstructured_horizontal_has_unit_stride: bool = config.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE, use_metrics: bool = True, use_zero_origin: bool = False, use_max_domain_range_on_unstructured_shift: bool | None = None, @@ -102,8 +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`. - unstructured_horizontal_has_unit_stride: When the memory layout has unit stride - in the horizontal dimension, replace the field stride symbol with '1'. use_metrics: Add SDFG instrumentation to collect the metric for stencil compute time. use_zero_origin: Can be set to `True` when all fields passed as program @@ -133,7 +130,6 @@ def make_dace_backend( gpu=gpu, auto_optimize=auto_optimize, external_workspace=external_workspace, - unstructured_horizontal_has_unit_stride=unstructured_horizontal_has_unit_stride, ), translation=functools.partial( gtx_wfdfactory.make_dace_translator, 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..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,10 +135,10 @@ 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, 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 9ba6cc48ea..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,16 +8,16 @@ from __future__ import annotations +import collections import dataclasses from typing import Any, Final, Literal, Optional 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.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 @@ -30,17 +30,8 @@ from gt4py.next.type_system import type_specifications as ts -def find_constant_symbols( - ir: itir.Program, - sdfg: dace.SDFG, - offset_provider_type: common.OffsetProviderType, - disable_field_origin_on_program_arguments: bool, - unstructured_horizontal_has_unit_stride: bool, -) -> dict[str, int]: - """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 +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 = ( @@ -51,31 +42,49 @@ def find_constant_symbols( 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, + offset_provider_type: common.OffsetProviderType, + disable_field_origin_on_program_arguments: bool, + layout_mapper: next_allocators.FieldLayoutMapper | None, +) -> dict[str, int]: + """ + 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] = {} + field_params = _field_params(ir) - if ( - unstructured_horizontal_has_unit_stride - and ir_misc.grid_type_from_program(ir) == common.GridType.UNSTRUCTURED - ): - # Search the stride symbols corresponding to the horizontal dimension + if layout_mapper 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) == 1: - sdfg_stride_symbol = gtx_dace_args.field_stride_symbol(name, h_dims[0]) - constant_symbols[sdfg_stride_symbol.name] = 1 - elif len(h_dims) > 1: - raise NotImplementedError( - f"Unsupported field with multiple horizontal dimensions '{name}'." + if ( + unit_stride_dim := next_allocators.unit_stride_dimension( + layout_mapper, field_type.dims ) - # Same for connectivity tables, for which the first dimension is always horizontal + ) 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, 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 + 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, conn_type.source_dim, offset_provider_type + conn_id, unit_stride_dim, offset_provider_type ) constant_symbols[sdfg_stride_symbol.name] = 1 @@ -89,6 +98,41 @@ def find_constant_symbols( return constant_symbols +def unit_stride_kind( + ir: itir.Program, + layout_mapper: next_allocators.FieldLayoutMapper | None, +) -> common.DimensionKind | None: + """ + 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 + 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()`. + + 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 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. + """ + 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: """Configure an SDFG to immediately return once all work has been scheduled. @@ -336,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"}) @@ -402,11 +448,12 @@ class DaCeTranslator( auto_optimize: bool auto_optimize_args: dict[str, Any] | None async_sdfg_call: bool - unstructured_horizontal_has_unit_stride: bool use_metrics: bool 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 ( @@ -415,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")) @@ -464,19 +520,16 @@ def _generate_sdfg_without_configuring_dace( sdfg, offset_provider_type, self.disable_field_origin_on_program_arguments, - self.unstructured_horizontal_has_unit_stride, + self.layout_mapper, ) 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=( - common.DimensionKind.HORIZONTAL - if self.unstructured_horizontal_has_unit_stride - else None - ), **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 af4a2ae0fb..e6bda8125e 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -167,45 +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. - - TODO(edopao): This class should be removed once the unit-stride dimensions - are derived from the backend allocator layout, which is the long-term solution. - """ - - 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 + layout_mapper=cfg.layout_mapper ) 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( 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..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 @@ -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,64 @@ 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_backend_allocator_layout_cartesian(): + """ + 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. + """ + nx = 6 + ny = 7 + backend = gtfn.make_gtfn_toolchain( + gtfn.GTFNConfig(use_backend_allocator_layout=True), + name_postfix="_backend_allocator_layout", + ) + + # 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)}), + ) + 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_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(use_backend_allocator_layout=True), + name_postfix="_backend_allocator_layout_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..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,7 +14,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, 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 ba83a07b2d..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,7 +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.UNSTRUCTURED_HORIZONTAL_HAS_UNIT_STRIDE - ), + binding_source=nanobind.create_bindings(program_source_example, None), ) 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..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 @@ -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( @@ -55,11 +56,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 +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) + # 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, - unstructured_horizontal_has_unit_stride=on_gpu, + use_backend_allocator_layout=True, ), translation=functools.partial( dace_wf_factory.make_dace_translator, @@ -136,9 +138,11 @@ 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={}, + 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"], @@ -151,12 +155,16 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: mock_auto_optimize.assert_called_once_with( sdfg, gpu=on_gpu, - constant_symbols={}, + constant_symbols={ + "__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_kind=gtx.common.DimensionKind.HORIZONTAL, ) mock_top_level_dataflow_hook1.assert_not_called() mock_top_level_dataflow_hook2.assert_called_once_with(sdfg) @@ -293,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) @@ -318,15 +343,12 @@ 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, 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 - ), + dace_wf_factory.DaCeConfig(external_workspace=workspace), translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args={"blocking_size": 10}, @@ -356,7 +378,6 @@ 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, use_metrics=False, ) translator = dace_wf_backend.run_dace_cpu.executor.translation.step @@ -601,3 +622,71 @@ 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, + use_backend_allocator_layout=True, + ), + name_postfix=f"_backend_allocator_layout_{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_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 + 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_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) + + 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_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) + + 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 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..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 @@ -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(use_backend_allocator_layout=False), 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(use_backend_allocator_layout=False), 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, 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 c48f3e18c1..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 @@ -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,10 +41,11 @@ 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) -EVFTYPE = ts.FieldType(dims=[Edge, Vertex], dtype=FLOAT_TYPE) -VFTYPE = ts.FieldType(dims=[Vertex], dtype=FLOAT_TYPE) +IJFTYPE = ts.FieldType(dims=[IDim, JDim], dtype=FLOAT_TYPE) @pytest.fixture( @@ -74,7 +75,6 @@ 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, use_metrics=use_metrics, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -104,9 +104,9 @@ def _make_unstructured_program(program_id: str) -> itir.Program: ) -@pytest.mark.parametrize("has_unit_stride", [False, True]) +@pytest.mark.parametrize("layout_mapper", [None, HORIZONTAL_FIRST], 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(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") @@ -124,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, + layout_mapper=layout_mapper, ) expected = {} - if has_unit_stride: + if layout_mapper is not None: # The vertical dimension stride symbols must not be set to 1. expected |= { "__x_Edge_stride": 1, @@ -166,25 +166,46 @@ def _make_cartesian_program(program_id: str) -> itir.Program: @pytest.mark.parametrize( - "grid_type", [gtx_common.GridType.CARTESIAN, gtx_common.GridType.UNSTRUCTURED] + "grid_type, layout_mapper, expected_horizontal_unit_stride", + [ + (gtx_common.GridType.UNSTRUCTURED, HORIZONTAL_FIRST, True), + (gtx_common.GridType.UNSTRUCTURED, None, False), + (gtx_common.GridType.CARTESIAN, None, False), + # 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_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, 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_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, @@ -201,8 +222,8 @@ def test_translation_grid_type(grid_type): auto_optimize=False, auto_optimize_args=None, async_sdfg_call=False, - unstructured_horizontal_has_unit_stride=True, use_metrics=False, + layout_mapper=layout_mapper, ) program_source = translator(compilable_program) @@ -216,21 +237,61 @@ def test_translation_grid_type(grid_type): assert strides == expected_strides -@pytest.mark.parametrize("has_unit_stride", [False, True]) +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( + 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=True, + auto_optimize_args=None, + async_sdfg_call=False, + use_metrics=False, + layout_mapper=HORIZONTAL_FIRST, + ) + + 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" + assert all(params[-1] == idim_map_variable for params in map_params) + + +@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(has_unit_stride, 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( - 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=[], @@ -252,9 +313,9 @@ 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, 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( @@ -262,12 +323,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, + layout_mapper=layout_mapper, ) field_names = ["x_0", "y_0", "y_1_0", "y_1_1"] expected = {} - if has_unit_stride: + 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} @@ -275,37 +336,30 @@ 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 layout_mapper is not None else f"__{name}_Vertex_stride" assert [str(stride) for stride in sdfg.arrays[name].strides] == [expected_stride] @pytest.mark.parametrize( - "param_type, field_name", + "param_type, field_names", [ - pytest.param(EVFTYPE, "x", id="field"), - pytest.param(ts.TupleType(types=[IFTYPE, EVFTYPE]), "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, EVFTYPE])]), - "x_1_1", + ts.TupleType(types=[IFTYPE, ts.TupleType(types=[IFTYPE, IJFTYPE])]), + ["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=[], - params=[itir.Sym(id="x", type=param_type), itir.Sym(id="y", type=VFTYPE)], + params=[itir.Sym(id="x", type=param_type)], declarations=[], - # unit stride is only applied to unstructured programs, so add an unstructured domain - body=[ - itir.SetAt( - expr=im.ref("y"), - domain=im.get_field_domain(gtx_common.GridType.UNSTRUCTURED, "y", VFTYPE.dims), - target=itir.SymRef(id="y"), - ) - ], + body=[], ) kwargs = { "ir": ir, @@ -314,19 +368,95 @@ 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, 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( + 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} + + +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(): + 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 + ) + + 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(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.""" - # the same field is supported when the unit-stride option is disabled + 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.find_constant_symbols( - **kwargs, unstructured_horizontal_has_unit_stride=False + dace_wf_translation.unit_stride_kind( + _make_program_with_params(kftype), c_order_layout_mapper ) - == {} + is gtx_common.DimensionKind.VERTICAL ) @@ -684,7 +814,6 @@ 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, 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..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, - unstructured_horizontal_has_unit_stride=False, 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, - unstructured_horizontal_has_unit_stride=False, 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, - unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) 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..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 @@ -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(): @@ -117,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"]) @@ -135,3 +196,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 b93f637cb0..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 @@ -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 @@ -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. @@ -212,33 +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( - "grid_type, dims, has_unit_stride, expected_stride_spec", + "dims, use_backend_allocator_layout, 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}", - ), + # 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}"), + # 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(grid_type, dims, has_unit_stride, expected_stride_spec): - program_source = gtfn_module.GTFNProgramSource( +def test_bindings_static_strides(dims, use_backend_allocator_layout, expected_stride_spec): + program_source = artifacts.ProgramSource( entry_point=interface.Function( "stencil", parameters=( @@ -251,10 +274,9 @@ 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) + gtfn.GTFNConfig(use_backend_allocator_layout=use_backend_allocator_layout) ) extension = bindings(program_source) diff --git a/tests/next_tests/unit_tests/test_config.py b/tests/next_tests/unit_tests/test_config.py index f353086309..8d0dfcd20e 100644 --- a/tests/next_tests/unit_tests/test_config.py +++ b/tests/next_tests/unit_tests/test_config.py @@ -50,6 +50,27 @@ 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, "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: + 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, + ) + + assert result.stdout.strip() == expected + + 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"} 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 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'" },