Skip to content

Commit 15c9566

Browse files
justinchubyCopilot
andauthored
Fix hybrid GGUF weight transforms (#626)
## Summary - reverse llama.cpp inherited Q/K permutation for Nemotron-H and Nemotron-H-MoE while retaining Mamba2 tensor transforms - admit complete dense GraniteHybrid FFN bias families and fuse gate/up weights and biases in authoritative gate-then-up order - fail closed on partial or malformed pairs and preserve routed/shared expert shape and ordering contracts - add synthetic value-based processor and graph coverage, including quantization rejection Fixes review comments 3854971160, 3854971221, and 3854971282. ## Validation - `python -m pytest src/mobius/integrations/gguf/_builder_test.py src/mobius/integrations/gguf/_tensor_processors_test.py src/mobius/integrations/gguf/_arch_registry_test.py src/mobius/integrations/gguf/_config_mapping_test.py src/mobius/integrations/gguf/_tensor_mapping_test.py -q --tb=short -n auto` (1770 passed) - `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` (7769 passed, 56 skipped, 1 subtest passed) - `python scripts/generate_gguf_support_docs.py --check` - `lintrunner f --output oneline --all-files` - GPT-5.6 Sol medium code review: no significant findings Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 5bfccb6 commit 15c9566

6 files changed

Lines changed: 269 additions & 55 deletions

File tree

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,7 +1069,8 @@
10691069
tensor_map_recipe=("nemotron_h",),
10701070
config_key_map="nemotron_h",
10711071
config_postprocessor="nemotron_h",
1072-
tensor_processor="mamba",
1072+
tensor_processor="nemotron_h",
1073+
llama_qk_permute=True,
10731074
required_metadata=(
10741075
"attention.layer_norm_rms_epsilon",
10751076
"ssm.conv_kernel",
@@ -1088,7 +1089,8 @@
10881089
tensor_map_recipe=("nemotron_h_moe",),
10891090
config_key_map="nemotron_h",
10901091
config_postprocessor="nemotron_h_moe",
1091-
tensor_processor="mamba",
1092+
tensor_processor="nemotron_h",
1093+
llama_qk_permute=True,
10921094
required_metadata=(
10931095
"attention.layer_norm_rms_epsilon",
10941096
"ssm.conv_kernel",
@@ -1121,6 +1123,7 @@
11211123
config_key_map="granitehybrid",
11221124
config_postprocessor="granitehybrid",
11231125
tensor_processor="granitehybrid",
1126+
llama_qk_permute=True,
11241127
required_metadata=(
11251128
"attention.layer_norm_rms_epsilon",
11261129
"ssm.conv_kernel",

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1550,6 +1550,8 @@ def test_legacy_exception_types_still_catch_everything(self) -> None:
15501550
def test_nemotron_h_moe_graph_is_supported_but_runtime_is_deferred(self) -> None:
15511551
spec = get_arch_spec("nemotron_h_moe")
15521552
assert spec.model_type == "nemotron_h"
1553+
assert spec.tensor_processor == "nemotron_h"
1554+
assert spec.llama_qk_permute is True
15531555
assert spec.config is Support.SUPPORTED
15541556
assert spec.tensor_map is Support.SUPPORTED
15551557
assert spec.graph is Support.SUPPORTED
@@ -1558,6 +1560,14 @@ def test_nemotron_h_moe_graph_is_supported_but_runtime_is_deferred(self) -> None
15581560
assert spec.reason is not None
15591561
assert "onnxruntime/mobius#605" in spec.reason
15601562

1563+
dense_spec = get_arch_spec("nemotron_h")
1564+
assert dense_spec.tensor_processor == "nemotron_h"
1565+
assert dense_spec.llama_qk_permute is True
1566+
1567+
granite_spec = get_arch_spec("granitehybrid")
1568+
assert granite_spec.tensor_processor == "granitehybrid"
1569+
assert granite_spec.llama_qk_permute is True
1570+
15611571

15621572
class TestDocumentedSupportMatrix:
15631573
"""The published matrix must be the registry, not a stale copy of it.

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2336,6 +2336,7 @@ def _raise_for_invalid_mamba_hybrid_tensor_contract(gguf_model) -> None:
23362336
"or both positive"
23372337
)
23382338
dense_ffn = {"ffn_gate.weight", "ffn_up.weight", "ffn_down.weight"}
2339+
dense_ffn_biases = {"ffn_gate.bias", "ffn_up.bias", "ffn_down.bias"}
23392340
routed_ffn = {
23402341
"ffn_gate_inp.weight",
23412342
"ffn_gate_exps.weight",
@@ -2378,6 +2379,9 @@ def _raise_for_invalid_mamba_hybrid_tensor_contract(gguf_model) -> None:
23782379
"rope_freqs.weight",
23792380
},
23802381
}
2382+
if not num_experts:
2383+
for optional in optional_by_type.values():
2384+
optional.update(dense_ffn_biases)
23812385
forbidden_ffn = dense_ffn if num_experts else routed_ffn | shared_ffn
23822386
present_forbidden = sorted(
23832387
f"blk.{index}.{suffix}"

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

Lines changed: 123 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1113,6 +1113,7 @@ def _write_granitehybrid_moe_gguf(
11131113
expert_used_count: int = 1,
11141114
shared_width: int = 16,
11151115
attention_biases: bool = True,
1116+
mlp_biases: bool = False,
11161117
malformed_shape: str | None = None,
11171118
) -> None:
11181119
"""Write a tiny mixed GraniteHybrid GGUF with routed and shared experts."""
@@ -1205,38 +1206,47 @@ def add_q4(name: str, shape: tuple[int, ...]) -> None:
12051206
prefix = f"blk.{layer}."
12061207
add_float(prefix + "attn_norm.weight", (hidden,))
12071208
add_float(prefix + "ffn_norm.weight", (hidden,))
1208-
add_float(prefix + "ffn_gate_inp.weight", (expert_count, hidden))
12091209
expert_projection = add_q4 if quantized else add_float
1210-
if quantized:
1211-
expert_projection(
1212-
prefix + "ffn_gate_exps.weight",
1213-
(expert_count, expert_width, hidden),
1214-
)
1215-
expert_projection(
1216-
prefix + "ffn_up_exps.weight",
1217-
(expert_count, expert_width, hidden),
1218-
)
1219-
expert_projection(
1220-
prefix + "ffn_down_exps.weight",
1221-
(expert_count, hidden, expert_width),
1222-
)
1210+
if not expert_count:
1211+
expert_projection(prefix + "ffn_gate.weight", (expert_width, hidden))
1212+
expert_projection(prefix + "ffn_up.weight", (expert_width, hidden))
1213+
expert_projection(prefix + "ffn_down.weight", (hidden, expert_width))
1214+
if mlp_biases:
1215+
add_float(prefix + "ffn_gate.bias", (expert_width,), fill=41.0)
1216+
add_float(prefix + "ffn_up.bias", (expert_width,), fill=42.0)
1217+
add_float(prefix + "ffn_down.bias", (hidden,), fill=43.0)
12231218
else:
1224-
add_float(
1225-
prefix + "ffn_gate_exps.weight",
1226-
(expert_count, expert_width, hidden),
1227-
expert_base=11.0,
1228-
)
1229-
add_float(
1230-
prefix + "ffn_up_exps.weight",
1231-
(expert_count, expert_width, hidden),
1232-
expert_base=21.0,
1233-
)
1234-
add_float(
1235-
prefix + "ffn_down_exps.weight",
1236-
(expert_count, hidden, expert_width),
1237-
expert_base=31.0,
1238-
)
1239-
if shared_width:
1219+
add_float(prefix + "ffn_gate_inp.weight", (expert_count, hidden))
1220+
if quantized:
1221+
expert_projection(
1222+
prefix + "ffn_gate_exps.weight",
1223+
(expert_count, expert_width, hidden),
1224+
)
1225+
expert_projection(
1226+
prefix + "ffn_up_exps.weight",
1227+
(expert_count, expert_width, hidden),
1228+
)
1229+
expert_projection(
1230+
prefix + "ffn_down_exps.weight",
1231+
(expert_count, hidden, expert_width),
1232+
)
1233+
else:
1234+
add_float(
1235+
prefix + "ffn_gate_exps.weight",
1236+
(expert_count, expert_width, hidden),
1237+
expert_base=11.0,
1238+
)
1239+
add_float(
1240+
prefix + "ffn_up_exps.weight",
1241+
(expert_count, expert_width, hidden),
1242+
expert_base=21.0,
1243+
)
1244+
add_float(
1245+
prefix + "ffn_down_exps.weight",
1246+
(expert_count, hidden, expert_width),
1247+
expert_base=31.0,
1248+
)
1249+
if expert_count and shared_width:
12401250
add_float(prefix + "ffn_gate_shexp.weight", (shared_width, hidden))
12411251
add_float(prefix + "ffn_up_shexp.weight", (shared_width, hidden))
12421252
add_float(prefix + "ffn_down_shexp.weight", (hidden, shared_width))
@@ -1622,11 +1632,24 @@ def add_float(
16221632
*,
16231633
expert_order: bool = False,
16241634
negative: bool = False,
1635+
permute_heads: int | None = None,
16251636
) -> None:
16261637
if name == omit:
16271638
return
16281639
shape = adjusted_shape(name, shape)
16291640
values = rng.normal(0.0, 0.03, size=shape).astype(np.float32)
1641+
if permute_heads is not None:
1642+
values = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)
1643+
values = (
1644+
values.reshape(
1645+
permute_heads,
1646+
2,
1647+
shape[0] // permute_heads // 2,
1648+
*shape[1:],
1649+
)
1650+
.swapaxes(1, 2)
1651+
.reshape(shape)
1652+
)
16301653
if negative:
16311654
values = -np.exp(values)
16321655
if expert_order:
@@ -1700,8 +1723,20 @@ def projection(name: str, shape: tuple[int, ...]) -> None:
17001723
projection("blk.1.ffn_latent_down.weight", (latent_width, hidden))
17011724
projection("blk.1.ffn_latent_up.weight", (hidden, latent_width))
17021725

1703-
projection("blk.2.attn_q.weight", (heads * head_dim, hidden))
1704-
projection("blk.2.attn_k.weight", (kv_heads * head_dim, hidden))
1726+
if quantized:
1727+
projection("blk.2.attn_q.weight", (heads * head_dim, hidden))
1728+
projection("blk.2.attn_k.weight", (kv_heads * head_dim, hidden))
1729+
else:
1730+
add_float(
1731+
"blk.2.attn_q.weight",
1732+
(heads * head_dim, hidden),
1733+
permute_heads=heads,
1734+
)
1735+
add_float(
1736+
"blk.2.attn_k.weight",
1737+
(kv_heads * head_dim, hidden),
1738+
permute_heads=kv_heads,
1739+
)
17051740
projection("blk.2.attn_v.weight", (kv_heads * head_dim, hidden))
17061741
projection("blk.2.attn_output.weight", (hidden, heads * head_dim))
17071742

@@ -5774,7 +5809,6 @@ def test_float_import_preserves_expert_order_and_round_trips(self, tmp_path: Pat
57745809
f"model.layers.1.feed_forward.experts.{expert}.{projection}.weight_t"
57755810
].const_value.numpy()
57765811
np.testing.assert_array_equal(value, expert + 1)
5777-
57785812
output_dir = tmp_path / "saved-jamba"
57795813
package.save(output_dir, progress_bar=False)
57805814
session = OnnxModelSession(ModelPackage.load(output_dir)["model"])
@@ -6472,6 +6506,32 @@ def test_attention_biases_can_be_absent(self, tmp_path: Path) -> None:
64726506
for name in model.graph.initializers
64736507
)
64746508

6509+
def test_dense_ffn_biases_are_fused_in_gate_then_up_order(self, tmp_path: Path) -> None:
6510+
from mobius.integrations.gguf import build_from_gguf
6511+
6512+
path = tmp_path / "granitehybrid-dense-biased.gguf"
6513+
_write_granitehybrid_moe_gguf(
6514+
path,
6515+
quantized=False,
6516+
expert_count=0,
6517+
expert_used_count=0,
6518+
shared_width=0,
6519+
mlp_biases=True,
6520+
)
6521+
6522+
model = build_from_gguf(path)["model"]
6523+
for layer in range(2):
6524+
prefix = f"model.layers.{layer}.shared_mlp."
6525+
fused_bias = model.graph.initializers[
6526+
prefix + "input_linear.bias"
6527+
].const_value.numpy()
6528+
np.testing.assert_array_equal(fused_bias[:32], 41.0)
6529+
np.testing.assert_array_equal(fused_bias[32:], 42.0)
6530+
np.testing.assert_array_equal(
6531+
model.graph.initializers[prefix + "output_linear.bias"].const_value.numpy(),
6532+
43.0,
6533+
)
6534+
64756535
def test_quantized_source_requires_explicit_dequantization(self, tmp_path: Path) -> None:
64766536
from mobius.integrations.gguf import build_from_gguf
64776537

@@ -6580,6 +6640,18 @@ def test_float_import_preserves_expert_order_state_and_roundtrip(
65806640
f"model.layers.1.moe.experts.{expert}.{projection}.weight_t"
65816641
].const_value.numpy()
65826642
np.testing.assert_array_equal(value, expert + 1)
6643+
np.testing.assert_array_equal(
6644+
model.graph.initializers[
6645+
"model.layers.2.self_attn.q_proj.weight_t"
6646+
].const_value.numpy(),
6647+
np.arange(32 * 32, dtype=np.float32).reshape(32, 32).T,
6648+
)
6649+
np.testing.assert_array_equal(
6650+
model.graph.initializers[
6651+
"model.layers.2.self_attn.k_proj.weight_t"
6652+
].const_value.numpy(),
6653+
np.arange(16 * 32, dtype=np.float32).reshape(16, 32).T,
6654+
)
65836655

65846656
output_dir = tmp_path / "saved-nemotron-h-moe"
65856657
package.save(output_dir, progress_bar=False)
@@ -7943,6 +8015,24 @@ def test_second_cohort_exact_closure_and_mutations(self, architecture: str) -> N
79438015
)
79448016
)
79458017

8018+
if architecture == "granitehybrid":
8019+
dense_biases = [
8020+
f"blk.{layer}.ffn_{projection}.bias"
8021+
for layer in range(2)
8022+
for projection in ("gate", "up", "down")
8023+
]
8024+
_raise_for_invalid_hybrid_tensor_contract(
8025+
self._FakeGGUF(architecture, metadata, [*names, *dense_biases])
8026+
)
8027+
with pytest.raises(ValueError, match=r"partial dense shared-MLP bias family"):
8028+
_raise_for_invalid_hybrid_tensor_contract(
8029+
self._FakeGGUF(
8030+
architecture,
8031+
metadata,
8032+
[*names, *dense_biases[:-1]],
8033+
)
8034+
)
8035+
79468036
def test_partial_fused_and_separate_experts_are_rejected(self) -> None:
79478037
from mobius.integrations.gguf._builder import (
79488038
_raise_for_invalid_hybrid_tensor_contract,

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

Lines changed: 55 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,15 @@ def _process_mamba(
318318
return state_dict
319319

320320

321+
def _process_nemotron_h(
322+
state_dict: dict[str, torch.Tensor],
323+
config: Any,
324+
) -> dict[str, torch.Tensor]:
325+
"""Invert both inherited GraniteHybrid attention and Mamba2 transforms."""
326+
state_dict = _process_llama(state_dict, config)
327+
return _process_mamba(state_dict, config)
328+
329+
321330
def _process_plamo2(
322331
state_dict: dict[str, torch.Tensor],
323332
config: Any,
@@ -433,29 +442,54 @@ def _process_granitehybrid(
433442
"""Invert Granite transforms and reconstruct fused shared/expert gate-up weights."""
434443
state_dict = _process_llama(state_dict, config)
435444
state_dict = _process_mamba(state_dict, config)
436-
for name in list(state_dict):
437-
if name.endswith(".shared_mlp.gate_proj.weight"):
438-
prefix = name.removesuffix("gate_proj.weight")
439-
up_name = f"{prefix}up_proj.weight"
440-
if up_name not in state_dict:
441-
raise ValueError(
442-
f"GraniteHybrid shared FFN is missing paired tensor {up_name!r}"
443-
)
444-
state_dict[f"{prefix}input_linear.weight"] = torch.cat(
445-
(state_dict.pop(name), state_dict.pop(up_name)), dim=0
446-
)
447-
elif name.endswith(".block_sparse_moe.gate_proj.weight"):
448-
prefix = name.removesuffix("gate_proj.weight")
449-
up_name = f"{prefix}up_proj.weight"
450-
if up_name not in state_dict:
445+
446+
def fuse_pairs(
447+
module_suffix: str,
448+
tensor_suffix: str,
449+
*,
450+
rank: int,
451+
dim: int,
452+
label: str,
453+
) -> None:
454+
gate_suffix = f"{module_suffix}gate_proj.{tensor_suffix}"
455+
up_suffix = f"{module_suffix}up_proj.{tensor_suffix}"
456+
prefixes = {
457+
name.removesuffix(suffix)
458+
for name in state_dict
459+
for suffix in (gate_suffix, up_suffix)
460+
if name.endswith(suffix)
461+
}
462+
for prefix in prefixes:
463+
gate_name = f"{prefix}{gate_suffix}"
464+
up_name = f"{prefix}{up_suffix}"
465+
present = [name for name in (gate_name, up_name) if name in state_dict]
466+
if len(present) != 2:
467+
missing = up_name if gate_name in state_dict else gate_name
468+
raise ValueError(f"GraniteHybrid {label} is missing paired tensor {missing!r}")
469+
gate = state_dict[gate_name]
470+
up = state_dict[up_name]
471+
if gate.dim() != rank or up.dim() != rank or gate.shape != up.shape:
451472
raise ValueError(
452-
f"GraniteHybrid routed experts are missing paired tensor {up_name!r}"
473+
f"GraniteHybrid {label} gate/up tensors must both have the same "
474+
f"rank-{rank} shape, got {gate_name}={tuple(gate.shape)} and "
475+
f"{up_name}={tuple(up.shape)}"
453476
)
454-
# GGUF stores [E, F, H] gate and up tensors separately while the
455-
# Transformers/Mobius module stores [E, 2F, H] in gate-then-up order.
456-
state_dict[f"{prefix}input_linear.weight"] = torch.cat(
457-
(state_dict.pop(name), state_dict.pop(up_name)), dim=1
477+
state_dict[f"{prefix}{module_suffix}input_linear.{tensor_suffix}"] = torch.cat(
478+
(state_dict.pop(gate_name), state_dict.pop(up_name)), dim=dim
458479
)
480+
481+
# HF splits every fused input projection into gate then up along its output
482+
# dimension. Reconstruct exactly that order for dense/shared weights and biases.
483+
fuse_pairs(".shared_mlp.", "weight", rank=2, dim=0, label="shared FFN weights")
484+
fuse_pairs(".shared_mlp.", "bias", rank=1, dim=0, label="shared FFN biases")
485+
# Routed experts add a leading expert axis: [E, F, H] -> [E, 2F, H].
486+
fuse_pairs(
487+
".block_sparse_moe.",
488+
"weight",
489+
rank=3,
490+
dim=1,
491+
label="routed expert weights",
492+
)
459493
return state_dict
460494

461495

@@ -476,6 +510,7 @@ def _process_granitehybrid(
476510
"muse_glimmer": _process_muse_glimmer,
477511
"gpt2": _process_gpt2,
478512
"mamba": _process_mamba,
513+
"nemotron_h": _process_nemotron_h,
479514
"plamo2": _process_plamo2,
480515
"granitehybrid": _process_granitehybrid,
481516
"kimi_linear": _process_kimi_linear,

0 commit comments

Comments
 (0)