okami.mom/strata

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

Niko1221Merge branch 'f-hf-misc' into f-14028aeefca2d

main
11.9 KiB282 linesraw
1"""The streaming detokenizer (perf-review F-1): the incremental one emits exactly what the old re-decode did, token
2by token, and its cost per token does not grow with the reply.
3
4    python -m unittest serve.test_detok      (needs a pack's tokenizer; skipped without one)
5"""
6import os
7import random
8import sys
9import time
10import unittest
11from pathlib import Path
12
13ROOT = Path(__file__).resolve().parent.parent
14sys.path.insert(0, str(ROOT / "tools"))
15sys.path.insert(0, str(ROOT))
16
17from serve.server import Detokenizer  # noqa: E402
18
19
20def find_tokenizer():
21    cands = [os.environ.get("STRATA_TOKENIZER", "")]
22    cands += [str(p) for p in ROOT.glob("packs/*/tokenizer")] + [str(p) for p in ROOT.glob("pack/*/tokenizer")]
23    cands += [r"C:\Users\AI-Server\Desktop\Strata\Public\Engine\pack\full\tokenizer"]
24    for c in cands:
25        if c and (Path(c) / "vocab.json").exists():
26            return Path(c)
27    return None
28
29
30class OldDetokenizer:
31    """The pre-0.1.22 algorithm: re-decode every generated id, hold a trailing U+FFFD."""
32
33    def __init__(self, tok):
34        self.tok, self.ids, self.sent = tok, [], 0
35
36    def push(self, t):
37        self.ids.append(t)
38        text = self.tok.decode(self.ids)
39        if text.endswith("\ufffd"):
40            return ""
41        delta, self.sent = text[self.sent:], len(text)
42        return delta
43
44
45@unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here")
46class Detok(unittest.TestCase):
47    @classmethod
48    def setUpClass(cls):
49        import json
50        import strata_tokenizer as ST
51        t = find_tokenizer()
52        vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))
53        toks = [None] * len(vocab)
54        for s, i in vocab.items():
55            toks[i] = s
56        cls.tok = ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"),
57                               json.loads((t / "token_type.json").read_text()))
58
59    def same_stream(self, ids):
60        """The same text as the old re-decode, never behind it (the old one held complete characters too while
61        the tail was an incomplete one; the new one holds only the incomplete bytes), and never ahead of what the
62        ids so far decode to."""
63        a, b = OldDetokenizer(self.tok), Detokenizer(self.tok)
64        self.assertIsNotNone(b.inc)
65        old = new = ""
66        for i, t in enumerate(ids):
67            old += a.push(t)
68            new += b.push(t)
69            self.assertTrue(new.startswith(old), f"token {i} ({t}): behind the old stream")
70            self.assertTrue(self.tok.decode(ids[:i + 1]).startswith(new), f"token {i} ({t}): ahead of the ids")
71        if not self.tok.decode(ids).endswith("�"):
72            self.assertEqual(old, new)
73
74    def test_text_with_split_characters(self):
75        text = ("Grüße aus Zürich! 你好,世界。日本語のテキスト 🌊🦊👩‍💻 and ASCII code: def f(x): return x**2\n" * 40)
76        self.same_stream(self.tok.encode(text))
77
78    def test_random_ids_and_broken_bytes(self):
79        rng = random.Random(5)
80        n = len(self.tok.tokens)
81        for _ in range(20):   # random ids: split and invalid UTF-8 sequences everywhere (no U+FFFD token itself)
82            ids = [rng.randrange(n) for _ in range(300)]
83            ids = [t for t in ids if "\ufffd" not in self.tok.decode([t], errors="strict" if False else "replace")
84                   or len(self.tok.token_bytes(t)) < 3]
85            self.same_stream(ids)
86
87    def test_constant_cost(self):
88        ids = self.tok.encode("The quick brown fox jumps over the lazy dog. " * 2000)[:16384]
89        d = Detokenizer(self.tok)
90        for t in ids[:1024]:
91            d.push(t)
92        t0 = time.perf_counter()
93        for t in ids[1024:1124]:
94            d.push(t)
95        early = time.perf_counter() - t0
96        for t in ids[1124:16000]:
97            d.push(t)
98        t0 = time.perf_counter()
99        for t in ids[16000:16100]:
100            d.push(t)
101        late = time.perf_counter() - t0
102        self.assertLess(late / 100, 0.0002, "a token after 16K tokens costs more than 0.2 ms")
103        self.assertLess(late, early * 5 + 0.002)
104
105
106# ------------------------------------------------------------------ #268: the heap BPE for long words
107_REAL = []
108
109
110def real_tokenizer():
111    """The pack's tokenizer, loaded once for every class that needs it (None when there is no pack here)."""
112    if not _REAL:
113        t = find_tokenizer()
114        if t is None:
115            _REAL.append(None)
116        else:
117            import json
118            import strata_tokenizer as ST
119            vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))
120            toks = [None] * len(vocab)
121            for s, i in vocab.items():
122                toks[i] = s
123            _REAL.append(ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"),
124                                      json.loads((t / "token_type.json").read_text())))
125    return _REAL[0]
126
127
128def random_text(rng, n_pieces=40):
129    """Strings shaped to make one pre-token piece long or awkward: CJK and Hangul runs (syllables and conjoining
130    jamo), letters under stacks of combining marks, URLs, minified code, digits, emoji, whitespace, specials."""
131    def run(lo, hi, k):
132        return "".join(chr(rng.randint(lo, hi)) for _ in range(k))
133
134    kinds = [
135        lambda: run(0x4E00, 0x9FFF, rng.randint(1, 400)),                       # CJK
136        lambda: run(0xAC00, 0xD7A3, rng.randint(1, 200)),                       # Hangul syllables
137        lambda: "".join(chr(0x1100 + rng.randrange(19)) + chr(0x1161 + rng.randrange(21))
138                        for _ in range(rng.randint(1, 60))),                    # conjoining jamo
139        lambda: "".join(rng.choice("aeiouxyz") + run(0x0300, 0x036F, rng.randint(0, 4))
140                        for _ in range(rng.randint(1, 80))),                    # combining marks
141        lambda: "https://example.com/" + "/".join(run(0x61, 0x7A, rng.randint(1, 12))
142                                                  for _ in range(rng.randint(1, 20))) + "?q=" + run(0x30, 0x39, 8),
143        lambda: "".join(rng.choice(["var ", "a=", "b", "(", ")", "{", "}", ";", "function", "return", "x", "+",
144                                    "!0", "void 0", ",", ".", "[", "]", "=>", "&&"]) for _ in range(rng.randint(1, 300))),
145        lambda: run(0x30, 0x39, rng.randint(1, 50)),
146        lambda: rng.choice([" ", "  ", "\n", "\n\n", "\t", "\r\n", " \n "]) * rng.randint(1, 30),
147        lambda: rng.choice(["\U0001f600", "\U0001f30a", "\U0001f469‍\U0001f4bb", "é", "ß"]) * rng.randint(1, 30),
148        lambda: rng.choice(["<|im_end|>", "<|im_start|>", "<think>", "</think>", "<tool_call>", "<|im_sta"]),
149        lambda: "a" * rng.randint(60, 300),
150        lambda: run(0x20, 0x7E, rng.randint(1, 200)),
151    ]
152    return "".join(rng.choice(kinds)() for _ in range(rng.randint(1, n_pieces)))
153
154
155def encode_with(tok, text, parse_special, heap_min):
156    tok.HEAP_MIN = heap_min
157    try:
158        return tok.encode(text, parse_special=parse_special)
159    finally:
160        del tok.HEAP_MIN
161
162
163def synthetic_tokenizer(seed=268, n_merges=1500):
164    """A small byte-level BPE vocabulary with merges learned (randomly) from random_text, and a few specials of
165    both kinds - so the parity test runs without a pack."""
166    import strata_tokenizer as ST
167    rng = random.Random(seed)
168    tokens = sorted(set(ST.BYTE_TO_UNICODE.values()))
169    have, merges = set(tokens), []
170    words = []
171    for _ in range(60):
172        for piece in ST.regex.compile(ST.QWEN35_PATTERN).findall(random_text(rng, 10)):
173            words.append([ST.BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")])
174    words = [w for w in words if len(w) > 1]
175    while len(merges) < n_merges:
176        w = rng.choice(words)
177        if len(w) < 2:
178            continue
179        i = rng.randrange(len(w) - 1)
180        a, b = w[i], w[i + 1]
181        w[i:i + 2] = [a + b]                        # learn in place, so later merges build on earlier ones
182        if a + b in have or f"{a} {b}" in merges:
183            continue
184        merges.append(f"{a} {b}")
185        tokens.append(a + b)
186        have.add(a + b)
187    types = [1] * len(tokens)
188    for lit, ty in [("<|im_end|>", 3), ("<|im_start|>", 3), ("<think>", 4), ("</think>", 4), ("<tool_call>", 4)]:
189        tokens.append(lit)
190        types.append(ty)
191    return ST.Tokenizer(tokens, merges, types)
192
193
194class ThreadedEncode(unittest.TestCase):
195    """#1385: 'int' object has no attribute 'ranks' in _bpe, seen once under load.  Could not be reproduced here (it
196    looks like an interpreter fault); this pins that many threads sharing one Tokenizer, as the server does, get
197    exactly the single-threaded ids, and that _bpe works with a tokenizer whose own state is only read."""
198
199    def test_threads_match_serial(self):
200        import threading
201        tok = synthetic_tokenizer()
202        rng = random.Random(1385)
203        texts = [random_text(rng, 6) for _ in range(40)]
204        want = [tok.encode(t) for t in texts]
205        errors = []
206
207        def work():
208            try:
209                for _ in range(15):
210                    for t, w in zip(texts, want):
211                        if tok.encode(t) != w:
212                            errors.append("mismatch")
213            except Exception as e:                  # noqa: BLE001
214                errors.append(repr(e))
215
216        ts = [threading.Thread(target=work) for _ in range(8)]
217        for t in ts:
218            t.start()
219        for t in ts:
220            t.join()
221        self.assertEqual(errors, [])
222
223
224class HeapBpe(unittest.TestCase):
225    """#268: words longer than HEAP_MIN symbols merge with a heap; the ids must be exactly the scan's."""
226
227    def parity(self, tok, texts):
228        for k, text in enumerate(texts):
229            for ps in (False, True):
230                old = encode_with(tok, text, ps, 10 ** 9)           # the scan for every word
231                self.assertEqual(encode_with(tok, text, ps, 0), old, f"text {k} parse_special={ps}")   # the heap
232                self.assertEqual(tok.encode(text, parse_special=ps), old, f"text {k} parse_special={ps}")
233
234    def test_words_directly(self):
235        tok = synthetic_tokenizer()
236        rng = random.Random(1)
237        import strata_tokenizer as ST
238        for _ in range(300):
239            for piece in ST.regex.compile(ST.QWEN35_PATTERN).findall(random_text(rng, 8)):
240                word = "".join(ST.BYTE_TO_UNICODE[b] for b in piece.encode("utf-8"))
241                tok.HEAP_MIN = 10 ** 9
242                try:
243                    old = tok._bpe(word)
244                finally:
245                    del tok.HEAP_MIN
246                self.assertEqual(tok._bpe_heap(word), old, repr(piece[:40]))
247
248    def test_synthetic_vocab(self):
249        tok = synthetic_tokenizer()
250        rng = random.Random(2)
251        self.parity(tok, [random_text(rng) for _ in range(60)] + ["a" * 5000, "ab" * 3000, ""])
252
253    @unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here")
254    def test_pack_vocab(self):
255        tok = real_tokenizer()
256        rng = random.Random(3)
257        fixed = ["你好,世界" * 150, "한국어 텍스트" * 100,
258                 "é́̂" * 200, "x" * 5000,
259                 "https://example.com/" + "a/b-c_d.e?f=g&h=i#j" * 60,
260                 "!function(e){var t={};function n(r){if(t[r])return t[r].exports}}" * 30,
261                 "<|im_start|>user\n日本語" * 40 + "<|im_end|><think>" + "漢" * 300]
262        self.parity(tok, fixed + [random_text(rng) for _ in range(40)])
263
264    def check_speed(self, tok):
265        rng = random.Random(4)
266        text = "".join(chr(rng.randint(0x4E00, 0x9FFF)) for _ in range(8192))       # one 24K-byte piece
267        t0 = time.perf_counter()
268        ids = tok.encode(text)
269        took = time.perf_counter() - t0
270        self.assertEqual(tok.decode(ids), text)
271        self.assertLess(took, 1.0, f"an 8K-character CJK run took {took:.2f} s")
272
273    def test_speed_synthetic(self):
274        self.check_speed(synthetic_tokenizer())
275
276    @unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here")
277    def test_speed_pack(self):
278        self.check_speed(real_tokenizer())
279
280
281if __name__ == "__main__":
282    unittest.main()