Skip to content

fix(models): fused QMoE export for per-expert GPTQ/AWQ MoE checkpoints (#513) - #517

Merged
justinchuby merged 2 commits into
mainfrom
fix-qwen2moe-shared-expert-quant
Aug 19, 2026
Merged

justinchuby merged 2 commits into
mainfrom
fix-qwen2moe-shared-expert-quant

Conversation

@justinchuby

@justinchuby justinchuby commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Summary

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 export fails with a shape mismatch (mobius#513):

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).

Root cause

Qwen2MoELayer already accepts a linear_class (added in #495), but its call site Qwen2MoEDecoderLayer never passed one; UngatedSharedMoELayer and MoEDecoderLayer did not thread quantization at all, so attention was always dense.

Change

  • Add _quantized_linear_class(config) deriving make_quantized_linear_factory(...) from config.quantization (returns None when unquantized, so unquantized models are unchanged).
  • Thread it into MoEDecoderLayer attention and the routed MoELayer dense-fallback experts, the Qwen2MoEDecoderLayer shared expert, and UngatedSharedMoELayer.
  • Keep the tiny 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 — attention q_proj and shared-expert gate/up/down_proj become QuantizedLinear (>=3 MatMulNBits), routed experts still fuse to one QMoE, and shared_expert_gate stays Linear.
  • 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.py MoE-family selection: 192 passed, 14 skipped, no regressions. ruff check clean.

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 quantized nn.Linear modules, whereas pack_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

  • New stack_per_expert_moe_weights in _weight_utils.py: after the MatMulNBits reshape, concatenate each expert's gate_proj/up_proj in HF-concatenated [gate; up] order and stack all experts into a leading expert axis, producing the fused gate_up_proj / down_proj tensors that pack_qmoe_expert_weights consumes. No-op on already-fused (Olive) checkpoints.
  • Wire the generic MoE models (MoECausalLMModel, Qwen2MoECausalLMModel, Ernie45MoECausalLMModel, Glm4MoECausalLMModel) through preprocess_quantized_weights(qmoe_target_path=".mlp") via a shared _preprocess_moe_weights helper.
  • Symmetric GPTQ (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)

  • Graph: before = 0 QMoE / 1440 Equal; after = 24 QMoE / 0 Equal, fc1_experts_weights populated [60, 2816, 1024] (was 96 empty initializers).
  • Numerical equivalence (fp32, same weights, dense per-expert MatMulNBits vs fused QMoE, CUDA): identical greedy output ("Paris"), identical token stream, identical top-5, max abs first-step logit diff 0.072 / mean 0.0058 over 151,936 logits. This magnitude is consistent with fused-SwiGLU FP accumulation order, not a wrong expert mapping (a permutation would diverge massively). Per-tensor validation additionally proved the fused fc1/fc2 weights+scales are a byte-exact rearrangement of the source experts (1080 checks across 3 layers × 60 experts, 0 failures).
  • fp16 note: the fp16 build produces garbage under onnxruntime 1.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-empty fc1/fc2_experts_weights with 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 --check clean. (tests/moe_integration_test.py needs onnxruntime_easy, absent on this box.)

@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 19, 2026 03:18
@github-actions

github-actions Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 1125b8a → bd666bc

Model Sub-model Changes Status

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@github-actions

github-actions Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 1125b8a → bd666bc

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 60 60 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 105 105 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 264 264 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 126 126 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 166 166 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 from config.quantization (or None when unquantized).
  • Thread that factory into shared-expert MLP construction for Qwen2MoEDecoderLayer and UngatedSharedMoELayer, while forcing shared_expert_gate to 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.

Comment thread tests/build_graph_test.py Resolved
…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
justinchuby force-pushed the fix-qwen2moe-shared-expert-quant branch from b06784f to 4dbab45 Compare August 19, 2026 03:39
@justinchuby justinchuby changed the title fix(models): quantize MoE shared experts for GPTQ/AWQ checkpoints (#513) fix(models): quantize MoE decoder-layer projections for GPTQ/AWQ checkpoints (#513) Aug 19, 2026
)

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]>
@justinchuby justinchuby changed the title fix(models): quantize MoE decoder-layer projections for GPTQ/AWQ checkpoints (#513) fix(models): fused QMoE export for per-expert GPTQ/AWQ MoE checkpoints (#513) Aug 19, 2026
@justinchuby
justinchuby merged commit eb5534f into main Aug 19, 2026
20 of 23 checks passed
@justinchuby
justinchuby deleted the fix-qwen2moe-shared-expert-quant branch August 19, 2026 23:58
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
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.

GPTQ/AWQ Qwen2-MoE export fails: shared_expert uses dense Linear, not quantized factory (shape mismatch)

2 participants