Skip to content

Commit 9df971f

Browse files
titaiwangmsCopilot
andcommitted
Fix Copilot review findings: share-buffer guard, QMoE fallback, embed quantize flag
Three follow-up fixes responding to GitHub Copilot's automated review of #495: - auto_export.py: the past_present_share_buffer guard incorrectly dropped its check when any GQA node existed anywhere in the graph, even though a separate unfused standard Attention node still coexisted (partial GQA fusion). A GQA node on one layer doesn't make a standard Attention node on another layer safe for a shared buffer. Removed the `not has_gqa` short-circuit so any standard Attention node co-existing with recurrent state is unconditionally rejected. - qwen35.py: Qwen35MoECausalLMModel.preprocess_weights's dense loop-over- experts fallback only knows how to unfuse *unquantized* float gate_up_proj/down_proj tensors. When quantization is present but doesn't match the native QMoE ABI, Olive's packed *_qweight/_scales/_qzeros keys stay fused and were silently passed through unchanged, producing a graph whose per-expert Linear modules expect keys that were never generated. Now raises a clear ValueError instead of emitting an unloadable graph. - _weight_utils.py: preprocess_olive_weights's embed_tokens branches matched purely on key suffix, ignoring the quantize_embeddings flag entirely. Now gated on quantize_embeddings, with an explicit error for a caller/state-dict mismatch instead of silently misrouting through the generic Linear renaming path (which would incorrectly 3-D reshape the 2-D embedding qweight table). Added regression tests for all three fixes. Co-authored-by: Copilot <[email protected]>
1 parent 831a4a2 commit 9df971f

6 files changed

Lines changed: 136 additions & 11 deletions

File tree

‎src/mobius/_weight_utils.py‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -778,7 +778,25 @@ def _rename(key: str, raw_suffix: str, dotted_name: str) -> str:
778778
return f"{stem}.{dotted_name}"
779779

780780
for key, value in state_dict.items():
781-
if key.endswith("embed_tokens.weight_qweight"):
781+
is_embed_qweight = key.endswith("embed_tokens.weight_qweight")
782+
is_embed_qzeros = key.endswith("embed_tokens.weight_qzeros")
783+
is_embed_scales = key.endswith("embed_tokens.weight_scales")
784+
if (
785+
is_embed_qweight or is_embed_qzeros or is_embed_scales
786+
) and not quantize_embeddings:
787+
# These Olive keys only exist when the embedding table itself was
788+
# quantized; ``quantize_embeddings=False`` means the caller
789+
# expects a float embedding, so a packed embedding key showing up
790+
# anyway indicates a caller/config mismatch rather than a case to
791+
# silently reroute through the generic Linear renaming below
792+
# (which would wrongly 3-D reshape ``qweight`` and break
793+
# ``GatherBlockQuantized``'s 2-D contract).
794+
raise ValueError(
795+
f"Found packed embedding quantization key {key!r} but "
796+
"quantize_embeddings=False; the caller's quantize_embeddings "
797+
"flag doesn't match the state dict."
798+
)
799+
if is_embed_qweight and quantize_embeddings:
782800
# GatherBlockQuantized consumes the 2-D uint8 table directly, so
783801
# this keeps the ``qweight`` name (unlike MatMulNBits linears,
784802
# which rename to ``weight`` below).
@@ -792,13 +810,13 @@ def _rename(key: str, raw_suffix: str, dotted_name: str) -> str:
792810
f"({value.shape[-1]}) must be divisible by blob_size ({blob_size})"
793811
)
794812
result[key[: -len("weight_qweight")] + "qweight"] = value.contiguous()
795-
elif key.endswith("embed_tokens.weight_qzeros"):
813+
elif is_embed_qzeros and quantize_embeddings:
796814
if value.dtype != torch.uint8:
797815
raise ValueError(
798816
f"Olive embedding qzeros must be uint8 for {key}, got {value.dtype}"
799817
)
800818
result[key[: -len("weight_qzeros")] + "zero_points"] = value.contiguous()
801-
elif key.endswith("embed_tokens.weight_scales"):
819+
elif is_embed_scales and quantize_embeddings:
802820
result[key[: -len("weight_scales")] + "scales"] = value
803821
elif key.endswith("_qweight"):
804822
if value.dtype != torch.uint8:

