Skip to content

Fix INT_MIN / -1 overflow in portable integer div and floor_divide - #25292

Merged
JakeStevens merged 3 commits into
pytorch:mainfrom
JakeStevens:fix-div-int-min-overflow
Nov 24, 2026
Merged

JakeStevens merged 3 commits into
pytorch:mainfrom
JakeStevens:fix-div-int-min-overflow

Conversation

@JakeStevens

Copy link
Copy Markdown
Contributor

Portable div.out_mode and div.Scalar_mode_out computed val_a / val_b before choosing a rounding mode, and utils::floor_divide divided directly, so int32 or int64 INT_MIN / -1 overflowed and killed the process with SIGFPE on x86. floor_divide now returns the dividend in that case, like ATen's c10::div_floor_integer, and a new utils::trunc_divide does the same for trunc mode, so each mode does only its own division.

While here, fmod.Scalar_out and div.Scalar_mode_out no longer reject an integer zero divisor for an empty input. ATen checks the divisor per element, and remainder.Scalar_out already behaves this way as of #24348.

Fixes #25285.

Test plan

New MostNegativeByMinusOneWraps tests for div (tensor and scalar, trunc and floor) and floor_divide, int32 and int64, plus empty-input zero-divisor tests for fmod and div. arm64 doesn't trap on INT_MIN / -1, so I built Debug with -fsanitize=signed-integer-overflow,integer-divide-by-zero -fno-sanitize-recover=all. All 1919 portable_kernels_test tests pass, and the div, floor_divide, fmod and remainder tests pass in optimized_kernels_test. With only the kernel sources reverted to main, the new tests trip UBSan at op_div.cpp (both overloads) and math_util.h.

This PR was authored with AI assistance (Claude Code).

Portable div.out_mode and div.Scalar_mode_out computed val_a / val_b before
choosing a rounding mode, and utils::floor_divide divided directly, so int32
or int64 INT_MIN / -1 overflowed and killed the process with SIGFPE on x86.
floor_divide now returns the dividend in that case, like ATen's
c10::div_floor_integer, and a new utils::trunc_divide does the same for trunc
mode, so each mode does only its own division.

While here, fmod.Scalar_out and div.Scalar_mode_out no longer reject an
integer zero divisor for an empty input. ATen checks the divisor per element,
and remainder.Scalar_out already behaves this way as of pytorch#24348.

Fixes pytorch#25285.

This change was authored with AI assistance (Claude Code).
@pytorch-bot

pytorch-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit b282fcc with merge base 729de6f (image):
💚 Looks good so far! There are no failures yet. 💚

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 19, 2026
@JakeStevens

Copy link
Copy Markdown
Contributor Author

@claude review effort:max

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Claude finished @JakeStevens's task in 4m 3s —— View job


The portable kernel fix looks right, but the new div mode tests in the shared kernels/test/op_div_test.cpp won't build for the Buck optimized target, and the forked Cadence div kernels still have the same INT_MIN / -1 crash.

Detailed review

PR Review: #25292

Summary

The PR adds INT_MIN / -1 guards to portable div (trunc and floor modes) and to utils::floor_divide, and lets the scalar fmod/div kernels accept a zero divisor when the input is empty. There is one confirmed build break for the Buck optimized test target. There is also an unfixed copy of the same bug in the Cadence kernels, and a "like ATen" claim I couldn't verify.

Infrastructure

  • Blocker: the new mode tests are in a shared test file, and the optimized kernel library doesn't provide the mode ops.
    • What breaks: the new tests and helpers at kernels/test/op_div_test.cpp:35-55, :224-245 and :653-671 call div_outf(context_, a, b, mode, out), which means div.out_mode and div.Scalar_mode_out. This file is built as ["aten", "portable", "optimized"] (kernels/test/targets.bzl:256). The optimized variant includes FunctionHeaderWrapper.h, which resolves to the header generated from kernels/optimized/optimized.yaml. That yaml only declares div.out and div.Scalar_out (lines 45-53), so the mode overloads are not declared there, and optimized_op_div_test fails to compile.
    • Why it passed for you: your CMake run of optimized_kernels_test links the portable fallbacks, so it doesn't catch this.
    • Existing pattern: before this PR, the shared file never called a mode variant. Mode tests live in kernels/portable/test/op_div_test.cpp, for example SanityCheckModeTrunc, TruncModeKeepsInt64Precision and ModeIntegerScalarIsCastToTensorDtype. That file includes kernels/portable/Functions.h directly.
    • Fix: move OpDivOutTest.MostNegativeByMinusOneWraps, OpDivScalarOutTest.MostNegativeByMinusOneWraps and EmptyInputWithZeroScalarDivisor into the portable test file.
    • Fix this →

