Skip to content

Commit 65df276

Browse files
justinchubyCopilot
andcommitted
Fix path-pinned Grok GGUF review findings
Restore the architecture-owned RMSNorm epsilon when Grok metadata also carries LayerNorm epsilon, and accept the pinned loader’s valid ungated dense up/down pair while preserving uniform topology checks. Preserve optional base-model outputs in the Grok wrapper and leave mapped auxiliary sidecars to the existing fail-closed quantization preflight, with discriminating execution and regression coverage. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 460fa59 commit 65df276

4 files changed

Lines changed: 140 additions & 22 deletions

File tree

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1630,6 +1630,10 @@ def finite(name: str, default: float) -> float:
16301630
return value
16311631

16321632
embedding_scale = finite("embedding_scale", 78.38367176906169)
1633+
rms_norm_eps = finite(
1634+
"attention.layer_norm_rms_epsilon",
1635+
config.rms_norm_eps,
1636+
)
16331637
attention_output_scale = finite(
16341638
"attention.output_scale",
16351639
0.08838834764831845,
@@ -1641,6 +1645,8 @@ def finite(name: str, default: float) -> float:
16411645
temperature_length = int(metadata.get(f"{arch}.attention.temperature_length", 0))
16421646
if math.isclose(logit_output_scale, 0.0, rel_tol=0.0, abs_tol=0.0):
16431647
raise ValueError("grok.logit_scale must be nonzero")
1648+
if rms_norm_eps <= 0:
1649+
raise ValueError("grok.attention.layer_norm_rms_epsilon must be positive")
16441650
if attn_softcap <= 0:
16451651
raise ValueError("grok.attn_logit_softcapping must be positive")
16461652
if final_softcap < 0:
@@ -1668,6 +1674,7 @@ def finite(name: str, default: float) -> float:
16681674
fields.update(
16691675
model_type="grok_gguf",
16701676
hidden_act="gelu_new",
1677+
rms_norm_eps=rms_norm_eps,
16711678
mlp_bias=False,
16721679
norm_topk_prob=True,
16731680
routed_scaling_factor=1.0,

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from collections.abc import Iterable, Mapping
1010
from typing import Any
1111

12-
from mobius.integrations.gguf._tensor_mapping import is_known_skip
12+
from mobius.integrations.gguf._tensor_mapping import is_known_skip, map_gguf_to_hf_names
1313

1414
_ARCHITECTURES = frozenset({"grok", "grovemoe", "hunyuan-moe"})
1515

@@ -175,6 +175,10 @@ def validate_remaining_moe_tensor_contract(gguf_model) -> None:
175175
name: tuple(int(dimension) for dimension in shape)
176176
for name, _raw, _qtype, shape in gguf_model.tensor_items_raw()
177177
if not is_known_skip(name)
178+
and not (
179+
name.endswith((".scale", ".input_scale"))
180+
and map_gguf_to_hf_names(name, architecture) is not None
181+
)
178182
}
179183
required: dict[str, tuple[int, ...]] = {
180184
"token_embd.weight": (vocab, hidden),
@@ -189,6 +193,7 @@ def validate_remaining_moe_tensor_contract(gguf_model) -> None:
189193
raise ValueError("grok.expert_feed_forward_length must be non-negative")
190194
expert_width = expert_width or dense_width
191195
dense_layers: list[bool] = []
196+
gated_dense_layers: list[bool] = []
192197
gated_expert_layers: list[bool] = []
193198
for layer in range(layers):
194199
prefix = f"blk.{layer}."
@@ -231,7 +236,6 @@ def validate_remaining_moe_tensor_contract(gguf_model) -> None:
231236
required[selected_post_norm] = (hidden,)
232237

233238
dense_shapes = {
234-
prefix + "ffn_gate.weight": (dense_width, hidden),
235239
prefix + "ffn_up.weight": (dense_width, hidden),
236240
prefix + "ffn_down.weight": (hidden, dense_width),
237241
}
@@ -240,11 +244,25 @@ def validate_remaining_moe_tensor_contract(gguf_model) -> None:
240244
raise ValueError(
241245
f"{architecture} layer {layer} has a partial dense FFN tensor family"
242246
)
243-
dense_layers.append(bool(present_dense))
247+
dense_gate = prefix + "ffn_gate.weight"
248+
has_dense = bool(present_dense)
249+
has_dense_gate = dense_gate in actual
250+
if has_dense_gate and not has_dense:
251+
raise ValueError(
252+
f"{architecture} layer {layer} has a dense FFN gate without "
253+
"complete up/down projections"
254+
)
255+
dense_layers.append(has_dense)
244256
if present_dense:
245257
required.update(dense_shapes)
258+
if has_dense_gate:
259+
required[dense_gate] = (dense_width, hidden)
260+
gated_dense_layers.append(True)
261+
else:
262+
gated_dense_layers.append(False)
246263
_require_uniform("grok attention projection biases", attention_biases)
247264
_require_uniform("grok dense FFN topology", dense_layers)
265+
_require_uniform("grok dense FFN gating topology", gated_dense_layers)
248266
_require_uniform("grok expert gating topology", gated_expert_layers)
249267
_validate_shapes(architecture, actual, required, optional)
250268
return

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

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

88
import dataclasses
99
import hashlib
10+
import json
1011
from pathlib import Path
1112
from types import SimpleNamespace
1213

@@ -143,6 +144,7 @@ def _fixture(architecture: str) -> _FakeGGUF:
143144
metadata.update(
144145
{
145146
"grok.expert_feed_forward_length": _EXPERT_WIDTH,
147+
"grok.attention.layer_norm_epsilon": 1e-12,
146148
"grok.embedding_scale": 2.0,
147149
"grok.attention.output_scale": 0.5,
148150
"grok.logit_scale": 0.25,
@@ -265,10 +267,17 @@ def _fixture(architecture: str) -> _FakeGGUF:
265267
return _FakeGGUF(architecture, metadata, tensors)
266268

267269

268-
def _write_fixture(path: Path, architecture: str) -> None:
270+
def _write_fixture(
271+
path: Path,
272+
architecture: str,
273+
*,
274+
source: _FakeGGUF | None = None,
275+
) -> None:
269276
from gguf import GGUFWriter
270277

271-
source = _fixture(architecture)
278+
source = source or _fixture(architecture)
279+
if source.architecture != architecture:
280+
raise ValueError("Synthetic GGUF source architecture does not match the writer")
272281
writer = GGUFWriter(str(path), architecture)
273282
for key, value in source.metadata.items():
274283
if isinstance(value, bool):
@@ -404,6 +413,11 @@ def test_exact_tensor_closure_config_and_graph(architecture: str) -> None:
404413
attention = next(node for node in graph if node.op_type == "Attention")
405414
assert attention.attributes["scale"].value == pytest.approx(0.5)
406415
assert attention.attributes["softcap"].value == pytest.approx(3.0)
416+
assert all(
417+
node.attributes["epsilon"].value == pytest.approx(1e-5)
418+
for node in graph
419+
if node.op_type == "RMSNormalization"
420+
)
407421
elif architecture == "grovemoe":
408422
assert any("chunk_experts.0" in name for name in graph.initializers)
409423
else:
@@ -424,14 +438,17 @@ def test_exact_tensor_closure_config_and_graph(architecture: str) -> None:
424438
assert rotary_index < q_norm_index
425439

426440

427-
@pytest.mark.parametrize("architecture", ["grok", "grovemoe", "hunyuan-moe"])
428-
def test_synthetic_gguf_build_executes_end_to_end(
429-
architecture: str,
430-
tmp_path: Path,
431-
) -> None:
432-
path = tmp_path / f"{architecture}.gguf"
433-
_write_fixture(path, architecture)
434-
package = build_from_gguf(path, keep_quantized=False)
441+
def test_grok_forward_preserves_optional_base_outputs() -> None:
442+
config = dataclasses.replace(
443+
gguf_to_config(_fixture("grok")),
444+
output_final_hidden_state=True,
445+
)
446+
module = registry.get(get_arch_spec("grok").module_type)(config)
447+
graph = CausalLMTask().build(module, config)["model"].graph
448+
assert "mtp_seed" in {output.name for output in graph.outputs}
449+
450+
451+
def _run_synthetic_package(package) -> np.ndarray:
435452
session = OnnxModelSession(package["model"], device="cpu")
436453
feeds = {
437454
"input_ids": np.array([[1, 2]], dtype=np.int64),
@@ -443,13 +460,67 @@ def test_synthetic_gguf_build_executes_end_to_end(
443460
feeds[f"past_key_values.{layer}.key"] = np.empty(shape, dtype=np.float32)
444461
feeds[f"past_key_values.{layer}.value"] = np.empty(shape, dtype=np.float32)
445462
try:
446-
logits = session.run(feeds)["logits"]
463+
return session.run(feeds)["logits"]
447464
finally:
448465
session.close()
466+
467+
468+
@pytest.mark.parametrize("architecture", ["grok", "grovemoe", "hunyuan-moe"])
469+
def test_synthetic_gguf_build_executes_end_to_end(
470+
architecture: str,
471+
tmp_path: Path,
472+
) -> None:
473+
path = tmp_path / f"{architecture}.gguf"
474+
_write_fixture(path, architecture)
475+
package = build_from_gguf(path, keep_quantized=False)
476+
logits = _run_synthetic_package(package)
477+
assert logits.shape == (1, 2, _VOCAB)
478+
assert np.isfinite(logits).all()
479+
480+
481+
def test_grok_ungated_dense_ffn_builds_applies_weights_and_executes(
482+
tmp_path: Path,
483+
) -> None:
484+
source = _fixture("grok")
485+
for layer in range(_LAYERS):
486+
del source._tensors[f"blk.{layer}.ffn_gate.weight"]
487+
validate_remaining_moe_tensor_contract(source)
488+
config = gguf_to_config(source)
489+
assert config.has_dense_ffn
490+
assert not config.has_gated_dense_ffn
491+
492+
path = tmp_path / "grok-ungated-dense.gguf"
493+
_write_fixture(path, "grok", source=source)
494+
package = build_from_gguf(path, keep_quantized=False)
495+
initializers = package["model"].graph.initializers
496+
for layer in range(_LAYERS):
497+
prefix = f"model.layers.{layer}.residual_mlp."
498+
assert not any(name.startswith(prefix + "gate_proj.") for name in initializers)
499+
assert initializers[prefix + "up_proj.weight_t"].const_value is not None
500+
assert initializers[prefix + "down_proj.weight_t"].const_value is not None
501+
logits = _run_synthetic_package(package)
449502
assert logits.shape == (1, 2, _VOCAB)
450503
assert np.isfinite(logits).all()
451504

452505

506+
def test_grok_dense_ffn_rejects_partial_and_mixed_gating() -> None:
507+
partial = _fixture("grok")
508+
del partial._tensors["blk.0.ffn_down.weight"]
509+
with pytest.raises(ValueError, match="partial dense FFN tensor family"):
510+
validate_remaining_moe_tensor_contract(partial)
511+
512+
gate_only = _fixture("grok")
513+
del gate_only._tensors["blk.0.ffn_up.weight"]
514+
del gate_only._tensors["blk.0.ffn_down.weight"]
515+
with pytest.raises(ValueError, match="gate without complete up/down"):
516+
validate_remaining_moe_tensor_contract(gate_only)
517+
518+
mixed = _fixture("grok")
519+
del mixed._tensors["blk.0.ffn_gate.weight"]
520+
with pytest.raises(ValueError, match="dense FFN gating topology"):
521+
validate_remaining_moe_tensor_contract(mixed)
522+
523+
453524
@pytest.mark.parametrize("architecture", ["grok", "grovemoe", "hunyuan-moe"])
454525
def test_stacked_experts_unpack_to_graph_parameters(architecture: str) -> None:
455526
source = _fixture(architecture)
@@ -493,9 +564,26 @@ def test_suffix_exact_mapping_rejects_legacy_and_cross_architecture_tensors() ->
493564
assert map_gguf_to_hf_names("blk.0.ffn_gate_chexps.weight", "hunyuan-moe") is None
494565

495566

567+
def test_auxiliary_sidecars_are_owned_by_the_fail_closed_preflight(tmp_path: Path) -> None:
568+
source = _fixture("grok")
569+
source._tensors["blk.0.ffn_up_exps.scale"] = (_EXPERTS,)
570+
validate_remaining_moe_tensor_contract(source)
571+
572+
path = tmp_path / "grok-sidecar.gguf"
573+
_write_fixture(path, "grok", source=source)
574+
with pytest.raises(ValueError, match="cannot represent GGUF scale/input_scale sidecars"):
575+
build_from_gguf(path, keep_quantized=False)
576+
577+
unowned = _fixture("grok")
578+
unowned._tensors["blk.0.unowned.scale"] = (1,)
579+
with pytest.raises(ValueError, match="unexpected"):
580+
validate_remaining_moe_tensor_contract(unowned)
581+
582+
496583
def test_config_closure_preserves_architecture_semantics() -> None:
497584
grok = gguf_to_config(_fixture("grok"))
498585
assert isinstance(grok, GrokGGUFConfig)
586+
assert grok.rms_norm_eps == pytest.approx(1e-5)
499587
assert grok.embedding_scale == pytest.approx(2.0)
500588
assert grok.attention_output_scale == pytest.approx(0.5)
501589
assert grok.logit_output_scale == pytest.approx(0.25)
@@ -578,6 +666,7 @@ def test_grok_yarn_defaults_and_fingerprint_isolation() -> None:
578666
assert config.rope_scaling["beta_slow"] == pytest.approx(1.0)
579667

580668
baseline = _serialize_route_graph_config(config, "grok")
669+
assert json.loads(baseline)["rms_norm_eps"] == pytest.approx(1e-5)
581670
changed_ignored = _serialize_route_graph_config(
582671
dataclasses.replace(config, router_logit_softcapping=99.0),
583672
"grok",
@@ -594,7 +683,10 @@ def test_grok_yarn_defaults_and_fingerprint_isolation() -> None:
594683

595684

596685
def test_grok_decoder_matches_pinned_synthetic_reference() -> None:
597-
config = GrokGGUFConfig(
686+
parsed = gguf_to_config(_fixture("grok"))
687+
assert isinstance(parsed, GrokGGUFConfig)
688+
config = dataclasses.replace(
689+
parsed,
598690
hidden_size=4,
599691
intermediate_size=6,
600692
num_hidden_layers=1,
@@ -605,13 +697,13 @@ def test_grok_decoder_matches_pinned_synthetic_reference() -> None:
605697
num_experts_per_tok=2,
606698
moe_intermediate_size=3,
607699
hidden_act="gelu_new",
608-
rms_norm_eps=1e-5,
609700
attention_output_scale=0.5,
610701
attn_logit_softcapping=2.0,
611702
has_dense_ffn=True,
612703
has_gated_dense_ffn=True,
613704
has_gated_experts=True,
614705
)
706+
eps = config.rms_norm_eps
615707
layer = GrokGGUFDecoderLayer(config)
616708
builder, op, graph = create_test_builder()
617709
hidden = create_test_input(builder, "hidden", [1, 2, 4])
@@ -625,7 +717,7 @@ def test_grok_decoder_matches_pinned_synthetic_reference() -> None:
625717
dtype=torch.float32,
626718
)
627719

628-
normalized = _rms_norm(hidden_value, weights["input_layernorm.weight"], 1e-5)
720+
normalized = _rms_norm(hidden_value, weights["input_layernorm.weight"], eps)
629721
query = _linear(normalized, weights, "self_attn.q_proj")
630722
key = _linear(normalized, weights, "self_attn.k_proj")
631723
value = _linear(normalized, weights, "self_attn.v_proj")
@@ -643,13 +735,13 @@ def test_grok_decoder_matches_pinned_synthetic_reference() -> None:
643735
attention = _rms_norm(
644736
attention,
645737
weights["attention_output_layernorm.weight"],
646-
1e-5,
738+
eps,
647739
)
648740
ffn_input = hidden_value + attention
649741
normalized = _rms_norm(
650742
ffn_input,
651743
weights["pre_feedforward_layernorm.weight"],
652-
1e-5,
744+
eps,
653745
)
654746
probabilities = torch.softmax(_linear(normalized, weights, "mlp.gate"), dim=-1)
655747
routing_weights, selected = torch.topk(probabilities, 2, dim=-1)
@@ -669,7 +761,7 @@ def test_grok_decoder_matches_pinned_synthetic_reference() -> None:
669761
ffn_output = _rms_norm(
670762
ffn_output,
671763
weights["post_feedforward_layernorm.weight"],
672-
1e-5,
764+
eps,
673765
)
674766
expected = ffn_input + ffn_output
675767

‎src/mobius/models/moe.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -585,13 +585,14 @@ def forward(
585585
position_ids: ir.Value,
586586
past_key_values: list | None = None,
587587
):
588-
logits, present_key_values = super().forward(
588+
outputs = super().forward(
589589
op,
590590
input_ids,
591591
attention_mask,
592592
position_ids,
593593
past_key_values,
594594
)
595+
logits = outputs[0]
595596
logits = op.Mul(logits, op.CastLike(self._logit_scale, logits))
596597
if not math.isclose(
597598
self._final_logit_softcapping,
@@ -601,7 +602,7 @@ def forward(
601602
):
602603
cap = op.CastLike(self._final_logit_softcapping, logits)
603604
logits = op.Mul(op.Tanh(op.Div(logits, cap)), cap)
604-
return logits, present_key_values
605+
return (logits, *outputs[1:])
605606

606607
def preprocess_weights(
607608
self, state_dict: dict[str, torch.Tensor]

0 commit comments

Comments
 (0)