Repository navigation
Port upstream affine qmv_mma for 3 to 16 rows on Metal (performance) - #64
Merged
Merged
Conversation
Co-authored-by: Cheng <git@zcbenz.com> osaurus-ai/mlx does not have the affine qmv_nax kernels (ml-explore#4781), so affine stays off this path on NAX GPUs. Affine qmv_mma also needs scales and biases of the input type: the fork's mixed bf16/f16 metadata path stays on qmv. The instantiations follow this fork's kernel names. (cherry picked from commit ba8c005)
osaurus-ai/mlx also keeps the fork's exact F32 q6 rows (exact_q6_f32_rows) on the single-row kernels, whose reduction order they depend on. (cherry picked from commit 6d38ff9)
osaurus-ai/mlx takes the non-NAX part only. The 4-bit affine_qmv_nax rows need ml-explore#4781. (cherry picked from commit 8f578df)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Branch
apple/r3-affine-qmv, 4 commits onorigin/main23f364e.This is a performance port, not a bug fix. It brings Apple's
affine_qmv_mmaMetal kernel, which multiplies 3 to 16rows by an affine-quantized matrix with simdgroup matrix instructions, and its routing, from ml-explore/mlx main:
ml-explore#4787 (older than round 3; the round's ml-explore#4860, ml-explore#4890 and ml-explore#4827 patch it), ml-explore#4860, ml-explore#4890 and ml-explore#4827. Each commit is a
git cherry-pick -xof the upstream commit, with the upstream author kept and the(cherry picked from commit …)linerecording provenance. The kernel template is Apple's unchanged; the kernel instantiations and the routing are ported
into this fork's
quantized.metalandquantized.cpp, which differ from Apple's. Each commit message notes where itdiffers from Apple's.
Why we push it: on
origin/main, affine quantized matmul with 3 to 16 rows runs the vector kernels. On an M4 Max thisbranch runs 4 to 16 rows up to 2.48 times as fast at LLM layer shapes, with no loss of accuracy (see Validation). The
port keeps the fork's own quantized paths (mixed bf16/f16 metadata, exact F32 q6 rows, 1-bit affine) on the kernels
they use today.
Included, in upstream order:
qmv,qmv_wide). Adds theaffine_qmv_mmakernel (4 and 8 bits) and routes affine to it from 3 rows (below GPU generation 15) or 4 rows (generation 15 and later) for large layers (N, K ≥ 512, N·K ≥ 2^21, N % 16 = 0; not on Ultras). Addstest_affine_qmm_few_rows. Here without the NAX branch, only for scales and biases of x's type, with instantiations in this fork's scheme.affine_qmv_mmaread only 4 and 8 bits. The kernel now reads 2 to 8 bits (not 7), the fork instantiates 2, 3, 5 and 6 bits too, and on generation 15 and later it takes layers from N·K ≥ 2^20. Here the fork's exact F32 q6 rows (exact_q6_f32_rows) stay on the single-row kernels.affine_qmv_mma(every Ultra kept the vector kernels); they now take it from 4 rows. M3 Ultra and later still keep the vector kernels.affine_qmv_mmafor large layers only (N, K ≥ 4096). Here without the 4-bit affineqmv_naxrows from 4 rows, which need ml-explore#4781.Not included here: ml-explore/mlx PR 4781 (affine
qmv_naxand the fp staged split-K) and every NAX branch of thesecommits: only an M5 can validate them. Without PR 4781,
use_qmv_mmareturns false for affine on NAX GPUs, so an M5keeps today's path. Apple's later NAX tuning of the fp rules is not taken either. The other round-3 commits are in
apple/r3-core,apple/r3-metal,apple/r3-metal-sdpa-vjp,apple/r3-cuda,apple/r3-python-docs-buildandapple/fixes-2. Also left out of the batch, by ml-explore/mlx PR number: 4887, 4883, 4903, 4801, 4734, 4647, and thewindow-size part of 4927.
Conflict resolutions
All four commits are ports:
origin/mainhas no affineqmv_mma, and itsuse_qmv_mmareturned false for affine.kernels/quantized.h): Apple's, unchanged in [Metal] Add affine qmv_mma for 3-16 rows ml-explore/mlx#4787 and [Metal] Add 2, 3, 5 and 6 bits to affine qmv_mma ml-explore/mlx#4860.kernels/quantized.metal), in this fork's scheme:affine_qmv_mma_<type>_gs_<gs>_b_<bits>_wk<wk>_bn<bn>_tm<tm>, tiles (wk, bn, tm) = (4, 16, 1), (4, 16, 2) and(4, 32, 1), bits 2, 3, 4, 5, 6 and 8, group sizes 32, 64 and 128,
float,float16_tandbfloat16_t: 162 kernels.use_qmv_mma(x, w, scales, biases, mode, group_size, bits, M, N, K, d): affine on NAX returns false; affine needsscales and biases of x's dtype (the fork's mixed bf16/f16 metadata path stays on
qmv);exact_q6_f32_rows()returns false (one predicate, now also used by the vector dispatch); then Apple's rule (minimum rows 3, or 4 on
generation 15 and later and on Ultras; bits 2 to 8 except 7; N·K ≥ 2^20 on generation 15 and later, else 2^21;
M3 Ultra and later only from 4096 × 4096). Bits ≥ 2 also keep 1-bit affine off this kernel. The fp rules are the
fork's, unchanged. The caller's
M >= 6is nowmin_rows(6 for fp).qmv_mma(): binds the biases when present (QuantizedMatmulhas 4 inputs only for affine; global scales gothrough
QQMatmul). wk and bn as Apple's: affine wk 4 everywhere without NAX; bn 32 below generation 15 when tm is 1and N % 32 = 0.
test_affine_qmm_few_rowsand the rename oftest_qmm_few_rowstotest_fp_qmm_few_rowsas Apple's.Overlaps
None with the batch's other branches (merge-tree). osaurus-ai has no competing work on this: the
qmv-multirow-experimentbranch (opt-inVMLX_QMV_MR) and the one-bit audit branch are unrelated.Validation
Compared with
main(23f364e), built and run the same way:Linux arm64 (container vmlx-arm64, clang Release, Highway), C++ suite on the CPU (no Metal: a build check).
macOS (M4 Max, Release, Metal on), C++ suite (
tests/tests) on the CPU and on Metal.Python (macOS, Python 3.14.5), on the GPU and with
DEVICE=cpu: the 16 test modules the batch touches, amongthem this branch's
test_quantized, onmainand on the integration tree 63ac1f9df (origin/mainwith all batchbranches merged, this one included).
Benchmark (M4 Max, quiet machine):
quantized_matmulwith transposed affine weights, bfloat16, group size 64,4 and 8 bits, M = 1 to 16, at 5 layer shapes (N × K: 4096 × 4096, 14336 × 4096, 4096 × 14336, 1024 × 4096,
2048 × 2048). Each cell evaluates 32 calls together, median of 7 rounds;
main23f364e against this branch at9caa7bb. Accuracy against
x @ dequantize(w).Tin float32.Linux: 412 of 412 cases pass, as
main.macOS: 390 of 390 cases pass on the CPU and on Metal, as
main.Python:
test_affine_qmm_few_rows(bits × group size × dtype × M = 3, 8, 9) passes on Metal. No test that passes onmainfails on the integration tree. GPU:mainfails 3 tests, the integration tree 1 (test_input_dilation_grad,as
main):test_qmm_mid_mandtest_qmm_splitk_precisionfail onmainand pass on the integration tree;apple/fixes-2alone fixes them (its owntest_quantizedrun). CPU: both fail the same 4 (GPU-only tests that donot skip on the CPU, and the Winograd budget). All new tests of the batch pass: 27 on the GPU, 85 on the CPU (the
rest skip).
main's CPU run stops attest_reduce:test_init_reduce_large_output(from ml-explore/mlx PR 4437)crashes it with SIGSEGV, the overflow that this batch's
fix/reduce-int64-loopsfixes. Sotest_reduce,test_threads,test_vmapandtest_zero_copyhave nomainCPU result; on the integration tree none of their tests fails onthe CPU.
Benchmark, speed of this branch over
main:mainaffine_qmv_mmaaffine_qmv_mmaaffine_qmv_mmaOver 5 shapes × 2 bit widths. For example, 4-bit 14336 × 4096 at M = 16: 287 µs to 148 µs; 4096 × 4096 at
M = 13: 109 µs to 48 µs. At M = 4 and 5 some cells are slightly slower (down to 0.93 times). Accuracy: no cell is worse than
main(largest error, 4-bit: 8.7e-3 against9.2e-3; 8-bit: 4.0e-3 against 9.2e-3). Timed one call per eval instead, an eval overhead of about 170 to 200 µs
hides most of the gain: 1.3 to 1.9 times, on the large layers only.
Not run: a check of the kernel each shape selects (beyond the timings); M1, M2, M3 and Ultra GPUs; NAX GPUs; a
model-level decode or prefill A/B.
Validation of the batch in
sharedThis batch's PRs but the last (
fix/float-floor-divide, which came out of this validation), merged together onmain23f364e with the two overlap resolutions (apple/fixes-2andapple/r3-coreinpython/tests/test_quantized.py;apple/r3-coreandapple/fixes-3inmlx/allocator.h), are mlx 8de1a51; vmlx-swift 31458a0d3 builds on it (osaurus-ai/vmlx-swiftmainbbd237750 with our open vmlx-swiftpatches). Built and run, compared with
main:its suite (
swift test --no-parallel, 1046 tests) fails no test that passes on itsmain.main412 of 412).vmlx-swift's Linux CI steps pass:
VMLXLinuxTests37 of 37, the CPU kernel tests 61 of 61 at both thread settings.DEVICE=cpu,python/testsmodule by module, torch 2.15 for the CPU). arm64:main881 pass, 92 skip, 2 fail;the batch 906 pass, 96 skip, 2 fail (tree c43a37eec, which differs from 8de1a51 only in a C++ test). amd64:
main882 pass, 92 skip, 1 fail; the batch 906 pass, 96 skip, 1 fail, 1 error. No test that passes on
mainfails on the batch. The failures aremain's own:test_compile_sigmoid_matches_eager(bfloat16: the compiled CPU sigmoid is less accurate than theeager Highway kernel) and, on arm64 only, bfloat16
test_torch_conv_2D, where torch 2.15's own aarch64 bfloat16conv2d is off by up to 8.8 against float64 (MLX is within 0.06).
test_async_eval_error_in_synchronizefailed once on amd64; it fails about 1 run in 5 there onmaintoo: the error it expects fromsynchronizecan come fromasync_eval(the same code is on ml-explore/mlx main).mainfail at random, on every branch alike, because they draw unseeded inputs or race:test_double.TestDouble.test_unary_opsin about 8% of runs (float32erfis accurate to 1.5e-7 absolute, whichmisses
rtol1e-5 near 0 against the fork's accurate float64erf);test_ops.TestOps.test_divmodin about 1%(the float16 quotient is off by one when
a / brounds up to an integer, e.g. 73.625 / 1.248 = 58.99 gives 59;ml-explore/mlx main has the same code); and, on amd64,
test_async_eval_error_in_synchronize(above). This batch'sfix/float-floor-dividefixes the second; the first gets a PR of its own.its Linux and macOS jobs.
test_compile_sigmoid_matches_eager,test_torch_conv_2Das onmain.🤖 Generated with Claude Code