okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
1"""2507-0: how idle are the GPUs, and does an existing switch close the gap? Interleaved A/B of whole engine runs 2(fresh engine per arm run, rotating arm order), with a per-card utilisation sampler (nvidia-smi, 5 samples/s) over every 3decode, prompt and batch window. Derived from the 0.2.1 split A/B harness; measurement only, no engine change. 4 5python split_ab.py single CONFIG OUTDIR --arm name=EXE!ARGS!K=V,K=V ... [--pairs 6] [--new 300] [--warm 2] [--pps 4096,20480] [--extra "..."] 6per run: WARM x 64-token requests, then story/code/facts greedy requests of --new tokens, then one prompt read per --pps length 7python split_ab.py batch CONFIG OUTDIR --batch N --arm ... [--pairs 5] [--new 200] 8per run: engine with --batch N, one warm batch (48 tokens), then --passes batch passes of N prompts (BGEN), aggregate tok/s 9python split_ab.py --summary OUTDIR [--base name] 10 11Results: OUTDIR/results.jsonl, one line per arm run. 12""" 13import hashlib 14import json 15import os 16import re 17import statistics 18import subprocess 19import sys 20import threading 21import time 22 23 24class Sampler : 25"""nvidia-smi utilisation/power per card, time stamped on arrival; window(t0, t1) -> per-card means.""" 26 27def __init__ (self ): 28self .rows = [] 29self .proc = subprocess .Popen (["nvidia-smi" ,"--query-gpu=index,utilization.gpu,power.draw" ,"--format=csv,noheader,nounits" , 30"-lms" ,"200" ],stdout = subprocess .PIPE ,text = True ) 31threading .Thread (target = self ._read ,daemon = True ).start () 32 33def _read (self ): 34for line in self .proc .stdout : 35try : 36i ,u ,w = [x .strip ()for x in line .split ("," )] 37self .rows .append ((time .time (),int (i ),float (u ),float (w ))) 38except ValueError : 39pass 40 41def window (self ,t0 ,t1 ): 42out = {} 43for t ,i ,u ,w in list (self .rows ): 44if t0 <= t <= t1 : 45d = out .setdefault (i , [[], []]) 46d [0 ].append (u ) 47d [1 ].append (w ) 48return {str (i ): {"util" :round (sum (d [0 ])/ len (d [0 ]),1 ),"power_w" :round (sum (d [1 ])/ len (d [1 ]),1 ),"n" :len (d [0 ])} 49for i ,d in sorted (out .items ())} 50 51def stop (self ): 52self .proc .kill () 53 54 55SMP = None 56from pathlib import Path 57 58 59def args_of (name ): 60return [sys .argv [i + 1 ]for i ,a in enumerate (sys .argv )if a == name ] 61 62 63def arg (name ,default ): 64return sys .argv [sys .argv .index (name )+ 1 ]if name in sys .argv else default 65 66 67def med (xs ): 68xs = [x for x in xs if x is not None ] 69return statistics .median (xs )if xs else float ("nan" ) 70 71 72def summary (out ,base = None ): 73R = [json .loads (l )for l in open (out / "results.jsonl" )] 74names = [] 75for r in R : 76if r ["arm" ]not in names : 77names .append (r ["arm" ]) 78base = base or names [0 ] 79keys = [] 80for r in R : 81for x in r ["rows" ]: 82k = (x ["kind" ],"tok_s" if x .get ("tok_s" )is not None else "pp_tok_s" ) 83if k not in keys and x ["kind" ]!= "batch" : 84keys .append (k ) 85if any (x ["kind" ]== "batch" for r in R for x in r ["rows" ]): 86keys += [("batch" ,"tok_s" ), ("batch" ,"steady" ), ("batch" ,"ttft" )] 87 88def per_round (arm ,kind ,key ): 89d = {} 90for r in R : 91if r ["arm" ]== arm : 92v = [x .get (key )for x in r ["rows" ]if x ["kind" ]== kind ] 93d [r ["round" ]]= med (v ) 94return d 95 96"arm | metric | median | vs base | pairs faster (higher) | rounds" ) 97for kind ,key in keys : 98for nm in names : 99a ,b = per_round (base ,kind ,key ),per_round (nm ,kind ,key ) 100rounds = [i for i in sorted (set (a )& set (b ))if a [i ]== a [i ]and b [i ]== b [i ]] 101if not rounds : 102continue 103ma ,mb = med ([a [i ]for i in rounds ]),med ([b [i ]for i in rounds ]) 104fb = sum (1 for i in rounds if (b [i ]< a [i ]if key == "ttft" else b [i ]> a [i ])) 105f" { nm } | { kind } : { key } | { mb :.2f } | { mb / ma :.3f } | { fb } / { len ( rounds ) } | { len ( rounds ) } " ) 106"\narm | window | mean util per card % (median over runs) | mean power W per card | idle% (mean over cards)" ) 107kinds = [] 108for r in R : 109for x in r ["rows" ]: 110if x ["kind" ]not in kinds : 111kinds .append (x ["kind" ]) 112for nm in names : 113for kind in kinds : 114us ,ws = {}, {} 115for r in R : 116if r ["arm" ]!= nm : 117continue 118for x in r ["rows" ]: 119if x ["kind" ]== kind : 120for gi ,g in (x .get ("gpu" )or {}).items (): 121us .setdefault (gi , []).append (g ["util" ]) 122ws .setdefault (gi , []).append (g ["power_w" ]) 123if us : 124mu = {gi :med (v )for gi ,v in us .items ()} 125f" { nm } | { kind } | { ', ' . join ( f'gpu { gi } { v :.0f } ' for gi , v in sorted ( mu . items ())) } | " 126f" { ', ' . join ( f' { med ( v ):.0f } ' for gi , v in sorted ( ws . items ())) } | { 100 - sum ( mu . values ()) / len ( mu ):.0f } " ) 127"\nanswer hashes per window kind (distinct values over all runs of all arms; 1 = byte-identical)" ) 128for kind in kinds : 129hs = {} 130for r in R : 131for x in r ["rows" ]: 132if x ["kind" ]== kind and x .get ("sha" ): 133hs .setdefault (x ["sha" ],set ()).add (r ["arm" ]) 134f" { kind } : { len ( hs ) } distinct" + ("" if len (hs )== 1 else " -> " + "; " .join (f" { h } : { ',' . join ( sorted ( a )) } " for h ,a in hs .items ()))) 135for nm in names : 136sl = sorted ({r .get ("slots" )for r in R if r ["arm" ]== nm },key = str ) 137f" { nm } : expert-cache slots { sl } " ) 138 139 140if "--summary" in sys .argv : 141summary (Path (arg ("--summary" ,"." )),arg ("--base" ,None )) 142sys .exit (0 ) 143 144MODE = sys .argv [1 ] 145REPO = Path (os .environ ["STRATA_REPO" ]) 146sys .path .insert (0 ,str (REPO / "tools" )) 147sys .path .insert (0 ,str (REPO )) 148import strata_tokenizer as ST # noqa: E402 149from serve .server import child_env # noqa: E402 150 151SMP = Sampler () 152CFG ,OUT = sys .argv [2 ],Path (sys .argv [3 ]) 153PAIRS = int (arg ("--pairs" ,"5" )) 154NEW = int (arg ("--new" ,"300" if MODE == "single" else "200" )) 155WARM = int (arg ("--warm" ,"2" )) 156PPS = [int (x )for x in arg ("--pps" ,"0" ).split ("," )if int (x )] 157BATCH = int (arg ("--batch" ,"2" )) 158PASSES = int (arg ("--passes" ,"2" )) 159extra = arg ("--extra" ,"" ).split () 160ARMS = [] 161for a in args_of ("--arm" ): 162nm ,rest = a .split ("=" ,1 ) 163exe ,xargs ,envs = (rest .split ("!" )+ ["" ,"" ])[:3 ] 164ARMS .append ((nm ,exe ,xargs .split (),dict (kv .split ("=" ,1 )for kv in envs .split ("," )if kv ))) 165OUT .mkdir (parents = True ,exist_ok = True ) 166cfg = json .load (open (CFG ,encoding = "utf-8-sig" )) 167tp = Path (cfg ["tokenizer" ]) 168vocab = json .loads ((tp / "vocab.json" ).read_text (encoding = "utf-8" )) 169toks = [None ]* len (vocab ) 170for t ,i in vocab .items (): 171toks [i ]= t 172tok = ST .Tokenizer (toks , (tp / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 173json .loads ((tp / "token_type.json" ).read_text ())) 174HEAD = tok .encode ("<|im_start|>user\n" ,parse_special = True ) 175TAIL = tok .encode ("<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" ,parse_special = True ) 176KINDS = ["story" ,"code" ,"facts" ] 177ASK = { 178"story" :"Write a long story about a lighthouse keeper who finds a message in a bottle. Make it detailed." , 179"code" :"Write a Python program that implements an LRU cache class with get and put, plus unit tests. Explain each part." , 180"facts" :"Give me twenty well-known facts about the planets of the solar system, one per line, with the key numbers for each." , 181} 182QUESTIONS = [ 183"Explain in detail how a B-tree works." , 184"Write a Python function that merges overlapping intervals, then explain it." , 185"Compare TCP and QUIC: handshake, congestion control, multiplexing." , 186"Tell the history of the calculation of pi, from Archimedes to today." , 187] 188_DOC = [] 189 190 191def doc_ids (n ,start = 30000 ): 192if not _DOC : 193txt = "" 194for f in sorted ((REPO / "docs" ).glob ("*.md" )): 195txt += f .read_text (encoding = "utf-8" ,errors = "replace" )+ "\n" 196txt = txt * 8 197_DOC .extend (tok .encode (txt [start :],parse_special = False )) 198return _DOC [:n ] 199 200 201def ids_for (name ,n = 0 ): 202if name == "pp" : 203return HEAD + tok .encode ("Summarise:\n\n" ,parse_special = False )+ doc_ids (n ,5000 )+ tok .encode ("\n\nOne line." ,parse_special = False )+ TAIL 204if name .startswith ("q" ): 205return HEAD + tok .encode (QUESTIONS [int (name [1 :])],parse_special = False )+ TAIL 206return HEAD + tok .encode (ASK [name ],parse_special = False )+ TAIL 207 208 209def clean_env (env_extra ): 210env = child_env (cfg ) 211for k in list (env ): 212if k .startswith ("STRATA_" ): 213env .pop (k ,None ) 214env ["STRATA_DECODE_TIMING" ]= "1" 215env .update (env_extra ) 216return env 217 218 219def finish (p ,log ): 220try : 221p .stdin .close () 222except Exception : 223pass 224try : 225p .wait (120 ) 226except Exception : 227p .kill () 228txt = open (log ,errors = "replace" ).read () 229slots = re .findall (r"expert cache (\d+) slots" ,txt ) 230notes = [l for l in txt .splitlines ()if re .search (r"batch_groups|pipeline.windows|SPLIT_OVERLAP|handoff" ,l ,re .I )][:4 ] 231return (slots [0 ]if slots else None ),notes 232 233 234def start (exe ,args ,env ,log ): 235lf = open (log ,"w" ) 236p = subprocess .Popen ([exe ,"--serve" ,* args ],cwd = cfg .get ("cwd" ),stdin = subprocess .PIPE ,stdout = subprocess .PIPE , 237stderr = lf ,text = True ,bufsize = 1 ,env = env ) 238for line in p .stdout : 239if line .startswith ("READY" ): 240return p 241raise SystemExit (f"engine ended before READY: { log } " ) 242 243 244def gen (p ,ids ,n ): 245p .stdin .write (f"GEN { n } { ',' . join ( map ( str , ids )) } \n" ) 246p .stdin .flush () 247got ,info = [],"" 248for line in p .stdout : 249line = line .rstrip ("\n" ) 250if line .startswith ("T " ): 251got .append (int (line .split ()[1 ])) 252elif line .startswith ("DONE" )or line .startswith ("ERR" ): 253info = line 254break 255return got ,info 256 257 258def kv_of (info ): 259f = info .split () 260if len (f )< 5 or f [0 ]!= "DONE" : 261return {} 262return {"generated" :f [1 ],"prompt_tokens" :f [2 ],"prompt_ms" :f [3 ],"decode_ms" :f [4 ]} 263 264 265def run_single (label ,exe ,xargs ,env_extra ): 266log = OUT / f" { label } .log" 267p = start (exe ,list (cfg ["args" ])+ extra + xargs ,clean_env (env_extra ),str (log )) 268for i in range (WARM ): 269gen (p ,ids_for (KINDS [i % len (KINDS )]),64 ) 270rows = [] 271for name in KINDS : 272t0 = time .time () 273out ,info = gen (p ,ids_for (name ),NEW ) 274t1 = time .time () 275d = kv_of (info ) 276g ,dms = d .get ("generated" ),d .get ("decode_ms" ) 277rows .append ({"kind" :name ,"gen" :len (out ),"tok_s" : (len (out )/ float (dms )* 1000.0 )if dms else None ,"ids" :out ,"info" :info , 278"sha" :hashlib .sha256 ("," .join (map (str ,out )).encode ()).hexdigest ()[:16 ],"gpu" :SMP .window (t0 ,t1 )}) 279for n in PPS : 280ids = ids_for ("pp" ,n ) 281t0 = time .time () 282out ,info = gen (p ,ids ,8 ) 283t1 = time .time () 284d = kv_of (info ) 285pms = d .get ("prompt_ms" ) 286rows .append ({"kind" :f"pp { n // 1024 } k" ,"pp_tokens" :len (ids ),"pp_tok_s" : (len (ids )/ float (pms )* 1000.0 )if pms else None , 287"ids" :out ,"info" :info ,"tok_s" :None ,"gpu" :SMP .window (t0 ,t1 ), 288"sha" :hashlib .sha256 ("," .join (map (str ,out )).encode ()).hexdigest ()[:16 ]}) 289slots ,notes = finish (p ,log ) 290return rows ,slots ,notes 291 292 293def batch_pass (p ,n_new ,n ): 294prompts = [ids_for (f"q { i % len ( QUESTIONS ) } " )for i in range (n )] 295got = {i : []for i in range (n )} 296first = {} 297sent = {} 298done = {} 299stamp = [] 300t0 = time .time () 301for i ,ids in enumerate (prompts ): 302sent [i ]= time .time () 303p .stdin .write (f"BGEN { i } { n_new } { ',' . join ( map ( str , ids )) } \n" ) 304p .stdin .flush () 305for line in p .stdout : 306if line .startswith ("T " ): 307got [i ].append (int (line .split ()[1 ])) 308first .setdefault (i ,time .time ()) 309stamp .append (time .time ()) 310elif line .startswith ("BT " ): 311_ ,s ,y = line .split () 312got [int (s )].append (int (y )) 313first .setdefault (int (s ),time .time ()) 314stamp .append (time .time ()) 315elif line .startswith ("BDONE " ): 316done [int (line .split ()[1 ])]= line 317elif line .startswith ("ERR" ): 318raise SystemExit ("batch ERR: " + line ) 319elif line .startswith ("BADM " ): 320if line .split ()[2 ]== "0" : 321done [i ]= line 322break 323t_adm = time .time () 324while len (done )< n : 325line = p .stdout .readline () 326if not line : 327raise SystemExit ("engine ended in batch" ) 328if line .startswith ("BT " ): 329_ ,s ,y = line .split () 330got [int (s )].append (int (y )) 331first .setdefault (int (s ),time .time ()) 332stamp .append (time .time ()) 333elif line .startswith ("BDONE " ): 334done [int (line .split ()[1 ])]= line 335elif line .startswith ("ERR" ): 336raise SystemExit ("batch ERR: " + line ) 337t_end = time .time () 338total = sum (len (v )for v in got .values ()) 339late = sum (1 for s in stamp if s > t_adm ) 340return {"kind" :"batch" ,"tokens" :total ,"tok_s" :total / (t_end - t0 ),"steady" :late / max (t_end - t_adm ,1e-9 ), 341"gpu" :SMP .window (t_adm ,t_end ),"sha" :hashlib .sha256 (json .dumps ([got [i ]for i in range (n )]).encode ()).hexdigest ()[:16 ], 342"ttft" :med ([first [i ]- sent [i ]for i in first ]),"ids" : [got [i ]for i in range (n )],"secs" :t_end - t0 } 343 344 345def run_batch (label ,exe ,xargs ,env_extra ): 346log = OUT / f" { label } .log" 347p = start (exe ,list (cfg ["args" ])+ ["--batch" ,str (BATCH )]+ extra + xargs ,clean_env (env_extra ),str (log )) 348batch_pass (p ,48 ,BATCH ) 349rows = [batch_pass (p ,NEW ,BATCH )for _ in range (PASSES )] 350for r in rows : 351r ["pass" ]= rows .index (r ) 352p .stdin .write ("QUIT\n" ) 353p .stdin .flush () 354slots ,notes = finish (p ,log ) 355return rows ,slots ,notes 356 357 358res = OUT / "results.jsonl" 359ROUND0 = int (arg ("--round0" ,"0" )) 360only = arg ("--only" ,None ) 361for rnd in range (ROUND0 ,ROUND0 + (1 if only else PAIRS )): 362order = ARMS [rnd % len (ARMS ):]+ ARMS [:rnd % len (ARMS )] 363for nm ,exe ,xargs ,e in order : 364if only and nm not in only .split ("," ): 365continue 366fn = run_single if MODE == "single" else run_batch 367rows ,slots ,notes = fn (f" { nm } _ { rnd } " ,exe ,xargs ,e ) 368with open (res ,"a" )as f : 369f .write (json .dumps ({"round" :rnd ,"arm" :nm ,"slots" :slots ,"notes" :notes ,"rows" :rows })+ "\n" ) 370if MODE == "single" : 371m = med ([r ["tok_s" ]for r in rows if r .get ("tok_s" )]) 372pp = [round (r .get ("pp_tok_s" )or 0 )for r in rows if r .get ("pp_tok_s" )] 373f"round { rnd } { nm } : decode median { m :.2f } tok/s, pp { pp } slots { slots } { notes [: 1 ] } " ,flush = True ) 374else : 375f"round { rnd } { nm } : agg { [ round ( r [ 'tok_s' ], 1 ) for r in rows ] } steady { [ round ( r [ 'steady' ], 1 ) for r in rows ] } " 376f"ttft { [ round ( r [ 'ttft' ], 2 ) for r in rows ] } slots { slots } { notes [: 2 ] } " ,flush = True )