Skip to content

Commit ee521b0

Browse files
authored
Validate exact GPT4O GGUF tokenizer routes (#650)
## Summary - reconstruct the Talkie tokenizer from its exact GGUF-native ordered vocabulary, types, merges, and special metadata, canonicalized to pinned llama.cpp GPT4O semantics - validate Talkie and Kanana2 independently against pinned llama.cpp across 444 adversarial, seeded-random, special-token, detokenization, and chat-template cases - keep `gpt-4o` and `llama4` fail closed with immutable candidate dispositions: wrong dispatch/inventory for the former, incomplete under-limit shard for the latter - generate compact network-free evidence and documentation for artifact/source identities, hashes, embedding rows, padding, and route-specific blockers ## Validation - all-files `lintrunner` - focused GGUF tokenizer/docs tests: 88 passed - broad serial suite: 8,352 passed, 57 skipped, 12 deselected, 1 subtest passed --------- Signed-off-by: Justin Chu <[email protected]> Copilot-Session: d5d1d772-b7f9-4243-b8de-a13634d0da7b
1 parent c83c668 commit ee521b0

10 files changed

Lines changed: 789 additions & 12 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 7 additions & 5 deletions
Large diffs are not rendered by default.

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,18 @@ def _tokenizer_evidence_table() -> str:
342342
f"`{evidence.source_config_asset[0]}` {evidence.source_config_asset[1]:,} B "
343343
f"`{evidence.source_config_asset[2]}`<br>{assets}"
344344
)
345+
reconstruction = (
346+
f"<br>GGUF-native GPT4O reconstruction; {evidence.source_disposition}"
347+
if evidence.reconstruct_gpt4o_from_gguf
348+
else ""
349+
)
350+
oracle = (
351+
f"<br>llama.cpp oracle `{evidence.llamacpp_oracle[0]}`: "
352+
f"{evidence.llamacpp_oracle[1]} cases "
353+
f"`{evidence.llamacpp_oracle[2]}`"
354+
if evidence.llamacpp_oracle is not None
355+
else ""
356+
)
345357
proof = (
346358
f"validated identifiers `{list(evidence.validated_identifiers)}`<br>"
347359
f"metadata `{evidence.tokenizer_metadata_sha256}`<br>"
@@ -352,6 +364,7 @@ def _tokenizer_evidence_table() -> str:
352364
f"rows={evidence.embedding_vocabulary_size:,}<br>"
353365
f"materialized `{evidence.materialized_tokenizer_sha256}`<br>{encodings}"
354366
f"{'<br>' + special_encodings if special_encodings else ''}"
367+
f"{reconstruction}{oracle}"
355368
)
356369
rows.append(
357370
"| "

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

Lines changed: 179 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,52 @@
9898
"use_regex": True,
9999
},
100100
}
101+
_GPT4O_SOURCE_SPLIT_PATTERN = (
102+
r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*"
103+
r"[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|"
104+
r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+"
105+
r"[\p{Ll}\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|"
106+
r"\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|"
107+
r"\s*[\r\n]+|\s+(?!\S)|\s+"
108+
)
109+
_GPT4O_SPLIT_PATTERN = (
110+
r"[^\r\n\p{L}\p{N}]?((?=[\p{L}])([^a-z]))*"
111+
r"((?=[\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|"
112+
r"'[mM]|'[lL][lL]|'[dD])?|[^\r\n\p{L}\p{N}]?"
113+
r"((?=[\p{L}])([^a-z]))+((?=[\p{L}])([^A-Z]))*"
114+
r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|"
115+
r"\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|"
116+
r"\s*[\r\n]+|\s+(?!\S)|\s+"
117+
)
118+
_GPT4O_PRE_TOKENIZER = {
119+
"type": "Sequence",
120+
"pretokenizers": [
121+
{
122+
"type": "Split",
123+
"pattern": {"Regex": _GPT4O_SPLIT_PATTERN},
124+
"behavior": "Isolated",
125+
"invert": False,
126+
},
127+
{
128+
"type": "ByteLevel",
129+
"add_prefix_space": False,
130+
"trim_offsets": True,
131+
"use_regex": False,
132+
},
133+
],
134+
}
135+
_GPT4O_POST_BYTE_LEVEL = {
136+
"type": "ByteLevel",
137+
"add_prefix_space": True,
138+
"trim_offsets": False,
139+
"use_regex": True,
140+
}
141+
_GPT4O_DECODER = {
142+
"type": "ByteLevel",
143+
"add_prefix_space": True,
144+
"trim_offsets": True,
145+
"use_regex": True,
146+
}
101147

