okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanatokenizer: remember whole special-delimited segments, so a resent conversation's earlier messages are looked up (80K-token prompt: encode 31 -> 1.4 ms, same ids)d86cebb9c

main
29.3 KiB567 linesraw
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
30    Bytes 33..126, 161..172 and 174..255 map to themselves; the remaining 68 (space, newline, the C0
31    controls and the high range that would be invisible) are shifted into 256+n so that no byte is
32    unprintable.  The shift is the whole trick and getting its ORDER wrong is invisible in the output ids.
33    """
34    bs = (list(range(0x21, 0x7F)) + list(range(0xA1, 0xAD)) + list(range(0xAE, 0x100)))
35    cs = bs[:]
36    n = 0
37    for b in range(256):
38        if b not in bs:
39            bs.append(b)
40            cs.append(256 + n)
41            n += 1
42    return 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 = (
59    r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])"
60    r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+"
61    r"|\p{N}"
62    r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*"
63    r"|\s*[\r\n]+"
64    r"|\s+(?!\S)"
65    r"|\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 = (
74    r"\p{N}{1,3}",
75    "[一-龥぀-ゟ゠-ヿ]+",
76    r"[!\"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~][A-Za-z]+|[^\r\n\p{L}\p{P}\p{S}]?[\p{L}\p{M}]+"
77    r"| ?[\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
83    matches and the unmatched spans between them."""
84    pieces = [text]
85    for pat in patterns:
86        nxt = []
87        for piece in pieces:
88            pos = 0
89            for m in pat.finditer(piece):
90                if m.start() > pos:
91                    nxt.append(piece[pos:m.start()])
92                nxt.append(m.group())
93                pos = m.end()
94            if pos < len(piece):
95                nxt.append(piece[pos:])
96        pieces = nxt
97    return 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
106    None for a type this file does not know.  An empty or missing value is the qwen35 default, as it always was."""
107    p = "qwen35" if pre is None or pre == "" else str(pre)
108    if p == "qwen35":
109        return "qwen35"
110    if p.startswith("deepseek"):
111        return "deepseek3"
112    return None
113
114
115class Tokenizer:
116    def __init__(self, tokens: list[str], merges: list[str], token_types: list[int] | None = None,
117                 pre: str = "qwen35", special_ids: dict[str, int] | None = None):
118        self.tokens = tokens
119        self.pre = pre
120        if 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).
123            raise 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,))
125        self.token_types = token_types
126        self.special_ids = special_ids or {}
127        self.ids = {t: i for i, t in enumerate(tokens)}
128        if len(self.ids) != len(tokens):
129            raise 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.
134        self.ranks: dict[tuple[str, str], int] = {}
135        for i, m in enumerate(merges):
136            parts = m.split(" ")
137            if len(parts) != 2:
138                raise ValueError("merge %d is not a pair: %r" % (i, m))
139            if parts[0] not in self.ids or parts[1] not in self.ids:
140                raise ValueError("merge %d names a token outside the vocabulary: %r" % (i, m))
141            self.ranks[(parts[0], parts[1])] = i
142        if pre_tokenizer_kind(pre) == "deepseek3":
143            seq = [regex.compile(x) for x in DEEPSEEK3_PATTERNS]
144            self._split = lambda text: _sequence_findall(seq, text)
145        else:
146            self._re = regex.compile(QWEN35_PATTERN)
147            self._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.
161        self.special_tokens: dict[str, int] = {}
162        if token_types:
163            for i, ty in enumerate(token_types):
164                if ty in (3, 4):
165                    self.special_tokens[tokens[i]] = i
166        always = [t for t, i in self.special_tokens.items() if token_types and token_types[i] == 4]
167        self.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.
170        self._always_re = self._alt(always)
171        self._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.
174        self._piece_ids: dict[str, list[int]] = {}
175        self._segment_ids: dict[str, list[int]] = {}
176        self._segment_chars = 0
177        self._bytes_cache: dict[int, bytes] = {}
178        # How far a special-token match can look ahead of where it starts (PromptEncoder's margin).
179        self.max_special_len = max((len(t) for t in self.special_tokens), default=1)
180
181    @staticmethod
182    def _alt(literals: list[str]):
183        if not literals:
184            return None
185        return regex.compile("|".join(regex.escape(s) for s in sorted(literals, key=len, reverse=True)))
186
187    # -------------------------------------------------------------- constructors
188    @classmethod
189    def from_gguf(cls, path) -> "Tokenizer":
190        sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
191        from gguf_reader import GGUFFile
192        md = GGUFFile(pathlib.Path(path)).metadata
193        need = ["tokenizer.ggml.tokens", "tokenizer.ggml.merges"]
194        missing = [k for k in need if k not in md]
195        if missing:
196            raise ValueError("GGUF is missing %s; it does not carry a tokenizer" % ", ".join(missing))
197        model = md.get("tokenizer.ggml.model")
198        if model != "gpt2":
199            raise ValueError("expected a byte-level BPE tokenizer (model 'gpt2'), got %r" % model)
200        special = {k: int(md[k]) for k in md
201                   if k.startswith("tokenizer.ggml.") and k.endswith("_token_id")}
202        return cls(list(md["tokenizer.ggml.tokens"]), list(md["tokenizer.ggml.merges"]),
203                   list(md.get("tokenizer.ggml.token_type") or []) or None,
204                   md.get("tokenizer.ggml.pre", "qwen35"), special)
205
206    # -------------------------------------------------------------- the algorithm
207    def _bpe(self, word: str) -> list[str]:
208        """Merge `word` (already byte-mapped) by LOWEST RANK first, repeatedly - not left to right.
209
210        Applying merges in list order rather than rank order is the classic BPE bug: it produces a different
211        segmentation and a plausible token count.
212
213        A word longer than HEAP_MIN symbols (a long CJK run, a minified blob: one pre-token piece of thousands of
214        bytes) goes to _bpe_heap, which applies the same merges in the same order without rescanning every pair
215        after each merge (#268: that rescan is O(n^2) and took seconds on an 8K-character CJK run).
216        """
217        if len(word) > self.HEAP_MIN:
218            return 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.
223        ranks_get = self.ranks.get
224        parts = list(word)
225        while len(parts) > 1:
226            best, best_rank = None, None
227            for i in range(len(parts) - 1):
228                r = ranks_get((parts[i], parts[i + 1]))
229                if r is not None and (best_rank is None or r < best_rank):
230                    best, best_rank = i, r
231            if best is None:
232                break
233            parts[best:best + 2] = [parts[best] + parts[best + 1]]
234        return parts
235
236    HEAP_MIN = 64       # words up to this many symbols keep the scan above, unchanged
237
238    def _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
240        keyed (rank, position).  Popping the lowest rank and then the lowest position is exactly the order the
241        scan picks (its strict `<` keeps the leftmost of equal ranks), and a symbol's position is where it starts
242        in the word, which only its left neighbour's merge can change - so a popped pair whose two symbols are
243        no longer the ones it was pushed with is stale and skipped."""
244        import heapq
245        parts = list(word)
246        n = len(parts)
247        nxt = list(range(1, n)) + [-1]
248        prv = list(range(-1, n - 1))
249        ranks = self.ranks
250        heap = []
251        for i in range(n - 1):
252            r = ranks.get((parts[i], parts[i + 1]))
253            if r is not None:
254                heap.append((r, i, parts[i], parts[i + 1]))
255        heapq.heapify(heap)
256        while heap:
257            r, i, left, right = heapq.heappop(heap)
258            j = nxt[i]
259            if parts[i] != left or j < 0 or parts[j] != right:
260                continue                                # stale: one of its symbols has merged since
261            parts[i] = left + right
262            parts[j] = None                             # j is gone: i takes its place in the list
263            k = nxt[j]
264            nxt[i] = k
265            if k >= 0:
266                prv[k] = i
267                r2 = ranks.get((parts[i], parts[k]))
268                if r2 is not None:
269                    heapq.heappush(heap, (r2, i, parts[i], parts[k]))
270            p = prv[i]
271            if p >= 0:
272                r2 = ranks.get((parts[p], parts[i]))
273                if r2 is not None:
274                    heapq.heappush(heap, (r2, p, parts[p], parts[i]))
275        return [s for s in parts if s is not None]
276
277    PIECE_CACHE_MAX = 200_000    # pre-tokenizer pieces remembered (an agent resends its whole history every turn)
278
279    def _encode_plain(self, text: str) -> list[int]:
280        out: 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.
283        cache = self._piece_ids
284        for piece in self._split(text):
285            got = cache.get(piece)
286            if got is None:
287                mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8"))
288                got = []
289                for tok in self._bpe(mapped):
290                    i = self.ids.get(tok)
291                    if i is None:
292                        raise KeyError("BPE produced a token outside the vocabulary: %r" % tok)
293                    got.append(i)
294                if len(cache) < self.PIECE_CACHE_MAX:
295                    cache[piece] = got
296            out.extend(got)
297        return out
298
299    SEGMENT_CACHE_CHARS = 8_000_000   # text between two special tokens remembered (a resent conversation's messages)
300
301    def _encode_segment(self, text: str) -> list[int]:
302        """_encode_plain(text), remembered whole: a resent conversation repeats every earlier message's text exactly,
303        so its ids are looked up instead of split and looked up piece by piece again.  The caller must not change the
304        list it gets."""
305        cache = self._segment_ids
306        got = cache.get(text)
307        if got is None:
308            got = self._encode_plain(text)
309            if self._segment_chars + len(text) > self.SEGMENT_CACHE_CHARS:
310                cache.clear()
311                self._segment_chars = 0
312            cache[text] = got
313            self._segment_chars += len(text)
314        return got
315
316    def _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
319        The split happens on the RAW text, before the byte mapping, because a special token's string is a
320        literal to match rather than bytes to decompose.  Everything between the matches is tokenized
321        normally - which is why a near-miss like `<|im_star` still costs ordinary tokens.  A match that starts
322        inside 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
325        the encoding of a longer text with the same beginning can resume (PromptEncoder).
326        """
327        if pat is None:
328            return self._encode_plain(text)
329        out: list[int] = []
330        pos = 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.
335        span_sequence = isinstance(plain, (list, tuple)) and bool(plain)
336        if span_sequence:
337            spans = iter(sorted(plain))
338            upcoming = next(spans, None)
339            plain_end = 0
340        for m in pat.finditer(text):
341            start = m.start()
342            if span_sequence:
343                while upcoming is not None and upcoming[0] <= start:
344                    plain_end = max(plain_end, upcoming[1])
345                    upcoming = next(spans, None)
346                if start < plain_end:
347                    continue
348            elif plain and any(a <= start < b for a, b in plain):
349                continue
350            if start > pos:
351                out.extend(self._encode_segment(text[pos:start]))
352            out.append(self.special_tokens[m.group(0)])
353            pos = m.end()
354            if marks is not None:
355                marks.append((pos, len(out)))
356        if pos < len(text):
357            out.extend(self._encode_segment(text[pos:]))
358        return out
359
360    def 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
364        USER_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        """
368        return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain)
369
370    def 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."""
372        marks: list[tuple[int, int]] = []
373        return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain, marks), marks
374
375    def token_bytes(self, i: int) -> bytes:
376        """The raw bytes of one token (a multi-byte character can be split across tokens)."""
377        cache = self._bytes_cache
378        b = cache.get(i)
379        if b is None:
380            if i < 0 or i >= len(self.tokens):
381                raise IndexError("token id %d is outside the vocabulary (%d)" % (i, len(self.tokens)))
382            if 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
385                b = cache[i] = self.tokens[i].encode("utf-8")
386                return b
387            raw = bytearray()
388            for ch in self.tokens[i]:
389                v = UNICODE_TO_BYTE.get(ch)
390                if v is None:
391                    raise KeyError("token %d contains a character outside the byte alphabet: %r" % (i, ch))
392                raw.append(v)
393            b = cache[i] = bytes(raw)
394        return b
395
396    def decode(self, ids: list[int], errors: str = "replace") -> str:
397        return 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."""
403    n = min(len(a), len(b))
404    lo, step = 0, 4096
405    while lo < n:                                       # whole chunks first, doubling
406        hi = min(n, lo + step)
407        if a[lo:hi] != b[lo:hi]:
408            break
409        lo, step = hi, min(step * 2, 1 << 20)
410    else:
411        return n
412    while hi - lo > 1:                                  # the first difference is in [lo, hi): bisect it
413        mid = (lo + hi) // 2
414        if a[lo:mid] == b[lo:mid]:
415            lo = mid
416        else:
417            hi = mid
418    return 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
423    span in one and not in the other - or `limit`.  Spans are (start, end), sorted and disjoint."""
424    def clip(spans):
425        return [(x, min(y, limit)) for x, y in spans if x < limit and y > x]
426    ca, cb = clip(a), clip(b)
427    for (xa, ya), (xb, yb) in zip(ca, cb):
428        if (xa, ya) != (xb, yb):
429            return min(xa, xb) if xa != xb else min(ya, yb)
430    if len(ca) != len(cb):
431        return (ca if len(ca) > len(cb) else cb)[min(len(ca), len(cb))][0]
432    return limit
433
434
435class PromptEncoder:
436    """`tok.encode(text, parse_special=True, plain=...)` for chat prompts, reusing the ids of an earlier prompt.
437
438    A chat client sends the whole conversation every turn, and the rendered prompt of turn n+1 starts with most of
439    turn n's.  Running BPE over all of it again costs hundreds of milliseconds at 100K tokens, even when the engine
440    reuses the whole prefix.  So the ids up to a SPECIAL-TOKEN BOUNDARY both prompts share are taken as they were,
441    and only the rest is encoded.
442
443    WHY THAT IS EXACT.  Encoding splits the text at special-token matches and BPE-encodes each stretch between two
444    matches on its own (`_encode_matching`): nothing crosses a match.  Whether a match is taken at position q
445    depends only on text[q : q + max_special_len] and on whether q lies inside a `plain` span (#537: a </think>
446    quoted in a message is text).  So if the two texts agree up to L and their plain spans agree below L, every
447    decision the scan makes at a position before c = the end of some match, with c + max_special_len - 1 <= L, is
448    the same for both - the same matches, the same stretches, the same ids up to c - and from c the scan starts
449    afresh, exactly as it does on text[c:] with the spans shifted by c.  Hence encode(new) == ids_old[:ids at c] +
450    encode(new[c:]).  The margin matters only for a vocabulary where a literal overlaps another's end; it costs
451    re-encoding one short stretch.
452
453    A few recent prompts are kept (one per conversation: a prompt replaces the one it continues, that is, one whose
454    text it reuses for more than half; a prompt that shares only the template's head with every entry is a new
455    entry), so a second client does not evict the first.  `encode(..., store=False)` reads the kept prompts without
456    writing one (a token count is not a conversation's turn).  The tokenizer needs `encode_marked` and
457    `max_special_len`.
458    """
459
460    def __init__(self, tok, keep: int = 4):
461        self.tok, self.keep = tok, keep
462        # (text, plain spans, ids, mark ends, mark counts)
463        self.entries: list[tuple[str, tuple, list[int], list[int], list[int]]] = []
464        self.lock = threading.Lock()
465        self.last_reused = 0                            # characters taken from an earlier prompt (for tests)
466
467    def encode(self, text: str, plain=(), store: bool = True) -> list[int]:
468        plain = tuple(sorted(plain))
469        with self.lock:
470            entries = self.entries                      # replaced, never changed in place
471        margin = self.tok.max_special_len - 1
472        src, cut_k = None, -1
473        for e in entries:
474            same = plain_agree_until(e[1], plain, common_prefix_len(e[0], text))
475            k = bisect.bisect_right(e[3], same - margin) - 1   # the last boundary c with c <= same - margin
476            if k >= 0 and (src is None or e[3][k] > src[3][cut_k]):
477                src, cut_k = e, k
478        if src is None:
479            ids, marks = self.tok.encode_marked(text, parse_special=True, plain=plain)
480            ends, counts = [m[0] for m in marks], [m[1] for m in marks]
481            self.last_reused = 0
482        else:
483            c, n = src[3][cut_k], src[4][cut_k]
484            rest = tuple((max(x - c, 0), y - c) for x, y in plain if y > c)
485            tail, marks = self.tok.encode_marked(text[c:], parse_special=True, plain=rest)
486            ids = src[2][:n] + tail
487            ends = src[3][:cut_k + 1] + [c + m[0] for m in marks]
488            counts = src[4][:cut_k + 1] + [n + m[1] for m in marks]
489            self.last_reused = c
490        if not store:
491            return 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
494        old = src if src is not None and 2 * src[3][cut_k] > len(src[0]) else None
495        with self.lock:
496            self.entries = [(text, plain, ids, ends, counts)] + [e for e in self.entries if e is not old][:self.keep - 1]
497        return list(ids)
498
499    def forget(self, ids: list[int]) -> None:
500        """The prompt with these ids was refused: it is not kept."""
501        with self.lock:
502            self.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."""
508    out = pathlib.Path(out_dir) / "tokenizer"
509    out.mkdir(parents=True, exist_ok=True)
510    tk = Tokenizer.from_gguf(gguf_path)
511    cfg = {
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
525                                              sorted(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)
529    sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
530    from gguf_reader import GGUFFile
531    tpl = GGUFFile(pathlib.Path(gguf_path)).metadata.get("tokenizer.chat_template")
532    if tpl:
533        (out / "chat_template.jinja").write_text(tpl, encoding="utf-8", newline="\n")
534    return cfg
535
536
537def main() -> int:
538    import argparse
539    ap = argparse.ArgumentParser()
540    ap.add_argument("--gguf", required=True)
541    ap.add_argument("--out", required=True)
542    ap.add_argument("--check", action="store_true", help="round-trip a corpus and report")
543    args = ap.parse_args()
544    cfg = extract(args.gguf, args.out)
545    print("tokenizer/: vocab %d, merges %d, pre %s, specials %s"
546          % (cfg["vocab_size"], cfg["n_merges"], cfg["pre"], cfg["special_ids"]))
547    if args.check:
548        tk = Tokenizer.from_gguf(args.gguf)
549        corpus = ["", "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]
554        bad = 0
555        for s in corpus:
556            ids = tk.encode(s)
557            back = tk.decode(ids)
558            if back != s:
559                print("  *** ROUND TRIP FAILED *** %r -> %d ids -> %r" % (s[:40], len(ids), back[:40]))
560                bad += 1
561        print("round trip: %d strings, %d failed" % (len(corpus), bad))
562        return 0 if bad == 0 else 1
563    return 0
564
565
566if __name__ == "__main__":
567    raise SystemExit(main())