okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0bc4a70f
main
1#!/usr/bin/env python3 2"""Small load generator for the OpenAI-compatible server: C clients at once, each a different prompt. 3 4python3 tools/serve_load.py http://127.0.0.1:8080 --clients 1,2,4,8 --rounds 3 --max-tokens 256 5 6For every client count it sends C streamed chat requests at the same moment (each prompt starts with its own nonce, so 7the prompt cache cannot help), and reports per round and as medians: total tokens/s (all generated tokens over the 8wall time of the burst), per-request tokens/s, time to first token (p50 / p95 over all requests of that count), and 9the request latency (p50 / p95). With --save DIR it writes every answer, so a later run can be compared byte for 10byte with `--compare DIR` (greedy answers of a request must not depend on who else ran). 11 12Standard library only. The prompts are fixed texts, so two runs of the tool send the same requests. 13""" 14import argparse ,json ,os ,statistics ,sys ,threading ,time ,urllib .request 15 16TOPICS = [ 17"the history of lighthouses and how their lenses worked" , 18"how a mechanical watch keeps time" , 19"why bridges are built as arches and as suspension spans" , 20"the water cycle and what a drought does to a river valley" , 21"how bread rises, from yeast to crust" , 22"the design of a medieval castle and why walls were stepped" , 23"how a transistor switches, explained for a curious teenager" , 24"the life of a honey bee colony through one year" , 25] 26 27 28def prompt_for (i :int ,words :int ,nonce :str = "" )-> str : 29topic = TOPICS [i % len (TOPICS )] 30return (f"[request { i } { nonce } ] Write a clear, well organised essay of about { words } words on { topic } . " 31f"Use plain prose, no lists." ) 32 33 34def one (url ,key ,model ,i ,words ,max_tokens ,res ,extra ,think ,nonce = "" ): 35body = {"model" :model ,"stream" :True ,"max_tokens" :max_tokens ,"temperature" :0 , 36"messages" : [{"role" :"user" ,"content" :prompt_for (i ,words ,nonce )}]} 37if not think : 38body ["reasoning_effort" ]= "none" 39body ["chat_template_kwargs" ]= {"enable_thinking" :False } 40body .update (extra ) 41req = urllib .request .Request (url + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 42headers = {"Content-Type" :"application/json" , 43** ({"Authorization" :"Bearer " + key }if key else {})}) 44t0 = time .perf_counter () 45first ,n ,text = None ,0 , [] 46err = None 47try : 48with urllib .request .urlopen (req ,timeout = 900 )as r : 49for raw in r : 50line = raw .decode ("utf-8" ,"replace" ).strip () 51if not line .startswith ("data:" ): 52continue 53d = line [5 :].strip () 54if d == "[DONE]" : 55break 56try : 57j = json .loads (d ) 58except ValueError : 59continue 60for ch in j .get ("choices" , []): 61dl = ch .get ("delta" , {}) 62piece = (dl .get ("content" )or "" )+ (dl .get ("reasoning_content" )or "" ) 63if piece : 64if first is None : 65first = time .perf_counter ()- t0 66n += 1 # one SSE chunk = one token (the server flushes per token) 67text .append (piece ) 68if j .get ("usage" ): 69n = j ["usage" ].get ("completion_tokens" ,n ) 70except Exception as e :# noqa: BLE001 71err = repr (e ) 72res [i ]= {"first" :first ,"tokens" :n ,"total" :time .perf_counter ()- t0 ,"text" :"" .join (text ),"err" :err } 73 74 75def pct (v ,p ): 76v = sorted (v ) 77if not v : 78return float ("nan" ) 79k = (len (v )- 1 )* p 80lo ,hi = int (k ),min (int (k )+ 1 ,len (v )- 1 ) 81return v [lo ]+ (v [hi ]- v [lo ])* (k - lo ) 82 83 84def main (): 85ap = argparse .ArgumentParser () 86ap .add_argument ("url" ) 87ap .add_argument ("--clients" ,default = "1,2,4,8" ) 88ap .add_argument ("--rounds" ,type = int ,default = 3 ) 89ap .add_argument ("--max-tokens" ,type = int ,default = 256 ) 90ap .add_argument ("--words" ,type = int ,default = 800 ,help = "the essay length asked for (longer = longer prompt? no: the answer)" ) 91ap .add_argument ("--model" ,default = "strata" ) 92ap .add_argument ("--key" ,default = os .environ .get ("STRATA_KEY" ,"" )) 93ap .add_argument ("--nonce" ,default = str (int (time .time ())),help = "prefix of the per-request nonce (every round reads fresh prompts); '' = identical prompts every round; fix it to compare two runs" ) 94ap .add_argument ("--think" ,action = "store_true" ) 95ap .add_argument ("--stagger" ,type = float ,default = 0.0 ,help = "seconds between the starts of the clients of a burst" ) 96ap .add_argument ("--save" ,help = "write every answer (clients/round/request) here" ) 97ap .add_argument ("--compare" ,help = "compare every answer with the files a --save run wrote" ) 98ap .add_argument ("--json" ,help = "write the table as JSON" ) 99a = ap .parse_args () 100extra = {} 101out = [] 102bad = 0 103for c in [int (x )for x in a .clients .split ("," )]: 104rows = [] 105for rd in range (a .rounds ): 106res = {} 107th = [] 108t0 = time .perf_counter () 109for i in range (c ): 110t = threading .Thread (target = one ,args = (a .url ,a .key ,a .model ,i ,a .words ,a .max_tokens ,res ,extra ,a .think ,f" { a . nonce } - { c } - { rd } " if a .nonce else "" )) 111t .start () 112th .append (t ) 113if a .stagger : 114time .sleep (a .stagger ) 115for t in th : 116t .join () 117wall = time .perf_counter ()- t0 118toks = sum (r ["tokens" ]for r in res .values ()) 119errs = [r ["err" ]for r in res .values ()if r ["err" ]] 120firsts = [r ["first" ]for r in res .values ()if r ["first" ]is not None ] 121tot = [r ["total" ]for r in res .values ()] 122per = [r ["tokens" ]/ max (r ["total" ]- (r ["first" ]or 0 ),1e-6 )for r in res .values ()] 123rows .append ({"wall" :wall ,"toks" :toks ,"tps" :toks / wall ,"first" :firsts ,"lat" :tot ,"per" :per ,"err" :errs }) 124if a .save : 125d = os .path .join (a .save ,f"c { c } " ,f"r { rd } " ) 126os .makedirs (d ,exist_ok = True ) 127for i ,r in res .items (): 128open (os .path .join (d ,f" { i } .txt" ),"w" ,encoding = "utf-8" ).write (r ["text" ]) 129if a .compare : 130for i ,r in res .items (): 131p = os .path .join (a .compare ,f"c { c } " ,f"r { rd } " ,f" { i } .txt" ) 132if os .path .exists (p ): 133ref = open (p ,encoding = "utf-8" ).read () 134if ref != r ["text" ]: 135n = next ((k for k , (x ,y )in enumerate (zip (ref ,r ["text" ]))if x != y ),min (len (ref ),len (r ["text" ]))) 136f" DIFF c= { c } round= { rd } req= { i } : first difference at char { n } " ) 137bad += 1 138f"c= { c } round= { rd } : { toks } tokens in { wall :.1f } s = { toks / wall :.1f } tok/s total" 139+ (f" ERRORS { errs [: 2 ] } " if errs else "" ),flush = True ) 140allf = [x for r in rows for x in r ["first" ]] 141alll = [x for r in rows for x in r ["lat" ]] 142allp = [x for r in rows for x in r ["per" ]] 143s = {"clients" :c ,"total_tps" :statistics .median (r ["tps" ]for r in rows ), 144"per_req_tps" :statistics .median (allp )if allp else float ("nan" ), 145"first_p50" :pct (allf ,.5 ),"first_p95" :pct (allf ,.95 ), 146"lat_p50" :pct (alll ,.5 ),"lat_p95" :pct (alll ,.95 ),"errors" :sum (len (r ["err" ])for r in rows )} 147out .append (s ) 148"\nclients total tok/s per-req tok/s first p50/p95 (s) latency p50/p95 (s) errors" ) 149for s in out : 150f" { s [ 'clients' ]:>7 } { s [ 'total_tps' ]:>11.1f } { s [ 'per_req_tps' ]:>13.1f } " 151f" { s [ 'first_p50' ]:>7.2f } / { s [ 'first_p95' ]:<7.2f } { s [ 'lat_p50' ]:>8.2f } / { s [ 'lat_p95' ]:<8.2f } { s [ 'errors' ] } " ) 152if a .json : 153json .dump (out ,open (a .json ,"w" ),indent = 1 ) 154if a .compare : 155"compare:" ,"ALL IDENTICAL" if not bad else f" { bad } DIFFERENT" ) 156return 1 if bad else 0 157 158 159if __name__ == "__main__" : 160sys .exit (main ())