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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ markers = [
'uses_scan: tests that uses scan',
'uses_scan_in_field_operator: tests that require backend support for scan in field operator',
'uses_scan_without_field_args: tests that require calls to scan that do not have any fields as arguments',
'uses_scan_with_unstructured_shift: tests that combine a scan with an unstructured shift',
'uses_scan_nested: tests that use nested scans',
'uses_sparse_fields: tests that require backend support for sparse fields',
'uses_sparse_fields_as_output: tests that require backend support for writing sparse fields',
Expand Down
39 changes: 20 additions & 19 deletions src/gt4py/next/embedded/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class ScanOperator(EmbeddedOperator[xtyping.MaybeNestedInTuple[core_defs.ScalarT
forward: bool
init: xtyping.MaybeNestedInTuple[core_defs.ScalarT | common.Field]
axis: common.Dimension
range: Optional[common.UnitRange] = None

def __call__( # type: ignore[override]
self,
Expand All @@ -54,16 +55,19 @@ def __call__( # type: ignore[override]
scan_axis = self.axis
all_args = [*args, *kwargs.values()]
domain_intersection = _intersect_scan_args(*all_args, self.init)
column_ranges = embedded_context.get_column_ranges()
if scan_axis not in column_ranges.dims:
raise errors.exceptions.EmbeddedExecutionError(
f"Scan axis '{scan_axis}' has no range, or ranges that differ, in the output domain."
)
scan_range = column_ranges[scan_axis]
if scan_axis in domain_intersection.dims:
scan_range = common.NamedRange(
scan_axis, scan_range.unit_range & domain_intersection[scan_axis].unit_range
)
if self.range is not None:
scan_range = common.NamedRange(scan_axis, self.range)
else:
column_ranges = embedded_context.get_column_ranges()
if scan_axis not in column_ranges.dims:
raise errors.exceptions.EmbeddedExecutionError(
f"Scan axis '{scan_axis}' has no range, or ranges that differ, in the output domain."
)
scan_range = column_ranges[scan_axis]
if scan_axis in domain_intersection.dims:
scan_range = common.NamedRange(
scan_axis, scan_range.unit_range & domain_intersection[scan_axis].unit_range
)
non_scan_domain = common.Domain(*[nr for nr in domain_intersection if nr.dim != scan_axis])

out_domain = common.Domain(
Expand Down Expand Up @@ -109,12 +113,6 @@ def scan_loop(hpos: Sequence[common.NamedIndex]) -> None:
return res


def _get_out_domain(out: xtyping.MaybeNestedInTuple[common.MutableField]) -> common.Domain:
return embedded_common.domain_intersection(
*[f.domain for f in utils.flatten_nested_tuple((out,))]
)


def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) -> Optional[_R]:
if "out" in kwargs:
# called from program or direct field_operator as program
Expand Down Expand Up @@ -145,7 +143,7 @@ def field_operator_call(op: EmbeddedOperator[_R, _P], args: Any, kwargs: Any) ->
out_domain = (
utils.tree_map(common.domain)(domain)
if domain is not None
else _get_out_domain(container_extracted_out)
else utils.tree_map(lambda f: f.domain)(container_extracted_out)
)

new_context_kwargs["column_ranges"] = _get_vertical_ranges(out_domain)
Expand Down Expand Up @@ -237,14 +235,17 @@ def impl(field: common.Field | array_ops.NDValue) -> array_ops.NDValue:

def _scan(
scan_pass: Callable,
axis: common.Dimension,
range: tuple[common.Dimension, int, int], # noqa: A002 # shadowing a Python built-in
forward: bool,
init: core_defs.Scalar | tuple,
/,
*args: Any,
**kwargs: Any,
) -> common.Field | tuple:
return ScanOperator(scan_pass, forward, init, axis)(*args, **kwargs)
axis, start, stop = range
return ScanOperator(scan_pass, forward, init, axis, common.UnitRange(start, stop))(
*args, **kwargs
)


# Registered here, not in `nd_array_field` like the other builtins: `nd_array_field` cannot
Expand Down
10 changes: 6 additions & 4 deletions src/gt4py/next/ffront/fbuiltins.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ def __gt_type__(self) -> ts.FunctionType:
pos_only_args=[ts.DeferredType(constraint=None)],
pos_or_kw_args={},
kw_only_args={
"axis": ts.DeferredType(constraint=ts.DimensionType),
"range": ts.DeferredType(constraint=ts.TupleType),
"forward": ts.DeferredType(constraint=ts.ScalarType),
"init": ts.DeferredType(constraint=(ts.ScalarType, ts.TupleType)),
},
Expand All @@ -324,7 +324,7 @@ def scan(
scan_pass: Callable,
/,
*,
axis: common.Dimension,
range: tuple[common.Dimension, int, int], # noqa: A002 # shadowing a Python built-in
forward: bool = True,
init: core_defs.Scalar | common.Field | Tuple,
) -> Callable[..., common.Field | Tuple]:
Expand All @@ -333,14 +333,16 @@ def scan(

Args:
scan_pass: Field operator `(carry, *args) -> carry` on scalars (or tuples thereof).
axis: Vertical dimension to scan along.
range: `(dim, start, stop)`: the vertical dimension to scan along and the half-open
interval of it the scan covers. The carry starts from `init` at `start` (forward)
or `stop - 1` (backward); the result is only defined on this interval.
forward: Scan direction.
init: Initial value of the carry: a constant, a scalar, or a field without the scan
dimension holding the initial value of each column. For tuple carries, each
element may be any of these; fields are not supported in named collections.

Examples:
>>> scan(my_pass, axis=KDim, forward=True, init=0.0)(a) # doctest: +SKIP
>>> scan(my_pass, range=(KDim, 0, nlev), forward=True, init=0.0)(a) # doctest: +SKIP
"""
raise NotImplementedError()

Expand Down
59 changes: 34 additions & 25 deletions src/gt4py/next/ffront/foast_passes/type_deduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,25 +167,39 @@ def _is_scan_builtin(expr: foast.Expr) -> bool:
return isinstance(expr, foast.Name) and expr.id == "scan"


def _check_scan_axis(axis: foast.Expr, description: str) -> Dimension:
if not isinstance(axis.type, ts.DimensionType):
raise errors.DSLError(axis.location, f"{description} must be a dimension.")
if axis.type.dim.kind != DimensionKind.VERTICAL:
raise errors.DSLError(axis.location, f"{description} must be a vertical dimension.")
return axis.type.dim


def _check_scan_range(range_: foast.Expr, name: str) -> Dimension:
if not (
isinstance(range_, foast.TupleExpr)
and len(range_.elts) == 3
and all(type_info.is_integral_scalar(bound.type) for bound in range_.elts[1:])
):
raise errors.DSLError(
range_.location,
f"Argument 'range' to scan operator '{name}' must be a tuple '(dim, start, stop)' "
"of a dimension and two integers.",
)
return _check_scan_axis(
range_.elts[0], f"The dimension in argument 'range' to scan operator '{name}'"
)


def _check_scan_args(
location: eve.SourceLocation,
name: str,
pass_type: ts.FunctionType,
*,
axis: foast.Expr,
forward: Optional[foast.Expr],
init: foast.Expr,
) -> Dimension:
"""Check the arguments of a scan operator and return its axis. An absent `forward` is checked by its default."""
if not isinstance(axis.type, ts.DimensionType):
raise errors.DSLError(
axis.location, f"Argument 'axis' to scan operator '{name}' must be a dimension."
)
if axis.type.dim.kind != DimensionKind.VERTICAL:
raise errors.DSLError(
axis.location,
f"Argument 'axis' to scan operator '{name}' must be a vertical dimension.",
)
) -> None:
"""Check the arguments of a scan operator. An absent `forward` is checked by its default."""
if forward is not None and not foast_utils.is_literal(forward):
raise errors.DSLError(
forward.location,
Expand Down Expand Up @@ -239,7 +253,6 @@ def _check_scan_args(
raise errors.DSLError(
location, f"Scan operator '{name}' must take and return scalars or tuples of scalars."
)
return axis.type.dim


def _check_scan_column_init(
Expand Down Expand Up @@ -349,13 +362,9 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S
new_forward = self.visit(node.forward, **kwargs)
new_init = self.visit(node.init, **kwargs)
new_definition = self.visit(node.definition, **kwargs)
axis = _check_scan_args(
node.location,
node.id,
new_definition.type,
axis=new_axis,
forward=new_forward,
init=new_init,
axis = _check_scan_axis(new_axis, f"Argument 'axis' to scan operator '{node.id}'")
_check_scan_args(
node.location, node.id, new_definition.type, forward=new_forward, init=new_init
)

new_type = ts_ffront.ScanOperatorType(axis=axis, definition=new_definition.type)
Expand All @@ -372,19 +381,19 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S
def _visit_scan_call(
self, node: foast.Call, scan_arg_types: list[ts.TypeSpec], **kwargs: Any
) -> foast.Call:
"""Type `scan(pass, axis=..., forward=..., init=...)`, the callee of a call-site scan."""
"""Type `scan(pass, range=..., forward=..., init=...)`, the callee of a call-site scan."""
new_func = self.visit(node.func, **kwargs)
if len(node.args) != 1:
raise errors.DSLError(
node.location,
f"'scan' takes exactly one positional argument (the scan pass), got {len(node.args)}.",
)
if unexpected := set(node.kwargs) - {"axis", "forward", "init"}:
if unexpected := set(node.kwargs) - {"range", "forward", "init"}:
raise errors.DSLError(
node.location,
f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.",
)
if missing := [name for name in ("axis", "init") if name not in node.kwargs]:
if missing := [name for name in ("range", "init") if name not in node.kwargs]:
raise errors.DSLError(
node.location,
f"Missing argument(s) {', '.join(repr(name) for name in missing)} to 'scan'.",
Expand All @@ -398,11 +407,11 @@ def _visit_scan_call(
pass_type = new_pass.type.definition

new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in node.kwargs.items()}
axis = _check_scan_args(
axis = _check_scan_range(new_kwargs["range"], str(new_pass))
_check_scan_args(
node.location,
str(new_pass),
pass_type,
axis=new_kwargs["axis"],
forward=new_kwargs.get("forward"),
init=new_kwargs["init"],
)
Expand Down
95 changes: 64 additions & 31 deletions src/gt4py/next/ffront/foast_to_gtir.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,14 @@ def _lower_scan(
init: itir.Expr,
axis: common.Dimension,
args: list[itir.Expr],
domain: Optional[itir.Expr] = None,
) -> itir.Expr:
"""Lower to `as_fieldop(scan(...))(*args)`, `param_names` being the carry and the arguments."""
carry, *arg_params = param_names
definition = im.lambda_(carry, *arg_params)(
im.call(scan_pass)(carry, *(im.deref(param) for param in arg_params))
)
return im.as_fieldop(im.scan(definition, forward, init, axis))(*args)
return im.as_fieldop(im.scan(definition, forward, init, axis), domain)(*args)


def _lower_scan_with_runtime_init(
Expand All @@ -90,6 +91,7 @@ def _lower_scan_with_runtime_init(
args: list[itir.Expr],
carry_type: ts.TypeSpec,
uids: utils.IDGeneratorPool,
domain: itir.Expr,
) -> itir.Expr:
# A stencil may not reference outer symbols, so a non-literal `init` cannot seed the scan.
# It is passed as an extra argument instead and read on the first level, marked by a flag
Expand All @@ -110,7 +112,9 @@ def _lower_scan_with_runtime_init(
result_collection_constructor=lambda _, elems: im.make_tuple(*elems),
)(carry_type)
seed = im.make_tuple(im.literal_from_value(False), placeholder)
return im.tuple_get(1, im.as_fieldop(im.scan(definition, forward, seed, axis))(*args, init))
return im.tuple_get(
1, im.as_fieldop(im.scan(definition, forward, seed, axis), domain)(*args, init)
)


@dataclasses.dataclass
Expand Down Expand Up @@ -427,19 +431,27 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
else:
raise AssertionError("Unexpected constructor encounterd.")

result = im.call(self.visit(node.func, **kwargs))(
*lowered_args, *lowered_kwargs.values()
func = (
self._visit_scan(node.func, result_type=node.type, **kwargs)
if isinstance(node.func, foast.Call)
and isinstance(node.func.func, foast.Name)
and node.func.func.id == "scan"
else self.visit(node.func, **kwargs)
)
result = im.call(func)(*lowered_args, *lowered_kwargs.values())

return result

raise AssertionError(
f"Call to object of type '{type(node.func.type).__name__}' not understood."
)

def _visit_scan(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
# `scan(scan_pass, axis=..., forward=..., init=...)`, lowered to a function of the
# scan pass's arguments
def _visit_scan(
self, node: foast.Call, *, result_type: ts.TypeSpec, **kwargs: Any
) -> itir.Expr:
# `scan(scan_pass, range=..., forward=..., init=...)`, lowered to a function of the
# scan pass's arguments. Arguments that are expressions are bound outside of it, so
# they are not shadowed by its parameters.
assert isinstance(node.type, ts_ffront.ScanOperatorType)
scan_pass = self.visit(node.args[0], **kwargs)
forward = (
Expand All @@ -450,34 +462,55 @@ def _visit_scan(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
param_names = list(node.type.definition.pos_or_kw_args)
args: list[itir.Expr] = [im.ref(param) for param in param_names[1:]]

range_ = node.kwargs["range"]
assert isinstance(range_, foast.TupleExpr)
_, start, stop = range_.elts
start_sym = next(self.uid_generator["__scan_start"])
stop_sym = next(self.uid_generator["__scan_stop"])
bindings = [
(start_sym, self.visit(start, **kwargs)),
(stop_sym, self.visit(stop, **kwargs)),
]
# The grid type and the bounds of the other dimensions are placeholders: domain inference
# only keeps the range of the scan dimension and infers the rest from the consumers.
domain = im.domain(
common.GridType.CARTESIAN,
{
dim: (im.ref(start_sym), im.ref(stop_sym))
if dim == node.type.axis
else (itir.InfinityLiteral.NEGATIVE, itir.InfinityLiteral.POSITIVE)
for dim in type_info.extract_dims(
next(iter(type_info.primitive_constituents(result_type)))
)
},
)

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

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

def _visit_astype(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
# Note: the type to convert to is uniquely identified by its GT4Py type (`ConstructorType`),
Expand Down
5 changes: 5 additions & 0 deletions src/gt4py/next/iterator/ir_utils/common_pattern_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ def is_applied_as_fieldop(arg: itir.Node) -> TypeGuard[_FunCallToFunCallToRef]:
return isinstance(arg, itir.FunCall) and is_call_to(arg.fun, "as_fieldop")


def is_applied_scan(arg: itir.Node) -> TypeGuard[_FunCallToFunCallToRef]:
"""Match expressions of the form `as_fieldop(scan(...))(*args)`."""
return is_applied_as_fieldop(arg) and is_call_to(arg.fun.args[0], "scan")


_FunCallToLambda: TypeAlias = _FunCallTo[itir.Lambda]


Expand Down
Loading
Loading