Repository navigation
feat(moe): expert-parallel fill-in for the TurboMind grouped W4A16 route - #5169
Open
windreamer wants to merge 6 commits into
Open
windreamer wants to merge 6 commits into
windreamer wants to merge 6 commits into
Conversation
Collaborator
Author
|
This change is part of the following stack:
Change managed by git-spice. |
This was referenced Nov 19, 2026
windreamer
marked this pull request as ready for review
November 19, 2026 05:08
windreamer
force-pushed
the
stack/c5-ep-moe
branch
from
November 19, 2026 09:36
a8ca8fc to
2242d47
Compare
This was referenced Nov 19, 2026
windreamer
force-pushed
the
stack/c5-ep-moe
branch
from
November 20, 2026 05:15
2242d47 to
1b69e98
Compare
This was referenced Nov 20, 2026
windreamer
force-pushed
the
stack/c5-ep-moe
branch
from
November 23, 2026 02:10
1b69e98 to
05db1bc
Compare
windreamer
force-pushed
the
stack/c5-ep-moe
branch
from
November 23, 2026 11:01
05db1bc to
5bc4095
Compare
windreamer
force-pushed
the
stack/c5-ep-moe
branch
from
November 25, 2026 03:44
5bc4095 to
c9aa32c
Compare
qescccczmr
reviewed
Nov 25, 2026
- 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.
windreamer
force-pushed
the
stack/c5-ep-moe
branch
from
November 25, 2026 08:54
c9aa32c to
a2f5d71
Compare
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.
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
TmMoeWeightsgrows 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.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 (DistConfigforcesworld_size == ep, so the group is the whole world and per-rank partials are disjoint additive contributions).ep > 1withdp > 1(DP attention needs all-to-all dispatch). EPLB / microbatch raises kept.quantization_configintobuild_fused_moelike its siblings; verified-zero expert bias tensors (GPTQ artifact) are dropped behind an exactabs().max() == 0gate,_is_sequential_g_idxaccepts the blockwise-identityg_idxits 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.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.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 > 1configuration, andep > 1withmoe_tp > 1cannot even reach the builder (DistConfigforcesmoe_tp = 1wheneverep > 1anddp == 1; thedp > 1combination 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
wait()contract untouched).