okami.mom/strata

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

Niko1221Merge f-q4-intake (37e91bfdb): tools/qwen4_intake.py, the tokenizer refuses an unknown pre-tokenizer, the server's tool-call parser follows the chat template (serve/toolformat.py), packaging/make_model_release.py dry run (Qwen4 prep)97a50dc24

main
21.4 KiB450 linesraw
1"""Tests for tools/strata_tokenizer.py: llama.cpp's reference vectors, the piece cache (0.1.41: the ids are the ones the
2merge loop gives, cache cold, warm or switched off), and the incremental prompt encoder, which must give exactly the
3ids of a plain encode.
4
5    python -m unittest tools.test_strata_tokenizer -v
6
7The real vocabulary comes from $STRATA_TOKENIZER (a pack's tokenizer/ directory) when set, else from llama.cpp's
8`models/ggml-vocab-qwen35.gguf` next to the gguf-py the tools use ($STRATA_GGUF_PY, third_party/llama.cpp); the
9tests that need it are skipped without one.  The chat template's USER_DEFINED tokens (`<think>`, `<tool_call>`,
10...) are added to the llama.cpp vocabulary, which does not have them, as the pack's has.
11"""
12from __future__ import annotations
13
14import json
15import os
16import random
17import sys
18import unittest
19from pathlib import Path
20
21ROOT = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT / "tools"))
23sys.path.insert(0, str(ROOT))
24import strata_tokenizer as ST  # noqa: E402
25
26ADDED = ["<think>", "</think>", "<tool_call>", "</tool_call>", "<tool_response>", "</tool_response>",
27         "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"]
28
29
30def vocab_gguf() -> Path | None:
31    cands = [os.environ.get("STRATA_GGUF_PY"), ROOT / "third_party" / "llama.cpp" / "gguf-py", "/opt/llama.cpp/gguf-py"]
32    for c in cands:
33        if c and (Path(c).parent / "models" / "ggml-vocab-qwen35.gguf").is_file():
34            return Path(c).parent / "models" / "ggml-vocab-qwen35.gguf"
35    return None
36
37
38def load_tokenizer():
39    pack = os.environ.get("STRATA_TOKENIZER")
40    if pack and (Path(pack) / "vocab.json").is_file():
41        t = Path(pack)
42        vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))
43        tokens = [None] * len(vocab)
44        for s, i in vocab.items():
45            tokens[i] = s
46        return ST.Tokenizer(tokens, (t / "merges.txt").read_text(encoding="utf-8").split("\n"),
47                            json.loads((t / "token_type.json").read_text()))
48    path = vocab_gguf()
49    return None if path is None else gguf_tokenizer(path)
50
51
52def gguf_tokenizer(path):
53    """llama.cpp's qwen35 vocabulary with the template's added tokens: the one its test vectors were made with."""
54    from gguf_reader import GGUFFile
55    md = GGUFFile(path).metadata
56    tokens, types = list(md["tokenizer.ggml.tokens"]), list(md["tokenizer.ggml.token_type"])
57    for s in ADDED:
58        if s not in tokens:
59            tokens.append(s)
60            types.append(4)
61    return ST.Tokenizer(tokens, list(md["tokenizer.ggml.merges"]), types)
62
63
64def byte_tokenizer(specials: list[str]) -> ST.Tokenizer:
65    """A vocabulary of the 256 byte tokens and `specials` (CONTROL), no merges: small enough to build per test."""
66    tokens = [ST.BYTE_TO_UNICODE[b] for b in range(256)] + specials
67    return ST.Tokenizer(tokens, [], [1] * 256 + [3] * len(specials))
68
69
70WORDS = ["the", "tokenizer", " ", "  ", "\n", "\n\n", "\t", "def", "f(x):", "return", "x", "==", "->", "café",
71         "你好", "\U0001f600", "é", "1234", "don't", "I'm", "<|im_", "<think", "</", "tool", "_call>",
72         " ", "\r\n", "Hello,", "world!", "<", ">", "|", "      ", "x" * 70]
73
74
75def random_text(rnd: random.Random, n: int, specials=()) -> str:
76    parts = []
77    for _ in range(n):
78        parts.append(rnd.choice(WORDS) if not specials or rnd.random() > 0.05 else rnd.choice(specials))
79        if rnd.random() < 0.5:
80            parts.append(" ")
81    return "".join(parts)
82
83
84def conversation_prompts(template, rnd: random.Random) -> list[tuple[str, str]]:
85    """Rendered prompts, in the order a server would see them, from clients that grow a conversation turn after turn,
86    use tools, send images, change the start of the prompt, edit an earlier turn, send a shorter conversation, and
87    interleave with each other: (what happens, prompt)."""
88    out: list[tuple[str, str]] = []
89    specials = ["<|im_start|>", "<|im_end|>", "<think>", "</think>", "<tool_call>", "</tool_response>"]
90    weather = [{"type": "function", "function": {"name": "get_weather", "description": "Get the weather",
91                                                  "parameters": {"type": "object", "properties": {
92                                                      "city": {"type": "string"}}, "required": ["city"]}}}]
93
94    def add(what, msgs, tools=None, **kw):
95        out.append((what, template.render(msgs, tools=tools, **kw)))
96
97    # several turns, with unicode, a literal special token inside the text, and reasoning kept or not
98    msgs = [{"role": "system", "content": "Be brief. Réponds en français si on te parle en français."}]
99    for turn in range(6):
100        msgs.append({"role": "user", "content": random_text(rnd, 60, specials) + " é你\U0001f600 " * turn})
101        add(f"turn {turn}", msgs)
102        answer = {"role": "assistant", "content": random_text(rnd, 30)}
103        if turn % 2:
104            answer["reasoning_content"] = random_text(rnd, 30)
105        msgs.append(answer)
106    grown = list(msgs)
107
108    # tools: definitions, a call, its response, then a following turn
109    tmsgs = [{"role": "user", "content": "Weather in Oslo?"}]
110    add("tools 1", tmsgs, weather)
111    tmsgs += [{"role": "assistant", "content": "", "tool_calls": [{"type": "function", "function": {
112        "name": "get_weather", "arguments": {"city": "Oslo"}}}]},
113        {"role": "tool", "content": "{\"temp\": 3}", "name": "get_weather"}]
114    add("tools 2", tmsgs, weather)
115    tmsgs += [{"role": "assistant", "content": "3 degrees."}, {"role": "user", "content": "And in Bergen? " * 20}]
116    add("tools 3", tmsgs, weather)
117
118    # images: one per user turn, the placeholder tokens are specials
119    imsgs = []
120    for turn in range(3):
121        imsgs.append({"role": "user", "content": [{"type": "image", "source": f"img{turn}"},
122                                                   {"type": "text", "text": f"What is on picture {turn}?"}]})
123        add(f"images {turn}", imsgs)
124        imsgs.append({"role": "assistant", "content": "A cat."})
125
126    # the start of the prompt changes (a thinking level, a system message), then the old conversation grows again
127    add("effort changed", grown, reasoning_effort="low")
128    add("system changed", [dict(grown[0], content=grown[0]["content"] + " Be kind.")] + grown[1:])
129    grown.append({"role": "user", "content": "one more question"})
130    add("grown again", grown)
131
132    # an earlier turn edited, then a conversation that got shorter, then the full one again
133    edited = list(grown)
134    edited[3] = dict(edited[3], content=edited[3]["content"] + " (edited)")
135    add("edited", edited)
136    add("shorter", grown[:5])
137    add("empty user", [{"role": "user", "content": ""}])
138    add("full again", grown)
139    return out
140
141
142class Oracle(unittest.TestCase):
143    """llama.cpp's own tokenizer test vectors for qwen35."""
144
145    def test_llama_cpp_vectors(self):
146        path = vocab_gguf()
147        if path is None or not path.with_suffix(".gguf.inp").is_file():
148            self.skipTest("llama.cpp's ggml-vocab-qwen35.gguf test vectors are not here")
149        tk = gguf_tokenizer(path)                  # not $STRATA_TOKENIZER: the vectors belong to this vocabulary
150        inp = path.with_suffix(".gguf.inp").read_text(encoding="utf-8").split("\n__ggml_vocab_test__\n")
151        out = path.with_suffix(".gguf.out").read_text(encoding="utf-8").split("\n")
152        n = 0
153        for text, want in zip(inp, out):
154            if text.endswith("\n__ggml_vocab_test__"):
155                text = text[:-len("\n__ggml_vocab_test__")]
156            self.assertEqual(tk.encode(text), [int(x) for x in want.split()], repr(text[:40]))
157            n += 1
158        self.assertGreater(n, 40)
159
160
161class Marks(unittest.TestCase):
162    @classmethod
163    def setUpClass(cls):
164        cls.tk = load_tokenizer()
165        if cls.tk is None:
166            raise unittest.SkipTest("no tokenizer (set STRATA_TOKENIZER or STRATA_GGUF_PY)")
167
168    def test_marks(self):
169        text = "a<|im_start|>user\nhi<|im_end|>\n<think>\n"
170        ids, marks = self.tk.encode_marked(text, parse_special=True)
171        self.assertEqual(ids, self.tk.encode(text, parse_special=True))
172        self.assertEqual([m[0] for m in marks], [text.index("user"), text.index("<|im_end|>") + len("<|im_end|>"),
173                                                  len(text) - 1])
174        for end, n in marks:                            # each mark: the ids of the text up to it
175            self.assertEqual(ids[:n], self.tk.encode(text[:end], parse_special=True))
176
177
178class Prompts(unittest.TestCase):
179    """PromptEncoder: the ids of a plain encode, whatever the earlier prompts were."""
180
181    @classmethod
182    def setUpClass(cls):
183        cls.tk = load_tokenizer()
184        if cls.tk is None:
185            raise unittest.SkipTest("no tokenizer (set STRATA_TOKENIZER or STRATA_GGUF_PY)")
186        from serve.frontend import ChatTemplate
187        cls.template = ChatTemplate(ROOT / "serve" / "chat_template.jinja")
188
189    def check(self, enc, text):
190        self.assertEqual(enc.encode(text), self.tk.encode(text, parse_special=True))
191
192    def test_chat_golden(self):
193        cases = json.loads((ROOT / "serve" / "chat_golden.json").read_text(encoding="utf-8"))
194        enc = ST.PromptEncoder(self.tk)
195        for c in cases + cases:                         # the second round finds its own earlier prompts
196            if c.get("rendered"):
197                with self.subTest(case=c["name"]):
198                    self.check(enc, c["rendered"])
199
200    def test_conversations(self):
201        for seed in range(3):
202            prompts = conversation_prompts(self.template, random.Random(seed))
203            wants = [self.tk.encode(prompt, parse_special=True) for _, prompt in prompts]
204            for keep in (1, 2, 4):
205                enc = ST.PromptEncoder(self.tk, keep=keep)
206                for (what, prompt), want in zip(prompts, wants):
207                    with self.subTest(seed=seed, keep=keep, what=what):
208                        self.assertEqual(enc.encode(prompt), want)
209
210    def test_growing_turn_reuses_the_previous_prompt(self):
211        enc = ST.PromptEncoder(self.tk)
212        msgs = [{"role": "user", "content": "first question " * 50}]
213        prev = ""
214        for turn in range(4):
215            prompt = self.template.render(msgs)
216            self.check(enc, prompt)
217            if turn:
218                self.assertGreater(enc.last_reused, len(prev) - 100)
219            prev = prompt
220            msgs += [{"role": "assistant", "content": f"answer {turn}"}, {"role": "user", "content": f"question {turn}"}]
221
222    def test_prefix_of_an_earlier_prompt_and_unrelated_prompts(self):
223        enc = ST.PromptEncoder(self.tk, keep=2)
224        a = self.template.render([{"role": "user", "content": "first question " * 50}])
225        b = self.template.render([{"role": "user", "content": "another conversation"}])
226        c = self.template.render([{"role": "user", "content": "a third one"}])
227        for text in (a, a[:len(a) // 2], b, c, a, a + "tail", "", "<|im_end|>", "<|im_end|><|im_end|>x"):
228            with self.subTest(text=text[:30]):
229                self.check(enc, text)
230
231    def test_a_read_only_encode_gives_the_ids_and_stores_nothing(self):
232        enc = ST.PromptEncoder(self.tk)
233        a = self.template.render([{"role": "user", "content": "first question " * 50}])
234        enc.encode(a)
235        kept = list(enc.entries)
236        for text in (a + "<|im_start|>user\nand a follow-up<|im_end|>\n", a[:len(a) // 2], "<|im_end|>x",
237                     self.template.render([{"role": "user", "content": "another conversation"}])):
238            with self.subTest(text=text[:30]):
239                self.assertEqual(enc.encode(text, store=False), self.tk.encode(text, parse_special=True))
240                self.assertTrue(enc.entries == kept, "a read-only encode wrote an entry")
241        self.assertEqual(enc.encode(a + "tail", store=False), self.tk.encode(a + "tail", parse_special=True))
242        self.assertGreater(enc.last_reused, len(a) // 2)
243
244    def test_the_returned_ids_are_the_callers(self):
245        enc = ST.PromptEncoder(self.tk)
246        text = "<|im_start|>user\nhi<|im_end|>\n" + "and a tail longer than the look-ahead margin. " * 3
247        want = self.tk.encode(text, parse_special=True)
248        got = enc.encode(text)
249        got[0] = -1                                     # inside the part the next call takes from this one
250        got.append(-1)
251        self.assertEqual(enc.encode(text), want)
252        self.assertGreater(enc.last_reused, 0)
253
254
255class Margin(unittest.TestCase):
256    """A special literal that is a prefix of a longer one: cutting at the shorter one's end without the look-ahead
257    margin would give different ids."""
258
259    def test_longer_literal_past_the_common_prefix(self):
260        tk = byte_tokenizer(["<|a|>", "<|a|>zz"])
261        enc = ST.PromptEncoder(tk)
262        first = "x<|a|>y" + "<|a|>" * 3 + "q"
263        self.assertEqual(enc.encode(first), tk.encode(first, parse_special=True))
264        second = "x<|a|>y" + "<|a|>" * 3 + "zz"             # shares everything up to the last <|a|>
265        got = enc.encode(second)
266        self.assertEqual(got, tk.encode(second, parse_special=True))
267        self.assertEqual(got[-1], tk.special_tokens["<|a|>zz"])
268        self.assertGreater(enc.last_reused, 0)              # the earlier boundaries were still reused
269
270    def test_literal_ending_inside_another(self):
271        tk = byte_tokenizer(["<|a|>", "b<|a|>c"])
272        enc = ST.PromptEncoder(tk)
273        for text in ("zzb<|a|>d", "zzb<|a|>c", "zzb<|a|>cz<|a|>", "zzb<|a|>cz<|a|>b<|a|>c"):
274            with self.subTest(text=text):
275                self.assertEqual(enc.encode(text), tk.encode(text, parse_special=True))
276
277    def test_random_specials(self):
278        """Literals that extend or end inside one another, texts that change right after one of them."""
279        rnd = random.Random(3)
280
281        def word(lo, hi):
282            return "".join(rnd.choice("<|ab>") for _ in range(rnd.randint(lo, hi)))
283        for trial in range(60):
284            a, b = word(2, 4), word(2, 4)
285            lits = sorted({a, a + word(1, 3), b, word(1, 2) + b + word(0, 2)})
286            tk = byte_tokenizer(lits)
287            enc = ST.PromptEncoder(tk, keep=3)
288            pieces = lits + [x[:rnd.randint(1, len(x))] for x in lits] + ["x", "y", "a", "|"]
289            base = "".join(rnd.choice(pieces) for _ in range(60))
290            for _ in range(30):
291                cut = rnd.randint(0, len(base))
292                text = base[:cut] + "".join(rnd.choice(pieces) for _ in range(rnd.randint(0, 6)))
293                self.assertEqual(enc.encode(text), tk.encode(text, parse_special=True), (lits, text))
294                if rnd.random() < 0.3:
295                    base = text + base[cut:]
296
297
298class CommonPrefix(unittest.TestCase):
299    def test_against_a_loop(self):
300        rnd = random.Random(5)
301        for _ in range(500):
302            a = "".join(rnd.choice("ab") for _ in range(rnd.randint(0, 9000)))
303            k = rnd.randint(0, len(a))
304            b = a[:k] + rnd.choice(["", "c", "cd"]) + a[k:k + rnd.randint(0, 50)]
305            want = 0
306            while want < min(len(a), len(b)) and a[want] == b[want]:
307                want += 1
308            self.assertEqual(ST.common_prefix_len(a, b), want)
309            self.assertEqual(ST.common_prefix_len(b, a), want)
310
311
312
313def toy() -> ST.Tokenizer:
314    base = [ST.BYTE_TO_UNICODE[b] for b in range(256)]
315    merges = ["t h", "th e", "i n", "a n", "an d", "Ġ t", "Ġt h", "Ġth e", "e r", "o n"]
316    merges = [m.replace("Ġ", ST.BYTE_TO_UNICODE[32]) for m in merges]
317    tokens = list(base)
318    for m in merges:
319        a, b = m.split(" ")
320        tokens.append(a + b)
321    return ST.Tokenizer(tokens, merges)
322
323
324class PieceCache(unittest.TestCase):
325    def test_same_ids_cold_warm_and_off(self):
326        rng = random.Random(7)
327        words = ["the", "and", "in", "on", "there", "other", "x" * 70, "你好", "def", "return", "\n\n", "  "]
328        text = "".join(rng.choice(words) + rng.choice([" ", "", "\n", "\t"]) for _ in range(3000))
329        a = toy()
330        a.PIECE_CACHE_MAX = 0
331        want = a.encode(text)
332        b = toy()
333        cold = b.encode(text)
334        warm = b.encode(text)
335        self.assertEqual(cold, want)
336        self.assertEqual(warm, want)
337        self.assertGreater(len(b._piece_ids), 0)
338        self.assertEqual(b.decode(warm), text)
339
340    def test_the_cache_is_bounded(self):
341        t = toy()
342        t.PIECE_CACHE_MAX = 5
343        t.encode(" ".join("w%d" % i for i in range(100)))
344        self.assertLessEqual(len(t._piece_ids), 5)
345
346
347class ByteCache(unittest.TestCase):
348    def test_decode_before_encode_cold_and_warm(self):
349        t = toy()
350        text = "café 日本語 🙂\r\n\x00"
351        ids = list(text.encode("utf-8"))  # toy's first 256 token IDs are the raw bytes
352        self.assertEqual(t.decode(ids, errors="strict"), text)
353        self.assertEqual(t.decode(ids, errors="strict"), text)
354        self.assertEqual(t.decode([]), "")
355        for i in range(256):
356            self.assertEqual(t.token_bytes(i), bytes([i]))
357
358    def test_invalid_ids_before_and_after_cache_use(self):
359        t = toy()
360        for _ in range(2):
361            for i in (-1, len(t.tokens), len(t.tokens) + 100):
362                with self.assertRaises(IndexError):
363                    t.token_bytes(i)
364            self.assertEqual(t.token_bytes(65), b"A")
365
366    def test_instances_with_different_vocabularies_stay_independent(self):
367        tokens = [ST.BYTE_TO_UNICODE[b] for b in range(256)]
368        a, b = ST.Tokenizer(tokens, []), ST.Tokenizer(tokens[::-1], [])
369        text = "the café 日本語 🙂\n"
370        for t in (a, b, a, b):
371            expected = [t.ids[ST.BYTE_TO_UNICODE[byte]] for byte in text.encode("utf-8")]
372            self.assertEqual(t.encode(text), expected)
373            self.assertEqual(t.decode(expected, errors="strict"), text)
374        self.assertEqual(a.token_bytes(0), b"\x00")
375        self.assertEqual(b.token_bytes(0), b"\xff")
376
377    def test_shared_tokenizer_concurrent_first_decode(self):
378        import threading
379        from concurrent.futures import ThreadPoolExecutor
380        t = toy()
381        texts = ["café", "日本語", "🙂\r\n", "\x00plain"]
382        barrier = threading.Barrier(len(texts))
383        def decode(text):
384            ids = list(text.encode("utf-8"))
385            barrier.wait(timeout=5)
386            for _ in range(100):
387                if t.decode(ids, errors="strict") != text:
388                    raise AssertionError("concurrent decode changed the text")
389            return text
390        with ThreadPoolExecutor(len(texts)) as pool:
391            self.assertEqual(list(pool.map(decode, texts)), texts)
392
393
394if __name__ == "__main__":
395    unittest.main()
396
397
398class PreTokenizerType(unittest.TestCase):
399    """P4 (Qwen4 prep): an unknown tokenizer.ggml.pre is refused, never split with another model's rule.  The types that were
400    accepted before (qwen35, an empty one, anything starting with deepseek) still build and split exactly as they did."""
401
402    def test_known_types(self):
403        self.assertEqual(ST.pre_tokenizer_kind("qwen35"), "qwen35")
404        self.assertEqual(ST.pre_tokenizer_kind(None), "qwen35")
405        self.assertEqual(ST.pre_tokenizer_kind(""), "qwen35")
406        for p in ("deepseek3", "deepseek-v3", "deepseek-llm", "deepseek41"):
407            self.assertEqual(ST.pre_tokenizer_kind(p), "deepseek3", p)
408
409    def test_unknown_types_are_refused_with_the_name(self):
410        for p in ("qwen2", "qwen3", "qwen4", "default", "gpt2", "llama-bpe", "joyai-llm", "Qwen35", " qwen35"):
411            with self.subTest(p):
412                self.assertIsNone(ST.pre_tokenizer_kind(p))
413                with self.assertRaises(ST.UnknownPreTokenizer) as cm:
414                    ST.Tokenizer([chr(i) for i in range(4)], [], None, p)
415                self.assertIn(repr(p), str(cm.exception))
416                self.assertIsInstance(cm.exception, ValueError)       # callers that catch ValueError keep working
417
418    def test_from_gguf_refuses_an_unknown_type(self):
419        import tempfile
420        import struct
421        from gguf_reader import GGUF_MAGIC
422        from gguf_writer import GGUFWriter
423        w = GGUFWriter()
424        w.add("tokenizer.ggml.model", "gpt2")
425        w.add("tokenizer.ggml.pre", "qwen4")
426        w.add("tokenizer.ggml.tokens", ["a", "b"], "array:string")
427        w.add("tokenizer.ggml.merges", ["a b"], "array:string")
428        with tempfile.TemporaryDirectory() as d:
429            p = w.write(Path(d) / "x.gguf")
430            with self.assertRaises(ST.UnknownPreTokenizer):
431                ST.Tokenizer.from_gguf(p)
432            w.add("tokenizer.ggml.pre", "qwen35")
433            w.add("tokenizer.ggml.tokens", ["a", "b", "ab"], "array:string")
434            w.add("tokenizer.ggml.merges", ["a b"], "array:string")
435            ok = ST.Tokenizer.from_gguf(w.write(Path(d) / "y.gguf"))
436            self.assertEqual(ok.pre, "qwen35")
437            self.assertEqual(ok.encode("ab"), [2])
438
439    def test_accepted_types_split_as_before(self):
440        rnd = random.Random(7)
441        toks = [chr(i) for i in range(32, 127)] + ["\n", "\t", "你", "好"]
442        text = "".join(rnd.choice(toks) for _ in range(400)) + "Hello, World 123 你好\n\n  x_y"
443        a = ST.Tokenizer(toks, [], None, "qwen35")
444        self.assertEqual(a._split(text), ST.regex.compile(ST.QWEN35_PATTERN).findall(text))
445        self.assertEqual(ST.Tokenizer(toks, [], None, None)._split(text), a._split(text))
446        self.assertEqual(ST.Tokenizer(toks, [], None, "")._split(text), a._split(text))
447        d = ST.Tokenizer(toks, [], None, "deepseek3")
448        seq = [ST.regex.compile(x) for x in ST.DEEPSEEK3_PATTERNS]
449        self.assertEqual(d._split(text), ST._sequence_findall(seq, text))
450        self.assertEqual(ST.Tokenizer(toks, [], None, "deepseek-v3")._split(text), d._split(text))