Skip to content

Metal NAX: port Muse Glimmer small-M K-split affine GEMM and double-buffered NVFP4 GEMM/QMV - #73

Merged
GumbiiDigital merged 3 commits into
mainfrom
muse-glimmer/challenge-nax-kernels
Dec 4, 2026
Merged

GumbiiDigital merged 3 commits into
mainfrom
muse-glimmer/challenge-nax-kernels

Conversation

@GumbiiDigital

@GumbiiDigital GumbiiDigital commented Dec 3, 2026 •

Copy link
Copy Markdown

Branch muse-glimmer/challenge-nax-kernels @ 500c5d7e (3 commits rebased cleanly onto main @ 56e12b00). Companion Swift PR: Layr-Labs/mlx-swift#79 (to be re-pinned after #73 lands); upstream model-layer PR: Layr-Labs/mlx-swift-lm#580. Ports the production-safe Metal NAX quantized kernel subset from Layr-Labs/mlxfast-muse-glimmer-30b-engine (80b35945 and 9976cc74); none of jonathan308's branches or PRs are touched.

Summary

  1. Opt-in small-M K-split affine NAX GEMM (mlx/backend/metal/kernels/quantized_nax.h, mlx/backend/metal/quantized.cpp, mlx/utils.h):
    • Adds qmm_t_nax_staged_ksplit_impl for 16-bit (float16/bfloat16) affine transposed quantized GEMM and split-K (BM=64, BK=64, BN=64, WM=4, WN=1). When M <= SM (M <= 16; reachable on M5+ NAX for 8 <= M <= 16 via qmm_splitk_nax and 12/13 <= M <= 16 via direct qmm_nax), all 4 simdgroups share the same M rows and split each BK=64 step into four 16-column slices instead of leaving 3 simdgroups idle, then reduce FP32 partials in Ws (12,288 <= 18,432 bytes) with uniform threadgroup barrier participation.
    • Opt-in default (MLX_NAX_KSPLIT=0) + #71 coordination gate: Gated via Metal function constant use_ksplit (index 203) through use_qmm_nax_ksplit(bool allow_ksplit = true) in quantized.cpp (allow_ksplit && env::nax_ksplit() && !env::qmv_batch_invariant()). Default is MLX_NAX_KSPLIT=0 (opt-in only) so production M5 output bits at 8..16 rows remain identical to main until an end-to-end soak proves KV-hash parity; MLX_QMV_BATCH_INVARIANT=1 always suppresses K-split; and qmm() / qmm_nax() accept an optional bool allow_ksplit = true parameter so [Metal] Prefill-row invariance scope: prompt chunks round like the reference rows (opt-in, per thread) #71 only needs to pass /*allow_ksplit=*/ref_rows <= 0 when qmm_splitk falls through to qmm at split_k <= 1 (e.g. large-N lm_head).
  2. Double-buffered NVFP4 NAX GEMM + 6 <= M <= 8 peeled-prefetch QMV (mlx/backend/metal/kernels/fp_quantized_nax.h):
    • Adds FPQuantizedNAXBlockLoader::fetch_nvfp4 / store_nvfp4, double-buffered Ws (kDoubleBuf, 18 KiB) in fp_qmm_t_impl / fp_qmm_t_nax, and bit-manipulation dequantize_fp4_x4_scaled + M <= 8 (reachable at 6 <= M <= 8) peeled 1-ahead prefetch in fp_qmv_nax.
    • Hardened with threadgroup-uniform (K > 0) && ((K & 31) == 0) and 16-byte wl / 2-byte scales alignment guards (plus if (kn < K) around the final peeled prefetch shift in fp_qmv_nax). sizeof(T) == 2 / sizeof(Wtype) == 2 checks the 16-bit threadgroup tile storage width (Wtype = bfloat across transposed/gather kernels for all activation dtypes; activation T in fp_qmm_n_impl) so vec<Wtype, 8> stores remain 16-byte aligned.
  3. Tests, CI & docs:
    • Adds tests/nax_quantized_kernel_tests.cpp logging the active GPU architecture (metal::device(Device::gpu).get_architecture()) and metal::is_nax_available(), testing shapes routed to all new M5 NAX paths (affine split-K N=K=2048 M=8..16, direct staged N=K=4160 M=13..16, unbatched M=512, N=1024 and batched B=2, M=64 NVFP4 double-buffered GEMM, 6 <= M <= 8 peeled QMV, NVFP4 MoE gather fp_gather_qmm_t_nax / fp_gather_qmm_rhs_nax, and genuinely misaligned 4-byte w / 1-byte scales offset fallback bitwise parity).
    • Asserts bitwise M <= 16 vs M = 17 prefix parity when K-split is off (the default MLX_NAX_KSPLIT=0 and MLX_QMV_BATCH_INVARIANT=1), and on NAX hardware (metal::is_nax_available()) asserts bitwise difference under MLX_NAX_KSPLIT=1 to prove qmm_t_nax_staged_ksplit_impl actually dispatched.
    • Adds ctest entry nax_ksplit_enabled (MLX_NAX_KSPLIT=1) in tests/CMakeLists.txt and wires it into .github/workflows/fork-tests.yml so CI runs both the default (MLX_NAX_KSPLIT=0) and opt-in (MLX_NAX_KSPLIT=1) paths.
    • Documents MLX_NAX_KSPLIT (default 0, opt-in) in docs/src/usage/environment_variables.rst and updates fork.yaml (including documenting AGENTS.md from 56e12b00 on main under "Fork tooling" so Fork Diff Check passes cleanly).

