Repository navigation
fix(models): fused QMoE export for per-expert GPTQ/AWQ MoE checkpoints (#513) - #517
Merged
Merged
Conversation
Performance Comparison
|
Contributor
There was a problem hiding this comment.
Pull request overview
Fixes MoE shared-expert construction so GPTQ/AWQ-quantized checkpoints load successfully by ensuring shared-expert MLP projections use the quantization-aware linear factory (while keeping the tiny shared_expert_gate dense), addressing mobius#513.
Changes:
- Add
_shared_expert_linear_class(config)to derive a quantized-linear factory fromconfig.quantization(orNonewhen unquantized). - Thread that factory into shared-expert MLP construction for
Qwen2MoEDecoderLayerandUngatedSharedMoELayer, while forcingshared_expert_gateto remain dense for Qwen2-MoE. - Add graph-build tests validating shared-expert quantization behavior for Qwen2-MoE and GLM4-MoE, plus a dense (unquantized) regression test.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
src/mobius/models/moe.py |
Adds shared-expert quantized-linear factory helper and wires it into Qwen2-MoE + ungated shared-expert MoE layers. |
tests/build_graph_test.py |
Adds targeted tests asserting shared-expert projections quantize correctly (and the gate remains dense) for relevant MoE models. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
…kpoints (#513) MoE decoder layers built their attention (Q/K/V/O) and always-active shared-expert projections with dense `Linear`/`MLP` regardless of the checkpoint's quantization. For GPTQ/AWQ MoE checkpoints this makes the model unloadable: the packed weight does not fit a dense `Linear`, and the export fails with a shape mismatch (mobius#513), e.g. Weight shape mismatch for 'model.layers.0.self_attn.k_proj.weight': model expects [2048, 2048], got [2048, 16, 64] and, once attention loads, the same on `mlp.shared_expert.*`. The GPTQ checkpoint `Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4` quantizes `self_attn.{q,k,v,o}_proj` and `mlp.shared_expert.{gate,up,down}_proj` (they are listed in `modules_in_block_to_quantize`), so those projections must be built through the same quantization-aware factory as the routed experts. Affected registry models: `qwen2_moe` (Qwen1.5-MoE), `glm4_moe` and `ernie4_5_moe` (ungated shared expert), plus attention for the whole generic MoE family (Mixtral / GraniteMoE / OLMoE / Qwen3-MoE). `Qwen2MoELayer` already accepted a `linear_class` (added in #495) but its call site never passed one; `UngatedSharedMoELayer` and `MoEDecoderLayer` did not thread quantization at all. Derive the factory from the config and pass it into attention and the shared-expert MLP. The tiny `shared_expert_gate` (hidden -> 1) stays dense: it is excluded from quantization in the source checkpoints. Adds graph-only tests asserting attention and shared-expert projections become MatMulNBits (routed experts still fuse to QMoE) under int4, and stay dense otherwise. Co-authored-by: Copilot <[email protected]>
justinchuby
force-pushed
the
fix-qwen2moe-shared-expert-quant
branch
from
August 19, 2026 03:39
b06784f to
4dbab45
Compare
) Per-expert GPTQ/AWQ MoE checkpoints (e.g. Qwen1.5-MoE-A2.7B-GPTQ-Int4) store every routed expert as a separate module, so the generic MoE models (MoECausalLMModel, Qwen2MoECausalLMModel, Ernie45MoECausalLMModel, Glm4MoECausalLMModel) emitted an unfused graph: per-expert MatMulNBits + Equal masking with empty fc1/fc2 QMoE initializers. The runtime then computes every expert each token. The native QMoE packer (pack_qmoe_expert_weights) expects the fused expert-major tensors that Olive emits, which per-expert checkpoints do not provide. Add stack_per_expert_moe_weights to bridge the two: after the MatMulNBits reshape, concatenate each expert's gate/up projections in HF-concatenated [gate; up] order and stack all experts into a new leading dim, producing the fused gate_up_proj / down_proj tensors the packer consumes. Wire the generic MoE models through preprocess_quantized_weights with qmoe_target_path=".mlp" so the stacking + packing runs. Result on Qwen1.5-MoE-A2.7B-GPTQ-Int4 (measured, RTX 4060): the graph now emits 24 fused com.microsoft::QMoE nodes (one per layer), 0 Equal ops, and populated fc1/fc2 expert weights (fc1 [60, 2816, 1024]). Numerically equivalent to the dense per-expert reference: identical argmax and top-5, max abs first-step logit diff 0.072 over 151,936 logits (fp32 A/B on CUDA, same weights) — consistent with fused-SwiGLU FP accumulation order, not a wrong expert mapping. Symmetric GPTQ (sym=True) drops zero-points on both the dense and QMoE paths (implicit zp=8), so no zero-point transport is added; asymmetric transport remains out of scope. Co-authored-by: Copilot <[email protected]>
titaiwangms
added a commit
that referenced
this pull request
Aug 24, 2026
## Summary - preserve packed Olive/GPTQ/AWQ fused expert tensors through generic MoE weight renaming so the QMoE packer receives the original expert-major layout - keep unquantized fused-expert splitting unchanged and centralize packed-sidecar suffix detection - emit the supported ORT GenAI `qwen3` runtime type for `qwen3_moe`, preserving Qwen3 reasoning token metadata - add weight-preprocessing, graph, runtime-config, and regression coverage This completes the generic Qwen3-MoE KQuant path built on #517. Before this change, packed `gate_up_proj_qweight` and `_scales` sidecars collided after being split into the same per-expert `.weight` keys, causing a deterministic weight-shape mismatch during export. ## Validation - `220 passed` — focused MoE, weight utility, Qwen3.5, and QMoE fusion tests - `94 passed, 8 skipped` — quantized/MoE graph tests - `192 passed` — ORT GenAI integration tests - Ruff check and format passed on all changed Python files - full `Qwen/Qwen3-30B-A3B` Olive KQuant + Mobius export completed successfully - exported 16 GB package loaded with ORT GenAI 0.16.0-dev on an A100 80 GB - Qwen3 reasoning IDs resolved correctly (`bor=151667`, `eor=151668`) - CUDA greedy generation produced coherent output and correctly answered `17 * 23 = 391` Copilot-Session: e10674c1-6909-4b09-9f5a-d41b28c89d2d
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
MoE decoder layers built their attention (Q/K/V/O) and always-active shared-expert projections with dense
Linear/MLPregardless of the checkpoint's quantization. For GPTQ/AWQ MoE checkpoints this makes the model unloadable — the packed weight does not fit a denseLinearand export fails with a shape mismatch (mobius#513):and, once attention loads, the same on
mlp.shared_expert.*.The GPTQ checkpoint
Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4quantizesself_attn.{q,k,v,o}_projandmlp.shared_expert.{gate,up,down}_proj(they are listed inmodules_in_block_to_quantize), so those projections must be built through the same quantization-aware factory as the routed experts.Affected registry models:
qwen2_moe(Qwen1.5-MoE),glm4_moeandernie4_5_moe(ungated shared expert), plus attention for the whole generic MoE family (Mixtral / GraniteMoE / OLMoE / Qwen3-MoE).Root cause
Qwen2MoELayeralready accepts alinear_class(added in #495), but its call siteQwen2MoEDecoderLayernever passed one;UngatedSharedMoELayerandMoEDecoderLayerdid not thread quantization at all, so attention was always dense.Change
_quantized_linear_class(config)derivingmake_quantized_linear_factory(...)fromconfig.quantization(returnsNonewhen unquantized, so unquantized models are unchanged).MoEDecoderLayerattention and the routedMoELayerdense-fallback experts, theQwen2MoEDecoderLayershared expert, andUngatedSharedMoELayer.shared_expert_gate(hidden -> 1) dense (shared_expert_gate_class=Linear): it is excluded from quantization in the source checkpoints.Tests
Graph-only (no weights / GPU), added to
TestBuildGraphQuantized:test_qwen2_moe_int4_quantizes_shared_expert— attentionq_projand shared-expertgate/up/down_projbecomeQuantizedLinear(>=3MatMulNBits), routed experts still fuse to oneQMoE, andshared_expert_gatestaysLinear.test_qwen2_moe_dense_shared_expert_stays_linear— unquantized config keeps the shared expert dense.test_glm4_moe_int4_quantizes_shared_expert— the ungated-shared variant quantizes its shared expert too.pytest tests/build_graph_test.pyMoE-family selection: 192 passed, 14 skipped, no regressions.ruff checkclean.Note (follow-up, out of scope here)
With this fix the Qwen1.5-MoE-GPTQ export progresses past attention and the shared expert, but still fails to populate the fused QMoE routed-expert weights (
fc1/fc2_experts_weights). AutoGPTQ stores the 60 routed experts as separate per-expert quantizednn.Linearmodules, whereaspack_qmoe_expert_weights(and the working DeepSeek / Qwen3.5-Olive QMoE paths) expect an already-fused expert-major tensor. Wiring per-expert-GPTQ → fused-QMoE stacking for the generic MoE family is a separate change and needs numerical validation, so it is intentionally not included here.Closes #513
Update — per-expert → fused QMoE stacking now implemented (commit bd666bc)
The "follow-up, out of scope" item above is now done in this branch, so the scope of the PR is broadened: Qwen1.5-MoE-A2.7B-GPTQ-Int4 (and the per-expert GPTQ/AWQ MoE family) now export a fully fused graph.
Change
stack_per_expert_moe_weightsin_weight_utils.py: after the MatMulNBits reshape, concatenate each expert'sgate_proj/up_projin HF-concatenated[gate; up]order and stack all experts into a leading expert axis, producing the fusedgate_up_proj/down_projtensors thatpack_qmoe_expert_weightsconsumes. No-op on already-fused (Olive) checkpoints.MoECausalLMModel,Qwen2MoECausalLMModel,Ernie45MoECausalLMModel,Glm4MoECausalLMModel) throughpreprocess_quantized_weights(qmoe_target_path=".mlp")via a shared_preprocess_moe_weightshelper.sym=True) drops zero-points on both the dense and QMoE paths (implicit zp=8); no zero-point transport is added. Asymmetric zero-point transport stays out of scope.Measured (RTX 4060 8 GB, Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4)
fc1_experts_weightspopulated[60, 2816, 1024](was 96 empty initializers).fc1/fc2weights+scales are a byte-exact rearrangement of the source experts (1080 checks across 3 layers × 60 experts, 0 failures).onnxruntime1.27.0 because the ORT QMoE CUDA kernel is fp32-activation-only (a known runtime kernel constraint, independently recorded on the H200 team's side). The fp32 build runs correctly. This is a runtime kernel property, not an emission bug — the fused graph itself is correct.Tests
TestStackPerExpertMoEWeights(5 tests): fused shape, gate-first/up-second row ordering, expert-axis order preservation (catches permutation), Olive already-fused no-op, non-expert passthrough.TestPreprocessQuantizedWeights::test_per_expert_gptq_moe_produces_populated_fused_qmoe: end-to-end per-expert GPTQ → populated non-emptyfc1/fc2_experts_weightswith a leading expert axis and no surviving per-expert tensors.pytest src/mobius/_weight_utils_test.py src/mobius/components/_moe_test.py src/mobius/rewrite_rules/_qmoe_fusion_test.py→ 162 passed.ruff check+ruff format --checkclean. (tests/moe_integration_test.pyneedsonnxruntime_easy, absent on this box.)