From f918acf6c51114b3ea21b87b8931edeb0d6be877 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 24 Sep 2026 16:25:20 +0200 Subject: [PATCH 01/69] update uv lock --- uv.lock | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/uv.lock b/uv.lock index 9b19c7ef58..d29c3f72bf 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { registry = "https://pypi.org/simple" } +source = { git = "https://github.com/spcl/dace.git?branch=nested-sdfg#ee0d1a27c7210219bfe4279181380ccf1e01e061" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -943,7 +943,6 @@ dependencies = [ { name = "sympy" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f3/29/83c0d23a228c5f5cd5f6bdae1a124fcc2dd45fba239bc2b05925b99a3451/dace-2.0.0a10.tar.gz", hash = "sha256:8cfe968729be96ac66c5fd8c0f7c85c705182d30e9a49e3418cd4aafda238c30", size = 6616842, upload-time = "2026-10-03T13:32:04.812Z" } [[package]] name = "debugpy" @@ -1469,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", specifier = "==2.0.0a10" }, + { name = "dace", git = "https://github.com/spcl/dace.git?branch=nested-sdfg" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 94551f66efdb40e69aa7fe320fd390bbf7553f82 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 8 May 2026 12:14:54 +0200 Subject: [PATCH 02/69] remove workaround --- .../dace/lowering/gtir_to_sdfg_lambda.py | 20 ++++--------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py index 1eb4900233..884d69cc8f 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py @@ -755,12 +755,7 @@ def _visit_if_branch_arg( inner_desc = arg_desc.clone() inner_desc.transient = False elif isinstance(arg.gt_dtype, ts.ScalarType): - if isinstance(arg, MemletExpr) and len(arg.gt_field.dims) == 1: - # TODO(edopao): we cannot use a scalar because of an issue in gpu codegen, - # which leads to compilation error: cannot convert 'const double' to 'const double*' - inner_desc = dace.data.Array(dtype=arg_desc.dtype, shape=(1,)) - else: - inner_desc = dace.data.Scalar(arg_desc.dtype) + inner_desc = dace.data.Scalar(arg_desc.dtype) else: # for list of values, we retrieve the local size from the corresponding offset local_dim = arg.gt_dtype.offset_type @@ -883,16 +878,9 @@ def _visit_if_branch_result( # If the result is currently written to a transient node, inside the nested SDFG, # we need to allocate a non-transient data node. result_desc = edge.result.dc_node.desc(sdfg) - if isinstance(sym.type, ts.ScalarType) and isinstance(result_desc, dace.data.Array): - # TODO(edopao): a scalar should not be represented as an array, but - # currently this can happen because of an issue workaround, see the - # todo comment above in `_visit_if_branch_arg()`. - assert len(result_desc.shape) == 1 and result_desc.shape[0] == 1 - _, output_desc = sdfg.add_scalar(output_data, result_desc.dtype) - else: - output_desc = result_desc.clone() - output_desc.transient = False - output_data = sdfg.add_datadesc(output_data, output_desc, find_new_name=True) + output_desc = result_desc.clone() + output_desc.transient = False + output_data = sdfg.add_datadesc(output_data, output_desc, find_new_name=True) output_node = state.add_access(output_data) state.add_nedge( edge.result.dc_node, From 972e8dca5bb6b08e658662851f70ebef4a591a7b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 25 Sep 2026 15:08:21 +0200 Subject: [PATCH 03/69] edit lowering --- .../runners/dace/lowering/gtir_to_sdfg.py | 33 +++++-- .../dace/lowering/gtir_to_sdfg_lambda.py | 56 +++++------- .../dace/lowering/gtir_to_sdfg_scan.py | 91 ++++++++----------- 3 files changed, 85 insertions(+), 95 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py index e645068f64..79713895ea 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py @@ -106,14 +106,14 @@ def unique_lib_node_name(self, lib_node_type: str) -> str: ... def add_temp_array( self, sdfg: dace.SDFG, shape: Sequence[Any], dtype: dace.dtypes.typeclass - ) -> tuple[str, dace.data.Scalar]: + ) -> tuple[str, dace.data.Array]: """Add a temporary array to the SDFG.""" temp_name = self.unique_temp_name() return sdfg.add_transient(temp_name, shape, dtype) def add_temp_array_like( self, sdfg: dace.SDFG, datadesc: dace.data.Array - ) -> tuple[str, dace.data.Scalar]: + ) -> tuple[str, dace.data.Array]: """Add a temporary array to the SDFG.""" temp_name = self.unique_temp_name() return sdfg.add_temp_transient_like(datadesc, name=temp_name) @@ -432,7 +432,11 @@ def add_nested_sdfg( data_args: Mapping[str, gtir_to_sdfg_types.FieldopData | None], inner_result: gtir_to_sdfg_types.FieldopResult, capture_outer_data: bool, - ) -> tuple[dace_nodes.NestedSDFG, Mapping[str, dace.Memlet]]: + ) -> tuple[ + dace_nodes.NestedSDFG, + Mapping[str, dace.Memlet], + dict[str, dace.symbolic.SymbolicType], + ]: """ Helper function that prepares the input connections and symbol mapping before calling `SDFG.add_nestd_sdfg()` to add the given SDFG as a nested SDFG node @@ -449,9 +453,12 @@ def add_nested_sdfg( capture_outer_data: Allow capturing scalars and arrays defined in the parent SDFG. Returns: - A tuple of two elements: + A tuple of three elements: - The nested SDFG graph node. - The mapping from input connectors to data memlets. + - The full symbol mapping from the nested SDFG to this context. Note that + this is not the same as `NestedSDFG.symbol_mapping`, which only retains + the entries that dace did not already apply inside the nested SDFG. """ ... @@ -701,7 +708,11 @@ def add_nested_sdfg( data_args: Mapping[str, gtir_to_sdfg_types.FieldopData | None], inner_result: gtir_to_sdfg_types.FieldopResult, capture_outer_data: bool, - ) -> tuple[dace_nodes.NestedSDFG, Mapping[str, dace.Memlet]]: + ) -> tuple[ + dace_nodes.NestedSDFG, + Mapping[str, dace.Memlet], + dict[str, dace.symbolic.SymbolicType], + ]: assert data_args.keys().isdisjoint(symbolic_args.keys()) # Collect the names of all output data, by flattening any tuple structure. @@ -800,7 +811,7 @@ def add_nested_sdfg( debuginfo=gtir_to_sdfg_utils.debug_info(node, default=outer_ctx.sdfg.debuginfo), ) - return nsdfg_node, input_memlets + return nsdfg_node, input_memlets, nsdfg_symbols_mapping def unique_nsdfg_name(self, prefix: str) -> str: return next(self.uids[prefix]) @@ -1284,7 +1295,7 @@ def visit_Lambda( # A let-lambda is allowed to capture GTIR-symbols from the outer scope, # therefore we call `add_nested_sdfg()` with `capture_outer_data=True`. - nsdfg_node, input_memlets = self.add_nested_sdfg( + nsdfg_node, input_memlets, nsdfg_symbols_mapping = self.add_nested_sdfg( node=node, inner_ctx=lambda_ctx, outer_ctx=ctx, @@ -1351,11 +1362,17 @@ def construct_output_for_nested_sdfg( # the corresponding data container inside the nested SDFG has to be changed to non-transient, # that is externally allocated, as required by the SDFG IR. An output edge will write the result # from the nested-SDFG to a new intermediate data container allocated in the parent SDFG. + # NOTE: We use the symbol mapping returned by `add_nested_sdfg()` rather than + # `nsdfg_node.symbol_mapping`: dace applies the mapping of the symbols that + # the nested SDFG uses directly inside it, and only keeps the remaining + # entries on the node. The field origin is not visible to dace, because it + # is not part of any data descriptor, so it has to be translated here with + # the full mapping. outer_data = ctx.map_nsdfg_field( sdfg_builder=self, nsdfg_field=inner_data, nsdfg=lambda_ctx.sdfg, - symbol_mapping=nsdfg_node.symbol_mapping, + symbol_mapping=nsdfg_symbols_mapping, ) ctx.state.add_edge( nsdfg_node, diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py index 884d69cc8f..328f9255ae 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py @@ -713,7 +713,7 @@ def _visit_if_branch_arg( arg: IteratorExpr | DataExpr, deref_on_input_memlet: bool, input_memlets: dict[str, MemletExpr | ValueExpr], - ) -> IteratorExpr | ValueExpr: + ) -> IteratorExpr | MemletExpr | ValueExpr: """ Helper method to be called by `_visit_if_branch()` to visit the input arguments. @@ -725,13 +725,10 @@ def _visit_if_branch_arg( deref_on_input_memlet: When True, the given iterator argument can be dereferenced on the input memlet. input_memlets: The memlets that provide input data to the SDFG, will be updated inside this function. """ - use_full_shape = False if isinstance(arg, (MemletExpr, ValueExpr)): - field_dims = [] arg_desc = arg.dc_node.desc(self.sdfg) arg_expr = arg elif isinstance(arg, IteratorExpr): - field_dims = [dim for dim, _ in arg.field_domain] arg_desc = arg.field.desc(self.sdfg) if deref_on_input_memlet: # If the iterator is just dereferenced inside the branch state, @@ -747,44 +744,24 @@ def _visit_if_branch_arg( arg_expr = MemletExpr( arg.field, arg.get_field_type(), dace_subsets.Range.from_array(arg_desc) ) - use_full_shape = True else: raise TypeError(f"Unexpected {arg} as input argument.") - if use_full_shape: - inner_desc = arg_desc.clone() - inner_desc.transient = False - elif isinstance(arg.gt_dtype, ts.ScalarType): - inner_desc = dace.data.Scalar(arg_desc.dtype) - else: - # for list of values, we retrieve the local size from the corresponding offset - local_dim = arg.gt_dtype.offset_type - assert local_dim is not None - assert isinstance( - self.subgraph_builder.get_offset_provider_type(local_dim.value), - gtx_common.NeighborConnectivityType, - ) - # find position of the local dimension in the field layout - assert isinstance(arg_desc, dace.data.Array) - assert all(dim.kind != gtx_common.DimensionKind.LOCAL for dim in field_dims) - extended_dims = gtx_common.order_dimensions([*field_dims, local_dim]) - local_dim_pos = extended_dims.index(local_dim) - inner_desc = dace.data.Array( - dtype=arg_desc.dtype, - shape=(arg_desc.shape[local_dim_pos],), - strides=(arg_desc.strides[local_dim_pos],), - ) - - if param_name in sdfg.arrays: - # the data desciptor was added by the visitor of the other branch expression - assert sdfg.data(param_name) == inner_desc - else: + inner_desc = arg_desc.clone() + inner_desc.transient = False + if param_name not in sdfg.arrays: sdfg.add_datadesc(param_name, inner_desc) input_memlets[param_name] = arg_expr inner_node = state.add_access(param_name) - if isinstance(arg, IteratorExpr) and use_full_shape: + if isinstance(arg, IteratorExpr): return IteratorExpr(inner_node, arg.gt_dtype, arg.field_domain, arg.indices) + elif isinstance(arg_expr, MemletExpr): + # The data descriptor inside the nested SDFG is a copy of the full outer + # container, because a nested SDFG connector has to be equivalent to the + # data it is connected to. Therefore the value has to be addressed with + # the same subset as on the outside, rather than as a single element. + return MemletExpr(inner_node, arg_expr.gt_field, copy.deepcopy(arg_expr.subset)) else: return ValueExpr(inner_node, arg.gt_dtype) @@ -958,6 +935,17 @@ def write_output_of_nested_sdfg_to_temporary(inner_value: ValueExpr) -> ValueExp nsdfg.add_symbol("__cond", dace.dtypes.bool) else: nsdfg.add_scalar("__cond", dace.dtypes.bool) + if isinstance(condition_value, MemletExpr): + # The condition is read from a field. We copy it to a scalar data + # container, because the `__cond` connector has to be equivalent to + # the data it is connected to, and it is accessed as a single value + # in the condition expression of the branch. + cond_data, _ = self.subgraph_builder.add_temp_scalar(self.sdfg, dace.dtypes.bool) + cond_node = self.state.add_access(cond_data) + self._add_input_data_edge( + condition_value.dc_node, condition_value.subset, cond_node + ) + condition_value = ValueExpr(cond_node, condition_value.gt_dtype) input_memlets["__cond"] = condition_value # Collect all field iterators that are shifted inside any of the then/else diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index ba50b21dee..57d3bd7b00 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -26,6 +26,7 @@ from typing import Iterable, Sequence import dace +import sympy from dace import nodes as dace_nodes, subsets as dace_subsets from gt4py import eve @@ -38,7 +39,6 @@ ir_makers as im, ) from gt4py.next.iterator.transforms import infer_domain -from gt4py.next.program_processors.runners.dace import sdfg_utils as gtx_dace_utils from gt4py.next.program_processors.runners.dace.lowering import ( gtir_domain, gtir_to_sdfg, @@ -136,13 +136,14 @@ def _create_scan_field_operator_impl( raise TypeError( f"Type mismatch, expected {output_type.dtype} got {output_edge.result.gt_dtype}." ) - # the scan field operator computes a column of scalar values - assert len(outer_output_desc.shape) == 1 + # the scan nested SDFG writes a column of scalar values into an array with + # the shape of the full field (see `_lower_lambda_to_nested_sdfg()`) + assert len(outer_output_desc.shape) == len(field_domain) else: raise NotImplementedError("scan with list output is not supported") # the memory layout of the output field follows the field operator compute domain - field_dims, field_origin, field_shape = gtir_domain.get_field_layout(field_domain) + field_dims, field_origin, _field_shape = gtir_domain.get_field_layout(field_domain) field_subset = gtir_domain.get_element_subset(field_dims, field_origin) # the vertical dimension used as scan column is computed by the `LoopRegion` @@ -152,14 +153,12 @@ def _create_scan_field_operator_impl( # The map scope writes the full-shape dimension corresponding to the scan column. field_subset = ( dace_subsets.Range(field_subset[:scan_dim_index]) - + dace_subsets.Range.from_string(f"0:{outer_output_desc.shape[0]}") + + dace_subsets.Range.from_string(f"0:{outer_output_desc.shape[scan_dim_index]}") + dace_subsets.Range(field_subset[scan_dim_index + 1 :]) ) # Create the final data storage, that is outside of the surrounding Map. - field_name, field_desc = sdfg_builder.add_temp_array( - ctx.sdfg, field_shape, outer_output_desc.dtype - ) + field_name, _field_desc = sdfg_builder.add_temp_array_like(ctx.sdfg, outer_output_desc) field_node = ctx.state.add_access(field_name) # Now connect the output connector on the nested SDFG with the result field @@ -172,32 +171,6 @@ def _create_scan_field_operator_impl( if not inner_map_output_temporary_removed: raise ValueError("The scan nested SDFG is expected to write directly to the result field.") - assert ctx.state.in_degree(field_node) == 1 - field_node_path = ctx.state.memlet_path(next(iter(ctx.state.in_edges(field_node)))) - assert field_node_path[-1].dst is field_node - - # The temporary node which the nested SDFG was writing to has been deleted, - # and the nested SDFG will write directly to the result field. Thus, we have - # to modify the stride of the scan column array inside the nested SDFG to match - # the stride outside in the corresponding field dimension. - nsdfg_scan = field_node_path[0].src - assert isinstance(nsdfg_scan, dace_nodes.NestedSDFG) - inner_output_name = field_node_path[0].src_conn - inner_output_desc = nsdfg_scan.sdfg.arrays[inner_output_name] - assert len(inner_output_desc.shape) == 1 - - if isinstance(inner_output_desc, dace.data.Array): - # The result field on the outside is a transient array, allocated inside this - # function, so we know that its stride is constant. We just need to set it on - # the inside array, and we do not need to map any stride symbol. - outside_output_stride = field_desc.strides[scan_dim_index] - assert gtx_dace_utils.is_compile_time_size(outside_output_stride) - inner_output_desc.set_shape(inner_output_desc.shape, strides=(outside_output_stride,)) - else: - # Special case where we only write the last level of the scan column. - assert isinstance(inner_output_desc, dace.data.Scalar) - assert bool(field_shape[scan_dim_index] == 1) - return gtir_to_sdfg_types.FieldopData( field_node, ts.FieldType(field_dims, output_edge.result.gt_dtype), tuple(field_origin) ) @@ -369,7 +342,12 @@ def _lower_lambda_to_nested_sdfg( init_state = lambda_ctx.state # use the vertical dimension in the domain as scan dimension - scan_domain = next(r for r in field_domain if sdfg_builder.is_column_axis(r.dim)) + scan_dim_index = [sdfg_builder.is_column_axis(r.dim) for r in field_domain].index(True) + scan_domain = field_domain[scan_dim_index] + + # extract the field layout and subset, to be used for the output of the scan operator + field_dims, field_origin, field_shape = gtir_domain.get_field_layout(field_domain) + field_subset = gtir_domain.get_element_subset(field_dims, field_origin) # extract the scan loop range scan_loop_var = gtir_to_sdfg_utils.get_map_variable(scan_domain.dim) @@ -377,17 +355,20 @@ def _lower_lambda_to_nested_sdfg( # in case the scan operator computes a list (not a scalar), we need to add an extra dimension def get_scan_output_shape( scan_init_data: gtir_to_sdfg_types.FieldopData, - ) -> list[dace.symbolic.SymExpr]: - scan_column_size = scan_domain.stop - scan_domain.start + ) -> list[dace.symbolic.SymbolicType]: if isinstance(scan_init_data.gt_type, ts.ScalarType): - return [scan_column_size] + return field_shape assert isinstance(scan_init_data.gt_type, ts.ListType) assert scan_init_data.gt_type.offset_type offset_type = scan_init_data.gt_type.offset_type offset_provider_type = sdfg_builder.get_offset_provider_type(offset_type.value) assert isinstance(offset_provider_type, gtx_common.NeighborConnectivityType) list_size = offset_provider_type.max_neighbors - return [scan_column_size, dace.symbolic.SymExpr(list_size)] + return [ + *field_shape[:scan_dim_index], + sympy.Integer(list_size), + *field_shape[scan_dim_index + 1 :], + ] if isinstance(init_data, tuple): lambda_result_shape = gtx_utils.tree_map(get_scan_output_shape)(init_data) @@ -473,22 +454,27 @@ def init_scan_carry(sym: gtir.Sym) -> None: else: init_scan_carry(scan_carry_input) - # connect the dataflow output nodes, called 'scan_result' below, to a global field called 'output' - output_column_index = dace.symbolic.pystr_to_symbolic(scan_loop_var) - scan_domain.start - def connect_scan_output( scan_output_edge: gtir_to_sdfg_lambda.DataflowOutputEdge, scan_output_shape: list[dace.symbolic.SymExpr], scan_carry_sym: gtir.Sym, ) -> gtir_to_sdfg_types.FieldopData: scan_result = scan_output_edge.result - if isinstance(scan_result.gt_dtype, ts.ScalarType): - assert scan_result.gt_dtype == scan_carry_sym.type - # the scan field operator computes a column of scalar values - assert len(scan_output_shape) == 1 - output_subset = dace_subsets.Range.from_string(str(output_column_index)) + assert scan_result.gt_dtype == scan_carry_sym.type + if isinstance(scan_result.gt_dtype, ts.ListType): + assert len(scan_output_shape) == len(field_subset) + 1 + output_subset = [ + dace_subsets.Range(field_subset[:scan_dim_index]), + dace_subsets.Range([(0, scan_output_shape[scan_dim_index] - 1, 1)]), + dace_subsets.Range(field_subset[scan_dim_index:]), + ] else: - raise NotImplementedError("scan with list output is not supported.") + assert isinstance(scan_result.gt_dtype, ts.ScalarType) + assert len(scan_output_shape) == len(field_subset) + # This function is called once per field of a tuple result, so the subset + # has to be copied: DaCe rejects an SDFG where two memlets refer to the + # same subset object. + output_subset = copy.deepcopy(field_subset) scan_result_data = scan_result.dc_node.data scan_result_desc = scan_result.dc_node.desc(lambda_ctx.sdfg) scan_result_subset = dace_subsets.Range.from_array(scan_result_desc) @@ -557,7 +543,7 @@ def _handle_dataflow_result_of_nested_sdfg( # The field is used outside the nested SDFG, therefore it needs to be copied # to a temporary array in the parent SDFG (outer context). - field_dims, _, field_shape = gtir_domain.get_field_layout( + field_dims, _field_origin, field_shape = gtir_domain.get_field_layout( gtir_domain.get_field_domain(output_domain) ) scan_dim_index = [sdfg_builder.is_column_axis(dim) for dim in field_dims].index(True) @@ -612,10 +598,9 @@ def _handle_dataflow_result_of_nested_sdfg( else: inner_desc.transient = False - outer_dataname, outer_desc = sdfg_builder.add_temp_array( - outer_ctx.sdfg, (scan_column_size,), inner_desc.dtype - ) + outer_dataname, outer_desc = sdfg_builder.add_temp_array_like(outer_ctx.sdfg, inner_desc) outer_node = outer_ctx.state.add_access(outer_dataname) + outer_ctx.state.add_edge( nsdfg_node, inner_dataname, @@ -717,7 +702,7 @@ def translate_scan( # The lambda expression of a scan field operator should never capture symbols # from the ouside scope, therefore we call `add_nested_sdfg()` with `capture_outer_data=False`. - nsdfg_node, input_memlets = sdfg_builder.add_nested_sdfg( + nsdfg_node, input_memlets, _ = sdfg_builder.add_nested_sdfg( node=stencil_expr, inner_ctx=lambda_ctx, outer_ctx=ctx, From 7ece292aedf0b2f12acfcaaee722f889e491c6e5 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 25 Sep 2026 15:49:48 +0200 Subject: [PATCH 04/69] code refactoring --- .../runners/dace/lowering/gtir_to_sdfg.py | 7 +- .../dace/lowering/gtir_to_sdfg_fieldop.py | 288 ++++++++++++++++++ .../dace/lowering/gtir_to_sdfg_primitives.py | 185 ++--------- .../dace/lowering/gtir_to_sdfg_scan.py | 228 ++------------ 4 files changed, 334 insertions(+), 374 deletions(-) create mode 100644 src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py index 79713895ea..dda7bae3d4 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py @@ -50,6 +50,7 @@ gtir_domain, gtir_to_sdfg_concat_where, gtir_to_sdfg_primitives, + gtir_to_sdfg_scan, gtir_to_sdfg_types, gtir_to_sdfg_utils, ) @@ -1243,7 +1244,11 @@ def visit_FunCall( if cpm.is_let(node): return self._visit_let(node, ctx) if cpm.is_applied_as_fieldop(node): - return gtir_to_sdfg_primitives.translate_as_fieldop(node, ctx, self) + return ( + gtir_to_sdfg_scan.translate_scan_fieldop(node, ctx, self) + if cpm.is_call_to(node.fun.args[0], "scan") + else gtir_to_sdfg_primitives.translate_as_fieldop(node, ctx, self) + ) # Name-matched builtins if isinstance(node.fun, gtir.SymRef): name = str(node.fun.id) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py new file mode 100644 index 0000000000..40259b8b0b --- /dev/null +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py @@ -0,0 +1,288 @@ +# 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 + +"""Construction of the map scope and the result fields of a field operator. + +The helpers in this module are shared by the lowering of regular field operators +(`gtir_to_sdfg_primitives.translate_as_fieldop()`) and of scan field operators +(`gtir_to_sdfg_scan.translate_scan_fieldop()`). The two differ in which dimensions +are traversed by the map scope: a regular field operator maps over the full domain, +while a scan traverses the column (vertical) dimension inside the stencil, by +means of a `LoopRegion`, and therefore maps only over the horizontal dimensions. +This is expressed by the `inner_dims` argument, that is the dimensions which the +dataflow computes by itself: they are excluded from the map range and written in +full shape by the output memlet. +""" + +from __future__ import annotations + +from typing import Iterable, Sequence + +import dace +from dace import nodes as dace_nodes, subsets as dace_subsets + +from gt4py.eve.extended_typing import MaybeNestedInTuple +from gt4py.next import common as gtx_common, utils as gtx_utils +from gt4py.next.iterator import ir as gtir +from gt4py.next.iterator.ir_utils import domain_utils, ir_makers as im +from gt4py.next.iterator.transforms import infer_domain +from gt4py.next.program_processors.runners.dace.lowering import ( + gtir_domain, + gtir_to_sdfg, + gtir_to_sdfg_lambda, + gtir_to_sdfg_types, + gtir_to_sdfg_utils, +) +from gt4py.next.type_system import type_specifications as ts + + +def parse_fieldop_arg( + node: gtir.Expr, + ctx: gtir_to_sdfg.SubgraphContext, + sdfg_builder: gtir_to_sdfg.SDFGBuilder, + domain: gtir_domain.FieldopDomain, + by_value: bool = False, +) -> MaybeNestedInTuple[gtir_to_sdfg_lambda.IteratorExpr | gtir_to_sdfg_lambda.MemletExpr]: + """ + Helper method to visit an expression passed as argument to a field operator + and create the local view for the field argument. + + Args: + node: The GTIR expression passed as argument to the field operator. + ctx: The SDFG context in which to lower the field operator. + sdfg_builder: The object used to build the map scope in the provided SDFG. + domain: The domain of the field operator. + by_value: When `True`, a field argument is passed by value, that is as a + `MemletExpr` with the full field shape, rather than as an iterator. + This is the case of a scan field operator, where the stencil accesses + the full column of its arguments. + + Returns: + The local view of the argument, in the form of a tuple in case of a tuple + of fields. + """ + + def parse_arg( + arg: gtir_to_sdfg_types.FieldopData, + ) -> gtir_to_sdfg_lambda.IteratorExpr | gtir_to_sdfg_lambda.MemletExpr: + arg_expr = arg.get_local_view(domain, ctx.sdfg) + if not by_value or isinstance(arg_expr, gtir_to_sdfg_lambda.MemletExpr): + return arg_expr + field_type = ts.FieldType( + dims=[dim for dim, _ in arg_expr.field_domain], dtype=arg_expr.gt_dtype + ) + return gtir_to_sdfg_lambda.MemletExpr( + arg_expr.field, field_type, arg_expr.get_memlet_subset(ctx.sdfg) + ) + + arg = sdfg_builder.visit(node, ctx=ctx) + + if isinstance(arg, gtir_to_sdfg_types.FieldopData): + return parse_arg(arg) + else: + # handle tuples of fields + return gtx_utils.tree_map(parse_arg)(arg) + + +def _create_field_operator_impl( + ctx: gtir_to_sdfg.SubgraphContext, + sdfg_builder: gtir_to_sdfg.SDFGBuilder, + output_edge: gtir_to_sdfg_lambda.DataflowOutputEdge | None, + output_domain: infer_domain.NonTupleDomainAccess, + output_type: ts.FieldType, + map_exit: dace_nodes.MapExit | None, + inner_dims: Sequence[gtx_common.Dimension], +) -> gtir_to_sdfg_types.FieldopData | None: + """ + Helper method to allocate a temporary array that stores one field computed + by a field operator. + + This method is called by `create_field_operator()`, once for each field of + the result, which is a tuple of fields in case of tuple return. For tuples, it + can happen that one of the nested fields is not used outside of the field + operator, and therefore does not need to be computed: in that case the domain + inferred by gt4py on this field is empty, the corresponding `output_edge` + argument is `None`, and this function returns `None` as well. + + Args: + ctx: The SDFG context in which to lower the field operator. + sdfg_builder: The object used to build the map scope in the provided SDFG. + output_edge: The dataflow write edge representing the output data. + output_domain: The domain of this field, as inferred by gt4py. + output_type: The GT4Py field type descriptor. + map_exit: The `MapExit` node of the field operator map scope, `None` when + the dataflow computes all dimensions of the domain by itself. + inner_dims: The dimensions that the dataflow computes by itself, therefore + written in full shape rather than element-wise. + + Returns: + The field data descriptor, which includes the field access node in the + given `state` and the field domain offset, or `None` if the field does + not need to be computed. + """ + if output_edge is None: + # According to domain inference, this tuple field does not need to be computed. + assert output_domain == infer_domain.DomainAccessDescriptor.NEVER + return None + assert isinstance(output_domain, domain_utils.SymbolicDomain) + field_domain = gtir_domain.get_field_domain(output_domain) + + dataflow_output_desc = output_edge.result.dc_node.desc(ctx.sdfg) + + # the memory layout of the output field follows the field operator compute domain + field_dims, field_origin, field_shape = gtir_domain.get_field_layout(field_domain) + if len(field_domain) == 0: + # The field operator computes a zero-dimensional field, and the data subset + # is set later depending on the element type (`ts.ListType` or `ts.ScalarType`) + field_subset = dace_subsets.Range([]) + else: + field_subset = gtir_domain.get_element_subset(field_dims, field_origin) + + if isinstance(output_edge.result.gt_dtype, ts.ScalarType): + if output_edge.result.gt_dtype != output_type.dtype: + raise TypeError( + f"Type mismatch, expected {output_type.dtype} got {output_edge.result.gt_dtype}." + ) + if len(inner_dims) == 0: + assert isinstance(dataflow_output_desc, dace.data.Scalar) + else: + assert isinstance(output_type.dtype, ts.ListType) + assert isinstance(output_edge.result.gt_dtype.element_type, ts.ScalarType) + if output_edge.result.gt_dtype.element_type != output_type.dtype.element_type: + raise TypeError( + f"Type mismatch, expected {output_type.dtype.element_type} got {output_edge.result.gt_dtype.element_type}." + ) + assert isinstance(dataflow_output_desc, dace.data.Array) + assert len(dataflow_output_desc.shape) == 1 + # extend the array with the local dimensions added by the field operator (e.g. `neighbors`) + assert all(dim.kind != gtx_common.DimensionKind.LOCAL for dim in field_dims) + assert output_edge.result.gt_dtype.offset_type is not None + local_dim = output_edge.result.gt_dtype.offset_type + # construct the full subset according to the canonical field domain + extended_dims = gtx_common.order_dimensions([*field_dims, local_dim]) + local_idx = extended_dims.index(local_dim) + + field_shape.insert(local_idx, dataflow_output_desc.shape[0]) + field_subset = ( + dace_subsets.Range(field_subset[:local_idx]) + + dace_subsets.Range.from_array(dataflow_output_desc) + + dace_subsets.Range(field_subset[local_idx:]) + ) + + # allocate local temporary storage + if len(inner_dims) != 0: + # The dataflow writes the dimensions it computes by itself in full shape, for + # each point of the map range on the other dimensions. The shape is taken from + # the data written by the dataflow, not from the domain of this field: the + # dataflow of a scan is lowered on the domain of the whole field operator, + # which is the union of the domains of the fields in a tuple result. + assert isinstance(dataflow_output_desc, dace.data.Array) + for dim in inner_dims: + dim_index = field_dims.index(dim) + field_subset = ( + dace_subsets.Range(field_subset[:dim_index]) + + dace_subsets.Range.from_string(f"0:{dataflow_output_desc.shape[dim_index]}") + + dace_subsets.Range(field_subset[dim_index + 1 :]) + ) + field_name, _ = sdfg_builder.add_temp_array_like(ctx.sdfg, dataflow_output_desc) + elif len(field_shape) == 0: # zero-dimensional field + field_name, _ = sdfg_builder.add_temp_scalar(ctx.sdfg, dataflow_output_desc.dtype) + field_subset = dace_subsets.Range.from_string("0") + else: + field_name, _ = sdfg_builder.add_temp_array( + ctx.sdfg, field_shape, dataflow_output_desc.dtype + ) + field_node = ctx.state.add_access(field_name) + + # and here the edge writing the dataflow result data through the map exit node + last_node_removed = output_edge.connect(map_exit, field_node, field_subset) + + if len(inner_dims) != 0 and not last_node_removed: + # The dataflow of a scan is lowered to a nested SDFG that writes the column + # into a transient data container. This container is expected to be removed + # by the connection above, so that the nested SDFG writes the result field + # directly, see `gtir_to_sdfg_scan._handle_dataflow_result_of_nested_sdfg()`. + raise ValueError("The scan nested SDFG is expected to write directly to the result field.") + + return gtir_to_sdfg_types.FieldopData( + field_node, ts.FieldType(field_dims, output_edge.result.gt_dtype), tuple(field_origin) + ) + + +def create_field_operator( + ctx: gtir_to_sdfg.SubgraphContext, + domain: gtir_domain.FieldopDomain, + node_type: ts.FieldType | ts.TupleType, + sdfg_builder: gtir_to_sdfg.SDFGBuilder, + input_edges: Iterable[gtir_to_sdfg_lambda.DataflowInputEdge], + output: MaybeNestedInTuple[gtir_to_sdfg_lambda.DataflowOutputEdge | None], + output_domain: infer_domain.DomainAccess, + inner_dims: Sequence[gtx_common.Dimension] = (), +) -> gtir_to_sdfg_types.FieldopResult: + """ + Helper method to build the output of a field operator, which can consist of + a single field or a tuple of fields. + + Args: + ctx: The SDFG context in which to lower the field operator. + domain: The domain of the field operator, used as map range. + node_type: The GT4Py type of the IR node that produces this field. + sdfg_builder: The object used to build the map scope in the provided SDFG. + input_edges: List of edges to pass input data into the dataflow. + output: Edge corresponding to the dataflow output, or a tuple of edges in + case the field operator computes a tuple of fields. The edge is `None` + for the fields that do not need to be computed. + output_domain: The domain of the result, as inferred by gt4py, in the form + of a tuple in case the field operator computes a tuple of fields. + inner_dims: The dimensions that the dataflow computes by itself, therefore + excluded from the map range. This is the column dimension of a scan. + + Returns: + The descriptor of the field operator result, which is a single field or a + tuple of fields defined on the domain of the field operator. + """ + map_ranges = [domain_range for domain_range in domain if domain_range.dim not in inner_dims] + + if len(domain) == 0: + # create a trivial map for zero-dimensional fields + map_entry, map_exit = sdfg_builder.add_map("fieldop", ctx.state, {"__gt4py_zerodim": "0"}) + elif len(map_ranges) == 0: + # The dataflow computes all dimensions of the domain by itself, therefore + # no map scope is needed. This is the case of a scan field operator on a + # 1d domain, containing only the column dimension. + map_entry, map_exit = (None, None) + else: + # create map range corresponding to the field operator domain + map_entry, map_exit = sdfg_builder.add_map( + "fieldop", + ctx.state, + { + gtir_to_sdfg_utils.get_map_variable( + domain_range.dim + ): f"{domain_range.start}:{domain_range.stop}" + for domain_range in map_ranges + }, + ) + + # here we setup the edges passing through the map entry node + for edge in input_edges: + edge.connect(map_entry) + + # Note that `output_symbols` below is not used, we only need the tree-like + # structure to get the type of each nested field in the `tree_map` visitor. + output_symbols = ( + gtir_to_sdfg_utils.make_symbol_tree("__gtir_unused_dummy_var", node_type) + if isinstance(node_type, ts.TupleType) + else im.sym("__gtir_unused_dummy_var", node_type) + ) + + return gtx_utils.tree_map( + lambda edge, field_domain, sym: _create_field_operator_impl( + ctx, sdfg_builder, edge, field_domain, sym.type, map_exit, inner_dims + ) + )(output, output_domain, output_symbols) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py index 8e14ae41bd..8b44519828 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py @@ -9,7 +9,7 @@ from __future__ import annotations import abc -from typing import TYPE_CHECKING, Iterable, Optional, Protocol +from typing import TYPE_CHECKING, Optional, Protocol import dace from dace import nodes as dace_nodes, subsets as dace_subsets @@ -27,6 +27,7 @@ gtir_domain, gtir_python_codegen, gtir_to_sdfg, + gtir_to_sdfg_fieldop, gtir_to_sdfg_lambda, gtir_to_sdfg_types, gtir_to_sdfg_utils, @@ -34,7 +35,9 @@ from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_concat_where import ( translate_concat_where, ) -from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_scan import translate_scan +from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_scan import ( + translate_scan_fieldop, +) from gt4py.next.type_system import type_info as ti, type_specifications as ts @@ -64,154 +67,6 @@ def __call__( """ -def _parse_fieldop_arg( - node: gtir.Expr, - ctx: gtir_to_sdfg.SubgraphContext, - sdfg_builder: gtir_to_sdfg.SDFGBuilder, - domain: gtir_domain.FieldopDomain, -) -> gtir_to_sdfg_lambda.IteratorExpr | gtir_to_sdfg_lambda.MemletExpr: - """ - Helper method to visit an expression passed as argument to a field operator - and create the local view for the field argument. - """ - arg = sdfg_builder.visit(node, ctx=ctx) - - if not isinstance(arg, gtir_to_sdfg_types.FieldopData): - raise ValueError("Expected a field, found a tuple of fields.") - return arg.get_local_view(domain, ctx.sdfg) - - -def _create_field_operator_impl( - ctx: gtir_to_sdfg.SubgraphContext, - sdfg_builder: gtir_to_sdfg.SDFGBuilder, - field_domain: gtir_domain.FieldopDomain, - output_edge: gtir_to_sdfg_lambda.DataflowOutputEdge, - output_type: ts.FieldType, - map_exit: dace_nodes.MapExit, -) -> gtir_to_sdfg_types.FieldopData: - """ - Helper method to allocate a temporary array that stores one field computed - by a field operator. - - This method is called by `_create_field_operator()`. - - Args: - ctx: The SDFG context in which to lower the field operator. - sdfg_builder: The object used to build the map scope in the provided SDFG. - domain: The domain of the field operator that computes the field. - output_edge: The dataflow write edge representing the output data. - output_type: The GT4Py field type descriptor. - map_exit: The `MapExit` node of the field operator map scope. - - Returns: - The field data descriptor, which includes the field access node in the - given `state` and the field domain offset. - """ - dataflow_output_desc = output_edge.result.dc_node.desc(ctx.sdfg) - - # the memory layout of the output field follows the field operator compute domain - field_dims, field_origin, field_shape = gtir_domain.get_field_layout(field_domain) - if len(field_domain) == 0: - # The field operator computes a zero-dimensional field, and the data subset - # is set later depending on the element type (`ts.ListType` or `ts.ScalarType`) - field_subset = dace_subsets.Range([]) - else: - field_subset = gtir_domain.get_element_subset(field_dims, field_origin) - - if isinstance(output_edge.result.gt_dtype, ts.ScalarType): - if output_edge.result.gt_dtype != output_type.dtype: - raise TypeError( - f"Type mismatch, expected {output_type.dtype} got {output_edge.result.gt_dtype}." - ) - assert isinstance(dataflow_output_desc, dace.data.Scalar) - else: - assert isinstance(output_type.dtype, ts.ListType) - assert isinstance(output_edge.result.gt_dtype.element_type, ts.ScalarType) - if output_edge.result.gt_dtype.element_type != output_type.dtype.element_type: - raise TypeError( - f"Type mismatch, expected {output_type.dtype.element_type} got {output_edge.result.gt_dtype.element_type}." - ) - assert isinstance(dataflow_output_desc, dace.data.Array) - assert len(dataflow_output_desc.shape) == 1 - # extend the array with the local dimensions added by the field operator (e.g. `neighbors`) - assert all(dim.kind != gtx_common.DimensionKind.LOCAL for dim in field_dims) - assert output_edge.result.gt_dtype.offset_type is not None - local_dim = output_edge.result.gt_dtype.offset_type - # construct the full subset according to the canonical field domain - extended_dims = gtx_common.order_dimensions([*field_dims, local_dim]) - local_idx = extended_dims.index(local_dim) - - field_shape.insert(local_idx, dataflow_output_desc.shape[0]) - field_subset = ( - dace_subsets.Range(field_subset[:local_idx]) - + dace_subsets.Range.from_array(dataflow_output_desc) - + dace_subsets.Range(field_subset[local_idx:]) - ) - - # allocate local temporary storage - if len(field_shape) == 0: # zero-dimensional field - field_name, _ = sdfg_builder.add_temp_scalar(ctx.sdfg, dataflow_output_desc.dtype) - field_subset = dace_subsets.Range.from_string("0") - else: - field_name, _ = sdfg_builder.add_temp_array( - ctx.sdfg, field_shape, dataflow_output_desc.dtype - ) - field_node = ctx.state.add_access(field_name) - - # and here the edge writing the dataflow result data through the map exit node - output_edge.connect(map_exit, field_node, field_subset) - - return gtir_to_sdfg_types.FieldopData( - field_node, ts.FieldType(field_dims, output_edge.result.gt_dtype), tuple(field_origin) - ) - - -def _create_field_operator( - ctx: gtir_to_sdfg.SubgraphContext, - domain: gtir_domain.FieldopDomain, - node_type: ts.FieldType, - sdfg_builder: gtir_to_sdfg.SDFGBuilder, - input_edges: Iterable[gtir_to_sdfg_lambda.DataflowInputEdge], - output_edge: gtir_to_sdfg_lambda.DataflowOutputEdge, -) -> gtir_to_sdfg_types.FieldopResult: - """ - Helper method to build the output of a field operator. - - Args: - ctx: The SDFG context in which to lower the field operator. - domain: The domain of the field operator that computes the field. - node_type: The GT4Py type of the IR node that produces this field. - sdfg_builder: The object used to build the map scope in the provided SDFG. - input_edges: List of edges to pass input data into the dataflow. - output_edge: Edge corresponding to the dataflow output. - - Returns: - The descriptor of the field operator result, which is a single field defined - on the domain of the field operator. - """ - - if len(domain) == 0: - # create a trivial map for zero-dimensional fields - map_range = { - "__gt4py_zerodim": "0", - } - else: - # create map range corresponding to the field operator domain - map_range = { - gtir_to_sdfg_utils.get_map_variable( - domain_range.dim - ): f"{domain_range.start}:{domain_range.stop}" - for domain_range in domain - } - map_entry, map_exit = sdfg_builder.add_map("fieldop", ctx.state, map_range) - - # here we setup the edges passing through the map entry node - for edge in input_edges: - edge.connect(map_entry) - - return _create_field_operator_impl(ctx, sdfg_builder, domain, output_edge, node_type, map_exit) - - def translate_as_fieldop( node: gtir.Node, ctx: gtir_to_sdfg.SubgraphContext, @@ -240,19 +95,19 @@ def translate_as_fieldop( ) fieldop_expr, fieldop_domain_expr = fun_node.args - if cpm.is_call_to(fieldop_expr, "scan"): - return translate_scan(node, ctx, sdfg_builder) - - if not isinstance(node.type, ts.FieldType): - raise NotImplementedError("Unexpected 'as_fieldop' with tuple output in SDFG lowering.") - # Parse the domain of the field operator. assert isinstance(fieldop_domain_expr.type, ts.DomainType) field_domain = gtir_domain.get_field_domain( domain_utils.SymbolicDomain.from_expr(fieldop_domain_expr) ) + if cpm.is_call_to(fieldop_expr, "scan"): + raise AssertionError( + "The 'scan' operator should be lowered by 'translate_scan_fieldop()' instead of 'translate_as_fieldop()'." + ) + if cpm.is_ref_to(fieldop_expr, "deref"): + assert isinstance(node.type, ts.FieldType) arg_type = node.args[0].type assert isinstance(arg_type, (ts.FieldType, ts.ScalarType)) if arg_type != node.type: @@ -277,16 +132,18 @@ def translate_as_fieldop( ) # visit the list of arguments to be passed to the lambda expression - fieldop_args = [_parse_fieldop_arg(arg, ctx, sdfg_builder, field_domain) for arg in node.args] + fieldop_args = [ + gtir_to_sdfg_fieldop.parse_fieldop_arg(arg, ctx, sdfg_builder, field_domain) + for arg in node.args + ] # represent the field operator as a mapped tasklet graph, which will range over the field domain - input_edges, output_edge = gtir_to_sdfg_lambda.translate_lambda_to_dataflow( + input_edges, output_tree = gtir_to_sdfg_lambda.translate_lambda_to_dataflow( ctx.sdfg, ctx.state, sdfg_builder, stencil_expr, fieldop_args ) - assert isinstance(output_edge, gtir_to_sdfg_lambda.DataflowOutputEdge) - return _create_field_operator( - ctx, field_domain, node.type, sdfg_builder, input_edges, output_edge + return gtir_to_sdfg_fieldop.create_field_operator( + ctx, field_domain, node.type, sdfg_builder, input_edges, output_tree, node.annex.domain ) @@ -498,8 +355,8 @@ def translate_index( gtir_to_sdfg_lambda.EmptyInputEdge(ctx.state, index_write_tasklet), ] output_edge = gtir_to_sdfg_lambda.DataflowOutputEdge(ctx.state, index_value) - return _create_field_operator( - ctx, field_domain, node.type, sdfg_builder, input_edges, output_edge + return gtir_to_sdfg_fieldop.create_field_operator( + ctx, field_domain, node.type, sdfg_builder, input_edges, output_edge, node.annex.domain ) @@ -745,6 +602,6 @@ def translate_symbol_ref( translate_make_tuple, translate_tuple_get, translate_scalar_expr, - translate_scan, + translate_scan_fieldop, translate_symbol_ref, ] diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index 57d3bd7b00..5a184686dc 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -23,14 +23,13 @@ from __future__ import annotations import copy -from typing import Iterable, Sequence +from typing import Sequence import dace import sympy from dace import nodes as dace_nodes, subsets as dace_subsets from gt4py import eve -from gt4py.eve.xtyping import MaybeNestedInTuple from gt4py.next import common as gtx_common, utils as gtx_utils from gt4py.next.iterator import ir as gtir from gt4py.next.iterator.ir_utils import ( @@ -42,6 +41,7 @@ from gt4py.next.program_processors.runners.dace.lowering import ( gtir_domain, gtir_to_sdfg, + gtir_to_sdfg_fieldop, gtir_to_sdfg_lambda, gtir_to_sdfg_types, gtir_to_sdfg_utils, @@ -49,208 +49,6 @@ from gt4py.next.type_system import type_info as ti, type_specifications as ts -def _parse_scan_fieldop_arg( - node: gtir.Expr, - ctx: gtir_to_sdfg.SubgraphContext, - sdfg_builder: gtir_to_sdfg.SDFGBuilder, - field_domain: gtir_domain.FieldopDomain, -) -> MaybeNestedInTuple[gtir_to_sdfg_lambda.MemletExpr]: - """Helper method to visit an expression passed as argument to a scan field operator. - - On the innermost level, a scan operator is lowered to a loop region which computes - column elements in the vertical dimension. - - It differs from the helper method `gtir_to_sdfg_primitives` in that field arguments - are passed in full shape along the vertical dimension, rather than as iterator. - """ - - def _parse_fieldop_arg_impl( - arg: gtir_to_sdfg_types.FieldopData, - ) -> gtir_to_sdfg_lambda.MemletExpr: - arg_expr = arg.get_local_view(field_domain, ctx.sdfg) - if isinstance(arg_expr, gtir_to_sdfg_lambda.MemletExpr): - return arg_expr - # In scan field operator, the arguments to the vertical stencil are passed by value. - # Therefore, the full field shape is passed as `MemletExpr` rather than `IteratorExpr`. - field_type = ts.FieldType( - dims=[dim for dim, _ in arg_expr.field_domain], dtype=arg_expr.gt_dtype - ) - return gtir_to_sdfg_lambda.MemletExpr( - arg_expr.field, field_type, arg_expr.get_memlet_subset(ctx.sdfg) - ) - - arg = sdfg_builder.visit(node, ctx=ctx) - - if isinstance(arg, gtir_to_sdfg_types.FieldopData): - return _parse_fieldop_arg_impl(arg) - else: - # handle tuples of fields - return gtx_utils.tree_map(_parse_fieldop_arg_impl)(arg) - - -def _create_scan_field_operator_impl( - ctx: gtir_to_sdfg.SubgraphContext, - sdfg_builder: gtir_to_sdfg.SDFGBuilder, - output_edge: gtir_to_sdfg_lambda.DataflowOutputEdge | None, - output_domain: infer_domain.NonTupleDomainAccess, - output_type: ts.FieldType, - map_exit: dace_nodes.MapExit | None, -) -> gtir_to_sdfg_types.FieldopData | None: - """ - Helper method to allocate a temporary array that stores one field computed - by the scan field operator. - - This method is called by `_create_scan_field_operator()`. - - Similar to `gtir_to_sdfg_primitives._create_field_operator_impl()` but - for scan field operators. It differs in that the scan loop region produces - a field along the vertical dimension, rather than a single point. - Therefore, the memlet subset will write a slice into the result array, that - corresponds to the full vertical shape for each horizontal grid point. - - Another difference is that this function is called on all fields inside a tuple, - in case of tuple return. Note that a regular field operator only computes a - single field, never a tuple of fields. For tuples, it can happen that one of - the nested fields is not used, outside the scan field operator, and therefore - does not need to be computed. Then, the domain inferred by gt4py on this field - is empty and the corresponding `output_edge` argument to this function is None. - In this case, the function does not allocate an array node for the output field - and returns None. - - Refer to `gtir_to_sdfg_primitives._create_field_operator_impl()` for - the description of function arguments. - """ - if output_edge is None: - # According to domain inference, this tuple field does not need to be computed. - assert output_domain == infer_domain.DomainAccessDescriptor.NEVER - return None - assert isinstance(output_domain, domain_utils.SymbolicDomain) - field_domain = gtir_domain.get_field_domain(output_domain) - - outer_output_desc = output_edge.result.dc_node.desc(ctx.sdfg) - assert isinstance(outer_output_desc, dace.data.Array) - - if isinstance(output_edge.result.gt_dtype, ts.ScalarType): - assert isinstance(output_type.dtype, ts.ScalarType) - if output_edge.result.gt_dtype != output_type.dtype: - raise TypeError( - f"Type mismatch, expected {output_type.dtype} got {output_edge.result.gt_dtype}." - ) - # the scan nested SDFG writes a column of scalar values into an array with - # the shape of the full field (see `_lower_lambda_to_nested_sdfg()`) - assert len(outer_output_desc.shape) == len(field_domain) - else: - raise NotImplementedError("scan with list output is not supported") - - # the memory layout of the output field follows the field operator compute domain - field_dims, field_origin, _field_shape = gtir_domain.get_field_layout(field_domain) - field_subset = gtir_domain.get_element_subset(field_dims, field_origin) - - # the vertical dimension used as scan column is computed by the `LoopRegion` - # inside the map scope, therefore it is excluded from the map range - scan_dim_index = [sdfg_builder.is_column_axis(dim) for dim in field_dims].index(True) - - # The map scope writes the full-shape dimension corresponding to the scan column. - field_subset = ( - dace_subsets.Range(field_subset[:scan_dim_index]) - + dace_subsets.Range.from_string(f"0:{outer_output_desc.shape[scan_dim_index]}") - + dace_subsets.Range(field_subset[scan_dim_index + 1 :]) - ) - - # Create the final data storage, that is outside of the surrounding Map. - field_name, _field_desc = sdfg_builder.add_temp_array_like(ctx.sdfg, outer_output_desc) - field_node = ctx.state.add_access(field_name) - - # Now connect the output connector on the nested SDFG with the result field - # outside the scan map scope. For 1D domain, containing only the column dimension, - # there is no map scope, since the map range is only on the horizontal domain. - # Up to now the nested SDFG is writing into a transient data container that - # has the size to hold one column. The function below, that does the connection, - # will remove that transient and write directly to the result field. - inner_map_output_temporary_removed = output_edge.connect(map_exit, field_node, field_subset) - if not inner_map_output_temporary_removed: - raise ValueError("The scan nested SDFG is expected to write directly to the result field.") - - return gtir_to_sdfg_types.FieldopData( - field_node, ts.FieldType(field_dims, output_edge.result.gt_dtype), tuple(field_origin) - ) - - -def _create_scan_field_operator( - ctx: gtir_to_sdfg.SubgraphContext, - field_domain: gtir_domain.FieldopDomain, - node_type: ts.FieldType | ts.TupleType, - sdfg_builder: gtir_to_sdfg.SDFGBuilder, - input_edges: Iterable[gtir_to_sdfg_lambda.DataflowInputEdge], - output: MaybeNestedInTuple[gtir_to_sdfg_lambda.DataflowOutputEdge | None], - output_domain: infer_domain.DomainAccess, -) -> gtir_to_sdfg_types.FieldopResult: - """ - Helper method to build the output of a field operator, which can consist of - a single field or a tuple of fields. - - Similar to `gtir_to_sdfg_primitives._create_field_operator()` but for scan - field operators. The main difference is that the scan vertical dimension is - excluded from the map range. This because the vertical dimension is traversed - by a loop region in a mapped nested SDFG. - - Refer to `gtir_to_sdfg_primitives._create_field_operator()` for the - description of function arguments. Note that the return value is different, - because the scan field operator can return a tuple of fields, while a regular - field operator return a single field. The domain of the nested fields, in - a tuple, can be empty, in case the nested field is not used outside the scan. - In this case, the corresponding `output` edge will be None and this function - will also return None for the corresponding field inside the tree-like result. - """ - dims, _, _ = gtir_domain.get_field_layout(field_domain) - - # create a map scope to execute the `LoopRegion` over the horizontal domain - if len(dims) == 1: - # We construct the scan field operator on the horizontal domain, while the - # vertical dimension (the column axis) is computed by the loop region. - # If the field operator computes only the column axis (a 1d scan field operator), - # there is no horizontal domain, therefore the map scope is not needed. - # This case currently produces wrong CUDA code because of a DaCe issue - # (see https://github.com/GridTools/gt4py/issues/1136). - # The corresponding GT4Py tests are disabled (pytest marker `uses_scan_1d_field`). - map_entry, map_exit = (None, None) - else: - # create map range corresponding to the field operator domain - map_entry, map_exit = sdfg_builder.add_map( - "fieldop", - ctx.state, - ndrange={ - gtir_to_sdfg_utils.get_map_variable(r.dim): f"{r.start}:{r.stop}" - for r in field_domain - if not sdfg_builder.is_column_axis(r.dim) - }, - ) - assert (len(map_entry.params) + 1) == len(field_domain) - - # here we setup the edges passing through the map entry node - for edge in input_edges: - edge.connect(map_entry) - - # Note that `output_symbol` below is not used, we only need the tree-like - # structure to get the type of each nested field in the `tree_map` visitor. - dummy_output_symbol = ( - gtir_to_sdfg_utils.make_symbol_tree("__gtir_unused_dummy_var", node_type) - if isinstance(node_type, ts.TupleType) - else im.sym("__gtir_unused_dummy_var", node_type) - ) - - return gtx_utils.tree_map( - lambda edge, domain, sym: _create_scan_field_operator_impl( - ctx, - sdfg_builder, - edge, - domain, - sym.type, - map_exit, - ) - )(output, output_domain, dummy_output_symbol) - - def _scan_input_name(input_name: str) -> str: """ Helper function to make naming of input connectors in the scan nested SDFG @@ -410,7 +208,9 @@ def get_scan_output_shape( # inside the 'compute' state, visit the list of arguments to be passed to the stencil stencil_args = [ - _parse_scan_fieldop_arg(im.ref(p.id), compute_ctx, sdfg_builder, field_domain) + gtir_to_sdfg_fieldop.parse_fieldop_arg( + im.ref(p.id), compute_ctx, sdfg_builder, field_domain, by_value=True + ) for p in lambda_node.params ] # still inside the 'compute' state, generate the dataflow representing the stencil @@ -612,7 +412,7 @@ def _handle_dataflow_result_of_nested_sdfg( return gtir_to_sdfg_lambda.DataflowOutputEdge(outer_ctx.state, output_expr) -def translate_scan( +def translate_scan_fieldop( node: gtir.Node, ctx: gtir_to_sdfg.SubgraphContext, sdfg_builder: gtir_to_sdfg.SDFGBuilder, @@ -745,7 +545,17 @@ def translate_scan( ) )(lambda_output, node.annex.domain) - # we call a helper method to create a map scope that will compute the entire field - return _create_scan_field_operator( - ctx, field_domain, node.type, sdfg_builder, input_edges, output_tree, node.annex.domain + # We call a helper method to create a map scope that will compute the entire field. + # The column dimension is excluded from the map range, because it is traversed by + # the `LoopRegion` inside the stencil dataflow. + scan_dim = next(r.dim for r in field_domain if sdfg_builder.is_column_axis(r.dim)) + return gtir_to_sdfg_fieldop.create_field_operator( + ctx, + field_domain, + node.type, + sdfg_builder, + input_edges, + output_tree, + node.annex.domain, + inner_dims=(scan_dim,), ) From 0240faf076a9e6f52dee8ca6711ff2bbc3949312 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 30 Sep 2026 14:49:58 +0200 Subject: [PATCH 05/69] refactor[next-dace]: integrate and restate nested SDFG connectors --- _dacegraphs/invalid.sdfgz | Bin 0 -> 4912 bytes .../runners/dace/lowering/gtir_to_sdfg.py | 18 +- .../dace/lowering/gtir_to_sdfg_fieldop.py | 10 +- .../dace/lowering/gtir_to_sdfg_scan.py | 30 +- .../transformations/concat_where_mapper.py | 274 +++++++----------- .../runners/dace/transformations/simplify.py | 12 +- .../runners/dace/transformations/strides.py | 181 ++++-------- .../runners/dace/transformations/utils.py | 91 +++++- .../dace_tests/test_gtir_to_sdfg.py | 11 +- .../test_concat_where_replacer.py | 193 +++++++++--- .../test_copy_chain_remover.py | 9 +- .../test_fuse_horizontal_conditionblocks.py | 46 ++- .../test_loop_blocking.py | 21 +- .../test_map_buffer_elimination.py | 153 ++++++---- .../test_move_dataflow_into_if_body.py | 193 ++++++++---- .../transformation_tests/test_strides.py | 272 +++++------------ .../test_vertical_map_split_fusion.py | 16 +- 17 files changed, 841 insertions(+), 689 deletions(-) create mode 100644 _dacegraphs/invalid.sdfgz diff --git a/_dacegraphs/invalid.sdfgz b/_dacegraphs/invalid.sdfgz new file mode 100644 index 0000000000000000000000000000000000000000..e5f919046c61f461559f18ccf8598a20b72e398e GIT binary patch literal 4912 zcmV-06VL1)iwFq51ifkk|7mV^VQgt+E^}mNXL;n8L%WayQ|(^@2FS(wVN*{ zq5Ho3%Mbtc-`!r<JO&R;wG&wY1=NC%ZJPtE8$^zqKEt83)V=Hkct=Rejw z|FQf$06C6v7V?AvhEF)b=+`*M;n?JY!{ym$ldk;QMXlh1Cr~Q@x}Uy%OSC_X&WkFY z7j5XgsHgLy2A@S8ofq|VUeutuI02m>hHFjdhXGj8d3hk6msL71+t7JgPv>O~KFc~f zFYD>NtU+^m0y;ko*P6}`1F)iVVSMtNNgtO8{);n1Gp$hk9@t1hUl@5d2qVBKpU%V1 z@Z`M1^FzetM{|3Hd!6*FB7MCYP611Q9E>XW!VrkmvNrLSR3vVH+7H!fKQvAIVQ1Qk zAiR0=-IE|yBe3I1J{XV8u=_rm;Vj%M!DpoaO!Ndact8%bL*$S=y_j4+4t zs(t~gE?-ssEUFGPo-J&C;OnaqOUs{PE3 zC!y~LE>DOfVAijnN|S(M27kTzbJwh`DL`!qQS%Hr6D8sqmqC;N)zdu!7YKj}p24qKPkyQ+)<4bc-@}lXrq1DGANQ}} z=NB`ahl=^$h{vu}^!vqw<9XiszC+&9T`Bo_k$)bK61#k`^XtJVj!VnL59!*6bPe#z z%{1>12P61`DBw{X3`2h~^5GU(_U&FcVR8`O(I~ilJYAc~4OHFtqxo=nC#cSYaN>|5 zr8!2NvkYm8IkGG>j1tYQQwiR+q^!uj5}#tE?IqBd&DeMAo^xR~`)TaUJS~Nkl@RX$ zqHv;ii9!-pS4`NMVvQ)L43rYkbJTjol?FtOmdI-_Xb?tWnr#pzha%b_KIC!YL*J68 z5g&52_=t?eObCl~3}EM?jR zZ~MhgVr}p0CO5b@+3qMGYe#93Aw0x`N3B6#rw!Xdwn`n&(pr9|yy0r>Gbat{d533b z8NT1Ys}})Zz?7ee5BCjDPCfXlxK#uCYewfaqjSED&b?wtUK2WxPv}(hH~Z_)PFkR{ z4Ap*FlZDt{sP6lc)PH%xT+T5Wn`84b4Fe8V&s^uX{mnzaQX&R%eT*+$4a{~zg#%;yQet!q z>yPtcKKR=vq4Ib5x{6`};oTGAW|d9az3a<(I4>gLgu`rZi?x3H&_9yRhc61-zXG73 z41ATOJBp^m$RPpDxPY0O+;k^WH2QxrYHUwjV6x9p`!y{9U`iRq_Gn=~p zIpCb-+hJFH7|e>rq7M^pjQ?nU(>H~frAgAGh3k=SC`N}t)`O?vw)w6tX94uRizWGe zDJ(51gQApp932AgDa18%NGnef0hU^?JQq@3FiYu{rR)%vHdQZ}bUqST-Mokxr~%#s zcnKI0E3_xtNl<{D>c#(z$CH1AYw)!zJf2T{qIE&>n<7}>_izR)uPr%eU&1sWKnUIW zzH?P~`LCTK@l%@=F5Iw#r%5h+HAuSJ_a(vEU&V>FQx5_CL|i{e;YM}pT3r642sNs~ zTy1#TJna`V9T;0kQ_U;~ZCJ+xiBFiO30(?N~g%!qx!~8%uz5!hd$9aN1 z-phL8uzD2jPlof^VYP&5n1QuQ^0dBSrq?NPclW7TqE1_8*g`)T)fX5NWE*WQfwwI> zG*%{7IPMoGm{XDqP7yW|{I@6tIIEH%N|e#Tf|G~&nQB|~QC>`@_%10~O>u&jTvi)} z;npD%I76Iha9J@0@fOTuFI1%5p1QWhp0y~lCl*C3uo1*Zq%#%MdLoiHZBV8i7FLVM z0y|TkjGbQ;*_|jl6NP4(M43|rf&~ob))|Tdlhmm!bJ(1?PIig_k*VftSv3aM48~Rr zNdmzFXP6+X!O9qjfmyUhg*#sIlc1QYTjweUuEt)YmKhwqvJz1v!3l&&7bz??GQk*5 zJSAAk4QkoN1bq*4ujJ?2%!48_i{K}C0Z~ApPh><`NRnkyT8p>)0L00|`@O=(qe5M! zTgCU4DL1@UgbU#^BpBrg+#IQi;R3mnIar5b_oWWVHgzEX9ND1iQlOQ=8N~=IM-f-TLZHMVB2sD|BNZ~Z3(o!U zEdz0tfjbWU%j9I)yWu!y*gNEy0S69zIb@kN;J|U^A_muv#|!49*m9CSdrmfOuBxxZ zZs>dHQxDnhrd?b0nX+9N+CB4-jP3*&4Ax`etpG~{KRC?{vXMvR0#ngsGz9IBkk40I zKUVXymNt~UYTonIJgZf(hHxZVmNHP3AO)cwveqe3Iuoc0ubTIVY94*|ns=D@QkTk( z84pJLfQVvgg9)a{U|1j+)-o^;UaHw&AXZdAGze=6>Y>5J;icuh#PLhuXDJ_SnFgjA ziU963yMspsx6U7ag7m`L@TL@mQh~b zjx&Z?`yFT6$jCf5;1qKSK^seZ6JdQOl6zR4F;>`~cE{O?ibJhr6%v(qk+mB0SX~nIuSa>Jjsqq=7Q3qq&@H@G%S5>lU{^K*CCfOjzT&2DK*4fgv-7 zA+XV)?`fYLcsrUC^3o;j#5?Y|rB+en5Co|P7QqOf5SJclB0>;e5m@kH`Z{CSMmRr= z@-Qu|b?x0-AUFgc4m>fd6yhW%pDb;HjM5N_wa6TA(y|0v)$=MlY9$XXUc=%7B-^ZX z#d2eZWB2chA~w2xLjwa8he39?OJ-Zw?+CZ=ajpW#;viSSU}ZB#F%m97+@OL+%2J1z zi=1k3AHcMq*6q8e@#}Gj%frj`<;HUvqQeftrWn(16G4y_TBHLS2>24<8{0#j!`CwX zDXO9uvOKksA@D%Gp&3Trrw$GQYGsTM$UtBfGO8%Z(QA49%z|+KOwzsUtB5iq!Aitb zI_M=ZimcZPF=7qVCT)hrXJ21+2J1k^Ba$M5w*+f`+HORVWMI-l2vlI&xW4wz08qff zU=|bt0;KGMGDroi5OEn6)Mw5UTEAC-KCs}g*W?wWcGi2cx8CDzOKktfOeTZTbz^62 z<;dcuF4?+sjO#jPYmR!ZZJwAeIb7S1Td@`Oy}5NK@YeL{R?pvU?%8c9lN`87TJ1X~xbO+#)9U+G1W-A)rDnr) zF}0&_Ek5Z3sIe5zh!^#v@6UQOQ&6NlM+xg3Zxyl`+*XYvI0D6 z)wI90*ql)IrMhw_S#KtPU$+HsXa?Hc$Ne}6LqDGUTFbQWH{Cb8>riDGdcWzE`B3SU z*=foDR55h5z`$J-Gc`BGSq1gd^l7~|w_CFhUz&@JU9FEAxYxfpq%(k%s?b+N`omBC z^1;_DDJx$jrHi-s$nO9C>z_3v?OY}0tGD|C>tn=>=nN_6V13dgAWMZqL@O?MAdzOV z{ch!|#HPy^Cb0K%L)39Yw&j4R<$&BLx@5$G$IMaCDTm8EMp_Y%Am$7rWF|@(n|4M& zU?uJkvBl#ygztygye7mJr8FrgJhPcWI0}d?F_R!=;2;{OASQ5JIN~;Fs?(Mo@qzZQ1 zVM8t|>2cNWZ5MC8yF#sBw{cuZ-u{&!2Zgxp-xPALq{u}hc8|GDwcO~4MH+%%#HAz1 zV(>y`#9UYvj8u5MT#U0B!8dFWo7 zs24T6s&^ASuVQzA*p>IXam!@{%P&c)(Wjk!nn;19@RnF%sHXT&CU&f~*!>aP`LC+4 zyhJsx;{5Ka`o>FC^UBTduFiH;?BmwnR@4xP7^OJ3(;$@XoSED^C5BTj`yit%)!Bp54iwf2IX%r?C+vbL}qXU~S*DYQOHq2-zV zCe$i6UYF(`j&@%Y7q5wn`>Mbv6}8q;%jy)EIz78R|9W}(;X{j)Y8EFur{*;%cxA~6 z7VW2V$+P>;#@ySPTXzyleOLCE3e7qAR@s{e>m$De#g-9FdGlrx$?3O3%4PL=z#j zQ<*36WuDJfFte#!Hqt;;@zy6v!2#mn02z)s%8WBwV(W?bXYZD^A)_`Bm=%X~T#^;Y zD)7gI4%{*7h^6|t(BqHw}~VyWq$0 z>D_hCCyRFg%=)iUxXs^9rsM0Wx#`32#KJK=I-LVI;I}s}yc>>x59wVo?^fbD?x$D5 zzn!E$ho_hc?jGC>^1+udd%{W6GVz4d4b6@9<_RZU_mHI-KPCGE^792ADc%j%rEl?D zY*I=nOs7dDzjkk6=+zs4Qo~8-iy00;W#INsG$42WeP?TDJHMrn_P1{5cQfl;1K&m+ zP@GQwIdld|twv_pN$S?|VdkcTNqXd}cwuwrs(AVF_kKLL!_ey#FFyYM3e}!PT5YQa zkGb~5&}tv_n>TMdgIQ-Z&O71%<^#Yci~z!M0pvbxYts~bx?zxau72y@{?_ev9sv2a z3h-?e+}kR!xBH;J?Rm;eB+gK|y) literal 0 HcmV?d00001 diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py index dda7bae3d4..f677559fa2 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py @@ -1368,11 +1368,11 @@ def construct_output_for_nested_sdfg( # that is externally allocated, as required by the SDFG IR. An output edge will write the result # from the nested-SDFG to a new intermediate data container allocated in the parent SDFG. # NOTE: We use the symbol mapping returned by `add_nested_sdfg()` rather than - # `nsdfg_node.symbol_mapping`: dace applies the mapping of the symbols that - # the nested SDFG uses directly inside it, and only keeps the remaining - # entries on the node. The field origin is not visible to dace, because it - # is not part of any data descriptor, so it has to be translated here with - # the full mapping. + # `nsdfg_node.symbol_mapping`: the mapping of the symbols that the nested + # SDFG uses is applied inside it, when it is integrated below, and only the + # remaining entries are kept on the node. The field origin is not visible to + # dace, because it is not part of any data descriptor, so it has to be + # translated here with the full mapping. outer_data = ctx.map_nsdfg_field( sdfg_builder=self, nsdfg_field=inner_data, @@ -1389,7 +1389,13 @@ def construct_output_for_nested_sdfg( return outer_data - return gtx_utils.tree_map(construct_output_for_nested_sdfg)(lambda_result) + result = gtx_utils.tree_map(construct_output_for_nested_sdfg)(lambda_result) + + # Now that the nested SDFG is connected, its connectors are made equivalent to + # the data connected to them, by applying the symbol mapping inside it. + nsdfg_node.integrate_into_parent() + + return result def visit_Literal( self, diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py index 40259b8b0b..af5283d77a 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py @@ -97,6 +97,7 @@ def _create_field_operator_impl( output_type: ts.FieldType, map_exit: dace_nodes.MapExit | None, inner_dims: Sequence[gtx_common.Dimension], + is_zero_dim: bool, ) -> gtir_to_sdfg_types.FieldopData | None: """ Helper method to allocate a temporary array that stores one field computed @@ -119,6 +120,8 @@ def _create_field_operator_impl( the dataflow computes all dimensions of the domain by itself. inner_dims: The dimensions that the dataflow computes by itself, therefore written in full shape rather than element-wise. + is_zero_dim: The field operator has an empty domain, thus it computes a + zero-dimensional field regardless of `output_domain`. Returns: The field data descriptor, which includes the field access node in the @@ -130,7 +133,10 @@ def _create_field_operator_impl( assert output_domain == infer_domain.DomainAccessDescriptor.NEVER return None assert isinstance(output_domain, domain_utils.SymbolicDomain) - field_domain = gtir_domain.get_field_domain(output_domain) + # A zero-dimensional field operator is lowered to a trivial map, therefore its + # result is a zero-dimensional field even when domain inference has assigned it + # a domain, e.g. `make_const_list` of a scalar value used as `concat_where` branch. + field_domain = [] if is_zero_dim else gtir_domain.get_field_domain(output_domain) dataflow_output_desc = output_edge.result.dc_node.desc(ctx.sdfg) @@ -283,6 +289,6 @@ def create_field_operator( return gtx_utils.tree_map( lambda edge, field_domain, sym: _create_field_operator_impl( - ctx, sdfg_builder, edge, field_domain, sym.type, map_exit, inner_dims + ctx, sdfg_builder, edge, field_domain, sym.type, map_exit, inner_dims, len(domain) == 0 ) )(output, output_domain, output_symbols) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index 5a184686dc..5c8df1ca12 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -351,9 +351,15 @@ def _handle_dataflow_result_of_nested_sdfg( if bool(scan_column_size == 1): # Special case where we only write the last level of the scan column. - # We represent the inner result as a single value and let the scan loop override it. - inner_desc = dace.data.Scalar(inner_desc.dtype, transient=False) - inner_ctx.sdfg.arrays[inner_dataname] = inner_desc + # The inner result keeps the layout of the field operator domain, but with + # a single level on the column dimension, and the scan loop overrides it. + # It remains an array, so that the nested-SDFG connector is equivalent to + # the outer data connected to it. + assert isinstance(inner_desc, dace.data.Array) + inner_desc.set_shape( + [*inner_desc.shape[:scan_dim_index], 1, *inner_desc.shape[scan_dim_index + 1 :]] + ) + inner_desc.transient = False # We write the result to the output field after the loop region has ended. if len(inner_ctx.sdfg.states()) == 3: assert sorted(st.label for st in inner_ctx.sdfg.states()) == [ @@ -377,7 +383,8 @@ def _handle_dataflow_result_of_nested_sdfg( last_level_state = next( s for s in inner_ctx.sdfg.states() if s.label == "scan_last_level" ) - # Update the write edge inside the scan nested SDFG to write into a scalar rather than a 1D array. + # Move the write of the result from the scan loop to the state after the loop, + # so that only the last level is written. scan_compute_state = next(s for s in inner_ctx.sdfg.states() if s.label == "scan_compute") inner_output_node = next( n for n in scan_compute_state.data_nodes() if n.data == inner_dataname @@ -389,11 +396,16 @@ def _handle_dataflow_result_of_nested_sdfg( inner_write_edge = scan_compute_state.in_edges(inner_output_node)[0] assert isinstance(inner_write_edge.src, dace_nodes.AccessNode) assert isinstance(inner_write_edge.src.desc(inner_ctx.sdfg), dace.data.Scalar) + # Same element subset as the write inside the loop, but on the single level. + last_level_subset = copy.deepcopy( + inner_write_edge.data.get_dst_subset(inner_write_edge, scan_compute_state) + ) + last_level_subset[scan_dim_index] = (0, 0, 1) scan_compute_state.remove_node(inner_output_node) last_level_state.add_nedge( last_level_state.add_access(inner_write_edge.src.data), last_level_state.add_access(inner_dataname), - dace.Memlet(data=inner_dataname, subset="0", other_subset="0"), + dace.Memlet(data=inner_dataname, subset=last_level_subset, other_subset="0"), ) else: inner_desc.transient = False @@ -549,7 +561,7 @@ def translate_scan_fieldop( # The column dimension is excluded from the map range, because it is traversed by # the `LoopRegion` inside the stencil dataflow. scan_dim = next(r.dim for r in field_domain if sdfg_builder.is_column_axis(r.dim)) - return gtir_to_sdfg_fieldop.create_field_operator( + result = gtir_to_sdfg_fieldop.create_field_operator( ctx, field_domain, node.type, @@ -559,3 +571,9 @@ def translate_scan_fieldop( node.annex.domain, inner_dims=(scan_dim,), ) + + # Now that the nested SDFG is connected, its connectors are made equivalent to + # the data connected to them, by applying the symbol mapping inside it. + nsdfg_node.integrate_into_parent() + + return result diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py index c445ee7bc8..fe0abcb7b2 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py @@ -8,8 +8,6 @@ import copy import dataclasses -import functools -import warnings from typing import Any, Collection, Literal, Mapping, Optional, Sequence, TypeAlias, Union, overload import dace @@ -21,14 +19,12 @@ transformation as dace_transformation, ) from dace.sdfg import graph as dace_graph, nodes as dace_nodes +from dace.sdfg.replace import replace_datadesc_names as dace_replace_datadesc_names from dace.transformation.passes import analysis as dace_analysis from ordered_set import OrderedSet from gt4py.next import config as gtx_config -from gt4py.next.program_processors.runners.dace import ( - sdfg_utils as gtx_dace_utils, - transformations as gtx_transformations, -) +from gt4py.next.program_processors.runners.dace import transformations as gtx_transformations @dace_properties.make_properties @@ -370,10 +366,10 @@ def __lt__(self, other: object) -> bool: It is a pair of `list`s. The first `list` contains the "genuine consumers", this are the consumers that only read one element from the concat where node. Essentially, these consumers can be handled by `_replace_single_read()`. -The second `list` contains the "descending points", these are essentially nested SDFGs, -that consume the entire data from the concat where node (a nested SDFG that just -consumes a single element is classified as a "genuine consumer"). These are the nodes -that needs further processing. +The second `list` contains the "descending points", these are the nested SDFGs that +consume the concat where node. Since the connector of a nested SDFG is equivalent to +the data connected to it, a nested SDFG always accesses the whole data, even if it +only reads a single element. These are the nodes that needs further processing. """ @@ -722,72 +718,68 @@ def _configure_descending_point( parent: nested for nested, parent in nested_to_parent_name_mapping.items() } + # Symbols that the nested SDFG assigns itself, e.g. on an interstate edge or as a + # loop variable. They are not necessarily listed in `nsdfg.symbols`. + reassigned_symbols: set[str] = set() + for isedge in nsdfg.all_interstate_edges(): + reassigned_symbols.update(isedge.data.assignments.keys()) + for region in nsdfg.all_control_flow_regions(): + reassigned_symbols.update(region.new_symbols(nsdfg.symbols).keys()) + nested_initial_producer_specs: list[_ProducerSpec] = [] handled_data: dict[str, _ProducerSpec] = {} - full_repl_dict: dict[str, str] = {} # All known replacements. for parent_prod_spec in parent_producer_specs: parent_data_name = parent_prod_spec.data_name - # Compute the replacement mapping for symbols. - repl_dict: dict[str, str] = {} # For this producer. + # The symbols used by the producer are mapped 1:1 into the nested SDFG. The + # data descriptors mapped into the nested SDFG have to be equivalent to the + # ones in the parent SDFG (see `NestedSDFG.validate()`), so the symbols they + # use, e.g. in the shape, must have the same name and meaning inside. If the + # nested SDFG uses the name of the symbol for something else, either a data + # container or a symbol, including one it assigns itself, it is renamed there. for psym in sorted(parent_prod_spec.free_symbols): + if psym in nsdfg.arrays: + _rename_nested_data(state, nsdfg_node, psym, parent_to_nested_name_mapping) ptype = state.sdfg.symbols[psym] - if psym in full_repl_dict: - # The symbol was already handled in a previous producer, so we reuse it. - nested_symbol = full_repl_dict[psym] - assert nested_symbol in nsdfg.symbols and nsdfg.symbols[nested_symbol] == ptype - - elif ( - psym in symbol_mapping + if ( + psym not in reassigned_symbols + and psym in symbol_mapping and psym == str(symbol_mapping[psym]) and psym in nsdfg.symbols and nsdfg.symbols[psym] == ptype ): # The symbol is already mapped 1:1 into the nested sdfg -> nothing to do. - nested_symbol = psym - assert nested_symbol not in repl_dict - - else: - # The symbol is either not known or it is not mapped 1:1 or has the wrong type, - # in either case we have to create a new symbol inside the nested SDFG. - nested_symbol = nsdfg.add_symbol(psym, ptype, find_new_name=True) - assert nested_symbol not in symbol_mapping - symbol_mapping[nested_symbol] = psym + continue - if psym != nested_symbol: - repl_dict[psym] = nested_symbol - if psym not in full_repl_dict: - full_repl_dict[psym] = nested_symbol + if psym in nsdfg.symbols or psym in symbol_mapping or psym in reassigned_symbols: + renamed_symbol = _find_new_nested_symbol(nsdfg, psym, reassigned_symbols) + nsdfg.replace_dict({psym: renamed_symbol}) + if psym in symbol_mapping: + symbol_mapping[renamed_symbol] = symbol_mapping.pop(psym) + if psym in reassigned_symbols: + reassigned_symbols.discard(psym) + reassigned_symbols.add(renamed_symbol) + nsdfg.add_symbol(psym, ptype) + symbol_mapping[psym] = psym # Compute the nested data descriptor. if parent_data_name in handled_data: # The data has already been handled before. So we can simply reuse it. - # Symbol renaming has already been handled. already_handled_prod_spec = handled_data[parent_data_name] nested_desc = already_handled_prod_spec.desc.clone() elif parent_data_name in parent_to_nested_name_mapping: # We have not handled the data, but it is already mapped into the nested # SDFG, for other reasons. Thus we will reuse this data descriptor. - # The symbol renaming is already done and not necessarily described - # through `repl_dict`. nested_data_name = parent_to_nested_name_mapping[parent_data_name] nested_desc = nsdfg.arrays[nested_data_name].clone() assert not nested_desc.transient else: # The data is not yet mapped into the nested SDFG, so we have to create - # a new one. And we have to apply symbol renaming on it. In addition - # we have to make sure that it is a global. + # a new one, and we have to make sure that it is a global. nested_desc = parent_prod_spec.desc.clone() nested_desc.transient = False - if repl_dict: - dace_sym.safe_replace( - mapping=repl_dict, - replace_callback=functools.partial( - dace.sdfg.replace_properties_dict, nested_desc - ), - ) nested_data_name = nsdfg.add_datadesc(parent_data_name, nested_desc, find_new_name=True) # We also need to map it into the nested SDFG. @@ -807,21 +799,11 @@ def _configure_descending_point( nested_data_name, dtype=dace.pointer(nested_desc.dtype) ) - # Apply symbol renaming on offset and subset; descriptor was handled above. - nested_offset = copy.deepcopy(parent_prod_spec.offset) - nested_subset = copy.deepcopy(parent_prod_spec.subset) - if repl_dict: - for nested_set in [nested_offset, nested_subset]: - dace_sym.safe_replace( # Performs inplace replacement - mapping=repl_dict, - replace_callback=nested_set.replace, - ) - nested_initial_producer_specs.append( _ProducerSpec( data_name=nested_data_name, - offset=nested_offset, - subset=nested_subset, + offset=copy.deepcopy(parent_prod_spec.offset), + subset=copy.deepcopy(parent_prod_spec.subset), desc=nested_desc, data_source={}, # Intentionally empty. ) @@ -833,6 +815,64 @@ def _configure_descending_point( return nested_initial_producer_specs +def _find_new_nested_symbol(nsdfg: dace.SDFG, name: str, reserved: Collection[str]) -> str: + """Returns a name, different from `name`, that is unused in `nsdfg` and not in `reserved`. + + `reserved` is needed because symbols that are only assigned inside `nsdfg`, e.g. + on an interstate edge, are not necessarily known to `nsdfg.is_name_free()`. + """ + taken = set(reserved) | {name} + while True: + new_name = dace_data.find_new_name(name, taken) + if nsdfg.is_name_free(new_name): + return new_name + taken.add(new_name) + + +def _rename_nested_data( + state: dace.SDFGState, + nsdfg_node: dace_nodes.NestedSDFG, + data_name: str, + parent_to_nested_name_mapping: dict[str, str], +) -> None: + """Renames the data container `data_name` inside the nested SDFG `nsdfg_node`. + + If the data is mapped into the nested SDFG, the connector of `nsdfg_node` is + renamed as well. The edges in `state` are modified in place, thus references to + them, such as `_FinalConsumerSpec.edge`, remain valid. `parent_to_nested_name_mapping` + is updated in place. + + Args: + state: The state containing `nsdfg_node`. + nsdfg_node: The nested SDFG in which the data should be renamed. + data_name: The name of the data inside the nested SDFG. + parent_to_nested_name_mapping: Maps the names of the data in the parent SDFG + to the names of the data inside the nested SDFG. + """ + nsdfg: dace.SDFG = nsdfg_node.sdfg + new_data_name = nsdfg.find_new_symbol(data_name) + dace_replace_datadesc_names(nsdfg, {data_name: new_data_name}) + + for parent_data_name, nested_data_name in parent_to_nested_name_mapping.items(): + if nested_data_name == data_name: + parent_to_nested_name_mapping[parent_data_name] = new_data_name + + if data_name in nsdfg_node.in_connectors: + conn_type = nsdfg_node.in_connectors[data_name] + nsdfg_node.remove_in_connector(data_name) + nsdfg_node.add_in_connector(new_data_name, dtype=conn_type) + for iedge in state.in_edges(nsdfg_node): + if iedge.dst_conn == data_name: + iedge.dst_conn = new_data_name + if data_name in nsdfg_node.out_connectors: + conn_type = nsdfg_node.out_connectors[data_name] + nsdfg_node.remove_out_connector(data_name) + nsdfg_node.add_out_connector(new_data_name, dtype=conn_type) + for oedge in state.out_edges(nsdfg_node): + if oedge.src_conn == data_name: + oedge.src_conn = new_data_name + + def _map_data_into_nested_scopes( state: dace.SDFGState, scope_dict: Mapping[dace_nodes.Node, _ScopeLocation], @@ -1302,27 +1342,20 @@ def _find_consumer_specs_single_source_single_level( return None raise ValueError(f"Expected that partition for {concat_node} exists but it does not.") - # Now wet and partition the consumer. Most importantly test if they only read - # a single element, in which case they are genuine consumers this applies to - # _all_ nodes, even nested SDFGs. Otherwise it might open up a "new level". - # For this the consumer must be a nested SDFG that reads the _whole_ concat - # where node. - concat_where_shape = dace_sbs.Range.from_array(concat_node.desc(state.sdfg)) + # Now wet and partition the consumer. A nested SDFG always opens up a "new level": + # its connector is equivalent to the concat where data (see `NestedSDFG.validate()`), + # so the nested SDFG accesses the data with the same indices as here, even if it + # only reads a single element. Thus, the accesses have to be replaced inside it. + # All other consumers have to read a single element, which makes them genuine + # consumers. stairs_to_deeper_levels: list[_FinalConsumerSpec] = [] # Better name appreciated. consumer_specs: list[_FinalConsumerSpec] = [] for consumer_spec in all_consumers: - consumed_subset = consumer_spec.consumed_subset(state) - if consumed_subset.num_elements() == 1: # Real consumer + if isinstance(consumer_spec.consumer, dace_nodes.NestedSDFG): + stairs_to_deeper_levels.append(consumer_spec) + elif consumer_spec.consumed_subset(state).num_elements() == 1: # Real consumer if not for_check: consumer_specs.append(consumer_spec) - elif isinstance(consumer_spec.consumer, dace_nodes.NestedSDFG) and ( - consumed_subset.covers(concat_where_shape) - or _handle_special_case_of_gt4py_scan_point( - state, consumer_spec, concat_node, consumed_subset - ) - ): - # The whole array is mapped into the nested SDFG. - stairs_to_deeper_levels.append(consumer_spec) else: if for_check: return None @@ -1333,101 +1366,6 @@ def _find_consumer_specs_single_source_single_level( return sorted(consumer_specs), sorted(stairs_to_deeper_levels) -def _handle_special_case_of_gt4py_scan_point( - state: dace.SDFGState, - descending_point: _FinalConsumerSpec, - concat_node: dace_nodes.AccessNode, - consumed_subset: dace_sbs.Range, -) -> bool: - """Performs special checking for cases where data is not properly mapped into a nested SDFG. - - In certain cases, especially for scans, DaCe Memlet propagation (or related) will - fail to properly annotate the consumer Memlet that maps the data inside a nested - SDFG. This function applies some heuristic checks if the nested SDFG can be - processed or not. - - The pathological case is a nested SDFG inside a Map scope, which is used for the - scan expressions. By construction, the scan nested SDFG does access to a single - point in the horizontal domain. However, for unknown reason, DaCe replaces the - point access with a subset, as an example `[i_Cell_gtx_horizontal, 0:3]` becomes - `[0:i_Cell_gtx_horizontal + 1, 0:3]`. Thus, `consumed_subset` is not a point - nor the full shape either, but we know that it is safe to apply the transformation. - """ - assert isinstance(descending_point.consumer, dace_nodes.NestedSDFG) - nsdfg: dace_nodes.NestedSDFG = descending_point.consumer - - if _handle_special_case_of_gt4py_scan_point_impl( - state, descending_point, concat_node, consumed_subset - ): - warnings.warn( - f"Special rule applied to `concat_where`-inline `{concat_node.data}` into `{nsdfg.label}`.", - stacklevel=1, - ) - return True - else: - warnings.warn( - f"Special rule applied to `concat_where`-inline `{concat_node.data}` into `{nsdfg.label}` was rejected.", - stacklevel=1, - ) - return False - - -def _handle_special_case_of_gt4py_scan_point_impl( - state: dace.SDFGState, - descending_point: _FinalConsumerSpec, - concat_node: dace_nodes.AccessNode, - consumed_subset: dace_sbs.Range, -) -> bool: - # There must be one node in the nested SDFG that is not a state. - # TODO(phimuell): Come up with a better test. - nsdfg: dace_nodes.NestedSDFG = descending_point.consumer - if all(isinstance(node, dace.SDFGState) for node in nsdfg.sdfg.nodes()): - return False - - # At this point `state` should be in a valid state so that it is safe to - # compute the scope dict. - scope_dict = state.scope_dict() - if scope_dict[nsdfg] is None: - return False - - parent_desc = concat_node.desc(state.sdfg) - nested_desc = nsdfg.sdfg.arrays[descending_point.edge.dst_conn] - - if type(parent_desc) is not type(nested_desc): - return False - # TODO(phimuell): Make the test involving the shape a bit smarter. - if len(parent_desc.shape) != len(nested_desc.shape): - return False - - if not all((start == 0) == True for start in consumed_subset.min_element()): # noqa: E712 [true-false-comparison] # SymPy comparison - return False - - # Find all map parameters. - edge = descending_point.edge - map_params: set[str] = set() - while isinstance(edge.src, dace_nodes.MapEntry): - assert edge.src_conn.startswith("OUT") - map_params.update(edge.src.map.params) - edge = next( - iter(e for e in state.in_edges_by_connector(edge.src, "IN_" + edge.src_conn[4:])) - ) - - assert scope_dict[edge.dst] is None # really strange case. - - for i, end in enumerate(consumed_subset.max_element()): - if gtx_dace_utils.is_compile_time_size(end): - if (int(end) + 1) != parent_desc.shape[i]: # `+1` because of storage format. - return False - # In case of a symbol, we only check for the pathological case, i.e. a Map - # parameter is the end value. We also allow only one symbol value. - elif (end_str := str(end)) in map_params: - map_params.discard(end_str) - else: - return False - - return True - - def _cleanup_memlet_path(state: dace.SDFGState, consumer_spec: _FinalConsumerSpec) -> None: """Similar to `remove_edge_and_dangling_path()` but special to our case. diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/simplify.py b/src/gt4py/next/program_processors/runners/dace/transformations/simplify.py index deccbf82a6..6515e48c93 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/simplify.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/simplify.py @@ -1329,9 +1329,6 @@ def apply( tmp_out_subset = dace_subsets.Range.from_array(tmp_desc) assert glob_in_subset is not None - # Recursively visit the nested SDFGs for mapping of strides from inner to outer array - gtx_transformations.gt_map_strides_to_src_nested_sdfg(sdfg, graph, map_to_tmp_edge, glob_ac) - # We now remove the `tmp` node, and create a new connection between # the global node and the map exit. new_map_to_glob_edge = graph.add_edge( @@ -1369,3 +1366,12 @@ def apply( curr_edge.data.data = glob_data if curr_dst_subset is not None: curr_dst_subset.offset(correcting_offset, negative=False) + # A NestedSDFG inside the Map now writes into `G`, thus its connector, + # which has to be equivalent to the data connected to it, is restated. + if isinstance(curr_edge.src, dace_nodes.NestedSDFG): + gtx_transformations.utils.restate_nested_sdfg_connector( + nsdfg_node=curr_edge.src, + connector=curr_edge.src_conn, + new_desc=glob_ac.desc(sdfg), + ss_offset=correcting_offset.min_element(), + ) 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 ca5be147c7..9a9fe664a0 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/strides.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/strides.py @@ -10,14 +10,10 @@ import dace from dace import data as dace_data -from dace.sdfg import nodes as dace_nodes +from dace.sdfg import dealias as dace_dealias, nodes as dace_nodes from gt4py.next import common as gtx_common -from gt4py.next.program_processors.runners.dace import ( - sdfg_args as gtx_dace_args, - sdfg_utils as gtx_dace_utils, - transformations as gtx_transformations, -) +from gt4py.next.program_processors.runners.dace import transformations as gtx_transformations PropagatedStrideRecord: TypeAlias = tuple[str, dace_nodes.NestedSDFG] @@ -317,9 +313,9 @@ def _gt_map_strides_to_nested_sdfg_src_dst( When the function encounters a NestedSDFG it will determine what data the `outer_node` is mapped to on the inside of the NestedSDFG. - It will then replace the stride of the inner descriptor with the ones - of the outside. Afterwards it will recursively propagate the strides - inside the NestedSDFG. + It will then set the strides of the inner descriptor to the ones outside, see + `_gt_map_strides_into_nested_sdfg()`. Afterwards it will recursively + propagate the strides inside the NestedSDFG. During this propagation the function will follow any edges. If the function reaches a NestedSDFG that is listed inside `processed_nsdfgs` @@ -361,12 +357,6 @@ def get_node(edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet]) -> dace_node def get_inner_data(edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet]) -> str: return edge.dst_conn - def get_subset( - state: dace.SDFGState, - edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet], - ) -> dace.subsets.Subset: - return edge.data.get_src_subset(edge, state) - def next_edges_by_connector( state: dace.SDFGState, edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet], @@ -385,12 +375,6 @@ def get_node(edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet]) -> dace_node def get_inner_data(edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet]) -> str: return edge.src_conn - def get_subset( - state: dace.SDFGState, - edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet], - ) -> dace.subsets.Subset: - return edge.data.get_dst_subset(edge, state) - def next_edges_by_connector( state: dace.SDFGState, edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet], @@ -420,14 +404,10 @@ def next_edges_by_connector( # Mark this nested SDFG as processed. processed_nsdfgs.add(process_record) - # Now set the stride of the data descriptor inside the nested SDFG to - # the ones it has outside. + # Now set the strides of the data descriptor inside the nested SDFG to the + # ones outside. _gt_map_strides_into_nested_sdfg( - sdfg=sdfg, - nsdfg_node=nsdfg_node, - inner_data=inner_data, - outer_subset=get_subset(state, edge), - outer_desc=outer_node.desc(sdfg), + sdfg=sdfg, edge=edge, nsdfg_node=nsdfg_node, inner_data=inner_data ) # Since the function call above is not recursive we have now to propagate @@ -454,114 +434,65 @@ def next_edges_by_connector( def _gt_map_strides_into_nested_sdfg( sdfg: dace.SDFG, - nsdfg_node: dace.nodes.NestedSDFG, + edge: dace.sdfg.graph.MultiConnectorEdge[dace.Memlet], + nsdfg_node: dace_nodes.NestedSDFG, inner_data: str, - outer_subset: dace.subsets.Subset, - outer_desc: dace_data.Data, ) -> None: - """Modify the strides of `inner_data` inside `nsdfg_node` to match `outer_desc`. + """Sets the strides of the connector `inner_data` to the ones of the outer data. + + The data descriptor of a NestedSDFG connector has to be equivalent to the data + connected to it on the outside, i.e. it must have the same shape and strides, + see `NestedSDFG.validate()`. The function handles the case that only the + strides of the outer data have changed. The symbols used by the new strides + are mapped 1:1 into the NestedSDFG. - `inner_data` is the name of a data descriptor inside the NestedSDFG. - The function will then modify the strides of `inner_data`, assuming this - is an array, to match the ones of `outer_desc`. + If a transformation connects different data to the connector, it has to restate + the connector itself, see `restate_nested_sdfg_connector()`, because only the + transformation knows where the old data is located inside the new one. Args: sdfg: The SDFG containing the NestedSDFG. - nsdfg_node: The node in the parent SDFG that contains the NestedSDFG. - inner_data: The name of the data descriptor that should be processed - inside the NestedSDFG (by construction also a connector name). - outer_subset: The subset that describes what part of the outer data is - mapped into the NestedSDFG. - outer_desc: The data descriptor of the data on the outside. - - Todo: - - Handle explicit dimensions of size 1. - - What should we do if the stride symbol is used somewhere else, creating an - alias is probably not the right thing? - - Handle the case if the outer stride symbol is already used in another - context inside the Neste SDFG. + edge: The edge between the outer data and the connector `inner_data`. + nsdfg_node: The NestedSDFG that should be processed. + inner_data: The name of the connector, and of the data inside the NestedSDFG. + + Raises: + ValueError: If the connector is still not equivalent to the outer data after + updating the strides, or if a stride symbol has a different meaning + inside the NestedSDFG. """ - # We need to compute the new strides. In the following we assume that the - # relative order of the dimensions does not change, but we support the case - # where some dimensions of the outer data descriptor are not present on the - # inside. For example this happens for the Memlet `a[__i0, 0:__a_size1]`. We - # detect this case by checking if the Memlet subset in that dimension has size 1. - # TODO(phimuell): Handle the case were some additional size 1 dimensions are added. - inner_desc: dace_data.Data = nsdfg_node.sdfg.arrays[inner_data] - inner_shape = inner_desc.shape - - outer_shape = outer_desc.shape - outer_strides = outer_desc.strides - outer_inflow = outer_subset.size() - - if isinstance(inner_desc, dace_data.Scalar): - # A scalar does not have a stride that must be propagated. + nsdfg: dace.SDFG = nsdfg_node.sdfg + if inner_data not in dace_dealias.windowed_connectors(nsdfg): return - # Now determine the new stride that is needed on the inside. - new_strides: list = [] - if len(outer_shape) == len(inner_shape): - # The inner and the outer descriptor have the same dimensionality. - # We now have to decide if we should take the stride from the outside, - # which happens for example in case of `A[0:N, 0:M] -> B[N, M]`, or if we - # must take 1, which happens if we do `A[0:N, i] -> B[N, 1]`, we detect that - # based on the volume that flows in. - for dim_ostride, dim_oinflow in zip(outer_strides, outer_inflow, strict=True): - new_strides.append(1 if dim_oinflow == 1 else dim_ostride) - - elif len(inner_shape) < len(outer_shape): - # There are less dimensions on the inside than on the outside. This means - # that some were sliced away. We detect this case by checking if the Memlet - # subset in that dimension has size 1. - # NOTE: That this is not always correct as it might be possible that there - # are some explicit size 1 dimensions at several places. - new_strides = [] - for dim_ostride, dim_oinflow in zip(outer_strides, outer_inflow, strict=True): - if dim_oinflow == 1: - pass - else: - new_strides.append(dim_ostride) - assert len(new_strides) <= len(inner_shape) - else: - # The case that we have more dimensions on the inside than on the outside. - # This is currently not supported. - raise NotImplementedError("NestedSDFGs can not be used to increase the rank.") - - if len(new_strides) != len(inner_shape): - raise ValueError("Failed to compute the inner strides.") - - # For the strides of the arrays inside the nested SDFG we will create a new unique - # symbol which is initialized, through the symbol mapping, to the value of this - # stride on the outside. The benefit is that only the mapped container is affected - # and nothing else. Consider for example the case where initially two arrays - # inside the nested SDFG use the same stride symbol, but only one array is mapped. - # The main drawback is that the logical connection is lost, thus if the old - # stride symbol is used somewhere inside the nested SDFG, with the expectation - # that it corresponds to the stride of the inner container, then this connection - # is lost. However, this is probably not much of an issue for the strides, but - # more problematic for the shape, whose symbols are likely to appear as loop bounds. - for i, dim_ostride in enumerate(new_strides): - if gtx_dace_utils.is_compile_time_size(dim_ostride): - # A literal stride (e.g. `1`) can be set directly - new_strides[i] = dim_ostride - else: - if dim_ostride.is_symbol: - # Try reusing the same symbol name as the outer stride, but find a new name if already used. - dim_istride = nsdfg_node.sdfg.add_symbol( - dim_ostride.name, sdfg.symbols[dim_ostride.name], find_new_name=True - ) - else: - # Map a symbolic expression such as `value1 - value2` to a new stride symbol. - dim_istride = nsdfg_node.sdfg.add_symbol( - f"__{inner_data}_stride_{i}", - gtx_dace_args.FIELD_SYMBOL_DTYPE, - find_new_name=True, + inner_desc = nsdfg.arrays[inner_data] + outer_desc = sdfg.arrays[edge.data.data] + if ( + isinstance(inner_desc, dace_data.Array) + and not isinstance(inner_desc, dace_data.View) + and len(inner_desc.shape) == len(outer_desc.strides) + ): + for sym in sorted( + str(fsym) + for stride in outer_desc.strides + if dace.symbolic.issymbolic(stride) + for fsym in stride.free_symbols + ): + if sym not in nsdfg.symbols: + nsdfg.add_symbol(sym, sdfg.symbols[sym]) + nsdfg_node.symbol_mapping[sym] = dace.symbolic.pystr_to_symbolic(sym) + elif str(nsdfg_node.symbol_mapping.get(sym, "")) != sym: + raise ValueError( + f"Can not map the stride symbol '{sym}' into NestedSDFG" + f" '{nsdfg_node.label}', because it has a different meaning there." ) - new_strides[i] = dace.symbolic.pystr_to_symbolic(dim_istride) - nsdfg_node.symbol_mapping[dim_istride] = dim_ostride + inner_desc.set_shape(inner_desc.shape, outer_desc.strides) - # We have to replace the `strides` attribute of the inner descriptor. - inner_desc.set_shape(inner_desc.shape, new_strides) + if inner_data in dace_dealias.windowed_connectors(nsdfg): + raise ValueError( + f"The connector '{inner_data}' of NestedSDFG '{nsdfg_node.label}' is not" + f" equivalent to the data '{edge.data.data}' connected to it." + ) def _gt_find_toplevel_data_accesses( diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py index 73cf02a7f2..a365ab154a 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py @@ -15,7 +15,7 @@ import dace from dace import data as dace_data, subsets as dace_sbs, symbolic as dace_sym from dace.libraries import standard as dace_stdlib -from dace.sdfg import graph as dace_graph, nodes as dace_nodes +from dace.sdfg import dealias as dace_dealias, graph as dace_graph, nodes as dace_nodes from dace.transformation.passes import analysis as dace_analysis from ordered_set import OrderedSet @@ -542,12 +542,29 @@ def reconfigure_dataflow_after_rerouting( assert subset_to_adjust is not None subset_to_adjust.offset(ss_offset, negative=False) + # A NestedSDFG inside the Map scope now accesses `new_node`. + nested_node, nested_conn = ( + (edge_to_adjust.src, edge_to_adjust.src_conn) + if is_producer_edge + else (edge_to_adjust.dst, edge_to_adjust.dst_conn) + ) + if isinstance(nested_node, dace_nodes.NestedSDFG): + restate_nested_sdfg_connector( + nsdfg_node=nested_node, + connector=nested_conn, + new_desc=new_node.desc(sdfg), + ss_offset=ss_offset, + ) + elif isinstance(other_node, dace_nodes.NestedSDFG): - # We have obviously to adjust the strides, however, this is done outside - # this function. - # TODO(phimuell): Look into the implication that we not necessarily pass - # the full array, but essentially slice a bit. - pass + # The connector has to be equivalent to `new_node`, which also sets the + # strides, and the accesses inside have to be shifted. + restate_nested_sdfg_connector( + nsdfg_node=other_node, + connector=new_edge.src_conn if is_producer_edge else new_edge.dst_conn, + new_desc=new_node.desc(sdfg), + ss_offset=ss_offset, + ) elif isinstance(other_node, (dace_stdlib.Reduce, gtx_lib.ReduceWithSkipValues)): # For now we only handle the case that the reduction node is writing into @@ -571,6 +588,68 @@ def reconfigure_dataflow_after_rerouting( ) +def restate_nested_sdfg_connector( + nsdfg_node: dace_nodes.NestedSDFG, + connector: str, + new_desc: dace_data.Data, + ss_offset: Sequence[dace_sym.SymExpr] | None, +) -> None: + """Restates `connector` of `nsdfg_node` as the new data connected to it. + + The data descriptor of a NestedSDFG connector has to be equivalent to the data + connected to it (see `NestedSDFG.validate()`), and the accesses inside use the + coordinates of that data. When a transformation connects different data to the + connector, e.g. through `reroute_edge()`, the connector has to adopt `new_desc` + and every access inside the NestedSDFG, and inside the NestedSDFGs below it, has + to be shifted by `ss_offset`. + + Args: + nsdfg_node: The NestedSDFG whose connector is connected to different data. + connector: The name of the connector, and of the data inside the NestedSDFG. + new_desc: The data descriptor of the data that is now connected to `connector`. + ss_offset: The position of the old data inside the new one, i.e. the offset + that has to be added to the accesses. If `None` then `new_desc` has to + be a scalar. + + Raises: + NotImplementedError: If the new data has a different rank than the old one, or + if a symbol used by `new_desc` or `ss_offset` has a different meaning + inside the NestedSDFG. + """ + nsdfg = nsdfg_node.sdfg + old_desc = nsdfg.arrays[connector] + if ss_offset is None: + if not isinstance(new_desc, dace_data.Scalar): + raise TypeError(f"Passed 'None' as 'ss_offset' but '{new_desc}' is not a scalar.") + elif len(old_desc.shape) != len(new_desc.shape) or len(ss_offset) != len(new_desc.shape): + raise NotImplementedError( + f"Can not restate the connector '{connector}' of NestedSDFG '{nsdfg_node.label}'" + f" with shape {old_desc.shape} as data with shape {new_desc.shape}." + ) + + # The symbols are passed 1:1 into the NestedSDFG, thus they must not be used there + # for something else. + passed_symbols = {str(sym) for sym in new_desc.free_symbols} + if ss_offset is not None: + passed_symbols.update( + str(sym) for off in ss_offset if dace_sym.issymbolic(off) for sym in off.free_symbols + ) + for sym in sorted(passed_symbols): + if sym in nsdfg.arrays or str(nsdfg_node.symbol_mapping.get(sym, sym)) != sym: + raise NotImplementedError( + f"Can not restate the connector '{connector}' of NestedSDFG '{nsdfg_node.label}'," + f" because the symbol '{sym}' has a different meaning inside it." + ) + + dace_dealias.reduce_connector( + nsdfg, + connector, + reduced_desc=new_desc, + # Where the origin of the new data is located in the coordinates of the old data. + offset=None if ss_offset is None else [-off for off in ss_offset], + ) + + def find_upstream_nodes( start: dace_nodes.Node, state: dace.SDFGState, diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py index 5a68f44961..7ad539c866 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_gtir_to_sdfg.py @@ -1223,14 +1223,13 @@ def test_gtir_neighbors_as_input(): gtir.SetAt( expr=im.let( "x", - im.as_fieldop_neighbors("V2E", "edges", outer_domain), + im.as_fieldop_neighbors("V2E", "edges"), )( im.as_fieldop( im.lambda_("it")( im.reduce("plus", im.literal_from_value(init_value))(im.deref("it")) - ), - inner_domain, - )(im.op_as_fieldop(im.map_list("divides"), inner_domain)("v2e_field", "x")) + ) + )(im.op_as_fieldop(im.map_list("divides"))("v2e_field", "x")) ), domain=outer_domain, target=gtir.SymRef(id="vertices"), @@ -1238,9 +1237,7 @@ def test_gtir_neighbors_as_input(): ], ) - # skip domain inference to test correct symbol mapping in let-statements, - # based on canonical order of field dimensions - sdfg = build_dace_sdfg(testee, SIMPLE_MESH.offset_provider, skip_domain_inference=True) + sdfg = build_dace_sdfg(testee, SIMPLE_MESH.offset_provider) connectivity_V2E = SIMPLE_MESH.offset_provider["V2E"] diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py index 1b2a784a53..ff5c1e372c 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py @@ -1343,15 +1343,16 @@ def test_concat_where_multi_level_nesting(): def _make_concat_where_nested_single_element_consumer() -> tuple[ dace.SDFG, dace.SDFGState, dace_nodes.AccessNode, dace_nodes.NestedSDFG, dace_nodes.NestedSDFG ]: - def make_single_element_consumer(name) -> dace.SDFG: + def make_single_element_consumer(name: str, in_index: str, out_index: str) -> dace.SDFG: + # The nested SDFG reads a single element of `c` and writes a single element of + # `d`. Since a nested SDFG connector has to be equivalent to the data it is + # connected to, the connectors are the full arrays and they are accessed with + # the same indices as on the outside. sdfg = dace.SDFG(name) state = sdfg.add_state() for aname in "ab": - sdfg.add_scalar( - aname, - dtype=dace.float64, - transient=False, - ) + sdfg.add_array(aname, shape=(10,), dtype=dace.float64, transient=False) + sdfg.add_symbol("__i", dace.int32) tlet = state.add_tasklet( f"single_element_consumer_{name}", @@ -1359,8 +1360,8 @@ def make_single_element_consumer(name) -> dace.SDFG: outputs={"__out"}, code="__out = __in + 1.9", ) - state.add_edge(state.add_access("a"), None, tlet, "__in", dace.Memlet("a[0]")) - state.add_edge(tlet, "__out", state.add_access("b"), None, dace.Memlet("b[0]")) + state.add_edge(state.add_access("a"), None, tlet, "__in", dace.Memlet(f"a[{in_index}]")) + state.add_edge(tlet, "__out", state.add_access("b"), None, dace.Memlet(f"b[{out_index}]")) sdfg.validate() return sdfg @@ -1378,7 +1379,7 @@ def make_single_element_consumer(name) -> dace.SDFG: state.add_nedge(b, c, dace.Memlet("b[3:8] -> [5:10]")) top_level_nsdfg = state.add_nested_sdfg( - make_single_element_consumer("top_level"), + make_single_element_consumer("top_level", in_index="0", out_index="9"), inputs={"a"}, outputs={"b"}, symbol_mapping={}, @@ -1387,10 +1388,10 @@ def make_single_element_consumer(name) -> dace.SDFG: state.add_edge(top_level_nsdfg, "b", d, None, dace.Memlet("d[9]")) nested_nsdfg = state.add_nested_sdfg( - make_single_element_consumer("nested"), + make_single_element_consumer("nested", in_index="__i + 1", out_index="__i"), inputs={"a"}, outputs={"b"}, - symbol_mapping={}, + symbol_mapping={"__i": "__i"}, ) me, mx = state.add_map("map", ndrange={"__i": "0:9"}) @@ -1434,20 +1435,14 @@ def test_concat_where_nested_single_element_consumer(): assert concat_node not in access_nodes_after assert concat_node.data not in sdfg.arrays - # Since the nested SDFG only consumed a single element they are not manipulated in - # any way, essentially they are a big Tasklet. But their surrounding has changed. - assert state.in_degree(nested_nsdfg) == 1 - assert nested_nsdfg.sdfg.arrays.keys() == {"a", "b"} - assert all( - isinstance(iedge.src, dace_nodes.AccessNode) and iedge.src not in access_nodes_before - for iedge in state.in_edges(nested_nsdfg) - ) - assert state.in_degree(top_level_nsdfg) - assert top_level_nsdfg.sdfg.arrays.keys() == {"a", "b"} - assert all( - isinstance(iedge.src, dace_nodes.AccessNode) and iedge.src not in access_nodes_before - for iedge in state.in_edges(top_level_nsdfg) - ) + # A nested SDFG accesses the whole data connected to it, even if it only reads a + # single element. Thus the replacement was performed inside of it: the concat + # where node is no longer read and its producers are mapped into the nested SDFG. + for nsdfg in [top_level_nsdfg, nested_nsdfg]: + assert "a" not in nsdfg.in_connectors + assert "a" not in nsdfg.sdfg.arrays + assert state.in_degree(nsdfg) == 2 + assert {iedge.data.data for iedge in state.in_edges(nsdfg)} == {"a", "b"} csdfg = util.compile_and_run_sdfg(sdfg, **res) assert util.compare_sdfg_res(ref=ref, res=res) @@ -1548,15 +1543,17 @@ def test_concat_where_nested_symbolic_bound( assert concat_node not in access_nodes_after assert concat_node.data not in sdfg.arrays assert state.in_degree(nested_sdfg) == 2 - assert str(nested_sdfg.symbol_mapping[nested_inc_symb]) == inc_symb if has_blocking_symbol: + # `split_sym` is mapped 1:1 into the nested SDFG, so the symbol that the nested + # SDFG used under this name, for the increment, has been renamed. assert len(nested_sdfg.symbol_mapping) == 2 + assert str(nested_sdfg.symbol_mapping[split_sym]) == split_sym - nested_split_sym = next( - iter(ss for s in nested_sdfg.symbol_mapping if (ss := str(s)) != nested_inc_symb) + renamed_inc_symb = next( + iter(ss for s in nested_sdfg.symbol_mapping if (ss := str(s)) != split_sym) ) - assert str(nested_sdfg.symbol_mapping[nested_split_sym]) == split_sym + assert str(nested_sdfg.symbol_mapping[renamed_inc_symb]) == inc_symb else: assert nested_sdfg.symbol_mapping.keys() == {nested_inc_symb, split_sym} @@ -1661,18 +1658,148 @@ def test_concat_where_with_symbolic_top_size(): assert concat_node not in access_nodes_after assert concat_node.data not in sdfg.arrays assert state.in_degree(nested_sdfg) == 2 - assert str(nested_sdfg.symbol_mapping[nested_inc_symb]) == inc_symb + # `symbolic_size` is mapped 1:1 into the nested SDFG, so the symbol that the nested + # SDFG used under this name, for the increment, has been renamed. assert len(nested_sdfg.symbol_mapping) == 2 - nested_symbolic_size = next( - iter(ss for s in nested_sdfg.symbol_mapping if (ss := str(s)) != nested_inc_symb) + assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size + + renamed_inc_symb = next( + iter(ss for s in nested_sdfg.symbol_mapping if (ss := str(s)) != symbolic_size) ) - assert str(nested_sdfg.symbol_mapping[nested_symbolic_size]) == symbolic_size + assert str(nested_sdfg.symbol_mapping[renamed_inc_symb]) == inc_symb csdfg = util.compile_and_run_sdfg(sdfg, **res) assert util.compare_sdfg_res(ref=ref, res=res) +def test_concat_where_with_symbolic_size_clashing_with_nested_data(): + # The symbol `n`, that defines the size of the producer `a`, has to be mapped into + # the nested SDFG, which uses `n` as the name of its output connector. + symbolic_size = "n" + + nested = dace.SDFG("nested") + nested_state = nested.add_state() + for aname in ["a", symbolic_size]: + nested.add_array(aname, shape=(10,), dtype=dace.float64, transient=False) + nested_state.add_mapped_tasklet( + "nested_map", + map_ranges={"__i": "0:10"}, + inputs={"__in": dace.Memlet("a[__i]")}, + outputs={"__out": dace.Memlet(f"{symbolic_size}[__i]")}, + code="__out = __in + 1.0", + external_edges=True, + ) + nested.validate() + + sdfg = dace.SDFG(util.unique_name("concat_where_symbolic_size_clashing_with_nested_data")) + state = sdfg.add_state() + sdfg.add_symbol(symbolic_size, dace.int32) + for aname in "abcd": + sdfg.add_array( + name=aname, + shape=((10,) if aname != "a" else (dace.symbolic.pystr_to_symbolic(symbolic_size),)), + dtype=dace.float64, + transient=(aname == "c"), + ) + + a, b, c, d = (state.add_access(aname) for aname in "abcd") + state.add_nedge(a, c, dace.Memlet("a[1:6] -> [0:5]")) + state.add_nedge(b, c, dace.Memlet("b[3:8] -> [5:10]")) + + nested_sdfg = state.add_nested_sdfg( + sdfg=nested, inputs={"a"}, outputs={symbolic_size}, symbol_mapping={} + ) + state.add_edge(c, None, nested_sdfg, "a", dace.Memlet("c[0:10]")) + state.add_edge(nested_sdfg, symbolic_size, d, None, dace.Memlet("d[0:10]")) + sdfg.validate() + + ref, res = util.make_sdfg_args(sdfg, symbols={symbolic_size: 10}) + util.compile_and_run_sdfg(sdfg, **ref) + + gtx_transformations.gt_replace_concat_where_node(state=state, sdfg=sdfg, concat_node=c) + sdfg.validate() + + assert c.data not in sdfg.arrays + assert state.in_degree(nested_sdfg) == 2 + assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size + assert symbolic_size in nested_sdfg.sdfg.symbols + + # The output connector, and the data inside the nested SDFG, has been renamed. + assert symbolic_size not in nested_sdfg.sdfg.arrays + assert symbolic_size not in nested_sdfg.out_connectors + oedge = next(iter(state.out_edges(nested_sdfg))) + assert oedge.dst is d + assert oedge.src_conn in nested_sdfg.out_connectors + assert oedge.src_conn in nested_sdfg.sdfg.arrays + + util.compile_and_run_sdfg(sdfg, **res) + assert util.compare_sdfg_res(ref=ref, res=res) + + +def test_concat_where_with_symbolic_size_clashing_with_nested_assignment(): + # The symbol `n`, that defines the size of the producer `a`, has to be mapped into + # the nested SDFG, which assigns its own value to `n` on an interstate edge. + symbolic_size = "n" + + nested = dace.SDFG("nested") + for aname in "ab": + nested.add_array(aname, shape=(10,), dtype=dace.float64, transient=False) + init_state = nested.add_state(is_start_block=True) + comp_state = nested.add_state_after(init_state, assignments={symbolic_size: "7"}) + comp_state.add_mapped_tasklet( + "nested_map", + map_ranges={"__i": "0:10"}, + inputs={"__in": dace.Memlet("a[__i]")}, + outputs={"__out": dace.Memlet("b[__i]")}, + code=f"__out = __in + {symbolic_size}", + external_edges=True, + ) + nested.validate() + assert symbolic_size not in nested.symbols + + sdfg = dace.SDFG(util.unique_name("concat_where_symbolic_size_clashing_with_nested_assignment")) + state = sdfg.add_state() + sdfg.add_symbol(symbolic_size, dace.int32) + for aname in "abcd": + sdfg.add_array( + name=aname, + shape=((10,) if aname != "a" else (dace.symbolic.pystr_to_symbolic(symbolic_size),)), + dtype=dace.float64, + transient=(aname == "c"), + ) + + a, b, c, d = (state.add_access(aname) for aname in "abcd") + state.add_nedge(a, c, dace.Memlet("a[1:6] -> [0:5]")) + state.add_nedge(b, c, dace.Memlet("b[3:8] -> [5:10]")) + + nested_sdfg = state.add_nested_sdfg(sdfg=nested, inputs={"a"}, outputs={"b"}, symbol_mapping={}) + state.add_edge(c, None, nested_sdfg, "a", dace.Memlet("c[0:10]")) + state.add_edge(nested_sdfg, "b", d, None, dace.Memlet("d[0:10]")) + sdfg.validate() + + ref, res = util.make_sdfg_args(sdfg, symbols={symbolic_size: 10}) + util.compile_and_run_sdfg(sdfg, **ref) + + gtx_transformations.gt_replace_concat_where_node(state=state, sdfg=sdfg, concat_node=c) + sdfg.validate() + + assert c.data not in sdfg.arrays + assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size + + # The symbol assigned inside the nested SDFG has been renamed. + (assignments,) = [ + isedge.data.assignments + for isedge in nested_sdfg.sdfg.all_interstate_edges() + if isedge.data.assignments + ] + assert symbolic_size not in assignments + assert list(assignments.values()) == ["7"] + + util.compile_and_run_sdfg(sdfg, **res) + assert util.compare_sdfg_res(ref=ref, res=res) + + def _make_multi_producer_sdfg( nb_producers: int, ) -> tuple[dace.SDFG, dace.SDFGState, dace_nodes.AccessNode]: diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py index c93000c1e3..b2f4d7b8e2 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py @@ -724,13 +724,12 @@ def inner_ref(i0, o0): assert {ac.data for ac in acnodes} == {"a", "e"} assert util.count_nodes(sdfg, dace_nodes.NestedSDFG) == 1 - # The shapes should be the same as before. - assert inner_sdfg.arrays["i0"].shape == inner_sdfg.arrays["o0"].shape + # A nested SDFG connector has to be equivalent to the data it is connected to. + # Thus `i0` is still `a`, but `o0` has been restated as `e`, into which the + # nested SDFG now writes directly, at the offset of the removed copy chain. assert inner_sdfg.arrays["i0"].shape == sdfg.arrays["a"].shape - - # The strides of `i0` should also be the same as before, but the strides - # of `o0` should now be the same as `e`. assert inner_sdfg.arrays["i0"].strides == sdfg.arrays["a"].strides + assert inner_sdfg.arrays["o0"].shape == sdfg.arrays["e"].shape assert inner_sdfg.arrays["o0"].strides == sdfg.arrays["e"].strides # Now run the transformed SDFG to see if the same output is generated. diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py index 53a594174a..7639725454 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py @@ -10,6 +10,8 @@ import pytest import sympy +from typing import Optional + from dace.sdfg import nodes as dace_nodes from gt4py.next import utils as gtx_utils @@ -34,16 +36,21 @@ def _make_if_block_with_tasklet( b1_type: dace.typeclass = dace.float64, b2_type: dace.typeclass = dace.float64, output_type: dace.typeclass = dace.float64, + output_shape: Optional[tuple[int, ...]] = None, ) -> dace_nodes.NestedSDFG: + """Create an if block, see `_make_if_block()` for the meaning of `output_shape`.""" inner_sdfg = dace.SDFG(util.unique_name("if_stmt_")) types = {b1_name: b1_type, b2_name: b2_type, cond_name: dace.bool_, output_name: output_type} - for name in {b1_name, b2_name, cond_name, output_name}: - inner_sdfg.add_scalar( - name, - dtype=types[name], - transient=False, - ) + for name in {b1_name, b2_name, cond_name}: + inner_sdfg.add_scalar(name, dtype=types[name], transient=False) + if output_shape is None: + inner_sdfg.add_scalar(output_name, dtype=output_type, transient=False) + output_index = "0" + else: + inner_sdfg.add_array(output_name, shape=output_shape, dtype=output_type, transient=False) + inner_sdfg.add_symbol("__i", stype=dace.int32) + output_index = "__i" if_region = dace.sdfg.state.ConditionalBlock(util.unique_name("if")) inner_sdfg.add_node(if_region, is_start_block=True) @@ -70,7 +77,7 @@ def _make_if_block_with_tasklet( "__tasklet_out", tstate.add_access(output_name), None, - dace.Memlet(f"{output_name}[0]"), + dace.Memlet(f"{output_name}[{output_index}]"), ) if with_false_branch or with_else_branch: @@ -79,7 +86,7 @@ def _make_if_block_with_tasklet( fstate.add_nedge( fstate.add_access(b2_name), fstate.add_access(output_name), - dace.Memlet(f"{b2_name}[0] -> [0]"), + dace.Memlet(f"{b2_name}[0] -> [{output_index}]"), ) if_region.add_branch(dace.sdfg.state.CodeBlock(cond_name), then_body) @@ -94,6 +101,7 @@ def _make_if_block_with_tasklet( sdfg=inner_sdfg, inputs={b1_name, b2_name, cond_name}, outputs={output_name}, + symbol_mapping=(None if output_shape is None else {"__i": "__i"}), ) # TODO(edoapo): The typecast to sympy is needed because the constructor of the `symbol_mapping` # dict property converts the values to symbolic expressions, but the assignment of entries @@ -173,11 +181,19 @@ def _make_map_with_conditional_blocks( state.add_edge(tmp_a, None, tasklet_cond, "__in", dace.Memlet("tmp_a[0]")) state.add_edge(tasklet_cond, "__out", cond_var, None, dace.Memlet("cond_var")) + # When the output is not written through a temporary, the if block writes directly + # into an element of the array, which it only does in the branches that write it. + # Since a nested SDFG connector has to be equivalent to the data it is connected + # to, the output of the if block is then the full array. + output_shape_0 = None if create_temporary_c else (10,) if_block_0 = ( - _make_if_block(state=state, outer_sdfg=sdfg) + _make_if_block(state=state, outer_sdfg=sdfg, output_shape=output_shape_0) if not both_ifs_with_taklets else _make_if_block_with_tasklet( - state=state, with_false_branch=with_false_branch, with_else_branch=with_else_branch + state=state, + with_false_branch=with_false_branch, + with_else_branch=with_else_branch, + output_shape=output_shape_0, ) ) state.add_edge(cond_var, None, if_block_0, "__cond", dace.Memlet("cond_var")) @@ -191,7 +207,10 @@ def _make_map_with_conditional_blocks( new_edge.data.allow_oob = True if_block_1 = _make_if_block_with_tasklet( - state=state, with_false_branch=with_false_branch, with_else_branch=with_else_branch + state=state, + with_false_branch=with_false_branch, + with_else_branch=with_else_branch, + output_shape=(None if create_temporary_d else (10,)), ) state.add_edge(cond_var, None, if_block_1, "__cond", dace.Memlet("cond_var")) state.add_edge(tmp_a, None, if_block_1, "__arg1", dace.Memlet("tmp_a[0]")) @@ -265,9 +284,8 @@ def test_fuse_horizontal_condition_blocks_single_false(uids: gtx_utils.IDGenerat ] assert len(new_conditional_blocks) == 1 conditional_block = new_conditional_blocks[0] - assert ( - len(conditional_block.sdfg.symbols) == 1 and "multiplier" in conditional_block.sdfg.symbols - ) + # `__i` is used to write the outputs in place, see `_make_map_with_conditional_blocks()`. + assert conditional_block.sdfg.symbols.keys() == {"multiplier", "__i"} true_branch_state = conditional_block.sdfg.states()[0] false_branch_state = conditional_block.sdfg.states()[1] diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py index 8c6e2565bc..e1e4630a92 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py @@ -1036,9 +1036,15 @@ def _apply_and_run_mixed_memlet_sdfg( def _make_conditional_block_sdfg(sdfg_label: str, sym: str, inp: str, out: str): + """The nested SDFG reads `inp[1, 1]` and writes the scalar `out`. + + Since a nested SDFG connector has to be equivalent to the data it is connected + to, `inp` is the full `(10, 10)` array, and it is accessed with the same indices + as on the outside. + """ sdfg = dace.SDFG(sdfg_label) - for data in [inp, out]: - sdfg.add_scalar(data, dtype=dace.float64) + sdfg.add_array(inp, shape=(10, 10), dtype=dace.float64) + sdfg.add_scalar(out, dtype=dace.float64) if_region = dace.sdfg.state.ConditionalBlock("if") sdfg.add_node(if_region) @@ -1049,14 +1055,14 @@ def _make_conditional_block_sdfg(sdfg_label: str, sym: str, inp: str, out: str): tstate = then_body.add_state("true_branch", is_start_block=True) if_region.add_branch(dace.sdfg.state.CodeBlock(f"{sym} % 2 == 0"), then_body) tskli = tstate.add_tasklet("write_0", inputs={"inp"}, outputs={"val"}, code=f"val = inp + 0") - tstate.add_edge(tstate.add_access(inp), None, tskli, "inp", dace.Memlet(f"{inp}[0]")) + tstate.add_edge(tstate.add_access(inp), None, tskli, "inp", dace.Memlet(f"{inp}[1, 1]")) tstate.add_edge(tskli, "val", tstate.add_access(out), None, dace.Memlet(f"{out}[0]")) else_body = dace.sdfg.state.ControlFlowRegion("else_body", sdfg=sdfg) fstate = else_body.add_state("false_branch", is_start_block=True) if_region.add_branch(dace.sdfg.state.CodeBlock(f"{sym} % 2 != 0"), else_body) tskli = fstate.add_tasklet("write_1", inputs={"inp"}, outputs={"val"}, code=f"val = inp + 1") - fstate.add_edge(fstate.add_access(inp), None, tskli, "inp", dace.Memlet(f"{inp}[0]")) + fstate.add_edge(fstate.add_access(inp), None, tskli, "inp", dace.Memlet(f"{inp}[1, 1]")) fstate.add_edge(tskli, "val", fstate.add_access(out), None, dace.Memlet(f"{out}[0]")) return sdfg @@ -1153,11 +1159,14 @@ def test_loop_blocking_no_independent_nodes(): nsdfg, inputs={nsdfg_inp}, outputs={nsdfg_out}, symbol_mapping={nsdfg_sym: "__i1"} ) state.add_memlet_path(A, me, nsdfg_node, dst_conn=nsdfg_inp, memlet=dace.Memlet("A[1,1]")) + # The scalar output connector can not write into an element of `C` directly. + sdfg.add_scalar("tmp", dtype=dace.float64, transient=True) + tmp = state.add_access("tmp") + state.add_edge(nsdfg_node, nsdfg_out, tmp, None, dace.Memlet("tmp[0]")) state.add_memlet_path( - nsdfg_node, + tmp, mx, state.add_access("C"), - src_conn=nsdfg_out, memlet=dace.Memlet("C[__i0, __i1]"), ) sdfg.validate() diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_buffer_elimination.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_buffer_elimination.py index 33e0d287c4..f542f04e0b 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_buffer_elimination.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_map_buffer_elimination.py @@ -262,81 +262,112 @@ def test_map_buffer_elimination_not_apply(): def test_map_buffer_elimination_with_nested_sdfgs(): """ - After removing a transient connected to a nested SDFG node, ensure that the strides - are propagated to the arrays in nested SDFG. + After removing a transient connected to a nested SDFG node, ensure that the connector + of the nested SDFG is restated as the new data, including its shape and strides. + + A nested SDFG connector has to be equivalent to the data connected to it. Thus, + the connectors initially describe the transients `tmp`, `tmp1` and `tmp2`, which + are written back into `__out`. Once the transients are removed, the + connectors, also the one of the second level, have to describe `__out`. """ - stride1, stride2, stride3 = [dace.symbol(f"stride{i}", dace.int32) for i in range(3)] + strides = [dace.symbol(f"stride{i}", dace.int32) for i in range(3)] + + def make_level2() -> dace.SDFG: + # Writes `tmp2`, then `__out[__i, __j, 0:10]` (i.e. `tmp1` of level 1). + nsdfg2 = dace.SDFG(util.unique_name("map_buffer_level2")) + for sym in ["__i", "__j"]: + nsdfg2.add_symbol(sym, dace.int32) + nsdfg2.add_array("__inp", (10,), dace.float64) + nsdfg2.add_array("__out", (10, 10, 10), dace.float64) + tmp2, _ = nsdfg2.add_temp_transient((10, 10, 10), dace.float64) + state2 = nsdfg2.add_state() + tmp2_node = state2.add_access(tmp2) + state2.add_mapped_tasklet( + "broadcast2", + map_ranges={"__k": "0:10"}, + code="__oval = __ival + 1.0", + inputs={"__ival": dace.Memlet("__inp[__k]")}, + outputs={"__oval": dace.Memlet(f"{tmp2}[__i, __j, __k]")}, + output_nodes={tmp2_node}, + external_edges=True, + ) + state2.add_nedge( + tmp2_node, + state2.add_access("__out"), + dace.Memlet(f"{tmp2}[__i, __j, 0:10] -> [__i, __j, 0:10]"), + ) + return nsdfg2 + + def make_level1() -> tuple[dace.SDFG, dace_nodes.NestedSDFG]: + # Writes `tmp1`, then `__out[__i, 0:10, 0:10]` (i.e. `tmp` of the top level). + nsdfg1 = dace.SDFG(util.unique_name("map_buffer_level1")) + nsdfg1.add_symbol("__i", dace.int32) + nsdfg1.add_array("__inp", (10,), dace.float64) + nsdfg1.add_array("__out", (10, 10, 10), dace.float64) + tmp1, _ = nsdfg1.add_temp_transient((10, 10, 10), dace.float64) + state1 = nsdfg1.add_state() + tmp1_node = state1.add_access(tmp1) + + nsdfg2_node = state1.add_nested_sdfg( + make_level2(), + inputs={"__inp"}, + outputs={"__out"}, + symbol_mapping={"__i": "__i", "__j": "__j"}, + ) + me1, mx1 = state1.add_map("broadcast1", ndrange={"__j": "0:10"}) + state1.add_memlet_path( + state1.add_access("__inp"), + me1, + nsdfg2_node, + dst_conn="__inp", + memlet=dace.Memlet("__inp[0:10]"), + ) + state1.add_memlet_path( + nsdfg2_node, + mx1, + tmp1_node, + src_conn="__out", + memlet=dace.Memlet(f"{tmp1}[__i, __j, 0:10]"), + ) + state1.add_nedge( + tmp1_node, + state1.add_access("__out"), + dace.Memlet(f"{tmp1}[__i, 0:10, 0:10] -> [__i, 0:10, 0:10]"), + ) + return nsdfg1, nsdfg2_node # top-level sdfg sdfg = dace.SDFG(util.unique_name("map_buffer")) - inp, inp_desc = sdfg.add_array("__inp", (10,), dace.float64) - out, out_desc = sdfg.add_array( - "__out", (10, 10, 10), dace.float64, strides=(stride1, stride2, stride3) - ) - tmp, _ = sdfg.add_temp_transient_like(out_desc) + sdfg.add_array("__inp", (10,), dace.float64) + _, out_desc = sdfg.add_array("__out", (10, 10, 10), dace.float64, strides=strides) + tmp, _ = sdfg.add_temp_transient((10, 10, 10), dace.float64) state = sdfg.add_state() tmp_node = state.add_access(tmp) - nsdfg1 = dace.SDFG(util.unique_name("map_buffer")) - inp1, inp1_desc = nsdfg1.add_array("__inp", (10,), dace.float64) - out1, out1_desc = nsdfg1.add_array("__out", (10, 10), dace.float64) - tmp1, _ = nsdfg1.add_temp_transient_like(out1_desc) - state1 = nsdfg1.add_state() - tmp1_node = state1.add_access(tmp1) - - nsdfg2 = dace.SDFG(util.unique_name("map_buffer")) - inp2, _ = nsdfg2.add_array("__inp", (10,), dace.float64) - out2, out2_desc = nsdfg2.add_array("__out", (10,), dace.float64) - tmp2, _ = nsdfg2.add_temp_transient_like(out2_desc) - state2 = nsdfg2.add_state() - tmp2_node = state2.add_access(tmp2) - - state2.add_mapped_tasklet( - "broadcast2", - map_ranges={"__i": "0:10"}, - code="__oval = __ival + 1.0", - inputs={ - "__ival": dace.Memlet(f"{inp2}[__i]"), - }, - outputs={ - "__oval": dace.Memlet(f"{tmp2}[__i]"), - }, - output_nodes={tmp2_node}, - external_edges=True, - ) - state2.add_nedge(tmp2_node, state2.add_access(out2), dace.Memlet.from_array(out2, out2_desc)) - - nsdfg2_node = state1.add_nested_sdfg(nsdfg2, inputs={"__inp"}, outputs={"__out"}) - me1, mx1 = state1.add_map("broadcast1", ndrange={"__i": "0:10"}) - state1.add_memlet_path( - state1.add_access(inp1), - me1, - nsdfg2_node, - dst_conn="__inp", - memlet=dace.Memlet.from_array(inp1, inp1_desc), - ) - state1.add_memlet_path( - nsdfg2_node, mx1, tmp1_node, src_conn="__out", memlet=dace.Memlet(f"{tmp1}[__i, 0:10]") + nsdfg1, nsdfg2_node = make_level1() + nsdfg1_node = state.add_nested_sdfg( + nsdfg1, inputs={"__inp"}, outputs={"__out"}, symbol_mapping={"__i": "__i"} ) - state1.add_nedge(tmp1_node, state1.add_access(out1), dace.Memlet.from_array(out1, out1_desc)) - - nsdfg1_node = state.add_nested_sdfg(nsdfg1, inputs={"__inp"}, outputs={"__out"}) me, mx = state.add_map("broadcast", ndrange={"__i": "0:10"}) state.add_memlet_path( - state.add_access(inp), + state.add_access("__inp"), me, nsdfg1_node, dst_conn="__inp", - memlet=dace.Memlet.from_array(inp, inp_desc), + memlet=dace.Memlet("__inp[0:10]"), ) state.add_memlet_path( nsdfg1_node, mx, tmp_node, src_conn="__out", memlet=dace.Memlet(f"{tmp}[__i, 0:10, 0:10]") ) - state.add_nedge(tmp_node, state.add_access(out), dace.Memlet.from_array(out, out_desc)) - + state.add_nedge(tmp_node, state.add_access("__out"), dace.Memlet.from_array("__out", out_desc)) sdfg.validate() + # Fortran order, so that the propagation of the strides is visible in the result. + stride_values = {"stride0": 1, "stride1": 10, "stride2": 100} + ref, res = util.make_sdfg_args(sdfg, symbols=stride_values) + util.compile_and_run_sdfg(sdfg, **ref) + count = sdfg.apply_transformations_repeated( gtx_transformations.GT4PyMapBufferElimination( assume_pointwise=False, @@ -345,5 +376,13 @@ def test_map_buffer_elimination_with_nested_sdfgs(): validate_all=True, ) assert count == 3 - assert out1_desc.strides == out_desc.strides[1:] - assert out2_desc.strides == out_desc.strides[2:] + + # The descriptors are replaced when a connector is restated, so look them up again. + for nsdfg_node in [nsdfg1_node, nsdfg2_node]: + inner_out_desc = nsdfg_node.sdfg.arrays["__out"] + assert inner_out_desc.shape == out_desc.shape + assert inner_out_desc.strides == out_desc.strides + assert tmp not in sdfg.arrays + + util.compile_and_run_sdfg(sdfg, **res) + assert util.compare_sdfg_res(ref=ref, res=res) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py index 0ebd75afd9..23313dc15a 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py @@ -36,16 +36,34 @@ def _make_if_block( b1_type: dace.typeclass = dace.float64, b2_type: dace.typeclass = dace.float64, output_type: dace.typeclass = dace.float64, + b1_shape: Optional[tuple[int, ...]] = None, + b2_shape: Optional[tuple[int, ...]] = None, + output_shape: Optional[tuple[int, ...]] = None, ) -> dace_nodes.NestedSDFG: + """Create an if block that selects between its arguments `b1_name` and `b2_name`. + + By default, the arguments and the output are scalars. If `b{1,2}_shape` or + `output_shape` is given, the corresponding connector is instead connected to an + array element `a[__i]` inside a Map with iteration variable `__i`. Because a nested + SDFG connector has to be equivalent to the data it is connected to, the connector + is then the full array, accessed at `[__i]`. + """ inner_sdfg = dace.SDFG(util.unique_name("if_stmt_")) types = {b1_name: b1_type, b2_name: b2_type, cond_name: dace.bool_, output_name: output_type} + shapes = {b1_name: b1_shape, b2_name: b2_shape, output_name: output_shape} for name in {b1_name, b2_name, cond_name, output_name}: - inner_sdfg.add_scalar( - name, - dtype=types[name], - transient=False, - ) + if shapes.get(name) is None: + inner_sdfg.add_scalar(name, dtype=types[name], transient=False) + else: + inner_sdfg.add_array(name, shape=shapes[name], dtype=types[name], transient=False) + symbol_mapping = None + if any(shape is not None for shape in shapes.values()): + inner_sdfg.add_symbol("__i", stype=dace.int32) + symbol_mapping = {"__i": "__i"} + b1_index = "0" if b1_shape is None else "__i" + b2_index = "0" if b2_shape is None else "__i" + output_index = "0" if output_shape is None else "__i" if_region = dace.sdfg.state.ConditionalBlock(util.unique_name("if")) inner_sdfg.add_node(if_region, is_start_block=True) @@ -55,7 +73,7 @@ def _make_if_block( tstate.add_nedge( tstate.add_access(b1_name), tstate.add_access(output_name), - dace.Memlet(f"{b1_name}[0] -> [0]"), + dace.Memlet(f"{b1_name}[{b1_index}] -> [{output_index}]"), ) else_body = dace.sdfg.state.ControlFlowRegion("else_body", sdfg=inner_sdfg) @@ -63,7 +81,7 @@ def _make_if_block( fstate.add_nedge( fstate.add_access(b2_name), fstate.add_access(output_name), - dace.Memlet(f"{b2_name}[0] -> [0]"), + dace.Memlet(f"{b2_name}[{b2_index}] -> [{output_index}]"), ) if_region.add_branch(dace.sdfg.state.CodeBlock(cond_name), then_body) @@ -73,9 +91,63 @@ def _make_if_block( sdfg=inner_sdfg, inputs={b1_name, b2_name, cond_name}, outputs={output_name}, + symbol_mapping=symbol_mapping, ) +def _write_if_output( + state: dace.SDFGState, + if_block: dace_nodes.NestedSDFG, + connector: str, + map_exit: dace_nodes.MapExit, + outer_data: str, +) -> str: + """Write the scalar output `connector` of `if_block` to `outer_data[__i]`. + + The value passes through a scalar transient, because the connector of a nested + SDFG has to be equivalent to the data it is connected to, so it cannot write + into an element of the outer array directly. This is also how the lowering + writes the result of an if-expression. + + Returns: + The name of the scalar transient. + """ + sdfg = state.sdfg + tmp = f"{outer_data}_if_out" + sdfg.add_scalar(tmp, dtype=sdfg.arrays[outer_data].dtype, transient=True) + tmp_node = state.add_access(tmp) + state.add_edge(if_block, connector, tmp_node, None, dace.Memlet(f"{tmp}[0]")) + state.add_edge(tmp_node, None, map_exit, f"IN_{outer_data}", dace.Memlet(f"{outer_data}[__i]")) + return tmp + + +def _read_if_cond( + state: dace.SDFGState, + map_entry: dace_nodes.MapEntry, + if_block: dace_nodes.NestedSDFG, + outer_data: str, + connector: str = "__cond", +) -> str: + """Pass the condition `outer_data[__i]` to the scalar `connector` of `if_block`. + + The value passes through a scalar transient for the same reason as in + `_write_if_output()`. This is also how the lowering passes a condition that + is read from a field. + + Returns: + The name of the scalar transient. + """ + sdfg = state.sdfg + tmp = f"{outer_data}_if_cond" + sdfg.add_scalar(tmp, dtype=dace.bool_, transient=True) + tmp_node = state.add_access(tmp) + state.add_edge( + map_entry, f"OUT_{outer_data}", tmp_node, None, dace.Memlet(f"{outer_data}[__i]") + ) + state.add_edge(tmp_node, None, if_block, connector, dace.Memlet(f"{tmp}[0]")) + return tmp + + def _make_if_block_with_different_number_of_outputs_in_branches( state: dace.SDFGState, outer_sdfg: dace.SDFG, @@ -332,7 +404,7 @@ def test_if_mover_independent_branches(): state.add_edge(c1, None, if_block, "__cond", dace.Memlet("c1[0]")) # Now handle the output. - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) # Now add the connectors to the Map* @@ -347,7 +419,7 @@ def test_if_mover_independent_branches(): # Examine the structure of the SDFG. top_ac: list[dace_nodes.AccessNode] = util.count_nodes(state, dace_nodes.AccessNode, True) - assert {ac.data for ac in top_ac} == set(input_names).union(["c1"]) + assert {ac.data for ac in top_ac} == set(input_names).union(["c1", "d_if_out"]) assert len(sdfg.arrays) == len(top_ac) top_tlet: list[dace_nodes.Tasklet] = util.count_nodes(state, dace_nodes.Tasklet, True) @@ -452,7 +524,7 @@ def test_if_mover_invalid_if_block(): state.add_edge(c1, None, if_block, "__cond", dace.Memlet("c1[0]")) # Now handle the output. - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) # Now add the connectors to the Map* @@ -565,7 +637,7 @@ def test_if_mover_dependent_branch_1(): state.add_edge(c1, None, if_block, "__cond", dace.Memlet("c1[0]")) # Now handle the output. - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) # Now add the connectors to the Map* @@ -580,7 +652,7 @@ def test_if_mover_dependent_branch_1(): # Examine the structure of the SDFG. top_ac: list[dace_nodes.AccessNode] = util.count_nodes(state, dace_nodes.AccessNode, True) - assert {ac.data for ac in top_ac} == set(input_names).union(["c1", "s1"]) + assert {ac.data for ac in top_ac} == set(input_names).union(["c1", "s1", "d_if_out"]) assert len(sdfg.arrays) == len(top_ac) top_tlet: list[dace_nodes.Tasklet] = util.count_nodes(state, dace_nodes.Tasklet, True) @@ -677,7 +749,7 @@ def test_if_mover_dependent_branch_2(): state.add_edge(c1, None, if_block, "__cond", dace.Memlet("c1[0]")) # Now handle the output. - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", d, None, dace.Memlet("d[0:10]")) # Now add the connectors to the Map* @@ -691,7 +763,7 @@ def test_if_mover_dependent_branch_2(): # Examine the structure of the SDFG. top_ac: list[dace_nodes.AccessNode] = util.count_nodes(state, dace_nodes.AccessNode, True) - assert {ac.data for ac in top_ac} == set(input_names).union(["c1"]) + assert {ac.data for ac in top_ac} == set(input_names).union(["c1", "d_if_out"]) assert len(sdfg.arrays) == len(top_ac) assert set(if_block.in_connectors.keys()) == set(input_names).union(["__cond"]).difference( @@ -775,13 +847,13 @@ def test_if_mover_dependent_branch_3(): imx2.add_scope_connectors("t2") state.add_edge(cond, None, me, "IN_cond", dace.Memlet("cond[0:10]")) - state.add_edge(me, "OUT_cond", if_block, "__cond", dace.Memlet("cond[__i]")) + _read_if_cond(state, me, if_block, "cond") me.add_scope_connectors("cond") state.add_edge(t1, None, if_block, "__arg1", dace.Memlet("t1[0]")) state.add_edge(t2, None, if_block, "__arg2", dace.Memlet("t2[0]")) - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", d, None, dace.Memlet("d[0:10]")) mx.add_scope_connectors("d") @@ -791,7 +863,7 @@ def test_if_mover_dependent_branch_3(): assert len(me.in_connectors) == 5 assert util.count_nodes(state, dace_nodes.Tasklet) == 2 assert util.count_nodes(state, dace_nodes.MapEntry) == 2 - assert util.count_nodes(state, dace_nodes.AccessNode) == 7 + assert util.count_nodes(state, dace_nodes.AccessNode) == 9 _perform_test(sdfg, expected_applies=1) @@ -801,8 +873,8 @@ def test_if_mover_dependent_branch_3(): assert len(me.in_connectors) == 4 assert util.count_nodes(state, dace_nodes.Tasklet) == 0 assert util.count_nodes(state, dace_nodes.MapEntry) == 1 - assert util.count_nodes(state, dace_nodes.AccessNode) == 5 - assert set(gnames) == sdfg.arrays.keys() + assert util.count_nodes(state, dace_nodes.AccessNode) == 7 + assert set(gnames).union(["cond_if_cond", "d_if_out"]) == sdfg.arrays.keys() def test_if_mover_dependent_branch_4(): @@ -926,8 +998,8 @@ def test_if_mover_dependent_branch_4(): state.add_edge(c1, None, if_block, "__cond", dace.Memlet("c1[0]")) # Now handle the output. - state.add_edge(if_block, "__output1", mx, "IN_d", dace.Memlet("d[__i]")) - state.add_edge(if_block, "__output2", mx, "IN_f", dace.Memlet("f[__i]")) + _write_if_output(state, if_block, "__output1", mx, "d") + _write_if_output(state, if_block, "__output2", mx, "f") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) state.add_edge(mx, "OUT_f", state.add_access("f"), None, dace.Memlet("f[0:10]")) @@ -944,7 +1016,9 @@ def test_if_mover_dependent_branch_4(): # Examine the structure of the SDFG. top_ac: list[dace_nodes.AccessNode] = util.count_nodes(state, dace_nodes.AccessNode, True) - assert {ac.data for ac in top_ac} == set(input_names).union(["c1", "s1"]) + assert {ac.data for ac in top_ac} == set(input_names).union( + ["c1", "s1", "d_if_out", "f_if_out"] + ) assert len(sdfg.arrays) == len(top_ac) assert all(state.out_degree(ac) == 1 for ac in [s1, c1]) assert all(oedge.dst_conn == "__arg4" for oedge in state.out_edges(s1)) @@ -1108,8 +1182,8 @@ def test_if_mover_dependent_branch_5(): state.add_edge(c1, None, if_block, "__cond", dace.Memlet("c1[0]")) # Now handle the output. - state.add_edge(if_block, "__output1", mx, "IN_d", dace.Memlet("d[__i]")) - state.add_edge(if_block, "__output2", mx, "IN_f", dace.Memlet("f[__i]")) + _write_if_output(state, if_block, "__output1", mx, "d") + _write_if_output(state, if_block, "__output2", mx, "f") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) state.add_edge(mx, "OUT_f", state.add_access("f"), None, dace.Memlet("f[0:10]")) @@ -1126,7 +1200,9 @@ def test_if_mover_dependent_branch_5(): # Examine the structure of the SDFG. top_ac: list[dace_nodes.AccessNode] = util.count_nodes(state, dace_nodes.AccessNode, True) - assert {ac.data for ac in top_ac} == set(input_names).union(["c1", "s1"]) + assert {ac.data for ac in top_ac} == set(input_names).union( + ["c1", "s1", "d_if_out", "f_if_out"] + ) assert len(sdfg.arrays) == len(top_ac) assert all(state.out_degree(ac) == 1 for ac in [s1, c1]) assert all(oedge.dst_conn == "__arg4" for oedge in state.out_edges(s1)) @@ -1258,15 +1334,15 @@ def test_if_mover_dependent_branch_6(): state.add_edge(tlet3, "__out", t3, None, dace.Memlet("t3[0]")) state.add_edge(cond, None, me, "IN_cond", dace.Memlet("cond[0:10]")) - state.add_edge(me, "OUT_cond", if_block, "__cond", dace.Memlet("cond[__i]")) + _read_if_cond(state, me, if_block, "cond") me.add_scope_connectors("cond") state.add_edge(t1, None, if_block, "__arg1", dace.Memlet("t1[0]")) state.add_edge(t2, None, if_block, "__arg2", dace.Memlet("t2[0]")) state.add_edge(t3, None, if_block, "__arg3", dace.Memlet("t3[0]")) - state.add_edge(if_block, "__output1", mx, "IN_d", dace.Memlet("d[__i]")) - state.add_edge(if_block, "__output2", mx, "IN_e", dace.Memlet("e[__i]")) + _write_if_output(state, if_block, "__output1", mx, "d") + _write_if_output(state, if_block, "__output2", mx, "e") state.add_edge(mx, "OUT_d", d, None, dace.Memlet("d[0:10]")) state.add_edge(mx, "OUT_e", e, None, dace.Memlet("e[0:10]")) mx.add_scope_connectors("d") @@ -1278,7 +1354,7 @@ def test_if_mover_dependent_branch_6(): assert len(me.in_connectors) == 5 assert util.count_nodes(state, dace_nodes.Tasklet) == 3 assert util.count_nodes(state, dace_nodes.MapEntry) == 2 - assert util.count_nodes(state, dace_nodes.AccessNode) == 9 + assert util.count_nodes(state, dace_nodes.AccessNode) == 12 _perform_test(sdfg, expected_applies=1) # Simplify the SDFG to remove double `b` AccessNode in the false branch. @@ -1289,8 +1365,8 @@ def test_if_mover_dependent_branch_6(): assert len(me.in_connectors) == 4 assert util.count_nodes(state, dace_nodes.Tasklet) == 0 assert util.count_nodes(state, dace_nodes.MapEntry) == 1 - assert util.count_nodes(state, dace_nodes.AccessNode) == 6 - assert set(gnames) == sdfg.arrays.keys() + assert util.count_nodes(state, dace_nodes.AccessNode) == 9 + assert set(gnames).union(["cond_if_cond", "d_if_out", "e_if_out"]) == sdfg.arrays.keys() expected_access_nodes_in_false_branch = [ "a", "b", @@ -1359,7 +1435,7 @@ def test_if_mover_no_ops(): me.add_scope_connectors(name) state.add_edge(state.add_access(name), None, me, f"IN_{name}", dace.Memlet(f"{name}[0:10]")) - if_block = _make_if_block(state, sdfg) + if_block = _make_if_block(state, sdfg, b1_shape=(10,), b2_shape=(10,)) state.add_edge(me, "OUT_a", if_block, "__arg1", dace.Memlet("a[__i]")) state.add_edge(me, "OUT_b", if_block, "__arg2", dace.Memlet("b[__i]")) @@ -1374,7 +1450,7 @@ def test_if_mover_no_ops(): # The output. mx.add_scope_connectors("d") - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) sdfg.validate() @@ -1443,13 +1519,13 @@ def test_if_mover_one_branch_is_nothing(): state.add_edge(tasklet_cond, "__out", c1, None, dace.Memlet("c1[0]")) # Make the if selection. - if_block = _make_if_block(state=state, outer_sdfg=sdfg) + if_block = _make_if_block(state=state, outer_sdfg=sdfg, b2_shape=(10,)) state.add_edge(a2, None, if_block, "__arg1", dace.Memlet("a2[0]")) state.add_edge(me, "OUT_b", if_block, "__arg2", dace.Memlet("b[__i]")) state.add_edge(c1, None, if_block, "__cond", dace.Memlet("c1[0]")) # Now handle the output. - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) # Now add the connectors to the Map* @@ -1463,7 +1539,7 @@ def test_if_mover_one_branch_is_nothing(): _perform_test(sdfg, expected_applies=1) top_ac: list[dace_nodes.AccessNode] = util.count_nodes(state, dace_nodes.AccessNode, True) - assert {ac.data for ac in top_ac} == set(input_names).union(["c1"]) + assert {ac.data for ac in top_ac} == set(input_names).union(["c1", "d_if_out"]) def test_if_mover_chain(): @@ -1565,7 +1641,7 @@ def test_if_mover_chain(): state.add_edge(cc1, None, bot_if_block, "__cond", dace.Memlet("cc1[0]")) # Generate the output - state.add_edge(bot_if_block, "__output", mx, "IN_e", dace.Memlet("e[__i]")) + _write_if_output(state, bot_if_block, "__output", mx, "e") state.add_edge(mx, "OUT_e", state.add_access("e"), None, dace.Memlet("e[0:10]")) # Now add the connectors to the Map* @@ -1668,7 +1744,7 @@ def test_if_mover_symbolic_tasklet(): # Connect the inputs to the if block. state.add_edge(tmp1, None, if_block, "__arg1", dace.Memlet("tmp1[0]")) state.add_edge(tmp2, None, if_block, "__arg2", dace.Memlet("tmp2[0]")) - state.add_edge(me, "OUT_cond", if_block, "__cond", dace.Memlet("cond[__i]")) + _read_if_cond(state, me, if_block, "cond") # Connect the output. state.add_edge(if_block, "__output", output, None, dace.Memlet("output[0]")) @@ -1784,7 +1860,7 @@ def test_if_mover_access_node_between(): state.add_edge(c2, None, bot_if_block, "__cond", dace.Memlet("c2[0]")) # Generate the output - state.add_edge(bot_if_block, "__output", mx, "IN_f", dace.Memlet("f[__i]")) + _write_if_output(state, bot_if_block, "__output", mx, "f") state.add_edge(mx, "OUT_f", state.add_access("f"), None, dace.Memlet("f[0:10]")) # Now add the connectors to the Map* @@ -1807,7 +1883,7 @@ def test_if_mover_access_node_between(): expected_applies=2, ) - expected_top_level_data: set[str] = {"a", "b", "c", "d", "e", "f", "c2"} + expected_top_level_data: set[str] = {"a", "b", "c", "d", "e", "f", "c2", "f_if_out"} assert set(dnode.data for dnode in state.data_nodes()) == expected_top_level_data assert sdfg.arrays.keys() == expected_top_level_data assert set(tlet for tlet in state.nodes() if isinstance(tlet, dace_nodes.Tasklet)) == { @@ -1930,7 +2006,7 @@ def test_if_mover_symbol_aliasing(): state.add_edge(false_ac, None, if_block, "__arg2", dace.Memlet(f"{false_ac}[0]")) state.add_edge(cond_ac, None, if_block, "__cond", dace.Memlet(f"{cond_ac}[0]")) - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", d, None, dace.Memlet("d[0:10]")) mx.add_scope_connectors("d") @@ -1946,13 +2022,21 @@ def test_if_mover_symbol_aliasing(): @pytest.mark.parametrize("outer_slice_variable", [True, False]) def test_if_mover_slice_input(outer_slice_variable: bool): - def _make_nested_sdfg(cond_name: str, iter_name: str) -> dace.SDFG: + def _make_nested_sdfg(cond_name: str, iter_name: str, outer_slice_variable: bool) -> dace.SDFG: sdfg = dace.SDFG("If_block") sdfg.add_scalar("arg1", dtype=dace.float64, transient=False) sdfg.add_scalar("out", dtype=dace.float64, transient=False) sdfg.add_scalar(cond_name, dtype=dace.bool_, transient=False) - sdfg.add_array("arg2", shape=(10,), dtype=dace.float64, transient=False) + if outer_slice_variable: + sdfg.add_array("arg2", shape=(10,), dtype=dace.float64, transient=False) + arg2_index = iter_name + else: + # The connector is connected to a slice of `b`: it has to be equivalent to + # `b`, therefore it is the full array and it is accessed with the same + # indices as `b` on the outside. + sdfg.add_array("arg2", shape=(10, 10), dtype=dace.float64, transient=False) + arg2_index = f"{iter_name}, {iter_name}" sdfg.add_symbol(iter_name, stype=dace.int32) then_body = dace.sdfg.state.ControlFlowRegion("then_body", sdfg=sdfg) @@ -1971,7 +2055,7 @@ def _make_nested_sdfg(cond_name: str, iter_name: str) -> dace.SDFG: "f_tasklet", inputs={"__in"}, outputs={"__out"}, code="__out = __in + 1.0" ) fstate.add_edge( - fstate.add_access("arg2"), None, f_tasklet, "__in", dace.Memlet(f"arg2[{iter_name}]") + fstate.add_access("arg2"), None, f_tasklet, "__in", dace.Memlet(f"arg2[{arg2_index}]") ) fstate.add_edge(f_tasklet, "__out", fstate.add_access("out"), None, dace.Memlet("out[0]")) @@ -2054,7 +2138,11 @@ def _make_outer_sdfg( # Nested SDFG nsdfg = state.add_nested_sdfg( - sdfg=_make_nested_sdfg(cond_name=cond_name, iter_name=iter_name), + sdfg=_make_nested_sdfg( + cond_name=cond_name, + iter_name=iter_name, + outer_slice_variable=outer_slice_variable, + ), inputs={"arg1", "arg2", cond_name}, outputs={"out"}, symbol_mapping={iter_name: iter_name}, @@ -2068,7 +2156,7 @@ def _make_outer_sdfg( state.add_edge(me, "OUT_b", nsdfg, "arg2", dace.Memlet(f"b[{iter_name}, 0:10]")) mx.add_scope_connectors("d") - state.add_edge(nsdfg, "out", mx, "IN_d", dace.Memlet(f"d[{iter_name}]")) + _write_if_output(state, nsdfg, "out", mx, "d") state.add_edge( mx, "OUT_d", state.add_access("d"), None, dace.Memlet(data="d", subset="0:10") ) @@ -2167,9 +2255,13 @@ def test_if_mover_symbol_clashes_with_inner_data(): # The two input connectors are named `my_var` (true branch) and `other_var` # (false branch). inner_sdfg = dace.SDFG("if_body_with_my_var") - for name in ["my_var", "other_var", "__output"]: + for name in ["my_var", "__output"]: inner_sdfg.add_scalar(name, dtype=dace.float64, transient=False) inner_sdfg.add_scalar("__cond", dtype=dace.bool_, transient=False) + # `other_var` is connected to `b[__i]`: a nested SDFG connector has to be + # equivalent to the data it is connected to, so it is the full array `b`. + inner_sdfg.add_array("other_var", shape=(10,), dtype=dace.float64, transient=False) + inner_sdfg.add_symbol("__i", stype=dace.int32) if_region = dace.sdfg.state.ConditionalBlock("if_region") inner_sdfg.add_node(if_region, is_start_block=True) @@ -2187,7 +2279,7 @@ def test_if_mover_symbol_clashes_with_inner_data(): fstate.add_nedge( fstate.add_access("other_var"), fstate.add_access("__output"), - dace.Memlet("other_var[0] -> [0]"), + dace.Memlet("other_var[__i] -> [0]"), ) if_region.add_branch(dace.sdfg.state.CodeBlock("__cond"), then_body) @@ -2197,6 +2289,7 @@ def test_if_mover_symbol_clashes_with_inner_data(): sdfg=inner_sdfg, inputs={"my_var", "other_var", "__cond"}, outputs={"__output"}, + symbol_mapping={"__i": "__i"}, ) # Tasklet with no input connectors that reads the outer symbol `my_var` as a @@ -2232,7 +2325,7 @@ def test_if_mover_symbol_clashes_with_inner_data(): state.add_edge(cond_ac, None, if_block, "__cond", dace.Memlet("cond[0]")) # Output path. - state.add_edge(if_block, "__output", mx, "IN_out", dace.Memlet("out[__i]")) + _write_if_output(state, if_block, "__output", mx, "out") state.add_edge(mx, "OUT_out", state.add_access("out"), None, dace.Memlet("out[0:10]")) mx.add_scope_connectors("out") @@ -2345,7 +2438,7 @@ def test_if_mover_two_accessnodes_same_outer_data(): state.add_edge(cond_an, None, if_block, "__cond", dace.Memlet("cond_val[0]")) mx.add_scope_connectors("d") - state.add_edge(if_block, "__output", mx, "IN_d", dace.Memlet("d[__i]")) + _write_if_output(state, if_block, "__output", mx, "d") state.add_edge(mx, "OUT_d", state.add_access("d"), None, dace.Memlet("d[0:10]")) sdfg.validate() diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py index 2c2e9849ed..436154810b 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py @@ -6,17 +6,14 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import dace -import pytest -import numpy as np import copy +import dace +import numpy as np from dace import symbolic as dace_symbolic from dace.sdfg import nodes as dace_nodes -from gt4py.next.program_processors.runners.dace import ( - transformations as gtx_transformations, -) +from gt4py.next.program_processors.runners.dace import transformations as gtx_transformations from . import util @@ -30,6 +27,7 @@ def _make_strides_propagation_level3_sdfg() -> dace.SDFG: for name in names: stride_name = name + "_stride" stride_sym = dace_symbolic.pystr_to_symbolic(stride_name) + sdfg.add_symbol(stride_name, dace.int32) sdfg.add_array( name, shape=(10,), @@ -90,18 +88,20 @@ def _make_strides_propagation_level2_sdfg() -> tuple[dace.SDFG, dace_nodes.Neste external_edges=True, ) - # This is the nested SDFG we have here. - sdfg_level3 = _make_strides_propagation_level3_sdfg() - + # This is the nested SDFG we have here. Its connectors have to be equivalent + # to the data they are connected to, thus the stride symbols are mapped to + # the ones of this level, which is applied inside the nested SDFG when it is + # integrated into this SDFG. nsdfg = state.add_nested_sdfg( - sdfg=sdfg_level3, + sdfg=_make_strides_propagation_level3_sdfg(), inputs={"a3"}, outputs={"c3"}, - symbol_mapping={s3: s3 for s3 in sdfg_level3.free_symbols}, + symbol_mapping={"a3_stride": "a2_stride", "c3_stride": "c2_stride"}, ) state.add_edge(state.add_access("a2"), None, nsdfg, "a3", dace.Memlet("a2[0:10]")) state.add_edge(nsdfg, "c3", state.add_access("c2"), None, dace.Memlet("c2[0:10]")) + nsdfg.integrate_into_parent() sdfg.validate() return sdfg, nsdfg @@ -114,7 +114,7 @@ def _make_strides_propagation_level1_sdfg() -> tuple[ Note that the SDFG is valid, but will be indeterminate. The only point of this SDFG is to have a lot of different situations that have to be handled - for renaming. + for the propagation. `a1` is connected to the connectors `a2` and `a2_alias`. Returns: A tuple of length three, with the following members: @@ -145,7 +145,9 @@ def _make_strides_propagation_level1_sdfg() -> tuple[ sdfg=sdfg_level2, inputs={"a2", "c2"}, outputs={"a2_alias", "b2", "c2"}, - symbol_mapping={s: s for s in sdfg_level2.free_symbols}, + symbol_mapping={ + f"{name}_stride": f"{name[0]}1_stride" for name in ["a2", "a2_alias", "b2", "c2"] + }, ) for inner_name in nsdfg_level2.in_connectors: @@ -167,72 +169,55 @@ def _make_strides_propagation_level1_sdfg() -> tuple[ dace.Memlet(f"{outer_name}[0:10]"), ) + nsdfg_level2.integrate_into_parent() sdfg.validate() return sdfg, nsdfg_level2, nsdfg_level3 +def _get_stride_of(sdfg: dace.SDFG, prefix: str) -> dict[str, str]: + """Returns the stride of all data of `sdfg`, whose name starts with `prefix`.""" + return { + aname: str(adesc.strides[0]) + for aname, adesc in sdfg.arrays.items() + if aname.startswith(prefix) + } + + def test_strides_propagation(): # Note that the SDFG we are building here is not really meaningful. sdfg_level1, nsdfg_level2, nsdfg_level3 = _make_strides_propagation_level1_sdfg() + all_sdfgs = [sdfg_level1, nsdfg_level2.sdfg, nsdfg_level3.sdfg] - # Tests if all strides are distinct in the beginning and match what we expect. - for sdfg in [sdfg_level1, nsdfg_level2.sdfg, nsdfg_level3.sdfg]: + # Since the connectors are equivalent to the data they are connected to, all + # levels use the stride symbols of the top level. + for sdfg in all_sdfgs: for aname, adesc in sdfg.arrays.items(): - exp_stride = f"{aname}_stride" - assert len(adesc.strides) == 1 - assert str(adesc.strides[0]) == exp_stride, ( - f"Expected that '{aname}' has strides '{exp_stride}', but found '{adesc.strides}'." - ) + assert [str(s) for s in adesc.strides] == [f"{aname[0]}1_stride"] - if (nsdfg := sdfg.parent_nsdfg_node) is not None: - assert exp_stride in nsdfg.symbol_mapping - assert str(nsdfg.symbol_mapping[exp_stride]) == exp_stride - - # Now we propagate `a` and `b`, but not `c`. + # Now we change the strides of `a1` and propagate them, but not the ones of `c1`. + sdfg_level1.add_symbol("a1_new_stride", dace.int32) + sdfg_level1.arrays["a1"].set_shape((10,), (dace_symbolic.pystr_to_symbolic("a1_new_stride"),)) gtx_transformations.gt_propagate_strides_of(sdfg_level1, "a1") sdfg_level1.validate() - gtx_transformations.gt_propagate_strides_of(sdfg_level1, "b1") - sdfg_level1.validate() - # Check that the strides inside the nested SDFGs have been updated for `a` and `b`. - for sdfg in [sdfg_level1, nsdfg_level2.sdfg, nsdfg_level3.sdfg]: - for aname, adesc in sdfg.arrays.items(): - if aname.startswith("c"): - target_symbol = exp_stride = f"{aname}_stride" - elif aname == "a2_alias": - # The outside symbol should be used for `a`, create a new one with `_0` suffix - exp_stride = f"{aname[0]}1_stride_0" - target_symbol = f"{aname[0]}1_stride" - else: - target_symbol = exp_stride = f"{aname[0]}1_stride" - assert len(adesc.strides) == 1 - assert str(adesc.strides[0]) == exp_stride, ( - f"Expected that '{aname}' has strides '{exp_stride}', but found '{adesc.strides}'." - ) - - if (nsdfg := sdfg.parent_nsdfg_node) is not None: - assert exp_stride in nsdfg.symbol_mapping - assert str(nsdfg.symbol_mapping[exp_stride]) == target_symbol - - # Now we also propagate `c` thus now all data descriptors have the same stride. + # The new strides have been propagated to all levels, including `a2_alias`, which is + # also connected to `a1`. Inside the nested SDFGs the new symbol is mapped 1:1. + for sdfg in all_sdfgs: + assert set(_get_stride_of(sdfg, "a").values()) == {"a1_new_stride"} + assert set(_get_stride_of(sdfg, "b").values()) <= {"b1_stride"} + assert set(_get_stride_of(sdfg, "c").values()) == {"c1_stride"} + if (nsdfg := sdfg.parent_nsdfg_node) is not None: + assert str(nsdfg.symbol_mapping["a1_new_stride"]) == "a1_new_stride" + + # Now we also change and propagate the strides of `c1`. + sdfg_level1.add_symbol("c1_new_stride", dace.int32) + sdfg_level1.arrays["c1"].set_shape((10,), (dace_symbolic.pystr_to_symbolic("c1_new_stride"),)) gtx_transformations.gt_propagate_strides_of(sdfg_level1, "c1") sdfg_level1.validate() - for sdfg in [sdfg_level1, nsdfg_level2.sdfg, nsdfg_level3.sdfg]: - for aname, adesc in sdfg.arrays.items(): - if aname == "a2_alias": - # The outside symbol should be used for `a`, create a new one with `_0` suffix - exp_stride = f"{aname[0]}1_stride_0" - target_symbol = f"{aname[0]}1_stride" - else: - target_symbol = exp_stride = f"{aname[0]}1_stride" - assert len(adesc.strides) == 1 - assert str(adesc.strides[0]) == exp_stride, ( - f"Expected that '{aname}' has strides '{exp_stride}', but found '{adesc.strides}'." - ) - if (nsdfg := sdfg.parent_nsdfg_node) is not None: - assert exp_stride in nsdfg.symbol_mapping - assert str(nsdfg.symbol_mapping[exp_stride]) == target_symbol + for sdfg in all_sdfgs: + assert set(_get_stride_of(sdfg, "a").values()) == {"a1_new_stride"} + assert set(_get_stride_of(sdfg, "c").values()) == {"c1_new_stride"} def _make_strides_propagation_dependent_symbol_nsdfg() -> dace.SDFG: @@ -269,11 +254,8 @@ def _make_strides_propagation_dependent_symbol_sdfg() -> tuple[dace.SDFG, dace_n array_names = ["a1", "b1"] for name in array_names: - stride_sym1 = dace.symbol(f"{name}_1stride", dtype=dace.uint32) - stride_sym2 = dace.symbol(f"{name}_2stride", dtype=dace.int32) - sdfg_level1.add_symbol(stride_sym1.name, stride_sym1.dtype) - sdfg_level1.add_symbol(stride_sym2.name, stride_sym2.dtype) - stride_sym = stride_sym1 * stride_sym2 + stride_sym = dace.symbol(f"{name}_stride", dtype=dace.uint32) + sdfg_level1.add_symbol(stride_sym.name, stride_sym.dtype) sdfg_level1.add_array( name, shape=(10,), @@ -282,20 +264,16 @@ def _make_strides_propagation_dependent_symbol_sdfg() -> tuple[dace.SDFG, dace_n transient=False, ) - sdfg_level2 = _make_strides_propagation_dependent_symbol_nsdfg() - - for sym, sym_dtype in sdfg_level2.symbols.items(): - sdfg_level1.add_symbol(sym, sym_dtype) - nsdfg = state.add_nested_sdfg( - sdfg=sdfg_level2, + sdfg=_make_strides_propagation_dependent_symbol_nsdfg(), inputs={"a2"}, outputs={"b2"}, - symbol_mapping={s: s for s in sdfg_level2.symbols}, + symbol_mapping={"a2_stride": "a1_stride", "b2_stride": "b1_stride"}, ) state.add_edge(state.add_access("a1"), None, nsdfg, "a2", dace.Memlet("a1[0:10]")) state.add_edge(nsdfg, "b2", state.add_access("b1"), None, dace.Memlet("b1[0:10]")) + nsdfg.integrate_into_parent() sdfg_level1.validate() return sdfg_level1, nsdfg @@ -304,42 +282,33 @@ def _make_strides_propagation_dependent_symbol_sdfg() -> tuple[dace.SDFG, dace_n def test_strides_propagation_symbolic_expression(): sdfg_level1, nsdfg_level2 = _make_strides_propagation_dependent_symbol_sdfg() - # Ensure that the special symbols are not already present inside the nested SDFG. + # Now change the strides of `a1` and `b1` to a symbolic expression. for aname, adesc in sdfg_level1.arrays.items(): - inner_aname = aname.replace("1", "2") - inner_stride = f"{inner_aname}_stride" - adesc2 = nsdfg_level2.sdfg.arrays[inner_aname] - assert len(adesc2.strides) == 1 and isinstance(adesc2.strides[0], dace.symbol) - assert adesc2.strides[0].name == inner_stride - assert str(nsdfg_level2.symbol_mapping[inner_stride]) == inner_stride + stride_sym1 = dace.symbol(f"{aname}_1stride", dtype=dace.uint32) + stride_sym2 = dace.symbol(f"{aname}_2stride", dtype=dace.int32) + sdfg_level1.add_symbol(stride_sym1.name, stride_sym1.dtype) + sdfg_level1.add_symbol(stride_sym2.name, stride_sym2.dtype) + adesc.set_shape((10,), (stride_sym1 * stride_sym2,)) - for sym, dtype in [(f"{aname}_1stride", dace.uint32), (f"{aname}_2stride", dace.int32)]: - assert sym in sdfg_level1.symbols - assert sym in {fs.name for fs in adesc.strides[0].free_symbols} - assert sdfg_level1.symbols[sym] == dtype + # Ensure that the symbols are not already present inside the nested SDFG. + for sym in [stride_sym1.name, stride_sym2.name]: assert sym not in nsdfg_level2.symbol_mapping assert sym not in nsdfg_level2.sdfg.symbols # Now propagate `a1` and `b1`. gtx_transformations.gt_propagate_strides_of(sdfg_level1, "a1") - sdfg_level1.validate() gtx_transformations.gt_propagate_strides_of(sdfg_level1, "b1") sdfg_level1.validate() - # Now we check if the update has worked. + # The inner descriptors use the same expression, and the symbols that appear in + # it have been mapped 1:1 into the nested SDFG, keeping their type. for aname, adesc in sdfg_level1.arrays.items(): - inner_aname = aname.replace("1", "2") - inner_stride = f"__{inner_aname}_stride_0" adesc2 = nsdfg_level2.sdfg.arrays[aname.replace("1", "2")] - assert len(adesc2.strides) == 1 and isinstance(adesc2.strides[0], dace.symbol) - assert adesc2.strides[0].name == inner_stride - assert nsdfg_level2.symbol_mapping[inner_stride] == adesc.strides[0] + assert adesc2.strides == adesc.strides - for sym in [f"{aname}_1stride", f"{aname}_2stride"]: - assert sym in sdfg_level1.symbols - assert sym in {fs.name for fs in adesc.strides[0].free_symbols} - assert sym not in nsdfg_level2.symbol_mapping - assert sym not in nsdfg_level2.sdfg.symbols + for sym, dtype in [(f"{aname}_1stride", dace.uint32), (f"{aname}_2stride", dace.int32)]: + assert str(nsdfg_level2.symbol_mapping[sym]) == sym + assert nsdfg_level2.sdfg.symbols[sym] == dtype def _make_strides_propagation_shared_symbols_nsdfg() -> dace.SDFG: @@ -348,8 +317,8 @@ def _make_strides_propagation_shared_symbols_nsdfg() -> dace.SDFG: # NOTE: Both arrays have the same symbols used for strides. array_names = ["a2", "b2"] - stride_sym0 = dace.symbol(f"__stride_0", dtype=dace.uint32) - stride_sym1 = dace.symbol(f"__stride_1", dtype=dace.uint32) + stride_sym0 = dace.symbol("__stride_0", dtype=dace.uint32) + stride_sym1 = dace.symbol("__stride_1", dtype=dace.uint32) sdfg.add_symbol(stride_sym0.name, stride_sym0.dtype) sdfg.add_symbol(stride_sym1.name, stride_sym1.dtype) for name in array_names: @@ -383,8 +352,8 @@ def _make_strides_propagation_shared_symbols_sdfg() -> tuple[dace.SDFG, dace_nod # NOTE: Both arrays use the same symbols as strides. # Furthermore, they are the same as in the nested SDFG, i.e. they are shared. array_names = ["a1", "b1"] - stride_sym0 = dace.symbol(f"__stride_0", dtype=dace.uint32) - stride_sym1 = dace.symbol(f"__stride_1", dtype=dace.uint32) + stride_sym0 = dace.symbol("__stride_0", dtype=dace.uint32) + stride_sym1 = dace.symbol("__stride_1", dtype=dace.uint32) sdfg_level1.add_symbol(stride_sym0.name, stride_sym0.dtype) sdfg_level1.add_symbol(stride_sym1.name, stride_sym1.dtype) for name in array_names: @@ -439,8 +408,8 @@ def ref(a1, b1): # Now we change the strides of `b1`, and then we propagate the new strides # into the nested SDFG. We want to keep (for whatever reasons) strides of `a1`. - stride_b1_sym0 = dace.symbol(f"__b1_stride_0", dtype=dace.uint32) - stride_b1_sym1 = dace.symbol(f"__b1_stride_1", dtype=dace.uint32) + stride_b1_sym0 = dace.symbol("__b1_stride_0", dtype=dace.uint32) + stride_b1_sym1 = dace.symbol("__b1_stride_1", dtype=dace.uint32) sdfg_level1.add_symbol(stride_b1_sym0.name, stride_b1_sym0.dtype) sdfg_level1.add_symbol(stride_b1_sym1.name, stride_b1_sym1.dtype) @@ -466,98 +435,3 @@ def ref(a1, b1): ref(**ref_args) sdfg_level1(**res_args) assert np.allclose(ref_args["b1"], res_args["b1"]) - - -def _make_strides_propagation_stride_1_nsdfg() -> dace.SDFG: - sdfg_level1 = dace.SDFG(util.unique_name("strides_propagation_stride_1_nsdfg")) - state = sdfg_level1.add_state(is_start_block=True) - - a_stride_sym = dace.symbol("a_stride", dtype=dace.uint32) - b_stride_sym = dace.symbol("b_stride", dtype=dace.uint32) - stride_syms = {"a": a_stride_sym, "b": b_stride_sym} - - for name in ["a", "b"]: - sdfg_level1.add_array( - name, - shape=(10, 1), - strides=(stride_syms[name], 1), - dtype=dace.float64, - transient=False, - ) - - state.add_mapped_tasklet( - "computation", - map_ranges={"__i": "0:10"}, - inputs={"__in": dace.Memlet("a[__i, 0]")}, - code="__out = __in + 10", - outputs={"__out": dace.Memlet("b[__i, 0]")}, - external_edges=True, - ) - sdfg_level1.validate() - return sdfg_level1 - - -def _make_strides_propagation_stride_1_sdfg() -> tuple[dace.SDFG, dace_nodes.NestedSDFG]: - sdfg = dace.SDFG(util.unique_name("strides_propagation_stride_1_sdfg")) - state = sdfg.add_state(is_start_block=True) - - a_stride_sym = dace.symbol("a_stride", dtype=dace.uint32) - b_stride_sym = dace.symbol("b_stride", dtype=dace.uint32) - stride_syms = {"a": a_stride_sym, "b": b_stride_sym} - - for name in ["a", "b"]: - sdfg.add_array( - name, - shape=(10, 10), - strides=(stride_syms[name], 1), - dtype=dace.float64, - transient=False, - ) - - # Now get the nested SDFG. - sdfg_level1 = _make_strides_propagation_stride_1_nsdfg() - - nsdfg = state.add_nested_sdfg( - sdfg=sdfg_level1, - inputs={"a"}, - outputs={"b"}, - symbol_mapping=None, - ) - - state.add_edge(state.add_access("a"), None, nsdfg, "a", dace.Memlet("a[0:10, 3]")) - state.add_edge(nsdfg, "b", state.add_access("b"), None, dace.Memlet("b[0:10, 2]")) - sdfg.validate() - return sdfg, nsdfg - - -def test_strides_propagation_stride_1(): - def ref(a, b): - for i in range(10): - b[i, 2] = a[i, 3] + 10.0 - - sdfg, nsdfg = _make_strides_propagation_stride_1_sdfg() - - outer_desc_a = sdfg.arrays["a"] - inner_desc_a = nsdfg.sdfg.arrays["a"] - assert outer_desc_a.strides == inner_desc_a.strides - - # Now switch the strides of `a` on the top level. - # Essentially going from `C` to FORTRAN order. - stride_outer_a_0, stride_outer_a_1 = outer_desc_a.strides - outer_desc_a.set_shape(outer_desc_a.shape, (stride_outer_a_1, stride_outer_a_0)) - - # Now we propagate the data into it. - gtx_transformations.gt_propagate_strides_of(sdfg=sdfg, data_name="a") - - # Because of the propagation it must now been changed to `(1, 1)` on the inside. - assert inner_desc_a.strides == (1, 1) - - res_args = { - "a": np.array(np.random.rand(10, 10), order="F", dtype=np.float64, copy=True), - "b": np.array(np.random.rand(10, 10), order="C", dtype=np.float64, copy=True), - } - ref_args = copy.deepcopy(res_args) - - sdfg(**res_args, a_stride=10, b_stride=10) - ref(**ref_args) - assert np.allclose(ref_args["b"], res_args["b"]) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py index 8e8222e32d..bdd18c0a39 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py @@ -442,6 +442,8 @@ def nested_sdfg_consumer_sdfg(N: int) -> dace.SDFG: external_edges=True, ) + # The scalar connectors of the if block can not be connected to an element of an + # array directly, thus the values pass through scalar transients, as in the lowering. map_entry, map_exit = st.add_map("map2", ndrange={"__i": f"1:{N}"}) nsdfg = _make_if_block(st) for conn, node, data, subset in [ @@ -451,9 +453,19 @@ def nested_sdfg_consumer_sdfg(N: int) -> dace.SDFG: ]: map_entry.add_scope_connectors(conn) st.add_edge(node, None, map_entry, f"IN_{conn}", dace.Memlet(data=data, subset=subset)) - st.add_edge(map_entry, f"OUT_{conn}", nsdfg, conn, dace.Memlet(data=data, subset="__i")) + scalar, _ = sdfg.add_scalar( + f"{conn}_val", dtype=sdfg.arrays[data].dtype, transient=True, find_new_name=True + ) + scalar_node = st.add_access(scalar) + st.add_edge( + map_entry, f"OUT_{conn}", scalar_node, None, dace.Memlet(data=data, subset="__i") + ) + st.add_edge(scalar_node, None, nsdfg, conn, dace.Memlet(data=scalar, subset="0")) map_exit.add_scope_connectors("B") - st.add_edge(nsdfg, "__output", map_exit, "IN_B", dace.Memlet(data=B, subset="__i")) + output, _ = sdfg.add_scalar("__output_val", dtype=dace.float64, transient=True) + output_node = st.add_access(output) + st.add_edge(nsdfg, "__output", output_node, None, dace.Memlet(data=output, subset="0")) + st.add_edge(output_node, None, map_exit, "IN_B", dace.Memlet(data=B, subset="__i")) st.add_edge(map_exit, "OUT_B", B_node, None, dace.Memlet(data=B, subset=f"1:{N}")) sdfg.validate() From bb4bebe0de09ae9902e8728f61be31c3c0fb2b54 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 1 Oct 2026 08:52:37 +0200 Subject: [PATCH 06/69] refactor[next-dace]: use outer data descriptors for reduce connectors --- .../library_nodes/reduce_with_skip_values.py | 61 +++++++++++++------ 1 file changed, 43 insertions(+), 18 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py b/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py index 8b1364b3a7..9d49cf3067 100644 --- a/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py +++ b/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py @@ -8,10 +8,11 @@ from __future__ import annotations +import copy from typing import Any, Final import dace -from dace import library as dace_library, properties as dace_properties +from dace import library as dace_library, properties as dace_properties, subsets as dace_subsets from dace.sdfg import graph as dace_graph from dace.transformation import transformation as dace_transform @@ -93,6 +94,17 @@ def validate(self, sdfg: dace.SDFG, state: dace.SDFGState) -> None: raise ValueError(f"Invalid memlet on output connector {self.output_conn}.") +_LOCAL_INDEX: Final[dace.symbol] = dace.symbol("__reduce_local_idx") +"""Map parameter that iterates over the local dimension in the expansion.""" + + +def _as_global(desc: dace.data.Data) -> dace.data.Data: + """Returns a non-transient copy of `desc`, to be used as nested SDFG connector.""" + global_desc = copy.deepcopy(desc) + global_desc.transient = False + return global_desc + + @dace_library.register_expansion(ReduceWithSkipValues, "pure") class ReduceWithSkipValuesExpandInlined(dace_transform.ExpandTransformation): """Implements pure expansion of the ReduceWithSkipValues library node.""" @@ -124,20 +136,31 @@ def expansion(node: ReduceWithSkipValues, state: dace.SDFGState, sdfg: dace.SDFG # `max_neighbors` elements along one dimension. local_dim_index = inedge.data.src_subset.size().index(max_neighbors) + # The connectors of the nested SDFG have to be equivalent to the data connected + # to them (see `NestedSDFG.validate()`). Thus, they are copies of the outer + # data descriptors, and inside they are accessed with the same indices as + # outside, where the local dimension is iterated by the map parameter `_LOCAL_INDEX`. + # This way, a later change of the strides of the outer data is propagated + # to the connectors, without the need of views. + def make_local_subset(subset: dace_subsets.Range, local_index: int) -> dace_subsets.Range: + local_subset = copy.deepcopy(subset) + local_start = local_subset[local_index][0] + local_subset[local_index] = (local_start + _LOCAL_INDEX, local_start + _LOCAL_INDEX, 1) + return local_subset + + input_subset = make_local_subset(inedge.data.src_subset, local_dim_index) + mask_subset = make_local_subset(maskedge.data.src_subset, 1) + nsdfg = dace.SDFG(node.label) - inp, _ = nsdfg.add_array( - node.input_conn, - (max_neighbors,), - input_desc.dtype, - strides=(input_desc.strides[local_dim_index],), - ) - mask, _ = nsdfg.add_array( - node.mask_conn, - (max_neighbors,), - mask_desc.dtype, - strides=(mask_desc.strides[1],), + inp = node.input_conn + nsdfg.add_datadesc(inp, _as_global(input_desc)) + mask = node.mask_conn + nsdfg.add_datadesc(mask, _as_global(mask_desc)) + outp = node.output_conn + nsdfg.add_datadesc(outp, _as_global(output_desc)) + output_subset = ( + "0" if isinstance(output_desc, dace.data.Scalar) else str(outedge.data.dst_subset) ) - outp, _ = nsdfg.add_scalar(node.output_conn, output_desc.dtype) st_init = nsdfg.add_state("init") init_tasklet = st_init.add_tasklet( name="write", @@ -150,7 +173,7 @@ def expansion(node: ReduceWithSkipValues, state: dace.SDFGState, sdfg: dace.SDFG "__tlet_out", st_init.add_access(outp), None, - dace.Memlet(data=outp, subset="0"), + dace.Memlet(data=outp, subset=output_subset), ) st_reduce = nsdfg.add_state_after(st_init, "compute") # Fill skip values in local dimension with the reduce identity value @@ -160,14 +183,16 @@ def expansion(node: ReduceWithSkipValues, state: dace.SDFGState, sdfg: dace.SDFG # TODO(phimuell): decide if auto-optimizer should reset `wcr_nonatomic` properties, as DaCe does. st_reduce.add_mapped_tasklet( name="reduce_with_skip_values", - map_ranges={"i": f"0:{max_neighbors}"}, + map_ranges={str(_LOCAL_INDEX): f"0:{max_neighbors}"}, inputs={ - "__tlet_inp": dace.Memlet(data=inp, subset="i"), - "__tlet_mask": dace.Memlet(data=mask, subset="i"), + "__tlet_inp": dace.Memlet(data=inp, subset=input_subset), + "__tlet_mask": dace.Memlet(data=mask, subset=mask_subset), }, code=f"__tlet_out = __tlet_inp if __tlet_mask != {gtx_common._DEFAULT_SKIP_VALUE} else {skip_value}", outputs={ - "__tlet_out": dace.Memlet(data=outp, subset="0", wcr=node.wcr, wcr_nonatomic=True), + "__tlet_out": dace.Memlet( + data=outp, subset=output_subset, wcr=node.wcr, wcr_nonatomic=True + ), }, external_edges=True, schedule=dace.dtypes.ScheduleType.Sequential, From fb0bfcc25dec7613d1a3d04eb807d9d12174f222 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 5 Oct 2026 09:19:05 +0200 Subject: [PATCH 07/69] unstage file --- _dacegraphs/invalid.sdfgz | Bin 4912 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 _dacegraphs/invalid.sdfgz diff --git a/_dacegraphs/invalid.sdfgz b/_dacegraphs/invalid.sdfgz deleted file mode 100644 index e5f919046c61f461559f18ccf8598a20b72e398e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4912 zcmV-06VL1)iwFq51ifkk|7mV^VQgt+E^}mNXL;n8L%WayQ|(^@2FS(wVN*{ zq5Ho3%Mbtc-`!r<JO&R;wG&wY1=NC%ZJPtE8$^zqKEt83)V=Hkct=Rejw z|FQf$06C6v7V?AvhEF)b=+`*M;n?JY!{ym$ldk;QMXlh1Cr~Q@x}Uy%OSC_X&WkFY z7j5XgsHgLy2A@S8ofq|VUeutuI02m>hHFjdhXGj8d3hk6msL71+t7JgPv>O~KFc~f zFYD>NtU+^m0y;ko*P6}`1F)iVVSMtNNgtO8{);n1Gp$hk9@t1hUl@5d2qVBKpU%V1 z@Z`M1^FzetM{|3Hd!6*FB7MCYP611Q9E>XW!VrkmvNrLSR3vVH+7H!fKQvAIVQ1Qk zAiR0=-IE|yBe3I1J{XV8u=_rm;Vj%M!DpoaO!Ndact8%bL*$S=y_j4+4t zs(t~gE?-ssEUFGPo-J&C;OnaqOUs{PE3 zC!y~LE>DOfVAijnN|S(M27kTzbJwh`DL`!qQS%Hr6D8sqmqC;N)zdu!7YKj}p24qKPkyQ+)<4bc-@}lXrq1DGANQ}} z=NB`ahl=^$h{vu}^!vqw<9XiszC+&9T`Bo_k$)bK61#k`^XtJVj!VnL59!*6bPe#z z%{1>12P61`DBw{X3`2h~^5GU(_U&FcVR8`O(I~ilJYAc~4OHFtqxo=nC#cSYaN>|5 zr8!2NvkYm8IkGG>j1tYQQwiR+q^!uj5}#tE?IqBd&DeMAo^xR~`)TaUJS~Nkl@RX$ zqHv;ii9!-pS4`NMVvQ)L43rYkbJTjol?FtOmdI-_Xb?tWnr#pzha%b_KIC!YL*J68 z5g&52_=t?eObCl~3}EM?jR zZ~MhgVr}p0CO5b@+3qMGYe#93Aw0x`N3B6#rw!Xdwn`n&(pr9|yy0r>Gbat{d533b z8NT1Ys}})Zz?7ee5BCjDPCfXlxK#uCYewfaqjSED&b?wtUK2WxPv}(hH~Z_)PFkR{ z4Ap*FlZDt{sP6lc)PH%xT+T5Wn`84b4Fe8V&s^uX{mnzaQX&R%eT*+$4a{~zg#%;yQet!q z>yPtcKKR=vq4Ib5x{6`};oTGAW|d9az3a<(I4>gLgu`rZi?x3H&_9yRhc61-zXG73 z41ATOJBp^m$RPpDxPY0O+;k^WH2QxrYHUwjV6x9p`!y{9U`iRq_Gn=~p zIpCb-+hJFH7|e>rq7M^pjQ?nU(>H~frAgAGh3k=SC`N}t)`O?vw)w6tX94uRizWGe zDJ(51gQApp932AgDa18%NGnef0hU^?JQq@3FiYu{rR)%vHdQZ}bUqST-Mokxr~%#s zcnKI0E3_xtNl<{D>c#(z$CH1AYw)!zJf2T{qIE&>n<7}>_izR)uPr%eU&1sWKnUIW zzH?P~`LCTK@l%@=F5Iw#r%5h+HAuSJ_a(vEU&V>FQx5_CL|i{e;YM}pT3r642sNs~ zTy1#TJna`V9T;0kQ_U;~ZCJ+xiBFiO30(?N~g%!qx!~8%uz5!hd$9aN1 z-phL8uzD2jPlof^VYP&5n1QuQ^0dBSrq?NPclW7TqE1_8*g`)T)fX5NWE*WQfwwI> zG*%{7IPMoGm{XDqP7yW|{I@6tIIEH%N|e#Tf|G~&nQB|~QC>`@_%10~O>u&jTvi)} z;npD%I76Iha9J@0@fOTuFI1%5p1QWhp0y~lCl*C3uo1*Zq%#%MdLoiHZBV8i7FLVM z0y|TkjGbQ;*_|jl6NP4(M43|rf&~ob))|Tdlhmm!bJ(1?PIig_k*VftSv3aM48~Rr zNdmzFXP6+X!O9qjfmyUhg*#sIlc1QYTjweUuEt)YmKhwqvJz1v!3l&&7bz??GQk*5 zJSAAk4QkoN1bq*4ujJ?2%!48_i{K}C0Z~ApPh><`NRnkyT8p>)0L00|`@O=(qe5M! zTgCU4DL1@UgbU#^BpBrg+#IQi;R3mnIar5b_oWWVHgzEX9ND1iQlOQ=8N~=IM-f-TLZHMVB2sD|BNZ~Z3(o!U zEdz0tfjbWU%j9I)yWu!y*gNEy0S69zIb@kN;J|U^A_muv#|!49*m9CSdrmfOuBxxZ zZs>dHQxDnhrd?b0nX+9N+CB4-jP3*&4Ax`etpG~{KRC?{vXMvR0#ngsGz9IBkk40I zKUVXymNt~UYTonIJgZf(hHxZVmNHP3AO)cwveqe3Iuoc0ubTIVY94*|ns=D@QkTk( z84pJLfQVvgg9)a{U|1j+)-o^;UaHw&AXZdAGze=6>Y>5J;icuh#PLhuXDJ_SnFgjA ziU963yMspsx6U7ag7m`L@TL@mQh~b zjx&Z?`yFT6$jCf5;1qKSK^seZ6JdQOl6zR4F;>`~cE{O?ibJhr6%v(qk+mB0SX~nIuSa>Jjsqq=7Q3qq&@H@G%S5>lU{^K*CCfOjzT&2DK*4fgv-7 zA+XV)?`fYLcsrUC^3o;j#5?Y|rB+en5Co|P7QqOf5SJclB0>;e5m@kH`Z{CSMmRr= z@-Qu|b?x0-AUFgc4m>fd6yhW%pDb;HjM5N_wa6TA(y|0v)$=MlY9$XXUc=%7B-^ZX z#d2eZWB2chA~w2xLjwa8he39?OJ-Zw?+CZ=ajpW#;viSSU}ZB#F%m97+@OL+%2J1z zi=1k3AHcMq*6q8e@#}Gj%frj`<;HUvqQeftrWn(16G4y_TBHLS2>24<8{0#j!`CwX zDXO9uvOKksA@D%Gp&3Trrw$GQYGsTM$UtBfGO8%Z(QA49%z|+KOwzsUtB5iq!Aitb zI_M=ZimcZPF=7qVCT)hrXJ21+2J1k^Ba$M5w*+f`+HORVWMI-l2vlI&xW4wz08qff zU=|bt0;KGMGDroi5OEn6)Mw5UTEAC-KCs}g*W?wWcGi2cx8CDzOKktfOeTZTbz^62 z<;dcuF4?+sjO#jPYmR!ZZJwAeIb7S1Td@`Oy}5NK@YeL{R?pvU?%8c9lN`87TJ1X~xbO+#)9U+G1W-A)rDnr) zF}0&_Ek5Z3sIe5zh!^#v@6UQOQ&6NlM+xg3Zxyl`+*XYvI0D6 z)wI90*ql)IrMhw_S#KtPU$+HsXa?Hc$Ne}6LqDGUTFbQWH{Cb8>riDGdcWzE`B3SU z*=foDR55h5z`$J-Gc`BGSq1gd^l7~|w_CFhUz&@JU9FEAxYxfpq%(k%s?b+N`omBC z^1;_DDJx$jrHi-s$nO9C>z_3v?OY}0tGD|C>tn=>=nN_6V13dgAWMZqL@O?MAdzOV z{ch!|#HPy^Cb0K%L)39Yw&j4R<$&BLx@5$G$IMaCDTm8EMp_Y%Am$7rWF|@(n|4M& zU?uJkvBl#ygztygye7mJr8FrgJhPcWI0}d?F_R!=;2;{OASQ5JIN~;Fs?(Mo@qzZQ1 zVM8t|>2cNWZ5MC8yF#sBw{cuZ-u{&!2Zgxp-xPALq{u}hc8|GDwcO~4MH+%%#HAz1 zV(>y`#9UYvj8u5MT#U0B!8dFWo7 zs24T6s&^ASuVQzA*p>IXam!@{%P&c)(Wjk!nn;19@RnF%sHXT&CU&f~*!>aP`LC+4 zyhJsx;{5Ka`o>FC^UBTduFiH;?BmwnR@4xP7^OJ3(;$@XoSED^C5BTj`yit%)!Bp54iwf2IX%r?C+vbL}qXU~S*DYQOHq2-zV zCe$i6UYF(`j&@%Y7q5wn`>Mbv6}8q;%jy)EIz78R|9W}(;X{j)Y8EFur{*;%cxA~6 z7VW2V$+P>;#@ySPTXzyleOLCE3e7qAR@s{e>m$De#g-9FdGlrx$?3O3%4PL=z#j zQ<*36WuDJfFte#!Hqt;;@zy6v!2#mn02z)s%8WBwV(W?bXYZD^A)_`Bm=%X~T#^;Y zD)7gI4%{*7h^6|t(BqHw}~VyWq$0 z>D_hCCyRFg%=)iUxXs^9rsM0Wx#`32#KJK=I-LVI;I}s}yc>>x59wVo?^fbD?x$D5 zzn!E$ho_hc?jGC>^1+udd%{W6GVz4d4b6@9<_RZU_mHI-KPCGE^792ADc%j%rEl?D zY*I=nOs7dDzjkk6=+zs4Qo~8-iy00;W#INsG$42WeP?TDJHMrn_P1{5cQfl;1K&m+ zP@GQwIdld|twv_pN$S?|VdkcTNqXd}cwuwrs(AVF_kKLL!_ey#FFyYM3e}!PT5YQa zkGb~5&}tv_n>TMdgIQ-Z&O71%<^#Yci~z!M0pvbxYts~bx?zxau72y@{?_ev9sv2a z3h-?e+}kR!xBH;J?Rm;eB+gK|y) From 0c9d769306fd296f061643f0d995944ba221000d Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 5 Oct 2026 09:21:34 +0200 Subject: [PATCH 08/69] fix merge conflict --- .../runners/dace/lowering/gtir_to_sdfg_fieldop.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py index af5283d77a..0d794f7280 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py @@ -26,7 +26,7 @@ import dace from dace import nodes as dace_nodes, subsets as dace_subsets -from gt4py.eve.extended_typing import MaybeNestedInTuple +from gt4py.eve.xtyping import MaybeNestedInTuple from gt4py.next import common as gtx_common, utils as gtx_utils from gt4py.next.iterator import ir as gtir from gt4py.next.iterator.ir_utils import domain_utils, ir_makers as im From 508e439c52b9638ef18bfc8dd1ede22a1a47723a Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 5 Oct 2026 16:20:56 +0200 Subject: [PATCH 09/69] update uv lock --- pyproject.toml | 3 ++- uv.lock | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0c0d1a630c..0ceef086a4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -433,7 +433,8 @@ url = 'https://gridtools.github.io/pypi/' # Add the uv source below to pull dace from the gridtools index instead of PyPI: # dace = {index = "gridtools"} [tool.uv.sources] -atlas4py = { index = "test.pypi" } +atlas4py = {index = "test.pypi"} +dace = {git = "https://github.com/spcl/dace.git", branch = "main"} # -- versioningit -- [tool.versioningit] diff --git a/uv.lock b/uv.lock index d29c3f72bf..efd4414a97 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=nested-sdfg#ee0d1a27c7210219bfe4279181380ccf1e01e061" } +source = { git = "https://github.com/spcl/dace.git?branch=main#97f98e31f9e350c6270ddd11766bbeb57416d7d7" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/spcl/dace.git?branch=nested-sdfg" }, + { name = "dace", git = "https://github.com/spcl/dace.git?branch=main" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From d1da3ed927120d11218a2de17211e006b649d20c Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 9 Oct 2026 09:58:20 +0200 Subject: [PATCH 10/69] fixes --- .../dace/lowering/gtir_to_sdfg_concat_where.py | 11 ++++++++++- .../runners/dace/workflow/common.py | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py index ed6b8dcc9c..94531219b9 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py @@ -104,7 +104,16 @@ def testee(interior: cases.IJKField, boundary: cases.IJField) -> cases.IJKField: """ assert isinstance(source_expr.type, (ts.FieldType, ts.ScalarType)) - source_domain = source_expr.annex.domain + # The annex domain of the expression node is read-only here: the local copy is + # specialized below to the region of this `concat_where` branch, but the node + # itself keeps its own domain. This is essential when the node is lowered as + # an argument of the promoted `as_fieldop` expression: there, the map ranges + # and the result write subset are both derived from the node's domain, and an + # inconsistency between them would produce subsets that reference map + # variables which are not in scope. + source_domain = domain_utils.SymbolicDomain( + source_expr.annex.domain.grid_type, dict(source_expr.annex.domain.ranges) + ) if source_expr.type != output_type: # We promote the input expression to a field defined on the output domain, # refer to the function documentation for examples of such field operators. diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 395063a97f..1e9cbb65fd 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -167,6 +167,18 @@ def set_dace_config( value=("development" if gtx_config.KEEP_DACE_BUILD_FILES else "production"), ) + # Do not lift implicit copies to `CopyLibraryNode` instances during code generation. + # The lowering and the transformations of the conditional expressions (`if_`) that + # GT4Py performs produce direct array-to-array copy edges, inside the branch states + # of nested SDFGs, that memlet propagation marks as dynamic. The `CopyLibraryNode` + # that the pass inserts for such an edge is expanded into a tasklet, whose dynamic + # output write is then silently dropped by the CPU code generator (the write is + # supposed to be emitted inline in the tasklet body, but the corresponding code + # path calls `TargetCodeGenerator.ptr()` with an outdated signature, raising a + # `TypeError` that is swallowed). Keeping the copies implicit makes the code + # generator handle them through the array copy path instead, which is correct. + dace.Config.set("compiler.cpu.explicit_copy", value=False) + # We are not interested in storing the history of SDFG transformations. dace.Config.set("store_history", value=False) From a97dc43a046c6f138a4f870a9555d8fa1310a022 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 9 Oct 2026 11:23:38 +0200 Subject: [PATCH 11/69] switch to dace dev branch --- pyproject.toml | 4 ++-- uv.lock | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0ceef086a4..5c9a9805fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -433,8 +433,8 @@ url = 'https://gridtools.github.io/pypi/' # Add the uv source below to pull dace from the gridtools index instead of PyPI: # dace = {index = "gridtools"} [tool.uv.sources] -atlas4py = {index = "test.pypi"} -dace = {git = "https://github.com/spcl/dace.git", branch = "main"} +atlas4py = { index = "test.pypi" } +dace = { git = "https://github.com/edopao/dace.git", branch = "fix-staging" } # -- versioningit -- [tool.versioningit] diff --git a/uv.lock b/uv.lock index efd4414a97..0516d9b5f0 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.12, !=3.13.10, !=3.14.1, <3.15" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=main#97f98e31f9e350c6270ddd11766bbeb57416d7d7" } +source = { git = "https://github.com/edopao/dace.git?branch=fix-staging#b10c5f892cd9e5b42f09df9f2a9e54652828ca9f" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/spcl/dace.git?branch=main" }, + { name = "dace", git = "https://github.com/edopao/dace.git?branch=fix-staging" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 724549cee4be9eca33f2e4f3f39c05833c322718 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 9 Oct 2026 12:55:37 +0200 Subject: [PATCH 12/69] fix remove_access_node_copies --- .../dace/transformations/remove_access_node_copies.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py index 97e9a18a4e..c6e82071b2 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py @@ -264,3 +264,10 @@ def apply( gtx_transformations_strides.gt_propagate_strides_from_access_node( sdfg, graph, modified_node ) + + # Restate connectors of NestedSDFGs whose edge data was changed above. + # Without this the nested SDFG contract is violated because the + # connector descriptors no longer match the parent data. + for node in graph.nodes(): + if isinstance(node, dace_nodes.NestedSDFG) and node.sdfg is not None: + node.integrate_into_parent() From c896927e3c763b5294b1c051c9f01ac539365a46 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 9 Oct 2026 14:03:36 +0200 Subject: [PATCH 13/69] update uv lock --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 0516d9b5f0..baa8afeb04 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/edopao/dace.git?branch=fix-staging#b10c5f892cd9e5b42f09df9f2a9e54652828ca9f" } +source = { git = "https://github.com/edopao/dace.git?branch=fix-staging#8a90455953dc52e917cfc709a875e9b2b0aae33a" } dependencies = [ { name = "astunparse" }, { name = "click" }, From 2f2cc58c2b29b60b752a537c77ada8d37d1ed707 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 9 Oct 2026 16:38:00 +0200 Subject: [PATCH 14/69] fix[next-dace]: move variable-length Register transients to GPU_Global MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GPUTransformLocalStorage (run with nested_seq=True) sets all StorageType.Default transients inside a GPU map to StorageType.Register. However, variable-length arrays (whose size is not known at compile time, e.g. scan column temporaries) cannot be allocated in registers on GPU — the DaCe code generator emits a call to the host-only dace::aligned_new_array() inside the __global__ kernel, which nvcc rejects. Move such arrays to GPU_Global with the pool allocator instead. --- .../runners/dace/transformations/gpu_utils.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py index e98c1ddfca..d896f57a02 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py @@ -97,6 +97,22 @@ def gt_gpu_transformation( simplify=False, ) + # `GPUTransformLocalStorage` (invoked above with `nested_seq=True`) sets all + # `StorageType.Default` transients inside a GPU map to `StorageType.Register`. + # However, a variable-length array (whose size is not known at compile time) + # cannot be allocated in registers on GPU — the DaCe code generator would + # emit a call to the host-only `dace::aligned_new_array()` inside the kernel, + # which nvcc rejects. Move such arrays to `GPU_Global` with the pool + # allocator instead. + for sd, _, desc in sdfg.arrays_recursive(): + if ( + isinstance(desc, dace.data.Array) + and desc.transient + and desc.storage == dace.dtypes.StorageType.Register + and dace.symbolic.issymbolic(desc.total_size, sd.constants) + ): + desc.storage = dace.dtypes.StorageType.GPU_Global + # The documentation recommends to run simplify afterwards gtx_transformations.gt_simplify(sdfg, validate=False, validate_all=validate_all) From db3da3c8e85fcaeaa507160e3554c6183fd07eaf Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 9 Oct 2026 17:37:29 +0200 Subject: [PATCH 15/69] Revert "fix[next-dace]: move variable-length Register transients to GPU_Global" This reverts commit d72f9493a529e4f55909456cd2dffb8f61b12401. --- .../runners/dace/transformations/gpu_utils.py | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py index d896f57a02..e98c1ddfca 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/gpu_utils.py @@ -97,22 +97,6 @@ def gt_gpu_transformation( simplify=False, ) - # `GPUTransformLocalStorage` (invoked above with `nested_seq=True`) sets all - # `StorageType.Default` transients inside a GPU map to `StorageType.Register`. - # However, a variable-length array (whose size is not known at compile time) - # cannot be allocated in registers on GPU — the DaCe code generator would - # emit a call to the host-only `dace::aligned_new_array()` inside the kernel, - # which nvcc rejects. Move such arrays to `GPU_Global` with the pool - # allocator instead. - for sd, _, desc in sdfg.arrays_recursive(): - if ( - isinstance(desc, dace.data.Array) - and desc.transient - and desc.storage == dace.dtypes.StorageType.Register - and dace.symbolic.issymbolic(desc.total_size, sd.constants) - ): - desc.storage = dace.dtypes.StorageType.GPU_Global - # The documentation recommends to run simplify afterwards gtx_transformations.gt_simplify(sdfg, validate=False, validate_all=validate_all) From 4e217601126e501249a3d6d7b6cd2ced0e4f5602 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 9 Oct 2026 17:39:54 +0200 Subject: [PATCH 16/69] update uv lock --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index baa8afeb04..9c159c99b5 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/edopao/dace.git?branch=fix-staging#8a90455953dc52e917cfc709a875e9b2b0aae33a" } +source = { git = "https://github.com/edopao/dace.git?branch=fix-staging#5e02c4157c71df548019cdc5ef71acaf8dfae4c4" } dependencies = [ { name = "astunparse" }, { name = "click" }, From 374965789e2b1e6f968e910d2dc3a4bc9bb6b7ed Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 12 Oct 2026 09:34:54 +0200 Subject: [PATCH 17/69] update uv lock --- pyproject.toml | 2 +- uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5c9a9805fb..4331baa319 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -434,7 +434,7 @@ url = 'https://gridtools.github.io/pypi/' # dace = {index = "gridtools"} [tool.uv.sources] atlas4py = { index = "test.pypi" } -dace = { git = "https://github.com/edopao/dace.git", branch = "fix-staging" } +dace = { git = "https://github.com/spcl/dace.git", branch = "main" } # -- versioningit -- [tool.versioningit] diff --git a/uv.lock b/uv.lock index 9c159c99b5..bd388adcc4 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/edopao/dace.git?branch=fix-staging#5e02c4157c71df548019cdc5ef71acaf8dfae4c4" } +source = { git = "https://github.com/spcl/dace.git?branch=main#44ee5d13543560d62895c81be1d542e31b849c72" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/edopao/dace.git?branch=fix-staging" }, + { name = "dace", git = "https://github.com/spcl/dace.git?branch=main" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 7bcfc0405e8ede3e43bdd6c6c491dee6d97cfa4f Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 12 Oct 2026 10:35:17 +0200 Subject: [PATCH 18/69] replace Indices with Range --- .../single_state_global_self_copy_elimination.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/single_state_global_self_copy_elimination.py b/src/gt4py/next/program_processors/runners/dace/transformations/single_state_global_self_copy_elimination.py index ec00ac4f8f..77123b1791 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/single_state_global_self_copy_elimination.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/single_state_global_self_copy_elimination.py @@ -816,7 +816,7 @@ def _compute_offset( # the matching. One idea would be to use `cover()`, however, there are # some rare cases where this is not possible. For that reason we use # the lower bound. This might be a bit dangerous. - lower_bound = dace_sbs.Indices(tdesc.subset.min_element()) + lower_bound = dace_sbs.Range.from_indices(tdesc.subset.min_element()) associated_tmp_subset: Optional[dace_sbs.Subset] = next( ( merged_tmp_subset From 1e0c1c484e1036d74f9080198bf820312950283a Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 12 Oct 2026 10:47:18 +0200 Subject: [PATCH 19/69] update uv lock --- pyproject.toml | 2 +- uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4331baa319..c6356bac86 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -434,7 +434,7 @@ url = 'https://gridtools.github.io/pypi/' # dace = {index = "gridtools"} [tool.uv.sources] atlas4py = { index = "test.pypi" } -dace = { git = "https://github.com/spcl/dace.git", branch = "main" } +dace = { git = "https://github.com/edopao/dace.git", branch = "map-fusion-intermediates-symbolic-size" } # -- versioningit -- [tool.versioningit] diff --git a/uv.lock b/uv.lock index bd388adcc4..70cb5271b6 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=main#44ee5d13543560d62895c81be1d542e31b849c72" } +source = { git = "https://github.com/edopao/dace.git?branch=map-fusion-intermediates-symbolic-size#877e91fa195d84b17744c2f7c9664a5b58cdbbdc" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/spcl/dace.git?branch=main" }, + { name = "dace", git = "https://github.com/edopao/dace.git?branch=map-fusion-intermediates-symbolic-size" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 0bdd4a6b77844e52597317f24ee108dce8cb9d74 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 12 Oct 2026 14:00:51 +0200 Subject: [PATCH 20/69] fix[next-dace]: restate NestedSDFG connectors before stride propagation in RemoveAccessNodeCopies RemoveAccessNodeCopies repoints the edges of scan NestedSDFGs at the full output field (e.g. next_w) by merging temporary access nodes. The scan's inner output connector, however, has the domain shape, which is windowed relative to the full field. This made _gt_map_strides_into_nested_sdfg() raise: ValueError: The connector '__gtir_scan_output_x_kplus1' of NestedSDFG 'scan_1' is not equivalent to the data 'next_w' The issue only surfaced with compile_time_domain/compile_time_vertical variants, where the domain bounds are concrete and the pattern matcher can prove the copy chain is a no-op; the default (symbolic) variant does not trigger the pattern. As the docstring of _gt_map_strides_into_nested_sdfg already states, a transformation that connects different data to a connector must restate it. Call restate_nested_sdfg_connector() to adopt the new outer descriptor and shift the memlets inside by the offset of the old domain-sized data within the full field, before propagating strides. --- .../remove_access_node_copies.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py index c6e82071b2..4f2272808e 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py @@ -259,6 +259,32 @@ def apply( second_node.data = first_node.data third_node.data = first_node.data + # Restate the connectors of any NestedSDFG whose edge data was changed + # above: the transformation connected different (larger) data to the + # connector, so the inner descriptor has to adopt the new outer one and + # the memlets inside have to be shifted by the offset of the old data + # within the new. This must happen *before* stride propagation, because + # `_gt_map_strides_into_nested_sdfg()` validates the connector and + # raises if it is still windowed (inner shape != outer shape). + outer_desc = sdfg.arrays[first_node.data] + for node in graph.nodes(): + if not isinstance(node, dace_nodes.NestedSDFG) or node.sdfg is None: + continue + for edge in graph.all_edges(node): + if edge.data.data != first_node.data: + continue + connector = edge.dst_conn if edge.dst is node else edge.src_conn + if not connector or connector not in node.sdfg.arrays: + continue + if node.sdfg.arrays[connector].transient: + continue + gtx_transformations_utils.restate_nested_sdfg_connector( + node, + connector, + outer_desc, + ss_offset=tuple(node_offset), + ) + # Update strides after changing the data of access nodes for modified_node in [second_node, third_node]: gtx_transformations_strides.gt_propagate_strides_from_access_node( From acd8a63c8d6574f30346dbcfe9c4040120ff515b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 12 Oct 2026 15:28:55 +0200 Subject: [PATCH 21/69] set explicitly allow_intermediates_with_symbolic_size=False --- .../runners/dace/transformations/map_fusion.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py index daad8c1530..bf74ad4e81 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py @@ -66,6 +66,9 @@ class MapFusionVertical(dace_dftrans.MapFusionVertical): Essentially the same as DaCe's `MapFusionVertical`, but with the following differences: - `strict_dataflow` is by default `False`, whereas in DaCe it is `True` for compatibility reasons. + - `allow_intermediates_with_symbolic_size` is set to `False`, to avoid the creation + of intermediate arrays with symbolic size, which would require dynamic allocation + and therefore are inefficient for GPU kernels. - It accepts the additional `check_fusion_callback`, which is called before the `can_be_applied()` function of the DaCe version is called. If it returns `False` then the fusion will be rejected. @@ -81,6 +84,7 @@ def __init__( ) -> None: super().__init__( strict_dataflow=strict_dataflow, + allow_intermediates_with_symbolic_size=False, **kwargs, ) self._check_fusion_callback = None From 90710d45de8568910bd0e4497d475922bd989b27 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 12 Oct 2026 21:54:38 +0200 Subject: [PATCH 22/69] update uv lock --- pyproject.toml | 2 +- uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c6356bac86..4331baa319 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -434,7 +434,7 @@ url = 'https://gridtools.github.io/pypi/' # dace = {index = "gridtools"} [tool.uv.sources] atlas4py = { index = "test.pypi" } -dace = { git = "https://github.com/edopao/dace.git", branch = "map-fusion-intermediates-symbolic-size" } +dace = { git = "https://github.com/spcl/dace.git", branch = "main" } # -- versioningit -- [tool.versioningit] diff --git a/uv.lock b/uv.lock index 70cb5271b6..94bd6c48c0 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/edopao/dace.git?branch=map-fusion-intermediates-symbolic-size#877e91fa195d84b17744c2f7c9664a5b58cdbbdc" } +source = { git = "https://github.com/spcl/dace.git?branch=main#fd7289d20d5dbddc512d4e37c88db60edcd1c144" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/edopao/dace.git?branch=map-fusion-intermediates-symbolic-size" }, + { name = "dace", git = "https://github.com/spcl/dace.git?branch=main" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 1411a878c600068f949464d676574c94209b901b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 07:30:12 +0200 Subject: [PATCH 23/69] update uv lock --- .../runners/dace/transformations/move_dataflow_into_if_body.py | 2 +- .../program_processors/runners/dace/transformations/utils.py | 2 +- .../transformation_tests/test_move_dataflow_into_if_body.py | 2 +- uv.lock | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/move_dataflow_into_if_body.py b/src/gt4py/next/program_processors/runners/dace/transformations/move_dataflow_into_if_body.py index 130a55d245..32ab0f379e 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/move_dataflow_into_if_body.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/move_dataflow_into_if_body.py @@ -896,7 +896,7 @@ def _partition_if_block( # Now inspect all states. for _, if_branch in inner_if_block.branches: - for inner_state in if_branch.all_states(): + for inner_state in if_branch.states(): for dnode in inner_state.data_nodes(): node_data = dnode.data diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py index a365ab154a..7088106003 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py @@ -736,7 +736,7 @@ def _impl( if isinstance(successor, dace.SDFGState): all_successors.append(successor) else: - all_successors.extend(successor.all_states()) + all_successors.extend(successor.states()) return all_successors diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py index 23313dc15a..007c87507d 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py @@ -511,7 +511,7 @@ def test_if_mover_invalid_if_block(): # Replace the reads to `__arg2` with ones to `__arg1`. This means the dataflow # that goes into `__arg1` would have to be replicated into two different places # which is not supported, thus the transformation will not apply. - for inner_state in if_block.sdfg.all_states(): + for inner_state in if_block.sdfg.states(): for dnode in inner_state.data_nodes(): if dnode.data == "__arg2": dnode.data = "__arg1" diff --git a/uv.lock b/uv.lock index 94bd6c48c0..988b40dbf8 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=main#fd7289d20d5dbddc512d4e37c88db60edcd1c144" } +source = { git = "https://github.com/spcl/dace.git?branch=main#6cdee42594c9f82f1b6768a97fe6076db5bfe6cb" } dependencies = [ { name = "astunparse" }, { name = "click" }, From 9666bd51f6d4f1907c1372c11a6ba3ef8f56c7cb Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 08:45:03 +0200 Subject: [PATCH 24/69] fix generator to list --- src/gt4py/cartesian/backend/dace_backend.py | 2 +- .../runners/dace/lowering/gtir_to_sdfg_scan.py | 13 ++++++------- .../transformation_tests/test_loop_blocking.py | 6 +++--- .../test_vertical_map_split_fusion.py | 2 +- 4 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/gt4py/cartesian/backend/dace_backend.py b/src/gt4py/cartesian/backend/dace_backend.py index bf3e09e592..748d939a29 100644 --- a/src/gt4py/cartesian/backend/dace_backend.py +++ b/src/gt4py/cartesian/backend/dace_backend.py @@ -287,7 +287,7 @@ def freeze_origin_domain_sdfg( # in special case of empty domain, remove entire SDFG. if any(d == 0 for d in domain): - states = wrapper_sdfg.states() + states = list(wrapper_sdfg.states()) assert len(states) == 1 for node in states[0].nodes(): state.remove_node(node) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index 5c8df1ca12..89c60fa4d7 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -361,8 +361,9 @@ def _handle_dataflow_result_of_nested_sdfg( ) inner_desc.transient = False # We write the result to the output field after the loop region has ended. - if len(inner_ctx.sdfg.states()) == 3: - assert sorted(st.label for st in inner_ctx.sdfg.states()) == [ + inner_states = list(inner_ctx.sdfg.states()) + if len(inner_states) == 3: + assert sorted(st.label for st in inner_states) == [ "scan_compute", "scan_entry", "scan_update", @@ -374,18 +375,16 @@ def _handle_dataflow_result_of_nested_sdfg( ) last_level_state = inner_ctx.sdfg.add_state_after(scan_loop, "scan_last_level") else: - assert sorted(st.label for st in inner_ctx.sdfg.states()) == [ + assert sorted(st.label for st in inner_states) == [ "scan_compute", "scan_entry", "scan_last_level", "scan_update", ] - last_level_state = next( - s for s in inner_ctx.sdfg.states() if s.label == "scan_last_level" - ) + last_level_state = next(s for s in inner_states if s.label == "scan_last_level") # Move the write of the result from the scan loop to the state after the loop, # so that only the last level is written. - scan_compute_state = next(s for s in inner_ctx.sdfg.states() if s.label == "scan_compute") + scan_compute_state = next(s for s in inner_states if s.label == "scan_compute") inner_output_node = next( n for n in scan_compute_state.data_nodes() if n.data == inner_dataname ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py index e1e4630a92..bb7e9e1290 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_loop_blocking.py @@ -243,8 +243,8 @@ def test_only_dependent(): ) assert count == 1 - assert len(sdfg.states()) == 1 - state = sdfg.states()[0] + assert len(list(sdfg.states())) == 1 + state = next(iter(sdfg.states())) source_nodes = state.source_nodes() assert len(source_nodes) == 2 assert all(isinstance(x, dace_nodes.AccessNode) for x in source_nodes) @@ -285,7 +285,7 @@ def test_intermediate_access_node(): ref = reff(a, b) # Now make a small modification is such that the transformation does something. - state = sdfg.states()[0] + state = next(iter(sdfg.states())) sdfg.add_scalar("tmp", dace.float64, transient=True) tmp = state.add_access("tmp") diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py index bdd18c0a39..e394d439ca 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_vertical_map_split_fusion.py @@ -106,7 +106,7 @@ def test_vertical_map_fusion(): assert ret == 1 assert util.count_nodes(sdfg, dace_nodes.MapEntry) == 1 - assert len(sdfg.states()) == 1 + assert len(list(sdfg.states())) == 1 st = next(iter(sdfg.states())) map_entry = next(node for node in st.nodes() if isinstance(node, dace_nodes.MapEntry)) From 6f8bd8402e5d29ad2fc6391cb43e30330d2a6bfa Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 09:03:43 +0200 Subject: [PATCH 25/69] fix generator to list --- .../test_fuse_horizontal_conditionblocks.py | 5 +++-- .../transformation_tests/test_move_dataflow_into_if_body.py | 5 ++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py index 7639725454..b853f9abbc 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_fuse_horizontal_conditionblocks.py @@ -287,8 +287,9 @@ def test_fuse_horizontal_condition_blocks_single_false(uids: gtx_utils.IDGenerat # `__i` is used to write the outputs in place, see `_make_map_with_conditional_blocks()`. assert conditional_block.sdfg.symbols.keys() == {"multiplier", "__i"} - true_branch_state = conditional_block.sdfg.states()[0] - false_branch_state = conditional_block.sdfg.states()[1] + true_branch_state, false_branch_state = (st for st in conditional_block.sdfg.states()) + assert "true_branch" in true_branch_state.label + assert "false_branch" in false_branch_state.label assert "true_tasklet" in [ n.label for n in true_branch_state.nodes() if isinstance(n, dace_nodes.Tasklet) ] diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py index 007c87507d..6033712f62 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py @@ -1378,7 +1378,8 @@ def test_if_mover_dependent_branch_6(): "__arg2", "__output1", ] - false_branch_state = if_block.sdfg.states()[1] + true_branch_state, false_branch_state = (st for st in if_block.sdfg.states()) + assert "true_branch" in true_branch_state.label assert "false_branch" in false_branch_state.label actual_access_nodes_in_false_branch = [ ac.data for ac in util.count_nodes(false_branch_state, dace_nodes.AccessNode, True) @@ -1391,8 +1392,6 @@ def test_if_mover_dependent_branch_6(): tlet.label for tlet in util.count_nodes(false_branch_state, dace_nodes.Tasklet, True) } assert expected_tasklets_in_false_branch == actual_tasklets_in_false_branch - true_branch_state = if_block.sdfg.states()[0] - assert "true_branch" in true_branch_state.label expected_access_nodes_in_true_branch = {"a", "b", "t1", "__arg1", "__output1"} actual_access_nodes_in_true_branch = [ ac.data for ac in util.count_nodes(true_branch_state, dace_nodes.AccessNode, True) From 997c4d08a1113d033f526ac600714cb2f1a863c9 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 09:06:50 +0200 Subject: [PATCH 26/69] edit dace version --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 4331baa319..a37ef2592c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -98,7 +98,7 @@ dependencies = [ 'click>=8.0.0', 'cmake>=3.22', 'cytoolz>=1.0.1', - 'dace==2.0.0a10', + 'dace==2.0.0b1', 'deepdiff>=8.1.0', 'devtools>=0.6', "filelock>=3.18.0", From 60d50702fe243933fdf6e46a1fdd89de014e912d Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 09:41:32 +0200 Subject: [PATCH 27/69] fix generator to list --- .../unit_tests/backend_tests/test_dace_backend.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py b/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py index 96b2546778..b75149bf93 100644 --- a/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py +++ b/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py @@ -110,7 +110,7 @@ def test_dace_cpu_loop_structure(): manager = SDFGManager(builder) sdfg = manager.sdfg_via_schedule_tree() - state = sdfg.states()[0] + state = next(iter(sdfg.states())) loop_indices = [node.map.params for node in state.nodes() if isinstance(node, nodes.MapEntry)] assert loop_indices[0] == [ @@ -125,7 +125,7 @@ def test_dace_cpu_kfirst_loop_structure(): manager = SDFGManager(builder) sdfg = manager.sdfg_via_schedule_tree() - state = sdfg.states()[0] + state = next(iter(sdfg.states())) loop_indices = [node.map.params for node in state.nodes() if isinstance(node, nodes.MapEntry)] assert loop_indices[0] == [ @@ -139,7 +139,7 @@ def test_dace_cpu_kfirst_loop_structure(): sdfg = manager.sdfg_via_schedule_tree() assert len(list(sdfg.states())) == 1, "expect one state" - state = sdfg.states()[0] + state = next(iter(sdfg.states())) # Expect a Map for IJ outside map_entry_nodes = [node for node in state.nodes() if isinstance(node, nodes.MapEntry)] @@ -165,7 +165,7 @@ def test_dace_cpu_KJI_loop_structure(): manager = SDFGManager(builder) sdfg = manager.sdfg_via_schedule_tree() - state = sdfg.states()[0] + state = next(iter(sdfg.states())) loop_indices = [ node.map.params for node in state.nodes() if isinstance(node, nodes.MapEntry) @@ -203,7 +203,7 @@ def test_dace_cpu_KJI_loop_structure_parallel(): sdfg = manager.sdfg_via_schedule_tree() assert len(list(sdfg.states())) == 1, "expect one state" - state = sdfg.states()[0] + state = next(iter(sdfg.states())) # Expect a Map for IJ outside map_entry_nodes = [node for node in state.nodes() if isinstance(node, nodes.MapEntry)] From 02259e704fcb10df4ec1861565e7bc0a119af33b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 10:53:15 +0200 Subject: [PATCH 28/69] fix generator to list --- .../runners_tests/dace_tests/test_dace_translation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 87e212afc9..8174c37190 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 @@ -174,7 +174,7 @@ def _check_sdfg_with_async_call(sdfg: dace.SDFG) -> None: def _check_sdfg_without_async_call(sdfg: dace.SDFG) -> None: - states = sdfg.states() + states = list(sdfg.states()) sink_states = sdfg.sink_nodes() # Test if the distinctive sink node is present. From d783a8ba6173049b4f4619fc2739dc1e66a27048 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 22 Sep 2026 17:51:30 +0200 Subject: [PATCH 29/69] Add SDFG int64 argument tp specify an external gpu stream --- .../runners/dace/workflow/backend.py | 8 +- .../runners/dace/workflow/common.py | 3 + .../runners/dace/workflow/decoration.py | 2 + .../runners/dace/workflow/translation.py | 87 ++++++++----------- .../dace_tests/test_dace_translation.py | 30 +++---- 5 files changed, 60 insertions(+), 70 deletions(-) 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 98149f20c4..ce0cc5fede 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -76,7 +76,7 @@ def make_dace_toolchain( def make_dace_backend( gpu: bool, auto_optimize: bool = True, - async_sdfg_call: bool = True, + sync_sdfg_call: bool = False, 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, @@ -94,8 +94,8 @@ def make_dace_backend( Args: gpu: Enable GPU transformations and code generation. auto_optimize: Enable the SDFG auto-optimize pipeline. - async_sdfg_call: Make an asynchronous SDFG call on GPU to allow overlapping - of GPU kernel execution with the Python driver code. + sync_sdfg_call: Force a synchronous SDFG call on GPU, instead of allowing + the GPU kernel execution to overlap with the Python driver code. optimization_args: A `dict` containing configuration parameters for the SDFG auto-optimize pipeline, see `gt_auto_optimize()`. external_workspace: Workspace memory externally allocated, which is used @@ -136,7 +136,7 @@ def make_dace_backend( translation=functools.partial( gtx_wfdfactory.make_dace_translator, auto_optimize_args=optimization_args, - async_sdfg_call=async_sdfg_call, + sync_sdfg_call=sync_sdfg_call, use_metrics=use_metrics, disable_field_origin_on_program_arguments=use_zero_origin, 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/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 1e9cbb65fd..5f8fc81613 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -33,6 +33,9 @@ SDFG_ARG_METRIC_COMPUTE_TIME_DTYPE: Final[dace.dtypes.typeclass] = dace.float64 """DaCe datatype of `SDFG_ARG_METRIC_COMPUTE_TIME` argument.""" +SDFG_ARG_EXTERNAL_GPU_STREAM: Final[str] = "gt_external_gpu_stream" +"""Name of SDFG argument to input an external GPU stream to GT4Py.""" + ExternalWorkspace: TypeAlias = dict[ core_defs.DeviceType, xtyping.ArrayInterface | xtyping.CUDAArrayInterface diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py index 57f45964ce..6c17403ea6 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py @@ -85,6 +85,8 @@ def __call__( gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL: metrics.get_current_level(), gtx_wfdcommon.SDFG_ARG_METRIC_COMPUTE_TIME: self._collect_time_arg, } + if gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM not in this_call_args: + this_call_args[gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM] = 0 self._fun.construct_arguments(**this_call_args) # Perform the call to the SDFG. 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 ee96fbeff2..372aaf304e 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -94,44 +94,6 @@ def find_constant_symbols( return constant_symbols -def make_sdfg_call_async(sdfg: dace.SDFG, gpu: bool) -> None: - """Configure an SDFG to immediately return once all work has been scheduled. - - This means that `CompiledSDFG.fast_call()` will return immediately after all - computations have been _scheduled_ on the device. This function only has an effect - for work that runs on the GPU. Furthermore, all work is scheduled on the - default stream. - - Todo: Revisit this function once DaCe changes its behaviour in this regard. - """ - - # This is only a problem on GPU. - # TODO(phimuell): Figuring out what about OpenMP. - if not gpu: - return - - assert dace.Config.get("compiler.cuda.max_concurrent_streams") == -1, ( - f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." - ) - - # NOTE: We are using the default stream this means that _**currently**_ the launch is - # already asynchronous, see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120) - # for more. However, DaCe still [generates streams internally](https://github.com/spcl/dace/blob/54c935cfe74a52c5107dc91680e6201ddbf86821/dace/codegen/targets/cuda.py#L467). - # Thus to be absolutely sure we will no set all streams, DaCe uses to the default - # stream. - # NOTE: Another important note here is, that it looks as if no synchronization - # what soever between states is generated if the default stream is used. This - # might lead to problems if a GPU kernel computes something that is needed for a - # condition of an interstate edge. However, we should not have that case. - # TODO(phimuell, edopao): Make sure if this is really the case. - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." - sdfg.append_init_code( - f"__dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault);", - location="cuda", - ) - - def _has_gpu_schedule(sdfg: dace.SDFG) -> bool: """Check if any node (e.g. maps) of the given SDFG is scheduled on GPU.""" return any( @@ -275,6 +237,34 @@ def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: sdfg.validate() +def add_configurable_stream(sdfg: dace.SDFG, on_gpu: bool) -> None: + """Add a configurable stream to the SDFG. + + This allows to set the stream used for all GPU work, which allows to + synchronize the execution of GPU kernels with external workload and to share + the stream memory pool. + + If the stream argument is not provided, the default stream is used. + """ + if not on_gpu: + # This is only a problem on GPU. Dace uses OpenMP on CPU and + # the OpenMP parallel region creates a synchronization point. + return + + stream_arg, _ = sdfg.add_scalar(gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM, dace.int64) + dace_gpu_backend = dace.Config.get("compiler.cuda.backend") + assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." + sdfg.append_init_code( + f"""\ +if ({stream_arg} == 0) {{ + __dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault); +}} else {{ + __dace_gpu_set_all_streams(__state, {stream_arg}); +}}""", + location="cuda", + ) + + def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: """Process the SDFG such that the call is synchronous. @@ -325,19 +315,14 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: "sync_tlet", inputs={}, outputs={}, - code=f"{dace_gpu_backend}StreamSynchronize({dace_gpu_backend}StreamDefault);", + code=f"""\ +for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {{ + {dace_gpu_backend}StreamSynchronize(__state->gpu_context->streams[__i]); +}}""", language=dace.dtypes.Language.CPP, side_effects=True, ) - # DaCe [still generates a stream](https://github.com/spcl/dace/blob/54c935cfe74a52c5107dc91680e6201ddbf86821/dace/codegen/targets/cuda.py#L467) - # despite not using it. Thus to be absolutely sure, we will not set that stream - # to the default stream. - sdfg.append_init_code( - f"__dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault);", - location="cuda", - ) - #: The parameters of `gt_auto_optimize()` that the translation step derives from #: its own configuration, and which therefore cannot be customized. @@ -360,7 +345,7 @@ class DaCeTranslator( device_type: core_defs.DeviceType auto_optimize: bool auto_optimize_args: dict[str, Any] | None - async_sdfg_call: bool + sync_sdfg_call: bool unstructured_horizontal_has_unit_stride: bool use_metrics: bool @@ -449,14 +434,14 @@ def _generate_sdfg_without_configuring_dace( sdfg, constant_symbols, validate=True ) - if self.async_sdfg_call: - make_sdfg_call_async(sdfg, on_gpu) - else: + if self.sync_sdfg_call: make_sdfg_call_sync(sdfg, on_gpu) if self.use_metrics: add_instrumentation(sdfg, on_gpu) + add_configurable_stream(sdfg, on_gpu) + return sdfg def __call__( 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..f36e7c71cd 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 @@ -62,7 +62,7 @@ def _translate_gtir_to_sdfg( offset_provider: gtx_common.OffsetProvider, device_type: core_defs.DeviceType, auto_optimize: bool, - async_sdfg_call: bool, + sync_sdfg_call: bool, use_metrics: bool = False, ) -> dace.SDFG: with dace.config.set_temporary("cache", value="hash"): @@ -71,7 +71,7 @@ def _translate_gtir_to_sdfg( device_type=device_type, auto_optimize=auto_optimize, auto_optimize_args=None, - async_sdfg_call=async_sdfg_call, + sync_sdfg_call=sync_sdfg_call, unstructured_horizontal_has_unit_stride=False, use_metrics=use_metrics, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -106,7 +106,7 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): offset_provider=SKIP_VALUE_MESH.offset_provider, device_type=core_defs.DeviceType.CPU, auto_optimize=False, - async_sdfg_call=False, + sync_sdfg_call=True, ) constant_symbols = dace_wf_translation.find_constant_symbols( @@ -206,12 +206,12 @@ def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: @pytest.mark.parametrize( - "make_async_sdfg_call", + "make_sync_sdfg_call", [False, True], ) -def test_generate_sdfg_async_call(make_async_sdfg_call: bool, device_type: core_defs.DeviceType): - """Verify that the flag `async_sdfg_call` takes effect on the SDFG generation.""" - program_name = "field_ir_{}_async_call".format("with" if make_async_sdfg_call else "without") +def test_generate_sdfg_sync_call(make_sync_sdfg_call: bool, device_type: core_defs.DeviceType): + """Verify that the flag `sync_sdfg_call` takes effect on the SDFG generation.""" + program_name = "field_ir_{}_sync_call".format("with" if make_sync_sdfg_call else "without") ir = itir.Program( id=program_name, @@ -235,19 +235,19 @@ def test_generate_sdfg_async_call(make_async_sdfg_call: bool, device_type: core_ offset_provider={}, device_type=device_type, auto_optimize=False, - async_sdfg_call=make_async_sdfg_call, + sync_sdfg_call=make_sync_sdfg_call, ) if device_type == core_defs.DeviceType.CPU: _check_cpu_sdfg_call(sdfg) - elif make_async_sdfg_call: - _check_sdfg_with_async_call(sdfg) - else: + elif make_sync_sdfg_call: _check_sdfg_without_async_call(sdfg) + else: + _check_sdfg_with_async_call(sdfg) def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): - """Verify that the flag `async_sdfg_call=True` has no effect on an SDFG that does not contain any GPU map.""" + """Verify that the flag `sync_sdfg_call=False` has no effect on an SDFG that does not contain any GPU map.""" ir = itir.Program( id="scalar_ir_with_async_call", @@ -271,7 +271,7 @@ def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): offset_provider={}, device_type=device_type, auto_optimize=False, - async_sdfg_call=True, + sync_sdfg_call=False, ) if device_type == core_defs.DeviceType.CPU: @@ -394,7 +394,7 @@ def test_generate_sdfg_async_call_multi_state( # NOTE: Here we should use a configuration context. But because of # [DaCe issue#2125](https://github.com/spcl/dace/issues/2125) this is not possible. with dace_wf_common.dace_context(device_type=device_type): - dace_wf_translation.make_sdfg_call_async(sdfg, on_gpu) + dace_wf_translation.add_configurable_stream(sdfg, on_gpu) if on_gpu: assert _are_streams_set_to_default_stream(sdfg) @@ -485,7 +485,7 @@ def test_translation_source_code_invariant_under_guid_change(): device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args=None, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) From 89f7c521587e3dc062f0e353959f851c178cd287 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 22 Sep 2026 18:17:25 +0200 Subject: [PATCH 30/69] change configurable stream to compile time arg --- .../runners/dace/workflow/backend.py | 5 ++ .../runners/dace/workflow/common.py | 3 - .../runners/dace/workflow/decoration.py | 2 - .../runners/dace/workflow/translation.py | 37 ++++++------ .../dace_tests/test_dace_translation.py | 58 ++++++++++++++++++- 5 files changed, 79 insertions(+), 26 deletions(-) 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 ce0cc5fede..9908f1e9b6 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -78,6 +78,7 @@ def make_dace_backend( auto_optimize: bool = True, sync_sdfg_call: bool = False, optimization_args: dict[str, Any] | None = None, + external_gpu_stream: int | 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, @@ -98,6 +99,10 @@ def make_dace_backend( the GPU kernel execution to overlap with the Python driver code. optimization_args: A `dict` containing configuration parameters for the SDFG auto-optimize pipeline, see `gt_auto_optimize()`. + external_gpu_stream: An external GPU stream to be used for the SDFG call, + which allows to synchronize the execution of GPU kernels with external + workload and to share the stream memory pool. If not provided, the + default stream is used. 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 diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 5f8fc81613..1e9cbb65fd 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -33,9 +33,6 @@ SDFG_ARG_METRIC_COMPUTE_TIME_DTYPE: Final[dace.dtypes.typeclass] = dace.float64 """DaCe datatype of `SDFG_ARG_METRIC_COMPUTE_TIME` argument.""" -SDFG_ARG_EXTERNAL_GPU_STREAM: Final[str] = "gt_external_gpu_stream" -"""Name of SDFG argument to input an external GPU stream to GT4Py.""" - ExternalWorkspace: TypeAlias = dict[ core_defs.DeviceType, xtyping.ArrayInterface | xtyping.CUDAArrayInterface diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py index 6c17403ea6..57f45964ce 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py @@ -85,8 +85,6 @@ def __call__( gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL: metrics.get_current_level(), gtx_wfdcommon.SDFG_ARG_METRIC_COMPUTE_TIME: self._collect_time_arg, } - if gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM not in this_call_args: - this_call_args[gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM] = 0 self._fun.construct_arguments(**this_call_args) # Perform the call to the SDFG. 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 372aaf304e..67aaa7ddbd 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -237,8 +237,8 @@ def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: sdfg.validate() -def add_configurable_stream(sdfg: dace.SDFG, on_gpu: bool) -> None: - """Add a configurable stream to the SDFG. +def add_configurable_gpu_stream(sdfg: dace.SDFG, external_gpu_stream: int | None) -> None: + """Use an external GPU stream for the SDFG. This allows to set the stream used for all GPU work, which allows to synchronize the execution of GPU kernels with external workload and to share @@ -246,23 +246,18 @@ def add_configurable_stream(sdfg: dace.SDFG, on_gpu: bool) -> None: If the stream argument is not provided, the default stream is used. """ - if not on_gpu: - # This is only a problem on GPU. Dace uses OpenMP on CPU and - # the OpenMP parallel region creates a synchronization point. - return - - stream_arg, _ = sdfg.add_scalar(gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM, dace.int64) - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." - sdfg.append_init_code( - f"""\ -if ({stream_arg} == 0) {{ - __dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault); -}} else {{ - __dace_gpu_set_all_streams(__state, {stream_arg}); -}}""", - location="cuda", - ) + if external_gpu_stream is None: + dace_gpu_backend = dace.Config.get("compiler.cuda.backend") + assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." + sdfg.append_init_code( + f"__dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault);", + location="cuda", + ) + else: + sdfg.append_init_code( + f"__dace_gpu_set_all_streams(__state, {external_gpu_stream});", + location="cuda", + ) def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: @@ -346,6 +341,7 @@ class DaCeTranslator( auto_optimize: bool auto_optimize_args: dict[str, Any] | None sync_sdfg_call: bool + external_gpu_stream: int | None unstructured_horizontal_has_unit_stride: bool use_metrics: bool @@ -440,7 +436,8 @@ def _generate_sdfg_without_configuring_dace( if self.use_metrics: add_instrumentation(sdfg, on_gpu) - add_configurable_stream(sdfg, on_gpu) + if on_gpu: + add_configurable_gpu_stream(sdfg, self.external_gpu_stream) return sdfg 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 f36e7c71cd..24a390fbe3 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 @@ -63,6 +63,7 @@ def _translate_gtir_to_sdfg( device_type: core_defs.DeviceType, auto_optimize: bool, sync_sdfg_call: bool, + external_gpu_stream: int | None = None, use_metrics: bool = False, ) -> dace.SDFG: with dace.config.set_temporary("cache", value="hash"): @@ -72,6 +73,7 @@ def _translate_gtir_to_sdfg( auto_optimize=auto_optimize, auto_optimize_args=None, sync_sdfg_call=sync_sdfg_call, + external_gpu_stream=external_gpu_stream, unstructured_horizontal_has_unit_stride=False, use_metrics=use_metrics, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -145,6 +147,19 @@ def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: ) +def _are_streams_set_to_external_stream(sdfg: dace.SDFG, external_gpu_stream: int) -> bool: + if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. + return False + + return ( + re.match( + rf"__dace_gpu_set_all_streams\(__state\s*,\s*{external_gpu_stream}\);", + sdfg.init_code["cuda"].as_string, + ) + is not None + ) + + def _are_streams_synchronized(sdfg: dace.SDFG) -> bool: re_stream_sync = re.compile(r"\b(cuda|hip)StreamSynchronize\b") # The synchronization calls are in the CPU not the GPU code. @@ -280,6 +295,45 @@ def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): _check_sdfg_with_async_call(sdfg) +@pytest.mark.parametrize("external_gpu_stream", [None, 0x1234]) +def test_generate_sdfg_external_gpu_stream( + external_gpu_stream: int | None, device_type: core_defs.DeviceType +): + """Verify that `external_gpu_stream` selects the GPU stream used by the SDFG.""" + ir = itir.Program( + id="field_ir_external_gpu_stream", + declarations=[], + function_definitions=[], + params=[ + itir.Sym(id="x", type=IFTYPE), + itir.Sym(id="y", type=IFTYPE), + ], + body=[ + itir.SetAt( + expr=im.op_as_fieldop("plus")("x", 1.0), + domain=im.get_field_domain(gtx_common.GridType.CARTESIAN, "y", IFTYPE.dims), + target=itir.SymRef(id="y"), + ), + ], + ) + + sdfg = _translate_gtir_to_sdfg( + ir=ir, + offset_provider={}, + device_type=device_type, + auto_optimize=False, + sync_sdfg_call=False, + external_gpu_stream=external_gpu_stream, + ) + + if device_type == core_defs.DeviceType.CPU: + assert "cuda" not in sdfg.init_code + elif external_gpu_stream is None: + assert _are_streams_set_to_default_stream(sdfg) + else: + assert _are_streams_set_to_external_stream(sdfg, external_gpu_stream) + + def _make_multi_state_sdfg_0( sdfg_name: str = "async_call_multi_state_0", ) -> tuple[dace.SDFG, dace.SDFGState, dace.SDFGState]: @@ -394,7 +448,8 @@ def test_generate_sdfg_async_call_multi_state( # NOTE: Here we should use a configuration context. But because of # [DaCe issue#2125](https://github.com/spcl/dace/issues/2125) this is not possible. with dace_wf_common.dace_context(device_type=device_type): - dace_wf_translation.add_configurable_stream(sdfg, on_gpu) + if on_gpu: + dace_wf_translation.add_configurable_gpu_stream(sdfg, external_gpu_stream=None) if on_gpu: assert _are_streams_set_to_default_stream(sdfg) @@ -486,6 +541,7 @@ def test_translation_source_code_invariant_under_guid_change(): auto_optimize=False, auto_optimize_args=None, sync_sdfg_call=True, + external_gpu_stream=None, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) From 8eb52c2c4b83a3b21dec3cb9b2928cf0fb5b2a2e Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 24 Sep 2026 12:29:40 +0200 Subject: [PATCH 31/69] edit --- .../runners/dace/workflow/translation.py | 26 ++++---- .../dace_tests/test_dace_translation.py | 66 ++++++++----------- 2 files changed, 42 insertions(+), 50 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 67aaa7ddbd..9d630f4b5d 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -278,18 +278,10 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: # are not imported and the SDFG is compiled as plain C++. return - assert dace.Config.get("compiler.cuda.max_concurrent_streams") == -1, ( - f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." - ) - - # If we are using the default stream, things are a bit simpler/harder. For some - # reasons when using the default stream, DaCe seems to skip _all_ synchronization, - # for more see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). - # Thus the `CompiledSDFG.fast_call()` call is truly asynchronous, i.e. just - # launches the kernels and then exist. Thus we have to add a synchronization - # at the end to have a synchronous call. We can not use `SDFG.append_exit_code()` - # because that code is only run at the `exit()` stage, not after a call. Thus we - # will generate an SDFGState that contains a Tasklet with the sync call. + # We synchronize the GPU streams explicitly at the end of the SDFG. We cannot + # use `SDFG.append_exit_code()` because that code is only run at the `exit()` + # stage, not after a call. Thus we add an `SDFGState` at the end that contains + # a `Tasklet` with the call to GPU stream synchronization. sync_state = sdfg.add_state("sync_state") for sink_node in sdfg.sink_nodes(): if sink_node is sync_state: @@ -307,7 +299,7 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: dace_gpu_backend = dace.Config.get("compiler.cuda.backend") assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." sync_state.add_tasklet( - "sync_tlet", + "stream_synchronize", inputs={}, outputs={}, code=f"""\ @@ -432,6 +424,14 @@ def _generate_sdfg_without_configuring_dace( if self.sync_sdfg_call: make_sdfg_call_sync(sdfg, on_gpu) + else: + # When using the default stream, DaCe seems to skip _all_ synchronization, + # for more see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). + # Thus the `CompiledSDFG.fast_call()` call is truly asynchronous, i.e. + # just launches the kernels and exits. This is the default behavior in GT4Py. + assert dace.Config.get("compiler.cuda.max_concurrent_streams") == -1, ( + f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." + ) if self.use_metrics: add_instrumentation(sdfg, on_gpu) 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 24a390fbe3..25834c9590 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 @@ -47,11 +47,10 @@ @pytest.fixture( params=[ - pytest.param(core_defs.DeviceType.CPU), - pytest.param(core_defs.DeviceType.CUDA, marks=[pytest.mark.requires_gpu]), - pytest.param(core_defs.DeviceType.ROCM, marks=[pytest.mark.requires_gpu]), - ], - ids=["CPU", "CUDA", "ROCM"], + pytest.param(core_defs.DeviceType.CPU, id="CPU"), + pytest.param(core_defs.DeviceType.CUDA, id="CUDA"), + pytest.param(core_defs.DeviceType.ROCM, id="ROCM"), + ] ) def device_type(request) -> str: return request.param @@ -188,7 +187,7 @@ def _check_sdfg_with_async_call(sdfg: dace.SDFG) -> None: assert _are_streams_set_to_default_stream(sdfg) -def _check_sdfg_without_async_call(sdfg: dace.SDFG) -> None: +def _check_sdfg_with_sync_call(sdfg: dace.SDFG) -> None: states = list(sdfg.states()) sink_states = sdfg.sink_nodes() @@ -220,13 +219,10 @@ def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: assert not _are_streams_synchronized(sdfg) -@pytest.mark.parametrize( - "make_sync_sdfg_call", - [False, True], -) -def test_generate_sdfg_sync_call(make_sync_sdfg_call: bool, device_type: core_defs.DeviceType): +@pytest.mark.parametrize("sync_call", [False, True]) +def test_generate_sdfg_sync_call(sync_call: bool, device_type: core_defs.DeviceType): """Verify that the flag `sync_sdfg_call` takes effect on the SDFG generation.""" - program_name = "field_ir_{}_sync_call".format("with" if make_sync_sdfg_call else "without") + program_name = "field_ir_{}_sync_call".format("with" if sync_call else "without") ir = itir.Program( id=program_name, @@ -250,13 +246,13 @@ def test_generate_sdfg_sync_call(make_sync_sdfg_call: bool, device_type: core_de offset_provider={}, device_type=device_type, auto_optimize=False, - sync_sdfg_call=make_sync_sdfg_call, + sync_sdfg_call=sync_call, ) if device_type == core_defs.DeviceType.CPU: _check_cpu_sdfg_call(sdfg) - elif make_sync_sdfg_call: - _check_sdfg_without_async_call(sdfg) + elif sync_call: + _check_sdfg_with_sync_call(sdfg) else: _check_sdfg_with_async_call(sdfg) @@ -428,10 +424,10 @@ def _make_multi_state_sdfg_3( @pytest.mark.parametrize( "multi_state_config", [ - (True, _make_multi_state_sdfg_0), - (False, _make_multi_state_sdfg_1), - (False, _make_multi_state_sdfg_2), - (False, _make_multi_state_sdfg_3), + (False, _make_multi_state_sdfg_0), + (True, _make_multi_state_sdfg_1), + (True, _make_multi_state_sdfg_2), + (True, _make_multi_state_sdfg_3), ], ) def test_generate_sdfg_async_call_multi_state( @@ -441,18 +437,16 @@ def test_generate_sdfg_async_call_multi_state( Verify that states are not made async when a data descriptor is accessed on an outgoing InterState edge. """ - on_gpu = device_type == core_defs.CUPY_DEVICE_TYPE - expect_async_sdfg_call_on_first_state, make_multi_state_sdfg = multi_state_config + if device_type == core_defs.DeviceType.CPU: + pytest.skip("This test is only relevant for GPU execution.") + + expect_sync_after_first_map, make_multi_state_sdfg = multi_state_config sdfg, first_state, second_state = make_multi_state_sdfg() # NOTE: Here we should use a configuration context. But because of # [DaCe issue#2125](https://github.com/spcl/dace/issues/2125) this is not possible. with dace_wf_common.dace_context(device_type=device_type): - if on_gpu: - dace_wf_translation.add_configurable_gpu_stream(sdfg, external_gpu_stream=None) - - if on_gpu: - assert _are_streams_set_to_default_stream(sdfg) + dace_wf_translation.add_configurable_gpu_stream(sdfg, external_gpu_stream=None) # No synchronization state is added. assert sdfg.number_of_nodes() == 2 @@ -463,17 +457,15 @@ def test_generate_sdfg_async_call_multi_state( assert first_state.nosync == False assert second_state.nosync == False - if device_type == core_defs.DeviceType.CPU: - _check_cpu_sdfg_call(sdfg) - elif expect_async_sdfg_call_on_first_state: - # NOTE: This test is plain wrong! Because there is a dependency between the first and the - # second state. This is because the Map in the first state computes something that is - # used on the Interstate edge. Thus there should be a sync at the end of the first - # state. But as the test bellow shows, there is no sync in the enter CPU code (syncs - # are never inside the GPU code). This is plain wrong, but we should not be affected - # by this. See https://github.com/spcl/dace/issues/2120 for more. - # In the case of `_make_multi_state_sdfg_3()` there would be a sync after the Map, before - # the Tasklet, if the default stream was not used! + if expect_sync_after_first_map: + # NOTE: This test is plain wrong, because there is a dependency between + # the first and the second state: the `Map` in the first state computes + # a value that is used either on the InterState edge or inside the second + # state. Thus, there should be a synchronization point at the end of the + # first state. On the contrary, as the test below shows, there is no sync + # in the generated code. This is plain wrong, but it works as long as + # all `Map`s are scheduled on the same GPU stream. + # See https://github.com/spcl/dace/issues/2120 for more information. assert not _are_streams_synchronized(sdfg) else: # There is no dependency between the states, so no sync. From e49f24191813222d7bb41c24876bf47c6a6bb4e2 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 24 Sep 2026 12:33:08 +0200 Subject: [PATCH 32/69] edit --- .../runners_tests/dace_tests/test_dace_translation.py | 1 + 1 file changed, 1 insertion(+) 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 25834c9590..f52cc59042 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 @@ -466,6 +466,7 @@ def test_generate_sdfg_async_call_multi_state( # in the generated code. This is plain wrong, but it works as long as # all `Map`s are scheduled on the same GPU stream. # See https://github.com/spcl/dace/issues/2120 for more information. + assert _are_streams_set_to_default_stream(sdfg) assert not _are_streams_synchronized(sdfg) else: # There is no dependency between the states, so no sync. From 6939d037ef953041d48a978faf55673906ef9f89 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 24 Sep 2026 13:50:41 +0200 Subject: [PATCH 33/69] fix test --- .../runners_tests/dace_tests/test_dace_translation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f52cc59042..b8d4c92de8 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 @@ -203,7 +203,7 @@ def _check_sdfg_with_sync_call(sdfg: dace.SDFG) -> None: sync_tlet = next(iter(sync_state.nodes())) assert isinstance(sync_tlet, dace_nodes.Tasklet) assert sync_tlet.side_effects - assert sync_tlet.label == "sync_tlet" + assert sync_tlet.label == "stream_synchronize" assert re.match(r"(cuda|hip)StreamSynchronize\(\1StreamDefault\)", sync_tlet.code.as_string) assert _are_streams_set_to_default_stream(sdfg) From 38b42683689e3f8b3b819b3c93fae6012c6bcd61 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 24 Sep 2026 14:50:18 +0200 Subject: [PATCH 34/69] fix test --- .../dace_tests/test_dace_translation.py | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 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 b8d4c92de8..3d668caf72 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 @@ -133,13 +133,15 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): assert constant_symbols == expected -def _are_streams_set_to_default_stream(sdfg: dace.SDFG) -> bool: +def _are_streams_set_to_default_stream(sdfg: dace.SDFG, device: core_defs.DeviceType) -> bool: if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. return False + platform = "cuda" if device == core_defs.DeviceType.CUDA else "hip" + return ( re.match( - r"__dace_gpu_set_all_streams\(__state\s*,\s*(cuda|hip)StreamDefault\);", + rf"__dace_gpu_set_all_streams\(__state\s*,\s*{platform}StreamDefault\);", sdfg.init_code["cuda"].as_string, ) is not None @@ -184,10 +186,9 @@ def _check_sdfg_with_async_call(sdfg: dace.SDFG) -> None: if isinstance(state, dace.SDFGState) ) assert not _are_streams_synchronized(sdfg) - assert _are_streams_set_to_default_stream(sdfg) -def _check_sdfg_with_sync_call(sdfg: dace.SDFG) -> None: +def _check_sdfg_with_sync_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> None: states = list(sdfg.states()) sink_states = sdfg.sink_nodes() @@ -205,8 +206,15 @@ def _check_sdfg_with_sync_call(sdfg: dace.SDFG) -> None: assert sync_tlet.side_effects assert sync_tlet.label == "stream_synchronize" - assert re.match(r"(cuda|hip)StreamSynchronize\(\1StreamDefault\)", sync_tlet.code.as_string) - assert _are_streams_set_to_default_stream(sdfg) + platform = "cuda" if device == core_defs.DeviceType.CUDA else "hip" + assert ( + sync_tlet.code.as_string + == f"""\ +for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {{ + {platform}StreamSynchronize(__state->gpu_context->streams[__i]); +}}""" + ) + assert _are_streams_set_to_default_stream(sdfg, device) def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: @@ -252,7 +260,7 @@ def test_generate_sdfg_sync_call(sync_call: bool, device_type: core_defs.DeviceT if device_type == core_defs.DeviceType.CPU: _check_cpu_sdfg_call(sdfg) elif sync_call: - _check_sdfg_with_sync_call(sdfg) + _check_sdfg_with_sync_call(sdfg, device_type) else: _check_sdfg_with_async_call(sdfg) @@ -296,6 +304,9 @@ def test_generate_sdfg_external_gpu_stream( external_gpu_stream: int | None, device_type: core_defs.DeviceType ): """Verify that `external_gpu_stream` selects the GPU stream used by the SDFG.""" + if device_type == core_defs.DeviceType.CPU: + pytest.skip("This test is only relevant for GPU execution.") + ir = itir.Program( id="field_ir_external_gpu_stream", declarations=[], @@ -321,11 +332,12 @@ def test_generate_sdfg_external_gpu_stream( sync_sdfg_call=False, external_gpu_stream=external_gpu_stream, ) + _check_sdfg_with_async_call(sdfg) if device_type == core_defs.DeviceType.CPU: assert "cuda" not in sdfg.init_code elif external_gpu_stream is None: - assert _are_streams_set_to_default_stream(sdfg) + assert _are_streams_set_to_default_stream(sdfg, device_type) else: assert _are_streams_set_to_external_stream(sdfg, external_gpu_stream) @@ -466,7 +478,7 @@ def test_generate_sdfg_async_call_multi_state( # in the generated code. This is plain wrong, but it works as long as # all `Map`s are scheduled on the same GPU stream. # See https://github.com/spcl/dace/issues/2120 for more information. - assert _are_streams_set_to_default_stream(sdfg) + assert _are_streams_set_to_default_stream(sdfg, device_type) assert not _are_streams_synchronized(sdfg) else: # There is no dependency between the states, so no sync. From 37988cedbde1beb2566661a0d46c68a659bb73d5 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 28 Sep 2026 12:25:58 +0200 Subject: [PATCH 35/69] cast external stream --- .../program_processors/runners/dace/workflow/translation.py | 2 +- .../runners_tests/dace_tests/test_dace_translation.py | 2 +- 2 files changed, 2 insertions(+), 2 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 9d630f4b5d..a2f7752ca0 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -255,7 +255,7 @@ def add_configurable_gpu_stream(sdfg: dace.SDFG, external_gpu_stream: int | None ) else: sdfg.append_init_code( - f"__dace_gpu_set_all_streams(__state, {external_gpu_stream});", + f"__dace_gpu_set_all_streams(__state, reinterpret_cast({external_gpu_stream}));", location="cuda", ) 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 3d668caf72..120297dce8 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 @@ -154,7 +154,7 @@ def _are_streams_set_to_external_stream(sdfg: dace.SDFG, external_gpu_stream: in return ( re.match( - rf"__dace_gpu_set_all_streams\(__state\s*,\s*{external_gpu_stream}\);", + rf"__dace_gpu_set_all_streams\(__state\s*,\s*reinterpret_cast\({external_gpu_stream}\)\);", sdfg.init_code["cuda"].as_string, ) is not None From ebd3915f8e04a8de38044ba4b1b30344c8140725 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 28 Sep 2026 13:38:26 +0200 Subject: [PATCH 36/69] switch to new dace gpu codegen --- pyproject.toml | 2 +- .../runners/dace/workflow/common.py | 12 ++ .../runners/dace/workflow/translation.py | 19 ++-- .../dace_tests/test_dace_translation.py | 105 +++++++++++++----- uv.lock | 4 +- 5 files changed, 104 insertions(+), 38 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index a37ef2592c..132f64709c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -434,7 +434,7 @@ url = 'https://gridtools.github.io/pypi/' # dace = {index = "gridtools"} [tool.uv.sources] atlas4py = { index = "test.pypi" } -dace = { git = "https://github.com/spcl/dace.git", branch = "main" } +dace = { git = "https://github.com/spcl/dace", branch = "new-gpu-codegen-dev" } # -- versioningit -- [tool.versioningit] diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 1e9cbb65fd..dd4fe9564a 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -146,6 +146,18 @@ def set_dace_config( # [DaCe issue#2120](https://github.com/spcl/dace/issues/2120) for more. dace.Config.set("compiler.cuda.max_concurrent_streams", value=-1) + # Use the experimental CUDA codegen: unlike the legacy one, it launches kernels + # and copies on the streams stored in `__state->gpu_context->streams`, even + # when `max_concurrent_streams` is `-1`. This allows to replace the default + # stream with an external stream, see `add_configurable_gpu_stream()`. + dace.Config.set("compiler.cuda.implementation", value="experimental") + + # The experimental CUDA codegen synchronizes the GPU streams at the end of + # the SDFG by default, which makes the SDFG call synchronous. We disable it + # because, when a synchronous call is requested, gt4py adds the stream + # synchronization itself, see `make_sdfg_call_sync()`. + dace.Config.set("compiler.cuda.synchronize_on_exit", value=False) + # This assumes that a process will only use one type of GPU. if device_type == core_defs.DeviceType.ROCM: dace.Config.set("compiler.cuda.backend", value="hip") 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 a2f7752ca0..a5af8ccf17 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -249,15 +249,18 @@ def add_configurable_gpu_stream(sdfg: dace.SDFG, external_gpu_stream: int | None if external_gpu_stream is None: dace_gpu_backend = dace.Config.get("compiler.cuda.backend") assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." - sdfg.append_init_code( - f"__dace_gpu_set_all_streams(__state, {dace_gpu_backend}StreamDefault);", - location="cuda", - ) + gpu_stream = f"{dace_gpu_backend}StreamDefault" else: - sdfg.append_init_code( - f"__dace_gpu_set_all_streams(__state, reinterpret_cast({external_gpu_stream}));", - location="cuda", - ) + gpu_stream = f"reinterpret_cast({external_gpu_stream})" + + # NOTE: The experimental DaCe CUDA codegen does not provide the helper function + # `__dace_gpu_set_all_streams()`, therefore we write the stream array directly. + sdfg.append_init_code( + "for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {\n" + f" __state->gpu_context->streams[__i] = {gpu_stream};\n" + "}\n", + location="cuda", + ) def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: 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 120297dce8..fff844c1b8 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 @@ -140,8 +140,8 @@ def _are_streams_set_to_default_stream(sdfg: dace.SDFG, device: core_defs.Device platform = "cuda" if device == core_defs.DeviceType.CUDA else "hip" return ( - re.match( - rf"__dace_gpu_set_all_streams\(__state\s*,\s*{platform}StreamDefault\);", + re.search( + rf"__state->gpu_context->streams\[__i\]\s*=\s*{platform}StreamDefault;", sdfg.init_code["cuda"].as_string, ) is not None @@ -153,25 +153,28 @@ def _are_streams_set_to_external_stream(sdfg: dace.SDFG, external_gpu_stream: in return False return ( - re.match( - rf"__dace_gpu_set_all_streams\(__state\s*,\s*reinterpret_cast\({external_gpu_stream}\)\);", + re.search( + rf"__state->gpu_context->streams\[__i\]\s*=\s*reinterpret_cast\({external_gpu_stream}\);", sdfg.init_code["cuda"].as_string, ) is not None ) -def _are_streams_synchronized(sdfg: dace.SDFG) -> bool: +def _are_streams_synchronized(sdfg: dace.SDFG, device: core_defs.DeviceType) -> bool: re_stream_sync = re.compile(r"\b(cuda|hip)StreamSynchronize\b") + # The code is generated with the DaCe configuration used by GT4Py. + with dace_wf_common.dace_context(device_type=device): + code_objects = sdfg.generate_code() # The synchronization calls are in the CPU not the GPU code. return any( - re_stream_sync.match(code.clean_code) - for code in sdfg.generate_code() + re_stream_sync.search(code.clean_code) is not None + for code in code_objects if code.language == "cpp" ) -def _check_sdfg_with_async_call(sdfg: dace.SDFG) -> None: +def _check_sdfg_with_async_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> None: # Because we are using the default stream, the launch is asynchronous. Thus we # have to check if there is no synchronization state. However, we will do a # stronger test. Instead we will make sure that there are no synchronization @@ -185,7 +188,7 @@ def _check_sdfg_with_async_call(sdfg: dace.SDFG) -> None: for state in sdfg.sink_nodes() if isinstance(state, dace.SDFGState) ) - assert not _are_streams_synchronized(sdfg) + assert not _are_streams_synchronized(sdfg, device) def _check_sdfg_with_sync_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> None: @@ -224,7 +227,7 @@ def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: for state in sdfg.sink_nodes() if isinstance(state, dace.SDFGState) ) - assert not _are_streams_synchronized(sdfg) + assert not _are_streams_synchronized(sdfg, core_defs.DeviceType.CPU) @pytest.mark.parametrize("sync_call", [False, True]) @@ -262,7 +265,7 @@ def test_generate_sdfg_sync_call(sync_call: bool, device_type: core_defs.DeviceT elif sync_call: _check_sdfg_with_sync_call(sdfg, device_type) else: - _check_sdfg_with_async_call(sdfg) + _check_sdfg_with_async_call(sdfg, device_type) def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): @@ -296,19 +299,57 @@ def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): if device_type == core_defs.DeviceType.CPU: _check_cpu_sdfg_call(sdfg) else: - _check_sdfg_with_async_call(sdfg) + _check_sdfg_with_async_call(sdfg, device_type) +def _are_gpu_operations_on_sdfg_streams( + sdfg: dace.SDFG, device: core_defs.DeviceType, gpu_operation: str +) -> bool: + """Check that the GPU operations are scheduled on the streams of the SDFG state. + + The code is generated with the DaCe configuration used by GT4Py, and the check + ensures that kernel launches and copies read their GPU stream from the array + `__state->gpu_context->streams`, which is the one set by the init code, instead + of using the default stream (`nullptr`). + """ + platform = "cuda" if device == core_defs.DeviceType.CUDA else "hip" + re_gpu_operation = { + "kernel": re.compile(r"\b__dace_runkernel_\w+\(__state\b.*,\s*(\w+)\);"), + "copy": re.compile(rf"\b{platform}Memcpy\w*Async\(.*,\s*(\w+)\);"), + }[gpu_operation] + + with dace_wf_common.dace_context(device_type=device): + # The GPU operations are launched from the CPU code. + code = "\n".join( + code_object.clean_code + for code_object in sdfg.generate_code() + if code_object.language == "cpp" + ) + + if ( + re.search(r"\bgpuStream_t\s*\*\s*gpu_streams\s*=\s*__state->gpu_context->streams;", code) + is None + ): + return False + + gpu_streams = re_gpu_operation.findall(code) + return len(gpu_streams) > 0 and all( + re.search(rf"\bgpuStream_t\s+{stream}\s*=\s*gpu_streams\[\d+\];", code) is not None + for stream in gpu_streams + ) + + +@pytest.mark.parametrize("gpu_operation", ["kernel", "copy"]) @pytest.mark.parametrize("external_gpu_stream", [None, 0x1234]) def test_generate_sdfg_external_gpu_stream( - external_gpu_stream: int | None, device_type: core_defs.DeviceType + external_gpu_stream: int | None, gpu_operation: str, device_type: core_defs.DeviceType ): """Verify that `external_gpu_stream` selects the GPU stream used by the SDFG.""" if device_type == core_defs.DeviceType.CPU: pytest.skip("This test is only relevant for GPU execution.") ir = itir.Program( - id="field_ir_external_gpu_stream", + id=f"field_ir_external_gpu_stream_{gpu_operation}", declarations=[], function_definitions=[], params=[ @@ -317,7 +358,11 @@ def test_generate_sdfg_external_gpu_stream( ], body=[ itir.SetAt( - expr=im.op_as_fieldop("plus")("x", 1.0), + # A field operator is lowered to a GPU kernel, while a plain field + # assignment is lowered to a GPU copy. + expr=im.op_as_fieldop("plus")("x", 1.0) + if gpu_operation == "kernel" + else itir.SymRef(id="x"), domain=im.get_field_domain(gtx_common.GridType.CARTESIAN, "y", IFTYPE.dims), target=itir.SymRef(id="y"), ), @@ -332,7 +377,7 @@ def test_generate_sdfg_external_gpu_stream( sync_sdfg_call=False, external_gpu_stream=external_gpu_stream, ) - _check_sdfg_with_async_call(sdfg) + _check_sdfg_with_async_call(sdfg, device_type) if device_type == core_defs.DeviceType.CPU: assert "cuda" not in sdfg.init_code @@ -341,6 +386,8 @@ def test_generate_sdfg_external_gpu_stream( else: assert _are_streams_set_to_external_stream(sdfg, external_gpu_stream) + assert _are_gpu_operations_on_sdfg_streams(sdfg, device_type, gpu_operation) + def _make_multi_state_sdfg_0( sdfg_name: str = "async_call_multi_state_0", @@ -438,7 +485,14 @@ def _make_multi_state_sdfg_3( [ (False, _make_multi_state_sdfg_0), (True, _make_multi_state_sdfg_1), - (True, _make_multi_state_sdfg_2), + pytest.param( + (True, _make_multi_state_sdfg_2), + marks=pytest.mark.xfail( + reason="DaCe does not synchronize the GPU stream before reading the result " + "of a device-to-host copy in the condition of an InterState edge.", + strict=True, + ), + ), (True, _make_multi_state_sdfg_3), ], ) @@ -470,19 +524,16 @@ def test_generate_sdfg_async_call_multi_state( assert second_state.nosync == False if expect_sync_after_first_map: - # NOTE: This test is plain wrong, because there is a dependency between - # the first and the second state: the `Map` in the first state computes - # a value that is used either on the InterState edge or inside the second - # state. Thus, there should be a synchronization point at the end of the - # first state. On the contrary, as the test below shows, there is no sync - # in the generated code. This is plain wrong, but it works as long as - # all `Map`s are scheduled on the same GPU stream. - # See https://github.com/spcl/dace/issues/2120 for more information. + # There is a dependency between the first and the second state: the `Map` + # in the first state computes a value that is copied to host memory and + # used either on the InterState edge or inside the first state. Thus, the + # GPU stream has to be synchronized after the device-to-host copy. + # See https://github.com/spcl/dace/issues/2120 for more information. assert _are_streams_set_to_default_stream(sdfg, device_type) - assert not _are_streams_synchronized(sdfg) + assert _are_streams_synchronized(sdfg, device_type) else: # There is no dependency between the states, so no sync. - assert not _are_streams_synchronized(sdfg) + assert not _are_streams_synchronized(sdfg, device_type) def _make_simple_field_operator_compilable_program() -> otf_workflow.ConcreteArtifact: diff --git a/uv.lock b/uv.lock index 988b40dbf8..248daf9f24 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=main#6cdee42594c9f82f1b6768a97fe6076db5bfe6cb" } +source = { git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev#afbf399b5f6c1de2be52c2a28e7428acad740164" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/spcl/dace.git?branch=main" }, + { name = "dace", git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 8d2c4a31dc14865e4dca5e85166434c37c4c305e Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 28 Sep 2026 13:54:02 +0200 Subject: [PATCH 37/69] edit --- .../runners/dace/workflow/common.py | 2 +- .../runners/dace/workflow/translation.py | 89 ++++++++++++------- .../dace_tests/test_dace_translation.py | 55 +++++------- 3 files changed, 81 insertions(+), 65 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index dd4fe9564a..842606cdfd 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -149,7 +149,7 @@ def set_dace_config( # Use the experimental CUDA codegen: unlike the legacy one, it launches kernels # and copies on the streams stored in `__state->gpu_context->streams`, even # when `max_concurrent_streams` is `-1`. This allows to replace the default - # stream with an external stream, see `add_configurable_gpu_stream()`. + # stream with an external stream, see `set_sdfg_gpu_stream()`. dace.Config.set("compiler.cuda.implementation", value="experimental") # The experimental CUDA codegen synchronizes the GPU streams at the end of 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 a5af8ccf17..bf9a604f8f 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -121,6 +121,29 @@ def _make_if_region_for_metrics_collection( return if_region, then_state +def _get_gpu_backend() -> str: + """Return the GPU backend, either 'cuda' or 'hip', configured in DaCe.""" + dace_gpu_backend = dace.Config.get("compiler.cuda.backend") + assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." + return dace_gpu_backend + + +def _for_each_sdfg_gpu_stream(statement: str) -> str: + """Return C++ code that applies `statement` to every GPU stream of the SDFG. + + Args: + statement: C++ statement, which refers to the current GPU stream as `__stream`. + + Returns: + A C++ loop over the streams in `__state->gpu_context->streams`. + """ + return f"""\ +for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {{ + gpuStream_t& __stream = __state->gpu_context->streams[__i]; + {statement} +}}""" + + def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: """ Instrument SDFG with measurement of total execution time. @@ -138,18 +161,18 @@ def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL, gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL_DTYPE ) - #### 1. Synchronize the CUDA device, in order to wait for kernels completion. + #### 1. Synchronize the SDFG GPU streams, in order to wait for kernels completion. + # We synchronize only the streams used by the SDFG, not the entire device, so + # that the measurement does not wait for unrelated work on other streams, e.g. + # external workload when the SDFG runs on an external GPU stream. # Even when the target device is GPU, it can happen that dace emits code without # GPU kernels. In this case, the cuda headers are not imported and the SDFG is # compiled as plain C++. Therefore, we also check here the schedule of SDFG maps. if gpu and _has_gpu_schedule(sdfg): - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." - - # NOTE: We should actually wrap the `DeviceSynchronize` function inside a + # NOTE: We should actually wrap the `StreamSynchronize` function inside a # `DACE_GPU_CHECK()` macro. However, this only works in GPU context, but # here we are in CPU context. Thus we cannot do it. - sync_code = f"{dace_gpu_backend}DeviceSynchronize();" + sync_code = _for_each_sdfg_gpu_stream(f"{_get_gpu_backend()}StreamSynchronize(__stream);") has_side_effects = True else: @@ -237,28 +260,28 @@ def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: sdfg.validate() -def add_configurable_gpu_stream(sdfg: dace.SDFG, external_gpu_stream: int | None) -> None: - """Use an external GPU stream for the SDFG. +def set_sdfg_gpu_stream(sdfg: dace.SDFG, external_gpu_stream: int | None) -> None: + """Set the GPU stream used for all GPU work of the SDFG. - This allows to set the stream used for all GPU work, which allows to - synchronize the execution of GPU kernels with external workload and to share - the stream memory pool. + Running the SDFG on an external GPU stream allows to synchronize the execution + of GPU kernels with external workload and to share the stream memory pool. + The stream is written into the SDFG init code, thus it is fixed at compile time. - If the stream argument is not provided, the default stream is used. + Args: + sdfg: The SDFG to process, modified in place. + external_gpu_stream: The handle of the external GPU stream, as an integer + value. If `None`, the default stream is used. """ - if external_gpu_stream is None: - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." - gpu_stream = f"{dace_gpu_backend}StreamDefault" - else: - gpu_stream = f"reinterpret_cast({external_gpu_stream})" + gpu_stream = ( + "nullptr" # The default stream. + if external_gpu_stream is None + else f"reinterpret_cast({external_gpu_stream})" + ) # NOTE: The experimental DaCe CUDA codegen does not provide the helper function # `__dace_gpu_set_all_streams()`, therefore we write the stream array directly. sdfg.append_init_code( - "for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {\n" - f" __state->gpu_context->streams[__i] = {gpu_stream};\n" - "}\n", + _for_each_sdfg_gpu_stream(f"__stream = {gpu_stream};") + "\n", location="cuda", ) @@ -299,16 +322,11 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: # NOTE: We should actually wrap the `StreamSynchronize` function inside a # `DACE_GPU_CHECK()` macro. However, this only works in GPU context, but # here we are in CPU context. Thus we can not do it. - dace_gpu_backend = dace.Config.get("compiler.cuda.backend") - assert dace_gpu_backend in ["cuda", "hip"], f"GPU backend '{dace_gpu_backend}' is unknown." sync_state.add_tasklet( "stream_synchronize", inputs={}, outputs={}, - code=f"""\ -for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {{ - {dace_gpu_backend}StreamSynchronize(__state->gpu_context->streams[__i]); -}}""", + code=_for_each_sdfg_gpu_stream(f"{_get_gpu_backend()}StreamSynchronize(__stream);"), language=dace.dtypes.Language.CPP, side_effects=True, ) @@ -427,20 +445,25 @@ def _generate_sdfg_without_configuring_dace( if self.sync_sdfg_call: make_sdfg_call_sync(sdfg, on_gpu) - else: - # When using the default stream, DaCe seems to skip _all_ synchronization, - # for more see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). - # Thus the `CompiledSDFG.fast_call()` call is truly asynchronous, i.e. - # just launches the kernels and exits. This is the default behavior in GT4Py. + elif on_gpu: + # All GPU work is scheduled on a single stream and, since we disable the + # synchronization of the GPU stream at the SDFG exit, the call to + # `CompiledSDFG.fast_call()` is asynchronous, i.e. it just launches the + # kernels and exits. This is the default behavior in GT4Py. Note that DaCe + # still synchronizes the stream before the host reads data computed on GPU, + # see [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). assert dace.Config.get("compiler.cuda.max_concurrent_streams") == -1, ( f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." ) + assert dace.Config.get("compiler.cuda.synchronize_on_exit") is False, ( + "Expected `synchronize_on_exit == False` but it was `True`." + ) if self.use_metrics: add_instrumentation(sdfg, on_gpu) if on_gpu: - add_configurable_gpu_stream(sdfg, self.external_gpu_stream) + set_sdfg_gpu_stream(sdfg, self.external_gpu_stream) return sdfg 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 fff844c1b8..dbf8c20c9c 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 @@ -13,7 +13,7 @@ import re import uuid -from typing import Callable +from typing import Callable, Literal from unittest import mock from gt4py._core import definitions as core_defs @@ -133,28 +133,26 @@ def test_find_constant_symbols(has_unit_stride, disable_field_origin): assert constant_symbols == expected -def _are_streams_set_to_default_stream(sdfg: dace.SDFG, device: core_defs.DeviceType) -> bool: - if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. - return False +def _gpu_platform(device: core_defs.DeviceType) -> str: + return "cuda" if device == core_defs.DeviceType.CUDA else "hip" - platform = "cuda" if device == core_defs.DeviceType.CUDA else "hip" - - return ( - re.search( - rf"__state->gpu_context->streams\[__i\]\s*=\s*{platform}StreamDefault;", - sdfg.init_code["cuda"].as_string, - ) - is not None - ) +def _are_streams_set_to(sdfg: dace.SDFG, external_gpu_stream: int | None) -> bool: + """Check that the SDFG init code sets all GPU streams to the given stream. -def _are_streams_set_to_external_stream(sdfg: dace.SDFG, external_gpu_stream: int) -> bool: + If `external_gpu_stream` is `None`, the streams should be set to the default stream. + """ if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. return False + gpu_stream = ( + "nullptr" + if external_gpu_stream is None + else rf"reinterpret_cast\({external_gpu_stream}\)" + ) return ( re.search( - rf"__state->gpu_context->streams\[__i\]\s*=\s*reinterpret_cast\({external_gpu_stream}\);", + rf"\b__stream\s*=\s*{gpu_stream};", sdfg.init_code["cuda"].as_string, ) is not None @@ -209,15 +207,15 @@ def _check_sdfg_with_sync_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> assert sync_tlet.side_effects assert sync_tlet.label == "stream_synchronize" - platform = "cuda" if device == core_defs.DeviceType.CUDA else "hip" assert ( sync_tlet.code.as_string == f"""\ for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {{ - {platform}StreamSynchronize(__state->gpu_context->streams[__i]); + gpuStream_t& __stream = __state->gpu_context->streams[__i]; + {_gpu_platform(device)}StreamSynchronize(__stream); }}""" ) - assert _are_streams_set_to_default_stream(sdfg, device) + assert _are_streams_set_to(sdfg, None) def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: @@ -303,7 +301,7 @@ def test_generate_sdfg_async_call_no_map(device_type: core_defs.DeviceType): def _are_gpu_operations_on_sdfg_streams( - sdfg: dace.SDFG, device: core_defs.DeviceType, gpu_operation: str + sdfg: dace.SDFG, device: core_defs.DeviceType, gpu_operation: Literal["kernel", "copy"] ) -> bool: """Check that the GPU operations are scheduled on the streams of the SDFG state. @@ -312,7 +310,7 @@ def _are_gpu_operations_on_sdfg_streams( `__state->gpu_context->streams`, which is the one set by the init code, instead of using the default stream (`nullptr`). """ - platform = "cuda" if device == core_defs.DeviceType.CUDA else "hip" + platform = _gpu_platform(device) re_gpu_operation = { "kernel": re.compile(r"\b__dace_runkernel_\w+\(__state\b.*,\s*(\w+)\);"), "copy": re.compile(rf"\b{platform}Memcpy\w*Async\(.*,\s*(\w+)\);"), @@ -342,7 +340,9 @@ def _are_gpu_operations_on_sdfg_streams( @pytest.mark.parametrize("gpu_operation", ["kernel", "copy"]) @pytest.mark.parametrize("external_gpu_stream", [None, 0x1234]) def test_generate_sdfg_external_gpu_stream( - external_gpu_stream: int | None, gpu_operation: str, device_type: core_defs.DeviceType + external_gpu_stream: int | None, + gpu_operation: Literal["kernel", "copy"], + device_type: core_defs.DeviceType, ): """Verify that `external_gpu_stream` selects the GPU stream used by the SDFG.""" if device_type == core_defs.DeviceType.CPU: @@ -378,14 +378,7 @@ def test_generate_sdfg_external_gpu_stream( external_gpu_stream=external_gpu_stream, ) _check_sdfg_with_async_call(sdfg, device_type) - - if device_type == core_defs.DeviceType.CPU: - assert "cuda" not in sdfg.init_code - elif external_gpu_stream is None: - assert _are_streams_set_to_default_stream(sdfg, device_type) - else: - assert _are_streams_set_to_external_stream(sdfg, external_gpu_stream) - + assert _are_streams_set_to(sdfg, external_gpu_stream) assert _are_gpu_operations_on_sdfg_streams(sdfg, device_type, gpu_operation) @@ -512,7 +505,7 @@ def test_generate_sdfg_async_call_multi_state( # NOTE: Here we should use a configuration context. But because of # [DaCe issue#2125](https://github.com/spcl/dace/issues/2125) this is not possible. with dace_wf_common.dace_context(device_type=device_type): - dace_wf_translation.add_configurable_gpu_stream(sdfg, external_gpu_stream=None) + dace_wf_translation.set_sdfg_gpu_stream(sdfg, external_gpu_stream=None) # No synchronization state is added. assert sdfg.number_of_nodes() == 2 @@ -529,7 +522,7 @@ def test_generate_sdfg_async_call_multi_state( # used either on the InterState edge or inside the first state. Thus, the # GPU stream has to be synchronized after the device-to-host copy. # See https://github.com/spcl/dace/issues/2120 for more information. - assert _are_streams_set_to_default_stream(sdfg, device_type) + assert _are_streams_set_to(sdfg, None) assert _are_streams_synchronized(sdfg, device_type) else: # There is no dependency between the states, so no sync. From 3b1aab3b9e2d8813ead2ca40653a9bfc4d3bf6cc Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 28 Sep 2026 15:01:54 +0200 Subject: [PATCH 38/69] switch to dace fork --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 248daf9f24..05c206988d 100644 --- a/uv.lock +++ b/uv.lock @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev" }, + { name = "dace", git = "https://github.com/edopao/dace?branch=fix-experimental-cuda-gpu-copy-fallback" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From c23608f7b6ac05f0cea3c3f916ec7c86f374610b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 28 Sep 2026 15:16:49 +0200 Subject: [PATCH 39/69] pass external gpu stream as SDFG runtime argument The GPU stream handle is a pointer that changes from run to run, so it cannot be a compile-time value baked into the generated code. Revive the SDFG argument approach from c56aff328, but declare it as an SDFG symbol so that DaCe passes it to the init functions, and inject it at load time through the backend, like the external workspace. --- .../runners/dace/workflow/backend.py | 12 +++- .../runners/dace/workflow/common.py | 10 +++- .../runners/dace/workflow/decoration.py | 22 ++++++- .../runners/dace/workflow/factory.py | 12 ++-- .../runners/dace/workflow/translation.py | 28 +++++---- .../dace_tests/test_dace_backend.py | 60 +++++++++++++++++++ .../dace_tests/test_dace_translation.py | 35 +++++------ 7 files changed, 138 insertions(+), 41 deletions(-) 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 9908f1e9b6..a26ca73454 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -24,15 +24,18 @@ @dataclasses.dataclass(frozen=True) class DaCeBackend(backend.Backend[Any]): - """DaCe backend with support for injecting an external workspace at load time.""" + """DaCe backend with support for injecting an external workspace and GPU stream at load time.""" external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None + external_gpu_stream: int | None = None def load_artifact(self, artifact: artifacts.CompilationArtifact) -> artifacts.ExecutableProgram: program = super().load_artifact(artifact) assert isinstance(program, gtx_wfddecoration.DaCeDecoratedProgram) # Inject the backend-level workspace so it is used when arguments are constructed. program.set_external_workspace(self.external_workspace or {}) + # Inject the backend-level GPU stream, it is passed as argument to the SDFG. + program.set_external_gpu_stream(self.external_gpu_stream) return program @@ -70,6 +73,7 @@ def make_dace_toolchain( allocator=cfg.make_allocator(), transforms=backend.DEFAULT_TRANSFORMS, external_workspace=cfg.external_workspace, + external_gpu_stream = cfg.external_gpu_stream, ) @@ -101,8 +105,9 @@ def make_dace_backend( the SDFG auto-optimize pipeline, see `gt_auto_optimize()`. external_gpu_stream: An external GPU stream to be used for the SDFG call, which allows to synchronize the execution of GPU kernels with external - workload and to share the stream memory pool. If not provided, the - default stream is used. + workload and to share the stream memory pool. The stream handle is + passed to the SDFG at runtime, on the first call, thus it does not + affect the generated code. If not provided, the default stream is used. 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 @@ -136,6 +141,7 @@ def make_dace_backend( gpu=gpu, auto_optimize=auto_optimize, external_workspace=external_workspace, + external_gpu_stream=external_gpu_stream, unstructured_horizontal_has_unit_stride=unstructured_horizontal_has_unit_stride, ), translation=functools.partial( diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 842606cdfd..6bc0cf7953 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -34,6 +34,14 @@ """DaCe datatype of `SDFG_ARG_METRIC_COMPUTE_TIME` argument.""" +SDFG_ARG_EXTERNAL_GPU_STREAM: Final[str] = "gt_external_gpu_stream" +"""Name of SDFG argument to input an external GPU stream to GT4Py.""" + + +SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE: Final[dace.dtypes.typeclass] = dace.int64 +"""DaCe datatype of `SDFG_ARG_EXTERNAL_GPU_STREAM` argument, the stream handle as integer.""" + + ExternalWorkspace: TypeAlias = dict[ core_defs.DeviceType, xtyping.ArrayInterface | xtyping.CUDAArrayInterface ] @@ -149,7 +157,7 @@ def set_dace_config( # Use the experimental CUDA codegen: unlike the legacy one, it launches kernels # and copies on the streams stored in `__state->gpu_context->streams`, even # when `max_concurrent_streams` is `-1`. This allows to replace the default - # stream with an external stream, see `set_sdfg_gpu_stream()`. + # stream with an external stream, see `add_external_gpu_stream_arg()`. dace.Config.set("compiler.cuda.implementation", value="experimental") # The experimental CUDA codegen synchronizes the GPU streams at the end of diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py index 57f45964ce..6a7d01b40c 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py @@ -34,7 +34,9 @@ class DaCeDecoratedProgram: program. External workspace memory (when the SDFG uses ``TransientMemoryMode.EXTERNAL``) is installed onto the underlying ``CompiledDaceProgram`` before the first call via `set_external_workspace`; - its lifetime is owned by the caller, not by this wrapper. + its lifetime is owned by the caller, not by this wrapper. Similarly, an external + GPU stream can be set before the first call via `set_external_gpu_stream`; it + is passed as argument to the SDFG and applied on SDFG initialization. """ def __init__( @@ -43,6 +45,7 @@ def __init__( device_type: core_defs.DeviceType = core_defs.DeviceType.CPU, ) -> None: self._fun = fun + self._external_gpu_stream: int | None = None # Retrieve metrics level from GT4Py environment variable. self._collect_time = metrics.is_level_enabled(metrics.PERFORMANCE) self._collect_time_arg = np.array( @@ -85,6 +88,11 @@ def __call__( gtx_wfdcommon.SDFG_ARG_METRIC_LEVEL: metrics.get_current_level(), gtx_wfdcommon.SDFG_ARG_METRIC_COMPUTE_TIME: self._collect_time_arg, } + if gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM in self._fun.sdfg_program.sdfg.symbols: + # The value `0` selects the default stream. + this_call_args[gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM] = ( + self._external_gpu_stream or 0 + ) self._fun.construct_arguments(**this_call_args) # Perform the call to the SDFG. @@ -101,3 +109,15 @@ def set_external_workspace(self, external_workspace: gtx_wfdcommon.ExternalWorks This method should be called before the first call to the program. """ self._fun.external_workspace = external_workspace + + def set_external_gpu_stream(self, external_gpu_stream: int | None) -> None: + """Set the external GPU stream used by the underlying compiled program. + + This method should be called before the first call to the program, because + the stream is applied on SDFG initialization. `None` selects the default stream. + """ + if self._fun.csdfg_argv is not None: + raise RuntimeError( + "The external GPU stream must be set before the first call to the program." + ) + self._external_gpu_stream = external_gpu_stream 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 6b3d52dba6..19cadd5087 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -43,6 +43,10 @@ class DaCeConfig(next_backend.ToolchainConfig): #: `EXTERNAL` transient memory mode, which stores the transients in it. The #: workspace is a dict, so a config holding one is not hashable. external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None + #: GPU stream allocated outside the SDFG. The toolchain injects it into the + #: loaded programs, and the translation step then passes it to the SDFG as an + #: argument. The stream is an integer, so a config holding one is hashable. + external_gpu_stream: int | None = None #: Name of the function that binds the SDFG arguments. The bindings and the #: compilation steps must agree on it. @@ -54,7 +58,7 @@ def make_dace_translator( /, *, auto_optimize_args: dict[str, Any] | None = None, - async_sdfg_call: bool = True, + sync_sdfg_call: bool = True, use_metrics: bool = True, disable_itir_transforms: bool = False, disable_field_origin_on_program_arguments: bool = False, @@ -71,8 +75,8 @@ def make_dace_translator( see `gt_auto_optimize()`. The parameters `DaCeTranslator` derives itself cannot be set here. With an external workspace in `cfg`, the `transient_memory_mode` defaults to `EXTERNAL`. - async_sdfg_call: Make an asynchronous SDFG call, to overlap GPU kernel - execution with the Python driver code. Only effective on GPU. + sync_sdfg_call: Make a synchronous SDFG call, to ensure that the GPU kernel + execution is completed before the Python driver code continues. Only effective on GPU. use_metrics: Add SDFG instrumentation for stencil compute time. disable_itir_transforms: Skip the GTIR transformation passes. disable_field_origin_on_program_arguments: Assume that all fields passed @@ -118,7 +122,7 @@ def make_dace_translator( device_type=cfg.device_type, auto_optimize=cfg.auto_optimize, auto_optimize_args=optimization_args, - async_sdfg_call=async_sdfg_call and cfg.gpu, + sync_sdfg_call=sync_sdfg_call, unstructured_horizontal_has_unit_stride=cfg.unstructured_horizontal_has_unit_stride, use_metrics=use_metrics, disable_itir_transforms=disable_itir_transforms, 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 bf9a604f8f..ca19a411ec 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -260,28 +260,33 @@ def add_instrumentation(sdfg: dace.SDFG, gpu: bool) -> None: sdfg.validate() -def set_sdfg_gpu_stream(sdfg: dace.SDFG, external_gpu_stream: int | None) -> None: - """Set the GPU stream used for all GPU work of the SDFG. +def add_external_gpu_stream_arg(sdfg: dace.SDFG) -> None: + """Add an SDFG argument to set the GPU stream used for all GPU work of the SDFG. Running the SDFG on an external GPU stream allows to synchronize the execution of GPU kernels with external workload and to share the stream memory pool. - The stream is written into the SDFG init code, thus it is fixed at compile time. + The stream handle is a pointer, which in general changes from run to run of + the application, therefore it cannot be a compile-time value. Instead, it is + passed as the SDFG argument `SDFG_ARG_EXTERNAL_GPU_STREAM` and applied in the + SDFG init code, which runs once on the first SDFG call. The value `0` selects + the default stream. Args: sdfg: The SDFG to process, modified in place. - external_gpu_stream: The handle of the external GPU stream, as an integer - value. If `None`, the default stream is used. """ - gpu_stream = ( - "nullptr" # The default stream. - if external_gpu_stream is None - else f"reinterpret_cast({external_gpu_stream})" + # NOTE: The argument has to be an SDFG symbol, not a scalar data container, + # because DaCe only passes the symbols to the SDFG init functions. + stream_arg = sdfg.add_symbol( + gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM, + gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE, ) # NOTE: The experimental DaCe CUDA codegen does not provide the helper function # `__dace_gpu_set_all_streams()`, therefore we write the stream array directly. + # The stream handle `0` is cast to `nullptr`, that is the default stream. sdfg.append_init_code( - _for_each_sdfg_gpu_stream(f"__stream = {gpu_stream};") + "\n", + _for_each_sdfg_gpu_stream(f"__stream = reinterpret_cast({stream_arg});") + + "\n", location="cuda", ) @@ -354,7 +359,6 @@ class DaCeTranslator( auto_optimize: bool auto_optimize_args: dict[str, Any] | None sync_sdfg_call: bool - external_gpu_stream: int | None unstructured_horizontal_has_unit_stride: bool use_metrics: bool @@ -463,7 +467,7 @@ def _generate_sdfg_without_configuring_dace( add_instrumentation(sdfg, on_gpu) if on_gpu: - set_sdfg_gpu_stream(sdfg, self.external_gpu_stream) + add_external_gpu_stream_arg(sdfg) return sdfg 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 13abf117de..cda368ae67 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 @@ -366,6 +366,66 @@ def test_compile_workflow_without_config_caches_translation(): assert isinstance(workflow.translation.step, dace_wf_translation.DaCeTranslator) +def _make_mocked_decorated_program( + sdfg_symbols: dict[str, dace.dtypes.typeclass], +) -> tuple[dace_wf_decoration.DaCeDecoratedProgram, mock.MagicMock]: + """Return a decorated program wrapping a mocked compiled program, and the mock.""" + sdfg = dace.SDFG("mocked_program") + for name, dtype in sdfg_symbols.items(): + sdfg.add_symbol(name, dtype) + + compiled_program = mock.MagicMock() + compiled_program.sdfg_program.sdfg = sdfg + compiled_program.csdfg_argv = None + compiled_program.csdfg_init_argv = None + + def construct_arguments(**kwargs: Any) -> None: + compiled_program.csdfg_argv = [] + compiled_program.csdfg_init_argv = [] + + compiled_program.construct_arguments.side_effect = construct_arguments + # Simulate the first call, where the argument vector is not yet constructed. + compiled_program.update_sdfg_ctype_arglist.side_effect = TypeError + + return dace_wf_decoration.DaCeDecoratedProgram(compiled_program), compiled_program + + +@pytest.mark.parametrize( + "external_gpu_stream, expected_arg", [(None, 0), (0x1234, 0x1234)], ids=["default", "external"] +) +def test_decorated_program_passes_external_gpu_stream_arg(external_gpu_stream, expected_arg): + program, compiled_program = _make_mocked_decorated_program( + { + dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM: dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE + } + ) + program.set_external_gpu_stream(external_gpu_stream) + + with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): + program(offset_provider={}) + + compiled_program.construct_arguments.assert_called_once() + call_kwargs = compiled_program.construct_arguments.call_args.kwargs + assert call_kwargs[dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM] == expected_arg + compiled_program.fast_call.assert_called_once() + + # The stream is applied on SDFG initialization, it cannot be changed later. + with pytest.raises(RuntimeError, match="before the first call"): + program.set_external_gpu_stream(0x5678) + + +def test_decorated_program_skips_external_gpu_stream_arg_on_cpu(): + # A CPU SDFG does not have the external GPU stream argument. + program, compiled_program = _make_mocked_decorated_program({}) + program.set_external_gpu_stream(0x1234) + + with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): + program(offset_provider={}) + + call_kwargs = compiled_program.construct_arguments.call_args.kwargs + assert dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM not in call_kwargs + + def _parse_generated_code_from_sdfg(sdfg: dace.SDFG, gpu_api_prefix: str) -> str: # Helper function to ignore the GPU device initialization code in the generated # cuda code, which is not relevant to the test. 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 dbf8c20c9c..c6610a6955 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 @@ -62,7 +62,6 @@ def _translate_gtir_to_sdfg( device_type: core_defs.DeviceType, auto_optimize: bool, sync_sdfg_call: bool, - external_gpu_stream: int | None = None, use_metrics: bool = False, ) -> dace.SDFG: with dace.config.set_temporary("cache", value="hash"): @@ -72,7 +71,6 @@ def _translate_gtir_to_sdfg( auto_optimize=auto_optimize, auto_optimize_args=None, sync_sdfg_call=sync_sdfg_call, - external_gpu_stream=external_gpu_stream, unstructured_horizontal_has_unit_stride=False, use_metrics=use_metrics, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -137,22 +135,23 @@ def _gpu_platform(device: core_defs.DeviceType) -> str: return "cuda" if device == core_defs.DeviceType.CUDA else "hip" -def _are_streams_set_to(sdfg: dace.SDFG, external_gpu_stream: int | None) -> bool: - """Check that the SDFG init code sets all GPU streams to the given stream. +def _are_streams_set_by_external_gpu_stream_arg(sdfg: dace.SDFG) -> bool: + """Check that the SDFG init code sets all GPU streams to the external stream argument. - If `external_gpu_stream` is `None`, the streams should be set to the default stream. + The external GPU stream is a runtime argument of the SDFG, it has to be a symbol + in order to be passed to the SDFG init functions. """ if "cuda" not in sdfg.init_code: # Here 'cuda' equals 'GPU backend'. return False - gpu_stream = ( - "nullptr" - if external_gpu_stream is None - else rf"reinterpret_cast\({external_gpu_stream}\)" - ) + stream_arg = dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM + if sdfg.symbols.get(stream_arg) != dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE: + return False + if re.search(rf"\b{stream_arg}\b", sdfg.init_signature()) is None: + return False return ( re.search( - rf"\b__stream\s*=\s*{gpu_stream};", + rf"\b__stream\s*=\s*reinterpret_cast\({stream_arg}\);", sdfg.init_code["cuda"].as_string, ) is not None @@ -215,7 +214,7 @@ def _check_sdfg_with_sync_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> {_gpu_platform(device)}StreamSynchronize(__stream); }}""" ) - assert _are_streams_set_to(sdfg, None) + assert _are_streams_set_by_external_gpu_stream_arg(sdfg) def _check_cpu_sdfg_call(sdfg: dace.SDFG) -> None: @@ -338,13 +337,11 @@ def _are_gpu_operations_on_sdfg_streams( @pytest.mark.parametrize("gpu_operation", ["kernel", "copy"]) -@pytest.mark.parametrize("external_gpu_stream", [None, 0x1234]) def test_generate_sdfg_external_gpu_stream( - external_gpu_stream: int | None, gpu_operation: Literal["kernel", "copy"], device_type: core_defs.DeviceType, ): - """Verify that `external_gpu_stream` selects the GPU stream used by the SDFG.""" + """Verify that the GPU stream used by the SDFG is selected by a runtime argument.""" if device_type == core_defs.DeviceType.CPU: pytest.skip("This test is only relevant for GPU execution.") @@ -375,10 +372,9 @@ def test_generate_sdfg_external_gpu_stream( device_type=device_type, auto_optimize=False, sync_sdfg_call=False, - external_gpu_stream=external_gpu_stream, ) _check_sdfg_with_async_call(sdfg, device_type) - assert _are_streams_set_to(sdfg, external_gpu_stream) + assert _are_streams_set_by_external_gpu_stream_arg(sdfg) assert _are_gpu_operations_on_sdfg_streams(sdfg, device_type, gpu_operation) @@ -505,7 +501,7 @@ def test_generate_sdfg_async_call_multi_state( # NOTE: Here we should use a configuration context. But because of # [DaCe issue#2125](https://github.com/spcl/dace/issues/2125) this is not possible. with dace_wf_common.dace_context(device_type=device_type): - dace_wf_translation.set_sdfg_gpu_stream(sdfg, external_gpu_stream=None) + dace_wf_translation.add_external_gpu_stream_arg(sdfg) # No synchronization state is added. assert sdfg.number_of_nodes() == 2 @@ -522,7 +518,7 @@ def test_generate_sdfg_async_call_multi_state( # used either on the InterState edge or inside the first state. Thus, the # GPU stream has to be synchronized after the device-to-host copy. # See https://github.com/spcl/dace/issues/2120 for more information. - assert _are_streams_set_to(sdfg, None) + assert _are_streams_set_by_external_gpu_stream_arg(sdfg) assert _are_streams_synchronized(sdfg, device_type) else: # There is no dependency between the states, so no sync. @@ -590,7 +586,6 @@ def test_translation_source_code_invariant_under_guid_change(): auto_optimize=False, auto_optimize_args=None, sync_sdfg_call=True, - external_gpu_stream=None, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) From f0c4a383e77105ff9af15b40309736165220327f Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 28 Sep 2026 15:45:27 +0200 Subject: [PATCH 40/69] do not add external gpu stream arg in orchestration In orchestration, the SDFG of a GT4Py program is nested in the SDFG of the orchestrated program, which owns the GPU streams and does not pass the external GPU stream argument. Add the translator flag 'use_external_gpu_stream' and disable it in '__sdfg__()'. --- .../runners/dace/program.py | 3 ++ .../runners/dace/workflow/translation.py | 3 +- .../dace_tests/test_dace_translation.py | 36 +++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/program_processors/runners/dace/program.py b/src/gt4py/next/program_processors/runners/dace/program.py index f8f8c7e1a4..170a00845d 100644 --- a/src/gt4py/next/program_processors/runners/dace/program.py +++ b/src/gt4py/next/program_processors/runners/dace/program.py @@ -86,11 +86,14 @@ def __sdfg__(self, *args: Any, **kwargs: Any) -> dace.sdfg.sdfg.SDFG: # TODO(ricoh): switch 'disable_itir_transforms=True' because we ran them separately previously # and so we can ensure the SDFG does not know any runtime info it shouldn't know. Remove with # the other parts of the workaround when possible. + # The SDFG is nested in the SDFG of the orchestrated program, which owns the GPU streams, + # therefore we do not add the argument to select an external GPU stream. sdfg = dace.SDFG.from_json( otf_workflow_translation.replace( # type: ignore[union-attr] disable_itir_transforms=True, disable_field_origin_on_program_arguments=True, use_metrics=False, + use_external_gpu_stream=False, )(gtir_stage).source_code ) 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 ca19a411ec..72054e4c8b 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -365,6 +365,7 @@ class DaCeTranslator( disable_itir_transforms: bool = False disable_field_origin_on_program_arguments: bool = False use_max_domain_range_on_unstructured_shift: bool | None = None + use_external_gpu_stream: bool = True def __post_init__(self) -> None: if self.auto_optimize_args and ( @@ -466,7 +467,7 @@ def _generate_sdfg_without_configuring_dace( if self.use_metrics: add_instrumentation(sdfg, on_gpu) - if on_gpu: + if on_gpu and self.use_external_gpu_stream: add_external_gpu_stream_arg(sdfg) return sdfg 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 c6610a6955..aa31521013 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 @@ -63,6 +63,7 @@ def _translate_gtir_to_sdfg( auto_optimize: bool, sync_sdfg_call: bool, use_metrics: bool = False, + use_external_gpu_stream: bool = True, ) -> dace.SDFG: with dace.config.set_temporary("cache", value="hash"): # we use the SDFG hash in build cache to avoid clashes between CPU and GPU SDFGs @@ -73,6 +74,7 @@ def _translate_gtir_to_sdfg( sync_sdfg_call=sync_sdfg_call, unstructured_horizontal_has_unit_stride=False, use_metrics=use_metrics, + use_external_gpu_stream=use_external_gpu_stream, ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) @@ -378,6 +380,40 @@ def test_generate_sdfg_external_gpu_stream( assert _are_gpu_operations_on_sdfg_streams(sdfg, device_type, gpu_operation) +def test_generate_sdfg_without_external_gpu_stream(device_type: core_defs.DeviceType): + """Verify that the external GPU stream argument is not added when disabled. + + This is the case of orchestration, where the SDFG is nested in another SDFG. + """ + ir = itir.Program( + id="field_ir_without_external_gpu_stream", + declarations=[], + function_definitions=[], + params=[ + itir.Sym(id="x", type=IFTYPE), + itir.Sym(id="y", type=IFTYPE), + ], + body=[ + itir.SetAt( + expr=im.op_as_fieldop("plus")("x", 1.0), + domain=im.get_field_domain(gtx_common.GridType.CARTESIAN, "y", IFTYPE.dims), + target=itir.SymRef(id="y"), + ), + ], + ) + + sdfg = _translate_gtir_to_sdfg( + ir=ir, + offset_provider={}, + device_type=device_type, + auto_optimize=False, + sync_sdfg_call=False, + use_external_gpu_stream=False, + ) + assert dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM not in sdfg.arglist() + assert "cuda" not in sdfg.init_code + + def _make_multi_state_sdfg_0( sdfg_name: str = "async_call_multi_state_0", ) -> tuple[dace.SDFG, dace.SDFGState, dace.SDFGState]: From cace0252ce5d03384d88e3ee613c5b37d90edc9f Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 28 Sep 2026 18:25:46 +0200 Subject: [PATCH 41/69] update uv lock --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 05c206988d..248daf9f24 100644 --- a/uv.lock +++ b/uv.lock @@ -1468,7 +1468,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/edopao/dace?branch=fix-experimental-cuda-gpu-copy-fallback" }, + { name = "dace", git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 13ef8557a1be6c07b8278d2f0c23cf8303aaa734 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 29 Sep 2026 09:22:52 +0200 Subject: [PATCH 42/69] fix fixture in codegen test --- .../dace_tests/test_dace_translation.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 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 aa31521013..99637b52d8 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 @@ -13,7 +13,7 @@ import re import uuid -from typing import Callable, Literal +from typing import Callable, Iterator, Literal from unittest import mock from gt4py._core import definitions as core_defs @@ -52,8 +52,14 @@ pytest.param(core_defs.DeviceType.ROCM, id="ROCM"), ] ) -def device_type(request) -> str: - return request.param +def device_type(request) -> Iterator[core_defs.DeviceType]: + # DaCe caches the GPU backend (`cuda` or `hip`) on first use, see `get_gpu_backend()`, + # because it assumes that a process only targets one type of GPU. These tests generate + # code for both CUDA and ROCm in the same process, so we clear the cache on each test, + # otherwise the code would be generated for the backend of a previous test. + dace.codegen.common.get_gpu_backend.cache_clear() + yield request.param + dace.codegen.common.get_gpu_backend.cache_clear() def _translate_gtir_to_sdfg( From 58439184982fa5327251530b31df27704f2bdc82 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 29 Sep 2026 09:38:30 +0200 Subject: [PATCH 43/69] use __dace_gpu_set_all_streams and fix stale comments Set the external GPU stream with the DaCe helper __dace_gpu_set_all_streams(), which the experimental CUDA codegen also provides. Fix code comments and docstrings that still referred to removed functions or to the default stream, the hard-coded assert message, and compare the sync tasklet code in the test against the helper function instead of a copy of the C++ code. --- .../runners/dace/workflow/common.py | 13 ++++--- .../runners/dace/workflow/decoration.py | 9 ++++- .../runners/dace/workflow/translation.py | 12 +++--- .../dace_tests/test_dace_translation.py | 39 +++++++++---------- 4 files changed, 39 insertions(+), 34 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 6bc0cf7953..d05e0857f7 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -146,12 +146,13 @@ def set_dace_config( # In some stencils, for example `apply_diffusion_to_w`, the cuda codegen messes # up with the cuda streams, i.e. it allocates N streams but uses N+1. The first # idea was to use just one stream. However, even in that case the generator - # generated wrong code. The current approach is to use the default stream, i.e. - # setting `max_concurrent_streams` to `-1`. However, the draw back is, that - # apparently then all synchronization is disabled, even the one at the very - # end of the SDFG call. To correct for that we are using either - # `make_sdfg_call_sync()` or `make_sdfg_call_async()`, see there or in - # [DaCe issue#2120](https://github.com/spcl/dace/issues/2120) for more. + # generated wrong code. The current approach is to use a single stream, i.e. + # setting `max_concurrent_streams` to `-1`. With the experimental CUDA codegen + # (see below), all GPU work is then scheduled on the streams stored in + # `__state->gpu_context->streams`, which are all set to the same stream: the + # default stream or an external stream, see `add_external_gpu_stream_arg()`. + # The synchronization at the end of the SDFG call is controlled by gt4py, see + # `make_sdfg_call_sync()` and [DaCe issue#2120](https://github.com/spcl/dace/issues/2120). dace.Config.set("compiler.cuda.max_concurrent_streams", value=-1) # Use the experimental CUDA codegen: unlike the legacy one, it launches kernels diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py index 6a7d01b40c..49e367b1c7 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py @@ -114,7 +114,14 @@ def set_external_gpu_stream(self, external_gpu_stream: int | None) -> None: """Set the external GPU stream used by the underlying compiled program. This method should be called before the first call to the program, because - the stream is applied on SDFG initialization. `None` selects the default stream. + the stream is applied on SDFG initialization. + + Args: + external_gpu_stream: The handle of the external GPU stream, as an integer + value. `None` selects the default stream. + + Raises: + RuntimeError: If the program was already called. """ if self._fun.csdfg_argv is not None: raise RuntimeError( 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 72054e4c8b..3781bd1b82 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -281,12 +281,11 @@ def add_external_gpu_stream_arg(sdfg: dace.SDFG) -> None: gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE, ) - # NOTE: The experimental DaCe CUDA codegen does not provide the helper function - # `__dace_gpu_set_all_streams()`, therefore we write the stream array directly. + # NOTE: `__dace_gpu_set_all_streams()` is defined by DaCe in the GPU code, it + # writes the given stream into every entry of `__state->gpu_context->streams`. # The stream handle `0` is cast to `nullptr`, that is the default stream. sdfg.append_init_code( - _for_each_sdfg_gpu_stream(f"__stream = reinterpret_cast({stream_arg});") - + "\n", + f"__dace_gpu_set_all_streams(__state, reinterpret_cast({stream_arg}));\n", location="cuda", ) @@ -296,7 +295,8 @@ def make_sdfg_call_sync(sdfg: dace.SDFG, gpu: bool) -> None: This means that `CompiledSDFG.fast_call()` will return only after all computations have _finished_ and the results are available. This function only has an effect for - work that runs on the GPU. Furthermore, all work is scheduled on the default stream. + work that runs on the GPU: it synchronizes all GPU streams of the SDFG, which by + default are the default stream, or an external stream, see `add_external_gpu_stream_arg()`. """ if not gpu: @@ -461,7 +461,7 @@ def _generate_sdfg_without_configuring_dace( f"Expected `max_concurrent_streams == -1` but it was `{dace.Config.get('compiler.cuda.max_concurrent_streams')}`." ) assert dace.Config.get("compiler.cuda.synchronize_on_exit") is False, ( - "Expected `synchronize_on_exit == False` but it was `True`." + f"Expected `synchronize_on_exit == False` but it was `{dace.Config.get('compiler.cuda.synchronize_on_exit')}`." ) if self.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 99637b52d8..eab2124dbd 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 @@ -159,7 +159,7 @@ def _are_streams_set_by_external_gpu_stream_arg(sdfg: dace.SDFG) -> bool: return False return ( re.search( - rf"\b__stream\s*=\s*reinterpret_cast\({stream_arg}\);", + rf"\b__dace_gpu_set_all_streams\(\s*__state\s*,\s*reinterpret_cast\({stream_arg}\)\s*\);", sdfg.init_code["cuda"].as_string, ) is not None @@ -180,13 +180,14 @@ def _are_streams_synchronized(sdfg: dace.SDFG, device: core_defs.DeviceType) -> def _check_sdfg_with_async_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> None: - # Because we are using the default stream, the launch is asynchronous. Thus we - # have to check if there is no synchronization state. However, we will do a - # stronger test. Instead we will make sure that there are no synchronization - # calls in the _entire_ generated code. - # NOTE: Even in asynchronous launch, there might be some need for synchronization, - # for example if something is computed in a kernel and used on an interstate - # edge. However, we do not have that case. + # The GPU work is launched on the SDFG streams and, since the synchronization at + # the SDFG exit is disabled, the call is asynchronous. Thus we have to check that + # there is no synchronization state. However, we will do a stronger test: we make + # sure that there are no synchronization calls in the _entire_ generated code. + # NOTE: Even in asynchronous launch, DaCe synchronizes the stream if something is + # computed in a kernel and read on the host, for example on an interstate edge, + # see `test_generate_sdfg_async_call_multi_state`. The SDFGs checked here do not + # have that case. assert not any( state.label == "sync_state" @@ -214,13 +215,8 @@ def _check_sdfg_with_sync_call(sdfg: dace.SDFG, device: core_defs.DeviceType) -> assert sync_tlet.side_effects assert sync_tlet.label == "stream_synchronize" - assert ( - sync_tlet.code.as_string - == f"""\ -for (int __i = 0; __i < __state->gpu_context->num_streams; ++__i) {{ - gpuStream_t& __stream = __state->gpu_context->streams[__i]; - {_gpu_platform(device)}StreamSynchronize(__stream); -}}""" + assert sync_tlet.code.as_string == dace_wf_translation._for_each_sdfg_gpu_stream( + f"{_gpu_platform(device)}StreamSynchronize(__stream);" ) assert _are_streams_set_by_external_gpu_stream_arg(sdfg) @@ -531,8 +527,11 @@ def test_generate_sdfg_async_call_multi_state( multi_state_config: tuple[bool, Callable], device_type: core_defs.DeviceType ): """ - Verify that states are not made async when a data descriptor is accessed - on an outgoing InterState edge. + Verify the synchronization of an asynchronous SDFG call with multiple states. + + The GPU streams of the SDFG have to be synchronized when the result of a + device-to-host copy is used on an outgoing InterState edge or on the host, + otherwise there should be no synchronization. """ if device_type == core_defs.DeviceType.CPU: pytest.skip("This test is only relevant for GPU execution.") @@ -540,17 +539,16 @@ def test_generate_sdfg_async_call_multi_state( expect_sync_after_first_map, make_multi_state_sdfg = multi_state_config sdfg, first_state, second_state = make_multi_state_sdfg() - # NOTE: Here we should use a configuration context. But because of - # [DaCe issue#2125](https://github.com/spcl/dace/issues/2125) this is not possible. with dace_wf_common.dace_context(device_type=device_type): dace_wf_translation.add_external_gpu_stream_arg(sdfg) + assert _are_streams_set_by_external_gpu_stream_arg(sdfg) # No synchronization state is added. assert sdfg.number_of_nodes() == 2 assert sdfg.out_degree(first_state) == 1 and sdfg.in_degree(first_state) == 0 assert sdfg.out_degree(second_state) == 0 and sdfg.in_degree(second_state) == 1 - # We do never a sync. + # The states are not marked as `nosync`. assert first_state.nosync == False assert second_state.nosync == False @@ -560,7 +558,6 @@ def test_generate_sdfg_async_call_multi_state( # used either on the InterState edge or inside the first state. Thus, the # GPU stream has to be synchronized after the device-to-host copy. # See https://github.com/spcl/dace/issues/2120 for more information. - assert _are_streams_set_by_external_gpu_stream_arg(sdfg) assert _are_streams_synchronized(sdfg, device_type) else: # There is no dependency between the states, so no sync. From b97d1ed6dd8610d01426f1cd4ec0de9162906640 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 29 Sep 2026 10:22:07 +0200 Subject: [PATCH 44/69] Support stream objects as external GPU stream handles --- .../runners/dace/workflow/backend.py | 12 +++-- .../runners/dace/workflow/common.py | 53 ++++++++++++++++++- .../runners/dace/workflow/decoration.py | 26 ++++++--- .../runners/dace/workflow/factory.py | 2 +- .../runners/dace/workflow/translation.py | 8 +-- .../dace_tests/test_dace_backend.py | 43 ++++++++++++++- 6 files changed, 126 insertions(+), 18 deletions(-) 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 a26ca73454..54724d612e 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -27,7 +27,7 @@ class DaCeBackend(backend.Backend[Any]): """DaCe backend with support for injecting an external workspace and GPU stream at load time.""" external_workspace: gtx_wfdcommon.ExternalWorkspace | None = None - external_gpu_stream: int | None = None + external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None = None def load_artifact(self, artifact: artifacts.CompilationArtifact) -> artifacts.ExecutableProgram: program = super().load_artifact(artifact) @@ -82,7 +82,7 @@ def make_dace_backend( auto_optimize: bool = True, sync_sdfg_call: bool = False, optimization_args: dict[str, Any] | None = None, - external_gpu_stream: int | None = None, + external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | 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, @@ -105,9 +105,11 @@ def make_dace_backend( the SDFG auto-optimize pipeline, see `gt_auto_optimize()`. external_gpu_stream: An external GPU stream to be used for the SDFG call, which allows to synchronize the execution of GPU kernels with external - workload and to share the stream memory pool. The stream handle is - passed to the SDFG at runtime, on the first call, thus it does not - affect the generated code. If not provided, the default stream is used. + workload and to share the stream memory pool. It can be the pointer + value of the stream, as an integer, or a stream object such as + `cupy.cuda.Stream`, see `GPUStreamHandle`. The stream handle is passed + to the SDFG at runtime, on the first call, thus it does not affect the + generated code. If not provided, the default stream is used. 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 diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index d05e0857f7..952401a5a2 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -11,6 +11,7 @@ from typing import Any, Final, Generator, Optional, TypeAlias import dace +from typing_extensions import Protocol, runtime_checkable from gt4py._core import definitions as core_defs from gt4py.eve import xtyping @@ -39,7 +40,7 @@ SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE: Final[dace.dtypes.typeclass] = dace.int64 -"""DaCe datatype of `SDFG_ARG_EXTERNAL_GPU_STREAM` argument, the stream handle as integer.""" +"""DaCe datatype of `SDFG_ARG_EXTERNAL_GPU_STREAM` argument, see `GPUStreamHandle`.""" ExternalWorkspace: TypeAlias = dict[ @@ -53,6 +54,56 @@ """ +@runtime_checkable +class GPUStream(Protocol): + """A GPU stream object that exposes its handle, for example `cupy.cuda.Stream`.""" + + @property + def ptr(self) -> int: + """The pointer value of the stream (`cudaStream_t` or `hipStream_t`).""" + ... + + +GPUStreamHandle: TypeAlias = int | GPUStream +""" Handle of a GPU stream (`cudaStream_t` or `hipStream_t`). + + Either the pointer value of the stream as an integer, or a stream object that + exposes it as the `ptr` attribute, for example `cupy.cuda.Stream`. It is passed + to the SDFG at runtime as an integer, see `SDFG_ARG_EXTERNAL_GPU_STREAM` and + `get_gpu_stream_ptr()`. +""" + + +DEFAULT_GPU_STREAM: Final[int] = 0 +"""The pointer value of the default GPU stream, i.e. `nullptr`.""" + + +def get_gpu_stream_ptr(stream: GPUStreamHandle | None) -> int: + """Return the pointer value of a GPU stream, as an integer. + + Args: + stream: The GPU stream handle. `None` selects the default stream. + + Returns: + The pointer value of the stream, `DEFAULT_GPU_STREAM` for the default stream. + + Raises: + TypeError: If `stream` is neither an integer nor a stream object that exposes + the `ptr` attribute. + """ + if stream is None: + return DEFAULT_GPU_STREAM + # NOTE: `bool` is a subclass of `int`, but it is not a valid stream handle. + if isinstance(stream, int) and not isinstance(stream, bool): + return stream + if isinstance(stream, GPUStream) and isinstance(stream.ptr, int): + return stream.ptr + raise TypeError( + f"Invalid GPU stream: should be of type 'int' or a stream object with an integer " + f"'ptr' attribute, for example 'cupy.cuda.Stream', got '{type(stream).__name__}'." + ) + + def set_dace_config( device_type: core_defs.DeviceType, cmake_build_type: Optional[gtx_config.CMakeBuildType] = None, diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py index 49e367b1c7..a6de2d6168 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/decoration.py @@ -45,7 +45,7 @@ def __init__( device_type: core_defs.DeviceType = core_defs.DeviceType.CPU, ) -> None: self._fun = fun - self._external_gpu_stream: int | None = None + self._external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None = None # Retrieve metrics level from GT4Py environment variable. self._collect_time = metrics.is_level_enabled(metrics.PERFORMANCE) self._collect_time_arg = np.array( @@ -89,9 +89,8 @@ def __call__( gtx_wfdcommon.SDFG_ARG_METRIC_COMPUTE_TIME: self._collect_time_arg, } if gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM in self._fun.sdfg_program.sdfg.symbols: - # The value `0` selects the default stream. this_call_args[gtx_wfdcommon.SDFG_ARG_EXTERNAL_GPU_STREAM] = ( - self._external_gpu_stream or 0 + gtx_wfdcommon.get_gpu_stream_ptr(self._external_gpu_stream) ) self._fun.construct_arguments(**this_call_args) @@ -106,25 +105,38 @@ def __call__( def set_external_workspace(self, external_workspace: gtx_wfdcommon.ExternalWorkspace) -> None: """Set the external workspace for the underlying compiled program. - This method should be called before the first call to the program. + This method should be called before the first call to the program, because + the workspace is installed when the SDFG arguments are constructed. + + Args: + external_workspace: Mapping from device types to the array-like objects + used as workspace memory for the SDFG transient arrays, when the + transient memory mode is `EXTERNAL`. """ self._fun.external_workspace = external_workspace - def set_external_gpu_stream(self, external_gpu_stream: int | None) -> None: + def set_external_gpu_stream( + self, external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None + ) -> None: """Set the external GPU stream used by the underlying compiled program. This method should be called before the first call to the program, because the stream is applied on SDFG initialization. Args: - external_gpu_stream: The handle of the external GPU stream, as an integer - value. `None` selects the default stream. + external_gpu_stream: The handle of the external GPU stream, either as an + integer or as a stream object, see `GPUStreamHandle`. `None` selects + the default stream. Raises: RuntimeError: If the program was already called. + TypeError: If `external_gpu_stream` is not a valid GPU stream handle. """ if self._fun.csdfg_argv is not None: raise RuntimeError( "The external GPU stream must be set before the first call to the program." ) + # Validate the stream handle, but store it as given: a stream object is thus + # kept alive as long as the program, which uses its pointer value. + gtx_wfdcommon.get_gpu_stream_ptr(external_gpu_stream) self._external_gpu_stream = external_gpu_stream 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 19cadd5087..5d81f1ae74 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -46,7 +46,7 @@ class DaCeConfig(next_backend.ToolchainConfig): #: GPU stream allocated outside the SDFG. The toolchain injects it into the #: loaded programs, and the translation step then passes it to the SDFG as an #: argument. The stream is an integer, so a config holding one is hashable. - external_gpu_stream: int | None = None + external_gpu_stream: gtx_wfdcommon.GPUStreamHandle | None = None #: Name of the function that binds the SDFG arguments. The bindings and the #: compilation steps must agree on it. 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 3781bd1b82..c28edebebd 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -268,8 +268,9 @@ def add_external_gpu_stream_arg(sdfg: dace.SDFG) -> None: The stream handle is a pointer, which in general changes from run to run of the application, therefore it cannot be a compile-time value. Instead, it is passed as the SDFG argument `SDFG_ARG_EXTERNAL_GPU_STREAM` and applied in the - SDFG init code, which runs once on the first SDFG call. The value `0` selects - the default stream. + SDFG init code, which runs once on the first SDFG call. The value of the + argument is the pointer value of the stream, see `get_gpu_stream_ptr()`, where + `DEFAULT_GPU_STREAM` selects the default stream. Args: sdfg: The SDFG to process, modified in place. @@ -283,7 +284,8 @@ def add_external_gpu_stream_arg(sdfg: dace.SDFG) -> None: # NOTE: `__dace_gpu_set_all_streams()` is defined by DaCe in the GPU code, it # writes the given stream into every entry of `__state->gpu_context->streams`. - # The stream handle `0` is cast to `nullptr`, that is the default stream. + # The handle `DEFAULT_GPU_STREAM`, i.e. `0`, is cast to `nullptr`, that is + # the default stream. sdfg.append_init_code( f"__dace_gpu_set_all_streams(__state, reinterpret_cast({stream_arg}));\n", location="cuda", 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 cda368ae67..764a0a698b 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 @@ -390,8 +390,49 @@ def construct_arguments(**kwargs: Any) -> None: return dace_wf_decoration.DaCeDecoratedProgram(compiled_program), compiled_program +@dataclasses.dataclass(frozen=True) +class _GPUStream: + """Minimal stand-in for a stream object such as `cupy.cuda.Stream`.""" + + ptr: Any + + +@pytest.mark.parametrize( + "stream, expected_ptr", + [ + (None, dace_wf_common.DEFAULT_GPU_STREAM), + (0x1234, 0x1234), + (_GPUStream(0x1234), 0x1234), + ], + ids=["default", "int", "stream_object"], +) +def test_get_gpu_stream_ptr(stream, expected_ptr): + assert dace_wf_common.get_gpu_stream_ptr(stream) == expected_ptr + + @pytest.mark.parametrize( - "external_gpu_stream, expected_arg", [(None, 0), (0x1234, 0x1234)], ids=["default", "external"] + "stream", + ["0x1234", True, 1.0, _GPUStream(None), object()], + ids=["str", "bool", "float", "stream_object_without_int_ptr", "object"], +) +def test_get_gpu_stream_ptr_rejects_invalid_stream(stream): + with pytest.raises(TypeError, match="Invalid GPU stream"): + dace_wf_common.get_gpu_stream_ptr(stream) + + +def test_make_backend_rejects_invalid_external_gpu_stream(): + with pytest.raises(TypeError, match="Invalid GPU stream"): + dace_wf_backend.make_dace_backend(gpu=True, auto_optimize=False, external_gpu_stream="0") + + +@pytest.mark.parametrize( + "external_gpu_stream, expected_arg", + [ + (None, dace_wf_common.DEFAULT_GPU_STREAM), + (0x1234, 0x1234), + (_GPUStream(0x1234), 0x1234), + ], + ids=["default", "int", "stream_object"], ) def test_decorated_program_passes_external_gpu_stream_arg(external_gpu_stream, expected_arg): program, compiled_program = _make_mocked_decorated_program( From 2cd42110de83429c79df8cc92f5623a142494895 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 16:49:15 +0200 Subject: [PATCH 45/69] fix merge conflicts --- .../runners/dace/transformations/map_fusion.py | 2 +- .../program_processors/runners/dace/workflow/factory.py | 4 ++++ .../runners_tests/dace_tests/test_dace_backend.py | 6 +++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py index bf74ad4e81..8b03ed5581 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py @@ -82,9 +82,9 @@ def __init__( check_fusion_callback: Optional[VerticalMapFusionCallback] = None, **kwargs: Any, ) -> None: + # TODO(edopao): Put back `allow_intermediates_with_symbolic_size=False,` once the new gpu codegen is based on main super().__init__( strict_dataflow=strict_dataflow, - allow_intermediates_with_symbolic_size=False, **kwargs, ) self._check_fusion_callback = None 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 5d81f1ae74..ff6ae22d0d 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/factory.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/factory.py @@ -52,6 +52,10 @@ class DaCeConfig(next_backend.ToolchainConfig): #: compilation steps must agree on it. bind_func_name: ClassVar[str] = "update_sdfg_args" + def __post_init__(self) -> None: + # Validate the stream handle early, it is only used when the program is loaded. + gtx_wfdcommon.get_gpu_stream_ptr(self.external_gpu_stream) + def make_dace_translator( cfg: DaCeConfig, 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 764a0a698b..78394b0d6b 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 @@ -284,7 +284,7 @@ def test_make_dace_backend_is_deprecated(): with pytest.warns(DeprecationWarning, match="make_dace_toolchain"): deprecated = dace_wf_backend.make_dace_backend( gpu=False, - async_sdfg_call=False, + sync_sdfg_call=True, optimization_args={"blocking_size": 10}, external_workspace=workspace, unstructured_horizontal_has_unit_stride=True, @@ -299,7 +299,7 @@ def test_make_dace_backend_is_deprecated(): translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args={"blocking_size": 10}, - async_sdfg_call=False, + sync_sdfg_call=True, use_metrics=False, disable_field_origin_on_program_arguments=True, use_max_domain_range_on_unstructured_shift=True, @@ -324,7 +324,7 @@ def test_translator_rejects_derived_optimization_args_on_every_route(): device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args={"gpu": True}, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) From ab2452703f5dfb898def2aaa8ff9dc5d2db65803 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 13 Oct 2026 18:16:46 +0200 Subject: [PATCH 46/69] edit --- .../dace/transformations/map_fusion.py | 2 +- .../runners/dace/workflow/backend.py | 2 +- .../runners/dace/workflow/common.py | 3 + .../dace_tests/test_dace_backend.py | 206 +++++++++--------- 4 files changed, 108 insertions(+), 105 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py index 8b03ed5581..bf74ad4e81 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/map_fusion.py @@ -82,9 +82,9 @@ def __init__( check_fusion_callback: Optional[VerticalMapFusionCallback] = None, **kwargs: Any, ) -> None: - # TODO(edopao): Put back `allow_intermediates_with_symbolic_size=False,` once the new gpu codegen is based on main super().__init__( strict_dataflow=strict_dataflow, + allow_intermediates_with_symbolic_size=False, **kwargs, ) self._check_fusion_callback = 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 54724d612e..4ccd18a223 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/backend.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/backend.py @@ -73,7 +73,7 @@ def make_dace_toolchain( allocator=cfg.make_allocator(), transforms=backend.DEFAULT_TRANSFORMS, external_workspace=cfg.external_workspace, - external_gpu_stream = cfg.external_gpu_stream, + external_gpu_stream=cfg.external_gpu_stream, ) diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/common.py b/src/gt4py/next/program_processors/runners/dace/workflow/common.py index 952401a5a2..cae4ef28d5 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/common.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/common.py @@ -63,6 +63,9 @@ def ptr(self) -> int: """The pointer value of the stream (`cudaStream_t` or `hipStream_t`).""" ... + def __hash__(self) -> int: + return self.ptr + GPUStreamHandle: TypeAlias = int | GPUStream """ Handle of a GPU stream (`cudaStream_t` or `hipStream_t`). 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 78394b0d6b..556f03250d 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 @@ -114,7 +114,7 @@ def mocked_gpu_transformation(*args, **kwargs) -> dace.SDFG: translation=functools.partial( dace_wf_factory.make_dace_translator, auto_optimize_args=optimization_args, - async_sdfg_call=True, + sync_sdfg_call=False, use_metrics=True, ), ) @@ -242,6 +242,107 @@ def test_make_backend_warns_external_workspace_without_external_mode(): assert backend.external_workspace[core_defs.DeviceType.CPU] is workspace +def _make_mocked_decorated_program( + sdfg_symbols: dict[str, dace.dtypes.typeclass], +) -> tuple[dace_wf_decoration.DaCeDecoratedProgram, mock.MagicMock]: + """Return a decorated program wrapping a mocked compiled program, and the mock.""" + sdfg = dace.SDFG("mocked_program") + for name, dtype in sdfg_symbols.items(): + sdfg.add_symbol(name, dtype) + + compiled_program = mock.MagicMock() + compiled_program.sdfg_program.sdfg = sdfg + compiled_program.csdfg_argv = None + compiled_program.csdfg_init_argv = None + + def construct_arguments(**kwargs: Any) -> None: + compiled_program.csdfg_argv = [] + compiled_program.csdfg_init_argv = [] + + compiled_program.construct_arguments.side_effect = construct_arguments + # Simulate the first call, where the argument vector is not yet constructed. + compiled_program.update_sdfg_ctype_arglist.side_effect = TypeError + + return dace_wf_decoration.DaCeDecoratedProgram(compiled_program), compiled_program + + +@dataclasses.dataclass(frozen=True) +class _GPUStream: + """Minimal stand-in for a stream object such as `cupy.cuda.Stream`.""" + + ptr: Any + + +@pytest.mark.parametrize( + "stream, expected_ptr", + [ + (None, dace_wf_common.DEFAULT_GPU_STREAM), + (0x1234, 0x1234), + (_GPUStream(0x1234), 0x1234), + ], + ids=["default", "int", "stream_object"], +) +def test_get_gpu_stream_ptr(stream, expected_ptr): + assert dace_wf_common.get_gpu_stream_ptr(stream) == expected_ptr + + +@pytest.mark.parametrize( + "stream", + ["0x1234", True, 1.0, _GPUStream(None), object()], + ids=["str", "bool", "float", "stream_object_without_int_ptr", "object"], +) +def test_get_gpu_stream_ptr_rejects_invalid_stream(stream): + with pytest.raises(TypeError, match="Invalid GPU stream"): + dace_wf_common.get_gpu_stream_ptr(stream) + + +def test_make_backend_rejects_invalid_external_gpu_stream(): + with pytest.raises(TypeError, match="Invalid GPU stream"): + dace_wf_backend.make_dace_backend(gpu=True, auto_optimize=False, external_gpu_stream="0") + + +@pytest.mark.parametrize( + "external_gpu_stream, expected_arg", + [ + (None, dace_wf_common.DEFAULT_GPU_STREAM), + (0x1234, 0x1234), + (_GPUStream(0x1234), 0x1234), + ], + ids=["default", "int", "stream_object"], +) +def test_decorated_program_passes_external_gpu_stream_arg(external_gpu_stream, expected_arg): + program, compiled_program = _make_mocked_decorated_program( + { + dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM: dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE + } + ) + program.set_external_gpu_stream(external_gpu_stream) + + with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): + program(offset_provider={}) + + compiled_program.construct_arguments.assert_called_once() + call_kwargs = compiled_program.construct_arguments.call_args.kwargs + assert call_kwargs[dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM] == expected_arg + compiled_program.fast_call.assert_called_once() + + # The stream is applied on SDFG initialization, it cannot be changed later. + with pytest.raises(RuntimeError, match="before the first call"): + program.set_external_gpu_stream(0x5678) + + +def test_decorated_program_skips_external_gpu_stream_arg_on_cpu(): + # A CPU SDFG does not have the external GPU stream argument. + program, compiled_program = _make_mocked_decorated_program({}) + program.set_external_gpu_stream(0x1234) + + with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): + program(offset_provider={}) + + call_kwargs = compiled_program.construct_arguments.call_args.kwargs + assert dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM not in call_kwargs + + def test_make_toolchain_derives_workspace_and_memory_mode_from_one_config(): """The toolchain and its translation step read the workspace from one config.""" workspace = _RecordingWorkspace() @@ -366,107 +467,6 @@ def test_compile_workflow_without_config_caches_translation(): assert isinstance(workflow.translation.step, dace_wf_translation.DaCeTranslator) -def _make_mocked_decorated_program( - sdfg_symbols: dict[str, dace.dtypes.typeclass], -) -> tuple[dace_wf_decoration.DaCeDecoratedProgram, mock.MagicMock]: - """Return a decorated program wrapping a mocked compiled program, and the mock.""" - sdfg = dace.SDFG("mocked_program") - for name, dtype in sdfg_symbols.items(): - sdfg.add_symbol(name, dtype) - - compiled_program = mock.MagicMock() - compiled_program.sdfg_program.sdfg = sdfg - compiled_program.csdfg_argv = None - compiled_program.csdfg_init_argv = None - - def construct_arguments(**kwargs: Any) -> None: - compiled_program.csdfg_argv = [] - compiled_program.csdfg_init_argv = [] - - compiled_program.construct_arguments.side_effect = construct_arguments - # Simulate the first call, where the argument vector is not yet constructed. - compiled_program.update_sdfg_ctype_arglist.side_effect = TypeError - - return dace_wf_decoration.DaCeDecoratedProgram(compiled_program), compiled_program - - -@dataclasses.dataclass(frozen=True) -class _GPUStream: - """Minimal stand-in for a stream object such as `cupy.cuda.Stream`.""" - - ptr: Any - - -@pytest.mark.parametrize( - "stream, expected_ptr", - [ - (None, dace_wf_common.DEFAULT_GPU_STREAM), - (0x1234, 0x1234), - (_GPUStream(0x1234), 0x1234), - ], - ids=["default", "int", "stream_object"], -) -def test_get_gpu_stream_ptr(stream, expected_ptr): - assert dace_wf_common.get_gpu_stream_ptr(stream) == expected_ptr - - -@pytest.mark.parametrize( - "stream", - ["0x1234", True, 1.0, _GPUStream(None), object()], - ids=["str", "bool", "float", "stream_object_without_int_ptr", "object"], -) -def test_get_gpu_stream_ptr_rejects_invalid_stream(stream): - with pytest.raises(TypeError, match="Invalid GPU stream"): - dace_wf_common.get_gpu_stream_ptr(stream) - - -def test_make_backend_rejects_invalid_external_gpu_stream(): - with pytest.raises(TypeError, match="Invalid GPU stream"): - dace_wf_backend.make_dace_backend(gpu=True, auto_optimize=False, external_gpu_stream="0") - - -@pytest.mark.parametrize( - "external_gpu_stream, expected_arg", - [ - (None, dace_wf_common.DEFAULT_GPU_STREAM), - (0x1234, 0x1234), - (_GPUStream(0x1234), 0x1234), - ], - ids=["default", "int", "stream_object"], -) -def test_decorated_program_passes_external_gpu_stream_arg(external_gpu_stream, expected_arg): - program, compiled_program = _make_mocked_decorated_program( - { - dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM: dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM_DTYPE - } - ) - program.set_external_gpu_stream(external_gpu_stream) - - with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): - program(offset_provider={}) - - compiled_program.construct_arguments.assert_called_once() - call_kwargs = compiled_program.construct_arguments.call_args.kwargs - assert call_kwargs[dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM] == expected_arg - compiled_program.fast_call.assert_called_once() - - # The stream is applied on SDFG initialization, it cannot be changed later. - with pytest.raises(RuntimeError, match="before the first call"): - program.set_external_gpu_stream(0x5678) - - -def test_decorated_program_skips_external_gpu_stream_arg_on_cpu(): - # A CPU SDFG does not have the external GPU stream argument. - program, compiled_program = _make_mocked_decorated_program({}) - program.set_external_gpu_stream(0x1234) - - with mock.patch.object(dace_wf_decoration.sdfg_callable, "get_sdfg_args", return_value={}): - program(offset_provider={}) - - call_kwargs = compiled_program.construct_arguments.call_args.kwargs - assert dace_wf_common.SDFG_ARG_EXTERNAL_GPU_STREAM not in call_kwargs - - def _parse_generated_code_from_sdfg(sdfg: dace.SDFG, gpu_api_prefix: str) -> str: # Helper function to ignore the GPU device initialization code in the generated # cuda code, which is not relevant to the test. @@ -527,7 +527,7 @@ def test_transient_memory_mode(device_type, transient_memory_mode, monkeypatch): auto_optimize_args={ "transient_memory_mode": transient_memory_mode, }, - async_sdfg_call=False, + sync_sdfg_call=True, ), ) From 3ded8c2678e9cd06bbcd19810cb6c1af8ac7c1f2 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 16 Oct 2026 08:59:14 +0200 Subject: [PATCH 47/69] update uv lock --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 988b40dbf8..8dd74afea2 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=main#6cdee42594c9f82f1b6768a97fe6076db5bfe6cb" } +source = { git = "https://github.com/spcl/dace.git?branch=main#f187d88a7aad49ff30296c5282783f8923832f9b" } dependencies = [ { name = "astunparse" }, { name = "click" }, From e22aef15c088dfa32cdef771d626f95da1c843e0 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 23 Oct 2026 08:26:37 +0200 Subject: [PATCH 48/69] update uv lock --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 8dd74afea2..179d79f7aa 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=main#f187d88a7aad49ff30296c5282783f8923832f9b" } +source = { git = "https://github.com/spcl/dace.git?branch=main#fe3ce2163fbc0b1531c2da31e3a8876d21a8de87" } dependencies = [ { name = "astunparse" }, { name = "click" }, From 9bfea69e9b8773525b08ad8e1b344a7364531641 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 23 Oct 2026 09:28:35 +0200 Subject: [PATCH 49/69] fix --- .../runners/dace/transformations/concat_where_mapper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py index fe0abcb7b2..8e9b4df45d 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py @@ -823,7 +823,7 @@ def _find_new_nested_symbol(nsdfg: dace.SDFG, name: str, reserved: Collection[st """ taken = set(reserved) | {name} while True: - new_name = dace_data.find_new_name(name, taken) + new_name = dace.utils.find_new_name(name, taken) if nsdfg.is_name_free(new_name): return new_name taken.add(new_name) From b080870bf8dc4338f226c47a5fa558579e682f4e Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 26 Oct 2026 09:21:55 +0100 Subject: [PATCH 50/69] switch to pypi --- pyproject.toml | 1 - uv.lock | 7 ++++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index a37ef2592c..5bab735230 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -434,7 +434,6 @@ url = 'https://gridtools.github.io/pypi/' # dace = {index = "gridtools"} [tool.uv.sources] atlas4py = { index = "test.pypi" } -dace = { git = "https://github.com/spcl/dace.git", branch = "main" } # -- versioningit -- [tool.versioningit] diff --git a/uv.lock b/uv.lock index 179d79f7aa..1c334afce3 100644 --- a/uv.lock +++ b/uv.lock @@ -922,8 +922,8 @@ wheels = [ [[package]] name = "dace" -version = "2.0.0a10" -source = { git = "https://github.com/spcl/dace.git?branch=main#fe3ce2163fbc0b1531c2da31e3a8876d21a8de87" } +version = "2.0.0b1" +source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -943,6 +943,7 @@ dependencies = [ { name = "sympy" }, { name = "typing-extensions" }, ] +sdist = { url = "https://files.pythonhosted.org/packages/07/08/e02a771ee94c47f5bede9d70f8299f29a2bd088b0f54a9a22b81f3923b82/dace-2.0.0b1.tar.gz", hash = "sha256:a645f17cf6155a8cf13543df2daf2823f7d1cc88984276e73206a652fe305698", size = 7104619, upload-time = "2026-10-26T08:06:49.246Z" } [[package]] name = "debugpy" @@ -1468,7 +1469,7 @@ requires-dist = [ { name = "cupy-cuda13x", marker = "extra == 'cuda13'", specifier = ">=14.0" }, { name = "cupy-rocm-7-0", marker = "extra == 'rocm7'", specifier = ">=14.0" }, { name = "cytoolz", specifier = ">=1.0.1" }, - { name = "dace", git = "https://github.com/spcl/dace.git?branch=main" }, + { name = "dace", specifier = "==2.0.0b1" }, { name = "deepdiff", specifier = ">=8.1.0" }, { name = "devtools", specifier = ">=0.6" }, { name = "filelock", specifier = ">=3.18.0" }, From 4ee97a3397c0492d94a810ef6eb6b866fd89a3f7 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 26 Oct 2026 17:21:40 +0100 Subject: [PATCH 51/69] edit lowering --- .../library_nodes/reduce_with_skip_values.py | 18 +++++++--------- .../lowering/gtir_to_sdfg_concat_where.py | 6 +----- .../dace/lowering/gtir_to_sdfg_fieldop.py | 9 +++++++- .../dace/lowering/gtir_to_sdfg_lambda.py | 21 +++++++++++-------- .../dace/lowering/gtir_to_sdfg_primitives.py | 9 +++++--- .../dace/lowering/gtir_to_sdfg_scan.py | 14 ++++++------- 6 files changed, 42 insertions(+), 35 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py b/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py index 9d49cf3067..d1d4615ae9 100644 --- a/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py +++ b/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py @@ -137,18 +137,16 @@ def expansion(node: ReduceWithSkipValues, state: dace.SDFGState, sdfg: dace.SDFG local_dim_index = inedge.data.src_subset.size().index(max_neighbors) # The connectors of the nested SDFG have to be equivalent to the data connected - # to them (see `NestedSDFG.validate()`). Thus, they are copies of the outer - # data descriptors, and inside they are accessed with the same indices as - # outside, where the local dimension is iterated by the map parameter `_LOCAL_INDEX`. - # This way, a later change of the strides of the outer data is propagated - # to the connectors, without the need of views. + # to them. Thus, they are copies of the outer data descriptors, and inside they + # are accessed with the same indices as outside, where the local dimension is + # iterated by the map parameter `_LOCAL_INDEX`. def make_local_subset(subset: dace_subsets.Range, local_index: int) -> dace_subsets.Range: local_subset = copy.deepcopy(subset) local_start = local_subset[local_index][0] local_subset[local_index] = (local_start + _LOCAL_INDEX, local_start + _LOCAL_INDEX, 1) return local_subset - input_subset = make_local_subset(inedge.data.src_subset, local_dim_index) + inp_subset = make_local_subset(inedge.data.src_subset, local_dim_index) mask_subset = make_local_subset(maskedge.data.src_subset, 1) nsdfg = dace.SDFG(node.label) @@ -158,7 +156,7 @@ def make_local_subset(subset: dace_subsets.Range, local_index: int) -> dace_subs nsdfg.add_datadesc(mask, _as_global(mask_desc)) outp = node.output_conn nsdfg.add_datadesc(outp, _as_global(output_desc)) - output_subset = ( + outp_subset = ( "0" if isinstance(output_desc, dace.data.Scalar) else str(outedge.data.dst_subset) ) st_init = nsdfg.add_state("init") @@ -173,7 +171,7 @@ def make_local_subset(subset: dace_subsets.Range, local_index: int) -> dace_subs "__tlet_out", st_init.add_access(outp), None, - dace.Memlet(data=outp, subset=output_subset), + dace.Memlet(data=outp, subset=outp_subset), ) st_reduce = nsdfg.add_state_after(st_init, "compute") # Fill skip values in local dimension with the reduce identity value @@ -185,13 +183,13 @@ def make_local_subset(subset: dace_subsets.Range, local_index: int) -> dace_subs name="reduce_with_skip_values", map_ranges={str(_LOCAL_INDEX): f"0:{max_neighbors}"}, inputs={ - "__tlet_inp": dace.Memlet(data=inp, subset=input_subset), + "__tlet_inp": dace.Memlet(data=inp, subset=inp_subset), "__tlet_mask": dace.Memlet(data=mask, subset=mask_subset), }, code=f"__tlet_out = __tlet_inp if __tlet_mask != {gtx_common._DEFAULT_SKIP_VALUE} else {skip_value}", outputs={ "__tlet_out": dace.Memlet( - data=outp, subset=output_subset, wcr=node.wcr, wcr_nonatomic=True + data=outp, subset=outp_subset, wcr=node.wcr, wcr_nonatomic=True ), }, external_edges=True, diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py index 94531219b9..e904ff4c1b 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_concat_where.py @@ -106,11 +106,7 @@ def testee(interior: cases.IJKField, boundary: cases.IJField) -> cases.IJKField: # The annex domain of the expression node is read-only here: the local copy is # specialized below to the region of this `concat_where` branch, but the node - # itself keeps its own domain. This is essential when the node is lowered as - # an argument of the promoted `as_fieldop` expression: there, the map ranges - # and the result write subset are both derived from the node's domain, and an - # inconsistency between them would produce subsets that reference map - # variables which are not in scope. + # itself has to keep the original domain. source_domain = domain_utils.SymbolicDomain( source_expr.annex.domain.grid_type, dict(source_expr.annex.domain.ranges) ) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py index 0d794f7280..659815204c 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_fieldop.py @@ -289,6 +289,13 @@ def create_field_operator( return gtx_utils.tree_map( lambda edge, field_domain, sym: _create_field_operator_impl( - ctx, sdfg_builder, edge, field_domain, sym.type, map_exit, inner_dims, len(domain) == 0 + ctx=ctx, + sdfg_builder=sdfg_builder, + output_edge=edge, + output_domain=field_domain, + output_type=sym.type, + map_exit=map_exit, + inner_dims=inner_dims, + is_zero_dim=(len(domain) == 0), ) )(output, output_domain, output_symbols) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py index 328f9255ae..b5458cbf0c 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py @@ -397,6 +397,13 @@ def get_tuple_type( return ts.TupleType(data_types) +def _as_global(desc: dace.data.Data) -> dace.data.Data: + """Returns a non-transient copy of `desc`, to be used as nested SDFG connector.""" + global_desc = copy.deepcopy(desc) + global_desc.transient = False + return global_desc + + @dataclasses.dataclass(frozen=True) class LambdaToDataflow(eve.NodeVisitor): """ @@ -747,8 +754,7 @@ def _visit_if_branch_arg( else: raise TypeError(f"Unexpected {arg} as input argument.") - inner_desc = arg_desc.clone() - inner_desc.transient = False + inner_desc = _as_global(arg_desc) if param_name not in sdfg.arrays: sdfg.add_datadesc(param_name, inner_desc) input_memlets[param_name] = arg_expr @@ -848,15 +854,13 @@ def _visit_if_branch_result( The result data inside the nested SDFG must have the same name as the connector. """ output_data = str(sym.id) - if output_data in sdfg.arrays: - output_desc = sdfg.data(output_data) + if output_desc := sdfg.arrays.get(output_data): assert not output_desc.transient else: # If the result is currently written to a transient node, inside the nested SDFG, # we need to allocate a non-transient data node. result_desc = edge.result.dc_node.desc(sdfg) - output_desc = result_desc.clone() - output_desc.transient = False + output_desc = _as_global(result_desc) output_data = sdfg.add_datadesc(output_data, output_desc, find_new_name=True) output_node = state.add_access(output_data) state.add_nedge( @@ -908,9 +912,8 @@ def write_output_of_nested_sdfg_to_temporary(inner_value: ValueExpr) -> ValueExp # add connectivities for aname, adesc in self.sdfg.arrays.items(): if gtx_dace_args.is_connectivity_identifier(aname): - adesc = adesc.clone() - adesc.transient = True - nsdfg.add_datadesc(aname, adesc) + inner_desc = _as_global(adesc) + nsdfg.add_datadesc(aname, inner_desc) # create states inside the nested SDFG for the if-branches if_region = dace.sdfg.state.ConditionalBlock("if") diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py index 8b44519828..60a275abe3 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_primitives.py @@ -35,12 +35,15 @@ from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_concat_where import ( translate_concat_where, ) -from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_scan import ( - translate_scan_fieldop, -) from gt4py.next.type_system import type_info as ti, type_specifications as ts +if TYPE_CHECKING: + from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_scan import ( + translate_scan_fieldop, + ) + + class PrimitiveTranslator(Protocol): @abc.abstractmethod def __call__( diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index 89c60fa4d7..e7df77a6c2 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -561,13 +561,13 @@ def translate_scan_fieldop( # the `LoopRegion` inside the stencil dataflow. scan_dim = next(r.dim for r in field_domain if sdfg_builder.is_column_axis(r.dim)) result = gtir_to_sdfg_fieldop.create_field_operator( - ctx, - field_domain, - node.type, - sdfg_builder, - input_edges, - output_tree, - node.annex.domain, + ctx=ctx, + domain=field_domain, + node_type=node.type, + sdfg_builder=sdfg_builder, + input_edges=input_edges, + output=output_tree, + output_domain=node.annex.domain, inner_dims=(scan_dim,), ) From e28310576ef29e5311d8c44a2dd8065b7934ae8e Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Tue, 27 Oct 2026 17:21:36 +0100 Subject: [PATCH 52/69] cartesian - convert legacy nested sdfgs before inlining - #2954 --- src/gt4py/cartesian/backend/dace_backend.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/gt4py/cartesian/backend/dace_backend.py b/src/gt4py/cartesian/backend/dace_backend.py index 748d939a29..5a41183566 100644 --- a/src/gt4py/cartesian/backend/dace_backend.py +++ b/src/gt4py/cartesian/backend/dace_backend.py @@ -17,6 +17,7 @@ from dace import SDFG, Memlet, SDFGState, config, data, dtypes, nodes, subsets, symbolic from dace.codegen import codeobject from dace.sdfg.analysis.schedule_tree import treenodes as tn +from dace.sdfg.dealias import convert_legacy_nested_sdfgs from dace.sdfg.utils import inline_sdfgs from dace.transformation.dataflow import MapCollapse @@ -297,6 +298,9 @@ def freeze_origin_domain_sdfg( if symbol not in wrapper_sdfg.symbols: wrapper_sdfg.add_symbol(symbol, nsdfg.sdfg.symbols[symbol]) + # Converts the legacy nested SDFGs of `wrapper_sdfg` before handing it to `inline_sdfgs` + convert_legacy_nested_sdfgs(wrapper_sdfg) + # Try to inline wrapped SDFG before symbols are specialized to avoid extra views inline_sdfgs(wrapper_sdfg) From cce7af43787dbe429d692f9bfca2997a6d07b7f1 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 28 Oct 2026 14:57:22 +0100 Subject: [PATCH 53/69] address review comments --- .../library_nodes/reduce_with_skip_values.py | 20 ++++------- .../dace/lowering/gtir_to_sdfg_lambda.py | 20 +++++------ .../dace/lowering/gtir_to_sdfg_scan.py | 11 +++--- .../dace/lowering/gtir_to_sdfg_utils.py | 8 +++++ .../transformations/concat_where_mapper.py | 34 ++++++++++--------- .../remove_access_node_copies.py | 5 +-- .../runners/dace/transformations/strides.py | 12 +++---- .../test_copy_chain_remover.py | 5 ++- .../test_move_dataflow_into_if_body.py | 5 --- .../transformation_tests/test_strides.py | 16 +++++---- 10 files changed, 67 insertions(+), 69 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py b/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py index d1d4615ae9..ca289ef00f 100644 --- a/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py +++ b/src/gt4py/next/program_processors/runners/dace/library_nodes/reduce_with_skip_values.py @@ -18,6 +18,7 @@ from gt4py.next import common as gtx_common from gt4py.next.program_processors.runners.dace import sdfg_utils as gtx_dace_utils +from gt4py.next.program_processors.runners.dace.lowering import gtir_to_sdfg_utils @dace.library.node @@ -98,13 +99,6 @@ def validate(self, sdfg: dace.SDFG, state: dace.SDFGState) -> None: """Map parameter that iterates over the local dimension in the expansion.""" -def _as_global(desc: dace.data.Data) -> dace.data.Data: - """Returns a non-transient copy of `desc`, to be used as nested SDFG connector.""" - global_desc = copy.deepcopy(desc) - global_desc.transient = False - return global_desc - - @dace_library.register_expansion(ReduceWithSkipValues, "pure") class ReduceWithSkipValuesExpandInlined(dace_transform.ExpandTransformation): """Implements pure expansion of the ReduceWithSkipValues library node.""" @@ -140,22 +134,22 @@ def expansion(node: ReduceWithSkipValues, state: dace.SDFGState, sdfg: dace.SDFG # to them. Thus, they are copies of the outer data descriptors, and inside they # are accessed with the same indices as outside, where the local dimension is # iterated by the map parameter `_LOCAL_INDEX`. - def make_local_subset(subset: dace_subsets.Range, local_index: int) -> dace_subsets.Range: + def access_list_elem(subset: dace_subsets.Range, local_index: int) -> dace_subsets.Range: local_subset = copy.deepcopy(subset) local_start = local_subset[local_index][0] local_subset[local_index] = (local_start + _LOCAL_INDEX, local_start + _LOCAL_INDEX, 1) return local_subset - inp_subset = make_local_subset(inedge.data.src_subset, local_dim_index) - mask_subset = make_local_subset(maskedge.data.src_subset, 1) + inp_subset = access_list_elem(inedge.data.src_subset, local_dim_index) + mask_subset = access_list_elem(maskedge.data.src_subset, 1) nsdfg = dace.SDFG(node.label) inp = node.input_conn - nsdfg.add_datadesc(inp, _as_global(input_desc)) + nsdfg.add_datadesc(inp, gtir_to_sdfg_utils.as_global_desc(input_desc)) mask = node.mask_conn - nsdfg.add_datadesc(mask, _as_global(mask_desc)) + nsdfg.add_datadesc(mask, gtir_to_sdfg_utils.as_global_desc(mask_desc)) outp = node.output_conn - nsdfg.add_datadesc(outp, _as_global(output_desc)) + nsdfg.add_datadesc(outp, gtir_to_sdfg_utils.as_global_desc(output_desc)) outp_subset = ( "0" if isinstance(output_desc, dace.data.Scalar) else str(outedge.data.dst_subset) ) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py index b5458cbf0c..fcf2702bbb 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py @@ -397,13 +397,6 @@ def get_tuple_type( return ts.TupleType(data_types) -def _as_global(desc: dace.data.Data) -> dace.data.Data: - """Returns a non-transient copy of `desc`, to be used as nested SDFG connector.""" - global_desc = copy.deepcopy(desc) - global_desc.transient = False - return global_desc - - @dataclasses.dataclass(frozen=True) class LambdaToDataflow(eve.NodeVisitor): """ @@ -754,10 +747,17 @@ def _visit_if_branch_arg( else: raise TypeError(f"Unexpected {arg} as input argument.") - inner_desc = _as_global(arg_desc) if param_name not in sdfg.arrays: + inner_desc = gtir_to_sdfg_utils.as_global_desc(arg_desc) sdfg.add_datadesc(param_name, inner_desc) input_memlets[param_name] = arg_expr + else: + # If the parameter name already exists in the nested SDFG, we assume that + # the data descriptor is equivalent to the argument data descriptor. + # This is a reasonable assumption because the nested SDFG is generated + # from a single if-expression, and therefore all branches of the if + # expression must have the same input arguments. + assert sdfg.arrays[param_name] == arg_desc inner_node = state.add_access(param_name) if isinstance(arg, IteratorExpr): @@ -860,7 +860,7 @@ def _visit_if_branch_result( # If the result is currently written to a transient node, inside the nested SDFG, # we need to allocate a non-transient data node. result_desc = edge.result.dc_node.desc(sdfg) - output_desc = _as_global(result_desc) + output_desc = gtir_to_sdfg_utils.as_global_desc(result_desc) output_data = sdfg.add_datadesc(output_data, output_desc, find_new_name=True) output_node = state.add_access(output_data) state.add_nedge( @@ -912,7 +912,7 @@ def write_output_of_nested_sdfg_to_temporary(inner_value: ValueExpr) -> ValueExp # add connectivities for aname, adesc in self.sdfg.arrays.items(): if gtx_dace_args.is_connectivity_identifier(aname): - inner_desc = _as_global(adesc) + inner_desc = gtir_to_sdfg_utils.as_global_desc(adesc) nsdfg.add_datadesc(aname, inner_desc) # create states inside the nested SDFG for the if-branches diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index e7df77a6c2..334481d28c 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -271,9 +271,6 @@ def connect_scan_output( else: assert isinstance(scan_result.gt_dtype, ts.ScalarType) assert len(scan_output_shape) == len(field_subset) - # This function is called once per field of a tuple result, so the subset - # has to be copied: DaCe rejects an SDFG where two memlets refer to the - # same subset object. output_subset = copy.deepcopy(field_subset) scan_result_data = scan_result.dc_node.data scan_result_desc = scan_result.dc_node.desc(lambda_ctx.sdfg) @@ -363,11 +360,11 @@ def _handle_dataflow_result_of_nested_sdfg( # We write the result to the output field after the loop region has ended. inner_states = list(inner_ctx.sdfg.states()) if len(inner_states) == 3: - assert sorted(st.label for st in inner_states) == [ + assert set(st.label for st in inner_states) == { "scan_compute", "scan_entry", "scan_update", - ] + } scan_loop = next( node for node in inner_ctx.sdfg.nodes() @@ -375,12 +372,12 @@ def _handle_dataflow_result_of_nested_sdfg( ) last_level_state = inner_ctx.sdfg.add_state_after(scan_loop, "scan_last_level") else: - assert sorted(st.label for st in inner_states) == [ + assert set(st.label for st in inner_states) == { "scan_compute", "scan_entry", "scan_last_level", "scan_update", - ] + } last_level_state = next(s for s in inner_states if s.label == "scan_last_level") # Move the write of the result from the scan loop to the state after the loop, # so that only the last level is written. 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 aabd0f64ed..9b5fbdbbc2 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 @@ -8,6 +8,7 @@ from __future__ import annotations +import copy from typing import Dict, Final, Mapping, Optional, TypeVar import dace @@ -25,6 +26,13 @@ """Prefix string to be used for tasklet connectors.""" +def as_global_desc(desc: dace.data.Data) -> dace.data.Data: + """Returns a non-transient copy of `desc`, to be used as nested SDFG connector.""" + global_desc = copy.deepcopy(desc) + global_desc.transient = False + return global_desc + + def debug_info( node: gtir.Node, *, default: Optional[dace.dtypes.DebugInfo] = None ) -> Optional[dace.dtypes.DebugInfo]: diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py index 8e9b4df45d..293444efea 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py @@ -720,11 +720,11 @@ def _configure_descending_point( # Symbols that the nested SDFG assigns itself, e.g. on an interstate edge or as a # loop variable. They are not necessarily listed in `nsdfg.symbols`. - reassigned_symbols: set[str] = set() + inner_written_symbols: set[str] = set() for isedge in nsdfg.all_interstate_edges(): - reassigned_symbols.update(isedge.data.assignments.keys()) + inner_written_symbols.update(isedge.data.assignments.keys()) for region in nsdfg.all_control_flow_regions(): - reassigned_symbols.update(region.new_symbols(nsdfg.symbols).keys()) + inner_written_symbols.update(region.new_symbols(nsdfg.symbols).keys()) nested_initial_producer_specs: list[_ProducerSpec] = [] handled_data: dict[str, _ProducerSpec] = {} @@ -742,7 +742,7 @@ def _configure_descending_point( _rename_nested_data(state, nsdfg_node, psym, parent_to_nested_name_mapping) ptype = state.sdfg.symbols[psym] if ( - psym not in reassigned_symbols + psym not in inner_written_symbols and psym in symbol_mapping and psym == str(symbol_mapping[psym]) and psym in nsdfg.symbols @@ -751,14 +751,14 @@ def _configure_descending_point( # The symbol is already mapped 1:1 into the nested sdfg -> nothing to do. continue - if psym in nsdfg.symbols or psym in symbol_mapping or psym in reassigned_symbols: - renamed_symbol = _find_new_nested_symbol(nsdfg, psym, reassigned_symbols) + if psym in nsdfg.symbols or psym in symbol_mapping or psym in inner_written_symbols: + renamed_symbol = _find_new_nested_symbol(nsdfg, psym, inner_written_symbols) nsdfg.replace_dict({psym: renamed_symbol}) if psym in symbol_mapping: symbol_mapping[renamed_symbol] = symbol_mapping.pop(psym) - if psym in reassigned_symbols: - reassigned_symbols.discard(psym) - reassigned_symbols.add(renamed_symbol) + if psym in inner_written_symbols: + inner_written_symbols.discard(psym) + inner_written_symbols.add(renamed_symbol) nsdfg.add_symbol(psym, ptype) symbol_mapping[psym] = psym @@ -778,6 +778,9 @@ def _configure_descending_point( else: # The data is not yet mapped into the nested SDFG, so we have to create # a new one, and we have to make sure that it is a global. + # The symbols used by the data descriptor, e.g. in the shape, must have + # the same name and meaning inside. Symbol clashes have been handled above, + # so we can safely use the same names. nested_desc = parent_prod_spec.desc.clone() nested_desc.transient = False nested_data_name = nsdfg.add_datadesc(parent_data_name, nested_desc, find_new_name=True) @@ -850,7 +853,7 @@ def _rename_nested_data( to the names of the data inside the nested SDFG. """ nsdfg: dace.SDFG = nsdfg_node.sdfg - new_data_name = nsdfg.find_new_symbol(data_name) + new_data_name = _find_new_nested_symbol(nsdfg, data_name, nsdfg.arrays.keys()) dace_replace_datadesc_names(nsdfg, {data_name: new_data_name}) for parent_data_name, nested_data_name in parent_to_nested_name_mapping.items(): @@ -1342,12 +1345,11 @@ def _find_consumer_specs_single_source_single_level( return None raise ValueError(f"Expected that partition for {concat_node} exists but it does not.") - # Now wet and partition the consumer. A nested SDFG always opens up a "new level": - # its connector is equivalent to the concat where data (see `NestedSDFG.validate()`), - # so the nested SDFG accesses the data with the same indices as here, even if it - # only reads a single element. Thus, the accesses have to be replaced inside it. - # All other consumers have to read a single element, which makes them genuine - # consumers. + # Now wet and partition the consumer. Most importantly test if they only read + # a single element, in which case they are genuine consumers this applies to + # _all_ nodes, even nested SDFGs. Otherwise it might open up a "new level". + # For this the consumer must be a nested SDFG that reads the _whole_ concat + # where node. stairs_to_deeper_levels: list[_FinalConsumerSpec] = [] # Better name appreciated. consumer_specs: list[_FinalConsumerSpec] = [] for consumer_spec in all_consumers: diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py index 4f2272808e..e2f33c815e 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py @@ -276,8 +276,9 @@ def apply( connector = edge.dst_conn if edge.dst is node else edge.src_conn if not connector or connector not in node.sdfg.arrays: continue - if node.sdfg.arrays[connector].transient: - continue + assert not node.sdfg.arrays[connector].transient, ( + "NestedSDFG connector data must be non-transient" + ) gtx_transformations_utils.restate_nested_sdfg_connector( node, connector, 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 9a9fe664a0..56ea0b9ae6 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/strides.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/strides.py @@ -440,15 +440,13 @@ def _gt_map_strides_into_nested_sdfg( ) -> None: """Sets the strides of the connector `inner_data` to the ones of the outer data. - The data descriptor of a NestedSDFG connector has to be equivalent to the data - connected to it on the outside, i.e. it must have the same shape and strides, - see `NestedSDFG.validate()`. The function handles the case that only the - strides of the outer data have changed. The symbols used by the new strides - are mapped 1:1 into the NestedSDFG. + The data descriptor of a NestedSDFG connector has to be equivalent to the + data connected to it on the outside, i.e. it must have the same shape and strides. + This function handles the case that only the strides of the outer data have changed. + The symbols used by the new strides are mapped 1:1 into the NestedSDFG. If a transformation connects different data to the connector, it has to restate - the connector itself, see `restate_nested_sdfg_connector()`, because only the - transformation knows where the old data is located inside the new one. + the connector itself: in that case, use `restate_nested_sdfg_connector()`. Args: sdfg: The SDFG containing the NestedSDFG. diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py index b2f4d7b8e2..c09d4568ae 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_copy_chain_remover.py @@ -724,9 +724,8 @@ def inner_ref(i0, o0): assert {ac.data for ac in acnodes} == {"a", "e"} assert util.count_nodes(sdfg, dace_nodes.NestedSDFG) == 1 - # A nested SDFG connector has to be equivalent to the data it is connected to. - # Thus `i0` is still `a`, but `o0` has been restated as `e`, into which the - # nested SDFG now writes directly, at the offset of the removed copy chain. + # The input descriptor should be the same as before, but the output descriptor + # should now be the same as `e`. assert inner_sdfg.arrays["i0"].shape == sdfg.arrays["a"].shape assert inner_sdfg.arrays["i0"].strides == sdfg.arrays["a"].strides assert inner_sdfg.arrays["o0"].shape == sdfg.arrays["e"].shape diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py index 6033712f62..c147a42852 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_move_dataflow_into_if_body.py @@ -104,11 +104,6 @@ def _write_if_output( ) -> str: """Write the scalar output `connector` of `if_block` to `outer_data[__i]`. - The value passes through a scalar transient, because the connector of a nested - SDFG has to be equivalent to the data it is connected to, so it cannot write - into an element of the outer array directly. This is also how the lowering - writes the result of an if-expression. - Returns: The name of the scalar transient. """ diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py index 436154810b..681e8ef3ed 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py @@ -195,17 +195,20 @@ def test_strides_propagation(): for aname, adesc in sdfg.arrays.items(): assert [str(s) for s in adesc.strides] == [f"{aname[0]}1_stride"] - # Now we change the strides of `a1` and propagate them, but not the ones of `c1`. - sdfg_level1.add_symbol("a1_new_stride", dace.int32) - sdfg_level1.arrays["a1"].set_shape((10,), (dace_symbolic.pystr_to_symbolic("a1_new_stride"),)) - gtx_transformations.gt_propagate_strides_of(sdfg_level1, "a1") - sdfg_level1.validate() + # Now we propagate `a` and `b`, but not `c`. + for data in ["a", "b"]: + sdfg_level1.add_symbol(f"{data}1_new_stride", dace.int32) + sdfg_level1.arrays[f"{data}1"].set_shape( + (10,), (dace_symbolic.pystr_to_symbolic(f"{data}1_new_stride"),) + ) + gtx_transformations.gt_propagate_strides_of(sdfg_level1, f"{data}1") + sdfg_level1.validate() # The new strides have been propagated to all levels, including `a2_alias`, which is # also connected to `a1`. Inside the nested SDFGs the new symbol is mapped 1:1. for sdfg in all_sdfgs: assert set(_get_stride_of(sdfg, "a").values()) == {"a1_new_stride"} - assert set(_get_stride_of(sdfg, "b").values()) <= {"b1_stride"} + assert set(_get_stride_of(sdfg, "b").values()) <= {"b1_new_stride"} assert set(_get_stride_of(sdfg, "c").values()) == {"c1_stride"} if (nsdfg := sdfg.parent_nsdfg_node) is not None: assert str(nsdfg.symbol_mapping["a1_new_stride"]) == "a1_new_stride" @@ -217,6 +220,7 @@ def test_strides_propagation(): sdfg_level1.validate() for sdfg in all_sdfgs: assert set(_get_stride_of(sdfg, "a").values()) == {"a1_new_stride"} + assert set(_get_stride_of(sdfg, "b").values()) <= {"b1_new_stride"} assert set(_get_stride_of(sdfg, "c").values()) == {"c1_new_stride"} From ae9a3cb4660e4d9f1cd39f42cc4401bf720cc126 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 28 Oct 2026 17:11:24 +0100 Subject: [PATCH 54/69] apply review comments --- .../dace/lowering/gtir_to_sdfg_scan.py | 2 + .../transformations/concat_where_mapper.py | 129 ++++++++++++------ .../runners/dace/transformations/utils.py | 12 +- .../test_concat_where_replacer.py | 83 +++++++++++ 4 files changed, 178 insertions(+), 48 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index 334481d28c..035558db83 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -162,6 +162,8 @@ def get_scan_output_shape( offset_provider_type = sdfg_builder.get_offset_provider_type(offset_type.value) assert isinstance(offset_provider_type, gtx_common.NeighborConnectivityType) list_size = offset_provider_type.max_neighbors + # The local (list) dimension of the scan result takes the position that + # the scan (column) dimension has in the field layout. return [ *field_shape[:scan_dim_index], sympy.Integer(list_size), diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py index 293444efea..49b7c93bc9 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py @@ -718,50 +718,89 @@ def _configure_descending_point( parent: nested for nested, parent in nested_to_parent_name_mapping.items() } - # Symbols that the nested SDFG assigns itself, e.g. on an interstate edge or as a - # loop variable. They are not necessarily listed in `nsdfg.symbols`. + # Symbols that the nested SDFG assigns itself, e.g. on an interstate edge, as a + # loop variable of a `LoopRegion`, or as a map parameter. Such a symbol binds the + # name inside the nested SDFG, so the name could mean something entirely different + # than in the parent SDFG. Note that these symbols are not necessarily listed in + # `nsdfg.symbols` and are thus unknown to `nsdfg.is_name_free()`. inner_written_symbols: set[str] = set() for isedge in nsdfg.all_interstate_edges(): inner_written_symbols.update(isedge.data.assignments.keys()) for region in nsdfg.all_control_flow_regions(): inner_written_symbols.update(region.new_symbols(nsdfg.symbols).keys()) + for inner_state in nsdfg.states(): + for inner_node in inner_state.nodes(): + if isinstance(inner_node, dace_nodes.MapEntry): + inner_written_symbols.update(inner_node.params) + + # Collect all the symbols that the producers use, e.g. in the shape of their data + # descriptors. They are mapped 1:1 into the nested SDFG, i.e. they have the same + # name and meaning inside. Note that a connector is not a view: the descriptor + # inside the nested SDFG is equivalent to the parent data once the symbol mapping + # of the node is applied, so instead of mapping 1:1, the symbols could also be + # renamed to fresh names that are mapped back onto the parent symbols, which is + # what previous versions of this code did. However, with renamed symbols, each + # object that crosses the scope boundary, e.g. a descriptor, an offset or a + # subset, would have to be rewritten through that rename map, and so on for each + # level of nesting. The 1:1 mapping avoids all of these rewrites: it is the reason + # why we can simply insert the objects, e.g. the data descriptors and the access + # patterns, from the parent SDFG into the nested SDFG as they are. The price is + # that a name clash, i.e. the nested SDFG uses the name of a symbol for something + # else, either a data container or a symbol, including one it assigns itself or + # binds as a map parameter, has to be resolved by renaming that symbol inside, + # which is done below. + parent_symbol_types: dict[str, dace.dtypes.typeclass] = { + psym: state.sdfg.symbols[psym] + for parent_prod_spec in parent_producer_specs + for psym in parent_prod_spec.free_symbols + } + + # In order to not scan the whole nested SDFG once per symbol, the renames of all + # conflicting symbols are first gathered and then applied in a single pass. + rename_dict: dict[str, str] = {} + symbols_to_map: set[str] = set() + taken_names: set[str] = inner_written_symbols | set(parent_symbol_types) + for psym in sorted(parent_symbol_types): + ptype = parent_symbol_types[psym] + if psym in nsdfg.arrays: + _rename_nested_data(state, nsdfg_node, psym, parent_to_nested_name_mapping) + if ( + psym not in inner_written_symbols + and psym in symbol_mapping + and psym == str(symbol_mapping[psym]) + and psym in nsdfg.symbols + and nsdfg.symbols[psym] == ptype + ): + # The symbol is already mapped 1:1 into the nested sdfg -> nothing to do. + continue + + if psym in nsdfg.symbols or psym in symbol_mapping or psym in inner_written_symbols: + renamed_symbol = _find_new_nested_symbol(nsdfg, psym, taken_names) + rename_dict[psym] = renamed_symbol + taken_names.add(renamed_symbol) + symbols_to_map.add(psym) + + if rename_dict: + # A single pass renames all the conflicting symbols inside the nested SDFG. Note + # that if the nested SDFG bound the name as a map parameter, then the parameter + # is renamed together with all the uses of it inside its scope. + nsdfg.replace_dict(rename_dict) + for psym, renamed_symbol in rename_dict.items(): + if psym in symbol_mapping: + symbol_mapping[renamed_symbol] = symbol_mapping.pop(psym) + if psym in inner_written_symbols: + inner_written_symbols.discard(psym) + inner_written_symbols.add(renamed_symbol) + + for psym in sorted(symbols_to_map): + nsdfg.add_symbol(psym, parent_symbol_types[psym]) + symbol_mapping[psym] = psym nested_initial_producer_specs: list[_ProducerSpec] = [] handled_data: dict[str, _ProducerSpec] = {} for parent_prod_spec in parent_producer_specs: parent_data_name = parent_prod_spec.data_name - # The symbols used by the producer are mapped 1:1 into the nested SDFG. The - # data descriptors mapped into the nested SDFG have to be equivalent to the - # ones in the parent SDFG (see `NestedSDFG.validate()`), so the symbols they - # use, e.g. in the shape, must have the same name and meaning inside. If the - # nested SDFG uses the name of the symbol for something else, either a data - # container or a symbol, including one it assigns itself, it is renamed there. - for psym in sorted(parent_prod_spec.free_symbols): - if psym in nsdfg.arrays: - _rename_nested_data(state, nsdfg_node, psym, parent_to_nested_name_mapping) - ptype = state.sdfg.symbols[psym] - if ( - psym not in inner_written_symbols - and psym in symbol_mapping - and psym == str(symbol_mapping[psym]) - and psym in nsdfg.symbols - and nsdfg.symbols[psym] == ptype - ): - # The symbol is already mapped 1:1 into the nested sdfg -> nothing to do. - continue - - if psym in nsdfg.symbols or psym in symbol_mapping or psym in inner_written_symbols: - renamed_symbol = _find_new_nested_symbol(nsdfg, psym, inner_written_symbols) - nsdfg.replace_dict({psym: renamed_symbol}) - if psym in symbol_mapping: - symbol_mapping[renamed_symbol] = symbol_mapping.pop(psym) - if psym in inner_written_symbols: - inner_written_symbols.discard(psym) - inner_written_symbols.add(renamed_symbol) - nsdfg.add_symbol(psym, ptype) - symbol_mapping[psym] = psym - # Compute the nested data descriptor. if parent_data_name in handled_data: # The data has already been handled before. So we can simply reuse it. @@ -777,10 +816,9 @@ def _configure_descending_point( else: # The data is not yet mapped into the nested SDFG, so we have to create - # a new one, and we have to make sure that it is a global. - # The symbols used by the data descriptor, e.g. in the shape, must have - # the same name and meaning inside. Symbol clashes have been handled above, - # so we can safely use the same names. + # a new one, and we have to make sure that it is a global. Per the policy + # described above, the descriptor is written with the parent's symbols as + # is. The symbol clashes have been handled there, so this is safe. nested_desc = parent_prod_spec.desc.clone() nested_desc.transient = False nested_data_name = nsdfg.add_datadesc(parent_data_name, nested_desc, find_new_name=True) @@ -1345,11 +1383,18 @@ def _find_consumer_specs_single_source_single_level( return None raise ValueError(f"Expected that partition for {concat_node} exists but it does not.") - # Now wet and partition the consumer. Most importantly test if they only read - # a single element, in which case they are genuine consumers this applies to - # _all_ nodes, even nested SDFGs. Otherwise it might open up a "new level". - # For this the consumer must be a nested SDFG that reads the _whole_ concat - # where node. + # Now we partition the consumers. A tasklet or access node has to read exactly a + # single element of the concat where data, only then it is a genuine consumer, + # i.e. the replacement is performed on this level: a tasklet is inserted here + # that produces the single consumed element. + # A nested SDFG is different, it always opens up a deeper level, a "descending + # point": in the SDFG IR the connector of a nested SDFG is not a view, it is + # equivalent to the whole data connected to it, so the accesses inside use the + # same coordinates as on this level, even if the nested SDFG only reads a single + # element inside. + # The replacement thus has to be performed inside it, which means that the + # producers of the concat where data have to be mapped into the nested SDFG, + # see `_configure_descending_point()`. stairs_to_deeper_levels: list[_FinalConsumerSpec] = [] # Better name appreciated. consumer_specs: list[_FinalConsumerSpec] = [] for consumer_spec in all_consumers: diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py index 7088106003..8ae0504912 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py @@ -596,12 +596,12 @@ def restate_nested_sdfg_connector( ) -> None: """Restates `connector` of `nsdfg_node` as the new data connected to it. - The data descriptor of a NestedSDFG connector has to be equivalent to the data - connected to it (see `NestedSDFG.validate()`), and the accesses inside use the - coordinates of that data. When a transformation connects different data to the - connector, e.g. through `reroute_edge()`, the connector has to adopt `new_desc` - and every access inside the NestedSDFG, and inside the NestedSDFGs below it, has - to be shifted by `ss_offset`. + In the SDFG IR a connector of a NestedSDFG is not a view: it is equivalent to + the data connected to it on the outside, i.e. it has the same shape and strides, + and the accesses inside use the coordinates of that data. When a transformation + connects different data to the connector, e.g. through `reroute_edge()`, the + connector has to adopt `new_desc` and every access inside the NestedSDFG, and + inside the NestedSDFGs below it, has to be shifted by `ss_offset`. Args: nsdfg_node: The NestedSDFG whose connector is connected to different data. diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py index ff5c1e372c..c4ba724386 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py @@ -1800,6 +1800,89 @@ def test_concat_where_with_symbolic_size_clashing_with_nested_assignment(): assert util.compare_sdfg_res(ref=ref, res=res) +def test_concat_where_with_symbolic_size_clashing_with_nested_map_param(): + # The symbol `n`, that defines the size of the producer `a`, has to be mapped into + # the nested SDFG, which binds `n` as the parameter of one of its maps. A map + # parameter shadows any outer symbol of the same name, so the map parameter has to + # be renamed inside the nested SDFG, together with all its uses, this also tests + # that `replace_dict()` performs these renames consistently (in particular the + # parameter of the map itself). + symbolic_size = "n" + + nested = dace.SDFG("nested") + for aname in "ab": + nested.add_array(aname, shape=(10,), dtype=dace.float64, transient=False) + nested_state = nested.add_state(is_start_block=True) + nested_state.add_mapped_tasklet( + "nested_map", + map_ranges={symbolic_size: "0:10"}, + inputs={"__in": dace.Memlet(f"a[{symbolic_size}]")}, + outputs={"__out": dace.Memlet(f"b[{symbolic_size}]")}, + code=f"__out = __in + {symbolic_size}", + external_edges=True, + ) + nested.validate() + assert symbolic_size not in nested.symbols + + sdfg = dace.SDFG(util.unique_name("concat_where_symbolic_size_clashing_with_nested_map_param")) + state = sdfg.add_state() + sdfg.add_symbol(symbolic_size, dace.int32) + for aname in "abcd": + sdfg.add_array( + name=aname, + shape=((10,) if aname != "a" else (dace.symbolic.pystr_to_symbolic(symbolic_size),)), + dtype=dace.float64, + transient=(aname == "c"), + ) + + a, b, c, d = (state.add_access(aname) for aname in "abcd") + state.add_nedge(a, c, dace.Memlet("a[1:6] -> [0:5]")) + state.add_nedge(b, c, dace.Memlet("b[3:8] -> [5:10]")) + + nested_sdfg = state.add_nested_sdfg(sdfg=nested, inputs={"a"}, outputs={"b"}, symbol_mapping={}) + state.add_edge(c, None, nested_sdfg, "a", dace.Memlet("c[0:10]")) + state.add_edge(nested_sdfg, "b", d, None, dace.Memlet("d[0:10]")) + sdfg.validate() + + ref, res = util.make_sdfg_args(sdfg, symbols={symbolic_size: 10}) + util.compile_and_run_sdfg(sdfg, **ref) + + gtx_transformations.gt_replace_concat_where_node(state=state, sdfg=sdfg, concat_node=c) + sdfg.validate() + + assert c.data not in sdfg.arrays + assert state.in_degree(nested_sdfg) == 2 + + # `n` is now mapped 1:1 into the nested SDFG... + assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size + assert nested_sdfg.sdfg.symbols[symbolic_size] == dace.int32 + + # ... and the map parameter, which used the name inside the nested SDFG, has been + # renamed, together with all of its uses. The consistency of the renaming (in + # particular of the uses inside the map scope) is verified by the compile and run. + map_entries = util.count_nodes(nested_sdfg.sdfg, dace_nodes.MapEntry, True) + assert len(map_entries) >= 1 + renamed_params = {param for me in map_entries for param in me.params} + assert symbolic_size not in renamed_params + assert all(param.startswith(symbolic_size + "_") for param in renamed_params) + (renamed_param,) = renamed_params + used_inside = { + str(fs) + for state_ in nested_sdfg.sdfg.states() + for edge in state_.edges() + for fs in edge.data.free_symbols + } + used_inside |= { + str(fs) + for tlet in util.count_nodes(nested_sdfg.sdfg, dace_nodes.Tasklet, True) + for fs in tlet.free_symbols + } + assert renamed_param in used_inside + + util.compile_and_run_sdfg(sdfg, **res) + assert util.compare_sdfg_res(ref=ref, res=res) + + def _make_multi_producer_sdfg( nb_producers: int, ) -> tuple[dace.SDFG, dace.SDFGState, dace_nodes.AccessNode]: From 8cbfd3b96a126af570325ee41e5c134d396d1710 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 28 Oct 2026 17:33:30 +0100 Subject: [PATCH 55/69] edit assert --- .../runners/dace/lowering/gtir_to_sdfg_lambda.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py index fcf2702bbb..b002aa0da4 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py @@ -757,7 +757,7 @@ def _visit_if_branch_arg( # This is a reasonable assumption because the nested SDFG is generated # from a single if-expression, and therefore all branches of the if # expression must have the same input arguments. - assert sdfg.arrays[param_name] == arg_desc + assert sdfg.arrays[param_name] == gtir_to_sdfg_utils.as_global_desc(arg_desc) inner_node = state.add_access(param_name) if isinstance(arg, IteratorExpr): From e2fa72c2c9598eca1ac910400f2728b7195130c0 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Wed, 28 Oct 2026 22:44:09 +0100 Subject: [PATCH 56/69] edit --- .../dace/lowering/gtir_to_sdfg_scan.py | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index 035558db83..747353b4e7 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -38,6 +38,7 @@ ir_makers as im, ) from gt4py.next.iterator.transforms import infer_domain +from gt4py.next.program_processors.runners.dace import sdfg_args as gtx_dace_args from gt4py.next.program_processors.runners.dace.lowering import ( gtir_domain, gtir_to_sdfg, @@ -535,11 +536,23 @@ def translate_scan_fieldop( input_edges = [] for input_connector, memlet in input_memlets.items(): - src_node = lambda_arg_nodes[input_connector] - assert src_node is not None - input_edge = gtir_to_sdfg_lambda.MemletInputEdge( - ctx.state, src_node.dc_node, memlet.src_subset, nsdfg_node, input_connector - ) + if src_node := lambda_arg_nodes.get(input_connector, None): + input_edge = gtir_to_sdfg_lambda.MemletInputEdge( + state=ctx.state, + source=src_node.dc_node, + subset=memlet.src_subset, + dest=nsdfg_node, + dest_conn=input_connector, + ) + else: + assert gtx_dace_args.is_connectivity_identifier(input_connector) + input_edge = gtir_to_sdfg_lambda.MemletInputEdge( + state=ctx.state, + source=ctx.state.add_access(input_connector), + subset=memlet.src_subset, + dest=nsdfg_node, + dest_conn=input_connector, + ) input_edges.append(input_edge) # for output connections, we create temporary arrays that contain the computation From 4cd6bf7994fb1d7ec57835571ed49e0eb5d9f01e Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 29 Oct 2026 11:11:09 +0100 Subject: [PATCH 57/69] address review comments --- .../dace/lowering/gtir_to_sdfg_lambda.py | 3 +- .../transformations/concat_where_mapper.py | 42 ++++++------------- .../remove_access_node_copies.py | 4 +- .../runners/dace/transformations/utils.py | 31 ++++++++++++-- .../transformation_tests/test_utils.py | 27 ++++++++++++ 5 files changed, 69 insertions(+), 38 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py index b002aa0da4..d432193523 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_lambda.py @@ -748,8 +748,7 @@ def _visit_if_branch_arg( raise TypeError(f"Unexpected {arg} as input argument.") if param_name not in sdfg.arrays: - inner_desc = gtir_to_sdfg_utils.as_global_desc(arg_desc) - sdfg.add_datadesc(param_name, inner_desc) + sdfg.add_datadesc(param_name, gtir_to_sdfg_utils.as_global_desc(arg_desc)) input_memlets[param_name] = arg_expr else: # If the parameter name already exists in the nested SDFG, we assume that diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py index 49b7c93bc9..0d9c90970c 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py @@ -718,20 +718,9 @@ def _configure_descending_point( parent: nested for nested, parent in nested_to_parent_name_mapping.items() } - # Symbols that the nested SDFG assigns itself, e.g. on an interstate edge, as a - # loop variable of a `LoopRegion`, or as a map parameter. Such a symbol binds the - # name inside the nested SDFG, so the name could mean something entirely different - # than in the parent SDFG. Note that these symbols are not necessarily listed in - # `nsdfg.symbols` and are thus unknown to `nsdfg.is_name_free()`. - inner_written_symbols: set[str] = set() - for isedge in nsdfg.all_interstate_edges(): - inner_written_symbols.update(isedge.data.assignments.keys()) - for region in nsdfg.all_control_flow_regions(): - inner_written_symbols.update(region.new_symbols(nsdfg.symbols).keys()) - for inner_state in nsdfg.states(): - for inner_node in inner_state.nodes(): - if isinstance(inner_node, dace_nodes.MapEntry): - inner_written_symbols.update(inner_node.params) + # Symbols assigned or bound inside the nested SDFG may have a different + # meaning than in the parent SDFG. + inner_written_symbols = gtx_transformations.utils.gt_collect_symbols_written_in_sdfg(nsdfg) # Collect all the symbols that the producers use, e.g. in the shape of their data # descriptors. They are mapped 1:1 into the nested SDFG, i.e. they have the same @@ -759,22 +748,21 @@ def _configure_descending_point( # conflicting symbols are first gathered and then applied in a single pass. rename_dict: dict[str, str] = {} symbols_to_map: set[str] = set() - taken_names: set[str] = inner_written_symbols | set(parent_symbol_types) + taken_names: set[str] = set(parent_symbol_types) | inner_written_symbols for psym in sorted(parent_symbol_types): - ptype = parent_symbol_types[psym] - if psym in nsdfg.arrays: - _rename_nested_data(state, nsdfg_node, psym, parent_to_nested_name_mapping) if ( - psym not in inner_written_symbols + psym in nsdfg.symbols and psym in symbol_mapping + and psym not in inner_written_symbols and psym == str(symbol_mapping[psym]) - and psym in nsdfg.symbols - and nsdfg.symbols[psym] == ptype + and nsdfg.symbols[psym] == parent_symbol_types[psym] ): # The symbol is already mapped 1:1 into the nested sdfg -> nothing to do. continue - if psym in nsdfg.symbols or psym in symbol_mapping or psym in inner_written_symbols: + if psym in nsdfg.arrays: + _rename_nested_data(state, nsdfg_node, psym, parent_to_nested_name_mapping) + elif psym in nsdfg.symbols or psym in symbol_mapping or psym in inner_written_symbols: renamed_symbol = _find_new_nested_symbol(nsdfg, psym, taken_names) rename_dict[psym] = renamed_symbol taken_names.add(renamed_symbol) @@ -1387,14 +1375,8 @@ def _find_consumer_specs_single_source_single_level( # single element of the concat where data, only then it is a genuine consumer, # i.e. the replacement is performed on this level: a tasklet is inserted here # that produces the single consumed element. - # A nested SDFG is different, it always opens up a deeper level, a "descending - # point": in the SDFG IR the connector of a nested SDFG is not a view, it is - # equivalent to the whole data connected to it, so the accesses inside use the - # same coordinates as on this level, even if the nested SDFG only reads a single - # element inside. - # The replacement thus has to be performed inside it, which means that the - # producers of the concat where data have to be mapped into the nested SDFG, - # see `_configure_descending_point()`. + # Before no-view NestedSDFG it was possible for a NestedSDFG to read a single element. + # This is no longer possible, thus we descend into every NestedSDFG level. stairs_to_deeper_levels: list[_FinalConsumerSpec] = [] # Better name appreciated. consumer_specs: list[_FinalConsumerSpec] = [] for consumer_spec in all_consumers: diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py index e2f33c815e..9a2ae495f4 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py @@ -276,9 +276,7 @@ def apply( connector = edge.dst_conn if edge.dst is node else edge.src_conn if not connector or connector not in node.sdfg.arrays: continue - assert not node.sdfg.arrays[connector].transient, ( - "NestedSDFG connector data must be non-transient" - ) + assert not node.sdfg.arrays[connector].transient gtx_transformations_utils.restate_nested_sdfg_connector( node, connector, diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py index 8ae0504912..3c50d76d46 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py @@ -22,6 +22,25 @@ from gt4py.next.program_processors.runners.dace import library_nodes as gtx_lib +def gt_collect_symbols_written_in_sdfg(sdfg: dace.SDFG) -> OrderedSet[str]: + """Returns symbols assigned or bound inside the SDFG. + + This includes symbols assigned on interstate edges, introduced by control-flow + regions, and used as map parameters. + """ + written_symbols: OrderedSet[str] = OrderedSet() + for isedge in sdfg.all_interstate_edges(): + written_symbols.update(isedge.data.assignments.keys()) + for region in sdfg.all_control_flow_regions(): + written_symbols.update(region.new_symbols(sdfg.symbols).keys()) + for state in sdfg.states(): + for node in state.nodes(): + if isinstance(node, dace_nodes.MapEntry): + written_symbols.update(node.params) + + return written_symbols + + def gt_configure_transient_lifetime( sdfg: dace.SDFG, lifetime: dace.AllocationLifetime, @@ -634,17 +653,23 @@ def restate_nested_sdfg_connector( passed_symbols.update( str(sym) for off in ss_offset if dace_sym.issymbolic(off) for sym in off.free_symbols ) + inner_written_symbols = gt_collect_symbols_written_in_sdfg(nsdfg) for sym in sorted(passed_symbols): - if sym in nsdfg.arrays or str(nsdfg_node.symbol_mapping.get(sym, sym)) != sym: + # Note that the default value passed to `get()` is the symbol itself, because missing + # symbols are added automatically. + if ( + sym in nsdfg.arrays + or sym in inner_written_symbols + or str(nsdfg_node.symbol_mapping.get(sym, sym)) != sym + ): raise NotImplementedError( f"Can not restate the connector '{connector}' of NestedSDFG '{nsdfg_node.label}'," f" because the symbol '{sym}' has a different meaning inside it." ) - dace_dealias.reduce_connector( + dace_dealias.rebase_connector( nsdfg, connector, - reduced_desc=new_desc, # Where the origin of the new data is located in the coordinates of the old data. offset=None if ss_offset is None else [-off for off in ss_offset], ) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py index 2076515e9b..a5ab55b006 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py @@ -80,6 +80,33 @@ def test_find_successor_state_non_terminal_loop_region(): assert gtx_transformations_utils.find_successor_state(body_state2) == [after_loop] +def test_collect_symbols_written_in_sdfg(): + sdfg = dace.SDFG(util.unique_name("collect_symbols_written_in_sdfg")) + state1 = sdfg.add_state(is_start_block=True) + state2 = sdfg.add_state_after(state1) + sdfg.add_edge( + state1, + state2, + dace.InterstateEdge(assignments={"interstate_symbol": "1"}), + ) + state2.add_map("map", {"map_parameter": "0:10"}) + + loop = LoopRegion( + label="loop", + condition_expr="loop_symbol < 2", + loop_var="loop_symbol", + initialize_expr="loop_symbol = 0", + update_expr="loop_symbol = loop_symbol + 1", + ) + sdfg.add_node(loop) + + assert gtx_transformations_utils.gt_collect_symbols_written_in_sdfg(sdfg) == { + "interstate_symbol", + "loop_symbol", + "map_parameter", + } + + def test_find_successor_state_nested_sdfg(): """Terminal state inside a nested SDFG. From 88d5310f87dbbc305a2580940693a94960479bbb Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 29 Oct 2026 11:49:29 +0100 Subject: [PATCH 58/69] fix --- .../program_processors/runners/dace/transformations/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py index 3c50d76d46..b7cd1d2a24 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py @@ -667,9 +667,10 @@ def restate_nested_sdfg_connector( f" because the symbol '{sym}' has a different meaning inside it." ) - dace_dealias.rebase_connector( + dace_dealias.reduce_connector( nsdfg, connector, + reduced_desc=new_desc, # Where the origin of the new data is located in the coordinates of the old data. offset=None if ss_offset is None else [-off for off in ss_offset], ) From 1bc4952b85bd66c945ed29985fc021e3b0e3b74b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 29 Oct 2026 11:59:11 +0100 Subject: [PATCH 59/69] another fix --- .../runners_tests/dace_tests/transformation_tests/test_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py index a5ab55b006..e758e7353e 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_utils.py @@ -83,7 +83,7 @@ def test_find_successor_state_non_terminal_loop_region(): def test_collect_symbols_written_in_sdfg(): sdfg = dace.SDFG(util.unique_name("collect_symbols_written_in_sdfg")) state1 = sdfg.add_state(is_start_block=True) - state2 = sdfg.add_state_after(state1) + state2 = sdfg.add_state() sdfg.add_edge( state1, state2, From 7812230dd252cd7f9fe3e1d3309f2dd17c3703ac Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 30 Oct 2026 12:52:30 +0100 Subject: [PATCH 60/69] address review comments --- .../runners/dace/lowering/__init__.py | 2 + .../remove_access_node_copies.py | 13 ------ .../runners/dace/transformations/strides.py | 40 +++++++++++-------- .../runners/dace/transformations/utils.py | 2 + 4 files changed, 28 insertions(+), 29 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 a0466c026e..b96538a0c1 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/__init__.py @@ -11,6 +11,7 @@ from gt4py.next.program_processors.runners.dace.lowering.gtir_to_sdfg_utils import ( flatten_tuple_fields, get_map_variable, + safe_replace_symbolic, ) @@ -18,4 +19,5 @@ "flatten_tuple_fields", "get_map_variable", "lower_program_to_sdfg", + "safe_replace_symbolic", ] diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py index 9a2ae495f4..3f48fa6763 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py @@ -28,7 +28,6 @@ from gt4py.next.program_processors.runners.dace.transformations import ( splitting_tools as gtx_dace_split, - strides as gtx_transformations_strides, utils as gtx_transformations_utils, ) @@ -283,16 +282,4 @@ def apply( outer_desc, ss_offset=tuple(node_offset), ) - - # Update strides after changing the data of access nodes - for modified_node in [second_node, third_node]: - gtx_transformations_strides.gt_propagate_strides_from_access_node( - sdfg, graph, modified_node - ) - - # Restate connectors of NestedSDFGs whose edge data was changed above. - # Without this the nested SDFG contract is violated because the - # connector descriptors no longer match the parent data. - for node in graph.nodes(): - if isinstance(node, dace_nodes.NestedSDFG) and node.sdfg is not None: node.integrate_into_parent() 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 56ea0b9ae6..0635639543 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/strides.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/strides.py @@ -10,10 +10,13 @@ import dace from dace import data as dace_data -from dace.sdfg import dealias as dace_dealias, nodes as dace_nodes +from dace.sdfg import nodes as dace_nodes from gt4py.next import common as gtx_common -from gt4py.next.program_processors.runners.dace import transformations as gtx_transformations +from gt4py.next.program_processors.runners.dace import ( + lowering as gtx_dace_lowering, + transformations as gtx_transformations, +) PropagatedStrideRecord: TypeAlias = tuple[str, dace_nodes.NestedSDFG] @@ -460,16 +463,17 @@ def _gt_map_strides_into_nested_sdfg( inside the NestedSDFG. """ nsdfg: dace.SDFG = nsdfg_node.sdfg - if inner_data not in dace_dealias.windowed_connectors(nsdfg): - return - inner_desc = nsdfg.arrays[inner_data] outer_desc = sdfg.arrays[edge.data.data] + if inner_desc.is_equivalent(outer_desc, symbol_mapping=nsdfg_node.symbol_mapping): + return + if ( isinstance(inner_desc, dace_data.Array) and not isinstance(inner_desc, dace_data.View) and len(inner_desc.shape) == len(outer_desc.strides) ): + replace_dict: dict[str, str] = {} for sym in sorted( str(fsym) for stride in outer_desc.strides @@ -479,18 +483,22 @@ def _gt_map_strides_into_nested_sdfg( if sym not in nsdfg.symbols: nsdfg.add_symbol(sym, sdfg.symbols[sym]) nsdfg_node.symbol_mapping[sym] = dace.symbolic.pystr_to_symbolic(sym) - elif str(nsdfg_node.symbol_mapping.get(sym, "")) != sym: - raise ValueError( - f"Can not map the stride symbol '{sym}' into NestedSDFG" - f" '{nsdfg_node.label}', because it has a different meaning there." + elif str(nsdfg_node.symbol_mapping[sym]) != sym: + inner_sym = next( + (k for k, v in nsdfg_node.symbol_mapping.items() if str(v) == sym), None ) - inner_desc.set_shape(inner_desc.shape, outer_desc.strides) - - if inner_data in dace_dealias.windowed_connectors(nsdfg): - raise ValueError( - f"The connector '{inner_data}' of NestedSDFG '{nsdfg_node.label}' is not" - f" equivalent to the data '{edge.data.data}' connected to it." - ) + if inner_sym is None: + raise ValueError( + f"Can not map the stride symbol '{sym}' into NestedSDFG" + f" '{nsdfg_node.label}', because it has a different meaning there." + ) + else: + replace_dict[sym] = inner_sym + inner_strides = [ + gtx_dace_lowering.safe_replace_symbolic(stride, replace_dict) + for stride in outer_desc.strides + ] + inner_desc.set_shape(inner_desc.shape, inner_strides) def _gt_find_toplevel_data_accesses( diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py index b7cd1d2a24..8121751156 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/utils.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/utils.py @@ -667,6 +667,8 @@ def restate_nested_sdfg_connector( f" because the symbol '{sym}' has a different meaning inside it." ) + # TODO(phimuell): The `reduce_connector()` function should be replaced with something + # that does not create views as a side effect. dace_dealias.reduce_connector( nsdfg, connector, From 44bb4516bcac584acf3da852fda5167d990eb291 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 30 Oct 2026 13:45:56 +0100 Subject: [PATCH 61/69] do not rename inner symbols, find new name when adding a symbol --- .../transformations/concat_where_mapper.py | 162 ++++++------------ .../test_concat_where_replacer.py | 87 ++++------ 2 files changed, 93 insertions(+), 156 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py index 0d9c90970c..08b48bd5aa 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py @@ -8,6 +8,7 @@ import copy import dataclasses +import functools from typing import Any, Collection, Literal, Mapping, Optional, Sequence, TypeAlias, Union, overload import dace @@ -19,7 +20,6 @@ transformation as dace_transformation, ) from dace.sdfg import graph as dace_graph, nodes as dace_nodes -from dace.sdfg.replace import replace_datadesc_names as dace_replace_datadesc_names from dace.transformation.passes import analysis as dace_analysis from ordered_set import OrderedSet @@ -719,76 +719,56 @@ def _configure_descending_point( } # Symbols assigned or bound inside the nested SDFG may have a different - # meaning than in the parent SDFG. + # meaning than in the parent SDFG. Keep those names unchanged and instead map + # parent symbols to fresh names inside the nested SDFG. inner_written_symbols = gtx_transformations.utils.gt_collect_symbols_written_in_sdfg(nsdfg) - - # Collect all the symbols that the producers use, e.g. in the shape of their data - # descriptors. They are mapped 1:1 into the nested SDFG, i.e. they have the same - # name and meaning inside. Note that a connector is not a view: the descriptor - # inside the nested SDFG is equivalent to the parent data once the symbol mapping - # of the node is applied, so instead of mapping 1:1, the symbols could also be - # renamed to fresh names that are mapped back onto the parent symbols, which is - # what previous versions of this code did. However, with renamed symbols, each - # object that crosses the scope boundary, e.g. a descriptor, an offset or a - # subset, would have to be rewritten through that rename map, and so on for each - # level of nesting. The 1:1 mapping avoids all of these rewrites: it is the reason - # why we can simply insert the objects, e.g. the data descriptors and the access - # patterns, from the parent SDFG into the nested SDFG as they are. The price is - # that a name clash, i.e. the nested SDFG uses the name of a symbol for something - # else, either a data container or a symbol, including one it assigns itself or - # binds as a map parameter, has to be resolved by renaming that symbol inside, - # which is done below. parent_symbol_types: dict[str, dace.dtypes.typeclass] = { psym: state.sdfg.symbols[psym] for parent_prod_spec in parent_producer_specs for psym in parent_prod_spec.free_symbols } - # In order to not scan the whole nested SDFG once per symbol, the renames of all - # conflicting symbols are first gathered and then applied in a single pass. - rename_dict: dict[str, str] = {} - symbols_to_map: set[str] = set() - taken_names: set[str] = set(parent_symbol_types) | inner_written_symbols - for psym in sorted(parent_symbol_types): - if ( - psym in nsdfg.symbols - and psym in symbol_mapping - and psym not in inner_written_symbols - and psym == str(symbol_mapping[psym]) - and nsdfg.symbols[psym] == parent_symbol_types[psym] - ): - # The symbol is already mapped 1:1 into the nested sdfg -> nothing to do. - continue - - if psym in nsdfg.arrays: - _rename_nested_data(state, nsdfg_node, psym, parent_to_nested_name_mapping) - elif psym in nsdfg.symbols or psym in symbol_mapping or psym in inner_written_symbols: - renamed_symbol = _find_new_nested_symbol(nsdfg, psym, taken_names) - rename_dict[psym] = renamed_symbol - taken_names.add(renamed_symbol) - symbols_to_map.add(psym) - - if rename_dict: - # A single pass renames all the conflicting symbols inside the nested SDFG. Note - # that if the nested SDFG bound the name as a map parameter, then the parameter - # is renamed together with all the uses of it inside its scope. - nsdfg.replace_dict(rename_dict) - for psym, renamed_symbol in rename_dict.items(): - if psym in symbol_mapping: - symbol_mapping[renamed_symbol] = symbol_mapping.pop(psym) - if psym in inner_written_symbols: - inner_written_symbols.discard(psym) - inner_written_symbols.add(renamed_symbol) - - for psym in sorted(symbols_to_map): - nsdfg.add_symbol(psym, parent_symbol_types[psym]) - symbol_mapping[psym] = psym + full_repl_dict: dict[str, str] = {} + taken_names: set[str] = set(parent_symbol_types) | inner_written_symbols | set(symbol_mapping) nested_initial_producer_specs: list[_ProducerSpec] = [] handled_data: dict[str, _ProducerSpec] = {} for parent_prod_spec in parent_producer_specs: parent_data_name = parent_prod_spec.data_name + repl_dict: dict[str, str] = {} + for psym in sorted(parent_prod_spec.free_symbols): + ptype = parent_symbol_types[psym] + if psym in full_repl_dict: + nested_symbol = full_repl_dict[psym] + assert nested_symbol in nsdfg.symbols and nsdfg.symbols[nested_symbol] == ptype + elif ( + psym not in inner_written_symbols + and psym in symbol_mapping + and psym == str(symbol_mapping[psym]) + and psym in nsdfg.symbols + and nsdfg.symbols[psym] == ptype + ): + nested_symbol = psym + else: + reserved_names = taken_names + if ( + nsdfg.is_name_free(psym) + and psym not in inner_written_symbols + and psym not in symbol_mapping + ): + nested_symbol = psym + else: + nested_symbol = _find_new_nested_symbol(nsdfg, psym, reserved_names) + nsdfg.add_symbol(nested_symbol, ptype) + assert nested_symbol not in symbol_mapping + symbol_mapping[nested_symbol] = psym + taken_names.add(nested_symbol) + + if psym != nested_symbol: + repl_dict[psym] = nested_symbol + full_repl_dict.setdefault(psym, nested_symbol) + # Compute the nested data descriptor. if parent_data_name in handled_data: # The data has already been handled before. So we can simply reuse it. @@ -804,11 +784,17 @@ def _configure_descending_point( else: # The data is not yet mapped into the nested SDFG, so we have to create - # a new one, and we have to make sure that it is a global. Per the policy - # described above, the descriptor is written with the parent's symbols as - # is. The symbol clashes have been handled there, so this is safe. + # a new one, and we have to make sure that it is a global. Its symbols are + # renamed to the corresponding nested symbols. nested_desc = parent_prod_spec.desc.clone() nested_desc.transient = False + if repl_dict: + dace_sym.safe_replace( + mapping=repl_dict, + replace_callback=functools.partial( + dace.sdfg.replace_properties_dict, nested_desc + ), + ) nested_data_name = nsdfg.add_datadesc(parent_data_name, nested_desc, find_new_name=True) # We also need to map it into the nested SDFG. @@ -828,11 +814,17 @@ def _configure_descending_point( nested_data_name, dtype=dace.pointer(nested_desc.dtype) ) + nested_offset = copy.deepcopy(parent_prod_spec.offset) + nested_subset = copy.deepcopy(parent_prod_spec.subset) + if repl_dict: + for nested_set in [nested_offset, nested_subset]: + dace_sym.safe_replace(mapping=repl_dict, replace_callback=nested_set.replace) + nested_initial_producer_specs.append( _ProducerSpec( data_name=nested_data_name, - offset=copy.deepcopy(parent_prod_spec.offset), - subset=copy.deepcopy(parent_prod_spec.subset), + offset=nested_offset, + subset=nested_subset, desc=nested_desc, data_source={}, # Intentionally empty. ) @@ -858,50 +850,6 @@ def _find_new_nested_symbol(nsdfg: dace.SDFG, name: str, reserved: Collection[st taken.add(new_name) -def _rename_nested_data( - state: dace.SDFGState, - nsdfg_node: dace_nodes.NestedSDFG, - data_name: str, - parent_to_nested_name_mapping: dict[str, str], -) -> None: - """Renames the data container `data_name` inside the nested SDFG `nsdfg_node`. - - If the data is mapped into the nested SDFG, the connector of `nsdfg_node` is - renamed as well. The edges in `state` are modified in place, thus references to - them, such as `_FinalConsumerSpec.edge`, remain valid. `parent_to_nested_name_mapping` - is updated in place. - - Args: - state: The state containing `nsdfg_node`. - nsdfg_node: The nested SDFG in which the data should be renamed. - data_name: The name of the data inside the nested SDFG. - parent_to_nested_name_mapping: Maps the names of the data in the parent SDFG - to the names of the data inside the nested SDFG. - """ - nsdfg: dace.SDFG = nsdfg_node.sdfg - new_data_name = _find_new_nested_symbol(nsdfg, data_name, nsdfg.arrays.keys()) - dace_replace_datadesc_names(nsdfg, {data_name: new_data_name}) - - for parent_data_name, nested_data_name in parent_to_nested_name_mapping.items(): - if nested_data_name == data_name: - parent_to_nested_name_mapping[parent_data_name] = new_data_name - - if data_name in nsdfg_node.in_connectors: - conn_type = nsdfg_node.in_connectors[data_name] - nsdfg_node.remove_in_connector(data_name) - nsdfg_node.add_in_connector(new_data_name, dtype=conn_type) - for iedge in state.in_edges(nsdfg_node): - if iedge.dst_conn == data_name: - iedge.dst_conn = new_data_name - if data_name in nsdfg_node.out_connectors: - conn_type = nsdfg_node.out_connectors[data_name] - nsdfg_node.remove_out_connector(data_name) - nsdfg_node.add_out_connector(new_data_name, dtype=conn_type) - for oedge in state.out_edges(nsdfg_node): - if oedge.src_conn == data_name: - oedge.src_conn = new_data_name - - def _map_data_into_nested_scopes( state: dace.SDFGState, scope_dict: Mapping[dace_nodes.Node, _ScopeLocation], diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py index c4ba724386..b53d952522 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_concat_where_replacer.py @@ -1545,15 +1545,14 @@ def test_concat_where_nested_symbolic_bound( assert state.in_degree(nested_sdfg) == 2 if has_blocking_symbol: - # `split_sym` is mapped 1:1 into the nested SDFG, so the symbol that the nested - # SDFG used under this name, for the increment, has been renamed. + # The nested symbol keeps its original mapping, and the parent symbol is mapped + # through a fresh name. assert len(nested_sdfg.symbol_mapping) == 2 - assert str(nested_sdfg.symbol_mapping[split_sym]) == split_sym - - renamed_inc_symb = next( + assert str(nested_sdfg.symbol_mapping[split_sym]) == inc_symb + mapped_parent_symb = next( iter(ss for s in nested_sdfg.symbol_mapping if (ss := str(s)) != split_sym) ) - assert str(nested_sdfg.symbol_mapping[renamed_inc_symb]) == inc_symb + assert str(nested_sdfg.symbol_mapping[mapped_parent_symb]) == split_sym else: assert nested_sdfg.symbol_mapping.keys() == {nested_inc_symb, split_sym} @@ -1659,15 +1658,14 @@ def test_concat_where_with_symbolic_top_size(): assert concat_node.data not in sdfg.arrays assert state.in_degree(nested_sdfg) == 2 - # `symbolic_size` is mapped 1:1 into the nested SDFG, so the symbol that the nested - # SDFG used under this name, for the increment, has been renamed. + # The nested symbol keeps its original mapping, and the parent symbol is mapped + # through a fresh name. assert len(nested_sdfg.symbol_mapping) == 2 - assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size - - renamed_inc_symb = next( - iter(ss for s in nested_sdfg.symbol_mapping if (ss := str(s)) != symbolic_size) + assert str(nested_sdfg.symbol_mapping[nested_inc_symb]) == inc_symb + mapped_parent_symb = next( + iter(ss for s in nested_sdfg.symbol_mapping if (ss := str(s)) != nested_inc_symb) ) - assert str(nested_sdfg.symbol_mapping[renamed_inc_symb]) == inc_symb + assert str(nested_sdfg.symbol_mapping[mapped_parent_symb]) == symbolic_size csdfg = util.compile_and_run_sdfg(sdfg, **res) assert util.compare_sdfg_res(ref=ref, res=res) @@ -1722,12 +1720,14 @@ def test_concat_where_with_symbolic_size_clashing_with_nested_data(): assert c.data not in sdfg.arrays assert state.in_degree(nested_sdfg) == 2 - assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size - assert symbolic_size in nested_sdfg.sdfg.symbols - - # The output connector, and the data inside the nested SDFG, has been renamed. - assert symbolic_size not in nested_sdfg.sdfg.arrays - assert symbolic_size not in nested_sdfg.out_connectors + # The nested data and connector keep their names; the imported symbol uses a fresh + # name instead. + mapped_parent_symb = next( + sym for sym, value in nested_sdfg.symbol_mapping.items() if str(value) == symbolic_size + ) + assert str(mapped_parent_symb) != symbolic_size + assert symbolic_size in nested_sdfg.sdfg.arrays + assert symbolic_size in nested_sdfg.out_connectors oedge = next(iter(state.out_edges(nested_sdfg))) assert oedge.dst is d assert oedge.src_conn in nested_sdfg.out_connectors @@ -1785,15 +1785,18 @@ def test_concat_where_with_symbolic_size_clashing_with_nested_assignment(): sdfg.validate() assert c.data not in sdfg.arrays - assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size + mapped_parent_symb = next( + sym for sym, value in nested_sdfg.symbol_mapping.items() if str(value) == symbolic_size + ) + assert str(mapped_parent_symb) != symbolic_size - # The symbol assigned inside the nested SDFG has been renamed. + # The symbol assigned inside the nested SDFG keeps its name and meaning. (assignments,) = [ isedge.data.assignments for isedge in nested_sdfg.sdfg.all_interstate_edges() if isedge.data.assignments ] - assert symbolic_size not in assignments + assert symbolic_size in assignments assert list(assignments.values()) == ["7"] util.compile_and_run_sdfg(sdfg, **res) @@ -1802,11 +1805,9 @@ def test_concat_where_with_symbolic_size_clashing_with_nested_assignment(): def test_concat_where_with_symbolic_size_clashing_with_nested_map_param(): # The symbol `n`, that defines the size of the producer `a`, has to be mapped into - # the nested SDFG, which binds `n` as the parameter of one of its maps. A map - # parameter shadows any outer symbol of the same name, so the map parameter has to - # be renamed inside the nested SDFG, together with all its uses, this also tests - # that `replace_dict()` performs these renames consistently (in particular the - # parameter of the map itself). + # the nested SDFG, which binds `n` as the parameter of one of its maps. Since map + # parameters shadow symbols with the same name, the imported symbol must use a + # distinct name and leave the map parameter and its uses unchanged. symbolic_size = "n" nested = dace.SDFG("nested") @@ -1853,31 +1854,19 @@ def test_concat_where_with_symbolic_size_clashing_with_nested_map_param(): assert c.data not in sdfg.arrays assert state.in_degree(nested_sdfg) == 2 - # `n` is now mapped 1:1 into the nested SDFG... - assert str(nested_sdfg.symbol_mapping[symbolic_size]) == symbolic_size - assert nested_sdfg.sdfg.symbols[symbolic_size] == dace.int32 + # The parent symbol is mapped through a fresh name, leaving the map parameter alone. + mapped_parent_symb = next( + sym for sym, value in nested_sdfg.symbol_mapping.items() if str(value) == symbolic_size + ) + assert str(mapped_parent_symb) != symbolic_size + assert nested_sdfg.sdfg.symbols[mapped_parent_symb] == dace.int32 - # ... and the map parameter, which used the name inside the nested SDFG, has been - # renamed, together with all of its uses. The consistency of the renaming (in - # particular of the uses inside the map scope) is verified by the compile and run. + # The map parameter and all its uses retain their names. The imported symbol uses a + # distinct name and is exercised by the compile and run below. map_entries = util.count_nodes(nested_sdfg.sdfg, dace_nodes.MapEntry, True) assert len(map_entries) >= 1 - renamed_params = {param for me in map_entries for param in me.params} - assert symbolic_size not in renamed_params - assert all(param.startswith(symbolic_size + "_") for param in renamed_params) - (renamed_param,) = renamed_params - used_inside = { - str(fs) - for state_ in nested_sdfg.sdfg.states() - for edge in state_.edges() - for fs in edge.data.free_symbols - } - used_inside |= { - str(fs) - for tlet in util.count_nodes(nested_sdfg.sdfg, dace_nodes.Tasklet, True) - for fs in tlet.free_symbols - } - assert renamed_param in used_inside + map_params = {param for me in map_entries for param in me.params} + assert symbolic_size in map_params util.compile_and_run_sdfg(sdfg, **res) assert util.compare_sdfg_res(ref=ref, res=res) From b8a86f40d91dfbd65ef2262b9b01f91f9830f255 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 30 Oct 2026 14:57:39 +0100 Subject: [PATCH 62/69] edit --- .../runners/dace/transformations/concat_where_mapper.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py index 08b48bd5aa..978e67f4ee 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/concat_where_mapper.py @@ -751,7 +751,6 @@ def _configure_descending_point( ): nested_symbol = psym else: - reserved_names = taken_names if ( nsdfg.is_name_free(psym) and psym not in inner_written_symbols @@ -759,7 +758,7 @@ def _configure_descending_point( ): nested_symbol = psym else: - nested_symbol = _find_new_nested_symbol(nsdfg, psym, reserved_names) + nested_symbol = _find_new_nested_symbol(nsdfg, psym, taken_names) nsdfg.add_symbol(nested_symbol, ptype) assert nested_symbol not in symbol_mapping symbol_mapping[nested_symbol] = psym From 5bb48efceb35f9f9a5413a2576ac68a986dd0ff2 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 30 Oct 2026 17:22:57 +0100 Subject: [PATCH 63/69] call integrate_into_parent only on root SDFG --- .../runners/dace/lowering/gtir_to_sdfg.py | 52 ++++++++++++------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py index f677559fa2..97c6b5380b 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py @@ -563,6 +563,11 @@ class GTIRToSDFG(eve.NodeVisitor, SDFGBuilder): from where to continue building the SDFG. """ + # The root SDFG, created by the caller and extended in place by the lowering. + # Used to decide when a let-lambda's nested SDFG should be integrated into its + # parent: only the top-level ones are, the rest are integrated by dace's + # top-down cascade. + sdfg: dace.SDFG offset_provider_type: gtx_common.OffsetProviderType column_axis: Optional[gtx_common.Dimension] uids: gtx_utils.IDGeneratorPool = dataclasses.field( @@ -1061,8 +1066,11 @@ def _add_sdfg_params( # the list of all sdfg arguments (aka non-transient arrays) which include tuple-element fields return [arg_name for arg_name, _ in sdfg_args] - def visit_Program(self, node: gtir.Program) -> dace.SDFG: - """Translates `ir.Program` to `dace.SDFG`. + def lower_program(self, node: gtir.Program) -> None: + """Lowers `ir.Program` to `dace.SDFG`. This is the entry point of the lowering. + + The root SDFG is created by the caller and passed to the constructor; + the translation extends it in place. First, it will allocate field and scalar storage for global data. The storage represents global data, available everywhere in the SDFG, either containing @@ -1070,30 +1078,27 @@ def visit_Program(self, node: gtir.Program) -> dace.SDFG: The temporary data is global, therefore available everywhere in the SDFG but not outside. Then, all statements are translated, one after the other. """ - sdfg = dace.SDFG(str(node.id)) - sdfg.debuginfo = gtir_to_sdfg_utils.debug_info(node) - # start block of the stateful graph - head_state = sdfg.add_state("program_entry", is_start_block=True) + head_state = self.sdfg.add_state("program_entry", is_start_block=True) # By passing `symbolic_arguments=None` all scalars are represented as dace symbols. # We do this to allow lowering of scalar expressions in let-statements, # that only depend on scalar parameters, as dace symbolic expressions # mapped to symbols on a nested SDFG. sdfg_arg_names = self._add_sdfg_params( - sdfg, node.params, symbolic_params=None, use_transient_storage=False + self.sdfg, node.params, symbolic_params=None, use_transient_storage=False ) # visit one statement at a time and expand the SDFG from the current head state scope_symbols = {str(p.id): p.type for p in node.params if isinstance(p.type, ts.DataType)} for i, stmt in enumerate(node.body): # include `debuginfo` only for `ir.Program` and `ir.Stmt` nodes: finer granularity would be too messy - head_state = sdfg.add_state_after(head_state, f"stmt_{i}") - head_state._debuginfo = gtir_to_sdfg_utils.debug_info(stmt, default=sdfg.debuginfo) - head_state = self.visit(stmt, ctx=SubgraphContext(sdfg, head_state, scope_symbols)) + head_state = self.sdfg.add_state_after(head_state, f"stmt_{i}") + head_state._debuginfo = gtir_to_sdfg_utils.debug_info(stmt, default=self.sdfg.debuginfo) + head_state = self.visit(stmt, ctx=SubgraphContext(self.sdfg, head_state, scope_symbols)) # remove unused connectivity tables (by design, arrays are marked as non-transient when they are used) - for nsdfg in sdfg.all_sdfgs_recursive(): + for nsdfg in self.sdfg.all_sdfgs_recursive(): unused_connectivities = [ data for data, datadesc in nsdfg.arrays.items() @@ -1108,9 +1113,9 @@ def visit_Program(self, node: gtir.Program) -> dace.SDFG: # Only the arguments required by the GT4Py program, i.e. `node.params`, are added # as positional arguments. The implicit arguments, such as the offset providers or # the arguments created by the translation process, must be passed as keyword arguments. - sdfg.arg_names = sdfg_arg_names + self.sdfg.arg_names = sdfg_arg_names - return sdfg + self.sdfg.validate() def visit_SetAt(self, stmt: gtir.SetAt, ctx: SubgraphContext) -> dace.SDFGState: """Visits a `SetAt` statement expression and writes the local result to some external storage. @@ -1393,7 +1398,16 @@ def construct_output_for_nested_sdfg( # Now that the nested SDFG is connected, its connectors are made equivalent to # the data connected to them, by applying the symbol mapping inside it. - nsdfg_node.integrate_into_parent() + # + # Only the top-level let-lambda nested SDFGs (those whose parent is the root + # SDFG) are integrated here. Nested lets whose parent is itself a nested SDFG + # are left for dace to integrate through the top-down cascade triggered by the + # top-level integration (`fold_symbol_mapping` -> `integrate_nested_sdfgs_within`). + # Integrating every level eagerly, bottom-up, would reprocess the whole subtree + # below each level once per nesting level, which is quadratic in the let-chain + # depth. + if ctx.sdfg is self.sdfg: + nsdfg_node.integrate_into_parent() return result @@ -1446,9 +1460,9 @@ def lower_program_to_sdfg( # Here we find new names for invalid symbols present in the IR. ir = gtir_to_sdfg_utils.replace_invalid_symbols(ir) - sdfg_genenerator = GTIRToSDFG(offset_provider_type, column_axis) - sdfg = sdfg_genenerator.visit(ir) - assert isinstance(sdfg, dace.SDFG) - - sdfg.validate() + # The root SDFG is created here and passed to the lowering visitor, which + # extends it in place while translating the program. + sdfg = dace.SDFG(str(ir.id)) + sdfg_generator = GTIRToSDFG(sdfg, offset_provider_type, column_axis) + sdfg_generator.lower_program(ir) return sdfg From d08177b5754509d01acdd27f569a97f04d8c2225 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 30 Oct 2026 18:07:40 +0100 Subject: [PATCH 64/69] Revert "call integrate_into_parent only on root SDFG" This reverts commit 5bb48efceb35f9f9a5413a2576ac68a986dd0ff2. --- .../runners/dace/lowering/gtir_to_sdfg.py | 52 +++++++------------ 1 file changed, 19 insertions(+), 33 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py index 97c6b5380b..f677559fa2 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py @@ -563,11 +563,6 @@ class GTIRToSDFG(eve.NodeVisitor, SDFGBuilder): from where to continue building the SDFG. """ - # The root SDFG, created by the caller and extended in place by the lowering. - # Used to decide when a let-lambda's nested SDFG should be integrated into its - # parent: only the top-level ones are, the rest are integrated by dace's - # top-down cascade. - sdfg: dace.SDFG offset_provider_type: gtx_common.OffsetProviderType column_axis: Optional[gtx_common.Dimension] uids: gtx_utils.IDGeneratorPool = dataclasses.field( @@ -1066,11 +1061,8 @@ def _add_sdfg_params( # the list of all sdfg arguments (aka non-transient arrays) which include tuple-element fields return [arg_name for arg_name, _ in sdfg_args] - def lower_program(self, node: gtir.Program) -> None: - """Lowers `ir.Program` to `dace.SDFG`. This is the entry point of the lowering. - - The root SDFG is created by the caller and passed to the constructor; - the translation extends it in place. + def visit_Program(self, node: gtir.Program) -> dace.SDFG: + """Translates `ir.Program` to `dace.SDFG`. First, it will allocate field and scalar storage for global data. The storage represents global data, available everywhere in the SDFG, either containing @@ -1078,27 +1070,30 @@ def lower_program(self, node: gtir.Program) -> None: The temporary data is global, therefore available everywhere in the SDFG but not outside. Then, all statements are translated, one after the other. """ + sdfg = dace.SDFG(str(node.id)) + sdfg.debuginfo = gtir_to_sdfg_utils.debug_info(node) + # start block of the stateful graph - head_state = self.sdfg.add_state("program_entry", is_start_block=True) + head_state = sdfg.add_state("program_entry", is_start_block=True) # By passing `symbolic_arguments=None` all scalars are represented as dace symbols. # We do this to allow lowering of scalar expressions in let-statements, # that only depend on scalar parameters, as dace symbolic expressions # mapped to symbols on a nested SDFG. sdfg_arg_names = self._add_sdfg_params( - self.sdfg, node.params, symbolic_params=None, use_transient_storage=False + sdfg, node.params, symbolic_params=None, use_transient_storage=False ) # visit one statement at a time and expand the SDFG from the current head state scope_symbols = {str(p.id): p.type for p in node.params if isinstance(p.type, ts.DataType)} for i, stmt in enumerate(node.body): # include `debuginfo` only for `ir.Program` and `ir.Stmt` nodes: finer granularity would be too messy - head_state = self.sdfg.add_state_after(head_state, f"stmt_{i}") - head_state._debuginfo = gtir_to_sdfg_utils.debug_info(stmt, default=self.sdfg.debuginfo) - head_state = self.visit(stmt, ctx=SubgraphContext(self.sdfg, head_state, scope_symbols)) + head_state = sdfg.add_state_after(head_state, f"stmt_{i}") + head_state._debuginfo = gtir_to_sdfg_utils.debug_info(stmt, default=sdfg.debuginfo) + head_state = self.visit(stmt, ctx=SubgraphContext(sdfg, head_state, scope_symbols)) # remove unused connectivity tables (by design, arrays are marked as non-transient when they are used) - for nsdfg in self.sdfg.all_sdfgs_recursive(): + for nsdfg in sdfg.all_sdfgs_recursive(): unused_connectivities = [ data for data, datadesc in nsdfg.arrays.items() @@ -1113,9 +1108,9 @@ def lower_program(self, node: gtir.Program) -> None: # Only the arguments required by the GT4Py program, i.e. `node.params`, are added # as positional arguments. The implicit arguments, such as the offset providers or # the arguments created by the translation process, must be passed as keyword arguments. - self.sdfg.arg_names = sdfg_arg_names + sdfg.arg_names = sdfg_arg_names - self.sdfg.validate() + return sdfg def visit_SetAt(self, stmt: gtir.SetAt, ctx: SubgraphContext) -> dace.SDFGState: """Visits a `SetAt` statement expression and writes the local result to some external storage. @@ -1398,16 +1393,7 @@ def construct_output_for_nested_sdfg( # Now that the nested SDFG is connected, its connectors are made equivalent to # the data connected to them, by applying the symbol mapping inside it. - # - # Only the top-level let-lambda nested SDFGs (those whose parent is the root - # SDFG) are integrated here. Nested lets whose parent is itself a nested SDFG - # are left for dace to integrate through the top-down cascade triggered by the - # top-level integration (`fold_symbol_mapping` -> `integrate_nested_sdfgs_within`). - # Integrating every level eagerly, bottom-up, would reprocess the whole subtree - # below each level once per nesting level, which is quadratic in the let-chain - # depth. - if ctx.sdfg is self.sdfg: - nsdfg_node.integrate_into_parent() + nsdfg_node.integrate_into_parent() return result @@ -1460,9 +1446,9 @@ def lower_program_to_sdfg( # Here we find new names for invalid symbols present in the IR. ir = gtir_to_sdfg_utils.replace_invalid_symbols(ir) - # The root SDFG is created here and passed to the lowering visitor, which - # extends it in place while translating the program. - sdfg = dace.SDFG(str(ir.id)) - sdfg_generator = GTIRToSDFG(sdfg, offset_provider_type, column_axis) - sdfg_generator.lower_program(ir) + sdfg_genenerator = GTIRToSDFG(offset_provider_type, column_axis) + sdfg = sdfg_genenerator.visit(ir) + assert isinstance(sdfg, dace.SDFG) + + sdfg.validate() return sdfg From c216d37d95e6fc1ebdfa7d1cf596d9b04a9f31db Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Mon, 2 Nov 2026 10:55:13 +0100 Subject: [PATCH 65/69] remove call to NestedSDFG.integrate_into_parent() --- .../runners/dace/lowering/gtir_to_sdfg.py | 4 --- .../dace/lowering/gtir_to_sdfg_scan.py | 4 --- .../remove_access_node_copies.py | 1 - .../transformation_tests/test_strides.py | 32 ++++++++++--------- 4 files changed, 17 insertions(+), 24 deletions(-) diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py index f677559fa2..1ecf34e1a4 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg.py @@ -1391,10 +1391,6 @@ def construct_output_for_nested_sdfg( result = gtx_utils.tree_map(construct_output_for_nested_sdfg)(lambda_result) - # Now that the nested SDFG is connected, its connectors are made equivalent to - # the data connected to them, by applying the symbol mapping inside it. - nsdfg_node.integrate_into_parent() - return result def visit_Literal( diff --git a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py index 747353b4e7..062cc12c3e 100644 --- a/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py +++ b/src/gt4py/next/program_processors/runners/dace/lowering/gtir_to_sdfg_scan.py @@ -583,8 +583,4 @@ def translate_scan_fieldop( inner_dims=(scan_dim,), ) - # Now that the nested SDFG is connected, its connectors are made equivalent to - # the data connected to them, by applying the symbol mapping inside it. - nsdfg_node.integrate_into_parent() - return result diff --git a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py index 3f48fa6763..41e5d0cd4e 100644 --- a/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py +++ b/src/gt4py/next/program_processors/runners/dace/transformations/remove_access_node_copies.py @@ -282,4 +282,3 @@ def apply( outer_desc, ss_offset=tuple(node_offset), ) - node.integrate_into_parent() diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py index 681e8ef3ed..a793ec5993 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/transformation_tests/test_strides.py @@ -101,7 +101,6 @@ def _make_strides_propagation_level2_sdfg() -> tuple[dace.SDFG, dace_nodes.Neste state.add_edge(state.add_access("a2"), None, nsdfg, "a3", dace.Memlet("a2[0:10]")) state.add_edge(nsdfg, "c3", state.add_access("c2"), None, dace.Memlet("c2[0:10]")) - nsdfg.integrate_into_parent() sdfg.validate() return sdfg, nsdfg @@ -169,7 +168,6 @@ def _make_strides_propagation_level1_sdfg() -> tuple[ dace.Memlet(f"{outer_name}[0:10]"), ) - nsdfg_level2.integrate_into_parent() sdfg.validate() return sdfg, nsdfg_level2, nsdfg_level3 @@ -189,11 +187,13 @@ def test_strides_propagation(): sdfg_level1, nsdfg_level2, nsdfg_level3 = _make_strides_propagation_level1_sdfg() all_sdfgs = [sdfg_level1, nsdfg_level2.sdfg, nsdfg_level3.sdfg] - # Since the connectors are equivalent to the data they are connected to, all - # levels use the stride symbols of the top level. + # Tests if all strides are distinct in the beginning and match what we expect. for sdfg in all_sdfgs: for aname, adesc in sdfg.arrays.items(): - assert [str(s) for s in adesc.strides] == [f"{aname[0]}1_stride"] + exp_stride = f"{aname}_stride" + assert [str(s) for s in adesc.strides] == [exp_stride], ( + f"Expected that '{aname}' has strides '{exp_stride}', but found '{adesc.strides}'." + ) # Now we propagate `a` and `b`, but not `c`. for data in ["a", "b"]: @@ -206,12 +206,12 @@ def test_strides_propagation(): # The new strides have been propagated to all levels, including `a2_alias`, which is # also connected to `a1`. Inside the nested SDFGs the new symbol is mapped 1:1. - for sdfg in all_sdfgs: + for i, sdfg in enumerate(all_sdfgs): assert set(_get_stride_of(sdfg, "a").values()) == {"a1_new_stride"} assert set(_get_stride_of(sdfg, "b").values()) <= {"b1_new_stride"} - assert set(_get_stride_of(sdfg, "c").values()) == {"c1_stride"} + assert set(_get_stride_of(sdfg, "c").values()) == {f"c{i + 1}_stride"} if (nsdfg := sdfg.parent_nsdfg_node) is not None: - assert str(nsdfg.symbol_mapping["a1_new_stride"]) == "a1_new_stride" + assert nsdfg.symbol_mapping["a1_new_stride"].name == "a1_new_stride" # Now we also change and propagate the strides of `c1`. sdfg_level1.add_symbol("c1_new_stride", dace.int32) @@ -256,6 +256,7 @@ def _make_strides_propagation_dependent_symbol_sdfg() -> tuple[dace.SDFG, dace_n sdfg_level1 = dace.SDFG(util.unique_name("strides_propagation_dependent_symbol_sdfg")) state = sdfg_level1.add_state(is_start_block=True) + symbol_mapping = {} array_names = ["a1", "b1"] for name in array_names: stride_sym = dace.symbol(f"{name}_stride", dtype=dace.uint32) @@ -267,17 +268,17 @@ def _make_strides_propagation_dependent_symbol_sdfg() -> tuple[dace.SDFG, dace_n strides=(stride_sym,), transient=False, ) + symbol_mapping[f"{name.replace('1', '2')}_stride"] = stride_sym nsdfg = state.add_nested_sdfg( sdfg=_make_strides_propagation_dependent_symbol_nsdfg(), inputs={"a2"}, outputs={"b2"}, - symbol_mapping={"a2_stride": "a1_stride", "b2_stride": "b1_stride"}, + symbol_mapping=symbol_mapping, ) state.add_edge(state.add_access("a1"), None, nsdfg, "a2", dace.Memlet("a1[0:10]")) state.add_edge(nsdfg, "b2", state.add_access("b1"), None, dace.Memlet("b1[0:10]")) - nsdfg.integrate_into_parent() sdfg_level1.validate() return sdfg_level1, nsdfg @@ -287,6 +288,9 @@ def test_strides_propagation_symbolic_expression(): sdfg_level1, nsdfg_level2 = _make_strides_propagation_dependent_symbol_sdfg() # Now change the strides of `a1` and `b1` to a symbolic expression. + # NOTE: the stride change and the propagation are done one array at a time, + # because in between, i.e. after changing the strides of `b1`, but before + # propagating it, the SDFG is invalid. for aname, adesc in sdfg_level1.arrays.items(): stride_sym1 = dace.symbol(f"{aname}_1stride", dtype=dace.uint32) stride_sym2 = dace.symbol(f"{aname}_2stride", dtype=dace.int32) @@ -299,10 +303,8 @@ def test_strides_propagation_symbolic_expression(): assert sym not in nsdfg_level2.symbol_mapping assert sym not in nsdfg_level2.sdfg.symbols - # Now propagate `a1` and `b1`. - gtx_transformations.gt_propagate_strides_of(sdfg_level1, "a1") - gtx_transformations.gt_propagate_strides_of(sdfg_level1, "b1") - sdfg_level1.validate() + gtx_transformations.gt_propagate_strides_of(sdfg_level1, aname) + sdfg_level1.validate() # The inner descriptors use the same expression, and the symbols that appear in # it have been mapped 1:1 into the nested SDFG, keeping their type. @@ -311,7 +313,7 @@ def test_strides_propagation_symbolic_expression(): assert adesc2.strides == adesc.strides for sym, dtype in [(f"{aname}_1stride", dace.uint32), (f"{aname}_2stride", dace.int32)]: - assert str(nsdfg_level2.symbol_mapping[sym]) == sym + assert nsdfg_level2.symbol_mapping[sym].name == sym assert nsdfg_level2.sdfg.symbols[sym] == dtype From 71a271b40c0cdaa5b75ddbf4cb99735d48a97e29 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 3 Dec 2026 14:04:19 +0100 Subject: [PATCH 66/69] update uv lock --- uv.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/uv.lock b/uv.lock index a16e9f2121..1d94fa8a61 100644 --- a/uv.lock +++ b/uv.lock @@ -1011,8 +1011,8 @@ wheels = [ [[package]] name = "dace" -version = "2.0.0b1" -source = { git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev#37df7bdb5ca8454b7f2e7bf2109e60ca6594ea0e" } +version = "2.0.0b2" +source = { git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev#9d475bd3f2be3d0e526c19486475aa0770263056" } dependencies = [ { name = "astunparse" }, { name = "click" }, @@ -1435,7 +1435,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" }, From 6bdef6f6796d8316e33a2dff1b70d6355980a6ea Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Thu, 3 Dec 2026 15:17:05 +0100 Subject: [PATCH 67/69] fix test --- .../runners_tests/dace_tests/test_dace_translation.py | 4 ++-- 1 file changed, 2 insertions(+), 2 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 b44eac8564..4924a18dad 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 @@ -206,7 +206,7 @@ def test_translation_grid_type(grid_type): device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args=None, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=True, use_metrics=False, ) @@ -257,7 +257,7 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) device_type=core_defs.DeviceType.CPU, auto_optimize=False, auto_optimize_args=None, - async_sdfg_call=False, + sync_sdfg_call=True, unstructured_horizontal_has_unit_stride=has_unit_stride, use_metrics=False, disable_field_origin_on_program_arguments=disable_field_origin, From 4bdc046b470ee45ff4e8edee543ac83d8dc0fcb0 Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 4 Dec 2026 07:10:10 +0100 Subject: [PATCH 68/69] update uv lock --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index 1d94fa8a61..435cda549c 100644 --- a/uv.lock +++ b/uv.lock @@ -1012,7 +1012,7 @@ wheels = [ [[package]] name = "dace" version = "2.0.0b2" -source = { git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev#9d475bd3f2be3d0e526c19486475aa0770263056" } +source = { git = "https://github.com/spcl/dace?branch=new-gpu-codegen-dev#3aa2c595bea1368c20ae5fcf2a77a18e0d34c1be" } dependencies = [ { name = "astunparse" }, { name = "click" }, From 224513ca22828864cee64c08ef1e0393c5895f0b Mon Sep 17 00:00:00 2001 From: Edoardo Paone Date: Fri, 4 Dec 2026 07:54:02 +0100 Subject: [PATCH 69/69] fix[cartesian]: initialize DaCe GPU context in dace:gpu wrapper The generated wrapper allocates the DaCe state struct on the stack and calls `__program_` without `__dace_init_`, so `gpu_context` was left uninitialized. The experimental DaCe CUDA codegen reads its streams from `__state->gpu_context`, which made every dace:gpu stencil call segfault. The wrapper now creates a `dace::cuda::Context` sized as in DaCe's generated init code, with all streams set to the default stream, and raises on any GPU error the program recorded. The backend always selects the experimental CUDA codegen. --- src/gt4py/cartesian/backend/dace_backend.py | 72 ++++++++++++++++++- .../backend_tests/test_dace_backend.py | 28 +++++++- 2 files changed, 96 insertions(+), 4 deletions(-) diff --git a/src/gt4py/cartesian/backend/dace_backend.py b/src/gt4py/cartesian/backend/dace_backend.py index 68f75f6515..d0e51cd854 100644 --- a/src/gt4py/cartesian/backend/dace_backend.py +++ b/src/gt4py/cartesian/backend/dace_backend.py @@ -538,11 +538,65 @@ class DaCeComputationCodegen: auto allocator = gt::sid::cached_allocator(&${allocator}); ${"\\n".join(tmp_allocs)} __program_${name}(${",".join(["&dace_handle", *dace_args])}); + ${gpu_context_check} }; } """ ) + # The GPU state of a DaCe program lives in a `dace::cuda::Context` owned by the state struct. + # DaCe normally creates it in `__dace_init_()`, which this wrapper does not call (it + # allocates the state struct on the stack and calls `__program_()` directly), so the + # wrapper creates the context itself. All streams are the default (null) stream, matching + # `max_concurrent_streams = -1`; events are created only if the generated code requests any. + gpu_context_template = as_mako( + """\ +dace::cuda::Context gpu_context(${num_streams}, ${num_events}); +for (int i = 0; i < ${num_streams}; ++i) { + gpu_context.internal_streams[i] = nullptr; + gpu_context.streams[i] = nullptr; +} +for (int i = 0; i < ${num_events}; ++i) { + ${gpu_api}EventCreateWithFlags(&gpu_context.events[i], ${gpu_api}EventDisableTiming); +} +dace_handle.gpu_context = &gpu_context; +""" + ) + + gpu_context_check_template = as_mako( + """\ +for (int i = 0; i < ${num_events}; ++i) { + ${gpu_api}EventDestroy(gpu_context.events[i]); +} +if (gpu_context.lasterror != (gpuError_t)0) { + throw std::runtime_error( + std::string("GPU error in DaCe program '${name}': ") + + gpuGetErrorString(gpu_context.lasterror)); +} +""" + ) + + _GPU_CONTEXT_REGEX = re.compile(r"new\s+dace::cuda::Context\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)") + + @classmethod + def _gpu_context_size(cls, code_objects: list[codeobject.CodeObject]) -> tuple[int, int]: + """Return the number of streams and events of the GPU context DaCe generated code expects. + + Args: + code_objects: Code objects generated by DaCe for a GPU SDFG. + + Returns: + A `(num_streams, num_events)` tuple, as passed to `dace::cuda::Context` in the + generated initialization code. + + Raises: + RuntimeError: If the generated code does not create a GPU context. + """ + for co in code_objects: + if match := cls._GPU_CONTEXT_REGEX.search(co.clean_code): + return int(match.group(1)), int(match.group(2)) + raise RuntimeError("DaCe generated GPU code does not create a 'dace::cuda::Context'.") + def generate_tmp_allocs(self, sdfg: SDFG) -> list[str]: global_fmt = ( "__{sdfg_id}_{name} = allocate(allocator, gt::meta::lazy::id<{dtype}>(), {size})();" @@ -624,6 +678,7 @@ def apply(cls, builder: StencilBuilder, sdfg: SDFG) -> str: # changes be under the temporary_config manager if core_defs.CUPY_DEVICE_TYPE == core_defs.DeviceType.ROCM: config.Config.set("compiler", "cuda", "backend", value="hip") + config.Config.set("compiler", "cuda", "implementation", value="experimental") config.Config.set("compiler", "cuda", "max_concurrent_streams", value=-1) config.Config.set( "compiler", @@ -660,9 +715,22 @@ def apply(cls, builder: StencilBuilder, sdfg: SDFG) -> str: omp_threads = "" omp_header = "" + backend_specifics = omp_threads + gpu_context_check = "" + if is_gpu: + num_streams, num_events = cls._gpu_context_size(code_objects) + gpu_api = "hip" if core_defs.CUPY_DEVICE_TYPE == core_defs.DeviceType.ROCM else "cuda" + backend_specifics = cls.gpu_context_template.definition.render( + num_streams=num_streams, num_events=num_events, gpu_api=gpu_api + ) + gpu_context_check = cls.gpu_context_check_template.definition.render( + name=sdfg.name, num_events=num_events, gpu_api=gpu_api + ) + interface = cls.template.definition.render( name=sdfg.name, - backend_specifics=omp_threads, + backend_specifics=backend_specifics, + gpu_context_check=gpu_context_check, dace_args=self.generate_dace_args(builder.gtir, sdfg), functor_args=self.generate_functor_args(sdfg), tmp_allocs=self.generate_tmp_allocs(sdfg), @@ -674,7 +742,7 @@ def apply(cls, builder: StencilBuilder, sdfg: SDFG) -> str: #include #include #include -{"#include " if is_gpu else omp_header} +{"#include \n#include \n#include " if is_gpu else omp_header} namespace gt = gridtools; {computations} diff --git a/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py b/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py index b75149bf93..fb3aebfe94 100644 --- a/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py +++ b/tests/cartesian_tests/unit_tests/backend_tests/test_dace_backend.py @@ -7,14 +7,16 @@ # SPDX-License-Identifier: BSD-3-Clause import os +import re + import pytest -from dace import nodes +from dace import config as dace_config, nodes from dace.sdfg.state import LoopRegion import dace.sdfg.analysis.schedule_tree.treenodes as tn from gt4py.cartesian import backend -from gt4py.cartesian.backend.dace_backend import SDFGManager +from gt4py.cartesian.backend.dace_backend import DaCeExtGenerator, SDFGManager from gt4py.cartesian.gtscript import computation, PARALLEL, interval, Field from gt4py.cartesian.stencil_builder import StencilBuilder from gt4py.cartesian.gtc.dace.treeir import Axis @@ -221,3 +223,25 @@ def test_dace_cpu_KJI_loop_structure_parallel(): loop_region = for_nested_nodes[0] assert isinstance(loop_region, LoopRegion) assert loop_region.loop_variable == Axis.K.iteration_symbol() + + +def test_dace_gpu_codegen_initializes_gpu_context(): + # Code generation only: no GPU needed. + builder = StencilBuilder(copy_stencil, backend="dace:gpu") + with dace_config.temporary_config(): + # The backend must select the experimental codegen regardless of the user's DaCe config. + dace_config.Config.set("compiler", "cuda", "implementation", value="legacy") + sources = DaCeExtGenerator("Copy", "m_copy", builder.backend)() + code = sources["computation"]["computation.hpp"] + + assert "__dace_init_experimental_cuda" in code + + # The generated program reads its streams from `__state->gpu_context`, which the wrapper + # must set up because it never calls `__dace_init_()`. + match = re.search(r"new\s+dace::cuda::Context\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)", code) + assert match is not None + context_init = f"dace::cuda::Context gpu_context({match.group(1)}, {match.group(2)});" + context_attach = "dace_handle.gpu_context = &gpu_context;" + program_call = code.rindex("__program_copy_stencil(") + assert code.index(context_init) < code.index(context_attach) < program_call + assert "gpu_context.lasterror" in code[program_call:]