Skip to content

Commit 356fcdb

Browse files
justinchubyCopilot
andauthored
Materialize exact GGUF tokenizers (#608)
## Summary - materialize tokenizer assets only from an immutable, evidence-pinned Hugging Face revision with exact size and SHA-256 identities - verify ordered vocabulary/token IDs, merges, special IDs and flags, tokenizer pipeline assets, chat templates, and GGUF metadata identity before atomic package publication - bind the route through CLI, YAML/golden provenance, offline cache handling, redirect/auth safety, direct-GGUF transaction checks, and runtime evidence - promote only the exact SmolLM F16 artifact/CPU/ORT 1.29.0 route; retain fail-closed SmolLM2 rejection because its GGUF padding ID 0 contradicts the official pinned tokenizer padding ID 2 ## Validation - `386 passed` focused GGUF/tokenizer/runtime/CLI/schema suite - `2658 passed` full GGUF + CLI suite - `7062 passed, 52 skipped` broad affected suite; only the two pre-existing `glm_moe_dsa` shape-inference failures remain - `2 passed` real SmolLM/SmolLM2 runtime integration - `6 passed` targeted L4/L5 golden tests - lintrunner passed - two independent reviews completed and findings addressed Stacked on #607 via `justinchuby-validate-small-gguf-models`. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 0c2d501 commit 356fcdb

23 files changed

Lines changed: 1574 additions & 164 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,12 @@ from mobius import build_from_gguf
1515

1616
| Census | Total | Closure |
1717
|---|---:|---|
18-
| Architectures | 147 | graph verdicts: {'deferred': 88, 'rejected': 2, 'supported': 57}; importable: 55; quantized import: {'rejected': 11, 'supported': 136}; runtime: {'deferred': 145, 'rejected': 2} |
18+
| Architectures | 147 | graph verdicts: {'deferred': 88, 'rejected': 2, 'supported': 57}; importable: 55; quantized import: {'rejected': 11, 'supported': 136}; runtime: {'deferred': 144, 'rejected': 2, 'supported': 1} |
1919
| Active stored qtypes | 25 | 24 have an import route; 1 are explicitly deferred with no route |
2020
| Serialized projector strings | 60 | {'graph-importable': 2, 'runtime-supported': 0} |
21-
| Tokenizer pre identifiers | 87 | 56 semantic groups; all default to deferred and become exact-copy only with a validated embedded `tokenizer.huggingface.json` |
21+
| Tokenizer pre identifiers | 87 | 56 semantic groups; all default to deferred and become materializable only from a validated embedded `tokenizer.huggingface.json` or an exact pinned source in runtime evidence |
2222

23-
`SUPPORTED` means the named capability is implemented and mechanically tested. `DEFERRED` means it is intentionally unavailable pending the stated work. `REJECTED` means the input or route is invalid by policy. Graph support proves construction/execution only; runtime support additionally requires a pinned real artifact, independent parity, and deterministic generation or stateful semantics. Tokenizer `copy` delegates algorithm semantics to an embedded, vocabulary-identical tokenizer JSON; it is not a reconstructed or independently proven tokenizer.
23+
`SUPPORTED` means the named capability is implemented and mechanically tested. `DEFERRED` means it is intentionally unavailable pending the stated work. `REJECTED` means the input or route is invalid by policy. Graph support proves construction/execution only; runtime support additionally requires a pinned real artifact, independent parity, and deterministic generation or stateful semantics. Tokenizer `copy` delegates algorithm semantics to an embedded, vocabulary-identical tokenizer JSON. A `pinned-source` route additionally binds an immutable Hub revision, exact asset hashes, and all reconstructible GGUF tokenizer semantics.
2424

2525
<!-- END GGUF CLOSURE SUMMARY -->
2626

@@ -31,21 +31,20 @@ normally stores only an opaque `tokenizer.ggml.pre` identifier, not the full
3131
normalizer, pre-tokenizer, added-token, decoder, and post-processor pipeline.
3232
Mobius never substitutes a generic BPE/SentencePiece tokenizer.
3333

34-
The only materialized route is `copy`: the GGUF must contain
35-
`tokenizer.huggingface.json`, and its loadable ordered vocabulary must exactly
36-
match `tokenizer.ggml.tokens`. Mobius copies that tokenizer pipeline verbatim
37-
rather than claiming to reconstruct its opaque `pre` semantics, then writes
38-
`tokenizer_config.json`, `special_tokens_map.json`, and a provenance manifest.
39-
Otherwise the route is `deferred`: graph-only import remains available, while
40-
runtime packaging rejects incomplete metadata before durable output. Unknown
41-
identifiers and malformed or contradictory complete tokenizer tables reject
42-
before graph construction.
34+
The `copy` route requires `tokenizer.huggingface.json` in the GGUF and an exact
35+
ordered-vocabulary match. The `pinned-source` route is narrower: a runtime evidence
36+
record names one immutable Hub revision and every copied asset's size and SHA-256.
37+
Mobius additionally compares ordered token IDs, merge order, special-token IDs,
38+
flags, and chat templates against all corresponding GGUF metadata. The remaining
39+
normalizer, pre-tokenizer, decoder, and post-processor semantics are accepted only
40+
through those exact asset hashes, never reconstructed from `tokenizer.ggml.pre`.
41+
Any missing or contradictory field rejects before durable output.
4342

4443
The graph package records a canonical digest of every tokenizer metadata field.
4544
Runtime packaging rechecks that digest before writing, so replacing a local
4645
GGUF between graph construction and package emission cannot mix tokenizer
47-
identity. The manifest reports ORT tokenizer compatibility as delegated to the
48-
embedded tokenizer JSON rather than claiming independent algorithm parity.
46+
identity. The manifest records the selected route, immutable source revision,
47+
asset hashes, and GGUF tokenizer metadata hash.
4948

5049
This generated policy table is pinned to llama.cpp commit
5150
`8d9af256337d1a501250f9bbf4c0859a654bddd6`. It enumerates all 87 accepted
@@ -305,13 +304,11 @@ validated embedding owner, but Mobius never invents a second head or silently
305304
drops an explicit conflicting output.
306305

307306
Complete runtime packages are staged in a sibling temporary directory and
308-
replace the destination with rollback on an ordinary in-process publication
309-
failure. Replacement uses separate destination-to-backup and stage-to-destination
310-
renames: readers can briefly observe no destination, and a process or host crash
311-
between them requires manual recovery from the sibling backup. This is not a
312-
single-step atomic exchange, crash-durable transaction, or multi-process lock;
313-
callers must serialize concurrent writers. The source tokenizer digest is
314-
rechecked before publication. Publication also requires the exact runtime
307+
published with one atomic rename. An existing destination is rejected rather
308+
than moved aside, so readers never observe a replacement gap or mixed package.
309+
This is not a multi-process lock; callers racing to the same absent destination
310+
must handle one publication failure. The source tokenizer digest is rechecked
311+
before publication. Publication also requires the exact runtime
315312
version from the evidence record and rechecks the source filename, size, SHA-256,
316313
canonical architecture, tensor/qtype census, and complete graph-shaping import
317314
route captured during construction. The serialized ONNX file list and graph
@@ -421,7 +418,7 @@ before graph construction or durable output.
421418
| `lfm2moe` | — | model=`lfm2_moe`; tensor=`lfm2`+`lfm2_moe_extras` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=rejected | Config extraction, exact pinned tensor-name closure, GGUF value transforms, and synthetic recurrent-state execution are covered, but no representative real-weight GGUF has yet passed independent full-logit parity and deterministic multi-token stateful ORT generation. Runtime packaging remains deferred until that evidence exists. The mobius graph uses floating Linear modules for this architecture, so no MatMulNBits or BlockQuantizedMatMul target can consume preserved GGUF projection weights. Use keep_quantized=False for explicit float import. |
422419
| `llada` | — | model=`llada`; tensor=`llama` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Config extraction, suffix-exact tensor closure, masked-diffusion task dispatch, and synthetic full-sequence execution are covered, but no pinned real GGUF has passed independent Hugging Face/llama.cpp masked-step logit parity and deterministic multi-step generation parity. Runtime packaging remains deferred until both exist. |
423420
| `llada-moe` | — | model=`llada`; module=`llada_moe`; tensor=`llama`+`diffusion_fused_qkv`+`moe_qk_norm_extras`+`moe_extras` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Config extraction, suffix-exact tensor closure, masked-diffusion task dispatch, and synthetic full-sequence execution are covered, but no pinned real GGUF has passed independent Hugging Face/llama.cpp masked-step logit parity and deterministic multi-step generation parity. Runtime packaging remains deferred until both exist. |
424-
| `llama` | `mistral` | model=`llama`; tensor=`llama` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Config extraction, exact tensor-name closure, and a full synthetic GGUF graph build are covered, but no representative real-weight GGUF has yet passed ORT parity or generation validation. Runtime packaging remains deferred until that evidence exists. |
421+
| `llama` | `mistral` | model=`llama`; tensor=`llama` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=supported; quantized_import=supported | Runtime support is restricted to exact structured evidence matches. Currently that is only neopolita/smollm-135m-gguf F16 at the pinned artifact, CPU import route, ONNX Runtime 1.29.0, and HuggingFaceTB/SmolLM-135M tokenizer revision. |
425422
| `llama-embed` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | llama-embed is a canonical embedding architecture that inherits Llama's conditional tensor loader but exposes the embedding graph rather than causal logits. Mobius has no GGUF embedding task/package contract for this ID, so it must not alias ordinary llama. |
426423
| `llama4` | — | none (fails before config extraction) | exact-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | Llama4 GGUF is the text member of a paired multimodal package and may contain routed experts and architecture-specific cross-modal layer scheduling. The llama4 clip vision tower, token mixing, position IDs, and package ABI remain deferred; text-backbone similarity is not evidence that the complete GGUF tensor closure is owned. |
427424
| `maincoder` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | Maincoder applies Q/K RMSNorm after RoPE and uses an exact tied-output QK-normalized SwiGLU closure. Existing generic QK-normalized graphs use different ordering, so a family alias would change attention. |

‎src/mobius/__main__.py‎

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import json
1111
import logging
1212
import os
13+
import re
1314
from collections.abc import Sequence
1415
from typing import TYPE_CHECKING
1516

@@ -642,6 +643,16 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
642643
"Error: dflash/eagle3 target-coupled drafts do not support standalone "
643644
"runtime packaging; omit --runtime to save the auxiliary graph and manifest."
644645
)
646+
tokenizer_repository = getattr(args, "tokenizer_repository", None)
647+
tokenizer_revision = getattr(args, "tokenizer_revision", None)
648+
if (tokenizer_repository is None) != (tokenizer_revision is None):
649+
raise SystemExit(
650+
"Error: --tokenizer-repository and --tokenizer-revision must be provided together."
651+
)
652+
if runtime is None and tokenizer_repository is not None:
653+
raise SystemExit(
654+
"Error: pinned tokenizer materialization is only available with --runtime."
655+
)
645656