102148
# Audited against the pinned C++ loader. ``tokenizer.huggingface.json`` and
103149
# ``tokenizer.chat_templates`` are converter/extension fields; llama.cpp does
@@ -171,6 +217,7 @@ class GGUFTokenizerSource:
171217
materialized_tokenizer_sha256: str | None = None
172218
representative_encodings: tuple[tuple[str, tuple[int, ...]], ...] = ()
173219
representative_special_encodings: tuple[tuple[str, tuple[int, ...]], ...] = ()
220+
reconstruct_gpt4o_from_gguf: bool = False
174221

175222
def __post_init__(self) -> None:
176223
if self.repository.count("/") != 1 or not all(self.repository.split("/")):
@@ -791,6 +838,28 @@ def _special_token_content(value: Any, *, key: str) -> str:
791838
raise ValueError(f"tokenizer_config.json {key} must be a string or token object")
792839

793840

841+
def _canonicalize_gpt4o_tokenizer_config(
842+
metadata: Mapping[str, Any],
843+
config: dict[str, Any],
844+
) -> dict[str, Any]:
845+
config = dict(config)
846+
tokens = metadata["tokenizer.ggml.tokens"]
847+
for suffix, name in (
848+
("bos_token_id", "bos_token"),
849+
("eos_token_id", "eos_token"),
850+
("unknown_token_id", "unk_token"),
851+
("padding_token_id", "pad_token"),
852+
):
853+
token_id = metadata.get(f"tokenizer.ggml.{suffix}")
854+
if token_id is not None:
855+
config[name] = tokens[token_id]
856+
for name in ("add_bos_token", "add_eos_token", "add_sep_token"):
857+
value = metadata.get(f"tokenizer.ggml.{name}")
858+
if value is not None:
859+
config[name] = value
860+
return config
861+
862+
794863
_ADDED_TOKEN_FIELDS = frozenset(
795864
{"content", "single_word", "lstrip", "rstrip", "normalized", "special"}
796865
)
@@ -951,9 +1020,86 @@ def _roberta_processor_proves_special_insertion(
9511020
)
9521021

9531022

