Skip to content

Commit aa19199

Browse files
justinchubyCopilot
andauthored
Close the GGUF tokenizer census (#603)
## Summary - close the pinned llama.cpp tokenizer pre-tokenizer census at `8d9af256337d1a501250f9bbf4c0859a654bddd6`: 87 identifiers across 56 exact semantic groups - remove generic BPE/SentencePiece reconstruction and default all 87 policies to deferred unless a vocabulary-identical embedded `tokenizer.huggingface.json` can be copied verbatim - validate tokenizer tables, IDs, flags, merges, scores, UTF-8, templates, and source identity; pin Hub revisions/files and thread exact parsed GGUF snapshots through text and VLM builds - stage complete runtime packages transactionally, preserve tokenizer/config/chat assets, reject undeclared ORT GenAI MTP packaging, and document loader-consumed versus converter-only metadata ## Route counts - deferred by default: 87 - rejected pinned identifiers: 0 - exact-copy eligible when an embedded vocabulary-identical tokenizer JSON is present: 87 - unknown identifiers: rejected ## Validation - `2586 passed` — full GGUF suite - `50 passed` — complete CLI suite - `7015 passed, 52 skipped` — broad non-integration suite excluding the unrelated baseline `glm_moe_dsa` shape-inference case - full lintrunner clean - two independent full-diff reviews clean ## Current baseline note The unfiltered broad suite currently has two unrelated `glm_moe_dsa` output shape/checker failures; no files for that model are changed here. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 13b2f84 commit aa19199

14 files changed

Lines changed: 1647 additions & 699 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,104 @@ from mobius import build_from_gguf
99
> **Note**: Requires the optional `gguf` package:
1010
> `pip install mobius-onnx[gguf]`
1111
12+
## Tokenizer truthfulness
13+
14+
Graph import and runtime-package emission are separate capabilities. GGUF
15+
normally stores only an opaque `tokenizer.ggml.pre` identifier, not the full
16+
normalizer, pre-tokenizer, added-token, decoder, and post-processor pipeline.
17+
Mobius never substitutes a generic BPE/SentencePiece tokenizer.
18+
19+
The only materialized route is `copy`: the GGUF must contain
20+
`tokenizer.huggingface.json`, and its loadable ordered vocabulary must exactly
21+
match `tokenizer.ggml.tokens`. Mobius copies that tokenizer pipeline verbatim
22+
rather than claiming to reconstruct its opaque `pre` semantics, then writes
23+
`tokenizer_config.json`, `special_tokens_map.json`, and a provenance manifest.
24+
Otherwise the route is `deferred`: graph-only import remains available, while
25+
runtime packaging rejects incomplete metadata before durable output. Unknown
26+
identifiers and malformed or contradictory complete tokenizer tables reject
27+
before graph construction.
28+
29+
The graph package records a canonical digest of every tokenizer metadata field.
30+
Runtime packaging rechecks that digest before writing, so replacing a local
31+
GGUF between graph construction and package emission cannot mix tokenizer
32+
identity. The manifest reports ORT tokenizer compatibility as delegated to the
33+
embedded tokenizer JSON rather than claiming independent algorithm parity.
34+
35+
This generated policy table is pinned to llama.cpp commit
36+
`8d9af256337d1a501250f9bbf4c0859a654bddd6`. It enumerates all 87 accepted
37+
identifiers. Aliases share a row only where the pinned pre-type and hard-coded
38+
overrides are identical; every policy defaults to `deferred`.
39+
40+
| Canonical | Exact identifiers |
41+
|---|---|
42+
| `default` | `default` |
43+
| `minicpm5` | `minicpm5` |
44+
| `llama3` | `llama3`, `llama-v3`, `llama-bpe`, `falcon3`, `falcon-h1`, `pixtral`, `midm-2.0`, `lfm2`, `jina-v5-nano` |
45+
| `deepseek-llm` | `deepseek-llm` |
46+
| `deepseek-coder` | `deepseek-coder` |
47+
| `deepseek-v3` | `deepseek-v3` |
48+
| `youtu` | `youtu` |
49+
| `falcon` | `falcon` |
50+
| `mpt` | `mpt` |
51+
| `starcoder` | `starcoder` |
52+
| `gpt-2` | `gpt-2`, `phi-2`, `jina-es`, `jina-de`, `gigachat`, `jina-v2-es`, `jina-v2-de`, `a.x-4.0`, `mellum`, `modern-bert`, `exaone4` |
53+
| `jais-2` | `jais-2` |
54+
| `gemma4` | `gemma4`, `granite-embed-multi-311m` |
55+
| `sarvam-moe` | `sarvam-moe` |
56+
| `jina-v1-en` | `jina-v1-en`, `jina-v2-code`, `roberta-bpe` |
57+
| `whitespace` | `whitespace` |
58+
| `refact` | `refact` |
59+
| `command-r` | `command-r` |
60+
| `qwen2` | `qwen2`, `deepseek-r1-qwen`, `kormo`, `f2llmv2` |
61+
| `qwen35` | `qwen35` |
62+
| `stablelm2` | `stablelm2` |
63+
| `olmo` | `olmo` |
64+
| `dbrx` | `dbrx` |
65+
| `smaug-bpe` | `smaug-bpe` |
66+
| `poro-chat` | `poro-chat` |
67+
| `glm4` | `glm4`, `chatglm-bpe` |
68+
| `viking` | `viking` |
69+
| `jais` | `jais` |
70+
| `tekken` | `tekken` |
71+
| `smollm` | `smollm` |
72+
| `codeshell` | `codeshell` |
73+
| `bloom` | `bloom` |
74+
| `gpt3-finnish` | `gpt3-finnish` |
75+
| `exaone` | `exaone` |
76+
| `exaone-moe` | `exaone-moe` |
77+
| `chameleon` | `chameleon` |
78+
| `minerva-7b` | `minerva-7b` |
79+
| `megrez` | `megrez` |
80+
| `gpt-4o` | `gpt-4o`, `llama4`, `kanana2`, `talkie` |
81+
| `granite-embed-multi-97m` | `granite-embed-multi-97m` |
82+
| `tiny_aya` | `tiny_aya`, `cohere2moe` |
83+
| `superbpe` | `superbpe` |
84+
| `trillion` | `trillion` |
85+
| `granite-docling` | `granite-docling` |
86+
| `bailingmoe` | `bailingmoe`, `bailingmoe2`, `llada-moe` |
87+
| `seed-coder` | `seed-coder` |
88+
| `hunyuan` | `hunyuan` |
89+
| `hunyuan-dense` | `hunyuan-dense` |
90+
| `joyai-llm` | `joyai-llm` |
91+
| `kimi-k2` | `kimi-k2` |
92+
| `grok-2` | `grok-2` |
93+
| `afmoe` | `afmoe` |
94+
| `laguna` | `laguna` |
95+
| `minimax-m2` | `minimax-m2` |
96+
| `solar-open` | `solar-open` |
97+
| `mellum2` | `mellum2` |
98+
99+
### Metadata audit
100+
101+
The pinned loader consumes tokenizer model/pre, token strings/types/count,
102+
scores, merges, BOS/EOS/EOT/EOM/UNK/PAD/SEP/mask/FIM IDs, add-token and
103+
whitespace/normalizer flags, suppression IDs, precompiled charsmap, and
104+
default/named chat templates. `tokenizer.chat_templates` is the converter's
105+
named-template inventory. `tokenizer.huggingface.json` and
106+
`tokenizer.rwkv.world` are declared extension keys but are not consumed by the
107+
pinned vocabulary loader. There is no pinned GGUF `byte_fallback` field;
108+
byte-fallback behavior is implicit in the complete tokenizer pipeline.
109+
12110
## Signature
13111

14112
```python

‎docs/design/gguf-support-proposal.md‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ created by the ggml/llama.cpp ecosystem. It stores:
3030
- **Model metadata** as key-value pairs (architecture, hyperparameters,
3131
RoPE config, vocabulary, tokenizer)
3232
- **Tensor data** with per-tensor quantization type annotations
33-
- **Tokenizer** (vocabulary, merges, special tokens) — fully self-contained
33+
- **Tokenizer metadata** (vocabulary, merges, special tokens). This is not a
34+
complete tokenizer pipeline: `tokenizer.ggml.pre` selects compiled llama.cpp
35+
behavior that the file does not serialize.
3436

3537
GGUF is the successor to GGML/GGMF/GGJT formats and is the standard
3638
for quantized model distribution on HuggingFace (>50,000 GGUF models
@@ -443,9 +445,9 @@ construction. The only new code is the GGUF → HF bridge.
443445

444446
### 5.2 Optional
445447

446-
- **`transformers`** (already optional dep): For tokenizer extraction
447-
from GGUF. GGUF embeds the tokenizer, but constructing a proper
448-
`tokenizer.json` requires HF's converter classes.
448+
- **`tokenizers`** (via the transformers extra): validates an exact embedded
449+
`tokenizer.huggingface.json`. Mobius does not use Transformers' generic GGUF
450+
conversion because it does not reproduce the pinned `pre` dispatch.
449451

450452
### 5.3 Dependency Strategy
451453

@@ -1097,10 +1099,10 @@ Apache-2.0 licensed, and actively maintained.
10971099
`internlm2`). We need a mapping from GGUF architecture names to our
10981100
registry's `model_type` values.
10991101

1100-
3. **Tokenizer extraction**: GGUF embeds the tokenizer. Should we
1101-
extract and convert it to `tokenizer.json` format, or require the
1102-
user to provide a tokenizer separately? HF Transformers extracts the
1103-
tokenizer. We should do the same.
1102+
3. **Tokenizer extraction**: resolved. Mobius copies a complete embedded
1103+
`tokenizer.huggingface.json` only after ordered-vocabulary validation.
1104+
Ordinary GGUF tokenizer metadata remains graph-only/deferred because it
1105+
cannot reproduce the full tokenizer pipeline.
11041106

11051107
4. **K-quant precision**: The super-block → single-block flattening
11061108
for Q4_K is lossy. How much quality do we lose? This needs

‎src/mobius/__main__.py‎

Lines changed: 45 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,27 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
637637
"runtime packaging; omit --runtime to save the auxiliary graph and manifest."
638638
)
639639

640+
if runtime is not None:
641+
from mobius.integrations.gguf._builder import (
642+
_resolve_gguf_path,
643+
_validate_gguf_model,
644+
)
645+
from mobius.integrations.gguf._reader import GGUFModel
646+
from mobius.integrations.gguf._tokenizer import inspect_gguf_tokenizer
647+
648+
# Resolve and validate the exact selected source before graph construction
649+
# so a deferred tokenizer cannot leave a graph-only directory behind.
650+
gguf_path = _resolve_gguf_path(gguf_path)
651+
gguf_model = GGUFModel(gguf_path)
652+
_validate_gguf_model(gguf_model, source=str(gguf_path))
653+
tokenizer_verdict = inspect_gguf_tokenizer(
654+
gguf_model.metadata, source=str(gguf_path), require_complete=True
655+
)
656+
if not tokenizer_verdict.materialized:
657+
raise SystemExit(
658+
f"Error: cannot emit a complete {runtime} package: {tokenizer_verdict.reason}"
659+
)
660+
640661
pkg = build_from_gguf(
641662
gguf_path,
642663
mmproj=mmproj_path,
@@ -647,19 +668,23 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
647668
max_seq_len=args.max_seq_len,
648669
reuse_gguf_weights=reuse_gguf_weights,
649670
target_config=target_config,
671+
_gguf_model=gguf_model if runtime is not None else None,
650672
)
651673

652674
if args.release:
653675
for model in pkg.values():
654676
strip_debug_metadata(model)
655677

656-
os.makedirs(output_dir, exist_ok=True)
657-
pkg.save(
658-
output_dir,
659-
external_data=args.external_data,
660-
max_shard_size_bytes=_parse_size(args.max_shard_size) if args.max_shard_size else None,
661-
max_workers=args.max_workers,
662-
)
678+
if runtime is None:
679+
os.makedirs(output_dir, exist_ok=True)
680+
pkg.save(
681+
output_dir,
682+
external_data=args.external_data,
683+
max_shard_size_bytes=(
684+
_parse_size(args.max_shard_size) if args.max_shard_size else None
685+
),
686+
max_workers=args.max_workers,
687+
)
663688
for name in pkg:
664689
use_subfolders = len(pkg) > 1
665690
if use_subfolders:
@@ -685,26 +710,19 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
685710
if runtime in ("onnx-genai", "ort-genai"):
686711
from mobius.integrations.gguf import write_gguf_runtime_package
687712

688-
# The graph is already saved above; this adds the tokenizer (rebuilt
689-
# from the GGUF's embedded ggml metadata, since a GGUF checkpoint has
690-
# no Hugging Face source directory) and the runtime's own contract.
691713
artifacts = write_gguf_runtime_package(
692-
pkg, gguf_path, output_dir, runtime=runtime, save_model=False
714+
pkg,
715+
gguf_path,
716+
output_dir,
717+
runtime=runtime,
718+
external_data=args.external_data,
719+
max_shard_size_bytes=(
720+
_parse_size(args.max_shard_size) if args.max_shard_size else None
721+
),
722+
max_workers=args.max_workers,
693723
)
694724
for name, path in artifacts.items():
695725
print(f" {name}: {path}")
696-
if mtp_head is not None:
697-
from mobius.integrations.onnx_genai.inference_metadata import (
698-
write_mtp_speculator_metadata,
699-
)
700-
701-
spec_path = write_mtp_speculator_metadata(
702-
output_dir,
703-
backbone_config=getattr(pkg, "config", None),
704-
proposer_config=getattr(mtp_head, "config", None),
705-
)
706-
if spec_path is not None:
707-
print(f" speculator: {spec_path}")
708726

709727

710728
def _cmd_convert_comfyui(args: argparse.Namespace) -> None:
@@ -1227,10 +1245,10 @@ def build_parser() -> argparse.ArgumentParser:
12271245
default=None,
12281246
help=(
12291247
"Generate runtime-specific config files after building. "
1230-
"'onnx-genai' writes inference_metadata.yaml plus a tokenizer.json "
1231-
"reconstructed from the GGUF's embedded tokenizer metadata; "
1232-
"'ort-genai' is currently rejected until GGUF cache/tokenizer "
1233-
"contracts have runtime generation coverage."
1248+
"Both routes require an exact tokenizer.huggingface.json embedded in "
1249+
"the GGUF; opaque tokenizer.ggml.pre metadata is not reconstructed. "
1250+
"'onnx-genai' writes inference_metadata.yaml and 'ort-genai' writes "
1251+
"genai_config.json."
12341252
),
12351253
)
12361254
gguf_parser.add_argument(

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

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from collections import Counter
2525
from collections.abc import Callable, Collection, Iterable, Mapping
2626
from pathlib import Path
27-
from typing import TYPE_CHECKING
27+
from typing import TYPE_CHECKING, Any
2828
from urllib.parse import urlparse
2929

3030
import tqdm
@@ -621,6 +621,13 @@ def _validate_gguf_model(
621621
from mobius.integrations.gguf._draft import validate_draft_tensor_contract
622622

623623
validate_draft_tensor_contract(gguf_model)
624+
if not allow_mmproj_companion:
625+
from mobius.integrations.gguf._tokenizer import inspect_gguf_tokenizer
626+
627+
# Validate tokenizer identity and tables before config extraction. A
628+
# known-but-deferred tokenizer is allowed for graph-only imports; an
629+
# unknown or contradictory tokenizer is not.
630+
inspect_gguf_tokenizer(gguf_model.metadata, source=source)
624631

625632

626633
def _raise_for_invalid_dense_c01_tensor_contract(gguf_model) -> None:
@@ -1731,15 +1738,21 @@ def _resolve_gguf_path_impl(gguf_path: str | Path, *, allow_mmproj_companion: bo
17311738

17321739
# Split the optional ":filename" suffix before classifying so HF refs like
17331740
# "owner/repo:weights.gguf" are not mistaken for a local path ending in .gguf.
1734-
repo_id, _, filename = raw.partition(":")
1741+
repo_revision, _, filename = raw.partition(":")
1742+
repo_id, revision_separator, requested_revision = repo_revision.partition("@")
1743+
revision = requested_revision if revision_separator else "main"
1744+
if not revision:
1745+
raise ValueError(f"HF GGUF reference {raw!r} has an empty revision")
17351746
if not _looks_like_hf_repo_id(repo_id):
17361747
# Looks like a local path that doesn't exist; let GGUFModel raise
17371748
# FileNotFoundError with the original path.
17381749
return raw
17391750

17401751
api = HfApi()
17411752
if not filename:
1742-
files = [f for f in api.list_repo_files(repo_id) if f.endswith(".gguf")]
1753+
files = [
1754+
f for f in api.list_repo_files(repo_id, revision=revision) if f.endswith(".gguf")
1755+
]
17431756
if not files:
17441757
raise FileNotFoundError(f"No *.gguf files found in HF repo {repo_id!r}")
17451758
if len(files) > 1:
@@ -1754,13 +1767,13 @@ def _resolve_gguf_path_impl(gguf_path: str | Path, *, allow_mmproj_companion: bo
17541767
resolved_revision = _preflight_hf_mmproj_companion_file(
17551768
repo_id,
17561769
filename,
1757-
revision="main",
1770+
revision=revision,
17581771
)
17591772
else:
17601773
resolved_revision = _preflight_hf_gguf_file(
17611774
repo_id,
17621775
filename,
1763-
revision="main",
1776+
revision=revision,
17641777
)
17651778
logger.info("Downloading %s from %s", filename, repo_id)
17661779
if resolved_revision is None:
@@ -1797,6 +1810,7 @@ def build_from_gguf(
17971810
allow_dense_moe: bool | None = None,
17981811
reuse_gguf_weights: bool = False,
17991812
target_config: str | Path | Mapping[str, object] | None = None,
1813+
_gguf_model: Any | None = None,
18001814
) -> ModelPackage:
18011815
"""Build an ONNX :class:`ModelPackage` from a GGUF file.
18021816
@@ -1896,12 +1910,14 @@ def build_from_gguf(
18961910
raise ValueError("static_cache=True is not supported with a companion mmproj.")
18971911
from mobius.integrations.gguf._mmproj import build_vlm_from_gguf
18981912

1913+
parsed_source = {"_text_gguf_model": _gguf_model} if _gguf_model is not None else {}
18991914
return build_vlm_from_gguf(
19001915
gguf_path,
19011916
mmproj,
19021917
dtype=dtype,
19031918
execution_provider=execution_provider,
19041919
keep_quantized=keep_quantized,
1920+
**parsed_source,
19051921
)
19061922

19071923
from mobius._builder import (
@@ -1937,7 +1953,7 @@ def build_from_gguf(
19371953
# A ``-000i-of-000N.gguf`` split set is assembled directly from its shards
19381954
# (never merged into a second on-disk GGUF); a plain file opens as before.
19391955
gguf_path = _resolve_gguf_path(gguf_path)
1940-
gguf_model = open_gguf_model(gguf_path)
1956+
gguf_model = _gguf_model if _gguf_model is not None else open_gguf_model(gguf_path)
19411957
_validate_gguf_model(gguf_model, source=str(gguf_path))
19421958
if reuse_gguf_weights and isinstance(gguf_model, GgufShardSet):
19431959
raise ValueError(
@@ -1950,6 +1966,9 @@ def build_from_gguf(
19501966
"external tensors interpret the referenced bytes as little-endian. "
19511967
"Build without reuse to convert this file."
19521968
)
1969+
from mobius.integrations.gguf._tokenizer import inspect_gguf_tokenizer
1970+
1971+
tokenizer_verdict = inspect_gguf_tokenizer(gguf_model.metadata, source=str(gguf_path))
19531972
gguf_arch = gguf_model.architecture
19541973
if static_cache and int(gguf_model.metadata.get(f"{gguf_arch}.nextn_predict_layers", 0)):
19551974
raise ValueError(
@@ -2337,6 +2356,8 @@ def build_from_gguf(
23372356

23382357
if draft_manifest is not None:
23392358
pkg.draft_manifest = draft_manifest
2359+
pkg.gguf_source_path = str(Path(gguf_path).resolve())
2360+
pkg.gguf_tokenizer_verdict = tokenizer_verdict
23402361

23412362
return pkg
23422363

0 commit comments

Comments
 (0)