Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions src/gt4py/next/embedded/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# SPDX-License-Identifier: BSD-3-Clause

import dataclasses
from typing import Any, Callable, Generic, Optional, ParamSpec, Sequence, TypeVar
from typing import Any, Callable, Generic, Optional, ParamSpec, Sequence, TypeVar, cast

from typing_extensions import TypeIs

Expand All @@ -22,7 +22,7 @@
)
from gt4py.next.ffront import fbuiltins
from gt4py.next.otf import arguments
from gt4py.next.type_system import type_specifications as ts, type_translation
from gt4py.next.type_system import type_info, type_specifications as ts, type_translation


_P = ParamSpec("_P")
Expand All @@ -40,7 +40,7 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
@dataclasses.dataclass(frozen=True)
class ScanOperator(EmbeddedOperator[xtyping.MaybeNestedInTuple[core_defs.ScalarT], _P]):
forward: bool
init: xtyping.MaybeNestedInTuple[core_defs.ScalarT]
init: xtyping.MaybeNestedInTuple[core_defs.ScalarT | common.Field]
axis: common.Dimension

def __call__( # type: ignore[override]
Expand All @@ -53,7 +53,7 @@ def __call__( # type: ignore[override]
):
scan_axis = self.axis
all_args = [*args, *kwargs.values()]
domain_intersection = _intersect_scan_args(*all_args)
domain_intersection = _intersect_scan_args(*all_args, self.init)
column_ranges = embedded_context.get_column_ranges()
if scan_axis not in column_ranges.dims:
raise errors.exceptions.EmbeddedExecutionError(
Expand All @@ -73,16 +73,20 @@ def __call__( # type: ignore[override]
# even if the scan dimension is not in the input, we can scan over it
out_domain = common.Domain(*out_domain, (scan_range))

init_type = type_translation.from_value(self.init)
init_type = type_info.tree_map_type(
lambda t: t.dtype if isinstance(t, ts.FieldType) else t
)(type_translation.from_value(self.init))
assert isinstance(init_type, ts.TupleType | ts.ScalarType | ts.NamedCollectionType)
res = field_utils.field_from_typespec(
init_type,
out_domain,
like=field_utils.first_buffer(*(arguments.extract(arg) for arg in all_args)),
like=field_utils.first_buffer(
*(arguments.extract(arg) for arg in (*all_args, self.init))
),
)

def scan_loop(hpos: Sequence[common.NamedIndex]) -> None:
acc: xtyping.MaybeNestedInTuple[core_defs.ScalarT] = self.init
acc = cast(xtyping.MaybeNestedInTuple[core_defs.ScalarT], _tuple_at(hpos, self.init))
for k in scan_range.unit_range if self.forward else reversed(scan_range.unit_range):
pos = (*hpos, common.NamedIndex(scan_axis, k))
new_args = [_tuple_at(pos, arg) for arg in args]
Expand Down Expand Up @@ -220,7 +224,11 @@ def _tuple_at(
) -> array_ops.NDValue | tuple[array_ops.NDValue | tuple, ...]:
@named_collections.tree_map_named_collection
def impl(field: common.Field | array_ops.NDValue) -> array_ops.NDValue:
res = field[pos].as_scalar() if isinstance(field, common.Field) else field
res = (
field[tuple(p for p in pos if p.dim in field.domain.dims)].as_scalar()
if isinstance(field, common.Field)
else field
)
assert array_ops.is_scalar_like(res)
return res

Expand Down
6 changes: 4 additions & 2 deletions src/gt4py/next/ffront/fbuiltins.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ def scan(
*,
axis: common.Dimension,
forward: bool = True,
init: core_defs.Scalar | Tuple = 0.0,
init: core_defs.Scalar | common.Field | Tuple,
) -> Callable[..., common.Field | Tuple]:
"""
Create a scan operator from a scan pass, to be called inside a field operator.
Expand All @@ -335,7 +335,9 @@ def scan(
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.
init: Initial value of the carry: a constant, a scalar, or a field without the scan
dimension holding the initial value of each column. For tuple carries, each
element may be any of these; fields are not supported in named collections.

Examples:
>>> scan(my_pass, axis=KDim, forward=True, init=0.0)(a) # doctest: +SKIP
Expand Down
66 changes: 50 additions & 16 deletions src/gt4py/next/ffront/foast_passes/type_deduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,9 @@ def _check_scan_args(
*,
axis: foast.Expr,
forward: Optional[foast.Expr],
init: Optional[foast.Expr],
init: foast.Expr,
) -> Dimension:
"""Check the arguments of a scan operator and return its axis. An absent `forward` or `init` is checked by its default."""
"""Check the arguments of a scan operator and return its axis. An absent `forward` is checked by its default."""
if not isinstance(axis.type, ts.DimensionType):
raise errors.DSLError(
axis.location, f"Argument 'axis' to scan operator '{name}' must be a dimension."
Expand All @@ -186,21 +186,18 @@ 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.",
)
forward_type = (
forward.type
if forward is not None
else type_translation.from_value(fbuiltins.SCAN_DEFAULTS["forward"])
)
init_type = (
init_type = type_info.tree_map_type(lambda t: t.dtype if isinstance(t, ts.FieldType) else t)(
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(
Expand Down Expand Up @@ -245,6 +242,33 @@ def _check_scan_args(
return axis.type.dim


def _check_scan_column_init(
init: foast.Expr, axis: Dimension, scan_arg_types: list[ts.TypeSpec]
) -> None:
output_dims = promote_dims(
*(
type_info.extract_dims(el)
for arg_type in scan_arg_types
for el in type_info.primitive_constituents(arg_type)
),
[axis],
)
for init_leaf_type in type_info.primitive_constituents(init.type):
if not isinstance(init_leaf_type, ts.FieldType):
continue
if axis in init_leaf_type.dims:
raise errors.DSLError(
init.location,
f"Argument 'init' to 'scan' must not be a field over the scan dimension '{axis.value}'.",
)
if not set(init_leaf_type.dims) <= set(output_dims):
raise errors.DSLError(
init.location,
f"Dimensions of argument 'init' to 'scan' ({', '.join(d.value for d in init_leaf_type.dims)}) "
f"must be a subset of the dimensions of the result ({', '.join(d.value for d in output_dims)}).",
)


class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTranslator):
"""
Deduce and check types of FOAST expressions and symbols.
Expand Down Expand Up @@ -345,7 +369,9 @@ 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:
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:
Expand All @@ -358,8 +384,11 @@ def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> foast.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'.")
if missing := [name for name in ("axis", "init") if name not in node.kwargs]:
raise errors.DSLError(
node.location,
f"Missing argument(s) {', '.join(repr(name) for name in missing)} to 'scan'.",
)
new_pass = self.visit(node.args[0], **kwargs)
if not isinstance(new_pass.type, ts_ffront.FieldOperatorType):
raise errors.DSLError(
Expand All @@ -375,8 +404,9 @@ def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> foast.Call:
pass_type,
axis=new_kwargs["axis"],
forward=new_kwargs.get("forward"),
init=new_kwargs.get("init"),
init=new_kwargs["init"],
)
_check_scan_column_init(new_kwargs["init"], axis, scan_arg_types)

return foast.Call(
func=new_func,
Expand Down Expand Up @@ -855,7 +885,11 @@ 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, **kwargs)
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)

Expand Down
78 changes: 65 additions & 13 deletions src/gt4py/next/ffront/foast_to_gtir.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,38 @@ def _lower_scan(
return im.as_fieldop(im.scan(definition, forward, init, axis))(*args)


def _lower_scan_with_runtime_init(
scan_pass: itir.Expr,
param_names: list[str],
forward: itir.Expr,
init: itir.Expr,
axis: common.Dimension,
args: list[itir.Expr],
carry_type: ts.TypeSpec,
uids: utils.IDGeneratorPool,
) -> itir.Expr:
# A stencil may not reference outer symbols, so a non-literal `init` cannot seed the scan.
# It is passed as an extra argument instead and read on the first level, marked by a flag
# in the carry: `carry = (is_initialized, state)`.
carry, *arg_params = param_names
init_param = next(uids["__scan_init"])
state = next(uids["__scan_state"])
definition = im.lambda_(carry, *arg_params, init_param)(
im.let(state, im.if_(im.tuple_get(0, carry), im.tuple_get(1, carry), im.deref(init_param)))(
im.make_tuple(
im.literal_from_value(True),
im.call(scan_pass)(state, *(im.deref(param) for param in arg_params)),
)
)
)
placeholder = type_info.tree_map_type(
lambda type_: im.literal_from_value(tt.as_dtype(type_).scalar_type(0)),
result_collection_constructor=lambda _, elems: im.make_tuple(*elems),
)(carry_type)
seed = im.make_tuple(im.literal_from_value(False), placeholder)
return im.tuple_get(1, im.as_fieldop(im.scan(definition, forward, seed, axis))(*args, init))


@dataclasses.dataclass
class FieldOperatorLowering(eve.PreserveLocationVisitor, eve.NodeTranslator):
"""
Expand Down Expand Up @@ -409,21 +441,41 @@ 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")
scan_pass = self.visit(node.args[0], **kwargs)
forward = (
self.visit(node.kwargs["forward"], **kwargs)
if "forward" in node.kwargs
else im.literal_from_value(fbuiltins.SCAN_DEFAULTS["forward"])
)
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:]],
args: list[itir.Expr] = [im.ref(param) for param in param_names[1:]]

init = node.kwargs["init"]
if foast_utils.is_literal(init):
return im.lambda_(*param_names[1:])(
_lower_scan(
scan_pass,
param_names,
forward,
self.visit(init, **kwargs),
node.type.axis,
args,
)
)

init_sym = next(self.uid_generator["__scan_init"])
return im.let(init_sym, self.visit(init, **kwargs))(
im.lambda_(*param_names[1:])(
_lower_scan_with_runtime_init(
scan_pass,
param_names,
forward,
im.ref(init_sym),
node.type.axis,
args,
node.type.definition.returns,
self.uid_generator,
)
)
)

Expand Down
Loading
Loading