1023+
def _template_processor_proves_bos_insertion(
1024+
tokenizer_json: Mapping[str, Any],
1025+
metadata: Mapping[str, Any],
1026+
) -> bool:
1027+
processor = tokenizer_json.get("post_processor")
1028+
if not isinstance(processor, Mapping) or processor.get("type") != "Sequence":
1029+
return False
1030+
processors = processor.get("processors")
1031+
if not isinstance(processors, list) or len(processors) != 2:
1032+
return False
1033+
template = processors[1]
1034+
token_id = metadata.get("tokenizer.ggml.bos_token_id")
1035+
tokens = metadata.get("tokenizer.ggml.tokens")
1036+
if (
1037+
processors[0] != _GPT4O_POST_BYTE_LEVEL
1038+
or not isinstance(template, Mapping)
1039+
or template.get("type") != "TemplateProcessing"
1040+
or type(token_id) is not int
1041+
or not isinstance(tokens, list)
1042+
or not 0 <= token_id < len(tokens)
1043+
):
1044+
return False
1045+
token = tokens[token_id]
1046+
special = {"SpecialToken": {"id": token, "type_id": 0}}
1047+
special_pair = {"SpecialToken": {"id": token, "type_id": 1}}
1048+
return (
1049+
template.get("single") == [special, {"Sequence": {"id": "A", "type_id": 0}}]
1050+
and template.get("pair")
1051+
== [
1052+
special,
1053+
{"Sequence": {"id": "A", "type_id": 0}},
1054+
special_pair,
1055+
{"Sequence": {"id": "B", "type_id": 1}},
1056+
]
1057+
and template.get("special_tokens", {}).get(token)
1058+
== {"id": token, "ids": [token_id], "tokens": [token]}
1059+
)
1060+
1061+
1062+
def _canonicalize_gpt4o_pipeline(
1063+
tokenizer_json: dict[str, Any],
1064+
metadata: Mapping[str, Any],
1065+
*,
1066+
pre: str,
1067+
) -> None:
1068+
pre_tokenizer = tokenizer_json.get("pre_tokenizer")
1069+
source_pre_tokenizer = {
1070+
**_GPT4O_PRE_TOKENIZER,
1071+
"pretokenizers": [
1072+
{
1073+
**_GPT4O_PRE_TOKENIZER["pretokenizers"][0],
1074+
"pattern": {"Regex": _GPT4O_SOURCE_SPLIT_PATTERN},
1075+
},
1076+
_GPT4O_PRE_TOKENIZER["pretokenizers"][1],
1077+
],
1078+
}
1079+
post_processor = tokenizer_json.get("post_processor")
1080+
valid_post_processor = post_processor == _GPT4O_POST_BYTE_LEVEL or (
1081+
metadata.get("tokenizer.ggml.add_bos_token") is True
1082+
and _template_processor_proves_bos_insertion(tokenizer_json, metadata)
1083+
)
1084+
if (
1085+
tokenizer_json.get("normalizer") is not None
1086+
or pre_tokenizer not in (source_pre_tokenizer, _GPT4O_PRE_TOKENIZER)
1087+
or tokenizer_json.get("decoder") != _GPT4O_DECODER
1088+
or not valid_post_processor
1089+
):
1090+
raise ValueError(f"Pinned tokenizer pipeline differs from GGUF pre {pre!r}")
1091+
tokenizer_json["pre_tokenizer"] = _GPT4O_PRE_TOKENIZER
1092+
model = tokenizer_json.get("model")
1093+
if not isinstance(model, dict):
1094+
raise TypeError("tokenizer.json must contain a mutable model object")
1095+
model["ignore_merges"] = False
1096+
1097+
9541098
def _validate_pinned_tokenizer(
9551099
metadata: Mapping[str, Any],
9561100
payloads: Mapping[str, bytes],
1101+
*,
1102+
reconstruct_gpt4o_from_gguf: bool = False,
9571103
) -> tuple[str, bytes]:
9581104
raw_tokenizer = payloads["tokenizer.json"]
9591105
tokenizer_json = _json_object(raw_tokenizer, filename="tokenizer.json")
@@ -968,6 +1114,18 @@ def _validate_pinned_tokenizer(
9681114
model = tokenizer_json.get("model")
9691115
if not isinstance(model, Mapping):
9701116
raise TypeError("tokenizer.json must contain a model object")
1117+
pre = metadata.get("tokenizer.ggml.pre")
1118+
policy = tokenizer_pre_policies().get(pre)
1119+
if reconstruct_gpt4o_from_gguf:
1120+
if policy is None or policy.pre_type != "GPT4O" or not isinstance(model, dict):
1121+
raise ValueError("GGUF-native reconstruction is supported only for GPT4O BPE")
1122+
model["merges"] = metadata.get("tokenizer.ggml.merges")
1123+
config = _canonicalize_gpt4o_tokenizer_config(metadata, config)
1124+
if policy is not None and policy.pre_type == "GPT4O":
1125+
_canonicalize_gpt4o_pipeline(tokenizer_json, metadata, pre=pre)
1126+
raw_tokenizer = json.dumps(
1127+
tokenizer_json, ensure_ascii=False, separators=(",", ":")
1128+
).encode()
9711129

9721130
try:
9731131
from tokenizers import Tokenizer
@@ -1031,7 +1189,6 @@ def _validate_pinned_tokenizer(
10311189
raise ValueError(
10321190
"Pinned tokenizer merge order differs from GGUF tokenizer.ggml.merges"
10331191
)
1034-
pre = metadata.get("tokenizer.ggml.pre")
10351192
if (
10361193
pre == "smollm"
10371194
and {
@@ -1112,12 +1269,17 @@ def _validate_pinned_tokenizer(
11121269
tokenizer_json, metadata, gguf_name
11131270
):
11141271
continue
1272+
if (
1273+
gguf_name == "add_bos_token"
1274+
and expected is True
1275+
and _template_processor_proves_bos_insertion(tokenizer_json, metadata)
1276+
):
1277+
continue
11151278
if expected is not False:
11161279
raise ValueError(f"Pinned tokenizer cannot prove GGUF {config_name}")
11171280
elif actual is not expected:
11181281
raise ValueError(f"Pinned tokenizer {config_name} differs from GGUF")
11191282

1120-
policy = tokenizer_pre_policies().get(pre)
11211283
if (
11221284
policy is not None
11231285
and policy.pre_type == "GPT2_ADD_SEP"
@@ -1290,7 +1452,21 @@ def materialize_gguf_tokenizer(
12901452
if verdict.metadata_sha256 != source.metadata_sha256:
12911453
raise ValueError("Pinned tokenizer evidence does not match GGUF tokenizer metadata")
12921454
payloads = _download_tokenizer_assets(source, local_files_only=local_files_only)
1293-
tokenizer_sha256, tokenizer_payload = _validate_pinned_tokenizer(metadata, payloads)
1455+
tokenizer_sha256, tokenizer_payload = _validate_pinned_tokenizer(
1456+
metadata,
1457+
payloads,
1458+
reconstruct_gpt4o_from_gguf=source.reconstruct_gpt4o_from_gguf,
1459+
)
1460+
if source.reconstruct_gpt4o_from_gguf:
1461+
config = _json_object(
1462+
payloads.get("tokenizer_config.json", b"{}"),
1463+
filename="tokenizer_config.json",
1464+
)
1465+
payloads["tokenizer_config.json"] = json.dumps(
1466+
_canonicalize_gpt4o_tokenizer_config(metadata, config),
1467+
ensure_ascii=False,
1468+
separators=(",", ":"),
1469+
).encode()
12941470
if (
12951471
source.materialized_tokenizer_sha256 is not None
12961472
and tokenizer_sha256 != source.materialized_tokenizer_sha256

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

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
]
2626
TokenizerBlocker = Literal[
2727
"pinned-artifact-source-parity-pending",
28+
"pinned-candidate-identifier-mismatch",
29+
"pinned-candidate-incomplete-shard",
30+
"pinned-candidate-source-merge-mismatch",
2831
"pinned-candidate-source-token-mismatch",
2932
"compiled-llama.cpp-semantic-dependency",
3033
]
@@ -53,6 +56,45 @@ class GGUFTokenizerRouteAudit:
5356

5457

5558
_PINNED_CANDIDATE_DISPOSITIONS = {
59+
"gpt-4o": GGUFTokenizerRouteAudit(
60+
identifier="gpt-4o",
61+
semantic_group="gpt-4o",
62+
pre_type="GPT4O",
63+
default_policy="deferred",
64+
current_status="deferred-pinned-artifact-evidence",
65+
evidence_id=None,
66+
artifact_repository="mradermacher/oh-dcft-v3.1-gpt-4o-mini-GGUF",
67+
artifact_revision="41c1d48055e3192a907c0ffc2a886288e9040e33",
68+
artifact_filename="oh-dcft-v3.1-gpt-4o-mini.Q2_K.gguf",
69+
artifact_size=3_179_132_928,
70+
artifact_sha256="e14b14b73e0f7f35b234df7c5f1a585869d1fb3634331d489b4184b61cec5d29",
71+
tokenizer_repository="Xenova/gpt-4o",
72+
tokenizer_revision="7956d98f2a83b2751a98ea7136fdf7fe6cf54e69",
73+
tokenizer_assets=(
74+
(
75+
"special_tokens_map.json",
76+
98,
77+
"7003e1e385ae2f4b32ca9ca8637c352553922adad120266cf82238155a21dd16",
78+
),
79+
(
80+
"tokenizer.json",
81+
9_729_051,
82+
"43a3ad4618a6a938f8c2614154ea10c31ad53a62d5683ae0b0e6133575cef07e",
83+
),
84+
(
85+
"tokenizer_config.json",
86+
236,
87+
"71424d4750066a6f9bcfea0699576c4284327ff25d388d42419506bcfb5535ab",
88+
),
89+
),
90+
blocker_category="pinned-candidate-identifier-mismatch",
91+
candidate_disposition=(
92+
"name-only candidate rejected: its complete GGUF header dispatches llama-bpe, "
93+
"not gpt-4o, and has 128256 tokens; the pinned llama.cpp fingerprint source has "
94+
"200000 vocabulary entries plus 2 added tokens and is tokenizer-only, with no "
95+
"model config, chat template, or embedding rows"
96+
),
97+
),
5698
"jina-v1-en": GGUFTokenizerRouteAudit(
5799
identifier="jina-v1-en",
58100
semantic_group="jina-v1-en",
@@ -95,6 +137,34 @@ class GGUFTokenizerRouteAudit:
95137
"U+0000; deterministic padding starts only at id 60516"
96138
),
97139
),
140+
"llama4": GGUFTokenizerRouteAudit(
141+
identifier="llama4",
142+
semantic_group="gpt-4o",
143+
pre_type="GPT4O",
144+
default_policy="deferred",
145+
current_status="deferred-pinned-artifact-evidence",
146+
evidence_id=None,
147+
artifact_repository="ggml-org/Llama-4-Scout-17B-16E-Instruct-GGUF",
148+
artifact_revision="42675345da11ade9203a5187595da7b74d4ff2ac",
149+
artifact_filename="Llama-4-Scout-17B-16E-Instruct-Q4_K_M-00002-of-00002.gguf",
150+
artifact_size=15_511_520_608,
151+
artifact_sha256="53d9a61b90e38330daa4bb07afe56aa3e74a3d3aa31d344c053ebbdcfe5d59fe",
152+
tokenizer_repository="meta-llama/Llama-4-Scout-17B-16E-Instruct",
153+
tokenizer_revision="92f3b1597a195b523d8d9e5700e57e4fbb8f20d3",
154+
tokenizer_assets=(
155+
(
156+
"tokenizer.json",
157+
27_948_578,
158+
"172c9eb4beafc72601690da3ccfcede5c2e6806a8d5ec1fca33e22acea8023a4",
159+
),
160+
),
161+
blocker_category="pinned-candidate-incomplete-shard",
162+
candidate_disposition=(
163+
"the only pinned Q4_K_M file within 16 GiB is shard 2 of 2; its complete "
164+
"header has only split metadata, 145 of 628 tensors, no tokenizer fields, and "
165+
"no embedding tensor, while shard 1 is 49848377344 bytes"
166+
),
167+
),
98168
}
99169

100170

0 commit comments

Comments
 (0)