okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
8.8 KiB163 linesraw
1"""serve/test_prompt_encoder.py - #567's incremental prompt encoding with #537's plain spans: every prompt's ids
2are those of a full encode, and a turn reuses the previous one's.
3
4    python -m unittest serve.test_prompt_encoder -v
5"""
6from __future__ import annotations
7
8import random
9import re
10import sys
11import unittest
12from pathlib import Path
13
14ROOT = Path(__file__).resolve().parents[1]
15sys.path.insert(0, str(ROOT))
16sys.path.insert(0, str(ROOT / "tools"))
17from serve.frontend import ChatTemplate  # noqa: E402
18from serve.server import ByteTokenizer, MockEngine, Service  # noqa: E402
19from strata_tokenizer import PromptEncoder, plain_agree_until  # noqa: E402
20
21
22class ThinkTokenizer(ByteTokenizer):
23    """ByteTokenizer whose <think> / </think> are specials matched even without parse_special (type 4), as in the
24    Qwen vocabulary: the case #537's plain spans exist for."""
25    SPECIALS = ByteTokenizer.SPECIALS + ["<think>", "</think>"]
26    ALWAYS = ("<think>", "</think>")
27
28
29PIECES = ["<|im_start|>user\n", "<|im_end|>\n", "<think>", "</think>", "hello ", "é你 ", "<|im_sta", "x" * 7,
30          "<|im_start|>assistant\n", "</thi", "\n\n", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>"]
31
32
33def spans_of(text, rng):
34    """Random plain spans over the specials' texts (<think>, </think>, <|im_start|>, ...), as unmark_think_literals
35    marks the ones quoted inside a message."""
36    matches = re.finditer("|".join(map(re.escape, ThinkTokenizer.SPECIALS)), text)
37    return tuple((m.start(), m.end()) for m in matches if rng.random() < 0.5)   # finditer: left to right, no overlap
38
39
40class Units(unittest.TestCase):
41    def test_plain_agree_until(self):
42        self.assertEqual(plain_agree_until((), (), 50), 50)
43        self.assertEqual(plain_agree_until(((5, 13),), ((5, 13),), 50), 50)
44        self.assertEqual(plain_agree_until(((5, 13),), (), 50), 5)
45        self.assertEqual(plain_agree_until(((5, 13),), ((5, 9),), 50), 9)
46        self.assertEqual(plain_agree_until(((60, 70),), (), 50), 50)          # beyond the shared text: no matter
47        self.assertEqual(plain_agree_until(((5, 13), (20, 28)), ((5, 13),), 50), 20)
48
49    def test_same_ids_as_a_full_encode(self):
50        tok = ThinkTokenizer()
51        rng = random.Random(7)
52        for conv in range(300):
53            enc = PromptEncoder(tok)
54            text, plain = "", ()
55            for turn in range(8):
56                text += "".join(rng.choice(PIECES) for _ in range(rng.randint(1, 12)))
57                if rng.random() < 0.6:
58                    plain = spans_of(text, rng)                     # the spans may change in the shared part too
59                with self.subTest(conv=conv, turn=turn):
60                    self.assertEqual(enc.encode(text, plain), tok.encode(text, True, plain))
61                if rng.random() < 0.2 and len(text) > 10:              # an edit: a client re-rendering its history
62                    cut = rng.randrange(len(text))
63                    text = text[:cut]
64                    plain = tuple((a, b) for a, b in plain if b <= cut)
65
66    def test_a_turn_reuses_the_previous_one(self):
67        tok = ThinkTokenizer()
68        enc = PromptEncoder(tok)
69        # as a chat turn: the earlier prompt goes on past its last special (the answer being written), and the
70        # next one shares it up to there - the resume point needs max_special_len characters after it
71        base = "<|im_start|>user\n" + "quoted </think> here " * 200 + "<|im_end|>\n<|im_start|>assistant\nan answer"
72        plain = tuple((i, i + 8) for i in range(len(base)) if base.startswith("</think>", i))
73        enc.encode(base, plain)
74        more = base + " that goes on<|im_end|>\n<|im_start|>user\nnext<|im_end|>\n"
75        self.assertEqual(enc.encode(more, plain), tok.encode(more, True, plain))
76        self.assertGreater(enc.last_reused, len(base) // 2)
77        # the same text with the quoted </think> no longer plain: nothing before it may be reused past its start
78        self.assertEqual(enc.encode(more, ()), tok.encode(more, True, ()))
79        self.assertLessEqual(enc.last_reused, plain[0][0])
80
81
82class Served(unittest.TestCase):
83    def test_quoted_think_across_turns(self):
84        tok = ThinkTokenizer()
85        template = ChatTemplate(ROOT / "serve/chat_template.jinja")
86        svc = Service(MockEngine(tok, "</think>\n\nok", max_context=1 << 20), tok, template)
87        full = Service(MockEngine(tok, "</think>\n\nok", max_context=1 << 20), tok, template)
88        full.prompts = None                                        # the reference: a full encode every time
89        self.assertIsNotNone(svc.prompts)
90        msgs = [{"role": "system", "content": "Explain tags."}]
91        for turn in range(5):
92            msgs.append({"role": "user", "content": f"turn {turn}: what does </think> mean? <think> too " * 3})
93            got, want = svc.encode_prompt(msgs, None, {}), full.encode_prompt(msgs, None, {})
94            self.assertEqual(got, want)
95            if turn:
96                self.assertGreater(svc.prompts.last_reused, 0)
97            msgs.append({"role": "assistant", "content": "It closes the reasoning: </think> is a marker."})
98
99    def service(self, max_context=1 << 22):
100        tok = ByteTokenizer()
101        return Service(MockEngine(tok, "ok", max_context=max_context), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
102
103    def test_another_conversation_does_not_evict_the_first(self):
104        """A subagent beside the main conversation: every rendered prompt starts with the template's header, which
105        must not make the second client's prompt a continuation of the first's entry."""
106        svc = self.service()
107        turn2 = [{"role": "user", "content": "a long question " * 500}, {"role": "assistant", "content": "answer"},
108                 {"role": "user", "content": "next"}]
109        svc.encode_prompt(turn2, None, {})
110        svc.encode_prompt([{"role": "user", "content": "one unrelated prompt " * 300}], None, {})
111        self.assertEqual(len(svc.prompts.entries), 2)
112        turn3 = turn2 + [{"role": "assistant", "content": "x"}, {"role": "user", "content": "more"}]
113        svc.encode_prompt(turn3, None, {})
114        self.assertGreater(svc.prompts.last_reused, len(turn2[0]["content"]))
115        self.assertEqual(len(svc.prompts.entries), 2)           # turn 3 replaced turn 2, the other one stayed
116
117    def test_a_refused_prompt_is_not_kept(self):
118        svc = self.service(max_context=4096)
119        svc.fit_max_tokens = False   # the strict mode refuses an over-long max_tokens (the default now shortens it)
120        msgs = [{"role": "user", "content": "kept " * 20}]
121        svc.prepare(msgs, None, {}, 16)
122        refused = msgs + [{"role": "assistant", "content": "a"}, {"role": "user", "content": "more " * 20}]
123        full = self.service(max_context=4096)
124        full.prompts = None
125        refused_ids = full.encode_prompt(refused, None, {})
126        with self.assertRaisesRegex(ValueError, "exceeds the context"):
127            svc.prepare(refused, None, {}, 1 << 20)
128        self.assertNotIn(refused_ids, [e[2] for e in svc.prompts.entries])
129        self.assertNotIn(full.render_prompt(refused, None, {}), [e[0] for e in svc.prompts.entries])
130
131    def test_random_messages_equal_a_full_encode(self):
132        """Messages quoting control-token texts and <think> tags at random, growing, edited and cut back between
133        requests: the incremental encoder's ids are the full encode's, 2400 prompts."""
134        tok = ThinkTokenizer()
135        template = ChatTemplate(ROOT / "serve/chat_template.jinja")
136        svc = Service(MockEngine(tok, "ok", max_context=1 << 20), tok, template)
137        full = Service(MockEngine(tok, "ok", max_context=1 << 20), tok, template)
138        full.prompts = None
139        rng = random.Random(567)
140        quoted = ThinkTokenizer.SPECIALS + ["<|im_sta", "</thi"]
141        words = ["hello ", "é你 ", "x" * 9, "\n", "tool "]
142
143        def text():
144            return "".join(rng.choice(quoted if rng.random() < 0.4 else words) for _ in range(rng.randint(1, 10)))
145
146        reused = 0
147        for conv in range(300):
148            msgs = [{"role": "system", "content": text()}]
149            for turn in range(8):
150                msgs.append({"role": "user", "content": text()})
151                if rng.random() < 0.15:                             # an earlier turn edited by the client
152                    msgs[rng.randrange(len(msgs))]["content"] = text()
153                if rng.random() < 0.1 and len(msgs) > 2:            # a shorter conversation
154                    msgs = msgs[:rng.randrange(1, len(msgs))] + msgs[-1:]
155                with self.subTest(conv=conv, turn=turn):
156                    self.assertEqual(svc.encode_prompt(msgs, None, {}), full.encode_prompt(msgs, None, {}))
157                reused += svc.prompts.last_reused > 0
158                msgs.append({"role": "assistant", "content": text()})
159        self.assertGreater(reused, 1000)
160
161
162if __name__ == "__main__":
163    unittest.main()