Skip to content

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

Open
havogt wants to merge 27 commits into
mainfrom
havogt/scan-call
Open

havogt wants to merge 27 commits into
mainfrom
havogt/scan-call

Conversation

@havogt

@havogt havogt commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

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, axis=KDim, 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 required and must be a vertical dimension.
  • 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 argument checks are shared with the decorator path.
  • Lowering: both forms lower through one function to as_fieldop(scan(λ(carry, *its) → pass(carry, ·its...), forward, init, axis))(*args).
  • Embedded: the builtin dispatches to an implementation that builds an embedded.operators.ScanOperator. It is registered from embedded/operators.py, because nd_array_field cannot import that module.
  • Reserved name: scan is now a reserved builtin name and is exported from gt4py.next.

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.
…builtin and scan_operator

- One check of axis, forward and init for both paths; absent arguments
  are checked by their default.
- Defaults are inserted by the lowering, taken from the signature of
  the scan builtin.
- One lowering helper for both paths; the scan lambda uses the scan
  pass's own parameter names.
- Move is_literal to foast_passes/utils.py.
@havogt

havogt commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Continues #2920, reopened from a branch in this repository so that PRs can be stacked on top. The earlier review discussion is on #2920.

🤖 Written by an agent on behalf of @havogt

@havogt havogt mentioned this pull request Dec 1, 2026
1 of 2 tasks
…side

fbuiltins no longer imports embedded.operators. As for the other
builtins, the embedded implementation is registered in
nd_array_field's builtin registry, from embedded/operators.py, and
dispatched on the arguments of the scan operator, so ArrayOps
builtin_overrides apply to scan too. The registry also finds fields
nested in tuples and passed as keyword arguments.
Comment thread src/gt4py/next/embedded/operators.py Resolved
Comment thread src/gt4py/next/ffront/foast_to_gtir.py Resolved
Comment thread src/gt4py/next/ffront/foast_to_past.py Resolved
Comment thread src/gt4py/next/ffront/past_to_itir.py Resolved
…ispatch

- 'axis' is required; the inference from the arguments and the embedded
  fallback to the closure column range are removed.
- 'scan(...)' is lowered by '_visit_scan' through the existing builtin
  dispatch to a function of the pass's arguments, and the outer call
  takes the generic call path; '_lower_scan' is a free function.
- The scalars-only check on the scan pass is shared with the decorator
  path, which failed with a bare AssertionError before; the
  unreachable positional-only/keyword-only check is removed.
- The embedded field lookup flattens tuples like the dispatch does.
`scan(scan_pass, forward, init, axis)` now takes the scan axis as a fourth
argument (an `AxisLiteral`), set by the frontend from the scan operator's
axis. gtfn, dace and the embedded iterator read the axis from the scan
node, so the program-wide `column_axis` (`CompileTimeArgs.column_axis`,
the backend parameters, the iterator `fendef(column_axis=...)` kwarg) is
removed, and with it the restriction that all scan operators in a program
use the same axis.

The embedded iterator executes a closure column-wise only when its stencil
is a `scan`; a scan nested inside a stencil is no longer supported there.
…omain

The embedded field-view scan reads the range of its own axis from the
vertical ranges of the output domain, which may be a tuple of domains on
different vertical dimensions. An axis that occurs with different ranges
in the tuple raises. The range is clipped to the range the scan's inputs
cover on the axis, so a scan over a shifted input under concat_where
starts where the compiled backends start.
- gtfn: merge adjacent scans only if they run on the same axis.
- Domain inference keeps the range of the scan's own axis instead of
  every vertical dimension of the target domain.
- iterator embedded: remove the column-mode arithmetic of `Column` and
  the `Column` branches of the builtins, unreachable now that only scans
  run column-wise; `Column.dtype` reads the first element.
- Drop a FIXME whose reason no longer holds.
…mension

Also remove the unused `Column.dtype` and `Column.__array__`, and use
`dim_from_axis_literal` in domain inference.
A scan nested inside a stencil is unsupported on every backend.
A scan whose inputs lack its axis now gets a result on that axis, as in
the frontend, instead of failing type inference when written to a field
on the axis.
# Conflicts:
#	src/gt4py/next/ffront/foast_to_gtir.py
#	src/gt4py/next/ffront/past_to_itir.py
#	tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py
@havogt
havogt changed the base branch from main to havogt/scan-axis December 2, 2026 08:29
@havogt
havogt added this pull request to stack #3069 December 2, 2026 08:36
Base automatically changed from havogt/scan-axis to main December 3, 2026 10:34
# Conflicts:
#	src/gt4py/next/ffront/foast_to_gtir.py
#	tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py
Comment thread src/gt4py/next/embedded/operators.py Resolved
Comment thread src/gt4py/next/ffront/fbuiltins.py Resolved
*,
axis: common.Dimension,
forward: bool = True,
init: core_defs.Scalar | Tuple = 0.0,

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.

