From aea2e29d958e668f1618074b8ca1b77d3dce0ecd Mon Sep 17 00:00:00 2001 From: Gumbii Digital <189439224+GumbiiDigital@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:51:58 -0500 Subject: [PATCH 1/3] Metal NAX: add small-M K-split affine GEMM and double-buffered NVFP4 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. --- fork.yaml | 21 + mlx/backend/metal/kernels/fp_quantized_nax.h | 629 ++++++++++++++++--- mlx/backend/metal/kernels/quantized_nax.h | 181 ++++++ 3 files changed, 746 insertions(+), 85 deletions(-) diff --git a/fork.yaml b/fork.yaml index 144d59b1cb..d9a90dbea7 100644 --- a/fork.yaml +++ b/fork.yaml @@ -584,6 +584,27 @@ def: globs: - "mlx/backend/metal/kernels/quantized_nax.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - title: "NAX small-M K-split affine GEMM and double-buffered NVFP4 GEMM/QMV" + description: | + Two M5-series NAX quantized Metal kernel optimizations ported from the Muse + Glimmer 30B challenge line (`Layr-Labs/mlxfast-muse-glimmer-30b-engine` + commits `80b35945` and `9976cc74`): + - `qmm_t_nax_staged_ksplit_impl` in `quantized_nax.h`: when `M <= SM` (`M <= 16`) + and `(BM / SM) * 16 == BK` (`BM=64, BK=64, BN=64, WM=4, WN=1`), splits each + `BK` step into 16-column slices across all 4 simdgroups instead of leaving 3 + simdgroups idle, then reduces FP32 partial tiles in simdgroup order in + threadgroup memory (FP32 throughout; changes only K-reduction summation order + for `M <= 16` affine 16-bit products on NAX). + - `FPQuantizedNAXBlockLoader::fetch_nvfp4` / `store_nvfp4`, double-buffered + `Ws` in `fp_qmm_t_impl` / `fp_qmm_t_nax`, and `dequantize_fp4_x4_scaled` + + `M <= 8` peeled 1-ahead prefetch in `fp_qmv_nax` (`fp_quantized_nax.h`): + vectorizes NVFP4 (`bits == 4, group_size == 16, !has_global_scale, sizeof(Wtype) == 2`) + weight/scale loads and `half2` E2M1 dequantization (0-ULP bit-identical to + stock over all 4,096 `(fp8_e4m3, fp4_e2m1)` pairs), guarded by alignment and + `K > 0` checks. + globs: + - "mlx/backend/metal/kernels/quantized_nax.h" + - "mlx/backend/metal/kernels/fp_quantized_nax.h" - title: "Run-time template of the head-dim split NAX attention" description: | Upstream's head-dim split attention (`attention_nax_dsplit`, the NAX full-attention diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index e4e554865e..c7873eb958 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -136,11 +136,127 @@ struct FPQuantizedNAXBlockLoader { } } + void fetch_nvfp4(thread uint2* q_buf, thread uint8_t* s_buf) const thread { + if constexpr (n_steps_per_read == 2) { + const uint4 q4 = *(const device uint4*)src; + q_buf[0] = q4.xy; + q_buf[1] = q4.zw; + const uchar2 s2 = *(const device uchar2*)scales; + s_buf[0] = s2.x; + s_buf[1] = s2.y; + } else { + const device uint2* src_u2 = (const device uint2*)src; + for (int i = 0; i < n_steps_per_read; i++) { + q_buf[i] = src_u2[i]; + s_buf[i] = scales[i]; + } + } + } + + void store_nvfp4( + threadgroup T* ws_base, + const thread uint2* q_buf, + const thread uint8_t* s_buf) const thread { + threadgroup vec* dst_v8 = + (threadgroup vec*)(ws_base + bi * dst_ld + bj * pack_factor); + for (int i = 0; i < n_steps_per_read; i++) { + const half scale = dequantize_scale(s_buf[i]); + const uint2 q = q_buf[i]; + { + const uint lo0 = (q.x & 0x000f) | ((q.x & 0x00f0) << 12); + const uint hi0 = ((q.x >> 8) & 0x000f) | ((q.x & 0xf000) << 4); + half2 a0 = + (as_type( + ((lo0 & 0x00070007) << 9) | ((lo0 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b0 = + (as_type( + ((hi0 & 0x00070007) << 9) | ((hi0 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + + const uint qx1 = q.x >> 16; + const uint lo1 = (qx1 & 0x000f) | ((qx1 & 0x00f0) << 12); + const uint hi1 = ((qx1 >> 8) & 0x000f) | ((qx1 & 0xf000) << 4); + half2 a1 = + (as_type( + ((lo1 & 0x00070007) << 9) | ((lo1 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b1 = + (as_type( + ((hi1 & 0x00070007) << 9) | ((hi1 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + dst_v8[2 * i + 0] = vec( + T(a0.x), + T(a0.y), + T(b0.x), + T(b0.y), + T(a1.x), + T(a1.y), + T(b1.x), + T(b1.y)); + } + { + const uint lo2 = (q.y & 0x000f) | ((q.y & 0x00f0) << 12); + const uint hi2 = ((q.y >> 8) & 0x000f) | ((q.y & 0xf000) << 4); + half2 a2 = + (as_type( + ((lo2 & 0x00070007) << 9) | ((lo2 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b2 = + (as_type( + ((hi2 & 0x00070007) << 9) | ((hi2 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + + const uint qy1 = q.y >> 16; + const uint lo3 = (qy1 & 0x000f) | ((qy1 & 0x00f0) << 12); + const uint hi3 = ((qy1 >> 8) & 0x000f) | ((qy1 & 0xf000) << 4); + half2 a3 = + (as_type( + ((lo3 & 0x00070007) << 9) | ((lo3 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b3 = + (as_type( + ((hi3 & 0x00070007) << 9) | ((hi3 & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + dst_v8[2 * i + 1] = vec( + T(a2.x), + T(a2.y), + T(b2.x), + T(b2.y), + T(a3.x), + T(a3.y), + T(b3.x), + T(b3.y)); + } + } + } + void load_unsafe() const thread { if (BCOLS_PACKED * BROWS < tgp_size && bi >= BROWS) { return; } + if constexpr ( + bits == 4 && group_size == 16 && !has_global_scale && sizeof(T) == 2 && + n_reads_per_scale == 8) { + if ((src_ld & 31) == 0 && (reinterpret_cast(src) & 15) == 0 && + (reinterpret_cast(scales) & 1) == 0) { + uint2 q_buf[n_steps_per_read]; + uint8_t s_buf[n_steps_per_read]; + fetch_nvfp4(q_buf, s_buf); + store_nvfp4(dst - (bi * dst_ld + bj * pack_factor), q_buf, s_buf); + return; + } + } + int k = 0; for (int i = 0; i < n_steps_per_read; i++) { float scale = @@ -208,7 +324,8 @@ template < const int BN = 64, const int WM = 2, const int WN = 2, - typename Wtype = bfloat> + typename Wtype = bfloat, + const bool double_buffer_ws = false> METAL_FUNC void fp_qmm_t_impl( const device uint32_t* w, const device uint8_t* scales, @@ -292,43 +409,181 @@ METAL_FUNC void fp_qmm_t_impl( dispatch_bool(!is_unaligned_sm, [&](auto kAlignedM) { dispatch_bool(aligned_N || !is_unaligned_bn, [&](auto kAlignedN) { - for (int k = 0; k < K; k += BK) { - threadgroup_barrier(mem_flags::mem_threadgroup); - if constexpr (kAlignedN.value) { - loader_w.load_unsafe(); + const bool fast_nvfp4 = (K > 0) && ((K & 31) == 0) && + ((reinterpret_cast(wl) & 15) == 0) && + ((reinterpret_cast(scales) & 1) == 0); + if constexpr ( + kAlignedN.value && bits == 4 && group_size == 16 && + !has_global_scale && sizeof(Wtype) == 2 && + loader_w_t::n_reads_per_scale == 8 && + loader_w_t::BCOLS_PACKED * BN >= WM * WN * SIMD_SIZE) { + if (fast_nvfp4) { + constexpr int ws_tile_size = BN * BK_padded; + uint2 q_buf[loader_w_t::n_steps_per_read]; + uint8_t s_buf[loader_w_t::n_steps_per_read]; + loader_w.fetch_nvfp4(q_buf, s_buf); + loader_w.next(); + if constexpr (double_buffer_ws) { + loader_w.store_nvfp4(Ws, q_buf, s_buf); + threadgroup_barrier(mem_flags::mem_threadgroup); + int stage = 0; + for (int k = 0; k < K; k += BK) { + if (k + BK < K) { + loader_w.fetch_nvfp4(q_buf, s_buf); + loader_w.next(); + } + + threadgroup Wtype* Ws_cur = Ws + stage * ws_tile_size; + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + } + + Btile.template load( + Ws_cur + tn * BK_padded + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; + } + + if (k + BK < K) { + loader_w.store_nvfp4( + Ws + (1 - stage) * ws_tile_size, q_buf, s_buf); + threadgroup_barrier(mem_flags::mem_threadgroup); + stage = 1 - stage; + } + + x += BK; + } + } else { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_w.store_nvfp4(Ws, q_buf, s_buf); + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (k + BK < K) { + loader_w.fetch_nvfp4(q_buf, s_buf); + loader_w.next(); + } + + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + } + + Btile.template load( + Ws + tn * BK_padded + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; + } + + x += BK; + } + } } else { - loader_w.load_safe(short2(BK, tgp_bn)); + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + loader_w.load_unsafe(); + threadgroup_barrier(mem_flags::mem_threadgroup); + + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile Atile; + NAXTile Btile; + + volatile int compiler_barrier; + + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + } + + Btile.template load( + Ws + tn * BK_padded + kk1); + + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); + + (void)compiler_barrier; + } + + x += BK; + loader_w.next(); + } } + } else { + for (int k = 0; k < K; k += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if constexpr (kAlignedN.value) { + loader_w.load_unsafe(); + } else { + loader_w.load_safe(short2(BK, tgp_bn)); + } - threadgroup_barrier(mem_flags::mem_threadgroup); + threadgroup_barrier(mem_flags::mem_threadgroup); - STEEL_PRAGMA_NO_UNROLL - for (int kk1 = 0; kk1 < BK; kk1 += SK) { - NAXTile Atile; - NAXTile Btile; + STEEL_PRAGMA_NO_UNROLL + for (int kk1 = 0; kk1 < BK; kk1 += SK) { + NAXTile Atile; + NAXTile Btile; - volatile int compiler_barrier; + volatile int compiler_barrier; - if constexpr (kAlignedM.value) { - Atile.load(x + kk1, K); - } else { - Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); - } + if constexpr (kAlignedM.value) { + Atile.load(x + kk1, K); + } else { + Atile.load_safe(x + kk1, K, short2(SK, sgp_sm)); + } - Btile.template load(Ws + tn * BK_padded + kk1); + Btile.template load(Ws + tn * BK_padded + kk1); - tile_matmad_nax( - Dtile, - Atile, - metal::bool_constant{}, - Btile, - metal::bool_constant{}); + tile_matmad_nax( + Dtile, + Atile, + metal::bool_constant{}, + Btile, + metal::bool_constant{}); - (void)compiler_barrier; - } + (void)compiler_barrier; + } - x += BK; - loader_w.next(); + x += BK; + loader_w.next(); + } } // Store results to device memory @@ -376,6 +631,21 @@ METAL_FUNC vec dequantize_fp_x4(uint q, uint8_t s) { } } +template +METAL_FUNC vec dequantize_fp4_x4_scaled(uint q, half scale) { + const uint lo = (q & 0x000f) | ((q & 0x00f0) << 12); + const uint hi = ((q >> 8) & 0x000f) | ((q & 0xf000) << 4); + half2 a = + (as_type(((lo & 0x00070007) << 9) | ((lo & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + half2 b = + (as_type(((hi & 0x00070007) << 9) | ((hi & 0x00080008) << 12)) * + half2(16384.0h)) * + scale; + return vec(Wtype(a.x), Wtype(a.y), Wtype(b.x), Wtype(b.y)); +} + template < typename T, const int group_size, @@ -625,8 +895,11 @@ template < (void)lid; constexpr int BK_padded = (BK + 16 / sizeof(Wtype)); + constexpr bool kDoubleBuf = + (bits == 4 && group_size == 16 && !has_global_scale && + sizeof(Wtype) == 2); - threadgroup Wtype Ws[BN * BK_padded]; + threadgroup Wtype Ws[(kDoubleBuf ? 2 : 1) * BN * BK_padded]; if (batched) { adjust_matrix_offsets( @@ -655,7 +928,8 @@ template < BN, WM, WN, - Wtype>( + Wtype, + kDoubleBuf>( w, scales, global_scale, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); } @@ -1128,80 +1402,265 @@ template < NAXTile Dtile; Dtile.clear(); - for (int k = simd_gid * BK; k < K; k += WK * BK) { - vec xs[2][4]; - STEEL_PRAGMA_UNROLL - for (short r = 0; r < 2; r++) { - STEEL_PRAGMA_UNROLL - for (short i = 0; i < 4; i++) { - xs[r][i] = x_rows[r] - ? *(const device vec*)(x + r * 8 * static_cast(K) + - k + 8 * i) - : vec(0); + if constexpr (bits == 4 && group_size == 16) { + if (M <= 8) { + const bool x_row0 = fm < M; + uint4 ws_cur[TN][2]; + ushort ss_cur[TN][2]; + const int k0 = simd_gid * BK; + if (k0 < K) { + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const int row = 16 * t + 8 * r; + ws_cur[t][r] = + *(const device uint4*)(wl + + row * static_cast(row_bytes) + + k0 / 2); + ss_cur[t][r] = + *(const device ushort*)(scales + + row * static_cast(row_scales) + + k0 / 16); + } + } } - } - uint4 ws[TN][2][loads]; - scale_bits_t ss[TN][2]; - STEEL_PRAGMA_UNROLL - for (short t = 0; t < TN; t++) { - STEEL_PRAGMA_UNROLL - for (short r = 0; r < 2; r++) { - const int row = 16 * t + 8 * r; - const device uint8_t* wt = - wl + row * static_cast(row_bytes) + k / pack_factor; - const device uint8_t* st = - scales + row * static_cast(row_scales) + k / group_size; + + for (int k = k0; k < K; k += WK * BK) { + vec xs0[4]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + xs0[i] = + x_row0 ? *(const device vec*)(x + k + 8 * i) : vec(0); + } + + uint4 ws_next[TN][2]; + ushort ss_next[TN][2]; + const int kn = k + WK * BK; + if (kn < K) { + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const int row = 16 * t + 8 * r; + ws_next[t][r] = + *(const device uint4*)(wl + + row * static_cast(row_bytes) + + kn / 2); + ss_next[t][r] = *( + const device ushort*)(scales + + row * static_cast(row_scales) + + kn / 16); + } + } + } + + half sc0[TN][2]; + half sc1[TN][2]; STEEL_PRAGMA_UNROLL - for (short l = 0; l < loads; l++) { - ws[t][r][l] = *(const device uint4*)(wt + 16 * l); + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + sc0[t][r] = dequantize_scale(uint8_t(ss_cur[t][r])); + sc1[t][r] = dequantize_scale(uint8_t(ss_cur[t][r] >> 8)); + } + } + + STEEL_PRAGMA_UNROLL + for (short f = 0; f < TK; f++) { + typename Frag::template dtype_frag_t a; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + a[j] = xs0[f / 2][4 * (f % 2) + j]; + a[4 + j] = T(0); + } + typename Frag::template dtype_frag_t b[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const uint q = ws_cur[t][r][f / 2] >> (16 * (f % 2)); + const half sc = (f < 4) ? sc0[t][r] : sc1[t][r]; + const vec v = dequantize_fp4_x4_scaled(q, sc); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + b[t][4 * r + j] = v[j]; + } + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t += 2) { + Frag::mma( + Dtile.frag_at(0, t), + Dtile.frag_at(0, t + 1), + a, + metal::bool_constant{}, + b[t], + b[t + 1], + metal::bool_constant{}); + } + } + + if (kn < K) { + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + ws_cur[t][r] = ws_next[t][r]; + ss_cur[t][r] = ss_next[t][r]; + } + } + } + } + } else { + for (int k = simd_gid * BK; k < K; k += WK * BK) { + vec xs[2][4]; + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short i = 0; i < 4; i++) { + xs[r][i] = x_rows[r] + ? *(const device vec*)(x + + r * 8 * static_cast(K) + + k + 8 * i) + : vec(0); + } + } + uint4 ws[TN][2]; + ushort ss[TN][2]; + half sc0[TN][2]; + half sc1[TN][2]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const int row = 16 * t + 8 * r; + ws[t][r] = + *(const device uint4*)(wl + + row * static_cast(row_bytes) + + k / 2); + ss[t][r] = + *(const device ushort*)(scales + + row * static_cast(row_scales) + + k / 16); + sc0[t][r] = dequantize_scale(uint8_t(ss[t][r])); + sc1[t][r] = dequantize_scale(uint8_t(ss[t][r] >> 8)); + } + } + STEEL_PRAGMA_UNROLL + for (short f = 0; f < TK; f++) { + typename Frag::template dtype_frag_t a; + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + a[4 * r + j] = xs[r][f / 2][4 * (f % 2) + j]; + } + } + typename Frag::template dtype_frag_t b[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + const uint q = ws[t][r][f / 2] >> (16 * (f % 2)); + const half sc = (f < 4) ? sc0[t][r] : sc1[t][r]; + const vec v = dequantize_fp4_x4_scaled(q, sc); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + b[t][4 * r + j] = v[j]; + } + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t += 2) { + Frag::mma( + Dtile.frag_at(0, t), + Dtile.frag_at(0, t + 1), + a, + metal::bool_constant{}, + b[t], + b[t + 1], + metal::bool_constant{}); + } } - ss[t][r] = *(const device scale_bits_t*)st; } } - - STEEL_PRAGMA_UNROLL - for (short f = 0; f < TK; f++) { - typename Frag::template dtype_frag_t a; + } else { + for (int k = simd_gid * BK; k < K; k += WK * BK) { + vec xs[2][4]; STEEL_PRAGMA_UNROLL for (short r = 0; r < 2; r++) { STEEL_PRAGMA_UNROLL - for (short j = 0; j < 4; j++) { - a[4 * r + j] = xs[r][f / 2][4 * (f % 2) + j]; + for (short i = 0; i < 4; i++) { + xs[r][i] = x_rows[r] + ? *(const device vec*)(x + r * 8 * static_cast(K) + + k + 8 * i) + : vec(0); } } - typename Frag::template dtype_frag_t b[TN]; + uint4 ws[TN][2][loads]; + scale_bits_t ss[TN][2]; STEEL_PRAGMA_UNROLL for (short t = 0; t < TN; t++) { STEEL_PRAGMA_UNROLL for (short r = 0; r < 2; r++) { - uint q; - if constexpr (bits == 4) { - q = ws[t][r][0][f / 2] >> (16 * (f % 2)); - } else { - q = ws[t][r][f / 4][f % 4]; - } - uint8_t s = ss[t][r]; - if constexpr (group_size == 16) { - s = ss[t][r] >> (8 * (f / 4)); - } - const vec v = - dequantize_fp_x4(q, s); + const int row = 16 * t + 8 * r; + const device uint8_t* wt = + wl + row * static_cast(row_bytes) + k / pack_factor; + const device uint8_t* st = + scales + row * static_cast(row_scales) + k / group_size; STEEL_PRAGMA_UNROLL - for (short j = 0; j < 4; j++) { - b[t][4 * r + j] = v[j]; + for (short l = 0; l < loads; l++) { + ws[t][r][l] = *(const device uint4*)(wt + 16 * l); } + ss[t][r] = *(const device scale_bits_t*)st; } } + STEEL_PRAGMA_UNROLL - for (short t = 0; t < TN; t += 2) { - Frag::mma( - Dtile.frag_at(0, t), - Dtile.frag_at(0, t + 1), - a, - metal::bool_constant{}, - b[t], - b[t + 1], - metal::bool_constant{}); + for (short f = 0; f < TK; f++) { + typename Frag::template dtype_frag_t a; + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + a[4 * r + j] = xs[r][f / 2][4 * (f % 2) + j]; + } + } + typename Frag::template dtype_frag_t b[TN]; + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t++) { + STEEL_PRAGMA_UNROLL + for (short r = 0; r < 2; r++) { + uint q; + if constexpr (bits == 4) { + q = ws[t][r][0][f / 2] >> (16 * (f % 2)); + } else { + q = ws[t][r][f / 4][f % 4]; + } + uint8_t s = ss[t][r]; + if constexpr (group_size == 16) { + s = ss[t][r] >> (8 * (f / 4)); + } + const vec v = + dequantize_fp_x4(q, s); + STEEL_PRAGMA_UNROLL + for (short j = 0; j < 4; j++) { + b[t][4 * r + j] = v[j]; + } + } + } + STEEL_PRAGMA_UNROLL + for (short t = 0; t < TN; t += 2) { + Frag::mma( + Dtile.frag_at(0, t), + Dtile.frag_at(0, t + 1), + a, + metal::bool_constant{}, + b[t], + b[t + 1], + metal::bool_constant{}); + } } } } diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index fb414f1a6e..f5b0fb0036 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -1125,6 +1125,178 @@ struct QuantizedBlockLoaderStaged { } }; +// With M <= SM, qmm_t_nax_staged_impl leaves every simdgroup but the first +// without rows. Here all simdgroups take the same rows, and simdgroup g takes +// the 16 columns [16 g, 16 g + 16) of every BK step, so each one issues a +// quarter of the MMAs. The partial tiles are added in simdgroup order in +// threadgroup memory at the end (fp32 throughout; only the summation order +// differs from the staged impl). +template < + typename T, + int group_size, + int bits, + typename U, + int BM, + int BK, + int BN, + int SM> +METAL_FUNC void qmm_t_nax_staged_ksplit_impl( + const device uint32_t* w, + const device T* scales, + const device T* biases, + const device T* x, + device U* y, + threadgroup T* Ws, + const constant int& K, + const constant int& N, + const constant int& M, + const int k_end, + uint3 tid, + uint simd_gid, + uint simd_lid) { + constexpr int WM = BM / SM; + static_assert(WM * 16 == BK, "One 16-column K slice per simdgroup"); + + constexpr int pack_factor = get_affine_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int tile_size = BN * BK_padded; + constexpr int n_frags = BN / 16; + constexpr int frag_elems = BaseNAXFrag::kElemsPerFrag; + static_assert( + (WM - 1) * n_frags * SIMD_SIZE * frag_elems * sizeof(float) <= + 2 * tile_size * sizeof(T), + "The partial tiles fit the weight buffers"); + + using loader_w_t = QuantizedBlockLoaderStaged< + T, + BN, + BK, + BK_padded, + WM * SIMD_SIZE, + group_size, + bits>; + using frag_t = typename BaseNAXFrag::template dtype_frag_t; + + const int K_w = K * bytes_per_pack / pack_factor; + const int K_g = K / group_size; + const int y_row = tid.y * BM; + const int y_col = tid.x * BN; + + loader_w_t loader_w( + (const device uint8_t*)w + y_col * K_w, + scales + y_col * K_g, + biases + y_col * K_g, + K, + simd_gid, + simd_lid); + + const int tile_rows = min(BM, M - y_row); + const int ks = 16 * int(simd_gid); + const short2 sc = BaseNAXFrag::get_coord(); + const int r0 = min(int(sc.y), tile_rows - 1); + const int r1 = min(int(sc.y) + 8, tile_rows - 1); + const device T* x0 = x + (y_row + r0) * static_cast(K) + ks + sc.x; + const device T* x1 = x + (y_row + r1) * static_cast(K) + ks + sc.x; + + NAXTile Dtile; + Dtile.clear(); + + loader_w.fetch(0); + loader_w.store(Ws); + vec a_cur0 = *(const device vec*)x0; + vec a_cur1 = *(const device vec*)x1; + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int k = 0, it = 0; k < k_end; k += BK, it++) { + const bool more = k + BK < k_end; + if (more) { + loader_w.fetch(k + BK); + } + const int kn = more ? k + BK : k; + const vec a_next0 = *(const device vec*)(x0 + kn); + const vec a_next1 = *(const device vec*)(x1 + kn); + frag_t a; + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + a[c] = a_cur0[c]; + a[4 + c] = a_cur1[c]; + } + const threadgroup T* ws = + Ws + (it & 1) * tile_size + sc.y * BK_padded + sc.x + ks; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < BN / 16; j += 2) { + const threadgroup T* p0 = ws + (j * 16) * BK_padded; + const threadgroup T* p1 = p0 + 16 * BK_padded; + frag_t b0; + frag_t b1; + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + const vec u0 = + *(const threadgroup vec*)(p0 + h * 8 * BK_padded); + const vec u1 = + *(const threadgroup vec*)(p1 + h * 8 * BK_padded); + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + b0[h * 4 + c] = u0[c]; + b1[h * 4 + c] = u1[c]; + } + } + BaseNAXFrag::mma( + Dtile.frag_at(0, j), + Dtile.frag_at(0, j + 1), + a, + metal::bool_constant{}, + b0, + b1, + metal::bool_constant{}); + } + a_cur0 = a_next0; + a_cur1 = a_next1; + if (more) { + loader_w.store(Ws + ((it + 1) & 1) * tile_size); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // The loop's last barrier ends every read of Ws: it holds the partials. + threadgroup float* part = (threadgroup float*)Ws; + if (simd_gid > 0) { + threadgroup float* p = part + + ((int(simd_gid) - 1) * n_frags * SIMD_SIZE + simd_lid) * frag_elems; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < n_frags; f++) { + STEEL_PRAGMA_UNROLL + for (short e = 0; e < frag_elems; e++) { + p[f * SIMD_SIZE * frag_elems + e] = Dtile.frag_at(0, f)[e]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd_gid > 0) { + return; + } + STEEL_PRAGMA_UNROLL + for (short g = 0; g < WM - 1; g++) { + const threadgroup float* p = + part + (g * n_frags * SIMD_SIZE + simd_lid) * frag_elems; + STEEL_PRAGMA_UNROLL + for (short f = 0; f < n_frags; f++) { + STEEL_PRAGMA_UNROLL + for (short e = 0; e < frag_elems; e++) { + Dtile.frag_at(0, f)[e] += p[f * SIMD_SIZE * frag_elems + e]; + } + } + } + + y += y_row * static_cast(N) + y_col; + if (tile_rows == SM) { + Dtile.store(y, N); + } else { + Dtile.store_safe(y, N, short2(BN, tile_rows)); + } +} + // Each simdgroup computes SM rows and prefetches the next activation tile. // Weights use two threadgroup buffers with one barrier between K steps. template < @@ -1170,6 +1342,15 @@ METAL_FUNC void qmm_t_nax_staged_impl( bits>; using frag_t = typename BaseNAXFrag::template dtype_frag_t; + // At most SM rows in all: split each BK step over the simdgroups instead. + if constexpr ((BM / SM) * 16 == BK) { + if (M <= SM) { + qmm_t_nax_staged_ksplit_impl( + w, scales, biases, x, y, Ws, K, N, M, k_end, tid, simd_gid, simd_lid); + return; + } + } + const int K_w = K * bytes_per_pack / pack_factor; const int K_g = K / group_size; const int y_row = tid.y * BM; From 5bead7b104076b837a103f6cd70fced5baa806f0 Mon Sep 17 00:00:00 2001 From: Gumbii Digital <189439224+GumbiiDigital@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:23:00 -0500 Subject: [PATCH 2/3] metal: gate NAX affine K-split and add M5-routed kernel tests 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. --- docs/src/usage/environment_variables.rst | 12 +- fork.yaml | 35 +- mlx/backend/metal/jit_kernels.cpp | 13 +- mlx/backend/metal/kernels.h | 4 +- mlx/backend/metal/kernels/fp_quantized_nax.h | 7 + mlx/backend/metal/kernels/quantized_nax.h | 7 +- mlx/backend/metal/nojit_kernels.cpp | 10 +- mlx/backend/metal/quantized.cpp | 135 +++++-- mlx/utils.h | 7 + tests/CMakeLists.txt | 13 +- tests/nax_quantized_kernel_tests.cpp | 404 +++++++++++++++++++ 11 files changed, 598 insertions(+), 49 deletions(-) create mode 100644 tests/nax_quantized_kernel_tests.cpp diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index b41afbc334..bed8192ff1 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -153,10 +153,20 @@ Metal give a row different bits at some row counts: ``qmv_mma`` for 6 to 16 rows of the floating-point modes, and the affine split-K kernel from 8 rows on GPUs with neural accelerators. The vector limit is 6 to 33 rows; it - depends on the GPU and on the shape. A row alone (``qmv``) can get bits + depends on the GPU and on the shape. A row alone (``qmv``) can get bits that are different from the bits of the same row among two or more rows. MLX reads this variable once in each process. +.. envvar:: MLX_NAX_KSPLIT + + Enable K-split across all four simdgroups in the staged NAX affine + quantized matmul kernel (``qmm_t_nax_staged_ksplit_impl``) when + ``M <= 16`` (reachable at ``8 <= M <= 16`` on M5+ GPUs with neural + accelerators). The default is ``1``. Set it to ``0`` to keep the unsplit + staged loop and match the FP32 K-reduction summation order of ``M > 16`` + rows. Setting ``MLX_QMV_BATCH_INVARIANT=1`` also disables K-split. MLX + reads this variable once in each process. + Advanced tuning --------------- diff --git a/fork.yaml b/fork.yaml index d9a90dbea7..1f8385e3cd 100644 --- a/fork.yaml +++ b/fork.yaml @@ -589,22 +589,41 @@ def: Two M5-series NAX quantized Metal kernel optimizations ported from the Muse Glimmer 30B challenge line (`Layr-Labs/mlxfast-muse-glimmer-30b-engine` commits `80b35945` and `9976cc74`): - - `qmm_t_nax_staged_ksplit_impl` in `quantized_nax.h`: when `M <= SM` (`M <= 16`) + - `qmm_t_nax_staged_ksplit_impl` in `quantized_nax.h`: when `M <= SM` (`M <= 16`, + reachable at `8 <= M <= 16` on M5+ NAX via `qmm_splitk_nax` and `qmm_nax`) and `(BM / SM) * 16 == BK` (`BM=64, BK=64, BN=64, WM=4, WN=1`), splits each `BK` step into 16-column slices across all 4 simdgroups instead of leaving 3 simdgroups idle, then reduces FP32 partial tiles in simdgroup order in threadgroup memory (FP32 throughout; changes only K-reduction summation order - for `M <= 16` affine 16-bit products on NAX). + for `8 <= M <= 16` affine 16-bit products on NAX). Gated via Metal function + constant `use_ksplit` (index 203) from the host (`MLX_NAX_KSPLIT`, default `1`; + disabled when `MLX_NAX_KSPLIT=0` or `MLX_QMV_BATCH_INVARIANT=1`). - `FPQuantizedNAXBlockLoader::fetch_nvfp4` / `store_nvfp4`, double-buffered - `Ws` in `fp_qmm_t_impl` / `fp_qmm_t_nax`, and `dequantize_fp4_x4_scaled` + - `M <= 8` peeled 1-ahead prefetch in `fp_qmv_nax` (`fp_quantized_nax.h`): - vectorizes NVFP4 (`bits == 4, group_size == 16, !has_global_scale, sizeof(Wtype) == 2`) - weight/scale loads and `half2` E2M1 dequantization (0-ULP bit-identical to - stock over all 4,096 `(fp8_e4m3, fp4_e2m1)` pairs), guarded by alignment and - `K > 0` checks. + `Ws` in `fp_qmm_t_impl` / `fp_qmm_t_nax`, and bit-manipulation + `dequantize_fp4_x4_scaled` + `6 <= M <= 8` (`M <= 8`) peeled 1-ahead prefetch + in `fp_qmv_nax` (`fp_quantized_nax.h`): vectorizes NVFP4 (`bits == 4, + group_size == 16, !has_global_scale`, 16-bit `Ws` storage width `Wtype = bfloat` + across `fp_qmm_t_nax`, `fp_gather_qmm_t_nax`, and `fp_gather_qmm_rhs_nax` for + all activation dtypes, plus 16-bit `fp_qmm_n_nax` when instantiated) weight/scale + loads and `half2` E2M1 dequantization (0-ULP bit-identical to stock over all + 4,096 `(fp8_e4m3, fp4_e2m1)` pairs), guarded by `K > 0`, `K % 32 == 0`, and + 16B `wl` / 2B `scales` alignment checks. + - `tests/nax_quantized_kernel_tests.cpp` covers M5-routed affine K-split + (split-K and direct staged, plus bitwise parity under `MLX_NAX_KSPLIT=0`), + unbatched/batched double-buffered NVFP4 GEMM, `6 <= M <= 8` peeled QMV, + NVFP4 MoE gather (`fp_gather_qmm_t_nax` and `fp_gather_qmm_rhs_nax`), and + genuinely misaligned 4B/1B offset fallback bitwise parity. globs: + - "mlx/utils.h" + - "mlx/backend/metal/kernels.h" + - "mlx/backend/metal/jit_kernels.cpp" + - "mlx/backend/metal/nojit_kernels.cpp" + - "mlx/backend/metal/quantized.cpp" - "mlx/backend/metal/kernels/quantized_nax.h" - "mlx/backend/metal/kernels/fp_quantized_nax.h" + - "docs/src/usage/environment_variables.rst" + - "tests/nax_quantized_kernel_tests.cpp" + - "tests/CMakeLists.txt" - title: "Run-time template of the head-dim split NAX attention" description: | Upstream's head-dim split attention (`attention_nax_dsplit`, the NAX full-attention diff --git a/mlx/backend/metal/jit_kernels.cpp b/mlx/backend/metal/jit_kernels.cpp index f231b9b483..5a1d565579 100644 --- a/mlx/backend/metal/jit_kernels.cpp +++ b/mlx/backend/metal/jit_kernels.cpp @@ -1293,7 +1293,9 @@ MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, const std::string& template_def, - const std::string& mode) { + const std::string& mode, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { const auto& lib_name = kernel_name; auto lib = d.get_library(lib_name, [&]() { std::string kernel_source; @@ -1306,7 +1308,14 @@ MTL::ComputePipelineState* get_qmm_nax_kernel( template_def); return kernel_source; }); - return d.get_kernel(kernel_name, lib); + if (func_consts.empty()) { + return d.get_kernel(kernel_name, lib); + } + return d.get_kernel( + kernel_name, + lib, + hash_name.empty() ? kernel_name : hash_name, + func_consts); } MTL::ComputePipelineState* get_gather_qmm_nax_kernel( diff --git a/mlx/backend/metal/kernels.h b/mlx/backend/metal/kernels.h index f19e8a7df1..b2bb739ae6 100644 --- a/mlx/backend/metal/kernels.h +++ b/mlx/backend/metal/kernels.h @@ -403,7 +403,9 @@ MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, const std::string& template_def, - const std::string& mode); + const std::string& mode, + const std::string& hash_name = "", + const metal::MTLFCList& func_consts = {}); MTL::ComputePipelineState* get_gather_qmm_nax_kernel( metal::Device& d, diff --git a/mlx/backend/metal/kernels/fp_quantized_nax.h b/mlx/backend/metal/kernels/fp_quantized_nax.h index c7873eb958..98d5946915 100644 --- a/mlx/backend/metal/kernels/fp_quantized_nax.h +++ b/mlx/backend/metal/kernels/fp_quantized_nax.h @@ -244,6 +244,10 @@ struct FPQuantizedNAXBlockLoader { return; } + // sizeof(T) == 2 checks the 16-bit threadgroup tile storage width (Wtype, + // which is bfloat across fp_qmm_t_nax / fp_gather_qmm_t_nax / + // fp_gather_qmm_rhs_nax regardless of activation dtype, and activation T + // in fp_qmm_n_impl) so vec stores remain 16-byte aligned. if constexpr ( bits == 4 && group_size == 16 && !has_global_scale && sizeof(T) == 2 && n_reads_per_scale == 8) { @@ -412,6 +416,9 @@ METAL_FUNC void fp_qmm_t_impl( const bool fast_nvfp4 = (K > 0) && ((K & 31) == 0) && ((reinterpret_cast(wl) & 15) == 0) && ((reinterpret_cast(scales) & 1) == 0); + // sizeof(Wtype) == 2 checks the 16-bit threadgroup weight-tile storage + // width (bfloat in fp_qmm_t_nax and fp_gather_qmm_t_nax for all + // activation dtypes) so vec stores remain 16-byte aligned. if constexpr ( kAlignedN.value && bits == 4 && group_size == 16 && !has_global_scale && sizeof(Wtype) == 2 && diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index f5b0fb0036..035d0da2ef 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -9,6 +9,7 @@ using namespace mlx::steel; constant bool align_M [[function_constant(200)]]; constant bool align_N [[function_constant(201)]]; constant bool align_K [[function_constant(202)]]; +constant bool use_ksplit [[function_constant(203)]]; using namespace metal; @@ -1342,9 +1343,11 @@ METAL_FUNC void qmm_t_nax_staged_impl( bits>; using frag_t = typename BaseNAXFrag::template dtype_frag_t; - // At most SM rows in all: split each BK step over the simdgroups instead. + // At most SM rows in all: split each BK step over the simdgroups instead + // unless disabled by the host (MLX_NAX_KSPLIT=0 or + // MLX_QMV_BATCH_INVARIANT=1). if constexpr ((BM / SM) * 16 == BK) { - if (M <= SM) { + if ((!is_function_constant_defined(use_ksplit) || use_ksplit) && M <= SM) { qmm_t_nax_staged_ksplit_impl( w, scales, biases, x, y, Ws, K, N, M, k_end, tid, simd_gid, simd_lid); return; diff --git a/mlx/backend/metal/nojit_kernels.cpp b/mlx/backend/metal/nojit_kernels.cpp index 4adb17659c..7df7785baa 100644 --- a/mlx/backend/metal/nojit_kernels.cpp +++ b/mlx/backend/metal/nojit_kernels.cpp @@ -476,8 +476,14 @@ MTL::ComputePipelineState* get_qmm_nax_kernel( metal::Device& d, const std::string& kernel_name, const std::string&, - const std::string&) { - return d.get_kernel(kernel_name); + const std::string&, + const std::string& hash_name, + const metal::MTLFCList& func_consts) { + if (func_consts.empty()) { + return d.get_kernel(kernel_name); + } + return d.get_kernel( + kernel_name, hash_name.empty() ? kernel_name : hash_name, func_consts); } MTL::ComputePipelineState* get_gather_qmm_nax_kernel( diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index 0d5e6c8220..9bbb0b17e0 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -57,6 +57,26 @@ auto get_qmm_nax_kernel_wrapped( return get_qmm_nax_kernel(d, name, template_def, mode); } +template +auto get_qmm_nax_kernel_wrapped_fc( + metal::Device& d, + const std::string& name, + const std::string& hash_name, + const metal::MTLFCList& func_consts, + const std::string& func, + const std::string& mode, + const std::string& type, + int group_size, + int bits, + Args... args) { + std::string template_def; + std::string fname = ((mode == "affine") ? "affine_" : "fp_") + func; + template_def = get_template_definition( + name, fname, type, group_size, bits, std::forward(args)...); + return get_qmm_nax_kernel( + d, name, template_def, mode, hash_name, func_consts); +} + inline array ensure_row_contiguous(const array& x, metal::Device& d, const Stream& s) { if (!x.flags().row_contiguous) { @@ -960,7 +980,8 @@ void qmm_nax( int bk = 64; bool aligned_n = (N % 64 == 0); - if (use_qmm_t_nax_staged(x, transpose, aligned_n, mode)) { + bool use_staged = use_qmm_t_nax_staged(x, transpose, aligned_n, mode); + if (use_staged) { wm = 4; wn = 1; bm = 64; @@ -996,22 +1017,47 @@ void qmm_nax( std::string template_def; MTL::ComputePipelineState* kernel; if (transpose) { - kernel = get_qmm_nax_kernel_wrapped( - d, - kname, - "qmm_t_nax", - mode, - type_string, - group_size, - bits, - aligned_n, - batched, - bm, - bk, - bn, - wm, - wn, - global_scale.has_value()); + if (use_staged) { + bool use_ksplit = env::nax_ksplit() && !env::qmv_batch_invariant(); + metal::MTLFCList func_consts = { + {&use_ksplit, MTL::DataType::DataTypeBool, 203}}; + std::string hash_name = kname + (use_ksplit ? "_ksplit_1" : "_ksplit_0"); + kernel = get_qmm_nax_kernel_wrapped_fc( + d, + kname, + hash_name, + func_consts, + "qmm_t_nax", + mode, + type_string, + group_size, + bits, + aligned_n, + batched, + bm, + bk, + bn, + wm, + wn, + global_scale.has_value()); + } else { + kernel = get_qmm_nax_kernel_wrapped( + d, + kname, + "qmm_t_nax", + mode, + type_string, + group_size, + bits, + aligned_n, + batched, + bm, + bk, + bn, + wm, + wn, + global_scale.has_value()); + } } else { kernel = get_qmm_nax_kernel_wrapped( d, @@ -1427,7 +1473,8 @@ void qmm_splitk_nax( int wn = 2; MTL::Size group_dims(32, wn, wm); - if (use_qmm_t_nax_staged(x, true, true, mode)) { + bool use_staged = use_qmm_t_nax_staged(x, true, true, mode); + if (use_staged) { bm = 64; wm = 4; wn = 1; @@ -1484,20 +1531,44 @@ void qmm_splitk_nax( "_wn", wn, "_alN_true"); - auto kernel = get_qmm_nax_kernel_wrapped( - d, - kname, - "qmm_t_nax_splitk", - mode, - type_string, - group_size, - bits, - true, - bm, - bk, - bn, - wm, - wn); + MTL::ComputePipelineState* kernel; + if (use_staged) { + bool use_ksplit = env::nax_ksplit() && !env::qmv_batch_invariant(); + metal::MTLFCList func_consts = { + {&use_ksplit, MTL::DataType::DataTypeBool, 203}}; + std::string hash_name = kname + (use_ksplit ? "_ksplit_1" : "_ksplit_0"); + kernel = get_qmm_nax_kernel_wrapped_fc( + d, + kname, + hash_name, + func_consts, + "qmm_t_nax_splitk", + mode, + type_string, + group_size, + bits, + true, + bm, + bk, + bn, + wm, + wn); + } else { + kernel = get_qmm_nax_kernel_wrapped( + d, + kname, + "qmm_t_nax_splitk", + mode, + type_string, + group_size, + bits, + true, + bm, + bk, + bn, + wm, + wn); + } compute_encoder.set_compute_pipeline_state(kernel); int c = 0; diff --git a/mlx/utils.h b/mlx/utils.h index f47f276431..95b8a9dd3f 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -242,6 +242,13 @@ inline bool qmv_batch_invariant() { return invariant_; } +// Enable K-split across simdgroups in staged NAX affine qmm when M <= 16. +// Disabled automatically when MLX_QMV_BATCH_INVARIANT=1 is set. +inline bool nax_ksplit() { + static bool enabled_ = get_var("MLX_NAX_KSPLIT", 1); + return enabled_; +} + inline bool metal_fast_synch() { static bool metal_fast_synch = get_var("MLX_METAL_FAST_SYNCH", 0); return metal_fast_synch; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index abb29b114d..80a3bc3376 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -26,7 +26,8 @@ if(MLX_BUILD_METAL) "MLX_METAL_FAST_SYNCH=1;MLX_MAX_OPS_PER_BUFFER=${ops}") endforeach() list(APPEND GPU_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp - quantized_tile_tests.cpp qmv_batch_invariant_tests.cpp) + quantized_tile_tests.cpp qmv_batch_invariant_tests.cpp + nax_quantized_kernel_tests.cpp) # MLX reads MLX_QMV_BATCH_INVARIANT once in each process, so this entry runs # the case again in a new process with the switch on. The tests entries run it # with the switch off. The entry fails also if no test case has this name. @@ -40,6 +41,16 @@ if(MLX_BUILD_METAL) qmv_batch_invariant PROPERTIES ENVIRONMENT "MLX_QMV_BATCH_INVARIANT=1" PASS_REGULAR_EXPRESSION "test cases: +1 \\| +1 passed \\| +0 failed") + add_test( + NAME nax_ksplit_disabled + COMMAND + tests + "--test-case=NAX affine K-split split-K and direct staged routes" + ) + set_tests_properties( + nax_ksplit_disabled + PROPERTIES ENVIRONMENT "MLX_NAX_KSPLIT=0" PASS_REGULAR_EXPRESSION + "test cases: +1 \\| +1 passed \\| +0 failed") endif() include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake) diff --git a/tests/nax_quantized_kernel_tests.cpp b/tests/nax_quantized_kernel_tests.cpp new file mode 100644 index 0000000000..9c5ffa70b2 --- /dev/null +++ b/tests/nax_quantized_kernel_tests.cpp @@ -0,0 +1,404 @@ +// Copyright © 2026 Eigen Labs. +#include +#include +#include +#include +#include + +#include "doctest/doctest.h" +#include "mlx/mlx.h" +#include "mlx/utils.h" + +using namespace mlx::core; + +namespace { + +bool same_bytes(const array& a, const array& b) { + auto bytes = [](const array& x) { + auto type = x.dtype() == float32 ? uint32 : uint16; + return view(contiguous(x, false, Device::gpu), type, Device::gpu); + }; + return array_equal(bytes(a), bytes(b), Device::cpu).item(); +} + +// Returns a row-contiguous view of `src` shifted by `elem_offset` elements in +// a freshly allocated 1D buffer so byte alignment is strictly non-multiple of +// 16 (for uint32 with elem_offset=1 -> 4B) or 2 (for uint8 with +// elem_offset=1 -> 1B). +array offset_view(const array& src, int elem_offset) { + auto flat = reshape(contiguous(src, false, Device::cpu), {-1}, Device::cpu); + auto pad = zeros({elem_offset}, src.dtype(), Device::cpu); + auto buf = concatenate({pad, flat}, 0, Device::cpu); + eval(buf); + auto shifted = slice( + buf, + {elem_offset}, + {elem_offset + static_cast(src.size())}, + Device::cpu); + auto out = reshape(shifted, src.shape(), Device::cpu); + eval(out); + return out; +} + +} // namespace + +TEST_CASE("NAX affine K-split split-K and direct staged routes") { + const char* ksplit_env = std::getenv("MLX_NAX_KSPLIT"); + bool expected_ksplit = ksplit_env == nullptr || std::atoi(ksplit_env) != 0; + REQUIRE(env::nax_ksplit() == expected_ksplit); + + const bool ksplit_disabled = !env::nax_ksplit() || env::qmv_batch_invariant(); + + // Route 1: split-K NAX staged (M in 8..16, N=2048, K=2048, biases present). + // Route 2: direct qmm_nax staged (M in 13..16, N=K=4160 = 65*64 so + // K % 64 == 0, K % 128 != 0, vector_limit = 13/12, split_k = 1). + struct Shape { + int N; + int K; + std::vector rows; + }; + std::vector shapes = { + {2048, 2048, {8, 12, 16, 17}}, + {4160, 4160, {13, 16, 17}}, + }; + + for (const auto& shape : shapes) { + for (auto dtype : {bfloat16, float16}) { + CAPTURE(shape.N); + CAPTURE(shape.K); + CAPTURE(dtype); + + auto w = astype( + random::uniform( + -0.5f, + 0.5f, + {shape.N, shape.K}, + float32, + random::key(101 + shape.N), + Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 64, 4, "affine", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + q[2], + 64, + 4, + "affine", + std::nullopt, + float32, + Device::cpu); + eval(q[0], q[1], q[2], dq); + + int max_m = shape.rows.back(); + auto x_all = astype( + random::uniform( + -0.5f, + 0.5f, + {max_m, shape.K}, + float32, + random::key(202 + shape.N), + Device::cpu), + dtype, + Device::cpu); + eval(x_all); + + auto out_max = quantized_matmul( + x_all, q[0], q[1], q[2], true, 64, 4, "affine", Device::gpu); + eval(out_max); + + double tol = dtype == bfloat16 ? 8e-2 : 2e-2; + for (int m : shape.rows) { + CAPTURE(m); + auto x = slice(x_all, {0, 0}, {m, shape.K}, Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + transpose(dq, Device::cpu), + Device::cpu); + auto actual = quantized_matmul( + x, q[0], q[1], q[2], true, 64, 4, "affine", Device::gpu); + eval(ref, actual); + CHECK(allclose( + astype(actual, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item()); + + // When K-split is disabled (MLX_NAX_KSPLIT=0 or + // MLX_QMV_BATCH_INVARIANT=1), the direct staged route (N=K=4160, + // M >= 13) uses the identical unsplit staged kernel for M <= 16 and + // M = 17, so prefix rows must match bitwise. + if (ksplit_disabled && shape.N == 4160 && m < max_m) { + auto expected_rows = + slice(out_max, {0, 0}, {m, shape.N}, Device::gpu); + CHECK(same_bytes(actual, expected_rows)); + } + } + } + } +} + +TEST_CASE( + "NAX NVFP4 double-buffered GEMM, peeled QMV, gather MoE, and misaligned fallback") { + for (auto dtype : {bfloat16, float16}) { + CAPTURE(dtype); + double tol = dtype == bfloat16 ? 1e-1 : 3e-2; + + // 1. Unbatched double-buffered fp_qmm_t_nax (M=512, N=1024 -> 512 tiles -> + // split_k <= 1 -> routes directly to qmm_nax on M5). + { + int M = 512, N = 1024, K = 256; + auto w = astype( + random::uniform( + -0.5f, 0.5f, {N, K}, float32, random::key(301), Device::cpu), + dtype, + Device::cpu); + auto x = astype( + random::uniform( + -0.5f, 0.5f, {M, K}, float32, random::key(302), Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + transpose(dq, Device::cpu), + Device::cpu); + auto actual = quantized_matmul( + x, q[0], q[1], std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + eval(ref, actual); + CHECK(allclose( + astype(actual, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item()); + } + + // 2. Batched double-buffered fp_qmm_t_nax (B=2, M=64, aligned N=128 and + // unaligned N=96) plus genuinely misaligned 4B weight / 1B scale offset + // fallback (must match the aligned fast path bitwise). + for (int N : {128, 96}) { + CAPTURE(N); + int B = 2, M = 64, K = 128; + auto w = astype( + random::uniform( + -0.5f, + 0.5f, + {B, N, K}, + float32, + random::key(401 + N), + Device::cpu), + dtype, + Device::cpu); + auto x = astype( + random::uniform( + -0.5f, + 0.5f, + {B, M, K}, + float32, + random::key(402 + N), + Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + swapaxes(dq, -1, -2, Device::cpu), + Device::cpu); + auto aligned_out = quantized_matmul( + x, q[0], q[1], std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + + auto w_mis = offset_view(q[0], 1); + auto s_mis = offset_view(q[1], 1); + REQUIRE(w_mis.offset() == 4); + REQUIRE(s_mis.offset() == 1); + REQUIRE(w_mis.flags().row_contiguous); + REQUIRE(s_mis.flags().row_contiguous); + + auto fallback_out = quantized_matmul( + x, w_mis, s_mis, std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + eval(ref, aligned_out, fallback_out); + CHECK(allclose( + astype(aligned_out, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item()); + CHECK(same_bytes(aligned_out, fallback_out)); + } + + // 3. Peeled fp_qmv_nax (6 <= M <= 8) and unpeeled fp_qmv_nax (M = 9). + { + int N = 2048, K = 2048; + auto w = astype( + random::uniform( + -0.5f, 0.5f, {N, K}, float32, random::key(501), Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + eval(q[0], q[1], dq); + for (int m : {6, 7, 8, 9}) { + CAPTURE(m); + auto x = astype( + random::uniform( + -0.5f, + 0.5f, + {m, K}, + float32, + random::key(510 + m), + Device::cpu), + dtype, + Device::cpu); + auto ref = matmul( + astype(x, float32, Device::cpu), + transpose(dq, Device::cpu), + Device::cpu); + auto actual = quantized_matmul( + x, q[0], q[1], std::nullopt, true, 16, 4, "nvfp4", Device::gpu); + eval(ref, actual); + CHECK(allclose( + astype(actual, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item()); + } + } + + // 4. NVFP4 MoE gather paths (fp_gather_qmm_t_nax for sorted=false, + // fp_gather_qmm_rhs_nax for sorted=true) + misaligned bitwise parity. + { + int E = 4, M = 64, N = 128, K = 128; + auto w = astype( + random::uniform( + -0.5f, 0.5f, {E, N, K}, float32, random::key(601), Device::cpu), + dtype, + Device::cpu); + auto x = astype( + random::uniform( + -0.5f, + 0.5f, + {M, 1, 1, K}, + float32, + random::key(602), + Device::cpu), + dtype, + Device::cpu); + auto q = quantize(w, 16, 4, "nvfp4", std::nullopt, Device::cpu); + auto dq = dequantize( + q[0], + q[1], + std::nullopt, + 16, + 4, + "nvfp4", + std::nullopt, + float32, + Device::cpu); + + auto w_mis = offset_view(q[0], 1); + auto s_mis = offset_view(q[1], 1); + REQUIRE(w_mis.offset() == 4); + REQUIRE(s_mis.offset() == 1); + + std::vector idx_vals(M); + for (int i = 0; i < M; ++i) { + idx_vals[i] = static_cast(i / (M / E)); + } + auto rhs_sorted = array(idx_vals.data(), {M, 1}, uint32); + auto rhs_unsorted = random::randint( + array(0), array(E), {M, 1}, uint32, random::key(603), Device::cpu); + eval(q[0], q[1], dq, x, w_mis, s_mis, rhs_sorted, rhs_unsorted); + + for (bool sorted : {false, true}) { + CAPTURE(sorted); + auto rhs = sorted ? rhs_sorted : rhs_unsorted; + auto out_aligned = gather_qmm( + x, + q[0], + q[1], + std::nullopt, + std::nullopt, + rhs, + true, + 16, + 4, + "nvfp4", + std::nullopt, + sorted, + Device::gpu); + auto out_fallback = gather_qmm( + x, + w_mis, + s_mis, + std::nullopt, + std::nullopt, + rhs, + true, + 16, + 4, + "nvfp4", + std::nullopt, + sorted, + Device::gpu); + auto w_gathered = + take(dq, squeeze(rhs, 1, Device::cpu), 0, Device::cpu); + auto ref = matmul( + reshape(astype(x, float32, Device::cpu), {M, 1, K}, Device::cpu), + swapaxes(w_gathered, -1, -2, Device::cpu), + Device::cpu); + ref = reshape(ref, {M, 1, 1, N}, Device::cpu); + eval(out_aligned, out_fallback, ref); + CHECK(allclose( + astype(out_aligned, float32, Device::cpu), + ref, + tol, + tol, + false, + Device::cpu) + .item()); + CHECK(same_bytes(out_aligned, out_fallback)); + } + } + } +} From 500c5d7e6fb720f49559e56aeb3b8066271db620 Mon Sep 17 00:00:00 2001 From: Gumbii Digital <189439224+GumbiiDigital@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:25:56 -0500 Subject: [PATCH 3/3] metal: default MLX_NAX_KSPLIT to 0, coordinate #71 gate, log/assert NAX path Address jonathan308's review comments on Layr-Labs/mlx#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 Layr-Labs/mlx#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 56e12b00 on main) under Fork tooling in fork.yaml so Fork Diff Check passes after rebasing onto main. --- .github/workflows/fork-tests.yml | 11 ++++++ docs/src/usage/environment_variables.rst | 9 ++--- fork.yaml | 21 +++++++---- mlx/backend/metal/quantized.cpp | 22 +++++++++--- mlx/utils.h | 6 ++-- tests/CMakeLists.txt | 23 ++++++------ tests/nax_quantized_kernel_tests.cpp | 46 +++++++++++++++++++----- 7 files changed, 102 insertions(+), 36 deletions(-) diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml index 1fce1030e5..9850902cc3 100644 --- a/.github/workflows/fork-tests.yml +++ b/.github/workflows/fork-tests.yml @@ -204,6 +204,17 @@ jobs: ctest --test-dir build -R '^qmv_batch_invariant$' \ --output-on-failure --no-tests=error + - name: Run the NAX quantized kernel tests with MLX_NAX_KSPLIT=1 + # MLX reads the switch once in each process. The C++ test steps above + # run the case with the default (MLX_NAX_KSPLIT=0); this ctest entry + # runs it again with K-split enabled (tests/CMakeLists.txt). + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + env: + LLVM_PROFILE_FILE: ${{ runner.temp }}/profiles/nax-ksplit-%p-%m.profraw + run: | + ctest --test-dir build -R '^nax_ksplit_enabled$' \ + --output-on-failure --no-tests=error + - name: Merge the coverage profiles if: ${{ !cancelled() && steps.build.outcome == 'success' }} run: | diff --git a/docs/src/usage/environment_variables.rst b/docs/src/usage/environment_variables.rst index bed8192ff1..b411152ab7 100644 --- a/docs/src/usage/environment_variables.rst +++ b/docs/src/usage/environment_variables.rst @@ -162,10 +162,11 @@ Metal Enable K-split across all four simdgroups in the staged NAX affine quantized matmul kernel (``qmm_t_nax_staged_ksplit_impl``) when ``M <= 16`` (reachable at ``8 <= M <= 16`` on M5+ GPUs with neural - accelerators). The default is ``1``. Set it to ``0`` to keep the unsplit - staged loop and match the FP32 K-reduction summation order of ``M > 16`` - rows. Setting ``MLX_QMV_BATCH_INVARIANT=1`` also disables K-split. MLX - reads this variable once in each process. + accelerators). The default is ``0`` (opt-in), because 4-way K-split + changes the FP32 K-reduction summation order relative to the unsplit + staged loop and to ``M > 16`` rows. Set it to ``1`` to opt in. Setting + ``MLX_QMV_BATCH_INVARIANT=1`` disables K-split even when ``MLX_NAX_KSPLIT=1`` + is set. MLX reads this variable once in each process. Advanced tuning --------------- diff --git a/fork.yaml b/fork.yaml index 1f8385e3cd..7e245c8cbf 100644 --- a/fork.yaml +++ b/fork.yaml @@ -596,8 +596,9 @@ def: simdgroups idle, then reduces FP32 partial tiles in simdgroup order in threadgroup memory (FP32 throughout; changes only K-reduction summation order for `8 <= M <= 16` affine 16-bit products on NAX). Gated via Metal function - constant `use_ksplit` (index 203) from the host (`MLX_NAX_KSPLIT`, default `1`; - disabled when `MLX_NAX_KSPLIT=0` or `MLX_QMV_BATCH_INVARIANT=1`). + constant `use_ksplit` (index 203) through `use_qmm_nax_ksplit(allow_ksplit)` + (`MLX_NAX_KSPLIT`, opt-in default `0`; disabled when `MLX_QMV_BATCH_INVARIANT=1` + or `allow_ksplit=false` for prefill-row invariance coordination with `#71`). - `FPQuantizedNAXBlockLoader::fetch_nvfp4` / `store_nvfp4`, double-buffered `Ws` in `fp_qmm_t_impl` / `fp_qmm_t_nax`, and bit-manipulation `dequantize_fp4_x4_scaled` + `6 <= M <= 8` (`M <= 8`) peeled 1-ahead prefetch @@ -608,11 +609,13 @@ def: loads and `half2` E2M1 dequantization (0-ULP bit-identical to stock over all 4,096 `(fp8_e4m3, fp4_e2m1)` pairs), guarded by `K > 0`, `K % 32 == 0`, and 16B `wl` / 2B `scales` alignment checks. - - `tests/nax_quantized_kernel_tests.cpp` covers M5-routed affine K-split - (split-K and direct staged, plus bitwise parity under `MLX_NAX_KSPLIT=0`), - unbatched/batched double-buffered NVFP4 GEMM, `6 <= M <= 8` peeled QMV, - NVFP4 MoE gather (`fp_gather_qmm_t_nax` and `fp_gather_qmm_rhs_nax`), and - genuinely misaligned 4B/1B offset fallback bitwise parity. + - `tests/nax_quantized_kernel_tests.cpp` logs GPU architecture and NAX status, + covers M5-routed affine K-split (split-K and direct staged, asserting bitwise + prefix parity when K-split is off and bitwise K-split dispatch on NAX when + `MLX_NAX_KSPLIT=1` via the `nax_ksplit_enabled` ctest entry), unbatched/batched + double-buffered NVFP4 GEMM, `6 <= M <= 8` peeled QMV, NVFP4 MoE gather + (`fp_gather_qmm_t_nax` and `fp_gather_qmm_rhs_nax`), and genuinely misaligned + 4B/1B offset fallback bitwise parity. globs: - "mlx/utils.h" - "mlx/backend/metal/kernels.h" @@ -624,6 +627,7 @@ def: - "docs/src/usage/environment_variables.rst" - "tests/nax_quantized_kernel_tests.cpp" - "tests/CMakeLists.txt" + - ".github/workflows/fork-tests.yml" - title: "Run-time template of the head-dim split NAX attention" description: | Upstream's head-dim split attention (`attention_nax_dsplit`, the NAX full-attention @@ -812,6 +816,8 @@ def: under PRoot (`.github/scripts/fedora-proot/`); the Fedora x86_64 job and the protected Pages publisher stay on GitHub-hosted runners. `FORKDIFF.md` describes the qualification and watchdog time bounds. + `AGENTS.md` adds the "Working in our MLX forks" section permitting agent-assisted + contributions in Layr-Labs forks (`56e12b00` on `main`). `darkbloom-watchdog.yml` remains unchanged; a rerun keeps these static labels. On a Darkbloom Sandbox that has no Darkbloom cache, `fork-build-cache` sets `CI_ACTIONS_CACHE=off` and every @@ -865,6 +871,7 @@ def: - ".github/scripts/test-ci-resource-sampler.py" - ".github/scripts/test-runner-sizes.py" - "scripts/check_forkdiff.py" + - "AGENTS.md" - "FORKDIFF.md" - "docs/ci-codeql-native.md" - "README.md" diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index 9bbb0b17e0..a9ace92263 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -952,6 +952,15 @@ bool use_qmm_t_nax_staged( (x.dtype() == float16 || x.dtype() == bfloat16) && (x.offset() % 8 == 0); } +// Enable 4-way simdgroup K-split in staged NAX affine qmm/qmm_splitk when +// M <= 16. Suppressed whenever batch-invariant or prefill-row-invariant +// reduction order is required (with Layr-Labs/mlx#71, pass +// `allow_ksplit = (ref_rows <= 0)` from `qmm_splitk` -> `qmm` -> `qmm_nax` +// when `split_k <= 1`). +inline bool use_qmm_nax_ksplit(bool allow_ksplit = true) { + return allow_ksplit && env::nax_ksplit() && !env::qmv_batch_invariant(); +} + void qmm_nax( const array& x, const array& w, @@ -967,7 +976,8 @@ void qmm_nax( int K, metal::Device& d, const Stream& s, - const std::string& mode) { + const std::string& mode, + bool allow_ksplit = true) { int B = out.size() / M / N; int wm = 2; @@ -1018,7 +1028,7 @@ void qmm_nax( MTL::ComputePipelineState* kernel; if (transpose) { if (use_staged) { - bool use_ksplit = env::nax_ksplit() && !env::qmv_batch_invariant(); + bool use_ksplit = use_qmm_nax_ksplit(allow_ksplit); metal::MTLFCList func_consts = { {&use_ksplit, MTL::DataType::DataTypeBool, 203}}; std::string hash_name = kname + (use_ksplit ? "_ksplit_1" : "_ksplit_0"); @@ -1235,7 +1245,8 @@ void qmm( int K, metal::Device& d, const Stream& s, - const std::string& mode) { + const std::string& mode, + bool allow_ksplit = true) { assert( (!global_scale || (transpose && !biases)) && "qmm global scale requires transposed weights without biases"); @@ -1260,7 +1271,8 @@ void qmm( /* int K = */ K, /* metal::Device& d = */ d, /* const Stream& s = */ s, - /* const std::string& mode = */ mode); + /* const std::string& mode = */ mode, + /* bool allow_ksplit = */ allow_ksplit); } int B = out.size() / M / N; @@ -1533,7 +1545,7 @@ void qmm_splitk_nax( "_alN_true"); MTL::ComputePipelineState* kernel; if (use_staged) { - bool use_ksplit = env::nax_ksplit() && !env::qmv_batch_invariant(); + bool use_ksplit = use_qmm_nax_ksplit(); metal::MTLFCList func_consts = { {&use_ksplit, MTL::DataType::DataTypeBool, 203}}; std::string hash_name = kname + (use_ksplit ? "_ksplit_1" : "_ksplit_0"); diff --git a/mlx/utils.h b/mlx/utils.h index 95b8a9dd3f..1ef39d7b8e 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -243,9 +243,11 @@ inline bool qmv_batch_invariant() { } // Enable K-split across simdgroups in staged NAX affine qmm when M <= 16. -// Disabled automatically when MLX_QMV_BATCH_INVARIANT=1 is set. +// Opt-in (default 0) because 4-way K-split changes FP32 K-reduction summation +// order at 8 <= M <= 16; disabled automatically when MLX_QMV_BATCH_INVARIANT=1 +// is set. inline bool nax_ksplit() { - static bool enabled_ = get_var("MLX_NAX_KSPLIT", 1); + static bool enabled_ = get_var("MLX_NAX_KSPLIT", 0) != 0; return enabled_; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 80a3bc3376..cc1c8cdcd6 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -25,9 +25,14 @@ if(MLX_BUILD_METAL) PROPERTIES TIMEOUT 60 ENVIRONMENT "MLX_METAL_FAST_SYNCH=1;MLX_MAX_OPS_PER_BUFFER=${ops}") endforeach() - list(APPEND GPU_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp - quantized_tile_tests.cpp qmv_batch_invariant_tests.cpp - nax_quantized_kernel_tests.cpp) + list( + APPEND + GPU_TEST_SOURCES + residency_tests.cpp + gptoss_mxfp4_tests.cpp + quantized_tile_tests.cpp + qmv_batch_invariant_tests.cpp + nax_quantized_kernel_tests.cpp) # MLX reads MLX_QMV_BATCH_INVARIANT once in each process, so this entry runs # the case again in a new process with the switch on. The tests entries run it # with the switch off. The entry fails also if no test case has this name. @@ -42,14 +47,12 @@ if(MLX_BUILD_METAL) PROPERTIES ENVIRONMENT "MLX_QMV_BATCH_INVARIANT=1" PASS_REGULAR_EXPRESSION "test cases: +1 \\| +1 passed \\| +0 failed") add_test( - NAME nax_ksplit_disabled - COMMAND - tests - "--test-case=NAX affine K-split split-K and direct staged routes" - ) + NAME nax_ksplit_enabled + COMMAND tests + "--test-case=NAX affine K-split split-K and direct staged routes") set_tests_properties( - nax_ksplit_disabled - PROPERTIES ENVIRONMENT "MLX_NAX_KSPLIT=0" PASS_REGULAR_EXPRESSION + nax_ksplit_enabled + PROPERTIES ENVIRONMENT "MLX_NAX_KSPLIT=1" PASS_REGULAR_EXPRESSION "test cases: +1 \\| +1 passed \\| +0 failed") endif() diff --git a/tests/nax_quantized_kernel_tests.cpp b/tests/nax_quantized_kernel_tests.cpp index 9c5ffa70b2..2fd1ddaec4 100644 --- a/tests/nax_quantized_kernel_tests.cpp +++ b/tests/nax_quantized_kernel_tests.cpp @@ -6,6 +6,7 @@ #include #include "doctest/doctest.h" +#include "mlx/backend/metal/device.h" #include "mlx/mlx.h" #include "mlx/utils.h" @@ -44,10 +45,21 @@ array offset_view(const array& src, int elem_offset) { TEST_CASE("NAX affine K-split split-K and direct staged routes") { const char* ksplit_env = std::getenv("MLX_NAX_KSPLIT"); - bool expected_ksplit = ksplit_env == nullptr || std::atoi(ksplit_env) != 0; + bool expected_ksplit = ksplit_env != nullptr && std::atoi(ksplit_env) != 0; REQUIRE(env::nax_ksplit() == expected_ksplit); - const bool ksplit_disabled = !env::nax_ksplit() || env::qmv_batch_invariant(); + const bool has_nax = metal::is_nax_available(); + const auto& arch = metal::device(Device::gpu).get_architecture(); + const bool ksplit_enabled = env::nax_ksplit() && !env::qmv_batch_invariant(); + MESSAGE( + "GPU arch: ", + arch, + ", is_nax_available=", + has_nax, + ", MLX_NAX_KSPLIT=", + env::nax_ksplit(), + ", MLX_QMV_BATCH_INVARIANT=", + env::qmv_batch_invariant()); // Route 1: split-K NAX staged (M in 8..16, N=2048, K=2048, biases present). // Route 2: direct qmm_nax staged (M in 13..16, N=K=4160 = 65*64 so @@ -128,14 +140,27 @@ TEST_CASE("NAX affine K-split split-K and direct staged routes") { Device::cpu) .item()); - // When K-split is disabled (MLX_NAX_KSPLIT=0 or - // MLX_QMV_BATCH_INVARIANT=1), the direct staged route (N=K=4160, - // M >= 13) uses the identical unsplit staged kernel for M <= 16 and - // M = 17, so prefix rows must match bitwise. - if (ksplit_disabled && shape.N == 4160 && m < max_m) { + if (m < max_m) { auto expected_rows = slice(out_max, {0, 0}, {m, shape.N}, Device::gpu); - CHECK(same_bytes(actual, expected_rows)); + if (!ksplit_enabled) { + // When K-split is disabled (default MLX_NAX_KSPLIT=0 or + // MLX_QMV_BATCH_INVARIANT=1), the direct staged route (N=K=4160, + // M >= 13) uses the identical unsplit staged kernel for M <= 16 + // and M = 17, so prefix rows must match bitwise. On NAX with + // !MLX_QMV_BATCH_INVARIANT, split-K (N=K=2048) also keeps the same + // split_k and unsplit staged loop across M=8..17. + if (shape.N == 4160 || + (has_nax && !env::qmv_batch_invariant() && shape.N == 2048)) { + CHECK(same_bytes(actual, expected_rows)); + } + } else if (has_nax) { + // On NAX hardware with MLX_NAX_KSPLIT=1 and batch invariance off, + // M <= 16 must dispatch qmm_t_nax_staged_ksplit_impl (4-way K-split + // reduction order), which differs bitwise from the M = 17 unsplit + // staged loop and proves the NAX K-split kernel actually ran. + CHECK_FALSE(same_bytes(actual, expected_rows)); + } } } } @@ -144,6 +169,11 @@ TEST_CASE("NAX affine K-split split-K and direct staged routes") { TEST_CASE( "NAX NVFP4 double-buffered GEMM, peeled QMV, gather MoE, and misaligned fallback") { + MESSAGE( + "GPU arch: ", + metal::device(Device::gpu).get_architecture(), + ", is_nax_available=", + metal::is_nax_available()); for (auto dtype : {bfloat16, float16}) { CAPTURE(dtype); double tol = dtype == bfloat16 ? 1e-1 : 3e-2;