Repository navigation
CPU backend: adopt ml-explore/mlx#3019's Highway kernels on Linux x86-64 - #10
Conversation
|
Background for the 16 CPU-JIT cases that this PR's Clang runs skip: they fail in any Linux Clang build of MLX, Describe the bug On Linux, the CPU JIT's prebuilt preamble is preprocessed with the build's compiler, but the JIT compiles every kernel at run time with a hard-coded The prebuilt preamble is used when no headers are installed next to the binary ( Code at main a32f0c3:
To Reproduce Linux, with clang++ and g++ both installed: git clone https://github.com/ml-explore/mlx && cd mlx # main, a32f0c3d
cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
-DMLX_BUILD_METAL=OFF -DMLX_BUILD_TESTS=ON
cmake --build build -j
./build/tests/tests -tc="test simple compile"Output (paths shortened; about 100 KB of compiler errors cut): The whole suite gives The JIT files have not changed since v0.32.2. A v0.32.2-based build fails the same 16 cases on aarch64 and on x86_64. Expected behavior The 16 cases pass, as they do with GCC (the Linux CI jobs, which build with GCC, pass 262 of 262 at a32f0c3). Regenerating only the preamble with g++, in the same Clang build, makes them pass: bash mlx/backend/cpu/make_compiled_preamble.sh "$PWD/build/mlx/backend/cpu/compiled_preamble.cpp" g++ "$PWD" FALSE aarch64 ""
cmake --build build
./build/tests/tests -tc="<the 16 cases above>"
# [doctest] test cases: 16 | 16 passed | 0 failed | 246 skippedDesktop (please complete the following information):
Additional context
🤖 Generated with Claude Code |
|
The CPU JIT under Clang is fixed separately in #13. |
Add an x86 CPU acceleration path behind MLX_ENABLE_AVX2. The implementation uses Google Highway for the AVX2 SIMD layer, clamps the emitted x86 target set to AVX2, and links Highway statically into MLX with CMake support for either a local source checkout or FetchContent. Add a shared CPU threading abstraction with an OpenBLAS-backed persistent thread pool on Linux/Windows and an Accelerate/GCD backend on Apple platforms. The thread pool defaults to physical cores, honors MLX_CPU_THREADS, and coordinates OpenBLAS to avoid oversubscription. Vectorize the CPU paths that matter for small-model inference: affine and FP quantized matmul, dequantization, norms, RoPE, SDPA, compiled CPU kernels, softmax, reductions, unary/binary ops, copies, indexing, and fp16/bf16 GEMM helpers. CPU JIT preamble generation and runtime compiler flags include the same AVX2/BMI2/FMA/F16C and Highway definitions so fused kernels use the accelerated SIMD layer when the host supports it. Add focused tests for CPU fast paths, quantized global-scale handling, compile coverage, and thread pool behavior. (cherry picked from commit 9217551)
(cherry picked from commit a4e93db)
ml-explore#3019 removes the scalar Simd's subscript operator. Upstream ml-explore#4157 added a simd::sincos that indexes Simd<T,N> for every N, including 1, so with both the CPU backend does not compile (unary.cpp: "type 'Simd<float, 1>' does not provide a subscript operator").
Upstream ml-explore#4157's simd::sincos_checked writes single lanes of a Simd<T,N> when an argument is past 2^23. The Highway Simd has only a const operator[] that returns a copy, so unary.cpp does not compile on x86: mlx/backend/cpu/simd/math.h:131:14: error: expression is not assignable 131 | out[i] = static_cast<T>(Sine ? std::sin(v) : std::cos(v)); | ~~~~~~ ^ Clang reports it for sincos_checked<Sine, float, 4> and <Sine, double, 2>. For bfloat16 the code compiled, but each write went to a temporary, so sin and cos returned zero in every lane of a vector holding such an argument. Add the writable operator[] that the Accelerate and NEON fp16 Simd types have.
MLX 0.32.3 (ml-explore#4442) routes the CPU Divide op through simd::divide, which defines an integer quotient by zero as 0, and makes an integer remainder by zero return the dividend. The Highway facade had no divide for vectors, so binary.cpp did not compile with MLX_USE_HIGHWAY_KERNELS, and its integer remainder divided by zero, which traps on x86-64. Add divide, and give remainder upstream's rule. A test runs floor_divide and remainder on int32, uint32 and uint8, the integer types the facade has vectors for, with zero divisors in vector lanes and in the scalar tail, and compares each element with the one-element path.
ml-explore#3019's JIT preprocesses Highway into per-tier preambles at build time and compiles them at run time with clang++ in Clang builds and g++ in GCC builds, which ties a host's compiler to the build's. Its CMake rule for the scalar preamble also passes an empty argument that CMake drops. In a Linux Clang build the embedded preamble came out empty, and every CPU compile that used it failed ("use of undeclared identifier 'mlx'"). A GCC 12 build was not affected: g++ reports the misplaced argument but still preprocesses the header. Keep the fork's jit_compiler.cpp, compiled.cpp, compiled_preamble.h, preamble scripts and CMake rule. A Highway JIT that the host's own compiler builds is separate work.
ml-explore#3019 rewrites quantized.cpp well beyond its Highway guards: thread-pool calls, a dequantize-then-SGEMM path and new kernels sit outside them, and every build compiles the file. Keep it as quantized_highway_backend.cpp, compiled only with MLX_USE_HIGHWAY_KERNELS, and restore the fork's quantized.cpp for every other build, so builds without Highway compile exactly what they did.
…WAY_KERNELS ml-explore#3019 changes files that every CPU build compiles, macOS included: thread-pool calls in binary.h, unary.h, copy.cpp, indexing.cpp, reduce.cpp, softmax.cpp and cblas.cpp; the SIMD headers; out-of-line fast-primitive declarations. It also changes two groups that macOS does not compile: the no-GPU fallbacks and the low-precision GEMMs. Guard every hunk with MLX_USE_HIGHWAY_KERNELS, so that a build without Highway preprocesses each file exactly as before; vmlx-swift checks the files macOS compiles. Thirteen of these files, and mlx/io/load.h, get back the copyright lines they had before ml-explore#3019 moved them to 2026. Without the macro, fast_primitives.h keeps its inline eval_cpu definitions, so ml-explore#3019's norms.cpp, rope.cpp and sdpa.cpp, which define them out of line, now compile only in Highway builds.
MLX 0.32.3 (ml-explore#4376) decodes the E4M3 codes 0x7F and 0xFF as NaN. ml-explore#3019's quantized backend decodes them through FP8_LUT, a table computed from the old FromFP8, which held 480 and -480 there, and its dispatched kernels decoded mxfp8 weights from the bits in the same way. Set the two entries to NaN. In the kernels, keep the bit decode, which is right for every other code, and select NaN for the two codes instead of a gather from the table. A test multiplies with mxfp8 weights and nvfp4 scales that hold both codes, and compares every other output exactly with dequantize, or with the value the codes give. It also multiplies every finite code by an identity matrix, with the weights transposed and not, and compares each output with dequantize.
… the GCD pool ml-explore#3019's new sources and its thread pool were compiled in every CPU build, macOS included, where a GCD pool drove parallel_for. Wrap each new library source in MLX_USE_HIGHWAY_KERNELS, except ml-explore#3019's MSVC-only dispatch shims, so that a build system which compiles every file it finds (SwiftPM) builds them only with the macro; in CMake, build the pool's directory only with Highway; and keep one pool: the std::thread pool Linux builds use. The pool's own test builds only where the pool does.
MLX_ENABLE_X86_SIMD stays as an alias on a fresh configure. The default is on for Linux x86-64 only: the kernels are tested there, and not yet on Windows or Intel macOS.
…path The dequantize-then-SGEMM path for M >= 32 reads 32 / bits values per word, which is wrong for 3, 5 and 6 bits: MLX packs those as a byte stream, and the result was garbage (relative error 1.3 to 2.2). Keep it for 2, 4 and 8 bits.
QQMatmul's simulated activation quantization rounded the mxfp block scale to nearest, saturating a block's largest elements, and broke FP4 ties toward the first table entry. Use upstream's to_fp8_e8m0_round_up (ml-explore#4353) and to_fp4_e2m1 (round half to even) again.
ml-explore#3019's native CPU SDPA indexes values and output with the query's head dimension, keeps queries in a float[256] buffer, and implements float32, float16 and bfloat16 only. MLA-style shapes came out wrong, and a head dimension above 256 would overflow the buffer. Let use_fallback compose those shapes and the other dtypes, and refuse them in eval_cpu.
The facade's lane maps called libm in float for every lane type, so float64 results of the functions they cover were rounded to float: the inverse trigonometric and hyperbolic functions, tan, sinh, cosh, tanh, the logarithms, expm1, pow, atan2 and remainder. Compute in double for double lanes.
The facade's integer pow looped forever on a negative exponent. Return 0, as base_simd does since upstream ml-explore#4100.
ml-explore#3019's parallel reductions rounded each thread's partial to the output dtype before combining them, so an fp16 sum depended on the thread count: 2^18 + 3 elements of 2^-4 and one -2^14 summed to 0 with 8 threads, not 0.1875. Keep the partials in the accumulator type and round once. MLX widens bf16 sums to float before this code, so the bf16 test passes without the change; fp16 sums it widens only where its SIMD width is 1, which under Highway it is not.
Every elementwise kernel runs the facade at Highway's static target, SSE2 on x86-64, where MulAdd is a multiply and an add. fma promises one rounding, as base_simd's std::fma gives, and MLX's polynomials rely on it: erfinv lost most of its bits near |x| = 1 (64.7 units in the last place at 0.99983, against at most 2.1 rounded once). Without native FMA, compute each lane with std::fma.
Highway emulates float16 -> float32 where a target has no conversion instruction, which on x86-64 includes the facade's static target, SSE2, and reads exponent 31 as finite there. float16 inf came out as 65536: sin(inf) gave 0.691895, which is sin(65536) in float16, and inf - inf gave 0. NaN came out as a number: NaN - NaN gave 0, and isnan(NaN) false. Give those lanes float32's inf or a quiet NaN, in the facade and in the loads the dispatched kernels share.
MLX 0.32.3 (ml-explore#4376) decodes the E4M3 codes 0x7F and 0xFF as NaN, carrying into an all-ones float16 exponent, and takes the sign from the bits. Under Highway, FromFP8 still decoded them as 480 and -480, as ml-explore#3019 wrote it. Decode the same bits there, widen to float, then multiply by 256. A test decodes all 256 codes in whole vectors, and 0x7F, 0xFF and 0x80 in the scalar tail, and dequantizes mxfp8 weights and nvfp4 scales that hold both codes.
ml-explore#3019 rounds quantized matmul activations to int8 per group whenever env::enable_tf32() is true, and MLX defaults that to true; the path takes 4- and 8-bit weights at group size 32 or more, K up to 16384 and fewer than 32 rows. That trades accuracy for speed without being asked. Gate the path on its own switch, mlx::core::cpu::quantized_int8(), off unless MLX_CPU_QUANTIZED_INT8=1 or set_quantized_int8(true). Without it, the Highway path for affine 2-, 4- and 8-bit weights with transposed layout sums in float32. ml-explore#3019's "token float32" test expected int8-rounded activations. It now checks the exact result, and a second case checks the int8 path with the switch on, where the build has one. Its "token bfloat16" bound assumes float32 sums, which builds without Highway do not do; quantized_float32_accumulation() says which a build does, and the test returns early where it does not.
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.
The CPU float-to-integer saturation calls convert_in_range<uint32_t> on Simd<float, N> in math.h's sincos. highway_simd.h had no vector overload, so a Linux build with MLX_USE_HIGHWAY did not compile once both were present. The overload uses the vector's own converting constructor, as the Highway build did before at this place.
Highway's ConvertTo gives a target-dependent result for NaN, and the fallback for lanes of different sizes used a plain cast. Both now give the result of saturating_cast, as the other Simd backends do.
Highway builds reduce with their own lane count and order. Also cover rms_norm over a long row.
simd.h declares a global bfloat16_t on arm64, which is ambiguous there.
Highway builds have their own LayerNorm and RMSNorm kernels. They now sum as the CPU reductions do.
K = 0 divided by zero, as in quantized.cpp before the same guard.
The scalar forms define y == 0 and INT_MIN / -1, which trap on x86-64.
The scalar form multiplies with wraparound, without signed overflow.
K = 0 or N = 0 trapped on x86-64 with an integer division by zero.
The scalar paths (_qmm, _qmm_t_cols and _qmm_t's sequential loop) summed in the input type, as quantized.cpp did before ml-explore#4803. The SIMD and BLAS paths already sum in float32.
The CPU's mixed bf16/f16 quantized path (osaurus-ai#11) is in quantized.cpp, which Highway builds do not compile. Their kernels read the f16 scales as bf16, so the mixed path gave wrong values. Highway builds now promote on the CPU as before, until the Highway kernels read f16 scales.
simd_gemm now takes the leading dimensions (osaurus-ai#26). The Highway path already passes them to cblas_sgemm, but not to simd_gemm, so it did not compile with both changes and would read a strided operand as dense.
… into hwy/arm64 # Conflicts: # tests/highway_simd_tests.cpp
|
Updated onto Merge
With 15 commits port the fixes from #55 to the Highway code:
Tests (
🤖 Generated with Claude Code |
|
Validated
|
CPU backend: Highway kernels on Linux arm64 (stacked on #10)
This PR adopts ml-explore#3019 (Highway-based x86 CPU kernels, by Daniel Hiltgen) for Linux
x86-64, and fixes the defects we found in it. It was based on this repository's
main(MLX 0.32.3), with 48 commits; since 2026-11-22 it alsomerges
mainat 61cc7a4 (#55) and has 15 more commits that port the CPU fixes merged there to itsHighway code (listed in the PR's comments). Without Highway, the library compiles the same code as
main, exceptprecision.cpp, the int8 switch, which changes nothing there.Please merge with a merge commit, not a squash or a rebase, so that ml-explore#3019's two commits keep
Daniel Hiltgen as their author.
#26 and #11, which change code this PR calls or, with Highway, replaces (
simd_gemm, and the CPU'squantized matmul in
quantized.cpp), merged in #55, and this PR is adapted to them:0a10b88cepassesldaandldbtosimd_gemmin the Highway low-precision GEMM (#26), and35a2a85bckeeps Highwaybuilds on the promoting quantized matmul, since their kernels read #11's f16 scales as bf16.
What it adopts
-x, author kept: "Add Highway-backed x86 CPU SIMDand threading" and "Adjust for runtime dynamic selection". The first conflicts with MLX 0.32.3 in
five files; the resolutions are inside the pick.
simd::sincos(upstream Send out of range trig arguments to libm ml-explore/mlx#4157) writes singlelanes: "Restore Simd<T,1>::operator[] for upstream's sincos" and "Fix the Highway build on MLX
0.32.2: writable Simd lanes". Without the second, x86-64 did not compile, and a probe of the bf16
path gave
sinandcos0 in every lane of a vector that holds an argument past 2^23. A testcovers it ("Tidy the Highway tests, and test bf16 sin and cos past 2^23"): with the writable lanes
removed for bf16 only, 127 of its 128 checks failed. MLX 0.32.3 also needs a vector
divide(item18 below).
0.32.2: writable Simd lanes":
binary.cppfails with 7 errors, eachno matching function for call to 'divide', until the next commit, "Fix the Highway build on MLX0.32.3: a vector divide". On arm64, Add support for x86 SIMD with Highway ml-explore/mlx#3019's two "token" tests fail until "Make Add support for x86 SIMD with Highway ml-explore/mlx#3019's int8
activation path opt-in".
mlx/io/load.hand does not need Highway, but it sends all eightlseekcalls of MLX's file readerand writer through a new
seek_fd, so it changes what macOS compiles. vmlx-swift does not build onWindows.
empty arguments that CMake drops. In our Linux Clang build the embedded preamble was empty (73
bytes) and all 16 CPU-JIT cases failed; our GCC 12 build embedded the header and passed them.
What it changes in ml-explore#3019
Each fix comes with a test, or for 14 and 26 a build, that failed before it and passes after it
(evidence below).
32 / bitsvalues perword, which is wrong for the byte-packed 3, 5 and 6 bits. Those widths now stay off that path; 2, 4
and 8 bits keep it. ("Keep 3, 5 and 6-bit weights off Add support for x86 SIMD with Highway ml-explore/mlx#3019's M >= 32 dequantize path")
to_fp8_e8m0_round_up(Round mxfp8 block scales up to avoid saturation ml-explore/mlx#4353) andto_fp4_e2m1. ("Round QQMatmul's simulated activations as upstream does")float16 and bfloat16 to the fallback, and
eval_cpurefuses them. ("Send attention the native CPUkernel cannot hold to the fallback")
float64 elementwise math in double in the Highway facade")
powwith a negative exponent returns 0, asbase_simd.hdoes since upstream Stop integer power from hanging on a negative exponent ml-explore/mlx#4100; itlooped forever. ("Return 0 for integer pow with a negative exponent in the Highway facade")
to the output dtype, so a sum depended on the thread count. Since MLX 0.32.3 (Widen float16/bfloat16 to float32 in cpu reduce ml-explore/mlx#4387), bf16 sums
reach this code already widened to float, so fp16 is what the fix keeps exact. ("Keep bf16 and fp16
reduction partials in float until the end")
fmarounds once. It runs at Highway's static target, SSE2 on x86-64, where itrounded twice. ("Round once in the Highway facade's fma, on every target")
the dispatched kernels share. ("Keep float16 inf and NaN through Highway's conversions")
floor,ceil,roundandtrunckeep the sign of zero at SSE2. ("Keep the sign of zero in theHighway facade's floor, ceil and rint")
env::enable_tf32()is true (MLX'sdefault), gets its own switch, off by default; Add support for x86 SIMD with Highway ml-explore/mlx#3019's "token float32" and "token bfloat16" tests
now hold in builds without Highway. ("Make Add support for x86 SIMD with Highway ml-explore/mlx#3019's int8 activation path opt-in")
ReorderWidenMulAccumulate, which it dropped.("Keep the whole 4-bit dot product in the int8 path on every target")
which Highway target each CPU kernel family ran")
nested
parallel_forinline, and pins OpenBLAS to one thread even withOPENBLAS_NUM_THREADSset. ("Size the CPU pool to the CPUs the process may use, and harden it")
cpu::ThreadPoolis exported, so a shared-library build of the tests links. ("Exportcpu::ThreadPool from shared builds")
slot count and the next slot, and a worker reads the generation before it announces itself ready.
Before, a worker that stalled between its check and its claim claimed a slot of the next call: it
ran that call with the old slot count, or took a slot and never ran it, so the call never returned,
or let the call return while a slot still ran. And a worker could miss the first call, which with
one worker (
MLX_CPU_THREADS=2) never returned. ("Fix a stale slot claim and a missed first call inthe CPU pool")
Simd<bool, N>built from a vector reads each lane asstatic_cast<bool>does: it compares the lanewith zero. Before, it took Highway's
MaskFromVec, which Highway defines only for lanes of all zerosor all ones: x86 reads each lane's top bit, so a nonzero lane with its top bit clear read as false,
and NEON one bit per lane. Since MLX 0.32.3's decode (item 19),
FromFP8takes its sign from the bits andbuilds no
Simd<bool>, so the fix has no caller here; the fix and its test stay. ("Read each lane asC++ does when a vector becomes Simd")
core_cpus_list(thread_siblings_listbefore Linux 5.3). It counted(physical_package_id, core_id)pairs, butcore_idis not unique within a package on every kernel: x86 kernels from 5.3until a fix in 6.1 (also in 6.0.6, 5.15.76 and 5.10.154) number cores per die on CPUs that report dies in
CPUID leaf 0x1F (5.3,
6.1), and since
Linux 6.0 device-tree systems restart
core_idin each cluster of a package(5.19,
6.0). Cores that
shared a pair counted once, so the pool came out smaller than the machine. On AMD family 15h the
kernel lists the two cores of a compute unit together, so the pool now counts compute units. ("Tell
cores apart by the CPUs they hold, not by core_id")
divide. MLX 0.32.3 (Fix integer div-by-zero crash in CPU backend (sort, scan, binary ops) ml-explore/mlx#4442) routes the CPU'sDividethroughsimd::divide, which the facade lacked, sobinary.cppdid not compile with Highway.dividegives 0 for an integer quotient by zero, and
remainderthe dividend for a remainder by zero, asbase_simd.hdoes; the facade's integer remainder by zero trapped on x86-64. ("Fix the Highwaybuild on MLX 0.32.3: a vector divide")
gave 480 and −480. The quantized backend's table holds NaN for them, for the paths that still read
it (the non-transposed
fp_qmmand the nvfp4 scales). The dispatched kernels keep Add support for x86 SIMD with Highway ml-explore/mlx#3019's bitdecode, which is right for every finite code, and select NaN for the two codes instead of gathering
from the table, since a per-lane gather is slow on Intel Skylake through Tiger Lake under the GDS
mitigation (nothing here was timed).
FromFP8, and with itfrom_fp8, computesmain's float16bits and widens them. A test checks the mxfp8 matmul at every Highway target the host runs.
("Decode E4M3 0x7F and 0xFF as NaN in the quantized fp8 paths", "Decode E4M3 0x7F and 0xFF as NaN
under Highway, as MLX 0.32.3 does", "Test the mxfp8 decode at every Highway target")
RMSNorm and LayerNorm return first for an empty array. They divided an element count by an inner
extent that is 0 for such an array, and integer division by zero traps on x86-64. No op is known to
reach the unary loop with an empty array; its guard stays. ("Return early from Add support for x86 SIMD with Highway ml-explore/mlx#3019's CPU kernels
for an empty array")
float only where the SIMD width is 1; under Highway the width is larger, so the strided and general
reductions rounded every step to float16. ("Widen float16 sums and products under Highway")
Add support for x86 SIMD with Highway ml-explore/mlx#3019's norms copy an input with gaps or a last stride other than 1, and their tasks read the copy
through a raw pointer; nothing registered the copy, so it was freed when
eval_cpureturned,before the tasks ran. The copy is now registered as a temporary, as
main's logsumexp does. ("Keepthe norms' input copy alive until their tasks run")
its attention the sinks through plain pointers with stride 1. The
fast::functions pass these onas they are or cast them, and a cast keeps a broadcast's stride 0, so a broadcast (stride 0), or a
stepped slice (stride 2) that needs no cast, reached the kernels, which read the wrong elements. For
a broadcast of a single value they read past its one-element buffer (from the code, not run). Each
kernel now copies such an input and registers the copy with the encoder: the norms and RoPE when its
stride is not 1, attention when the sinks are not row-contiguous. For the norms and RoPE, Metal and
CUDA pass the strides to their kernels. ("Copy the norms' weight and bias when their stride is not 1", "Copy rope's offsets
and freqs when their stride is not 1", "Copy sdpa's sinks when they are not row-contiguous")
wunder Highway, as it does without. Without Highway, the CPU'sQQMatmul supports only a quantized
wand one row ofx, and throws "[QQMatmul] NYI for thegeneral case" for any other input.
qqmmalso passes an unquantizedw, alone or with scales ornvfp4 global scales, and Add support for x86 SIMD with Highway ml-explore/mlx#3019's QQMatmul read
inputs[2]as the packed scales andwas packedvalues in every case. With scales, it computed from the wrong data. With global scales only, it
took
global_scale_x, one float32, as the scales and read N·K/16 bytes from it, for an N by Kw(from the code, not run). With
{x, w}only, it read past the end of its inputs. It now throws thesame error for any unquantized
w, before it reads an input. More than one row ofx, which thecode without Highway refuses, stays supported (from the code; no test covers it). ("Reject an
unquantized weight in QQMatmul under Highway")
fast::scaled_dot_product_attentionchecks that keys and values have the same number of heads, butnot the same length; without Highway, the composed path then raises an error, since its matmul of
the scores and the values checks their shapes as the graph is built. With Highway, Add support for x86 SIMD with Highway ml-explore/mlx#3019's native
kernel took such inputs and used the keys' length for the values too, so it read past the end of
shorter values, and the wrong rows of longer ones (both read from the code, not run). They now raise
the same error as without Highway, and the kernel's own guard has the same condition. ("Take sdpa's
composed path when keys and values differ in length")
of 16 floats, each for one float vector, but nothing stated that limit. The limit holds on every
target built today: Highway builds only for x86-64, whose float vectors have at most 16 lanes, and
the next PR, which adds Linux arm64, disables every SVE target. A wider target would overrun the
buffers without a sign. One constant,
kMaxLanes, now sizes the four buffers, and a compile-timecheck keeps
hn::MaxLaneswithin it, so that a wider target fails to compile. The tail loop thatfills one of them now starts where the loop over four rows stops, so that GCC can see its range.
GCC's Release builds warned at that loop (
-Waggressive-loop-optimizations), a false positive:those targets have 8 or 16 lanes, a multiple of four, so the loop ran zero times. ("Bound sdpa's
per-lane buffers at compile time")
Evidence: the failing run before each fix, and the passing run after
x86-64 runs are in a Debian 12 container under Rosetta (Clang 21, Release, Highway on); arm64 runs in
a Debian 12 arm64 container (Clang 21, Release, Highway off). Items 1–17 were tested before this PR
moved to
main, on its old base,qwen4-exp(MLX 0.32.2), and the suite counts after those fixes arethe branch's counts then. Items 18–26 were tested on
main(MLX 0.32.3). An item that also ran on theother base says so.
and in
gather_qmm(values: CHECK( 1.66975 < 1e-05 )). After:[doctest] test cases: 265 | 265 passed | 0 failed | 16 skipped.values: CHECK( 0.5 == 1 )forvalues[i] := 0.75; mxfp8 block scale:values: CHECK( 448 == 576 ). After:[doctest] test cases: 267 | 267 passed | 0 failed | 16 skipped.munmap_chunk(): invalid pointer(which shape did it is notlogged). After, three float32 shapes and float64:
[doctest] assertions: 4 | 4 passed | 0 failed |.On Add support for x86 SIMD with Highway ml-explore/mlx#3019's own head (research probe, macOS arm64, CPU only):
dqk=192 dv=128 L= 1 S= 17 causal=0 out_shape_ok=1 max_abs_err=1.99326 FAIL.[doctest] assertions: 68 | 4 passed | 64 failed |, then68 | 68 passed.STALLED: no test output for 60 s; killing the tests., then17 | 17 passed.reduce.cpp, x86-64: the fp16 case fails,values: CHECK( 0 == 0.1875 ), and the bf16 case passes, since Widen float16/bfloat16 to float32 in cpu reduce ml-explore/mlx#4387 widens bf16 sums to floatbefore this code. With the commit's
reduce.cpp, both pass. On the old base, 2^20 + 3 bf16 ones andone −2^20 gave
values: CHECK( 0 == 3 )with 8 threads andvalues: CHECK( -8192 == 3 )with 9 andwith 12.
erfinvnear 1:values: CHECK( 64.6857 <= 8 )units in the last place, thenvalues: CHECK( 2.05542 <= 8 ).[doctest] assertions: 384 | 272 passed | 112 failed |(sin(inf)gave0.691895), then384 | 384 passed. The kernels' loads: vmlx-swift's test of the norm kernels passes at everytarget the host runs, and fails at each of them once its reference reads exponent 31 as the
software conversion does.
[doctest] assertions: 512 | 464 passed | 48 failed |, each on the sign, the same in all fourdtypes; then
512 | 512 passed.arm64 before:
[doctest] test cases: 263 | 261 passed | 2 failed | 16 skipped(the twotoken tests); after:
[doctest] test cases: 249 | 249 passed | 0 failed | 16 skipped. Onmain,at the commit before it:
[doctest] test cases: 274 | 272 passed | 2 failed | 16 skipped, thetwo token tests again.
↳ int8 on EMU128: element 55 is 43.309791564941406, float64 gives -41.17641308103933, 6.094187488224424 times its bound. AVX2, SSE4, SSSE3 and SSE2passed before the fix; Highway 1.4.0's x86 code ignores
sum1. On NEON, Highway 1.4.0 puts theupper half's products in
sum1, so the path would lose them there; not run.THREW exception: "[RMSNorm::eval_cpu] Unsupported type", and the same for LayerNorm and RoPE;then
[doctest] test cases: 280 | 280 passed | 0 failed | 16 skipped.terminate called after throwing an instance of 'std::runtime_error'.Slot 0's:
values: CHECK( 0 == 7 ). A nested call:STALLED. Add support for x86 SIMD with Highway ml-explore/mlx#3019's OpenBLAS condition withOPENBLAS_NUM_THREADS=4:values: CHECK( 4 == 1 ). After:[doctest] test cases: 290 | 290 passed | 0 failed | 16 skipped.-DBUILD_SHARED_LIBS=ONon x86-64:undefined reference to 'mlx::core::cpu::ThreadPool::instance()'(and
max_threads(),parallel_for());libmlx.so dynamic symbols of cpu::ThreadPool: 0.After:
[doctest] test cases: 292 | 292 passed | 0 failed | 16 skipped.the first parallel_for did not return in 5 s,slot 1 ran with nth 3andslot 1 ran 0 times; after:test cases: 2 | 2 passed, also in 50 of50 repeated runs. The pool alone under GCC 12's ThreadSanitizer on arm64, two callers of 20000
calls each:
old stress runs: 3 of 3 hung; TSan reports: 5, and after the fixnew stress runs: 143 runs, 143 with 'bad slots=0'; hung: 0; TSan reports: 0.Simd<bool, N>from vectors whose lanes are neither zero nor all ones:uint8_tat2, 4, 8 and 16 lanes,
uint32_t,int32_t,floatanddouble, each value in every lane. Before,on x86-64:
test cases: 2 | 0 passed | 2 failed, e.g.values: CHECK( false == true )for auint8_tlane of0x1, andvalues: CHECK( true == false )for afloatlane of-0x0p+0; after,the whole suite:
test cases: 299 | 299 passed. On the old base, whereFromFP8still built aSimd<bool>,test fp8 conversionfailed on arm64 with Highway forced on, as the next PR does it,before the fix (
test cases: 297 | 296 passed | 1 failed) and passed after(
test cases: 299 | 299 passed).core_idrestarts, SMT siblings listed as8-9, a pre-5.3 kernel'sthread_siblings_listof10,12, and CPUs without a list. Before, onx86-64:
values: CHECK( 4 == 8 )andvalues: CHECK( 1 == 2 )for the cluster counts, the threedirect key checks failing, and
values: CHECK_FALSE( true )for a CPU with acore_idbut no list;after, the whole suite:
test cases: 300 | 300 passed. On arm64 with Highway on, in the nextPR's branch on top of this commit:
test cases: 303 | 303 passed; at that branch's head onmain:[doctest] test cases: 342 | 342 passed | 0 failed | 16 skipped.ninja -k 0): 7 errors, eachno matching function for call to 'divide'atbinary_ops.h:28:27,and only
binary.cpp.ofailed. With adividethat divides each integer lane asoperator/does,the new case,
floor_divideandremainderon int32, uint32 and uint8 with zero divisors in wholevectors and in the tail, crashed in its first check:
test case CRASHED: SIGFPE - Floating point error signaland[doctest] assertions: 0 | 0 passed | 0 failed |. After, x86-64:[doctest] test cases: 287 | 287 passed | 0 failed | 16 skipped; arm64 fails only Add support for x86 SIMD with Highway ml-explore/mlx#3019's twotoken tests. With either rule removed alone, the case crashes with SIGFPE again.
three NaN checks, mxfp8 at M = 1 and M = 32 and the nvfp4 scales,
[doctest] assertions: 11 | 8 passed | 3 failed |; arm64 passes 11 of 11. After, x86-64:[doctest] test cases: 288 | 288 passed | 0 failed | 16 skipped. With the table's entry forcode 1 set to 0, only the non-transposed check fails, so the transposed kernels do not read the
table for mxfp8 weights; with the select removed, the two mxfp8 NaN checks fail.
from_fp8, with the conversion before the fix, on x86-64: all 24 assertions fail, for 0x7F and0xFF in whole vectors and in the tail, in float32, float16 and bfloat16, and for
dequantizeofmxfp8 weights and nvfp4 scales:
[doctest] assertions: 24 | 0 passed | 24 failed |; arm64 passes 24of 24. After, x86-64:
[doctest] test cases: 300 | 300 passed | 0 failed | 16 skipped. Withthe Highway arm decoding as Add support for x86 SIMD with Highway ml-explore/mlx#3019 did, the case fails exactly as before the fix.
The per-target test pins dispatch to each target the host both compiled and supports (AVX2, SSE4,
SSSE3 and SSE2 under Rosetta) and checks NaN in exactly the outputs of the 0x7F and 0xFF rows,
every other output equal to
dequantize's, and that the mxfp8 kernel ran at that target:[doctest] assertions: 28 | 28 passed | 0 failed |. With the select removed, it fails at each ofthe four targets:
[doctest] assertions: 28 | 24 passed | 4 failed |.test case CRASHED: SIGFPE - Floating point error signalwith[doctest] assertions: 1 | 1 passed | 0 failed |; arm64, whichcompiles
main's loops and norms, passed 8 of 8. After: x86-64[doctest] test cases: 329 | 329 passed | 0 failed | 16 skipped, arm64[doctest] test cases: 276 | 276 passed | 0 failed | 16 skipped. With one guard removed at atime, the binary loop, the copy and both norms each crash with SIGFPE; the unary loop's removal
leaves the case passing, since no op in it reaches that loop.
[doctest] assertions: 4 | 2 passed | 2 failed |; the sumprints as 2048 and the product as inf in every printed element, where a build without Highway
gives 4096 and 1. After: x86-64
[doctest] test cases: 330 | 330 passed | 0 failed | 16 skipped. With the widening removed,the same two checks fail.
into its cache. With it off, under ASan with Highway on arm64, at the next PR's head before the move
to
main: the new case failed 5 of 5 runs withERROR: AddressSanitizer: heap-use-after-free, thebuffer freed in
RMSNorm::eval_cpuand written by the copy task; with only RMSNorm fixed, 5 of 5,freed in
LayerNorm::eval_cpu; with both fixed, 5 of 5 clean. After, x86-64[doctest] test cases: 331 | 331 passed | 0 failed | 16 skipped, arm64[doctest] test cases: 277 | 277 passed | 0 failed | 16 skipped. Onmain, at the next PR'shead, the case passes alone under ASan with Highway in 5 of 5 runs, with no AddressSanitizer line.
[doctest] assertions: 6 | 0 passed | 6 failed |, RoPE's[doctest] assertions: 4 | 0 passed | 4 failed |and the sinks'[doctest] assertions: 2 | 0 passed | 2 failed |; arm64, wheremaincomposes these ops, passesall of them. On MLX 0.32.3's composed CPU path (Python), each strided input gives the same output
as its contiguous copy (0 of 512 or 0 of 1024 elements differ), as the tests expect. After, at the
sinks' commit: x86-64
[doctest] test cases: 337 | 337 passed | 0 failed | 16 skipped, arm64[doctest] test cases: 283 | 283 passed | 0 failed | 16 skipped. With one copy removed at atime, its test fails again.
{x, w}crashed,test case CRASHED: SIGSEGV - Segmentation violation signal, with[doctest] assertions: 2 | 0 passed | 2 failed |; arm64 passed[doctest] assertions: 3 | 3 passed | 0 failed |. After: x86-64[doctest] test cases: 338 | 338 passed | 0 failed | 16 skipped, arm64[doctest] test cases: 284 | 284 passed | 0 failed | 16 skipped. With the guard removed, thecrash again.
[doctest] assertions: 1 | 0 passed | 1 failed |, with no crash; arm64 passed,[doctest] assertions: 1 | 1 passed | 0 failed |. After:x86-64
[doctest] test cases: 339 | 339 passed | 0 failed | 16 skipped, arm64[doctest] test cases: 285 | 285 passed | 0 failed | 16 skipped. With the length conditionremoved, the check fails again.
sdpa_highway.cpp, one per target (AVX2 and the four AVX3 targets) and type (float, bf16 andfp16), such as
warning: iteration 2147483634 invokes undefined behavior [-Waggressive-loop-optimizations].GCC 11's Release build gave 12; GCC 12's Debug build and Clang gave none. After: GCC 12 Release, 0
warnings, and
[doctest] test cases: 355 | 355 passed | 0 failed | 0 skipped; the Clang suitesunchanged. With the tail loop's start bound dropped, the 15 warnings return. With
kMaxLanes = 8,the build fails at the four AVX3 targets,
the comparison reduces to '(16 <= 8)'.Mutation checks: undoing the fix, or breaking the test's target, turns the test red again for 1, 3,
4, 7, 8, 10 and 13, and for the counters, the column split and scratch release below. Items 18–21 and
23–26 give theirs above.
What it adds
highway_info.h): each dispatched kernel records its family and the targetthat ran (
HWY_TARGET), and norms, RoPE and the FP-quantized matmul record when they fall back tocode that is not dispatched. Tests restrict dispatch to one target and read back what ran: RMSNorm
ran AVX2, SSE4, SSSE3 and SSE2, each when restricted to it. The int8 family records only when the
int8 path ran.
MLX_CPU_THREADSwhen set; otherwise the physical cores in the affinitymask, capped by the cgroup v2
cpu.maxquota. In an x86-64 container whose quota is 8 CPUs:threads 8 (cgroup cpu.max), pool 8; undertaskset -c 0-2:threads 3 (physical cores), pool 3.An invalid value is recorded and the default is used. OpenBLAS is pinned to one thread at every
pool size ("Pin OpenBLAS to one thread at every CPU pool size"): before, at
MLX_CPU_THREADS=1itran 9 threads.
across the pool, each slice calling
cblas_sgemmon its own columns ("Split short fp32 GEMMs bycolumns across the CPU pool"). No speed is claimed: nothing here was timed.
per-thread float32 scratch through a lease that frees a buffer larger than 64 MiB when the operation
ends ("Free CPU kernel scratch that grew past 64 MiB"). Without it, 78381056 bytes stayed after one
test call. A second lease on the same thread throws
std::logic_error("Refuse a nested scratchlease").
precision.h):set_quantized_int8(),quantized_int8(),quantized_int8_available(), andMLX_CPU_QUANTIZED_INT8, read as MLX reads its variables. Off bydefault: unset, a 4-bit matmul that meets every other condition of the int8 path stays within the
float32 bound; switched on, it leaves it.
quantized_float32_accumulation()is a test hook incpu::detail("Make quantized_float32_accumulation() a test hook in cpu::detail").Boundaries
precision.cpp. Every change to afile
mainhas is behindMLX_USE_HIGHWAY_KERNELS, except in build files and tests. Checked withunifdef -UMLX_USE_HIGHWAY_KERNELS -UMLX_USE_HIGHWAY_JIT_SIMDat this branch's last commit: of the25 files it changes that
mainhas, 15 reduce to theirmaintext, among them the Linux-onlyno_gpu/primitives.cpp,gemms/simd_bf16.cppandgemms/simd_fp16.cpp. The other 10 are the buildfiles, which add the
MLX_USE_HIGHWAYoption and its settings,precision.cpp(in the no-CPUbackend's source list too) and one empty variable, and put the rest under
if(MLX_USE_HIGHWAY); thetests, among them
tests/ops_tests.cpp, whose 462 changed lines are all added cases (those of items18–20 and 22–25); and
quantized.cpp, whose one remaining difference is a comment inside its own#if !defined(MLX_USE_HIGHWAY_KERNELS).simd/base_simd.handsimd/math.hgain 83 and 103 lines, all behind the macro.tests/fast_tests.cppcompiles and runs in every build. Its MSVC-only*_highway_dispatch.cppfiles compile in no build here.
quantized.cppis chosen by file: without Highway this repository'sown
quantized.cppcompiles, with Highway Add support for x86 SIMD with Highway ml-explore/mlx#3019's, kept asquantized_highway_backend.cpp.precision.cpp: the int8 switch compiles in every build, the no-CPU backend'sincluded, since
fast_tests.cppcalls it. Without the int8 path it changes nothing:quantized_int8_available()is false.scripts/check-macos-identity.pypreprocesses the 195Cmlxsources SwiftPM compiles on macOS and compares the 135 files the Xcode project compiles, at
vmlx-swift's
mainand with this branch as itsmlxsubmodule:macOS identity holds: 195 Cmlx sources and 135 Xcode members compile the same. Before the move tomainit was also run along the branch, from "Put Add support for x86 SIMD with Highway ml-explore/mlx#3019's changes to shared CPU files behindMLX_USE_HIGHWAY_KERNELS" on, and found only new files, which vmlx-swift excludes on Apple platforms.
The check covers SwiftPM and Xcode, not CMake: MLX's CMake build on macOS compiles
precision.cpptoo (vmlx-swift's macOS CMake build:
[257/257]at itsmain,[258/258]with this branch).MLX_USE_HIGHWAYis on by default only for Linux x86-64. A fresh x86-64 configureenables Highway; a fresh arm64 configure does not, and
-DMLX_USE_HIGHWAY=ONon arm64 is refused(
MLX_USE_HIGHWAY requires an x86-64 target). These configures ran on the old base; the build filesadd the same lines at the last commit. Windows and Intel macOS default to off (code, not built).
MLX_ENABLE_X86_SIMD, Add support for x86 SIMD with Highway ml-explore/mlx#3019's name, sets it on any configure ("Fix the edges of the Highway CMakeoption").
MLX_USE_HIGHWAY_KERNELSis public ("Make MLX_USE_HIGHWAY_KERNELS a public compiledefinition"): installed headers (
fast_primitives.h,unary.h,binary.h) change with it, so thetests and the exported
MLXtarget get it. Code compiled against the installed headers without thattarget must define it when libmlx was built with Highway.
Verified
At the last commit, in Debian 12 containers (x86-64 under Rosetta, and arm64), unless marked:
tests/tests):[doctest] test cases: 339 | 339 passed | 0 failed | 16 skipped; the same withMLX_CPU_THREADS=1. The 16 are the CPU-JIT cases, which our Clang builds skip, formaintoo; theGCC builds below run them.
[doctest] test cases: 285 | 285 passed | 0 failed | 16 skipped.[doctest] test cases: 355 | 355 passed | 0 failed | 0 skipped,with 0 warnings; Release, built fresh, 0 warnings.
off): ASan and UBSan,
[doctest] test cases: 301 | 301 passed | 0 failed | 0 skippedeach, with 0warning or error lines and 0 AddressSanitizer reports. UBSan reports the same 20 runtime errors as
main, one of them at a moved line ofbase_simd.h; none is in Add support for x86 SIMD with Highway ml-explore/mlx#3019's code or ours.libmlx.so):[doctest] test cases: 339 | 339 passed | 0 failed | 16 skipped.composed path when keys and values differ in length". The last commit changes only
sdpa_highway.cpp, which builds without Highway do not compile, so the arm64 results hold for it;the shared-library build did not run again.
fork-runtime-contracts, at the commit before the last: the job's build and contracts, run locallyas a stand-in with GCC 11.3.0, Release and Highway on, and with Ninja where the job uses Unix
Makefiles:
PASS 15 CPU runtime contractsin each of four runs, as inmain's four.test_quantized,Ran 48 testsandOK (skipped=8), withtest_qqmv_nvfp4_global_scale, whichthis PR adds, among the passes;
test_ops'test_maximum,test_minimum,test_to_from_fp8,test_floor_divideandtest_remainder,OK.VMLXCPUKernelTests): each kernel family runs at every Highwaytarget the host runs, one at a time, against float64 references and derived bounds, with
MLX_CPU_THREADS=1and with the default pool.main, with this branch as itsmlxsubmodule: x86-64 at
AVX2 SSE4 SSSE3 SSE2 EMU128, and arm64 without Highway:✔ Test run with 57 tests in 12 suites passedin both pool configurations.main(run 36745683516): the same on a native
x86-64 runner (
CPU: AMD EPYC 7763 64-Core Processor, targetsAVX2 SSE4 SSSE3 SSE2 EMU128) and onan arm64 runner (Highway off); under Intel SDE (emulated Sapphire Rapids), the per-target subset at
AVX3_SPR AVX3_DL AVX3 AVX2 SSE4 SSSE3 SSE2 EMU128:✔ Test run with 22 tests in 5 suites passed.(run 40005531639): on a native x86-64
runner with AVX-512 (
CPU: AMD EPYC 9V74 80-Core Processor), atAVX3_ZEN4 AVX3_DL AVX3 AVX2 SSE4 SSSE3 SSE2 EMU128, and on an arm64 runner (Highway off),✔ Test run with 57 tests in 12 suites passedin both pool configurations; under SDE, the per-targetsubset at
AVX3_SPR AVX3_DL AVX3 AVX2 SSE4 SSSE3 SSE2 EMU128:✔ Test run with 22 tests in 5 suites passed.(
CPU: AMD EPYC 9V45 96-Core Processor), atAVX3_ZEN4 AVX3_DL AVX3 AVX2 SSE4 SSSE3 SSE2 EMU128, inboth configurations (run 36404542342).
Debug, Highway on, no suppressions): the pool and threaded-kernel subset,
[doctest] test cases: 74 | 74 passed | 0 failed | 284 skipped, and the whole suite, 358 of358, with no ThreadSanitizer warning; twelve more runs of the subset, at pool sizes default, 1, 2 and
4, each exit 0 with no warning.
mainholds Make scheduler active task observations atomic #15 and Synchronize CPU and Metal allocator statistics #16, which made atomic the two counters thatevery earlier run reported.
for
main:DEVICE=cpu,[doctest] test cases: 329 | 329 passed | 0 failed | 0 skipped. OnMetal, the first run failed only
test concurrent allocator statistics(
values: CHECK_EQ( 0, 16 )), asmain's first run did, and the rerun passed 329 of 329. The 21cases this PR adds to
main's passed on both devices.mainand with thisbranch: the same results on both, in the same order
(
Executed 567 tests, with 3 tests skipped and 7 failures). The failures, and the Xcode project'stest build, which fails, are vmlx-swift
main's; neither this PR nor vmlx-swift's change touchesthe files involved.
11 texts with Granite Embedding R2 and with its 8-bit conversion and compares them with stored
references:
PASS granite: 11 texts against base.fp32andPASS granite-q8: 11 texts against q8.fp32, andint8 switch: same output. Its output isidentical to the probe's run before the move, at "Keep the whole 4-bit dot product in the int8 path
on every target", which gave
worst raw 7.305576e-07 of max |truth| (bound 1e-4)for granite.main:mainmoved twice while this PR was rebuilt on it (Accept LFM feed-forward JANGH banks in named mmap #23–Mixed BF16/F16 q4 qmv: widen before the affine bias sum #25, then Use allocator-owned safetensors despite legacy mmap settings #27), in filesthis PR does not change. Each time, the commits replayed with no conflict, the new tip's diff from
the old equals
main's own change, and the suites gave the same counts, plusmain's three newcases the first time.
Not verified
2026-10-08, none at
main's later commits, and the cause is not known to us. CI's Fedora jobs buildwith GCC 15.2.1 and its sanitizer jobs with GCC 11.4.0; our mirrors used GCC 12.2 and GCC 11, and no
GCC 15 build ran on x86-64. Fedora's aarch64 leg without a sanitizer did not run here.
fork-runtime-contracts' duration on CI: the job runs only in this repository, and the localstand-in above gives no estimate of it.
above, with Highway. Without it, Add support for x86 SIMD with Highway ml-explore/mlx#3019's
test_qqmv_nvfp4_global_scale, which skips only on theGPU, is likely to fail on the CPU, by the code:
qqmmpasses the nvfp4 global scales as inputs, andQQMatmul::eval_cpuin this repository'squantized.cppreads none.CI job, on the per-target subset (above). AVX3_ZEN4, AVX3_DL and AVX3 ran natively in vmlx-swift's CI,
at the commit before the pool fix and at the last commit (above); the containers run AVX2 and below.
test it. The containers' kernels show one CPU per core, where the old and new keys agree.
that force it on, as the next PR does, or from the next PR's branch.
are unchanged.
control, not a measurement.
only.
code were not run under it. The fixed cases ran under ASan with Highway in the next PR's branch on
arm64, with no report; this PR's own arm64 ASan build has no Highway, so it runs
main's composednorms.
pre-commitover the whole branch:check_lintruns it on this PR.🤖 Generated with Claude Code