okami.mom/strata

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

Niko1221Merge f-agent-turn b92075d92 into f-p4-int291b91025

main
9.9 KiB184 linesraw
1"""The thinking budget's hold on a --batch engine (lane AGENT-TURN, P2b): GEN / BGEN hold=N:ID reaches the batch slots too.
2
3The fake engine of test_parallel.py (a script speaking GEN / BGEN / T / DONE / BADM / BT / BDONE / BSTOP) is given the engine's side of the
4hold, as generate.cpp has it: READY says "hold holdb"; a solo GEN ends after N emitted tokens unless token ID came first (DONE hold); a BGEN's
5admission token counts toward N and its slot ends with BDONE hold at exactly N; once ID is emitted the hold is over.  What is tested is the
6server: the key's count falls by what an earlier leg of the same pass already sent (the solo leg promoted to a slot), the finish "hold" ends
7the pass, no key goes to an engine whose READY lacks holdb, and the tokens of a held pass are exactly the first N of the unheld reply."""
8from __future__ import annotations
9
10import sys
11import threading
12import time
13import unittest
14from pathlib import Path
15
16sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
17from serve.server import HOLD_KEY  # noqa: E402
18from serve.test_parallel import FAKE_BATCH, FakeEngineCase  # noqa: E402
19
20
21def with_hold(script: str, says_holdb: bool = True) -> str:
22    """FAKE_BATCH with the engine's hold (every replaced text must be there once: a change of the fake fails loudly here)."""
23    def swap(text, old, new):
24        assert text.count(old) == 1, old
25        return text.replace(old, new)
26    s = swap(script, 'print("READY 4096 stop", flush=True)', 'print("READY 4096 stop hold%s", flush=True)' % (" holdb" if says_holdb else ""))
27    s = swap(s, '        ids = f[-1].split(",")\n',
28             '        ids = f[-1].split(",")\n'
29             '        hold = next(((int(x[5:].split(":")[0]), int(x[5:].split(":")[1])) for x in f if x.startswith("hold=")), None)\n')
30    s = swap(s, 'log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)}\\n"); log.flush()',
31             'log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)} hold={hold[0] if hold else None}:{hold[1] if hold else None}\\n"); log.flush()')
32    s = swap(s, "        out = 0\n        for t in toks[:n]:\n            if stop.is_set():\n                break\n            print(f\"T {t}\", flush=True)\n            out += 1\n            time.sleep(STEP)\n"
33                "        fin = \"stop\" if out and toks[out - 1] == 257 else (\"cancel\" if stop.is_set() else \"length\")\n",
34             "        out = 0\n        hold_on = hold is not None\n        for t in toks[:n]:\n            if stop.is_set():\n                break\n"
35             "            if hold_on and out >= hold[0]:\n                break\n"
36             "            print(f\"T {t}\", flush=True)\n            out += 1\n            if hold_on and t == hold[1]:\n                hold_on = False\n            time.sleep(STEP)\n"
37             "        fin = \"stop\" if out and toks[out - 1] == 257 else (\"cancel\" if stop.is_set() else "
38             "\"hold\" if hold_on and out >= hold[0] and (out < n or slot is not None) else \"length\")\n")
39    s = swap(s, "                active[slot] = [toks[1:], max_new, 1]\n", "                active[slot] = [toks[1:], max_new, 1, hold, hold_on]\n")
40    s = swap(s, "        left, max_new, produced = active[b]\n", "        left, max_new, produced, hold, hold_on = active[b]\n")
41    s = swap(s, "        print(f\"BT {b} {t}\", flush=True)\n        if t == 257 or produced >= max_new:\n"
42                "            fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length'\n",
43             "        print(f\"BT {b} {t}\", flush=True)\n        if hold_on and t == hold[1]:\n            hold_on = False\n"
44             "        if t == 257 or produced >= max_new or (hold_on and produced >= hold[0]):\n"
45             "            fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length' if produced >= max_new else 'hold'\n")
46    s = swap(s, "            active[b] = [left, max_new, produced]\n", "            active[b] = [left, max_new, produced, hold, hold_on]\n")
47    return s
48
49
50REPLY = list(b"ok, " + b"la " * 15 + b"done.") + [257]     # what the fake engine says to a prompt with LONGREPLY in it (then <|im_end|>)
51NO_ID = 199                                                 # a token the reply never has: the hold stays on
52COMMA = ord(",")                                            # the reply's third token: the hold ends there
53
54
55class HoldBatchCase(FakeEngineCase):
56    def start_hold(self, slots=2, says_holdb=True, **kw):
57        import serve.test_parallel as tp
58        old = tp.FAKE_BATCH
59        tp.FAKE_BATCH = with_hold(FAKE_BATCH, says_holdb)
60        try:
61            self.start(slots, **kw)
62        finally:
63            tp.FAKE_BATCH = old
64
65    def run_pass(self, text, max_new, hold):
66        """One engine pass through generate (the real StrataEngine.generate -> generate_batched): -> (tokens, finish)"""
67        ids = list(text.encode())
68        cancel = threading.Event()
69        sampling = {HOLD_KEY: hold} if hold else {}
70        out = [t for t in self.engine.generate(ids, max_new, sampling, cancel) if t is not None]
71        return out, (self.engine.last or {}).get("finish")
72
73    def requests(self):
74        return [ln.split() for ln in self.log.read_text().splitlines()] if self.log.exists() else []
75
76
77class SoloAndSlots(HoldBatchCase):
78    def test_a_batch_engine_says_holdb_in_ready(self):
79        self.start_hold()
80        self.assertTrue(self.engine.can_hold)
81        self.assertTrue(self.engine.can_hold_batch)
82
83    def test_an_engine_without_holdb_says_so(self):
84        self.start_hold(says_holdb=False)
85        self.assertTrue(self.engine.can_hold)
86        self.assertFalse(self.engine.can_hold_batch)
87
88    def test_old_server_new_engine_the_tokens_are_ignored_and_no_key_means_no_hold(self):
89        """Mixed versions, old server + new engine: the server before P2 reads READY with `"stop" in f[2:]` and sends no hold key.  The new
90        engine's extra READY tokens change nothing it reads (can_stop, the context), and a request with no key runs as it always did,
91        through the solo path and through a slot."""
92        self.start_hold()
93        self.assertTrue(self.engine.can_stop)
94        self.assertEqual(self.engine.max_context, 4096)
95        results = {}
96
97        def first():
98            results["first"] = self.run_pass("LONGREPLY first", 64, None)
99
100        t = threading.Thread(target=first)
101        t.start()
102        time.sleep(0.15)
103        results["second"] = self.run_pass("LONGREPLY second", 64, None)     # admitted into a slot
104        t.join(30)
105        self.assertEqual(results["first"][0], REPLY)
106        self.assertEqual(results["second"][0], REPLY)
107        self.assertEqual({results["first"][1], results["second"][1]}, {"stop"})
108        self.assertTrue(any(r[0] == "BGEN" for r in self.requests()))
109        self.assertTrue(all(r[-1] == "hold=None:None" for r in self.requests()))
110
111    def test_alone_the_solo_path_ends_at_the_hold(self):
112        self.start_hold()
113        got, finish = self.run_pass("LONGREPLY please", 64, (12, NO_ID))
114        self.assertEqual(got, REPLY[:12])
115        self.assertEqual(finish, "hold")
116        gen = [r for r in self.requests() if r[0] == "GEN"]
117        self.assertEqual(len(gen), 1)
118        self.assertEqual(gen[0][-1], "hold=12:%d" % NO_ID)
119
120    def test_the_hold_ends_when_its_token_comes_first(self):
121        self.start_hold()
122        got, finish = self.run_pass("LONGREPLY please", 64, (12, COMMA))
123        self.assertEqual(got, REPLY)           # </think> came at the third token: the pass runs on to its own end
124        self.assertEqual(finish, "stop")
125
126    def test_no_hold_no_key(self):
127        self.start_hold()
128        got, finish = self.run_pass("LONGREPLY please", 64, None)
129        self.assertEqual(got, REPLY)
130        self.assertTrue(all(r[-1] == "hold=None:None" for r in self.requests()))
131
132    def test_a_request_that_goes_to_a_slot_ends_at_the_hold(self):
133        """Another request holds the solo path: this one is admitted into a slot (BGEN) and its slot ends with BDONE hold at exactly N."""
134        self.start_hold()
135        results = {}
136
137        def first():
138            results["first"] = self.run_pass("LONGREPLY first", 64, None)
139
140        t = threading.Thread(target=first)
141        t.start()
142        time.sleep(0.15)
143        got, finish = self.run_pass("LONGREPLY second", 64, (20, NO_ID))
144        t.join(30)
145        self.assertEqual(got, REPLY[:20])
146        self.assertEqual(finish, "hold")
147        self.assertEqual(results["first"][0], REPLY)
148        bgen = [r for r in self.requests() if r[0] == "BGEN" and r[-1].startswith("hold=20")]
149        self.assertEqual(len(bgen), 1, self.requests())
150
151    def test_a_solo_leg_promoted_to_a_slot_holds_what_is_left(self):
152        """The pass starts alone (GEN, hold=N), another request arrives, the pass is stopped and goes on in a slot: its key counts the tokens
153        the solo leg already sent, and the pass still ends at exactly N tokens in all."""
154        self.start_hold()
155        results = {}
156
157        def first():
158            results["first"] = self.run_pass("LONGREPLY first", 64, (40, NO_ID))
159
160        t = threading.Thread(target=first)
161        t.start()
162        time.sleep(0.15)
163        other = self.run_pass("LONGREPLY other", 64, None)
164        t.join(30)
165        got, finish = results["first"]
166        self.assertEqual(got, REPLY[:40])
167        self.assertEqual(finish, "hold")
168        self.assertEqual(other[0], REPLY)
169        keys = [r[-1] for r in self.requests() if r[0] in ("GEN", "BGEN") and r[-1] != "hold=None:None"]
170        self.assertEqual(keys[0], "hold=40:%d" % NO_ID)
171        legs = [int(k.split("=")[1].split(":")[0]) for k in keys]
172        self.assertTrue(all(n <= 40 for n in legs) and legs == sorted(legs, reverse=True), keys)
173
174    def test_the_tokens_of_a_held_pass_are_the_first_n_of_the_unheld_reply(self):
175        self.start_hold()
176        for n in (1, 2, 3, 10, 30, 53):
177            with self.subTest(n=n):
178                got, finish = self.run_pass("LONGREPLY please", 64, (n, NO_ID))
179                self.assertEqual(got, REPLY[:n])
180                self.assertEqual(finish, "hold")
181
182
183if __name__ == "__main__":
184    unittest.main()