Repository navigation
perf(qwen3_moe): batch the decode forward instead of per-row forwards - #1623
Merged
Merged
Conversation
`Qwen3MoeModel` (like every MoE family) never overrode `forward_batched`, so the server's batched decode ran the `LanguageModel` default: one single-sequence `forward` per row, evaluated together. Issue #1616 assumed the opposite, that B>=2 dropped the fused MoE kernel and fell back to `gather_qmm`. Measured on M1 Ultra with `MLXCEL_PROFILE_BLOCKS=1`, a B=4 tick was four serialized single-token graphs (518 block summaries for 128 ticks), each still launching the fused kernel, and those graphs overlap only about 30% on this GPU (tick 12.3 ms at B=1, 33.6 ms at B=4). An op-level profile of the real layer-0 expert planes showed per-token fused launches scale linearly (3.9, 7.5, 14.7, 29.2 ms per 48 layers at n=1/2/4/8), that identical and disjoint expert sets cost the same at every n (plane traffic is not the limiter, so cross-cohort dedup buys nothing), and that a batched prototype of the issue's proposed kernel (grid z of k * n_tokens, bit-identical to per-token launches) loses to `gather_qmm` from n=4 (11.1 vs 9.3 to 9.7 ms). The batched kernel was therefore not built; the profile is written up in `docs/benchmark_results/moe-batched-decode-m1ultra-2026-09-04.md` on the benchmark-refresh branch. What the profile did justify is a real batched forward, mirroring the Qwen3 dense port: `Attention::apply_rope_batched` and `Attention::forward_split_attention` apply Q/K RMSNorm and per-row RoPE while batched and run the KV-cache update and SDPA per sequence against dense caches; `DecoderLayer::forward_batched` runs the norms, fused QKV projection, output projection and the MoE block once over `[B, T, hidden]`, so from B=2 the experts take the multi-token `gather_qmm` chain; `Qwen3MoeModel::forward_batched_impl` batches the embedding, final norm and LM head, with `MLXCEL_PROFILE_BLOCKS` support tagged by batch size. The `LanguageModel` override keeps a one-row batch on the exact single-sequence graph (fused kernel included) and returns the trait default's empty logits for zero rows, so B=1 is untouched. The paged decode backend is not opted into, so the context is ignored. The `MLXCEL_PROFILE_QWEN3_MOE_DETAIL=1` hook always ran the gather path and never said which path it timed, so a single-token trace attributed a kernel the production step never launched; `SparseMoeBlock::forward_profiled` now follows the production dispatch and returns a `MoeProfile` with `path` and `tokens`, printed on the `[QWEN3_MOE_SPARSE]` line. `docs/CONTINUOUS_BATCHING.md` now names which families override `forward_batched` and what the default does for the rest. Validation on M1 Ultra (mlxcel 0.7.0-beta.1, MLX pin 9a795735, `bench_serving_concurrency.py --prompt-tokens 512 --max-tokens 128` against `--parallel 4 --max-batch-prefill 4`): `qwen3-30b-a3b-4bit` B=4 aggregate 93.3 to 103.7 tok/s (1.72x to 1.88x of this host's own B=1), per-request 29.8 to 34.2 tok/s; B=1 81.5 to 81.6 tok/s; dense rows unchanged (llama-3.1-8b 120.5 to 119.3, qwen2.5-0.5b 367.5 to 369.0, both inside the 0.3% run-to-run band). `mlxcel generate -m models/mlx/qwen3-30b-a3b-4bit -p Hello -n 128 --temp 0` is byte-identical before and after. Four simultaneous greedy 128-token requests at B=4 produce identical rows that match the single-sequence `MLXCEL_FUSED_MOE=0` output character for character. New tests pin batched-equals-sequential on a synthetic three-expert model with per-row RoPE offsets, the one-row delegation and the empty batch (`cargo test --profile test-fast --features metal,accelerate -p mlxcel qwen3_moe::tests::`, 9 passed); `cargo fmt --all -- --check` clean. Refs #1616
inureyes
force-pushed
the
feature/issue-1616-moe-batched-decode-profile
branch
from
September 4, 2026 04:28
cad0741 to
4aee0fb
Compare
3 tasks
This was referenced Oct 23, 2026
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
Attribution first, then the fix the profile justified. Issue #1616 assumed that at B>=2
qwen3_moeloses the fused MoE kernel and falls back togather_qmm. Measured, that is not what happens:Qwen3MoeModel(like all 16 MoE families carrying the== 1gate) never overrodeforward_batched, so the server's batched decode ran theLanguageModeldefault, one single-sequenceforwardper row evaluated together. A B=4 tick was four serialized single-token graphs, each still launching the fused kernel, overlapping only about 30% on the GPU. This PR givesQwen3MoeModela real batched forward (Rust only, mirroring the Qwen3 dense port), fixes the MoE profile hook so it reports the path it actually timed, and documents which families batch for real.Host substitution (approved by the user): the issue's numbers are M5 Max; everything here was measured on Mac Studio M1 Ultra 128 GB (macOS 26.6.2, mlxcel 0.7.0-beta.1, MLX pin
9a795735) against this host's own before-baseline. None of the M5 Max values (169.6, 65.5, 1.55x, 3.25x, 3.17x) was used as a target, and an M5 Max re-run against this PR is pending.What the profile found (M1 Ultra)
bench_serving_concurrency.py --prompt-tokens 512 --max-tokens 128,--parallel 4 --max-batch-prefill 4, one fresh server per model): qwen2.5-0.5b-bf16 216.2 / 174.2 / 367.5 tok/s aggregate at B=1/2/4 (1.70x), llama-3.1-8b-4bit 57.2 / 105.6 / 120.5 (2.11x), qwen3-30b-a3b-4bit 54.3 / 88.0 / 93.3 (1.72x); a second pass reproduced every B=4 aggregate within 0.3%. The dense-versus-MoE gap on this host is 0.39x of scaling, not 1.7x.MLXCEL_PROFILE_BLOCKS=1on the server: 128 block summaries for 128 ticks at B=1 and 518 for 128 ticks at B=4, four per tick, each with the same 25:75 attention:MoE split.gather_qmmis never reached at B=4.k * n_tokens, bit-identical to per-token launches, built from the verbatim Metal source) loses togather_qmmfrom n=4 (11.1 vs 9.3 to 9.7 ms). So the batched fused kernel was not built;do_sortat 32 slots is a measured 1% of a tick and is left alone.What changed
src/models/qwen3_moe.rs:Attention::apply_rope_batched,Attention::forward_split_attention(batched Q/K norm and per-row RoPE, per-sequence dense-cache update and SDPA),DecoderLayer::forward_batched/forward_batched_timed,Qwen3MoeModel::forward_batched_impl, and theLanguageModel::forward_batched/forward_batched_with_contextoverrides. One row keeps the exact single-sequence graph (fused kernel included), zero rows return the trait default's empty logits, two or more rows take the batched forward, where the MoE block sees[B, hidden]and its experts run throughgather_qmmoverB * top_kslots. The paged decode backend is not opted into.src/models/qwen3_moe.rs:SparseMoeBlock::forward_profiledfollows the production dispatch and returns aMoeProfilewithpathandtokens, soMLXCEL_PROFILE_QWEN3_MOE_DETAIL=1no longer attributes a gather path the single-token step never launched.src/models/qwen3_moe_tests.rs: batched-equals-sequential on a synthetic three-expert model with different per-row RoPE offsets, one-row delegation, and the empty batch.docs/CONTINUOUS_BATCHING.md: names the families that overrideforward_batchedand what the default does for the rest.Results (M1 Ultra, same harness)
gather_qmmand two fused launches cost about the same); B=1 81.5 to 81.0 tok/s.cargo build --releaseon the final commit exposed by recompiling. The conclusion is unchanged and the numbers move by about 1%. Gate on the final tree:cargo test --workspace --profile test-fast --features metal,accelerate10510 passed, 0 failed../target/release/mlxcel generate -m models/mlx/qwen3-30b-a3b-4bit -p "Hello" -n 128 --temp 0: byte-identical text before and after (only the load-time and tok/s lines differ).MLXCEL_FUSED_MOE=0output character for character; the only divergence anywhere is the pre-existing fused-versus-gather numeric difference at B=1.Where the acceptance criteria live
The user split this work across two destinations. On
mainthrough this PR: the code change, the profile-hook fix, the tests, the batching doc note, and therefore the criteria "MoE B=1 decode unregressed with byte-identical greedy output", "dense B=4 rows unchanged within noise", and the measured B=4 gain itself.cargo test --release -p mlxcel-core fused_moe_parity_testsis unaffected because no kernel changed; its pre-existingfused_moe_geglu_kernel_matches_references_gemma4_shapefailure at seed 886 (#964) is not touched by this PR. Onbench/0.7.0-refresh(PR #1617), as separate commits: the recorded profiledocs/benchmark_results/moe-batched-decode-m1ultra-2026-09-04.md, the CSVsbenchmarks/metal_m1ultra_batch_2026-09-04.csv(before) andbenchmarks/metal_m1ultra_batch_2026-09-04_pr1616.csv(after), the new "Batched serving (B = 1/2/4)" section indocs/benchmark_results/model_tests_m1ultra.md, and the M5 Max section note that its re-run is pending. So this PR can merge and close the issue while the profile and CSV criteria sit unmerged in #1617; they are not satisfied onmainby this PR alone.Test plan
cargo test --profile test-fast --features metal,accelerate -p mlxcel qwen3_moe::tests::(9 passed)cargo clippy --lib --tests --features metal,accelerate -- -D warningscargo fmt --all -- --checkcargo build --release --features metal,accelerate, then the B=1 greedy byte-identity check, the B=4 greedy equivalence check and the three-model serving ladder above on M1 UltraFollow-ups (not in this PR)
== 1gate still run the per-row default; each needs its ownforward_batchedafter the same premise check.Closes #1616