Skip to content

Do signed integer negation, abs and pow in unsigned types on the CPU - #42

Merged
jjang-ai merged 2 commits into
osaurus-ai:mainfrom
rcfa:fix/unary-overflow-wrap
Nov 22, 2026
Merged

jjang-ai merged 2 commits into
osaurus-ai:mainfrom
rcfa:fix/unary-overflow-wrap

Conversation

@rcfa

@rcfa rcfa commented Nov 3, 2026 •

Copy link
Copy Markdown

Stacked on #39 (fix/signed-overflow-wrap), whose wrapping() helper it uses; its first commit is #39's. Both are on main 3b39b5e. This PR and #43 both add a test case after #39's in tests/ops_tests.cpp, so whichever merges second needs that hunk rebased, keeping both cases.

Problem

Signed integer overflow is undefined behavior in C++. Three scalar operations of Simd<T, 1> in mlx/backend/cpu/simd/base_simd.h can trigger it: unary minus (std::negate) and abs (std::abs) at INT_MIN / INT64_MIN, and the integer pow, whose products res *= base and base *= base overflow int32 and int64 when the power does not fit. The last squaring of the base is computed even when the result does not need it, so pow(100000, 1) overflowed int32 with a result that fits. uint16 operands are promoted to int, so 65535 * 65535 overflowed in pow too. On Linux every unary and binary op goes through these scalar functions (max_size<T> is 1); on macOS they run the scalar tails of the vector loops and the JIT preamble.

A UBSan build (-DUSE_UBSAN=ON, Debug) reports, with GCC 12.2 (clang 21 reports the same sites with other columns, and the uint16 pow at the squaring):

stl_function.h:332:33: runtime error: negation of -2147483648 cannot be represented in type 'int'      (negative, from base_simd.h:86)
base_simd.h:111:29: runtime error: negation of -2147483648 cannot be represented in type 'int'          (abs, int32)
std_abs.h:56:44: runtime error: negation of -9223372036854775808 cannot be represented in type 'long int'  (abs, int64)
base_simd.h:313:13: runtime error: signed integer overflow: -501334399 * 6561 cannot be represented in type 'int'   (res *= base)
base_simd.h:316:12: runtime error: signed integer overflow: 43046721 * 43046721 cannot be represented in type 'int'  (base *= base)

No test case of the existing suite reaches any of these lines: the UBSan list of the whole suite (19 lines with GCC, 45 with clang) is identical before and after this change.

The semantics are the two's complement ones, as in numpy and in Metal: -MIN = MIN, abs(MIN) = MIN, and an integer power is the exact power modulo 2^N. Measured with the mlx 0.32.3 wheel and numpy 2.5.4 on a Mac against Python integers reduced modulo 2^N: negative of every int8 / int16 / uint8 / uint16 value, abs of every int8 / int16 value, the powers of every int8 / uint8 base with every exponent, every int16 / uint16 base with exponents 0 to 64, and boundary plus random values for 32 and 64 bit, on numpy, the Metal GPU stream and the CPU stream of the wheel: 0 mismatches in all 25 op / dtype cells and all three implementations (65,538 to 4,259,848 elements per 16-bit cell). The values the CPU stores were already the wrapped ones on arm64 and x86-64 in every build I ran; what the undefined behavior changed is what the compiler is allowed to do with the result.

That is visible in compiled kernels. compile() builds its fused kernels with g++ -std=c++17 -O3 (jit_compiler.cpp), and with GCC 12 the comparisons abs(x) < 0, abs(x) >= 0, -x > 0, -x < 0 and -x == x inside one fused kernel are folded as if x could never be INT_MIN: they gave the wrong answer at INT_MIN for int32 and int64 (101 of 1003 elements wrong in each form with boundary values at every position; no sanitizer involved). The same kernel loops built with clang 21 -O3 (on macOS g++ is Apple clang; the compiled test, on the CPU, passes there with this change, see Verification) are wrong in seven forms: those five, abs(x) == x, and astype(abs(x), int64) for int32, which returns +2147483648 for INT_MIN (and one element of astype(negative(x), int64)). After this change all of them give the wrapped answer in both compilers.

Fix

