diff --git a/src/gt4py/next/__init__.py b/src/gt4py/next/__init__.py index cfcb0bc831..5657965937 100644 --- a/src/gt4py/next/__init__.py +++ b/src/gt4py/next/__init__.py @@ -84,6 +84,7 @@ neg, neighbor_sum, power, + scan, sin, sinh, sqrt, @@ -190,6 +191,7 @@ "neg", "neighbor_sum", "power", + "scan", "sin", "sinh", "sqrt", diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 2be6dcd62a..c71c469758 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -37,7 +37,7 @@ 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) raise AssertionError("No 'NdArrayField' found in the arguments.") @@ -804,7 +804,9 @@ def _register_builtin(builtin: fbuiltins.BuiltInFunction, impl: Callable[..., An """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 diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index 2a8863f0b7..0234dbf24d 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -14,7 +14,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 @@ -222,3 +228,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: common.Dimension, + forward: bool, + init: core_defs.Scalar | tuple, + /, + *args: Any, + **kwargs: Any, +) -> common.Field | tuple: + return ScanOperator(scan_pass, forward, init, axis)(*args, **kwargs) + + +# 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/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index c67febaf0a..fb9e307f75 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 @@ -58,6 +58,7 @@ "where", "broadcast", "astype", + "scan", "abs", "neg", "sin", @@ -290,6 +291,62 @@ def broadcast( return field # type: ignore[return-value] # see comment above +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=[], + pos_or_kw_args={}, + kw_only_args={}, + 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( + scan_pass: Callable, + /, + *, + axis: common.Dimension, + 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. + 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 + """ + raise NotImplementedError() + + +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, @@ -430,6 +487,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..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 @@ -163,6 +164,92 @@ 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 _check_scan_args( + location: eve.SourceLocation, + name: str, + pass_type: ts.FunctionType, + *, + axis: foast.Expr, + forward: Optional[foast.Expr], + init: Optional[foast.Expr], +) -> 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." + ) + if axis.type.dim.kind != DimensionKind.VERTICAL: + raise errors.DSLError( + axis.location, + f"Argument 'axis' to scan operator '{name}' must be a vertical dimension.", + ) + 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 + 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." + ) + 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}'.", + ) + 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." + ) + + class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTranslator): """ Deduce and check types of FOAST expressions and symbols. @@ -240,53 +327,21 @@ 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) - 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) - ): - 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.", - ) new_definition = self.visit(node.definition, **kwargs) - new_def_type = new_definition.type - if not new_def_type.pos_or_kw_args: - raise errors.DSLError( - node.location, - f"Scan operator '{node.id}' must have at least one argument (the carry).", - ) - 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: - 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}'.", - ) - elif new_init.type != carry_type: - 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}'.", - ) + _check_scan_args( + node.location, + node.id, + new_definition.type, + axis=new_axis, + forward=new_forward, + init=new_init, + ) - new_type = ts_ffront.ScanOperatorType(axis=new_axis.type.dim, definition=new_def_type) + new_type = ts_ffront.ScanOperatorType( + axis=new_axis.type.dim, definition=new_definition.type + ) return foast.ScanOperator( id=node.id, axis=new_axis, @@ -297,6 +352,39 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S location=node.location, ) + 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) + 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( + new_pass.location, + f"The scan pass must be a field operator, got '{new_pass.type}'.", + ) + pass_type = new_pass.type.definition + + new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in node.kwargs.items()} + _check_scan_args( + node.location, + str(new_pass), + pass_type, + axis=new_kwargs["axis"], + forward=new_kwargs.get("forward"), + init=new_kwargs.get("init"), + ) + + return foast.Call( + func=new_func, + args=[new_pass], + kwargs=new_kwargs, + location=node.location, + type=ts_ffront.ScanOperatorType(axis=new_kwargs["axis"].type.dim, definition=pass_type), + ) + def visit_Name(self, node: foast.Name, **kwargs: Any) -> foast.Name: symtable = kwargs["symtable"] if node.id not in symtable or symtable[node.id].type is None: @@ -757,9 +845,19 @@ 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) + # TODO(havogt): This limitation will be removed with general higher-order function support. + 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, **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 +877,11 @@ 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 ( + # `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) ): raise errors.DSLError(node.location, "Functions can only be called directly.") elif isinstance(new_func.type, ts.FieldType): @@ -811,6 +914,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_passes/utils.py b/src/gt4py/next/ffront/foast_passes/utils.py index fa066e9d76..b3afad3c5a 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, *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 c453193eba..99e02494a3 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -65,6 +65,22 @@ 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, + axis: common.Dimension, + 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, axis))(*args) + + @dataclasses.dataclass class FieldOperatorLowering(eve.PreserveLocationVisitor, eve.NodeTranslator): """ @@ -132,19 +148,18 @@ 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, node.type.axis))(*stencil_args) + params = func_definition.params + body = _lower_scan( + itir.Lambda(params=params, expr=func_definition.expr), + [param.id for param in params], + forward, + init, + node.type.axis, + [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.") @@ -390,6 +405,31 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: f"Call to object of type '{type(node.func.type).__name__}' not understood." ) + def _visit_scan(self, node: foast.Call, **kwargs: Any) -> itir.Expr: + # `scan(scan_pass, axis=..., forward=..., init=...)`, lowered to a function of the + # scan pass's arguments + assert isinstance(node.type, ts_ffront.ScanOperatorType) + 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) + 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`), # not by e.g. its name. 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_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index 77b793f93b..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 +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 @@ -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=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 8e46e93fd1..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 @@ -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.experimental import concat_where from gt4py.next.ffront.decorator import program, scan_operator @@ -574,3 +574,128 @@ 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(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, 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 +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 +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 +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_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 b6ae674312..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 @@ -26,7 +26,10 @@ float64, int32, int64, + field_operator, neighbor_sum, + scan, + scan_operator, where, ) from gt4py.next.ffront.experimental import concat_where @@ -798,3 +801,151 @@ 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, axis=KDim, 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_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, init=0.0) + 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_missing_axis(): + def missing_axis(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, init=0.0)(a) + + with pytest.raises(errors.DSLError, match=r"missing 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, init=0.0)(a) + + 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) + + +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 + ) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=KDim, init=init)(a) + + 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) + + +@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) + + 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, 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)