Omitted / dropped items from mlxfast-muse-glimmer-30b-engine (4a28444e)

Challenge item Status Reason
steel_gemm_fused_nax.h & steel_gemm_splitk_nax.h early return on sgp_sm <= 0 || sgp_sn <= 0 Dropped Returns before mlx::steel::gemm_loop(...) (steel/gemm/gemm_nax.h:54), which executes threadgroup_barrier(mem_flags::mem_none) every kk0 iteration — divergent barrier UB.
gather_front.cpp (cbv2_array_backing) Dropped Dead contest artifact; Layr-Labs/mlx-swift-lm#580 uses public mlx_array_get_buffer_info + mlx_array_data_uint8.

Placeholders / pending rollout items

Blast Radius / What This Could Affect

Shared seams touched

File / Symbol Behavior changed Models / subsystems affected (M5+ NAX only) Gating / isolation
quantized_nax.h (qmm_t_nax_staged_impl -> qmm_t_nax_staged_ksplit_impl) + quantized.cpp + mlx/utils.h Off by default (MLX_NAX_KSPLIT=0). When opted in (MLX_NAX_KSPLIT=1), splits BK=64 across 4 simdgroups when M <= 16 (reachable for 8 <= M <= 16 via qmm_splitk_nax and 12/13 <= M <= 16 via qmm_nax). Changes FP32 K-reduction summation order (~1 ULP / KV-hash delta vs. stock staged and M >= 17) only when MLX_NAX_KSPLIT=1. Only processes opting into MLX_NAX_KSPLIT=1 running 16-bit (bf16/fp16) affine-quantized models at 8 <= M <= 16 on M5+ NAX. Zero behavior change under default settings. metal::is_nax_available() + use_ksplit FC 203 via use_qmm_nax_ksplit(allow_ksplit) (MLX_NAX_KSPLIT=0 default, disabled when MLX_QMV_BATCH_INVARIANT=1 or allow_ksplit=false).
fp_quantized_nax.h (FPQuantizedNAXBlockLoader::fetch_nvfp4/store_nvfp4, load_unsafe, fp_qmm_t_impl, fp_qmm_t_nax) Vectorized uint4/uchar2 loads, half2 bit-manipulation E2M1 dequantization, and 18 KiB double-buffered Ws in fp_qmm_t_nax (kDoubleBuf = true for non-hgs NVFP4). 0-ULP bit-identical output (confirmed on M5 Max applegpu_g17s). All NVFP4 models on M5+ NAX across all activation dtypes (float, fp16, bf16): fp_qmm_t_nax (double-buffered), fp_gather_qmm_t_nax (MoE gather, single-buffered fast path), fp_gather_qmm_rhs_nax (nt/nn sorted MoE hot path, via load_unsafe()), and fp_qmm_n_nax (16-bit T when instantiated; not host-routed today). metal::is_nax_available(), bits == 4 && group_size == 16 && !has_global_scale, K > 0 && (K & 31) == 0, 16B wl & 2B scales alignment.
fp_quantized_nax.h (fp_qmv_nax + dequantize_fp4_x4_scaled) Bit-manipulation half2 dequantization + 1-ahead peeled prefetch for M <= 8 (reachable at 6 <= M <= 8 via qmv_mma). 0-ULP bit-identical output. All NVFP4 models running 6 <= M <= 8 (N >= 2048) on M5+ NAX (Muse Glimmer 30B NVFP4 and other NVFP4 models). metal::is_nax_available(), bits == 4 && group_size == 16, M <= 8 (6 <= M <= 8 host-routed); MLX_QMV_BATCH_INVARIANT=1 bypasses qmv_mma.

