Skip to content

Commit 0de76c6

Browse files
justinchubyCopilot
andcommitted
Enable PLaMo2 ORT GenAI recurrent state
Align PLaMo2's public recurrent-state ABI with ORT GenAI 0.15.2 while preserving sparse alternating layer indices. Package the immutable custom tokenizer sources, propagate remote-code trust during chat-template discovery, and record exact token-ID generation plus the tokenizer format limitation. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 846b298 commit 0de76c6

8 files changed

Lines changed: 80 additions & 25 deletions

File tree

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4505,7 +4505,7 @@ def _inputs(batch: int) -> dict[str, np.ndarray]:
45054505
"position_ids": np.asarray([[0, 1], [0, 1]][:batch], np.int64),
45064506
"attention_mask": np.ones((batch, 2), np.int64),
45074507
"past_key_values.0.conv_state": np.zeros((batch, 32, 3), np.float32),
4508-
"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),
45094509
"past_key_values.1.key": np.zeros((batch, 2, 0, 8), np.float32),
45104510
"past_key_values.1.value": np.zeros((batch, 2, 0, 8), np.float32),
45114511
}
@@ -4534,13 +4534,13 @@ def test_float_import_executes_and_round_trips(self, tmp_path: Path) -> None:
45344534
model.graph.initializers[initializer_name].const_value.numpy(),
45354535
source_tensors[source_name],
45364536
)
4537-
assert model.metadata_props["mobius.runtime_support"].endswith(
4538-
"onnxruntime/mobius#605"
4537+
assert model.metadata_props["mobius.runtime_support"] == (
4538+
"ORT GenAI 0.15.2 state ABI; package requires GQA-specialized attention"
45394539
)
45404540
assert [value.name for value in model.graph.outputs] == [
45414541
"logits",
45424542
"present.0.conv_state",
4543-
"present.0.ssm_state",
4543+
"present.0.recurrent_state",
45444544
"present.1.key",
45454545
"present.1.value",
45464546
]
@@ -4549,7 +4549,7 @@ def test_float_import_executes_and_round_trips(self, tmp_path: Path) -> None:
45494549
session = OnnxModelSession(ModelPackage.load(output_dir)["model"])
45504550
outputs = session.run(self._inputs(2))
45514551
assert outputs["logits"].shape == (2, 2, 64)
4552-
assert outputs["present.0.ssm_state"].dtype == np.float32
4552+
assert outputs["present.0.recurrent_state"].dtype == np.float32
45534553

45544554
def test_legacy_scalar_heads_infer_exact_tensor_schedule(self, tmp_path: Path) -> None:
45554555
from mobius.integrations.gguf import build_from_gguf

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,13 +205,15 @@ def _revision_kwargs(revision: str | None) -> dict[str, str]:
205205

206206
_TOKENIZER_FILES = [
207207
"tokenizer.json",
208+
"tokenizer.jsonl", # PLaMo2 scored vocabulary
208209
"tokenizer_config.json",
209210
"special_tokens_map.json",
210211
"tokenizer.model", # SentencePiece
211212
"added_tokens.json",
212213
"merges.txt", # BPE
213214
"vocab.json", # BPE
214215
"chat_template.jinja", # Chat template for ORT GenAI
216+
"tokenization_plamo.py", # PLaMo2's exact custom tokenizer implementation
215217
# Preserve HuggingFace processor metadata for VLMs whose preprocessing
216218
# cannot be represented by an ort-extensions image_processor.json.
217219
"preprocessor_config.json",
@@ -480,6 +482,7 @@ def _fix_chat_template(
480482
hf_model_id: str | None,
481483
*,
482484
revision: str | None = None,
485+
trust_remote_code: bool = False,
483486
) -> bool:
484487
"""Ensure chat_template is present in tokenizer_config.json.
485488
@@ -511,6 +514,7 @@ def _fix_chat_template(
511514

512515
tokenizer = AutoTokenizer.from_pretrained(
513516
hf_model_id,
517+
trust_remote_code=trust_remote_code,
514518
**_revision_kwargs(revision),
515519
)
516520
template = getattr(tokenizer, "chat_template", None)
@@ -1763,7 +1767,12 @@ def write_ort_genai_config(
17631767
_fix_tokenizer_config(directory)
17641768

17651769
# Ensure chat_template is in tokenizer_config.json
1766-
_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+
)
17671776

17681777
# Correct assets that ship broken from upstream
17691778
apply_asset_patches(directory)

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -810,10 +810,20 @@ def test_adds_chat_template(self, tmp_path):
810810
with mock.patch(
811811
"transformers.AutoTokenizer.from_pretrained",
812812
return_value=fake_tokenizer,
813-
):
814-
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+
)
815820

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

@@ -949,7 +959,9 @@ def test_copies_present_files(self, tmp_path):
949959
src = tmp_path / "model"
950960
src.mkdir()
951961
(src / "tokenizer.json").write_text('{"test": true}')
962+
(src / "tokenizer.jsonl").write_text('["token", 0.0, "NORMAL"]\n')
952963
(src / "tokenizer_config.json").write_text('{"model_type": "llama"}')
964+
(src / "tokenization_plamo.py").write_text("class Plamo2Tokenizer: pass\n")
953965
(src / "chat_template.jinja").write_text("{{ messages }}")
954966

955967
dst = tmp_path / "output"
@@ -958,7 +970,9 @@ def test_copies_present_files(self, tmp_path):
958970

959971
assert set(copied) == {
960972
"tokenizer.json",
973+
"tokenizer.jsonl",
961974
"tokenizer_config.json",
975+
"tokenization_plamo.py",
962976
"chat_template.jinja",
963977
}
964978
assert (dst / "tokenizer.json").read_text() == '{"test": true}'

‎src/mobius/models/plamo2_test.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def _empty_states(config: Plamo2Config, batch: int) -> dict[str, np.ndarray]:
6060
"past_key_values.0.conv_state": np.zeros(
6161
(batch, config.mamba_inner_size, config.mamba_d_conv - 1), np.float32
6262
),
63-
"past_key_values.0.ssm_state": np.zeros(
63+
"past_key_values.0.recurrent_state": np.zeros(
6464
(
6565
batch,
6666
config.mamba_num_heads,
@@ -226,7 +226,9 @@ def assign(name: str, scale: float = 0.05) -> np.ndarray:
226226
rtol=1e-6,
227227
atol=1e-7,
228228
)
229-
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+
)
230232

231233

232234
def test_plamo2_attention_and_mlp_match_independent_reduced_reference() -> None:
@@ -404,7 +406,9 @@ def test_plamo2_left_padding_does_not_change_recurrent_state_or_valid_logits() -
404406
padded["present.0.conv_state"], unpadded["present.0.conv_state"], atol=1e-7
405407
)
406408
np.testing.assert_allclose(
407-
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,
408412
)
409413

410414

‎src/mobius/tasks/_plamo2.py‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def build(self, module: nn.Module, config: BaseModelConfig) -> ModelPackage:
7474
[batch, config.mamba_inner_size, config.mamba_d_conv - 1],
7575
)
7676
state_b = builder.input(
77-
f"past_key_values.{layer}.ssm_state",
77+
f"past_key_values.{layer}.recurrent_state",
7878
ir.DataType.FLOAT,
7979
[
8080
batch,
@@ -130,7 +130,7 @@ def build(self, module: nn.Module, config: BaseModelConfig) -> ModelPackage:
130130
config.mamba_d_state,
131131
]
132132
)
133-
names = ("conv_state", "ssm_state")
133+
names = ("conv_state", "recurrent_state")
134134
state_b.type = ir.TensorType(ir.DataType.FLOAT)
135135
state_a.type = ir.TensorType(config.dtype)
136136
builder.add_output(state_a, f"present.{layer}.{names[0]}")
@@ -139,15 +139,14 @@ def build(self, module: nn.Module, config: BaseModelConfig) -> ModelPackage:
139139
model = _make_model(graph)
140140
self._register_functions(model, config)
141141
model.metadata_props["mobius.cache_abi"] = (
142-
"per-layer:attention=key,value;mamba=conv_state,ssm_state-f32"
142+
"per-layer:attention=key,value;mamba=conv_state,recurrent_state-f32"
143143
)
144144
model.metadata_props["mobius.state_semantics"] = (
145145
"batch-axis reorder;copy-for-rollback;deterministic replay"
146146
)
147147
model.metadata_props["mobius.max_verified_context"] = str(config.attention_window_size)
148148
model.metadata_props["mobius.runtime_support"] = (
149-
"deferred: released ORT GenAI cannot represent heterogeneous recurrent/KV "
150-
"state; see onnxruntime/mobius#605"
149+
"ORT GenAI 0.15.2 state ABI; package requires GQA-specialized attention"
151150
)
152151
return ModelPackage({"model": model}, config=config)
153152

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ generation:
1515
max_new_tokens: 20
1616
do_sample: false
1717

18-
notes: "The pinned source checkpoint and public F32 GGUF pass raw ORT prefill, all cached decode steps, rollback/replay, and exact 20-token generation. ORT GenAI remains deferred because 0.15.2 cannot bind the heterogeneous recurrent/KV state ABI."
18+
notes: "The pinned source checkpoint and public F32 GGUF pass raw ORT prefill, all cached decode steps, rollback/replay, and exact 20-token generation. ORT GenAI 0.15.2 also passes exact token-ID generation through its sparse KV+recurrent ABI on a CPU-specialized GQA package; unspecialized Attention plus recurrent state is rejected during package config generation. Text tokenization remains deferred because the official custom tokenizer has no identity-preserving tokenizer.json representation."

‎testdata/evidence/causal-lm/plamo2-1b-real.json‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@
9393
],
9494
"sha256": "5a9a6638087d4b76fff79e102e665fb963e505cd17812f909cfc33e42a29b640",
9595
"state_interfaces": 16,
96-
"state_abi": "even layers: conv_state+ssm_state; odd layers: key+value"
96+
"state_abi": "even layers: conv_state+recurrent_state (semantic SSM state); odd layers: key+value"
9797
},
9898
"independent_reference": {
9999
"implementation": "pinned HuggingFace remote model with upstream pure-PyTorch causal_conv1d_ref and selective_state_update_ref equivalents",
@@ -209,18 +209,46 @@
209209
},
210210
"ort_genai": {
211211
"released_version": "0.15.2",
212+
"released_source_tree": "ed5f4e87147731e5b07810f9f5c90103b3603cdf",
212213
"generated_model_type": "decoder",
213-
"generated_state_schema": "homogeneous past_key_names/past_value_names templates",
214+
"attention_graph": "CPU-specialized export with all eight attention layers lowered to GroupQueryAttention; unspecialized Attention plus recurrent state is rejected by package config generation",
215+
"generated_state_schema": "sparse global layer indices with key/value on odd layers and conv_state/recurrent_state on even layers",
214216
"model_load": "passed with type=decoder and num_hidden_layers=16 discovered from sparse global state indices",
215-
"tokenizer_load": "failed: the exact packaged tokenizer.jsonl format is not accepted by ORT GenAI 0.15.2",
216-
"generation_with_prompt_tokens": "failed: Model input was not found: past_key_values.0.recurrent_state",
217+
"state_contract_proof": "v0.15.2 src/models/kv_cache.cpp independently discovers sparse key inputs; src/models/recurrent_state.cpp independently discovers sparse conv_state inputs and derives paired recurrent_state names",
218+
"generation_with_prompt_tokens": "passed: [1,6721] generated the exact verified 20-token continuation",
219+
"generated_tokens": [
220+
44,
221+
2268,
222+
1101,
223+
1080,
224+
1087,
225+
8789,
226+
45114,
227+
2002,
228+
3104,
229+
1131,
230+
1385,
231+
1031,
232+
73,
233+
39,
234+
109,
235+
2569,
236+
3648,
237+
353,
238+
32,
239+
79135
240+
],
241+
"tokenizer_source_revision": "92c75fd6eea9018bcb9c33ee8921589febe071fa",
242+
"tokenizer_jsonl_sha256": "9fa8276a87dd2440bb9496f1d569c05ded6274fd2854de802e12dc6545804b95",
243+
"tokenizer_identity": "all 100000 ordered tokens, token types, float32 scores, and special IDs 0/1/2/3 match the pinned GGUF exactly; the official tokenizer has no normalizer or pre-tokenizer",
244+
"tokenizer_load": "deferred with exact rejection: ORT GenAI 0.15.2 requires tokenizer.json and reports Invalid file; a standard Unigram(byte_fallback=true) conversion is not identical because official encoding of literal <0xFA> is [60,48,120,5109,62] while the standard tokenizer emits byte token [250]",
217245
"upstream_main_commit": "a8e0fdf81b061e67c1c3f9485bfdc06735ccd473",
218246
"upstream_main_install": "not feasible from the Python source package: pip built UNKNOWN-0.0.0 without an onnxruntime_genai module",
219-
"promotion_decision": "blocked: no released heterogeneous-state schema, no compatible tokenizer artifact, and no successful end-to-end generation"
247+
"promotion_decision": "token-ID generation passed; text-tokenizer entry points remain deferred because no identity-preserving tokenizer.json representation was proven"
220248
},
221249
"l4_l5": {
222250
"raw_ort_parity": "passed",
223251
"generated_tokens_committed": true,
224-
"ort_genai_e2e": "deferred because released ORT GenAI cannot represent the alternating state ABI"
252+
"ort_genai_e2e": "passed on the CPU-specialized GQA package with exact prompt token IDs; text tokenization remains deferred by the proven tokenizer-format mismatch"
225253
}
226254
}

‎tests/build_graph_test.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ def test_graph_builds_without_weights(self, model_type: str, config_overrides: d
288288
assert f"present.{i}.conv_state" in output_names, (
289289
f"Missing present.{i}.conv_state"
290290
)
291-
assert f"present.{i}.ssm_state" in output_names, (
292-
f"Missing present.{i}.ssm_state"
291+
state_name = "recurrent_state" if model_type == "plamo2" else "ssm_state"
292+
assert f"present.{i}.{state_name}" in output_names, (
293+
f"Missing present.{i}.{state_name}"
293294
)
294295
elif ltype == "conv":
295296
assert f"present.{i}.conv_state" in output_names, (

0 commit comments

Comments
 (0)