Skip to content

Commit 0432dab

Browse files
justinchubyCopilot
andauthored
Fix GGUF output head correctness (#627)
## Summary - honor `quantize_lm_head` for PhiMoE GGUF graphs while preserving exact packed output-head values - preserve PLaMo2 tied checkpoints serialized with either embedding-only or head-only weights - deduplicate exact tied copies and fail closed on conflicting tied tensors Addresses review comments 3854449574 and 3855717041. ## Tests - `python -m pytest src/mobius/models/_models_test.py src/mobius/models/plamo2_test.py src/mobius/integrations/gguf/_builder_test.py -q -k "phimoe or plamo2" --tb=short` - `python -m pytest tests/build_graph_test.py tests/cli_test.py src/ -q -k "not phi4mm and not apply_weights_unknown" --tb=short -n auto` - `lintrunner f --output oneline --all-files` ## Review - GPT-5.6 Sol, medium reasoning: no significant issues found Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 15c9566 commit 0432dab

5 files changed

Lines changed: 152 additions & 13 deletions

File tree

‎src/mobius/integrations/gguf/_builder_test.py‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2032,6 +2032,7 @@ def _write_moe_gguf(
20322032
diffusion_fused_qkv: bool = False,
20332033
fused_qkv_float: bool = False,
20342034
quantize_tied_embedding: bool = False,
2035+
output_quantization: str | None = None,
20352036
expert_scale_suffix: str | None = None,
20362037
malformed_expert_scale: bool = False,
20372038
) -> None:
@@ -2116,6 +2117,11 @@ def add_mxfp4(name: str, shape: tuple[int, ...]) -> None:
21162117
"mxfp4": add_mxfp4,
21172118
"q4_0": add_q4,
21182119
}[projection_quantization]
2120+
add_output = {
2121+
"f32": add_float,
2122+
"mxfp4": add_mxfp4,
2123+
"q4_0": add_q4,
2124+
}[output_quantization or projection_quantization]
21192125

21202126
if quantize_tied_embedding:
21212127
assert architecture in {"qwen3moe", "granitemoe"}
@@ -2192,7 +2198,7 @@ def add_mxfp4(name: str, shape: tuple[int, ...]) -> None:
21922198
if architecture == "phimoe":
21932199
add_float("output_norm.bias", (hidden_size,))
21942200
if architecture not in {"qwen3moe", "granitemoe"}:
2195-
add_projection("output.weight", (vocab_size, hidden_size))
2201+
add_output("output.weight", (vocab_size, hidden_size))
21962202
if architecture == "phimoe":
21972203
add_float("output.bias", (vocab_size,))
21982204

@@ -3447,6 +3453,51 @@ def test_phimoe_fused_qkv_is_split_without_loss(
34473453
)
34483454
offset = end
34493455

