Skip to content

Commit 1a88a3c

Browse files
committed
fix(weight_utils): match Olive's underscore quantized-weight suffix convention
preprocess_olive_weights() assumed a dotted suffix convention (<pname>.qweight/.scales/.qzeros) that never matches Olive's actual on-disk keys, which use an underscore suffix appended directly to the owning parameter name (<pname>_qweight/_scales/_qzeros, e.g. "...gate_proj.weight_qweight" or "...experts.gate_up_proj_qweight" -- see olive/common/quant/state_dict.py). Every endswith/replace check in this function silently failed to match, so any real Olive-quantized checkpoint fell through to the "pass through unchanged" branch instead of being renamed/reshaped for MatMulNBits/GatherBlockQuantized/QMoE consumption, and was missing an explicit rename branch for `_scales` entirely. This was flagged (for a different, narrower symptom) in #427, which scoped itself to a defensive ndim==2 guard for RTN's older moe=True 3-D case and left "real MoE quantization support" for a follow-up. #451 added that follow-up (QMoE emission for Qwen3.5/3.6-MoE), but its projections dict and `preprocess_olive_weights` reshape logic were themselves written against the same incorrect dotted-suffix assumption, so they never actually exercised a real Olive checkpoint end-to-end. Repro: chaining Olive's Rtn(moe=true) -> MobiusBuilder against yujiepan/qwen3.5-moe-tiny-random surfaced "N initializer(s) without weights" at save time, because every quantized nn.Linear/nn.Embedding key in the checkpoint (attention/MLP projections, embeddings) failed to match and was left un-renamed. Fix: introduce a `_rename` helper that strips the underscore suffix, drops a redundant trailing ".weight" component (present for regular nn.Linear/nn.Embedding parameters but not for bare fused-MoE parameters like "gate_up_proj"), and appends the target dotted name. Update the embed_tokens special case (which keeps the "qweight" name for GatherBlockQuantized instead of renaming to "weight") accordingly, and add the previously-missing "_scales" rename branch for the general (non-embedding) case. Update tests in _weight_utils_test.py/qwen35_test.py/_moe_test.py that had been written against the same incorrect fixture convention. Note: this fixes weight *naming*, not quantization *coverage*. Qwen3.5's Qwen35Attention/GatedDeltaNet/MLP call sites still hardcode plain Linear regardless of config.quantization (only the MoE fused-expert path added in #451 threads through quantization), so self_attn/linear_attn/MLP weights in a quantized Qwen3.5/3.6 checkpoint still fail to load with a shape mismatch after this fix. Tracked separately.
1 parent 01008cf commit 1a88a3c

5 files changed

Lines changed: 114 additions & 52 deletions

File tree

‎src/mobius/_weight_utils.py‎

