Skip to content

perf(cuda): run one-row MoE gathers on gather_qmv, not qmm_naive - #3732

Open
Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:perf/2784-cuda-moe-gather-once
Open

Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:perf/2784-cuda-moe-gather-once

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

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_gpu ran an affine gather_qmm whose 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-pair gather_qmv below 8 pairs, and from 8 pairs on on qmm_sm80 where it applies and on qmm_naive everywhere else. qmm_naive spends a whole GEMM tile on each one-row pair. Those qmm_naive gathers now run gather_qmv, the kernel the same gather already took below 8 pairs.

  • Dispatch (quantized.cpp overlay, GatherQMM::eval_gpu): in the qmm_naive branch, affine and M == 1 and supports_qmv now also call call_qmv(). It applies from 8 pairs on (below 8 prefer_qmv already held) where qmm_sm80 does 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_sm80 keeps its gathers, the sorted grouped-GEMM prefill (perf(cuda/moe): fix MoE prefill collapse on CUDA (gather_qmm / grouped GEMM path) #629, from 8 * E sorted pairs) is checked first and is unchanged, and the fp modes keep fp_gather_qmv / the sorted sm80 gather. Metal's GatherQMM already sends one-row gathers to gather_qmv unless M == 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 to gather_qmm_rhs; N and K alignment there only picks that kernel's variant, not the path.
  • Numerics. Each pair now gets the bits it gets when gathered alone (a single-pair gather runs gather_qmv). Against qmm_naive the rounding moves; see the logit traces below.
  • Kill switch. MLXCEL_GATHER_QMM_ONE_ROW_QMV=0 restores qmm_naive; documented in docs/environment-variables.md.
  • No upper bound on pair count. Kernel timings from 8 to 16384 pairs (below) found no shape of a supported model where qmm_naive was faster.
  • Record. docs/benchmark_results/moe-gather-one-row-qmv-gb10-2026-12-03.md with its drivers bench_moe.py and ttft.py, indexed in docs/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_qmv variant 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 took qmm_naive. Measured against main and against a third arm that sent exactly the same gathers to the per-pair gather_qmv (same host and protocol as below, base 9402cf893, n = 3):

Clients main (6 runs) grouped, read each expert once per-pair gather_qmv (this PR's change)
1 74.62 74.49 (-0.2%) 74.73 (+0.1%)
4 87.85 100.89 (+14.9%) 110.69 (+26.0%)
8 155.75 159.55 (+2.4%) 163.47 (+5.0%)

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

  1. Boundaries. Tests cover 1, 2 and 7 pairs (below 8, gather_qmv as before, single-pair bits) at a qmm_naive and a qmm_sm80 shape; from 8 pairs: 8 pairs of one expert (the smallest gather that took qmm_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 the 8 * E grouped-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); the qmm_sm80 shape from 8 pairs on is bounded by a dequantized reference. Empty inputs return before the dispatch as before.
  2. Large inputs. Both kernels read every pair's expert once per pair, so the work is O(pairs * N * K) either way; call_qmv goes through run_batch_chunked, so grid z stays at most 65535. The probe below runs up to 16384 pairs.
  3. Other callers. Every CUDA one-row affine gather_qmm passes the new condition, and it changes only gathers that ran qmm_naive. MoE expert stacks whose projections take qmm_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 ran qmm_naive), measured on Qwen3-30B-A3B-3bit below; the 6-bit down of a mixed 4/6-bit stack in batched decode (not measured); and qwen4_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 ran qmm_naive and now runs gather_qmv (8 to 16x faster for N = 1 in the probe, 1.5 to 8x for N = 32 / 64). In gather_qmv each row's result depends only on its own input row and the weights (a warp computes one output element of pair l from x[lhs[l]] and w[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-warp qmv, it is also the same qmv_kernel_impl instance as the one-row decode linear.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 unmodified 9402cf893 (three runs), so at that shape it does not separate the two kernels. No Qwen4-Exp checkpoint was run. ROCm and Metal have their own GatherQMM and 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).
  4. CHANGELOG under ## [Unreleased] / Performance.
  5. Comments. No existing explanatory comment was removed; the overlay header lists the change as item (6).
  6. fmt. 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. Checkpoints mlx-community/gemma-4-26b-a4b-it-4bit at 0d77464eeb233a2da68ebf9d7dc4edaac7db956d and mlx-community/Qwen3-30B-A3B-3bit at 6add5f3b9ef4219603698b4b996e20a6da6d8793.

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:

Clients main 9402cf893 this PR Change
1 73.12 (73.06 to 73.27) 73.06 (72.97 to 73.09) -0.1%
4 90.20 (89.80 to 90.39) 110.98 (110.56 to 111.12) +23.0%
8 155.12 (154.66 to 156.98) 167.04 (166.89 to 167.21) +7.7%

The two main arms differ by 0.12 to 0.32% in median. The one-client text differs from main's in every round (176c7e8499c4 against 6f1cbc7620f7): 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_naive on main from 8 pairs; the fused decode-MoE kernel declines 3-bit, so one client gathers 8 pairs per projection):

Clients main 9402cf893 this PR Change
1 69.88 (65.35 to 72.73) 92.01 (90.82 to 92.42) +31.7%
4 111.72 (110.86 to 112.34) 142.62 (142.28 to 143.17) +27.7%
8 124.02 (121.69 to 124.86) 146.13 (144.56 to 146.20) +17.8%

The two main arms differ by 0.26 to 0.73% in median.

Short-prompt prefill, Gemma 4 26B

Raw /v1/completions prompts of exactly L tokens, max_tokens 1 (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:

Prompt tokens main (6) this PR (3) Change
8 66.04 60.05 -9.1%
16 84.62 76.26 -9.9%
32 118.95 109.98 -7.5%
64 185.74 174.39 -6.1%
96 253.03 238.97 -5.6%
127 319.96 302.56 -5.4%
128 697.08 697.19 0.0%
256 758.35 758.35 0.0%

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_qmm per 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. Ratio gather_qmv / qmm_naive (below 1 is faster):

Stack (E = 128, top 8) N K bits 8 32 64 sorted 256 sorted 1016 sorted 1016 4096 16384
Gemma 4 gate/up 704 2816 4 0.78 0.69 0.66 0.89 0.90 0.59 0.57 0.56
Gemma 4 gate/up 704 2816 8 0.46 0.80 0.89 0.88 0.75 0.83 0.83 0.83
Qwen3-30B-A3B-like gate/up 768 2048 3 0.73 0.81 0.74 0.85 0.89 0.70 0.65 0.64
Qwen3-30B-A3B-like down 2048 768 3 1.43 1.17 0.93 0.95 1.07 0.89 0.87 0.88
Qwen3-30B-A3B-like gate/up 768 2048 6 0.62 0.73 0.75 0.74 0.57 0.71 0.69 0.68
Qwen3-30B-A3B-like down 2048 768 6 0.85 0.73 0.78 0.90 0.77 0.69 0.67 0.66
synthetic 704 704 4 0.89 1.15 0.83 0.98 1.23 1.06 1.01 1.05

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_qmv was 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 off qmm_sm80). Nothing grows worse with the pair count, so the dispatch has no upper bound.

Logit traces

examples/logit_trace over tests/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's qmm_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" is MLXCEL_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:

Comparison 64-token chunks 16-token chunks
on vs off, prefill 7.8% / 0 of 91 8.2% / 0 of 67
on vs off, 1 row 8.2% / 0 of 92 8.6% / 0 of 66
on vs off, 4 rows 6.6% / 0 of 91 7.8% / 0 of 67
main: prefill vs 1 row 6.6% / 0 of 91 7.8% / 0 of 67
main: 1 row vs 4 rows 4.7% / 0 of 92 2.0% / 0 of 66

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_naive about 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:

Against the 1-row trace 64-token chunks, off (main's path) 64-token chunks, on (this PR) 16-token chunks, off 16-token chunks, on
prefill 23.4% / 6 of 115 (5.2%) 24.2% / 5 of 115 (4.3%) 27.0% / 8 of 96 (8.3%) 27.3% / 7 of 96 (7.3%)
4 rows 20.7% / 4 of 115 (3.5%) 21.1% / 6 of 115 (5.2%) 28.5% / 7 of 96 (7.3%) 25.4% / 4 of 96 (4.2%)
8 rows 21.5% / 6 of 115 (5.2%) 23.4% / 5 of 115 (4.3%) 23.8% / 5 of 96 (5.2%) 24.2% / 5 of 96 (5.2%)

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_qmv bits 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.

  • New tests (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.
    • On unmodified 9402cf893 with only this file and its mod line 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 took qmm_naive), the second passes.
    • With this change both pass; with MLXCEL_GATHER_QMM_ONE_ROW_QMV=0 the 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 other scripts/ci/check_*.py and *_test.sh, scripts/insert_apache_header.py --check and fmt: 35 of 37 pass. check_helm_chart.py and helm_chart_package_test.sh fail because helm is not installed in the test environment (FileNotFoundError: 'helm'), unrelated to this change.
  • make verify-test-cuda (private 0700 TMPDIR): 18,893 passed, 2 failed, 578 ignored. The two failures, mlx_test_guard_coverage::mlx_evaluating_lib_tests_take_mlx_test_guard (flags src/vision/encoders/nemotron_h_nano_omni_tests.rs pos_embed_resample_runs_in_f32) and step3p7_parity::text_decode_delegates_sequence_local_native_batching (assertion failed: !wrapper.supports_padded_prefill()), fail the same way on unmodified 9402cf893 (same messages; both are stale tests unrelated to this change).
  • git merge-tree --write-tree origin/main HEAD: clean against 9402cf893, the latest origin/main checked.

Limits

  • Two checkpoints on one host (GB10). The kernel timings cover other shapes and bit widths on synthetic stacks only; no 6-bit or mixed-precision MoE checkpoint and no Qwen4-Exp checkpoint was run.
  • Devices below sm_80, where every one-row gather of 8 or more pairs ran 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.
  • On the 3-bit Qwen3-like down shape (N = 2048, K = 768) at 8 and 32 unsorted pairs the kernel timing favours qmm_naive; the end-to-end decode of that checkpoint is faster at 1, 4 and 8 clients.
  • The Gemma 4 logit traces run an instruct checkpoint on raw wikitext, where main already disagrees with itself on a fifth of all positions; they place the change at main's distance from a common reference rather than bounding it tightly (see above).

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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(cuda): MoE batched decode reads top_k * B expert matrices per gather

1 participant