‎src/mobius/_weight_utils_test.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,9 @@ def test_embed_non_uint8_qweight_raises(self):
689689
)
690690
}
691691
with pytest.raises(ValueError, match="Olive embedding qweight must be uint8"):
692-
preprocess_olive_weights(sd, bits=self.BITS, group_size=self.GROUP_SIZE)
692+
preprocess_olive_weights(
693+
sd, bits=self.BITS, group_size=self.GROUP_SIZE, quantize_embeddings=True
694+
)
693695

694696
def test_embed_non_uint8_qzeros_raises(self):
695697
sd = {
@@ -698,7 +700,28 @@ def test_embed_non_uint8_qzeros_raises(self):
698700
)
699701
}
700702
with pytest.raises(ValueError, match="Olive embedding qzeros must be uint8"):
701-
preprocess_olive_weights(sd, bits=self.BITS, group_size=self.GROUP_SIZE)
703+
preprocess_olive_weights(
704+
sd, bits=self.BITS, group_size=self.GROUP_SIZE, quantize_embeddings=True
705+
)
706+
707+
def test_embed_qweight_with_quantize_embeddings_false_raises(self):
708+
"""quantize_embeddings=False must not silently accept a packed embedding key.
709+
710+
Regression test: previously this branch matched on key suffix alone
711+
and ignored ``quantize_embeddings`` entirely, so a caller/config
712+
mismatch (a packed embedding key present while the caller declares
713+
the embedding float) would either sneak through unnoticed or, worse,
714+
get incorrectly reshaped/renamed via the generic Linear branch.
715+
"""
716+
sd = {
717+
"model.embed_tokens.weight_qweight": torch.randint(
718+
0, 255, (self.V, self.PACKED_K), dtype=torch.uint8
719+
)
720+
}
721+
with pytest.raises(ValueError, match="quantize_embeddings=False"):
722+
preprocess_olive_weights(
723+
sd, bits=self.BITS, group_size=self.GROUP_SIZE, quantize_embeddings=False
724+
)
702725

703726
# --- Tied LM head synthesis ---
704727

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1044,16 +1044,21 @@ def _write_genai_config(
10441044
node.op_type == "Attention" and node.domain in ("", "ai.onnx")
10451045
for node in decoder_model.graph
10461046
)
1047-
if has_recurrent_state and has_standard_attention and not has_gqa:
1047+
if has_recurrent_state and has_standard_attention:
1048+
# A GQA node elsewhere in the graph does NOT make a co-existing
1049+
# standard Attention node compatible with a shared buffer --
1050+
# each op instance is independently (in)compatible, so this
1051+
# must reject on the mere presence of standard Attention, not
1052+
# only when GQA is completely absent (partial GQA fusion still
1053+
# leaves the unfused standard Attention layers broken).
10481054
raise ValueError(
10491055
"This decoder graph mixes com.microsoft.LinearAttention "
10501056
"(recurrent state, requires past_present_share_buffer=True) "
10511057
"with standard (non-GQA) Attention (incompatible with "
1052-
"past_present_share_buffer=True), and no GroupQueryAttention "
1053-
"node was found. This EP/dtype combination cannot produce a "
1054-
"runnable genai_config -- pick an EP/dtype that lowers full "
1055-
"attention to GroupQueryAttention instead (e.g. fp32 on the "
1056-
"CPU EP)."
1058+
"past_present_share_buffer=True). This EP/dtype combination "
1059+
"cannot produce a runnable genai_config -- pick an EP/dtype "
1060+
"that lowers *all* full-attention layers to "
1061+
"GroupQueryAttention instead (e.g. fp32 on the CPU EP)."
10571062
)
10581063
supports_in_place_kv_cache = has_gqa or has_recurrent_state
10591064

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2312,6 +2312,26 @@ def test_recurrent_state_with_gqa_does_not_raise(self, tmp_path):
23122312
data = json.load(f)
23132313
assert data["search"]["past_present_share_buffer"] is True
23142314

2315+
def test_recurrent_state_with_standard_attention_and_gqa_raises(self, tmp_path):
2316+
"""Partial GQA fusion still leaves an incompatible standard Attention node.
2317+
2318+
Regression test: the guard previously read
2319+
``has_recurrent_state and has_standard_attention and not has_gqa``, so
2320+
a GQA node present *anywhere* in the graph would short-circuit the
2321+
check even though a separate, unfused standard Attention node
2322+
coexists. A GQA node on one layer doesn't make a standard Attention
2323+
node on another layer safe for ``past_present_share_buffer=True``.
2324+
"""
2325+
pkg = self._make_pkg(
2326+
[
2327+
("LinearAttention", "com.microsoft"),
2328+
("GroupQueryAttention", "com.microsoft"),
2329+
("Attention", ""),
2330+
],
2331+
)
2332+
with pytest.raises(ValueError, match="past_present_share_buffer"):
2333+
self._write(pkg, tmp_path)
2334+
23152335
def test_recurrent_state_only_does_not_raise(self, tmp_path):
23162336
"""LinearAttention with no full-attention layers at all is unaffected."""
23172337
pkg = self._make_pkg([("LinearAttention", "com.microsoft")])

