Skip to content

CPU backend: adopt ml-explore/mlx#3019's Highway kernels on Linux x86-64 - #10

Merged
jjang-ai merged 66 commits into
osaurus-ai:mainfrom
rcfa:hwy/adopt-x86
Nov 22, 2026
Merged

jjang-ai merged 66 commits into
osaurus-ai:mainfrom
rcfa:hwy/adopt-x86

Conversation

@rcfa

@rcfa rcfa commented Sep 28, 2026 •

Copy link
Copy Markdown

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 also
merges main at 61cc7a4 (#55) and has 15 more commits that port the CPU fixes merged there to its
Highway code (listed in the PR's comments). Without Highway, the library compiles the same code as main, except
precision.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's
quantized matmul in quantized.cpp), merged in #55, and this PR is adapted to them: 0a10b88ce passes
lda and ldb to simd_gemm in the Highway low-precision GEMM (#26), and 35a2a85bc keeps Highway
builds on the promoting quantized matmul, since their kernels read #11's f16 scales as bf16.

What it adopts

  • Add support for x86 SIMD with Highway ml-explore/mlx#3019's first two commits, cherry-picked with -x, author kept: "Add Highway-backed x86 CPU SIMD
    and threading" and "Adjust for runtime dynamic selection". The first conflicts with MLX 0.32.3 in
    five files; the resolutions are inside the pick.
  • Two commits that made them build on MLX 0.32.2, whose simd::sincos (upstream Send out of range trig arguments to libm ml-explore/mlx#4157) writes single
    lanes: "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 sin and cos 0 in every lane of a vector that holds an argument past 2^23. A test
    covers 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 (item
    18 below).
  • Bisect: on MLX 0.32.3, x86-64 with Highway does not build at "Fix the Highway build on MLX
    0.32.2: writable Simd lanes": binary.cpp fails with 7 errors, each
    no matching function for call to 'divide', until the next commit, "Fix the Highway build on MLX
    0.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".
  • Not adopted: Add support for x86 SIMD with Highway ml-explore/mlx#3019's third commit, "Use 64-bit file seeks on Windows". It changes only
    mlx/io/load.h and does not need Highway, but it sends all eight lseek calls of MLX's file reader
    and writer through a new seek_fd, so it changes what macOS compiles. vmlx-swift does not build on
    Windows.
  • Not adopted: Add support for x86 SIMD with Highway ml-explore/mlx#3019's CPU JIT ("Keep the fork's CPU JIT"). Its rule for the scalar preamble passes
    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).

  1. From 32 rows on, Add support for x86 SIMD with Highway ml-explore/mlx#3019 dequantizes transposed weights for SGEMM, reading 32 / bits values per
    word, 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")
  2. QQMatmul's simulated activations round as upstream does: to_fp8_e8m0_round_up (Round mxfp8 block scales up to avoid saturation ml-explore/mlx#4353) and
    to_fp4_e2m1. ("Round QQMatmul's simulated activations as upstream does")
  3. SDPA sends unequal head dimensions, head dimensions above 256, and dtypes other than float32,
    float16 and bfloat16 to the fallback, and eval_cpu refuses them. ("Send attention the native CPU
    kernel cannot hold to the fallback")
  4. The facade computes float64 lanes in double: it called libm in float for every lane type. ("Compute
    float64 elementwise math in double in the Highway facade")
  5. Integer pow with a negative exponent returns 0, as base_simd.h does since upstream Stop integer power from hanging on a negative exponent ml-explore/mlx#4100; it
    looped forever. ("Return 0 for integer pow with a negative exponent in the Highway facade")
  6. bf16 and fp16 reduction partials stay in float until the end. Add support for x86 SIMD with Highway ml-explore/mlx#3019 rounded each thread's partial
    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")
  7. The facade's fma rounds once. It runs at Highway's static target, SSE2 on x86-64, where it
    rounded twice. ("Round once in the Highway facade's fma, on every target")
  8. float16 inf and NaN survive Highway's emulated float16 conversion, in the facade and in the loads
    the dispatched kernels share. ("Keep float16 inf and NaN through Highway's conversions")
  9. floor, ceil, round and trunc keep the sign of zero at SSE2. ("Keep the sign of zero in the
    Highway facade's floor, ceil and rint")
  10. The int8 activation path, which Add support for x86 SIMD with Highway ml-explore/mlx#3019 takes whenever env::enable_tf32() is true (MLX's
    default), 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")
  11. The int8 path keeps the second accumulator of ReorderWidenMulAccumulate, which it dropped.
    ("Keep the whole 4-bit dot product in the int8 path on every target")
  12. float64 RMSNorm, LayerNorm and RoPE compose through the fallback instead of throwing. (in "Record
    which Highway target each CPU kernel family ran")
  13. The pool catches every slot's exception and rethrows the first, waits for every slot, runs a
    nested parallel_for inline, and pins OpenBLAS to one thread even with OPENBLAS_NUM_THREADS
    set. ("Size the CPU pool to the CPUs the process may use, and harden it")
  14. cpu::ThreadPool is exported, so a shared-library build of the tests links. ("Export
    cpu::ThreadPool from shared builds")
  15. The pool claims a slot with one compare-and-swap, on a word that holds the call's generation, its
    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 in
    the CPU pool")
  16. Simd<bool, N> built from a vector reads each lane as static_cast<bool> does: it compares the lane
    with zero. Before, it took Highway's MaskFromVec, which Highway defines only for lanes of all zeros
    or 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), FromFP8 takes its sign from the bits and
    builds no Simd<bool>, so the fix has no caller here; the fix and its test stay. ("Read each lane as
    C++ does when a vector becomes Simd")
  17. The pool's default counts a core by the CPUs it holds: its package and the first CPU of its
    core_cpus_list (thread_siblings_list before Linux 5.3). It counted (physical_package_id, core_id) pairs, but core_id is not unique within a package on every kernel: x86 kernels from 5.3
    until 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_id in 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")
  18. The facade gains a vector 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's Divide through
    simd::divide, which the facade lacked, so binary.cpp did not compile with Highway. divide
    gives 0 for an integer quotient by zero, and remainder the dividend for a remainder by zero, as
    base_simd.h does; the facade's integer remainder by zero trapped on x86-64. ("Fix the Highway
    build on MLX 0.32.3: a vector divide")
  19. E4M3 codes 0x7F and 0xFF decode as NaN under Highway, as MLX 0.32.3 (Fix mx.from_fp8 E4M3FN NaN decode with branchless carry ml-explore/mlx#4376) decodes them; Add support for x86 SIMD with Highway ml-explore/mlx#3019
    gave 480 and −480. The quantized backend's table holds NaN for them, for the paths that still read
    it (the non-transposed fp_qmm and the nvfp4 scales). The dispatched kernels keep Add support for x86 SIMD with Highway ml-explore/mlx#3019's bit
    decode, 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 it from_fp8, computes main's float16
    bits 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")
  20. Add support for x86 SIMD with Highway ml-explore/mlx#3019's threaded strided binary loop, its general copy and strided unary loops, and its native
    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")
  21. float16 sums and products accumulate in float under Highway. MLX 0.32.3 (Widen float16/bfloat16 to float32 in cpu reduce ml-explore/mlx#4387) widens float16 to
    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")
  22. RMSNorm and LayerNorm keep their copy of a non-contiguous input alive until their tasks run.
    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_cpu returned,
    before the tasks ran. The copy is now registered as a temporary, as main's logsumexp does. ("Keep
    the norms' input copy alive until their tasks run")
  23. Add support for x86 SIMD with Highway ml-explore/mlx#3019's native RMSNorm and LayerNorm read the weight and bias, its RoPE the offsets and freqs, and
    its attention the sinks through plain pointers with stride 1. The fast:: functions pass these on
    as 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")
  24. QQMatmul refuses an unquantized w under Highway, as it does without. Without Highway, the CPU's
    QQMatmul supports only a quantized w and one row of x, and throws "[QQMatmul] NYI for the
    general case" for any other input. qqmm also passes an unquantized w, alone or with scales or
    nvfp4 global scales, and Add support for x86 SIMD with Highway ml-explore/mlx#3019's QQMatmul read inputs[2] as the packed scales and w as packed
    values 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 K w
    (from the code, not run). With {x, w} only, it read past the end of its inputs. It now throws the
    same error for any unquantized w, before it reads an input. More than one row of x, which the
    code without Highway refuses, stays supported (from the code; no test covers it). ("Reject an
    unquantized weight in QQMatmul under Highway")
  25. Attention sends keys and values of different lengths to the composed path.
    fast::scaled_dot_product_attention checks that keys and values have the same number of heads, but
    not 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")
  26. The native attention kernel's per-lane buffers are bounded at compile time. It keeps four buffers
    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-time
    check keeps hn::MaxLanes within it, so that a wider target fails to compile. The tail loop that
    fills 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 are
the branch's counts then. Items 18–26 were tested on main (MLX 0.32.3). An item that also ran on the
other base says so.

  1. x86-64, 3/5/6 bits at groups 32, 64 and 128: outside the float32 bound at 32, 33 and 64 rows only,
    and in gather_qmm (values: CHECK( 1.66975 < 1e-05 )). After:
    [doctest] test cases: 265 | 265 passed | 0 failed | 16 skipped.
  2. mxfp4 ties: values: CHECK( 0.5 == 1 ) for values[i] := 0.75; mxfp8 block scale:
    values: CHECK( 448 == 576 ). After: [doctest] test cases: 267 | 267 passed | 0 failed | 16 skipped.
  3. Before: the test process aborted, munmap_chunk(): invalid pointer (which shape did it is not
    logged). 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.
  4. [doctest] assertions: 68 | 4 passed | 64 failed |, then 68 | 68 passed.
  5. STALLED: no test output for 60 s; killing the tests., then 17 | 17 passed.
  6. On MLX 0.32.3, with the commit's tests on its parent's 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 float
    before this code. With the commit's reduce.cpp, both pass. On the old base, 2^20 + 3 bf16 ones and
    one −2^20 gave values: CHECK( 0 == 3 ) with 8 threads and values: CHECK( -8192 == 3 ) with 9 and
    with 12.
  7. erfinv near 1: values: CHECK( 64.6857 <= 8 ) units in the last place, then
    values: CHECK( 2.05542 <= 8 ).
  8. [doctest] assertions: 384 | 272 passed | 112 failed | (sin(inf) gave 0.691895), then
    384 | 384 passed. The kernels' loads: vmlx-swift's test of the norm kernels passes at every
    target the host runs, and fails at each of them once its reference reads exponent 31 as the
    software conversion does.
  9. [doctest] assertions: 512 | 464 passed | 48 failed |, each on the sign, the same in all four
    dtypes; then 512 | 512 passed.
  10. With the path's gates as Add support for x86 SIMD with Highway ml-explore/mlx#3019 has them, the default 4-bit matmul leaves the float32 bound. On
    arm64 before: [doctest] test cases: 263 | 261 passed | 2 failed | 16 skipped (the two
    token tests); after: [doctest] test cases: 249 | 249 passed | 0 failed | 16 skipped. On main,
    at the commit before it: [doctest] test cases: 274 | 272 passed | 2 failed | 16 skipped, the
    two token tests again.
  11. vmlx-swift's quantized-matmul test at EMU128: ↳ int8 on EMU128: element 55 is 43.309791564941406, float64 gives -41.17641308103933, 6.094187488224424 times its bound. AVX2, SSE4, SSSE3 and SSE2
    passed before the fix; Highway 1.4.0's x86 code ignores sum1. On NEON, Highway 1.4.0 puts the
    upper half's products in sum1, so the path would lose them there; not run.
  12. 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.
  13. A worker's exception: 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 with
    OPENBLAS_NUM_THREADS=4: values: CHECK( 4 == 1 ). After:
    [doctest] test cases: 290 | 290 passed | 0 failed | 16 skipped.
  14. -DBUILD_SHARED_LIBS=ON on 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.
  15. A test hook holds a worker at each window. Before: the first parallel_for did not return in 5 s,
    slot 1 ran with nth 3 and slot 1 ran 0 times; after: test cases: 2 | 2 passed, also in 50 of
    50 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 fix new stress runs: 143 runs, 143 with 'bad slots=0'; hung: 0; TSan reports: 0.
  16. A test builds Simd<bool, N> from vectors whose lanes are neither zero nor all ones: uint8_t at
    2, 4, 8 and 16 lanes, uint32_t, int32_t, float and double, each value in every lane. Before,
    on x86-64: test cases: 2 | 0 passed | 2 failed, e.g. values: CHECK( false == true ) for a
    uint8_t lane of 0x1, and values: CHECK( true == false ) for a float lane of -0x0p+0; after,
    the whole suite: test cases: 299 | 299 passed. On the old base, where FromFP8 still built a
    Simd<bool>, test fp8 conversion failed 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).
  17. A synthetic sysfs tree: two clusters of four cores whose core_id restarts, SMT siblings listed as
    8-9, a pre-5.3 kernel's thread_siblings_list of 10,12, and CPUs without a list. Before, on
    x86-64: values: CHECK( 4 == 8 ) and values: CHECK( 1 == 2 ) for the cluster counts, the three
    direct key checks failing, and values: CHECK_FALSE( true ) for a CPU with a core_id but no list;
    after, the whole suite: test cases: 300 | 300 passed. On arm64 with Highway on, in the next
    PR's branch on top of this commit: test cases: 303 | 303 passed; at that branch's head on
    main: [doctest] test cases: 342 | 342 passed | 0 failed | 16 skipped.
  18. Before, at "Fix the Highway build on MLX 0.32.2: writable Simd lanes", x86-64 (built with
    ninja -k 0): 7 errors, each no matching function for call to 'divide' at binary_ops.h:28:27,
    and only binary.cpp.o failed. With a divide that divides each integer lane as operator/ does,
    the new case, floor_divide and remainder on int32, uint32 and uint8 with zero divisors in whole
    vectors and in the tail, crashed in its first check:
    test case CRASHED: SIGFPE - Floating point error signal and
    [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 two
    token tests. With either rule removed alone, the case crashes with SIGFPE again.
  19. The quantized matmuls, with the quantized sources before the fix, on x86-64: the new case fails its
    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 for
    code 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 and
    0xFF in whole vectors and in the tail, in float32, float16 and bfloat16, and for dequantize of
    mxfp8 weights and nvfp4 scales: [doctest] assertions: 24 | 0 passed | 24 failed |; arm64 passes 24
    of 24. After, x86-64: [doctest] test cases: 300 | 300 passed | 0 failed | 16 skipped. With
    the 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 of
    the four targets: [doctest] assertions: 28 | 24 passed | 4 failed |.
  20. Before, on x86-64: the new case crashed after its first check,
    test case CRASHED: SIGFPE - Floating point error signal with
    [doctest] assertions: 1 | 1 passed | 0 failed |; arm64, which
    compiles 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 a
    time, 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.
  21. Before, on x86-64: both checks fail, [doctest] assertions: 4 | 2 passed | 2 failed |; the sum
    prints 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.
  22. With the CPU buffer cache on, AddressSanitizer saw nothing: the allocator recycles a freed buffer
    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 with ERROR: AddressSanitizer: heap-use-after-free, the
    buffer freed in RMSNorm::eval_cpu and 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. On main, at the next PR's
    head, the case passes alone under ASan with Highway in 5 of 5 runs, with no AddressSanitizer line.
  23. Before, on x86-64, each test fails all its checks, on wrong values, with no crash: the norms'
    [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, where main composes these ops, passes
    all 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 a
    time, its test fails again.
  24. Before, on x86-64: the checks with scales and with global scales did not throw, and the check of
    {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, the
    crash again.
  25. Before, on x86-64: the test's one check did not throw,
    [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 condition
    removed, the check fails again.
  26. Before, a fresh GCC 12 Release build on x86-64 gave 15 warnings, all at the same line of
    sdpa_highway.cpp, one per target (AVX2 and the four AVX3 targets) and type (float, bf16 and
    fp16), 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 suites
    unchanged. 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

  • Dispatch counters (highway_info.h): each dispatched kernel records its family and the target
    that ran (HWY_TARGET), and norms, RoPE and the FP-quantized matmul record when they fall back to
    code 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.
  • The thread policy: MLX_CPU_THREADS when set; otherwise the physical cores in the affinity
    mask, capped by the cgroup v2 cpu.max quota. In an x86-64 container whose quota is 8 CPUs:
    threads 8 (cgroup cpu.max), pool 8; under taskset -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=1 it
    ran 9 threads.
  • The column split: fp32 SGEMMs with fewer than 16 rows and M·N·K ≥ 65536 split by columns
    across the pool, each slice calling cblas_sgemm on its own columns ("Split short fp32 GEMMs by
    columns across the CPU pool"). No speed is claimed: nothing here was timed.
  • Scratch release: the dequantize-then-SGEMM path and the low-precision GEMMs borrow their
    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 scratch
    lease").
  • The int8 switch (precision.h): set_quantized_int8(), quantized_int8(),
    quantized_int8_available(), and MLX_CPU_QUANTIZED_INT8, read as MLX reads its variables. Off by
    default: 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 in
    cpu::detail ("Make quantized_float32_accumulation() a test hook in cpu::detail").

Boundaries

  • Without Highway, nothing changes but build files, tests and precision.cpp. Every change to a
    file main has is behind MLX_USE_HIGHWAY_KERNELS, except in build files and tests. Checked with
    unifdef -UMLX_USE_HIGHWAY_KERNELS -UMLX_USE_HIGHWAY_JIT_SIMD at this branch's last commit: of the
    25 files it changes that main has, 15 reduce to their main text, among them the Linux-only
    no_gpu/primitives.cpp, gemms/simd_bf16.cpp and gemms/simd_fp16.cpp. The other 10 are the build
    files, which add the MLX_USE_HIGHWAY option and its settings, precision.cpp (in the no-CPU
    backend's source list too) and one empty variable, and put the rest under if(MLX_USE_HIGHWAY); the
    tests, among them tests/ops_tests.cpp, whose 462 changed lines are all added cases (those of items
    18–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.h and simd/math.h gain 83 and 103 lines, all behind the macro.
  • Add support for x86 SIMD with Highway ml-explore/mlx#3019's new files: none of its new library sources compiles without Highway; its
    tests/fast_tests.cpp compiles and runs in every build. Its MSVC-only *_highway_dispatch.cpp
    files compile in no build here. quantized.cpp is chosen by file: without Highway this repository's
    own quantized.cpp compiles, with Highway Add support for x86 SIMD with Highway ml-explore/mlx#3019's, kept as quantized_highway_backend.cpp.
  • The exception, precision.cpp: the int8 switch compiles in every build, the no-CPU backend's
    included, since fast_tests.cpp calls it. Without the int8 path it changes nothing:
    quantized_int8_available() is false.
  • What macOS compiles: vmlx-swift's scripts/check-macos-identity.py preprocesses the 195 Cmlx
    sources SwiftPM compiles on macOS and compares the 135 files the Xcode project compiles, at
    vmlx-swift's main and with this branch as its mlx submodule:
    macOS identity holds: 195 Cmlx sources and 135 Xcode members compile the same. Before the move to
    main it 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 behind
    MLX_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.cpp
    too (vmlx-swift's macOS CMake build: [257/257] at its main, [258/258] with this branch).
  • Default: MLX_USE_HIGHWAY is on by default only for Linux x86-64. A fresh x86-64 configure
    enables Highway; a fresh arm64 configure does not, and -DMLX_USE_HIGHWAY=ON on arm64 is refused
    (MLX_USE_HIGHWAY requires an x86-64 target). These configures ran on the old base; the build files
    add 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 CMake
    option").
  • MLX_USE_HIGHWAY_KERNELS is public ("Make MLX_USE_HIGHWAY_KERNELS a public compile
    definition"): installed headers (fast_primitives.h, unary.h, binary.h) change with it, so the
    tests and the exported MLX target get it. Code compiled against the installed headers without that
    target 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:

  • The C++ suite (tests/tests):
    • x86-64, Clang 21, Release, Highway on:
      [doctest] test cases: 339 | 339 passed | 0 failed | 16 skipped; the same with
      MLX_CPU_THREADS=1. The 16 are the CPU-JIT cases, which our Clang builds skip, for main too; the
      GCC builds below run them.
    • arm64, Clang 21, Release, Highway off: [doctest] test cases: 285 | 285 passed | 0 failed | 16 skipped.
    • x86-64, GCC 12.2, Highway on: Debug, [doctest] test cases: 355 | 355 passed | 0 failed | 0 skipped,
      with 0 warnings; Release, built fresh, 0 warnings.
    • This repository's sanitizer job, mirrored on arm64 with GCC 11 (Debug, warnings as errors, Highway
      off): ASan and UBSan, [doctest] test cases: 301 | 301 passed | 0 failed | 0 skipped each, with 0
      warning or error lines and 0 AddressSanitizer reports. UBSan reports the same 20 runtime errors as
      main, one of them at a moved line of base_simd.h; none is in Add support for x86 SIMD with Highway ml-explore/mlx#3019's code or ours.
    • x86-64, a shared-library build (libmlx.so):
      [doctest] test cases: 339 | 339 passed | 0 failed | 16 skipped.
    • The sanitizer mirrors and the shared-library build ran at the commit before the last, "Take sdpa's
      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 locally
    as 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 contracts in each of four runs, as in main's four.
  • MLX's Python tests, x86-64 with Highway (GCC 12.2, Release), at the commit before the last:
    test_quantized, Ran 48 tests and OK (skipped=8), with test_qqmv_nvfp4_global_scale, which
    this PR adds, among the passes; test_ops' test_maximum, test_minimum, test_to_from_fp8,
    test_floor_divide and test_remainder, OK.
  • vmlx-swift's CPU kernel tests (VMLXCPUKernelTests): each kernel family runs at every Highway
    target the host runs, one at a time, against float64 references and derived bounds, with
    MLX_CPU_THREADS=1 and with the default pool.
    • In the containers, in vmlx-swift's change rebuilt on its main, with this branch as its mlx
      submodule: x86-64 at AVX2 SSE4 SSSE3 SSE2 EMU128, and arm64 without Highway:
      ✔ Test run with 57 tests in 12 suites passed in both pool configurations.
    • In vmlx-swift's CI, at this PR's head before it moved to main
      (run 36745683516): the same on a native
      x86-64 runner (CPU: AMD EPYC 7763 64-Core Processor, targets AVX2 SSE4 SSSE3 SSE2 EMU128) and on
      an 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.
    • In vmlx-swift's CI at the last commit
      (run 40005531639): on a native x86-64
      runner with AVX-512 (CPU: AMD EPYC 9V74 80-Core Processor), at
      AVX3_ZEN4 AVX3_DL AVX3 AVX2 SSE4 SSSE3 SSE2 EMU128, and on an arm64 runner (Highway off),
      ✔ Test run with 57 tests in 12 suites passed in both pool configurations; under SDE, the per-target
      subset at AVX3_SPR AVX3_DL AVX3 AVX2 SSE4 SSSE3 SSE2 EMU128:
      ✔ Test run with 22 tests in 5 suites passed.
    • At the commit before the pool fix, on a native x86-64 runner with AVX-512
      (CPU: AMD EPYC 9V45 96-Core Processor), at AVX3_ZEN4 AVX3_DL AVX3 AVX2 SSE4 SSSE3 SSE2 EMU128, in
      both configurations (run 36404542342).
  • ThreadSanitizer, in the next PR's branch on arm64, which holds all of this PR's commits (GCC 12,
    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 of
    358, with no ThreadSanitizer warning; twelve more runs of the subset, at pool sizes default, 1, 2 and
    4, each exit 0 with no warning. main holds Make scheduler active task observations atomic #15 and Synchronize CPU and Metal allocator statistics #16, which made atomic the two counters that
    every earlier run reported.
  • This repository's C++ suite on macOS (on the host: CMake, Release, Metal on, Highway off), built as
    for main: DEVICE=cpu, [doctest] test cases: 329 | 329 passed | 0 failed | 0 skipped. On
    Metal, the first run failed only test concurrent allocator statistics
    (values: CHECK_EQ( 0, 16 )), as main's first run did, and the rerun passed 329 of 329. The 21
    cases this PR adds to main's passed on both devices.
  • vmlx-swift's macOS build and tests (on the host, Metal), at vmlx-swift's main and with this
    branch: 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's
    test build, which fails, are vmlx-swift main's; neither this PR nor vmlx-swift's change touches
    the files involved.
  • The macOS identity check, as above (on macOS).
  • End to end, on x86-64 (Highway), in vmlx-swift's change with this branch: a vmlx-swift probe embeds
    11 texts with Granite Embedding R2 and with its 8-bit conversion and compares them with stored
    references: PASS granite: 11 texts against base.fp32 and
    PASS granite-q8: 11 texts against q8.fp32, and int8 switch: same output. Its output is
    identical 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.
  • The move to main: main moved 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 files
    this 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, plus main's three new
    cases the first time.

Not verified

  • This PR's own checks at its last commit. This repository's Actions have run no workflow since
    2026-10-08, none at main's later commits, and the cause is not known to us. CI's Fedora jobs build
    with 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 local
    stand-in above gives no estimate of it.
  • MLX's Python tests on CI: the job that runs them is limited to ml-explore/mlx. They ran only as
    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 the
    GPU, is likely to fail on the CPU, by the code: qqmm passes the nvfp4 global scales as inputs, and
    QQMatmul::eval_cpu in this repository's quantized.cpp reads none.
  • AVX3_SPR on hardware: it ran only under Intel SDE (emulated Sapphire Rapids), in vmlx-swift's advisory
    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.
  • The core count on a multi-die x86 or multi-cluster device-tree kernel: only synthetic sysfs trees
    test it. The containers' kernels show one CPU per core, where the old and new keys agree.
  • Highway on arm64: this PR refuses it there. The arm64 results with Highway above come from builds
    that force it on, as the next PR does, or from the next PR's branch.
  • Windows and Intel macOS builds.
  • Metal beyond this repository's C++ suite on macOS and vmlx-swift's macOS tests: the Metal kernels
    are unchanged.
  • The int8 path end to end: the switch is off by default, and the end-to-end probe's int8 run is a
    control, not a measurement.
  • float16 inf and NaN through RoPE's load: the loads' fix is tested through RMSNorm and LayerNorm
    only.
  • Which pool path a kernel took: no counter records it.
  • An op that reaches the strided unary loop's guard (item 20): none is known.
  • AddressSanitizer on the reds of items 23–25: the reads past a buffer that they name as read from the
    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 composed
    norms.
  • Speed: nothing is timed.
  • ThreadSanitizer on x86-64: nothing ran under it.
  • pre-commit over the whole branch: check_lint runs it on this PR.
  • The macOS jobs of this repository's CI are limited to ml-explore/mlx.

🤖 Generated with Claude Code

@rcfa

rcfa commented Sep 28, 2026

Copy link
Copy Markdown
Author

Background for the 16 CPU-JIT cases that this PR's Clang runs skip: they fail in any Linux Clang build of MLX, qwen4-exp included, because the JIT compiles with g++ a preamble that clang++ preprocessed. This PR keeps the fork's JIT as it is. The report below was reproduced on ml-explore/mlx main (a32f0c3) and on a v0.32.2-based build (the qwen4-exp base, 0b9bdfb), on aarch64 and x86_64.

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 g++. In a Clang build the preamble contains libstdc++ as clang++ preprocessed it. libstdc++ selects Clang builtins with __has_builtin (GCC 12: bits/utility.h:146, bits/new_allocator.h:101), and g++ rejects them. So every fused CPU kernel fails to compile.

The prebuilt preamble is used when no headers are installed next to the binary (jit_compiler.cpp:183-191), for example for tests/tests in a build tree. ml-explore#3463 fixed the case with installed headers (ml-explore#3430, ml-explore#3080). This case remains.

Code at main a32f0c3:

  • mlx/backend/cpu/CMakeLists.txt:1-7: off Darwin, COMPILER is ${CMAKE_CXX_COMPILER} and CLANG is FALSE. make_compiled_preamble.sh:27-31 then preprocesses compiled_preamble.h with that compiler (-std=c++17 ... -E -P), which expands the standard headers into the preamble.
  • mlx/backend/cpu/jit_compiler.cpp:273-277: kernels are built with g++ -std=c++17 -O3 -Wall -fPIC -shared ..., and available() checks g++ --version (:209-214).
  • The MSVC branch already handles this (:106-113): "It was generated by the build compiler and may contain compiler-specific builtins, so prefer the same compiler family when possible."

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):

tests/compile_tests.cpp:30: ERROR: CHECK( array_equal(out, array({3.0f, 4.0f})).item<bool>() ) THREW exception: "[Compile::eval_cpu] Failed to compile function Cf4IBroadcastBDf4OAddAC_VS_f4f4_6142509188972423790_contiguous: Failed to execute command with return code 1: "g++ -std=c++17 -O3 -Wall -fPIC -shared  ".../mlx/0.32.3/cpu/Cf4IBroadcastBDf4OAddAC_VS_f4f4_6142509188972423790_contiguous.cpp" -o ".../mlx/0.32.3/cpu/libCf4IBroadcastBDf4OAddAC_VS_f4f4_6142509188972423790_contiguous.so" 2>&1", the output is: .../Cf4IBroadcastBDf4OAddAC_VS_f4f4_6142509188972423790_contiguous.cpp:2840:22: error: '__make_integer_seq' does not name a type
 2840 |       using __type = __make_integer_seq<_IdxTuple, size_t, _Num>;
...
...contiguous.cpp:2856:32: error: 'make_index_sequence' does not name a type; did you mean 'index_sequence'?
...
...contiguous.cpp:17397:53: error: '__builtin_operator_new' was not declared in this scope; did you mean '__builtin_return'?
...
...contiguous.cpp:17407:31: error: '__builtin_operator_delete' was not declared in this scope
...
[doctest] test cases: 1 | 0 passed | 1 failed | 261 skipped
[doctest] assertions: 6 | 2 passed | 4 failed |

The whole suite gives [doctest] test cases: 262 | 246 passed | 16 failed | 0 skipped. The 16 are the cases in tests/compile_tests.cpp that compile a kernel: test simple compile, test compile with grad, test nested compile, test compile with non-finite constants, test compile unary fused, test compile binary fused, test compile gelu, test compile tape with outside parents, test compile internal output, test compile deep graph, test compile repeat input, test fusion kernel reuse, test fusion types, test shapeless compile, test compile strides, test compile random bits.

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 skipped

Desktop (please complete the following information):

  • OS Version: Debian 12 (bookworm), aarch64; CMake 3.25.1, Ninja 1.11.1
  • Compilers: clang 21.0.0 as CMAKE_CXX_COMPILER; g++ 12.2.0 (Debian 12.2.0-14+deb12u1) on PATH
  • Version: main a32f0c3 (0.32.3); also v0.32.2 (aarch64 and x86_64)

Additional context

  • CI does not see this, because the Linux jobs that set Clang build with GCC. .github/scripts/setup+build-cpp-linux-fedora-container.sh:19-20 and .github/scripts/build-sanitizer-tests.sh:4-5 export CMAKE_C_COMPILER and CMAKE_CXX_COMPILER as environment variables. CMake does not read these; it reads CC and CXX. The logs of run 36374719247 (a32f0c3) show The CXX compiler identification is GNU 15.2.1 in both Fedora jobs and GNU 11.4.0 in both sanitizer jobs.
  • Two possible fixes:
    1. Preprocess the preamble with the compiler that the JIT runs. For example, one CMake variable (default g++) used at CMakeLists.txt:5 and passed to jit_compiler.cpp for available() and build_command(). The g++-made preamble above shows that this works.
    2. Or compile the kernels with the build's compiler, as the MSVC branch does. Then clang++ also needs -Wno-invalid-constexpr. With the JIT's flags, clang++ rejects the same kernel source with constexpr function never produces a constant expression [-Winvalid-constexpr] errors, because -E -P removes the system-header line markers. With -Wno-invalid-constexpr, or -Wno-everything as the clang-cl branch adds (:237-242), it compiles.

🤖 Generated with Claude Code

@rcfa

rcfa commented Sep 28, 2026

Copy link
Copy Markdown
Author

The CPU JIT under Clang is fixed separately in #13.

dhiltgen and others added 21 commits October 23, 2026 07:59
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)
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.
rcfa added 16 commits November 22, 2026 14:28
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.
rcfa added a commit to rcfa/mlx that referenced this pull request Nov 22, 2026
… into hwy/arm64

# Conflicts:
#	tests/highway_simd_tests.cpp
@rcfa

rcfa commented Nov 22, 2026

Copy link
Copy Markdown
Author

Updated onto main 61cc7a4 (#55), as suggested there. Thanks for merging the others.

Merge 303d8d4ff. Six files conflicted, each where a fix merged in #55 meets this PR's Highway code. The merge message lists the resolutions:

With MLX_USE_HIGHWAY_KERNELS undefined (unifdef), every changed source file reduces to main's, except one comment in cpu/quantized.cpp that this PR already had. The test files hold the union of main's and this PR's cases.

15 commits port the fixes from #55 to the Highway code:

  • ca35adaa6 Add convert_in_range for Highway vectors
  • a4d45df0a Saturate float to integer conversions in the Highway Simd type
  • 74477bb5f Take the sum order of the Highway Simd type in the block sum tests
  • 5e52728f8 Keep the Highway Simd type out of ops_tests.cpp
  • 2916b318c Declare the Highway test hooks outside the anonymous namespace
  • a430b14e6 Sum long rows in blocks in the Highway norm kernels
  • 97c141ce0 Test an E8M0 scale of 0xFF in Highway builds
  • a073c53b2 Decode an E8M0 scale of 0xFF as NaN in the Highway quantized code
  • 2536f9cd1 Return early from empty quantized matmuls in Highway builds
  • 5a644034f Use the scalar integer divide and remainder in Highway's vector forms
  • a275efd6c Use the scalar integer pow in Highway's vector form
  • acf0c6697 Return early from an empty qqmm in Highway builds
  • 6beda62b8 Accumulate in float32 in the Highway affine quantized matmul
  • 35a2a85bc Keep the CPU on promoting quantized matmuls in Highway builds
  • 0a10b88ce Pass lda and ldb to simd_gemm in the Highway low-precision GEMM

Tests (tests/tests, Release):

🤖 Generated with Claude Code

@jjang-ai

Copy link
Copy Markdown

Validated b6e5b8a42a394be12e3cecad7be5fa57db33b15d against main 61cc7a4d7f510f627098e4a83e09a25bacb3a12a. The final commit guards the four optional Highway dispatch translation units so a SwiftPM build with Highway disabled can compile Cmlx. Both the local macOS CMake build and the Release Osaurus SwiftPM build resolved the exact revision.

  • Local Linux x86-64 tests with Highway enabled passed 409/409. Hosted Linux checks are absent. Dispatching the existing GitHub workflow returned HTTP 422 with “Actions has been disabled for this repository.”
  • With MLX_ENABLE_TF32=0, the 14 extracted macOS CPU/Metal results matched the control by key, dtype, shape and bytes. The candidate native CTest run passed 391/391. The frozen older control had one shared-buffer CTest failure.
  • The frozen control and exact candidate completed the same six-turn native Osaurus workflow. The first requests matched at 2,165 tokens after excluding the application's generated local clock. Both tool calls reported the same five configured agents. All six chat answers in each run ended with stop and showed clean protocol output.
  • After relaunch, both apps restored the same 2,074-token prefix from disk. Sampled physical peaks were 29.676 GiB on control and 29.689 GiB on the candidate. Each three-run local RunBench smoke used 2,292 prompt tokens, generated 175 tokens each time, and restored 2,271 tokens on each repeat.

@jjang-ai
jjang-ai merged commit 99291e6 into osaurus-ai:main Nov 22, 2026
jjang-ai added a commit that referenced this pull request Nov 22, 2026
CPU backend: Highway kernels on Linux arm64 (stacked on #10)
@rcfa
rcfa deleted the hwy/adopt-x86 branch November 23, 2026 00:43
@rcfa rcfa mentioned this pull request Nov 26, 2026
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.

3 participants