Skip to content

Add floor.Scalar prim op for symbolic math.floor - #25773

Open
abaybektursun wants to merge 5 commits into
pytorch:mainfrom
abaybektursun:fix/sym-floor-prim-op
Open

abaybektursun wants to merge 5 commits into
pytorch:mainfrom
abaybektursun:fix/sym-floor-prim-op

Conversation

@abaybektursun

@abaybektursun abaybektursun commented Nov 27, 2026 •

Copy link
Copy Markdown

Summary

Fixes #25772

torch._export.verifier.Verifier.allowed_builtin_ops allows all four rounding builtins (math.ceil, math.floor, math.trunc, round), but math.floor is missing from _PYTHON_SYM_OPS_TO_EXECUTORCH_SYM_OPS. Because EdgeToBackendOpsPass leaves it unrewritten, ToOutVarPass fails with AttributeError: 'builtin_function_or_method' object has no attribute '_schema'.

This registers executorch_prim::floor.Scalar and adds the C++ prim kernel behind INCLUDE_EXECUTORCH_PRIM_FLOOR_SCALAR. On Double inputs it checks that std::floor(x) falls in [-2^63, 2^63) before casting to int64_t (failing with InvalidArgument rather than UB), and passes Int through unchanged since PyTorch's SymNode tracing can emit math.floor on a SymInt. Existing rounding prim ops (ceil, round, trunc, sym_int) are left untouched to keep this PR scoped; happy to add range checks to them in a follow-up.

Tracked in huggingface/transformers#51303 (item 10).

Authored with Gemini and audited with Claude Code.

Test plan

Added C++ tests (TestFloor, TestFloorInvalidInputs, and a short-stack entry) in kernels/prim_ops/test/prim_ops_test.cpp and an end-to-end emit/runtime test (test_emit_sym_floor, covering positive and negative symbolic floor) in exir/emit/test/test_emit.py.