‎src/mobius/models/qwen35.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,40 @@ def preprocess_weights(
395395
# instead of un-fusing into per-expert MLPs. Uses the same predicate
396396
# as MoELayer so the weights and the emitted graph never disagree.
397397
use_qmoe = _supported_qmoe_quantization(self.config.quantization) is not None
398+
if not use_qmoe:
399+
# The dense per-expert fallback (MoELayer.experts) only knows how
400+
# to consume *unquantized* fused expert tensors -- the split
401+
# below un-fuses a bare float [num_experts, ...] tensor into
402+
# per-expert nn.Linear-shaped weights. If quantization produced
403+
# packed Olive tensors here (suffixed "_qweight"/"_scales"/
404+
# "_qzeros", see preprocess_olive_weights) but the quantization
405+
# config doesn't match the native QMoE ABI, there is no code path
406+
# that splits a *packed* fused expert tensor into per-expert
407+
# quantized Linear initializers -- silently falling through would
408+
# emit a graph whose per-expert Linear modules request
409+
# "experts.N.{gate,up}_proj.weight_qweight" keys that were never
410+
# produced, since the packed tensor stays fused under
411+
# "experts.gate_up_proj_qweight" instead. Reject explicitly
412+
# rather than emit an unloadable graph.
413+
packed_expert_keys = [
414+
key
415+
for key in state_dict
416+
if ".mlp.experts." in key
417+
and any(key.endswith(suffix) for suffix in ("_qweight", "_scales", "_qzeros"))
418+
]
419+
if packed_expert_keys:
420+
raise ValueError(
421+
"Quantized MoE expert weights were found "
422+
f"(e.g. {packed_expert_keys[0]!r}) but this quantization "
423+
"config doesn't match the native QMoE ABI "
424+
"(_supported_qmoe_quantization returned None). The dense "
425+
"loop-over-experts fallback only supports unquantized "
426+
"fused expert tensors, not packed quantized ones -- "
427+
"there is no path to un-fuse a packed expert tensor into "
428+
"per-expert quantized Linear initializers. Use a "
429+
"QMoE-ABI-compatible quantization config (see "
430+
"_supported_qmoe_quantization) for MoE models instead."
431+
)
398432
cleaned: dict[str, torch.Tensor] = {}
399433
for key, value in state_dict.items():
400434
if key.startswith(("mtp_", "mtp.")):

‎src/mobius/models/qwen35_test.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,28 @@ def test_unquantized_preprocess_unfuses_dense_fallback(self):
126126
_INT,
127127
)
128128
assert not any("fc1_experts_weights" in k for k in out)
129+
130+
def test_unsupported_qmoe_quantization_with_packed_experts_raises(self):
131+
"""Packed quantized expert weights + an unsupported QMoE ABI must raise.
132+
133+
Regression test: ``group_size=24`` (not a power of two) makes
134+
``_supported_qmoe_quantization`` reject the config, so
135+
``preprocess_weights`` takes the dense-fallback branch. But that
136+
branch's fused-tensor unfuser only knows how to split *unquantized*
137+
float ``experts.gate_up_proj``/``experts.down_proj`` tensors -- there
138+
is no code path that splits packed ``_qweight``/``_scales``/
139+
``_qzeros`` fused-expert tensors into per-expert quantized Linear
140+
initializers. Previously this silently fell through to
141+
``cleaned[key] = value`` and produced a graph whose per-expert
142+
Linear modules expect keys that were never generated.
143+
"""
144+
config = _moe_config(
145+
QuantizationConfig(bits=8, group_size=_BLK, quant_method="olive", sym=False)
146+
)
147+
model = Qwen35MoECausalLMModel(config)
148+
try:
149+
model.preprocess_weights(_olive_expert_state_dict())
150+
except ValueError as e:
151+
assert "QMoE ABI" in str(e)
152+
else:
153+
raise AssertionError("expected ValueError for unsupported QMoE + packed experts")

0 commit comments

Comments
 (0)