Repository navigation
Conversation
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." |
There was a problem hiding this comment.
have only one check of the kwargs shared between scan_call and ScanOperator.
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
defaults should come from lowering
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
does init have a default value?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
In a separate PR we should remove the default from init.
There was a problem hiding this comment.
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)` |
There was a problem hiding this comment.
is there overlap between this and visitScanOperator
There was a problem hiding this comment.
Yes. Both end in as_fieldop(scan(λ, forward, init))(*args). They differ only in how the λ is built:
visit_ScanOperatorinlines the lowered definition andlet-binds thederefed 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"]) |
There was a problem hiding this comment.
why do we need to generate the name? and not use the name of the first parameter of the scanpass.
There was a problem hiding this comment.
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
| **node.kwargs, | ||
| } | ||
| new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in new_kwargs.items()} | ||
| for name in ("forward", "init"): |
There was a problem hiding this comment.
init should be runtime
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
don't we have a similar check somewhere else on foast level?
There was a problem hiding this comment.
There are similar checks, but none we can reuse:
func_to_foast._verify_builtin_type_constructor: Python-AST level, acceptsConstantor±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:±intconstants 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( |
There was a problem hiding this comment.
can we remove this limitation
There was a problem hiding this comment.
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;
axisto 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 ( |
There was a problem hiding this comment.
mention here that scan is the only higher order function (if it applies here).
There was a problem hiding this comment.
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
| 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 |
There was a problem hiding this comment.
move to foast_passes/utils.py
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_operatordecorator.scan_passis a@field_operatoron scalars (or tuples of scalars) whose first argument is the carry.axisis 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.forwardandinitmust be literals, with the same defaults as the decorator (True,0.0). Literals include tuples, unary minus, and type constructors such asfloat32(1.0).Changes:
ScanOperatorType, so argument promotion and return-type logic are reused. The checks on the scan pass are shared with the decorator path.as_fieldop(scan(λ(carry, *its) → pass(carry, ·its...), forward, init))(*args)._column_axisalso collects the axes of call-site scans. For this,ItirShim, used when a field operator is called directly, now exposesfoast_stage.embedded.operators.ScanOperator.scanis now a reserved builtin name.Requirements