@tehrengruber Removing the default is in a next PR

Keep _register_builtin private, make _check_scan_args a plain check, split the forward and init literal checks, and add TODOs.
@havogt
havogt marked this pull request as ready for review December 3, 2026 13:06
@havogt
havogt requested a review from tehrengruber December 3, 2026 13:07
Comment on lines +95 to +96
case foast.Call(func=foast.Name(type=ts.ConstructorType())):
return all(is_literal(arg) for arg in expr.args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Edge Case

The constructor-call case of the new is_literal checks only positional arguments and ignores
expr.kwargs, so a call such as float32(x=<runtime value>) (also under a unary minus or
inside a tuple) is classified as a compile-time constant. If such an expression reaches
_check_scan_args as init or forward, the scan accepts a runtime-dependent value that the
lowering then treats as a constant. It is uncertain whether the FOAST frontend currently
permits keyword arguments on constructor calls (type deduction may reject them earlier), so
the practical reachability is unclear, but closing the gap is cheap: also require that the
call has no keyword arguments (or that they are literal) in this match case.

Comment on lines 357 to 366
if len(node.args) != 1:
raise errors.DSLError(
node.location,
f"Scan operator '{node.id}' must have at least one argument (the carry).",
f"'scan' takes exactly one positional argument (the scan pass), got {len(node.args)}.",
)
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:
if unexpected := set(node.kwargs) - {"axis", "forward", "init"}:
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}'.",
f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.",
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Test Coverage

Two new error branches in _visit_scan_call — more than one positional argument passed to
scan, and unexpected keyword names — have no matching tests, while every other diagnostic
introduced by this PR (missing axis, non-vertical axis, non-constant init, wrong init type,
non-field-operator pass, un-called scan, scalar-only pass) is covered in
tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py. Since tests are the spec in
this repo, add cases such as scan(pass, extra, axis=KDim) and
scan(pass, axis=KDim, foo=1) to lock in the messages and the early-return behavior.

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
✅ Merge recommendation: Needs review
🔎 Failure modes

What: A runtime-dependent `init` (or `forward`) can pass the compile-time-constant check when wrapped in a type-constructor call that uses keyword arguments, because the new `is_literal` helper only inspects positional arguments of constructor calls; the scan would then be lowered with a non-constant init expression instead of either rejecting the code or folding it to a literal.
Where: src/gt4py/next/ffront/foast_passes/utils.py:is_literal (consumed by _check_scan_args)
Trigger: Something like `scan(pass, axis=KDim, init=float32(x=runtime_scalar))` inside a field operator; reachable only if the FOAST frontend accepts keyword arguments on constructor calls, which is not settled from the diff.
Detected by: Nothing; no test in this PR covers constructor calls with keyword arguments in scan arguments.
Covered in this PR: No

What: Existing user code that defines its own operator named `scan` regresses: scan detection in type deduction is purely name-based (`expr.id == "scan"`), so any call `scan(...)` inside a field operator is now rejected as an un-instantiated scan builtin instead of resolving to the user's own symbol.
Where: src/gt4py/next/ffront/foast_passes/type_deduction.py:visit_Call (_is_scan_builtin)
Trigger: A field operator named `scan` (shadowing the newly reserved builtin) called inside another field operator, which was valid before this PR.
Detected by: Downstream user test suites hitting the new DSLError; no shadowing scenario is tested here.
Covered in this PR: No

What: The new diagnostics for a wrong positional-argument count and for unexpected keyword names in `scan(...)` can silently change or disappear in later refactors because they are the only new scan error paths without test coverage.
Where: src/gt4py/next/ffront/foast_passes/type_deduction.py:_visit_scan_call
Trigger: `scan(pass, extra_arg, axis=KDim)` or `scan(pass, axis=KDim, foo=1)` inside a field operator.
Detected by: Nothing; the new unit tests in test_type_deduction.py cover the other scan error branches but not these two.
Covered in this PR: No

🏅 Score: 86
🧪 PR contains tests
🔒 No security concerns identified
🔀 No multiple PR themes

⚙️ Agent run details
  • Model: openai/zai-org/GLM-5.3-Flash
  • Tokens: 18,447 in / 50,032 out / 68,479 total
  • Time cost: 312.9s
  • AI calls: 1

- is_literal also checks keyword arguments of constructor calls
- check the scan call against the signature of 'scan' instead of restating it
- split the forward and init lowering
- test the forward literal check, keyword arguments, named-collection carry,
  input without the scan axis, error paths and the GTIR lowering
- explicit init in tests that are not about its default

This branch was successfully deployed

1 active (outdated) deployment
pr-agent — 59e11615 Deployed Dec 3, 2026 by havogt via pr-agent / pr-agent #293
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