okami.mom/strata

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

waveringanaserve tests: bring back the DeepSeek V4.1 cases upstream cut with the enginecded60248

main
13.8 KiB278 linesraw
1"""The end of a reply and the text held back in front of a stop string (#4576: "Nerazim" came out as "Neraz").
2
3DeepSeek-V4.1's tokenizer has no single token for Qwen's <|im_end|> / <|endoftext|>: it splits them into '<', '|', 'im', '_end',
4'|', '>' and 'end', 'of', 'text'.  A server that took the ids of those pieces as its stop ids (a config without "arch") ended the
5reply in front of the first "im" it wrote: Nerazim = N, er, az, im.  These tests keep three things true, for the OpenAI and the
6Anthropic route, streamed and not, with and without the family named:
7
8  * the reply that has no stop string comes out whole (every word that ends in a piece of a stop string or of an end marker);
9  * a stop string cuts the reply exactly there, whatever the chunking;
10  * the text held back for a stop string that does not come is given back at the end.
11
12    python -m unittest serve.test_stop_holdback -v
13"""
14from __future__ import annotations
15
16import json
17import sys
18import unittest
19import urllib.request
20from pathlib import Path
21
22ROOT = Path(__file__).resolve().parents[1]
23sys.path.insert(0, str(ROOT))
24sys.path.insert(0, str(ROOT / "tools"))
25import strata_tokenizer as ST  # noqa: E402
26from serve import frontend, server  # noqa: E402
27from serve.frontend import ChatTemplate  # noqa: E402
28from serve.server import ByteTokenizer, Detokenizer, Service, StopMatcher, end_token_ids, serve  # noqa: E402
29from serve.test_dsv41 import EOS, SPECIALS, TEMPLATE, DsEngine  # noqa: E402
30
31QWEN_STOPS = ["<|im_end|>", "<|im_start|>", "<|endoftext|>", "\nUser:"]
32DEEPSEEK_STOPS = ["<|end▁of▁sentence|>", "<|User|>", "</s>", "\n\nHuman:"]
33# words and endings that look like the start of a stop string or a piece of an end marker
34WORDS = ["Nerazim", "Zim", "swim", "Neraz", "im", "im_end", "Nerazimville", "a|b|c|", "x > y and a < b", "the end of the text",
35         "<", "<|", "<|im", "<|im_end", "|>", "friend", "legend", "\nUser", "\n\nHuman", "</", "</s", "<|User", "<|", "Nerazim<",
36         "Nerazim|", "Nerazim <|im_start|"]
37
38
39def nerazim_tokenizer() -> ST.Tokenizer:
40    """DeepSeek's specials, the 256 byte tokens and the pieces of the real vocabulary that matter here: N er az im ('im' is id
41    328 in the real one), and the pieces its tokenizer cuts Qwen's end markers into."""
42    b2u = ST.bytes_to_unicode()
43    extra = ["er", "az", "im", "_e", "_en", "_end", "en", "end", "of", "te", "tex", "text"]
44    merges = ["e r", "a z", "i m", "_ e", "_e n", "_en d", "e n", "en d", "o f", "t e", "te x", "tex t"]
45    tokens = [s for s, _ in SPECIALS] + [b2u[b] for b in range(256)] + extra
46    types = [t for _, t in SPECIALS] + [1] * (256 + len(extra))
47    return ST.Tokenizer(tokens, merges, types, "deepseek3", {"bos": 0, "eos": EOS})
48
49
50class Fixture(unittest.TestCase):
51    @classmethod
52    def setUpClass(cls):
53        cls.tok = nerazim_tokenizer()
54
55    def test_the_fixture_has_the_real_tokenizer_shape(self):
56        self.assertEqual([self.tok.tokens[i] for i in self.tok.encode("Nerazim")], ["N", "er", "az", "im"])
57        pieces = [self.tok.tokens[i] for i in self.tok.encode("<|im_end|>", parse_special=True)]
58        self.assertEqual(pieces, ["<", "|", "im", "_end", "|", ">"])
59        pieces = [self.tok.tokens[i] for i in self.tok.encode("<|endoftext|>", parse_special=True)]
60        self.assertEqual(pieces, ["<", "|", "end", "of", "text", "|", ">"])
61
62
63class EndTokenIds(Fixture):
64    def test_pieces_of_the_qwen_markers_are_not_stop_ids(self):
65        ids = end_token_ids(self.tok)
66        self.assertEqual(ids, {EOS})
67        pieces = set(self.tok.encode("<|im_end|>", parse_special=True)) | set(self.tok.encode("<|endoftext|>", parse_special=True))
68        self.assertFalse(ids & pieces)
69
70    def test_qwen_markers_that_are_one_token_each_are_the_stop_ids(self):
71        tok = ByteTokenizer()
72        self.assertEqual(end_token_ids(tok), set(tok.encode("<|im_end|>", parse_special=True))
73                         | set(tok.encode("<|endoftext|>", parse_special=True)))
74        self.assertEqual(len(end_token_ids(tok)), 2)
75
76    def test_no_marker_and_no_eos_means_no_stop_id(self):
77        class Bare:
78            def encode(self, text, parse_special=False):
79                return list(text.encode())
80        self.assertEqual(end_token_ids(Bare()), set())
81
82    def test_a_service_without_a_family_does_not_stop_on_im(self):
83        svc = Service(DsEngine(self.tok, "x"), self.tok, ChatTemplate(TEMPLATE))
84        im = self.tok.encode("im")[0]
85        for piece in ("im", "<", "|", ">", "end", "of", "text", "_end"):
86            self.assertNotIn(self.tok.encode(piece)[0], svc.stop_ids, piece)
87        self.assertIn(im, set(self.tok.encode("<|im_end|>", parse_special=True)))
88        self.assertEqual(svc.stop_ids, {EOS})
89
90
91class StopMatcherSplits(unittest.TestCase):
92    """StopMatcher alone: every way to cut the text in two, and one character at a time."""
93
94    @staticmethod
95    def run_matcher(stops, chunks):
96        m = StopMatcher(stops)
97        out = "".join(m.push(c) for c in chunks)
98        if m.hit is None:
99            out += m.flush()
100        return out, m.hit
101
102    def chunkings(self, text):
103        yield [text]
104        for i in range(1, len(text)):
105            yield [text[:i], text[i:]]
106        yield list(text)
107
108    def test_text_without_a_stop_string_comes_out_whole_at_every_split(self):
109        for stops in (QWEN_STOPS, DEEPSEEK_STOPS, ["im_end"], ["im"], ["zim"], ["|", ">"], ["end"]):
110            for word in WORDS:
111                text = "My friend " + word
112                if any(s in text for s in stops):
113                    continue
114                for chunks in self.chunkings(text):
115                    with self.subTest(stops=stops, text=text, chunks=chunks):
116                        self.assertEqual(self.run_matcher(stops, chunks), (text, None))
117
118    def test_a_stop_string_cuts_exactly_there_at_every_split(self):
119        for stops in (QWEN_STOPS, DEEPSEEK_STOPS):
120            for stop in stops:
121                for word in ("Nerazim", "swim"):
122                    text = f"My friend {word}{stop}never seen"
123                    for chunks in self.chunkings(text):
124                        with self.subTest(stops=stops, text=text, chunks=chunks):
125                            first = min((text.find(s), s) for s in stops if s in text)
126                            self.assertEqual(self.run_matcher(stops, chunks), (text[:first[0]], first[1]))
127
128    def test_the_held_back_tail_is_given_back_at_the_end(self):
129        for stops in (QWEN_STOPS, DEEPSEEK_STOPS):
130            for text in ("Nerazim <|im", "Nerazim <|User", "Nerazim\nUser", "Nerazim <", "ends with a pipe |"):
131                with self.subTest(stops=stops, text=text):
132                    self.assertEqual(self.run_matcher(stops, list(text)), (text, None))
133
134    def test_a_stop_string_that_starts_like_the_word_costs_nothing_but_the_wait(self):
135        # "im_end" as a stop: "Nerazim" holds "im" until the next character says it is not the stop string
136        m = StopMatcher(["im_end"])
137        self.assertEqual(m.push("Neraz"), "Neraz")
138        self.assertEqual(m.push("im"), "")
139        self.assertEqual(m.held, "im")
140        self.assertEqual(m.flush(), "im")
141
142
143class ByteWise(Fixture):
144    """The text path as the server runs it: one token per byte through the Detokenizer (a UTF-8 character split across tokens is held
145    until it is whole), then the StopMatcher."""
146
147    def run_bytes(self, stops, text):
148        tok = ByteTokenizer()
149        detok, m, out = Detokenizer(tok), StopMatcher(stops), ""
150        for b in text.encode("utf-8"):
151            out += m.push(detok.push(b))
152            if m.hit is not None:
153                break
154        if m.hit is None:
155            out += m.flush()
156        return out, m.hit
157
158    def test_every_word_comes_out_whole_byte_by_byte(self):
159        for stops in (QWEN_STOPS, DEEPSEEK_STOPS):
160            for word in WORDS + ["Zażółć", "日本語の名前"]:
161                text = "Hello " + word
162                if any(s in text for s in stops):
163                    continue
164                with self.subTest(stops=stops, text=text):
165                    self.assertEqual(self.run_bytes(stops, text), (text, None))
166
167    def test_a_multibyte_stop_string_is_cut_byte_by_byte(self):
168        text = "Nerazim<|end▁of▁sentence|>not shown"
169        self.assertEqual(self.run_bytes(DEEPSEEK_STOPS, text), ("Nerazim", "<|end▁of▁sentence|>"))
170
171
172class Routes(Fixture):
173    """The four ways out of the server (OpenAI and Anthropic, streamed and whole), with the family named and without it."""
174
175    def start(self, script, named):
176        """A server for `named` (one per test and setting, reused); the engine replays `script` for the next request."""
177        if named in self.servers:
178            engine = self.servers[named]
179            engine.script = self.tok.encode(script) + [EOS]     # (a marker in the script is text the model wrote)
180            self.base = self.bases[named]
181            return engine
182        engine = self.servers[named] = DsEngine(self.tok, script)
183        engine.script = self.tok.encode(script) + [EOS]
184        svc = Service(engine, self.tok, ChatTemplate(TEMPLATE), model_name="deepseek-v4.1-flash")
185        if named:
186            svc.model_arch = "deepseek41"
187            svc.set_family("deepseek41")
188        httpd = serve(svc, port=0)
189        self.addCleanup(httpd.server_close)
190        self.addCleanup(httpd.shutdown)
191        self.addCleanup(frontend.use_family, None)
192        self.base = self.bases[named] = f"http://127.0.0.1:{httpd.server_address[1]}"
193        return engine
194
195    def send(self, route, stream, stops):
196        if route == "openai":
197            path = "/v1/chat/completions"
198            body = {"model": "m", "max_tokens": 200, "stream": stream, "chat_template_kwargs": {"enable_thinking": False},
199                    "messages": [{"role": "user", "content": "Use the name Nerazim in a sentence."}]}
200            if stops:
201                body["stop"] = stops[:4]
202        else:
203            path = "/v1/messages"
204            body = {"model": "m", "max_tokens": 200, "stream": stream, "thinking": {"type": "disabled"},
205                    "messages": [{"role": "user", "content": "Use the name Nerazim in a sentence."}]}
206            if stops:
207                body["stop_sequences"] = stops
208        req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
209        with urllib.request.urlopen(req, timeout=30) as r:
210            raw = r.read().decode("utf-8")
211        text, finish, stop_seq = "", None, None
212        if not stream:
213            d = json.loads(raw)
214            if route == "openai":
215                text, finish = d["choices"][0]["message"].get("content") or "", d["choices"][0]["finish_reason"]
216            else:
217                text = "".join(b.get("text", "") for b in d["content"] if b["type"] == "text")
218                finish, stop_seq = d["stop_reason"], d.get("stop_sequence")
219            return text, finish, stop_seq
220        for line in raw.splitlines():
221            if not line.startswith("data:") or line.strip() == "data: [DONE]":
222                continue
223            d = json.loads(line[5:])
224            if route == "openai":
225                for ch in d.get("choices", []):
226                    text += (ch.get("delta") or {}).get("content") or ""
227                    finish = ch.get("finish_reason") or finish
228            elif d.get("type") == "content_block_delta":
229                text += d["delta"].get("text", "")
230            elif d.get("type") == "message_delta":
231                finish, stop_seq = d["delta"].get("stop_reason"), d["delta"].get("stop_sequence")
232        return text, finish, stop_seq
233
234    def setUp(self):
235        self.servers = {}
236        self.bases = {}
237
238    def every_route(self):
239        for named in (False, True):
240            for route in ("openai", "anthropic"):
241                for stream in (False, True):
242                    yield named, route, stream
243
244    def test_nerazim_and_its_kin_come_out_whole_with_no_stop_string(self):
245        for word in ("Nerazim", "Nerazimville and Nerazim", "swim", "Zim", "a|b|c|", "x > y", "the end of the text", "im_end", "<", "Nerazim<|im"):
246            for named, route, stream in self.every_route():
247                with self.subTest(word=word, named=named, route=route, stream=stream):
248                    self.start(word, named)
249                    text, finish, _ = self.send(route, stream, None)
250                    self.assertEqual(text.strip(), word)
251                    self.assertIn(finish, ("stop", "end_turn"))
252
253    def test_the_held_tail_is_given_back_when_the_stop_string_never_comes(self):
254        for stops in (QWEN_STOPS, DEEPSEEK_STOPS, ["im_end", "|>"]):
255            for named, route, stream in self.every_route():
256                for word in ("My friend Nerazim", "Nerazim <|im", "Nerazim <|User", "ends with a pipe |"):
257                    with self.subTest(stops=stops, word=word, named=named, route=route, stream=stream):
258                        self.start(word, named)
259                        text, finish, stop_seq = self.send(route, stream, stops)
260                        self.assertEqual(text.strip(), word)
261                        self.assertIn(finish, ("stop", "end_turn"))
262                        self.assertIsNone(stop_seq)
263
264    def test_a_stop_string_cuts_the_reply_there(self):
265        for stops in (QWEN_STOPS, DEEPSEEK_STOPS):
266            for named, route, stream in self.every_route():
267                for stop in stops:
268                    with self.subTest(stops=stops, stop=stop, named=named, route=route, stream=stream):
269                        self.start("My friend Nerazim" + stop + "and more", named)
270                        text, finish, stop_seq = self.send(route, stream, stops)
271                        self.assertEqual(text.strip(), "My friend Nerazim")
272                        self.assertIn(finish, ("stop", "end_turn", "stop_sequence"))
273                        if route == "anthropic":
274                            self.assertEqual(stop_seq, stop)
275
276
277if __name__ == "__main__":
278    unittest.main()