Skip to content

Commit 2481e3c

Browse files
titaiwangmsCopilot
andauthored
Fix Qwen3.5/3.6-MoE VL decoder QMoE quantization support (#511)
## Summary `Qwen35MoEVL3ModelCausalLMModel.preprocess_weights` (the 3-model-split vision-language wrapper for Qwen3.5/3.6-MoE) previously had **zero quantization awareness**, unlike its text-only sibling `Qwen35MoECausalLMModel`. An Olive-quantized VL checkpoint would be silently mishandled: quantized MoE expert weights would be routed as if float, producing a broken/incomplete ONNX export with no error raised. This is one of the pieces needed to support end-to-end quantized export of `Qwen/Qwen3.6-35B-A3B` (256-expert MoE VL model) via `MobiusBuilder`, alongside microsoft/Olive#2628 and microsoft/Olive#2457. ## Changes - `use_qmoe` detection (via `_supported_qmoe_quantization`), mirroring the text-only sibling. - A guard that raises a clear `ValueError` when packed-but-unsupported quantized expert weights are found, instead of silently falling back to the (incompatible) dense per-expert path. - `preprocess_olive_weights` + `pack_qmoe_expert_weights` calls to rename and pack Olive-quantized decoder MoE expert weights into the native QMoE ONNX parameter layout (`target_moe_path=".mlp"`, matching the text-only sibling's `Qwen35MoEBlock` placement). - Explicit `NotImplementedError` guards for: - `quant_method` in `{"gptq", "awq"}` — not yet supported by this VL wrapper (only Olive-quantized checkpoints are handled today). - `quantize_embeddings` / `quantize_lm_head` — no quantized `Embedding`/`Linear` module variants are wired up anywhere in this 3-model split, so these flags previously produced orphaned initializers with no error. Both guards fail loudly instead of silently producing a broken export. - Honors `quantization.tie_word_embeddings` (not just `config.tie_word_embeddings`) when deciding whether to duplicate `lm_head` from `embed_tokens`, for internal consistency with the recovered "effective tie" value. ## Tests New `TestQwen35MoEVL3ModelQMoEExport` class covering: - QMoE packing/binding (Olive-quantized) - Dense fallback (unquantized) - Unsupported-ABI guard (packed-but-non-QMoE quantization) - Vision/embedding/MTP-routing preservation (unaffected by decoder quantization) - GPTQ/AWQ rejection (clear error) - Quantized-embeddings/lm_head rejection (clear error) ``` python -m pytest src/mobius/models/qwen35_test.py -v 10 passed ``` Full model suite: `python -m pytest src/mobius/models/ -q` → 401 passed, 3 pre-existing unrelated failures (confirmed present on clean `main`: `deepseek_v4_flash_test.py::test_ort_genai_sidecar_metadata`, `qwen_image_test.py::test_cuda_matches_cpu`, `world_model_test.py::test_mlp_world_model_matches_pytorch`). `ruff check` / `ruff format --check`: clean. ## Review This change went through a full internal review pass (readability, correctness, adversarial/critical, spec-adherence, and cross-module integration review, plus independent test execution) before being opened. Findings from that review (GPTQ/AWQ gap, quantized-embedding binding gap) are addressed via the explicit guards above rather than full implementations, since neither is needed by the current Olive→Mobius pipeline for Qwen3.6-35B-A3B. --------- Co-authored-by: Copilot <[email protected]> Copilot-Session: e10674c1-6909-4b09-9f5a-d41b28c89d2d
1 parent 5589243 commit 2481e3c

6 files changed

Lines changed: 727 additions & 132 deletions

File tree

‎src/mobius/_weight_utils.py‎

Lines changed: 198 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,40 @@
1616

1717
import logging
1818
import math
19-
from collections.abc import Sequence
19+
from collections.abc import Collection, Sequence
2020

2121
import torch
2222

23+
from mobius._configs import QuantizationConfig
24+
2325
logger = logging.getLogger(__name__)
2426

2527

28+
def supported_qmoe_quantization(
29+
quantization: QuantizationConfig | None,
30+
) -> QuantizationConfig | None:
31+
"""Return quantization settings when they match the native QMoE ABI.
32+
33+
Accepts the integer-affine int4 block schemes whose ``(q - zero_point) *
34+
scale`` dequantization is byte-identical to ``MatMulNBits`` and to the
35+
``com.microsoft::QMoE`` kernel: GPTQ, AWQ, and Olive RTN. The CUDA QMoE
36+
kernel requires a power-of-two ``block_size >= 16``; unsupported configs
37+
fall back to the portable dense representation instead of emitting an
38+
unrunnable node.
39+
"""
40+
if (
41+
quantization is None
42+
or quantization.bits != 4
43+
or quantization.float_zero_point
44+
or quantization.quant_method not in {"gptq", "awq", "olive"}
45+
):
46+
return None
47+
block_size = quantization.group_size
48+
if block_size < 16 or (block_size & (block_size - 1)) != 0:
49+
return None
50+
return quantization
51+
52+
2653
def merge_lora_weights(
2754
base_state_dict: dict[str, torch.Tensor],
2855
lora_state_dict: dict[str, torch.Tensor],
@@ -431,6 +458,11 @@ def tie_word_embeddings(
431458
table in the ONNX file, used by both the Gather (embedding lookup)
432459
and MatMul (LM head projection) nodes.
433460
461+
This also supports subclasses that replace ``self.model`` after
462+
:class:`CausalLMModel` construction (for example, Cohere and GPT-2-family
463+
models). Their embedding and head Parameters may initially be distinct,
464+
but the shared tensor storage lets weight loading unify them.
465+
434466
Mutates *state_dict* in place.
435467
436468
Args:
@@ -713,6 +745,8 @@ def preprocess_olive_weights(
713745
quantize_embeddings: bool = False,
714746
quantize_lm_head: bool = False,
715747
tie_word_embeddings: bool = False,
748+
embed_key: str = "model.embed_tokens.weight",
749+
head_key: str = "lm_head.weight",
716750
) -> dict[str, torch.Tensor]:
717751
"""Rename and reshape Olive-packed quantized weights.
718752
@@ -753,6 +787,8 @@ def preprocess_olive_weights(
753787
quantize_embeddings: Whether the embedding table is quantized.
754788
quantize_lm_head: Whether the LM head is quantized.
755789
tie_word_embeddings: Whether embedding and LM head share weights.
790+
embed_key: Float embedding key used for the tied-head fallback.
791+
head_key: Float LM-head key used for the tied-head fallback.
756792
757793
Returns:
758794
State dict with renamed and reshaped weights (and, for a float tied
@@ -849,10 +885,10 @@ def _rename(key: str, raw_suffix: str, dotted_name: str) -> str:
849885
if (
850886
tie_word_embeddings
851887
and not quantize_lm_head
852-
and "lm_head.weight" not in result
853-
and "model.embed_tokens.weight" in result
888+
and head_key not in result
889+
and embed_key in result
854890
):
855-
result["lm_head.weight"] = result["model.embed_tokens.weight"]
891+
result[head_key] = result[embed_key]
856892

857893
return result
858894

@@ -917,3 +953,161 @@ def preprocess_awq_weights(
917953
result[key] = value
918954

919955
return result
956+
957+
958+
def preprocess_quantized_weights(
959+
state_dict: dict[str, torch.Tensor],
960+
quantization: QuantizationConfig | None,
961+
*,
962+
tie_embeddings: bool = False,
963+
embed_key: str = "model.embed_tokens.weight",
964+
head_key: str = "lm_head.weight",
965+
qmoe_target_path: str | None = None,
966+
qmoe_quant_methods: Collection[str] = ("gptq", "awq", "olive"),
967+
reject_quantized_embeddings_lm_head: bool = False,
968+
) -> dict[str, torch.Tensor]:
969+
"""Apply shared quantization conversion, tying, and QMoE packing.
970+
971+
Args:
972+
state_dict: Weight dictionary to preprocess.
973+
quantization: Quantization format and packing settings, or ``None`` for
974+
float weights.
975+
tie_embeddings: Whether to alias missing float embedding/head weights.
976+
embed_key: Canonical float embedding-table key.
977+
head_key: Canonical float LM-head key.
978+
qmoe_target_path: MoE path replaced by packed QMoE parameter names.
979+
``None`` means this model does not support or require QMoE handling.
980+
qmoe_quant_methods: Quantization methods supported by this caller when
981+
the config matches the native QMoE ABI.
982+
reject_quantized_embeddings_lm_head: Reject packed embedding/head
983+
weights because the caller's graph requires float parameters.
984+
985+
Returns:
986+
The preprocessed weight dictionary.
987+
988+
GPTQ and AWQ conversion falls through to the shared float-tying and QMoE
989+
packing tail. Olive returns from its own branch because
990+
:func:`preprocess_olive_weights` must handle quantized embedding/head tying
991+
internally before optional QMoE packing.
992+
"""
993+
use_qmoe = (
994+
supported_qmoe_quantization(quantization) is not None
995+
if qmoe_target_path is not None
996+
else False
997+
)
998+
packed_suffixes = (
999+
"_qweight",
1000+
"_scales",
1001+
"_qzeros",
1002+
".qweight",
1003+
".scales",
1004+
".qzeros",
1005+
)
1006+
if (
1007+
use_qmoe
1008+
and quantization is not None
1009+
and quantization.quant_method not in qmoe_quant_methods
1010+
):
1011+
methods = tuple(qmoe_quant_methods)
1012+
if methods == ("olive",):
1013+
raise NotImplementedError(
1014+
"This model currently only supports QMoE export for "
1015+
"Olive-quantized checkpoints (quant_method='olive'); got "
1016+
f"quant_method={quantization.quant_method!r}. GPTQ/AWQ VL-MoE "
1017+
"export is not yet implemented."
1018+
)
1019+
raise NotImplementedError(
1020+
"This model supports QMoE export for quant_method values "
1021+
f"{methods!r}; got quant_method={quantization.quant_method!r}."
1022+
)
1023+
1024+
if qmoe_target_path is not None and not use_qmoe:
1025+
packed_expert_keys = [
1026+
key
1027+
for key in state_dict
1028+
if qmoe_target_path in key and ".experts." in key and key.endswith(packed_suffixes)
1029+
]
1030+
if packed_expert_keys:
1031+
raise ValueError(
1032+
"Quantized MoE expert weights were found for this model "
1033+
f"(e.g. {packed_expert_keys[0]!r}) but this quantization "
1034+
"config doesn't match the native QMoE ABI "
1035+
"(supported_qmoe_quantization returned None). The dense "
1036+
"loop-over-experts fallback only supports unquantized fused "
1037+
"expert tensors, not packed quantized ones. Use a "
1038+
"QMoE-ABI-compatible quantization config (see "
1039+
"supported_qmoe_quantization) for MoE models instead."
1040+
)
1041+
1042+
def _is_packed_key(key: str, float_key: str) -> bool:
1043+
owner = float_key.removesuffix(".weight")
1044+
return any(key == float_key + suffix for suffix in packed_suffixes[:3]) or any(
1045+
key == owner + suffix for suffix in packed_suffixes[3:]
1046+
)
1047+
1048+
packed_embedding_or_head = (
1049+
next(
1050+
(
1051+
key
1052+
for key in state_dict
1053+
if _is_packed_key(key, embed_key) or _is_packed_key(key, head_key)
1054+
),
1055+
None,
1056+
)
1057+
if reject_quantized_embeddings_lm_head
1058+
else None
1059+
)
1060+
configured_quantized_table = quantization is not None and (
1061+
quantization.quantize_embeddings or quantization.quantize_lm_head
1062+
)
1063+
if reject_quantized_embeddings_lm_head and (
1064+
configured_quantized_table or packed_embedding_or_head is not None
1065+
):
1066+
packed_key_detail = (
1067+
f" Packed checkpoint key {packed_embedding_or_head!r} was found."
1068+
if packed_embedding_or_head is not None
1069+
else ""
1070+
)
1071+
raise NotImplementedError(
1072+
"Quantized embeddings and LM heads are not yet supported by "
1073+
f"this model: {embed_key.removesuffix('.weight')}, "
1074+
f"{head_key.removesuffix('.weight')}, and related embedding "
1075+
f"initializers currently require float weights.{packed_key_detail}"
1076+
)
1077+
1078+
if quantization is not None and quantization.quant_method == "gptq":
1079+
state_dict = preprocess_gptq_weights(
1080+
state_dict, bits=quantization.bits, group_size=quantization.group_size
1081+
)
1082+
elif quantization is not None and quantization.quant_method == "awq":
1083+
state_dict = preprocess_awq_weights(
1084+
state_dict, bits=quantization.bits, group_size=quantization.group_size
1085+
)
1086+
elif quantization is not None and quantization.quant_method == "olive":
1087+
olive_tie = tie_embeddings or quantization.tie_word_embeddings
1088+
return_state_dict = preprocess_olive_weights(
1089+
state_dict,
1090+
bits=quantization.bits,
1091+
group_size=quantization.group_size,
1092+
quantize_embeddings=quantization.quantize_embeddings,
1093+
quantize_lm_head=quantization.quantize_lm_head,
1094+
tie_word_embeddings=olive_tie,
1095+
embed_key=embed_key,
1096+
head_key=head_key,
1097+
)
1098+
if use_qmoe and qmoe_target_path is not None:
1099+
return_state_dict = pack_qmoe_expert_weights(
1100+
return_state_dict, target_moe_path=qmoe_target_path
1101+
)
1102+
return return_state_dict
1103+
1104+
tied_quantized_table = (
1105+
quantization is not None
1106+
and quantization.quantize_embeddings
1107+
and quantization.quantize_lm_head
1108+
)
1109+
if tie_embeddings and not tied_quantized_table:
1110+
tie_word_embeddings(state_dict, embed_key=embed_key, head_key=head_key)
1111+
if use_qmoe and qmoe_target_path is not None:
1112+
state_dict = pack_qmoe_expert_weights(state_dict, target_moe_path=qmoe_target_path)
1113+
return state_dict

‎src/mobius/_weight_utils_test.py‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
import pytest
99
import torch
1010

11+
from mobius._configs import QuantizationConfig
1112
from mobius._weight_utils import (
1213
merge_lora_weights,
1314
preprocess_awq_weights,
1415
preprocess_gptq_weights,
1516
preprocess_olive_weights,
17+
preprocess_quantized_weights,
1618
rename_weight_keys,
1719
split_codegen_qkv,
1820
split_fused_qkv,
@@ -760,6 +762,19 @@ def test_float_tie_fallback(self):
760762
)
761763
assert result["lm_head.weight"] is embed
762764

765+
def test_float_tie_fallback_uses_custom_keys(self):
766+
embed = torch.randn(self.V, self.K)
767+
result = preprocess_olive_weights(
768+
{"decoder.model.embed_tokens.weight": embed},
769+
bits=self.BITS,
770+
group_size=self.GROUP_SIZE,
771+
tie_word_embeddings=True,
772+
embed_key="decoder.model.embed_tokens.weight",
773+
head_key="decoder.lm_head.weight",
774+
)
775+
assert result["decoder.lm_head.weight"] is embed
776+
assert "lm_head.weight" not in result
777+
763778
def test_untied_quantized_lm_head_not_overwritten(self):
764779
"""A present lm_head.weight_qweight must not be replaced by embed synthesis."""
765780
lm_head = torch.randint(0, 255, (self.V, self.PACKED_K), dtype=torch.uint8)
@@ -924,6 +939,110 @@ def test_missing_qweight_raises(self):
924939
preprocess_awq_weights(sd, bits=self.BITS, group_size=self.GROUP_SIZE)
925940

926941

942+
class TestPreprocessQuantizedWeights:
943+
@pytest.mark.parametrize("quant_method", ["gptq", "awq", "olive"])
944+
def test_dispatches_quantization_method(self, quant_method):
945+
quantization = QuantizationConfig(bits=4, group_size=16, quant_method=quant_method)
946+
if quant_method == "olive":
947+
state_dict = {"layer.weight_qweight": torch.zeros(8, 16, dtype=torch.uint8)}
948+
else:
949+
state_dict = {"layer.qweight": torch.zeros(4, 8, dtype=torch.int32)}
950+
951+
result = preprocess_quantized_weights(state_dict, quantization)
952+
953+
assert result["layer.weight"].shape == (8, 2, 8)
954+
955+
@pytest.mark.parametrize(
956+
"suffix",
957+
["_qweight", "_scales", "_qzeros", ".qweight", ".scales", ".qzeros"],
958+
)
959+
def test_rejects_packed_experts_for_unsupported_qmoe_abi(self, suffix):
960+
quantization = QuantizationConfig(bits=8, group_size=16, quant_method="olive")
961+
state_dict = {
962+
f"decoder.model.layers.0.mlp.experts.gate_up_proj{suffix}": torch.zeros(1)
963+
}
964+
965+
with pytest.raises(ValueError, match="QMoE ABI"):
966+
preprocess_quantized_weights(
967+
state_dict,
968+
quantization,
969+
qmoe_target_path=".mlp",
970+
)
971+
972+
def test_rejects_unsupported_qmoe_quantization_method(self):
973+
quantization = QuantizationConfig(bits=4, group_size=16, quant_method="gptq")
974+
with pytest.raises(NotImplementedError, match="only supports QMoE export"):
975+
preprocess_quantized_weights(
976+
{},
977+
quantization,
978+
qmoe_target_path=".mlp",
979+
qmoe_quant_methods=("olive",),
980+
)
981+
982+
@pytest.mark.parametrize("flag", ["quantize_embeddings", "quantize_lm_head"])
983+
def test_rejects_quantized_embedding_or_lm_head(self, flag):
984+
quantization = QuantizationConfig(
985+
bits=4,
986+
group_size=16,
987+
quant_method="olive",
988+
**{flag: True},
989+
)
990+
with pytest.raises(NotImplementedError, match="Quantized embeddings and LM heads"):
991+
preprocess_quantized_weights(
992+
{},
993+
quantization,
994+
reject_quantized_embeddings_lm_head=True,
995+
)
996+
997+
@pytest.mark.parametrize(
998+
("float_key", "suffix"),
999+
[
1000+
(float_key, suffix)
1001+
for float_key in (
1002+
"decoder.model.embed_tokens.weight",
1003+
"decoder.lm_head.weight",
1004+
)
1005+
for suffix in (
1006+
"_qweight",
1007+
"_scales",
1008+
"_qzeros",
1009+
".qweight",
1010+
".scales",
1011+
".qzeros",
1012+
)
1013+
],
1014+
)
1015+
def test_rejects_packed_embedding_or_head_key_without_config_flags(
1016+
self, float_key, suffix
1017+
):
1018+
owner = float_key.removesuffix(".weight")
1019+
packed_key = float_key + suffix if suffix.startswith("_") else owner + suffix
1020+
quantization = QuantizationConfig(bits=4, group_size=16, quant_method="gptq")
1021+
1022+
with pytest.raises(NotImplementedError, match="Packed checkpoint key") as error:
1023+
preprocess_quantized_weights(
1024+
{packed_key: torch.zeros(1)},
1025+
quantization,
1026+
reject_quantized_embeddings_lm_head=True,
1027+
embed_key="decoder.model.embed_tokens.weight",
1028+
head_key="decoder.lm_head.weight",
1029+
)
1030+
1031+
assert packed_key in str(error.value)
1032+
1033+
def test_ties_custom_float_keys(self):
1034+
embedding = torch.randn(8, 16)
1035+
result = preprocess_quantized_weights(
1036+
{"decoder.model.embed_tokens.weight": embedding},
1037+
None,
1038+
tie_embeddings=True,
1039+
embed_key="decoder.model.embed_tokens.weight",
1040+
head_key="decoder.lm_head.weight",
1041+
)
1042+
1043+
assert result["decoder.lm_head.weight"] is embedding
1044+
1045+
9271046
class TestMergeLoraWeights:
9281047
"""Tests for merge_lora_weights()."""
9291048

0 commit comments

Comments
 (0)