646657
if runtime is not None:
647658
from mobius.integrations.gguf._arch_registry import get_arch_spec
@@ -651,7 +662,6 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
651662
)
652663
from mobius.integrations.gguf._reader import GGUFModel
653664
from mobius.integrations.gguf._spec import Support
654-
from mobius.integrations.gguf._tokenizer import inspect_gguf_tokenizer
655665

656666
# Resolve and validate the exact selected source before graph construction
657667
# so a deferred tokenizer cannot leave a graph-only directory behind.
@@ -664,12 +674,18 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
664674
f"Error: GGUF runtime packaging for {architecture_spec.gguf_arch!r} is "
665675
f"{architecture_spec.runtime.value}: {architecture_spec.reason}"
666676
)
667-
tokenizer_verdict = inspect_gguf_tokenizer(
668-
gguf_model.metadata, source=str(resolved_gguf_path), require_complete=True
669-
)
670-
if not tokenizer_verdict.materialized:
677+
if tokenizer_repository is None or tokenizer_revision is None:
671678
raise SystemExit(
672-
f"Error: cannot emit a complete {runtime} package: {tokenizer_verdict.reason}"
679+
"Error: GGUF runtime packaging requires --tokenizer-repository and an "
680+
"immutable --tokenizer-revision."
681+
)
682+
if tokenizer_repository.count("/") != 1 or not all(tokenizer_repository.split("/")):
683+
raise SystemExit(
684+
"Error: --tokenizer-repository must be an owner/repository Hub ID."
685+
)
686+
if re.fullmatch(r"[0-9a-f]{40}", tokenizer_revision) is None:
687+
raise SystemExit(
688+
"Error: --tokenizer-revision must be an immutable 40-hex commit SHA."
673689
)
674690