3456+
@pytest.mark.parametrize("output_quantization", ["f32", "q4_0"])
3457+
def test_phimoe_output_head_honors_storage_and_values(
3458+
self, output_quantization: str, tmp_path: Path
3459+
) -> None:
3460+
from mobius.integrations.gguf import build_from_gguf
3461+
from mobius.integrations.gguf._reader import GGUFModel
3462+
from mobius.integrations.gguf._repacker import repack_gguf_tensor
3463+
3464+
path = tmp_path / f"phimoe-output-{output_quantization}.gguf"
3465+
_write_moe_gguf(
3466+
path,
3467+
"phimoe",
3468+
"q4_0",
3469+
output_quantization=output_quantization,
3470+
)
3471+
source = GGUFModel(path)
3472+
package = build_from_gguf(path, keep_quantized=True)
3473+
model = package["model"]
3474+
raw, qtype, shape = next(
3475+
(raw, qtype, shape)
3476+
for name, raw, qtype, shape in source.tensor_items_raw()
3477+
if name == "output.weight"
3478+
)
3479+
3480+
if output_quantization == "q4_0":
3481+
assert package.config.quantization is not None
3482+
assert package.config.quantization.quantize_lm_head
3483+
repacked = repack_gguf_tensor(raw, qtype.value, shape)
3484+
np.testing.assert_array_equal(
3485+
model.graph.initializers["lm_head.weight"].const_value.numpy(),
3486+
repacked.weight,
3487+
)
3488+
np.testing.assert_array_equal(
3489+
model.graph.initializers["lm_head.scales"].const_value.numpy(),
3490+
repacked.scales,
3491+
)
3492+
else:
3493+
assert package.config.quantization is not None
3494+
assert not package.config.quantization.quantize_lm_head
3495+
assert "lm_head.scales" not in model.graph.initializers
3496+
np.testing.assert_array_equal(
3497+
model.graph.initializers["lm_head.weight_t"].const_value.numpy(),
3498+
source.get_tensor("output.weight").T,
3499+
)
3500+
34503501
@pytest.mark.parametrize("architecture", ["qwen3moe", "granitemoe"])
34513502
def test_tied_quantized_embedding_is_shared_with_output_head(
34523503
self, architecture: str, tmp_path: Path

‎src/mobius/models/_models_test.py‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@
1616
import torch
1717

1818
from mobius._builder import build_from_module
19+
from mobius._configs import QuantizationConfig
1920
from mobius._registry import (
2021
MODEL_MAP,
2122
ModelRegistry,
2223
registry,
2324
)
2425
from mobius._testing import make_config
25-
from mobius.components import LayerNorm, RMSNormBias
26+
from mobius.components import LayerNorm, Linear, QuantizedLinear, RMSNormBias
2627
from mobius.models.base import CausalLMModel, TextModel
2728
from mobius.models.moe import Phi3MoECausalLMModel, PhiMoEGGUFCausalLMModel
2829
from mobius.tasks import CausalLMTask
@@ -78,6 +79,33 @@ def test_phimoe_norm_matches_checkpoint_format(self):
7879
assert isinstance(native.model.layers[0].input_layernorm, LayerNorm)
7980
assert isinstance(gguf.model.layers[0].input_layernorm, RMSNormBias)
8081

82+
@pytest.mark.parametrize(
83+
("quantize_lm_head", "head_type"),
84+
[(False, Linear), (True, QuantizedLinear)],
85+
)
86+
def test_phimoe_gguf_honors_quantized_head_contract(self, quantize_lm_head, head_type):
87+
config = make_config(
88+
num_local_experts=4,
89+
num_experts_per_tok=2,
90+
partial_rotary_factor=0.5,
91+
quantization=QuantizationConfig(
92+
bits=4,
93+
group_size=32,
94+
quant_method="gguf",
95+
sym=True,
96+
quantize_lm_head=quantize_lm_head,
97+
),
98+
)
99+
module = PhiMoEGGUFCausalLMModel(config)
100+
101+
assert isinstance(module.model.layers[0].self_attn.q_proj, QuantizedLinear)
102+
assert isinstance(module.lm_head, head_type)
103+
104+
model = build_from_module(module, config, task=CausalLMTask())["model"]
105+
op_types = [node.op_type for node in model.graph]
106+
assert "MatMulNBits" in op_types
107+
assert ("lm_head.scales" in model.graph.initializers) is quantize_lm_head
108+
81109

82110
class TestBuildFromModule:
83111
def test_build_base_model(self):

‎src/mobius/models/moe.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,8 +329,12 @@ def __init__(self, config: ArchitectureConfig):
329329
nn.Module.__init__(self)
330330
self.config = config
331331
self.model = MoETextModel(config, norm_class=RMSNormBias)
332-
linear_class = _quantized_linear_class(config) or Linear
333-
self.lm_head = linear_class(config.hidden_size, config.vocab_size, bias=True)
332+
quantization = getattr(config, "quantization", None)
333+
quantized_head = quantization is not None and bool(
334+
getattr(quantization, "quantize_lm_head", False)
335+
)
336+
head_class = _quantized_linear_class(config) if quantized_head else None
337+
self.lm_head = (head_class or Linear)(config.hidden_size, config.vocab_size, bias=True)
334338

335339

336340
class MoECausalLMModel(CausalLMModel):

‎src/mobius/models/plamo2.py‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -426,15 +426,31 @@ def preprocess_weights(
426426
}
427427
norms_are_folded = bool(getattr(self.config, "_plamo2_norms_are_folded", False))
428428
tied_embeddings = effective_tie_word_embeddings(self.config)
429+
tied_weight: torch.Tensor | None = None
430+
if tied_embeddings:
431+
embedding_weight = state_dict.get("model.embed_tokens.weight")
432+
head_weight = state_dict.get("lm_head.weight")
433+
if embedding_weight is not None and head_weight is not None:
434+
if not torch.equal(embedding_weight, head_weight):
435+
raise ValueError(
436+
"PLaMo2 tied checkpoint contains conflicting "
437+
"model.embed_tokens.weight and lm_head.weight tensors"
438+
)
439+
tied_weight = embedding_weight
440+
else:
441+
tied_weight = embedding_weight if embedding_weight is not None else head_weight
442+
429443
for name, value in state_dict.items():
430444
name = name.replace("model.layers.layers.", "model.layers.")
431-
if name == "model.embed_tokens.weight" and tied_embeddings:
432-
result[name] = value
433-
# onnxscript materializes the shared Parameter under both use
434-
# sites, while the official checkpoint stores only the embedding.
435-
result["lm_head.weight"] = value
436-
continue
437-
if name == "lm_head.weight" and tied_embeddings:
445+
if (
446+
tied_embeddings
447+
and tied_weight is not None
448+
and name in {"model.embed_tokens.weight", "lm_head.weight"}
449+
):
450+
# Checkpoints may serialize either tied key. Keep one tensor object
451+
# under both graph parameter names so weight loading deduplicates it.
452+
result["model.embed_tokens.weight"] = tied_weight
453+
result["lm_head.weight"] = tied_weight
438454
continue
439455
if name == "model.norm.weight":
440456
result[name] = value if norms_are_folded else value + 1.0

‎src/mobius/models/plamo2_test.py‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import numpy as np
99
import onnx_ir as ir
10+
import pytest
1011
import torch
1112

1213
from mobius import build_from_module
@@ -453,7 +454,7 @@ def test_plamo2_preprocesses_offsets_and_decay_values() -> None:
453454
"model.layers.layers.0.post_mlp_norm.weight": torch.tensor([6.0]),
454455
"model.layers.layers.0.mixer.A_log": torch.tensor([0.0, 1.0]),
455456
"model.embed_tokens.weight": torch.tensor([8.0]),
456-
"lm_head.weight": torch.tensor([9.0]),
457+
"lm_head.weight": torch.tensor([8.0]),
457458
}
458459
actual = model.preprocess_weights(weights)
459460
torch.testing.assert_close(actual["model.norm.weight"], torch.tensor([3.0]))
@@ -480,6 +481,45 @@ def test_plamo2_preprocesses_offsets_and_decay_values() -> None:
480481
torch.testing.assert_close(actual["lm_head.weight"], torch.tensor([8.0]))
481482

