77
88import dataclasses
99import hashlib
10+ import json
1011from pathlib import Path
1112from 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" ])
454525def 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+
496583def 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
596685def 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
0 commit comments