Skip to content

feat[next]: embedded accepts 0-d arrays as scalars (traced scalars under jax.jit / torch.compile) - #3030

Merged
havogt merged 13 commits into
GridTools:mainfrom
havogt:embedded-0d-scalars
Nov 23, 2026
Merged

havogt merged 13 commits into
GridTools:mainfrom
havogt:embedded-0d-scalars

Conversation

@havogt

@havogt havogt commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Under jax.jit or torch.compile, a scalar argument is a traced 0-d array. Embedded now accepts 0-d arrays wherever it accepts scalars.

  • array_ops.is_scalar_like: a scalar or a 0-d array. It is used for field operands, __setitem__ and the scan carry.
  • The scalar defaults of the builtins compute with ArrayOps: a 0-d array's own, or NumPy's for Python/NumPy scalars, which replaces the np/math maps in fbuiltins. abs/neg of a Python int now return a NumPy int.
  • ArrayOps.scalar (used by as_scalar) keeps a traced element as a 0-d array under jax and torch.
  • embedded/__init__.py no longer imports nd_array_field and array_libraries (gt4py.next does), which avoids an import cycle with fbuiltins.

@havogt

havogt commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Written by an agent on behalf of @havogt

Comment on lines +429 to +433
if core_defs.is_scalar_type(lhs) and core_defs.is_scalar_type(rhs):
return getattr(np, name)(lhs, rhs)
array = cast(core_defs.NDArrayObject, rhs if core_defs.is_scalar_type(lhs) else lhs)
ops = array_ops.of(array)
return ops.elementwise_function(name)(ops.operand(lhs, array), ops.operand(rhs, array))

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.

this looks a bit patchy, why does dispatching via the normal field not work?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't we follow the same approach as suggested above for the unary functions: convert scalar arguments to numpy scalars and dispatch based on that?

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.

These are the scalar defaults. Under jit, a traced scalar is a 0-d array, not a field, so field dispatch does not apply to it. The defaults treat it as the scalar it stands for.

On the suggestion above: done in 62aa8d5. Every scalar goes through ArrayOps. A 0-d array goes through its library's; a Python or NumPy scalar goes through NumPy's. The binary case converts the other operand with operand(…, like=array).

🤖 Written by an agent on behalf of @havogt