wrapping() and WRAPPING_BINARY, added by #39, already do +, - and * in the unsigned type of the result. This change uses the same helper: unary minus becomes 0 - x through wrapping() for integer types and is the original std::negate{}(x) otherwise; abs returns x < 0 ? -x : x for signed integers (unsigned and floating point as before); in pow the two products go through wrapping() (the squaring after the last needed bit may wrap now instead of being undefined). The early return of 0 for a negative exponent is unchanged. Float, float16, bfloat16, complex64, bool and unsigned code is untouched. The two unary functions moved below wrapping() in the file, which keeps the previous change out of this diff.

The JIT needs no separate change: compiled_preamble.h includes unary_ops.h and binary_ops.h, and make_compiled_preamble.sh preprocesses them (and so base_simd.h) at build time. accelerate_simd.h (macOS only) is not changed: its operator- and pow are arithmetic on clang ext_vector_type values, which has no overflow assumption (a Linux stand-in with the same attribute, clang 21 -fsanitize=signed-integer-overflow, -O0 and -O3: -MIN and the powers 3^40, 100000^1, (-2)^31 etc. give the wrapped values, no report); its abs is Apple's simd_abs, whose integer implementation I could not read. On macOS the eager case below, whose arrays are longer than those vector loops, passes on the CPU, and UBSan reports nothing in accelerate_simd.h (see Verification).

Not in this PR

  • ops.cpp:6390, int n = a_size + std::abs(k) with the user's int diagonal offset k: undefined for INT_MIN, but an argument of the op and not array arithmetic.
  • The other overflow sites that the same probes report (shifts by a count out of range, INT_MIN / -1 and INT_MIN % -1, divmod, cumsum / cumprod, scatter, arange) are separate changes.

Verification

