Skip to content

Commit 9d1c0bb

Browse files
authored
Fix Olive-quantized Qwen3 MoE export (#525)
## 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
1 parent 0665542 commit 9d1c0bb

8 files changed

Lines changed: 620 additions & 18 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,59 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Packed fused MoE experts (Olive/GPTQ/AWQ) survive HF weight renaming
11+
12+
#### Fixed
13+
14+
- MoE exports whose routed experts go through the fused `com.microsoft::QMoE`
15+
packer (`qwen3_moe`, Mixtral, OLMoE, Qwen2-MoE, Ernie4.5-MoE, GLM4-MoE) no
16+
longer fail on **packed quantized** fused expert tensors.
17+
`_rename_moe_expert_weights` matched packed sidecars by substring
18+
(`.experts.gate_up_proj` also matches `experts.gate_up_proj_qweight`) and
19+
split them as if they were float weights, writing the `qweight`, `scales` and
20+
`qzeros` of one projection to the *same* per-expert `.weight` key — so only
21+
the last one survived, and the restacked tensor no longer matched the QMoE
22+
parameter, aborting the export at weight binding:
23+
24+
```
25+
ValueError: Weight shape mismatch for 'model.layers.0.mlp.fc1_experts_weights':
26+
model expects [4, 64, 32], got [4, 256]
27+
```
28+
29+
Packed tensors now pass through untouched and reach
30+
`pack_qmoe_expert_weights` in the expert-major layout it expects (Qwen3-MoE
31+
Olive int4: `[128, 1536, 1024]` uint8 weights + `[128, 1536, 16]` bf16
32+
scales). Unquantized fused experts still un-fuse into the dense per-expert
33+
fallback.
34+
35+
#### Added
36+
37+
- `mobius._weight_utils.is_packed_quant_key` plus the shared
38+
`OLIVE_PACKED_QUANT_SUFFIXES` / `DOTTED_PACKED_QUANT_SUFFIXES` /
39+
`PACKED_QUANT_SUFFIXES` constants: one predicate for
40+
`_qweight`/`_scales`/`_qzeros` (Olive) and `.qweight`/`.scales`/`.qzeros`
41+
(GPTQ/AWQ) sidecar keys, reused by `preprocess_quantized_weights`.
42+
43+
---
44+
45+
### Qwen3-MoE packages load in ONNX Runtime GenAI
46+
47+
#### Fixed
48+
49+
- Exported `qwen3_moe` packages no longer fail to load with
50+
`RuntimeError: Unsupported model_type in config.json: qwen3_moe`.
51+
`_ORT_GENAI_MODEL_TYPE` had no `qwen3_moe` entry, so `--config` mode wrote
52+
the HuggingFace type straight into `genai_config.json` and ORT GenAI
53+
rejected it (its LLM type registry has no `qwen3_moe`). Qwen3-MoE now
54+
resolves to the accepted `qwen3` type: both `qwen2` and `qwen3` dispatch to
55+
ORT GenAI's `DecoderOnly_Model`, but its tokenizer tag fallback
56+
(`tokenizer_tag_utils.cpp`) only supplies the Qwen3 reasoning-token IDs
57+
(`bor` 151667 / `eor` 151668) for `qwen3` — under `qwen2` they are absent and
58+
`tokenizer.bor_token_id` / `eor_token_id` throws. The pre-existing dense
59+
`qwen3 -> qwen2` alias is unchanged.
60+
61+
---
62+
1063
### Fixed
1164

1265
- An exported graph is no longer transcribed into its own workflow component.

‎src/mobius/_weight_utils.py‎

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,42 @@
2424

2525
logger = logging.getLogger(__name__)
2626

27+
# Key suffixes marking a *packed quantized* sidecar tensor rather than a float
28+
# weight. A "sidecar" here is an auxiliary tensor that rides alongside a
29+
# quantized parameter's canonical ``.weight`` key instead of replacing it —
30+
# the packed integer payload (``qweight``) plus its per-group ``scales`` and
31+
# ``qzeros`` are each stored under their own key, so one logical weight is
32+
# split across several sidecar keys until they are unpacked back into a
33+
# single dequantized tensor. Olive appends them with an underscore directly
34+
# to the parameter name (``<pname>_qweight``, see Olive's
35+
# ``olive/common/quant/state_dict.py``), while GPTQ/AWQ store dotted sibling
36+
# buffers on the owning module (``<module>.qweight``). Both conventions occur
37+
# in raw HF checkpoints.
38+
OLIVE_PACKED_QUANT_SUFFIXES: frozenset[str] = frozenset({"_qweight", "_scales", "_qzeros"})
39+
DOTTED_PACKED_QUANT_SUFFIXES: frozenset[str] = frozenset({".qweight", ".scales", ".qzeros"})
40+
# str.endswith() requires a tuple (not a set), so the combined predicate below
41+
# needs a tuple even though the two suffix sets above are otherwise unordered.
42+
PACKED_QUANT_SUFFIXES: tuple[str, ...] = tuple(
43+
OLIVE_PACKED_QUANT_SUFFIXES | DOTTED_PACKED_QUANT_SUFFIXES
44+
)
45+
46+
47+
def is_packed_quant_key(name: str) -> bool:
48+
"""Whether ``name`` is a packed-quantization sidecar key.
49+
50+
Packed keys carry the quantized payload (``qweight``), the per-group
51+
``scales`` or the ``qzeros`` of a quantized parameter, in either the Olive
52+
underscore convention (``…experts.gate_up_proj_qweight``) or the GPTQ/AWQ
53+
dotted convention (``…gate_proj.qweight``).
54+
55+
HF→ONNX key rewriting must leave these tensors intact until
56+
:func:`preprocess_quantized_weights` unpacks them: they are packed bytes,
57+
not float weights, so reshaping or splitting them corrupts the payload —
58+
and several sidecars of one projection would collapse onto a single
59+
renamed ``.weight`` key.
60+
"""
61+
return name.endswith(PACKED_QUANT_SUFFIXES)
62+
2763

2864
def supported_qmoe_quantization(
2965
quantization: QuantizationConfig | None,
@@ -1077,14 +1113,6 @@ def preprocess_quantized_weights(
10771113
if qmoe_target_path is not None
10781114
else False
10791115
)
1080-
packed_suffixes = (
1081-
"_qweight",
1082-
"_scales",
1083-
"_qzeros",
1084-
".qweight",
1085-
".scales",
1086-
".qzeros",
1087-
)
10881116
if (
10891117
use_qmoe
10901118
and quantization is not None
@@ -1107,7 +1135,7 @@ def preprocess_quantized_weights(
11071135
packed_expert_keys = [
11081136
key
11091137
for key in state_dict
1110-
if qmoe_target_path in key and ".experts." in key and key.endswith(packed_suffixes)
1138+
if qmoe_target_path in key and ".experts." in key and is_packed_quant_key(key)
11111139
]
11121140
if packed_expert_keys:
11131141
raise ValueError(
@@ -1121,18 +1149,24 @@ def preprocess_quantized_weights(
11211149
"supported_qmoe_quantization) for MoE models instead."
11221150
)
11231151

1124-
def _is_packed_key(key: str, float_key: str) -> bool:
1152+
def _is_packed_sidecar_of(key: str, float_key: str) -> bool:
1153+
"""Whether ``key`` is a packed sidecar of the specific ``float_key``.
1154+
1155+
Unlike the module-level :func:`is_packed_quant_key` suffix predicate,
1156+
this matches the *exact* sidecar keys of one named float parameter.
1157+
"""
11251158
owner = float_key.removesuffix(".weight")
1126-
return any(key == float_key + suffix for suffix in packed_suffixes[:3]) or any(
1127-
key == owner + suffix for suffix in packed_suffixes[3:]
1159+
return any(key == float_key + suffix for suffix in OLIVE_PACKED_QUANT_SUFFIXES) or any(
1160+
key == owner + suffix for suffix in DOTTED_PACKED_QUANT_SUFFIXES
11281161
)
11291162

11301163
packed_embedding_or_head = (
11311164
next(
11321165
(
11331166
key
11341167
for key in state_dict
1135-
if _is_packed_key(key, embed_key) or _is_packed_key(key, head_key)
1168+
if _is_packed_sidecar_of(key, embed_key)
1169+
or _is_packed_sidecar_of(key, head_key)
11361170
),
11371171
None,
11381172
)

‎src/mobius/_weight_utils_test.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
from mobius._configs import QuantizationConfig
1212
from mobius._weight_utils import (
13+
is_packed_quant_key,
1314
merge_lora_weights,
1415
preprocess_awq_weights,
1516
preprocess_gptq_weights,
@@ -1393,3 +1394,43 @@ def test_non_expert_keys_pass_through(self):
13931394
assert torch.equal(
13941395
result["model.embed_tokens.weight"], sd["model.embed_tokens.weight"]
13951396
)
1397+
1398+
1399+
class TestIsPackedQuantKey:
1400+
"""Shared predicate for packed-quantization sidecar keys."""
1401+
1402+
@pytest.mark.parametrize(
1403+
"key",
1404+
[
1405+
# Olive underscore convention (suffix on the parameter name).
1406+
"model.layers.0.mlp.experts.gate_up_proj_qweight",
1407+
"model.layers.0.mlp.experts.gate_up_proj_scales",
1408+
"model.layers.0.mlp.experts.down_proj_qzeros",
1409+
"model.layers.0.self_attn.q_proj.weight_qweight",
1410+
# GPTQ/AWQ dotted convention (sibling buffers of the module).
1411+
"model.layers.0.mlp.experts.0.gate_proj.qweight",
1412+
"model.layers.0.mlp.experts.0.gate_proj.scales",
1413+
"model.layers.0.mlp.experts.0.gate_proj.qzeros",
1414+
],
1415+
)
1416+
def test_packed_keys_detected(self, key):
1417+
assert is_packed_quant_key(key)
1418+
1419+
@pytest.mark.parametrize(
1420+
"key",
1421+
[
1422+
# Float weights, including the fused MoE tensors that *are* split.
1423+
"model.layers.0.mlp.experts.gate_up_proj",
1424+
"model.layers.0.mlp.experts.down_proj",
1425+
"model.layers.0.mlp.gate.weight",
1426+
"model.layers.0.self_attn.q_proj.bias",
1427+
"model.layers.0.block_sparse_moe.input_linear.weight",
1428+
# Already-unpacked names produced downstream by the preprocessors.
1429+
"model.layers.0.mlp.fc1_experts_weights",
1430+
"model.layers.0.self_attn.q_proj.zero_points",
1431+
# Suffix must be terminal, not merely present.
1432+
"model.layers.0.mlp.experts.gate_up_proj_qweight.extra",
1433+
],
1434+
)
1435+
def test_unpacked_keys_rejected(self, key):
1436+
assert not is_packed_quant_key(key)

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,17 @@ def _revision_kwargs(revision: str | None) -> dict[str, str]:
7575
"llama": "llama",
7676
"qwen2": "qwen2",
7777
"qwen3": "qwen2",
78+
# Qwen3-MoE shares the dense Qwen3 decoder contract (same inputs, position
79+
# IDs and KV cache layout); only the MLP differs, and that is fused into
80+
# the exported graph. ORT GenAI has no "qwen3_moe" entry in its LLM type
81+
# registry (see onnxruntime-genai/src/models/model_type.h), so passing the
82+
# HF type through fails to load with "Unsupported model_type in
83+
# config.json: qwen3_moe". It maps to "qwen3" rather than reusing the dense
84+
# "qwen3" -> "qwen2" alias: both types dispatch to DecoderOnly_Model, but
85+
# ORT GenAI's tokenizer tag fallback (tokenizer_tag_utils.cpp) only supplies
86+
# Qwen3 reasoning-token IDs (bor 151667 / eor 151668) for "qwen3"; under
87+
# "qwen2" those are absent and tokenizer.bor_token_id/eor_token_id throws.
88+
"qwen3_moe": "qwen3",
7889
"phi3": "phi3",
7990
"phi": "phi",
8091
"phi4mm": "phi4mm",

‎src/mobius/integrations/ort_genai/auto_export_test.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,14 @@ def test_phi4mm_model_types(self):
123123
assert _resolve_ort_genai_model_type("phi4_multimodal") == "phi4mm"
124124
assert _resolve_ort_genai_model_type("phi") == "phi"
125125

126+
def test_qwen3_moe_maps_to_supported_decoder_type(self):
127+
# ORT GenAI's LLM type registry has no "qwen3_moe" entry, so passing
128+
# the HF type through fails to load with "Unsupported model_type in
129+
# config.json: qwen3_moe". Qwen3-MoE maps to the accepted "qwen3" type
130+
# (not the dense "qwen3" -> "qwen2" alias) so ORT GenAI's tokenizer tag
131+
# fallback still supplies the Qwen3 reasoning-token IDs.
132+
assert _resolve_ort_genai_model_type("qwen3_moe") == "qwen3"
133+
126134
def test_gemma4_unified_model_types(self):
127135
# The gemma-4-12B unified checkpoint (model_type "gemma4_unified")
128136
# reuses the multimodal "gemma4" ORT GenAI pipeline; its standalone
@@ -161,6 +169,14 @@ def test_multimodal_keeps_hf_type(self):
161169
def test_decoder_only_falls_back_to_hf_when_config_missing(self):
162170
assert _select_ort_model_type(None, "qwen3", is_decoder_only=True) == "qwen2"
163171

172+
def test_decoder_only_qwen3_moe_resolves_to_supported_type(self):
173+
# hf_model_id mode: both the package config and the HF config report
174+
# "qwen3_moe"; the decoder-only preference must still resolve through
175+
# the alias rather than emitting the unsupported HF type.
176+
assert (
177+
_select_ort_model_type("qwen3_moe", "qwen3_moe", is_decoder_only=True) == "qwen3"
178+
)
179+
164180
def test_decoder_only_unknown_config_falls_back_to_hf(self):
165181
# An unrecognised config.model_type (not in _ORT_GENAI_MODEL_TYPE) must
166182
# not pass straight through as an invalid ORT type; fall back to the
@@ -2085,6 +2101,25 @@ class FakeConfig:
20852101
# "gemma2" maps to "gemma" in _ORT_GENAI_MODEL_TYPE
20862102
assert data["model"]["type"] == "gemma"
20872103

2104+
def test_config_mode_qwen3_moe_emits_supported_decoder_type(self, tmp_path):
2105+
"""Qwen3-MoE --config exports must not emit the unsupported HF type.
2106+
2107+
Regression: a decoder-only Qwen3-MoE package wrote
2108+
``"type": "qwen3_moe"`` into genai_config.json, and loading it raised
2109+
``RuntimeError: Unsupported model_type in config.json: qwen3_moe``
2110+
because ORT GenAI's LLM registry has no such type. The emitted type is
2111+
literally ``"qwen3"``: ORT GenAI's tokenizer tag fallback keys the
2112+
Qwen3 reasoning-token IDs off that name.
2113+
"""
2114+
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
2115+
2116+
pkg = _make_fake_llm_pkg("qwen3_moe")
2117+
result = write_ort_genai_config(pkg, str(tmp_path), hf_model_id=None)
2118+
2119+
with open(result["genai_config"]) as f:
2120+
data = json.load(f)
2121+
assert data["model"]["type"] == "qwen3"
2122+
20882123
def test_config_mode_gemma3_text_vlm_uses_multimodal_model_type(self, tmp_path):
20892124
"""Gemma3 VLM --config exports use ORT's multimodal gemma3 type."""
20902125
import dataclasses

‎src/mobius/models/moe.py‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from onnxscript import OpBuilder, nn
1313

1414
from mobius._configs import ArchitectureConfig
15-
from mobius._weight_utils import preprocess_quantized_weights
15+
from mobius._weight_utils import is_packed_quant_key, preprocess_quantized_weights
1616
from mobius.components import (
1717
Attention,
1818
Embedding,
@@ -611,6 +611,22 @@ def _rename_moe_expert_weights(
611611
``input_linear.weight [N, 2*inter, hidden]`` → per-expert gate_proj + up_proj
612612
``output_linear.weight [N, hidden, inter]`` → per-expert down_proj
613613
``router.layer.weight`` → ``gate.weight``
614+
615+
Packed quantized expert tensors (Olive ``…_qweight``/``_scales``/``_qzeros``,
616+
GPTQ/AWQ ``….qweight``/``.scales``/``.qzeros`` — see
617+
:func:`~mobius._weight_utils.is_packed_quant_key`) are **never** split.
618+
Splitting them would reinterpret packed bytes as float rows *and* collapse
619+
every sidecar of one projection onto the same per-expert ``.weight`` key,
620+
keeping only the last one. Call sites that continue into
621+
:func:`_preprocess_moe_weights` (the :class:`MoECausalLMModel` family) need
622+
the fused expert-major layout intact for ``pack_qmoe_expert_weights``; for
623+
every other call site this function simply leaves the packed keys alone.
624+
625+
Module-path renames still apply to packed keys under the Olive convention,
626+
where the suffix hangs off a retained ``.weight`` component
627+
(``…mlp.router.weight_qweight`` → ``…mlp.gate.weight_qweight``). Dotted
628+
GPTQ/AWQ sidecars have no ``.weight`` component (``…mlp.router.qweight``),
629+
so no rename pattern matches them and they pass through as-is.
614630
"""
615631
# Step 0: GraniteMoE uses block_sparse_moe; rename to mlp to match our attribute.
616632
state_dict = {
@@ -632,6 +648,10 @@ def _rename_moe_expert_weights(
632648
# Second pass: split fused 3D expert weights and rename routers
633649
fused: dict[str, torch.Tensor] = {}
634650
for name, tensor in list(renamed.items()):
651+
# Packed quantized sidecars are never split: they must stay fused for the
652+
# downstream QMoE packer, and splitting also collides their keys. Only
653+
# float fused tensors are split into per-expert ``.weight`` keys.
654+
is_packed = is_packed_quant_key(name)
635655
# GraniteMoE: router.layer.weight → gate.weight
636656
if ".router.layer.weight" in name:
637657
new_name = name.replace(".router.layer.weight", ".gate.weight")
@@ -643,7 +663,7 @@ def _rename_moe_expert_weights(
643663
fused[new_name] = tensor
644664
del renamed[name]
645665
# GraniteMoE: input_linear.weight [N, 2*inter, hidden] → gate_proj + up_proj
646-
elif ".input_linear.weight" in name and tensor.dim() == 3:
666+
elif not is_packed and ".input_linear.weight" in name and tensor.dim() == 3:
647667
prefix = name.replace(".input_linear.weight", "")
648668
num_experts = tensor.shape[0]
649669
half = tensor.shape[1] // 2
@@ -654,15 +674,15 @@ def _rename_moe_expert_weights(
654674
fused[f"{prefix}.experts.{i}.up_proj.weight"] = up_w
655675
del renamed[name]
656676
# GraniteMoE: output_linear.weight [N, hidden, inter] → down_proj
657-
elif ".output_linear.weight" in name and tensor.dim() == 3:
677+
elif not is_packed and ".output_linear.weight" in name and tensor.dim() == 3:
658678
prefix = name.replace(".output_linear.weight", "")
659679
num_experts = tensor.shape[0]
660680
for i in range(num_experts):
661681
fused[f"{prefix}.experts.{i}.down_proj.weight"] = tensor[i]
662682
del renamed[name]
663683
# Fused gate_up_proj [N, 2*inter, hidden] → per-expert gate_proj + up_proj
664684
# (Mixtral, OLMoE, Qwen2-MoE, PhiMoE)
665-
elif ".experts.gate_up_proj" in name and tensor.dim() == 3:
685+
elif not is_packed and ".experts.gate_up_proj" in name and tensor.dim() == 3:
666686
prefix = name.split(".experts.gate_up_proj")[0]
667687
num_experts = tensor.shape[0]
668688
half = tensor.shape[1] // 2
@@ -674,7 +694,12 @@ def _rename_moe_expert_weights(
674694
del renamed[name]
675695
# Fused experts.down_proj [N, hidden, inter] → per-expert down_proj
676696
# Only match the fused format (3D tensor), not per-expert experts.{i}.down_proj
677-
elif ".experts.down_proj" in name and tensor.dim() == 3 and "experts." in name:
697+
elif (
698+
not is_packed
699+
and ".experts.down_proj" in name
700+
and tensor.dim() == 3
701+
and "experts." in name
702+
):
678703
parts = name.split(".experts.down_proj")
679704
if len(parts) == 2 and not parts[0].endswith(tuple("0123456789")):
680705
prefix = parts[0]

0 commit comments

Comments
 (0)