Repository navigation
Add floor.Scalar prim op for symbolic math.floor - #25773
abaybektursun wants to merge 5 commits into
Conversation
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.
|
@pytorchbot label "release notes: ops & kernels" |
🔗 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 ( 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. |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
| _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, |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Addressed in f0bc506d1a:
- Added
math.floorto_SYM_INT_OPS, added"math."resolution inGraphModuleDeserializer.deserialize_operator, and addedFloorToInttosympy.sympifylocals inexir/serde/export_serialize.py(soFloorToInt(...)expressions deserialize astorch.utils._sympy.functions.FloorToIntrather than an undefined sympy function). - Added
test_etrecord_round_trip_sym_floorindevtools/etrecord/tests/etrecord_test.pycoveringx + math.floor(x.shape[0])with a dynamic first dimension (generate_etrecord=True->save()->parse_etrecord(), checking graph closeness,math.floor/SymIntexpr type, and numerical execution for both exported and edge graphs), plustest_sym_floor_round_tripinexir/tests/test_serde.py.
| out = EValue(static_cast<int64_t>(val)); | ||
| } else if (a.isInt()) { | ||
| out = EValue(a.toInt()); | ||
| } else { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Addressed in f0bc506d1a:
- Added
else if (a.isBool()) { out = EValue(static_cast<int64_t>(a.toBool())); }toexecutorch_prim::floor.Scalarmatchingsym_int.Scalar. - Added
false -> 0andtrue -> 1checks (verifyingTag::Intoutput) inTestFloorand switchedTestFloorInvalidInputstoEValue()(None) to exerciseError::InvalidType(verified with normal and UBSankernels_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).
|
Thanks for the review @JakeStevens! Both review items are addressed in |
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.
|
Quick follow-up in Rather than bumping the threshold in Local verification on
@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]) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Good catch — fixed in 156a540de4:
- Added
SymFloat,SymFloatArgument,Argument.as_sym_float(s), and defaultedGraph.sym_float_valuesinexir/serde/schema.py(minor bump5.6→5.7, keeping5.6payloads backward-compatible). - Added
SymFloat+operator.truediv(along withoperator.negandIntTrueDiv/FloatTrueDiv/ToFloatsympy functions) acrossexir/serde/export_serialize.py(serializer, deserializer,canonicalize) andexir/serde/serialize.py. - Added
test_etrecord_round_trip_sym_floor_truediv_sliceindevtools/etrecord/tests/etrecord_test.pycoveringx[:math.floor(x.shape[0] / 3)](Dim("batch", min=6, max=20)) throughto_edge(..., generate_etrecord=True).to_executorch()→save()→parse_etrecord(), checking bothexported_programandedge_dialect_programreturn the first 2 rows for 8 input rows (plus additional batch sizes andSymFloat/SymIntmetadata), along with expandedSymFloatand5.6legacy-payload tests inexir/tests/test_serde.py.
# Conflicts: # kernels/prim_ops/register_prim_ops.cpp
|
@JakeStevens Updated the branch with Verified locally:
Ready for CI re-approval and another look when you have a moment! |
|
thanks for the back and forth.
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: |
There was a problem hiding this comment.
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?
Summary
Fixes #25772
torch._export.verifier.Verifier.allowed_builtin_opsallows all four rounding builtins (math.ceil,math.floor,math.trunc,round), butmath.flooris missing from_PYTHON_SYM_OPS_TO_EXECUTORCH_SYM_OPS. BecauseEdgeToBackendOpsPassleaves it unrewritten,ToOutVarPassfails withAttributeError: 'builtin_function_or_method' object has no attribute '_schema'.This registers
executorch_prim::floor.Scalarand adds the C++ prim kernel behindINCLUDE_EXECUTORCH_PRIM_FLOOR_SCALAR. OnDoubleinputs it checks thatstd::floor(x)falls in[-2^63, 2^63)before casting toint64_t(failing withInvalidArgumentrather than UB), and passesIntthrough unchanged since PyTorch'sSymNodetracing can emitmath.flooron aSymInt. 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) inkernels/prim_ops/test/prim_ops_test.cppand an end-to-end emit/runtime test (test_emit_sym_floor, covering positive and negative symbolic floor) inexir/emit/test/test_emit.py.Built with
-DEXECUTORCH_BUILD_TESTS=ON(and also with-DCMAKE_CXX_FLAGS="-fsanitize=address,undefined"):28 tests passed.
With
portable_librebuilt from this branch:pytest exir/emit/test/test_emit.py -k "test_emit_sym_"5 tests passed, and the 8-row
Dim.AUTOXnnpackPartitionerrepro from the issue matches eager for rows 2..8.cc @nil-is-all