Skip to content

Sum long float rows in blocks on the CPU - #34

Merged
jjang-ai merged 2 commits into
osaurus-ai:mainfrom
rcfa:fix/cpu-cascade-sum
Nov 22, 2026
Merged

jjang-ai merged 2 commits into
osaurus-ai:mainfrom
rcfa:fix/cpu-cascade-sum

Conversation

@rcfa

@rcfa rcfa commented Oct 30, 2026

Copy link
Copy Markdown

What fails

Without Highway, the CPU sums a long float row with a single running sum, or one per SIMD lane for a contiguous row (8 lanes for float32 with Accelerate, 1 on Linux). Each new element meets an ever larger sum and loses its low bits, so the error grows with the row. A sum of 0.375s stops growing at 2^23. Line numbers in this section are at main = 4a22e4fed.

  • mlx/backend/cpu/reduce.cpp:
    • contiguous_reduce (:110-124): lanes from init, then *accumulator = op(*accumulator, op(accumulator_v)) (:119) and the tail into *accumulator. ContiguousAllReduce, ContiguousReduce (layer_norm's mean over the last axis) and General/ContiguousReduce reach it.
    • strided_reduce (:83-108): one running sum per column, size steps. ContiguousStridedReduce and General/ContiguousStridedReduce reach it.
    • GeneralReduce (:259-273): one element at a time through nd_loop, e.g. a broadcast row (stride 0).
  • The normalizers of mlx/backend/cpu/softmax.cpp (:56-82) and mlx/backend/cpu/logsumexp.cpp (:53-69): lanes from 0, sum(vnormalizer), then the tail.
  • fast::layer_norm's fallback takes its mean and variance with mean (mlx/fast.cpp:351, :353), so it inherits the error of the sums.

Over 3·2^23 elements (the tests below), the relative errors in the old order:

check Linux (x86-64 and arm64, 1 lane) macOS (Accelerate, 8 lanes)
sum of a row of u² 0.0301 0.0016
sums of the columns of [3·2^22, 2] 0.0116 0.0116
sums of the columns of [3·2^20, 8] 0.0016 0.0016
sum of a broadcast 0.375 0.111 0.111
softmax, x = -8u 0.0480 0.0057
logsumexp, x = -8u (the error of the log) 0.0469 0.0057
layer_norm fallback 0.0164 0.0004

The tests

Six new cases at the end of tests/ops_tests.cpp, all on the CPU stream. The long rows have n = 3·2^23 elements, and each bound, 1e-5 against a float64 result, was fixed before any run:

  • :4763 "test float sums over long rows on the cpu": :4780 the sum of a row of u² (ContiguousAllReduce); :4788 the sums over axis 0 of reshape(x, {n / 2, 2}) (ContiguousStridedReduce), per column; :4796 the same for {n / 8, 8}, so that macOS's SIMD column loop runs into the partial sums; :4800 the sum of broadcast_to(0.375, {n}) (GeneralReduce) against 0.375·n.
  • :4803 softmax of x = -8u, shape [1, n]; :4822 the largest relative error.
  • :4825 logsumexp of the same x; :4841 |y - truth|. The error of the log is the relative error of the sum.
  • :4844 fast::layer_norm(x, nullopt, nullopt, 1e-5) with x = u - 0.25 or u + 0.25, so that no output is near 0; :4869.
  • :4872 "test float sums of 4096 elements keep their order on the cpu", all exact (CHECK_EQ, array_equal): a row's sum against lane_order_sum (:4884); each column of [4096, 2] against a float32 loop (:4893); a broadcast 0.1 against a float32 loop (:4901); softmax against e_i * (1 / lane_order_sum(e)) with e = exp(x - max(x)) (:4911 max(e) == 1, :4918); logsumexp of one 0 and 4095 values -16 - 8u against log(lane_order_sum(e)) (:4928, :4930). There the sum is near 1, so its log keeps the bits that a different order changes.
  • :4933 "test float sums with a short last block on the cpu": 8197 = 2·4096 + 5 elements, so each sum ends with a short block (on macOS also a lane tail). All results are exact in any order: the sum of ones (:4939), a broadcast 1.0 (:4940, GeneralReduce's last short block), the columns of [8197, 2] and [8197, 8] arrays of ones (:4942, :4944), softmax of zeros equal to 1/8197 (:4949) and logsumexp of zeros equal to log(8197.0f) (:4950).

u is a hash of the index into a 24-bit float in [0, 1). The data were chosen before any run, with a host emulation of the old and new orders (1 and 8 lanes, Apple's halving reduce_add, MLX's simd::exp). With u itself, the old order missed a row's sum by only 2.1e-5 on Linux, too near the bound, so the sums use u².

sum_lanes. lane_order_sum needs the CPU's float32 lane count, simd::max_size<float>. Including mlx/backend/cpu/simd/simd.h in ops_tests.cpp fails to compile with Accelerate: reference to 'bfloat16_t' is ambiguous, between arm_neon.h's global bfloat16_t and the file's using namespace mlx::core. So the test states the count: 8 when MLX_USE_ACCELERATE is set and the target is not x86-64 (accelerate_simd.h), else 1 (base_simd.h). It must change if the backend's lane count does (see Highway below).

The final tests on main's backend files fail at the seven long checks with the values of the table; the 4096 and 8197 cases pass. On arm64 Linux:

tests/ops_tests.cpp:4780: ERROR: CHECK_LE( std::abs(y - truth) / truth, bound ) is NOT correct!
  values: CHECK_LE( 0.0301017, 1e-05 )

and the same form at :4788, :4796, :4800, :4822, :4841 and :4869 (bf-cs-red3-arm.tests.log). Earlier versions of the tests failed the same way at main on x86-64 Linux, arm64 Linux and macOS (bf-cs-red-*, bf-cs-red2-*), and the old order (blocks of 2^30, below) gives every value of the table on all three.

The fix

Each of these sums now adds its row in blocks of sum_block = 4096 elements, each block with the code it had, and adds the block sums in a second accumulator:

  • reduce.cpp, for SumReduce when the accumulator type is not integral (cascade_sum<U, Op>: float32, float64, float16, bfloat16 through its float accumulator, complex64):
    • contiguous_reduce calls the old body, now contiguous_reduce_block, once per block, into the same *accumulator. The lanes restart from init in each block, and *accumulator is the second accumulator.
    • strided_reduce: the first 4096 steps go into the accumulators as before. Each later block goes into partial, a std::vector<U>(stride) made only when size > 4096, from 0, and is then added in.
    • GeneralReduce computes the number of elements per output once (the product of the reduced shape). Above 4096, the first 4096 go into val, each later 4096 into block from 0, which is then added to val, and so is a short last block. Otherwise the old loop runs, unchanged.
  • softmax.cpp and logsumexp.cpp: a row of 4096 elements or fewer runs the old loop, unchanged. A longer row runs that loop as block_normalizer(n) per block: the first block gives the normalizer, and each later block's result is added to it.

A sum of 4096 elements or fewer computes as before, bit for bit. 4096 is a multiple of every lane count (1 on Linux; with Accelerate 8 for float and float16, 4 for double), so only a row's last block can have a tail. Max, min, prod, and/or, and integer sums are unchanged.

Not changed: the nd_loop paths of GeneralContiguousReduce and GeneralStridedReduce (reduce.cpp:245-255, :295-305 on this branch). Each row is summed in blocks, but the rows' results are added into the output one after another. So an output that gathers more than 4096 short rows still adds their partial sums in sequence; on macOS, rows shorter than 8 elements are added element by element.

Highway (#10, #18)

#10 (head f3b3b94e5, read here, not built) has its own summation loops in Highway builds, and each needs the same block split:

  • softmax.cpp:27-104, softmax_row, copies the normalizer loop (:51-77).
  • reduce.cpp sends contiguous sums through contiguous_reduce_impl (float accumulators for half types) and through a threaded all-reduce (:185-220), whose per-thread partials are summed with the same single-accumulator loop.
  • logsumexp.cpp keeps the generic loop there, so this change carries over as it is.
  • The 4096-element test knows only 1 and 8 lanes and Apple's halving. With Highway, max_size<float> is highway_max_f32_lanes (highway_simd.h:31) and the order is hn::ReduceSum's (:943-947), so sum_lanes and lane_order_sum need a branch there.

Speed

Release builds, float32, the CPU stream. Each call builds the op and reads one element with .item<float>(). A is main's libmlx.a, B this branch's, A′ main's again. A run is valid if A′/A is in [0.98, 1.02] and passes if B/A ≤ 1.02; the gate was fixed before any timing.

platform op and shape design A µs B µs A′ µs A′/A B/A
arm64 Linux softmax [512, 4096] 1 4846.67 4761.25 4899.62 1.0109 0.9824 pass
arm64 Linux softmax [64, 4096] 1 634.92 640.08 622.38 0.9802 1.0081 pass
arm64 Linux softmax [65536, 16], first version 2 1660.66 1747.73 1642.73 0.9890 1.0528 fail, fixed (next row)
arm64 Linux softmax [65536, 16] 2 1662.38 1660.62 1669.01 1.0034 0.9974 pass
arm64 Linux logsumexp [65536, 16] 2 1713.28 1732.22 1714.14 1.0001 1.0103 pass
arm64 Linux sum(x, -1) [512, 4096] 1 1170.12 1182.50 1153.79 0.9860 1.0106 pass
arm64 Linux sum(x, -1) [64, 4096] 2 172.19 172.70 172.68 1.0027 1.0017 pass
arm64 Linux sum(x, 0) [4096, 64] 2 51.77 51.49 51.61 0.9971 1.0002 pass
macOS softmax [512, 4096] 1 1361.67 1363.00 1344.17 0.9871 1.0010 pass
macOS softmax [64, 4096] 1 179.17 180.17 176.38 0.9844 1.0056 pass
macOS softmax [65536, 16] 2 722.36 721.42 722.35 0.9999 0.9988 pass
macOS logsumexp [65536, 16] 2 762.56 762.42 761.88 0.9993 0.9998 pass
macOS sum(x, -1) [512, 4096] 1 161.21 160.38 160.38 0.9949 0.9949 pass
macOS sum(x, -1) [64, 4096] 2 28.95 28.95 29.05 1.0029 0.9970 pass
macOS sum(x, 0) [4096, 64] 2 34.84 34.43 34.57 0.9966 0.9914 pass
  • Design 1: one process each for A, B and A′, back to back; 300 timed calls after 30 warm-up calls; the medians; the first valid of at most three triples (arm64 softmax [64, 4096] took three, arm64 sum [512, 4096] two, the rest one). Logs bf-cs-speed-{arm,mac}-{1,2,3}.log. macOS sum(x, -1) [64, 4096] was never valid this way (A′/A 1.0409, 0.9565, 1.1667), so it was re-measured with design 2.
  • Design 2: three long-lived processes (A, B, and a second process of main's build as A′). One sample is a batch of calls timed as a whole, at least 20 ms: 1000 calls for sum(x, -1) [64, 4096] and macOS sum(x, 0), 500 for arm64 sum(x, 0), 50 for macOS softmax and logsumexp [65536, 16], 20 for arm64 softmax and logsumexp [65536, 16]. The triples rotate the order, (A, B, A′), (B, A′, A), (A′, A, B). 120 warm-up triples are discarded and 300 counted; the statistic is the median of the per-triple ratios, whose standard error was 0.0003 to 0.0024. Every cell was valid on its first try. Logs bf-cs-speed2-{arm,mac}-1.log, bf-cs-speed3-mac-{softmax,ssum}-1.log, bf-cs-speed4-arm-{softmax,lse,ssum}-1.log, bf-cs-speed4-mac-lse-1.log.
  • A failure, and its fix. The first version ran every row of softmax and logsumexp through the block loop's lambda. arm64 softmax [65536, 16] then gave B/A 1.0528 (valid, A′/A 0.9890; bf-cs-speed3-arm-softmax-1.log), so rows of 4096 or fewer now run the old loop, and the re-time above passes. arm64 logsumexp [65536, 16] is still 1.0 % slower (B/A 1.0103, standard error 0.0003), within the 2 % bound; its row loop is main's, unchanged.
  • B is this branch at the time of each run. The arm64 softmax and logsumexp [65536, 16] rows, arm64 sum(x, 0) and macOS logsumexp time the tip. The other rows time earlier versions, which differ from the tip only off their paths, except softmax: the design-1 softmax rows and macOS softmax [65536, 16] ran the lambda version for every row.

The x86-64 Linux build runs under Rosetta here and was not timed.

Verification

At the branch tip:

Platform Cases passed Failed Skipped Assertions passed
x86-64 Linux (Clang, Release) 270 0 16 (the CPU-JIT cases) 4013
arm64 Linux (Clang, Release) 270 0 16 4013
macOS (Accelerate, Metal off, Release) 286 0 0 4106

main passes 264 and 280 cases (3992 and 4085 assertions) in the same builds, so nothing newly fails. Logs: bf-cs-suite4-{x86,arm,mac}.tests.log. Each rebuilt object has main's build warnings: on Linux logsumexp.cpp.o 8, softmax.cpp.o 12, reduce.cpp.o 2, ops_tests.cpp.o 4; on macOS none. The six new cases alone pass on all three (bf-cs-green4-{x86,arm,mac}.tests.log).

Mutation checks, the new cases alone, on all three platforms unless named:

  • sum_block = 1 << 30 in all three files (one block per row, the old order): the seven long checks fail with the table's values, value for value, and the 4096 and 8197 cases pass (bf-cs-mut30d-*; before the speed fix bf-cs-mut30c-*).
  • The flush of GeneralReduce's last short block removed: only :4940 fails, CHECK_EQ( 8192, 8197 ) (bf-cs-mutflush4-*, bf-cs-mutflush-*).
  • sum_block = 1024, arm64 Linux and macOS, on the previous version of the tests: the long rows pass, and the 4096-element case fails at its contiguous, column-0, broadcast, softmax and logsumexp checks (bf-cs-mut10b-{arm,mac}.tests.log). So the checks see a change of order inside 4096 elements.

The fork's sanitizer CI configuration (.github/scripts/build-sanitizer-tests.sh), arm64 Linux, clang 21: Debug, -DCMAKE_COMPILE_WARNING_AS_ERROR=ON, Metal off, -DUSE_ASAN=ON or -DUSE_UBSAN=ON, the script's *SAN_OPTIONS.

  • As it stands, it fails on main's own code with this clang: tests/random_tests.cpp:358 and seven more lines, and tests/ops_tests.cpp:3130-3138, -Werror,-Wabsolute-value. Every object also warns -Wdeprecated-declarations on std::result_of. (The script exports CMAKE_CXX_COMPILER as an environment variable, which CMake does not read, so the GitHub job likely builds with GCC.)
  • With exactly those two kinds exempted (-Wno-error=deprecated-declarations -Wno-error=absolute-value), both builds succeed: no other warning in any object. The six new cases pass with no AddressSanitizer report and no UBSan runtime error:. ASan: 43.4 s and a peak resident size of 1.34 GB for the six (softmax 18.4 s, logsumexp 15.0 s). UBSan: 22.7 s and 1.14 GB. Run at the tip and before the speed fix, with the same results. Logs bf-cs-ci4-{asan,ubsan}-arm.* (tip), bf-cs-ci4-{asan,ubsan}-arm-green3.*.

Upstream

ml-explore/mlx main at 97462e188 has the same loops. Its softmax.cpp and logsumexp.cpp are byte-identical to main here. Its reduce.cpp has the same accumulation, with int64_t sizes and offsets (ml-explore#4549). So it has the same error. This patch does not apply there as it is (reduce.cpp's signatures, and the end of tests/ops_tests.cpp), so it needs a rebase.

Merge note

git merge-tree against the heads of the open PRs: #10 (f3b3b94e5) and #18 (465f8a329), the Highway PRs, conflict with this branch in reduce.cpp, softmax.cpp and tests/ops_tests.cpp, and each merges cleanly with main. Whichever merges second rebases, and the Highway loops then need the block split (see Highway above). #28 (fix/cpu-int-min-div) also adds cases to tests/ops_tests.cpp and merges cleanly. Every other open PR merges with this branch as it merges with main.

🤖 Generated with Claude Code

Without Highway, the CPU sums a long float row with a single running
sum, or with one per SIMD lane for a contiguous row (eight lanes with
Accelerate, one on Linux). Along the row each element meets an ever
larger sum and loses its low bits, so the error grows with the row,
and a sum of 0.375s stops growing at 2^23. This holds for the CPU's
sum and mean, the normalizers of softmax and logsumexp, and
layer_norm's fallback, whose mean and variance are CPU means.

This commit's tests take rows of 3 * 2^23 float32 elements on the CPU
and bound each error against a float64 result by 1e-5: the sum of a
row, the sums of the columns of [3 * 2^22, 2] and [3 * 2^20, 8]
arrays, the sum of a broadcast 0.375, softmax, logsumexp (the error
of the log, which is the relative error of its sum), and layer_norm
without weight and bias. Before this commit, on arm64 Linux, all
seven failed, by 0.0016 (the eight columns) to 0.111 (the broadcast
sum); the row's sum, for one:

    /work/src-bf-cs/tests/ops_tests.cpp:4780: ERROR: CHECK_LE( std::abs(y - truth) / truth, bound ) is NOT correct!
      values: CHECK_LE( 0.0301017, 1e-05 )

On macOS, with eight lanes, the old order misses by 0.0004 to 0.111.

Each of these sums now adds its row in blocks of 4096 elements, each
block with the code it had before, and adds the block sums in a second
accumulator. This applies to the contiguous, strided and general sum
reductions whose accumulator is not an integer type (float32, float64,
float16, bfloat16, complex64), and to the normalizers of softmax and
logsumexp. A sum of 4096 elements or fewer runs as before, bit for
bit; another test checks this for a row's sum, the columns of a
[4096, 2] array, a broadcast 0.1, softmax and logsumexp.

A third test sums 8197 = 2 * 4096 + 5 elements, so that each sum ends
with a short block: ones, a broadcast 1.0, the columns of [8197, 2]
and [8197, 8] arrays of ones, and softmax and logsumexp of zeros, all
exact in any order. Without the general reduction's sum of its last
short block, the broadcast sum gives 8192. With blocks of 2^30 the
long rows fail as before; with blocks of 1024 they pass and the
4096-element test fails.
The general reduction's cascade loop computed the input offset and the
element count in int, so a reduction over 2^31 or more elements wrapped.
Apple's 64-bit reduce offsets (in osaurus-ai#48) do the same for the other loops.
@jjang-ai
jjang-ai merged commit e93ecd7 into osaurus-ai:main Nov 22, 2026
rcfa pushed a commit to cubiculum-ai/mlx that referenced this pull request Nov 22, 2026
Conflicts with osaurus-ai#34 (blocked float sums) and osaurus-ai#45 (saturating casts):
- cpu/reduce.cpp: keep osaurus-ai#34's blocked contiguous/strided reductions and give
  contiguous_reduce and contiguous_reduce_block upstream ml-explore#4549's int64_t size.
- cpu/copy.cpp: keep osaurus-ai#45's saturating_cast copy loop; for complex64 -> bool it
  ends in static_cast<bool>, which now takes upstream ml-explore#4593's explicit
  complex64_t::operator bool.
rcfa added a commit to cubiculum-ai/mlx that referenced this pull request Nov 22, 2026
Conflicts, all where main's CPU fixes meet this PR's Highway code:
- cpu/reduce.cpp: strided_reduce (osaurus-ai#34's cascade) is common to both builds;
  the Highway contiguous_reduce sums in blocks of sum_block, as osaurus-ai#34 does.
  The non-Highway code is main's.
- cpu/softmax.cpp: the Highway row kernel sums in blocks of sum_block, as
  osaurus-ai#34 does. The non-Highway code is main's.
- cpu/binary.h: main's size_t loop (osaurus-ai#48) under this PR's guard.
- cpu/simd/base_simd.h, tests/blas_tests.cpp, tests/ops_tests.cpp: both
  sides kept.

Check: with MLX_USE_HIGHWAY_KERNELS undefined (unifdef), every source file
reduces to main's version, except one comment in cpu/quantized.cpp that
this PR already had. The tests are the union of main's and this PR's.
@rcfa
rcfa deleted the fix/cpu-cascade-sum branch November 23, 2026 00:43
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