Built with -DEXECUTORCH_BUILD_TESTS=ON (and also with -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined"):

cmake --build cmake-out --target kernels_prim_ops_test
./cmake-out/kernels/prim_ops/test/kernels_prim_ops_test

28 tests passed.

With portable_lib rebuilt from this branch:

pytest exir/emit/test/test_emit.py -k "test_emit_sym_"

5 tests passed, and the 8-row Dim.AUTO XnnpackPartitioner repro from the issue matches eager for rows 2..8.

cc @nil-is-all

Register executorch_prim::floor.Scalar in executorch_prim_ops_registry.py and implement the C++ kernel behind INCLUDE_EXECUTORCH_PRIM_FLOOR_SCALAR so dynamically-shaped exported programs calling math.floor lower cleanly in to_executorch().

Fixes pytorch#25772.
@abaybektursun

Copy link
Copy Markdown
Author

@pytorchbot label "release notes: ops & kernels"

@pytorch-bot

pytorch-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25773

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (3 Unrelated Failures)

As of commit 156a540 with merge base 93ba1f2 (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs failed but was present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 27, 2026
@pytorch-bot pytorch-bot Bot added the release notes: ops & kernels Changes to the opset and any new / changed kernel implementations label Nov 27, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T10:25:02.348467Z 94f87ca PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@executorch-triage executorch-triage Bot added the community: contribution PRs coming from community (excluding hardware partners) label Nov 27, 2026
@JakeStevens
JakeStevens self-requested a review November 30, 2026 19:27
_PYTHON_SYM_OPS_TO_EXECUTORCH_SYM_OPS: Dict[Any, OpOverload] = {
builtins.round: ops.backend.executorch_prim.round.Scalar,
math.ceil: ops.backend.executorch_prim.ceil.Scalar,
math.floor: ops.backend.executorch_prim.floor.Scalar,

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.

With a dynamic first dimension, x + math.floor(x.shape[0]) now lowers successfully. With generate_etrecord=True, calling program.get_etrecord().save(...) still raises SerializeError: Failed serializing node floor because the recorded export graph contains the Python builtin. Could you add math.floor support to the serializer and deserializer in exir/serde/export_serialize.py and cover this model with an ETRecord round-trip test?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Addressed in f0bc506d1a:

  • Added math.floor to _SYM_INT_OPS, added "math." resolution in GraphModuleDeserializer.deserialize_operator, and added FloorToInt to sympy.sympify locals in exir/serde/export_serialize.py (so FloorToInt(...) expressions deserialize as torch.utils._sympy.functions.FloorToInt rather than an undefined sympy function).
  • Added test_etrecord_round_trip_sym_floor in devtools/etrecord/tests/etrecord_test.py covering x + math.floor(x.shape[0]) with a dynamic first dimension (generate_etrecord=True -> save() -> parse_etrecord(), checking graph closeness, math.floor / SymInt expr type, and numerical execution for both exported and edge graphs), plus test_sym_floor_round_trip in exir/tests/test_serde.py.

Comment thread kernels/prim_ops/register_prim_ops.cpp Outdated
out = EValue(static_cast<int64_t>(val));
} else if (a.isInt()) {
out = EValue(a.toInt());
} else {

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.

The registered Python floor.Scalar returns integer 0 for False and 1 for True, but the C++ kernel returns InvalidType for both. Could you handle a.isBool() using the same int64_t conversion as sym_int.Scalar and test both values? A None input would still exercise the InvalidType path.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Addressed in f0bc506d1a:

  • Added else if (a.isBool()) { out = EValue(static_cast<int64_t>(a.toBool())); } to executorch_prim::floor.Scalar matching sym_int.Scalar.
  • Added false -> 0 and true -> 1 checks (verifying Tag::Int output) in TestFloor and switched TestFloorInvalidInputs to EValue() (None) to exercise Error::InvalidType (verified with normal and UBSan kernels_prim_ops_test).

…upport

- Add math.floor to _SYM_INT_OPS, handle math. prefixes in
  GraphModuleDeserializer.deserialize_operator, and pass FloorToInt in
  sympy.sympify locals in exir/serde/export_serialize.py.
- Handle a.isBool() in executorch_prim::floor.Scalar via
  static_cast<int64_t>(a.toBool()) to match sym_int.Scalar and Python
  floor.Scalar.
- Add ETRecord round-trip test (test_etrecord_round_trip_sym_floor),
  direct serde round-trip test (test_sym_floor_round_trip), and C++
  unit tests for false/true and EValue() (None -> InvalidType).
@abaybektursun

Copy link
Copy Markdown
Author

Thanks for the review @JakeStevens! Both review items are addressed in f0bc506d1a (details inline on both threads). Verified locally with kernels_prim_ops_test (normal + UBSan, 28/28), TestETRecord (55/55), TestSerde (19/19), and test_emit_sym_floor. Ready for another look whenever you have time.

test-binary-size-linux-gcc failed at 52200 > 52168 (+32B) because main
had 0B headroom in the GCC size_test binary while the 23 scalar prim-op
lambdas duplicated ~5.8KB of tag dispatch, stack-size checks, and EValue
assignment boilerplate.

- Share ET_NOINLINE binary_scalar_op, unary_scalar_op, and
  check_stack_size helpers across the scalar prim ops while preserving
  all per-op selective-build #if guards and static Kernel prim_ops[]
  layout for gen_max_kernel_num.py.
- Compute floor via std::trunc so no additional libm floor PLT/GOT
  entry is needed (exact for all IEEE 754 doubles, same range checks).
- Simplifies sym_ite scalar copy to out = selected.

Reduces register_prim_ops.o .text by ~49% on arm64 (-Os) and ~32% on
x86_64 Clang (-Os) without touching the CI binary-size threshold.
@abaybektursun

Copy link
Copy Markdown
Author

Quick follow-up in 672fc85563 for the sole CI failure (test-binary-size-linux-gcc: 52200 > 52168, +32B, with main at 52168 <= 52168 and all 155 other checks green):

Rather than bumping the threshold in .github/workflows/pull.yml, 672fc85563 consolidates the duplicated scalar prim-op macro expansions in kernels/prim_ops/register_prim_ops.cpp into shared ET_NOINLINE binary_scalar_op / unary_scalar_op / check_stack_size helpers (preserving all 29 per-op EXECUTORCH_ENABLE_PRIM_OPS_SELECTIVE_BUILD guards and the static Kernel prim_ops[] layout for gen_max_kernel_num.py), and computes floor via std::trunc to avoid adding a separate libm floor PLT/GOT entry.

Local verification on 672fc85563:

  • register_prim_ops.o .text (-Os -DET_LOG_ENABLED=0): -48.9% on arm64 (4160 -> 2124B) and -32.2% on x86_64 Clang (3415 -> 2316B), projecting enough .text reduction on GCC9 to drop LOAD #3 [RX] by a full 4KB page below the 52168 budget.
  • kernels_prim_ops_test: 28/28 passed (normal + UBSan).
  • All 29/29 single-op selective builds (ET_LOG_ENABLED=0 and 1, -Wall -Wextra -Werror): passed.
  • test_emit.py (test_emit_sym_floor + sym ops) & test_gen_max_kernel_num.py (12/12, 29 prim ops): passed.

@JakeStevens Ready for CI re-run / review whenever convenient!

def test_etrecord_round_trip_sym_floor(self):
class SymFloorModel(torch.nn.Module):
def forward(self, x):
return x + math.floor(x.shape[0])

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.

This test passes an integer dimension directly to floor. I tried the model from #25772, x[:math.floor(x.shape[0] / 3)], with 8 input rows and a dynamic batch dimension from 6 to 20. On 672fc85563, to_edge(ep, generate_etrecord=True).to_executorch() succeeds, then get_etrecord().save(...) raises SerializeError: Failed serializing node truediv. The division produces a SymFloat before the graph reaches floor.

Could you add serialization and deserialization for that operator.truediv result and cover the fractional model in this round-trip test? With 8 input rows, the parsed graph should return the first 2 rows.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch — fixed in 156a540de4:

  • Added SymFloat, SymFloatArgument, Argument.as_sym_float(s), and defaulted Graph.sym_float_values in exir/serde/schema.py (minor bump 5.6 → 5.7, keeping 5.6 payloads backward-compatible).
  • Added SymFloat + operator.truediv (along with operator.neg and IntTrueDiv/FloatTrueDiv/ToFloat sympy functions) across exir/serde/export_serialize.py (serializer, deserializer, canonicalize) and exir/serde/serialize.py.
  • Added test_etrecord_round_trip_sym_floor_truediv_slice in devtools/etrecord/tests/etrecord_test.py covering x[:math.floor(x.shape[0] / 3)] (Dim("batch", min=6, max=20)) through to_edge(..., generate_etrecord=True).to_executorch() → save() → parse_etrecord(), checking both exported_program and edge_dialect_program return the first 2 rows for 8 input rows (plus additional batch sizes and SymFloat/SymInt metadata), along with expanded SymFloat and 5.6 legacy-payload tests in exir/tests/test_serde.py.

@abaybektursun

Copy link
Copy Markdown
Author

@JakeStevens Updated the branch with c0f9341d69 (merged main, preserving #25823's floordiv/mod zero-divisor and INT64_MIN // -1 fixes inside the shared scalar dispatcher) and 156a540de4 (added SymFloat + operator.truediv serde support and covered x[:math.floor(x.shape[0] / 3)] in the ETRecord and serde round-trip tests).

Verified locally:

  • kernels_prim_ops_test: 30/30 (normal + UBSan), 60/60 selective-build compiles (-Wall -Wextra -Werror), and register_prim_ops.o .text stays -46.9% (arm64) / -29.5% (x86_64) vs main.
  • TestETRecord, TestSerde, TestFakeTensorArtifacts, TestGenMaxKernelNum, and test_emit sym tests: 101/101 passed, plus end-to-end runtime execution of x[:math.floor(x.shape[0] / 3)] across n = 6, 7, 8, 9, 10, 14, 20.

Ready for CI re-approval and another look when you have a moment!

@JakeStevens

Copy link
Copy Markdown
Contributor

thanks for the back and forth.

  1. please drop 672fc85 and just raise the size limit within this PR, I approve that change, it is a small enough delta I don't want to muddy this PR.

  2. Float literals lose precision through serde, so a reloaded program gets the wrong symbolic ranges.

class M(nn.Module):
    def forward(self, x):
        return torch.zeros(math.floor(x.shape[0] * (1 / 3)), 2)

ep = to_edge(export(M(), (torch.randn(9, 4),),
                    dynamic_shapes={"x": {0: Dim("b", min=6, max=30)}})).exported_program()
ld = deserialize(serialize(ep))

Both programs print FloorToInt(0.333333333333333*ToFloat(s77)), but they evaluate differently:

The same applies to the SymInt path at L270/L273, since the float literal sits inside a SymInt expression. Upstream serializes these with sympy.srepr (_print_sympy in torch/_export/serde/serialize.py), which round-trips exactly. Could you do the same here?

f"SymInt has invalid field type {s.type} with value {s.value}"
)

def _add_float_var_to_val(self, sym: sympy.Symbol, hint: float) -> None:

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.

The hasattr checks for backed_var_to_val and name_to_symbol and the direct writes into those ShapeEnv dicts depend on private torch internals. The SymInt path next to this just calls self.shape_env.add_var_to_val(sym, hint). Could the float path use the same API, or something equally public?

This branch has not been deployed

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

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. community: contribution PRs coming from community (excluding hardware partners) release notes: ops & kernels Changes to the opset and any new / changed kernel implementations

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support math.floor on symbolic scalars (executorch_prim::floor.Scalar)

2 participants