okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0b65d593c
main
1"""bench-local/ab.py - short A/B arms against the installed IQ2_XS model: one setting changed per arm, the server 2restarted for each, the same fixed requests, results appended to ab.jsonl. 3 4python ab.py base workers15 base cyr ... (arm names from ARMS, run in the order given) 5python ab.py --quick v139 v139-stage0 ... (decode only, without the prompt reads) 6""" 7from __future__import annotations 8 9import json 10import os 11import shutil 12import statistics 13import subprocess 14import sys 15import time 16import uuid 17from pathlib import Path 18 19sys .path .insert (0 ,str (Path (__file__ ).parent )) 20import run_all as R # noqa: E402 21 22HERE = Path (__file__ ).parent 23ROOT = HERE .parent 24BASE_CFG = HERE / "base-iq2_xs.json" # the configuration every arm starts from 25RT = Path (r"D:\Strata-data\mtp\rt" ) 26BUILD = Path (r"D:\Strata-build" ) 27 28EN = ["Explain in detail how a hash map works: hashing, collisions, resizing, complexity. About 300 words." , 29"Describe how TCP establishes and closes a connection, and what each flag means. About 300 words." , 30"Compare processes and threads: memory, scheduling, communication, failure isolation. About 300 words." ] 31UK = ["Поясни докладно, як працює хеш-таблиця: хешування, колізії, розширення, складність. Приблизно 300 слів." , 32"Опиши, як TCP встановлює і закриває з'єднання і що означає кожен прапорець. Приблизно 300 слів." ] 33CODE = ["Write a complete Python module implementing an LRU cache class with get/put, a TTL option, type hints, " 34"docstrings and a small unittest suite. Code only." ] 35 36 37def set_arg (args ,flag ,value ): 38args = list (args ) 39if flag in args : 40args [args .index (flag )+ 1 ]= value 41else : 42args += [flag ,value ] 43return args 44 45 46def local_engine (name ): 47"""exe + library folders of a local build (D:\\Strata-build\\dist-<name>, unpacked from its zip).""" 48d = BUILD / f"dist- { name } " / "engine" 49return {"exe" :str (d / "strata.exe" ),"lib_dirs" : [str (d / "rocm" / "bin" )]} 50 51 52QUICK = "--quick" in sys .argv # decode only: no 8K / 30K prompt reads (an arm in ~2 min instead of ~4) 53QSETS = ("hard" ,"js" ,"sql" ,"regex" )# strata_eval2.py's suites an arm with "quality" runs 54V139 = {"engine" :"139" ,"root" :"src-139" } 55 56 57def v139s (env = None ,** more ): 58"""A 0.1.39 arm with STRATA_SH_STREAM=0, plus this arm's own environment and settings.""" 59return {** V139 ,** more ,"env" : {"STRATA_SH_STREAM" :"0" ,** (env or {})}} 60 61ARMS = { 62"base" : {}, 63"workers11" : {"args" : {"--pool-workers" :"11" }}, 64"workers15" : {"args" : {"--pool-workers" :"15" }}, 65"cyr" : {"draft_vocab" :"draft_vocab_cyrillic.bin" }, 66"en" : {"draft_vocab" :"draft_vocab_en.bin" }, 67"prefill16k" : {"args" : {"--prefill" :"auto:16384" }}, 68# MMQ is already on by default (prefill.cpp mmq_plan), so the A/B is turning it off: the FP16 expert path. 69# STRATA_PF_FUSED=1 is not an arm: on HIP the fused kernels fall back to MMQ (moe_fused.hpp). 70"mmq0" : {"env" : {"STRATA_PREFILL_MMQ" :"0" }}, 71"ring96" : {"env" : {"STRATA_PREFILL_RING" :"96" }}, 72"pcie30" : {"args" : {"--pcie-frac" :"0.3" }}, 73"pcie80" : {"args" : {"--pcie-frac" :"0.8" }}, 74"spec3" : {"args" : {"--spec" :"3" }}, 75"spec5" : {"args" : {"--spec" :"5" }}, 76"minp30" : {"args" : {"--spec-min-p" :"0.3" }}, 77"minp70" : {"args" : {"--spec-min-p" :"0.7" }}, 78# local builds 79"build-base" : {"engine" :"base" }, 80"build-prs" : {"engine" :"prs" }, 81"prs-pipeline" : {"engine" :"prs" ,"env" : {"STRATA_POOL_PIPELINE" :"1" }}, 82"prs-kvprefetch" : {"engine" :"prs" ,"env" : {"STRATA_KV_PREFETCH" :"1" }}, 83"prs-hcq8" : {"engine" :"prs" ,"env" : {"STRATA_HC_Q8" :"1" }}, 84"prs-16k" : {"engine" :"prs" ,"args" : {"--prefill" :"auto:16384" }}, 85"prs-all" : {"engine" :"prs" ,"args" : {"--prefill" :"auto:16384" }, 86"env" : {"STRATA_POOL_PIPELINE" :"1" ,"STRATA_KV_PREFETCH" :"1" ,"STRATA_HC_Q8" :"1" }}, 87# 0.1.39 (released 2026-10-04): its engine built here for gfx1030 and its own server, from D:\Strata-build\src-139 88"v139" : {** V139 }, 89# 0.1.39 decodes slower than 0.1.38 here: its new decode steps turned off one at a time (each is default on) 90"v139-stage0" : {** V139 ,"env" : {"STRATA_IQ_STAGE_GRID" :"0" }},# i-quant grids not staged in shared memory 91"v139-decbatch0" : {** V139 ,"env" : {"STRATA_DEC_BATCH" :"0" }},# the window's rows token by token 92"v139-plebatch0" : {** V139 ,"env" : {"STRATA_PLE_BATCH" :"0" }},# the PLE block token by token 93"v139-shstream0" : {** V139 ,"env" : {"STRATA_SH_STREAM" :"0" }}, 94"v139-oldmmvq" : {** V139 ,"env" : {"STRATA_OLD_IQ_MMVQ" :"1" }},# the per-column i-quant kernels 95# v139s = 0.1.39 with STRATA_SH_STREAM=0 (the shared expert on the window's own stream): measured here 96# 56.4 / 43.5 / 62.7 tok/s (en / uk / code) against 42.5 / 32.5 / 50.2 with the forked stream. The arms below 97# change one more thing each. 98"v139s" :v139s (), 99"v139s-queue" :v139s (par = [2 ,4 ]),# one at a time: the others wait in the queue 100"v139s-par2" :v139s (cfg = {"parallel" :2 },par = [1 ,2 ,4 ]),# what 2 batch slots cost a request alone 101"v139s-par4" :v139s (cfg = {"parallel" :4 },par = [1 ,2 ,4 ]), 102"v139s-cyr" :v139s (draft_vocab = "draft_vocab_cyrillic.bin" ), 103"v139s-ring0" :v139s ({"STRATA_RING_BYTES" :"0" }),# 0.1.38's prompt ring (#583 off) 104"v139s-stage0" :v139s ({"STRATA_IQ_STAGE_GRID" :"0" }), 105"v139s-nowait" :v139s ({"STRATA_ADAPT_NOWAIT" :"1" }), 106"v139s-spec6" :v139s (args = {"--spec" :"6" }),# issue #775's settings, one at a time 107"v139s-minp70" :v139s (args = {"--spec-min-p" :"0.7" }), 108"v139s-pcie0" :v139s (args = {"--pcie-frac" :"0.0" }), 109# the model sizes side by side on the same engine: speed, and the correctness suites with reasoning off 110"v139s-qual" :v139s (quick = True ,quality = True ),# IQ2_XS, the installed size 111"v139s-q20" :v139s (model = "q2_0" ,quality = True ), 112"v139s-iq3xxs" :v139s (model = "iq3_xxs" ,quality = True ), 113# IQ3_XXS: 0.1.39's opt-in AVX2 gather for the IQ3 grids on the CPU (#622, bit-exact), and the Cyrillic drafts 114"v139s-iq3xxs-g" :v139s ({"STRATA_IQ256_GATHER" :"1" },model = "iq3_xxs" ), 115"v139s-iq3xxs-cyr" :v139s (model = "iq3_xxs" ,draft_vocab = "draft_vocab_cyrillic.bin" ), 116} 117 118 119def start (arm ): 120spec = ARMS [arm ] 121# another model size: its own config as setup wrote it (strata-<model>.json), with this script's one engine log 122base = ROOT / f"strata- { spec [ 'model' ] } .json" if spec .get ("model" )else BASE_CFG 123cfg = json .loads (base .read_text (encoding = "utf-8" )) 124cfg ["log" ]= str (ROOT / "strata-iq2_xs.log" ) 125for flag ,value in spec .get ("args" , {}).items (): 126cfg ["args" ]= set_arg (cfg ["args" ],flag ,value ) 127if spec .get ("env" ): 128cfg ["env" ]= {** (cfg .get ("env" )or {}),** spec ["env" ]} 129if spec .get ("engine" ): 130cfg .update (local_engine (spec ["engine" ])) 131cfg .update (spec .get ("cfg" , {})) 132root = BUILD / spec ["root" ]if spec .get ("root" )else ROOT # the checkout whose server and data/ the arm runs 133if root != ROOT : 134cfg ["cwd" ]= str (root ) 135cfg ["args" ]= set_arg (cfg ["args" ],"--expert-profile" ,str (root / "data" / "expert-profile.bin" )) 136R .stop_server () 137vocab = spec .get ("draft_vocab" ,"draft_vocab.bin" )# the default subset unless the arm names another 138shutil .copyfile (root / "data" / vocab ,RT / "draft_vocab.bin" ) 139R .CFG .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 140return R .start_server ()if root == ROOT else start_server (root ) 141 142 143def start_server (root ): 144"""R.start_server with another checkout's server (a newer version's worktree); the same wait for /health.""" 145out = open (ROOT / "server.out" ,"w" ) 146err = open (ROOT / "server.err" ,"w" ) 147proc = subprocess .Popen ([R .PY ,"serve/server.py" ,"--engine" ,"strata" ,"--config" ,str (R .CFG ),"--port" ,"8080" ], 148cwd = root ,stdout = out ,stderr = err ,creationflags = subprocess .CREATE_NO_WINDOW ) 149t = time .time () 150while time .time ()- t < 1200 : 151if R .health ().get ("loaded" ): 152return round (time .time ()- t ) 153if proc .poll ()is not None : 154return None 155time .sleep (3 ) 156return None 157 158 159def measure (arm ): 160rec = {"arm" :arm ,"time" :time .strftime ("%H:%M:%S" )} 161for name ,prompts ,mt in (("en" ,EN ,420 ), ("uk" ,UK ,520 ), ("code" ,CODE ,700 )): 162runs = [R .ask (f"[ { uuid . uuid4 (). hex [: 8 ] } ] " + p ,mt )for p in prompts ] 163rec [name ]= [r .get ("tok_s" )for r in runs ] 164src = (ROOT / "serve" / "server.py" ).read_text (encoding = "utf-8" ) 165rec .update ({"read8k" :None ,"read30k" :None }) 166for name ,kb in ()if QUICK or ARMS [arm ].get ("quick" )else (("read8k" ,30 ), ("read30k" ,125 )): 167r = R .ask (f"Run { uuid . uuid4 (). hex } .\n\n" + src [:kb * 1000 ]+ "\n\nIn one sentence: what is this code?" ,40 ) 168rec [name ]= r .get ("prompt_tok_s" ) 169rec [name + "_err" ]= r .get ("error" ) 170rec .update (R .engine_facts ()) 171log = (ROOT / "strata-iq2_xs.log" ).read_text (encoding = "utf-8" ,errors = "replace" )[- 60000 :] 172acc = [(int (a ),int (b ))for a ,b in __import__ ("re" ).findall (r"drafts accepted (\d+) of (\d+)" ,log )][- 8 :] 173rec ["draft_accept" ]= round (sum (a for a ,_ in acc )/ max (1 ,sum (b for _ ,b in acc )),3 ) 174return rec 175 176 177def main (): 178if not BASE_CFG .exists (): 179shutil .copyfile (R .CFG ,BASE_CFG ) 180for arm in [a for a in sys .argv [1 :]if not a .startswith ("--" )]: 181secs = start (arm ) 182if secs is None : 183rec = {"arm" :arm ,"failed_to_start" :True } 184tail = (ROOT / "server.err" ).read_text (encoding = "utf-8" ,errors = "replace" )[- 400 :] 185f"AB { arm } : FAILED TO START | { tail . splitlines ()[ - 1 ] if tail . strip () else '' } " ,flush = True ) 186else : 187rec = measure (arm ) 188med = lambda v :round (statistics .median ([x for x in v if x ]),1 )if any (v )else None # noqa: E731 189f"AB { arm } : en { med ( rec [ 'en' ]) } uk { med ( rec [ 'uk' ]) } code { med ( rec [ 'code' ]) } tok/s | read 8K " 190f" { rec [ 'read8k' ] } 30K { rec [ 'read30k' ] } tok/s | slots { rec . get ( 'expert_slots' ) } free " 191f" { rec . get ( 'vram_free_mib' ) } MiB | drafts { rec [ 'draft_accept' ] } " ,flush = True ) 192if ARMS [arm ].get ("par" ):# several requests at once against this arm's server: par.py's PAR lines 193subprocess .run ([R .PY ,str (HERE / "par.py" ),* map (str ,ARMS [arm ]["par" ])],cwd = HERE ) 194if ARMS [arm ].get ("quality" ):# the small correctness suites (strata_eval2.py), reasoning off 195res = f"results2- { arm } .json" 196with (HERE / f"eval2- { arm } .log" ).open ("w" ,encoding = "utf-8" )as out : 197subprocess .run ([R .PY ,str (HERE / "strata_eval2.py" ),"hard" ,"js" ,"sql" ,"regex" ],cwd = HERE , 198stdout = out ,stderr = subprocess .STDOUT , 199env = {** os .environ ,"EFFORTS" :"none" ,"RESULTS2" :res ,"PYTHONIOENCODING" :"utf-8" }) 200q = json .loads ((HERE / res ).read_text (encoding = "utf-8" )) 201failed = [x .get ("task" )or x .get ("q" )or x .get ("what" )for k in QSETS for x in q [k ]if not x .get ("pass" )] 202secs = [x ["wall" ]for x in q ["hard" ]if x .get ("wall" )] 203f"QUAL { arm } : " + ", " .join (f" { k } { sum ( 1 for x in q [ k ] if x . get ( 'pass' )) } / { len ( q [ k ]) } " 204for k in QSETS )+ 205f" | hard tasks { min ( secs , default = 0 ) } - { max ( secs , default = 0 ) } s | failed: { failed } " ,flush = True ) 206with (HERE / "ab.jsonl" ).open ("a" ,encoding = "utf-8" )as f : 207f .write (json .dumps (rec ,ensure_ascii = False )+ "\n" ) 208if "--no-restore" in sys .argv :# another ab.py run follows at once 209return 210start ("base" )# leave the default configuration running 211"AB done; base configuration restored" ,flush = True ) 212 213 214if __name__ == "__main__" : 215main ()