Skip to content

feat[next]: call-site scan builtin - #2920

Closed
havogt wants to merge 1 commit into
GridTools:mainfrom
havogt:scan-call
Closed

havogt wants to merge 1 commit into
GridTools:mainfrom
havogt:scan-call

Conversation

@havogt

@havogt havogt commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Description

Adds a call-site form of scans: scan(scan_pass, axis=..., forward=..., init=...)(args) can be used inside a field operator, in addition to the @scan_operator decorator.

@gtx.field_operator
def add(carry: float, x: float) -> float:
    return carry + x

@gtx.field_operator
def foo(a: gtx.Field[[IDim, KDim], float]) -> gtx.Field[[IDim, KDim], float]:
    return scan(add, forward=True, init=0.0)(a)
  • scan_pass is a @field_operator on scalars (or tuples of scalars) whose first argument is the carry.
  • axis is optional. If it is omitted, it is the unique vertical dimension of the arguments; it is an error if there is none or more than one.
  • forward and init must be literals, with the same defaults as the decorator (True, 0.0). Literals include tuples, unary minus, and type constructors such as float32(1.0).

Changes:

  • Type deduction: the call is typed as the existing ScanOperatorType, so argument promotion and return-type logic are reused. The checks on the scan pass are shared with the decorator path.
  • Lowering: the scan is lowered inline to as_fieldop(scan(λ(carry, *its) → pass(carry, ·its...), forward, init))(*args).
  • Column axis: _column_axis also collects the axes of call-site scans. For this, ItirShim, used when a field operator is called directly, now exposes foast_stage.
  • Embedded: the builtin returns an embedded.operators.ScanOperator.
  • Reserved name: scan is now a reserved builtin name.

Requirements

  • All fixes and/or new features come with corresponding tests.
  • Important design decisions have been documented in the appropriate ADR inside the docs/development/ADRs/ folder.

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.
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."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have only one check of the kwargs shared between scan_call and ScanOperator.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. forward and init already share _check_scan_pass, but the axis check is duplicated: here, and in visit_ScanOperator (L300-309).

Recommendation: fold the axis check into the shared helper so it covers all three kwargs, e.g. _check_scan_kwargs(location, name, pass_type, axis_type, forward_type, init_type) -> Dimension, and call it from both visitors. The compile-time-constant check on forward/init can go in there too: on the decorator path both are always literals, so it costs nothing. Only the axis inference (no axis= given) stays specific to scan(...).

🤖 Written by an agent on behalf of @havogt

pass_name = str(new_pass)

new_kwargs = {
"forward": foast.Constant(value=True, location=node.location),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

defaults should come from lowering

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Type deduction shouldn't rewrite the node with materialised defaults.

Recommendation: leave absent kwargs absent in FOAST and insert the literals in foast_to_gtir._visit_scan_call. The default values should live in exactly one place, the signature of fbuiltins.scan, and the lowering reads them from there instead of repeating True/0.0. Type deduction then checks against the type of the default without inserting it. If we make init required (see the next thread), only forward is left to default, which makes this simpler still.

🤖 Written by an agent on behalf of @havogt


new_kwargs = {
"forward": foast.Constant(value=True, location=node.location),
"init": foast.Constant(value=0.0, location=node.location),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does init have a default value?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently yes: 0.0, mirroring @scan_operator(init=0.0) and the fbuiltins.scan signature. But that default only type-checks for a float64 carry. Any other carry (float32, int, bool, tuple) fails with "Argument 'init' ... must have same type as ..." until the user passes init explicitly.

Recommendation: make init required for the scan builtin. There is no backwards-compatibility constraint because the builtin is new. A default that is only right for one dtype is a trap. And the stacked scan-init branch makes init a runtime/per-column value anyway, where a scalar default makes even less sense. @scan_operator keeps its default.

🤖 Written by an agent on behalf of @havogt

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a separate PR we should remove the default from init.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. #2920 keeps init=0.0 so it behaves like @scan_operator, and the default gets removed in a follow-up.

Recommendation: do it in the same follow-up that makes init runtime (see the thread on L360). Both change what init is, and a runtime init has no sensible default anyway.

🤖 Written by an agent on behalf of @havogt

)

def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
# `scan(scan_pass, forward=..., init=...)(*args)`

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there overlap between this and visitScanOperator

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Both end in as_fieldop(scan(λ, forward, init))(*args). They differ only in how the λ is built:

  • visit_ScanOperator inlines the lowered definition and let-binds the derefed params.
  • This version calls the pass by reference: λ(carry, *params): pass(carry, *deref(params)).

After InlineFundefs/InlineLambdas both are the same thing.

Recommendation: extract one helper, e.g. _lower_scan(pass_expr, param_names, forward, init, args), and use it from both. visit_ScanOperator would pass its lowered definition as a lambda. No unit test pins the scan GTIR of either path, so the change is covered by the existing scan integration tests. The decorator path goes away later in the stack (scan-drop-decorator), so the alternative is to accept the duplication until then. I'd still share it now, since it is small and keeps the two paths from drifting.

🤖 Written by an agent on behalf of @havogt

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"])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we need to generate the name? and not use the name of the first parameter of the scanpass.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no real need. The λ is a fresh scope, and its only free symbol is the reference to the pass itself. A collision would only happen if a pass parameter had the same name as the pass, which isn't worth guarding against.

Recommendation: use the pass's own parameter names, pass_type.pos_or_kw_args (carry first). The GTIR becomes readable, matches what visit_ScanOperator emits, and drops the __scan_carry/__scan_arg uids. This fits naturally into the shared helper from the previous thread.

🤖 Written by an agent on behalf of @havogt

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's keep as is

**node.kwargs,
}
new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in new_kwargs.items()}
for name in ("forward", "init"):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

