Skip to content

feat(moe): expert-parallel fill-in for the TurboMind grouped W4A16 route - #5169

Open
windreamer wants to merge 6 commits into
stack/c4-moe-w4a16from
stack/c5-ep-moe
Open

windreamer wants to merge 6 commits into
stack/c4-moe-w4a16from
stack/c5-ep-moe

Conversation

@windreamer

@windreamer windreamer commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

The W4A16 stack (#5158-#5161) grafts TurboMind's grouped-GEMM channel into the PyTorch engine, and #5161 landed grouped MoE with expert parallelism explicitly out of scope. Meanwhile a GPTQ quantized MoE checkpoint could not reach that route from the pipeline at all: qwen2_moe never passed the quantization config to the MoE builder, so the checkpoint built ~20 GB of dense bf16 experts and OOMed. This PR closes both gaps: EP fill-in for the TM grouped W4A16 route, and the pipeline-level wiring that lets GPTQ MoE checkpoints actually drive it. Follow-ups: #5171 adds CUDA graph capture for this route; #5173 (NVFP4) and #5176/#5177 (CT-FP8 and MXFP4) extend the channel — see #5158 for the series overview.

Modification

  • TmMoeWeights grows the EP view (num_local_experts / first_local_expert / expert_map), modeled on the compressed-tensors route; the loader accepts rank-local experts only - foreign keys are skipped before the ledger, a missing local key still fails the loud completeness check.
  • Forward remaps global expert ids to local slots before blocked_route: the TM blocked slot layout indexes prefix sums by raw expert id, so under EP the remap is what keeps foreign routes inside the zeroed skip block instead of silently corrupting the sum. EP combine is a single all-reduce over the ep group (DistConfig forces world_size == ep, so the group is the whole world and per-rank partials are disjoint additive contributions).
  • New loud guards: indivisible experts, ep > 1 with dp > 1 (DP attention needs all-to-all dispatch). EPLB / microbatch raises kept.
  • qwen2_moe threads quantization_config into build_fused_moe like its siblings; verified-zero expert bias tensors (GPTQ artifact) are dropped behind an exact abs().max() == 0 gate, _is_sequential_g_idx accepts the blockwise-identity g_idx its docstring always promised (arange(n) // group_size, per-proj group sizes 128/32), and the shared-expert add is rank-normalized against the W4A16 impls' always-3D contract.
  • EP routes serve top_k above the rank-local expert count: surplus foreign
    routes park in the zeroed skip block (the remap is injective; e.g.
    Qwen2-57B-A14B GPTQ at EP=16 with top_k=8), where the initial implementation
    crashed per-forward after the full weight load; a build-time global invariant
    (top_k ≤ num_experts) still guards the truly-invalid case.
  • AWQ MoE EP CPU-direct loading: raw weights stay CPU-resident through
    transform/packing (part of the series' load-path rework; wakeup re-packs from
    the CPU source of truth).

BC-breaking

None. Models without quantized experts behave exactly as before; configs that previously raised still raise. Before this PR the TM grouped W4A16 MoE route raised loudly on every ep > 1 configuration, and ep > 1 with moe_tp > 1 cannot even reach the builder (DistConfig forces moe_tp = 1 whenever ep > 1 and dp == 1; the dp > 1 combination is rejected by the dedicated DP guard) — so nothing is newly rejected, and no combination ever silently computed wrong results on this route.

Use cases

EP deployment of quantized MoE checkpoints through the PyTorch engine, e.g. pipeline('Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4', backend_config=PytorchEngineConfig(ep=2)), and GPTQ MoE checkpoints (previously load-time OOM) driving the same TM grouped-GEMM channel as AWQ.

Checklist

  1. Pre-commit or other linting tools are used to fix the potential lint issues.
  2. The modification is covered by complete unit tests: in-process EP=2 (two rank modules over disjoint expert subsets through the real loader) vs an ep=1 monolith aligns within 1e-6 (2.4e-7 at 1 token, 4.8e-7 at 64 tokens across 45 split routes); loader filtering/completeness, combine-group and build-guard cases; pipeline e2e on Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4 against the TurboMind engine (4 prompts x 100 greedy tokens, zero NaN, byte-identical on short prompts); stack-wide sweep 389 passed / 2 hardware-capability skips.
  3. No new downstream dependencies.
  4. Docstrings updated accordingly (route boundary comment rewritten; sync-only wait() contract untouched).

@windreamer
windreamer added this pull request to stack #5162 November 19, 2026 05:04
@windreamer
windreamer marked this pull request as ready for review November 19, 2026 05:08
@windreamer
windreamer removed this pull request from stack #5162 November 20, 2026 05:16
@windreamer
windreamer added this pull request to stack #5178 November 20, 2026 05:16
Comment thread lmdeploy/pytorch/models/qwen2_moe.py Resolved
windreamer and others added 5 commits November 25, 2026 16:46
- TmMoeWeights grows the EP view (num_local_experts / first_local_expert / expert_map), modeled on the compressed-tensors route; the loader now accepts rank-local experts only - foreign keys are skipped before the ledger, a missing local key still fails the loud completeness check, and out-of-range global ids raise.
- Forward remaps global expert ids to local slots before blocked_route: the TM blocked slot layout indexes prefix sums by raw expert id (spike S10), so under EP the remap (with the sentinel moved to num_local_experts) is what keeps foreign routes inside the zeroed skip block instead of silently corrupting the sum.
- EP combine is a single all-reduce over the ep group: DistConfig forces world_size == ep, so the group is the whole world and per-rank partials are disjoint additive contributions. The ep>1 + moe_tp>1 corner is now a loud guard - expert blocks and moe-TP width shards cannot co-exist (each expert would materialize at partial width on one rank).
- Divisible-experts, dp>1 (DP attention needs all-to-all), EPLB and microbatch keep loud raises; the route boundary comment is rewritten and the sync-only wait() contract is untouched.
- Tests: in-process EP=2 (two rank modules over disjoint expert subsets, full global weight stream through the real loader) vs an ep=1 monolith aligns within 1e-6 at tokens=1 (2.4e-7) and tokens=64 with 45 split routes (4.8e-7); loader filtering/mapping/completeness, combine-group, and four build-guard cases.
… path

- qwen2_moe threads quantization_config into build_fused_moe like its siblings (qwen3_moe, mixtral); without it the GPTQ MoE dispatch never left the default dense route and a 7.8 GiB checkpoint OOMed building ~20 GB of bf16 experts.
- The checkpoint ships verified-zero bias tensors for the bias-free expert linears (4320 keys, GPTQ artifact): drop them behind an exact abs().max() == 0 gate, raise loudly on any non-zero orphan, and keep the loud KeyError for every other unmatched name.
- _is_sequential_g_idx now honors its own documented contract: arange(n) // run_len blockwise-identity buffers (Qwen1.5-MoE materializes g_idx with per-proj group sizes 128/32) are the identity mapping and are consumed; act-order permutations and shifted buffers still reject.
- The shared-expert add is rank-normalized: both W4A16 impls promote 2D input to [1, m, n] ("always 3D"), while the fused experts stay [m, n]; reshaping the add makes the model shape-independent of which backend impl the selector picked.
- Evidence: pipeline e2e on Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4, PyTorch engine vs TurboMind engine, 4 prompts x 100 greedy tokens, zero NaN; prompts 2/3 byte-identical, prompt 1 common prefix 1256/1348 chars. Regression: 58 passed / 1 pre-existing skip across the moe/gptq/golden-gate suites; ruff clean.
…ount

Under EP the grouped W4A16 route receives global router ids remapped to
rank-local slots (global id - first_local_expert). Foreign experts land
outside [0, num_local) and blocked_route parks them, together with invalid
sentinels, in the extra skip block: the grouped GEMM never walks that block
and the impl zeroes the skip rows before the weighted reduce. A token may
therefore legitimately carry more routes than the rank has local experts.

Remove the pre-EP-era shape raises that rejected exactly that shape:
blocked_route's top_k <= num_experts check, the twin sanity check in
TurbomindMoeW4A16Impl.__init__ (built with the rank-local count under EP),
and the route-metadata bounds in fused_moe's _get_sorted_idx_{triton,
single_cta} (the counters place multiple routes per bin; nothing requires
top_k <= bins). This drops the wrong guard from c20f5fd4, which rejected
builds whose top_k exceeded the rank-local expert count.

The only router invariant that survives EP is global: top_k <= num_experts
(both known by the module constructor on any EP width) - more routes than
experts would silently produce all-zero outputs. It now fires at build
time before device/impl work, and the dropped guard's regression test is
replaced by it.

Add test_ep2_serves_top_k_above_local_experts: EP=2 over 16 experts with
top_k=12 (8 local), two rank modules through the real loader path plus a
16-expert monolith, per-token randperm(16)[:12] routes straddling both
ranks; summed partials match the monolith within 1e-6.
Step 4 of the CPU-direct packing sequence: the TurboMind grouped W4A16
MoE route's rank-local expert bytes (qweight/scales/qzeros) become
CPU-resident, mirroring the mxfp4 module.

- TmMoeWeights: parameters constructed CPU-resident with a cpu_resident
  flag; _apply excludes them from module moves (post-load and wakeup
  model.to(cuda)).
- FusedMoETmW4A16: drop release_torch_weights and the spill handle;
  update_weights packs from host bytes, sleep_release frees only the
  packed handles, sleep_wakeup re-packs from the unchanged CPU
  parameters. The checkpoint GPTQ repack follows the source tensor's
  device (host) and the qwen2_moe loaders never staged .cuda(), so no
  loader edits are needed.

Evidence:
- W4A16 MoE suite green: 20 passed incl. in-process EP=2 vs TP monolith
  (1e-6) and the surplus top_k=12 EP test; layer sleep-hook test
  rewritten for the CPU-direct steady state.
- Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4 pipeline (ModelScope): 24
  FusedMoETmW4A16 modules built, gate_up.qweight CPU-resident (60, 2048,
  352), 0 loader empty_cache sweeps, peak alloc 10.6 GiB; 2-prompt
  greedy outputs byte-exact vs the pre-change tree.
The 'ep > 1 and tp > 1' guard in the TurboMind W4A16 MoE builder was
dead code: DistConfig.__post_init__ (lmdeploy/pytorch/config.py) forces
moe_tp = 1 whenever ep > 1 and dp == 1 ('self.moe_tp = self.moe_tp or
(1 if ep > 1 else self.mlp_tp)' after the dp==1 branch resets moe_tp to
None), and any ep > 1 with dp > 1 is already rejected by the dedicated
DP-attention guard immediately above. So self.tp (the moe-TP world size
from init_dist_args) can never exceed 1 under ep > 1 at this point, and
the branch was unreachable — no config could ever hit it, and no test
exercised it (verified: no reference to the 'requires moe_tp=1' message
anywhere in tests/).
- Qwen2MoeSparseMoeBlock/Qwen2MoeMLP thread module prefixes into build_fused_moe
  and the shared-expert builders so gptq/ct ignore rules evaluate per real
  projection; group-128 GPTQ + modules_to_not_convert=['lm_head'] now constructs
  (PR 5169 review thread 4691049438).
- Regression: construction with the output-head exclusion, plus parametrized
  exact-rule exclusions of experts.gate_up_proj / shared_expert.gate_up_proj.

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.

2 participants