Skip to content

perf(qwen3_moe): batch the decode forward instead of per-row forwards - #1623

Merged
inureyes merged 2 commits into
mainfrom
feature/issue-1616-moe-batched-decode-profile
Sep 4, 2026
Merged

inureyes merged 2 commits into
mainfrom
feature/issue-1616-moe-batched-decode-profile

Conversation

@inureyes

@inureyes inureyes commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Attribution first, then the fix the profile justified. Issue #1616 assumed that at B>=2 qwen3_moe loses the fused MoE kernel and falls back to gather_qmm. Measured, that is not what happens: Qwen3MoeModel (like all 16 MoE families carrying the == 1 gate) never overrode forward_batched, so the server's batched decode ran the LanguageModel default, one single-sequence forward per 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 gives Qwen3MoeModel a 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)

  • Before ladder (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=1 on 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_qmm is never reached at B=4.
  • Op-level microbench on the real layer-0 expert planes (48-layer graph, min of 3x10 pipelined evals): per-token fused launches scale linearly (3.9 / 7.5 / 14.7 / 29.2 ms at n=1/2/4/8), identical and disjoint expert sets cost the same at every n (plane traffic is not the limiter, so cross-cohort dedup buys nothing here), and a batched prototype of the proposed kernel (grid z of k * n_tokens, bit-identical to per-token launches, built from the verbatim Metal source) loses to gather_qmm from n=4 (11.1 vs 9.3 to 9.7 ms). So the batched fused kernel was not built; do_sort at 32 slots is a measured 1% of a tick and is left alone.
  • TTFT at B=4 is prompt-cache serialization, not decode: dense prompt-cache entries are one-shot, so only as many rows adopt as entries were donated by the previous level (one at B=2, two at B=4) and the rest pay a cold 440-token prefill serialized ahead of the first decode tick. llama adopts on every row (paged clone adoption) and its TTFT stays at 165 ms.

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 the LanguageModel::forward_batched / forward_batched_with_context overrides. 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 through gather_qmm over B * top_k slots. The paged decode backend is not opted into.
  • src/models/qwen3_moe.rs: SparseMoeBlock::forward_profiled follows the production dispatch and returns a MoeProfile with path and tokens, so MLXCEL_PROFILE_QWEN3_MOE_DETAIL=1 no 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 override forward_batched and what the default does for the rest.

Results (M1 Ultra, same harness)

  • qwen3-30b-a3b-4bit: B=4 aggregate 93.3 to 102.9 tok/s (1.72x to 1.86x of B=1), per-request decode 29.8 to 33.9 tok/s; B=2 unchanged within noise (88.0 to 85.0, at 16 slots gather_qmm and two fused launches cost about the same); B=1 81.5 to 81.0 tok/s.
  • Dense rows unchanged inside the run-to-run band: llama-3.1-8b-4bit 120.5 to 118.9, qwen2.5-0.5b-bf16 367.5 to 369.5 at B=4.
  • The after pass was re-measured on this PR's final commit. An earlier pass read 103.7 at B=4 but came from a binary built before the last edit to the branch, which a cargo build --release on 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,accelerate 10510 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).
  • Four simultaneous greedy 128-token requests at B=4 produce four identical rows that match the single-sequence MLXCEL_FUSED_MOE=0 output 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 main through 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_tests is unaffected because no kernel changed; its pre-existing fused_moe_geglu_kernel_matches_references_gemma4_shape failure at seed 886 (#964) is not touched by this PR. On bench/0.7.0-refresh (PR #1617), as separate commits: the recorded profile docs/benchmark_results/moe-batched-decode-m1ultra-2026-09-04.md, the CSVs benchmarks/metal_m1ultra_batch_2026-09-04.csv (before) and benchmarks/metal_m1ultra_batch_2026-09-04_pr1616.csv (after), the new "Batched serving (B = 1/2/4)" section in docs/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 on main by 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 warnings
  • cargo fmt --all -- --check
  • cargo 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 Ultra

Follow-ups (not in this PR)

  • The other 15 MoE families with the == 1 gate still run the per-row default; each needs its own forward_batched after the same premise check.
  • One-shot prompt-cache adoption for dense-backed families makes N simultaneous identical prompts pay N minus (entries) cold prefills; the paged backend's clone adoption is the fix pattern.
  • Dense batched decode on M1 Ultra (llama-3.1-8b at 2.11x) is far from the M5 Max 3.25x and deserves its own profile.

Closes #1616

@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Sep 4, 2026
`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
inureyes force-pushed the feature/issue-1616-moe-batched-decode-profile branch from cad0741 to 4aee0fb Compare September 4, 2026 04:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(moe): batched decode scales 1.55x against 3.25x on dense

1 participant