Skip to content

Commit 79efe2c

Browse files
justinchubyCopilot
andauthored
Validate real PLaMo2 GGUF import (#617)
## Summary - accept the exact legacy scalar-head and tokenizer metadata used by the pinned public PLaMo2 F32 GGUF - add an explicit opt-in 5.16 GB import/save/reload integration test - record immutable source provenance, full tensor comparison, raw ORT parity results, and ORT GenAI blockers - keep L4/L5 and packaged runtime support deferred because cached decode diverges ## Historical evidence - full 218-tensor provenance comparison completed against the pinned checkpoint and GGUF revisions - exact artifact size/SHA, tensor census, package identity, reference generation, raw ORT CPU results, and ORT GenAI 0.15.2 blockers remain recorded in `testdata/evidence/causal-lm/plamo2-1b-real.json` - the opt-in real-artifact round trip previously passed; the exact artifact is required through `MOBIUS_PLAMO2_REAL_GGUF` ## Post-rebase validation - rebased as one patch-identical commit onto `c98ee9e` after #612 was squash-merged - focused import/tokenizer/cache/schema/evidence selection: 255 passed, 1 expected env-gated skip - broad non-integration suite: 7,522 passed, 54 skipped, 1 subtest passed - initialized pinned `lintrunner` tools: clean - GPT-only post-rebase review: no actionable findings Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent c98ee9e commit 79efe2c

7 files changed

Lines changed: 309 additions & 14 deletions

File tree

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

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1109,14 +1109,47 @@ def _raise_for_invalid_plamo2_tensor_contract(gguf_model) -> None:
11091109

11101110
head_counts = metadata[f"{arch}.attention.head_count"]
11111111
kv_counts = metadata[f"{arch}.attention.head_count_kv"]
1112-
if not isinstance(head_counts, (list, tuple, np.ndarray)) or not isinstance(
1113-
kv_counts, (list, tuple, np.ndarray)
1114-
):
1115-
raise TypeError("PLaMo2 attention head counts must be per-layer arrays")
1112+
head_counts_are_arrays = isinstance(head_counts, (list, tuple, np.ndarray))
1113+
kv_counts_are_arrays = isinstance(kv_counts, (list, tuple, np.ndarray))
1114+
if head_counts_are_arrays and len(head_counts) != layers:
1115+
raise ValueError("PLaMo2 attention head arrays must match block_count")
1116+
if kv_counts_are_arrays and len(kv_counts) != layers:
1117+
raise ValueError("PLaMo2 attention head arrays must match block_count")
1118+
if kv_counts_are_arrays:
1119+
attention_layers = [int(value) > 0 for value in kv_counts]
1120+
elif head_counts_are_arrays:
1121+
attention_layers = [int(value) > 0 for value in head_counts]
1122+
else:
1123+
# Early llama.cpp PLaMo2 converters serialized the attention dimensions
1124+
# as scalars. The mutually exclusive tensor families still encode the
1125+
# exact layer schedule, so expand it only when every layer is unambiguous.
1126+
tensor_names = set(gguf_model.tensor_names)
1127+
attention_layers = []
1128+
for layer in range(layers):
1129+
has_attention = f"blk.{layer}.attn_qkv.weight" in tensor_names
1130+
has_mamba = f"blk.{layer}.ssm_in.weight" in tensor_names
1131+
if has_attention == has_mamba:
1132+
raise ValueError(
1133+
"PLaMo2 scalar head metadata requires exactly one attention or "
1134+
f"Mamba tensor family in layer {layer}"
1135+
)
1136+
attention_layers.append(has_attention)
1137+
if not head_counts_are_arrays:
1138+
attention_heads = int(head_counts)
1139+
if attention_heads <= 0:
1140+
raise ValueError("PLaMo2 scalar attention head_count must be positive")
1141+
head_counts = metadata[f"{arch}.attention.head_count"] = [
1142+
attention_heads if is_attention else 0 for is_attention in attention_layers
1143+
]
1144+
if not kv_counts_are_arrays:
1145+
attention_kv_heads = int(kv_counts)
1146+
if attention_kv_heads <= 0:
1147+
raise ValueError("PLaMo2 scalar attention head_count_kv must be positive")
1148+
kv_counts = metadata[f"{arch}.attention.head_count_kv"] = [
1149+
attention_kv_heads if is_attention else 0 for is_attention in attention_layers
1150+
]
11161151
head_counts = [int(value) for value in head_counts]
11171152
kv_counts = [int(value) for value in kv_counts]
1118-
if len(head_counts) != layers or len(kv_counts) != layers:
1119-
raise ValueError("PLaMo2 attention head arrays must match block_count")
11201153

11211154
actual_shapes = {
11221155
name: tuple(int(dim) for dim in gguf_model.get_tensor_shape(name))

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,7 @@ def _write_plamo2_gguf(
837837
predefined_state: bool = False,
838838
head_counts: list[int] | None = None,
839839
kv_head_counts: list[int] | None = None,
840+
legacy_scalar_heads: bool = False,
840841
quantized_embedding: bool = False,
841842
include_output: bool = False,
842843
) -> None:
@@ -861,8 +862,10 @@ def _write_plamo2_gguf(
861862
writer.add_embedding_length(hidden)
862863
writer.add_feed_forward_length(intermediate)
863864
writer.add_block_count(2)
864-
writer.add_head_count(head_counts or [0, heads])
865-
writer.add_head_count_kv(kv_head_counts or [0, kv_heads])
865+
writer.add_head_count(heads if legacy_scalar_heads else head_counts or [0, heads])
866+
writer.add_head_count_kv(
867+
kv_heads if legacy_scalar_heads else kv_head_counts or [0, kv_heads]
868+
)
866869
writer.add_layer_norm_rms_eps(epsilon)
867870
writer.add_rope_freq_base(10_000.0)
868871
writer.add_vocab_size(vocab)
@@ -4547,6 +4550,16 @@ def test_float_import_executes_and_round_trips(self, tmp_path: Path) -> None:
45474550
assert outputs["logits"].shape == (2, 2, 64)
45484551
assert outputs["present.0.ssm_state"].dtype == np.float32
45494552

4553+
def test_legacy_scalar_heads_infer_exact_tensor_schedule(self, tmp_path: Path) -> None:
4554+
from mobius.integrations.gguf import build_from_gguf
4555+
4556+
path = tmp_path / "plamo2-legacy-scalar-heads.gguf"
4557+
_write_plamo2_gguf(path, quantized=False, legacy_scalar_heads=True)
4558+
package = build_from_gguf(path)
4559+
assert package.config.layer_types == ["mamba", "full_attention"]
4560+
assert package.config.attention_head_counts == (0, 4)
4561+
assert package.config.attention_kv_head_counts == (0, 2)
4562+
45504563
def test_quantized_source_preserves_exact_projection_roles(self, tmp_path: Path) -> None:
45514564
from mobius.integrations.gguf import build_from_gguf
45524565

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

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -252,10 +252,15 @@ def inspect_gguf_tokenizer(
252252
if policy is None:
253253
raise ValueError(f"{source} declares unknown tokenizer.ggml.pre {pre_value!r}")
254254
elif pre_value is not None:
255-
raise ValueError(
256-
f"{source} declares tokenizer.ggml.pre for non-BPE model {model!r}; "
257-
"the pinned loader does not consume that combination"
258-
)
255+
# The public PLaMo2 F32 conversion predates per-model tokenizer cleanup
256+
# and carries the inert legacy value "default". Validate that exact
257+
# known identifier, but keep tokenizer materialization deferred below.
258+
if model != "plamo2" or pre_value != "default":
259+
raise ValueError(
260+
f"{source} declares tokenizer.ggml.pre for non-BPE model {model!r}; "
261+
"the pinned loader does not consume that combination"
262+
)
263+
policy = tokenizer_pre_policies()[pre_value]
259264
else:
260265
policy = None
261266

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,15 @@ def test_known_pre_without_complete_pipeline_is_deferred(self):
179179
assert verdict.pre == "hunyuan-dense"
180180
assert "compiled llama.cpp behavior" in verdict.reason
181181

182+
def test_plamo2_legacy_default_pre_is_validated_but_deferred(self):
183+
metadata = _metadata(pre="default")
184+
metadata["tokenizer.ggml.model"] = "plamo2"
185+
metadata.pop("tokenizer.ggml.merges")
186+
verdict = inspect_gguf_tokenizer(metadata)
187+
assert verdict.route == "deferred"
188+
assert verdict.pre == "default"
189+
assert verdict.canonical_pre == "default"
190+
182191
def test_exact_embedded_json_is_copy_route(self):
183192
verdict = inspect_gguf_tokenizer(_metadata(embedded=True))
184193
assert verdict.route == "copy"

‎testdata/cases/causal-lm/plamo2-1b.yaml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ generation:
1515
max_new_tokens: 20
1616
do_sample: false
1717

18-
notes: "Dedicated alternating Mamba1 and local-attention graph with mixed recurrent/KV state."
19-
skip_reason: "The smallest public checkpoint is 5.16 GB, and released ORT GenAI cannot represent the heterogeneous state ABI; runtime validation is deferred to onnxruntime/mobius#605."
18+
notes: "The exact public checkpoint/GGUF route was exercised; see testdata/evidence/causal-lm/plamo2-1b-real.json."
19+
skip_reason: "Real CPU validation found cached-decode divergence, and ORT GenAI 0.15.2 cannot bind the heterogeneous recurrent/KV state ABI; do not claim L4/L5 yet."
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
{
2+
"schema_version": 1,
3+
"validated_at_utc": "2026-08-25T06:14:35Z",
4+
"validated_parent_commit": "64aa8fb55d10d3097d944e44231f0301d2527113",
5+
"validation_change_set": "the compatibility and evidence changes committed with this record",
6+
"status": "runtime-deferred",
7+
"source_checkpoint": {
8+
"repository": "pfnet/plamo-2-1b",
9+
"revision": "92c75fd6eea9018bcb9c33ee8921589febe071fa",
10+
"files": [
11+
{
12+
"filename": "model-00001-of-00007.safetensors",
13+
"bytes": 4060618320,
14+
"lfs_sha256": "306bfd09ff22b5c044abfbc310b0a916a85a450ff52beaa90e245bb67b4cb1e9"
15+
},
16+
{
17+
"filename": "model-00002-of-00007.safetensors",
18+
"bytes": 285214592,
19+
"lfs_sha256": "759d54a62b8f8124031bf4048b2b7e9b9fe3439e75ce772e48562369768836a8"
20+
},
21+
{
22+
"filename": "model-00003-of-00007.safetensors",
23+
"bytes": 819200136,
24+
"lfs_sha256": "c7172210250c2b4030b1bc9c75a68224844e770838159e939bb6c68593d2e235"
25+
},
26+
{
27+
"filename": "model-00004-of-00007.safetensors",
28+
"bytes": 621448,
29+
"lfs_sha256": "017d164149a8e31acdde2f8c6dd45568d7a8900951f83cb5fbcebac64c662695"
30+
},
31+
{
32+
"filename": "model-00005-of-00007.safetensors",
33+
"bytes": 131976,
34+
"lfs_sha256": "6bfe7b7d45c40c75d7ff7b362fd88bf34e23aedf6a637df4eafc9f7d6231f8ca"
35+
},
36+
{
37+
"filename": "model-00006-of-00007.safetensors",
38+
"bytes": 5296,
39+
"lfs_sha256": "3dadc185925d0be7f495c51924546b0f07f93550cf4222da96dedd335beb3b8f"
40+
},
41+
{
42+
"filename": "model-00007-of-00007.safetensors",
43+
"bytes": 40,
44+
"lfs_sha256": "60d95b10b6e140a9626a7058d5038528f2ff80148dc4569b881db56052046509"
45+
}
46+
],
47+
"config_sha256": "7cd00447566283be63bf20efac313f02423129586c5b348466f09d15082053e9",
48+
"tokenizer_jsonl_sha256": "9fa8276a87dd2440bb9496f1d569c05ded6274fd2854de802e12dc6545804b95",
49+
"tokenizer_config_sha256": "3472dc70138f3d98161b0d54ca424519f031d865882e85efc75e30c349879050",
50+
"tokenization_code_sha256": "ebddaf4cd8c4f7cde47d9e94a227a1cec7eccfbf303a70f520a3fda7c060abef",
51+
"modeling_code_sha256": "21c0e1d8ba2f777c69305259254da865cf79145c1e06fee4fd26ed926b82451e"
52+
},
53+
"gguf": {
54+
"repository": "yt-koike/plamo-2-1b-gguf",
55+
"revision": "184326afcef7232d94df09a33279598255890325",
56+
"filename": "plamo-2-1B-F32.gguf",
57+
"bytes": 5168220288,
58+
"lfs_sha256": "c5deb94bcd21f516db2b00ba4e923e02cc1dede4b7531ef81a15899130b0e5ef",
59+
"format_version": 3,
60+
"tensor_count": 218,
61+
"qtypes": {
62+
"F32": 218
63+
}
64+
},
65+
"provenance_comparison": {
66+
"method": "streamed comparison of every GGUF tensor against the pinned safetensors after documented norm-offset, convolution-shape, and Mamba-decay transforms",
67+
"compared_tensors": 218,
68+
"exact_tensors": 213,
69+
"missing_tensors": 0,
70+
"elements": 1291441920,
71+
"max_abs_error": 9.5367431640625e-07,
72+
"mean_abs_error": 3.323056466858475e-15,
73+
"non_exact_tensors": "five ssm_a tensors differ only by float32 -exp(A_log) rounding"
74+
},
75+
"architecture": {
76+
"layers": 16,
77+
"schedule": "alternating mamba and attention, starting with mamba",
78+
"hidden_size": 2048,
79+
"feed_forward_size": 8192,
80+
"attention_heads": 16,
81+
"kv_heads": 1,
82+
"mamba_inner_size": 4096,
83+
"mamba_heads": 32,
84+
"mamba_state_size": 64,
85+
"mamba_conv_kernel": 4
86+
},
87+
"mobius_package": {
88+
"import": "passed",
89+
"save_check_reload": "passed",
90+
"files": [
91+
"model.onnx",
92+
"model.onnx.data"
93+
],
94+
"sha256": "5a9a6638087d4b76fff79e102e665fb963e505cd17812f909cfc33e42a29b640",
95+
"state_interfaces": 16,
96+
"state_abi": "even layers: conv_state+ssm_state; odd layers: key+value"
97+
},
98+
"independent_reference": {
99+
"implementation": "pinned HuggingFace remote model with upstream pure-PyTorch causal_conv1d_ref and selective_state_update_ref equivalents",
100+
"transformers_version": "5.12.1",
101+
"torch_version": "2.12.1",
102+
"compatibility_shims": [
103+
"adapt Transformers 5 tied-weight metadata and tie lm_head to embed_tokens",
104+
"rebuild non-persistent RoPE caches after meta-device loading",
105+
"provide pure-PyTorch causal convolution and selective state update"
106+
],
107+
"prompt": "Hello",
108+
"prompt_tokens": [
109+
1,
110+
6721
111+
],
112+
"generated_tokens": [
113+
44,
114+
24514,
115+
45119,
116+
7982,
117+
45114,
118+
2166,
119+
353,
120+
1468,
121+
15658,
122+
1090,
123+
2596,
124+
1031,
125+
73,
126+
1170,
127+
1090,
128+
2596,
129+
45114,
130+
2166,
131+
353,
132+
1468
133+
],
134+
"generated_text": ", my name is Alex and I'm a software engineer at Google.\n\nI work at Google and I'm a software",
135+
"generated_length": 20,
136+
"rollback_replay_exact": true
137+
},
138+
"ort_cpu": {
139+
"onnxruntime_version": "1.29.0",
140+
"execution_provider": "CPUExecutionProvider",
141+
"fused_and_portable_results_equal": true,
142+
"prefill_max_abs_error": 0.011388778686523438,
143+
"prefill_mean_abs_error": 0.000737154199364013,
144+
"decode_steps": 19,
145+
"decode_max_abs_error": 23.476438999176025,
146+
"decode_mean_abs_error": 1.668023172595157,
147+
"generated_tokens": [
148+
44,
149+
2268,
150+
1101,
151+
1080,
152+
1087,
153+
8789,
154+
45114,
155+
2002,
156+
2569,
157+
3035,
158+
8435,
159+
46,
160+
7525,
161+
2004,
162+
1078,
163+
1652,
164+
290,
165+
15143,
166+
45116,
167+
2057
168+
],
169+
"generated_length": 20,
170+
"token_equality": false,
171+
"rollback_replay_exact": true,
172+
"promotion_decision": "blocked: cached decode does not meet numerical or token-equality gates"
173+
},
174+
"ort_genai": {
175+
"released_version": "0.15.2",
176+
"generated_model_type": "plamo2",
177+
"generated_state_schema": "homogeneous past_key_names/past_value_names templates",
178+
"model_load": "failed: Unsupported model_type in config.json: plamo2",
179+
"tokenizer_load_after_forcing_llama": "failed: Invalid file: tokenizer.json",
180+
"generation_after_forcing_llama_and_supplying_prompt_tokens": "failed: Model input was not found: past_key_values.0.recurrent_state",
181+
"upstream_main_commit": "a8e0fdf81b061e67c1c3f9485bfdc06735ccd473",
182+
"upstream_main_install": "not feasible from the Python source package: pip built UNKNOWN-0.0.0 without an onnxruntime_genai module",
183+
"promotion_decision": "blocked: no released heterogeneous-state schema, no compatible tokenizer artifact, and no successful end-to-end generation"
184+
},
185+
"l4_l5": {
186+
"goldens_committed": false,
187+
"reason": "real prefill exceeds the parity gate and cached generation diverges; committing passing goldens would misrepresent support"
188+
}
189+
}

‎tests/integration_test.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@
2222
from __future__ import annotations
2323

2424
import gc
25+
import hashlib
2526
import os
27+
from pathlib import Path
2628

2729
import numpy as np
2830
import pytest
@@ -47,6 +49,50 @@
4749
)
4850

4951

52+
@pytest.mark.integration
53+
@pytest.mark.integration_slow
54+
def test_plamo2_pinned_real_gguf_import_roundtrip(tmp_path: Path):
55+
"""Import and serialize the exact public PLaMo2 F32 artifact on explicit opt-in."""
56+
source = os.environ.get("MOBIUS_PLAMO2_REAL_GGUF")
57+
if source is None:
58+
pytest.skip("set MOBIUS_PLAMO2_REAL_GGUF to the pinned 5.16 GB F32 artifact")
59+
60+
from mobius._model_package import ModelPackage
61+
from mobius.integrations.gguf import build_from_gguf
62+
63+
source_path = Path(source)
64+
expected_sha256 = "c5deb94bcd21f516db2b00ba4e923e02cc1dede4b7531ef81a15899130b0e5ef"
65+
digest = hashlib.sha256()
66+
with source_path.open("rb") as stream:
67+
while chunk := stream.read(1024 * 1024):
68+
digest.update(chunk)
69+
assert digest.hexdigest() == expected_sha256
70+
71+
package = build_from_gguf(
72+
source_path,
73+
keep_quantized=False,
74+
execution_provider="cpu",
75+
)
76+
assert (
77+
package.config.layer_types
78+
== [
79+
"mamba",
80+
"full_attention",
81+
]
82+
* 8
83+
)
84+
assert package.gguf_tokenizer_verdict.route == "deferred"
85+
86+
output_dir = tmp_path / "plamo2-real"
87+
package.save(str(output_dir), progress_bar=False)
88+
reloaded = ModelPackage.load(str(output_dir))
89+
graph = reloaded["model"].graph
90+
assert len(graph.inputs) == 34
91+
assert len(graph.outputs) == 33
92+
assert graph.inputs[2].name == "past_key_values.0.conv_state"
93+
assert graph.inputs[4].name == "past_key_values.1.key"
94+
95+
5096
@pytest.mark.integration
5197
@pytest.mark.integration_slow
5298
def test_nemotron_parse_real_weight_cuda_parity():

0 commit comments

Comments
 (0)