Repository navigation
perf(cuda): run one-row MoE gathers on gather_qmv, not qmm_naive - #3732
Open
Jaeyeong-CHOI wants to merge 1 commit into
Open
Jaeyeong-CHOI wants to merge 1 commit into
Jaeyeong-CHOI wants to merge 1 commit into
Conversation
GatherQMM::eval_gpu ran an affine gather_qmm whose pairs each have one row (MoE decode and short prefill: [T, 1, 1, K] against [T, top_k] experts, or the same pairs sorted) on the per-pair gather_qmv below 8 pairs, and from 8 pairs on, wherever qmm_sm80 did not apply (expert N not a multiple of 128, 3/5/6-bit stacks, f32 activations, devices below sm_80), on qmm_naive, which spends a whole GEMM tile on every one-row pair. Those gathers now take gather_qmv, so each pair gets the bits it gets when gathered alone. qmm_sm80 and the sorted grouped-GEMM prefill (lablup#629) keep their gathers. MLXCEL_GATHER_QMM_ONE_ROW_QMV=0 restores qmm_naive. On GB10, Gemma 4 26B A4B 4-bit aggregate decode goes from 90.20 to 110.98 tok/s at 4 clients and from 155.12 to 167.04 at 8 (n = 3), one-client decode unchanged, and prompts of 8 to 127 tokens prefill 5.4% to 9.9% faster. Qwen3-30B-A3B 3-bit decodes 31.7% / 27.7% / 17.8% faster at 1 / 4 / 8 clients. A kernel that grouped the pairs by expert to read each selected expert once was built first and was slower than this per-pair launch at 4 and 8 clients. Closes lablup#2784
This branch has not been deployed
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.
Summary
Closes #2784.
On GB10, Gemma 4 26B A4B 4-bit aggregate decode goes from 90.20 to 110.98 tok/s (+23.0%) at 4 clients, the server's default slot count, and from 155.12 to 167.04 tok/s (+7.7%) at 8 clients; both are above the 5% the reopening comment set, with every run of the new binary above every run of main (n = 3). The one-client decode rate is unchanged (-0.1%), and prompts of 8 to 127 tokens prefill 5.4% to 9.9% faster. On Qwen3-30B-A3B 3-bit, where every expert projection was affected, decode is +31.7%, +27.7% and +17.8% at 1, 4 and 8 clients. The change is a few lines of dispatch: no new kernel. The issue's approach, a kernel that reads each selected expert once, was built and measured first and was slower than this (see below).
On CUDA,
GatherQMM::eval_gpuran an affinegather_qmmwhose pairs each have one row (MoE decode and short prefill:[T, 1, 1, K]against an[E, N, K]expert stack with[T, top_k]indices, or the same pairs flattened and sorted) on the per-pairgather_qmvbelow 8 pairs, and from 8 pairs on onqmm_sm80where it applies and onqmm_naiveeverywhere else.qmm_naivespends a whole GEMM tile on each one-row pair. Thoseqmm_naivegathers now rungather_qmv, the kernel the same gather already took below 8 pairs.quantized.cppoverlay,GatherQMM::eval_gpu): in theqmm_naivebranch, affine andM == 1andsupports_qmvnow also callcall_qmv(). It applies from 8 pairs on (below 8prefer_qmvalready held) whereqmm_sm80does not: expert N not a multiple of 128, bit widths other than 4 and 8, f32 activations, devices below sm_80. Nothing else moves:qmm_sm80keeps its gathers, the sorted grouped-GEMM prefill (perf(cuda/moe): fix MoE prefill collapse on CUDA (gather_qmm / grouped GEMM path) #629, from8 * Esorted pairs) is checked first and is unchanged, and the fp modes keepfp_gather_qmv/ the sorted sm80 gather. Metal'sGatherQMMalready sends one-row gathers togather_qmvunlessM == 1 && B >= 16 && right_sorted && B / E >= 4(sorted, at least 16 pairs, and at least four pairs per expert of the whole stack on average), which goes togather_qmm_rhs; N and K alignment there only picks that kernel's variant, not the path.gather_qmv). Againstqmm_naivethe rounding moves; see the logit traces below.MLXCEL_GATHER_QMM_ONE_ROW_QMV=0restoresqmm_naive; documented indocs/environment-variables.md.qmm_naivewas faster.docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03.mdwith its driversbench_moe.pyandttft.py, indexed indocs/benchmark_results/README.md; CHANGELOG under[Unreleased].Why not the issue's grouped kernel
The issue proposed reading each selected expert once per gather by grouping pairs by expert. That was built first: a
gather_qmvvariant whose blocks found the other pairs of their expert with warp ballots and applied each dequantized tile to up to eight of them, used for the one-row gathers of 8 to 256 pairs that tookqmm_naive. Measured against main and against a third arm that sent exactly the same gathers to the per-pairgather_qmv(same host and protocol as below, base9402cf893, n = 3):gather_qmv(this PR's change)Both arms produced the same text (the grouped kernel gave every pair the per-pair bits), and the per-pair arm was faster at 4 and 8 clients: all of the gain was leaving
qmm_naive, and grouping cost more than the reads it saved. In #2796's terms the saved reads were never worth much: with these prompts a MoE layer selects 27 distinct experts of 32 pairs at 4 clients (45 of 64 at 8; #2796 found 28 and 45 on the N1X), so at most 15.6% of the 4-client gate/up reads could go, about 5 to 6% of a step. So this PR is the dispatch change alone, with no new kernel.Maintainer checklist
gather_qmvas before, single-pair bits) at aqmm_naiveand aqmm_sm80shape; from 8 pairs: 8 pairs of one expert (the smallest gather that tookqmm_naive), 9 and 20 of one expert, 16 all distinct, 32 and 64 overlapping (Gemma 4 at 4 and 8 clients, unsorted and sorted), 257 sorted, 511 sorted (one below the8 * Egrouped-GEMM floor of the 64-expert test stack), 512 unsorted, each pair compared byte for byte with the same pair gathered alone, and K = 704 (a residue after the 512-wide k-steps); theqmm_sm80shape from 8 pairs on is bounded by a dequantized reference. Empty inputs return before the dispatch as before.call_qmvgoes throughrun_batch_chunked, so grid z stays at most 65535. The probe below runs up to 16384 pairs.gather_qmmpasses the new condition, and it changes only gathers that ranqmm_naive. MoE expert stacks whose projections takeqmm_sm80(4 or 8 bits with N and K multiples of 128 and 64: for example Qwen3-30B-A3B-4bit at 768 / 2048, ERNIE-4.5-21B-A3B at 1536 / 2560, Kimi-VL-A3B at 1408 / 2048, DeepSeek-VL2-tiny at 896 / 1280, Mixtral, Llama 4) are unchanged. What changes: Gemma 4 26B gate/up (N = 704); every expert projection of a 3-, 5- or 6-bit stack (all of them ranqmm_naive), measured on Qwen3-30B-A3B-3bit below; the 6-bit down of a mixed 4/6-bit stack in batched decode (not measured); andqwen4_exp_linear::row_invariant_projection, which runs Qwen4-Exp's router-side projections (N = 1 shared-expert gate, GatedDeltaNet a/b gates) as one-row gathers of a one-expert stack during prefill. Its doc comment asks for "the singleton quantized matrix-vector kernel" per token; on CUDA from 8 tokens it ranqmm_naiveand now runsgather_qmv(8 to 16x faster for N = 1 in the probe, 1.5 to 8x for N = 32 / 64). Ingather_qmveach row's result depends only on its own input row and the weights (a warp computes one output element of pairlfromx[lhs[l]]andw[rhs[l]], with no branch on the pair count or on the other pairs), so batch independence holds; outside Volta, whose one-row decode takes the two-row-per-warpqmv, it is also the sameqmv_kernel_implinstance as the one-row decodelinear.forward. The existing contract test on this path,qwen4_exp::parity_tests::quantized_gate_prefill_matches_independent_decode_rows([2, 17, 256]bf16 input, N = 4, 8-bit: 34 one-row pairs, exact equality of every row against its own one-row decode), passes with this change (in the full test gate below) and also on unmodified9402cf893(three runs), so at that shape it does not separate the two kernels. No Qwen4-Exp checkpoint was run. ROCm and Metal have their ownGatherQMMand are untouched. On Gemma 4 one-token decode uses the fused GeGLU kernel and MTP verify runs per position (perf: Trace the two remaining speculative verify mismatches: Gemma 4 26B A4B MoE and token-only verify rounds #3418), so neither reaches it, but prefill of up to 127 tokens does (below).## [Unreleased]/ Performance.cargo fmt --all -- --check(see verification).Verification
GB10 (sm_121, 121 GiB unified memory), driver 580.178.04, CUDA 13.0.88, Ubuntu 24.04.5, rustc 1.97.1, base
9402cf893. Checkpointsmlx-community/gemma-4-26b-a4b-it-4bitat0d77464eeb233a2da68ebf9d7dc4edaac7db956dandmlx-community/Qwen3-30B-A3B-3bitat6add5f3b9ef4219603698b4b996e20a6da6d8793.Serving A/B, n = 3
One server per arm (
--parallel 8 --no-prompt-cache, decode graphs on), 1 / 4 / 8 concurrent streaming chat completions with eight different prompts, greedy,ignore_eos, 512 tokens; arms rotated main / new / main per round; before each cell the driver waited for a load average of at most 4 and a GPU at most 60 C (one Qwen3 cell started at load 4.7, which rose during the temperature wait); median SM clock 2080 to 2093 MHz in every cell; no other GPU process when a run started. Driver:docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/bench_moe.py. Medians with ranges, main 6 runs, new 3.Gemma 4 26B A4B 4-bit:
9402cf893The two main arms differ by 0.12 to 0.32% in median. The one-client text differs from main's in every round (
176c7e8499c4against6f1cbc7620f7): the one-sentence prompt plus chat template is prefilled through the changed gathers; one-token decode is the fused kernel either way.Qwen3-30B-A3B 3-bit (every expert projection 3-bit, so
qmm_naiveon main from 8 pairs; the fused decode-MoE kernel declines 3-bit, so one client gathers 8 pairs per projection):9402cf893The two main arms differ by 0.26 to 0.73% in median.
Short-prompt prefill, Gemma 4 26B
Raw
/v1/completionsprompts of exactly L tokens,max_tokens1 (prefill plus one token), one server per arm with the prompt cache off, seven timed requests per server after one discarded, arms rotated main / new / main over three rounds. Driver:docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03/ttft.py. Median of the per-server medians, ms:Every range separates up to 127 tokens; the main arms differ by at most 0.57%. From 128 tokens (1024 sorted pairs) the #629 grouped GEMM takes the gather on both binaries. Every length gave the same first token on both. (On both binaries a 128-token prompt takes 2.2 times as long as a 127-token one, at the #629 threshold; untouched here.)
Kernel timings
A temporary probe (not committed) timed one
gather_qmmper pair count on synthetic expert stacks, unsorted and sorted (below the #629 floor), in one binary with the kill switch on and off, alternated twice. Ratiogather_qmv/qmm_naive(below 1 is faster):One-expert stacks with one row per pair (Qwen4-Exp's row-invariant projections, K = 4096, 4-bit): 0.06 to 0.13 at N = 1, 0.12 to 0.48 at N = 32, 0.16 to 0.65 at N = 64, from 8 to 8192 pairs. Calls are synchronous and small ones are noisy (two runs of one arm differ by up to 1.5x below about 0.3 ms). The two places
gather_qmvwas not faster are the 3-bit down at 8 and 32 pairs (slower in both runs, while gate and up at the same counts are faster by more; Qwen3-30B-A3B-3bit end to end is above) and a synthetic N = 704, K = 704 4-bit stack that scatters around 1.0 (no supported model is known to run that shape offqmm_sm80). Nothing grows worse with the pair count, so the dispatch has no upper bound.Logit traces
examples/logit_traceovertests/fixtures/wikitext2_excerpt.txt, top 8, 64-token chunks (4) and 16-token chunks (16), each arm traced with the change on and off (MLXCEL_GATHER_QMM_ONE_ROW_QMV=0, main'sqmm_naive) in one binary,scripts/compare_logit_traces.py. "Prefill" traces each chunk from a forward at the chunk's width (512 and 128 pairs, both through the changed gathers); "N rows" isMLXCEL_TRACE_BATCH_ROWS=N. Top-1 disagreement on all positions / on positions the reference had decided (top-two gap at least 2).Qwen3-30B-A3B 3-bit:
On Qwen3-30B-A3B 3-bit, where the excerpt scores a normal perplexity (74 to 75 and 232 to 240, every arm within 3.5% of the others in both directions), the change disagrees with
qmm_naiveabout as often as main's prefill and decode kernels disagree with each other, and never on a decided position.Gemma 4 26B A4B: the one-row traces are byte-identical on and off (one-token decode runs the fused GeGLU kernel and never reaches the changed gathers), so the one-row trace is a reference the change does not touch. Each arm against it:
Summed over the six cells, this PR's arm disagrees with the common reference on 32 of 633 decided positions (5.1%) and main's path on 36 of 633 (5.7%); this PR is closer in four cells, equal in one and farther in one (4 rows, 64-token chunks: 6 against 4). On all positions the two are 373 and 371 of 1536 (24.3% and 24.2%), and the largest logit move on the reference's choice is 8.0 to 13.0 against 6.4 to 13.4. The direct on-vs-off comparison is larger (prefill 9.2% and 12.2%, 4 rows 8.1% and 11.2%, 8 rows 3.6% and 10.8% of decided positions) because both of its arms changed the rounding, each in its own way, and two independent perturbations tend to sit farther from each other than either sits from the reference. The checkpoint is an instruct model on raw text: its perplexity is in the thousands (64-token chunks) and tens of thousands (16-token chunks) in every arm, and main disagrees with itself on 21 to 29% of all positions between batch sizes, so these traces cannot bound the change tightly; what they show is that it sits at main's own distance from the reference (closer in total). The unit tests below pin every changed gather to the single-pair
gather_qmvbits and to a dequantized reference.Tests and gate
On tree
c033db32f61e, which differs from the committed tree only in the Numerics section of the benchmark document; the release server built from it is byte-identical (sha256) to the binary measured above.src/lib/mlxcel-core/src/gather_qmm_one_row_tests.rs):one_row_gather_matches_each_pair_gathered_alone,below_eight_pairs_and_qmm_sm80_shapes_keep_their_kernels.9402cf893with only this file and itsmodline added: the first fails (eight pairs, one expert (N=704 K=2816): pair 0 (expert 5) differs from the same pair gathered alone, the smallest gather that tookqmm_naive), the second passes.MLXCEL_GATHER_QMM_ONE_ROW_QMV=0the first fails again with the same message.cargo test --workspace --profile test-fast --features cuda --lib -- --test-threads=1 gather_qmm_one_row_tests qmm_fold_batch_tests qmv_multirow fused_moe_parity cuda_graph_commit qmm_naive_tile: 28 passed, 0 failed.cargo fmt --all -- --check: clean.cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: pass.python3 scripts/ci/check_used_by.py(OK, 78 top-level pub fn, 57 annotated),bash scripts/ci/check_used_by_test.sh,check_env_var_docs.py(OK),check_cross_repo_refs.py, every otherscripts/ci/check_*.pyand*_test.sh,scripts/insert_apache_header.py --checkand fmt: 35 of 37 pass.check_helm_chart.pyandhelm_chart_package_test.shfail becausehelmis not installed in the test environment (FileNotFoundError: 'helm'), unrelated to this change.make verify-test-cuda(private0700TMPDIR): 18,893 passed, 2 failed, 578 ignored. The two failures,mlx_test_guard_coverage::mlx_evaluating_lib_tests_take_mlx_test_guard(flagssrc/vision/encoders/nemotron_h_nano_omni_tests.rspos_embed_resample_runs_in_f32) andstep3p7_parity::text_decode_delegates_sequence_local_native_batching(assertion failed: !wrapper.supports_padded_prefill()), fail the same way on unmodified9402cf893(same messages; both are stale tests unrelated to this change).git merge-tree --write-tree origin/main HEAD: clean against9402cf893, the latestorigin/mainchecked.Limits
qmm_naive, were not measured. The RTX Spark N1X of docs(cuda): record the MoE expert overlap and why no grouped kernel #2796 was not re-measured.qmm_naive; the end-to-end decode of that checkpoint is faster at 1, 4 and 8 clients.