Skip to content

Commit 8a39113

Browse files
justinchubyCopilot
andcommitted
Preserve GGUF fingerprints and ERNIE shared experts
Serialize new graph configuration fields only for their consuming architectures so pinned runtime route identities remain stable. Treat ERNIE shared width and merged tensors as authoritative while validating the optional shared-count multiplier exactly. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 72a2c1ea-03e1-42a3-8439-c5a0f2e3fde7 Signed-off-by: Justin Chu <[email protected]>
1 parent 34646fe commit 8a39113

3 files changed

Lines changed: 213 additions & 44 deletions

File tree

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

Lines changed: 57 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import shutil
2424
from collections import Counter
2525
from collections.abc import Callable, Collection, Iterable, Mapping
26-
from dataclasses import dataclass
26+
from dataclasses import asdict, dataclass
2727
from pathlib import Path, PurePosixPath
2828
from typing import TYPE_CHECKING, Any
2929
from urllib.parse import urlparse
@@ -2738,9 +2738,6 @@ def _raise_for_invalid_moe_cohort_tensor_contract(gguf_model) -> None:
27382738
top_k = int(metadata[f"{architecture}.expert_used_count"])
27392739
frequency = int(metadata[f"{architecture}.interleave_moe_layer_step"])
27402740
dense_prefix = int(metadata.get(f"{architecture}.leading_dense_block_count", 0))
2741-
shared_intermediate = int(
2742-
metadata.get(f"{architecture}.expert_shared_feed_forward_length", 0)
2743-
)
27442741
vocab = int(metadata.get(f"{architecture}.vocab_size", 0)) or len(
27452742
metadata.get("tokenizer.ggml.tokens", ())
27462743
)
@@ -2783,6 +2780,15 @@ def _raise_for_invalid_moe_cohort_tensor_contract(gguf_model) -> None:
27832780
for name, _raw, _qtype, shape in gguf_model.tensor_items_raw()
27842781
if not is_known_skip(name)
27852782
}
2783+
from mobius.integrations.gguf._config_mapping import (
2784+
_ernie45_shared_expert_width,
2785+
)
2786+
2787+
shared_intermediate, _shared_count = _ernie45_shared_expert_width(
2788+
metadata,
2789+
actual,
2790+
routed_layers,
2791+
)
27862792
required = {
27872793
"token_embd.weight": (vocab, hidden),
27882794
"output_norm.weight": (hidden,),
@@ -2836,7 +2842,7 @@ def _raise_for_invalid_moe_cohort_tensor_contract(gguf_model) -> None:
28362842
)
28372843
correction_biases.add(prefix + "exp_probs_b.bias")
28382844
optional[prefix + "exp_probs_b.bias"] = (experts,)
2839-
if shared_intermediate > 0:
2845+
if shared_intermediate is not None:
28402846
required.update(
28412847
{
28422848
prefix + "ffn_gate_shexp.weight": (shared_intermediate, hidden),
@@ -5810,6 +5816,51 @@ def _logical_source_filename(reference: str | Path, resolved_path: str | Path) -
58105816
return resolved.name
58115817

58125818

5819+
_SPECIALIZED_ENCODER_FINGERPRINT_ARCHITECTURES = frozenset(
5820+
{
5821+
"eurobert",
5822+
"neo-bert",
5823+
"nomic-bert",
5824+
"nomic-bert-moe",
5825+
"jina-bert-v2",
5826+
"gemma-embedding",
5827+
"llama-embed",
5828+
}
5829+
)
5830+
_SPECIALIZED_ENCODER_FINGERPRINT_FIELDS = (
5831+
"encoder_use_token_type_embeddings",
5832+
"encoder_q_bias",
5833+
"encoder_k_bias",
5834+
"encoder_v_bias",
5835+
"encoder_ffn_up_bias",
5836+
"encoder_ffn_down_bias",
5837+
"encoder_qk_norm",
5838+
"encoder_extra_attention_norm",
5839+
"encoder_fused_geglu",
5840+
"pooling_type",
5841+
"embedding_dense_2_out",
5842+
"embedding_dense_3_in",
5843+
)
5844+
_ARCHITECTURE_CONFIG_FINGERPRINT_FIELDS = {
5845+
"attention_clamp": frozenset({"dbrx"}),
5846+
"moe_layer_frequency": frozenset({"ernie4_5-moe", "nomic-bert-moe"}),
5847+
}
5848+
5849+
5850+
def _graph_config_fields_for_fingerprint(config, gguf_arch: str) -> dict[str, object]:
5851+
"""Serialize only fields consumed by an architecture's imported graph."""
5852+
fields = asdict(config)
5853+
if gguf_arch not in _SPECIALIZED_ENCODER_FINGERPRINT_ARCHITECTURES:
5854+
# Keep established route fingerprints byte-identical when encoder-only
5855+
# graph fields are added to ArchitectureConfig.
5856+
for field_name in _SPECIALIZED_ENCODER_FINGERPRINT_FIELDS:
5857+
fields.pop(field_name, None)
5858+
for field_name, consumers in _ARCHITECTURE_CONFIG_FINGERPRINT_FIELDS.items():
5859+
if gguf_arch not in consumers:
5860+
fields.pop(field_name, None)
5861+
return fields
5862+
5863+
58135864
def build_from_gguf(
58145865
gguf_path: str | Path,
58155866
*,
@@ -6590,34 +6641,7 @@ def combine_mtp_report(mtp_report) -> None:
65906641
task_state = resolved_task
65916642
else:
65926643
task_state = dict(sorted(vars(resolved_task).items()))
6593-
graph_config_fields = dataclasses.asdict(config)
6594-
if spec.gguf_arch not in {
6595-
"eurobert",
6596-
"neo-bert",
6597-
"nomic-bert",
6598-
"nomic-bert-moe",
6599-
"jina-bert-v2",
6600-
"gemma-embedding",
6601-
"llama-embed",
6602-
}:
6603-
# These fields were added for specialized encoder graph variants. Keep
6604-
# the established route fingerprint byte-identical for every existing
6605-
# architecture so pinned runtime evidence remains valid.
6606-
for field_name in (
6607-
"encoder_use_token_type_embeddings",
6608-
"encoder_q_bias",
6609-
"encoder_k_bias",
6610-
"encoder_v_bias",
6611-
"encoder_ffn_up_bias",
6612-
"encoder_ffn_down_bias",
6613-
"encoder_qk_norm",
6614-
"encoder_extra_attention_norm",
6615-
"encoder_fused_geglu",
6616-
"pooling_type",
6617-
"embedding_dense_2_out",
6618-
"embedding_dense_3_in",
6619-
):
6620-
graph_config_fields.pop(field_name, None)
6644+
graph_config_fields = _graph_config_fields_for_fingerprint(config, spec.gguf_arch)
66216645
graph_config = json.dumps(
66226646
graph_config_fields,
66236647
default=str,

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

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1539,6 +1539,50 @@ def _arctic_postprocess(
15391539
)
15401540

15411541

1542+
def _ernie45_shared_expert_width(
1543+
metadata: dict[str, Any],
1544+
tensor_names: Iterable[str],
1545+
routed_layers: Iterable[int],
1546+
) -> tuple[int | None, int | None]:
1547+
"""Resolve ERNIE's merged shared MLP width and optional width multiplier."""
1548+
width = int(metadata.get("ernie4_5-moe.expert_shared_feed_forward_length", 0))
1549+
count_value = metadata.get("ernie4_5-moe.expert_shared_count")
1550+
count = None if count_value is None else int(count_value)
1551+
expected = {
1552+
f"blk.{layer}.ffn_{projection}_shexp.weight"
1553+
for layer in routed_layers
1554+
for projection in ("gate", "up", "down")
1555+
}
1556+
present = expected & set(tensor_names)
1557+
1558+
if width < 0:
1559+
raise ValueError("ernie4_5-moe.expert_shared_feed_forward_length must be non-negative")
1560+
if width == 0:
1561+
if present:
1562+
raise ValueError(
1563+
"ernie4_5-moe shared-expert tensors require a positive shared FFN width"
1564+
)
1565+
if count not in {None, 0}:
1566+
raise ValueError(
1567+
"ernie4_5-moe.expert_shared_count requires a positive shared FFN width"
1568+
)
1569+
return None, count
1570+
1571+
if present != expected:
1572+
raise ValueError(
1573+
"ernie4_5-moe positive shared FFN width requires complete shared-expert tensors"
1574+
)
1575+
if count is not None:
1576+
expert_width = int(metadata["ernie4_5-moe.expert_feed_forward_length"])
1577+
if count <= 0 or width != count * expert_width:
1578+
expected_width = count * expert_width
1579+
raise ValueError(
1580+
"ernie4_5-moe.expert_shared_count is inconsistent with its merged shared "
1581+
f"FFN width: expected {expected_width}, got {width}"
1582+
)
1583+
return width, count
1584+
1585+
15421586
def _ernie45_moe_postprocess(
15431587
config: ArchitectureConfig,
15441588
metadata: dict[str, Any],
@@ -1564,12 +1608,11 @@ def _ernie45_moe_postprocess(
15641608
present_correction = correction & names
15651609
if present_correction and present_correction != correction:
15661610
raise ValueError("ernie4_5-moe correction bias must be complete across routed layers")
1567-
shared_width = config.shared_expert_intermediate_size
1568-
shared_count = int(metadata.get("ernie4_5-moe.expert_shared_count", 0))
1569-
if shared_count > 0 and (shared_width is None or shared_width <= 0):
1570-
raise ValueError("ernie4_5-moe shared experts require a positive shared FFN width")
1571-
if shared_count == 0:
1572-
shared_width = None
1611+
shared_width, shared_count = _ernie45_shared_expert_width(
1612+
metadata,
1613+
names,
1614+
routed_layers,
1615+
)
15731616
return dataclasses.replace(
15741617
config,
15751618
hidden_act="silu",
@@ -1584,6 +1627,7 @@ def _ernie45_moe_postprocess(
15841627
routed_scaling_factor=1.0,
15851628
use_expert_bias=bool(present_correction),
15861629
shared_expert_intermediate_size=shared_width,
1630+
n_shared_experts=shared_count,
15871631
attn_qkv_bias=False,
15881632
attn_o_bias=False,
15891633
mlp_bias=False,

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

Lines changed: 106 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,22 @@
33

44
from __future__ import annotations
55

6+
import dataclasses
7+
import json
68
from types import SimpleNamespace
79

810
import numpy as np
911
import onnx_ir as ir
1012
import pytest
1113
import torch
1214

15+
from mobius._configs import ArchitectureConfig
1316
from mobius._registry import registry
1417
from mobius._testing.ort_inference import OnnxModelSession
1518
from mobius.integrations.gguf._arch_registry import Support, get_arch_spec
1619
from mobius.integrations.gguf._builder import (
20+
_SPECIALIZED_ENCODER_FINGERPRINT_FIELDS,
21+
_graph_config_fields_for_fingerprint,
1722
_normalize_gguf_weights,
1823
_raise_for_invalid_moe_cohort_tensor_contract,
1924
)
@@ -57,6 +62,60 @@
5762
}
5863

5964

65+
@pytest.mark.parametrize("architecture", ["llama", "qwen2", "lfm2", "qwen35moe"])
66+
def test_new_cohort_fields_preserve_existing_route_fingerprint_bytes(
67+
architecture: str,
68+
) -> None:
69+
config = ArchitectureConfig(
70+
hidden_size=8,
71+
intermediate_size=12,
72+
num_attention_heads=2,
73+
num_key_value_heads=1,
74+
attention_clamp=8.0,
75+
moe_layer_frequency=2,
76+
)
77+
legacy_fields = dataclasses.asdict(config)
78+
for field_name in (
79+
*_SPECIALIZED_ENCODER_FINGERPRINT_FIELDS,
80+
"attention_clamp",
81+
"moe_layer_frequency",
82+
):
83+
legacy_fields.pop(field_name, None)
84+
legacy_bytes = json.dumps(
85+
legacy_fields,
86+
default=str,
87+
separators=(",", ":"),
88+
sort_keys=True,
89+
).encode()
90+
current_bytes = json.dumps(
91+
_graph_config_fields_for_fingerprint(config, architecture),
92+
default=str,
93+
separators=(",", ":"),
94+
sort_keys=True,
95+
).encode()
96+
97+
assert current_bytes == legacy_bytes
98+
99+
100+
@pytest.mark.parametrize(
101+
("architecture", "included"),
102+
[
103+
("arctic", frozenset()),
104+
("dbrx", frozenset({"attention_clamp"})),
105+
("ernie4_5-moe", frozenset({"moe_layer_frequency"})),
106+
("nomic-bert-moe", frozenset({"moe_layer_frequency"})),
107+
],
108+
)
109+
def test_cohort_route_fingerprint_includes_only_consumed_new_fields(
110+
architecture: str,
111+
included: frozenset[str],
112+
) -> None:
113+
config = ArchitectureConfig(attention_clamp=8.0, moe_layer_frequency=2)
114+
fields = _graph_config_fields_for_fingerprint(config, architecture)
115+
116+
assert included == {"attention_clamp", "moe_layer_frequency"} & fields.keys()
117+
118+
60119
class _FakeGGUF:
61120
def __init__(
62121
self,
@@ -216,8 +275,8 @@ def _fixture(architecture: str) -> _FakeGGUF:
216275
{
217276
f"{architecture}.attention.layer_norm_rms_epsilon": 1e-5,
218277
f"{architecture}.expert_feed_forward_length": expert_intermediate,
219-
f"{architecture}.expert_shared_count": 1,
220-
f"{architecture}.expert_shared_feed_forward_length": expert_intermediate,
278+
f"{architecture}.expert_shared_count": 2,
279+
f"{architecture}.expert_shared_feed_forward_length": 2 * expert_intermediate,
221280
f"{architecture}.leading_dense_block_count": 1,
222281
f"{architecture}.interleave_moe_layer_step": 2,
223282
}
@@ -262,9 +321,18 @@ def _fixture(architecture: str) -> _FakeGGUF:
262321
hidden,
263322
expert_intermediate,
264323
),
265-
prefix + "ffn_gate_shexp.weight": (expert_intermediate, hidden),
266-
prefix + "ffn_up_shexp.weight": (expert_intermediate, hidden),
267-
prefix + "ffn_down_shexp.weight": (hidden, expert_intermediate),
324+
prefix + "ffn_gate_shexp.weight": (
325+
2 * expert_intermediate,
326+
hidden,
327+
),
328+
prefix + "ffn_up_shexp.weight": (
329+
2 * expert_intermediate,
330+
hidden,
331+
),
332+
prefix + "ffn_down_shexp.weight": (
333+
hidden,
334+
2 * expert_intermediate,
335+
),
268336
}
269337
)
270338
else:
@@ -502,6 +570,8 @@ def test_cohort_config_preserves_routing_and_schedule_semantics() -> None:
502570
assert ernie.first_k_dense_replace == 1
503571
assert ernie.use_expert_bias
504572
assert ernie.norm_topk_prob
573+
assert ernie.shared_expert_intermediate_size == 12
574+
assert ernie.n_shared_experts == 2
505575
assert ernie.routing_weight_normalization_floor == pytest.approx(6.103515625e-5)
506576

507577
nomic = gguf_to_config(_fixture("nomic-bert-moe"))
@@ -510,6 +580,37 @@ def test_cohort_config_preserves_routing_and_schedule_semantics() -> None:
510580
assert nomic.hidden_act == "gelu_pytorch_tanh"
511581

512582

583+
def test_ernie_shared_expert_width_is_authoritative_without_count() -> None:
584+
source = _fixture("ernie4_5-moe")
585+
del source.metadata["ernie4_5-moe.expert_shared_count"]
586+
587+
_raise_for_invalid_moe_cohort_tensor_contract(source)
588+
config = gguf_to_config(source)
589+
module = registry.get(get_arch_spec(source.architecture).module_type)(config)
590+
591+
assert config.shared_expert_intermediate_size == 12
592+
assert config.n_shared_experts is None
593+
assert any("shared_expert" in name for name, _parameter in module.named_parameters())
594+
595+
596+
@pytest.mark.parametrize("shared_count", [0, 1, 3])
597+
def test_ernie_shared_expert_count_must_match_width(shared_count: int) -> None:
598+
source = _fixture("ernie4_5-moe")
599+
source.metadata["ernie4_5-moe.expert_shared_count"] = shared_count
600+
601+
with pytest.raises(ValueError, match="expert_shared_count"):
602+
_raise_for_invalid_moe_cohort_tensor_contract(source)
603+
604+
605+
def test_ernie_shared_expert_width_requires_complete_tensors() -> None:
606+
source = _fixture("ernie4_5-moe")
607+
del source._tensors["blk.1.ffn_gate_shexp.weight"]
608+
source.tensor_names = list(source._tensors)
609+
610+
with pytest.raises(ValueError, match="complete shared-expert tensors"):
611+
_raise_for_invalid_moe_cohort_tensor_contract(source)
612+
613+
513614
def test_ernie_rejects_ignored_attention_output_bias() -> None:
514615
source = _fixture("ernie4_5-moe")
515616
for layer in range(int(source.metadata["ernie4_5-moe.block_count"])):

0 commit comments

Comments
 (0)