Non-interference

  • Default production builds (M5+ NAX and M1–M4): With MLX_NAX_KSPLIT=0 by default, affine NAX output bits at 8 <= M <= 16 are bit-identical to main. NVFP4 fast paths are 0-ULP bit-identical to stock.
  • M1–M4 Macs and CPU: Zero runtime paths change (metal::is_nax_available() == false).
  • MXFP4 / MXFP8 models (e.g., GPT-OSS 20B MXFP4): Completely untouched (bits == 4 && group_size == 16 excludes group_size == 32 MXFP4/MXFP8).
  • Non-affine / has_global_scale NVFP4 / M > 16 affine NAX: fp_qmm_t_nax with has_global_scale keeps single-buffered Ws and stock loop; M > 16 affine staged NAX runs the unmodified stock loop; sibling models using MXFP4 or non-NAX hardware (GPT-OSS, non-NAX Inkling 2 / Gemma 4 / GLM5-Next / Nemotron / Qwen / MiMo) are unaffected.

Rollback / fail-closed profile

  • Affine K-split is already fail-closed (default MLX_NAX_KSPLIT=0); MLX_QMV_BATCH_INVARIANT=1 and allow_ksplit=false force FC 203 = false even if MLX_NAX_KSPLIT=1 is set.
  • Full rollback: revert these 3 commits on muse-glimmer/challenge-nax-kernels to restore 56e12b00.

Before and After

flowchart LR
  subgraph Before["Before (main @ 56e12b00)"]
    B1["NAX affine qmm_t_nax_staged_impl (8 <= M <= 16)"] --> B2["Only sgid 0 active; 3 of 4 simdgroups idle"]
    B3["NAX NVFP4 fp_qmm_t_nax / gather / fp_qmv_nax"] --> B4["Single-buffered Ws; scalar load_unsafe; non-peeled QMV"]
  end

  subgraph After["After (500c5d7e)"]
    A1["NAX affine qmm_t_nax_staged_impl (8 <= M <= 16)"] --> A2{"use_ksplit FC 203<br/>use_qmm_nax_ksplit(allow_ksplit)<br/>(MLX_NAX_KSPLIT=0 default)"}
    A2 -->|true (opt-in)| A3["qmm_t_nax_staged_ksplit_impl: 4 simdgroups split BK=64 + Ws FP32 reduction"]
    A2 -->|false (default)| B2
    A4["NAX NVFP4 GEMM / MoE gather / QMV"] --> A5["Aligned fast_nvfp4 (double-buffered Ws in fp_qmm_t_nax, bit-manip dequant in gather/QMV) + scalar fallback"]
  end
Loading

Before any rollout

  1. Wait for green CI on 500c5d7e (lint, fork.yaml, C++ Metal tests including nax_ksplit_enabled, and Python shards).
  2. Re-pin Source/Cmlx/mlx in metal: port Muse Glimmer NAX quantized GEMM/QMV kernels mlx-swift#79 to the merged Layr-Labs/mlx main SHA.
  3. Coordinate allow_ksplit = (ref_rows <= 0) in qmm_splitk -> qmm when [Metal] Prefill-row invariance scope: prompt chunks round like the reference rows (opt-in, per thread) #71 lands.
  4. Keep MLX_NAX_KSPLIT=0 as the default until an end-to-end real-checkpoint Muse Glimmer 30B soak test on M5 confirms KV-hash / OpenRouter parity, and run a side-by-side NVFP4 microbenchmark against base main (including attributing the M=32 latency cliff).

Validation

1. Current Head (500c5d7e, rebased on 56e12b00) — Apple M4 Max (applegpu_g16s, macOS 27.2.1, Metal 410)

