okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d86cebb9c
main
1"""tools/strata_tokenizer.py - the tokenizer, as the reference implementation of record. 2 3WHY THIS EXISTS AND WHERE IT SITS. The GGUF carries the whole tokenizer in metadata: `tokenizer.ggml.model` 4= `gpt2`, 248,320 `tokens`, 247,587 `merges`, `token_type`, `pre` = `qwen35`, and a Jinja `chat_template`. 5None of that needs the 35 GB of weights, so it is extracted into the pack's `tokenizer/` directory 6(docs/pack-format.md §6) and this module is what reads it back. A C++ port follows and is tested against 7this one. 8 9THE DECISIVE PROPERTY IS THE ROUND TRIP. Byte-level BPE maps each BYTE to a printable unicode character so 10that any UTF-8 input is representable with no UNK token. Every failure mode of that mapping - the wrong 11offset for a byte, a merge applied in the wrong order, a pre-tokenizer split that drops a character - still 12produces plausible token ids. `decode(encode(s)) == s` is the check that sees them, and it is exact because 13the byte layer is lossless. It is asserted over a corpus chosen to hit the boundaries: multi-byte UTF-8, 14emoji (4-byte), combining marks, whitespace runs, and C0 control bytes. 15""" 16from __future__import annotations 17 18import bisect 19import json 20import pathlib 21import sys 22import threading 23 24import regex 25 26# ------------------------------------------------------------------ byte <-> unicode (GPT-2 byte-level BPE) 27def bytes_to_unicode ()-> dict [int ,str ]: 28"""The GPT-2 byte encoder: 256 bytes -> 256 printable characters, reversibly. 29 30Bytes 33..126, 161..172 and 174..255 map to themselves; the remaining 68 (space, newline, the C0 31controls and the high range that would be invisible) are shifted into 256+n so that no byte is 32unprintable. The shift is the whole trick and getting its ORDER wrong is invisible in the output ids. 33""" 34bs = (list (range (0x21 ,0x7F ))+ list (range (0xA1 ,0xAD ))+ list (range (0xAE ,0x100 ))) 35cs = bs [:] 36n = 0 37for b in range (256 ): 38if b not in bs : 39bs .append (b ) 40cs .append (256 + n ) 41n += 1 42return dict (zip (bs , (chr (c )for c in cs ))) 43 44 45BYTE_TO_UNICODE = bytes_to_unicode () 46UNICODE_TO_BYTE = {v :k for k ,v in BYTE_TO_UNICODE .items ()} 47 48# The `qwen35` pre-tokenizer, transcribed from the ORACLE rather than from the family resemblance: 49# `.ref/llama.cpp/src/llama-vocab.cpp` L396, `case LLAMA_VOCAB_PRE_TYPE_QWEN35`. The commented-out line 50# above it is the `tokenizer.json` original, and llama.cpp's active version differs from it - it spells the 51# contraction classes out instead of using `(?i:...)`, which is behaviourally the same. 52# 53# THE `\p{M}` IS THE WHOLE POINT OF THIS BEING TRANSCRIBED. The QWEN3 pattern two cases earlier (L389) is 54# the same shape with `\p{L}` where this has `[\p{L}\p{M}]` and without `\p{M}` in the punctuation negation. 55# Writing the QWEN3 pattern for `qwen35` looks right, round-trips perfectly, and is wrong: a combining mark 56# is `\p{M}`, so without it the mark gets swallowed into the following punctuation run and a token like `_j` 57# never forms. It cost 3 strings out of 1875 and only `tokenize_oracle_check` could see it. 58QWEN35_PATTERN = ( 59r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" 60r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+" 61r"|\p{N}" 62r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*" 63r"|\s*[\r\n]+" 64r"|\s+(?!\S)" 65r"|\s+" 66) 67 68 69# The `deepseek-v3` pre-tokenizer (DeepSeek-V3 / V4.1; llama.cpp LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM, the same regex list as 70# JoyAI and Hunyuan-dense). UNLIKE the single-pattern families it is a SEQUENCE: each pattern splits the pieces the 71# one before it left (a span a pattern does not match stays a piece of its own), so digits (runs of 1..3) and CJK 72# runs are cut out before the general word / punctuation / whitespace pattern sees the rest. 73DEEPSEEK3_PATTERNS = ( 74r"\p{N}{1,3}" , 75"[一-龥-ゟ゠-ヿ]+" , 76r"[!\"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~][A-Za-z]+|[^\r\n\p{L}\p{P}\p{S}]?[\p{L}\p{M}]+" 77r"| ?[\p{P}\p{S}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+" , 78) 79 80 81def _sequence_findall (patterns ,text :str )-> list [str ]: 82"""llama.cpp's unicode_regex_split: the pieces of `text` after each pattern in turn splits every piece into its 83matches and the unmatched spans between them.""" 84pieces = [text ] 85for pat in patterns : 86nxt = [] 87for piece in pieces : 88pos = 0 89for m in pat .finditer (piece ): 90if m .start ()> pos : 91nxt .append (piece [pos :m .start ()]) 92nxt .append (m .group ()) 93pos = m .end () 94if pos < len (piece ): 95nxt .append (piece [pos :]) 96pieces = nxt 97return pieces 98 99 100class UnknownPreTokenizer (ValueError ): 101"""The model names a pre-tokenizer type this file has no splitting rule for.""" 102 103 104def pre_tokenizer_kind (pre )-> str | None : 105"""The splitting rule `pre` (the GGUF's tokenizer.ggml.pre, or a pack's tokenizer.json "pre") stands for: "qwen35", "deepseek3", or 106None for a type this file does not know. An empty or missing value is the qwen35 default, as it always was.""" 107p = "qwen35" if pre is None or pre == "" else str (pre ) 108if p == "qwen35" : 109return "qwen35" 110if p .startswith ("deepseek" ): 111return "deepseek3" 112return None 113 114 115class Tokenizer : 116def __init__ (self ,tokens :list [str ],merges :list [str ],token_types :list [int ]| None = None , 117pre :str = "qwen35" ,special_ids :dict [str ,int ]| None = None ): 118self .tokens = tokens 119self .pre = pre 120if pre_tokenizer_kind (pre )is None : 121# Not a fallback: another model's pre-tokenizer splits text differently, so encoding with the qwen35 rule would 122# change every prompt without any error (llama.cpp has one rule per `tokenizer.ggml.pre` type for the same reason). 123raise UnknownPreTokenizer ("This model splits text with a rule Strata doesn't have yet (%r), so it isn't loaded: " 124"running it with the wrong rule would change what it reads." % (pre ,)) 125self .token_types = token_types 126self .special_ids = special_ids or {} 127self .ids = {t :i for i ,t in enumerate (tokens )} 128if len (self .ids )!= len (tokens ): 129raise ValueError ("vocabulary has duplicate tokens: %d entries, %d unique" 130% (len (tokens ),len (self .ids ))) 131# Merge rules as (left, right) -> rank. A merge list that is not a total order over its pairs, or one 132# naming a token that is not in the vocabulary, would make BPE silently produce different ids than the 133# model was trained with, so both are checked here rather than discovered as a bad answer later. 134self .ranks :dict [tuple [str ,str ],int ]= {} 135for i ,m in enumerate (merges ): 136parts = m .split (" " ) 137if len (parts )!= 2 : 138raise ValueError ("merge %d is not a pair: %r" % (i ,m )) 139if parts [0 ]not in self .ids or parts [1 ]not in self .ids : 140raise ValueError ("merge %d names a token outside the vocabulary: %r" % (i ,m )) 141self .ranks [(parts [0 ],parts [1 ])]= i 142if pre_tokenizer_kind (pre )== "deepseek3" : 143seq = [regex .compile (x )for x in DEEPSEEK3_PATTERNS ] 144self ._split = lambda text :_sequence_findall (seq ,text ) 145else : 146self ._re = regex .compile (QWEN35_PATTERN ) 147self ._split = self ._re .findall 148 149# The literals matched directly instead of being run through BPE. GGUF token types: 3 = CONTROL, 150# 4 = USER_DEFINED. The two classes behave DIFFERENTLY and llama.cpp's own tokenizer settled which: 151# 152# * type 4 (USER_DEFINED: `<think>`, `<tool_call>`, `<tool_response>`, ...) is matched ALWAYS, 153# with or without parse_special. 154# * type 3 (CONTROL: `<|im_start|>`, `<|im_end|>`, `<|endoftext|>`, ...) is matched ONLY when 155# parse_special is set. 156# 157# Measured, not assumed: with parse_special=False the oracle still emitted `<tool_response>` as one 158# token and mine emitted four, and the three disagreements were exactly the type-4 cases while every 159# type-3 case agreed. Treating both classes alike costs 3 strings in 1229 and silently changes a chat 160# prompt, because `<|im_end|>` decomposed into ordinary pieces is not the token the model expects. 161self .special_tokens :dict [str ,int ]= {} 162if token_types : 163for i ,ty in enumerate (token_types ): 164if ty in (3 ,4 ): 165self .special_tokens [tokens [i ]]= i 166always = [t for t ,i in self .special_tokens .items ()if token_types and token_types [i ]== 4 ] 167self .control_tokens = [t for t ,i in self .special_tokens .items ()if token_types and token_types [i ]== 3 ] 168# Longest literal first, or `<|im_end|>` could match a shorter prefix of itself. `regex.escape` so a 169# token containing regex metacharacters (several do: `<|`, `[`, `(`) is matched literally. 170self ._always_re = self ._alt (always ) 171self ._special_re = self ._alt (list (self .special_tokens )) 172# Initialize once, rather than allocating a default dict and looking it up 173# through __dict__.setdefault on each encoded segment or decoded token. 174self ._piece_ids :dict [str ,list [int ]]= {} 175self ._segment_ids :dict [str ,list [int ]]= {} 176self ._segment_chars = 0 177self ._bytes_cache :dict [int ,bytes ]= {} 178# How far a special-token match can look ahead of where it starts (PromptEncoder's margin). 179self .max_special_len = max ((len (t )for t in self .special_tokens ),default = 1 ) 180 181@staticmethod 182def _alt (literals :list [str ]): 183if not literals : 184return None 185return regex .compile ("|" .join (regex .escape (s )for s in sorted (literals ,key = len ,reverse = True ))) 186 187# -------------------------------------------------------------- constructors 188@classmethod 189def from_gguf (cls ,path )-> "Tokenizer" : 190sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent )) 191from gguf_reader import GGUFFile 192md = GGUFFile (pathlib .Path (path )).metadata 193need = ["tokenizer.ggml.tokens" ,"tokenizer.ggml.merges" ] 194missing = [k for k in need if k not in md ] 195if missing : 196raise ValueError ("GGUF is missing %s; it does not carry a tokenizer" % ", " .join (missing )) 197model = md .get ("tokenizer.ggml.model" ) 198if model != "gpt2" : 199raise ValueError ("expected a byte-level BPE tokenizer (model 'gpt2'), got %r" % model ) 200special = {k :int (md [k ])for k in md 201if k .startswith ("tokenizer.ggml." )and k .endswith ("_token_id" )} 202return cls (list (md ["tokenizer.ggml.tokens" ]),list (md ["tokenizer.ggml.merges" ]), 203list (md .get ("tokenizer.ggml.token_type" )or [])or None , 204md .get ("tokenizer.ggml.pre" ,"qwen35" ),special ) 205 206# -------------------------------------------------------------- the algorithm 207def _bpe (self ,word :str )-> list [str ]: 208"""Merge `word` (already byte-mapped) by LOWEST RANK first, repeatedly - not left to right. 209 210Applying merges in list order rather than rank order is the classic BPE bug: it produces a different 211segmentation and a plausible token count. 212 213A word longer than HEAP_MIN symbols (a long CJK run, a minified blob: one pre-token piece of thousands of 214bytes) goes to _bpe_heap, which applies the same merges in the same order without rescanning every pair 215after each merge (#268: that rescan is O(n^2) and took seconds on an 8K-character CJK run). 216""" 217if len (word )> self .HEAP_MIN : 218return self ._bpe_heap (word ) 219# `self` is read ONCE, here. #1385: an interpreter (CPython 3.14.4) was seen handing this frame an int 220# for `self` partway through the scan (`'int' object has no attribute 'ranks'`). Nothing in this class 221# can do that (no cache, decorator, slots or callback; a thread hammering test cannot make it happen), 222# so the scan below works on a local and no longer re-reads `self` once per symbol pair. 223ranks_get = self .ranks .get 224parts = list (word ) 225while len (parts )> 1 : 226best ,best_rank = None ,None 227for i in range (len (parts )- 1 ): 228r = ranks_get ((parts [i ],parts [i + 1 ])) 229if r is not None and (best_rank is None or r < best_rank ): 230best ,best_rank = i ,r 231if best is None : 232break 233parts [best :best + 2 ]= [parts [best ]+ parts [best + 1 ]] 234return parts 235 236HEAP_MIN = 64 # words up to this many symbols keep the scan above, unchanged 237 238def _bpe_heap (self ,word :str )-> list [str ]: 239"""_bpe's result in O(n log n): the symbols as a linked list, every adjacent pair with a rank in a heap 240keyed (rank, position). Popping the lowest rank and then the lowest position is exactly the order the 241scan picks (its strict `<` keeps the leftmost of equal ranks), and a symbol's position is where it starts 242in the word, which only its left neighbour's merge can change - so a popped pair whose two symbols are 243no longer the ones it was pushed with is stale and skipped.""" 244import heapq 245parts = list (word ) 246n = len (parts ) 247nxt = list (range (1 ,n ))+ [- 1 ] 248prv = list (range (- 1 ,n - 1 )) 249ranks = self .ranks 250heap = [] 251for i in range (n - 1 ): 252r = ranks .get ((parts [i ],parts [i + 1 ])) 253if r is not None : 254heap .append ((r ,i ,parts [i ],parts [i + 1 ])) 255heapq .heapify (heap ) 256while heap : 257r ,i ,left ,right = heapq .heappop (heap ) 258j = nxt [i ] 259if parts [i ]!= left or j < 0 or parts [j ]!= right : 260continue # stale: one of its symbols has merged since 261parts [i ]= left + right 262parts [j ]= None # j is gone: i takes its place in the list 263k = nxt [j ] 264nxt [i ]= k 265if k >= 0 : 266prv [k ]= i 267r2 = ranks .get ((parts [i ],parts [k ])) 268if r2 is not None : 269heapq .heappush (heap , (r2 ,i ,parts [i ],parts [k ])) 270p = prv [i ] 271if p >= 0 : 272r2 = ranks .get ((parts [p ],parts [i ])) 273if r2 is not None : 274heapq .heappush (heap , (r2 ,p ,parts [p ],parts [i ])) 275return [s for s in parts if s is not None ] 276 277PIECE_CACHE_MAX = 200_000 # pre-tokenizer pieces remembered (an agent resends its whole history every turn) 278 279def _encode_plain (self ,text :str )-> list [int ]: 280out :list [int ]= [] 281# A piece's ids depend on the piece alone, so repeated pieces (most of a resent conversation) are looked up 282# instead of merged again. The ids are the ones _bpe gives: this only skips the work. 283cache = self ._piece_ids 284for piece in self ._split (text ): 285got = cache .get (piece ) 286if got is None : 287mapped = "" .join (BYTE_TO_UNICODE [b ]for b in piece .encode ("utf-8" )) 288got = [] 289for tok in self ._bpe (mapped ): 290i = self .ids .get (tok ) 291if i is None : 292raise KeyError ("BPE produced a token outside the vocabulary: %r" % tok ) 293got .append (i ) 294if len (cache )< self .PIECE_CACHE_MAX : 295cache [piece ]= got 296out .extend (got ) 297return out 298 299SEGMENT_CACHE_CHARS = 8_000_000 # text between two special tokens remembered (a resent conversation's messages) 300 301def _encode_segment (self ,text :str )-> list [int ]: 302"""_encode_plain(text), remembered whole: a resent conversation repeats every earlier message's text exactly, 303so its ids are looked up instead of split and looked up piece by piece again. The caller must not change the 304list it gets.""" 305cache = self ._segment_ids 306got = cache .get (text ) 307if got is None : 308got = self ._encode_plain (text ) 309if self ._segment_chars + len (text )> self .SEGMENT_CACHE_CHARS : 310cache .clear () 311self ._segment_chars = 0 312cache [text ]= got 313self ._segment_chars += len (text ) 314return got 315 316def _encode_matching (self ,text :str ,pat ,plain = (),marks :list | None = None )-> list [int ]: 317"""Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest. 318 319The split happens on the RAW text, before the byte mapping, because a special token's string is a 320literal to match rather than bytes to decompose. Everything between the matches is tokenized 321normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. A match that starts 322inside one of the `plain` (start, end) spans is left to the text around it (#537). 323 324`marks`, when given, receives (end of the match in `text`, ids so far) for every match: the points where 325the encoding of a longer text with the same beginning can resume (PromptEncoder). 326""" 327if pat is None : 328return self ._encode_plain (text ) 329out :list [int ]= [] 330pos = 0 331# Matches arrive in text order. For reusable span sequences, consume each 332# span once instead of scanning the entire list for every literal match. 333# Sorting a copy handles unsorted/overlapping input without mutating it. 334# Other iterables keep the original consumption semantics below. 335span_sequence = isinstance (plain , (list ,tuple ))and bool (plain ) 336if span_sequence : 337spans = iter (sorted (plain )) 338upcoming = next (spans ,None ) 339plain_end = 0 340for m in pat .finditer (text ): 341start = m .start () 342if span_sequence : 343while upcoming is not None and upcoming [0 ]<= start : 344plain_end = max (plain_end ,upcoming [1 ]) 345upcoming = next (spans ,None ) 346if start < plain_end : 347continue 348elif plain and any (a <= start < b for a ,b in plain ): 349continue 350if start > pos : 351out .extend (self ._encode_segment (text [pos :start ])) 352out .append (self .special_tokens [m .group (0 )]) 353pos = m .end () 354if marks is not None : 355marks .append ((pos ,len (out ))) 356if pos < len (text ): 357out .extend (self ._encode_segment (text [pos :])) 358return out 359 360def encode (self ,text :str ,parse_special :bool = False ,plain = ())-> list [int ]: 361"""Tokenize `text`. 362 363`parse_special` controls only the type-3 CONTROL literals such as `<|im_end|>`; the type-4 364USER_DEFINED ones such as `<think>` are matched either way. See the note in `__init__`. 365`plain`: (start, end) spans of `text` that are ordinary text even where they spell a literal - a 366`</think>` quoted in a message (#537) - and are tokenized with the text around them. 367""" 368return self ._encode_matching (text ,self ._special_re if parse_special else self ._always_re ,plain ) 369 370def encode_marked (self ,text :str ,parse_special :bool = False ,plain = ())-> tuple [list [int ],list [tuple [int ,int ]]]: 371"""encode() and its resume points: (end offset in `text`, ids so far) after every special-token match.""" 372marks :list [tuple [int ,int ]]= [] 373return self ._encode_matching (text ,self ._special_re if parse_special else self ._always_re ,plain ,marks ),marks 374 375def token_bytes (self ,i :int )-> bytes : 376"""The raw bytes of one token (a multi-byte character can be split across tokens).""" 377cache = self ._bytes_cache 378b = cache .get (i ) 379if b is None : 380if i < 0 or i >= len (self .tokens ): 381raise IndexError ("token id %d is outside the vocabulary (%d)" % (i ,len (self .tokens ))) 382if self .token_types and i < len (self .token_types )and self .token_types [i ]in (3 ,4 ): 383# a special token's string is the literal text (DeepSeek's `<|User|>`, `|DSML|` hold characters outside 384# the byte alphabet); for Qwen's ASCII specials it is the same bytes the alphabet would give 385b = cache [i ]= self .tokens [i ].encode ("utf-8" ) 386return b 387raw = bytearray () 388for ch in self .tokens [i ]: 389v = UNICODE_TO_BYTE .get (ch ) 390if v is None : 391raise KeyError ("token %d contains a character outside the byte alphabet: %r" % (i ,ch )) 392raw .append (v ) 393b = cache [i ]= bytes (raw ) 394return b 395 396def decode (self ,ids :list [int ],errors :str = "replace" )-> str : 397return b"" .join (self .token_bytes (i )for i in ids ).decode ("utf-8" ,errors = errors ) 398 399 400# ------------------------------------------------------------------ incremental prompts (#567) 401def common_prefix_len (a :str ,b :str )-> int : 402"""Length of the longest common prefix, by slices (C speed) rather than a loop over characters.""" 403n = min (len (a ),len (b )) 404lo ,step = 0 ,4096 405while lo < n :# whole chunks first, doubling 406hi = min (n ,lo + step ) 407if a [lo :hi ]!= b [lo :hi ]: 408break 409lo ,step = hi ,min (step * 2 ,1 << 20 ) 410else : 411return n 412while hi - lo > 1 :# the first difference is in [lo, hi): bisect it 413mid = (lo + hi )// 2 414if a [lo :mid ]== b [lo :mid ]: 415lo = mid 416else : 417hi = mid 418return lo 419 420 421def plain_agree_until (a ,b ,limit :int )-> int : 422"""The first position below `limit` where the `plain` spans (#537) of two texts differ - a position inside a 423span in one and not in the other - or `limit`. Spans are (start, end), sorted and disjoint.""" 424def clip (spans ): 425return [(x ,min (y ,limit ))for x ,y in spans if x < limit and y > x ] 426ca ,cb = clip (a ),clip (b ) 427for (xa ,ya ), (xb ,yb )in zip (ca ,cb ): 428if (xa ,ya )!= (xb ,yb ): 429return min (xa ,xb )if xa != xb else min (ya ,yb ) 430if len (ca )!= len (cb ): 431return (ca if len (ca )> len (cb )else cb )[min (len (ca ),len (cb ))][0 ] 432return limit 433 434 435class PromptEncoder : 436"""`tok.encode(text, parse_special=True, plain=...)` for chat prompts, reusing the ids of an earlier prompt. 437 438A chat client sends the whole conversation every turn, and the rendered prompt of turn n+1 starts with most of 439turn n's. Running BPE over all of it again costs hundreds of milliseconds at 100K tokens, even when the engine 440reuses the whole prefix. So the ids up to a SPECIAL-TOKEN BOUNDARY both prompts share are taken as they were, 441and only the rest is encoded. 442 443WHY THAT IS EXACT. Encoding splits the text at special-token matches and BPE-encodes each stretch between two 444matches on its own (`_encode_matching`): nothing crosses a match. Whether a match is taken at position q 445depends only on text[q : q + max_special_len] and on whether q lies inside a `plain` span (#537: a </think> 446quoted in a message is text). So if the two texts agree up to L and their plain spans agree below L, every 447decision the scan makes at a position before c = the end of some match, with c + max_special_len - 1 <= L, is 448the same for both - the same matches, the same stretches, the same ids up to c - and from c the scan starts 449afresh, exactly as it does on text[c:] with the spans shifted by c. Hence encode(new) == ids_old[:ids at c] + 450encode(new[c:]). The margin matters only for a vocabulary where a literal overlaps another's end; it costs 451re-encoding one short stretch. 452 453A few recent prompts are kept (one per conversation: a prompt replaces the one it continues, that is, one whose 454text it reuses for more than half; a prompt that shares only the template's head with every entry is a new 455entry), so a second client does not evict the first. `encode(..., store=False)` reads the kept prompts without 456writing one (a token count is not a conversation's turn). The tokenizer needs `encode_marked` and 457`max_special_len`. 458""" 459 460def __init__ (self ,tok ,keep :int = 4 ): 461self .tok ,self .keep = tok ,keep 462# (text, plain spans, ids, mark ends, mark counts) 463self .entries :list [tuple [str ,tuple ,list [int ],list [int ],list [int ]]]= [] 464self .lock = threading .Lock () 465self .last_reused = 0 # characters taken from an earlier prompt (for tests) 466 467def encode (self ,text :str ,plain = (),store :bool = True )-> list [int ]: 468plain = tuple (sorted (plain )) 469with self .lock : 470entries = self .entries # replaced, never changed in place 471margin = self .tok .max_special_len - 1 472src ,cut_k = None ,- 1 473for e in entries : 474same = plain_agree_until (e [1 ],plain ,common_prefix_len (e [0 ],text )) 475k = bisect .bisect_right (e [3 ],same - margin )- 1 # the last boundary c with c <= same - margin 476if k >= 0 and (src is None or e [3 ][k ]> src [3 ][cut_k ]): 477src ,cut_k = e ,k 478if src is None : 479ids ,marks = self .tok .encode_marked (text ,parse_special = True ,plain = plain ) 480ends ,counts = [m [0 ]for m in marks ], [m [1 ]for m in marks ] 481self .last_reused = 0 482else : 483c ,n = src [3 ][cut_k ],src [4 ][cut_k ] 484rest = tuple ((max (x - c ,0 ),y - c )for x ,y in plain if y > c ) 485tail ,marks = self .tok .encode_marked (text [c :],parse_special = True ,plain = rest ) 486ids = src [2 ][:n ]+ tail 487ends = src [3 ][:cut_k + 1 ]+ [c + m [0 ]for m in marks ] 488counts = src [4 ][:cut_k + 1 ]+ [n + m [1 ]for m in marks ] 489self .last_reused = c 490if not store : 491return ids 492# every rendered prompt starts with the template's header, so sharing a special boundary does not make two 493# prompts one conversation: only the entry whose text is mostly reused is replaced 494old = src if src is not None and 2 * src [3 ][cut_k ]> len (src [0 ])else None 495with self .lock : 496self .entries = [(text ,plain ,ids ,ends ,counts )]+ [e for e in self .entries if e is not old ][:self .keep - 1 ] 497return list (ids ) 498 499def forget (self ,ids :list [int ])-> None : 500"""The prompt with these ids was refused: it is not kept.""" 501with self .lock : 502self .entries = [e for e in self .entries if e [2 ]!= ids ] 503 504 505# ------------------------------------------------------------------ the pack's tokenizer/ directory 506def extract (gguf_path ,out_dir )-> dict : 507"""Write the tokenizer into `<out_dir>/tokenizer/` so the engine never opens the weight shards for it.""" 508out = pathlib .Path (out_dir )/ "tokenizer" 509out .mkdir (parents = True ,exist_ok = True ) 510tk = Tokenizer .from_gguf (gguf_path ) 511cfg = { 512"model" :"gpt2" , 513"pre" :tk .pre , 514"vocab_size" :len (tk .tokens ), 515"n_merges" :len (tk .ranks ), 516"special_ids" :tk .special_ids , 517"add_bos_token" :False , 518# The pattern is SHIPPED, not recomputed by the reader: it is transcribed from llama.cpp for the 519# declared `pre` type, and a C++ port that re-derived it would be free to get `\p{M}` wrong again. 520"pre_pattern" :QWEN35_PATTERN , 521"pre_pattern_source" :".ref/llama.cpp src/llama-vocab.cpp L396 (LLAMA_VOCAB_PRE_TYPE_QWEN35)" , 522 } 523 (out / "vocab.json" ).write_text (json .dumps (tk .ids ,ensure_ascii = False ),encoding = "utf-8" ) 524 (out / "merges.txt" ).write_text ("\n" .join ("%s %s" % k for k ,_ in 525sorted (tk .ranks .items (),key = lambda kv :kv [1 ])),encoding = "utf-8" ) 526 (out / "token_type.json" ).write_text (json .dumps (tk .token_types ),encoding = "utf-8" ) 527 (out / "tokenizer.json" ).write_text (json .dumps (cfg ,ensure_ascii = False ,indent = 1 ),encoding = "utf-8" ) 528# the model's own chat template: fine-tunes change it (Swift 1.5 differs from Qwen3.8-Flash-Next's) 529sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent )) 530from gguf_reader import GGUFFile 531tpl = GGUFFile (pathlib .Path (gguf_path )).metadata .get ("tokenizer.chat_template" ) 532if tpl : 533 (out / "chat_template.jinja" ).write_text (tpl ,encoding = "utf-8" ,newline = "\n" ) 534return cfg 535 536 537def main ()-> int : 538import argparse 539ap = argparse .ArgumentParser () 540ap .add_argument ("--gguf" ,required = True ) 541ap .add_argument ("--out" ,required = True ) 542ap .add_argument ("--check" ,action = "store_true" ,help = "round-trip a corpus and report" ) 543args = ap .parse_args () 544cfg = extract (args .gguf ,args .out ) 545"tokenizer/: vocab %d, merges %d, pre %s, specials %s" 546% (cfg ["vocab_size" ],cfg ["n_merges" ],cfg ["pre" ],cfg ["special_ids" ])) 547if args .check : 548tk = Tokenizer .from_gguf (args .gguf ) 549corpus = ["" ,"Hello, world!" ," leading and trailing " ,"a\n\n\nb" , 550"def f(x):\n\treturn x # comment\n" ,"\u4f60\u597d\uff0c\u4e16\u754c" ,"\u0645\u0631\u062d\u0628\u0627" , 551"\U0001f600\U0001f680\U0001f1fa\U0001f1f8" ,"e\u0301\u0301 combining" ,"\x00\x01\x7f control" , 552"\u00a0non-breaking\u00a0space" ,"1234567890" ,"MixedCASE_and-dashes" ,"\r\n\r\n" ,"\u2028\u2029" , 553"x" * 5000 ] 554bad = 0 555for s in corpus : 556ids = tk .encode (s ) 557back = tk .decode (ids ) 558if back != s : 559" *** ROUND TRIP FAILED *** %r -> %d ids -> %r" % (s [:40 ],len (ids ),back [:40 ])) 560bad += 1 561"round trip: %d strings, %d failed" % (len (corpus ),bad )) 562return 0 if bad == 0 else 1 563return 0 564 565 566if __name__ == "__main__" : 567raise SystemExit (main ())