675691
pkg = build_from_gguf(
@@ -730,6 +746,9 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
730746
output_dir,
731747
runtime=runtime,
732748
runtime_version=getattr(args, "runtime_version", None),
749+
tokenizer_repository=tokenizer_repository,
750+
tokenizer_revision=tokenizer_revision,
751+
local_files_only=getattr(args, "local_files_only", False),
733752
external_data=args.external_data,
734753
max_shard_size_bytes=(
735754
_parse_size(args.max_shard_size) if args.max_shard_size else None
@@ -1274,6 +1293,26 @@ def build_parser() -> argparse.ArgumentParser:
12741293
"runtime-supported evidence record; it must equal the version validated there."
12751294
),
12761295
)
1296+
gguf_parser.add_argument(
1297+
"--tokenizer-repository",
1298+
default=None,
1299+
metavar="OWNER/REPO",
1300+
help=(
1301+
"Exact Hugging Face repository containing tokenizer assets for runtime "
1302+
"packaging. Requires --tokenizer-revision and must match runtime evidence."
1303+
),
1304+
)
1305+
gguf_parser.add_argument(
1306+
"--tokenizer-revision",
1307+
default=None,
1308+
metavar="COMMIT_SHA",
1309+
help="Immutable 40-hex revision for --tokenizer-repository.",
1310+
)
1311+
gguf_parser.add_argument(
1312+
"--local-files-only",
1313+
action="store_true",
1314+
help="Use only already-cached pinned tokenizer assets; perform no Hub requests.",
1315+
)
12771316
gguf_parser.add_argument(
12781317
"--static-cache",
12791318
action="store_true",

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
# Multimodal (text + companion mmproj vision/audio encoder)
1919
pkg = build_from_gguf("path/to/model.gguf", mmproj="path/to/mmproj.gguf")
2020
21-
# Runtime packaging is fail-closed and currently unavailable because no
22-
# architecture has complete real-artifact runtime evidence.
21+
# Runtime packaging is fail-closed and available only for an exact artifact,
22+
# import route, runtime version, and pinned tokenizer evidence record.
2323
2424
:func:`build_from_gguf` is the single entry point; passing ``mmproj`` delegates
2525
to :func:`build_gemma4_vlm_from_gguf` for the multimodal assembly.
@@ -52,11 +52,19 @@
5252
discover_gguf_shards,
5353
open_gguf_model,
5454
)
55-
from mobius.integrations.gguf._tokenizer import write_gguf_tokenizer_json
55+
from mobius.integrations.gguf._tokenizer import (
56+
GGUFTokenizerAsset,
57+
GGUFTokenizerSource,
58+
materialize_gguf_tokenizer,
59+
write_gguf_tokenizer_json,
60+
)
5661