Check Command Result
AOT Metal 410 metallib + C++ tests (MLX_METAL_JIT=OFF) cmake --build /tmp/mlx73-build-aot --target mlx-metallib tests -j$(sysctl -n hw.ncpu) PASS — 0 errors
JIT library compile (MLX_METAL_JIT=ON) cmake --build /tmp/mlx73-build-jit --target mlx -j$(sysctl -n hw.ncpu) PASS — 0 errors
Quantized + NAX C++ tests (default MLX_NAX_KSPLIT=0) tests --test-case="*quant*,*qmm*,*qmv*,*NAX*,*nvfp4*,*mxfp*" PASS — 12/12 cases, 658/658 assertions (logs GPU arch: applegpu_g16s, is_nax_available=false)
NAX tests (MLX_NAX_KSPLIT=1, MLX_QMV_BATCH_INVARIANT=1, --cpu) tests --source-file="*nax_quantized_kernel_tests.cpp" in all 3 modes PASS — 2/2 passed in every mode
CTest entries (nax_ksplit_enabled + qmv_batch_invariant) ctest --test-dir /tmp/mlx73-build-aot -R '^(nax_ksplit_enabled|qmv_batch_invariant)$' -V PASS — 2/2 passed (0.95 s)
Formatting (clang-format 21.1.8 + cmake-format 0.6.13) uvx clang-format==21.1.8 --dry-run --Werror <8 C++/Metal files> + cmake-format --check tests/CMakeLists.txt PASS — 0 violations
fork.yaml & CI workflow checks scripts/check_forkdiff.py + yaml.safe_load + .github/scripts/test-runner-sizes.py PASS — 164/164 files described, 3/3 runner-size tests OK
Exhaustive NVFP4 bit-manipulation parity Python check over all 4,096 (fp8_e4m3, fp4_e2m1) pairs (bf16 + fp16) PASS — 0/4,096 mismatches (0 ULP)

2. Apple M5 Max (applegpu_g17s, arch_gen=17, 40 GPU cores, metal::is_nax_available() == true, macOS 27.2.1, Metal 4 — measured on 979ad5da, identical Metal kernel headers)

Check Command Result
Release Metal AOT build (MLX_METAL_JIT=OFF) cmake --build build --target tests -j$(sysctl -n hw.ncpu) PASS — mlx.metallib 215 MiB (1,176 compiled NAX kernel symbols), 0 errors
C++ NAX tests (MLX_NAX_KSPLIT=1, MLX_NAX_KSPLIT=0, MLX_QMV_BATCH_INVARIANT=1) ./tests/tests --source-file="*nax_quantized_kernel_tests.cpp" in all 3 modes PASS — 2/2 test cases in all 3 modes (61 / 65 / 65 assertions)
CTest NAX & batch-invariant entries + all quantized C++ cases ctest (4/4) + ./tests/tests --test-case="*quant*,*qmm*,*qmv*,*NAX*,*nvfp4*,*mxfp*" PASS — 12/12 C++ cases (654/654 assertions), 4/4 CTest
Swift NAXQuantizedKernelTests + combined #73/#79/#579/#580 stack NAXQuantizedKernelTests (4/4 × 3 modes) + mlx-swift-lm suites (--no-parallel) PASS — 4/4 × 3 modes, 254/254 test executions passed across tested modes

M5 NAX execution & gate proof (applegpu_g17s, Affine Q4 bf16 gs=64):

  • Split-K staged (N=K=2048, M ∈ {8, 12, 16}): KSPLIT=1 output differs bitwise from KSPLIT=0 and M=17 (confirming qmm_t_nax_staged_ksplit_impl executed via FC 203 = true), while KSPLIT=0 matches M=17 bitwise; QMV_BATCH_INVARIANT=1 routes to dispatch_qmv below vector_limit=33.
  • Direct staged (N=K=4160, M ∈ {13, 16}): KSPLIT=1 differs bitwise from KSPLIT=0 and M=17, while KSPLIT=0 and QMV_BATCH_INVARIANT=1 are bit-identical to rows(M=17, 0..m).
  • NVFP4 aligned fast paths (fp_qmm_t_nax, fp_gather_qmm_t_nax, fp_gather_qmm_rhs_nax) matched 4-byte w / 1-byte scales misaligned fallback bitwise (0 ULP) on applegpu_g17s.