On main 3b39b5e, with the previous change (#39) below this one:

  • GCC 12 Debug + UBSan, arm64 Linux: 287 | 286 passed | 1 failed, 4141 | 4140 passed | 1 failed. The one failure is main's own test one-bit affine endpoints CPU GPU and small-K dispatch, which requires a GPU. The runtime error: list is the previous change's 19 lines (main's 20 minus base_simd.h:181:1). The two new cases alone exit 0 with halt_on_error=1 (30 and 12 assertions). With this change's base_simd.h reverted, the compiled case fails 12 | 2 passed | 10 failed, with no sanitizer report.
  • x86-64 (GCC 12 Debug, Rosetta): the compiled case passes, 12 | 12.
  • macOS 27.2 (AppleClang 21, M4 Max), Release with Metal: 323 | 323 passed with DEVICE=cpu; with Metal 323 | 322 passed | 1 failed, the one failure being main's intermittent test concurrent allocator statistics (Synchronize streams before the allocator statistics baseline #33 fixes it). The two new cases pass on Metal too, the compiled one through the CPU JIT (12 | 12), and alone on both devices.
  • macOS Debug + UBSan: 323 | 323 passed on both devices. The sites on cpu are main's 59 minus base_simd.h:181 (58), as with the previous change alone; on Metal they are main's 55. Nothing is added, nothing is reported in accelerate_simd.h, and the stack's three new cases alone report nothing on either device (with halt_on_error=1 and suppressions for main's Metal start-up sites, which stop every process otherwise).
  • The compiled case runs on the CPU (StreamContext sc(Device::cpu)), so that compile() builds its kernels with the CPU JIT also where the default device is a GPU. On a Mac's GPU, the fused Metal kernel gets the three -x comparisons wrong at MIN, for int32 and int64, on main too: its results are those of x < 0, x > 0 and x == 0, as if x could never be MIN. The abs comparisons and the eager Metal ops are right. This PR does not change the GPU.
  • The diff on top of the previous change applies to ml-explore/main c69303b00 (git apply --cached --check on a temporary index that holds the previous change).

The rest was measured before the rebase, on the fork's previous main 4a22e4f (the patch is the same, except that the compiled case now runs on the CPU), with GCC 12.2 and clang 21 in aarch64 Linux containers and GCC 12.2 in an x86-64 container (Rosetta).

  • Full suite, GCC Debug, no sanitizer: [doctest] test cases: 283 | 283 passed | 0 failed | 0 skipped, [doctest] assertions: 4140 | 4140 passed | 0 failed. Without the two new cases: 281 | 281, 4098 | 4098. x86-64: the same counts. clang 21 (UBSan build): 283 | 266 passed | 17 failed: the 16 test compile ... cases that this clang setup cannot JIT with and without the change, plus the new compiled case for the same reason; the new eager case passes (30 | 30).

  • UBSan, GCC Debug, halt_on_error=0: the sorted, address-normalised list of runtime error: lines is the same 19 lines before and after, with and without the new tests; 283 processes, one case each, none reports base_simd.h, stl_function.h or std_abs.h. clang 21: the same 45 lines. The new eager case alone with halt_on_error=1: exit 0 in both compilers.

  • A probe, one process per call (UBSan reports a site once per process), 34 calls: before the change 19 reports at the five sites above, plus the same sites through the strided, sliced, 0-d and scalar paths; none for int8 / int16 / unsigned negation, abs and pow, negative exponents, float or complex; after the change 0 reports.

  • Values: a standalone program (not included) checks negative, abs (signed) and power for all eight integer dtypes against a reference computed in uint64_t arithmetic (negation and abs as 0 - x; the power by repeated multiplication up to exponent 200, cross-checked against square-and-multiply: 9.5 million products, 0 differences): every value of the 8 and 16 bit types for negative and abs, every base times every exponent for int8 and uint8, every base times 76 exponents for int16 and uint16, boundary and random values for 32 and 64 bit, contiguous arrays of length 1 to 1003, a transposed input, a stride-2 slice, a broadcast row, 0-d arrays, scalar-array and array-scalar power: CHECKED checked=11135864 bad=0 before and after, in GCC and clang, Debug (with UBSan) and Release, and on x86-64. The arrays are byte-identical before and after in all of them (one case differs in the clang Release build before the change: Simd<int, 1> abs(INT_MIN) widened inline, see above). The compile()d forms: GCC FUSED checked=20060 bad=150 before, bad=0 after, on arm64 and on x86-64.

  • Regression tests (tests/ops_tests.cpp, after "test integer arithmetic wraps around"), expected values computed with Python integers: "test integer unary ops and pow wrap around" (30 assertions: negative and abs for int8 to uint64, power for all eight dtypes, each table longer than the widest SIMD loop, a stride-2 slice, 0-d INT_MIN, scalar-array and array-scalar) and "test compiled integer unary ops wrap around" (12 assertions: the five comparison forms, each in its own fused kernel, int32 and int64). Without the fix: the first case passes in a normal build and fails under UBSan (halt_on_error=1: exit 1, first report stl_function.h:332:33; 8 distinct report lines); the second fails in a normal GCC build with no sanitizer: 12 | 2 passed | 10 failed (arm64 and x86-64), and it is blind to UBSan because the JIT object is not instrumented. Each change reverted on its own (GCC Debug UBSan, one build per row):

    change reverted eager case, halt_on_error=1 (lines of the changed file) compiled case
    operator- exit 1, stl_function.h:332:33 10 failed
    abs exit 1, base_simd.h:232:29 4 failed
    res *= base exit 1, base_simd.h:329:13 ... -501334399 * 6561 passes
    base *= base exit 1, base_simd.h:332:12 ... 43046721 * 43046721 passes
    all four exit 1, stl_function.h:332:33 10 failed

    Three mutants that break the value instead (negative returns x, abs negates the positives, pow never squares the base) fail 14, 5 and 10 assertions of the eager case. In a clang build the compiled case fails like the other test compile ... cases (Failed to compile function); the eager case is independent of the JIT.

  • Speed, Release, GCC 12.2 and clang 21: negative, abs, power on int32 and int64, n = 1e3, 1e6, 1e7; the raw CPU loops (the contiguous loop of unary_op; VectorVector / ScalarVector / VectorScalar<detail::Power> with exponents 0 to 15 and with random exponents over the whole range) and the whole op (negative(a) + eval, ...). 72 numbers per compiler, each the minimum of 15 repetitions, old and new built from the same tree with and without the change. Noise thresholds first, from old against old (5 runs, then 5 interleaved runs): the raw loops 3.0 % at n = 1e3, 5.8 % (GCC) / 12.0 % (clang) at n = 1e6, 6.3 % at n = 1e7; the whole op 3.9 % / 6.2 % at n = 1e6 and 14.1 % / 11.5 % at n = 1e7. New against old, minimum of 5 against minimum of 5: GCC 70 of 72 within their threshold (raw loops 0.951 to 1.023, the power loops 0.968 to 1.023), two flagged (a whole-op benchmark at n = 1e3 and abs int32 at n = 1e6); clang 67 of 72 (raw power loops 0.981 to 1.021), five flagged (raw negative / abs loops, int32 and int64, at n = 1e6 and n = 1e7: 1.06 to 1.31, and one whole-op abs). In clang the machine code of all four unary loops is identical before and after (35, 34, 35, 34 instructions), so those are noise; ten more alternating pairs of the unary benchmarks with a rule fixed beforehand (flagged only if the minimum ratio exceeds the threshold and the median ratio exceeds half of it) leave none flagged in either compiler. In GCC negative and the power loops are the same code; GCC 12 does not turn x < 0 ? -x : x (through the unsigned negate) into abs, so the vector body of abs is neg + cmge + bsl (5 instructions per vector) instead of abs (3), which the load / store traffic of the loop hides (raw abs / negative ratios 0.951 to 1.010).

  • Earlier, on ml-explore/main 1ba7f969a: the diff on top of the previous change applied (the two diffs with offsets of 23 and 108 lines), and was built there with GCC 12.2 and clang 21 under UBSan: 279 | 279 passed, 4489 | 4489 passed (GCC), the two new cases 30 | 30 and 12 | 12 with halt_on_error=1 exit 0; with this change's source reverted the new cases fail as above (4489 | 4479 passed | 10 failed).

🤖 Generated with Claude Code

rcfa added 2 commits November 3, 2026 12:27
… CPU

Signed integer overflow is undefined behavior in C++, but the scalar
operators of Simd<T, 1> (DEFAULT_BINARY in simd/base_simd.h) computed
a.value + b.value directly, so int32 and int64 add, subtract and multiply
overflowed in the compiler's eyes whenever the true result did not fit.
UBSan reports "signed integer overflow: 127 + 2147483647 cannot be
represented in type 'int'" at base_simd.h:181 from three existing test
cases. uint16 * uint16 has the same problem through the promotion to int
(65535 * 65535).

Add WRAPPING_BINARY for +, - and *. When the result type is a signed
integer, the operands are converted to the unsigned type of the same
size, the operation is done there and the result is converted back
(modular since C++20). Other result types and the other operators are
untouched.

Array results are unchanged: add, subtract, multiply and square over a
grid of boundary and random values give the same bytes before and after.
The new test "test integer arithmetic wraps around" fails under UBSan with
halt_on_error=1 when any one of the three operators is reverted.
Signed integer overflow is undefined behavior in C++, and three scalar
operations of Simd<T, 1> in simd/base_simd.h could trigger it:

- unary minus, std::negate, at INT_MIN and INT64_MIN;
- abs, std::abs, at INT_MIN and INT64_MIN;
- the integer pow, whose products "res *= base" and "base *= base"
  overflow int32 and int64 when the power does not fit, and whose last
  squaring of the base is computed even when the result does not need
  it, so pow(100000, 1) overflowed int32 with a result that fits.
  uint16 operands are promoted to int, so 65535 * 65535 overflowed too.

UBSan reports each of them (stl_function.h:332, base_simd.h:111,
std_abs.h:56, base_simd.h:313 and :316). No test case of the suite
reaches them.

Reuse wrapping(), added for add, subtract and multiply: unary minus
becomes 0 - x, abs becomes x < 0 ? -x : x, and the products of pow go
through wrapping() as well. The results are the two's complement ones,
-MIN = MIN, abs(MIN) = MIN and the power modulo 2^N, which is also what
numpy and Metal return. A negative exponent still gives 0. Float,
complex and unsigned paths are unchanged.

The undefined behavior had a visible effect. compile() builds its
kernels with "g++ -std=c++17 -O3", and GCC 12 folds abs(x) < 0,
abs(x) >= 0, -x > 0, -x < 0 and -x == x in a fused kernel as if x
could never be INT_MIN, so these comparisons gave the wrong answer
there; clang 21 does the same and also widens abs(INT_MIN) to +2^31.
The new test "test compiled integer unary ops wrap around" fails on
the old code with GCC without any sanitizer. "test integer unary ops
and pow wrap around" covers every integer dtype at the boundaries, and
the strided, 0-d and broadcast kernels for int32. It fails under UBSan
with halt_on_error=1 when any one of the changes is reverted.

The compiled test runs on the CPU, so that compile() uses the CPU JIT
also where the default device is a GPU.
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