okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
291b91025
main
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).""" 23def swap (text ,old ,new ): 24assert text .count (old )== 1 ,old 25return text .replace (old ,new ) 26s = swap (script ,'print("READY 4096 stop", flush=True)' ,'print("READY 4096 stop hold%s", flush=True)' % (" holdb" if says_holdb else "" )) 27s = 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' ) 30s = 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()' ) 32s = 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" ) 39s = swap (s ," active[slot] = [toks[1:], max_new, 1]\n" ," active[slot] = [toks[1:], max_new, 1, hold, hold_on]\n" ) 40s = swap (s ," left, max_new, produced = active[b]\n" ," left, max_new, produced, hold, hold_on = active[b]\n" ) 41s = 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" ) 46s = swap (s ," active[b] = [left, max_new, produced]\n" ," active[b] = [left, max_new, produced, hold, hold_on]\n" ) 47return 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 ): 56def start_hold (self ,slots = 2 ,says_holdb = True ,** kw ): 57import serve .test_parallel as tp 58old = tp .FAKE_BATCH 59tp .FAKE_BATCH = with_hold (FAKE_BATCH ,says_holdb ) 60try : 61self .start (slots ,** kw ) 62finally : 63tp .FAKE_BATCH = old 64 65def run_pass (self ,text ,max_new ,hold ): 66"""One engine pass through generate (the real StrataEngine.generate -> generate_batched): -> (tokens, finish)""" 67ids = list (text .encode ()) 68cancel = threading .Event () 69sampling = {HOLD_KEY :hold }if hold else {} 70out = [t for t in self .engine .generate (ids ,max_new ,sampling ,cancel )if t is not None ] 71return out , (self .engine .last or {}).get ("finish" ) 72 73def requests (self ): 74return [ln .split ()for ln in self .log .read_text ().splitlines ()]if self .log .exists ()else [] 75 76 77class SoloAndSlots (HoldBatchCase ): 78def test_a_batch_engine_says_holdb_in_ready (self ): 79self .start_hold () 80self .assertTrue (self .engine .can_hold ) 81self .assertTrue (self .engine .can_hold_batch ) 82 83def test_an_engine_without_holdb_says_so (self ): 84self .start_hold (says_holdb = False ) 85self .assertTrue (self .engine .can_hold ) 86self .assertFalse (self .engine .can_hold_batch ) 87 88def 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 90engine's extra READY tokens change nothing it reads (can_stop, the context), and a request with no key runs as it always did, 91through the solo path and through a slot.""" 92self .start_hold () 93self .assertTrue (self .engine .can_stop ) 94self .assertEqual (self .engine .max_context ,4096 ) 95results = {} 96 97def first (): 98results ["first" ]= self .run_pass ("LONGREPLY first" ,64 ,None ) 99 100t = threading .Thread (target = first ) 101t .start () 102time .sleep (0.15 ) 103results ["second" ]= self .run_pass ("LONGREPLY second" ,64 ,None )# admitted into a slot 104t .join (30 ) 105self .assertEqual (results ["first" ][0 ],REPLY ) 106self .assertEqual (results ["second" ][0 ],REPLY ) 107self .assertEqual ({results ["first" ][1 ],results ["second" ][1 ]}, {"stop" }) 108self .assertTrue (any (r [0 ]== "BGEN" for r in self .requests ())) 109self .assertTrue (all (r [- 1 ]== "hold=None:None" for r in self .requests ())) 110 111def test_alone_the_solo_path_ends_at_the_hold (self ): 112self .start_hold () 113got ,finish = self .run_pass ("LONGREPLY please" ,64 , (12 ,NO_ID )) 114self .assertEqual (got ,REPLY [:12 ]) 115self .assertEqual (finish ,"hold" ) 116gen = [r for r in self .requests ()if r [0 ]== "GEN" ] 117self .assertEqual (len (gen ),1 ) 118self .assertEqual (gen [0 ][- 1 ],"hold=12:%d" % NO_ID ) 119 120def test_the_hold_ends_when_its_token_comes_first (self ): 121self .start_hold () 122got ,finish = self .run_pass ("LONGREPLY please" ,64 , (12 ,COMMA )) 123self .assertEqual (got ,REPLY )# </think> came at the third token: the pass runs on to its own end 124self .assertEqual (finish ,"stop" ) 125 126def test_no_hold_no_key (self ): 127self .start_hold () 128got ,finish = self .run_pass ("LONGREPLY please" ,64 ,None ) 129self .assertEqual (got ,REPLY ) 130self .assertTrue (all (r [- 1 ]== "hold=None:None" for r in self .requests ())) 131 132def 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.""" 134self .start_hold () 135results = {} 136 137def first (): 138results ["first" ]= self .run_pass ("LONGREPLY first" ,64 ,None ) 139 140t = threading .Thread (target = first ) 141t .start () 142time .sleep (0.15 ) 143got ,finish = self .run_pass ("LONGREPLY second" ,64 , (20 ,NO_ID )) 144t .join (30 ) 145self .assertEqual (got ,REPLY [:20 ]) 146self .assertEqual (finish ,"hold" ) 147self .assertEqual (results ["first" ][0 ],REPLY ) 148bgen = [r for r in self .requests ()if r [0 ]== "BGEN" and r [- 1 ].startswith ("hold=20" )] 149self .assertEqual (len (bgen ),1 ,self .requests ()) 150 151def 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 153the solo leg already sent, and the pass still ends at exactly N tokens in all.""" 154self .start_hold () 155results = {} 156 157def first (): 158results ["first" ]= self .run_pass ("LONGREPLY first" ,64 , (40 ,NO_ID )) 159 160t = threading .Thread (target = first ) 161t .start () 162time .sleep (0.15 ) 163other = self .run_pass ("LONGREPLY other" ,64 ,None ) 164t .join (30 ) 165got ,finish = results ["first" ] 166self .assertEqual (got ,REPLY [:40 ]) 167self .assertEqual (finish ,"hold" ) 168self .assertEqual (other [0 ],REPLY ) 169keys = [r [- 1 ]for r in self .requests ()if r [0 ]in ("GEN" ,"BGEN" )and r [- 1 ]!= "hold=None:None" ] 170self .assertEqual (keys [0 ],"hold=40:%d" % NO_ID ) 171legs = [int (k .split ("=" )[1 ].split (":" )[0 ])for k in keys ] 172self .assertTrue (all (n <= 40 for n in legs )and legs == sorted (legs ,reverse = True ),keys ) 173 174def test_the_tokens_of_a_held_pass_are_the_first_n_of_the_unheld_reply (self ): 175self .start_hold () 176for n in (1 ,2 ,3 ,10 ,30 ,53 ): 177with self .subTest (n = n ): 178got ,finish = self .run_pass ("LONGREPLY please" ,64 , (n ,NO_ID )) 179self .assertEqual (got ,REPLY [:n ]) 180self .assertEqual (finish ,"hold" ) 181 182 183if __name__ == "__main__" : 184unittest .main ()