Code Quality

  • Major: the forked Cadence div kernels still divide before checking the mode.
    • Where: backends/cadence/hifi/operators/op_div.cpp:326 and backends/cadence/fusion_g3/operators/op_div.cpp:453 and :699. These are copies of the old portable code. They compute CTYPE_COMPUTE value = val_a / val_b; before picking a rounding mode, so they still hit the INT_MIN / -1 undefined behaviour (SIGFPE on an x86 host build). Their later floor_divide call does pick up your new guard, but that doesn't help because the plain division runs first.
    • Also out of sync: their scalar-mode zero checks (hifi :321, g3 :448) don't have the new a.numel() > 0 condition, so their empty-input behaviour now differs from portable.
    • Suggestion: apply the same trunc_divide/floor_divide swap there, or at least list them in Portable integer div(rounding_mode="floor") aborts the process on INT_MIN / -1 #25285 as still affected.
  • Minor: trunc_divide doesn't follow the style of its neighbours. In kernels/portable/cpu/util/math_util.h:76-90 it is a single unconstrained template <typename T> that branches with if constexpr. floor_divide, remainder_override and fmod_override in the same file are pairs of overloads constrained by enable_if on integral vs. floating types. Splitting trunc_divide the same way would match the file.

Testing

  • Low confidence, please check: ATen parity and the aten test variants.
    • The concern: op_div_test and op_floor_divide_test also build aten targets (targets.bzl:256, :275), and the new MostNegativeByMinusOneWraps tests have no SupportedFeatures::get()->is_aten skip. As I remember it, ATen's integer div_trunc kernel is a plain a / b. I also recall that c10::div_floor_integer only special-cases operands with different signs and otherwise returns a / b. In that case ATen also traps on INT_MIN / -1. That would contradict the "Like ATen" comments (math_util.h:37-38, :80-81) and the PR description, and the aten_* tests would crash with SIGFPE on x86.
    • Why it's low confidence: I couldn't read the PyTorch source in this environment. The existing OpRemainderOutTest.MostNegativeByMinusOneIsZero (op_remainder_test.cpp:97) also runs unskipped on ATen, so you may already know this works.
    • To settle it: run torch.tensor([-2**31], dtype=torch.int32).div(-1, rounding_mode='floor') on x86, plus the trunc and floor_divide variants.
    • If ATen traps: add the is_aten skip, and change the comments to say the kernel defines the result rather than matching ATen.

Recommendation

Request Changes: move the mode tests out of the shared test file so the Buck optimized target builds. I'd also fix the Cadence copies (or track them in #25285), and confirm the ATen claim.

@JakeStevens

Copy link
Copy Markdown
Contributor Author

@x0w3n please see if this fixes your issue

The shared kernels/test/op_div_test.cpp also builds against the optimized
kernels, whose generated header doesn't declare div.out_mode or
div.Scalar_mode_out, so the Buck optimized_op_div_test failed to compile. The
new mode tests now sit next to the existing ones in
kernels/portable/test/op_div_test.cpp.

utils::trunc_divide is split into integral and floating overloads like its
neighbours, and its comment no longer implies ATen parity: ATen's integer
trunc kernel overflows on INT_MIN / -1.

This change was authored with AI assistance (Claude Code).
@x0w3n

x0w3n commented Nov 22, 2026

Copy link
Copy Markdown

@x0w3n please see if this fixes your issue

Thanks.

I built the wheel from this branch (a9a575f) and re-ran my repro. The SIGFPE is gone for int32/int64, floor/trunc, tensor/scalar and broadcast inputs, and normal inputs still give the expected results.

Confirmed fixed on my side.

@JakeStevens

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude finished @JakeStevens's task in 3m 49s —— View job


The portable kernel fix is correct, and moving the div mode tests fixed the Buck optimized build. Two problems remain: the shared floor_divide test may crash the ATen variant (the "like ATen" claim is probably wrong), and the Cadence div copies still have the same INT_MIN / -1 crash.

Detailed review

PR Review: #25292

Summary

