Repository navigation
Sum long float rows in blocks on the CPU - #34
Merged
Merged
Conversation
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.
This was referenced Nov 5, 2026
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.
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.
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.
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 frominit, then*accumulator = op(*accumulator, op(accumulator_v))(:119) and the tail into*accumulator. ContiguousAllReduce, ContiguousReduce (layer_norm'smeanover the last axis) and General/ContiguousReduce reach it.strided_reduce(:83-108): one running sum per column,sizesteps. ContiguousStridedReduce and General/ContiguousStridedReduce reach it.:259-273): one element at a time throughnd_loop, e.g. a broadcast row (stride 0).mlx/backend/cpu/softmax.cpp(:56-82) andmlx/backend/cpu/logsumexp.cpp(:53-69): lanes from 0,sum(vnormalizer), then the tail.fast::layer_norm's fallback takes its mean and variance withmean(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:
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"::4780the sum of a row of u² (ContiguousAllReduce);:4788the sums over axis 0 ofreshape(x, {n / 2, 2})(ContiguousStridedReduce), per column;:4796the same for{n / 8, 8}, so that macOS's SIMD column loop runs into the partial sums;:4800the sum ofbroadcast_to(0.375, {n})(GeneralReduce) against 0.375·n.:4803softmax of x = -8u, shape [1, n];:4822the largest relative error.:4825logsumexp of the same x;:4841|y - truth|. The error of the log is the relative error of the sum.:4844fast::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 againstlane_order_sum(:4884); each column of [4096, 2] against a float32 loop (:4893); a broadcast 0.1 against a float32 loop (:4901); softmax againste_i * (1 / lane_order_sum(e))withe = exp(x - max(x))(:4911max(e) == 1,:4918); logsumexp of one 0 and 4095 values-16 - 8uagainstlog(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 tolog(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'ssimd::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_sumneeds the CPU's float32 lane count,simd::max_size<float>. Includingmlx/backend/cpu/simd/simd.hinops_tests.cppfails to compile with Accelerate:reference to 'bfloat16_t' is ambiguous, betweenarm_neon.h's globalbfloat16_tand the file'susing namespace mlx::core. So the test states the count: 8 whenMLX_USE_ACCELERATEis 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:and the same form at
:4788,:4796,:4800,:4822,:4841and:4869(bf-cs-red3-arm.tests.log). Earlier versions of the tests failed the same way atmainon 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 = 4096elements, each block with the code it had, and adds the block sums in a second accumulator:reduce.cpp, forSumReducewhen the accumulator type is not integral (cascade_sum<U, Op>: float32, float64, float16, bfloat16 through its float accumulator, complex64):contiguous_reducecalls the old body, nowcontiguous_reduce_block, once per block, into the same*accumulator. The lanes restart frominitin each block, and*accumulatoris the second accumulator.strided_reduce: the first 4096 steps go into the accumulators as before. Each later block goes intopartial, astd::vector<U>(stride)made only whensize > 4096, from 0, and is then added in.val, each later 4096 intoblockfrom 0, which is then added toval, and so is a short last block. Otherwise the old loop runs, unchanged.softmax.cppandlogsumexp.cpp: a row of 4096 elements or fewer runs the old loop, unchanged. A longer row runs that loop asblock_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_looppaths of GeneralContiguousReduce and GeneralStridedReduce (reduce.cpp:245-255,:295-305on 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.cppsends contiguous sums throughcontiguous_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.cppkeeps the generic loop there, so this change carries over as it is.max_size<float>ishighway_max_f32_lanes(highway_simd.h:31) and the order ishn::ReduceSum's (:943-947), sosum_lanesandlane_order_sumneed a branch there.Speed
Release builds, float32, the CPU stream. Each call builds the op and reads one element with
.item<float>(). A ismain'slibmlx.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.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.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. Logsbf-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.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 ismain's, unchanged.The x86-64 Linux build runs under Rosetta here and was not timed.
Verification
At the branch tip:
mainpasses 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 hasmain's build warnings: on Linuxlogsumexp.cpp.o8,softmax.cpp.o12,reduce.cpp.o2,ops_tests.cpp.o4; 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 << 30in 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 fixbf-cs-mut30c-*).:4940fails,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=ONor-DUSE_UBSAN=ON, the script's*SAN_OPTIONS.main's own code with this clang:tests/random_tests.cpp:358and seven more lines, andtests/ops_tests.cpp:3130-3138,-Werror,-Wabsolute-value. Every object also warns-Wdeprecated-declarationsonstd::result_of. (The script exportsCMAKE_CXX_COMPILERas an environment variable, which CMake does not read, so the GitHub job likely builds with GCC.)-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 UBSanruntime 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. Logsbf-cs-ci4-{asan,ubsan}-arm.*(tip),bf-cs-ci4-{asan,ubsan}-arm-green3.*.Upstream
ml-explore/mlx
mainat97462e188has the same loops. Itssoftmax.cppandlogsumexp.cppare byte-identical tomainhere. Itsreduce.cpphas the same accumulation, withint64_tsizes 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 oftests/ops_tests.cpp), so it needs a rebase.Merge note
git merge-treeagainst the heads of the open PRs: #10 (f3b3b94e5) and #18 (465f8a329), the Highway PRs, conflict with this branch inreduce.cpp,softmax.cppandtests/ops_tests.cpp, and each merges cleanly withmain. 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 totests/ops_tests.cppand merges cleanly. Every other open PR merges with this branch as it merges withmain.🤖 Generated with Claude Code