diff --git a/pyproject.toml b/pyproject.toml index a9daac3da0..32bb848171 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -270,6 +270,7 @@ markers = [ 'uses_scan: tests that uses scan', 'uses_scan_in_field_operator: tests that require backend support for scan in field operator', 'uses_scan_without_field_args: tests that require calls to scan that do not have any fields as arguments', + 'uses_scan_with_unstructured_shift: tests that combine a scan with an unstructured shift', 'uses_scan_nested: tests that use nested scans', 'uses_sparse_fields: tests that require backend support for sparse fields', 'uses_sparse_fields_as_output: tests that require backend support for writing sparse fields', diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 467b8132f9..b148d7aa23 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -42,6 +42,7 @@ class ScanOperator(EmbeddedOperator[xtyping.MaybeNestedInTuple[core_defs.ScalarT forward: bool init: xtyping.MaybeNestedInTuple[core_defs.ScalarT | common.Field] axis: common.Dimension + range: Optional[common.UnitRange] = None def __call__( # type: ignore[override] self, @@ -54,16 +55,19 @@ def __call__( # type: ignore[override] scan_axis = self.axis all_args = [*args, *kwargs.values()] domain_intersection = _intersect_scan_args(*all_args, self.init) - column_ranges = embedded_context.get_column_ranges() - if scan_axis not in column_ranges.dims: - raise errors.exceptions.EmbeddedExecutionError( - f"Scan axis '{scan_axis}' has no range, or ranges that differ, in the output domain." - ) - scan_range = column_ranges[scan_axis] - if scan_axis in domain_intersection.dims: - scan_range = common.NamedRange( - scan_axis, scan_range.unit_range & domain_intersection[scan_axis].unit_range - ) + if self.range is not None: + scan_range = common.NamedRange(scan_axis, self.range) + else: + column_ranges = embedded_context.get_column_ranges() + if scan_axis not in column_ranges.dims: + raise errors.exceptions.EmbeddedExecutionError( + f"Scan axis '{scan_axis}' has no range, or ranges that differ, in the output domain." + ) + scan_range = column_ranges[scan_axis] + if scan_axis in domain_intersection.dims: + scan_range = common.NamedRange( + scan_axis, scan_range.unit_range & domain_intersection[scan_axis].unit_range + ) non_scan_domain = common.Domain(*[nr for nr in domain_intersection if nr.dim != scan_axis]) out_domain = common.Domain( @@ -109,12 +113,6 @@ def scan_loop(hpos: Sequence[common.NamedIndex]) -> None: return res -def _get_out_domain(out: xtyping.MaybeNestedInTuple[common.MutableField]) -> common.Domain: - return embedded_common.domain_intersection( - *[f.domain for f in utils.flatten_nested_tuple((out,))] - ) - - def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) -> Optional[_R]: if "out" in kwargs: # called from program or direct field_operator as program @@ -145,7 +143,7 @@ def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) -> out_domain = ( utils.tree_map(common.domain)(domain) if domain is not None - else _get_out_domain(container_extracted_out) + else utils.tree_map(lambda f: f.domain)(container_extracted_out) ) new_context_kwargs["column_ranges"] = _get_vertical_ranges(out_domain) @@ -237,14 +235,17 @@ def impl(field: common.Field | array_ops.NDValue) -> array_ops.NDValue: def _scan( scan_pass: Callable, - axis: common.Dimension, + range: tuple[common.Dimension, int, int], # noqa: A002 # shadowing a Python built-in forward: bool, init: core_defs.Scalar | tuple, /, *args: Any, **kwargs: Any, ) -> common.Field | tuple: - return ScanOperator(scan_pass, forward, init, axis)(*args, **kwargs) + axis, start, stop = range + return ScanOperator(scan_pass, forward, init, axis, common.UnitRange(start, stop))( + *args, **kwargs + ) # Registered here, not in `nd_array_field` like the other builtins: `nd_array_field` cannot diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index a612e9ea86..c822510b13 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -297,7 +297,7 @@ def __gt_type__(self) -> ts.FunctionType: pos_only_args=[ts.DeferredType(constraint=None)], pos_or_kw_args={}, kw_only_args={ - "axis": ts.DeferredType(constraint=ts.DimensionType), + "range": ts.DeferredType(constraint=ts.TupleType), "forward": ts.DeferredType(constraint=ts.ScalarType), "init": ts.DeferredType(constraint=(ts.ScalarType, ts.TupleType)), }, @@ -324,7 +324,7 @@ def scan( scan_pass: Callable, /, *, - axis: common.Dimension, + range: tuple[common.Dimension, int, int], # noqa: A002 # shadowing a Python built-in forward: bool = True, init: core_defs.Scalar | common.Field | Tuple, ) -> Callable[..., common.Field | Tuple]: @@ -333,14 +333,16 @@ def scan( Args: scan_pass: Field operator `(carry, *args) -> carry` on scalars (or tuples thereof). - axis: Vertical dimension to scan along. + range: `(dim, start, stop)`: the vertical dimension to scan along and the half-open + interval of it the scan covers. The carry starts from `init` at `start` (forward) + or `stop - 1` (backward); the result is only defined on this interval. forward: Scan direction. init: Initial value of the carry: a constant, a scalar, or a field without the scan dimension holding the initial value of each column. For tuple carries, each element may be any of these; fields are not supported in named collections. Examples: - >>> scan(my_pass, axis=KDim, forward=True, init=0.0)(a) # doctest: +SKIP + >>> scan(my_pass, range=(KDim, 0, nlev), forward=True, init=0.0)(a) # doctest: +SKIP """ raise NotImplementedError() diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index b9aad06763..780f8a8752 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -167,25 +167,39 @@ def _is_scan_builtin(expr: foast.Expr) -> bool: return isinstance(expr, foast.Name) and expr.id == "scan" +def _check_scan_axis(axis: foast.Expr, description: str) -> Dimension: + if not isinstance(axis.type, ts.DimensionType): + raise errors.DSLError(axis.location, f"{description} must be a dimension.") + if axis.type.dim.kind != DimensionKind.VERTICAL: + raise errors.DSLError(axis.location, f"{description} must be a vertical dimension.") + return axis.type.dim + + +def _check_scan_range(range_: foast.Expr, name: str) -> Dimension: + if not ( + isinstance(range_, foast.TupleExpr) + and len(range_.elts) == 3 + and all(type_info.is_integral_scalar(bound.type) for bound in range_.elts[1:]) + ): + raise errors.DSLError( + range_.location, + f"Argument 'range' to scan operator '{name}' must be a tuple '(dim, start, stop)' " + "of a dimension and two integers.", + ) + return _check_scan_axis( + range_.elts[0], f"The dimension in argument 'range' to scan operator '{name}'" + ) + + def _check_scan_args( location: eve.SourceLocation, name: str, pass_type: ts.FunctionType, *, - axis: foast.Expr, forward: Optional[foast.Expr], init: foast.Expr, -) -> Dimension: - """Check the arguments of a scan operator and return its axis. An absent `forward` is checked by its default.""" - if not isinstance(axis.type, ts.DimensionType): - raise errors.DSLError( - axis.location, f"Argument 'axis' to scan operator '{name}' must be a dimension." - ) - if axis.type.dim.kind != DimensionKind.VERTICAL: - raise errors.DSLError( - axis.location, - f"Argument 'axis' to scan operator '{name}' must be a vertical dimension.", - ) +) -> None: + """Check the arguments of a scan operator. An absent `forward` is checked by its default.""" if forward is not None and not foast_utils.is_literal(forward): raise errors.DSLError( forward.location, @@ -239,7 +253,6 @@ def _check_scan_args( raise errors.DSLError( location, f"Scan operator '{name}' must take and return scalars or tuples of scalars." ) - return axis.type.dim def _check_scan_column_init( @@ -349,13 +362,9 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S new_forward = self.visit(node.forward, **kwargs) new_init = self.visit(node.init, **kwargs) new_definition = self.visit(node.definition, **kwargs) - axis = _check_scan_args( - node.location, - node.id, - new_definition.type, - axis=new_axis, - forward=new_forward, - init=new_init, + axis = _check_scan_axis(new_axis, f"Argument 'axis' to scan operator '{node.id}'") + _check_scan_args( + node.location, node.id, new_definition.type, forward=new_forward, init=new_init ) new_type = ts_ffront.ScanOperatorType(axis=axis, definition=new_definition.type) @@ -372,19 +381,19 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S def _visit_scan_call( self, node: foast.Call, scan_arg_types: list[ts.TypeSpec], **kwargs: Any ) -> foast.Call: - """Type `scan(pass, axis=..., forward=..., init=...)`, the callee of a call-site scan.""" + """Type `scan(pass, range=..., forward=..., init=...)`, the callee of a call-site scan.""" new_func = self.visit(node.func, **kwargs) if len(node.args) != 1: raise errors.DSLError( node.location, f"'scan' takes exactly one positional argument (the scan pass), got {len(node.args)}.", ) - if unexpected := set(node.kwargs) - {"axis", "forward", "init"}: + if unexpected := set(node.kwargs) - {"range", "forward", "init"}: raise errors.DSLError( node.location, f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.", ) - if missing := [name for name in ("axis", "init") if name not in node.kwargs]: + if missing := [name for name in ("range", "init") if name not in node.kwargs]: raise errors.DSLError( node.location, f"Missing argument(s) {', '.join(repr(name) for name in missing)} to 'scan'.", @@ -398,11 +407,11 @@ def _visit_scan_call( pass_type = new_pass.type.definition new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in node.kwargs.items()} - axis = _check_scan_args( + axis = _check_scan_range(new_kwargs["range"], str(new_pass)) + _check_scan_args( node.location, str(new_pass), pass_type, - axis=new_kwargs["axis"], forward=new_kwargs.get("forward"), init=new_kwargs["init"], ) diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 7683b59701..09f89a4062 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -72,13 +72,14 @@ def _lower_scan( init: itir.Expr, axis: common.Dimension, args: list[itir.Expr], + domain: Optional[itir.Expr] = None, ) -> itir.Expr: """Lower to `as_fieldop(scan(...))(*args)`, `param_names` being the carry and the arguments.""" carry, *arg_params = param_names definition = im.lambda_(carry, *arg_params)( im.call(scan_pass)(carry, *(im.deref(param) for param in arg_params)) ) - return im.as_fieldop(im.scan(definition, forward, init, axis))(*args) + return im.as_fieldop(im.scan(definition, forward, init, axis), domain)(*args) def _lower_scan_with_runtime_init( @@ -90,6 +91,7 @@ def _lower_scan_with_runtime_init( args: list[itir.Expr], carry_type: ts.TypeSpec, uids: utils.IDGeneratorPool, + domain: itir.Expr, ) -> itir.Expr: # A stencil may not reference outer symbols, so a non-literal `init` cannot seed the scan. # It is passed as an extra argument instead and read on the first level, marked by a flag @@ -110,7 +112,9 @@ def _lower_scan_with_runtime_init( result_collection_constructor=lambda _, elems: im.make_tuple(*elems), )(carry_type) seed = im.make_tuple(im.literal_from_value(False), placeholder) - return im.tuple_get(1, im.as_fieldop(im.scan(definition, forward, seed, axis))(*args, init)) + return im.tuple_get( + 1, im.as_fieldop(im.scan(definition, forward, seed, axis), domain)(*args, init) + ) @dataclasses.dataclass @@ -427,9 +431,14 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: else: raise AssertionError("Unexpected constructor encounterd.") - result = im.call(self.visit(node.func, **kwargs))( - *lowered_args, *lowered_kwargs.values() + func = ( + self._visit_scan(node.func, result_type=node.type, **kwargs) + if isinstance(node.func, foast.Call) + and isinstance(node.func.func, foast.Name) + and node.func.func.id == "scan" + else self.visit(node.func, **kwargs) ) + result = im.call(func)(*lowered_args, *lowered_kwargs.values()) return result @@ -437,9 +446,12 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: f"Call to object of type '{type(node.func.type).__name__}' not understood." ) - def _visit_scan(self, node: foast.Call, **kwargs: Any) -> itir.Expr: - # `scan(scan_pass, axis=..., forward=..., init=...)`, lowered to a function of the - # scan pass's arguments + def _visit_scan( + self, node: foast.Call, *, result_type: ts.TypeSpec, **kwargs: Any + ) -> itir.Expr: + # `scan(scan_pass, range=..., forward=..., init=...)`, lowered to a function of the + # scan pass's arguments. Arguments that are expressions are bound outside of it, so + # they are not shadowed by its parameters. assert isinstance(node.type, ts_ffront.ScanOperatorType) scan_pass = self.visit(node.args[0], **kwargs) forward = ( @@ -450,34 +462,55 @@ def _visit_scan(self, node: foast.Call, **kwargs: Any) -> itir.Expr: param_names = list(node.type.definition.pos_or_kw_args) args: list[itir.Expr] = [im.ref(param) for param in param_names[1:]] + range_ = node.kwargs["range"] + assert isinstance(range_, foast.TupleExpr) + _, start, stop = range_.elts + start_sym = next(self.uid_generator["__scan_start"]) + stop_sym = next(self.uid_generator["__scan_stop"]) + bindings = [ + (start_sym, self.visit(start, **kwargs)), + (stop_sym, self.visit(stop, **kwargs)), + ] + # The grid type and the bounds of the other dimensions are placeholders: domain inference + # only keeps the range of the scan dimension and infers the rest from the consumers. + domain = im.domain( + common.GridType.CARTESIAN, + { + dim: (im.ref(start_sym), im.ref(stop_sym)) + if dim == node.type.axis + else (itir.InfinityLiteral.NEGATIVE, itir.InfinityLiteral.POSITIVE) + for dim in type_info.extract_dims( + next(iter(type_info.primitive_constituents(result_type))) + ) + }, + ) + init = node.kwargs["init"] if foast_utils.is_literal(init): - return im.lambda_(*param_names[1:])( - _lower_scan( - scan_pass, - param_names, - forward, - self.visit(init, **kwargs), - node.type.axis, - args, - ) + body = _lower_scan( + scan_pass, + param_names, + forward, + self.visit(init, **kwargs), + node.type.axis, + args, + domain, ) - - init_sym = next(self.uid_generator["__scan_init"]) - return im.let(init_sym, self.visit(init, **kwargs))( - im.lambda_(*param_names[1:])( - _lower_scan_with_runtime_init( - scan_pass, - param_names, - forward, - im.ref(init_sym), - node.type.axis, - args, - node.type.definition.returns, - self.uid_generator, - ) + else: + init_sym = next(self.uid_generator["__scan_init"]) + bindings.append((init_sym, self.visit(init, **kwargs))) + body = _lower_scan_with_runtime_init( + scan_pass, + param_names, + forward, + im.ref(init_sym), + node.type.axis, + args, + node.type.definition.returns, + self.uid_generator, + domain, ) - ) + return im.let(*bindings)(im.lambda_(*param_names[1:])(body)) def _visit_astype(self, node: foast.Call, **kwargs: Any) -> itir.Expr: # Note: the type to convert to is uniquely identified by its GT4Py type (`ConstructorType`), diff --git a/src/gt4py/next/iterator/ir_utils/common_pattern_matcher.py b/src/gt4py/next/iterator/ir_utils/common_pattern_matcher.py index c0090ed3a2..aba5a50a59 100644 --- a/src/gt4py/next/iterator/ir_utils/common_pattern_matcher.py +++ b/src/gt4py/next/iterator/ir_utils/common_pattern_matcher.py @@ -100,6 +100,11 @@ def is_applied_as_fieldop(arg: itir.Node) -> TypeGuard[_FunCallToFunCallToRef]: return isinstance(arg, itir.FunCall) and is_call_to(arg.fun, "as_fieldop") +def is_applied_scan(arg: itir.Node) -> TypeGuard[_FunCallToFunCallToRef]: + """Match expressions of the form `as_fieldop(scan(...))(*args)`.""" + return is_applied_as_fieldop(arg) and is_call_to(arg.fun.args[0], "scan") + + _FunCallToLambda: TypeAlias = _FunCallTo[itir.Lambda] diff --git a/src/gt4py/next/iterator/transforms/global_tmps.py b/src/gt4py/next/iterator/transforms/global_tmps.py index b2eafc1090..9bc6d2203c 100644 --- a/src/gt4py/next/iterator/transforms/global_tmps.py +++ b/src/gt4py/next/iterator/transforms/global_tmps.py @@ -20,7 +20,7 @@ misc as ir_utils_misc, ) from gt4py.next.iterator.ir_utils.domain_utils import SymbolicDomain -from gt4py.next.iterator.transforms import cse, infer_domain, inline_lambdas +from gt4py.next.iterator.transforms import constant_folding, cse, infer_domain, inline_lambdas from gt4py.next.iterator.type_system import inference as type_inference from gt4py.next.type_system import type_info, type_specifications as ts @@ -111,14 +111,6 @@ def _populate_and_homogenize_domains(stmts: list[itir.Stmt]) -> list[itir.Stmt]: return new_stmts -def _is_as_fieldop_of_scan(expr: itir.Expr) -> bool: - return ( - cpm.is_applied_as_fieldop(expr) - and isinstance(expr.fun, itir.FunCall) - and cpm.is_call_to(expr.fun.args[0], "scan") - ) - - def _transform_if( stmt: itir.Stmt, declarations: list[itir.Temporary], @@ -144,6 +136,160 @@ def _transform_if( return None +def _fold_tuple_get(expr: itir.Expr) -> itir.Expr: + if cpm.is_call_to(expr, "make_tuple"): + return im.make_tuple(*(_fold_tuple_get(arg) for arg in expr.args)) + if cpm.is_call_to(expr, "tuple_get"): + idx, tuple_expr = expr.args + assert isinstance(idx, itir.Literal) + tuple_expr = _fold_tuple_get(tuple_expr) + if cpm.is_call_to(tuple_expr, "make_tuple"): + return tuple_expr.args[int(idx.value)] + return im.tuple_get(idx, tuple_expr) + return expr + + +def _transform_scan_on_other_domain( + stmt: itir.Stmt, + declarations: list[itir.Temporary], + uids: next_utils.IDGeneratorPool, +) -> Optional[list[itir.Stmt]]: + # A scan is computed on its own vertical range, which can differ from the domain of the + # statement. Materialize it in a temporary and copy the part of it that is requested. + if not isinstance(stmt, itir.SetAt) or cpm.is_ref_to(stmt.domain, "UNPOPULATED"): + return None + projector, expr = ir_utils_misc.extract_projector(stmt.expr) + if not cpm.is_applied_scan(expr): + return None + stmt_domain = infer_domain._make_symbolic_domain_tuple( + constant_folding.ConstantFolding.apply(stmt.domain) + ) + scan_domains = set(next_utils.flatten_nested_tuple((expr.annex.domain,))) - { + infer_domain.DomainAccessDescriptor.NEVER + } + if scan_domains <= set(next_utils.flatten_nested_tuple((stmt_domain,))): + return None + + tmp_target, tmp_stmts = _materialize_in_temporaries(expr, declarations, uids) + source = ( + _fold_tuple_get( + inline_lambdas.inline_lambda(im.call(projector)(tmp_target), opcount_preserving=False) + ) + if projector is not None + else tmp_target + ) + scan_domain = SymbolicDomain.from_expr(expr.fun.args[1]) + + elems_by_domain: dict[SymbolicDomain, list[tuple[int, ...]]] = {} + next_utils.tree_map( + lambda domain, path: elems_by_domain.setdefault(domain, []).append(path), + with_path_arg=True, + )(stmt_domain) + + get_path = lambda expr, path: functools.reduce( # noqa: E731 + lambda e, idx: e.args[idx] if cpm.is_call_to(e, "make_tuple") else im.tuple_get(idx, e), + path, + expr, + ) + copy_stmts: list[itir.Stmt] = [] + for domain, paths in elems_by_domain.items(): + copy_domain = domain_utils.domain_intersection(domain, scan_domain) + if paths == [()]: + target, elems = stmt.target, source + else: + target = im.make_tuple(*(get_path(stmt.target, path) for path in paths)) + elems = im.make_tuple(*(get_path(source, path) for path in paths)) + copy = im.as_fieldop("deref", copy_domain.as_expr())(elems) + copy.annex.domain = copy_domain + copy_stmts.append(itir.SetAt(target=target, domain=copy_domain.as_expr(), expr=copy)) + return [*tmp_stmts, *copy_stmts] + + +def _materialize_in_temporaries( + tmp_expr: itir.Expr, + declarations: list[itir.Temporary], + uids: next_utils.IDGeneratorPool, +) -> tuple[itir.Expr, list[itir.Stmt]]: + """Declare temporaries for `tmp_expr` and return a reference to them and the statements filling them.""" + as_tuple = lambda _, elts: tuple(elts) # noqa: E731 + + assert isinstance(tmp_expr.type, ts.TypeSpec) + tmp_names: str | tuple[str | tuple, ...] = type_info.tree_map_type( + lambda x: next(uids["__tmp"]), + result_collection_constructor=as_tuple, + )(tmp_expr.type) + tmp_dtypes: ts.ScalarType | ts.ListType | tuple[ts.ScalarType | ts.ListType | tuple, ...] = ( + type_info.tree_map_type( + type_info.extract_dtype, + result_collection_constructor=as_tuple, + )(tmp_expr.type) + ) + + tmp_domains: SymbolicDomain | tuple[SymbolicDomain | tuple, ...] = tmp_expr.annex.domain + + if cpm.is_applied_as_fieldop(tmp_expr): + # In this case all tuple elements have the same size (or will be `NEVER`). + # Create the tuple structure with that domain. + domain = list( + set(next_utils.flatten_nested_tuple((tmp_domains,))) + - {infer_domain.DomainAccessDescriptor.NEVER} + ) + assert len(domain) == 1 + # this is the domain used as initial value in the tuple construction below + tmp_domains = domain[0] + + def get_domain( + _, path: tuple[int, ...] + ) -> domain_utils.SymbolicDomain: # function only used inside loop + domain = functools.reduce( + lambda var, idx: var[idx] if isinstance(var, tuple) else var, + path, + tmp_domains, + ) + assert isinstance(domain, domain_utils.SymbolicDomain) + return domain + + # The following propagates the domains to the tuple structure of `tmp_expr.type`. + # `tmp_domains` might not have this structure because domain inference was not able to infer the tuple structure. + tmp_domains = type_info.tree_map_type( + get_domain, + result_collection_constructor=as_tuple, + with_path_arg=True, + )(tmp_expr.type) + + declarations.extend( + itir.Temporary(id=tmp_name, domain=domain.as_expr(), dtype=dtype) + for tmp_name, domain, dtype in zip( + next_utils.flatten_nested_tuple((tmp_names,)), + next_utils.flatten_nested_tuple((tmp_domains,)), + next_utils.flatten_nested_tuple((tmp_dtypes,)), + strict=True, + ) + ) + + # if the expr is a field this just gives a simple `itir.SymRef`, otherwise we generate a + # `make_tuple` expression. + target_expr: itir.Expr = next_utils.tree_map( + lambda name, domain: im.ref(name, annex={"domain": domain}), + result_collection_constructor=lambda _, elts: im.make_tuple(*elts), + )(tmp_names, tmp_domains) # type: ignore[assignment] # typing of tree_map does not reflect action of `result_collection_constructor` yet + + # TODO(tehrengruber): _transform_stmt not needed if deepest_expr_first=True + stmts = _transform_stmt( + itir.SetAt( + target=target_expr, + # The domain is populated later in `_populate_and_homogenize_domains` + # at this point the `SetAt` contains possibly expressions on different domains. + domain=im.ref("UNPOPULATED"), + expr=tmp_expr, + ), + declarations, + uids, + ) + + return target_expr, stmts + + def _transform_by_pattern( stmt: itir.Stmt, predicate: Callable[[itir.Expr, int], bool], @@ -169,94 +315,19 @@ def _transform_by_pattern( if extracted_fields: tmp_stmts: list[itir.Stmt] = [] - as_tuple = lambda _, elts: tuple(elts) # noqa: E731 - # for each extracted expression generate: # - one or more `Temporary` declarations (depending on whether the expression is a field # or a tuple thereof) # - one `SetAt` statement that materializes the expression into the temporary for tmp_sym, tmp_expr in extracted_fields.items(): - assert isinstance(tmp_expr.type, ts.TypeSpec) - tmp_names: str | tuple[str | tuple, ...] = type_info.tree_map_type( - lambda x: next(uids["__tmp"]), - result_collection_constructor=as_tuple, - )(tmp_expr.type) - tmp_dtypes: ( - ts.ScalarType | ts.ListType | tuple[ts.ScalarType | ts.ListType | tuple, ...] - ) = type_info.tree_map_type( - type_info.extract_dtype, - result_collection_constructor=as_tuple, - )(tmp_expr.type) - - tmp_domains: SymbolicDomain | tuple[SymbolicDomain | tuple, ...] = tmp_expr.annex.domain - - if cpm.is_applied_as_fieldop(tmp_expr): - # In this case all tuple elements have the same size (or will be `NEVER`). - # Create the tuple structure with that domain. - domain = list( - set(next_utils.flatten_nested_tuple((tmp_domains,))) - - {infer_domain.DomainAccessDescriptor.NEVER} - ) - assert len(domain) == 1 - # this is the domain used as initial value in the tuple construction below - tmp_domains = domain[0] - - def get_domain( - _, path: tuple[int, ...] - ) -> domain_utils.SymbolicDomain: # function only used inside loop - domain = functools.reduce( - lambda var, idx: var[idx] if isinstance(var, tuple) else var, - path, - tmp_domains, # noqa: B023 - ) - assert isinstance(domain, domain_utils.SymbolicDomain) - return domain - - # The following propagates the domains to the tuple structure of `tmp_expr.type`. - # `tmp_domains` might not have this structure because domain inference was not able to infer the tuple structure. - tmp_domains = type_info.tree_map_type( - get_domain, - result_collection_constructor=as_tuple, - with_path_arg=True, - )(tmp_expr.type) - - declarations.extend( - itir.Temporary(id=tmp_name, domain=domain.as_expr(), dtype=dtype) - for tmp_name, domain, dtype in zip( - next_utils.flatten_nested_tuple((tmp_names,)), - next_utils.flatten_nested_tuple((tmp_domains,)), - next_utils.flatten_nested_tuple((tmp_dtypes,)), - strict=True, - ) - ) - - # if the expr is a field this just gives a simple `itir.SymRef`, otherwise we generate a - # `make_tuple` expression. - target_expr: itir.Expr = next_utils.tree_map( - lambda name, domain: im.ref(name, annex={"domain": domain}), - result_collection_constructor=lambda _, elts: im.make_tuple(*elts), - )(tmp_names, tmp_domains) # type: ignore[assignment] # typing of tree_map does not reflect action of `result_collection_constructor` yet - + target_expr, stmts = _materialize_in_temporaries(tmp_expr, declarations, uids) # note: the let would be removed automatically by the `cse.extract_subexpression`, but # we remove it here for readability & debuggability. new_expr = inline_lambdas.inline_lambda( im.let(tmp_sym, target_expr)(new_expr), opcount_preserving=False ) - # TODO(tehrengruber): _transform_stmt not needed if deepest_expr_first=True - tmp_stmts.extend( - _transform_stmt( - itir.SetAt( - target=target_expr, - # The domain is populated later in `_populate_and_homogenize_domains` - # at this point the `SetAt` contains possibly expressions on different domains. - domain=im.ref("UNPOPULATED"), - expr=tmp_expr, - ), - declarations, - uids, - ) - ) + tmp_stmts.extend(stmts) if projector is not None: # add the projector back @@ -279,6 +350,7 @@ def _transform_stmt( transforms: list[Callable] = [ # transform `if_` call into `IfStmt` _transform_if, + _transform_scan_on_other_domain, # extract applied `as_fieldop` to top-level functools.partial( _transform_by_pattern, predicate=lambda expr, _: cpm.is_applied_as_fieldop(expr) diff --git a/src/gt4py/next/iterator/transforms/infer_domain.py b/src/gt4py/next/iterator/transforms/infer_domain.py index 0027d2c766..458131fbaf 100644 --- a/src/gt4py/next/iterator/transforms/infer_domain.py +++ b/src/gt4py/next/iterator/transforms/infer_domain.py @@ -519,6 +519,22 @@ def infer_expr( ) )(domain, el_types, additional_dims) + # A scan is computed on the vertical range of its domain argument, independent of the + # domain it is accessed on. + if ( + cpm.is_applied_scan(expr) + and len(expr.fun.args) == 2 + and cpm.is_call_to(expr.fun.args[1], ("cartesian_domain", "unstructured_domain")) + ): + scan_range = _extract_scan_axis(SymbolicDomain.from_expr(expr.fun.args[1]), axis) + domain = gtx_utils.tree_map( + lambda d: ( + SymbolicDomain(d.grid_type, {**d.ranges, **scan_range}) + if isinstance(d, SymbolicDomain) + else d + ) + )(domain) + inferred_expr, accessed_domains = _infer_expr( expr, domain, 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 e904ff4c1b..d97e6040a5 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 @@ -25,6 +25,7 @@ common_pattern_matcher as cpm, domain_utils, ir_makers as im, + misc as gtir_misc, ) from gt4py.next.program_processors.runners.dace import sdfg_args as gtx_dace_args from gt4py.next.program_processors.runners.dace.lowering import ( @@ -139,6 +140,18 @@ def testee(interior: cases.IJKField, boundary: cases.IJField) -> cases.IJKField: assert source.gt_type == output_type source_domain_range = source_domain.ranges[concat_dim] + if cpm.is_applied_scan(gtir_misc.extract_projector(source_expr)[1]): + # A scan is computed on its own range, which can exceed the region of this branch. + output_range = output_domain.ranges[concat_dim] + branch_start, branch_stop = ( + (output_range.start, concat_dim_bound_expr) + if is_lower + else (concat_dim_bound_expr, output_range.stop) + ) + source_domain_range = domain_utils.SymbolicRange( + start=im.maximum(source_domain_range.start, branch_start), + stop=im.minimum(source_domain_range.stop, branch_stop), + ) source_range_0 = gtir_to_sdfg_utils.get_symbolic(source_domain_range.start) source_range_1 = gtir_to_sdfg_utils.get_symbolic( im.maximum(source_domain_range.start, source_domain_range.stop) diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index 734c4677ff..0625522b77 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -165,6 +165,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): USES_SCAN = "uses_scan" USES_SCAN_IN_FIELD_OPERATOR = "uses_scan_in_field_operator" USES_SCAN_WITHOUT_FIELD_ARGS = "uses_scan_without_field_args" +USES_SCAN_WITH_UNSTRUCTURED_SHIFT = "uses_scan_with_unstructured_shift" USES_SCAN_NESTED = "uses_scan_nested" USES_SPARSE_FIELDS = "uses_sparse_fields" USES_SPARSE_FIELDS_AS_OUTPUT = "uses_sparse_fields_as_output" @@ -298,6 +299,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): XFAIL, OFFSET_TAG_DIFFERING_FROM_LOCAL_DIM_MESSAGE, ), + (USES_SCAN_WITH_UNSTRUCTURED_SHIFT, XFAIL, UNSUPPORTED_MESSAGE), ] GTFN_SKIP_TEST_LIST = ( COMMON_SKIP_TEST_LIST diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py index ef53a24226..81de103a55 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py @@ -11,20 +11,27 @@ import pytest import gt4py.next as gtx -from gt4py.next import errors, float64, int32, maximum, scan +from gt4py.next import common, errors, float64, int32, maximum, neighbor_sum, scan from gt4py.next.experimental import concat_where from gt4py.next.ffront.decorator import program, scan_operator from next_tests.integration_tests import cases from next_tests.integration_tests.cases import ( + Edge, IDim, JDim, KDim, KHalfDim, + V2E, + V2EDim, + Vertex, cartesian_case, + unstructured_case, + unstructured_case_3d, ) from next_tests.integration_tests.cases_utils import ( exec_alloc_descriptor, + mesh_descriptor, ) @@ -584,7 +591,7 @@ def add(carry: float, inp: float) -> float: @gtx.field_operator def testee(inp: cases.IKFloatField) -> cases.IKFloatField: - return scan(add, axis=KDim, forward=True, init=1.0)(inp) + return scan(add, range=(KDim, 0, 9), forward=True, init=1.0)(inp) inp = cases.allocate(cartesian_case, testee, "inp")() out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() @@ -601,7 +608,7 @@ def add(carry: float, inp: float, scalar: float) -> float: @gtx.field_operator def testee(inp: cases.IKFloatField, scalar: float) -> cases.IKFloatField: - return scan(add, axis=KDim, forward=False, init=-1.0)(inp, scalar) + inp + return scan(add, range=(KDim, 0, 9), forward=False, init=-1.0)(inp, scalar) + inp inp = cases.allocate(cartesian_case, testee, "inp")() out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() @@ -621,7 +628,7 @@ def add_pair(carry: float, pair: tuple[float, float]) -> float: @gtx.field_operator def testee(a: cases.IKFloatField, b: cases.IKFloatField) -> cases.IKFloatField: - return scan(add_pair, axis=KDim, init=0.0)((a, b)) + return scan(add_pair, range=(KDim, 0, 9), init=0.0)((a, b)) a = cases.allocate(cartesian_case, testee, "a")() b = cases.allocate(cartesian_case, testee, "b")() @@ -641,7 +648,7 @@ def add(carry: float, inp: float) -> float: @gtx.field_operator def testee(inp: cases.IKFloatField, init: float) -> cases.IKFloatField: - return scan(add, axis=KDim, forward=True, init=init)(inp) + return scan(add, range=(KDim, 0, 9), forward=True, init=init)(inp) inp = cases.allocate(cartesian_case, testee, "inp")() out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() @@ -660,7 +667,7 @@ def add(carry: float, inp: float) -> float: @gtx.field_operator def testee(inp: cases.IKFloatField, init: cases.IFloatField) -> cases.IKFloatField: - return scan(add, axis=KDim, forward=False, init=init)(inp) + return scan(add, range=(KDim, 0, 9), forward=False, init=init)(inp) inp = cases.allocate(cartesian_case, testee, "inp")() init = cartesian_case.as_field( @@ -691,7 +698,7 @@ def sum_and_max(carry: tuple[float, float], inp: float) -> tuple[float, float]: def testee( inp: cases.IKFloatField, init: cases.IFloatField ) -> tuple[cases.IKFloatField, cases.IKFloatField]: - return scan(sum_and_max, axis=KDim, forward=True, init=(1.0, init))(inp) + return scan(sum_and_max, range=(KDim, 0, 9), forward=True, init=(1.0, init))(inp) inp = cases.allocate(cartesian_case, testee, "inp")() init = cartesian_case.as_field( @@ -725,7 +732,7 @@ def sum_and_count(carry: tuple[float, int32], inp: float) -> tuple[float, int32] @gtx.field_operator def testee(inp: cases.IKFloatField) -> tuple[cases.IKFloatField, cases.IKField]: - return scan(sum_and_count, axis=KDim, init=(0.0, int32(0)))(inp) + return scan(sum_and_count, range=(KDim, 0, 9), init=(0.0, int32(0)))(inp) inp = cases.allocate(cartesian_case, testee, "inp")() out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() @@ -742,3 +749,166 @@ def testee(inp: cases.IKFloatField) -> tuple[cases.IKFloatField, cases.IKField]: np.full((isize, ksize), np.arange(1, ksize + 1, dtype=np.int32)), ), ) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_concat_where +@pytest.mark.parametrize("k_start", [0, 2]) +def test_scan_range_under_concat_where(cartesian_case, k_start): + """The scan covers exactly its range, whatever part of it the consumer reads.""" + + @gtx.field_operator + def add(carry: float, inp: float) -> float: + return carry + inp + + @gtx.field_operator + def testee(inp: cases.IKFloatField, k_start: int32) -> cases.IKFloatField: + return concat_where( + KDim >= 2, scan(add, range=(KDim, k_start, 9), forward=True, init=0.0)(inp), -inp + ) + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + inp_np = inp.asnumpy() + ref = -inp_np.copy() + ref[:, 2:] = np.cumsum(inp_np[:, k_start:], axis=1)[:, 2 - k_start :] + + cases.verify(cartesian_case, testee, inp, k_start, out=out, ref=ref) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_concat_where +def test_scan_range_runtime_bounds_backward(cartesian_case): + @gtx.field_operator + def add(carry: float, inp: float) -> float: + return carry + inp + + @gtx.field_operator + def testee(inp: cases.IKFloatField, k_start: int32, k_end: int32) -> cases.IKFloatField: + return concat_where( + (KDim >= k_start) & (KDim < k_end), + scan(add, range=(KDim, k_start, k_end), forward=False, init=0.0)(inp), + inp, + ) + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + inp_np = inp.asnumpy() + ref = inp_np.copy() + ref[:, 3:7] = np.flip(np.cumsum(np.flip(inp_np[:, 3:7], axis=1), axis=1), axis=1) + + cases.verify(cartesian_case, testee, inp, 3, 7, out=out, ref=ref) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_range_larger_than_output(cartesian_case): + @gtx.field_operator + def add(carry: float, inp: float) -> float: + return carry + inp + + @gtx.field_operator + def testee(inp: cases.IKFloatField) -> cases.IKFloatField: + return scan(add, range=(KDim, 0, 9), forward=True, init=0.0)(inp) + + @gtx.program + def prog(inp: cases.IKFloatField, out: cases.IKFloatField): + testee(inp, out=out, domain={IDim: (0, 5), KDim: (2, 5)}) + + inp = cases.allocate(cartesian_case, prog, "inp")() + out = cases.allocate(cartesian_case, prog, "out").zeros()() + ref = np.zeros_like(inp.asnumpy()) + ref[:, 2:5] = np.cumsum(inp.asnumpy(), axis=1)[:, 2:5] + + cases.verify(cartesian_case, prog, inp, out, inout=out, ref=ref) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_range_bound_named_like_pass_parameter(cartesian_case): + @gtx.field_operator + def add(carry: float, k_start: float) -> float: + return carry + k_start + + @gtx.field_operator + def testee(inp: cases.IKFloatField, k_start: int32) -> cases.IKFloatField: + return scan(add, range=(KDim, k_start, 9), forward=True, init=0.0)(inp) + + @gtx.program + def prog(inp: cases.IKFloatField, k_start: int32, out: cases.IKFloatField): + testee(inp, k_start, out=out, domain={IDim: (0, 5), KDim: (2, 9)}) + + inp = cases.allocate(cartesian_case, prog, "inp")() + out = cases.allocate(cartesian_case, prog, "out").zeros()() + ref = np.zeros_like(inp.asnumpy()) + ref[:, 2:] = np.cumsum(inp.asnumpy()[:, 2:], axis=1) + + cases.verify(cartesian_case, prog, inp, 2, out, inout=out, ref=ref) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_tuple_returns +@pytest.mark.uses_program_with_sliced_out_arguments +def test_scan_range_tuple_outputs_on_different_domains(cartesian_case): + @gtx.field_operator + def sum_and_double(carry: tuple[float, float], inp: float) -> tuple[float, float]: + return carry[0] + inp, carry[1] + 2.0 * inp + + @gtx.field_operator + def testee(inp: cases.IKFloatField) -> tuple[cases.IKFloatField, cases.IKFloatField]: + return scan(sum_and_double, range=(KDim, 0, 9), forward=True, init=(0.0, 0.0))(inp) + + @gtx.program + def prog(inp: cases.IKFloatField, out1: cases.IKFloatField, out2: cases.IKFloatField): + testee(inp, out=(out1, out2[:, 2:7])) + + inp = cases.allocate(cartesian_case, prog, "inp")() + out1 = cases.allocate(cartesian_case, prog, "out1").zeros()() + out2 = cases.allocate(cartesian_case, prog, "out2").zeros()() + cumsum = np.cumsum(inp.asnumpy(), axis=1) + ref2 = np.zeros_like(cumsum) + ref2[:, 2:7] = 2.0 * cumsum[:, 2:7] + + cases.verify( + cartesian_case, + prog, + inp, + out1, + out2, + inout=(out1, out2), + ref=(cumsum, ref2), + comparison=lambda ref, out: all(np.allclose(r, o) for r, o in zip(ref, out)), + ) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_unstructured_shift +@pytest.mark.uses_scan_with_unstructured_shift +def test_scan_range_unstructured_backward(unstructured_case_3d): + @gtx.field_operator + def add(carry: float, inp: float) -> float: + return carry + inp + + @gtx.field_operator + def testee( + e: gtx.Field[[Edge, KDim], float64], k_start: int32, k_end: int32 + ) -> gtx.Field[[Vertex, KDim], float64]: + s = scan(add, range=(KDim, k_start, k_end), forward=False, init=0.0)(e) + return neighbor_sum(s(V2E), axis=V2EDim) + + e = cases.allocate(unstructured_case_3d, testee, "e")() + out = cases.allocate(unstructured_case_3d, testee, cases.RETURN).zeros()() + v2e_table = unstructured_case_3d.offset_provider["V2E"].asnumpy() + backward_cumsum = np.flip(np.cumsum(np.flip(e.asnumpy(), axis=1), axis=1), axis=1) + ref = np.sum( + backward_cumsum[v2e_table], + axis=1, + initial=0, + where=(v2e_table != common._DEFAULT_SKIP_VALUE)[:, :, np.newaxis], + ) + + cases.verify(unstructured_case_3d, testee, e, 0, 10, out=out, ref=ref) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py b/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py index cc08459aed..622fa56651 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py @@ -813,7 +813,7 @@ def _scan_pass(carry: float, inp: float) -> float: def test_scan_call(): def scan_call(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass, axis=KDim, init=0.0)(a) + return scan(_scan_pass, range=(KDim, 0, 10), init=0.0)(a) parsed = FieldOperatorParser.apply_to_function(scan_call) @@ -832,7 +832,7 @@ def field_param(carry: float, inp: Field[[TDim, KDim], float64]) -> float: def test_scan_call_not_called(): def scan_not_called(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: - op = scan(_scan_pass, axis=KDim, init=0.0) + op = scan(_scan_pass, range=(KDim, 0, 10), init=0.0) return a with pytest.raises( @@ -841,17 +841,48 @@ def scan_not_called(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], floa _ = FieldOperatorParser.apply_to_function(scan_not_called) -def test_scan_call_missing_axis(): - def missing_axis(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: +def test_scan_call_missing_range(): + def missing_range(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: return scan(_scan_pass, init=0.0)(a) - with pytest.raises(errors.DSLError, match=r"Missing argument\(s\) 'axis' to 'scan'"): - _ = FieldOperatorParser.apply_to_function(missing_axis) + with pytest.raises(errors.DSLError, match=r"Missing argument\(s\) 'range' to 'scan'"): + _ = FieldOperatorParser.apply_to_function(missing_range) + + +def test_scan_call_axis_instead_of_range(): + def axis_instead_of_range(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=KDim, init=0.0)(a) + + with pytest.raises(errors.DSLError, match=r"Unexpected keyword argument\(s\) axis to 'scan'"): + _ = FieldOperatorParser.apply_to_function(axis_instead_of_range) + + +def test_scan_call_malformed_range(): + def malformed_range(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, range=(KDim, 0.0, 10), init=0.0)(a) + + with pytest.raises( + errors.DSLError, match=r"'range' to scan operator '_scan_pass' must be a tuple" + ): + _ = FieldOperatorParser.apply_to_function(malformed_range) + + +def test_scan_call_runtime_range(): + def runtime_range( + a: Field[[TDim, KDim], float64], start: int32, stop: int32 + ) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, range=(KDim, start, stop), init=0.0)(a) + + parsed = FieldOperatorParser.apply_to_function(runtime_range) + + assert parsed.type.returns == ts.FieldType( + dims=[TDim, KDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) + ) def test_scan_call_missing_init(): def missing_init(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass, axis=KDim)(a) + return scan(_scan_pass, range=(KDim, 0, 10))(a) with pytest.raises(errors.DSLError, match=r"Missing argument\(s\) 'init' to 'scan'"): _ = FieldOperatorParser.apply_to_function(missing_init) @@ -859,10 +890,11 @@ def missing_init(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64 def test_scan_call_non_vertical_axis(): def non_vertical_axis(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass, axis=TDim, init=0.0)(a) + return scan(_scan_pass, range=(TDim, 0, 10), init=0.0)(a) with pytest.raises( - errors.DSLError, match=r"'axis' to scan operator '_scan_pass' must be a vertical dimension" + errors.DSLError, + match=r"dimension in argument 'range' to scan operator '_scan_pass' must be a vertical dimension", ): _ = FieldOperatorParser.apply_to_function(non_vertical_axis) @@ -871,7 +903,7 @@ def test_scan_call_non_constant_forward(): def non_constant_forward( a: Field[[TDim, KDim], float64], forward: bool ) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass, axis=KDim, init=0.0, forward=forward)(a) + return scan(_scan_pass, range=(KDim, 0, 10), init=0.0, forward=forward)(a) with pytest.raises( errors.DSLError, @@ -884,7 +916,7 @@ def test_scan_call_column_init(): def column_init( a: Field[[TDim, KDim], float64], init: Field[[TDim], float64] ) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass, axis=KDim, init=init)(a) + return scan(_scan_pass, range=(KDim, 0, 10), init=init)(a) parsed = FieldOperatorParser.apply_to_function(column_init) @@ -897,7 +929,7 @@ def test_scan_call_init_over_scan_dim(): def init_over_scan_dim( a: Field[[TDim, KDim], float64], init: Field[[TDim, KDim], float64] ) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass, axis=KDim, init=init)(a) + return scan(_scan_pass, range=(KDim, 0, 10), init=init)(a) with pytest.raises( errors.DSLError, match=r"'init' to 'scan' must not be a field over the scan" @@ -909,7 +941,7 @@ def test_scan_call_init_dims_not_in_result(): def init_dims_not_in_result( a: Field[[KDim], float64], init: Field[[TDim], float64] ) -> Field[[KDim], float64]: - return scan(_scan_pass, axis=KDim, init=init)(a) + return scan(_scan_pass, range=(KDim, 0, 10), init=init)(a) with pytest.raises(errors.DSLError, match=r"must be a subset of the dimensions of the result"): _ = FieldOperatorParser.apply_to_function(init_dims_not_in_result) @@ -917,7 +949,7 @@ def init_dims_not_in_result( def test_scan_call_wrong_init_type(): def wrong_init_type(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass, axis=KDim, init=0)(a) + return scan(_scan_pass, range=(KDim, 0, 10), init=0)(a) with pytest.raises(errors.DSLError, match=r"Argument 'init' to scan operator '_scan_pass'"): _ = FieldOperatorParser.apply_to_function(wrong_init_type) @@ -925,7 +957,7 @@ def wrong_init_type(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], floa def test_scan_call_pass_not_a_field_operator(): def pass_is_builtin(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: - return scan(where, axis=KDim, init=0.0)(a) + return scan(where, range=(KDim, 0, 10), init=0.0)(a) with pytest.raises(errors.DSLError, match=r"The scan pass must be a field operator"): _ = FieldOperatorParser.apply_to_function(pass_is_builtin) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py index 3aab352b32..276cd614c2 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_domain_inference.py @@ -1167,6 +1167,21 @@ def test_scan(): ) +def test_scan_pinned_vertical_range(): + float_ik_field = ts.FieldType(dims=[IDim, KDim], dtype=float_type) + stencil = im.scan(im.lambda_("carry", "it")(im.plus("carry", im.deref("it"))), True, 0.0, KDim) + pinned = im.domain( + common.GridType.CARTESIAN, + {IDim: (itir.InfinityLiteral.NEGATIVE, itir.InfinityLiteral.POSITIVE), KDim: (0, 10)}, + ) + domain = im.domain(common.GridType.CARTESIAN, {IDim: (0, 5), KDim: (2, 4)}) + testee = im.as_fieldop(stencil, pinned)(im.ref("a", float_ik_field)) + inferred = im.domain(common.GridType.CARTESIAN, {IDim: (0, 5), KDim: (0, 10)}) + expected = im.as_fieldop(stencil, inferred)(im.ref("a", float_ik_field)) + + run_test_expr(testee, expected, domain, {"a": inferred}) + + def test_symbolic_domain_sizes(unstructured_offset_provider): stencil = im.lambda_("arg0")(im.deref(im.shift("E2V", 1)("arg0"))) domain = im.domain(common.GridType.UNSTRUCTURED, {Edge: (0, 1)})