The PR guards INT_MIN / -1 in portable div (trunc and floor modes) and in utils::floor_divide. It also lets the scalar fmod and div kernels accept a zero divisor when the input is empty. One possible ATen test crash is still open from the last review (I couldn't confirm it), and the forked Cadence kernels and the prim ops still divide without the guard.

Infrastructure

  • Major (suspected, all 3 reviewers): the new shared floor_divide test probably crashes the ATen test build.
    • Where: kernels/test/op_floor_divide_test.cpp:404 (MostNegativeByMinusOneWraps).
    • Why it runs under ATen: the test file is built for ["aten", "portable"] (kernels/test/targets.bzl:275), and the test has no is_aten skip.
    • Why it would crash: as far as we recall, c10::div_floor_integer only takes its special path when signs_differ(a, b). INT_MIN and -1 have the same sign, so it falls through to a plain a / b, which raises SIGFPE on x86.
    • Stale comment: if that's right, the "Like ATen" comment at kernels/portable/cpu/util/math_util.h:37-38 and the same claim in the PR description are wrong. They also contradict the new trunc_divide comment at math_util.h:81-82, which says ATen overflows. The second commit moved only the div mode tests to the portable-only file. floor_divide didn't get the same treatment.
    • Why OSS CI won't catch it: the ATen variant is Buck-only.
    • Why this is low confidence: the PyTorch source wasn't available here. Also, the existing OpRemainderOutTest.MostNegativeByMinusOneIsZero (kernels/test/op_remainder_test.cpp:97) already runs INT_MIN % -1 on ATen without a skip. It's worth checking whether that test actually passes on the ATen target before treating it as precedent.
    • To settle it: run torch.floor_divide(torch.tensor([-2**31], dtype=torch.int32), -1) on x86.
    • If it traps: add ET_SKIP_IF(SupportedFeatures::get()->is_aten, ...) or move the test into a portable-only test file. Then reword the floor_divide comment to say the kernel defines this result, rather than matching ATen.
    • Fix this →

Code Quality

  • Major (confirmed, all 3 reviewers): the forked Cadence div kernels still divide before checking the mode.
    • Where: backends/cadence/hifi/operators/op_div.cpp:326, and backends/cadence/fusion_g3/operators/op_div.cpp:453 and :699.
    • Problem: each one still computes CTYPE_COMPUTE value = val_a / val_b; before choosing trunc or floor. The new guard inside utils::floor_divide never gets a chance to run, so int32 INT_MIN / -1 through div.out_mode or div.Scalar_mode_out on these backends still hits undefined behaviour.
    • Also out of sync: their scalar zero-divisor checks (hifi :321, g3 :448 and :688) don't have the new a.numel() > 0 condition, so their empty-input behaviour now differs from portable.
    • Fix: switch them to utils::trunc_divide / utils::floor_divide as well, or track them in Portable integer div(rounding_mode="floor") aborts the process on INT_MIN / -1 #25285.
    • Fix this →
  • Minor (confirmed, 1 reviewer): the prim ops have the same INT64_MIN / -1 pattern.

Recommendation

Needs Discussion: confirm how ATen behaves for floor_divide(INT_MIN, -1). If it traps, gate the shared test and fix the comment. I'd also bring the Cadence copies in line, or track them in #25285.

@JakeStevens JakeStevens added the release notes: ops & kernels Changes to the opset and any new / changed kernel implementations label Nov 23, 2026
@JakeStevens

Copy link
Copy Markdown
Contributor Author

On the second review:

  • OpFloorDivideTest.MostNegativeByMinusOneWraps under ATen: no skip needed. ATen's floor_divide_out dispatches to div_floor_stub; its integral CPU path calls c10::div_floor_integer, which special-cases this before dividing (c10/util/generic_math.h):

    if (C10_UNLIKELY(
            std::is_signed<scalar_t>::value &&
            a == std::numeric_limits<scalar_t>::min() && b == scalar_t(-1))) {
      return a;
    }

    The guard landed in torch 2.10 (it's absent through v2.9.0, which matches the reviewer's recollection), and ExecuTorch pins 2.14, so the "Like ATen" comment on floor_divide holds for supported torch versions.

    Verified on x86 (via Rosetta, where INT_MIN / -1 traps; arm64 sdiv doesn't):

    • c10::div_floor_integer from the torch 2.14 headers, compiled for x86_64: returns INT_MIN for int32 and int64; a plain a / b in the same binary dies with SIGFPE.
    • torch 2.2.2 (the last macOS x86_64 wheel, no guard): floor_divide, div(rounding_mode="floor") and div(rounding_mode="trunc") all die with SIGFPE, for int32/int64, tensor and scalar divisors.
    • kernels/test/op_floor_divide_test.cpp built in ATen mode (USE_ATEN_LIB) against arm64 libtorch 2.14: all tests pass, including MostNegativeByMinusOneWraps (this checks the value; the x86 checks above cover the trap).

    Trunc is the one that still differs: ATen's integer div_trunc_kernel is a plain a / b even on main, which is why the trunc tests live only in the portable test file and trunc_divide's comment no longer claims parity.

  • Cadence copies: tracked separately, not in this PR.

  • Prim ops floordiv/mod: out of scope here. They operate on symbolic sizes, where INT64_MIN / -1 isn't realistic; the more relevant gap there is the missing zero-divisor check. I'll handle that in a follow-up.

The Android emulator failure is a boot timeout, unrelated to this change.

@JakeStevens
JakeStevens merged commit dae52e3 into pytorch:main Nov 24, 2026
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. 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.

Portable integer div(rounding_mode="floor") aborts the process on INT_MIN / -1

4 participants