From a19d90f4c581933e997ebd90069ed7cd9f8939ae Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 24 Sep 2026 17:26:07 +0200 Subject: [PATCH 01/18] feat[next]: call-site scan builtin Add `scan(scan_pass, axis=..., forward=..., init=...)(args)`, usable inside a field operator with a scalar field operator as the scan pass. The scan is lowered inline to `as_fieldop(scan(...))`; the axis defaults to the unique vertical dimension of the arguments. --- src/gt4py/next/__init__.py | 2 + src/gt4py/next/ffront/fbuiltins.py | 47 ++++ .../ffront/foast_passes/type_deduction.py | 205 +++++++++++++++--- src/gt4py/next/ffront/foast_to_gtir.py | 26 ++- src/gt4py/next/ffront/foast_to_past.py | 4 + src/gt4py/next/ffront/past_to_itir.py | 12 + .../ffront_tests/test_foast_pretty_printer.py | 6 +- .../feature_tests/ffront_tests/test_scan.py | 67 +++++- .../ffront_tests/test_type_deduction.py | 74 +++++++ 9 files changed, 405 insertions(+), 38 deletions(-) diff --git a/src/gt4py/next/__init__.py b/src/gt4py/next/__init__.py index 3b9f97592f..1fffc296e6 100644 --- a/src/gt4py/next/__init__.py +++ b/src/gt4py/next/__init__.py @@ -83,6 +83,7 @@ neg, neighbor_sum, power, + scan, sin, sinh, sqrt, @@ -186,6 +187,7 @@ "neg", "neighbor_sum", "power", + "scan", "sin", "sinh", "sqrt", diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 2fd072a483..010a3267d2 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -61,6 +61,7 @@ "where", "broadcast", "astype", + "scan", "abs", "neg", "sin", @@ -293,6 +294,51 @@ def broadcast( return field # type: ignore[return-value] # see comment above +class ScanBuiltinFunction(BuiltInFunction[_R, _P]): + def __gt_type__(self) -> ts.FunctionType: + return ts.FunctionType( + pos_only_args=[ts.DeferredType(constraint=None)], + pos_or_kw_args={}, + kw_only_args={ + "axis": ts.DeferredType(constraint=ts.DimensionType), + "forward": ts.DeferredType(constraint=ts.ScalarType), + "init": ts.DeferredType(constraint=(ts.ScalarType, ts.TupleType)), + }, + returns=ts.DeferredType(constraint=None), + ) + + +@ScanBuiltinFunction +def scan( + scan_pass: Callable, + /, + *, + axis: common.Dimension | None = None, + forward: bool = True, + init: core_defs.Scalar | Tuple = 0.0, +) -> Callable[..., common.Field | Tuple]: + """ + Create a scan operator from a scan pass, to be called inside a field operator. + + Args: + scan_pass: Field operator `(carry, *args) -> carry` on scalars (or tuples thereof). + axis: Vertical dimension to scan along. If omitted, it is the unique vertical + dimension of the arguments the scan operator is called with. + forward: Scan direction. + init: Initial value of the carry, a compile-time constant. + + Examples: + >>> scan(my_pass, axis=KDim, forward=True, init=0.0)(a) # doctest: +SKIP + """ + from gt4py.next.embedded import context as embedded_context, operators as embedded_operators + + def scan_operator(*args: Any, **kwargs: Any) -> common.Field | Tuple: + scan_axis = axis if axis is not None else embedded_context.get_closure_column_range().dim + return embedded_operators.ScanOperator(scan_pass, forward, init, scan_axis)(*args, **kwargs) + + return scan_operator + + @WhereBuiltinFunction def where( mask: common.Field, @@ -453,6 +499,7 @@ def impl( "broadcast", "where", "astype", + "scan", *MATH_BUILTIN_NAMES, ] diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index 738b105a61..8415e43135 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -163,6 +163,64 @@ def _no_implicit_conversion_diagnostic(left: foast.Expr, right: foast.Expr) -> d } +def _is_scan_builtin(expr: foast.Expr) -> bool: + return isinstance(expr, foast.Name) and expr.id == "scan" + + +def _is_literal(expr: foast.Expr) -> bool: + match expr: + case foast.Constant(): + return True + case foast.TupleExpr(): + return all(_is_literal(el) for el in expr.elts) + case foast.UnaryOp(): + return _is_literal(expr.operand) + case foast.Call(func=foast.Name(type=ts.ConstructorType())): + return all(_is_literal(arg) for arg in expr.args) + return False + + +def _check_scan_pass( + location: eve.SourceLocation, + name: str, + pass_type: ts.FunctionType, + forward_type: ts.TypeSpec, + init_type: ts.TypeSpec, +) -> None: + if not (isinstance(forward_type, ts.ScalarType) and forward_type.kind == ts.ScalarKind.BOOL): + raise errors.DSLError( + location, f"Argument 'forward' to scan operator '{name}' must be a boolean." + ) + if not all( + type_info.is_arithmetic(type_) or type_info.is_logical(type_) + for type_ in type_info.primitive_constituents(init_type) + ): + raise errors.DSLError( + location, + f"Argument 'init' to scan operator '{name}' must " + "be an arithmetic type or a logical type or a composite of arithmetic and logical types.", + ) + if not pass_type.pos_or_kw_args: + raise errors.DSLError( + location, + f"Scan operator '{name}' must have at least one argument (the carry).", + ) + carry_arg_name = next(iter(pass_type.pos_or_kw_args.keys())) + carry_type = pass_type.pos_or_kw_args[carry_arg_name] + if carry_type != pass_type.returns: + raise errors.DSLError( + location, + f"Argument '{carry_arg_name}' to scan operator '{name}' must have same type as its return: " + f"expected '{pass_type.returns}', got '{carry_type}'.", + ) + elif init_type != carry_type: + raise errors.DSLError( + location, + f"Argument 'init' to scan operator '{name}' must have same type as '{carry_arg_name}' argument: " + f"expected '{carry_type}', got '{init_type}'.", + ) + + class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTranslator): """ Deduce and check types of FOAST expressions and symbols. @@ -250,51 +308,115 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S f"Argument 'axis' to scan operator '{node.id}' must be a vertical dimension.", ) new_forward = self.visit(node.forward, **kwargs) - if not new_forward.type.kind == ts.ScalarKind.BOOL: - raise errors.DSLError( - node.location, f"Argument 'forward' to scan operator '{node.id}' must be a boolean." - ) new_init = self.visit(node.init, **kwargs) - if not all( - type_info.is_arithmetic(type_) or type_info.is_logical(type_) - for type_ in type_info.primitive_constituents(new_init.type) - ): + new_definition = self.visit(node.definition, **kwargs) + _check_scan_pass( + node.location, node.id, new_definition.type, new_forward.type, new_init.type + ) + + new_type = ts_ffront.ScanOperatorType( + axis=new_axis.type.dim, definition=new_definition.type + ) + return foast.ScanOperator( + id=node.id, + axis=new_axis, + forward=new_forward, + init=new_init, + definition=new_definition, + type=new_type, + location=node.location, + ) + + 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.""" + new_func = self.visit(node.func, **kwargs) + if len(node.args) != 1: raise errors.DSLError( node.location, - f"Argument 'init' to scan operator '{node.id}' must " - "be an arithmetic type or a logical type or a composite of arithmetic and logical types.", + f"'scan' takes exactly one positional argument (the scan pass), got {len(node.args)}.", ) - new_definition = self.visit(node.definition, **kwargs) - new_def_type = new_definition.type - if not new_def_type.pos_or_kw_args: + if unexpected := set(node.kwargs) - {"axis", "forward", "init"}: raise errors.DSLError( node.location, - f"Scan operator '{node.id}' must have at least one argument (the carry).", + f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.", ) - carry_arg_name = next(iter(new_def_type.pos_or_kw_args.keys())) - carry_type = new_def_type.pos_or_kw_args[carry_arg_name] - if carry_type != new_def_type.returns: + new_pass = self.visit(node.args[0], **kwargs) + if not isinstance(new_pass.type, ts_ffront.FieldOperatorType): raise errors.DSLError( - node.location, - f"Argument '{carry_arg_name}' to scan operator '{node.id}' must have same type as its return: " - f"expected '{new_def_type.returns}', got '{carry_type}'.", + new_pass.location, + f"The scan pass must be a field operator, got '{new_pass.type}'.", ) - elif new_init.type != carry_type: + pass_type = new_pass.type.definition + pass_name = str(new_pass) + + new_kwargs = { + "forward": foast.Constant(value=True, location=node.location), + "init": foast.Constant(value=0.0, location=node.location), + **node.kwargs, + } + new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in new_kwargs.items()} + for name in ("forward", "init"): + if not _is_literal(new_kwargs[name]): + raise errors.DSLError( + new_kwargs[name].location, + f"Argument '{name}' to 'scan' must be a compile-time constant.", + ) + _check_scan_pass( + node.location, pass_name, pass_type, new_kwargs["forward"].type, new_kwargs["init"].type + ) + if not all( + isinstance(t, ts.ScalarType) + for param in [*pass_type.pos_or_kw_args.values(), pass_type.returns] + for t in type_info.primitive_constituents(param) + ): raise errors.DSLError( - node.location, - f"Argument 'init' to scan operator '{node.id}' must have same type as '{carry_arg_name}' argument: " - f"expected '{carry_type}', got '{new_init.type}'.", + new_pass.location, + f"The scan pass '{pass_name}' must take and return scalars or tuples of scalars.", + ) + if pass_type.pos_only_args or pass_type.kw_only_args: + raise errors.DSLError( + new_pass.location, + f"The scan pass '{pass_name}' must not have positional-only or keyword-only arguments.", ) - new_type = ts_ffront.ScanOperatorType(axis=new_axis.type.dim, definition=new_def_type) - return foast.ScanOperator( - id=node.id, - axis=new_axis, - forward=new_forward, - init=new_init, - definition=new_definition, - type=new_type, + if "axis" in new_kwargs: + axis_type = new_kwargs["axis"].type + if not isinstance(axis_type, ts.DimensionType): + raise errors.DSLError( + new_kwargs["axis"].location, "Argument 'axis' to 'scan' must be a dimension." + ) + axis = axis_type.dim + if axis.kind != DimensionKind.VERTICAL: + raise errors.DSLError( + new_kwargs["axis"].location, + "Argument 'axis' to 'scan' must be a vertical dimension.", + ) + else: + vertical_dims = { + dim + for arg_type in scan_arg_types + for el in type_info.primitive_constituents(arg_type) + for dim in type_info.extract_dims(el) + if dim.kind == DimensionKind.VERTICAL + } + if len(vertical_dims) != 1: + found = ", ".join(sorted(f"'{d.value}'" for d in vertical_dims)) or "none" + raise errors.DSLError( + node.location, + "Cannot infer the 'axis' of 'scan' from its arguments, expected exactly one " + f"vertical dimension, found {found}.", + hints=["Pass the axis explicitly, e.g. 'scan(..., axis=KDim)'."], + ) + (axis,) = vertical_dims + + return foast.Call( + func=new_func, + args=[new_pass], + kwargs=new_kwargs, location=node.location, + type=ts_ffront.ScanOperatorType(axis=axis, definition=pass_type), ) def visit_Name(self, node: foast.Name, **kwargs: Any) -> foast.Name: @@ -757,9 +879,22 @@ def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> foast.TupleEx return foast.TupleExpr(elts=new_elts, type=new_type, location=node.location) def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: - new_func = self.visit(node.func, **kwargs) + if _is_scan_builtin(node.func): + raise errors.DSLError( + node.location, + "'scan' creates a scan operator which must be called directly: " + "'scan(scan_pass, ...)(args)'.", + ) new_args = self.visit(node.args, **kwargs) new_kwargs = self.visit(node.kwargs, **kwargs) + if isinstance(node.func, foast.Call) and _is_scan_builtin(node.func.func): + new_func = self._visit_scan_call( + node.func, + scan_arg_types=[arg.type for arg in [*new_args, *new_kwargs.values()]], + **kwargs, + ) + else: + new_func = self.visit(node.func, **kwargs) func_type = new_func.type arg_types = [arg.type for arg in new_args] @@ -779,6 +914,9 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: if not isinstance( new_func, (foast.FunctionDefinition, foast.FieldOperator, foast.ScanOperator, foast.Name), + ) and not ( + isinstance(new_func, foast.Call) + and isinstance(new_func.type, ts_ffront.ScanOperatorType) ): raise errors.DSLError(node.location, "Functions can only be called directly.") elif isinstance(new_func.type, ts.FieldType): @@ -811,6 +949,7 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: f"Expression of type '{new_func.type}' is not callable, must be a 'Function', 'FieldOperator', 'ScanOperator' or 'Field'.", ) + assert isinstance(func_type, ts.CallableType) # ensure signature is valid try: type_info.accepts_args( diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 9b3c15d7eb..3e2e957d2b 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -351,7 +351,11 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr: return current_expr def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: - if type_info.type_class(node.func.type) is ts.FieldType: + if isinstance(node.func, foast.Call) and isinstance( + node.func.type, ts_ffront.ScanOperatorType + ): + return self._visit_scan_call(node, **kwargs) + elif type_info.type_class(node.func.type) is ts.FieldType: return self._visit_shift(node, **kwargs) elif isinstance(node.func, foast.Name) and node.func.id in fbuiltins.MATH_BUILTIN_NAMES: return self._visit_math_built_in(node, **kwargs) @@ -393,6 +397,26 @@ 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_call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: + # `scan(scan_pass, forward=..., init=...)(*args)` + scan_call = node.func + assert isinstance(scan_call, foast.Call) + assert isinstance(scan_call.type, ts_ffront.ScanOperatorType) + scan_pass = self.visit(scan_call.args[0], **kwargs) + forward = self.visit(scan_call.kwargs["forward"], **kwargs) + init = self.visit(scan_call.kwargs["init"], **kwargs) + + lowered_args, lowered_kwargs = type_info.canonicalize_arguments( + scan_call.type, self.visit(node.args, **kwargs), self.visit(node.kwargs, **kwargs) + ) + stencil_args = [*lowered_args, *lowered_kwargs.values()] + carry = next(self.uid_generator["__scan_carry"]) + params = [next(self.uid_generator["__scan_arg"]) for _ in stencil_args] + definition = im.lambda_(carry, *params)( + im.call(scan_pass)(carry, *(im.deref(param) for param in params)) + ) + return im.as_fieldop(im.scan(definition, forward, init))(*stencil_args) + 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`), # not by e.g. its name. diff --git a/src/gt4py/next/ffront/foast_to_past.py b/src/gt4py/next/ffront/foast_to_past.py index beabe53c71..edc37bdeb8 100644 --- a/src/gt4py/next/ffront/foast_to_past.py +++ b/src/gt4py/next/ffront/foast_to_past.py @@ -36,6 +36,10 @@ class ItirShim: definition: ConcreteFOASTOperatorDef foast_to_itir: workflow.Workflow[ConcreteFOASTOperatorDef, itir.FunctionDefinition] + @property + def foast_stage(self) -> ffront_stages.FOASTOperatorDef: + return self.definition.data + def __gt_closure_vars__(self) -> Optional[dict[str, Any]]: return self.definition.data.closure_vars diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index cd908fca14..dfa3d4b5cd 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -18,6 +18,7 @@ from gt4py.next import common, config, errors, utils from gt4py.next.ffront import ( fbuiltins, + field_operator_ast as foast, gtcallable, program_ast as past, stages as ffront_stages, @@ -168,6 +169,17 @@ def _column_axis(all_closure_vars: dict[str, Any]) -> Optional[common.Dimension] ).items(): if isinstance((type_ := gt_callable.__gt_type__()), ts_ffront.ScanOperatorType): scanops_per_axis.setdefault(type_.axis, []).append(name) + elif isinstance( + foast_stage := getattr(gt_callable, "foast_stage", None), ffront_stages.FOASTOperatorDef + ): + for scan_call in ( + foast_stage.foast_node.walk_values() + .if_isinstance(foast.Call) + .filter(lambda call: isinstance(call.type, ts_ffront.ScanOperatorType)) + ): + scanops_per_axis.setdefault(scan_call.type.axis, []).append( + f"scan in '{name}' (line {scan_call.location.line})" + ) if len(scanops_per_axis.values()) == 0: return None diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py index 8ba6f3091a..3d0ab5e772 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py @@ -70,17 +70,17 @@ def test_scanop(): KDim = Dimension("KDim", kind=DimensionKind.VERTICAL) @scan_operator(axis=KDim, forward=False, init=1) - def scan(inp: int32) -> int32: + def scan_op(inp: int32) -> int32: foo = inp return inp expected = textwrap.dedent( f""" @scan_operator(axis=KDim[vertical], forward=False, init=1) - def scan(inp: int32) -> int32: + def scan_op(inp: int32) -> int32: {ssa.unique_name("foo", 0)} = inp return inp """ ).strip() - assert pretty_format(scan.foast_stage.foast_node) == expected + assert pretty_format(scan_op.foast_stage.foast_node) == expected 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 ae9e9b37ef..508c3b0d1a 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,7 +11,7 @@ import pytest import gt4py.next as gtx -from gt4py.next import errors, float64, int32 +from gt4py.next import errors, float64, int32, scan from gt4py.next.ffront.decorator import program, scan_operator from next_tests.integration_tests import cases @@ -391,3 +391,68 @@ def test_scan_without_carry(cartesian_case): @scan_operator(axis=KDim, forward=True, init=0) def testee_scan() -> float: return 1.0 + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_call(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, axis=KDim, forward=True, init=1.0)(inp) + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + + cases.verify(cartesian_case, testee, inp, out=out, ref=1.0 + np.cumsum(inp.asnumpy(), axis=1)) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_call_backward_inferred_axis(cartesian_case): + @gtx.field_operator + def add(carry: float, inp: float, scalar: float) -> float: + return carry + inp * scalar + + @gtx.field_operator + def testee(inp: cases.IKFloatField, scalar: float) -> cases.IKFloatField: + return scan(add, forward=False, init=-1.0)(inp, scalar) + inp + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + inp_np = inp.asnumpy() + backward_cumsum = np.flip(np.cumsum(np.flip(2.0 * inp_np, axis=1), axis=1), axis=1) + + cases.verify(cartesian_case, testee, inp, 2.0, out=out, ref=backward_cumsum - 1.0 + inp_np) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_tuple_returns +def test_scan_call_tuple_carry(cartesian_case): + @gtx.field_operator + def sum_and_count(carry: tuple[float, int32], inp: float) -> tuple[float, int32]: + return carry[0] + inp, carry[1] + int32(1) + + @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) + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + isize = cartesian_case.default_sizes[IDim] + ksize = cartesian_case.default_sizes[KDim] + + cases.verify( + cartesian_case, + testee, + inp, + out=out, + ref=( + np.cumsum(inp.asnumpy(), axis=1), + np.full((isize, ksize), np.arange(1, ksize + 1, dtype=np.int32)), + ), + ) 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 b6ae674312..3ddee90be9 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 @@ -26,7 +26,9 @@ float64, int32, int64, + field_operator, neighbor_sum, + scan, where, ) from gt4py.next.ffront.experimental import concat_where @@ -798,3 +800,75 @@ def testee( match="Second and third argument to 'concat_where' must have the same tuple/collection structure", ): parsed = FieldOperatorParser.apply_to_function(testee) + + +KDim = Dimension("KDim", kind=DimensionKind.VERTICAL) + + +@field_operator +def _scan_pass(carry: float, inp: float) -> float: + return carry + inp + + +def test_scan_call(): + def scan_call(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, init=0.0)(a) + + parsed = FieldOperatorParser.apply_to_function(scan_call) + + assert parsed.type.returns == ts.FieldType( + dims=[TDim, KDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) + ) + + +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) + return a + + with pytest.raises( + errors.DSLError, match=r"'scan' creates a scan operator which must be called" + ): + _ = FieldOperatorParser.apply_to_function(scan_not_called) + + +def test_scan_call_axis_not_inferable(): + def no_vertical_dim(a: Field[[TDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass)(a) + + with pytest.raises(errors.DSLError, match=r"Cannot infer the 'axis' of 'scan'"): + _ = FieldOperatorParser.apply_to_function(no_vertical_dim) + + +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)(a) + + with pytest.raises(errors.DSLError, match=r"'axis' to 'scan' must be a vertical dimension"): + _ = FieldOperatorParser.apply_to_function(non_vertical_axis) + + +def test_scan_call_non_constant_init(): + def non_constant_init( + a: Field[[TDim, KDim], float64], init: float64 + ) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=KDim, init=init)(a) + + with pytest.raises(errors.DSLError, match=r"'init' to 'scan' must be a compile-time constant"): + _ = FieldOperatorParser.apply_to_function(non_constant_init) + + +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) + + with pytest.raises(errors.DSLError, match=r"Argument 'init' to scan operator '_scan_pass'"): + _ = FieldOperatorParser.apply_to_function(wrong_init_type) + + +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)(a) + + with pytest.raises(errors.DSLError, match=r"The scan pass must be a field operator"): + _ = FieldOperatorParser.apply_to_function(pass_is_builtin) From c4ea9d77bf5e16be2501cbc1ca7d3280cb5b4d2e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 1 Dec 2026 15:14:58 +0100 Subject: [PATCH 02/18] refactor[next]: share scan argument checks and lowering between scan builtin and scan_operator - One check of axis, forward and init for both paths; absent arguments are checked by their default. - Defaults are inserted by the lowering, taken from the signature of the scan builtin. - One lowering helper for both paths; the scan lambda uses the scan pass's own parameter names. - Move is_literal to foast_passes/utils.py. --- src/gt4py/next/ffront/fbuiltins.py | 7 ++ .../ffront/foast_passes/type_deduction.py | 100 +++++++++--------- src/gt4py/next/ffront/foast_passes/utils.py | 15 +++ src/gt4py/next/ffront/foast_to_gtir.py | 58 ++++++---- .../ffront_tests/test_type_deduction.py | 9 +- 5 files changed, 117 insertions(+), 72 deletions(-) diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 558f344726..0e6cca7c53 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -336,6 +336,13 @@ def scan_operator(*args: Any, **kwargs: Any) -> common.Field | Tuple: return scan_operator +SCAN_DEFAULTS: Final[dict[str, Any]] = { + name: param.default + for name, param in inspect.signature(scan.function).parameters.items() + if param.default is not inspect.Parameter.empty +} + + @WhereBuiltinFunction def where( mask: common.Field, diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index 8415e43135..294df8caed 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -167,26 +167,42 @@ def _is_scan_builtin(expr: foast.Expr) -> bool: return isinstance(expr, foast.Name) and expr.id == "scan" -def _is_literal(expr: foast.Expr) -> bool: - match expr: - case foast.Constant(): - return True - case foast.TupleExpr(): - return all(_is_literal(el) for el in expr.elts) - case foast.UnaryOp(): - return _is_literal(expr.operand) - case foast.Call(func=foast.Name(type=ts.ConstructorType())): - return all(_is_literal(arg) for arg in expr.args) - return False - - -def _check_scan_pass( +def _check_scan_args( location: eve.SourceLocation, name: str, pass_type: ts.FunctionType, - forward_type: ts.TypeSpec, - init_type: ts.TypeSpec, + *, + axis: Optional[foast.Expr], + forward: Optional[foast.Expr], + init: Optional[foast.Expr], ) -> None: + """Check the arguments of a scan operator. An absent argument is checked by its default.""" + if axis is not None: + 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.", + ) + for arg_name, arg in (("forward", forward), ("init", init)): + if arg is not None and not foast_utils.is_literal(arg): + raise errors.DSLError( + arg.location, + f"Argument '{arg_name}' to scan operator '{name}' must be a compile-time constant.", + ) + forward_type = ( + forward.type + if forward is not None + else type_translation.from_value(fbuiltins.SCAN_DEFAULTS["forward"]) + ) + init_type = ( + init.type + if init is not None + else type_translation.from_value(fbuiltins.SCAN_DEFAULTS["init"]) + ) if not (isinstance(forward_type, ts.ScalarType) and forward_type.kind == ts.ScalarKind.BOOL): raise errors.DSLError( location, f"Argument 'forward' to scan operator '{name}' must be a boolean." @@ -298,20 +314,16 @@ def visit_FieldOperator(self, node: foast.FieldOperator, **kwargs: Any) -> foast def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.ScanOperator: new_axis = self.visit(node.axis, **kwargs) - if not isinstance(new_axis.type, ts.DimensionType): - raise errors.DSLError( - node.location, f"Argument 'axis' to scan operator '{node.id}' must be a dimension." - ) - if not new_axis.type.dim.kind == DimensionKind.VERTICAL: - raise errors.DSLError( - node.location, - f"Argument 'axis' to scan operator '{node.id}' must be a vertical dimension.", - ) new_forward = self.visit(node.forward, **kwargs) new_init = self.visit(node.init, **kwargs) new_definition = self.visit(node.definition, **kwargs) - _check_scan_pass( - node.location, node.id, new_definition.type, new_forward.type, new_init.type + _check_scan_args( + node.location, + node.id, + new_definition.type, + axis=new_axis, + forward=new_forward, + init=new_init, ) new_type = ts_ffront.ScanOperatorType( @@ -351,20 +363,14 @@ def _visit_scan_call( pass_type = new_pass.type.definition pass_name = str(new_pass) - new_kwargs = { - "forward": foast.Constant(value=True, location=node.location), - "init": foast.Constant(value=0.0, location=node.location), - **node.kwargs, - } - new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in new_kwargs.items()} - for name in ("forward", "init"): - if not _is_literal(new_kwargs[name]): - raise errors.DSLError( - new_kwargs[name].location, - f"Argument '{name}' to 'scan' must be a compile-time constant.", - ) - _check_scan_pass( - node.location, pass_name, pass_type, new_kwargs["forward"].type, new_kwargs["init"].type + new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in node.kwargs.items()} + _check_scan_args( + node.location, + pass_name, + pass_type, + axis=new_kwargs.get("axis"), + forward=new_kwargs.get("forward"), + init=new_kwargs.get("init"), ) if not all( isinstance(t, ts.ScalarType) @@ -383,16 +389,8 @@ def _visit_scan_call( if "axis" in new_kwargs: axis_type = new_kwargs["axis"].type - if not isinstance(axis_type, ts.DimensionType): - raise errors.DSLError( - new_kwargs["axis"].location, "Argument 'axis' to 'scan' must be a dimension." - ) + assert isinstance(axis_type, ts.DimensionType) axis = axis_type.dim - if axis.kind != DimensionKind.VERTICAL: - raise errors.DSLError( - new_kwargs["axis"].location, - "Argument 'axis' to 'scan' must be a vertical dimension.", - ) else: vertical_dims = { dim @@ -915,6 +913,8 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: new_func, (foast.FunctionDefinition, foast.FieldOperator, foast.ScanOperator, foast.Name), ) and not ( + # `scan(pass, ...)` is the only higher-order builtin, so its result is the only + # callable call result. isinstance(new_func, foast.Call) and isinstance(new_func.type, ts_ffront.ScanOperatorType) ): diff --git a/src/gt4py/next/ffront/foast_passes/utils.py b/src/gt4py/next/ffront/foast_passes/utils.py index fa066e9d76..808ca6fc69 100644 --- a/src/gt4py/next/ffront/foast_passes/utils.py +++ b/src/gt4py/next/ffront/foast_passes/utils.py @@ -7,6 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause from gt4py.next.ffront import dialect_ast_enums, field_operator_ast as foast +from gt4py.next.type_system import type_specifications as ts def compute_assign_indices( @@ -80,3 +81,17 @@ def expr_to_index(expr: foast.Expr) -> int: return expr.operand.value raise ValueError(f"Not an index: '{expr}'.") + + +def is_literal(expr: foast.Expr) -> bool: + """Whether `expr` is a constant, or a tuple, unary operation or type constructor of constants.""" + match expr: + case foast.Constant(): + return True + case foast.TupleExpr(): + return all(is_literal(el) for el in expr.elts) + case foast.UnaryOp(): + return is_literal(expr.operand) + case foast.Call(func=foast.Name(type=ts.ConstructorType())): + return all(is_literal(arg) for arg in expr.args) + return False diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index b08129d7b3..2dce60d192 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -134,19 +134,17 @@ def visit_ScanOperator( # lower definition function func_definition: itir.FunctionDefinition = self.visit(node.definition, **kwargs) - new_body = func_definition.expr - - stencil_args: list[itir.Expr] = [] assert not node.type.definition.pos_only_args and not node.type.definition.kw_only_args - for param in func_definition.params[1:]: - new_body = im.let(param.id, im.deref(param.id))(new_body) - stencil_args.append(im.ref(param.id)) - - definition = itir.Lambda(params=func_definition.params, expr=new_body) - - body = im.as_fieldop(im.scan(definition, forward, init))(*stencil_args) + params = func_definition.params + body = self._lower_scan( + itir.Lambda(params=params, expr=func_definition.expr), + [param.id for param in params], + forward, + init, + [im.ref(param.id) for param in params[1:]], + ) - return itir.FunctionDefinition(id=node.id, params=definition.params[1:], expr=body) + return itir.FunctionDefinition(id=node.id, params=params[1:], expr=body) def visit_Stmt(self, node: foast.Stmt, **kwargs: Any) -> Never: raise AssertionError("Statements must always be visited in the context of a function.") @@ -401,20 +399,40 @@ def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: scan_call = node.func assert isinstance(scan_call, foast.Call) assert isinstance(scan_call.type, ts_ffront.ScanOperatorType) - scan_pass = self.visit(scan_call.args[0], **kwargs) - forward = self.visit(scan_call.kwargs["forward"], **kwargs) - init = self.visit(scan_call.kwargs["init"], **kwargs) + scan_kwargs = { + name: ( + self.visit(scan_call.kwargs[name], **kwargs) + if name in scan_call.kwargs + else im.literal_from_value(fbuiltins.SCAN_DEFAULTS[name]) + ) + for name in ("forward", "init") + } lowered_args, lowered_kwargs = type_info.canonicalize_arguments( scan_call.type, self.visit(node.args, **kwargs), self.visit(node.kwargs, **kwargs) ) - stencil_args = [*lowered_args, *lowered_kwargs.values()] - carry = next(self.uid_generator["__scan_carry"]) - params = [next(self.uid_generator["__scan_arg"]) for _ in stencil_args] - definition = im.lambda_(carry, *params)( - im.call(scan_pass)(carry, *(im.deref(param) for param in params)) + return self._lower_scan( + self.visit(scan_call.args[0], **kwargs), + list(scan_call.type.definition.pos_or_kw_args), + scan_kwargs["forward"], + scan_kwargs["init"], + [*lowered_args, *lowered_kwargs.values()], + ) + + @staticmethod + def _lower_scan( + scan_pass: itir.Expr, + param_names: list[str], + forward: itir.Expr, + init: itir.Expr, + args: list[itir.Expr], + ) -> 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))(*stencil_args) + return im.as_fieldop(im.scan(definition, forward, init))(*args) 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/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py b/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py index 3ddee90be9..3bfd4d1aaa 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 @@ -844,7 +844,9 @@ 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)(a) - with pytest.raises(errors.DSLError, match=r"'axis' to 'scan' must be a vertical dimension"): + with pytest.raises( + errors.DSLError, match=r"'axis' to scan operator '_scan_pass' must be a vertical dimension" + ): _ = FieldOperatorParser.apply_to_function(non_vertical_axis) @@ -854,7 +856,10 @@ def non_constant_init( ) -> Field[[TDim, KDim], float64]: return scan(_scan_pass, axis=KDim, init=init)(a) - with pytest.raises(errors.DSLError, match=r"'init' to 'scan' must be a compile-time constant"): + with pytest.raises( + errors.DSLError, + match=r"'init' to scan operator '_scan_pass' must be a compile-time constant", + ): _ = FieldOperatorParser.apply_to_function(non_constant_init) From 1063ce3888c46ca3e547cb00426dc70351c7c5de Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 1 Dec 2026 15:27:21 +0100 Subject: [PATCH 03/18] refactor[next]: register the embedded scan builtin from the embedded side fbuiltins no longer imports embedded.operators. As for the other builtins, the embedded implementation is registered in nd_array_field's builtin registry, from embedded/operators.py, and dispatched on the arguments of the scan operator, so ArrayOps builtin_overrides apply to scan too. The registry also finds fields nested in tuples and passed as keyword arguments. --- src/gt4py/next/embedded/nd_array_field.py | 36 ++++++++++--------- src/gt4py/next/embedded/operators.py | 24 ++++++++++++- src/gt4py/next/ffront/fbuiltins.py | 24 ++++++++----- .../feature_tests/ffront_tests/test_scan.py | 21 +++++++++++ 4 files changed, 80 insertions(+), 25 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 2be6dcd62a..b583ed0769 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -40,6 +40,8 @@ def _ops_of(*values: Any) -> array_ops.ArrayOps: for v in values: if isinstance(v, NdArrayField): return array_ops.of(v._ndarray) + if nested := [el for v in values if isinstance(v, tuple) for el in v]: + return _ops_of(*nested) raise AssertionError("No 'NdArrayField' found in the arguments.") @@ -800,22 +802,24 @@ def _inverse_image_box( _builtin_implementations: dict[fbuiltins.BuiltInFunction, Callable[..., Any]] = {} -def _register_builtin(builtin: fbuiltins.BuiltInFunction, impl: Callable[..., Any]) -> None: +def register_builtin(builtin: fbuiltins.BuiltInFunction, impl: Callable[..., Any]) -> None: """Register `impl` for `builtin`, unless the `ArrayOps` of the first field argument replaces it.""" def dispatch(*args: Any, **kwargs: Any) -> Any: - return _ops_of(*args).builtin_overrides.get(builtin, impl)(*args, **kwargs) + return _ops_of(*args, *kwargs.values()).builtin_overrides.get(builtin, impl)( + *args, **kwargs + ) dispatch.__name__ = getattr(impl, "__name__", builtin.name) assert builtin not in _builtin_implementations _builtin_implementations[builtin] = dispatch -_register_builtin( +register_builtin( fbuiltins.abs, NdArrayField.__abs__, ) -_register_builtin( +register_builtin( fbuiltins.power, NdArrayField.__pow__, ) @@ -827,21 +831,21 @@ def dispatch(*args: Any, **kwargs: Any) -> Any: ): if name in ["abs", "power"]: continue - _register_builtin(getattr(fbuiltins, name), _make_builtin(name, name)) + register_builtin(getattr(fbuiltins, name), _make_builtin(name, name)) -_register_builtin( +register_builtin( fbuiltins.minimum, _make_builtin("minimum", "minimum"), ) -_register_builtin( +register_builtin( fbuiltins.maximum, _make_builtin("maximum", "maximum"), ) -_register_builtin( +register_builtin( fbuiltins.fmod, _make_builtin("fmod", "fmod"), ) -_register_builtin(fbuiltins.where, _make_builtin("where", "where")) +register_builtin(fbuiltins.where, _make_builtin("where", "where")) def _to_field(value: common.Field | core_defs.Scalar, like: NdArrayField) -> common.Field: @@ -984,7 +988,7 @@ def _concat_where( return _concat(*f_slices, *t_slices, dim=domain_dim) -_register_builtin(experimental.concat_where, _concat_where) +register_builtin(experimental.concat_where, _concat_where) def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> common.Connectivity: @@ -1008,7 +1012,7 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> com ) -_register_builtin(experimental.as_offset, _as_offset) +register_builtin(experimental.as_offset, _as_offset) def _make_reduction( @@ -1086,7 +1090,7 @@ def _builtin_op( return _builtin_op -_register_builtin( +register_builtin( fbuiltins.neighbor_sum, _make_reduction( "neighbor_sum", @@ -1095,7 +1099,7 @@ def _builtin_op( lambda x: x.dtype.scalar_type(0), ), ) -_register_builtin( +register_builtin( fbuiltins.max_over, _make_reduction( "max_over", @@ -1103,7 +1107,7 @@ def _builtin_op( lambda x: array_ops.of(x._ndarray).xp.min(x._ndarray), ), ) -_register_builtin( +register_builtin( fbuiltins.min_over, _make_reduction( "min_over", @@ -1170,7 +1174,7 @@ def _builtins_broadcast( raise AssertionError("Scalar case not reachable from 'fbuiltins.broadcast'.") -_register_builtin(fbuiltins.broadcast, _builtins_broadcast) +register_builtin(fbuiltins.broadcast, _builtins_broadcast) def _astype(field: common.Field | core_defs.ScalarT | tuple, type_: type) -> NdArrayField: @@ -1182,7 +1186,7 @@ def _astype(field: common.Field | core_defs.ScalarT | tuple, type_: type) -> NdA raise AssertionError("This is the NdArrayField implementation of 'fbuiltins.astype'.") -_register_builtin(fbuiltins.astype, _astype) # type: ignore[arg-type] # because fbuiltins.astype is overloaded +register_builtin(fbuiltins.astype, _astype) # type: ignore[arg-type] # because fbuiltins.astype is overloaded def _get_slices_from_domain_slice( diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 05e8e7a46a..d85fd1fa92 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -15,7 +15,13 @@ from gt4py._core import definitions as core_defs from gt4py.eve import xtyping from gt4py.next import common, errors, field_utils, named_collections, utils -from gt4py.next.embedded import array_ops, common as embedded_common, context as embedded_context +from gt4py.next.embedded import ( + array_ops, + common as embedded_common, + context as embedded_context, + nd_array_field, +) +from gt4py.next.ffront import fbuiltins from gt4py.next.otf import arguments from gt4py.next.type_system import type_specifications as ts, type_translation @@ -209,3 +215,19 @@ def impl(field: common.Field | array_ops.NDValue) -> array_ops.NDValue: return res return impl(field) # type: ignore[return-value] + + +def _scan( + scan_pass: Callable, + axis: Optional[common.Dimension], + forward: bool, + init: core_defs.Scalar | tuple, + /, + *args: Any, + **kwargs: Any, +) -> common.Field | tuple: + scan_axis = axis if axis is not None else embedded_context.get_closure_column_range().dim + return ScanOperator(scan_pass, forward, init, scan_axis)(*args, **kwargs) + + +nd_array_field.register_builtin(fbuiltins.scan, _scan) diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 0e6cca7c53..fbdc6eac47 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -29,7 +29,7 @@ from numpy import float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64 from gt4py._core import definitions as core_defs -from gt4py.next import common, named_collections +from gt4py.next import common, named_collections, utils from gt4py.next.common import Dimension, Field # noqa: F401 [unused-import] for TYPE_BUILTINS from gt4py.next.embedded import array_ops, context as embedded_context from gt4py.next.iterator import runtime @@ -304,6 +304,20 @@ def __gt_type__(self) -> ts.FunctionType: returns=ts.DeferredType(constraint=None), ) + def __call__( # type: ignore[override] # the implementation is dispatched on the arguments of the scan operator + self, scan_pass: Callable, /, **scan_kwargs: Any + ) -> Callable[..., common.Field | Tuple]: + bound = inspect.signature(self.function).bind(scan_pass, **scan_kwargs) + bound.apply_defaults() + + def scan_operator(*args: Any, **kwargs: Any) -> common.Field | Tuple: + impl = self.dispatch(*utils.flatten_nested_tuple((*args, *kwargs.values()))) + if impl is self.function: + raise NotImplementedError(f"No implementation of 'scan' for arguments {args}.") + return cast(common.Field | Tuple, impl(*bound.arguments.values(), *args, **kwargs)) + + return scan_operator + @ScanBuiltinFunction def scan( @@ -327,13 +341,7 @@ def scan( Examples: >>> scan(my_pass, axis=KDim, forward=True, init=0.0)(a) # doctest: +SKIP """ - from gt4py.next.embedded import context as embedded_context, operators as embedded_operators - - def scan_operator(*args: Any, **kwargs: Any) -> common.Field | Tuple: - scan_axis = axis if axis is not None else embedded_context.get_closure_column_range().dim - return embedded_operators.ScanOperator(scan_pass, forward, init, scan_axis)(*args, **kwargs) - - return scan_operator + raise NotImplementedError() SCAN_DEFAULTS: Final[dict[str, Any]] = { 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 f990e86a2d..f7598503d6 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 @@ -430,6 +430,27 @@ def testee(inp: cases.IKFloatField, scalar: float) -> cases.IKFloatField: cases.verify(cartesian_case, testee, inp, 2.0, out=out, ref=backward_cumsum - 1.0 + inp_np) +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_tuple_args +def test_scan_call_tuple_arg(cartesian_case): + @gtx.field_operator + def add_pair(carry: float, pair: tuple[float, float]) -> float: + return carry + pair[0] * pair[1] + + @gtx.field_operator + def testee(a: cases.IKFloatField, b: cases.IKFloatField) -> cases.IKFloatField: + return scan(add_pair, axis=KDim)((a, b)) + + a = cases.allocate(cartesian_case, testee, "a")() + b = cases.allocate(cartesian_case, testee, "b")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + + cases.verify( + cartesian_case, testee, a, b, out=out, ref=np.cumsum(a.asnumpy() * b.asnumpy(), axis=1) + ) + + @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator @pytest.mark.uses_tuple_returns From 15844d6c8c1b30a2d848713a42c31731fb446158 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 1 Dec 2026 16:58:38 +0100 Subject: [PATCH 04/18] refactor[next]: require axis for scan, lower it through the builtin dispatch - 'axis' is required; the inference from the arguments and the embedded fallback to the closure column range are removed. - 'scan(...)' is lowered by '_visit_scan' through the existing builtin dispatch to a function of the pass's arguments, and the outer call takes the generic call path; '_lower_scan' is a free function. - The scalars-only check on the scan pass is shared with the decorator path, which failed with a bare AssertionError before; the unreachable positional-only/keyword-only check is removed. - The embedded field lookup flattens tuples like the dispatch does. --- src/gt4py/next/embedded/nd_array_field.py | 4 +- src/gt4py/next/embedded/operators.py | 7 +- src/gt4py/next/ffront/fbuiltins.py | 5 +- .../ffront/foast_passes/type_deduction.py | 95 ++++++------------- src/gt4py/next/ffront/foast_to_gtir.py | 76 +++++++-------- .../feature_tests/ffront_tests/test_scan.py | 4 +- .../ffront_tests/test_type_deduction.py | 19 +++- 7 files changed, 87 insertions(+), 123 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index b583ed0769..696944a4e3 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -37,11 +37,9 @@ def _ops_of(*values: Any) -> array_ops.ArrayOps: # TODO(havogt): the first field's array library decides, so mixing libraries depends on the # order of the operands; reject mixed libraries or define a priority instead. - for v in values: + for v in utils.flatten_nested_tuple(values): if isinstance(v, NdArrayField): return array_ops.of(v._ndarray) - if nested := [el for v in values if isinstance(v, tuple) for el in v]: - return _ops_of(*nested) raise AssertionError("No 'NdArrayField' found in the arguments.") diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index d85fd1fa92..c1c79fdafb 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -219,15 +219,16 @@ def impl(field: common.Field | array_ops.NDValue) -> array_ops.NDValue: def _scan( scan_pass: Callable, - axis: Optional[common.Dimension], + axis: common.Dimension, forward: bool, init: core_defs.Scalar | tuple, /, *args: Any, **kwargs: Any, ) -> common.Field | tuple: - scan_axis = axis if axis is not None else embedded_context.get_closure_column_range().dim - return ScanOperator(scan_pass, forward, init, scan_axis)(*args, **kwargs) + return ScanOperator(scan_pass, forward, init, axis)(*args, **kwargs) +# Registered here, not in `nd_array_field` like the other builtins: `nd_array_field` cannot +# import this module, which depends on it through `field_utils`. nd_array_field.register_builtin(fbuiltins.scan, _scan) diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index fbdc6eac47..851cc65b0e 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -324,7 +324,7 @@ def scan( scan_pass: Callable, /, *, - axis: common.Dimension | None = None, + axis: common.Dimension, forward: bool = True, init: core_defs.Scalar | Tuple = 0.0, ) -> Callable[..., common.Field | Tuple]: @@ -333,8 +333,7 @@ def scan( Args: scan_pass: Field operator `(carry, *args) -> carry` on scalars (or tuples thereof). - axis: Vertical dimension to scan along. If omitted, it is the unique vertical - dimension of the arguments the scan operator is called with. + axis: Vertical dimension to scan along. forward: Scan direction. init: Initial value of the carry, a compile-time constant. diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index 294df8caed..6abb38ae3e 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -172,21 +172,20 @@ def _check_scan_args( name: str, pass_type: ts.FunctionType, *, - axis: Optional[foast.Expr], + axis: foast.Expr, forward: Optional[foast.Expr], init: Optional[foast.Expr], -) -> None: - """Check the arguments of a scan operator. An absent argument is checked by its default.""" - if axis is not None: - 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.", - ) +) -> Dimension: + """Check the arguments of a scan operator and return its axis. An absent `forward` or `init` 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.", + ) for arg_name, arg in (("forward", forward), ("init", init)): if arg is not None and not foast_utils.is_literal(arg): raise errors.DSLError( @@ -235,6 +234,15 @@ def _check_scan_args( f"Argument 'init' to scan operator '{name}' must have same type as '{carry_arg_name}' argument: " f"expected '{carry_type}', got '{init_type}'.", ) + if not all( + isinstance(t, ts.ScalarType) + for param in [*pass_type.pos_or_kw_args.values(), pass_type.returns] + for t in type_info.primitive_constituents(param) + ): + raise errors.DSLError( + location, f"Scan operator '{name}' must take and return scalars or tuples of scalars." + ) + return axis.type.dim class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTranslator): @@ -317,7 +325,7 @@ 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) - _check_scan_args( + axis = _check_scan_args( node.location, node.id, new_definition.type, @@ -326,9 +334,7 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S init=new_init, ) - new_type = ts_ffront.ScanOperatorType( - axis=new_axis.type.dim, definition=new_definition.type - ) + new_type = ts_ffront.ScanOperatorType(axis=axis, definition=new_definition.type) return foast.ScanOperator( id=node.id, axis=new_axis, @@ -339,9 +345,7 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S location=node.location, ) - def _visit_scan_call( - self, node: foast.Call, scan_arg_types: list[ts.TypeSpec], **kwargs: Any - ) -> foast.Call: + def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> foast.Call: """Type `scan(pass, axis=..., forward=..., init=...)`, the callee of a call-site scan.""" new_func = self.visit(node.func, **kwargs) if len(node.args) != 1: @@ -354,6 +358,8 @@ def _visit_scan_call( node.location, f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.", ) + if "axis" not in node.kwargs: + raise errors.DSLError(node.location, "Missing argument 'axis' to 'scan'.") new_pass = self.visit(node.args[0], **kwargs) if not isinstance(new_pass.type, ts_ffront.FieldOperatorType): raise errors.DSLError( @@ -361,53 +367,16 @@ def _visit_scan_call( f"The scan pass must be a field operator, got '{new_pass.type}'.", ) pass_type = new_pass.type.definition - pass_name = str(new_pass) new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in node.kwargs.items()} - _check_scan_args( + axis = _check_scan_args( node.location, - pass_name, + str(new_pass), pass_type, - axis=new_kwargs.get("axis"), + axis=new_kwargs["axis"], forward=new_kwargs.get("forward"), init=new_kwargs.get("init"), ) - if not all( - isinstance(t, ts.ScalarType) - for param in [*pass_type.pos_or_kw_args.values(), pass_type.returns] - for t in type_info.primitive_constituents(param) - ): - raise errors.DSLError( - new_pass.location, - f"The scan pass '{pass_name}' must take and return scalars or tuples of scalars.", - ) - if pass_type.pos_only_args or pass_type.kw_only_args: - raise errors.DSLError( - new_pass.location, - f"The scan pass '{pass_name}' must not have positional-only or keyword-only arguments.", - ) - - if "axis" in new_kwargs: - axis_type = new_kwargs["axis"].type - assert isinstance(axis_type, ts.DimensionType) - axis = axis_type.dim - else: - vertical_dims = { - dim - for arg_type in scan_arg_types - for el in type_info.primitive_constituents(arg_type) - for dim in type_info.extract_dims(el) - if dim.kind == DimensionKind.VERTICAL - } - if len(vertical_dims) != 1: - found = ", ".join(sorted(f"'{d.value}'" for d in vertical_dims)) or "none" - raise errors.DSLError( - node.location, - "Cannot infer the 'axis' of 'scan' from its arguments, expected exactly one " - f"vertical dimension, found {found}.", - hints=["Pass the axis explicitly, e.g. 'scan(..., axis=KDim)'."], - ) - (axis,) = vertical_dims return foast.Call( func=new_func, @@ -886,11 +855,7 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: new_args = self.visit(node.args, **kwargs) new_kwargs = self.visit(node.kwargs, **kwargs) if isinstance(node.func, foast.Call) and _is_scan_builtin(node.func.func): - new_func = self._visit_scan_call( - node.func, - scan_arg_types=[arg.type for arg in [*new_args, *new_kwargs.values()]], - **kwargs, - ) + new_func = self._visit_scan_call(node.func, **kwargs) else: new_func = self.visit(node.func, **kwargs) diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 2dce60d192..c6fccaee91 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -65,6 +65,21 @@ def promote_to_list(node_type: ts.TypeSpec) -> Callable[[itir.Expr], itir.Expr]: return lambda x: x +def _lower_scan( + scan_pass: itir.Expr, + param_names: list[str], + forward: itir.Expr, + init: itir.Expr, + args: list[itir.Expr], +) -> 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))(*args) + + @dataclasses.dataclass class FieldOperatorLowering(eve.PreserveLocationVisitor, eve.NodeTranslator): """ @@ -136,7 +151,7 @@ def visit_ScanOperator( func_definition: itir.FunctionDefinition = self.visit(node.definition, **kwargs) assert not node.type.definition.pos_only_args and not node.type.definition.kw_only_args params = func_definition.params - body = self._lower_scan( + body = _lower_scan( itir.Lambda(params=params, expr=func_definition.expr), [param.id for param in params], forward, @@ -348,11 +363,7 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr: return current_expr def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: - if isinstance(node.func, foast.Call) and isinstance( - node.func.type, ts_ffront.ScanOperatorType - ): - return self._visit_scan_call(node, **kwargs) - elif type_info.type_class(node.func.type) is ts.FieldType: + if type_info.type_class(node.func.type) is ts.FieldType: return self._visit_shift(node, **kwargs) elif isinstance(node.func, foast.Name) and node.func.id in fbuiltins.MATH_BUILTIN_NAMES: return self._visit_math_built_in(node, **kwargs) @@ -394,45 +405,26 @@ 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_call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: - # `scan(scan_pass, forward=..., init=...)(*args)` - scan_call = node.func - assert isinstance(scan_call, foast.Call) - assert isinstance(scan_call.type, ts_ffront.ScanOperatorType) - scan_kwargs = { - name: ( - self.visit(scan_call.kwargs[name], **kwargs) - if name in scan_call.kwargs - else im.literal_from_value(fbuiltins.SCAN_DEFAULTS[name]) - ) + 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 + assert isinstance(node.type, ts_ffront.ScanOperatorType) + forward, init = ( + self.visit(node.kwargs[name], **kwargs) + if name in node.kwargs + else im.literal_from_value(fbuiltins.SCAN_DEFAULTS[name]) for name in ("forward", "init") - } - - lowered_args, lowered_kwargs = type_info.canonicalize_arguments( - scan_call.type, self.visit(node.args, **kwargs), self.visit(node.kwargs, **kwargs) - ) - return self._lower_scan( - self.visit(scan_call.args[0], **kwargs), - list(scan_call.type.definition.pos_or_kw_args), - scan_kwargs["forward"], - scan_kwargs["init"], - [*lowered_args, *lowered_kwargs.values()], ) - - @staticmethod - def _lower_scan( - scan_pass: itir.Expr, - param_names: list[str], - forward: itir.Expr, - init: itir.Expr, - args: list[itir.Expr], - ) -> 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)) + param_names = list(node.type.definition.pos_or_kw_args) + return im.lambda_(*param_names[1:])( + _lower_scan( + self.visit(node.args[0], **kwargs), + param_names, + forward, + init, + [im.ref(param) for param in param_names[1:]], + ) ) - return im.as_fieldop(im.scan(definition, forward, init))(*args) 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/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 f7598503d6..8b47af8d1f 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 @@ -413,14 +413,14 @@ def testee(inp: cases.IKFloatField) -> cases.IKFloatField: @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator -def test_scan_call_backward_inferred_axis(cartesian_case): +def test_scan_call_backward(cartesian_case): @gtx.field_operator def add(carry: float, inp: float, scalar: float) -> float: return carry + inp * scalar @gtx.field_operator def testee(inp: cases.IKFloatField, scalar: float) -> cases.IKFloatField: - return scan(add, forward=False, init=-1.0)(inp, scalar) + inp + return scan(add, axis=KDim, forward=False, init=-1.0)(inp, scalar) + inp inp = cases.allocate(cartesian_case, testee, "inp")() out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() 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 3bfd4d1aaa..5c872937d9 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 @@ -29,6 +29,7 @@ field_operator, neighbor_sum, scan, + scan_operator, where, ) from gt4py.next.ffront.experimental import concat_where @@ -812,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, init=0.0)(a) + return scan(_scan_pass, axis=KDim, init=0.0)(a) parsed = FieldOperatorParser.apply_to_function(scan_call) @@ -821,6 +822,14 @@ def scan_call(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: ) +def test_scan_operator_field_param(): + with pytest.raises(errors.DSLError, match=r"must take and return scalars"): + + @scan_operator(axis=KDim, forward=True, init=0.0) + def field_param(carry: float, inp: Field[[TDim, KDim], float64]) -> float: + return carry + + 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) @@ -832,12 +841,12 @@ def scan_not_called(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], floa _ = FieldOperatorParser.apply_to_function(scan_not_called) -def test_scan_call_axis_not_inferable(): - def no_vertical_dim(a: Field[[TDim], float64]) -> Field[[TDim, KDim], float64]: +def test_scan_call_missing_axis(): + def missing_axis(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: return scan(_scan_pass)(a) - with pytest.raises(errors.DSLError, match=r"Cannot infer the 'axis' of 'scan'"): - _ = FieldOperatorParser.apply_to_function(no_vertical_dim) + with pytest.raises(errors.DSLError, match=r"Missing argument 'axis' to 'scan'"): + _ = FieldOperatorParser.apply_to_function(missing_axis) def test_scan_call_non_vertical_axis(): From df49ba458fea99b60ca2568155a4b4b62f326aad Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 1 Dec 2026 17:45:24 +0100 Subject: [PATCH 05/18] refactor[next]: carry the scan axis on the GTIR `scan` builtin `scan(scan_pass, forward, init, axis)` now takes the scan axis as a fourth argument (an `AxisLiteral`), set by the frontend from the scan operator's axis. gtfn, dace and the embedded iterator read the axis from the scan node, so the program-wide `column_axis` (`CompileTimeArgs.column_axis`, the backend parameters, the iterator `fendef(column_axis=...)` kwarg) is removed, and with it the restriction that all scan operators in a program use the same axis. The embedded iterator executes a closure column-wise only when its stencil is a `scan`; a scan nested inside a stencil is no longer supported there. --- src/gt4py/next/ffront/foast_to_gtir.py | 4 +- src/gt4py/next/ffront/foast_to_past.py | 1 - src/gt4py/next/ffront/past_process_args.py | 1 - src/gt4py/next/ffront/past_to_itir.py | 32 +--------- src/gt4py/next/iterator/ARCHITECTURE.md | 2 +- src/gt4py/next/iterator/embedded.py | 61 +++++++++---------- src/gt4py/next/iterator/ir_utils/ir_makers.py | 4 +- src/gt4py/next/iterator/ir_utils/misc.py | 15 +++-- src/gt4py/next/iterator/runtime.py | 22 ++----- .../next/iterator/transforms/trace_shifts.py | 2 +- .../iterator/type_system/type_synthesizer.py | 6 +- src/gt4py/next/otf/arguments.py | 6 +- src/gt4py/next/otf/compiled_program.py | 1 - .../codegens/gtfn/gtfn_module.py | 8 +-- .../codegens/gtfn/itir_to_gtfn_ir.py | 12 ++-- .../program_processors/formatters/gtfn.py | 1 - .../runners/dace/lowering/gtir_to_sdfg.py | 28 +-------- .../dace/lowering/gtir_to_sdfg_scan.py | 18 ++++-- .../runners/dace/workflow/translation.py | 6 +- .../program_processors/runners/roundtrip.py | 7 --- tests/next_tests/definitions.py | 1 + .../feature_tests/ffront_tests/test_scan.py | 34 +++++++++++ .../iterator_tests/test_builtins.py | 23 +++---- .../feature_tests/iterator_tests/test_scan.py | 5 +- .../iterator_tests/test_column_stencil.py | 34 ++++++----- .../iterator_tests/test_vertical_advection.py | 9 ++- .../iterator_tests/test_type_inference.py | 4 +- .../transforms_tests/test_collapse_tuple.py | 7 ++- .../transforms_tests/test_domain_inference.py | 4 +- .../transforms_tests/test_fuse_as_fieldop.py | 6 +- .../transforms_tests/test_global_tmps.py | 2 +- .../transforms_tests/test_inline_into_scan.py | 2 + .../transforms_tests/test_scan_fusion.py | 1 + .../test_simple_inline_heuristic.py | 2 + .../otf_tests/test_compiled_program.py | 2 - .../gtfn_tests/test_gtfn_module.py | 6 -- .../gtfn_tests/test_itir_to_gtfn_ir.py | 14 ++--- .../dace_tests/test_dace_translation.py | 3 +- .../dace_tests/test_gtir_to_sdfg.py | 4 +- .../dace_tests/test_scan_fusion.py | 12 ++-- 40 files changed, 181 insertions(+), 231 deletions(-) diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 6913b5d6be..c453193eba 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -122,8 +122,6 @@ def visit_FieldOperator( def visit_ScanOperator( self, node: foast.ScanOperator, **kwargs: Any ) -> itir.FunctionDefinition: - # note: we don't need the axis here as this is handled by the program - # decorator assert isinstance(node.type, ts_ffront.ScanOperatorType) # We are lowering node.forward and node.init to iterators, but here we expect values -> `deref`. @@ -144,7 +142,7 @@ def visit_ScanOperator( definition = itir.Lambda(params=func_definition.params, expr=new_body) - body = im.as_fieldop(im.scan(definition, forward, init))(*stencil_args) + body = im.as_fieldop(im.scan(definition, forward, init, node.type.axis))(*stencil_args) return itir.FunctionDefinition(id=node.id, params=definition.params[1:], expr=body) diff --git a/src/gt4py/next/ffront/foast_to_past.py b/src/gt4py/next/ffront/foast_to_past.py index beabe53c71..5faa7aba2a 100644 --- a/src/gt4py/next/ffront/foast_to_past.py +++ b/src/gt4py/next/ffront/foast_to_past.py @@ -78,7 +78,6 @@ class OperatorToProgram(workflow.Workflow[ConcreteFOASTOperatorDef, ConcretePAST ... ), ... kwargs={}, ... offset_provider={}, - ... column_axis=None, ... argument_descriptor_contexts={}, ... ) diff --git a/src/gt4py/next/ffront/past_process_args.py b/src/gt4py/next/ffront/past_process_args.py index 859776ccc7..13da6915d0 100644 --- a/src/gt4py/next/ffront/past_process_args.py +++ b/src/gt4py/next/ffront/past_process_args.py @@ -30,7 +30,6 @@ def transform_program_args( args=rewritten_args, kwargs=rewritten_kwargs, offset_provider=inp.args.offset_provider, - column_axis=inp.args.column_axis, argument_descriptor_contexts=inp.args.argument_descriptor_contexts, ), ) diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index cd908fca14..13b5a76f8a 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -58,7 +58,6 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: ... args=tuple(param.type for param in copy_program.past_stage.past_node.params), ... kwargs={}, ... offset_provider={}, - ... column_axis=None, ... argument_descriptor_contexts={}, ... ) @@ -137,9 +136,7 @@ def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: kwargs: dict[str, ts.TypeSpec] = { k: ffront_ti.named_collections_to_tuple_types(v) for k, v in inp.args.kwargs.items() } - compile_time_args = dataclasses.replace( - inp.args, args=args, kwargs=kwargs, column_axis=_column_axis(all_closure_vars) - ) + compile_time_args = dataclasses.replace(inp.args, args=args, kwargs=kwargs) if config.DEBUG or inp.data.debug: devtools.debug(itir_program) @@ -158,33 +155,6 @@ def past_to_gtir_factory( return wf -def _column_axis(all_closure_vars: dict[str, Any]) -> Optional[common.Dimension]: - # construct mapping from column axis to scan operators defined on - # that dimension. only one column axis is allowed, but we can use - # this mapping to provide good error messages. - scanops_per_axis: dict[common.Dimension, list[str]] = {} - for name, gt_callable in transform_utils._filter_closure_vars_by_type( - all_closure_vars, gtcallable.GTCallable - ).items(): - if isinstance((type_ := gt_callable.__gt_type__()), ts_ffront.ScanOperatorType): - scanops_per_axis.setdefault(type_.axis, []).append(name) - - if len(scanops_per_axis.values()) == 0: - return None - - if len(scanops_per_axis.values()) != 1: - scanops_per_axis_str = "\n".join( - f"- {dim.value}: {', '.join(scanops)}" for dim, scanops in scanops_per_axis.items() - ) - - raise TypeError( - "Only 'ScanOperator's defined on the same axis " - f"can be used in a 'Program', found:\n{scanops_per_axis_str}\n" - ) - - return iter(scanops_per_axis.keys()).__next__() - - def _compute_field_slice(node: past.Subscript) -> list[past.Slice]: out_field_name: past.Name = node.value out_field_slice_: list[past.Slice] diff --git a/src/gt4py/next/iterator/ARCHITECTURE.md b/src/gt4py/next/iterator/ARCHITECTURE.md index e7cc832f00..47d33d1c1b 100644 --- a/src/gt4py/next/iterator/ARCHITECTURE.md +++ b/src/gt4py/next/iterator/ARCHITECTURE.md @@ -26,7 +26,7 @@ Sketch: - fields are np arrays with named axes; names are instances of `Dimension` - in `closure()`, the stencil is executed for each point in the domain, the fields are wrapped in an iterator pointing to the current point of execution. - as described in the design, offsets are abstract; on fencil execution the `offset_provider` keyword argument needs to be specified, which is a dict of `str` to either `Dimension` or `Connectivity` -- if `column_axis` keyword argument is specified on fencil execution (or in the fencil decorator), all operations will be done column wise in the give axis; `column_axis` needs to be specified if `scan` is used +- a closure whose stencil is a `scan(scan_pass, forward, init, axis)` is executed column wise along `axis` ## Tracing diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 9f3ecf1a80..4ab7319971 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -263,7 +263,7 @@ def _numpy_structured_value_to_tuples(value: Any) -> Any: class Column(np.lib.mixins.NDArrayOperatorsMixin): - """Represents a column when executed in column mode (`column_axis != None`). + """Represents a column when executed in column mode, i.e. within a scan. Implements `__array_ufunc__` and `__array_function__` to isolate and simplify dispatching in iterator ir builtins. @@ -1627,23 +1627,28 @@ def _elem_dtype(elem: Any) -> np.dtype: return np.dtype(type(elem)) -@builtins.scan.register(EMBEDDED) -def scan(scan_pass, is_forward: bool, init): - def impl(*iters: ItIterator): - column_range = embedded_context.get_closure_column_range().unit_range - if column_range is None: - raise RuntimeError("Column range is not defined, cannot scan.") +@dataclasses.dataclass(frozen=True) +class _Scan: + scan_pass: Callable + is_forward: bool + init: Any + axis: common.Dimension - sorted_column_range = column_range if is_forward else reversed(column_range) - state = init - col = Column(column_range.start, np.zeros(len(column_range), dtype=_elem_dtype(init))) + def __call__(self, *iters: ItIterator) -> Column: + column_range = embedded_context.get_closure_column_range().unit_range + sorted_column_range = column_range if self.is_forward else reversed(column_range) + state = self.init + col = Column(column_range.start, np.zeros(len(column_range), dtype=_elem_dtype(self.init))) for i in sorted_column_range: - state = scan_pass(state, *map(shifted_scan_arg(i), iters)) + state = self.scan_pass(state, *map(shifted_scan_arg(i), iters)) col[i] = state return col - return impl + +@builtins.scan.register(EMBEDDED) +def scan(scan_pass: Callable, is_forward: bool, init: Any, axis: common.Dimension) -> _Scan: + return _Scan(scan_pass, is_forward, init, axis) def _dimension_to_tag( @@ -1720,17 +1725,14 @@ def _compute_at_position( return sten(*ins_iters) -def _extract_column_range(domain) -> common.NamedRange | eve.NothingType: - if (col_range_placeholder := embedded_context.get_closure_column_range(None)) is not None: - assert ( - col_range_placeholder.unit_range.is_empty() - ) # check it's just the placeholder with empty range - column_axis = col_range_placeholder.dim - if column_axis is not None and column_axis.value in domain: - return common.NamedRange( - column_axis, - common.UnitRange(domain[column_axis.value].start, domain[column_axis.value].stop), - ) +def _extract_column_range( + domain: dict[Tag, range], sten: Callable +) -> common.NamedRange | eve.NothingType: + if isinstance(sten, _Scan) and (column_axis := sten.axis).value in domain: + return common.NamedRange( + column_axis, + common.UnitRange(domain[column_axis.value].start, domain[column_axis.value].stop), + ) return eve.NOTHING @@ -1740,7 +1742,7 @@ def _get_output_type( args: tuple[Any, ...], ) -> ts.TypeSpec: domain = _dimension_to_tag(domain_) - col_range = _extract_column_range(domain) + col_range = _extract_column_range(domain, fun) col_dim: Optional[common.Dimension] = None if isinstance(col_range, common.NamedRange): @@ -1818,7 +1820,7 @@ def closure( if not (isinstance(out, common.Field) or is_tuple_of_field(out)): raise TypeError("'Out' needs to be a located field.") - column_range: common.NamedRange | eve.NothingType = _extract_column_range(domain) + column_range: common.NamedRange | eve.NothingType = _extract_column_range(domain, sten) column_dim = None if isinstance(column_range, common.NamedRange): @@ -1848,14 +1850,7 @@ def fendef_embedded(fun: Callable[..., None], *args: Any, **kwargs: Any): if "offset_provider" not in kwargs: raise RuntimeError("'offset_provider' not provided.") - context_vars = {"offset_provider": kwargs["offset_provider"]} - if "column_axis" in kwargs: - context_vars["closure_column_range"] = common.NamedRange( - kwargs["column_axis"], - common.UnitRange(0, 0), # empty: indicates column operation, will update later - ) - - with embedded_context.update(**context_vars): + with embedded_context.update(offset_provider=kwargs["offset_provider"]): fun(*args) diff --git a/src/gt4py/next/iterator/ir_utils/ir_makers.py b/src/gt4py/next/iterator/ir_utils/ir_makers.py index cc7dc3ea3d..5ef7399b2a 100644 --- a/src/gt4py/next/iterator/ir_utils/ir_makers.py +++ b/src/gt4py/next/iterator/ir_utils/ir_makers.py @@ -663,9 +663,9 @@ def reduce(op, expr): return call(call("reduce")(op, expr)) -def scan(expr, forward, init): +def scan(expr, forward, init, axis: itir.AxisLiteral | common.Dimension): """Create a `scan` call.""" - return call("scan")(expr, forward, init) + return call("scan")(expr, forward, init, axis) def list_get(list_idx, list_): diff --git a/src/gt4py/next/iterator/ir_utils/misc.py b/src/gt4py/next/iterator/ir_utils/misc.py index d9a6e85f57..35322172f2 100644 --- a/src/gt4py/next/iterator/ir_utils/misc.py +++ b/src/gt4py/next/iterator/ir_utils/misc.py @@ -121,14 +121,17 @@ def unwrap_scan( identity function. This function allows treating a scan stencil like a regular stencil during a transformation avoiding the complexity introduced by the different IR format. - >>> scan = im.call("scan")( - ... im.lambda_("state", "arg")(im.plus("state", im.deref("arg"))), True, 0.0 + >>> scan = im.scan( + ... im.lambda_("state", "arg")(im.plus("state", im.deref("arg"))), + ... True, + ... 0.0, + ... common.Dimension("K", common.DimensionKind.VERTICAL), ... ) >>> stencil, back_trafo = unwrap_scan(scan) >>> str(stencil) 'λ(arg) → state + ·arg' >>> str(back_trafo(stencil)) - 'scan(λ(state, arg) → state + ·arg, True, 0.0)' + 'scan(λ(state, arg) → state + ·arg, True, 0.0, Kᵥ)' In case a regular stencil is given it is returned as-is: @@ -137,8 +140,8 @@ def unwrap_scan( >>> assert stencil == deref_stencil """ if cpm.is_call_to(stencil, "scan"): - scan_pass, direction, init = stencil.args - assert isinstance(scan_pass, itir.Lambda) + scan_pass, direction, init, axis = stencil.args + assert isinstance(scan_pass, itir.Lambda) and isinstance(axis, itir.AxisLiteral) # remove scan pass state to be used by caller state_param = scan_pass.params[0] stencil_like = im.lambda_(*scan_pass.params[1:])(scan_pass.expr) @@ -151,7 +154,7 @@ def restore_scan(transformed_stencil_like: itir.Lambda): ) ) ) - return im.call("scan")(new_scan_pass, direction, init) + return im.scan(new_scan_pass, direction, init, axis) return stencil_like, restore_scan diff --git a/src/gt4py/next/iterator/runtime.py b/src/gt4py/next/iterator/runtime.py index 88a466229f..52bb5d4ff1 100644 --- a/src/gt4py/next/iterator/runtime.py +++ b/src/gt4py/next/iterator/runtime.py @@ -57,7 +57,6 @@ class UnstructuredDomain(dict): ... class FendefDispatcher: definition: types.FunctionType offset_provider: Optional[common.OffsetProvider] - column_axis: Optional[common.Dimension] def itir(self, *args): # TODO(ricoh): refactor so that `tracing` does not import this module @@ -76,10 +75,8 @@ def __call__( *args, backend: Optional[next_backend.Backend | program_formatter.ProgramFormatter] = None, offset_provider=None, - column_axis=None, ): offset_provider = offset_provider or self.offset_provider - column_axis = column_axis or self.column_axis if backend is not None: itir_node = self.itir(*args) @@ -91,15 +88,11 @@ def __call__( assert isinstance(backend, next_backend.Backend) compiled_program = backend.compile( itir_node, - arguments.CompileTimeArgs.from_concrete( - *args, offset_provider=offset_provider, column_axis=column_axis - ), + arguments.CompileTimeArgs.from_concrete(*args, offset_provider=offset_provider), ) compiled_program(*args, offset_provider=offset_provider) elif isinstance(backend, program_formatter.ProgramFormatter): - return backend( - itir_node, *args, offset_provider=offset_provider, column_axis=column_axis - ) + return backend(itir_node, *args, offset_provider=offset_provider) else: raise ValueError( "Backend must be a 'gt4py.next.backend.Backend' or " @@ -108,16 +101,13 @@ def __call__( else: if fendef_embedded is None: raise RuntimeError("Embedded execution is not registered.") - fendef_embedded( - self.definition, *args, offset_provider=offset_provider, column_axis=column_axis - ) + fendef_embedded(self.definition, *args, offset_provider=offset_provider) def fendef( definition: Optional[types.FunctionType] = None, *, offset_provider: Optional[common.OffsetProvider] = None, - column_axis: Optional[common.Dimension] = None, ): """ Dispatches to embedded execution or execution with code generation. @@ -126,11 +116,9 @@ def fendef( else `fendef_codegen` will be called. """ if not definition: - return functools.partial(fendef, offset_provider=offset_provider, column_axis=column_axis) + return functools.partial(fendef, offset_provider=offset_provider) - return FendefDispatcher( - definition=definition, offset_provider=offset_provider or {}, column_axis=column_axis - ) + return FendefDispatcher(definition=definition, offset_provider=offset_provider or {}) def _deduce_domain( diff --git a/src/gt4py/next/iterator/transforms/trace_shifts.py b/src/gt4py/next/iterator/transforms/trace_shifts.py index b62f894796..f4e2d260ee 100644 --- a/src/gt4py/next/iterator/transforms/trace_shifts.py +++ b/src/gt4py/next/iterator/transforms/trace_shifts.py @@ -186,7 +186,7 @@ def _neighbors(o, x): return _deref(_shift(o, Sentinel.ALL_NEIGHBORS)(x)) -def _scan(f, forward, init): +def _scan(f, forward, init, axis): def apply(*args): return f(init, *args) diff --git a/src/gt4py/next/iterator/type_system/type_synthesizer.py b/src/gt4py/next/iterator/type_system/type_synthesizer.py index abaaaf27a2..c8a14fc9ad 100644 --- a/src/gt4py/next/iterator/type_system/type_synthesizer.py +++ b/src/gt4py/next/iterator/type_system/type_synthesizer.py @@ -628,9 +628,13 @@ def get_domain_range(field: ts.FieldType, dim: ts.DimensionType) -> ts.TupleType @_register_builtin_type_synthesizer def scan( - scan_pass: TypeSynthesizer, direction: ts.ScalarType, init: ts.ScalarType + scan_pass: TypeSynthesizer, + direction: ts.ScalarType, + init: ts.ScalarType, + axis: ts.DimensionType, ) -> TypeSynthesizer: assert isinstance(direction, ts.ScalarType) and direction.kind == ts.ScalarKind.BOOL + assert isinstance(axis, ts.DimensionType) @type_synthesizer def apply_scan( diff --git a/src/gt4py/next/otf/arguments.py b/src/gt4py/next/otf/arguments.py index 67c9f2bdc4..5b825b7a05 100644 --- a/src/gt4py/next/otf/arguments.py +++ b/src/gt4py/next/otf/arguments.py @@ -12,7 +12,7 @@ import dataclasses import enum from collections.abc import Callable, Mapping -from typing import Any, Generic, Hashable, Optional, Self, TypeAlias, TypeVar, cast, final +from typing import Any, Generic, Hashable, Self, TypeAlias, TypeVar, cast, final from typing_extensions import TypeIs @@ -136,7 +136,6 @@ class CompileTimeArgs: args: tuple[ts.TypeSpec, ...] kwargs: dict[str, ts.TypeSpec] offset_provider: common.OffsetProvider # TODO(havogt): replace with common.OffsetProviderType once the temporary pass doesn't require the runtime information - column_axis: Optional[common.Dimension] #: A mapping from an argument descriptor type to a context containing the actual descriptors. #: If an argument or element of an argument has no descriptor, the respective value is `None`. #: E.g., for a tuple argument `a` with type `ts.TupleTupe(types=[field_t, int32_t])` a possible @@ -154,7 +153,6 @@ def from_concrete(cls, *args: Any, **kwargs: Any) -> Self: return cls( args=tuple(type_translation.from_value(arg) for arg in args), offset_provider=kwargs_copy.pop("offset_provider", {}), - column_axis=kwargs_copy.pop("column_axis", None), kwargs={ k: type_translation.from_value(v) for k, v in kwargs_copy.items() if v is not None }, @@ -163,7 +161,7 @@ def from_concrete(cls, *args: Any, **kwargs: Any) -> Self: @classmethod def empty(cls) -> Self: - return cls(tuple(), {}, {}, None, {}) + return cls(tuple(), {}, {}, {}) # This is not really accurate, just an approximation diff --git a/src/gt4py/next/otf/compiled_program.py b/src/gt4py/next/otf/compiled_program.py index 36b49631eb..c3fc14bd91 100644 --- a/src/gt4py/next/otf/compiled_program.py +++ b/src/gt4py/next/otf/compiled_program.py @@ -674,7 +674,6 @@ def _compile_variant( compile_time_args = arguments.CompileTimeArgs( offset_provider=offset_provider, - column_axis=None, # TODO(havogt): column_axis seems to a unused, even for programs with scans args=arg_types, kwargs=kwarg_types, argument_descriptor_contexts=argument_descriptor_contexts, diff --git a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py index f1c6978791..9ca37e1958 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -157,7 +157,6 @@ def generate_stencil_source( self, program: itir.Program, offset_provider: common.OffsetProvider | common.OffsetProviderType, - column_axis: Optional[common.Dimension], ) -> str: if self.enable_itir_transforms: new_program = self._preprocess_program(program, offset_provider) @@ -168,7 +167,6 @@ def generate_stencil_source( gtfn_ir = GTFN_lowering.apply( new_program, offset_provider_type=common.offset_provider_to_type(offset_provider), - column_axis=column_axis, ) return GTFNCodegen.apply(gtfn_ir) @@ -203,11 +201,7 @@ def __call__( f"{', '.join(connectivity_args_expr)})({', '.join(args_expr)});" ) decl_src = cpp_interface.render_function_declaration(function, body=decl_body) - stencil_src = self.generate_stencil_source( - program, - inp.args.offset_provider, - inp.args.column_axis, - ) + stencil_src = self.generate_stencil_source(program, inp.args.offset_provider) source_code = "\n".join( [ f"#include <{self._backend_header()}>", diff --git a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py index 8e07a908ca..739cfd141c 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py @@ -238,7 +238,6 @@ class GTFN_lowering(eve.NodeTranslator, eve.VisitorWithSymbolTableTrait): _unary_op_map: ClassVar[dict[str, str]] = {"not_": "!"} offset_provider_type: common.OffsetProviderType - column_axis: Optional[common.Dimension] grid_type: common.GridType # we use one UID generator per instance such that the generated ids are @@ -253,7 +252,6 @@ def apply( node: itir.Program, *, offset_provider_type: common.OffsetProviderType, - column_axis: Optional[common.Dimension], ) -> Program: if not isinstance(node, itir.Program): raise TypeError(f"Expected a 'Program', got '{type(node).__name__}'.") @@ -262,9 +260,7 @@ def apply( grid_type = ir_utils_misc.grid_type_from_program(node) if grid_type == common.GridType.UNSTRUCTURED: node = _CannonicalizeUnstructuredDomain.apply(node) - return cls( - offset_provider_type=offset_provider_type, column_axis=column_axis, grid_type=grid_type - ).visit(node) + return cls(offset_provider_type=offset_provider_type, grid_type=grid_type).visit(node) def visit_Sym(self, node: itir.Sym, **kwargs: Any) -> Sym: return Sym(id=node.id) @@ -587,13 +583,13 @@ def convert_el_to_sid(el_expr: Expr, el_type: ts.ScalarType | ts.FieldType) -> E inputs=[i + 1 for i, _ in enumerate(inputs)], init=self.visit(stencil.args[2], **kwargs), ) - column_axis = self.column_axis - assert isinstance(column_axis, common.Dimension) + axis = stencil.args[3] + assert isinstance(axis, itir.AxisLiteral) return ScanExecution( backend=backend, scans=[scan], args=[self._visit_output_argument(node.target), *lowered_inputs], - axis=SymRef(id=column_axis.value), + axis=SymRef(id=axis.value), ) assert projector is None # only scans have projectors return StencilExecution( diff --git a/src/gt4py/next/program_processors/formatters/gtfn.py b/src/gt4py/next/program_processors/formatters/gtfn.py index a2ccab6168..f1a74d9a17 100644 --- a/src/gt4py/next/program_processors/formatters/gtfn.py +++ b/src/gt4py/next/program_processors/formatters/gtfn.py @@ -19,5 +19,4 @@ def format_cpp(program: itir.Program, *args: Any, **kwargs: Any) -> str: return gtfn_translation.generate_stencil_source( program, offset_provider=kwargs.get("offset_provider", {}), - column_axis=kwargs.get("column_axis", None), ) 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 1ecf34e1a4..748172444f 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 @@ -16,19 +16,7 @@ import abc import dataclasses -from typing import ( - Any, - Dict, - Final, - Iterable, - List, - Mapping, - Optional, - Protocol, - Sequence, - Tuple, - Union, -) +from typing import Any, Dict, Final, Iterable, List, Mapping, Protocol, Sequence, Tuple, Union import dace from dace import nodes as dace_nodes, subsets as dace_subsets @@ -384,11 +372,6 @@ def make_field( """ ... - @abc.abstractmethod - def is_column_axis(self, dim: gtx_common.Dimension) -> bool: - """Check if the given dimension is the column axis.""" - ... - @abc.abstractmethod def setup_nested_context( self, @@ -564,7 +547,6 @@ class GTIRToSDFG(eve.NodeVisitor, SDFGBuilder): """ offset_provider_type: gtx_common.OffsetProviderType - column_axis: Optional[gtx_common.Dimension] uids: gtx_utils.IDGeneratorPool = dataclasses.field( init=False, repr=False, default_factory=lambda: gtx_utils.IDGeneratorPool() ) @@ -603,10 +585,6 @@ def make_field( ) return gtir_to_sdfg_types.FieldopData(data_node, field_type, field_origin) - def is_column_axis(self, dim: gtx_common.Dimension) -> bool: - assert self.column_axis - return dim == self.column_axis - def setup_nested_context( self, expr: gtir.Lambda, @@ -1411,7 +1389,6 @@ def visit_SymRef( def lower_program_to_sdfg( ir: gtir.Program, offset_provider_type: gtx_common.OffsetProviderType, - column_axis: Optional[gtx_common.Dimension] = None, ) -> dace.SDFG: """ Receives a GTIR program and lowers it to a DaCe SDFG. @@ -1422,7 +1399,6 @@ def lower_program_to_sdfg( Args: ir: The GTIR program node to be lowered to SDFG offset_provider_type: The definitions of offset providers used by the program node - column_axis: Vertical dimension used for column scan expressions. Returns: An SDFG in the DaCe canonical form (simplified) @@ -1442,7 +1418,7 @@ 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_genenerator = GTIRToSDFG(offset_provider_type) sdfg = sdfg_genenerator.visit(ir) assert isinstance(sdfg, dace.SDFG) 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 062cc12c3e..de38900e6a 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 @@ -36,6 +36,7 @@ common_pattern_matcher as cpm, domain_utils, ir_makers as im, + misc as ir_misc, ) from gt4py.next.iterator.transforms import infer_domain from gt4py.next.program_processors.runners.dace import sdfg_args as gtx_dace_args @@ -74,6 +75,7 @@ def _lower_lambda_to_nested_sdfg( lambda_params: Sequence[gtir.Sym], scan_forward: bool, scan_carry_symbol: gtir.Sym, + scan_dim: gtx_common.Dimension, ) -> tuple[gtir_to_sdfg.SubgraphContext, gtir_to_sdfg_types.FieldopResult]: """ Helper method to lower the lambda node representing the scan stencil dataflow @@ -101,6 +103,7 @@ def _lower_lambda_to_nested_sdfg( when False, traverse towards origin. scan_carry_symbol: The symbol used in the stencil expression to carry the intermediate result along the vertical dimension. + scan_dim: The dimension along which the scan is computed. Returns: A tuple of two elements: @@ -140,8 +143,7 @@ def _lower_lambda_to_nested_sdfg( # We use the entry state for initialization of the scan carry variable. init_state = lambda_ctx.state - # use the vertical dimension in the domain as scan dimension - scan_dim_index = [sdfg_builder.is_column_axis(r.dim) for r in field_domain].index(True) + scan_dim_index = [r.dim for r in field_domain].index(scan_dim) scan_domain = field_domain[scan_dim_index] # extract the field layout and subset, to be used for the output of the scan operator @@ -327,6 +329,7 @@ def _handle_dataflow_result_of_nested_sdfg( outer_ctx: gtir_to_sdfg.SubgraphContext, inner_data: gtir_to_sdfg_types.FieldopData, output_domain: infer_domain.NonTupleDomainAccess, + scan_dim: gtx_common.Dimension, ) -> gtir_to_sdfg_lambda.DataflowOutputEdge | None: assert isinstance(inner_data.gt_type, ts.FieldType) inner_dataname = inner_data.dc_node.data @@ -346,7 +349,7 @@ def _handle_dataflow_result_of_nested_sdfg( 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) + scan_dim_index = field_dims.index(scan_dim) scan_column_size = field_shape[scan_dim_index] if bool(scan_column_size == 1): @@ -458,7 +461,7 @@ def translate_scan_fieldop( ) # parse scan parameters - assert len(scan_expr.args) == 3 + assert len(scan_expr.args) == 4 stencil_expr = scan_expr.args[0] assert isinstance(stencil_expr, gtir.Lambda) @@ -476,6 +479,10 @@ def translate_scan_fieldop( # visit the initialization value of the scan expression init_data = sdfg_builder.visit(init_expr, ctx=ctx) + # params[3]: the scan dimension + assert isinstance(scan_expr.args[3], gtir.AxisLiteral) + scan_dim = ir_misc.dim_from_axis_literal(scan_expr.args[3]) + # define the symbols passed as parameter to the lambda expression, which consists # of the carry argument and all lambda function arguments lambda_arg_types: list[ts.DataType] = [scan_carry_type] + [ @@ -496,6 +503,7 @@ def translate_scan_fieldop( lambda_params, scan_forward, im.sym(scan_carry, scan_carry_type), + scan_dim, ) # visit the arguments to be passed to the lambda expression @@ -565,13 +573,13 @@ def translate_scan_fieldop( outer_ctx=ctx, inner_data=output_data, output_domain=output_domain, + scan_dim=scan_dim, ) )(lambda_output, 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)) result = gtir_to_sdfg_fieldop.create_field_operator( ctx=ctx, domain=field_domain, diff --git a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py index 2909e1a651..04873079f2 100644 --- a/src/gt4py/next/program_processors/runners/dace/workflow/translation.py +++ b/src/gt4py/next/program_processors/runners/dace/workflow/translation.py @@ -9,7 +9,7 @@ from __future__ import annotations import dataclasses -from typing import Any, Final, Literal, Optional +from typing import Any, Final, Literal import dace @@ -442,7 +442,6 @@ def _generate_sdfg_without_configuring_dace( self, ir: itir.Program, offset_provider: common.OffsetProvider, - column_axis: Optional[common.Dimension], ) -> dace.SDFG: offset_provider_type = common.offset_provider_to_type(offset_provider) on_gpu = self.device_type != core_defs.DeviceType.CPU @@ -463,7 +462,7 @@ def _generate_sdfg_without_configuring_dace( use_max_domain_range_on_unstructured_shift=self.use_max_domain_range_on_unstructured_shift, ) - sdfg = gtx_dace_lowering.lower_program_to_sdfg(ir, offset_provider_type, column_axis) + sdfg = gtx_dace_lowering.lower_program_to_sdfg(ir, offset_provider_type) constant_symbols = find_constant_symbols( ir, @@ -524,7 +523,6 @@ def __call__( sdfg = self.generate_sdfg( program, inp.args.offset_provider, # TODO(havogt): should be offset_provider_type once the transformation don't require run-time info - inp.args.column_axis, ) arg_types = inp.args.args diff --git a/src/gt4py/next/program_processors/runners/roundtrip.py b/src/gt4py/next/program_processors/runners/roundtrip.py index 29afc3535a..d5384e1d2b 100644 --- a/src/gt4py/next/program_processors/runners/roundtrip.py +++ b/src/gt4py/next/program_processors/runners/roundtrip.py @@ -215,23 +215,18 @@ class RoundtripArtifact: source_code: str entry_point_name: str - column_axis: common.Dimension | None dispatch_backend: next_backend.Backend | None debug: bool def load(self) -> artifacts.ExecutableProgram: mod = _load_module(self.source_code, self.debug) fencil = getattr(mod, self.entry_point_name) - captured_column_axis = self.column_axis dispatch_backend = self.dispatch_backend def decorated_fencil( *args: Any, offset_provider: dict[str, common.Connectivity | common.Dimension], out: Any = None, - column_axis: Optional[ - common.Dimension - ] = None, # TODO(tehrengruber): unused, kept for signature compat **kwargs: Any, ) -> None: if out is not None: @@ -240,7 +235,6 @@ def decorated_fencil( *args, offset_provider=offset_provider, backend=dispatch_backend, - column_axis=captured_column_axis, **kwargs, ) @@ -268,7 +262,6 @@ def __call__(self, inp: stages.CompilableProgramDef) -> RoundtripArtifact: return RoundtripArtifact( source_code=source_code, entry_point_name=entry_point_name, - column_axis=inp.args.column_axis, dispatch_backend=self.dispatch_backend, debug=debug, ) diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index efd4560823..fbd2a76492 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -288,6 +288,7 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): ] ROUNDTRIP_SKIP_LIST = DOMAIN_INFERENCE_SKIP_LIST + [ (USES_PROGRAM_METRICS, XFAIL, UNSUPPORTED_MESSAGE), + (USES_SCAN_IN_STENCIL, XFAIL, UNSUPPORTED_MESSAGE), (USES_SPARSE_FIELDS_AS_OUTPUT, XFAIL, UNSUPPORTED_MESSAGE), (USES_TUPLES_ARGS_WITH_DIFFERENT_BUT_PROMOTABLE_DIMS, XFAIL, UNSUPPORTED_MESSAGE), (USES_CONCAT_WHERE, XFAIL, UNSUPPORTED_MESSAGE), 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 7078efcff7..551064ce52 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 @@ -19,6 +19,7 @@ IDim, JDim, KDim, + KHalfDim, cartesian_case, ) from next_tests.integration_tests.cases_utils import ( @@ -123,6 +124,39 @@ def testee( ) +@pytest.mark.uses_scan +def test_scans_on_different_axes_in_program(cartesian_case): + @gtx.scan_operator(axis=KDim, forward=True, init=0.0) + def scan_k(state: float, inp: float) -> float: + return state + inp + + @gtx.scan_operator(axis=KHalfDim, forward=False, init=0.0) + def scan_khalf(state: float, inp: float) -> float: + return state + inp + + @gtx.program + def testee( + a: gtx.Field[[IDim, KDim], float], + b: gtx.Field[[IDim, KHalfDim], float], + out_a: gtx.Field[[IDim, KDim], float], + out_b: gtx.Field[[IDim, KHalfDim], float], + ): + scan_k(a, out=out_a) + scan_khalf(b, out=out_b) + + a = cases.allocate(cartesian_case, testee, "a")() + b = cases.allocate(cartesian_case, testee, "b")() + out_a = cases.allocate(cartesian_case, testee, "out_a").zeros()() + out_b = cases.allocate(cartesian_case, testee, "out_b").zeros()() + + cases.run(cartesian_case, testee, a, b, out_a, out_b) + + np.testing.assert_allclose(out_a.asnumpy(), np.cumsum(a.asnumpy(), axis=1)) + np.testing.assert_allclose( + out_b.asnumpy(), np.flip(np.cumsum(np.flip(b.asnumpy(), axis=1), axis=1), axis=1) + ) + + @pytest.mark.uses_scan @pytest.mark.uses_scan_without_field_args @pytest.mark.parametrize("forward", [True, False]) diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py index b60626acd9..408f0d9d5f 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_builtins.py @@ -75,8 +75,7 @@ def field_maker(*arrays): return res -def fencil(builtin, out, *inps, processor, as_column=False): - column_axis = IDim if as_column else None +def fencil(builtin, out, *inps, processor): if len(inps) == 1: @fundef @@ -88,7 +87,7 @@ def sten(fun, arg0): def dispatch(arg0): return sten(builtin, arg0) - @fendef(offset_provider={}, column_axis=column_axis) + @fendef(offset_provider={}) def fenimpl(size, arg0, out): domain = cartesian_domain(named_range(IDim, 0, size)) @@ -105,7 +104,7 @@ def sten(fun, arg0, arg1): def dispatch(arg0, arg1): return sten(builtin, arg0, arg1) - @fendef(offset_provider={}, column_axis=column_axis) + @fendef(offset_provider={}) def fenimpl(size, arg0, arg1, out): domain = cartesian_domain(named_range(IDim, 0, size)) @@ -122,7 +121,7 @@ def sten(fun, arg0, arg1, arg2): def dispatch(arg0, arg1, arg2): return sten(builtin, arg0, arg1, arg2) - @fendef(offset_provider={}, column_axis=column_axis) + @fendef(offset_provider={}) def fenimpl(size, arg0, arg1, arg2, out): domain = cartesian_domain(named_range(IDim, 0, size)) @@ -168,15 +167,14 @@ def arithmetic_and_logical_test_data(): ] -@pytest.mark.parametrize("as_column", [False, True]) @pytest.mark.parametrize("builtin, inputs, expected", arithmetic_and_logical_test_data()) -def test_arithmetic_and_logical_builtins(program_processor, builtin, inputs, expected, as_column): +def test_arithmetic_and_logical_builtins(program_processor, builtin, inputs, expected): program_processor, validate = program_processor inps = field_maker(*array_maker(*inputs)) out = field_maker((np.zeros_like(*array_maker(expected))))[0] - fencil(builtin, out, *inps, processor=program_processor, as_column=as_column) + fencil(builtin, out, *inps, processor=program_processor) if validate: assert np.allclose(out.asnumpy(), expected) @@ -194,9 +192,8 @@ def test_arithmetic_and_logical_functors_gtfn(builtin, inputs, expected): assert np.allclose(out.asnumpy(), expected) -@pytest.mark.parametrize("as_column", [False, True]) @pytest.mark.parametrize("builtin_name, inputs", math_builtin_test_data()) -def test_math_function_builtins(program_processor, builtin_name, inputs, as_column): +def test_math_function_builtins(program_processor, builtin_name, inputs): program_processor, validate = program_processor if builtin_name == "gamma": @@ -215,7 +212,6 @@ def test_math_function_builtins(program_processor, builtin_name, inputs, as_colu out, *inps, processor=program_processor, - as_column=as_column, ) if validate: @@ -289,10 +285,8 @@ def test_can_deref(program_processor, stencil): (int64(2147483648), int64, np.int64), ], ) -@pytest.mark.parametrize("as_column", [False, True]) -def test_cast(program_processor, as_column, input_value, dtype, np_dtype): +def test_cast(program_processor, input_value, dtype, np_dtype): program_processor, validate = program_processor - column_axis = IDim if as_column else None inp = field_maker(np.array([input_value]))[0] @@ -310,7 +304,6 @@ def sten_cast(it, casted_valued): casted_valued, out=out, offset_provider={}, - column_axis=column_axis, ) if validate: diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py index 93e86c8319..aa90cd5d7a 100644 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py +++ b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py @@ -22,6 +22,8 @@ def test_scan_in_stencil(program_processor): # FIXME[#1582](tehrengruber): Remove test after scan is reworked. program_processor, validate = program_processor + if program_processor is None: + pytest.xfail("Embedded execution only runs a 'scan' that is the stencil of a closure.") isize = 1 ksize = 3 @@ -43,7 +45,7 @@ def sum(state, k, kp): @fundef def wrapped(inp): - return scan(sum, True, 0.0)(inp, shift(Koff, 1)(inp)) + return scan(sum, True, 0.0, KDim)(inp, shift(Koff, 1)(inp)) run_processor( wrapped[cartesian_domain(named_range(IDim, 0, isize), named_range(KDim, 0, ksize - 1))], @@ -51,7 +53,6 @@ def wrapped(inp): inp, out=out, offset_provider={}, - column_axis=KDim, ) if validate: diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_column_stencil.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_column_stencil.py index 53581b9ec4..1472b46b27 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_column_stencil.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_column_stencil.py @@ -92,7 +92,6 @@ def test_basic_column_stencils(program_processor, basic_stencils): inp, out=out, offset_provider={}, - column_axis=KDim, ) if validate: @@ -162,7 +161,6 @@ def test_k_level_condition(program_processor, fun, k_level, inp_function, ref_fu k_level(inp), out=out, offset_provider={}, - column_axis=KDim, ) if validate: @@ -174,10 +172,10 @@ def ksum(state, inp): return state + deref(inp) -@fendef(column_axis=KDim) +@fendef def ksum_fencil(i_size, k_start, k_end, inp, out): domain = cartesian_domain(named_range(IDim, 0, i_size), named_range(KDim, k_start, k_end)) - set_at(as_fieldop(scan(ksum, True, 0.0), domain)(inp), domain, out) + set_at(as_fieldop(scan(ksum, True, 0.0, KDim), domain)(inp), domain, out) @pytest.mark.parametrize( @@ -206,10 +204,10 @@ def test_ksum_scan(program_processor, kstart, reference): assert np.allclose(reference, out.asnumpy()) -@fendef(column_axis=KDim) +@fendef def ksum_back_fencil(i_size, k_size, inp, out): domain = cartesian_domain(named_range(IDim, 0, i_size), named_range(KDim, 0, k_size)) - set_at(as_fieldop(scan(ksum, False, 0.0), domain)(inp), domain, out) + set_at(as_fieldop(scan(ksum, False, 0.0, KDim), domain)(inp), domain, out) @pytest.mark.uses_scan @@ -247,10 +245,10 @@ def ksum_even_odd(state, inp): ) -@fendef(column_axis=KDim) +@fendef def ksum_even_odd_fencil(i_size, k_size, inp, out): domain = cartesian_domain(named_range(IDim, 0, i_size), named_range(KDim, 0, k_size)) - scanop = as_fieldop(scan(ksum_even_odd, True, (0.0, True, 0.0)), domain)(inp) + scanop = as_fieldop(scan(ksum_even_odd, True, (0.0, True, 0.0), KDim), domain)(inp) expr = make_tuple(tuple_get(0, scanop), tuple_get(2, scanop)) # we remove the middle element set_at(expr, domain, out) @@ -296,10 +294,10 @@ def ksum_even_odd_nested(state, inp): ) -@fendef(column_axis=KDim) +@fendef def ksum_even_odd_nested_fencil(i_size, k_size, inp, out): domain = cartesian_domain(named_range(IDim, 0, i_size), named_range(KDim, 0, k_size)) - scanop = as_fieldop(scan(ksum_even_odd_nested, True, (True, (0.0, 0.0))), domain)(inp) + scanop = as_fieldop(scan(ksum_even_odd_nested, True, (True, (0.0, 0.0)), KDim), domain)(inp) expr = tuple_get(1, scanop) set_at(expr, domain, out) @@ -333,10 +331,10 @@ def test_ksum_even_odd_nested_scan(program_processor): assert np.allclose(odd_ref, out[1].asnumpy()) -@fendef(column_axis=KDim) +@fendef def ksum_even_odd_nested_only_odd_fencil(i_size, k_size, inp, out): domain = cartesian_domain(named_range(IDim, 0, i_size), named_range(KDim, 0, k_size)) - scanop = as_fieldop(scan(ksum_even_odd_nested, True, (True, (0.0, 0.0))), domain)(inp) + scanop = as_fieldop(scan(ksum_even_odd_nested, True, (True, (0.0, 0.0)), KDim), domain)(inp) expr = tuple_get(0, tuple_get(1, scanop)) set_at(expr, domain, out) @@ -369,10 +367,14 @@ def kdoublesum(state, inp0, inp1): return make_tuple(tuple_get(0, state) + deref(inp0), tuple_get(1, state) + deref(inp1)) -@fendef(column_axis=KDim) +@fendef def kdoublesum_fencil(i_size, k_start, k_end, inp0, inp1, out): domain = cartesian_domain(named_range(IDim, 0, i_size), named_range(KDim, k_start, k_end)) - set_at(as_fieldop(scan(kdoublesum, True, make_tuple(0.0, 0)), domain)(inp0, inp1), domain, out) + set_at( + as_fieldop(scan(kdoublesum, True, make_tuple(0.0, 0), KDim), domain)(inp0, inp1), + domain, + out, + ) @pytest.mark.parametrize( @@ -427,7 +429,7 @@ def sum_shifted(inp0, inp1): return deref(inp0) + deref(shift(K, 1)(inp1)) -@fendef(column_axis=KDim) +@fendef def sum_shifted_fencil(out, inp0, inp1, k_size): domain = cartesian_domain(named_range(KDim, 1, k_size)) set_at(as_fieldop(sum_shifted, domain)(inp0, inp1), domain, out) @@ -455,7 +457,7 @@ def sum(inp0, inp1): return deref(inp0) + deref(shift(K, -1)(inp1)) -@fendef(column_axis=KDim) +@fendef def sum_fencil(out, inp0, inp1, k_size): domain = cartesian_domain(named_range(KDim, 0, k_size)) set_at(as_fieldop(sum, domain)(inp0, inp1), domain, out) diff --git a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py index f9b2060621..715cc54c2c 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/iterator_tests/test_vertical_advection.py @@ -43,14 +43,14 @@ def tridiag_backward2(x_kp1, cp, dp): @fundef def solve_tridiag(domain, a, b, c, d): - cpdp = as_fieldop(scan(tridiag_forward, True, make_tuple(0.0, 0.0)), domain)(a, b, c, d) - return as_fieldop(scan(tridiag_backward, False, 0.0), domain)(cpdp) + cpdp = as_fieldop(scan(tridiag_forward, True, make_tuple(0.0, 0.0), KDim), domain)(a, b, c, d) + return as_fieldop(scan(tridiag_backward, False, 0.0, KDim), domain)(cpdp) @fundef def solve_tridiag2(domain, a, b, c, d): - cpdp = as_fieldop(scan(tridiag_forward, True, make_tuple(0.0, 0.0)), domain)(a, b, c, d) - return as_fieldop(scan(tridiag_backward2, False, 0.0), domain)( + cpdp = as_fieldop(scan(tridiag_forward, True, make_tuple(0.0, 0.0), KDim), domain)(a, b, c, d) + return as_fieldop(scan(tridiag_backward2, False, 0.0, KDim), domain)( tuple_get(0, cpdp), tuple_get(1, cpdp) ) @@ -124,7 +124,6 @@ def test_tridiag(fencil, tridiag_reference, program_processor): d_s, x_s, offset_provider={}, - column_axis=KDim, ) if validate: diff --git a/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py b/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py index 92bc96e714..af2eb1398b 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_type_inference.py @@ -243,7 +243,9 @@ def expression_test_cases(): ), ( im.as_fieldop( - im.scan(im.lambda_("state", "inp")(im.plus("state", im.deref("inp"))), True, 0.0), + im.scan( + im.lambda_("state", "inp")(im.plus("state", im.deref("inp"))), True, 0.0, KDim + ), k_domain, )(im.ref("inp", float_k_field)), float_k_field, diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py index 1ef26e988c..ebb1c74c22 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py @@ -17,6 +17,7 @@ int_type = ts.ScalarType(kind=ts.ScalarKind.INT32) Vertex = common.Dimension(value="Vertex", kind=common.DimensionKind.HORIZONTAL) +KDim = common.Dimension(value="KDim", kind=common.DimensionKind.VERTICAL) def test_simple_make_tuple_tuple_get(uids: utils.IDGeneratorPool): @@ -453,7 +454,10 @@ def test_flatten_as_fieldop_args_scan(uids: utils.IDGeneratorPool): ) testee = im.as_fieldop( im.scan( - im.lambda_("state", im.sym("it", it_type))(im.tuple_get(1, im.deref("it"))), True, 0 + im.lambda_("state", im.sym("it", it_type))(im.tuple_get(1, im.deref("it"))), + True, + 0, + KDim, ) )(im.make_tuple(1, 2)) expected = im.as_fieldop( @@ -463,6 +467,7 @@ def test_flatten_as_fieldop_args_scan(uids: utils.IDGeneratorPool): ), True, 0, + KDim, ) )(1, 2) actual = CollapseTuple.apply( 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 317ce27774..3aab352b32 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 @@ -1152,10 +1152,10 @@ def test_arithmetic_builtin(): def test_scan(): domain = im.domain(common.GridType.CARTESIAN, {IDim: (0, 11)}) testee = im.as_fieldop( - im.scan(im.lambda_("init", "it")(im.deref(im.shift(Ioff, 1)("it"))), True, 0.0) + im.scan(im.lambda_("init", "it")(im.deref(im.shift(Ioff, 1)("it"))), True, 0.0, KDim) )(im.ref("a", float_i_field)) expected = im.as_fieldop( - im.scan(im.lambda_("init", "it")(im.deref(im.shift(Ioff, 1)("it"))), True, 0.0), + im.scan(im.lambda_("init", "it")(im.deref(im.shift(Ioff, 1)("it"))), True, 0.0, KDim), domain, )(im.ref("a", float_i_field)) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py index c1720fe1bb..3af2dd09f9 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_fuse_as_fieldop.py @@ -381,7 +381,7 @@ def test_inline_as_fieldop_with_list_dtype(uids: utils.IDGeneratorPool): def test_inline_into_scan(uids: utils.IDGeneratorPool): d = im.domain("cartesian_domain", {IDim: (0, 1)}) - scan = im.call("scan")(im.lambda_("state", "a")(im.plus("state", im.deref("a"))), True, 0) + scan = im.scan(im.lambda_("state", "a")(im.plus("state", im.deref("a"))), True, 0, IDim) testee = im.as_fieldop(scan, d)(im.as_fieldop("deref")(im.ref("a", field_type))) expected = im.as_fieldop(scan, d)(im.ref("a", field_type)) actual = fuse_as_fieldop.FuseAsFieldOp.apply( @@ -392,9 +392,7 @@ def test_inline_into_scan(uids: utils.IDGeneratorPool): def test_no_inline_into_scan(uids: utils.IDGeneratorPool): d = im.domain("cartesian_domain", {IDim: (0, 1)}) - scan_stencil = im.call("scan")( - im.lambda_("state", "a")(im.plus("state", im.deref("a"))), True, 0 - ) + scan_stencil = im.scan(im.lambda_("state", "a")(im.plus("state", im.deref("a"))), True, 0, IDim) scan = im.as_fieldop(scan_stencil, d)(im.ref("a", field_type)) testee = im.as_fieldop(im.lambda_("arg")(im.deref("arg")), d)(scan) actual = fuse_as_fieldop.FuseAsFieldOp.apply( diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py index 14e626be3a..c6c82d56a7 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_global_tmps.py @@ -162,7 +162,7 @@ def test_dont_extract_projector(projector_maker, inp_type, out_type, uids: utils domain = im.domain("cartesian_domain", {IDim: (0, 1)}) # this is a a scan, because we assert that we only extract projectors from scans scan = im.as_fieldop( - im.call("scan")(im.lambda_("state", "inp")(im.call("deref")("inp")), True, 0), domain + im.scan(im.lambda_("state", "inp")(im.call("deref")("inp")), True, 0, KDim), domain )(im.ref("inp", inp_type)) testee = program_factory( diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py index 445886e76b..53ba1627b4 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_inline_into_scan.py @@ -6,6 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +from gt4py.next import common from gt4py.next.iterator import ir from gt4py.next.iterator.transforms.inline_into_scan import InlineIntoScan from gt4py.next.iterator.ir_utils import ir_makers as im @@ -21,6 +22,7 @@ def _make_scan(*args: list[str], scanpass_body: ir.Expr) -> ir.Expr: ), im.literal("0.0", "float64"), im.literal("True", "bool"), + im.axis_literal(common.Dimension("KDim", common.DimensionKind.VERTICAL)), ], ) diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py index b56ebd1114..095820fc2a 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_scan_fusion.py @@ -26,6 +26,7 @@ def make_shadowed_program(scope): im.lambda_("carry", "a", "b")(im.plus("carry", im.plus(im.deref("a"), im.deref("b")))), True, 0.0, + k, ) wrapper = ir.FunctionDefinition( id="scan_wrapper", diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py index 68ec931ce0..edb16c0381 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_simple_inline_heuristic.py @@ -8,6 +8,7 @@ import pytest +from gt4py.next import common from gt4py.next.iterator import ir from gt4py.next.iterator.transforms.simple_inline_heuristic import is_eligible_for_inlining from gt4py.next.iterator.ir_utils import ir_makers as im @@ -30,6 +31,7 @@ def scan(): ), im.literal("True", "bool"), im.literal("0.0", "float64"), + im.axis_literal(common.Dimension("KDim", common.DimensionKind.VERTICAL)), ], ) diff --git a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py index 3abbce9df8..f8323091c4 100644 --- a/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py +++ b/tests/next_tests/unit_tests/otf_tests/test_compiled_program.py @@ -103,7 +103,6 @@ def test_inlining_of_scalars_works(testee_prog): args=list(testee_prog.past_stage.past_node.type.definition.pos_or_kw_args.values()), kwargs={}, offset_provider={}, - column_axis=None, argument_descriptor_contexts={ arguments.StaticArg: {"cond": arguments.StaticArg(value=True)} }, @@ -587,7 +586,6 @@ def test_inlining_of_static_domain_works(testee_prog, uids: utils.IDGeneratorPoo args=list(testee_prog.past_stage.past_node.type.definition.pos_or_kw_args.values()), kwargs={}, offset_provider={}, - column_axis=None, argument_descriptor_contexts={ arguments.FieldDomainDescriptor: {"out": arguments.FieldDomainDescriptor(domain)} }, diff --git a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py index af958b84d9..47aff6caed 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py +++ b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py @@ -121,12 +121,6 @@ def test_hash_and_diskcache(program_example, tmp_path): compilable_program ) != fingerprinting.strict_fingerprinter(altered_program_offset_provider) - altered_program_column_axis = copy.deepcopy(compilable_program) - object.__setattr__(altered_program_column_axis.args, "column_axis", KDim) - assert fingerprinting.strict_fingerprinter( - compilable_program - ) != fingerprinting.strict_fingerprinter(altered_program_column_axis) - def test_gtfn_file_cache(program_example): fencil, parameters = program_example diff --git a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py index 7c8c93e8ef..036b41370a 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py +++ b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py @@ -29,9 +29,9 @@ def test_funcall_to_op(): op="+", lhs=gtfn_ir.SymRef(id="foo"), rhs=gtfn_ir.SymRef(id="bar") ) - actual = it2gtfn.GTFN_lowering( - grid_type=gtx.GridType.CARTESIAN, offset_provider_type={}, column_axis=None - ).visit(testee) + actual = it2gtfn.GTFN_lowering(grid_type=gtx.GridType.CARTESIAN, offset_provider_type={}).visit( + testee + ) assert expected == actual @@ -40,9 +40,9 @@ def test_unapplied_funcall_to_function_object(): testee = itir.SymRef(id="plus") expected = gtfn_ir.SymRef(id="plus") - actual = it2gtfn.GTFN_lowering( - grid_type=gtx.GridType.CARTESIAN, offset_provider_type={}, column_axis=None - ).visit(testee) + actual = it2gtfn.GTFN_lowering(grid_type=gtx.GridType.CARTESIAN, offset_provider_type={}).visit( + testee + ) assert expected == actual @@ -71,6 +71,6 @@ def test_unstructured_param_dimension_tag(dim, alias): ) ], ) - result = it2gtfn.GTFN_lowering.apply(testee, offset_provider_type={}, column_axis=None) + result = it2gtfn.GTFN_lowering.apply(testee, offset_provider_type={}) aliases = {str(tag.name.id): tag.alias for tag in result.offset_definitions} assert aliases[dim.value] == alias 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..dfb2ee8d82 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 @@ -74,7 +74,7 @@ def _translate_gtir_to_sdfg( async_sdfg_call=async_sdfg_call, unstructured_horizontal_has_unit_stride=False, use_metrics=use_metrics, - ).generate_sdfg(ir, offset_provider=offset_provider, column_axis=None) + ).generate_sdfg(ir, offset_provider=offset_provider) @pytest.mark.parametrize("has_unit_stride", [False, True]) @@ -449,7 +449,6 @@ def _make_simple_field_operator_compilable_program() -> otf_workflow.ConcreteArt args=tuple(param.type for param in ir.params), kwargs={}, offset_provider={}, - column_axis=None, argument_descriptor_contexts={}, ), ) 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 7ad539c866..28c50dedc6 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 @@ -135,7 +135,7 @@ def build_dace_sdfg( symbolic_domain_sizes=pass_manager._max_domain_range_sizes(offset_provider), ) offset_provider_type = gtx_common.offset_provider_to_type(offset_provider) - return dace_lowering.lower_program_to_sdfg(ir, offset_provider_type, column_axis=KDim) + return dace_lowering.lower_program_to_sdfg(ir, offset_provider_type) def apply_margin_on_field_domain( @@ -2316,6 +2316,7 @@ def test_gtir_scan(id, use_symbolic_column_size): ), True, im.make_tuple(0.0, True), + KDim, ) )("x"), domain=im.make_tuple(domain, domain), @@ -2380,6 +2381,7 @@ def test_gtir_scan_single_level_output(): ), True, im.make_tuple(VAL0, VAL1), + KDim, ) )("x"), domain=im.make_tuple(full_domain, one_level_domain), diff --git a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py index 4da343b7e5..e0ba4f6d04 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py +++ b/tests/next_tests/unit_tests/program_processor_tests/runners_tests/dace_tests/test_scan_fusion.py @@ -53,6 +53,7 @@ def make_program(levels=17, forward=True, shift_axis=K): ), forward, im.make_tuple(1.0, 2.0), + K, ) return ir.Program( id="scan_coefficient_fusion", @@ -78,7 +79,7 @@ def translate(program, enabled, **extra_options): unstructured_horizontal_has_unit_stride=False, use_metrics=False, ) - return translator.generate_sdfg(program, offset_provider={}, column_axis=K) + return translator.generate_sdfg(program, offset_provider={}) @pytest.mark.parametrize("enabled, expected_arrays", [(False, 2), (True, 0)]) @@ -90,9 +91,7 @@ def test_toolchain_scan_options_reach_lowering(enabled, expected_arrays): factory.make_dace_translator, auto_optimize_args=options, use_metrics=False ), ) - graph = toolchain.executor.translation.generate_sdfg( - make_program(), offset_provider={}, column_axis=K - ) + graph = toolchain.executor.translation.generate_sdfg(make_program(), offset_provider={}) assert ( sum( descriptor.transient @@ -199,6 +198,7 @@ def make_staggered_program(input_dim, scan_dim, levels=80, forward=True, mixed=F ), forward, 0.75, + scan_dim, ) return ir.Program( id="staggered_scan_fusion", @@ -229,7 +229,7 @@ def test_compiled_staggered_scan_fusion(tmp_path, input_dim, forward, mixed, lev async_sdfg_call=False, unstructured_horizontal_has_unit_stride=False, use_metrics=False, - ).generate_sdfg(program, offset_provider={}, column_axis=scan_dim) + ).generate_sdfg(program, offset_provider={}) graph.validate() assert not any( desc.transient and isinstance(desc, dace.data.Array) and len(desc.shape) == 2 @@ -576,7 +576,7 @@ def unexpected(*args, **kwargs): auto_optimize_args={"fuse_scan_inputs": True, "scan_fusion_scope": "field_operator"}, use_metrics=False, ) - translator.generate_sdfg(make_program(), offset_provider={}, column_axis=K) + translator.generate_sdfg(make_program(), offset_provider={}) def test_invalid_scan_fusion_scope_is_rejected(): From a7ddb951a1b140f1feb2021e94ce998f5725c48a Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 2 Dec 2026 08:17:40 +0100 Subject: [PATCH 06/18] fix[next]: embedded scans take their range per axis from the output domain The embedded field-view scan reads the range of its own axis from the vertical ranges of the output domain, which may be a tuple of domains on different vertical dimensions. An axis that occurs with different ranges in the tuple raises. The range is clipped to the range the scan's inputs cover on the axis, so a scan over a shifted input under concat_where starts where the compiled backends start. --- src/gt4py/next/embedded/context.py | 28 ++++++- src/gt4py/next/embedded/operators.py | 30 +++++--- .../feature_tests/ffront_tests/test_scan.py | 73 +++++++++++++++++++ .../embedded_tests/test_basic_program.py | 33 +++++++++ .../embedded_tests/test_nd_array_field.py | 2 +- .../test_nd_array_field_with_torch.py | 2 +- 6 files changed, 155 insertions(+), 13 deletions(-) diff --git a/src/gt4py/next/embedded/context.py b/src/gt4py/next/embedded/context.py index 1b44e90453..70ab2fa6cd 100644 --- a/src/gt4py/next/embedded/context.py +++ b/src/gt4py/next/embedded/context.py @@ -21,6 +21,7 @@ _closure_column_range: contextvars.ContextVar[common.NamedRange] = contextvars.ContextVar( "_column_range" ) +_column_ranges: contextvars.ContextVar[common.Domain] = contextvars.ContextVar("_column_ranges") _offset_provider: contextvars.ContextVar[common.OffsetProvider] = contextvars.ContextVar( "_offset_provider" ) @@ -50,6 +51,24 @@ def get_closure_column_range(default: _T = _NO_DEFAULT_SENTINEL) -> common.Named return result +@overload +def get_column_ranges() -> common.Domain: ... + + +@overload +def get_column_ranges(default: _T) -> common.Domain | _T: ... + + +def get_column_ranges(default: _T = _NO_DEFAULT_SENTINEL) -> common.Domain | _T: + """Ranges of the vertical dimensions of the output domain of the current field operator call.""" + result = _column_ranges.get(default) + if result is _NO_DEFAULT_SENTINEL: + raise exceptions.EmbeddedExecutionError( + "No column ranges set in the current embedded field operator execution context." + ) + return result + + @overload def get_offset_provider() -> common.OffsetProvider: ... @@ -72,14 +91,18 @@ def get_offset_provider(default: _T = _NO_DEFAULT_SENTINEL) -> common.OffsetProv def update( *, closure_column_range: common.NamedRange | eve.NothingType = eve.NOTHING, + column_ranges: common.Domain | eve.NothingType = eve.NOTHING, offset_provider: common.OffsetProvider | eve.NothingType = eve.NOTHING, ) -> Generator[None, None, None]: """Context handler updating the current embedded context with the provided values.""" - closure_token, offset_provider_token = None, None + closure_token, column_ranges_token, offset_provider_token = None, None, None if closure_column_range is not eve.NOTHING: assert not isinstance(closure_column_range, eve.NothingType) closure_token = _closure_column_range.set(closure_column_range) + if column_ranges is not eve.NOTHING: + assert not isinstance(column_ranges, eve.NothingType) + column_ranges_token = _column_ranges.set(column_ranges) if offset_provider is not eve.NOTHING: assert not isinstance(offset_provider, eve.NothingType) offset_provider_token = _offset_provider.set(offset_provider) @@ -90,6 +113,9 @@ def update( if closure_column_range is not eve.NOTHING: assert closure_token is not None _closure_column_range.reset(closure_token) + if column_ranges is not eve.NOTHING: + assert column_ranges_token is not None + _column_ranges.reset(column_ranges_token) if offset_provider is not eve.NOTHING: assert offset_provider_token is not None _offset_provider.reset(offset_provider_token) diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 05e8e7a46a..8b72c43910 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -11,7 +11,6 @@ from typing_extensions import TypeIs -from gt4py import eve from gt4py._core import definitions as core_defs from gt4py.eve import xtyping from gt4py.next import common, errors, field_utils, named_collections, utils @@ -46,11 +45,19 @@ def __call__( # type: ignore[override] common.Field[Any, core_defs.ScalarT] | tuple[common.Field[Any, core_defs.ScalarT] | tuple, ...] ): - scan_range = embedded_context.get_closure_column_range() - assert self.axis == scan_range.dim - scan_axis = scan_range.dim + scan_axis = self.axis all_args = [*args, *kwargs.values()] domain_intersection = _intersect_scan_args(*all_args) + 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( @@ -131,7 +138,7 @@ def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) -> else _get_out_domain(container_extracted_out) ) - new_context_kwargs["closure_column_range"] = _get_vertical_range(out_domain) + new_context_kwargs["column_ranges"] = _get_vertical_ranges(out_domain) with embedded_context.update(**new_context_kwargs): res = op(*args, **kwargs) @@ -146,11 +153,14 @@ def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) -> return op(*args, **kwargs) -@utils.tree_map -def _get_vertical_range(domain: common.Domain) -> common.NamedRange | eve.NothingType: - vertical_dim_filtered = [nr for nr in domain if nr.dim.kind == common.DimensionKind.VERTICAL] - assert len(vertical_dim_filtered) <= 1 - return vertical_dim_filtered[0] if vertical_dim_filtered else eve.NOTHING +def _get_vertical_ranges(domain: xtyping.MaybeNestedInTuple[common.Domain]) -> common.Domain: + ranges: dict[common.Dimension, common.NamedRange] = {} + ambiguous: set[common.Dimension] = set() + for d in utils.flatten_nested_tuple((domain,)): + for nr in d: + if nr.dim.kind == common.DimensionKind.VERTICAL and ranges.setdefault(nr.dim, nr) != nr: + ambiguous.add(nr.dim) + return common.Domain(*(nr for dim, nr in ranges.items() if dim not in ambiguous)) def _tuple_assign_field( 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 551064ce52..6b2eadb177 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 @@ -12,6 +12,7 @@ import gt4py.next as gtx from gt4py.next import errors, float64, int32 +from gt4py.next.experimental import concat_where from gt4py.next.ffront.decorator import program, scan_operator from next_tests.integration_tests import cases @@ -157,6 +158,78 @@ def testee( ) +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_tuple_returns +def test_scan_with_tuple_domain_on_different_vertical_dims(cartesian_case): + @gtx.scan_operator(axis=KHalfDim, forward=True, init=0.0) + def cumsum(state: float, inp: float) -> float: + return state + inp + + @gtx.field_operator + def testee_op( + a: gtx.Field[[IDim, KHalfDim], float], b: cases.IKFloatField + ) -> tuple[gtx.Field[[IDim, KHalfDim], float], cases.IKFloatField]: + return cumsum(a), b + 1.0 + + @gtx.program + def testee( + a: gtx.Field[[IDim, KHalfDim], float], + b: cases.IKFloatField, + out_a: gtx.Field[[IDim, KHalfDim], float], + out_b: cases.IKFloatField, + isize: int32, + ksize: int32, + ): + testee_op( + a, + b, + out=(out_a, out_b), + domain=( + {IDim: (0, isize), KHalfDim: (0, ksize)}, + {IDim: (0, isize), KDim: (0, ksize)}, + ), + ) + + isize = cartesian_case.default_sizes[IDim] + ksize = cartesian_case.default_sizes[KHalfDim] + a = cases.allocate(cartesian_case, testee, "a")() + b = cases.allocate(cartesian_case, testee, "b")() + out_a = cases.allocate(cartesian_case, testee, "out_a").zeros()() + out_b = cases.allocate(cartesian_case, testee, "out_b").zeros()() + + cases.run(cartesian_case, testee, a, b, out_a, out_b, isize, ksize) + + np.testing.assert_allclose( + out_a.asnumpy()[:, :ksize], np.cumsum(a.asnumpy()[:, :ksize], axis=1) + ) + np.testing.assert_allclose(out_b.asnumpy()[:, :ksize], b.asnumpy()[:, :ksize] + 1.0) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_cartesian_shift +@pytest.mark.uses_concat_where +def test_scan_on_shifted_input_in_concat_where(cartesian_case): + @gtx.scan_operator(axis=KDim, forward=True, init=0.0) + def cumsum(state: float, inp: float) -> float: + return state + inp + + @gtx.field_operator + def testee(a: cases.IKFloatField) -> cases.IKFloatField: + return concat_where(KDim > 0, cumsum(a(KDim - 1)), -a) + + a = cases.allocate(cartesian_case, testee, "a")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + + def ref(a): + res = -a.copy() + res[:, 1:] = np.cumsum(a[:, :-1], axis=1) + return res + + cases.verify(cartesian_case, testee, a, out=out, ref=ref(a.asnumpy())) + + @pytest.mark.uses_scan @pytest.mark.uses_scan_without_field_args @pytest.mark.parametrize("forward", [True, False]) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py b/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py index a3e2c18e34..025957fdab 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_basic_program.py @@ -7,8 +7,10 @@ # SPDX-License-Identifier: BSD-3-Clause import numpy as np +import pytest import gt4py.next as gtx +from gt4py.next import errors IDim = gtx.Dimension("IDim") @@ -38,3 +40,34 @@ def test_basic(): prog(a, b, out) assert out.domain == b.domain assert np.allclose(out.ndarray, a.ndarray + b.ndarray) + + +KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) + + +@gtx.scan_operator(axis=KDim, forward=True, init=0.0) +def cumsum(state: gtx.float64, inp: gtx.float64) -> gtx.float64: + return state + inp + + +@gtx.field_operator +def scan_twice( + a: gtx.Field[[KDim], gtx.float64], +) -> tuple[gtx.Field[[KDim], gtx.float64], gtx.Field[[KDim], gtx.float64]]: + return cumsum(a), a + + +@gtx.program +def prog_scan_with_differing_ranges( + a: gtx.Field[[KDim], gtx.float64], + out1: gtx.Field[[KDim], gtx.float64], + out2: gtx.Field[[KDim], gtx.float64], +): + scan_twice(a, out=(out1, out2), domain=({KDim: (0, 4)}, {KDim: (1, 4)})) + + +def test_scan_with_differing_ranges_of_scan_axis_raises(): + a, out1, out2 = (gtx.as_field([KDim], np.ones(4)) for _ in range(3)) + + with pytest.raises(errors.exceptions.EmbeddedExecutionError, match="Scan axis"): + prog_scan_with_differing_ranges(a, out1, out2) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 80394dd18f..5883fe254d 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2732,7 +2732,7 @@ def _scan_cumsum(x, k_dim): scan = operators.ScanOperator(lambda state, v: state + v, forward=True, init=0.0, axis=k_dim) with embedded_context.update( - closure_column_range=NamedRange(k_dim, UnitRange(0, 4)), offset_provider={} + column_ranges=common.Domain(NamedRange(k_dim, UnitRange(0, 4))), offset_provider={} ): return scan(x) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py index 3dfdf3406a..6344be0bb4 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py @@ -122,7 +122,7 @@ def test_torch_scan_result_on_device_of_inputs(device): ) with embedded_context.update( - closure_column_range=NamedRange(K, UnitRange(0, 4)), offset_provider={} + column_ranges=common.Domain(NamedRange(K, UnitRange(0, 4))), offset_provider={} ): result = scan(x) From edcf7c3d7ea4906832038ef7caa39a555ed0b151 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 2 Dec 2026 08:34:21 +0100 Subject: [PATCH 07/18] fix[next]: address review of the scan-axis change - gtfn: merge adjacent scans only if they run on the same axis. - Domain inference keeps the range of the scan's own axis instead of every vertical dimension of the target domain. - iterator embedded: remove the column-mode arithmetic of `Column` and the `Column` branches of the builtins, unreachable now that only scans run column-wise; `Column.dtype` reads the first element. - Drop a FIXME whose reason no longer holds. --- src/gt4py/next/ffront/past_to_itir.py | 2 - src/gt4py/next/iterator/embedded.py | 67 +-------- .../next/iterator/transforms/infer_domain.py | 15 +- .../codegens/gtfn/itir_to_gtfn_ir.py | 1 + .../iterator_tests/test_embedded_internals.py | 130 ------------------ .../gtfn_tests/test_itir_to_gtfn_ir.py | 31 +++++ 6 files changed, 46 insertions(+), 200 deletions(-) diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index 13b5a76f8a..07b7a1d013 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -33,8 +33,6 @@ from gt4py.next.type_system import type_info, type_specifications as ts -# FIXME[#1582](tehrengruber): This should only depend on the program not the arguments. Remove -# dependency as soon as column axis can be deduced from ITIR in consumers of the CompilableProgram. def past_to_gtir(inp: ConcretePASTProgramDef) -> stages.CompilableProgramDef: """ Lower a PAST program definition to Iterator IR. diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 4ab7319971..8ad994ee59 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -262,29 +262,21 @@ def _numpy_structured_value_to_tuples(value: Any) -> Any: return value -class Column(np.lib.mixins.NDArrayOperatorsMixin): - """Represents a column when executed in column mode, i.e. within a scan. +class Column: + """A column of values along the scan axis, starting at index `kstart`.""" - Implements `__array_ufunc__` and `__array_function__` to isolate - and simplify dispatching in iterator ir builtins. - """ - - def __init__(self, kstart: int, data: np.ndarray | Scalar) -> None: + def __init__(self, kstart: int, data: np.ndarray) -> None: + assert isinstance(data, np.ndarray) self.kstart = kstart - assert isinstance(data, (np.ndarray, Scalar)) - column_range: common.NamedRange = embedded_context.get_closure_column_range() - self.data = ( - data if isinstance(data, np.ndarray) else np.full(len(column_range.unit_range), data) - ) + self.data = data @property def dtype(self) -> np.dtype: # not directly dtype of `self.data` as that might be a structured type containing `None` - return _elem_dtype(self.data[self.kstart]) + return _elem_dtype(self.data[0]) def __gt_type__(self) -> ts.TypeSpec: - elem = self.data[self.kstart] - return type_translation.from_value(_numpy_structured_value_to_tuples(elem)) + return type_translation.from_value(_numpy_structured_value_to_tuples(self.data[0])) def __getitem__(self, i: int) -> Any: result = self.data[i - self.kstart] @@ -293,45 +285,12 @@ def __getitem__(self, i: int) -> Any: return tuple(result) return result - def tuple_get(self, i: int) -> Column: - if self.data.dtype.names: - return Column(self.kstart, self.data[self.data.dtype.names[i]]) - else: - return Column(self.kstart, self.data[i, ...]) - def __setitem__(self, i: int, v: Any) -> None: self.data[i - self.kstart] = v def __array__(self, dtype: Optional[npt.DTypeLike] = None) -> np.ndarray: return self.data.astype(dtype, copy=False) - def _validate_kstart(self, args): - if wrong_kstarts := ( # noqa: F841 [unused-variable] - set(arg.kstart for arg in args if isinstance(arg, Column)) - {self.kstart} - ): - raise ValueError( - "Incompatible 'Column.kstart': it should be '{self.kstart}' but found other values: {wrong_kstarts}." - ) - - def __array_ufunc__(self, ufunc, method, *inputs, **kwargs) -> Column: - # note: - # - we allow scalars to silently pass through and be handled correctly by numpy - # - we let numpy do the checking of compatible shapes - assert method == "__call__" - self._validate_kstart(inputs) - return self.__class__( - self.kstart, - ufunc(*(inp.data if isinstance(inp, Column) else inp for inp in inputs), **kwargs), - ) - - def __array_function__(self, func, types, args, kwargs) -> Column: - # see note in `__array_ufunc__` - self._validate_kstart(args) - return self.__class__( - self.kstart, - func(*(arg.data if isinstance(arg, Column) else arg for arg in args), **kwargs), - ) - @builtins.deref.register(EMBEDDED) def deref(it): @@ -347,37 +306,27 @@ def can_deref(it): def if_(cond, t, f): # ensure someone doesn't accidentally pass an iterator assert not hasattr(cond, "shift") - if any(isinstance(arg, Column) for arg in (cond, t, f)): - return np.where(cond, t, f) return t if cond else f @builtins.cast_.register(EMBEDDED) def cast_(obj, new_dtype): - if isinstance(obj, Column): - return obj.data.astype(new_dtype.__name__) return new_dtype(obj) @builtins.not_.register(EMBEDDED) def not_(a): - if isinstance(a, Column): - return np.logical_not(a) return not a @builtins.neg.register(EMBEDDED) def neg(a): - if isinstance(a, Column): - return np.negative(a) return np.negative(a) @builtins.gamma.register(EMBEDDED) def gamma(a): gamma_ = np.vectorize(math.gamma) - if isinstance(a, Column): - return Column(kstart=a.kstart, data=gamma_(a.data)) res = gamma_(a) assert res.ndim == 0 return res.item() @@ -385,8 +334,6 @@ def gamma(a): @builtins.tuple_get.register(EMBEDDED) def tuple_get(i, tup): - if isinstance(tup, Column): - return tup.tuple_get(i) return tup[i] diff --git a/src/gt4py/next/iterator/transforms/infer_domain.py b/src/gt4py/next/iterator/transforms/infer_domain.py index 5466843476..31d78132ab 100644 --- a/src/gt4py/next/iterator/transforms/infer_domain.py +++ b/src/gt4py/next/iterator/transforms/infer_domain.py @@ -171,15 +171,11 @@ def _filter_domain_dimensions( return domain_utils.SymbolicDomain(grid_type=domain.grid_type, ranges=retained) -def _extract_vertical_dims( - domain: domain_utils.SymbolicDomain, +def _extract_scan_axis( + domain: domain_utils.SymbolicDomain, axis: common.Dimension ) -> dict[common.Dimension, domain_utils.SymbolicRange]: assert isinstance(domain, domain_utils.SymbolicDomain) - return { - dim: range_ - for dim, range_ in domain.ranges.items() - if dim.kind == common.DimensionKind.VERTICAL - } + return {axis: domain.ranges[axis]} if axis in domain.ranges else {} def _infer_as_fieldop( @@ -500,9 +496,12 @@ def infer_expr( ) if cpm.is_applied_as_fieldop(expr) and cpm.is_call_to(expr.fun.args[0], "scan"): + axis_literal = expr.fun.args[0].args[3] + assert isinstance(axis_literal, itir.AxisLiteral) + axis = common.Dimension(value=axis_literal.value, kind=axis_literal.kind) additional_dims = gtx_utils.tree_map( lambda d: ( - _extract_vertical_dims(d) if isinstance(d, domain_utils.SymbolicDomain) else {} + _extract_scan_axis(d, axis) if isinstance(d, domain_utils.SymbolicDomain) else {} ) )(domain) else: diff --git a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py index 739cfd141c..9604dca506 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py @@ -512,6 +512,7 @@ def remap_args(s: Scan) -> Scan: isinstance(execution, ScanExecution) and isinstance(res[-1], ScanExecution) and execution.backend == res[-1].backend + and execution.axis == res[-1].axis ): res[-1] = merge(res[-1], execution) else: diff --git a/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py b/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py index f41e819475..2591683672 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py @@ -19,136 +19,6 @@ from next_tests.unit_tests.conftest import strict_array_on_device1 -def test_column_ufunc(): - def test_func(): - a = embedded.Column(1, np.asarray(range(0, 3))) - b = embedded.Column(1, np.asarray(range(3, 6))) - res = a + b - - assert isinstance(res, embedded.Column) - assert np.array_equal(res.data, a.data + b.data) - assert res.kstart == 1 - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - def test_func(data_a: int, data_b: int): - a = embedded.Column(1, data_a) - b = embedded.Column(1, data_b) - res = a + b - - assert isinstance(res, embedded.Column) - assert np.array_equal(res.data, a.data + b.data) - assert res.kstart == 1 - - with embedded_context.update(closure_column_range=range(2, 999)): - # Setting an invalid column_range here shouldn't affect other contexts - - with embedded_context.update( - offset_provider={}, - closure_column_range=common.NamedRange( - common.Dimension("K", kind=common.DimensionKind.VERTICAL), range(0, 3) - ), - ): - test_func(2, 3) - - -def test_column_ufunc_with_scalar(): - def test_func(): - a = embedded.Column(1, np.asarray(range(0, 3))) - res = 1.0 + a - assert isinstance(res, embedded.Column) - assert np.array_equal(res.data, a.data + 1.0) - assert res.kstart == 1 - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - -def test_column_ufunc_wrong_kstart(): - def test_func(): - a = embedded.Column(1, np.asarray(range(0, 3))) - wrong_kstart = embedded.Column(2, np.asarray(range(3, 6))) - - with pytest.raises(ValueError): - a + wrong_kstart - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - -def test_column_ufunc_wrong_shape(): - def test_func(): - a = embedded.Column(1, np.asarray(range(0, 3))) - wrong_shape = embedded.Column(1, np.asarray([1, 2])) - - with pytest.raises(ValueError): - a + wrong_shape - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - -def test_column_array_function(): - def test_func(): - cond = embedded.Column(1, np.asarray([True, False])) - a = embedded.Column(1, np.asarray([1, 1])) - b = embedded.Column(1, np.asarray([2, 2])) - - res = np.where(cond, a, b) - ref = np.asarray([1, 2]) - - assert isinstance(res, embedded.Column) - assert np.array_equal(res.data, ref) - assert res.kstart == 1 - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - -def test_column_array_function_with_scalar(): - def test_func(): - cond = embedded.Column(1, np.asarray([True, False])) - a = 1 - b = embedded.Column(1, np.asarray([2, 2])) - - res = np.where(cond, a, b) - ref = np.asarray([1, 2]) - - assert isinstance(res, embedded.Column) - assert np.array_equal(res.data, ref) - assert res.kstart == 1 - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - -def test_column_array_function_wrong_kstart(): - def test_func(): - cond = embedded.Column(1, np.asarray([True, False])) - wrong_kstart = embedded.Column(2, np.asarray([1, 1])) - b = embedded.Column(1, np.asarray([2, 2])) - - with pytest.raises(ValueError): - np.where(cond, wrong_kstart, b) - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - -def test_column_array_function_wrong_shape(): - def test_func(): - cond = embedded.Column(1, np.asarray([True, False])) - wrong_shape = embedded.Column(2, np.asarray([1, 1, 1])) - b = embedded.Column(1, np.asarray([2, 2])) - - with pytest.raises(ValueError): - np.where(cond, wrong_shape, b) - - with embedded_context.update(offset_provider={}, closure_column_range="SOMETHING"): - test_func() - - def test_lift_accepts_cartesian_dimension_offset(): K = common.Dimension("K", kind=common.DimensionKind.VERTICAL) lifted = embedded.lift(lambda *args: 0)() diff --git a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py index 036b41370a..c533629c74 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py +++ b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_itir_to_gtfn_ir.py @@ -74,3 +74,34 @@ def test_unstructured_param_dimension_tag(dim, alias): result = it2gtfn.GTFN_lowering.apply(testee, offset_provider_type={}) aliases = {str(tag.name.id): tag.alias for tag in result.offset_definitions} assert aliases[dim.value] == alias + + +def _scan_execution(axis: str, output: str) -> gtfn_ir.ScanExecution: + return gtfn_ir.ScanExecution( + backend=gtfn_ir.Backend(domain=gtfn_ir.SymRef(id="domain")), + scans=[ + gtfn_ir.Scan( + function=gtfn_ir.SymRef(id="scan_pass"), + output=0, + inputs=[1], + init=gtfn_ir.Literal(value="0.0", type="float64"), + ) + ], + args=[gtfn_ir.SymRef(id=output), gtfn_ir.SymRef(id="inp")], + axis=gtfn_ir.SymRef(id=axis), + ) + + +def test_merge_scans_on_same_axis(): + merged = it2gtfn.GTFN_lowering._merge_scans( + [_scan_execution("K", "out_a"), _scan_execution("K", "out_b")] + ) + + assert len(merged) == 1 + assert len(merged[0].scans) == 2 + + +def test_no_merge_of_scans_on_different_axes(): + executions = [_scan_execution("K", "out_a"), _scan_execution("L", "out_b")] + + assert it2gtfn.GTFN_lowering._merge_scans(executions) == executions From 5c9c549cd10deeb49e0890e77bed252f1f874c4f Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 2 Dec 2026 08:48:51 +0100 Subject: [PATCH 08/18] test[next]: cover a scan combined with a field on another vertical dimension Also remove the unused `Column.dtype` and `Column.__array__`, and use `dim_from_axis_literal` in domain inference. --- src/gt4py/next/iterator/embedded.py | 8 ----- .../next/iterator/transforms/infer_domain.py | 2 +- .../feature_tests/ffront_tests/test_scan.py | 30 +++++++++++++++++++ .../iterator_tests/test_embedded_internals.py | 3 -- 4 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 8ad994ee59..2c2f8ff350 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -270,11 +270,6 @@ def __init__(self, kstart: int, data: np.ndarray) -> None: self.kstart = kstart self.data = data - @property - def dtype(self) -> np.dtype: - # not directly dtype of `self.data` as that might be a structured type containing `None` - return _elem_dtype(self.data[0]) - def __gt_type__(self) -> ts.TypeSpec: return type_translation.from_value(_numpy_structured_value_to_tuples(self.data[0])) @@ -288,9 +283,6 @@ def __getitem__(self, i: int) -> Any: def __setitem__(self, i: int, v: Any) -> None: self.data[i - self.kstart] = v - def __array__(self, dtype: Optional[npt.DTypeLike] = None) -> np.ndarray: - return self.data.astype(dtype, copy=False) - @builtins.deref.register(EMBEDDED) def deref(it): diff --git a/src/gt4py/next/iterator/transforms/infer_domain.py b/src/gt4py/next/iterator/transforms/infer_domain.py index 31d78132ab..0027d2c766 100644 --- a/src/gt4py/next/iterator/transforms/infer_domain.py +++ b/src/gt4py/next/iterator/transforms/infer_domain.py @@ -498,7 +498,7 @@ def infer_expr( if cpm.is_applied_as_fieldop(expr) and cpm.is_call_to(expr.fun.args[0], "scan"): axis_literal = expr.fun.args[0].args[3] assert isinstance(axis_literal, itir.AxisLiteral) - axis = common.Dimension(value=axis_literal.value, kind=axis_literal.kind) + axis = ir_misc.dim_from_axis_literal(axis_literal) additional_dims = gtx_utils.tree_map( lambda d: ( _extract_scan_axis(d, axis) if isinstance(d, domain_utils.SymbolicDomain) else {} 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 6b2eadb177..4557bbbf4c 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 @@ -206,6 +206,36 @@ def testee( np.testing.assert_allclose(out_b.asnumpy()[:, :ksize], b.asnumpy()[:, :ksize] + 1.0) +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_combined_with_field_on_another_vertical_dim(cartesian_case): + LDim = gtx.Dimension("LDim", kind=gtx.DimensionKind.VERTICAL) + + @gtx.scan_operator(axis=KDim, forward=True, init=0.0) + def cumsum(state: float, inp: float) -> float: + return state + inp + + @gtx.field_operator + def testee( + a: cases.IKFloatField, b: gtx.Field[[IDim, KDim, LDim], float] + ) -> gtx.Field[[IDim, KDim, LDim], float]: + return cumsum(a) + b + + isize, ksize, lsize = cartesian_case.default_sizes[IDim], cartesian_case.default_sizes[KDim], 3 + a = cartesian_case.as_field([IDim, KDim], np.random.rand(isize, ksize)) + b = cartesian_case.as_field([IDim, KDim, LDim], np.random.rand(isize, ksize, lsize)) + out = cartesian_case.as_field([IDim, KDim, LDim], np.zeros((isize, ksize, lsize))) + + cases.verify( + cartesian_case, + testee, + a, + b, + out=out, + ref=np.cumsum(a.asnumpy(), axis=1)[:, :, np.newaxis] + b.asnumpy(), + ) + + @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator @pytest.mark.uses_cartesian_shift diff --git a/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py b/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py index 2591683672..7a133e2d49 100644 --- a/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py +++ b/tests/next_tests/unit_tests/iterator_tests/test_embedded_internals.py @@ -6,9 +6,6 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import contextvars as cvars -from typing import Any, Callable, Optional - import numpy as np import pytest From 09046ac50e95efc22b1f7192dded9516b1dcec6f Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 2 Dec 2026 08:58:20 +0100 Subject: [PATCH 09/18] test[next]: remove test_scan_in_stencil and its marker A scan nested inside a stencil is unsupported on every backend. --- pyproject.toml | 1 - tests/next_tests/definitions.py | 5 -- .../feature_tests/iterator_tests/test_scan.py | 59 ------------------- 3 files changed, 65 deletions(-) delete mode 100644 tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py diff --git a/pyproject.toml b/pyproject.toml index 01dff97bc1..a9daac3da0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -269,7 +269,6 @@ markers = [ 'uses_scalar_in_domain_and_fo', 'uses_scan: tests that uses scan', 'uses_scan_in_field_operator: tests that require backend support for scan in field operator', - 'uses_scan_in_stencil: tests that require backend support for scan in stencil', 'uses_scan_without_field_args: tests that require calls to scan that do not have any fields as arguments', 'uses_scan_nested: tests that use nested scans', 'uses_sparse_fields: tests that require backend support for sparse fields', diff --git a/tests/next_tests/definitions.py b/tests/next_tests/definitions.py index fbd2a76492..734c4677ff 100644 --- a/tests/next_tests/definitions.py +++ b/tests/next_tests/definitions.py @@ -164,7 +164,6 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): USES_REDUCE_WITH_LAMBDA = "uses_reduce_with_lambda" USES_SCAN = "uses_scan" USES_SCAN_IN_FIELD_OPERATOR = "uses_scan_in_field_operator" -USES_SCAN_IN_STENCIL = "uses_scan_in_stencil" USES_SCAN_WITHOUT_FIELD_ARGS = "uses_scan_without_field_args" USES_SCAN_NESTED = "uses_scan_nested" USES_SPARSE_FIELDS = "uses_sparse_fields" @@ -240,7 +239,6 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): (USES_COMPOSITE_SHIFTS, XFAIL, UNSUPPORTED_MESSAGE), (USES_LIFT, XFAIL, UNSUPPORTED_MESSAGE), (USES_REDUCE_WITH_LAMBDA, XFAIL, UNSUPPORTED_MESSAGE), - (USES_SCAN_IN_STENCIL, XFAIL, BINDINGS_UNSUPPORTED_MESSAGE), (USES_SPARSE_FIELDS, XFAIL, UNSUPPORTED_MESSAGE), (USES_TUPLE_ITERATOR, XFAIL, UNSUPPORTED_MESSAGE), ( @@ -288,7 +286,6 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): ] ROUNDTRIP_SKIP_LIST = DOMAIN_INFERENCE_SKIP_LIST + [ (USES_PROGRAM_METRICS, XFAIL, UNSUPPORTED_MESSAGE), - (USES_SCAN_IN_STENCIL, XFAIL, UNSUPPORTED_MESSAGE), (USES_SPARSE_FIELDS_AS_OUTPUT, XFAIL, UNSUPPORTED_MESSAGE), (USES_TUPLES_ARGS_WITH_DIFFERENT_BUT_PROMOTABLE_DIMS, XFAIL, UNSUPPORTED_MESSAGE), (USES_CONCAT_WHERE, XFAIL, UNSUPPORTED_MESSAGE), @@ -308,7 +305,6 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): + [ # floordiv not yet supported, see https://github.com/GridTools/gt4py/issues/1136 (USES_FLOORDIV, XFAIL, BINDINGS_UNSUPPORTED_MESSAGE), - (USES_SCAN_IN_STENCIL, XFAIL, BINDINGS_UNSUPPORTED_MESSAGE), (USES_STRIDED_NEIGHBOR_OFFSET, XFAIL, BINDINGS_UNSUPPORTED_MESSAGE), # max_over broken, see https://github.com/GridTools/gt4py/issues/1289 (USES_MAX_OVER, XFAIL, UNSUPPORTED_MESSAGE), @@ -342,7 +338,6 @@ class ProgramFormatterId(_PythonObjectIdMixin, str, enum.Enum): + [(USES_SCAN_NESTED, XFAIL, UNSUPPORTED_MESSAGE)], ProgramFormatterId.GTFN_CPP_FORMATTER: DOMAIN_INFERENCE_SKIP_LIST + [ - (USES_SCAN_IN_STENCIL, XFAIL, BINDINGS_UNSUPPORTED_MESSAGE), (USES_REDUCTION_WITH_ONLY_SPARSE_FIELDS, XFAIL, REDUCTION_WITH_ONLY_SPARSE_FIELDS_MESSAGE), ], ProgramFormatterId.LISP_FORMATTER: DOMAIN_INFERENCE_SKIP_LIST, diff --git a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py deleted file mode 100644 index aa90cd5d7a..0000000000 --- a/tests/next_tests/integration_tests/feature_tests/iterator_tests/test_scan.py +++ /dev/null @@ -1,59 +0,0 @@ -# GT4Py - GridTools Framework -# -# Copyright (c) 2014-2024, ETH Zurich -# All rights reserved. -# -# Please, refer to the LICENSE file in the root directory. -# SPDX-License-Identifier: BSD-3-Clause - -import numpy as np -import pytest - -import gt4py.next as gtx -from gt4py.next.iterator.builtins import cartesian_domain, deref, named_range, scan, shift -from gt4py.next.iterator.runtime import fundef - -from next_tests.integration_tests.cases import IDim, KDim -from next_tests.unit_tests.conftest import program_processor, run_processor - - -@pytest.mark.uses_cartesian_shift -@pytest.mark.uses_scan_in_stencil -def test_scan_in_stencil(program_processor): - # FIXME[#1582](tehrengruber): Remove test after scan is reworked. - program_processor, validate = program_processor - if program_processor is None: - pytest.xfail("Embedded execution only runs a 'scan' that is the stencil of a closure.") - - isize = 1 - ksize = 3 - Koff = gtx.CartesianConnectivity(KDim) - inp = gtx.as_field( - [IDim, KDim], - np.copy(np.broadcast_to(np.arange(0, ksize, dtype=np.float64), (isize, ksize))), - ) - out = gtx.as_field([IDim, KDim], np.zeros((isize, ksize))) - - reference = np.zeros((isize, ksize - 1)) - reference[:, 0] = inp.ndarray[:, 0] + inp.ndarray[:, 1] - for k in range(1, ksize - 1): - reference[:, k] = reference[:, k - 1] + inp.ndarray[:, k] + inp.ndarray[:, k + 1] - - @fundef - def sum(state, k, kp): - return state + deref(k) + deref(kp) - - @fundef - def wrapped(inp): - return scan(sum, True, 0.0, KDim)(inp, shift(Koff, 1)(inp)) - - run_processor( - wrapped[cartesian_domain(named_range(IDim, 0, isize), named_range(KDim, 0, ksize - 1))], - program_processor, - inp, - out=out, - offset_provider={}, - ) - - if validate: - assert np.allclose(out[:, :-1].asnumpy(), reference) From b06becef692dd6a446eabac6163580d7dc607732 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 2 Dec 2026 08:58:20 +0100 Subject: [PATCH 10/18] fix[next]: include the scan axis in the type of an applied scan A scan whose inputs lack its axis now gets a result on that axis, as in the frontend, instead of failing type inference when written to a field on the axis. --- .../next/iterator/type_system/inference.py | 6 ++- .../iterator/type_system/type_synthesizer.py | 6 +++ .../feature_tests/ffront_tests/test_scan.py | 44 +++++++++++++++++++ .../transforms_tests/test_collapse_tuple.py | 2 +- 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/iterator/type_system/inference.py b/src/gt4py/next/iterator/type_system/inference.py index c2ee562fff..3fa95f6123 100644 --- a/src/gt4py/next/iterator/type_system/inference.py +++ b/src/gt4py/next/iterator/type_system/inference.py @@ -549,7 +549,7 @@ def visit_FunCall( return tuple_.type.types[index] # Additional information beyond what is given by the argument types - syntactic_info = {} + syntactic_info: dict[str, Any] = {} if is_applied_as_fieldop(node): # Collect shifts and pass them as a kwarg to :func:`type_synthesizer.applied_as_fieldop`. # The node is available here, but not within the `TypeSynthesizer`, so we handle it here. @@ -560,6 +560,10 @@ def visit_FunCall( if not referenced_fun_names else None ) + if is_call_to(stencil, "scan"): + axis = stencil.args[3] + assert isinstance(axis, itir.AxisLiteral) + syntactic_info["scan_axis"] = common.Dimension(value=axis.value, kind=axis.kind) fun = self.visit(node.fun, ctx=ctx) args = self.visit(node.args, ctx=ctx) diff --git a/src/gt4py/next/iterator/type_system/type_synthesizer.py b/src/gt4py/next/iterator/type_system/type_synthesizer.py index c8a14fc9ad..c1f6c31e79 100644 --- a/src/gt4py/next/iterator/type_system/type_synthesizer.py +++ b/src/gt4py/next/iterator/type_system/type_synthesizer.py @@ -566,6 +566,7 @@ def applied_as_fieldop( # For each stencil parameter all locations it is `deref`ed on # see :func:`gt4py.next.iterator.transforms.trace_stencil`. shift_sequences_per_param: list[set[tuple[itir.OffsetLiteral, ...]]] | None, + scan_axis: common.Dimension | None = None, ) -> ts.FieldType | ts.TupleType | ts.DeferredType: if any( isinstance(el, ts.DeferredType) @@ -597,6 +598,11 @@ def applied_as_fieldop( assert all(isinstance(dim, common.Dimension) for dim in output_dims) deduced_domain = ts.DomainType(dims=output_dims) + if deduced_domain and scan_axis is not None: + deduced_domain = ts.DomainType( + dims=common.promote_dims(deduced_domain.dims, [scan_axis]) + ) + if deduced_domain: domain = deduced_domain else: 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 4557bbbf4c..3dab7561aa 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 @@ -206,6 +206,50 @@ def testee( np.testing.assert_allclose(out_b.asnumpy()[:, :ksize], b.asnumpy()[:, :ksize] + 1.0) +@pytest.mark.uses_scan +def test_scan_over_axis_not_in_inputs(cartesian_case): + @gtx.scan_operator(axis=KDim, forward=True, init=0.0) + def cumsum(state: float, inp: float) -> float: + return state + inp + + @gtx.program + def testee(a: cases.IFloatField, out: cases.IKFloatField): + cumsum(a, out=out) + + a = cases.allocate(cartesian_case, testee, "a")() + out = cases.allocate(cartesian_case, testee, "out").zeros()() + ksize = cartesian_case.default_sizes[KDim] + + cases.verify( + cartesian_case, + testee, + a, + out, + inout=out, + ref=a.asnumpy()[:, np.newaxis] * np.arange(1, ksize + 1), + ) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_over_axis_not_in_inputs_combined_with_field(cartesian_case): + @gtx.scan_operator(axis=KDim, forward=True, init=0.0) + def cumsum(state: float, inp: float) -> float: + return state + inp + + @gtx.field_operator + def testee(a: cases.IFloatField, b: cases.IKFloatField) -> cases.IKFloatField: + return cumsum(a) + b + + ksize = cartesian_case.default_sizes[KDim] + + cases.verify_with_default_data( + cartesian_case, + testee, + ref=lambda a, b: a[:, np.newaxis] * np.arange(1, ksize + 1) + b, + ) + + @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator def test_scan_combined_with_field_on_another_vertical_dim(cartesian_case): diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py index ebb1c74c22..e4a8bf2330 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py @@ -448,7 +448,7 @@ def test_flatten_as_fieldop_args_nested(uids: utils.IDGeneratorPool): def test_flatten_as_fieldop_args_scan(uids: utils.IDGeneratorPool): it_type = it_ts.IteratorType( - position_dims=[], + position_dims=[KDim], defined_dims=[], element_type=ts.TupleType(types=[int_type, int_type]), ) From 98694eee4047054c7bd9d496630da33c3b07c9f7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 2 Dec 2026 09:45:38 +0100 Subject: [PATCH 11/18] test[next]: mark the tuple-domain scan test as using scalars in the domain jax_jit traces the domain bounds and cannot build the scan range from them. --- .../integration_tests/feature_tests/ffront_tests/test_scan.py | 1 + 1 file changed, 1 insertion(+) 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 3dab7561aa..8e46e93fd1 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 @@ -161,6 +161,7 @@ def testee( @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator @pytest.mark.uses_tuple_returns +@pytest.mark.uses_scalar_in_domain def test_scan_with_tuple_domain_on_different_vertical_dims(cartesian_case): @gtx.scan_operator(axis=KHalfDim, forward=True, init=0.0) def cumsum(state: float, inp: float) -> float: From 7f3c39e7c24dae276e4bba0228e0e7df192f4983 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 2 Dec 2026 09:45:45 +0100 Subject: [PATCH 12/18] refactor[next]: one embedded context variable for column ranges The iterator embedded stores the column of a scan closure in `column_ranges` as well, replacing `closure_column_range`. --- src/gt4py/next/embedded/context.py | 34 ++---------- src/gt4py/next/iterator/embedded.py | 25 ++++++--- .../unit_tests/embedded_tests/test_context.py | 54 +++++++++---------- 3 files changed, 46 insertions(+), 67 deletions(-) diff --git a/src/gt4py/next/embedded/context.py b/src/gt4py/next/embedded/context.py index 70ab2fa6cd..8d7d97ce47 100644 --- a/src/gt4py/next/embedded/context.py +++ b/src/gt4py/next/embedded/context.py @@ -18,9 +18,6 @@ import gt4py.next.errors.exceptions as exceptions -_closure_column_range: contextvars.ContextVar[common.NamedRange] = contextvars.ContextVar( - "_column_range" -) _column_ranges: contextvars.ContextVar[common.Domain] = contextvars.ContextVar("_column_ranges") _offset_provider: contextvars.ContextVar[common.OffsetProvider] = contextvars.ContextVar( "_offset_provider" @@ -33,24 +30,6 @@ _NO_DEFAULT_SENTINEL: Any = object() -@overload -def get_closure_column_range() -> common.NamedRange: ... - - -@overload -def get_closure_column_range(default: _T) -> common.NamedRange | _T: ... - - -def get_closure_column_range(default: _T = _NO_DEFAULT_SENTINEL) -> common.NamedRange | _T: - """Column range used in 'column mode' in the current embedded iterator closure execution context.""" - result = _closure_column_range.get(default) - if result is _NO_DEFAULT_SENTINEL: - raise exceptions.EmbeddedExecutionError( - "No column range set in the current embedded iterator closure execution context." - ) - return result - - @overload def get_column_ranges() -> common.Domain: ... @@ -60,11 +39,11 @@ def get_column_ranges(default: _T) -> common.Domain | _T: ... def get_column_ranges(default: _T = _NO_DEFAULT_SENTINEL) -> common.Domain | _T: - """Ranges of the vertical dimensions of the output domain of the current field operator call.""" + """Ranges of the column (scan) dimensions in the current embedded execution context.""" result = _column_ranges.get(default) if result is _NO_DEFAULT_SENTINEL: raise exceptions.EmbeddedExecutionError( - "No column ranges set in the current embedded field operator execution context." + "No column ranges set in the current embedded execution context." ) return result @@ -90,16 +69,12 @@ def get_offset_provider(default: _T = _NO_DEFAULT_SENTINEL) -> common.OffsetProv @contextlib.contextmanager def update( *, - closure_column_range: common.NamedRange | eve.NothingType = eve.NOTHING, column_ranges: common.Domain | eve.NothingType = eve.NOTHING, offset_provider: common.OffsetProvider | eve.NothingType = eve.NOTHING, ) -> Generator[None, None, None]: """Context handler updating the current embedded context with the provided values.""" - closure_token, column_ranges_token, offset_provider_token = None, None, None - if closure_column_range is not eve.NOTHING: - assert not isinstance(closure_column_range, eve.NothingType) - closure_token = _closure_column_range.set(closure_column_range) + column_ranges_token, offset_provider_token = None, None if column_ranges is not eve.NOTHING: assert not isinstance(column_ranges, eve.NothingType) column_ranges_token = _column_ranges.set(column_ranges) @@ -110,9 +85,6 @@ def update( try: yield None finally: - if closure_column_range is not eve.NOTHING: - assert closure_token is not None - _closure_column_range.reset(closure_token) if column_ranges is not eve.NOTHING: assert column_ranges_token is not None _column_ranges.reset(column_ranges_token) diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 2c2f8ff350..1765fd5121 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -765,7 +765,7 @@ def _make_tuple( except embedded_exceptions.IndexOutOfBounds: return _UNDEFINED else: - column_range = embedded_context.get_closure_column_range().unit_range + column_range = _get_column_range().unit_range assert column_range is not None col: list[ @@ -836,7 +836,7 @@ def deref(self) -> Any: raise IndexError("Iterator position doesn't point to valid location for its field.") slice_column = dict[Tag, range]() if self.column_axis is not None: - column_range = embedded_context.get_closure_column_range() + column_range = _get_column_range() assert column_range is not None k_pos = shifted_pos.pop(self.column_axis) assert isinstance(k_pos, int) @@ -876,7 +876,7 @@ def make_in_iterator( init = [None] * sparse_dimensions.count(sparse_dim) new_pos[sparse_dim.value] = init # type: ignore[assignment] # looks like mypy is confused if column_dimension is not None: - column_range = embedded_context.get_closure_column_range().unit_range + column_range = _get_column_range().unit_range # if we deal with column stencil the column position is just an offset by which the whole column needs to be shifted assert column_range is not None new_pos[column_dimension.value] = column_range.start @@ -1574,7 +1574,7 @@ class _Scan: axis: common.Dimension def __call__(self, *iters: ItIterator) -> Column: - column_range = embedded_context.get_closure_column_range().unit_range + column_range = _get_column_range().unit_range sorted_column_range = column_range if self.is_forward else reversed(column_range) state = self.init col = Column(column_range.start, np.zeros(len(column_range), dtype=_elem_dtype(self.init))) @@ -1675,6 +1675,19 @@ def _extract_column_range( return eve.NOTHING +def _as_column_ranges( + column_range: common.NamedRange | eve.NothingType, +) -> common.Domain | eve.NothingType: + return ( + common.Domain(column_range) if isinstance(column_range, common.NamedRange) else eve.NOTHING + ) + + +def _get_column_range() -> common.NamedRange: + (column_range,) = embedded_context.get_column_ranges() + return column_range + + def _get_output_type( fun: Callable, domain_: runtime.CartesianDomain | runtime.UnstructuredDomain, @@ -1690,7 +1703,7 @@ def _get_output_type( # determine dtype by computing result at one point pos_in_domain = next(iter(_domain_iterator(domain))) - with embedded_context.update(closure_column_range=col_range): + with embedded_context.update(column_ranges=_as_column_ranges(col_range)): single_pos_result = _compute_at_position(fun, args, pos_in_domain, col_dim) assert single_pos_result is not _UNDEFINED, "Stencil contains an Out-Of-Bound access." return type_translation.from_value(single_pos_result) @@ -1769,7 +1782,7 @@ def closure( out = as_tuple_field(out) if is_tuple_of_field(out) else _wrap_field(out) promoted_ins = [promote_scalars(inp) for inp in ins] - with embedded_context.update(closure_column_range=column_range): + with embedded_context.update(column_ranges=_as_column_ranges(column_range)): for pos in _domain_iterator(domain): res = _compute_at_position(sten, promoted_ins, pos, column_dim) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_context.py b/tests/next_tests/unit_tests/embedded_tests/test_context.py index 8ceeb82174..c215a3ef52 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_context.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_context.py @@ -15,11 +15,11 @@ def test_getters(): DEFAULT = object() - assert ctx.get_closure_column_range(DEFAULT) is DEFAULT + assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT - with pytest.raises(exceptions.EmbeddedExecutionError, match="closure execution context."): - assert ctx.get_closure_column_range() + with pytest.raises(exceptions.EmbeddedExecutionError, match="No column ranges set"): + assert ctx.get_column_ranges() with pytest.raises(exceptions.EmbeddedExecutionError, match="closure execution context."): assert ctx.get_offset_provider() @@ -27,62 +27,56 @@ def test_getters(): def test_update_with_both_parameters(): DEFAULT = object() - assert ctx.get_closure_column_range(DEFAULT) is DEFAULT + assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT initial_column_range = common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)) initial_offset_provider = {} - with ctx.update( - closure_column_range=initial_column_range, offset_provider=initial_offset_provider - ): - assert ctx.get_closure_column_range() is initial_column_range + with ctx.update(column_ranges=initial_column_range, offset_provider=initial_offset_provider): + assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider test_column_range = common.NamedRange(common.Dimension("NewDim"), common.UnitRange(-1, 1)) test_offset_provider = {"I": "NewDim"} - with ctx.update( - closure_column_range=test_column_range, offset_provider=test_offset_provider - ): - assert ctx.get_closure_column_range() is test_column_range + with ctx.update(column_ranges=test_column_range, offset_provider=test_offset_provider): + assert ctx.get_column_ranges() is test_column_range assert ctx.get_offset_provider() is test_offset_provider - assert ctx.get_closure_column_range() is initial_column_range + assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider - assert ctx.get_closure_column_range(DEFAULT) is DEFAULT + assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT def test_update_with_no_parameters(): DEFAULT = object() - assert ctx.get_closure_column_range(DEFAULT) is DEFAULT + assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT initial_column_range = common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)) initial_offset_provider = {} - with ctx.update( - closure_column_range=initial_column_range, offset_provider=initial_offset_provider - ): - assert ctx.get_closure_column_range() is initial_column_range + with ctx.update(column_ranges=initial_column_range, offset_provider=initial_offset_provider): + assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider with ctx.update(): - assert ctx.get_closure_column_range() is initial_column_range + assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider - assert ctx.get_closure_column_range() is initial_column_range + assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider - assert ctx.get_closure_column_range(DEFAULT) is DEFAULT + assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT def test_update_with_exception(): DEFAULT = object() - assert ctx.get_closure_column_range(DEFAULT) is DEFAULT + assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT initial_column_range = common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)) @@ -90,9 +84,9 @@ def test_update_with_exception(): with pytest.raises(RuntimeError, match="Outer exception"): with ctx.update( - closure_column_range=initial_column_range, offset_provider=initial_offset_provider + column_ranges=initial_column_range, offset_provider=initial_offset_provider ): - assert ctx.get_closure_column_range() is initial_column_range + assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider test_column_range = common.NamedRange( @@ -102,19 +96,19 @@ def test_update_with_exception(): with pytest.raises(RuntimeError, match="Inner exception"): with ctx.update( - closure_column_range=test_column_range, offset_provider=test_offset_provider + column_ranges=test_column_range, offset_provider=test_offset_provider ): - assert ctx.get_closure_column_range() is test_column_range + assert ctx.get_column_ranges() is test_column_range assert ctx.get_offset_provider() is test_offset_provider raise RuntimeError("Inner exception") - assert ctx.get_closure_column_range() is initial_column_range + assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider raise RuntimeError("Outer exception") - assert ctx.get_closure_column_range(DEFAULT) is DEFAULT + assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT @@ -122,7 +116,7 @@ def test_within_valid_context(): assert not ctx.within_valid_context() test_column_range = "TEST_COLUMN_RANGE" - with ctx.update(closure_column_range=test_column_range): + with ctx.update(column_ranges=test_column_range): assert not ctx.within_valid_context() test_offset_provider = "TEST_OFFSET_PROVIDER" From 591b782ef74b65151760fffe2892072d7c248924 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 09:45:26 +0100 Subject: [PATCH 13/18] refactor[next]: hold the embedded column ranges as a tuple of named ranges, not a domain --- src/gt4py/next/embedded/context.py | 14 +++++++++----- src/gt4py/next/embedded/operators.py | 13 ++++++++----- src/gt4py/next/iterator/embedded.py | 6 ++---- .../unit_tests/embedded_tests/test_context.py | 14 ++++++++------ .../embedded_tests/test_nd_array_field.py | 2 +- .../test_nd_array_field_with_torch.py | 2 +- 6 files changed, 29 insertions(+), 22 deletions(-) diff --git a/src/gt4py/next/embedded/context.py b/src/gt4py/next/embedded/context.py index 8d7d97ce47..0e25af0067 100644 --- a/src/gt4py/next/embedded/context.py +++ b/src/gt4py/next/embedded/context.py @@ -18,7 +18,9 @@ import gt4py.next.errors.exceptions as exceptions -_column_ranges: contextvars.ContextVar[common.Domain] = contextvars.ContextVar("_column_ranges") +_column_ranges: contextvars.ContextVar[tuple[common.NamedRange, ...]] = contextvars.ContextVar( + "_column_ranges" +) _offset_provider: contextvars.ContextVar[common.OffsetProvider] = contextvars.ContextVar( "_offset_provider" ) @@ -31,14 +33,16 @@ @overload -def get_column_ranges() -> common.Domain: ... +def get_column_ranges() -> tuple[common.NamedRange, ...]: ... @overload -def get_column_ranges(default: _T) -> common.Domain | _T: ... +def get_column_ranges(default: _T) -> tuple[common.NamedRange, ...] | _T: ... -def get_column_ranges(default: _T = _NO_DEFAULT_SENTINEL) -> common.Domain | _T: +def get_column_ranges( + default: _T = _NO_DEFAULT_SENTINEL, +) -> tuple[common.NamedRange, ...] | _T: """Ranges of the column (scan) dimensions in the current embedded execution context.""" result = _column_ranges.get(default) if result is _NO_DEFAULT_SENTINEL: @@ -69,7 +73,7 @@ def get_offset_provider(default: _T = _NO_DEFAULT_SENTINEL) -> common.OffsetProv @contextlib.contextmanager def update( *, - column_ranges: common.Domain | eve.NothingType = eve.NOTHING, + column_ranges: tuple[common.NamedRange, ...] | eve.NothingType = eve.NOTHING, offset_provider: common.OffsetProvider | eve.NothingType = eve.NOTHING, ) -> Generator[None, None, None]: """Context handler updating the current embedded context with the provided values.""" diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 8b72c43910..2a8863f0b7 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -48,12 +48,13 @@ def __call__( # type: ignore[override] scan_axis = self.axis all_args = [*args, *kwargs.values()] domain_intersection = _intersect_scan_args(*all_args) - column_ranges = embedded_context.get_column_ranges() - if scan_axis not in column_ranges.dims: + scan_range = next( + (nr for nr in embedded_context.get_column_ranges() if nr.dim == scan_axis), None + ) + if scan_range is None: 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 @@ -153,14 +154,16 @@ def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) -> return op(*args, **kwargs) -def _get_vertical_ranges(domain: xtyping.MaybeNestedInTuple[common.Domain]) -> common.Domain: +def _get_vertical_ranges( + domain: xtyping.MaybeNestedInTuple[common.Domain], +) -> tuple[common.NamedRange, ...]: ranges: dict[common.Dimension, common.NamedRange] = {} ambiguous: set[common.Dimension] = set() for d in utils.flatten_nested_tuple((domain,)): for nr in d: if nr.dim.kind == common.DimensionKind.VERTICAL and ranges.setdefault(nr.dim, nr) != nr: ambiguous.add(nr.dim) - return common.Domain(*(nr for dim, nr in ranges.items() if dim not in ambiguous)) + return tuple(nr for dim, nr in ranges.items() if dim not in ambiguous) def _tuple_assign_field( diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 1765fd5121..1a84a488a8 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -1677,10 +1677,8 @@ def _extract_column_range( def _as_column_ranges( column_range: common.NamedRange | eve.NothingType, -) -> common.Domain | eve.NothingType: - return ( - common.Domain(column_range) if isinstance(column_range, common.NamedRange) else eve.NOTHING - ) +) -> tuple[common.NamedRange] | eve.NothingType: + return (column_range,) if isinstance(column_range, common.NamedRange) else eve.NOTHING def _get_column_range() -> common.NamedRange: diff --git a/tests/next_tests/unit_tests/embedded_tests/test_context.py b/tests/next_tests/unit_tests/embedded_tests/test_context.py index c215a3ef52..36fe0d0c71 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_context.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_context.py @@ -30,14 +30,16 @@ def test_update_with_both_parameters(): assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT - initial_column_range = common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)) + initial_column_range = (common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)),) initial_offset_provider = {} with ctx.update(column_ranges=initial_column_range, offset_provider=initial_offset_provider): assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider - test_column_range = common.NamedRange(common.Dimension("NewDim"), common.UnitRange(-1, 1)) + test_column_range = ( + common.NamedRange(common.Dimension("NewDim"), common.UnitRange(-1, 1)), + ) test_offset_provider = {"I": "NewDim"} with ctx.update(column_ranges=test_column_range, offset_provider=test_offset_provider): @@ -56,7 +58,7 @@ def test_update_with_no_parameters(): assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT - initial_column_range = common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)) + initial_column_range = (common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)),) initial_offset_provider = {} with ctx.update(column_ranges=initial_column_range, offset_provider=initial_offset_provider): @@ -79,7 +81,7 @@ def test_update_with_exception(): assert ctx.get_column_ranges(DEFAULT) is DEFAULT assert ctx.get_offset_provider(DEFAULT) is DEFAULT - initial_column_range = common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)) + initial_column_range = (common.NamedRange(common.Dimension("IDim"), common.UnitRange(0, 4)),) initial_offset_provider = {} with pytest.raises(RuntimeError, match="Outer exception"): @@ -89,8 +91,8 @@ def test_update_with_exception(): assert ctx.get_column_ranges() is initial_column_range assert ctx.get_offset_provider() is initial_offset_provider - test_column_range = common.NamedRange( - common.Dimension("NewDim"), common.UnitRange(-1, 1) + test_column_range = ( + common.NamedRange(common.Dimension("NewDim"), common.UnitRange(-1, 1)), ) test_offset_provider = {"I": "NewDim"} diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py index 5883fe254d..a851bd1d55 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field.py @@ -2732,7 +2732,7 @@ def _scan_cumsum(x, k_dim): scan = operators.ScanOperator(lambda state, v: state + v, forward=True, init=0.0, axis=k_dim) with embedded_context.update( - column_ranges=common.Domain(NamedRange(k_dim, UnitRange(0, 4))), offset_provider={} + column_ranges=(NamedRange(k_dim, UnitRange(0, 4)),), offset_provider={} ): return scan(x) diff --git a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py index 6344be0bb4..c8bf0d0211 100644 --- a/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py +++ b/tests/next_tests/unit_tests/embedded_tests/test_nd_array_field_with_torch.py @@ -122,7 +122,7 @@ def test_torch_scan_result_on_device_of_inputs(device): ) with embedded_context.update( - column_ranges=common.Domain(NamedRange(K, UnitRange(0, 4))), offset_provider={} + column_ranges=(NamedRange(K, UnitRange(0, 4)),), offset_provider={} ): result = scan(x) From c8215e52d128233098e2d857df9f4d5fffa474e2 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 10:14:19 +0100 Subject: [PATCH 14/18] ci: 12 xdist workers for the internal cuda13 CSCS jobs --- .cscs-ci/default.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.cscs-ci/default.yml b/.cscs-ci/default.yml index 6145017c92..c40d9fefb4 100644 --- a/.cscs-ci/default.yml +++ b/.cscs-ci/default.yml @@ -105,8 +105,8 @@ test_cscs_gh200: SLURM_TIMELIMIT: "00:15:00" - if: $SUBPACKAGE == 'next' && $VARIANT == 'internal' && $SUBVARIANT == 'cuda13' variables: - # 32 workers run the node out of host memory - PYTEST_XDIST_AUTO_NUM_WORKERS: 16 + # 16 or more workers run the node out of host memory + PYTEST_XDIST_AUTO_NUM_WORKERS: 12 SLURM_TIMELIMIT: "00:15:00" - if: $SUBPACKAGE == 'next' && $VARIANT == 'internal' && $DETAIL == 'nomesh' variables: From 026b7377eb03876c44487555503666eda836cfcd Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 10:38:31 +0100 Subject: [PATCH 15/18] test[next]: drop column_axis from tests merged in from main --- .../codegens_tests/gtfn_tests/test_gtfn_module.py | 1 - .../runners_tests/dace_tests/test_dace_translation.py | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py index b2afc60e7d..4c761ec4b7 100644 --- a/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py +++ b/tests/next_tests/unit_tests/program_processor_tests/codegens_tests/gtfn_tests/test_gtfn_module.py @@ -107,7 +107,6 @@ def _make_compilable_program( args=tuple(param.type for param in program.params), kwargs={}, offset_provider=offset_provider, - column_axis=None, argument_descriptor_contexts={}, ), ) 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 541885d3c3..078a5a2620 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 @@ -192,7 +192,6 @@ def test_translation_grid_type(grid_type): args=tuple(param.type for param in ir.params), kwargs={}, offset_provider=offset_provider, - column_axis=None, argument_descriptor_contexts={}, ), ) @@ -255,7 +254,7 @@ def test_find_constant_symbols_tuple_args(has_unit_stride, disable_field_origin) unstructured_horizontal_has_unit_stride=has_unit_stride, use_metrics=False, disable_field_origin_on_program_arguments=disable_field_origin, - ).generate_sdfg(ir, offset_provider={}, column_axis=None) + ).generate_sdfg(ir, offset_provider={}) constant_symbols = dace_wf_translation.find_constant_symbols( ir=ir, From 59e116159efb08806ead79a4a5f7326e158dd567 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 13:33:16 +0100 Subject: [PATCH 16/18] refactor[next]: address review on call-site scan Keep _register_builtin private, make _check_scan_args a plain check, split the forward and init literal checks, and add TODOs. --- src/gt4py/next/embedded/nd_array_field.py | 30 ++++++++--------- src/gt4py/next/embedded/operators.py | 5 ++- .../ffront/foast_passes/type_deduction.py | 33 +++++++++++-------- 3 files changed, 37 insertions(+), 31 deletions(-) diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 696944a4e3..c71c469758 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -800,7 +800,7 @@ def _inverse_image_box( _builtin_implementations: dict[fbuiltins.BuiltInFunction, Callable[..., Any]] = {} -def register_builtin(builtin: fbuiltins.BuiltInFunction, impl: Callable[..., Any]) -> None: +def _register_builtin(builtin: fbuiltins.BuiltInFunction, impl: Callable[..., Any]) -> None: """Register `impl` for `builtin`, unless the `ArrayOps` of the first field argument replaces it.""" def dispatch(*args: Any, **kwargs: Any) -> Any: @@ -813,11 +813,11 @@ def dispatch(*args: Any, **kwargs: Any) -> Any: _builtin_implementations[builtin] = dispatch -register_builtin( +_register_builtin( fbuiltins.abs, NdArrayField.__abs__, ) -register_builtin( +_register_builtin( fbuiltins.power, NdArrayField.__pow__, ) @@ -829,21 +829,21 @@ def dispatch(*args: Any, **kwargs: Any) -> Any: ): if name in ["abs", "power"]: continue - register_builtin(getattr(fbuiltins, name), _make_builtin(name, name)) + _register_builtin(getattr(fbuiltins, name), _make_builtin(name, name)) -register_builtin( +_register_builtin( fbuiltins.minimum, _make_builtin("minimum", "minimum"), ) -register_builtin( +_register_builtin( fbuiltins.maximum, _make_builtin("maximum", "maximum"), ) -register_builtin( +_register_builtin( fbuiltins.fmod, _make_builtin("fmod", "fmod"), ) -register_builtin(fbuiltins.where, _make_builtin("where", "where")) +_register_builtin(fbuiltins.where, _make_builtin("where", "where")) def _to_field(value: common.Field | core_defs.Scalar, like: NdArrayField) -> common.Field: @@ -986,7 +986,7 @@ def _concat_where( return _concat(*f_slices, *t_slices, dim=domain_dim) -register_builtin(experimental.concat_where, _concat_where) +_register_builtin(experimental.concat_where, _concat_where) def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> common.Connectivity: @@ -1010,7 +1010,7 @@ def _as_offset(offset: fbuiltins.FieldOffset, offset_field: NdArrayField) -> com ) -register_builtin(experimental.as_offset, _as_offset) +_register_builtin(experimental.as_offset, _as_offset) def _make_reduction( @@ -1088,7 +1088,7 @@ def _builtin_op( return _builtin_op -register_builtin( +_register_builtin( fbuiltins.neighbor_sum, _make_reduction( "neighbor_sum", @@ -1097,7 +1097,7 @@ def _builtin_op( lambda x: x.dtype.scalar_type(0), ), ) -register_builtin( +_register_builtin( fbuiltins.max_over, _make_reduction( "max_over", @@ -1105,7 +1105,7 @@ def _builtin_op( lambda x: array_ops.of(x._ndarray).xp.min(x._ndarray), ), ) -register_builtin( +_register_builtin( fbuiltins.min_over, _make_reduction( "min_over", @@ -1172,7 +1172,7 @@ def _builtins_broadcast( raise AssertionError("Scalar case not reachable from 'fbuiltins.broadcast'.") -register_builtin(fbuiltins.broadcast, _builtins_broadcast) +_register_builtin(fbuiltins.broadcast, _builtins_broadcast) def _astype(field: common.Field | core_defs.ScalarT | tuple, type_: type) -> NdArrayField: @@ -1184,7 +1184,7 @@ def _astype(field: common.Field | core_defs.ScalarT | tuple, type_: type) -> NdA raise AssertionError("This is the NdArrayField implementation of 'fbuiltins.astype'.") -register_builtin(fbuiltins.astype, _astype) # type: ignore[arg-type] # because fbuiltins.astype is overloaded +_register_builtin(fbuiltins.astype, _astype) # type: ignore[arg-type] # because fbuiltins.astype is overloaded def _get_slices_from_domain_slice( diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index f7b3259239..0234dbf24d 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -242,6 +242,5 @@ def _scan( return ScanOperator(scan_pass, forward, init, axis)(*args, **kwargs) -# Registered here, not in `nd_array_field` like the other builtins: `nd_array_field` cannot -# import this module, which depends on it through `field_utils`. -nd_array_field.register_builtin(fbuiltins.scan, _scan) +# TODO(havogt): Registration is here to avoid a circular import. Consider refactoring the structure of embedded builtins registration in nd_array_field. +nd_array_field._register_builtin(fbuiltins.scan, _scan) diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index 6abb38ae3e..acfe53c0a6 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -175,8 +175,8 @@ def _check_scan_args( axis: foast.Expr, forward: Optional[foast.Expr], init: Optional[foast.Expr], -) -> Dimension: - """Check the arguments of a scan operator and return its axis. An absent `forward` or `init` is checked by its default.""" +) -> None: + """Check the arguments of a scan operator. An absent `forward` or `init` 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." @@ -186,12 +186,17 @@ def _check_scan_args( axis.location, f"Argument 'axis' to scan operator '{name}' must be a vertical dimension.", ) - for arg_name, arg in (("forward", forward), ("init", init)): - if arg is not None and not foast_utils.is_literal(arg): - raise errors.DSLError( - arg.location, - f"Argument '{arg_name}' to scan operator '{name}' must be a compile-time constant.", - ) + if forward is not None and not foast_utils.is_literal(forward): + raise errors.DSLError( + forward.location, + f"Argument 'forward' to scan operator '{name}' must be a compile-time constant.", + ) + # TODO(havogt): We will relax init to be run-time in a follow-up commit. + if init is not None and not foast_utils.is_literal(init): + raise errors.DSLError( + init.location, + f"Argument 'init' to scan operator '{name}' must be a compile-time constant.", + ) forward_type = ( forward.type if forward is not None @@ -242,7 +247,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 class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTranslator): @@ -325,7 +329,7 @@ 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( + _check_scan_args( node.location, node.id, new_definition.type, @@ -334,7 +338,9 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S init=new_init, ) - new_type = ts_ffront.ScanOperatorType(axis=axis, definition=new_definition.type) + new_type = ts_ffront.ScanOperatorType( + axis=new_axis.type.dim, definition=new_definition.type + ) return foast.ScanOperator( id=node.id, axis=new_axis, @@ -369,7 +375,7 @@ def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> foast.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( + _check_scan_args( node.location, str(new_pass), pass_type, @@ -383,7 +389,7 @@ def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> foast.Call: args=[new_pass], kwargs=new_kwargs, location=node.location, - type=ts_ffront.ScanOperatorType(axis=axis, definition=pass_type), + type=ts_ffront.ScanOperatorType(axis=new_kwargs["axis"].type.dim, definition=pass_type), ) def visit_Name(self, node: foast.Name, **kwargs: Any) -> foast.Name: @@ -846,6 +852,7 @@ def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> foast.TupleEx return foast.TupleExpr(elts=new_elts, type=new_type, location=node.location) def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: + # TODO(havogt): This limitation will be removed with general higher-order function support. if _is_scan_builtin(node.func): raise errors.DSLError( node.location, From 3f8fa6c2fc71801385055edc4726a873f61c360c Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 17:40:45 +0100 Subject: [PATCH 17/18] fix[next]: address independent review of call-site scan - is_literal also checks keyword arguments of constructor calls - check the scan call against the signature of 'scan' instead of restating it - split the forward and init lowering - test the forward literal check, keyword arguments, named-collection carry, input without the scan axis, error paths and the GTIR lowering - explicit init in tests that are not about its default --- src/gt4py/next/ffront/fbuiltins.py | 9 +-- .../ffront/foast_passes/type_deduction.py | 17 ++--- src/gt4py/next/ffront/foast_passes/utils.py | 2 +- src/gt4py/next/ffront/foast_to_gtir.py | 31 ++++---- .../ffront_tests/test_named_collections.py | 18 ++++- .../feature_tests/ffront_tests/test_scan.py | 39 ++++++++++ .../ffront_tests/test_foast_to_gtir.py | 48 ++++++++++++ .../ffront_tests/test_type_deduction.py | 73 +++++++++++++++++-- 8 files changed, 197 insertions(+), 40 deletions(-) diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 851cc65b0e..fb9e307f75 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -293,14 +293,11 @@ def broadcast( class ScanBuiltinFunction(BuiltInFunction[_R, _P]): def __gt_type__(self) -> ts.FunctionType: + # The arguments are checked against the signature of `scan` in type deduction. return ts.FunctionType( - pos_only_args=[ts.DeferredType(constraint=None)], + pos_only_args=[], pos_or_kw_args={}, - kw_only_args={ - "axis": ts.DeferredType(constraint=ts.DimensionType), - "forward": ts.DeferredType(constraint=ts.ScalarType), - "init": ts.DeferredType(constraint=(ts.ScalarType, ts.TupleType)), - }, + kw_only_args={}, returns=ts.DeferredType(constraint=None), ) diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index acfe53c0a6..5692998fa2 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -6,6 +6,7 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import inspect import textwrap from typing import Any, Optional, Sequence, TypeAlias, TypeVar, cast @@ -354,18 +355,10 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> foast.Call: """Type `scan(pass, axis=..., 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"}: - raise errors.DSLError( - node.location, - f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.", - ) - if "axis" not in node.kwargs: - raise errors.DSLError(node.location, "Missing argument 'axis' to 'scan'.") + try: + inspect.signature(fbuiltins.scan.function).bind(*node.args, **node.kwargs) + except TypeError as err: + raise errors.DSLError(node.location, f"Invalid arguments to 'scan': {err}.") from err new_pass = self.visit(node.args[0], **kwargs) if not isinstance(new_pass.type, ts_ffront.FieldOperatorType): raise errors.DSLError( diff --git a/src/gt4py/next/ffront/foast_passes/utils.py b/src/gt4py/next/ffront/foast_passes/utils.py index 808ca6fc69..b3afad3c5a 100644 --- a/src/gt4py/next/ffront/foast_passes/utils.py +++ b/src/gt4py/next/ffront/foast_passes/utils.py @@ -93,5 +93,5 @@ def is_literal(expr: foast.Expr) -> bool: case foast.UnaryOp(): return is_literal(expr.operand) case foast.Call(func=foast.Name(type=ts.ConstructorType())): - return all(is_literal(arg) for arg in expr.args) + return all(is_literal(arg) for arg in (*expr.args, *expr.kwargs.values())) return False diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index f54dae468d..99e02494a3 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -409,23 +409,26 @@ 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 assert isinstance(node.type, ts_ffront.ScanOperatorType) - forward, init = ( - self.visit(node.kwargs[name], **kwargs) - if name in node.kwargs - else im.literal_from_value(fbuiltins.SCAN_DEFAULTS[name]) - for name in ("forward", "init") + forward = ( + self.visit(node.kwargs["forward"], **kwargs) + if "forward" in node.kwargs + else im.literal_from_value(fbuiltins.SCAN_DEFAULTS["forward"]) + ) + init = ( + self.visit(node.kwargs["init"], **kwargs) + if "init" in node.kwargs + else im.literal_from_value(fbuiltins.SCAN_DEFAULTS["init"]) ) param_names = list(node.type.definition.pos_or_kw_args) - return im.lambda_(*param_names[1:])( - _lower_scan( - self.visit(node.args[0], **kwargs), - param_names, - forward, - init, - node.type.axis, - [im.ref(param) for param in param_names[1:]], - ) + body = _lower_scan( + self.visit(node.args[0], **kwargs), + param_names, + forward, + init, + node.type.axis, + [im.ref(param) for param in param_names[1:]], ) + return 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/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index 77b793f93b..f3f433ebd6 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -13,7 +13,7 @@ from typing import NamedTuple import gt4py.next as gtx -from gt4py.next import common, neighbor_sum +from gt4py.next import common, neighbor_sum, scan from gt4py.next.ffront import decorator from gt4py.next.ffront.fbuiltins import where from gt4py.next.ffront.experimental import concat_where @@ -338,9 +338,23 @@ def scan_named_tuple_wrapper(inp: gtx.Field[[KDim], gtx.float32]) -> gtx.Field[[ return scan_named_tuple(inp).value +@gtx.field_operator +def _add_to_state_dataclass(state: StateDataclass, inp: gtx.float32) -> StateDataclass: + return StateDataclass(value=inp + state.value) + + +@gtx.field_operator +def scan_call_dataclass_wrapper( + inp: gtx.Field[[KDim], gtx.float32], +) -> gtx.Field[[KDim], gtx.float32]: + return scan( + _add_to_state_dataclass, axis=cases.KDim, init=StateDataclass(value=gtx.float32(0.0)) + )(inp).value + + @pytest.mark.parametrize( "testee", - [scan_named_tuple_wrapper, scan_dataclass_wrapper], + [scan_named_tuple_wrapper, scan_dataclass_wrapper, scan_call_dataclass_wrapper], ) @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator 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 dd3df13d8c..7d51c83bb7 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 @@ -612,6 +612,45 @@ def testee(inp: cases.IKFloatField, scalar: float) -> cases.IKFloatField: cases.verify(cartesian_case, testee, inp, 2.0, out=out, ref=backward_cumsum - 1.0 + inp_np) +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_call_keyword_args(cartesian_case): + @gtx.field_operator + def add(carry: float, inp: float, scalar: float) -> float: + return carry + inp * scalar + + @gtx.field_operator + def testee(inp: cases.IKFloatField, scalar: float) -> cases.IKFloatField: + return scan(add, axis=KDim, init=0.0)(scalar=scalar, inp=inp) + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + + cases.verify( + cartesian_case, testee, inp, 2.0, out=out, ref=np.cumsum(2.0 * inp.asnumpy(), axis=1) + ) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_call_over_axis_not_in_inputs_combined_with_field(cartesian_case): + @gtx.field_operator + def add(carry: float, inp: float) -> float: + return carry + inp + + @gtx.field_operator + def testee(a: cases.IFloatField, b: cases.IKFloatField) -> cases.IKFloatField: + return scan(add, axis=KDim, init=0.0)(a) + b + + ksize = cartesian_case.default_sizes[KDim] + + cases.verify_with_default_data( + cartesian_case, + testee, + ref=lambda a, b: a[:, np.newaxis] * np.arange(1, ksize + 1) + b, + ) + + @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator @pytest.mark.uses_tuple_args diff --git a/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py b/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py index eb1927a776..5f33fea258 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py @@ -29,6 +29,8 @@ max_over, min_over, neighbor_sum, + scan, + scan_operator, where, ) from gt4py.next.ffront import type_specifications as ts_ffront @@ -55,6 +57,7 @@ RenamedV2EDim = gtx.Dimension("RenamedLocal", gtx.DimensionKind.LOCAL) renamed_v2e = gtx.FieldOffset("RenamedTag", source=Edge, target=(Vertex, RenamedV2EDim)) UDim = gtx.Dimension("UDim") +KDim = gtx.Dimension("KDim", kind=gtx.DimensionKind.VERTICAL) def test_return(): @@ -1002,3 +1005,48 @@ def foo(inp: DataclassNamedCollection) -> DataclassNamedCollection: lowered = FieldOperatorLowering.apply(parsed) # assert False # TODO + + +@gtx.field_operator +def _scan_pass(carry: float64, inp: float64, scalar: float64) -> float64: + return carry + inp * scalar + + +def _scan_definition(scan_pass: itir.Expr) -> itir.Lambda: + return im.lambda_("carry", "inp", "scalar")( + im.call(scan_pass)("carry", im.deref("inp"), im.deref("scalar")) + ) + + +def test_scan_call(): + def foo(a: gtx.Field[[TDim, KDim], float64], s: float64) -> gtx.Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=KDim, forward=False, init=1.0)(a, s) + + parsed = FieldOperatorParser.apply_to_function(foo) + lowered = FieldOperatorLowering.apply(parsed) + + scan_op = im.lambda_("inp", "scalar")( + im.as_fieldop( + im.scan(_scan_definition("_scan_pass"), False, im.literal_from_value(1.0), KDim) + )("inp", "scalar") + ) + reference = im.call(scan_op)("a", "s") + + assert lowered.expr == reference + + +def test_scan_operator(): + @scan_operator(axis=KDim, forward=False, init=1.0) + def foo(carry: float64, inp: float64, scalar: float64) -> float64: + return carry + inp * scalar + + lowered = FieldOperatorLowering.apply(foo.foast_stage.foast_node) + + scan_pass = im.lambda_("carry", "inp", "scalar")( + im.plus("carry", im.multiplies_("inp", "scalar")) + ) + reference = im.as_fieldop( + im.scan(_scan_definition(scan_pass), False, im.literal_from_value(1.0), KDim) + )("inp", "scalar") + + assert lowered.expr == reference 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 5c872937d9..64ded5930d 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 @@ -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) + op = scan(_scan_pass, axis=KDim, init=0.0) return a with pytest.raises( @@ -843,15 +843,31 @@ def scan_not_called(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], floa def test_scan_call_missing_axis(): def missing_axis(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: - return scan(_scan_pass)(a) + return scan(_scan_pass, init=0.0)(a) - with pytest.raises(errors.DSLError, match=r"Missing argument 'axis' to 'scan'"): + with pytest.raises(errors.DSLError, match=r"missing a required .*argument: 'axis'"): _ = FieldOperatorParser.apply_to_function(missing_axis) +def test_scan_call_axis_positional(): + def axis_positional(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, KDim, init=0.0)(a) + + with pytest.raises(errors.DSLError, match=r"Invalid arguments to 'scan': too many positional"): + _ = FieldOperatorParser.apply_to_function(axis_positional) + + +def test_scan_call_unexpected_kwarg(): + def unexpected_kwarg(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=KDim, init=0.0, backward=True)(a) + + with pytest.raises(errors.DSLError, match=r"unexpected keyword argument 'backward'"): + _ = FieldOperatorParser.apply_to_function(unexpected_kwarg) + + 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)(a) + return scan(_scan_pass, axis=TDim, init=0.0)(a) with pytest.raises( errors.DSLError, match=r"'axis' to scan operator '_scan_pass' must be a vertical dimension" @@ -859,6 +875,19 @@ def non_vertical_axis(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], fl _ = FieldOperatorParser.apply_to_function(non_vertical_axis) +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) + + with pytest.raises( + errors.DSLError, + match=r"'forward' to scan operator '_scan_pass' must be a compile-time constant", + ): + _ = FieldOperatorParser.apply_to_function(non_constant_forward) + + def test_scan_call_non_constant_init(): def non_constant_init( a: Field[[TDim, KDim], float64], init: float64 @@ -872,6 +901,40 @@ def non_constant_init( _ = FieldOperatorParser.apply_to_function(non_constant_init) +@dataclasses.dataclass +class _State: + value: float64 + + +@field_operator +def _scan_pass_state(carry: _State, inp: float) -> _State: + return _State(value=carry.value + inp) + + +def test_scan_call_named_collection_init(): + def named_collection_init(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass_state, axis=KDim, init=_State(value=0.0))(a).value + + parsed = FieldOperatorParser.apply_to_function(named_collection_init) + + assert parsed.type.returns == ts.FieldType( + dims=[TDim, KDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) + ) + + +def test_scan_call_non_constant_named_collection_init(): + def non_constant_named_collection_init( + a: Field[[TDim, KDim], float64], init: float64 + ) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass_state, axis=KDim, init=_State(value=init))(a).value + + with pytest.raises( + errors.DSLError, + match=r"'init' to scan operator '_scan_pass_state' must be a compile-time constant", + ): + _ = FieldOperatorParser.apply_to_function(non_constant_named_collection_init) + + 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) @@ -882,7 +945,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)(a) + return scan(where, axis=KDim, 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) From 440afcaaa6a09ed97d63d9700f07b1e94bbcb6b2 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 17:55:01 +0100 Subject: [PATCH 18/18] test[next]: use a bare type constructor in the named-collection scan call test --- .../feature_tests/ffront_tests/test_named_collections.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index f3f433ebd6..664efccc39 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -13,7 +13,7 @@ from typing import NamedTuple import gt4py.next as gtx -from gt4py.next import common, neighbor_sum, scan +from gt4py.next import common, float32, neighbor_sum, scan from gt4py.next.ffront import decorator from gt4py.next.ffront.fbuiltins import where from gt4py.next.ffront.experimental import concat_where @@ -347,9 +347,9 @@ def _add_to_state_dataclass(state: StateDataclass, inp: gtx.float32) -> StateDat def scan_call_dataclass_wrapper( inp: gtx.Field[[KDim], gtx.float32], ) -> gtx.Field[[KDim], gtx.float32]: - return scan( - _add_to_state_dataclass, axis=cases.KDim, init=StateDataclass(value=gtx.float32(0.0)) - )(inp).value + return scan(_add_to_state_dataclass, axis=cases.KDim, init=StateDataclass(value=float32(0.0)))( + inp + ).value @pytest.mark.parametrize(