okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
df44bcb71
main
1#!/usr/bin/env python3 2"""Batch slots, the parts batch_test.py does not reach (#465): a long prompt read WHILE other slots decode (its 3chunks interleaved with their windows), and a conversation's next turn continued from the slot that holds it. 4 51. solo references (GEN): A, then A's next turn (from the live session), B, C (a long prompt) 62. the same in the slots: A in slot 0, B in slot 1 next to it, then C in slot 2 while A and B decode - every slot's 7tokens must equal its solo tokens 83. A's next turn (BGEN into slot 0, which still holds A): read from the slot, its tokens must equal the solo next turn 94. a long prompt D gives way (BYIELD) at its first chunk boundary, a short E is admitted, D goes on from its slot 10while E decodes: both equal their solo tokens. On a pipelined batch (a layer split, more than one group) a read 11never gives way: D is then read whole into slot 2 and E admitted into slot 1 beside it; both must still equal 12solo, only the give-way is not required (--yield auto; --yield expect requires it anyway) 136. A in a slot, stopped after 50 tokens and continued on the solo path (GEN of A + its tokens, from the slot): the 14whole equals solo A (what the server does with a request left alone in a slot) 155. (a measurement) a solo next turn continued from a slot: the drafts accepted 167. F, A's history as a client sends it back without the reply's thinking, from slot 1's turn checkpoint: equal to 17F solo (which continues from the same checkpoint of the live chain) 18(after step 6 the solo path holds A's start, so F's start comes from the live chain or the prompt cache here) 197b. A in slot 1 to its end, --flush unrelated solo GENs, then F2 (A's question, another reply) into slot 2: its 20start can only come from slot 1's turn checkpoint; equal to F2 solo. The engine log line says which source was used. 21 22Exact comparisons need the same settings as batch_test.py (this script sets STRATA_IQ_MT_MIN=1): 23python tools/batch_interleave_test.py --exe build/strata --config strata-<model>.json \\ 24--extra "--pcie-frac 0 --adapt-every 1000000 --no-prefill-borrow" 25Without --no-prefill-borrow the slots decoding during C's read see the expert cache without the slots C's prompt 26borrowed (those experts run on the CPU, which rounds differently): A's and B's text may then drift from solo. 27""" 28import argparse ,json ,os ,re ,sys ,time 29from pathlib import Path 30 31sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 32from batch_test import Engine ,tokenizer # noqa: E402 33 34LONG = ("The history of mathematics is long and full of surprising turns. Early civilizations counted with tally marks, " 35"then with symbols, and later with place-value systems that made arithmetic far easier. " ) 36 37 38def run (eng ,out ,line ,slot = None ): 39"""Send one GEN/BGEN; returns (tokens of the request line, the BADM flag) - BT/BDONE of other slots are kept.""" 40eng .send (line ) 41got = [] 42for l in out : 43if l .startswith ("T " ): 44got .append (int (l .split ()[1 ])) 45elif l .startswith (("BT " ,"BDONE " )): 46eng .pending .append (l ) 47elif l .startswith ("ERR" ): 48raise SystemExit ("engine: " + l ) 49elif slot is None and l .startswith ("DONE" ): 50return got ,None 51elif slot is not None and l .startswith ("BADM " ): 52return got ,l .split ()[2 ]== "1" 53raise SystemExit (f"the engine ended during: { line [: 40 ] } (see { eng . log_path } )" ) 54 55 56def engine_pipelined (eng ,extra ): 57"""Does the engine run the batch in pipelined groups (a layer split, more than one group)? Then a BYIELD is 58dropped: a pipelined read never gives way.""" 59if "--batch-groups" in extra : 60v = extra [extra .index ("--batch-groups" )+ 1 ]if extra .index ("--batch-groups" )+ 1 < len (extra )else "" 61if v .isdigit (): 62return int (v )> 1 63eng .log .flush () 64m = re .search (r"--batch-groups auto: (\d+) groups? of" ,Path (eng .log_path ).read_text (errors = "replace" )) 65return bool (m )and int (m .group (1 ))> 1 66 67 68def main (): 69ap = argparse .ArgumentParser () 70ap .add_argument ("--exe" ,required = True ) 71ap .add_argument ("--config" ,required = True ) 72ap .add_argument ("--max-new" ,type = int ,default = 200 ) 73ap .add_argument ("--long" ,type = int ,default = 5000 ,help = "tokens of the long prompt C (several prompt chunks)" ) 74ap .add_argument ("--extra" ,default = "" ) 75ap .add_argument ("--yield" ,dest = "yield_mode" ,choices = ("auto" ,"expect" ,"skip" ),default = "auto" , 76help = "step 4's give-way: auto = expect a YIELDED unless the batch is pipelined (the engine log " 77"says '--batch-groups auto: N groups' with N > 1, or --extra has --batch-groups N > 1), " 78"where a read never gives way; expect = always required; skip = never required" ) 79ap .add_argument ("--flush" ,type = int ,default = 8 , 80help = "7b: unrelated solo GENs between A in slot 1 and F, so only the slot holds A's start (0: off)" ) 81ap .add_argument ("--dump" ,default = "" ,help = "write every solo and slot token list as JSON: an A/B of two builds" ) 82a = ap .parse_args () 83cfg = json .loads (Path (a .config ).read_text ()) 84tok = tokenizer (cfg ["tokenizer" ]) 85 86def chat (q ): 87return tok .encode (f"<|im_start|>user\n { q } <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" , 88parse_special = True ) 89body = LONG * (a .long // max (1 ,len (tok .encode (LONG )))+ 1 ) 90A = chat ("Write a Python function that merges overlapping intervals, then explain it." ) 91B = chat ("Compare TCP and QUIC: handshake, congestion control, multiplexing." ) 92C = chat (body + "\nSummarize the text above in three sentences." ) 93D = chat (body + "\nWhat are the three most important ideas in the text above?" ) 94E = chat ("Describe the life cycle of a star like the Sun." ) 95f"prompts: A { len ( A ) } , B { len ( B ) } , C { len ( C ) } tokens" ,flush = True ) 96eng = Engine (a .exe ,cfg ,3 , {"STRATA_IQ_MT_MIN" :"1" },a .extra .split ()) 97eng .pending = [] 98out = eng .lines () 99ids = lambda v :"," .join (map (str ,v )) 100M = a .max_new 101 102# 1. solo 103sA ,_ = run (eng ,out ,f"GEN { M } { ids ( A ) } " ) 104A2 = A + sA + chat ("Now do the same in Rust." ) 105sA2 ,_ = run (eng ,out ,f"GEN { M } { ids ( A2 ) } " ) 106# F: A's history as a client sends it back WITHOUT the reply's thinking - it shares A only up to A's last turn 107# boundary (the checkpoint there); solo it continues from that checkpoint of the live chain 108turn_at = max (i for i ,t in enumerate (A )if t == A [0 ])# A[0] is <|im_start|> 109F = A [:turn_at ]+ tok .encode ("<|im_start|>assistant\nA short answer.<|im_end|>\n" ,parse_special = True )+ \ 110chat ("Now in Go." ) 111sF ,_ = run (eng ,out ,f"GEN { M } { ids ( F ) } " ) 112# F2 (step 7b): another reply to A's question - it too shares A only up to A's turn checkpoint 113F2 = A [:turn_at ]+ tok .encode ("<|im_start|>assistant\nAnother short answer.<|im_end|>\n" ,parse_special = True )+ \ 114chat ("Now in C." ) 115sF2 ,_ = run (eng ,out ,f"GEN { M } { ids ( F2 ) } " )if a .flush > 0 else ([],None ) 116sB ,_ = run (eng ,out ,f"GEN { M } { ids ( B ) } " ) 117sC ,_ = run (eng ,out ,f"GEN { M } { ids ( C ) } " ) 118sD ,_ = run (eng ,out ,f"GEN { M } { ids ( D ) } " ) 119sE ,_ = run (eng ,out ,f"GEN { M } { ids ( E ) } " ) 120f"solo: A { len ( sA ) } , A2 { len ( sA2 ) } , B { len ( sB ) } , C { len ( sC ) } , D { len ( sD ) } , E { len ( sE ) } tokens" ,flush = True ) 121 122# 2. the slots: A, B, then the long C while they decode 123got = {0 : [],1 : [],2 : []} 124done = {} 125t0 = time .time () 126for s ,P in ((0 ,A ), (1 ,B ), (2 ,C )): 127first ,cont = run (eng ,out ,f"BGEN { s } { M } { ids ( P ) } " ,slot = s ) 128got [s ]+= first 129if not cont : 130done [s ]= True 131t_admit = time .time ()- t0 132during_c = sum (1 for l in eng .pending if l .startswith ("BT " ))# windows the slots ran while C was admitted 133 134def drain (): 135while eng .pending or len (done )< 3 : 136l = eng .pending .pop (0 )if eng .pending else next (out ) 137if l .startswith ("BT " ): 138_ ,s ,y = l .split () 139got [int (s )].append (int (y )) 140elif l .startswith ("BDONE " ): 141done [int (l .split ()[1 ])]= True 142elif l .startswith ("ERR" ): 143raise SystemExit ("engine: " + l ) 144drain () 145f"slots: admissions { t_admit :.1f } s; { during_c } slot tokens arrived while the admissions read their prompts" , 146flush = True ) 147ok = True 148for s ,ref ,name in ((0 ,sA ,"A" ), (1 ,sB ,"B" ), (2 ,sC ,"C" )): 149same = got [s ]== ref 150ok &= same 151d = next ((k for k in range (min (len (got [s ]),len (ref )))if got [s ][k ]!= ref [k ]),None ) 152f"slot { s } ( { name } ): { len ( got [ s ]) } tokens, solo { len ( ref ) } : " 153f" { 'IDENTICAL' if same else f'DIFFERS at { d } ' } " ,flush = True ) 154 155# 3. A's next turn from slot 0 (the engine's log says "slot 0 gave back ...") 156first ,cont = run (eng ,out ,f"BGEN 0 { M } { ids ( A2 ) } " ,slot = 0 ) 157got2 ,done = first , {} 158if cont : 159while True : 160l = eng .pending .pop (0 )if eng .pending else next (out ) 161if l .startswith ("BT 0 " ): 162got2 .append (int (l .split ()[2 ])) 163elif l .startswith ("BDONE 0 " ): 164break 165same = got2 == sA2 166ok &= same 167d = next ((k for k in range (min (len (got2 ),len (sA2 )))if got2 [k ]!= sA2 [k ]),None ) 168f"A's next turn from its slot: { len ( got2 ) } tokens, solo { len ( sA2 ) } : " 169f" { 'IDENTICAL' if same else f'DIFFERS at { d } ' } " ,flush = True ) 170# 4. a long prompt D gives way (BYIELD) to a short E at its first chunk boundary, then goes on from its slot. 171# On a pipelined batch (a layer split with more than one group) a read never gives way (generate.cpp: the BYIELD 172# is dropped): D is then admitted whole into slot 2 and E goes into the free slot 1 while D decodes - both must 173# still equal solo, only the give-way itself is not checked (--yield) 174pipelined = engine_pipelined (eng ,a .extra .split ()) 175expect_yield = a .yield_mode == "expect" or (a .yield_mode == "auto" and not pipelined ) 176eng .send (f"BGEN 2 { M } { ids ( D ) } " ) 177eng .send ("BYIELD 2" ) 178yielded ,firstD ,contD = None , [],None 179for l in out : 180if l .startswith ("T " ): 181firstD .append (int (l .split ()[1 ])) 182elif l .startswith ("YIELDED " ): 183yielded = l 184elif l .startswith (("BT " ,"BDONE " )): 185eng .pending .append (l ) 186elif l .startswith ("ERR" ): 187raise SystemExit ("engine: " + l ) 188elif l .startswith ("BADM 2 " ): 189contD = l .split ()[2 ]== "1" 190break 191if yielded is not None : 192f"D gave way: { yielded } " ,flush = True ) 193elif expect_yield : 194f"D gave way: None (expected a YIELDED: batch { 'pipelined' if pipelined else 'not pipelined' } )" , 195flush = True ) 196ok = False 197else : 198f"D gave way: None - the batch is pipelined ( { pipelined } ), where a read never gives way; D stays in " 199f"slot 2 ( { len ( firstD ) } first tokens, { 'continues' if contD else 'done' } ), E goes into slot 1 beside it" , 200flush = True ) 201got4 = {1 : [],2 : []} 202first ,cont1 = run (eng ,out ,f"BGEN 1 { M } { ids ( E ) } " ,slot = 1 ) 203got4 [1 ]+= first 204if yielded is not None : 205first ,cont2 = run (eng ,out ,f"BGEN 2 { M } { ids ( D ) } " ,slot = 2 ) 206got4 [2 ]+= first 207else :# D never left slot 2: its tokens so far are the read's first ones plus the BT 2 lines kept in pending 208got4 [2 ]+= firstD 209cont2 = contD 210done4 = {s for s ,c in ((1 ,cont1 ), (2 ,cont2 ))if not c } 211while len (done4 )< 2 : 212l = eng .pending .pop (0 )if eng .pending else next (out ) 213if l .startswith ("BT " ): 214_ ,s ,y = l .split () 215if int (s )in got4 and int (s )not in done4 : 216got4 [int (s )].append (int (y )) 217elif l .startswith ("BDONE " ): 218done4 .add (int (l .split ()[1 ])) 219elif l .startswith ("ERR" ): 220raise SystemExit ("engine: " + l ) 221for s ,ref ,name in ((1 ,sE ,"E (short, admitted while D waited)" ), (2 ,sD ,"D (gave way, then went on)" if yielded else "D (read whole, E admitted beside it)" )): 222same = got4 [s ]== ref 223ok &= same 224d = next ((k for k in range (min (len (got4 [s ]),len (ref )))if got4 [s ][k ]!= ref [k ]),None ) 225f"slot { s } { name } : { len ( got4 [ s ]) } tokens, solo { len ( ref ) } : " 226f" { 'IDENTICAL' if same else f'DIFFERS at { d } ' } " ,flush = True ) 227# 6. back to the solo path (what the server does with a request left alone in a slot): A in slot 1, BSTOP after 228# 50 tokens, then GEN of A + what it produced - the engine continues from the slot with MTP drafts again 229first ,cont = run (eng ,out ,f"BGEN 1 { M } { ids ( A ) } " ,slot = 1 ) 230got6 ,sent = list (first ),False 231while cont : 232l = eng .pending .pop (0 )if eng .pending else next (out ) 233if l .startswith ("BT 1 " ): 234got6 .append (int (l .split ()[2 ])) 235if len (got6 )>= 50 and not sent : 236eng .send ("BSTOP 1" ) 237sent = True 238elif l .startswith ("BDONE 1 " ): 239break 240tail6 ,_ = run (eng ,out ,f"GEN { M - len ( got6 ) } { ids ( A + got6 ) } " )if len (got6 )< M else ([],None ) 241same = got6 + tail6 == sA 242ok &= same 243both = got6 + tail6 244d = next ((k for k in range (min (len (both ),len (sA )))if both [k ]!= sA [k ]),None ) 245f"A in a slot, then solo again after { len ( got6 ) } tokens: { len ( both ) } tokens, solo { len ( sA ) } : " 246f" { 'IDENTICAL' if same else f'DIFFERS at { d } ' } " ,flush = True ) 247 248# 5. (a measurement, not a check) a SOLO next turn continued from slot 0: its tokens are exact either way, but the 249# draft layer's own K/V was built for another conversation, so fewer drafts may be accepted than in a solo next 250# turn whose drafter read the conversation (A2 in step 1) 251A3 = A2 + got2 + chat ("Now in Go." ) 252eng .send (f"GEN { M } { ids ( A3 ) } " ) 253for l in out : 254if l .startswith (("BT " ,"BDONE " )): 255eng .pending .append (l ) 256elif l .startswith ("DONE" ): 257f = l .split () 258f"solo next turn from a slot: drafts accepted { f [ 6 ] } of { f [ 7 ] } ( { f [ 1 ] } tokens in { f [ 4 ] } ms)" , 259flush = True ) 260break 261# 7. F, A's history without the reply's thinking, into slot 2 (its start comes from the live chain or the prompt 262# cache: step 6's solo continuation took slot 1's contents back; 7b below makes a slot the only source) 263first ,cont = run (eng ,out ,f"BGEN 2 { M } { ids ( F ) } " ,slot = 2 ) 264got7 = list (first ) 265while cont : 266l = eng .pending .pop (0 )if eng .pending else next (out ) 267if l .startswith ("BT 2 " ): 268got7 .append (int (l .split ()[2 ])) 269elif l .startswith ("BDONE 2 " ): 270break 271same = got7 == sF 272ok &= same 273d = next ((k for k in range (min (len (got7 ),len (sF )))if got7 [k ]!= sF [k ]),None ) 274f"F (A's history without the reply's thinking) in slot 2: { len ( got7 ) } tokens, solo " 275f" { len ( sF ) } : { 'IDENTICAL' if same else f'DIFFERS at { d } ' } " ,flush = True ) 276# 7b. step 7 where only a SLOT can give the start: after step 6 the solo path took slot 1's contents back, so the 277# live chain (or the prompt cache) held A's start in step 7 and F came from there. Here A runs to its end in 278# slot 1, then --flush unrelated solo GENs push A out of the live session and the prompt cache's checkpoints; F2 279# (A's question, another reply) into slot 2 can then only start from slot 1's turn checkpoint (slot 2 holds F, 280# which shares no more with F2 than A does; the engine log line is printed) - its tokens must equal F2 solo 281got7b = [] 282if a .flush > 0 : 283first ,cont = run (eng ,out ,f"BGEN 1 { M } { ids ( A ) } " ,slot = 1 ) 284gotA = list (first ) 285while cont : 286l = eng .pending .pop (0 )if eng .pending else next (out ) 287if l .startswith ("BT 1 " ): 288gotA .append (int (l .split ()[2 ])) 289elif l .startswith ("BDONE 1 " ): 290break 291same = gotA == sA 292ok &= same 293f"7b: A in slot 1 to its end: { len ( gotA ) } tokens, solo { len ( sA ) } : { 'IDENTICAL' if same else 'DIFFERS' } " , 294flush = True ) 295for k in range (a .flush ): 296run (eng ,out ,f"GEN 8 { ids ( chat ( f'Unrelated question { k } : name one prime number above { 100 * k } .' )) } " ) 297eng .log .flush () 298mark = len (Path (eng .log_path ).read_text (errors = "replace" )) 299first ,cont = run (eng ,out ,f"BGEN 2 { M } { ids ( F2 ) } " ,slot = 2 ) 300got7b = list (first ) 301while cont : 302l = eng .pending .pop (0 )if eng .pending else next (out ) 303if l .startswith ("BT 2 " ): 304got7b .append (int (l .split ()[2 ])) 305elif l .startswith ("BDONE 2 " ): 306break 307tail = Path (eng .log_path ).read_text (errors = "replace" )[mark :] 308src = [l for l in tail .splitlines ()if "gave back" in l or "strata serve: prompt" in l ][:2 ] 309same = got7b == sF2 310ok &= same 311d = next ((k for k in range (min (len (got7b ),len (sF2 )))if got7b [k ]!= sF2 [k ]),None ) 312f"7b: F2 after { a . flush } unrelated GENs, from slot 1: { len ( got7b ) } tokens, solo { len ( sF2 ) } : " 313f" { 'IDENTICAL' if same else f'DIFFERS at { d } ' } " ,flush = True ) 314for l in src : 315" 7b log:" ,l .split ("strata " )[- 1 ][:160 ],flush = True ) 316if a .dump : 317Path (a .dump ).write_text (json .dumps ({ 318"solo" : {"A" :sA ,"A2" :sA2 ,"B" :sB ,"C" :sC ,"D" :sD ,"E" :sE ,"F" :sF ,"F2" :sF2 }, 319"slots" : {"A" :got [0 ],"B" :got [1 ],"C" :got [2 ],"A2" :got2 ,"E" :got4 [1 ],"D" :got4 [2 ], 320"A_slot_then_solo" :got6 + tail6 ,"F" :got7 ,"F2" :got7b }, 321"yielded" :yielded is not None ,"pipelined" :pipelined }),encoding = "utf-8" ) 322eng .send ("QUIT" ) 323eng .p .wait (timeout = 180 ) 324log = Path (eng .log_path ).read_text (errors = "replace" ) 325for l in log .splitlines (): 326if "drafts accepted" in l : 327" log:" ,l .split ("strata serve: " )[- 1 ][:160 ],flush = True ) 328for key in ("gave back" ,"its turn checkpoint" ,"takes" ,"the prompt was read in" ,"gives way" ): 329f"engine log ' { key } ': { log . count ( key ) } lines" ,flush = True ) 330return 0 if ok else 2 331 332 333if __name__ == "__main__" : 334sys .exit (main ())