okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e2de691c7
main
1#!/usr/bin/env python3 2"""Strata vs llama.cpp head-to-head (stream 1402-h). Measurement only. 3 4Both engines are driven through their OpenAI-compatible HTTP servers (/v1/chat/completions), with the same prompt 5text, same sampler settings and the same GGUF. Server-side timings (llama.cpp's names, which Strata's server also 6emits) give prompt tok/s and decode tok/s; time to first token is the server's prompt_ms (non-streaming request, 7so TTFT = prompt processing time). Peak VRAM comes from nvidia-smi polling (minus the idle baseline), RAM from the 8engine process tree (psutil RSS, which counts mmap'd file pages) and the system's used-memory delta. 9 10python bench_vs_llama.py prompts --out DIR --tokenizer DIR --corpus FILE... # build 4K / 32K prompt files 11python bench_vs_llama.py run --machine CFG.json --out DIR --rounds N [--configs a,b] [--cells ...] 12python bench_vs_llama.py quality --machine CFG.json --out DIR [--configs a,b] 13python bench_vs_llama.py summary --out DIR 14 15CFG.json: {"gguf": ..., "strata_cfg": ..., "llama_server": ..., "configs": [{"name","kind":"llama|strata","args":[...]}]} 16Interleaving: engines cannot be loaded together (12 GB card, 64 GB RAM), so one ROUND runs every config once 17(start, warm-up, cells, stop), and rounds alternate the config order. Medians are taken over rounds. 18The caller holds the machine's GPU lock. Processes are stopped by PID only. 19""" 20import argparse ,json ,os ,statistics ,subprocess ,sys ,threading ,time ,urllib .request 21from pathlib import Path 22 23import psutil 24 25CELLS = [("4k" ,4000 ,2 ), ("32k" ,32000 ,1 )]# (name, prompt tokens, reps per round) 26TEMPS = [0.0 ,0.7 ] 27GEN = 256 28PORT = 8190 29 30 31def http (url ,body = None ,timeout = 3600 ): 32req = urllib .request .Request (url ,data = json .dumps (body ).encode ()if body is not None else None , 33headers = {"Content-Type" :"application/json" }) 34with urllib .request .urlopen (req ,timeout = timeout )as r : 35return json .loads (r .read ()) 36 37 38def vram_used_mib (): 39try : 40out = subprocess .run (["nvidia-smi" ,"--query-gpu=memory.used" ,"--format=csv,noheader,nounits" ], 41capture_output = True ,text = True ,timeout = 20 ).stdout .split () 42return int (out [0 ]) 43except Exception : 44return - 1 45 46 47class Sampler (threading .Thread ): 48def __init__ (self ,pid ): 49super ().__init__ (daemon = True ) 50self .pid ,self .stop ,self .vram ,self .rss ,self .sysused = pid ,False ,0 ,0 ,0 51 52def run (self ): 53while not self .stop : 54self .vram = max (self .vram ,vram_used_mib ()) 55try : 56p = psutil .Process (self .pid ) 57self .rss = max (self .rss ,sum (c .memory_info ().rss for c in [p ]+ p .children (recursive = True ))) 58except psutil .Error : 59pass 60self .sysused = max (self .sysused ,psutil .virtual_memory ().used ) 61time .sleep (1.0 ) 62 63 64class Engine : 65def __init__ (self ,machine ,cfg ): 66self .m ,self .cfg ,self .proc ,self .log = machine ,cfg ,None ,None 67 68def command (self ): 69c = self .cfg 70if c ["kind" ]== "llama" : 71return [self .m ["llama_server" ],"-m" ,self .m ["gguf" ],"--port" ,str (PORT ),"--host" ,"127.0.0.1" , 72"-np" ,"1" ,"--no-webui" ,"--jinja" ]+ c ["args" ] 73scfg = json .load (open (self .m ["strata_cfg" ],encoding = "utf-8-sig" )) 74scfg ["port" ]= PORT 75scfg .pop ("vision" ,None ) 76args = [a for a in scfg ["args" ]] 77for k ,v in c .get ("override" , {}).items ():# replace "--flag value" pairs 78if k in args : 79args [args .index (k )+ 1 ]= v 80else : 81args += [k ,v ] 82scfg ["args" ]= args + c ["args" ] 83if self .m .get ("strata_exe" ): 84scfg ["exe" ]= self .m ["strata_exe" ] 85p = Path (self .out )/ ("strata-cfg-%s.json" % c ["name" ]) 86p .write_text (json .dumps (scfg ,indent = 1 )) 87return [sys .executable ,str (Path (self .m ["serve" ])/ "server.py" ),"--engine" ,"strata" ,"--config" ,str (p ), 88"--port" ,str (PORT )] 89 90def start (self ,out ): 91self .out = out = str (Path (out ).resolve ()) 92self .base_vram ,self .base_used = vram_used_mib (),psutil .virtual_memory ().used 93cmd = self .command () 94self .cmdline = " " .join (cmd ) 95self .log = open (Path (out )/ ("server-%s-%d.log" % (self .cfg ["name" ],int (time .time ()))),"w" ,encoding = "utf-8" ) 96env = dict (os .environ ,PYTHONIOENCODING = "utf-8" ) 97self .proc = subprocess .Popen (cmd ,stdout = self .log ,stderr = subprocess .STDOUT ,env = env , 98cwd = self .m .get ("cwd" )) 99self .t0 = time .time () 100self .sampler = Sampler (self .proc .pid ) 101self .sampler .start () 102health = "http://127.0.0.1:%d/health" % PORT 103while time .time ()- self .t0 < 1500 : 104if self .proc .poll ()is not None : 105raise RuntimeError ("server exited rc=%s (see %s)" % (self .proc .returncode ,self .log .name )) 106try : 107r = http (health ,timeout = 5 ) 108if r .get ("status" ,"ok" )== "ok" : 109break 110except Exception : 111pass 112time .sleep (2 ) 113else : 114raise RuntimeError ("server not ready in 1500 s" ) 115self .load_s = time .time ()- self .t0 116 117def stop (self ): 118if self .proc : 119self .sampler .stop = True 120try : 121p = psutil .Process (self .proc .pid ) 122kids = p .children (recursive = True ) 123for c in kids + [p ]: 124try : 125c .terminate () 126except psutil .Error : 127pass 128psutil .wait_procs (kids + [p ],timeout = 30 ) 129for c in kids + [p ]: 130try : 131if c .is_running (): 132c .kill () 133except psutil .Error : 134pass 135except psutil .Error : 136pass 137self .log .close () 138self .proc = None 139time .sleep (5 ) 140 141def chat (self ,prompt ,temp ,max_tokens = GEN ,seed = 1 ): 142body = {"model" :"x" ,"messages" : [{"role" :"user" ,"content" :prompt }],"max_tokens" :max_tokens , 143"temperature" :temp ,"top_k" :20 ,"top_p" :0.95 ,"seed" :seed ,"stream" :False , 144"cache_prompt" :False ,"chat_template_kwargs" : {"enable_thinking" :False }} 145if temp == 0 : 146body .pop ("top_p" ),body .pop ("top_k" ) 147t = time .time () 148r = http ("http://127.0.0.1:%d/v1/chat/completions" % PORT ,body ) 149wall = time .time ()- t 150tm = r .get ("timings" )or {} 151u = r .get ("usage" )or {} 152return {"wall_s" :round (wall ,2 ),"prompt_n" :tm .get ("prompt_n" ,u .get ("prompt_tokens" )), 153"prompt_ms" :tm .get ("prompt_ms" ),"prompt_tps" :tm .get ("prompt_per_second" ), 154"pred_n" :tm .get ("predicted_n" ,u .get ("completion_tokens" )),"pred_tps" :tm .get ("predicted_per_second" ), 155"draft_n" :tm .get ("draft_n" ),"draft_acc" :tm .get ("draft_n_accepted" ), 156"text" : (r ["choices" ][0 ]["message" ].get ("content" )or "" )} 157 158 159def cmd_prompts (a ): 160sys .path .insert (0 ,str (Path (a .repo )/ "tools" )) 161import strata_tokenizer as ST 162tp = Path (a .tokenizer ) 163vocab = json .loads ((tp / "vocab.json" ).read_text (encoding = "utf-8" )) 164toks = [None ]* len (vocab ) 165for t ,i in vocab .items (): 166toks [i ]= t 167tok = ST .Tokenizer (toks , (tp / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 168json .loads ((tp / "token_type.json" ).read_text ())) 169corpus = "\n\n" .join (Path (f ).read_text (encoding = "utf-8" ,errors = "replace" )for f in a .corpus ) 170"corpus chars" ,len (corpus )) 171out = Path (a .out ) 172out .mkdir (parents = True ,exist_ok = True ) 173allids = tok .encode (corpus ) 174"corpus tokens" ,len (allids )) 175for name ,n ,_ in CELLS : 176if len (allids )< n : 177raise SystemExit ("corpus too small for %s" % name ) 178 (out / ("prompt-%s.txt" % name )).write_text (tok .decode (allids [:n ]),encoding = "utf-8" ) 179name ,n ,"tokens" ) 180 181 182def load_prompt (out ,name ): 183return (Path (out )/ ("prompt-%s.txt" % name )).read_text (encoding = "utf-8" ) 184 185 186def cmd_run (a ): 187m = json .load (open (a .machine )) 188out = Path (a .out ) 189 (out / "raw" ).mkdir (parents = True ,exist_ok = True ) 190cfgs = [c for c in m ["configs" ]if not a .configs or c ["name" ]in a .configs .split ("," )] 191cells = [c for c in CELLS if not a .cells or c [0 ]in a .cells .split ("," )] 192prompts = {c [0 ]:load_prompt (out ,c [0 ])for c in cells } 193for rnd in range (a .start_round ,a .start_round + a .rounds ): 194order = cfgs if rnd % 2 == 0 else cfgs [::- 1 ] 195for cfg in order : 196eng = Engine (m ,cfg ) 197rec_path = out / "raw" / ("%s.jsonl" % cfg ["name" ]) 198try : 199eng .start (str (out )) 200eng .chat ("Say hello." ,0.0 ,16 )# warm-up, discarded 201eng .chat (prompts ["4k" ][:6000 ]if "4k" in prompts else "hi" ,0.0 ,32 ) 202for cname ,n ,reps in cells : 203for t in TEMPS : 204for k in range (reps ): 205nonce = "[bench %s r%d %s t%.1f k%d %d]\n" % (cfg ["name" ],rnd ,cname ,t ,k ,time .time ()) 206r = eng .chat (nonce + prompts [cname ]+ "\n\nSummarize the text above in three sentences." ,t ) 207r .update (config = cfg ["name" ],round = rnd ,cell = cname ,temp = t ,rep = k , 208vram_peak_mib = eng .sampler .vram ,vram_base_mib = eng .base_vram , 209rss_peak_gib = round (eng .sampler .rss / 2 ** 30 ,2 ), 210sys_used_delta_gib = round ((eng .sampler .sysused - eng .base_used )/ 2 ** 30 ,2 ), 211load_s = round (eng .load_s ,1 ),cmd = eng .cmdline if (rnd == a .start_round and k == 0 )else None ) 212r ["text" ]= r ["text" ][:300 ] 213with open (rec_path ,"a" ,encoding = "utf-8" )as f : 214f .write (json .dumps (r )+ "\n" ) 215cfg ["name" ],rnd ,cname ,t ,"pp %s tg %s draft %s/%s ttft %s" % ( 216r ["prompt_tps" ],r ["pred_tps" ],r ["draft_acc" ],r ["draft_n" ],r ["prompt_ms" ]),flush = True ) 217except Exception as e : 218"ERROR" ,cfg ["name" ],rnd ,repr (e ),flush = True ) 219with open (out / "raw" / "errors.log" ,"a" )as f : 220f .write ("%s r%d %r\n" % (cfg ["name" ],rnd ,e )) 221finally : 222eng .stop () 223 224 225QPROMPT = "Write a short story about a lighthouse keeper." 226 227 228def cmd_quality (a ): 229m = json .load (open (a .machine )) 230out = Path (a .out ) 231 (out / "raw" ).mkdir (parents = True ,exist_ok = True ) 232cfgs = [c for c in m ["configs" ]if not a .configs or c ["name" ]in a .configs .split ("," )] 233res = {} 234for cfg in cfgs : 235eng = Engine (m ,cfg ) 236try : 237eng .start (str (out )) 238eng .chat ("Say hello." ,0.0 ,16 ) 239for q in (QPROMPT ,"Write a Python function that parses a CSV file into a list of dicts, with tests." ): 240r = eng .chat (q ,0.0 ,200 ) 241res .setdefault (cfg ["name" ], []).append (r ["text" ]) 242finally : 243eng .stop () 244 (out / "raw" / "quality.json" ).write_text (json .dumps (res ,indent = 1 ),encoding = "utf-8" ) 245 246 247def cmd_summary (a ): 248out = Path (a .out ) 249rows = {} 250for f in sorted ((out / "raw" ).glob ("*.jsonl" )): 251for line in open (f ,encoding = "utf-8" ): 252r = json .loads (line ) 253rows .setdefault ((r ["config" ],r ["cell" ],r ["temp" ]), []).append (r ) 254med = lambda xs :statistics .median (xs )if xs else float ("nan" ) 255"| config | ctx | temp | n | prompt tok/s | decode tok/s | TTFT s | draft acc | VRAM peak MiB (delta) | RSS GiB |" ) 256"|---|---|---|---|---|---|---|---|---|---|" ) 257for (c ,cell ,t ),rs in sorted (rows .items ()): 258pp = [r ["prompt_tps" ]for r in rs if r ["prompt_tps" ]] 259tg = [r ["pred_tps" ]for r in rs if r ["pred_tps" ]] 260tt = [r ["prompt_ms" ]/ 1000 for r in rs if r ["prompt_ms" ]] 261da = [r ["draft_acc" ]/ r ["draft_n" ]for r in rs if r .get ("draft_n" )] 262"| %s | %s | %.1f | %d | %.1f | %.2f | %.2f | %s | %d (+%d) | %.1f |" % ( 263c ,cell ,t ,len (rs ),med (pp ),med (tg ),med (tt ), ("%.2f" % med (da ))if da else "-" , 264max (r ["vram_peak_mib" ]for r in rs ),max (r ["vram_peak_mib" ]- r ["vram_base_mib" ]for r in rs ), 265max (r ["rss_peak_gib" ]for r in rs ))) 266 267 268if __name__ == "__main__" : 269ap = argparse .ArgumentParser () 270ap .add_argument ("mode" ,choices = ["prompts" ,"run" ,"quality" ,"summary" ]) 271ap .add_argument ("--out" ,required = True ) 272ap .add_argument ("--machine" ) 273ap .add_argument ("--configs" ) 274ap .add_argument ("--cells" ) 275ap .add_argument ("--rounds" ,type = int ,default = 1 ) 276ap .add_argument ("--start-round" ,type = int ,default = 0 ) 277ap .add_argument ("--tokenizer" ) 278ap .add_argument ("--repo" ) 279ap .add_argument ("--corpus" ,nargs = "*" ) 280a = ap .parse_args () 281 {"prompts" :cmd_prompts ,"run" :cmd_run ,"quality" :cmd_quality ,"summary" :cmd_summary }[a .mode ](a )