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