Skip to content

Commit 9703140

Browse files
justinchubyCopilot
andauthored
Fix real PLaMo2 cached decode parity (#620)
## Summary - restore PLaMo2's published `1e4` local RoPE base for the legacy public GGUF profile whose metadata incorrectly declares `1e6` - preserve `A_log` and evaluate `-exp(A_log)` in the ONNX graph, including correct HF/GGUF and effectively-tied weight loading - align PLaMo2's public recurrent state ABI with ORT GenAI 0.15.2 and add durable real-model L4/L5 evidence ## Root cause The pinned GGUF declares `plamo2.rope.freq_base=1e6`, while the pinned HF architecture has `full_attention_idx=[]` and uses `rope_local_theta=1e4` for every attention layer. Trusting the contradictory GGUF field caused the first divergence in layer 1 attention during cached decode; later recurrent layers amplified it. Mamba state update, convolution orientation, attention QKV/QK norm, residual ordering, cache indexing, fusion, and rollback/replay were not the source. ## Real-model validation Pinned revisions: - HF `pfnet/plamo-2-1b`: `92c75fd6eea9018bcb9c33ee8921589febe071fa` - F32 GGUF: `184326afcef7232d94df09a33279598255890325` Raw ORT 1.29 CPU after the fix: - prefill max abs error: `5.34057617e-05` - first cached decode max abs error: `2.47955322e-05` - maximum over 19 cached steps: `4.62532043e-05` - exact 20/20 greedy token match - rollback/replay exact ORT GenAI 0.15.2 source independently discovers sparse KV indices and sparse `conv_state` indices, then derives the paired `recurrent_state` names. After renaming PLaMo2's semantic SSM state to that public ABI, a CPU-specialized package with all eight attention layers lowered to GQA loaded and generated the exact verified 20-token continuation from prompt IDs `[1, 6721]`. Unspecialized `Attention` plus recurrent state is still rejected during package config generation. The immutable tokenizer source was audited against the GGUF: all 100,000 ordered tokens, token types, float32 scores, and special IDs match exactly, with no normalizer or pre-tokenizer. Text tokenization remains deferred because ORT GenAI requires `tokenizer.json`, and standard Unigram byte fallback is not identity-preserving: the official tokenizer encodes literal `<0xFA>` as `[60, 48, 120, 5109, 62]`, while the standard tokenizer emits byte token `[250]`. ## Branch reconstruction Parent #617 was admin squash-merged as `79efe2c4512a40900ac5af5e794d057ea39c8f5b`. This branch was reconstructed directly on that commit and retains only the two reviewed #620 commits, preserving #617 as the explicit parent while removing its duplicated pre-squash history. ## Tests - focused PLaMo2 raw ORT state/rollback, GGUF, OGA metadata, evidence, tokenizer, and graph tests: 53 passed - PLaMo2 synthetic parity/weight selection: 2 passed, 1 expected skip - YAML model-case schema validation: 252 passed - broad non-integration suite: 7,525 passed, 54 skipped, 1 subtest passed - initialized pinned lintrunner tools; formatting and lint clean - GPT-5.6-sol medium post-rebase review: no actionable findings - durable real-model L4 passed and L5 matched 20/20 tokens; the removed 19 GB validation cache was not redownloaded --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 79efe2c commit 9703140

12 files changed

Lines changed: 301 additions & 93 deletions

File tree

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

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,7 @@ def _write_plamo2_gguf(
840840
legacy_scalar_heads: bool = False,
841841
quantized_embedding: bool = False,
842842
include_output: bool = False,
843+
rope_theta: float = 10_000.0,
843844
) -> None:
844845
"""Write a complete tiny alternating PLaMo2 GGUF."""
845846
from gguf import GGMLQuantizationType, GGUFWriter
@@ -867,7 +868,7 @@ def _write_plamo2_gguf(
867868
kv_heads if legacy_scalar_heads else kv_head_counts or [0, kv_heads]
868869
)
869870
writer.add_layer_norm_rms_eps(epsilon)
870-
writer.add_rope_freq_base(10_000.0)
871+
writer.add_rope_freq_base(rope_theta)
871872
writer.add_vocab_size(vocab)
872873
writer.add_ssm_conv_kernel(kernel)
873874
writer.add_ssm_inner_size(inner)
@@ -4504,7 +4505,7 @@ def _inputs(batch: int) -> dict[str, np.ndarray]:
45044505
"position_ids": np.asarray([[0, 1], [0, 1]][:batch], np.int64),
45054506
"attention_mask": np.ones((batch, 2), np.int64),
45064507
"past_key_values.0.conv_state": np.zeros((batch, 32, 3), np.float32),
4507-
"past_key_values.0.ssm_state": np.zeros((batch, 4, 8, 4), np.float32),
4508+
"past_key_values.0.recurrent_state": np.zeros((batch, 4, 8, 4), np.float32),
45084509
"past_key_values.1.key": np.zeros((batch, 2, 0, 8), np.float32),
45094510
"past_key_values.1.value": np.zeros((batch, 2, 0, 8), np.float32),
45104511
}
@@ -4533,13 +4534,13 @@ def test_float_import_executes_and_round_trips(self, tmp_path: Path) -> None:
45334534
model.graph.initializers[initializer_name].const_value.numpy(),
45344535
source_tensors[source_name],
45354536
)
4536-
assert model.metadata_props["mobius.runtime_support"].endswith(
4537-
"onnxruntime/mobius#605"
4537+
assert model.metadata_props["mobius.runtime_support"] == (
4538+
"ORT GenAI 0.15.2 state ABI; package requires GQA-specialized attention"
45384539
)
45394540
assert [value.name for value in model.graph.outputs] == [
45404541
"logits",
45414542
"present.0.conv_state",
4542-
"present.0.ssm_state",
4543+
"present.0.recurrent_state",
45434544
"present.1.key",
45444545
"present.1.value",
45454546
]
@@ -4548,7 +4549,7 @@ def test_float_import_executes_and_round_trips(self, tmp_path: Path) -> None:
45484549
session = OnnxModelSession(ModelPackage.load(output_dir)["model"])
45494550
outputs = session.run(self._inputs(2))
45504551
assert outputs["logits"].shape == (2, 2, 64)
4551-
assert outputs["present.0.ssm_state"].dtype == np.float32
4552+
assert outputs["present.0.recurrent_state"].dtype == np.float32
45524553

45534554
def test_legacy_scalar_heads_infer_exact_tensor_schedule(self, tmp_path: Path) -> None:
45544555
from mobius.integrations.gguf import build_from_gguf
@@ -4560,6 +4561,14 @@ def test_legacy_scalar_heads_infer_exact_tensor_schedule(self, tmp_path: Path) -
45604561
assert package.config.attention_head_counts == (0, 4)
45614562
assert package.config.attention_kv_head_counts == (0, 2)
45624563

4564+
def test_legacy_million_base_restores_reference_local_rope(self, tmp_path: Path) -> None:
4565+
from mobius.integrations.gguf import build_from_gguf
4566+
4567+
path = tmp_path / "plamo2-legacy-rope.gguf"
4568+
_write_plamo2_gguf(path, quantized=False, rope_theta=1_000_000.0)
4569+
package = build_from_gguf(path)
4570+
assert package.config.rope_theta == pytest.approx(10_000.0)
4571+
45634572
def test_quantized_source_preserves_exact_projection_roles(self, tmp_path: Path) -> None:
45644573
from mobius.integrations.gguf import build_from_gguf
45654574

@@ -4568,7 +4577,7 @@ def test_quantized_source_preserves_exact_projection_roles(self, tmp_path: Path)
45684577
model = build_from_gguf(path, keep_quantized=True)["model"]
45694578
assert sum(node.op_type == "MatMulNBits" for node in model.graph) == 9
45704579
assert (
4571-
model.graph.initializers["model.layers.0.mixer.A"].const_value.dtype
4580+
model.graph.initializers["model.layers.0.mixer.A_log"].const_value.dtype
45724581
== ir.DataType.FLOAT
45734582
)
45744583
assert (

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2244,6 +2244,14 @@ def _plamo2_postprocess(
22442244
fields.update(
22452245
hidden_act="silu",
22462246
head_dim=key_length,
2247+
# The released PLaMo2 converter wrote 1e6 here even though the pinned
2248+
# reference architecture uses its 1e4 local-RoPE default for every
2249+
# attention layer. Preserve other explicit bases for future variants.
2250+
rope_theta=(
2251+
10_000.0
2252+
if float(metadata[f"{arch}.rope.freq_base"]) == 1_000_000.0 # noqa: RUF069
2253+
else config.rope_theta
2254+
),
22472255
attention_head_counts=head_counts,
22482256
attention_kv_head_counts=kv_head_counts,
22492257
mamba_num_heads=ssm_heads,

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ def _revision_kwargs(revision: str | None) -> dict[str, str]:
108108
# ORT GenAI (see onnxruntime-genai/src/models/model_type.h LLM list).
109109
"hunyuan_v1_dense": "decoder",
110110
"deepseek_v4": "decoder",
111+
# PLaMo2 is a decoder-only hybrid. Released ORT GenAI does not have a
112+
# model-specific registry entry, so emit its generic decoder type.
113+
"plamo2": "decoder",
111114
# Qwen VL model families have separate ORT GenAI model types.
112115
"qwen2_vl": "qwen2_5_vl",
113116
"qwen3_vl": "qwen3_vl",
@@ -202,13 +205,15 @@ def _revision_kwargs(revision: str | None) -> dict[str, str]:
202205

203206
_TOKENIZER_FILES = [
204207
"tokenizer.json",
208+
"tokenizer.jsonl", # PLaMo2 scored vocabulary
205209
"tokenizer_config.json",
206210
"special_tokens_map.json",
207211
"tokenizer.model", # SentencePiece
208212
"added_tokens.json",
209213
"merges.txt", # BPE
210214
"vocab.json", # BPE
211215
"chat_template.jinja", # Chat template for ORT GenAI
216+
"tokenization_plamo.py", # PLaMo2's exact custom tokenizer implementation
212217
# Preserve HuggingFace processor metadata for VLMs whose preprocessing
213218
# cannot be represented by an ort-extensions image_processor.json.
214219
"preprocessor_config.json",
@@ -477,6 +482,7 @@ def _fix_chat_template(
477482
hf_model_id: str | None,
478483
*,
479484
revision: str | None = None,
485+
trust_remote_code: bool = False,
480486
) -> bool:
481487
"""Ensure chat_template is present in tokenizer_config.json.
482488
@@ -508,6 +514,7 @@ def _fix_chat_template(
508514

509515
tokenizer = AutoTokenizer.from_pretrained(
510516
hf_model_id,
517+
trust_remote_code=trust_remote_code,
511518
**_revision_kwargs(revision),
512519
)
513520
template = getattr(tokenizer, "chat_template", None)
@@ -1760,7 +1767,12 @@ def write_ort_genai_config(
17601767
_fix_tokenizer_config(directory)
17611768

17621769
# Ensure chat_template is in tokenizer_config.json
1763-
_fix_chat_template(directory, hf_model_id, revision=revision)
1770+
_fix_chat_template(
1771+
directory,
1772+
hf_model_id,
1773+
revision=revision,
1774+
trust_remote_code=trust_remote_code,
1775+
)
17641776

17651777
# Correct assets that ship broken from upstream
17661778
apply_asset_patches(directory)

‎src/mobius/integrations/ort_genai/auto_export_test.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,9 @@ def test_hunyuan_v1_dense_maps_to_decoder(self):
110110
# decoder-only causal LM not in its built-in registry.
111111
assert _resolve_ort_genai_model_type("hunyuan_v1_dense") == "decoder"
112112

113+
def test_plamo2_maps_to_generic_decoder(self):
114+
assert _resolve_ort_genai_model_type("plamo2") == "decoder"
115+
113116
def test_unknown_model_type_passthrough(self):
114117
assert _resolve_ort_genai_model_type("my_custom") == "my_custom"
115118

@@ -807,10 +810,20 @@ def test_adds_chat_template(self, tmp_path):
807810
with mock.patch(
808811
"transformers.AutoTokenizer.from_pretrained",
809812
return_value=fake_tokenizer,
810-
):
811-
result = _fix_chat_template(str(tmp_path), "fake/model")
813+
) as from_pretrained:
814+
result = _fix_chat_template(
815+
str(tmp_path),
816+
"fake/model",
817+
revision="immutable-revision",
818+
trust_remote_code=True,
819+
)
812820

813821
assert result is True
822+
from_pretrained.assert_called_once_with(
823+
"fake/model",
824+
revision="immutable-revision",
825+
trust_remote_code=True,
826+
)
814827
fixed = json.loads((tmp_path / "tokenizer_config.json").read_text())
815828
assert fixed["chat_template"] == "{{ bos_token }}"
816829

@@ -946,7 +959,9 @@ def test_copies_present_files(self, tmp_path):
946959
src = tmp_path / "model"
947960
src.mkdir()
948961
(src / "tokenizer.json").write_text('{"test": true}')
962+
(src / "tokenizer.jsonl").write_text('["token", 0.0, "NORMAL"]\n')
949963
(src / "tokenizer_config.json").write_text('{"model_type": "llama"}')
964+
(src / "tokenization_plamo.py").write_text("class Plamo2Tokenizer: pass\n")
950965
(src / "chat_template.jinja").write_text("{{ messages }}")
951966

952967
dst = tmp_path / "output"
@@ -955,7 +970,9 @@ def test_copies_present_files(self, tmp_path):
955970

956971
assert set(copied) == {
957972
"tokenizer.json",
973+
"tokenizer.jsonl",
958974
"tokenizer_config.json",
975+
"tokenization_plamo.py",
959976
"chat_template.jinja",
960977
}
961978
assert (dst / "tokenizer.json").read_text() == '{"test": true}'

‎src/mobius/models/plamo2.py‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,7 @@ def __init__(self, config: Plamo2Config):
140140
# dt participates in Softplus and remains float even for quantized GGUF imports.
141141
self.dt_proj = Linear(self.dt_rank, self.num_heads, bias=False)
142142
self.dt_bias = nn.Parameter([self.num_heads])
143-
# GGUF stores the already transformed negative decay directly.
144-
self.A = nn.Parameter([self.num_heads])
143+
self.A_log = nn.Parameter([self.num_heads])
145144
self.D = nn.Parameter([self.num_heads])
146145
self.dt_norm_weight = nn.Parameter([self.dt_rank])
147146
self.B_norm_weight = nn.Parameter([self.state_size])
@@ -198,7 +197,10 @@ def forward(
198197
)
199198
)
200199
dt = op.Mul(dt, op.CastLike(padding_mask, dt))
201-
decay = op.Mul(dt, op.Cast(self.A, to=ir.DataType.FLOAT))
200+
# Match the reference's float32 discretization at runtime rather than
201+
# baking a rounded -exp(A_log) into imported weights.
202+
a = op.Neg(op.Exp(op.Cast(self.A_log, to=ir.DataType.FLOAT)))
203+
decay = op.Mul(dt, a)
202204
x_f32 = op.Cast(x, to=ir.DataType.FLOAT)
203205
x_heads = op.Reshape(x_f32, [0, 0, self.num_heads, self.head_dim])
204206
value = op.Reshape(
@@ -414,7 +416,7 @@ def preprocess_weights(
414416
self,
415417
state_dict: dict[str, torch.Tensor],
416418
) -> dict[str, torch.Tensor]:
417-
"""Convert the official offset norms and Mamba decay to graph values."""
419+
"""Convert official and GGUF offset norms and Mamba decay names."""
418420
result: dict[str, torch.Tensor] = {}
419421
norm_offsets = {
420422
".pre_mixer_norm.weight": 1.0,
@@ -423,9 +425,16 @@ def preprocess_weights(
423425
".post_mlp_norm.weight": 1.0 / (5.0**1.5),
424426
}
425427
norms_are_folded = bool(getattr(self.config, "_plamo2_norms_are_folded", False))
428+
tied_embeddings = effective_tie_word_embeddings(self.config)
426429
for name, value in state_dict.items():
427430
name = name.replace("model.layers.layers.", "model.layers.")
428-
if name == "lm_head.weight" and self.config.tie_word_embeddings:
431+
if name == "model.embed_tokens.weight" and tied_embeddings:
432+
result[name] = value
433+
# onnxscript materializes the shared Parameter under both use
434+
# sites, while the official checkpoint stores only the embedding.
435+
result["lm_head.weight"] = value
436+
continue
437+
if name == "lm_head.weight" and tied_embeddings:
429438
continue
430439
if name == "model.norm.weight":
431440
result[name] = value if norms_are_folded else value + 1.0
@@ -436,8 +445,9 @@ def preprocess_weights(
436445
)
437446
if offset is not None:
438447
result[name] = value if norms_are_folded else value + offset
439-
elif name.endswith(".mixer.A_log"):
440-
result[name.removesuffix("A_log") + "A"] = -torch.exp(value)
448+
elif name.endswith(".mixer.A"):
449+
# llama.cpp serializes PLaMo2's A_log as -exp(A_log).
450+
result[name.removesuffix("A") + "A_log"] = torch.log(-value)
441451
else:
442452
result[name] = value
443453
return result

‎src/mobius/models/plamo2_test.py‎

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import torch
1111

1212
from mobius import build_from_module
13-
from mobius._configs import Plamo2Config
13+
from mobius._configs import Plamo2Config, QuantizationConfig
1414
from mobius._testing.ort_inference import OnnxModelSession
1515
from mobius.models.plamo2 import Plamo2ForCausalLM
1616
from mobius.tasks import Plamo2CausalLMTask
@@ -50,9 +50,7 @@ def _fill_weights(model: ir.Model) -> None:
5050
continue
5151
shape = [dim if isinstance(dim, int) else 1 for dim in initializer.shape]
5252
values = (rng.standard_normal(shape) * 0.03).astype(initializer.dtype.numpy())
53-
if initializer.name.endswith(".A"):
54-
values = -np.exp(values)
55-
elif "norm" in initializer.name:
53+
if "norm" in initializer.name:
5654
values += 1.0
5755
initializer.const_value = ir.Tensor(values)
5856

@@ -62,7 +60,7 @@ def _empty_states(config: Plamo2Config, batch: int) -> dict[str, np.ndarray]:
6260
"past_key_values.0.conv_state": np.zeros(
6361
(batch, config.mamba_inner_size, config.mamba_d_conv - 1), np.float32
6462
),
65-
"past_key_values.0.ssm_state": np.zeros(
63+
"past_key_values.0.recurrent_state": np.zeros(
6664
(
6765
batch,
6866
config.mamba_num_heads,
@@ -124,10 +122,8 @@ def test_plamo2_mamba_matches_independent_reduced_reference() -> None:
124122
initializer.const_value = ir.Tensor(value)
125123
values[initializer.name] = value
126124

127-
def assign(name: str, scale: float = 0.05, *, negative: bool = False) -> np.ndarray:
125+
def assign(name: str, scale: float = 0.05) -> np.ndarray:
128126
value = (rng.standard_normal(values[name].shape) * scale).astype(np.float32)
129-
if negative:
130-
value = -np.exp(value)
131127
model.graph.initializers[name].const_value = ir.Tensor(value)
132128
values[name] = value
133129
return value
@@ -138,7 +134,7 @@ def assign(name: str, scale: float = 0.05, *, negative: bool = False) -> np.ndar
138134
assign("model.layers.0.mixer.bcdt_proj.weight")
139135
assign("model.layers.0.mixer.dt_proj.weight")
140136
assign("model.layers.0.mixer.dt_bias")
141-
assign("model.layers.0.mixer.A", negative=True)
137+
assign("model.layers.0.mixer.A_log")
142138
assign("model.layers.0.mixer.D")
143139
assign("model.layers.0.mixer.out_proj.weight")
144140

@@ -204,7 +200,8 @@ def assign(name: str, scale: float = 0.05, *, negative: bool = False) -> np.ndar
204200
scan_outputs = []
205201
for index in range(input_ids.shape[1]):
206202
decay = np.exp(
207-
dt[:, index, :, None, None] * values["model.layers.0.mixer.A"][None, :, None, None]
203+
dt[:, index, :, None, None]
204+
* -np.exp(values["model.layers.0.mixer.A_log"])[None, :, None, None]
208205
)
209206
update = (
210207
dt[:, index, :, None, None]
@@ -229,7 +226,9 @@ def assign(name: str, scale: float = 0.05, *, negative: bool = False) -> np.ndar
229226
rtol=1e-6,
230227
atol=1e-7,
231228
)
232-
np.testing.assert_allclose(outputs["present.0.ssm_state"], state, rtol=2e-5, atol=2e-6)
229+
np.testing.assert_allclose(
230+
outputs["present.0.recurrent_state"], state, rtol=2e-5, atol=2e-6
231+
)
233232

234233

235234
def test_plamo2_attention_and_mlp_match_independent_reduced_reference() -> None:
@@ -407,7 +406,9 @@ def test_plamo2_left_padding_does_not_change_recurrent_state_or_valid_logits() -
407406
padded["present.0.conv_state"], unpadded["present.0.conv_state"], atol=1e-7
408407
)
409408
np.testing.assert_allclose(
410-
padded["present.0.ssm_state"], unpadded["present.0.ssm_state"], atol=1e-7
409+
padded["present.0.recurrent_state"],
410+
unpadded["present.0.recurrent_state"],
411+
atol=1e-7,
411412
)
412413

413414

@@ -451,6 +452,7 @@ def test_plamo2_preprocesses_offsets_and_decay_values() -> None:
451452
"model.layers.layers.0.pre_mlp_norm.weight": torch.tensor([5.0]),
452453
"model.layers.layers.0.post_mlp_norm.weight": torch.tensor([6.0]),
453454
"model.layers.layers.0.mixer.A_log": torch.tensor([0.0, 1.0]),
455+
"model.embed_tokens.weight": torch.tensor([8.0]),
454456
"lm_head.weight": torch.tensor([9.0]),
455457
}
456458
actual = model.preprocess_weights(weights)
@@ -468,10 +470,31 @@ def test_plamo2_preprocesses_offsets_and_decay_values() -> None:
468470
actual["model.layers.0.post_mlp_norm.weight"],
469471
torch.tensor([6.0 + 1.0 / (5.0**1.5)]),
470472
)
473+
torch.testing.assert_close(actual["model.layers.0.mixer.A_log"], torch.tensor([0.0, 1.0]))
474+
gguf_actual = model.preprocess_weights(
475+
{"model.layers.0.mixer.A": -torch.exp(torch.tensor([0.0, 1.0]))}
476+
)
471477
torch.testing.assert_close(
472-
actual["model.layers.0.mixer.A"], -torch.exp(torch.tensor([0.0, 1.0]))
478+
gguf_actual["model.layers.0.mixer.A_log"], torch.tensor([0.0, 1.0])
479+
)
480+
torch.testing.assert_close(actual["lm_head.weight"], torch.tensor([8.0]))
481+
482+
483+
def test_plamo2_preprocesses_effectively_tied_quantized_embeddings() -> None:
484+
config = _config()
485+
config.tie_word_embeddings = False
486+
config.quantization = QuantizationConfig(tie_word_embeddings=True)
487+
model = Plamo2ForCausalLM(config)
488+
489+
actual = model.preprocess_weights(
490+
{
491+
"model.embed_tokens.weight": torch.tensor([8.0]),
492+
"lm_head.weight": torch.tensor([9.0]),
493+
}
473494
)
474-
assert "lm_head.weight" not in actual
495+
496+
torch.testing.assert_close(actual["model.embed_tokens.weight"], torch.tensor([8.0]))
497+
torch.testing.assert_close(actual["lm_head.weight"], torch.tensor([8.0]))
475498

476499

477500
def test_plamo2_transformers_config_uses_explicit_schedule_and_pinned_defaults() -> None:

0 commit comments

Comments
 (0)