Lines changed: 50 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -716,19 +716,29 @@ def preprocess_olive_weights(
716716
) -> dict[str, torch.Tensor]:
717717
"""Rename and reshape Olive-packed quantized weights.
718718
719-
Olive stores quantized weights with uint8 packing:
720-
- ``*.qweight``: [N, packed_K] uint8
721-
- ``*.scales``: [N, n_blocks]
722-
- ``*.qzeros``: [N, ceil(n_blocks * bits / 8)] uint8, asymmetric only
719+
Olive stores the quantized state of a parameter named ``<pname>`` (e.g.
720+
``"weight"`` for ``nn.Linear``/``nn.Embedding``, or ``"gate_up_proj"`` for
721+
a fused-3D MoE expert parameter) as sibling buffers on the owning module,
722+
using an *underscore* suffix convention (see Olive's
723+
``olive/common/quant/state_dict.py``) — **not** a dotted one:
724+
- ``<pname>_qweight``: [N, packed_K] uint8 (always present)
725+
- ``<pname>_scales``: [N, n_blocks] (always present)
726+
- ``<pname>_qzeros``: [N, ceil(n_blocks * bits / 8)] uint8 (asymmetric only)
727+
728+
e.g. ``model.layers.0.mlp.gate_proj.weight_qweight`` (regular ``nn.Linear``)
729+
or ``model.layers.0.mlp.experts.gate_up_proj_qweight`` (fused MoE param,
730+
no ``.weight`` component since the parameter itself has no nested Linear).
723731
724732
Linear projections target ``MatMulNBits``, which expects ``weight`` as
725733
[N, n_blocks, blob_size]; scales and zero-points already match the
726734
expected orientation, so they are renamed but not transposed.
727735
728-
The input embedding table (``*.embed_tokens.qweight``) instead targets
729-
``GatherBlockQuantized``, which consumes the **2-D** uint8 ``qweight``
730-
directly — so it is kept as-is (only ``qzeros`` is renamed to
731-
``zero_points``).
736+
The input embedding table (``*.embed_tokens.weight_qweight``) instead
737+
targets ``GatherBlockQuantized``, which consumes the **2-D** uint8
738+
``qweight`` directly — so it is renamed to ``*.embed_tokens.qweight``
739+
(dropping only the redundant ``weight`` component, not the ``qweight``
740+
name itself); ``qzeros``/``scales`` are renamed the same way as the
741+
general case below.
732742
733743
Tied LM head: Olive RTN drops ``lm_head.*`` when the head is tied. When the
734744
head is **quantized**, no ``lm_head`` weights are produced here — the model
@@ -751,9 +761,27 @@ def preprocess_olive_weights(
751761
blob_size = group_size * bits // 8
752762
result: dict[str, torch.Tensor] = {}
753763

764+
def _rename(key: str, raw_suffix: str, dotted_name: str) -> str:
765+
"""Convert an Olive ``<owner>[.weight]{raw_suffix}`` key to ``<owner>.<dotted_name>``.
766+
767+
Olive's ``pname`` is either the bare ``"weight"`` parameter of an
768+
``nn.Linear``/``nn.Embedding`` (so the raw key carries a redundant
769+
``.weight`` component before the suffix, e.g. ``...gate_proj.weight_qweight``)
770+
or a fused MoE parameter with no nested Linear (e.g.
771+
``...experts.gate_up_proj_qweight``). Strip the suffix, drop a
772+
trailing ``.weight`` if present, then append ``.<dotted_name>`` so
773+
both shapes land on a single canonical ``<owner>.<dotted_name>`` key.
774+
"""
775+
stem = key[: -len(raw_suffix)]
776+
if stem.endswith(".weight"):
777+
stem = stem[: -len(".weight")]
778+
return f"{stem}.{dotted_name}"
779+
754780
for key, value in state_dict.items():
755-
if key.endswith("embed_tokens.qweight"):
756-
# GatherBlockQuantized consumes the 2-D uint8 table directly.
781+
if key.endswith("embed_tokens.weight_qweight"):
782+
# GatherBlockQuantized consumes the 2-D uint8 table directly, so
783+
# this keeps the ``qweight`` name (unlike MatMulNBits linears,
784+
# which rename to ``weight`` below).
757785
if value.dtype != torch.uint8:
758786
raise ValueError(
759787
f"Olive embedding qweight must be uint8 for {key}, got {value.dtype}"
@@ -763,34 +791,37 @@ def preprocess_olive_weights(
763791
f"Olive embedding qweight packed dimension for {key} "
764792
f"({value.shape[-1]}) must be divisible by blob_size ({blob_size})"
765793
)
766-
result[key] = value.contiguous()
767-
elif key.endswith("embed_tokens.qzeros"):
794+
result[key[: -len("weight_qweight")] + "qweight"] = value.contiguous()
795+
elif key.endswith("embed_tokens.weight_qzeros"):
768796
if value.dtype != torch.uint8:
769797
raise ValueError(
770798
f"Olive embedding qzeros must be uint8 for {key}, got {value.dtype}"
771799
)
772-
result[key.replace(".qzeros", ".zero_points")] = value.contiguous()
773-
elif key.endswith("embed_tokens.scales"):
774-
result[key] = value
775-
elif key.endswith(".qweight"):
800+
result[key[: -len("weight_qzeros")] + "zero_points"] = value.contiguous()
801+
elif key.endswith("embed_tokens.weight_scales"):
802+
result[key[: -len("weight_scales")] + "scales"] = value
803+
elif key.endswith("_qweight"):
776804
if value.dtype != torch.uint8:
777805
raise ValueError(f"Olive qweight must be uint8 for {key}, got {value.dtype}")
778806
if value.shape[-1] % blob_size != 0:
779807
raise ValueError(
780808
f"Olive qweight packed dimension for {key} ({value.shape[-1]}) "
781809
f"must be divisible by blob_size ({blob_size})"
782810
)
783-
new_key = key.replace(".qweight", ".weight")
811+
new_key = _rename(key, "_qweight", "weight")
784812
# Preserve all leading dims so fused expert-major tensors
785813
# ``[E, N, packed_K]`` reshape to ``[E, N, n_blocks, blob_size]``
786814
# for the QMoE repacker; 2-D linears ``[N, packed_K]`` are
787815
# unchanged (``[N, n_blocks, blob_size]``).
788816
result[new_key] = value.reshape(*value.shape[:-1], -1, blob_size).contiguous()
789-
elif key.endswith(".qzeros"):
817+
elif key.endswith("_qzeros"):
790818
if value.dtype != torch.uint8:
791819
raise ValueError(f"Olive qzeros must be uint8 for {key}, got {value.dtype}")
792-
new_key = key.replace(".qzeros", ".zero_points")
820+
new_key = _rename(key, "_qzeros", "zero_points")
793821
result[new_key] = value.contiguous()
822+
elif key.endswith("_scales"):
823+
new_key = _rename(key, "_scales", "scales")
824+
result[new_key] = value
794825
else:
795826
result[key] = value
796827

‎src/mobius/_weight_utils_test.py‎

Lines changed: 43 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -574,21 +574,43 @@ class TestPreprocessOliveWeights:
574574

575575
def test_qweight_renamed_and_reshaped_to_matmulnbits_weight(self):
576576
sd = {
577-
"q_proj.qweight": torch.randint(0, 255, (self.N, self.PACKED_K), dtype=torch.uint8)
577+
"q_proj.weight_qweight": torch.randint(
578+
0, 255, (self.N, self.PACKED_K), dtype=torch.uint8
579+
)
578580
}
579581

580582
result = preprocess_olive_weights(sd, bits=self.BITS, group_size=self.GROUP_SIZE)
581583

582584
assert "q_proj.weight" in result
583-
assert "q_proj.qweight" not in result
585+
assert "q_proj.weight_qweight" not in result
584586
assert result["q_proj.weight"].shape == (self.N, self.N_BLOCKS, self.BLOB_SIZE)
585587
assert result["q_proj.weight"].dtype == torch.uint8
586588

589+
def test_fused_moe_qweight_renamed_and_reshaped(self):
590+
"""Fused MoE expert params (no nested ``.weight``) get ``.weight`` appended."""
591+
num_experts = 4
592+
sd = {
593+
"mlp.experts.gate_up_proj_qweight": torch.randint(
594+
0, 255, (num_experts, self.N, self.PACKED_K), dtype=torch.uint8
595+
)
596+
}
597+
598+
result = preprocess_olive_weights(sd, bits=self.BITS, group_size=self.GROUP_SIZE)
599+
600+
assert "mlp.experts.gate_up_proj.weight" in result
601+
assert "mlp.experts.gate_up_proj_qweight" not in result
602+
assert result["mlp.experts.gate_up_proj.weight"].shape == (
603+
num_experts,
604+
self.N,
605+
self.N_BLOCKS,
606+
self.BLOB_SIZE,
607+
)
608+
587609
def test_scales_orientation_is_preserved(self):
588610
scales = torch.randn(self.N, self.N_BLOCKS)
589611

590612
result = preprocess_olive_weights(
591-
{"q_proj.scales": scales}, bits=self.BITS, group_size=self.GROUP_SIZE
613+
{"q_proj.weight_scales": scales}, bits=self.BITS, group_size=self.GROUP_SIZE
592614
)
593615

594616
assert result["q_proj.scales"] is scales
@@ -597,11 +619,11 @@ def test_qzeros_renamed_to_zero_points_without_reshape(self):
597619
qzeros = torch.randint(0, 255, (self.N, self.N_BLOCKS // 2), dtype=torch.uint8)
598620

599621
result = preprocess_olive_weights(
600-
{"q_proj.qzeros": qzeros}, bits=self.BITS, group_size=self.GROUP_SIZE
622+
{"q_proj.weight_qzeros": qzeros}, bits=self.BITS, group_size=self.GROUP_SIZE
601623
)
602624

603625
assert "q_proj.zero_points" in result
604-
assert "q_proj.qzeros" not in result
626+
assert "q_proj.weight_qzeros" not in result
605627
assert torch.equal(result["q_proj.zero_points"], qzeros)
606628

607629
def test_non_quantized_keys_pass_through(self):
@@ -615,15 +637,17 @@ def test_non_quantized_keys_pass_through(self):
615637

616638
def test_non_uint8_qweight_raises(self):
617639
sd = {
618-
"q_proj.qweight": torch.randint(0, 255, (self.N, self.PACKED_K), dtype=torch.int32)
640+
"q_proj.weight_qweight": torch.randint(
641+
0, 255, (self.N, self.PACKED_K), dtype=torch.int32
642+
)
619643
}
620644

621645
with pytest.raises(ValueError, match="Olive qweight must be uint8"):
622646
preprocess_olive_weights(sd, bits=self.BITS, group_size=self.GROUP_SIZE)
623647

624648
def test_non_uint8_qzeros_raises(self):
625649
sd = {
626-
"q_proj.qzeros": torch.randint(
650+
"q_proj.weight_qzeros": torch.randint(
627651
0, 255, (self.N, self.N_BLOCKS // 2), dtype=torch.int32
628652
)
629653
}
@@ -635,10 +659,10 @@ def test_non_uint8_qzeros_raises(self):
635659
V = 64 # vocab size for embedding tests
636660

637661
def test_embed_qweight_kept_2d(self):
638-
"""embed_tokens.qweight targets GatherBlockQuantized: keep 2-D uint8."""
662+
"""embed_tokens.weight_qweight targets GatherBlockQuantized: keep 2-D uint8."""
639663
qweight = torch.randint(0, 255, (self.V, self.PACKED_K), dtype=torch.uint8)
640664
result = preprocess_olive_weights(
641-
{"model.embed_tokens.qweight": qweight},
665+
{"model.embed_tokens.weight_qweight": qweight},
642666
bits=self.BITS,
643667
group_size=self.GROUP_SIZE,
644668
quantize_embeddings=True,
@@ -650,17 +674,17 @@ def test_embed_qweight_kept_2d(self):
650674
def test_embed_qzeros_renamed_to_zero_points(self):
651675
qzeros = torch.randint(0, 255, (self.V, self.N_BLOCKS // 2), dtype=torch.uint8)
652676
result = preprocess_olive_weights(
653-
{"model.embed_tokens.qzeros": qzeros},
677+
{"model.embed_tokens.weight_qzeros": qzeros},
654678
bits=self.BITS,
655679
group_size=self.GROUP_SIZE,
656680
quantize_embeddings=True,
657681
)
658682
assert "model.embed_tokens.zero_points" in result
659-
assert "model.embed_tokens.qzeros" not in result
683+
assert "model.embed_tokens.weight_qzeros" not in result
660684

661685
def test_embed_non_uint8_qweight_raises(self):
662686
sd = {
663-
"model.embed_tokens.qweight": torch.randint(
687+
"model.embed_tokens.weight_qweight": torch.randint(
664688
0, 255, (self.V, self.PACKED_K), dtype=torch.int32
665689
)
666690
}
@@ -669,7 +693,7 @@ def test_embed_non_uint8_qweight_raises(self):
669693

670694
def test_embed_non_uint8_qzeros_raises(self):
671695
sd = {
672-
"model.embed_tokens.qzeros": torch.randint(
696+
"model.embed_tokens.weight_qzeros": torch.randint(
673697
0, 255, (self.V, self.N_BLOCKS // 2), dtype=torch.int32
674698
)
675699
}
@@ -688,9 +712,9 @@ def test_tied_quantized_head_produces_no_lm_head_keys(self):
688712
qzeros = torch.randint(0, 255, (self.V, self.N_BLOCKS // 2), dtype=torch.uint8)
689713
result = preprocess_olive_weights(
690714
{
691-
"model.embed_tokens.qweight": qweight,
692-
"model.embed_tokens.scales": scales,
693-
"model.embed_tokens.qzeros": qzeros,
715+
"model.embed_tokens.weight_qweight": qweight,
716+
"model.embed_tokens.weight_scales": scales,
717+
"model.embed_tokens.weight_qzeros": qzeros,
694718
},
695719
bits=self.BITS,
696720
group_size=self.GROUP_SIZE,
@@ -714,13 +738,13 @@ def test_float_tie_fallback(self):
714738
assert result["lm_head.weight"] is embed
715739

716740
def test_untied_quantized_lm_head_not_overwritten(self):
717-
"""A present lm_head.qweight must not be replaced by embed synthesis."""
741+
"""A present lm_head.weight_qweight must not be replaced by embed synthesis."""
718742
lm_head = torch.randint(0, 255, (self.V, self.PACKED_K), dtype=torch.uint8)
719743
embed = torch.randint(0, 255, (self.V, self.PACKED_K), dtype=torch.uint8)
720744
result = preprocess_olive_weights(
721745
{
722-
"lm_head.qweight": lm_head,
723-
"model.embed_tokens.qweight": embed,
746+
"lm_head.weight_qweight": lm_head,
747+
"model.embed_tokens.weight_qweight": embed,
724748
},
725749
bits=self.BITS,
726750
group_size=self.GROUP_SIZE,

‎src/mobius/components/_moe_test.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -301,12 +301,12 @@ def test_olive_fused_expert_packing_is_byte_exact_vs_dense(self):
301301
fc2_zp = torch.randint(0, 16, (num_experts, hidden_size, fc2_blocks))
302302

303303
raw = {
304-
"model.layers.1.mlp.experts.gate_up_proj.qweight": _to_olive_qweight(fc1_codes),
305-
"model.layers.1.mlp.experts.gate_up_proj.scales": fc1_scales,
306-
"model.layers.1.mlp.experts.gate_up_proj.qzeros": _to_olive_qzeros(fc1_zp),
307-
"model.layers.1.mlp.experts.down_proj.qweight": _to_olive_qweight(fc2_codes),
308-
"model.layers.1.mlp.experts.down_proj.scales": fc2_scales,
309-
"model.layers.1.mlp.experts.down_proj.qzeros": _to_olive_qzeros(fc2_zp),
304+
"model.layers.1.mlp.experts.gate_up_proj_qweight": _to_olive_qweight(fc1_codes),
305+
"model.layers.1.mlp.experts.gate_up_proj_scales": fc1_scales,
306+
"model.layers.1.mlp.experts.gate_up_proj_qzeros": _to_olive_qzeros(fc1_zp),
307+
"model.layers.1.mlp.experts.down_proj_qweight": _to_olive_qweight(fc2_codes),
308+
"model.layers.1.mlp.experts.down_proj_scales": fc2_scales,
309+
"model.layers.1.mlp.experts.down_proj_qzeros": _to_olive_qzeros(fc2_zp),
310310
}
311311
packed = pack_qmoe_expert_weights(
312312
preprocess_olive_weights(raw, bits=4, group_size=block_size),

‎src/mobius/models/qwen35.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ def preprocess_weights(
388388

389389
# Unpack fused float expert weights into per-expert tensors for the
390390
# dense fallback. When ``use_qmoe`` is set the fused quantized
391-
# tensors arrive as ``.qweight``/``.scales``/``.qzeros`` (which do
391+
# tensors arrive as ``_qweight``/``_scales``/``_qzeros`` (which do
392392
# not match these suffixes) and are kept expert-major for
393393
# ``pack_qmoe_expert_weights`` below.
394394
# HF format: [num_experts, fused_dim, hidden] with gate+up fused

‎src/mobius/models/qwen35_test.py‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,21 +41,28 @@ def _moe_config(quantization: QuantizationConfig | None) -> object:
4141

4242

4343
def _olive_expert_state_dict() -> dict[str, torch.Tensor]:
44-
"""Synthetic HF-style fused Olive-quantized MoE expert tensors."""
44+
"""Synthetic HF-style fused Olive-quantized MoE expert tensors.
45+
46+
Olive's on-disk suffix convention is an *underscore* suffix directly on
47+
the parameter name (``<pname>_qweight``/``_scales``/``_qzeros``), not a
48+
dotted one -- see ``olive/common/quant/state_dict.py``. For a fused MoE
49+
parameter like ``gate_up_proj`` (no nested ``nn.Linear``), this means
50+
``experts.gate_up_proj_qweight``, not ``experts.gate_up_proj.qweight``.
51+
"""
4552
p = "model.language_model.layers.0.mlp."
4653
return {
47-
p + "experts.gate_up_proj.qweight": torch.randint(
54+
p + "experts.gate_up_proj_qweight": torch.randint(
4855
0, 256, (_E, _FC1_OUT, _H * _BITS // 8), dtype=torch.uint8
4956
),
50-
p + "experts.gate_up_proj.scales": torch.rand(_E, _FC1_OUT, _H // _BLK),
51-
p + "experts.gate_up_proj.qzeros": torch.randint(
57+
p + "experts.gate_up_proj_scales": torch.rand(_E, _FC1_OUT, _H // _BLK),
58+
p + "experts.gate_up_proj_qzeros": torch.randint(
5259
0, 256, (_E, _FC1_OUT, 1), dtype=torch.uint8
5360
),
54-
p + "experts.down_proj.qweight": torch.randint(
61+
p + "experts.down_proj_qweight": torch.randint(
5562
0, 256, (_E, _H, _INT * _BITS // 8), dtype=torch.uint8
5663
),
57-
p + "experts.down_proj.scales": torch.rand(_E, _H, _INT // _BLK),
58-
p + "experts.down_proj.qzeros": torch.randint(0, 256, (_E, _H, 1), dtype=torch.uint8),
64+
p + "experts.down_proj_scales": torch.rand(_E, _H, _INT // _BLK),
65+
p + "experts.down_proj_qzeros": torch.randint(0, 256, (_E, _H, 1), dtype=torch.uint8),
5966
p + "gate.weight": torch.rand(_E, _H),
6067
}
6168

0 commit comments

Comments
 (0)