init should be runtime

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping this check alone doesn't work. GTIR stencils must be closed, and a non-literal init in scan(λ, fwd, init) refers to an outer symbol. Every backend then fails in TraceShifts with ValueError: Undefined symbol init_param (trace_shifts.py:291; verified on roundtrip, gtfn and dace). Allowing open stencils would mean auditing every pass that assumes they are closed: trace_shifts, fuse_as_fieldop, inline_lambdas/CSE, global_tmps, and dace's capture_outer_data=False.

There is an approach that works without any GTIR or backend change, and it is already implemented on the stacked branch scan-init (c590dae, 1658535; +221/-38). The frontend desugars the scan: init becomes an extra stencil argument, and the carry gets a "first level" flag. That handles both a runtime scalar and a per-column field (no scan axis). An init with the scan axis is rejected, because which level it reads would move with domain inference.

Recommendation: keep #2920 compile-time and make runtime init the next PR, together with removing the default. It's a separate, self-contained lowering with its own design decision (rejecting init with the scan axis), and keeping it out keeps #2920 reviewable. If you'd rather have it here, I can merge scan-init's two commits into this branch.

🤖 Written by an agent on behalf of @havogt

return isinstance(expr, foast.Name) and expr.id == "scan"


def _is_literal(expr: foast.Expr) -> bool:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we have a similar check somewhere else on foast level?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are similar checks, but none we can reuse:

  • func_to_foast._verify_builtin_type_constructor: Python-AST level, accepts Constant or ±Constant, for type-constructor arguments.
  • foast_to_gtir._visit_type_constr: the same shape again, raised only at lowering.
  • foast_passes/utils.expr_to_index: ±int constants for tuple indices.

None of them handles tuples or constructor calls, which a tuple init needs.

Recommendation: keep _is_literal here for now and delete it in the runtime-init PR. Then only forward needs the check, and that is a plain isinstance(..., foast.Constant). forward=FWD with a closure variable still works, because ClosureVarFolding turns it into a Constant before type deduction (func_to_foast.py:187-190).

🤖 Written by an agent on behalf of @havogt

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(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we remove this limitation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not in this PR, in my view. Allowing s = scan(p, ...) with a later s(a), or passing the result around, makes a scan operator a first-class value. That is the first step of general (user-defined) higher-order functions. It needs:

  • a standalone scan(...) to lower to a GTIR lambda λ(*args) → as_fieldop(scan(...))(*args) instead of being fused with its call;
  • calls of function-typed values to go through the generic call path;
  • axis to be explicit whenever the call isn't directly attached, since there are no arguments to infer it from at the definition.

GTIR already supports this, and InlineLambdas specialises it away. The work is in the frontend gates, and that is exactly what the HOF follow-up replaces.

Recommendation: keep the limitation in #2920 and lift it in the HOF PR, together with removing the scan-specific special cases at L890 and L917. Relaxing it here would grow the scan-specific code that the HOF PR then throws away.

🤖 Written by an agent on behalf of @havogt

if not isinstance(
new_func,
(foast.FunctionDefinition, foast.FieldOperator, foast.ScanOperator, foast.Name),
) and not (

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mention here that scan is the only higher order function (if it applies here).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it applies. scan is the only builtin that returns a function, so a call to a scan(...) result is the only callee here that isn't a name or definition.

Recommendation: add a one-line comment on the clause: "scan(pass, ...) is the only higher-order builtin, so its result is the only callable call result." Both the comment and the clause go away with general HOF support.

🤖 Written by an agent on behalf of @havogt

Comment on lines +166 to +180
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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move to foast_passes/utils.py

@havogt

havogt commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #3065, the same branch pushed to GridTools/gt4py so that PRs can be stacked on top of it.

🤖 Written by an agent on behalf of @havogt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant