diff --git a/mlx/backend/metal/kernels/quantized_nax.h b/mlx/backend/metal/kernels/quantized_nax.h index 95f26868fc..c75f6a3974 100644 --- a/mlx/backend/metal/kernels/quantized_nax.h +++ b/mlx/backend/metal/kernels/quantized_nax.h @@ -563,9 +563,13 @@ qouter(const thread uint8_t* w, U x, U scale, U bias, thread U* result) { } } -template -inline void -dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local) { +template < + typename U, + int N, + int bits, + typename BytePtr = const device uint8_t*, + typename OutPtr = threadgroup U*> +inline void dequantize(BytePtr w, U scale, U bias, OutPtr w_local) { static_assert( bits == 1 || bits == 2 || bits == 3 || bits == 4 || bits == 5 || bits == 6 || bits == 8, @@ -1020,26 +1024,291 @@ METAL_FUNC void adjust_matrix_offsets( y += tid.z * output_stride; } +// QuantizedBlockLoader's thread mapping split into two steps: fetch() reads the +// packed words and the group's scale and bias for one BK step into registers, +// store() dequantizes them into threadgroup memory. Fetching step k + 1 before +// the MMAs of step k hides the device reads behind the matrix work. template < typename T, - const int group_size, - const int bits, - const bool aligned_N, - const int BM = 64, - const int BK = 64, - const int BN = 64, - const int WM = 2, - const int WN = 2> + short BROWS, + short BCOLS, + short dst_ld, + short tgp_size, + short group_size, + short bits> +struct QuantizedBlockLoaderStaged { + MLX_MTL_CONST short pack_factor = get_pack_factor(); + MLX_MTL_CONST short bytes_per_pack = get_bytes_per_pack(); + MLX_MTL_CONST short BCOLS_PACKED = BCOLS / pack_factor; + MLX_MTL_CONST short n_reads = (BCOLS_PACKED * BROWS) / tgp_size; + MLX_MTL_CONST short n_words = n_reads * bytes_per_pack / 4; + + static_assert( + BCOLS_PACKED * BROWS >= tgp_size && + n_words * 4 == n_reads * bytes_per_pack, + "Every thread loads whole words"); + static_assert( + n_reads * pack_factor <= group_size && n_reads * pack_factor <= BCOLS, + "A thread's values must lie in one row and quantization group"); + + const short thread_idx; + const short bi; + const short bj; + const device uint8_t* src; + const device T* scales; + const device T* biases; + uint32_t raw[n_words]; + T scale; + T bias; + + QuantizedBlockLoaderStaged( + const device uint8_t* src_, + const device T* scales_, + const device T* biases_, + const int src_ld, + ushort simd_group_id, + ushort simd_lane_id) thread + : thread_idx(simd_group_id * 32 + simd_lane_id), + bi(n_reads* thread_idx / BCOLS_PACKED), + bj((n_reads * thread_idx) % BCOLS_PACKED), + src(src_ + bi * src_ld * bytes_per_pack / pack_factor + + bj * bytes_per_pack), + scales(scales_ + bi * src_ld / group_size), + biases(biases_ + bi * src_ld / group_size) {} + + // k: first column of the step + void fetch(const int k) thread { + auto p = (const device uint32_t*)(src + k * bytes_per_pack / pack_factor); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_words; i++) { + raw[i] = p[i]; + } + const int g = (k + bj * pack_factor) / group_size; + scale = scales[g]; + bias = biases[g]; + } + + // Dequantize into registers, then write 8 values per store + void store(threadgroup T* dst) const thread { + constexpr short n_vals = n_reads * pack_factor; + static_assert(n_vals % 8 == 0, "8-value stores"); + T v[n_vals]; + // Unpack with shifts (constant indices keep it in registers) + uint8_t b[n_words * 4]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_words * 4; i++) { + b[i] = uint8_t(raw[i / 4] >> (8 * (i % 4))); + } + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_reads; i++) { + dequantize( + b + i * bytes_per_pack, scale, bias, v + i * pack_factor); + } + dst += bi * dst_ld + bj * pack_factor; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < n_vals; i += 8) { + *(threadgroup vec*)(dst + i) = *(thread vec*)(v + i); + } + } +}; + +// Each simdgroup computes SM rows and prefetches the next activation tile. +// Weights use two threadgroup buffers with one barrier between K steps. +template < + typename T, + int group_size, + int bits, + typename U = T, + int BM = 64, + int BK = 64, + int BN = 64, + int SM = 16> +METAL_FUNC void qmm_t_nax_staged_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 [[threadgroup_position_in_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + static_assert(BK == 64 && BN == 64, "64-column tiles"); + static_assert(SM > 0 && SM % 16 == 0 && BM % SM == 0, "Whole row fragments"); + static_assert( + sizeof(T) == 2, "Two tiles fit threadgroup memory for 16-bit T"); + + constexpr int pack_factor = get_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; + + using loader_w_t = QuantizedBlockLoaderStaged< + T, + BN, + BK, + BK_padded, + (BM / SM) * 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); + + // This simdgroup's rows and the two rows each thread holds in a fragment + const int tile_rows = min(BM, M - y_row); + constexpr int TM = SM / 16; + const int sm = SM * int(simd_gid); + const int rows = min(SM, tile_rows - sm); + const short2 sc = BaseNAXFrag::get_coord(); + const device T* x0[TM]; + const device T* x1[TM]; + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + const int r0 = min(sm + m * 16 + int(sc.y), tile_rows - 1); + const int r1 = min(sm + m * 16 + int(sc.y) + 8, tile_rows - 1); + x0[m] = x + (y_row + r0) * static_cast(K) + sc.x; + x1[m] = x + (y_row + r1) * static_cast(K) + sc.x; + } + + NAXTile Dtile; + Dtile.clear(); + vec a_cur[BK / 16][TM][2]; + vec a_next[BK / 16][TM][2]; + + loader_w.fetch(0); + loader_w.store(Ws); + if (rows > 0) { + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + a_cur[s][m][0] = *(const device vec*)(x0[m] + s * 16); + a_cur[s][m][1] = *(const device vec*)(x1[m] + s * 16); + } + } + } + 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); + } + if (rows > 0) { + const int kn = more ? k + BK : k; + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + a_next[s][m][0] = *(const device vec*)(x0[m] + kn + s * 16); + a_next[s][m][1] = *(const device vec*)(x1[m] + kn + s * 16); + } + } + const threadgroup T* ws = + Ws + (it & 1) * tile_size + sc.y * BK_padded + sc.x; + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < BN / 16; j += 2) { + const threadgroup T* p0 = ws + (j * 16) * BK_padded + s * 16; + 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]; + } + } + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + frag_t a; + STEEL_PRAGMA_UNROLL + for (short c = 0; c < 4; c++) { + a[c] = a_cur[s][m][0][c]; + a[4 + c] = a_cur[s][m][1][c]; + } + BaseNAXFrag::mma( + Dtile.frag_at(m, j), + Dtile.frag_at(m, j + 1), + a, + metal::bool_constant{}, + b0, + b1, + metal::bool_constant{}); + } + } + } + STEEL_PRAGMA_UNROLL + for (short s = 0; s < BK / 16; s++) { + STEEL_PRAGMA_UNROLL + for (short m = 0; m < TM; m++) { + a_cur[s][m][0] = a_next[s][m][0]; + a_cur[s][m][1] = a_next[s][m][1]; + } + } + } + if (more) { + loader_w.store(Ws + ((it + 1) & 1) * tile_size); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + if (rows <= 0) { + return; + } + y += (y_row + sm) * static_cast(N) + y_col; + if (rows == SM) { + Dtile.store(y, N); + } else { + Dtile.store_safe(y, N, short2(BN, rows)); + } +} + +template < + typename T, + int group_size, + int bits, + bool aligned_N, + typename U = T, + int BM = 64, + int BK = 64, + int BN = 64, + int WM = 2, + int WN = 2> METAL_FUNC void qmm_t_nax_tgp_impl( const device uint32_t* w, const device T* scales, const device T* biases, const device T* x, - device T* y, + device U* y, threadgroup T* Ws, const constant int& K, const constant int& N, const constant int& M, + const int k_end, uint3 tid [[threadgroup_position_in_grid]], uint lid [[thread_index_in_threadgroup]], uint simd_gid [[simdgroup_index_in_threadgroup]], @@ -1112,7 +1381,7 @@ METAL_FUNC void qmm_t_nax_tgp_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) { + for (int k = 0; k < k_end; k += BK) { threadgroup_barrier(mem_flags::mem_threadgroup); if constexpr (kAlignedN.value) { loader_w.load_unsafe(); @@ -1330,7 +1599,8 @@ template < constexpr int BK_padded = (BK + 16 / sizeof(T)); - threadgroup T Ws[BN * BK_padded]; + // WN == 1 selects the staged impl + threadgroup T Ws[(WN == 1 ? 2 : 1) * BN * BK_padded]; if (batched) { adjust_matrix_offsets( @@ -1350,8 +1620,98 @@ template < b_strides, tid); } - qmm_t_nax_tgp_impl( - w, scales, biases, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + if constexpr (WN == 1) { + static_assert(aligned_N, "Aligned output columns"); + qmm_t_nax_staged_impl( + w, scales, biases, x, y, Ws, K, N, M, K, tid, simd_gid, simd_lid); + } else { + qmm_t_nax_tgp_impl( + w, scales, biases, x, y, Ws, K, N, M, K, tid, lid, simd_gid, simd_lid); + } +} + +template < + typename T, + int group_size, + int bits, + bool aligned_N, + int BM = 64, + int BK = 64, + int BN = 64, + int WM = 2, + int WN = 2> +[[kernel]] void affine_qmm_t_nax_splitk( + const device uint32_t* w [[buffer(0)]], + const device T* scales [[buffer(1)]], + const device T* biases [[buffer(2)]], + const device T* x [[buffer(3)]], + device float* y [[buffer(4)]], + const constant int& K [[buffer(5)]], + const constant int& N [[buffer(6)]], + const constant int& M [[buffer(7)]], + const constant int& k_partition_size [[buffer(8)]], + const constant int& split_k_partition_stride [[buffer(9)]], + uint3 tid [[threadgroup_position_in_grid]], + uint lid [[thread_index_in_threadgroup]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int BK_padded = (BK + 16 / sizeof(T)); + constexpr int pack_factor = get_pack_factor(); + constexpr int bytes_per_pack = get_bytes_per_pack(); + + threadgroup T Ws[(WN == 1 ? 2 : 1) * BN * BK_padded]; + + const int k_start = tid.z * k_partition_size; + x += k_start; + auto wl = (const device uint8_t*)w; + wl += k_start * bytes_per_pack / pack_factor; + scales += k_start / group_size; + biases += k_start / group_size; + y += tid.z * static_cast(split_k_partition_stride); + + if constexpr (WN == 1) { + static_assert(aligned_N, "Aligned output columns"); + qmm_t_nax_staged_impl( + (const device uint32_t*)wl, + scales, + biases, + x, + y, + Ws, + K, + N, + M, + k_partition_size, + tid, + simd_gid, + simd_lid); + } else { + qmm_t_nax_tgp_impl< + T, + group_size, + bits, + aligned_N, + float, + BM, + BK, + BN, + WM, + WN>( + (const device uint32_t*)wl, + scales, + biases, + x, + y, + Ws, + K, + N, + M, + k_partition_size, + tid, + lid, + simd_gid, + simd_lid); + } } template < @@ -1480,8 +1840,8 @@ template < s_strides, b_strides, tid); - qmm_t_nax_tgp_impl( - w, scales, biases, x, y, Ws, K, N, M, tid, lid, simd_gid, simd_lid); + qmm_t_nax_tgp_impl( + w, scales, biases, x, y, Ws, K, N, M, K, tid, lid, simd_gid, simd_lid); } template < diff --git a/mlx/backend/metal/kernels/quantized_nax.metal b/mlx/backend/metal/kernels/quantized_nax.metal index 4d61232ea7..f627298740 100644 --- a/mlx/backend/metal/kernels/quantized_nax.metal +++ b/mlx/backend/metal/kernels/quantized_nax.metal @@ -91,10 +91,23 @@ instantiate_quantized_all_aligned(type, group_size, bits) \ instantiate_quantized_all_rhs(type, group_size, bits) +#define instantiate_quantized_splitk(group_size, bits) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, float, group_size, bits, 32, 64, 64, 2, 2, true) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, float, group_size, bits, 64, 64, 64, 2, 2, true) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, float16_t, group_size, bits, 64, 64, 64, 4, 1, true) \ + instantiate_quantized_aligned(affine_qmm_t_nax_splitk, bfloat16_t, group_size, bits, 64, 64, 64, 4, 1, true) + +#define instantiate_quantized_staged(type, group_size, bits) \ + instantiate_quantized_aligned_batched(affine_qmm_t_nax, type, group_size, bits, 64, 64, 64, 4, 1, true, 1) \ + instantiate_quantized_aligned_batched(affine_qmm_t_nax, type, group_size, bits, 64, 64, 64, 4, 1, true, 0) + #define instantiate_quantized_types(group_size, bits) \ instantiate_quantized_funcs(float, group_size, bits) \ instantiate_quantized_funcs(float16_t, group_size, bits) \ - instantiate_quantized_funcs(bfloat16_t, group_size, bits) + instantiate_quantized_funcs(bfloat16_t, group_size, bits) \ + instantiate_quantized_splitk(group_size, bits) \ + instantiate_quantized_staged(float16_t, group_size, bits) \ + instantiate_quantized_staged(bfloat16_t, group_size, bits) #define instantiate_quantized_groups(bits) \ instantiate_quantized_types(128, bits) \ diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index 052dd761c4..77ad347d90 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -829,6 +829,15 @@ void qvm( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); } +bool use_qmm_t_nax_staged( + const array& x, + bool transpose, + bool aligned_n, + const std::string& mode) { + return transpose && aligned_n && (mode == "affine") && + (x.dtype() == float16 || x.dtype() == bfloat16) && (x.offset() % 8 == 0); +} + void qmm_nax( const array& x, const array& w, @@ -849,17 +858,24 @@ void qmm_nax( int wm = 2; int wn = 2; + MTL::Size group_dims(32, wn, wm); // Use smaller bm when one block covers all of M. Only qmm_t_nax has a 32-row // instantiation. int bm = (transpose && M <= 32) ? 32 : 64; int bn = 64; int bk = 64; - MTL::Size group_dims(32, wn, wm); - MTL::Size grid_dims((N + bn - 1) / bn, (M + bm - 1) / bm, B); + + bool aligned_n = (N % 64 == 0); + if (use_qmm_t_nax_staged(x, transpose, aligned_n, mode)) { + wm = 4; + wn = 1; + bm = 64; + // A flat threadgroup runs the 16-row schedule faster than (32, 1, wm). + group_dims = MTL::Size(32 * wm, 1, 1); + } std::string kname; kname.reserve(64); - bool aligned = N % 64 == 0; bool batched = B > 1; std::string type_string = get_type_string(x.dtype()); concatenate( @@ -880,7 +896,7 @@ void qmm_nax( wm, "_wn", wn, - transpose ? (aligned ? "_alN_true" : "_alN_false") : "", + transpose ? (aligned_n ? "_alN_true" : "_alN_false") : "", batched ? "_batch_1" : "_batch_0", global_scale ? "_hgs" : ""); std::string template_def; @@ -894,7 +910,7 @@ void qmm_nax( type_string, group_size, bits, - aligned, + aligned_n, batched, bm, bk, @@ -939,7 +955,8 @@ void qmm_nax( compute_encoder.set_bytes(M, c++); add_strides_and_shapes(compute_encoder, B <= 1, x, w, scales, biases, c); - compute_encoder.dispatch_threadgroups(grid_dims, group_dims); + compute_encoder.dispatch_threadgroups( + MTL::Size(ceildiv(N, bn), ceildiv(M, bm), B), group_dims); } void gather_qmm_nax( @@ -1163,6 +1180,170 @@ void qmm( compute_encoder.dispatch_threadgroups(grid_dims, group_dims); } +bool use_qmm_nax_splitk( + const array& x, + const std::string& mode, + int M, + int N, + int K, + int group_size) { + // Use split-k for transposed affine weights with aligned N and K. + if (!metal::is_nax_available() || + (x.dtype() == float32 && !env::enable_tf32() || (mode != "affine") || + (N % 64 != 0) || (K % 64 != 0) || (K % group_size != 0))) { + return false; + } + // A two-way K split must fit within 256 threadgroups. + int bm = (M <= 32) ? 32 : 64; + int tiles = (N / 64) * ceildiv(M, bm); + return (tiles * 2 <= 256) && (K % (2 * std::max(64, group_size)) == 0); +} + +// K partitions for the NAX split-K launch over 64 x 64 output tiles. +int qmm_nax_k_partitions(int M, int N, int K, int group_size) { + int tiles = (N / 64) * ceildiv(M, 64); + int k_align = std::max(64, group_size); + int split_k = 1; + // Double up to 4 while the grid stays within 256 threadgroups and every + // partition keeps at least 256 columns. + while ((split_k < 4) && (tiles * split_k * 2 <= 256) && + (K % (split_k * 2 * k_align) == 0) && (K / (split_k * 2) >= 256)) { + split_k *= 2; + } + return split_k; +} + +void qmm_splitk_nax( + const array& x, + const array& w, + const array& scales, + const std::optional& biases, + array& out, + int group_size, + int bits, + int M, + int N, + int K, + metal::Device& d, + const Stream& s, + const std::string& mode) { + // The staged kernel needs an 8-byte aligned activation offset. + auto& compute_encoder = metal::get_command_encoder(s); + if ((x.dtype() != float32) && (x.offset() % 8 != 0)) { + array x_copy = contiguous_copy_gpu(x, s); + compute_encoder.add_temporary(x_copy); + return qmm_splitk_nax( + x_copy, w, scales, biases, out, group_size, bits, M, N, K, d, s, mode); + } + + int bm = (M <= 32) ? 32 : 64; + int bn = 64; + int bk = 64; + int wm = 2; + int wn = 2; + MTL::Size group_dims(32, wn, wm); + + if (use_qmm_t_nax_staged(x, true, true, mode)) { + bm = 64; + wm = 4; + wn = 1; + // A flat threadgroup runs the 16-row schedule faster than (32, 1, wm). + group_dims = MTL::Size(32 * wm, 1, 1); + } + + int split_k = qmm_nax_k_partitions(M, N, K, group_size); + if (split_k == 1) { + return qmm_nax( + x, + w, + scales, + biases, + std::nullopt, + out, + true, + group_size, + bits, + M, + N, + K, + d, + s, + mode); + } + + int k_partition_size = K / split_k; + int split_k_partition_stride = M * N; + + array intermediate({split_k, M, N}, float32, nullptr, {}); + intermediate.set_data(allocator::malloc(intermediate.nbytes())); + compute_encoder.add_temporary(intermediate); + + std::string type_string = get_type_string(x.dtype()); + std::string kname; + kname.reserve(64); + concatenate( + kname, + mode + "_qmm_t_nax_splitk_", + type_string, + "_gs_", + group_size, + "_b_", + bits, + "_bm", + bm, + "_bn", + bn, + "_bk", + bk, + "_wm", + wm, + "_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); + compute_encoder.set_compute_pipeline_state(kernel); + + int c = 0; + compute_encoder.set_input_array(w, c++); + compute_encoder.set_input_array(scales, c++); + compute_encoder.set_input_array(*biases, c++); + compute_encoder.set_input_array(x, c++); + compute_encoder.set_output_array(intermediate, c++); + compute_encoder.set_bytes(K, c++); + compute_encoder.set_bytes(N, c++); + compute_encoder.set_bytes(M, c++); + compute_encoder.set_bytes(k_partition_size, c++); + compute_encoder.set_bytes(split_k_partition_stride, c++); + compute_encoder.dispatch_threadgroups( + MTL::Size(N / bn, ceildiv(M, bm), split_k), group_dims); + + // Sum the partitions and cast to the output type. + auto accum_kname = "steel_gemm_splitk_accum_" + type_to_name(out) + "_" + + type_to_name(intermediate); + auto accum_kernel = get_steel_gemm_splitk_accum_kernel( + d, accum_kname, intermediate, out, false); + compute_encoder.set_compute_pipeline_state(accum_kernel); + compute_encoder.set_input_array(intermediate, 0); + compute_encoder.set_output_array(out, 1); + compute_encoder.set_bytes(split_k, 2); + compute_encoder.set_bytes(split_k_partition_stride, 3); + compute_encoder.set_bytes(N, 4); + compute_encoder.dispatch_threads(MTL::Size(N, M, 1), get_block_dims(N, M, 1)); +} + void qmm_splitk( const array& x, const array& w, @@ -1177,6 +1358,12 @@ void qmm_splitk( metal::Device& d, const Stream& s, const std::string& mode) { + // The split-K NAX route. + if (biases && use_qmm_nax_splitk(x, mode, M, N, K, group_size)) { + return qmm_splitk_nax( + x, w, scales, biases, out, group_size, bits, M, N, K, d, s, mode); + } + // Choose split_k to target ~512 threadgroups int bm = 32, bn = 32; int n_tiles = (N + bn - 1) / bn; @@ -1905,6 +2092,16 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { int vector_limit = transpose_ ? get_qmv_batch_limit(K, N, d) : 4; auto mode = quantization_mode_to_string(mode_); + // On NAX devices the NAX qmm (splitting K where that helps) also beats + // qmv / qmv_wide from 8 rows, when the output is wide enough to fill its + // tiles and narrow enough that a two-way K split fits in 256 threadgroups. + if (transpose_ && (M >= 8) && (M < vector_limit) && (M * N >= 16384) && + (out.size() == size_t(M) * N) && (inputs.size() == 4) && + use_qmm_nax_splitk(x, mode, M, N, K, group_size_)) { + qmm_splitk_nax( + x, w, scales, biases, out, group_size_, bits_, M, N, K, d, s, mode); + return; + } // It is a matrix matrix product. if (M >= vector_limit) { // Use split-K qmm for small M with transposed weights (non-batched only) diff --git a/python/tests/test_quantized.py b/python/tests/test_quantized.py index 3c1bf0bbf8..ac7c461672 100644 --- a/python/tests/test_quantized.py +++ b/python/tests/test_quantized.py @@ -685,6 +685,71 @@ def test_qmm_splitk_precision(self): rounding = (y_ref.astype(dtype).astype(mx.float32) - y_ref).abs().mean() self.assertLess(error.item(), 1.1 * rounding.item()) + @unittest.skipIf(not mx.metal.is_available(), "requires Metal") + def test_qmm_mid_m(self): + # Mid-size M with narrow outputs, where a single batch routes to the + # split-K and vector kernels: every split count, both row tilings and + # the boundaries between the routes. + if mx.default_device() == mx.cpu: + self.skipTest("Covers GPU kernels only") + shapes = [ + (256, 4096), + (1024, 6144), + (2560, 1024), + (4096, 2048), + ] + for (K, N), M, bits, group_size, dtype in product( + shapes, + [8, 31, 33, 130], + [2, 3, 4, 6, 8], + [32, 64, 128], + [mx.bfloat16, mx.float16, mx.float32], + ): + if K % group_size != 0: + continue + with self.subTest( + K=K, N=N, M=M, bits=bits, group_size=group_size, dtype=dtype + ): + k1, k2 = mx.random.split(mx.random.key(M * K + N)) + x = mx.random.normal((M, K), key=k1).astype(dtype) + w = (0.02 * mx.random.normal((N, K), key=k2)).astype(dtype) + wq = mx.quantize(w, group_size=group_size, bits=bits) + w_hat = mx.dequantize(*wq, group_size=group_size, bits=bits) + y_ref = x.astype(mx.float32) @ w_hat.astype(mx.float32).T + y = mx.quantized_matmul( + x, *wq, transpose=True, group_size=group_size, bits=bits + ) + self.assertEqual(y.shape, (M, N)) + error = (y.astype(mx.float32) - y_ref).abs().mean() + if dtype == mx.float32: + rounding = mx.array(1) + else: + rounding = ( + (y_ref.astype(dtype).astype(mx.float32) - y_ref).abs().mean() + ) + # The split-K and NAX routes round once. The vector kernels + # (below 16384 outputs, or when K does not split in two) reach + # ~1.6x the output rounding. + splits = K % (2 * max(64, group_size)) == 0 + tol = 1.1 if M * N >= 16384 and splits else 2.0 + if error.item() >= tol * rounding.item(): + # Vector kernels can dequantize weights in float32. + qw, scales, biases = wq + w_hat = mx.dequantize( + qw, + scales.astype(mx.float32), + biases.astype(mx.float32), + group_size=group_size, + bits=bits, + ) + y_ref = mx.matmul(x.astype(mx.float32), w_hat.T, stream=mx.cpu) + error = (y.astype(mx.float32) - y_ref).abs().mean() + rounding = ( + (y_ref.astype(dtype).astype(mx.float32) - y_ref).abs().mean() + ) + tol = 1.1 + self.assertLess(error.item(), tol * rounding.item()) + def test_qmm_vjp(self): key = mx.random.key(0) k1, k2 = mx.random.split(key)