Repository navigation
Do signed integer negation, abs and pow in unsigned types on the CPU - #42
Merged
Merged
Conversation
… 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.
This was referenced Nov 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #39 (
fix/signed-overflow-wrap), whosewrapping()helper it uses; its first commit is #39's. Both are onmain3b39b5e. This PR and #43 both add a test case after #39's intests/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>inmlx/backend/cpu/simd/base_simd.hcan trigger it: unary minus (std::negate) andabs(std::abs) atINT_MIN/INT64_MIN, and the integerpow, whose productsres *= baseandbase *= baseoverflow 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, sopow(100000, 1)overflowed int32 with a result that fits. uint16 operands are promoted toint, so65535 * 65535overflowed inpowtoo. 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 uint16powat the squaring):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 withg++ -std=c++17 -O3(jit_compiler.cpp), and with GCC 12 the comparisonsabs(x) < 0,abs(x) >= 0,-x > 0,-x < 0and-x == xinside one fused kernel are folded as ifxcould never beINT_MIN: they gave the wrong answer atINT_MINfor 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 macOSg++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, andastype(abs(x), int64)for int32, which returns+2147483648forINT_MIN(and one element ofastype(negative(x), int64)). After this change all of them give the wrapped answer in both compilers.Fix
wrapping()andWRAPPING_BINARY, added by #39, already do+,-and*in the unsigned type of the result. This change uses the same helper: unary minus becomes0 - xthroughwrapping()for integer types and is the originalstd::negate{}(x)otherwise;absreturnsx < 0 ? -x : xfor signed integers (unsigned and floating point as before); inpowthe two products go throughwrapping()(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 belowwrapping()in the file, which keeps the previous change out of this diff.The JIT needs no separate change:
compiled_preamble.hincludesunary_ops.handbinary_ops.h, andmake_compiled_preamble.shpreprocesses them (and sobase_simd.h) at build time.accelerate_simd.h(macOS only) is not changed: itsoperator-andpoware arithmetic on clangext_vector_typevalues, which has no overflow assumption (a Linux stand-in with the same attribute, clang 21-fsanitize=signed-integer-overflow,-O0and-O3:-MINand the powers3^40,100000^1,(-2)^31etc. give the wrapped values, no report); itsabsis Apple'ssimd_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 inaccelerate_simd.h(see Verification).Not in this PR
ops.cpp:6390,int n = a_size + std::abs(k)with the user'sintdiagonal offsetk: undefined forINT_MIN, but an argument of the op and not array arithmetic.INT_MIN / -1andINT_MIN % -1,divmod,cumsum/cumprod, scatter,arange) are separate changes.Verification
On
main3b39b5e, with the previous change (#39) below this one:287 | 286 passed | 1 failed,4141 | 4140 passed | 1 failed. The one failure ismain's owntest one-bit affine endpoints CPU GPU and small-K dispatch, which requires a GPU. Theruntime error:list is the previous change's 19 lines (main's 20 minusbase_simd.h:181:1). The two new cases alone exit 0 withhalt_on_error=1(30 and 12 assertions). With this change'sbase_simd.hreverted, the compiled case fails12 | 2 passed | 10 failed, with no sanitizer report.12 | 12.323 | 323 passedwithDEVICE=cpu; with Metal323 | 322 passed | 1 failed, the one failure beingmain's intermittenttest 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.323 | 323 passedon both devices. The sites on cpu aremain's 59 minusbase_simd.h:181(58), as with the previous change alone; on Metal they aremain's 55. Nothing is added, nothing is reported inaccelerate_simd.h, and the stack's three new cases alone report nothing on either device (withhalt_on_error=1and suppressions formain's Metal start-up sites, which stop every process otherwise).StreamContext sc(Device::cpu)), so thatcompile()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-xcomparisons wrong at MIN, for int32 and int64, onmaintoo: its results are those ofx < 0,x > 0andx == 0, as ifxcould never be MIN. Theabscomparisons and the eager Metal ops are right. This PR does not change the GPU.c69303b00(git apply --cached --checkon a temporary index that holds the previous change).The rest was measured before the rebase, on the fork's previous
main4a22e4f (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 16test 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 ofruntime error:lines is the same 19 lines before and after, with and without the new tests; 283 processes, one case each, none reportsbase_simd.h,stl_function.horstd_abs.h. clang 21: the same 45 lines. The new eager case alone withhalt_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) andpowerfor all eight integer dtypes against a reference computed inuint64_tarithmetic (negation and abs as0 - 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-scalarpower:CHECKED checked=11135864 bad=0before 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). Thecompile()d forms: GCCFUSED checked=20060 bad=150before,bad=0after, 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-dINT_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 reportstl_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):halt_on_error=1(lines of the changed file)operator-stl_function.h:332:33absbase_simd.h:232:29res *= basebase_simd.h:329:13 ... -501334399 * 6561base *= basebase_simd.h:332:12 ... 43046721 * 43046721stl_function.h:332:33Three 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 othertest compile ...cases (Failed to compile function); the eager case is independent of the JIT.Speed, Release, GCC 12.2 and clang 21:
negative,abs,poweron int32 and int64, n = 1e3, 1e6, 1e7; the raw CPU loops (the contiguous loop ofunary_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, thepowerloops 0.968 to 1.023), two flagged (a whole-op benchmark at n = 1e3 andabsint32 at n = 1e6); clang 67 of 72 (rawpowerloops 0.981 to 1.021), five flagged (rawnegative/absloops, int32 and int64, at n = 1e6 and n = 1e7: 1.06 to 1.31, and one whole-opabs). 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 GCCnegativeand thepowerloops are the same code; GCC 12 does not turnx < 0 ? -x : x(through the unsigned negate) intoabs, so the vector body ofabsisneg+cmge+bsl(5 instructions per vector) instead ofabs(3), which the load / store traffic of the loop hides (rawabs/negativeratios 0.951 to 1.010).Earlier, on
ml-explore/main1ba7f969a: 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 cases30 | 30and12 | 12withhalt_on_error=1exit 0; with this change's source reverted the new cases fail as above (4489 | 4479 passed | 10 failed).🤖 Generated with Claude Code