okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0b65d593c
main
1"""bench-local/run_all.py - the full local benchmark: quality suites, speed per configuration, the longest contexts. 2 3Runs detached; restarts the Strata server with other settings between phases and restores 128K / 2048 MiB at the 4end. Progress: run_all.log; numbers: run_all.json. 5""" 6from __future__import annotations 7 8import base64 9import io 10import json 11import random 12import re 13import statistics 14import subprocess 15import sys 16import time 17import uuid 18from pathlib import Path 19 20import psutil 21import requests 22 23HERE = Path (__file__ ).parent 24ROOT = HERE .parent 25PY = sys .executable 26BASE = "http://127.0.0.1:8080" 27CFG = ROOT / "strata-iq2_xs.json" 28LOG = HERE / "run_all.log" 29RES :dict = {"speed" : [],"longctx" : [],"vision" : [],"config" : [],"suites" : []} 30 31 32def log (msg ): 33line = f" { time . strftime ( '%H:%M:%S' ) } { msg } " 34with LOG .open ("a" ,encoding = "utf-8" )as f : 35f .write (line + "\n" ) 36 (HERE / "run_all.json" ).write_text (json .dumps (RES ,ensure_ascii = False ,indent = 1 ),encoding = "utf-8" ) 37 38 39# ------------------------------------------------------------------------------------------------ the server 40def stop_server (): 41for p in psutil .process_iter (["name" ,"cmdline" ]): 42try : 43cl = " " .join (p .info ["cmdline" ]or []) 44if p .info ["name" ]in ("strata.exe" ,"strata-vision.exe" )or ("serve" in cl and "server.py" in cl ): 45p .kill () 46except (psutil .NoSuchProcess ,psutil .AccessDenied ): 47pass 48time .sleep (5 ) 49 50 51def health (): 52try : 53return requests .get (BASE + "/health" ,timeout = 5 ).json () 54except Exception : 55return {} 56 57 58def start_server (): 59out = open (ROOT / "server.out" ,"w" ) 60err = open (ROOT / "server.err" ,"w" ) 61proc = subprocess .Popen ([PY ,"serve/server.py" ,"--engine" ,"strata" ,"--config" ,str (CFG ),"--port" ,"8080" ], 62cwd = ROOT ,stdout = out ,stderr = err ,creationflags = subprocess .CREATE_NO_WINDOW ) 63t = time .time () 64while time .time ()- t < 1200 : 65if health ().get ("loaded" ): 66return round (time .time ()- t ) 67if proc .poll ()is not None : 68return None 69time .sleep (3 ) 70return None 71 72 73def engine_facts (): 74text = (ROOT / "strata-iq2_xs.log" ).read_text (encoding = "utf-8" ,errors = "replace" )[- 200000 :] 75slots = re .findall (r"expert cache (\d+) slots, ([\d.]+) GiB" ,text ) 76free = re .findall (r"(\d+) MiB of VRAM free with everything loaded" ,text ) 77return {"expert_slots" :int (slots [- 1 ][0 ])if slots else None ,"cache_gib" :float (slots [- 1 ][1 ])if slots else None , 78"vram_free_mib" :int (free [- 1 ])if free else None } 79 80 81def configure (ctx ,reserve ,vision_tokens = None ): 82stop_server () 83p = subprocess .run ([PY ,"setup.py" ,"--setup" ,"--yes" ,"--family" ,"qwen" ,"--model" ,"IQ2_XS" ,"--context" , 84str (ctx ),"--vram-reserve-mib" ,str (reserve ),"--vision" ,"cpu" ,"--data-dir" , 85r"D:\Strata-data" ,"--no-start" ],cwd = ROOT ,stdin = subprocess .DEVNULL ,capture_output = True , 86text = True ,encoding = "utf-8" ,errors = "replace" ) 87notes = [ln .strip ()[:220 ]for ln in p .stdout .splitlines ()if "[!]" in ln or "context" in ln .lower ()or "rope" in ln .lower ()] 88if vision_tokens : 89cfg = json .loads (CFG .read_text (encoding = "utf-8" )) 90cfg ["vision" ]["max_tokens" ]= vision_tokens 91CFG .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 92secs = start_server () 93h = health () 94rec = {"asked_context" :ctx ,"reserve_mib" :reserve ,"vision_tokens" :vision_tokens ,"start_s" :secs , 95"max_context" :h .get ("max_context" ),"setup_exit" :p .returncode ,"notes" :notes [- 8 :],** engine_facts ()} 96RES ["config" ].append (rec ) 97log (f"CONFIG ctx { ctx } reserve { reserve } : started in { secs } s, max_context { h . get ( 'max_context' ) } , { engine_facts () } " ) 98for n in notes [- 8 :]: 99log (" setup: " + n ) 100return secs is not None 101 102 103# ------------------------------------------------------------------------------------------------ requests 104def ask (content ,max_tokens = 300 ,effort = "none" ,timeout = 7200 ): 105t = time .time () 106try : 107r = requests .post (BASE + "/v1/chat/completions" ,timeout = timeout ,json = { 108"model" :"strata" ,"messages" : [{"role" :"user" ,"content" :content }],"max_tokens" :max_tokens , 109"reasoning_effort" :effort ,"temperature" :0 }).json () 110except Exception as e : 111return {"error" :f" { type ( e ). __name__ } : { e } " [:300 ]} 112if "choices" not in r : 113return {"error" :json .dumps (r )[:300 ]} 114tm = r .get ("timings" , {}) 115return {"content" :r ["choices" ][0 ]["message" ].get ("content" )or "" ,"wall" :round (time .time ()- t ,1 ), 116"prompt_n" :tm .get ("prompt_n" ),"prompt_s" :round (tm .get ("prompt_ms" ,0 )/ 1000 ,1 ), 117"prompt_tok_s" :tm .get ("prompt_per_second" ),"out_n" :tm .get ("predicted_n" ), 118"tok_s" :tm .get ("predicted_per_second" )} 119 120 121def speed (label ): 122dec = [ask (f"[ { uuid . uuid4 (). hex [: 8 ] } ] Explain in detail how a hash map works: hashing, collisions, resizing, " 123"complexity. About 300 words." ,420 )for _ in range (3 )] 124src = (ROOT / "serve" / "server.py" ).read_text (encoding = "utf-8" ) 125reads = {} 126for name ,kb in (("2K" ,8 ), ("8K" ,30 ), ("32K" ,125 )): 127mc = health ().get ("max_context" )or 0 128if kb * 280 > mc - 2000 :# ~280 tokens per KB of this file 129continue 130r = ask (f"Run { uuid . uuid4 (). hex } .\n\n" + src [:kb * 1000 ]+ "\n\nIn one sentence: what is this code?" ,60 ) 131reads [name ]= {k :r .get (k )for k in ("prompt_n" ,"prompt_s" ,"prompt_tok_s" ,"tok_s" ,"error" )} 132ok = [d ["tok_s" ]for d in dec if d .get ("tok_s" )] 133rec = {"label" :label ,"decode_tok_s" :ok ,"decode_median" :statistics .median (ok )if ok else None ,"read" :reads , 134** engine_facts ()} 135RES ["speed" ].append (rec ) 136log (f"SPEED { label } : decode { ok } tok/s; read " + 137", " .join (f" { k } { v . get ( 'prompt_n' ) } tok at { v . get ( 'prompt_tok_s' ) } tok/s" for k ,v in reads .items ())) 138 139 140# ------------------------------------------------------------------------------------------------ long context 141WORDS = ("river mountain engine garden window bridge market signal harbor library forest station valley mirror " 142"ladder castle meadow tunnel beacon anchor copper marble velvet thunder lantern compass orchard glacier " 143"pepper cotton ribbon basket candle feather hammer island jacket kettle lemon magnet needle ocean pillow " 144"quartz rocket saddle timber violet walnut yarn zipper" ).split () 145COLORS = ["red" ,"green" ,"blue" ,"amber" ,"violet" ] 146 147 148def filler (rng ,n_chars ): 149out ,size ,i = [],0 ,0 150while size < n_chars : 151i += 1 152s = f"Section { i } . " + " " .join ( 153f"The { rng . choice ( WORDS ) } near the { rng . choice ( WORDS ) } was moved to the { rng . choice ( WORDS ) } on day " 154f" { rng . randint ( 1 , 365 ) } ." for _ in range (6 ))+ "\n" 155out .append (s ) 156size += len (s ) 157return out 158 159 160def longctx (target_tokens ,label ): 161rng = random .Random (target_tokens ) 162cal = ask ("" .join (filler (rng ,40000 ))+ "\nReply OK." ,5 ) 163if cal .get ("error" ): 164log (f"LONGCTX { label } : calibration failed { cal [ 'error' ] } " ) 165return 166per_tok = 40000 / cal ["prompt_n" ] 167paras = filler (rng ,int (target_tokens * per_tok )) 168codes = {c :str (rng .randint (100000 ,999999 ))for c in COLORS } 169for c ,depth in zip (COLORS , (0.1 ,0.3 ,0.5 ,0.7 ,0.9 )): 170paras .insert (int (len (paras )* depth ),f"Important: the secret code for { c } is { codes [ c ] } .\n" ) 171q = ("\nQuestion: the text above contains five secret codes, one each for red, green, blue, amber and violet. " 172"Reply with only JSON like {\"red\": \"...\", \"green\": \"...\", \"blue\": \"...\", \"amber\": \"...\", " 173"\"violet\": \"...\"}." ) 174r = ask (f"Document { uuid . uuid4 (). hex } :\n\n" + "" .join (paras )+ q ,200 ,timeout = 14400 ) 175found = {c : (codes [c ]in r .get ("content" ,"" ))for c in COLORS } 176rec = {"label" :label ,"target" :target_tokens ,"found" :sum (found .values ()),"by_depth" :found , 177** {k :r .get (k )for k in ("prompt_n" ,"prompt_s" ,"prompt_tok_s" ,"tok_s" ,"wall" ,"error" )}, 178"answer" :r .get ("content" ,"" )[:200 ]} 179RES ["longctx" ].append (rec ) 180log (f"LONGCTX { label } : { r . get ( 'prompt_n' ) } tok read in { r . get ( 'prompt_s' ) } s ( { r . get ( 'prompt_tok_s' ) } tok/s), " 181f"found { sum ( found . values ()) } /5 { found } , decode { r . get ( 'tok_s' ) } tok/s { r . get ( 'error' , '' ) } " ) 182if not r .get ("error" ):# a follow-up in the same conversation is not possible through ask(); a new short 183r2 = ask ("What is 12 * 12? Number only." ,20 )# request shows the server still answers after the long one 184log (f" after it, a short request: { r2 . get ( 'content' , r2 . get ( 'error' ))!r } in { r2 . get ( 'wall' ) } s" ) 185 186 187# ------------------------------------------------------------------------------------------------ pictures 188def vision (label ): 189from PIL import Image ,ImageDraw ,ImageFont 190for name ,size ,px ,rows in (("1600x900 16px" , (1600 ,900 ),16 ,40 ), ("3840x2160 16px" , (3840 ,2160 ),16 ,95 ), 191 ("3840x2160 28px" , (3840 ,2160 ),28 ,60 )): 192rng = random .Random (px + size [0 ]) 193font = ImageFont .truetype ("consola.ttf" ,px ) 194lines = [f" { i :02d } cfg. { rng . choice ([ 'port' , 'retries' , 'timeout' , 'workers' , 'limit' , 'depth' ]) } _ { i } = " 195f" { rng . randint ( 1000 , 9999 ) } " for i in range (1 ,rows + 1 )] 196img = Image .new ("RGB" ,size , (30 ,30 ,30 )) 197d = ImageDraw .Draw (img ) 198for i ,s in enumerate (lines ): 199d .text ((40 ,20 + i * int (px * 1.35 )),s ,font = font ,fill = (220 ,220 ,220 )) 200buf = io .BytesIO () 201img .save (buf ,"PNG" ) 202b64 = base64 .b64encode (buf .getvalue ()).decode () 203hits ,walls ,ptoks = 0 , [],None 204picks = [3 ,rows // 3 ,rows // 2 , (2 * rows )// 3 ,rows - 2 ] 205for ln in picks : 206r = ask ([{"type" :"text" ,"text" :f"This is a screenshot of code. Copy line { ln :02d } exactly." }, 207 {"type" :"image_url" ,"image_url" : {"url" :"data:image/png;base64," + b64 }}],80 ) 208want = lines [ln - 1 ].split (" " ,1 )[1 ] 209hits += want in r .get ("content" ,"" ) 210walls .append (r .get ("wall" )) 211ptoks = r .get ("prompt_n" )or ptoks 212RES ["vision" ].append ({"label" :label ,"image" :name ,"exact" :hits ,"of" :len (picks ),"prompt_tokens" :ptoks , 213"wall" :walls }) 214log (f"VISION { label } { name } : { hits } / { len ( picks ) } lines exact, { ptoks } prompt tokens, { walls } s" ) 215 216 217def suite (script ,tag ,args = ()): 218t = time .time () 219with (HERE / f" { tag } .log" ).open ("w" ,encoding = "utf-8" )as f : 220p = subprocess .run ([PY ,str (HERE / script ),* args ],cwd = ROOT ,stdout = f ,stderr = subprocess .STDOUT , 221env = {** __import__ ("os" ).environ ,"PYTHONIOENCODING" :"utf-8" }) 222RES ["suites" ].append ({"tag" :tag ,"exit" :p .returncode ,"minutes" :round ((time .time ()- t )/ 60 ,1 )}) 223log (f"SUITE { tag } finished in { ( time . time () - t ) / 60 :.1f } min (exit { p . returncode } )" ) 224 225 226def main (): 227log ("=== run_all started" ) 228try : 229if not health ().get ("loaded" ): 230configure (131072 ,2048 ) 231# 1. the everyday configuration: 128K, 2048 MiB kept free 232# (the 128K speed test and the round-1 suites were measured before; only what is still missing runs here) 233vision ("300 image tokens" ) 234suite ("strata_eval2.py" ,"eval2-qa" , ["qa" ]) 235suite ("strata_eval2.py" ,"eval2-hard" , ["hard" ]) 236longctx (118000 ,"128K config" ) 237# 2. the upper speed limit: a small context and the smallest VRAM reserve 238if configure (8192 ,700 ): 239speed ("8K reserve 700" ) 240# 3. the trained maximum, and pictures with more tokens 241if configure (262144 ,2048 ,vision_tokens = 1024 ): 242speed ("256K reserve 2048" ) 243vision ("1024 image tokens" ) 244longctx (248000 ,"256K config" ) 245# 4. past the trained range (experimental rope scaling) 246if configure (524288 ,2048 ): 247mc = health ().get ("max_context" )or 0 248speed (f" { mc // 1024 } K (asked 512K) reserve 2048" ) 249if mc > 270000 : 250longctx (mc - 14000 ,f" { mc // 1024 } K config" ) 251except Exception as e : 252log (f"CRASHED { type ( e ). __name__ } : { e } " ) 253finally : 254configure (131072 ,2048 ) 255log ("=== run_all finished; server restored to 128K / 2048 MiB" ) 256 257 258if __name__ == "__main__" : 259main ()