Pre-existing upstream M5 TF32 note (not from #73/#79): On M5 (arch_gen >= 17), upstream MLX defaults MLX_ENABLE_TF32=1 (mlx/utils.h:269), routing float32 matrix products through NAX TF32 (~1e-3 rounding). An independent control build on clean base mlx-swift c633d22 / mlx 72dffa2d reproduced the identical 6/17 float32 QuantizedLayerTests tolerance failures with TF32 on and 17/17 pass with MLX_ENABLE_TF32=0. Production Muse Glimmer loads weights and runs all matmuls/SDPA in bf16, so TF32 does not apply in production.

M5 Max (applegpu_g17s) NAX Microbenchmarks (bf16, transpose=true, host wall-clock alternating KS1→KS0→KS1→KS0)

Methodology notes: Timings are host wall-clock (including graph construction and eval dispatch overhead). Each timed batch reuses one weight tensor across back-to-back ops, so reported GB/s values are cache-warm reused-weight throughput (not DRAM bandwidth). No affine K-split regression was observed outside ±5% run-to-run noise.

Affine Q4 (bits=4, gs=64) — MLX_NAX_KSPLIT=1 vs 0 A/B:

Shape (N×K) M KS=1 (µs) KS=0 (µs) Speedup (KS=1 / KS=0) KS=1 TFLOPS Cache-warm reused-weight GB/s Route
2048×6144 8 33.51 37.80 1.13x (1.12–1.14x across pairings) 6.01 215.1 Split-K NAX K-split
2048×6144 12 / 13 / 16 41.56 / 41.81 / 42.56 43.94 / 44.13 / 44.72 1.06x / 1.06x / 1.05x 7.27 / 7.82 / 9.46 175 / 174 / 172 Split-K NAX K-split
2048×2048 8 / 12 / 16 16.88 / 20.12 / 20.47 18.54 / 20.55 / 20.67 1.10x / 1.02x / 1.01x 3.98 / 5.00 / 6.56 144 / 122 / 122 Split-K NAX K-split
6144×6144 8 / 12 / 13 / 16 48.33 / 50.66 / 50.91 / 52.18 51.92 / 52.87 / 52.83 / 53.97 1.07x / 1.04x / 1.04x / 1.03x 12.50 / 17.88 / 19.28 / 23.15 443 / 425 / 424 / 415 Split-K / direct staged K-split
6144×2048 8 / 12 / 16 23.92 / 23.98 / 24.59 24.64 / 25.16 / 24.80 1.03x / 1.05x / 1.01x 8.42 / 12.59 / 16.37 301 / 303 / 299 Split-K NAX K-split
4160×4160 8 / 12 — — 0.98–1.01x (flat across pairings) — — Below direct staged (M < 13, split-K / QMV)
4160×4160 13 / 16 24.75 / 24.92 25.03 / 25.29 1.01x / 1.01x 18.18 / 22.22 402 / 401 Direct staged (split_k=1)
6144×6144 512 649.79 660.74 1.02x 59.49 52.0 Prefill (unsplit staged)
  • Affine Q8 (bits=8, gs=64) — MLX_NAX_KSPLIT=1 vs 0 A/B: 2048×6144 M=8–16: 1.04–1.09x (medians 1.08x / 1.05x / 1.07x); 2048×2048 M=8/12/16: 1.04x / 1.00x / 1.03x; 6144×2048 M=8/12/16: 1.02x / 1.01x / 1.00x; 4160×4160 M=8/12: 0.98–1.01x (flat), M=13/16: 1.02x / 1.03x; 6144×6144 M=8..16: 0.95–1.03x across run pairings (medians 0.99x / 1.00x / 1.00x, up to ~6% run-to-run variance).
  • NVFP4 (bits=4, gs=16) & MXFP8 (bits=8, gs=32) — absolute measurements on #73 only (no base 72dffa2d A/B run yet):
    • nvfp4 6144×6144: M=1 731 GB/s cache-warm (29.10 µs), M=8 538 GB/s cache-warm (39.80 µs), M=16 28.5 TFLOPS (42.32 µs), M=32 9.5 TFLOPS (255.06 µs), M=64 45.7 TFLOPS (105.84 µs), M=512 53.8 TFLOPS (718.65 µs).
    • mxfp8 6144×6144: M=1 816 GB/s cache-warm (47.74 µs), M=8 829 GB/s cache-warm (47.18 µs), M=32 9.3 TFLOPS (259.30 µs), M=64 42.6 TFLOPS (113.31 µs), M=512 50.5 TFLOPS (764.93 µs).
    • Note: Because MLX_NAX_KSPLIT only toggles affine K-split, these NVFP4/MXFP8 figures are absolute measurements on #73 and do not yet compare #73 against base 72dffa2d. Likewise, the M=32 latency cliff (255 µs at M=32 vs 106 µs at M=64 on 6144×6144) has not been attributed to #73 vs. base 72dffa2d yet.

Skipped / Ignored

  • Python wheel build and unrelated non-quantized C++ tests locally (running in GitHub Actions CI on 500c5d7e).
  • Re-running the updated has_nax CHECK_FALSE assertions in 500c5d7e on M5 Max (SSH to M5 Max timed out from this host; the exact same M=8..16 vs M=17 bitwise divergence under KSPLIT=1 and bitwise equality under KSPLIT=0 were already proven on M5 Max on 979ad5da, whose kernel headers are unchanged).

Not proven

  • NVFP4 speedup vs. base main and M=32 cliff attribution: NVFP4/MXFP8 microbenchmarks above are absolute measurements on #73 with no side-by-side base A/B run yet.
  • End-to-end real-checkpoint Muse Glimmer 30B throughput & KV-hash soak on M5 Max (reason MLX_NAX_KSPLIT now defaults to 0).

Reviewer Notes

  • Inspect commit 500c5d7e:
    • mlx/utils.h (MLX_NAX_KSPLIT default changed 1 -> 0)
    • mlx/backend/metal/quantized.cpp (use_qmm_nax_ksplit(bool allow_ksplit = true) and allow_ksplit threaded through qmm -> qmm_nax for #71 ref_rows <= 0 coordination)
    • tests/nax_quantized_kernel_tests.cpp, tests/CMakeLists.txt, and .github/workflows/fork-tests.yml (GPU arch / is_nax_available() logging, NAX K-split dispatch assertion, and nax_ksplit_enabled ctest wired into CI)
    • fork.yaml (also adds AGENTS.md from 56e12b00 on main under "Fork tooling" so Fork Diff Check passes)

Upstream PR Template / AI Disclosure

  • ☑️ I understand it is strictly prohibited to use AI to write PR description (Note: per the Darkbloom fork exception documented in AGENTS.md on Layr-Labs/mlx main @ 56e12b00 under "Working in our MLX forks", AI-assisted descriptions are permitted in this Layr-Labs fork with explicit disclosure below; a human reviewer should confirm before merge.)
  • AI usage disclosure: Cursor cloud agent drafted the port, use_ksplit gate, hardening guards, C++ tests, review fixes, and this PR description, and ran local M4 Max (m4-max-1) and M5 Max (applegpu_g17s) validation and microbenchmarks at the user's request.

GumbiiDigital added a commit to Layr-Labs/mlx-swift that referenced this pull request Dec 4, 2026
Address adversarial review findings (H1, M1, M2, L1, L4):

- Advance Source/Cmlx/mlx from ce27c709 to 979ad5da (head of Layr-Labs/mlx#73),
  regenerate mlx-generated/{quantized_nax,fp_quantized_nax}.{h,cpp}, and sync
  Source/Cmlx/include-framework/mlx-utils.h (adds env::nax_ksplit()).
- Gate qmm_t_nax_staged_ksplit_impl via Metal function constant 203
  (use_ksplit), controlled by MLX_NAX_KSPLIT (default 1) and automatically
  disabled when MLX_QMV_BATCH_INVARIANT=1 is set.
- Rewrite Tests/MLXTests/NAXQuantizedKernelTests.swift so every shape routes
  to its target M5 NAX kernel path:
  - Affine K-split split-K (N=K=2048, M=8..16, biases present) and direct
    staged qmm_nax (N=K=4160 = 65*64, M=13..16), plus bitwise M=13/16 vs
    M=17 parity when MLX_NAX_KSPLIT=0 or MLX_QMV_BATCH_INVARIANT=1.
  - Unbatched (M=512, N=1024) and batched (B=2, M=64, aligned N=128 and
    unaligned N=96) double-buffered NVFP4 fp_qmm_t_nax.
  - Peeled fp_qmv_nax (K=N=2048, 6 <= M <= 8 and M=9).
  - NVFP4 MoE gather (fp_gather_qmm_t_nax and fp_gather_qmm_rhs_nax).
  - Genuinely misaligned 4B weight / 1B scale offset fallback with bitwise
    sameBytes parity against the aligned fast paths.
  - NVFP4 globalScale GEMM route (M=512, N=1024, K=128).
- Update fork.yaml with the 979ad5da pin, accurate NVFP4 blast radius
  (including MoE gather paths), and updated test coverage description.
@GumbiiDigital
GumbiiDigital marked this pull request as ready for review December 4, 2026 14:40

@jonathan308 jonathan308 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The kernel work looks right. NVFP4 dequant is bit-identical, the double-buffering is race-free, threadgroup memory fits (18,432 B for staged tiles, 12,288 B for K-split partial sums), and M1–M4 are untouched behind is_nax_available(). Two things I'd want fixed before merge, plus one merge-order item:

  1. Default MLX_NAX_KSPLIT to 0 (mlx/utils.h:248; used at quantized.cpp:1021/1536 and quantized_nax.h:1350). With it on, affine bf16/fp16 at 8–16 rows adds the four partial sums in a different order. M5 output bits then differ from today's production build, and from the same rows computed at 17+ rows. OpenRouter flags output drift, and end-to-end KV-hash parity is still "not proven" per the description. Ship it opt-in and flip the default after a soak test shows parity.
  2. CI has never actually run on this PR. Every Darkbloom self-hosted job sat about 40 minutes with no runner and got cancelled by the watchdog, and the dependent jobs cancelled at 0s. Only CodeQL ran. So lint, clang-format, the C++ tests (including the new nax_ksplit_disabled check) and fork.yaml are all unverified. The branch is also 20 commits behind main. Please rebase and get a green run.
  3. Merge order with my mlx#71 (prefill-row invariance). #71 skips the NAX split-K route inside its scope. But when the split count resolves to 1 (large N, e.g. an lm_head with N ≥ 16384), the call goes qmm → staged kernel. K-split would then make 2–16 row prompt chunks round differently from 17+ row chunks. Whichever PR lands second needs prefill_rows <= 0 in the K-split gate.

Minor: the tests compare against CPU with a loose tolerance (0.08 for bf16) plus fast-path-vs-fallback bitwise checks. Nothing asserts that the NAX path actually ran on the runner, so an assert or log check would make the bitwise tests meaningful.

…GEMM/QMV

Ports the two production-safe NAX Metal kernel optimizations from the Muse
Glimmer 30B challenge line (Layr-Labs/mlxfast-muse-glimmer-30b-engine
commits 80b35945 and 9976cc74):

- quantized_nax.h: qmm_t_nax_staged_ksplit_impl splits each BK=64 step into
  four 16-column slices across all 4 simdgroups when M <= SM (M <= 16) in
  qmm_t_nax_staged_impl, reducing FP32 partial tiles in threadgroup memory.
- fp_quantized_nax.h: vectorized uint4/uchar2 NVFP4 loads and half2 E2M1
  dequantization (fetch_nvfp4/store_nvfp4) with double-buffered Ws in
  fp_qmm_t_impl/fp_qmm_t_nax, plus dequantize_fp4_x4_scaled and M <= 8
  peeled 1-ahead prefetch in fp_qmv_nax, hardened with alignment, K > 0,
  sizeof(T) == 2, and final-iteration copy guards.

Drops the divergent early-return edits to steel_gemm_fused_nax.h and
steel_gemm_splitk_nax.h (threadgroup_barrier(mem_flags::mem_none) inside
gemm_loop makes per-simdgroup early return MSL UB) and the dead
cbv2_array_backing symbol in gather_front.cpp.
Address adversarial review findings (H1, M1, M2, L1, L4):

- Gate qmm_t_nax_staged_ksplit_impl via Metal function constant 203
  (use_ksplit), controlled by env::nax_ksplit() (MLX_NAX_KSPLIT, default 1)
  and automatically disabled when MLX_QMV_BATCH_INVARIANT=1 is set.
  Eliminates the M=16/17 batch-size boundary under batch invariance and
  provides an explicit kill switch without adding AOT kernel instantiations.
- Document MLX_NAX_KSPLIT in docs/src/usage/environment_variables.rst and
  clarify that sizeof(T) == 2 / sizeof(Wtype) == 2 in fp_quantized_nax.h
  checks the 16-bit threadgroup tile storage width (Wtype = bfloat across
  fp_qmm_t_nax, fp_gather_qmm_t_nax, and fp_gather_qmm_rhs_nax for all
  activation dtypes; activation T in fp_qmm_n_impl).
- Add tests/nax_quantized_kernel_tests.cpp and ctest nax_ksplit_disabled
  covering M5-routed affine K-split (split-K N=K=2048 M=8..16 and direct
  staged N=K=4160 M=13..16, plus bitwise M=13/16 vs M=17 parity when
  MLX_NAX_KSPLIT=0), unbatched/batched double-buffered NVFP4 GEMM, peeled
  6 <= M <= 8 QMV, NVFP4 MoE gather (fp_gather_qmm_t_nax and
  fp_gather_qmm_rhs_nax), and genuinely misaligned 4B/1B offset fallback
  bitwise parity.
- Update fork.yaml with the complete file globs and NVFP4 blast radius.
…AX path

Address jonathan308's review comments on #73:

- Default MLX_NAX_KSPLIT to 0 (opt-in) in mlx/utils.h and update
  docs/src/usage/environment_variables.rst and fork.yaml so M5 output bits
  at 8..16 affine rows stay identical to production unless explicitly opted in.
- Factor the K-split gate into use_qmm_nax_ksplit(bool allow_ksplit = true)
  and thread an optional allow_ksplit parameter through qmm() -> qmm_nax(),
  ready for #71 to pass allow_ksplit = (ref_rows <= 0) when
  qmm_splitk falls through to qmm at split_k <= 1.
- Log GPU architecture and metal::is_nax_available() in
  tests/nax_quantized_kernel_tests.cpp, assert bitwise M<=16 vs M=17 parity
  when K-split is off (default) and bitwise K-split dispatch on NAX when
  MLX_NAX_KSPLIT=1, replace ctest nax_ksplit_disabled with nax_ksplit_enabled
  (MLX_NAX_KSPLIT=1), and run it in .github/workflows/fork-tests.yml.
- Document AGENTS.md (from 56e12b0 on main) under Fork tooling in fork.yaml
  so Fork Diff Check passes after rebasing onto main.

@jonathan308 jonathan308 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving at 500c5d7e. All of my earlier items are fixed:

  1. MLX_NAX_KSPLIT defaults to 0 (mlx/utils.h). Default M5 output bits at 8–16 rows now match main.
  2. CI ran fully on this head and passed, including the new nax_ksplit_enabled ctest step. The branch is 3 ahead of main and 0 behind.
  3. Merge order with #71: allow_ksplit is threaded through qmm → qmm_nax → use_qmm_nax_ksplit. #71 is still a draft, so it lands second and should pass ref_rows <= 0 at the qmm_splitk → qmm fallthrough.
  4. The tests now assert a bitwise difference under MLX_NAX_KSPLIT=1 on NAX hardware, so the dispatch is proven.

Both kernel headers (quantized_nax.h, fp_quantized_nax.h) are byte-identical to 979ad5da, the commit you ran on the M5 Max.

Notes, not blocking:

  • The CI runner's GPU has no NAX (GPU arch: air64_v27, is_nax_available=false in the build-cpp log). CI only compiles the new kernels; your M5 Max run is the only on-hardware evidence. Please re-run the NAX tests on an M5 after any kernel change.
  • The NVFP4 double-buffered GEMM and QMV are on by default for every NVFP4 model on M5. They're bit-identical, but there's no speed comparison against main yet. Please post one, along with the cause of the M=32 cliff, before we count this as a speed-up.
  • Nit: qmm_t_nax_staged_impl treats an undefined FC 203 as K-split on (!is_function_constant_defined(use_ksplit) || use_ksplit). Every current host dispatcher sets it, so nothing reaches this today. Treating undefined as off would be safer.
  • Remember to re-pin Source/Cmlx/mlx in mlx-swift#79 once this merges.

@GumbiiDigital
GumbiiDigital merged commit 4ef15bc into main Dec 4, 2026
26 of 27 checks passed
GumbiiDigital added a commit to Layr-Labs/mlx-swift that referenced this pull request Dec 4, 2026
Advance Source/Cmlx/mlx from 979ad5da to 4ef15bc7d43527e2018596a23445aa4f0c698662
(merged Layr-Labs/mlx#73 on Layr-Labs/mlx main, including 500c5d7e's opt-in
MLX_NAX_KSPLIT=0 default, allow_ksplit plumbing for #71 coordination, and
the main empty-CPU-reduction fix from #54):

- Sync Source/Cmlx/include-framework/mlx-utils.h so env::nax_ksplit() matches
  mlx/utils.h (default 0, != 0).
- Update Tests/MLXTests/NAXQuantizedKernelTests.swift so unset MLX_NAX_KSPLIT
  asserts bitwise parity (default disabled), while explicit MLX_NAX_KSPLIT=1
  exercises K-split unless MLX_QMV_BATCH_INVARIANT=1 is set.
- Verified Source/Cmlx/mlx-generated/ matches 4ef15bc7 (zero Metal kernel
  header diff vs 979ad5da; check-generated-metal-sources.py passes).
- Update fork.yaml with the 4ef15bc7 pin and opt-in default.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants