Skip to content

Commit 0e791a5

Browse files
justinchubyCopilot
andcommitted
Harden exact tokenizer publication
Validate the complete SmolLM tokenizer pipeline rather than only its presence and publish runtime package directories with platform no-replace atomics to prevent concurrent destination clobbering. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 288987e commit 0e791a5

4 files changed

Lines changed: 168 additions & 12 deletions

File tree

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

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@
1616

1717
from __future__ import annotations
1818

19+
import ctypes
1920
import os
2021
import shutil
22+
import sys
2123
import tempfile
2224
from pathlib import Path
2325
from typing import Any, Literal
@@ -38,6 +40,53 @@
3840

3941
__all__ = ["write_gguf_runtime_package"]
4042

43+
44+
def _publish_directory_no_replace(stage: Path, destination: Path) -> None:
45+
"""Atomically publish a directory while refusing an existing destination."""
46+
if sys.platform == "linux":
47+
libc = ctypes.CDLL(None, use_errno=True)
48+
renameat2 = getattr(libc, "renameat2", None)
49+
if renameat2 is None:
50+
raise OSError(
51+
"Atomic no-replace directory publication requires renameat2 on Linux"
52+
)
53+
renameat2.argtypes = [
54+
ctypes.c_int,
55+
ctypes.c_char_p,
56+
ctypes.c_int,
57+
ctypes.c_char_p,
58+
ctypes.c_uint,
59+
]
60+
renameat2.restype = ctypes.c_int
61+
result = renameat2(
62+
-100,
63+
os.fsencode(stage),
64+
-100,
65+
os.fsencode(destination),
66+
1,
67+
)
68+
elif sys.platform == "darwin":
69+
libc = ctypes.CDLL(None, use_errno=True)
70+
renamex_np = libc.renamex_np
71+
renamex_np.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]
72+
renamex_np.restype = ctypes.c_int
73+
result = renamex_np(os.fsencode(stage), os.fsencode(destination), 0x00000004)
74+
elif os.name == "nt":
75+
os.rename(stage, destination)
76+
return
77+
else:
78+
raise OSError(
79+
f"Atomic no-replace directory publication is unsupported on {sys.platform!r}"
80+
)
81+
if result != 0:
82+
error_number = ctypes.get_errno()
83+
raise OSError(
84+
error_number,
85+
os.strerror(error_number),
86+
str(destination),
87+
)
88+
89+
4190
Runtime = Literal["onnx-genai", "ort-genai"]
4291

4392

@@ -263,7 +312,7 @@ def write_gguf_runtime_package(
263312
f"sha256={evidence.runtime_package_sha256}; "
264313
f"got files={runtime_identity.files}, sha256={runtime_identity.sha256}."
265314
)
266-
os.replace(stage, output_dir)
315+
_publish_directory_no_replace(stage, output_dir)
267316
return {
268317
name: str(output_dir / Path(path).relative_to(stage))
269318
for name, path in artifacts.items()

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import pytest
1313

14-
from mobius.integrations.gguf import write_gguf_runtime_package
14+
from mobius.integrations.gguf import _runtime_package, write_gguf_runtime_package
1515
from mobius.integrations.gguf._spec import Support
1616

1717
_TOKENIZER_REPOSITORY = "owner/tokenizer"
@@ -105,6 +105,19 @@ def _runtime_supported():
105105

106106

107107
class TestWriteGgufRuntimePackage:
108+
def test_atomic_publication_refuses_concurrent_destination(self, tmp_path):
109+
stage = tmp_path / "stage"
110+
stage.mkdir()
111+
(stage / "model.onnx").write_bytes(b"staged")
112+
output = tmp_path / "output"
113+
output.mkdir()
114+
115+
with pytest.raises(FileExistsError):
116+
_runtime_package._publish_directory_no_replace(stage, output)
117+
118+
assert (stage / "model.onnx").read_bytes() == b"staged"
119+
assert not list(output.iterdir())
120+
108121
def test_deferred_architecture_rejects_before_source_read_or_output(self, tmp_path):
109122
pkg = _FakePackage()
110123
out = tmp_path / "out"

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

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,28 @@
7474
}
7575
)
7676
_MAX_TOKENIZER_ASSET_BYTES = 64 * 1024 * 1024
77+
_SMOLLM_PIPELINE = {
78+
"normalizer": None,
79+
"pre_tokenizer": {
80+
"type": "Sequence",
81+
"pretokenizers": [
82+
{"type": "Digits", "individual_digits": True},
83+
{
84+
"type": "ByteLevel",
85+
"add_prefix_space": False,
86+
"trim_offsets": True,
87+
"use_regex": True,
88+
},
89+
],
90+
},
91+
"post_processor": None,
92+
"decoder": {
93+
"type": "ByteLevel",
94+
"add_prefix_space": True,
95+
"trim_offsets": True,
96+
"use_regex": True,
97+
},
98+
}
7799

78100
# Audited against the pinned C++ loader. ``tokenizer.huggingface.json`` and
79101
# ``tokenizer.chat_templates`` are converter/extension fields; llama.cpp does
@@ -792,11 +814,18 @@ def _validate_pinned_tokenizer(
792814
raise ValueError(
793815
"Pinned tokenizer merge order differs from GGUF tokenizer.ggml.merges"
794816
)
795-
if (
796-
metadata.get("tokenizer.ggml.pre") is not None
797-
and tokenizer_json.get("pre_tokenizer") is None
798-
):
799-
raise ValueError("Pinned tokenizer omits pre-tokenizer semantics required by GGUF")
817+
pre = metadata.get("tokenizer.ggml.pre")
818+
expected_pipeline = _SMOLLM_PIPELINE if pre == "smollm" else None
819+
if expected_pipeline is None:
820+
raise ValueError(
821+
f"Pinned tokenizer pipeline validation is not implemented for GGUF pre {pre!r}"
822+
)
823+
actual_pipeline = {
824+
name: tokenizer_json.get(name)
825+
for name in ("normalizer", "pre_tokenizer", "post_processor", "decoder")
826+
}
827+
if actual_pipeline != expected_pipeline:
828+
raise ValueError(f"Pinned tokenizer pipeline differs from GGUF pre {pre!r}")
800829
token_types = metadata.get("tokenizer.ggml.token_type")
801830
if token_types is not None:
802831
unsupported_types = sorted(set(token_types) - {1, 2, 3})
@@ -845,7 +874,7 @@ def _validate_pinned_tokenizer(
845874
if expected is None:
846875
continue
847876
if actual is None:
848-
if expected is not False or tokenizer_json.get("post_processor") is not None:
877+
if expected is not False:
849878
raise ValueError(f"Pinned tokenizer cannot prove GGUF {config_name}")
850879
elif actual is not expected:
851880
raise ValueError(f"Pinned tokenizer {config_name} differs from GGUF")

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

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,26 @@ def test_write_exact_tokenizer_assets_removes_stale_default_template(tmp_path: P
339339
def _pinned_payloads(metadata: dict) -> dict[str, bytes]:
340340
tokenizer = json.loads(_tokenizer_json(metadata["tokenizer.ggml.tokens"]))
341341
tokenizer["model"]["merges"] = metadata["tokenizer.ggml.merges"]
342-
tokenizer["pre_tokenizer"] = {"type": "Whitespace"}
342+
tokenizer["normalizer"] = None
343+
tokenizer["pre_tokenizer"] = {
344+
"type": "Sequence",
345+
"pretokenizers": [
346+
{"type": "Digits", "individual_digits": True},
347+
{
348+
"type": "ByteLevel",
349+
"add_prefix_space": False,
350+
"trim_offsets": True,
351+
"use_regex": True,
352+
},
353+
],
354+
}
355+
tokenizer["post_processor"] = None
356+
tokenizer["decoder"] = {
357+
"type": "ByteLevel",
358+
"add_prefix_space": True,
359+
"trim_offsets": True,
360+
"use_regex": True,
361+
}
343362
tokenizer["added_tokens"] = [
344363
{
345364
"id": index,
@@ -418,7 +437,7 @@ def test_pinned_source_missing_tokenizer_json_rejects() -> None:
418437

419438

420439
def test_missing_pinned_hub_asset_leaves_no_output(tmp_path: Path, monkeypatch) -> None:
421-
metadata = _metadata()
440+
metadata = _metadata(pre="smollm")
422441
payloads = _pinned_payloads(metadata)
423442
source = _pinned_source(metadata, payloads)
424443
monkeypatch.setattr(
@@ -442,7 +461,7 @@ def test_missing_pinned_hub_asset_leaves_no_output(tmp_path: Path, monkeypatch)
442461
def test_tokenizer_evidence_metadata_mismatch_rejects_before_download(
443462
tmp_path: Path, monkeypatch
444463
) -> None:
445-
metadata = _metadata()
464+
metadata = _metadata(pre="smollm")
446465
payloads = _pinned_payloads(metadata)
447466
source = _pinned_source(metadata, payloads)
448467
source = GGUFTokenizerSource(
@@ -466,7 +485,7 @@ def test_tokenizer_evidence_metadata_mismatch_rejects_before_download(
466485

467486

468487
def test_semantic_mismatch_leaves_no_partial_output(tmp_path: Path, monkeypatch) -> None:
469-
metadata = _metadata()
488+
metadata = _metadata(pre="smollm")
470489
payloads = _pinned_payloads(metadata)
471490
config = json.loads(payloads["tokenizer_config.json"])
472491
config["bos_token"] = "<eos>"
@@ -486,6 +505,52 @@ def test_semantic_mismatch_leaves_no_partial_output(tmp_path: Path, monkeypatch)
486505
assert not output.exists()
487506

488507

508+
def test_pipeline_mismatch_leaves_no_partial_output(tmp_path: Path, monkeypatch) -> None:
509+
metadata = _metadata(pre="smollm")
510+
payloads = _pinned_payloads(metadata)
511+
tokenizer = json.loads(payloads["tokenizer.json"])
512+
tokenizer["pre_tokenizer"]["pretokenizers"].reverse()
513+
payloads["tokenizer.json"] = json.dumps(tokenizer).encode()
514+
source = _pinned_source(metadata, payloads)
515+
monkeypatch.setattr(_tokenizer, "_download_tokenizer_assets", lambda *_a, **_k: payloads)
516+
output = tmp_path / "output"
517+
518+
with pytest.raises(ValueError, match="pipeline differs"):
519+
materialize_gguf_tokenizer(
520+
tmp_path / "model.gguf",
521+
output,
522+
source=source,
523+
metadata=metadata,
524+
)
525+
526+
assert not output.exists()
527+
528+
529+
def test_post_processor_cannot_hide_matching_special_token_flags(
530+
tmp_path: Path, monkeypatch
531+
) -> None:
532+
metadata = _metadata(pre="smollm")
533+
payloads = _pinned_payloads(metadata)
534+
tokenizer = json.loads(payloads["tokenizer.json"])
535+
tokenizer["post_processor"] = {
536+
"type": "TemplateProcessing",
537+
"single": [{"SpecialToken": {"id": "<bos>", "type_id": 0}}],
538+
"pair": [{"Sequence": {"id": "A", "type_id": 0}}],
539+
"special_tokens": {"<bos>": {"id": "<bos>", "ids": [2], "tokens": ["<bos>"]}},
540+
}
541+
payloads["tokenizer.json"] = json.dumps(tokenizer).encode()
542+
source = _pinned_source(metadata, payloads)
543+
monkeypatch.setattr(_tokenizer, "_download_tokenizer_assets", lambda *_a, **_k: payloads)
544+
545+
with pytest.raises(ValueError, match="pipeline differs"):
546+
materialize_gguf_tokenizer(
547+
tmp_path / "model.gguf",
548+
tmp_path / "output",
549+
source=source,
550+
metadata=metadata,
551+
)
552+
553+
489554
def test_cross_host_asset_request_strips_auth_and_rejects_redirect(monkeypatch) -> None:
490555
payload = b"{}"
491556
source = GGUFTokenizerSource(

0 commit comments

Comments
 (0)