482483

484+
@pytest.mark.parametrize("source_key", ["model.embed_tokens.weight", "lm_head.weight"])
485+
def test_plamo2_preprocesses_either_single_tied_weight(source_key: str) -> None:
486+
model = Plamo2ForCausalLM(_config())
487+
weight = torch.arange(8, dtype=torch.float32)
488+
489+
actual = model.preprocess_weights({source_key: weight})
490+
491+
assert actual["model.embed_tokens.weight"] is weight
492+
assert actual["lm_head.weight"] is weight
493+
494+
495+
def test_plamo2_unifies_exact_duplicate_tied_weights() -> None:
496+
model = Plamo2ForCausalLM(_config())
497+
embedding_weight = torch.arange(8, dtype=torch.float32)
498+
head_weight = embedding_weight.clone()
499+
500+
actual = model.preprocess_weights(
501+
{
502+
"model.embed_tokens.weight": embedding_weight,
503+
"lm_head.weight": head_weight,
504+
}
505+
)
506+
507+
assert actual["model.embed_tokens.weight"] is embedding_weight
508+
assert actual["lm_head.weight"] is embedding_weight
509+
510+
511+
def test_plamo2_rejects_conflicting_tied_weights() -> None:
512+
model = Plamo2ForCausalLM(_config())
513+
514+
with pytest.raises(ValueError, match="conflicting"):
515+
model.preprocess_weights(
516+
{
517+
"model.embed_tokens.weight": torch.tensor([8.0]),
518+
"lm_head.weight": torch.tensor([9.0]),
519+
}
520+
)
521+
522+
483523
def test_plamo2_preprocesses_effectively_tied_quantized_embeddings() -> None:
484524
config = _config()
485525
config.tie_word_embeddings = False
@@ -489,7 +529,7 @@ def test_plamo2_preprocesses_effectively_tied_quantized_embeddings() -> None:
489529
actual = model.preprocess_weights(
490530
{
491531
"model.embed_tokens.weight": torch.tensor([8.0]),
492-
"lm_head.weight": torch.tensor([9.0]),
532+
"lm_head.weight": torch.tensor([8.0]),
493533
}
494534
)
495535

0 commit comments

Comments
 (0)