okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1fb3e9a32
main
1#!/usr/bin/env python3 2"""Batching test: the same prompts decoded alone (GEN, the usual path with drafts) and together in the batch 3windows (BGEN), greedy. Every slot's tokens must equal its solo tokens; prints the aggregate decode rate. 4 5python3 tools/batch_test.py --exe engine/strata --config strata-<model>.json --batch 4 --n 4 \ 6--extra "--layer-split 12,24,36 --trim-stage-weights --pcie-frac 0 --adapt-every 1000000" 7""" 8import argparse ,json ,os ,subprocess ,sys ,tempfile ,threading ,time 9from pathlib import Path 10 11sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 12import strata_tokenizer as ST # noqa: E402 13 14QUESTIONS = [ 15"Explique en detail le fonctionnement d'un B-tree." , 16"Write a Python function that merges overlapping intervals, then explain it." , 17"Compare TCP and QUIC: handshake, congestion control, multiplexing." , 18"Raconte l'histoire du calcul de pi, d'Archimede a nos jours." , 19"What are the main causes of the French Revolution?" , 20"Explain how a transformer's attention works, step by step." , 21"Donne une recette de tarte aux pommes, etape par etape." , 22"Describe the life cycle of a star like the Sun." , 23"Erklaere ausfuehrlich, wie ein Dieselmotor funktioniert." , 24"Write a Rust function that parses a CSV line with quoted fields, then explain it." , 25"What were the main consequences of the invention of the printing press?" , 26"Explique le theoreme de Pythagore avec trois demonstrations differentes." , 27"Describe how the immune system responds to a viral infection." , 28"Explain the difference between processes and threads in an operating system." , 29"Beschreibe die Geschichte des Roemischen Reiches in Grundzuegen." , 30"How does public-key cryptography work? Give an example with RSA." , 31] 32# more than 16 slots: the same questions again, asked to answer in German 33QUESTIONS = QUESTIONS + [q + " Answer in German." for q in QUESTIONS ] 34 35 36def tokenizer (path ): 37t = Path (path ) 38vocab = json .loads ((t / "vocab.json" ).read_text (encoding = "utf-8" )) 39tokens = [None ]* len (vocab ) 40for s ,i in vocab .items (): 41tokens [i ]= s 42merges = (t / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ) 43types = json .loads ((t / "token_type.json" ).read_text ()) 44return ST .Tokenizer (tokens ,merges ,types ) 45 46 47class Engine : 48def __init__ (self ,exe ,cfg ,batch ,extra_env ,extra_args ): 49args = list (cfg ["args" ]) 50if len (cfg .get ("gpu" )or [])> 1 : 51args += ["--layer-split" ,str (cfg .get ("layer_split" )or "auto" )] 52if batch : 53args += ["--batch" ,str (batch )] 54args += extra_args 55env = dict (os .environ ,** extra_env ) 56env ["LD_LIBRARY_PATH" ]= ":" .join (cfg .get ("lib_dirs" , [])+ [env .get ("LD_LIBRARY_PATH" ,"" )]) 57if os .name == "nt" : 58env ["PATH" ]= os .pathsep .join (cfg .get ("lib_dirs" , [])+ [env .get ("PATH" ,"" )]) 59self .log_path = os .environ .get ("BATCH_TEST_LOG" )or os .path .join (tempfile .gettempdir (),"batch_test_engine.log" ) 60self .log = open (self .log_path ,"w" ) 61self .p = subprocess .Popen ([exe ,"--serve" ,* args ],cwd = cfg .get ("cwd" ),stdin = subprocess .PIPE , 62stdout = subprocess .PIPE ,stderr = self .log ,text = True ,bufsize = 1 ,env = env ) 63for line in self .p .stdout : 64if line .startswith ("READY" ): 65return 66raise SystemExit (f"the engine ended before READY - see { self . log_path } " ) 67 68def send (self ,line ): 69self .p .stdin .write (line + "\n" ) 70self .p .stdin .flush () 71 72def lines (self ): 73for line in self .p .stdout : 74yield line .rstrip ("\n" ) 75 76 77def main (): 78ap = argparse .ArgumentParser () 79ap .add_argument ("--exe" ,required = True ) 80ap .add_argument ("--config" ,required = True ) 81ap .add_argument ("--batch" ,type = int ,default = 4 ) 82ap .add_argument ("--n" ,type = int ,default = 4 ,help = "prompts (<= --batch)" ) 83ap .add_argument ("--max-new" ,type = int ,default = 64 ) 84ap .add_argument ("--skip-solo" ,action = "store_true" ) 85ap .add_argument ("--keys" ,default = "" ,help = 'sampling keys for every request, e.g. "temperature=0.7 top_k=20"' ) 86ap .add_argument ("--extra" ,default = "" ,help = 'more engine arguments in one string, e.g. "--adapt-every 1000000"' ) 87ap .add_argument ("--dump" ,default = "" ,help = "write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds" ) 88ap .add_argument ("--long-tokens" ,type = int ,default = 0 , 89help = "the LAST prompt is read from about this many tokens of filler text first: its chunks run " 90"beside the earlier slots' windows (the prompt path lends experts then)" ) 91ap .add_argument ("--co" ,action = "store_true" , 92help = "PAR-H: before the first BGEN send BCO lines for the other prompts, so the engine reads every prompt " 93"in one layer-major pass (the engine needs STRATA_PREFILL_LM_FORCE=1 for prompts this short to be " 94"layer-major in the arm without --co)" ) 95ap .add_argument ("--seq" ,action = "store_true" ,help = "PAR-H: admit the prompts one at a time, each run to its end (no batch composition)" ) 96ap .add_argument ("--pad" ,type = int ,default = 0 ,help = "PAR-H: every prompt gets about this many tokens of its own filler text first" ) 97ap .add_argument ("--mt-min" ,default = "1" ,help = "STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)" ) 98a = ap .parse_args () 99cfg = json .loads (Path (a .config ).read_text ()) 100tok = tokenizer (cfg ["tokenizer" ]) 101prompts = [] 102for q in QUESTIONS [:a .n ]: 103text = f"<|im_start|>user\n { q } <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" 104if a .long_tokens and q is QUESTIONS [a .n - 1 ]: 105para = ("The committee reviewed item %d of the long agenda, noting the budget, the schedule and the open " 106"risks, and asked the staff to report back next quarter. " ) 107per = max (1 ,len (tok .encode (para % 100 ))) 108filler = "" .join (para % i for i in range (a .long_tokens // per + 1 )) 109text = f"<|im_start|>user\n { filler } \n\n { q } <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" 110if a .pad : 111para = ("Note %d-%d: the survey team measured the northern ridge, logged the readings of station %d, and sent the " 112"figures to the office, where a clerk filed the sheets under reference %d. " ) 113qi = QUESTIONS .index (q ) 114per = max (1 ,len (tok .encode (para % (qi ,100 ,100 ,100 )))) 115filler = "" .join (para % (qi ,i , (i * 7 + qi )% 97 ,i * 13 + qi )for i in range (a .pad // per + 1 )) 116text = f"<|im_start|>user\n { filler } \n\n { q } <|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" 117prompts .append (tok .encode (text ,parse_special = True )) 118env = {"STRATA_DECODE_TIMING" :"1" ,** ({"STRATA_VERIFY_PROFILE" :"1" }if os .environ .get ("PROF" )else {})} 119if a .mt_min : 120env ["STRATA_IQ_MT_MIN" ]= a .mt_min 121eng = Engine (a .exe ,cfg ,a .batch ,env ,a .extra .split ()) 122out = eng .lines () 123 124solo = [] 125if not a .skip_solo : 126for i ,ids in enumerate (prompts ): 127eng .send (" " .join (x for x in ("GEN" ,str (a .max_new ),a .keys ,"," .join (map (str ,ids )))if x )) 128got ,t0 = [],time .time () 129for line in out : 130if line .startswith ("T " ): 131got .append (int (line .split ()[1 ])) 132elif line .startswith ("DONE" )or line .startswith ("ERR" ): 133f"solo { i } : { len ( got ) } tokens in { time . time () - t0 :.1f } s { line [: 60 ] } " ,flush = True ) 134break 135solo .append (got ) 136 137# batch: admit every prompt, then the slots decode together 138got = {i : []for i in range (len (prompts ))} 139done = {} 140t_admit = time .time () 141first_bt = None 142if a .co : 143for i ,ids in enumerate (prompts ): 144if i >= 1 : 145eng .send (f"BCO { i } " + "," .join (map (str ,ids ))) 146for i ,ids in enumerate (prompts ): 147eng .send (" " .join (x for x in ("BGEN" ,str (i ),str (a .max_new ),a .keys ,"," .join (map (str ,ids )))if x )) 148for line in out : 149if line .startswith ("T " ): 150got [i ].append (int (line .split ()[1 ])) 151elif line .startswith ("BT " ): 152_ ,s ,y = line .split () 153got [int (s )].append (int (y )) 154first_bt = first_bt or time .time () 155elif line .startswith ("BDONE " ): 156done [int (line .split ()[1 ])]= line 157elif line .startswith ("ERR" ): 158"batch:" ,line ) 159return 1 160elif line .startswith ("BADM " ): 161if line .split ()[2 ]== "0" : 162done [i ]= line 163break 164if a .seq and i not in done :# one prompt at a time: this slot runs to its end before the next is admitted 165for line in out : 166if line .startswith ("BT " ): 167_ ,s ,y = line .split () 168got [int (s )].append (int (y )) 169elif line .startswith ("BDONE " ): 170done [int (line .split ()[1 ])]= line 171break 172elif line .startswith ("ERR" ): 173"batch:" ,line ) 174return 1 175t_admitted = time .time () 176for line in (out if len (done )< len (prompts )else []): 177if line .startswith ("BT " ): 178_ ,s ,y = line .split () 179got [int (s )].append (int (y )) 180first_bt = first_bt or time .time () 181elif line .startswith ("BDONE " ): 182done [int (line .split ()[1 ])]= line 183if len (done )== len (prompts ): 184break 185elif line .startswith ("ERR" ): 186"batch:" ,line ) 187return 1 188t_end = time .time () 189total = sum (len (v )for v in got .values ()) 190f"batch: { len ( prompts ) } slots, { total } tokens; admissions { t_admitted - t_admit :.1f } s; " 191f"then { t_end - t_admitted :.1f } s -> aggregate { total / max ( t_end - t_admit , 1e-9 ):.1f } tok/s overall, " 192f" { sum ( len ( v ) for v in got . values ()) / max ( t_end - ( first_bt or t_admit ), 1e-9 ):.1f } tok/s from the first batch token" , 193flush = True ) 194ok = True 195for i in range (len (prompts )): 196b = got [i ] 197if solo : 198same = b == solo [i ] 199ok &= same 200first_diff = next ((k for k in range (min (len (b ),len (solo [i ])))if b [k ]!= solo [i ][k ]),None ) 201f"slot { i } : { len ( b ) } tokens, solo { len ( solo [ i ]) } : { 'IDENTICAL' if same else f'DIFFERS at { first_diff } ' } " ) 202" " ,ascii (tok .decode (b )[:160 ])) 203if a .dump : 204Path (a .dump ).write_text (json .dumps ({"solo" :solo ,"batch" : [got [i ]for i in range (len (prompts ))]}),encoding = "utf-8" ) 205eng .send ("QUIT" ) 206eng .p .wait (timeout = 180 )# the next run needs the GPUs back 207return 0 if ok else 2 208 209 210if __name__ == "__main__" : 211sys .exit (main ())