okami.mom/strata

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

Niko1221Merge f-int-tidy 4e9dde87e into f-p4-int (conversation tests in the CPU check preset, packer probe without bytecode, a per-architecture spill-guard baseline, a log line for a driver GPU pause between requests on AMD under Linux)466626cbb

main
17.5 KiB336 linesraw
1"""The thinking budget's hold (GEN hold=N:ID, lane AGENT-TURN P2): the budget's second engine pass continues from the
2live session instead of reading the whole reasoning again.
3
4The stub engine below behaves like the real one where it matters: it decodes in windows of several tokens, commits a
5window before it sends its tokens, sees a STOP only at a window's end (and can run one more window before it does), and
6keeps as its live session the prompt plus every token it sent but the last.  A prompt that the live session is not a
7prefix of falls back to the checkpoint at the previous prompt's last <|im_start|>.  With the hold it stops exactly at
8the hold and commits nothing past it, as serve_hold_remaining() does in the engine."""
9from __future__ import annotations
10
11import json
12import sys
13import unittest
14import urllib.request
15from pathlib import Path
16
17sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
18from serve.frontend import ChatTemplate  # noqa: E402
19from serve.server import HOLD_KEY, REASONING_WRAP_UP, ByteTokenizer, Service, StrataEngine, serve  # noqa: E402
20
21ROOT = Path(__file__).resolve().parents[1]
22
23
24class ThinkTokenizer(ByteTokenizer):
25    """The byte tokenizer with <think> / </think> as one token each, as the real tokenizer has them."""
26    SPECIALS = ByteTokenizer.SPECIALS + ["<think>", "</think>"]
27    ALWAYS = ("<think>", "</think>")
28
29
30class WindowEngine:
31    THOUGHT = "Let me think step by step about two plus two. " * 4
32    ANSWER = "The answer is 4."
33
34    def __init__(self, tok, windows=(3, 2, 4), overrun=True, can_hold=True, honours_hold=True, thought=None, can_hold_batch=False):
35        self.tok, self.max_context = tok, 4096
36        self.windows, self.overrun = windows, overrun
37        self.can_hold, self.honours_hold = can_hold, honours_hold
38        self.can_hold_batch = can_hold_batch   # READY says holdb: the --batch slots end at the hold too (P2b)
39        self.batch = 0
40        self.thought = thought if thought is not None else self.THOUGHT
41        self.start = tok.encode("<|im_start|>", parse_special=True)[0]
42        self.think_end = tok.encode("</think>", parse_special=True)[0]
43        self.end = tok.encode("<|im_end|>", parse_special=True)
44        self.wrap = tok.encode(REASONING_WRAP_UP, parse_special=True)
45        self.sampling_objects: list = []   # the sampling object each pass was handed (identity, as test_reasoning_loop_recovery reads it)
46        self.live: list[int] = []
47        self.checkpoints: list[int] = []
48        self.turn: list[int] | None = None
49        self.last: dict = {}
50        self.passes: list[dict] = []
51
52    def _model(self, ids):
53        """The tokens the model writes after `ids` (greedy, deterministic)."""
54        full = self.tok.encode(self.thought + "</think>\n\n" + self.ANSWER, parse_special=True) + self.end
55        if self.turn is not None and ids[:len(self.turn)] == self.turn:
56            so_far = ids[len(self.turn):]
57            if so_far[-len(self.wrap):] == self.wrap:
58                return self.tok.encode(self.ANSWER) + self.end
59            if full[:len(so_far)] == so_far:
60                return full[len(so_far):]
61        self.turn = list(ids)
62        return full
63
64    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
65        ids = list(ids)
66        if self.live and len(self.live) <= len(ids) - 1 and ids[:len(self.live)] == self.live:
67            reused = len(self.live)
68        else:
69            reused = max([c for c in self.checkpoints if c <= len(ids) - 1 and c <= len(self.live)
70                          and ids[:c] == self.live[:c]] or [0])
71        self.sampling_objects.append(sampling)
72        hold = (sampling or {}).get(HOLD_KEY) if self.honours_hold else None
73        row = {"prompt": len(ids), "reused": reused, "read": len(ids) - reused, "hold": hold}
74        self.passes.append(row)
75        last_start = max(i for i, t in enumerate(ids) if t == self.start)
76        out = self._model(ids)
77        hold_n = hold[0] if hold else -1
78        sent: list[int] = []
79        finish = "length"
80        w = 0
81        try:
82            k = 0
83            while k < len(out):
84                cap = min(max_new, hold_n) if hold_n > 0 else max_new
85                if len(sent) >= cap:
86                    break
87                window = out[k:k + self.windows[w % len(self.windows)]]
88                w += 1
89                if hold_n > 0:   # the engine's bound: rows up to the hold unless </think> comes first
90                    room = cap - len(sent)
91                    if self.think_end in window[:room]:
92                        room = max_new - len(sent)
93                    window = window[:room]
94                else:
95                    window = window[:max_new - len(sent)]
96                k += len(window)
97                pending = list(window)
98                while pending:
99                    if cancel.is_set():
100                        finish = "cancel"
101                        return
102                    t = pending.pop(0)
103                    sent.append(t)
104                    if t == self.think_end:
105                        hold_n = -1
106                    if t in self.end:
107                        finish = "stop"
108                        return
109                    yield t
110            if hold_n > 0 and len(sent) >= hold_n and len(sent) < max_new:
111                finish = "hold"
112        except GeneratorExit:
113            # the STOP is seen at the window's end: the window was committed and sent whole, and one more window may
114            # have run before the STOP arrived
115            sent.extend(pending)
116            if self.overrun and k < len(out):
117                more = out[k:k + self.windows[w % len(self.windows)]]
118                if hold_n > 0:   # with the hold the engine never runs past it (its bound ends the request there)
119                    more = more[:max(0, hold_n - len(sent))]
120                sent.extend(more)
121            finish = "hold" if hold_n > 0 and len(sent) >= hold_n else "cancel"
122            raise
123        finally:
124            self.live = ids + sent[:-1] if sent else ids[:-1]
125            if last_start not in self.checkpoints:
126                self.checkpoints.append(last_start)
127            row.update(sent=len(sent), finish=finish)
128            self.last = {"finish": finish, "reused": reused, "prompt_read": len(ids) - reused, "generated": len(sent)}
129
130
131class HoldCase(unittest.TestCase):
132    def start(self, **kw):
133        self.tok = ThinkTokenizer()
134        self.engine = WindowEngine(self.tok, **kw)
135        svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
136        self.svc = svc
137        self.httpd = serve(svc, port=0)
138        self.addCleanup(self.httpd.server_close)
139        self.addCleanup(self.httpd.shutdown)
140        self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
141
142    def chat(self, **extra):
143        body = {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], "max_tokens": 400, **extra}
144        req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
145                                     headers={"Content-Type": "application/json"})
146        with urllib.request.urlopen(req, timeout=30) as r:
147            msg = json.loads(r.read().decode())["choices"][0]["message"]
148        return msg.get("reasoning_content"), msg.get("content")
149
150    def reply(self, budget, **kw):
151        self.start(**kw)
152        return self.chat(reasoning_budget_tokens=budget), self.engine.passes
153
154    def expected(self, budget, thought=WindowEngine.THOUGHT):
155        return thought[:budget] + REASONING_WRAP_UP.split("</think>")[0], WindowEngine.ANSWER
156
157
158class ThinkingHold(HoldCase):
159    def test_without_the_hold_the_second_pass_reads_the_reasoning_again(self):
160        """Today's behaviour, kept for an engine that does not say "hold": the engine ran past the cut, so the second
161        pass falls back to the checkpoint before the assistant turn and reads the reasoning again."""
162        got, passes = self.reply(20, can_hold=False)
163        self.assertEqual(got, self.expected(20))
164        self.assertEqual(len(passes), 2)
165        self.assertIsNone(passes[0]["hold"])
166        wrap = len(self.tok.encode(REASONING_WRAP_UP, parse_special=True))
167        self.assertGreater(passes[1]["read"], 20 + wrap)
168
169    def test_the_hold_makes_the_second_pass_continue_from_the_live_session(self):
170        got, passes = self.reply(20)
171        self.assertEqual(got, self.expected(20))
172        self.assertEqual(len(passes), 2)
173        think_end = self.tok.encode("</think>", parse_special=True)[0]
174        self.assertEqual(passes[0]["hold"], (20, think_end))
175        self.assertEqual((passes[0]["sent"], passes[0]["finish"]), (20, "hold"))
176        wrap = len(self.tok.encode(REASONING_WRAP_UP, parse_special=True))
177        # all but the last reasoning token is reused; the read is that token and the wrap-up
178        self.assertEqual(passes[1]["reused"], passes[0]["prompt"] + 20 - 1)
179        self.assertEqual(passes[1]["read"], 1 + wrap)
180        self.assertIsNone(passes[1]["hold"])   # the budget is spent: the answer pass has none
181
182    def test_same_answer_with_and_without_the_hold_for_every_budget(self):
183        for budget in (1, 2, 5, 19, 20, 21, 100, 183):
184            with self.subTest(budget=budget):
185                got_hold, _ = self.reply(budget)
186                got_old, _ = self.reply(budget, can_hold=False)
187                self.assertEqual(got_hold, got_old)
188                self.assertEqual(got_hold, self.expected(budget))
189
190    def test_a_cut_that_is_not_clean_at_the_hold_takes_one_more_matching_pass(self):
191        """A character split across tokens at the hold: the server does not wrap there; the next pass (a hold of one
192        more token) continues from the live session, and the wrap-up comes at the same clean point as without the hold."""
193        thought = "Two plus two: " + "é" * 10 + " is four. " * 8   # two bytes per e-acute
194        budget = len("Two plus two: ".encode()) + 3                       # inside the third e-acute
195        got_hold, passes = self.reply(budget, thought=thought)
196        got_old, _ = self.reply(budget, thought=thought, can_hold=False)
197        self.assertEqual(got_hold, got_old)
198        self.assertEqual(len(passes), 3)
199        self.assertEqual(passes[0]["finish"], "hold")
200        self.assertEqual(passes[1]["hold"][0], 1)
201        self.assertEqual(passes[1]["reused"], passes[0]["prompt"] + passes[0]["sent"] - 1)
202        self.assertEqual(passes[1]["read"], 1)
203        self.assertEqual(passes[2]["reused"], passes[1]["prompt"] + passes[1]["sent"] - 1)
204
205    def test_thinking_that_ends_before_the_budget_runs_in_one_pass(self):
206        got, passes = self.reply(500)
207        self.assertEqual(got, (WindowEngine.THOUGHT, WindowEngine.ANSWER))
208        self.assertEqual(len(passes), 1)
209        self.assertEqual(passes[0]["finish"], "stop")
210
211    def test_an_engine_that_says_hold_but_ignores_it_gives_the_same_answer(self):
212        """A new server with an engine that does not act on the key: the server cuts and STOPs as before."""
213        got, passes = self.reply(20, honours_hold=False)
214        self.assertEqual(got, self.expected(20))
215        self.assertEqual(len(passes), 2)
216
217    def test_no_budget_no_hold(self):
218        self.start()
219        self.assertEqual(self.chat(), (WindowEngine.THOUGHT, WindowEngine.ANSWER))
220        self.assertEqual(len(self.engine.passes), 1)
221        self.assertIsNone(self.engine.passes[0]["hold"])
222
223    def test_a_batch_engine_whose_slots_do_not_say_holdb_gets_no_hold(self):
224        self.start()
225        self.engine.batch = 4
226        self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
227        self.assertTrue(all(p["hold"] is None for p in self.engine.passes))
228
229    def test_new_server_old_engine_no_token_no_hold_for_a_batch_engine(self):
230        """Mixed versions, new server + old engine: an engine that says neither hold nor holdb (before P2), and one that says hold but
231        not holdb (P2 without P2b), get no key when they run --batch; the budget then cuts and STOPs as it always did."""
232        for kw in ({"can_hold": False}, {"can_hold": True}, {"can_hold": False, "can_hold_batch": True}):
233            with self.subTest(**kw):
234                self.start(**kw)
235                self.engine.batch = 4
236                self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
237                self.assertTrue(all(p["hold"] is None for p in self.engine.passes))
238
239    def test_a_split_engine_never_gets_the_hold_even_if_its_ready_said_hold(self):
240        """The split engine's parser ends a request that carries a key it does not know ("GEN: unknown key hold"): the server also keeps the hold
241        from an engine it knows is a split engine by name, whatever READY said."""
242        self.start(can_hold=True, can_hold_batch=True)
243        self.engine.split_engine = True
244        self.engine.batch = 4
245        self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
246        self.assertTrue(all(p["hold"] is None for p in self.engine.passes))
247
248    def test_a_batch_engine_that_says_holdb_gets_the_hold(self):
249        """P2b: a --batch engine whose slots end at the hold (READY holdb) gets the key like a solo engine: the second pass reads the last
250        reasoning token and the wrap-up, as in the solo case."""
251        self.start(can_hold_batch=True)
252        self.engine.batch = 4
253        self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
254        passes = self.engine.passes
255        self.assertEqual(len(passes), 2)
256        self.assertEqual(passes[0]["hold"], (20, self.tok.encode("</think>", parse_special=True)[0]))
257        wrap = len(self.tok.encode(REASONING_WRAP_UP, parse_special=True))
258        self.assertEqual((passes[1]["reused"], passes[1]["read"]), (passes[0]["prompt"] + 20 - 1, 1 + wrap))
259
260    def test_holdb_does_not_matter_without_batch(self):
261        self.start(can_hold_batch=True)
262        self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20))
263        self.assertEqual(self.engine.passes[0]["hold"], (20, self.tok.encode("</think>", parse_special=True)[0]))
264
265
266class SamplerObject(HoldCase):
267    """The engine is handed the caller's own sampling object on every pass unless this pass adds (or must strip) the hold, and the caller's dict is
268    never mutated (serve/test_reasoning_loop_recovery.py::test_frozen_cohort_sampler_is_unchanged_during_recovery reads the identity; found by round 18's
269    py-serve run: be101072b made every pass hand the engine a copy)."""
270
271    def run_it(self, sampling, **kw):
272        import copy
273        import threading
274        self.start(**kw)
275        ids = self.tok.encode("<|im_start|>user\n2+2?<|im_end|>\n<|im_start|>assistant\n<think>\n", parse_special=True)
276        before = copy.deepcopy(sampling)
277        events = list(self.svc.run(ids, True, [], 400, sampling, threading.Event()))
278        self.assertEqual(sampling, before, "the caller's dict was mutated")
279        self.assertEqual(events[-1][0], "done")
280        return self.engine.sampling_objects
281
282    def test_no_hold_the_engine_gets_the_callers_own_object_on_every_pass(self):
283        for kw in ({"can_hold": False}, {"can_hold": True, "honours_hold": True, "batch_engine": True}):
284            with self.subTest(**kw):
285                batch = kw.pop("batch_engine", False)
286                sampling = {"temperature": 0.0, "reasoning_budget_tokens": 20}
287                self.start(**kw)
288                self.engine.batch = 4 if batch else 0   # (a --batch engine without holdb: no hold is sent either)
289                import threading
290                ids = self.tok.encode("<|im_start|>user\n2+2?<|im_end|>\n<|im_start|>assistant\n<think>\n", parse_special=True)
291                list(self.svc.run(ids, True, [], 400, sampling, threading.Event()))
292                objs = self.engine.sampling_objects
293                self.assertEqual(len(objs), 2)   # the budget's two passes
294                self.assertTrue(all(o is sampling for o in objs))
295                self.assertNotIn(HOLD_KEY, sampling)
296
297    def test_no_budget_one_pass_the_callers_own_object(self):
298        sampling = {"temperature": 0.0}
299        objs = self.run_it(sampling)
300        self.assertEqual(len(objs), 1)
301        self.assertIs(objs[0], sampling)
302
303    def test_a_hold_is_added_to_a_copy_and_the_callers_dict_keeps_no_key(self):
304        sampling = {"temperature": 0.0, "reasoning_budget_tokens": 20}
305        objs = self.run_it(sampling)
306        self.assertEqual(len(objs), 2)
307        self.assertIsNot(objs[0], sampling)
308        self.assertIn(HOLD_KEY, objs[0])              # the first pass carries the hold
309        self.assertNotIn(HOLD_KEY, objs[1])           # the answer pass: the budget is spent
310        self.assertNotIn(HOLD_KEY, sampling)
311        self.assertEqual({k: v for k, v in objs[0].items() if k != HOLD_KEY}, sampling)
312
313    def test_a_hold_key_in_the_callers_dict_is_stripped_from_a_copy(self):
314        """The hold is the server's own key, never a client's: a caller's dict that carries one is not mutated and the engine does not see it
315        when this pass adds none."""
316        sampling = {"temperature": 0.0, "reasoning_budget_tokens": 20, HOLD_KEY: (3, 5)}
317        objs = self.run_it(sampling, can_hold=False)
318        self.assertEqual(len(objs), 2)
319        for o in objs:
320            self.assertIsNot(o, sampling)
321            self.assertNotIn(HOLD_KEY, o)
322        self.assertEqual(sampling[HOLD_KEY], (3, 5))
323
324
325class HoldKey(unittest.TestCase):
326    def test_the_gen_key(self):
327        self.assertEqual(StrataEngine.sampling_keys({HOLD_KEY: (512, 248069)}), " hold=512:248069")
328
329    def test_only_the_servers_own_value_is_sent(self):
330        for v in ([512, 1], (0, 1), (5, -1), (5,), ("5", 1), (True, 1), None, 7):
331            with self.subTest(v=v):
332                self.assertNotIn("hold=", StrataEngine.sampling_keys({HOLD_KEY: v}))
333
334
335if __name__ == "__main__":
336    unittest.main()