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+
9541098def _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
0 commit comments