5762
__all__ = [
5863
"build_from_gguf",
5964
"build_gemma4_vlm_from_gguf",
65+
"GGUFTokenizerAsset",
66+
"GGUFTokenizerSource",
67+
"materialize_gguf_tokenizer",
6068
"write_gguf_runtime_package",
6169
"write_gguf_tokenizer_json",
6270
"verify_gguf_reuse_manifest",

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -679,8 +679,13 @@
679679
tensor_map_recipe=("llama",),
680680
tensor_processor="llama",
681681
llama_qk_permute=True,
682-
runtime=Support.DEFERRED,
683-
reason=_RUNTIME_VALIDATION_PENDING,
682+
runtime=Support.SUPPORTED,
683+
runtime_evidence_ids=("smollm-135m-f16-onnxruntime-1.29.0",),
684+
reason=(
685+
"Runtime support is restricted to exact structured evidence matches. Currently "
686+
"that is only neopolita/smollm-135m-gguf F16 at the pinned artifact, CPU import "
687+
"route, ONNX Runtime 1.29.0, and HuggingFaceTB/SmolLM-135M tokenizer revision."
688+
),
684689
),
685690
GGUFArchitectureSpec(
686691
gguf_arch="deci",

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ def _summary() -> str:
100100
(
101101
f"| Tokenizer pre identifiers | {len(tokenizers)} | "
102102
f"{len({policy.canonical for policy in tokenizers.values()})} semantic groups; "
103-
"all default to deferred and become exact-copy only with a validated embedded "
104-
"`tokenizer.huggingface.json` |"
103+
"all default to deferred and become materializable only from a validated embedded "
104+
"`tokenizer.huggingface.json` or an exact pinned source in runtime evidence |"
105105
),
106106
"",
107107
(
@@ -111,8 +111,9 @@ def _summary() -> str:
111111
"construction/execution only; runtime support additionally requires a pinned real "
112112
"artifact, independent parity, and deterministic generation or stateful semantics. "
113113
"Tokenizer `copy` delegates algorithm semantics to an embedded, "
114-
"vocabulary-identical tokenizer JSON; it is not a reconstructed or independently "
115-
"proven tokenizer."
114+
"vocabulary-identical tokenizer JSON. A `pinned-source` route additionally binds "
115+
"an immutable Hub revision, exact asset hashes, and all reconstructible GGUF "
116+
"tokenizer semantics."
116117
),
117118
)
118119
)

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,10 @@ def test_generated_census_counts_and_pin_are_closed() -> None:
4848

4949

5050
def test_runtime_support_requires_structured_evidence() -> None:
51-
# Architecture evidence is not yet represented as structured records, so no
52-
# architecture may claim runtime support by inheriting a permissive default.
53-
assert all(spec.runtime is not Support.SUPPORTED for spec in iter_arch_specs())
51+
supported = [spec for spec in iter_arch_specs() if spec.runtime is Support.SUPPORTED]
52+
assert [(spec.gguf_arch, spec.runtime_evidence_ids) for spec in supported] == [
53+
("llama", ("smollm-135m-f16-onnxruntime-1.29.0",))
54+
]
5455

5556
pins = {pin.artifact_id for pin in MMPROJ_ARTIFACT_PINS}
5657
for spec in iter_projector_specs():

0 commit comments

Comments
 (0)