Comment thread src/gt4py/next/__init__.py Outdated
)
from .constructors import FieldConstructor, as_connectivity, as_field, empty, full, ones, zeros
from .embedded import ( # Just for registering field implementations
array_libraries as _array_libraries,

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.

what's this about?

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.

nd_array_field and array_libraries import ffront.fbuiltins, which in this PR needs array_ops at module level. So embedded/__init__ no longer imports those two, and gt4py.next imports them for their registrations (the comment there says so now). #3033 removes the reason: fbuiltins then imports nothing from embedded, and this goes back to what main has.

🤖 Written by an agent on behalf of @havogt

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

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

What: `as_scalar()` on a traced field element now returns a 0-d tracer/tensor instead of failing at the conversion point. Code that needs a concrete Python value from it (e.g. `float(...)`, `bool(...)`, or an `if` on the value) now fails later, with a less specific error (e.g. jax `ConcretizationTypeError`) far from the `as_scalar` call, instead of the previous immediate conversion error.
Where: src/gt4py/next/embedded/nd_array_field.py:as_scalar (via the `scalar` overrides in jax_ops.py / torch_ops.py)
Trigger: An embedded operator or scan run under `jax.jit` / `torch.compile` whose traced scalar result is used in a Python-level branch or concrete conversion.
Detected by: Nothing in this PR — the new traced-scalar tests only exercise arithmetic uses of the result.
Covered in this PR: No

What: `broadcast` now admits 0-d arrays through its widened assert, but the default implementation still returns the value unchanged and, per the in-code TODO, skips the dimension-compatibility check; a 0-d array broadcast with incompatible `dims` silently succeeds instead of erroring.
Where: src/gt4py/next/ffront/fbuiltins.py:broadcast
Trigger: Embedded execution calling `broadcast` with a 0-d array and dimensions that do not match the surrounding computation.
Detected by: Nothing — no test in this PR exercises `broadcast` with a 0-d array.
Covered in this PR: No

🏅 Score: 89
🧪 PR contains tests
🔒 No security concerns identified
🔀 No multiple PR themes
⚡ No major issues detected

⚙️ Agent run details
  • Model: openai/zai-org/GLM-5.3-Flash
  • Tokens: 16,103 in / 30,229 out / 46,332 total
  • Time cost: 227.3s
  • AI calls: 1

@egparedes egparedes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I have some questions and comments.

Comment thread src/gt4py/next/embedded/operators.py Outdated
pos: Sequence[common.NamedIndex],
target: xtyping.MaybeNestedInTuple[common.MutableField],
source: xtyping.MaybeNestedInTuple[core_defs.Scalar],
source: xtyping.MaybeNestedInTuple[core_defs.Scalar | core_defs.NDArrayObject],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Would it make sense to create an alias for embedded related modules for core_defs.Scalar | core_defs.NDArrayObject? It is probably used in several places

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.

Done: array_ops.ScalarLike, used in operators (7362c8a).

🤖 Written by an agent on behalf of @havogt

Comment thread src/gt4py/next/embedded/array_ops.py Outdated
return ops


def is_scalar_or_0d_array(value: Any) -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe call it is_scalar_like()?

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.

Renamed to is_scalar_like, a TypeIs[ScalarLike]. The check for a 0-d array alone is is_0d_array.

🤖 Written by an agent on behalf of @havogt

Comment thread src/gt4py/next/ffront/fbuiltins.py Outdated
Comment on lines +386 to +389
# default implementation for scalars, Fields are handled via dispatch
assert array_ops.is_scalar_or_0d_array(value)
if core_defs.is_scalar_type(value):
return cast(common.Field | core_defs.ScalarT, _math_builtin(value))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can't this case be implemented as a preliminary conversion to numpy scalar (or 0D array) and then just dispatch to the array_ops? We could then drop the implementation maps for functions which exist in this file.

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.

Done in 62aa8d5. Python and NumPy scalars go to NumPy's ArrayOps, and 0-d arrays to their library's. The np/math maps are gone from fbuiltins. It is also faster: sqrt(np.float64) takes 0.59 µs instead of 1.92 µs.

One result type changes: abs/neg of a Python int now return a NumPy int (pinned in ca92357). NumPy scalar types are kept. Without SciPy, NumPy's gamma fallback now returns a scalar for a scalar.

🤖 Written by an agent on behalf of @havogt

Comment on lines +429 to +433
if core_defs.is_scalar_type(lhs) and core_defs.is_scalar_type(rhs):
return getattr(np, name)(lhs, rhs)
array = cast(core_defs.NDArrayObject, rhs if core_defs.is_scalar_type(lhs) else lhs)
ops = array_ops.of(array)
return ops.elementwise_function(name)(ops.operand(lhs, array), ops.operand(rhs, array))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Couldn't we follow the same approach as suggested above for the unary functions: convert scalar arguments to numpy scalars and dispatch based on that?

Comment on lines +9 to +11
# not `nd_array_field` and `array_libraries`: they import `ffront.fbuiltins`, which imports
# this package
from . import array_ops, common, context, exceptions

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Question: is it really needed to import these modules here? They are only used for reexporting them, right? Is that a requirement of coding conventions? If not, why is this done 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.

Not a convention. They make gt4py.next.embedded.context etc. reliable as attributes (next_embedded.context in the decorator, gtx_embedded.context in context.py). What this PR changes is that nd_array_field/array_libraries are no longer imported here; see the reply on next/__init__.py.

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

Can we avoid all these important?

@egparedes egparedes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. We can address my comment in next PR #3027

Comment on lines +288 to +295
#: What embedded accepts where it accepts a scalar: a scalar, or a 0-d array (`is_scalar_like`)
ScalarLike: TypeAlias = core_defs.Scalar | core_defs.NDArrayObject


def is_scalar_like(value: Any) -> TypeIs[ScalarLike]:
"""A scalar, or a 0-d array."""
return core_defs.is_scalar_type(value) or is_0d_array(value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

scalar_like makes sense for the function name and for the case where the NDArrayObject represents a 0-D array, but not for the general case where scalars or ndarray objects are allowed. For this case, I think we should use a more general name like TensorLike, or NDScalar.

@havogt
havogt merged commit baf3162 into GridTools:main Nov 23, 2026
26 checks passed
@havogt
havogt deleted the embedded-0d-scalars branch November 23, 2026 22:50
havogt added a commit to havogt/gt4py that referenced this pull request Nov 23, 2026
havogt added a commit to havogt/gt4py that referenced this pull request Nov 23, 2026
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.

2 participants