okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1#!/usr/bin/env python3 2"""Shared load harness for the parallelism program (research tool, standard library only). 3 4Wraps the OpenAI-compatible server the way tools/serve_load.py does, and adds what an SLO-capacity harness needs: 5 6* closed-loop concurrency staircases (fixed work, shared wall window incl. the final drain), 7* open-loop seeded Poisson arrivals (offered rate independent of completions; late/unfinished requests are failures), 8* token counts from the server's `usage` (completion_tokens / prompt_tokens), NEVER from SSE chunks; a request with 9no usage is marked `tokens_source: "sse"` and the run is flagged invalid, 10* per request: TTFT, TPOT, max gap between content chunks (a chunk can hold several tokens when the engine flushes 11speculative windows, so "gap" is a chunk gap), client scheduling lag, finish reason, cached prompt tokens, 12* aggregate tok/s = total committed completion tokens / ONE shared wall-clock window (first submit to last completion), 13* the workloads W1 solo, W2 short concurrent, W4 long joiner, W6 shared-prefix cohorts, 14* one JSON ledger per run (args, server status before/after, per-request records, per-level blocks). 15 16python3 tools/par_load.py http://127.0.0.1:8080 --workload w2 --conc 1,2,4,8 --rounds 3 --out run.json 17python3 tools/par_load.py URL --workload w1 --prompt-tokens 512 --max-tokens 512 --rounds 3 --out w1.json 18python3 tools/par_load.py URL --workload w4 --conc 4 --joiner-tokens 32768 --out w4.json 19python3 tools/par_load.py URL --workload w6 --conc 4 --share 0,0.5,0.9 --out w6.json 20python3 tools/par_load.py URL --workload w2 --open-rates 0.25,0.5,1 --duration 120 --slo-ttft 10 --out open.json 21 22Labelling for the paired analysis (tools/par_analyze.py): --arm A|B --pair N --label "free text". The ledger's 23`blocks` list holds one entry per (workload, level) with the headline metrics. See Desktop 30thOctober results/par/HARNESS.md. 24Prompts are deterministic from --seed and carry a unique nonce, so the prompt cache cannot help unless W6 asks for a shared prefix. 25""" 26import argparse ,http .client ,json ,os ,platform ,random ,statistics ,sys ,threading ,time ,urllib .parse ,urllib .request 27 28HARNESS_VERSION = "1.0" 29WORDS = ("time year people way day man thing woman life child world school state family student group country problem hand " 30"part place case week company system program question work government number night point home water room mother area " 31"money story fact month lot right study book eye job word business issue side kind head house service friend father " 32"power hour game line end member law car city community name president team minute idea kid body information back " 33"parent face others level office door health person art war history party result change morning reason research girl " 34"guy moment air teacher force education foot boy age policy music market sense nation plan college interest death " 35"experience effect use class control care field development role effort rate heart drug show leader light voice wife " 36"police mind price report decision son view relationship town road arm difference value building action model season " 37"society tax director position player record paper space ground form event official matter center couple site project " 38"activity star table need court oil situation cost industry figure street image phone data picture practice piece " 39"land product doctor wall patient worker news test movie north love support technology step baby computer type " 40"attention film tree source organization hair window culture chance brother energy period course summer plant" ).split () 41TOPICS = ["the history of lighthouses" ,"how a mechanical watch keeps time" ,"why bridges are built as arches" , 42"the water cycle and droughts" ,"how bread rises" ,"the design of a medieval castle" , 43"how a transistor switches" ,"the life of a honey bee colony" ] 44 45 46# ----------------------------------------------------------------------------------------------------------- prompts 47class Prompter : 48"""Deterministic filler text of a target token count. The words-per-token ratio is calibrated once against the 49server's own usage.prompt_tokens (a max_tokens=1 probe), so the target counts tokens after the real template.""" 50 51def __init__ (self ,url ,key ,model ,seed ,think ,calib = None ): 52self .url ,self .key ,self .model ,self .seed ,self .think = url ,key ,model ,seed ,think 53self .tok_per_word = (calib or {}).get ("tok_per_word" ) 54self .overhead = (calib or {}).get ("overhead" ,40 ) 55self .calib = calib or {} 56 57def words (self ,n ,rng ): 58return " " .join (rng .choice (WORDS )for _ in range (n )) 59 60def body_text (self ,key ,n_words ): 61return self .words (n_words ,random .Random (f" { self . seed } / { key } " )) 62 63def calibrate (self ): 64if self .tok_per_word : 65return 66n = 1500 67text = "[calibration] " + self .body_text ("calib" ,n )+ "\nSay ok." 68u = chat_once (self .url ,self .key ,self .model ,text ,1 ,self .think ) 69pt = u .get ("usage" , {}).get ("prompt_tokens" ) 70if not pt : 71self .tok_per_word ,self .overhead = 1.3 ,40 # server gave no usage: a guess, the ledger says so 72self .calib = {"tok_per_word" :1.3 ,"overhead" :40 ,"guess" :True } 73return 74# prompt = template overhead (about 25-40 tokens) + n words; assume the overhead is the same as the tail 75self .overhead = 40 76self .tok_per_word = max (0.5 , (pt - self .overhead )/ n ) 77self .calib = {"tok_per_word" :self .tok_per_word ,"overhead" :self .overhead ,"probe_prompt_tokens" :pt ,"probe_words" :n } 78 79def make (self ,key ,target_tokens ,prefix = None ,share = 0.0 ,tail = "Now write a long, detailed essay about " ): 80"""A prompt of ~target_tokens. With prefix (a stable string) and share: the first share*target tokens are 81the prefix's words (the same text for the whole cohort), the rest is unique to `key`.""" 82self .calibrate () 83nw = max (8 ,int ((target_tokens - self .overhead )/ self .tok_per_word )) 84topic = TOPICS [hash_int (key )% len (TOPICS )] 85nonce = f"[req { key } ] " 86if prefix is not None and share > 0 : 87ns = int (nw * share ) 88pre = self .body_text ("prefix/" + prefix ,ns ) 89rest = self .body_text (key ,nw - ns ) 90return pre + "\n" + nonce + rest + f"\n { tail } { topic } ." 91return nonce + self .body_text (key ,nw )+ f"\n { tail } { topic } ." 92 93 94def hash_int (s ): 95h = 1469598103934665603 96for ch in s .encode (): 97h = ((h ^ ch )* 1099511628211 )& 0xFFFFFFFFFFFFFFFF 98return h 99 100 101# ------------------------------------------------------------------------------------------------------------ request 102def _conn (url ): 103u = urllib .parse .urlparse (url ) 104cls = http .client .HTTPSConnection if u .scheme == "https" else http .client .HTTPConnection 105return cls (u .hostname ,u .port or (443 if u .scheme == "https" else 80 ),timeout = 1800 ),u .path .rstrip ("/" ) 106 107 108def _body (model ,text ,max_tokens ,think ,stream ,extra = None ): 109b = {"model" :model ,"stream" :stream ,"max_tokens" :max_tokens ,"temperature" :0 , 110"messages" : [{"role" :"user" ,"content" :text }]} 111if stream : 112b ["stream_options" ]= {"include_usage" :True } 113if not think : 114b ["reasoning_effort" ]= "none" 115b ["chat_template_kwargs" ]= {"enable_thinking" :False } 116if extra : 117b .update (extra ) 118return b 119 120 121def chat_once (url ,key ,model ,text ,max_tokens ,think ): 122c ,base = _conn (url ) 123h = {"Content-Type" :"application/json" ,** ({"Authorization" :"Bearer " + key }if key else {})} 124c .request ("POST" ,base + "/v1/chat/completions" ,json .dumps (_body (model ,text ,max_tokens ,think ,False )),h ) 125r = c .getresponse () 126d = json .loads (r .read ()or b"{}" ) 127c .close () 128return d 129 130 131def stream_request (url ,key ,model ,text ,max_tokens ,think ,sched_t0 ,extra = None ,keep_times = False ,keep_text = False ): 132"""One streamed chat request. Times are seconds on the perf_counter clock of this process; the record also 133carries them relative to the run start (t_rel_*) by the caller.""" 134rec = {"t_sched" :sched_t0 ,"t_send" :None ,"t_first" :None ,"t_last" :None ,"t_end" :None ,"completion_tokens" :None , 135"prompt_tokens" :None ,"cached_tokens" :0 ,"finish" :None ,"tokens_source" :None ,"chunks" :0 ,"max_gap" :0.0 , 136"gaps_ge1s" :0 ,"err" :None ,"timings" :None ,"reasoning_chars" :0 ,"content_chars" :0 } 137times = []if keep_times else None 138texts = []if keep_text else None 139rec ["t_send" ]= time .perf_counter () 140last = None 141sse_tokens = 0 142try : 143c ,base = _conn (url ) 144h = {"Content-Type" :"application/json" ,** ({"Authorization" :"Bearer " + key }if key else {})} 145c .request ("POST" ,base + "/v1/chat/completions" ,json .dumps (_body (model ,text ,max_tokens ,think ,True ,extra )),h ) 146r = c .getresponse () 147if r .status != 200 : 148rec ["err" ]= f"http { r . status } : { r . read ( 300 ). decode ( 'utf-8' , 'replace' ) } " 149else : 150while True : 151raw = r .readline () 152if not raw : 153break 154line = raw .decode ("utf-8" ,"replace" ).strip () 155if not line .startswith ("data:" ): 156continue 157d = line [5 :].strip () 158if d == "[DONE]" : 159break 160try : 161j = json .loads (d ) 162except ValueError : 163continue 164now = time .perf_counter () 165if j .get ("error" ): 166rec ["err" ]= str (j ["error" ])[:300 ] 167for ch in j .get ("choices" , []): 168dl = ch .get ("delta" , {}) 169a ,b = dl .get ("content" )or "" ,dl .get ("reasoning_content" )or "" 170if a or b : 171if rec ["t_first" ]is None : 172rec ["t_first" ]= now 173elif last is not None : 174g = now - last 175if g > rec ["max_gap" ]: 176rec ["max_gap" ]= g 177if g >= 1.0 : 178rec ["gaps_ge1s" ]+= 1 179last = now 180rec ["t_last" ]= now 181rec ["chunks" ]+= 1 182sse_tokens += 1 183rec ["content_chars" ]+= len (a ) 184if texts is not None : 185texts .append (a + b ) 186rec ["reasoning_chars" ]+= len (b ) 187if times is not None : 188times .append (now ) 189if ch .get ("finish_reason" ): 190rec ["finish" ]= ch ["finish_reason" ] 191u = j .get ("usage" ) 192if u : 193rec ["completion_tokens" ]= u .get ("completion_tokens" ) 194rec ["prompt_tokens" ]= u .get ("prompt_tokens" ) 195rec ["cached_tokens" ]= (u .get ("prompt_tokens_details" )or {}).get ("cached_tokens" ,0 )or 0 196rec ["tokens_source" ]= "usage" 197if j .get ("timings" ): 198rec ["timings" ]= j ["timings" ] 199c .close () 200except Exception as e :# noqa: BLE001 201rec ["err" ]= repr (e )[:300 ] 202rec ["t_end" ]= time .perf_counter () 203if rec ["completion_tokens" ]is None : 204rec ["completion_tokens" ]= sse_tokens 205rec ["tokens_source" ]= "sse" # NOT a valid token count; the ledger marks the run invalid 206if times is not None : 207rec ["chunk_times" ]= times 208if texts is not None : 209rec ["text" ]= "" .join (texts ) 210return rec 211 212 213def finish_record (rec ,t0 ): 214"""Derived per-request metrics, and times relative to the run start.""" 215ttft = rec ["t_first" ]- rec ["t_send" ]if rec ["t_first" ]is not None else None 216n = rec ["completion_tokens" ]or 0 217tpot = (rec ["t_last" ]- rec ["t_first" ])/ (n - 1 )if (ttft is not None and n > 1 and rec ["t_last" ]is not None )else None 218out = {k :rec [k ]for k in ("completion_tokens" ,"prompt_tokens" ,"cached_tokens" ,"finish" ,"tokens_source" ,"chunks" ,"max_gap" , 219"gaps_ge1s" ,"err" ,"timings" ,"reasoning_chars" ,"content_chars" )} 220out .update ({"t_sched" :rec ["t_sched" ]- t0 ,"t_send" :rec ["t_send" ]- t0 ,"t_end" :rec ["t_end" ]- t0 , 221"t_first" : (rec ["t_first" ]- t0 )if rec ["t_first" ]is not None else None , 222"lag" :rec ["t_send" ]- rec ["t_sched" ],"ttft" :ttft ,"tpot" :tpot ,"latency" :rec ["t_end" ]- rec ["t_send" ]}) 223if "text" in rec : 224out ["text" ]= rec ["text" ] 225if "chunk_times" in rec : 226out ["chunk_t" ]= [round (x - t0 ,4 )for x in rec ["chunk_times" ]] 227return out 228 229 230# --------------------------------------------------------------------------------------------------------- aggregates 231def pct (v ,p ): 232v = sorted (x for x in v if x is not None ) 233if not v : 234return None 235k = (len (v )- 1 )* p 236lo = int (k ) 237hi = min (lo + 1 ,len (v )- 1 ) 238return v [lo ]+ (v [hi ]- v [lo ])* (k - lo ) 239 240 241def aggregate (recs ,window_s ,slo = None ): 242"""Level metrics. window_s = one shared wall window for all requests (first submit to last completion).""" 243ok = [r for r in recs if not r ["err" ]] 244toks = sum (r ["completion_tokens" ]or 0 for r in ok ) 245agg = {"requests" :len (recs ),"errors" :len (recs )- len (ok ),"window_s" :window_s ,"tokens" :toks , 246"agg_tps" :toks / window_s if window_s > 0 else None , 247"prompt_tokens" :sum (r ["prompt_tokens" ]or 0 for r in ok ), 248"invalid_token_source" :sum (1 for r in recs if r ["tokens_source" ]!= "usage" ), 249"length_stops" :sum (1 for r in ok if r ["finish" ]== "length" ),"early_stops" :sum (1 for r in ok if r ["finish" ]== "stop" )} 250for k in ("ttft" ,"tpot" ,"max_gap" ,"latency" ,"lag" ): 251v = [r [k ]for r in ok ] 252agg [k + "_p50" ],agg [k + "_p95" ],agg [k + "_max" ]= pct (v ,.5 ),pct (v ,.95 ), (max (x for x in v if x is not None )if any (x is not None for x in v )else None ) 253per = [(r ["completion_tokens" ]- 1 )/ (r ["t_end" ]- r ["t_first" ])for r in ok 254if r ["t_first" ]is not None and (r ["completion_tokens" ]or 0 )> 1 and r ["t_end" ]> r ["t_first" ]] 255agg ["per_req_tps_p50" ]= pct (per ,.5 ) 256if slo : 257good = [r for r in ok if (slo .get ("ttft" )is None or (r ["ttft" ]is not None and r ["ttft" ]<= slo ["ttft" ])) 258and (slo .get ("gap" )is None or r ["max_gap" ]<= slo ["gap" ])] 259agg ["slo" ]= slo 260agg ["slo_pass" ]= len (good ) 261agg ["goodput_tps" ]= sum (r ["completion_tokens" ]or 0 for r in good )/ window_s if window_s > 0 else None 262return agg 263 264 265# --------------------------------------------------------------------------------------------------------- runners 266class Ctx : 267def __init__ (self ,a ,prompter ): 268self .a ,self .p = a ,prompter 269 270 271def closed_loop (ctx ,level ,n_requests ,make_job ,label ): 272"""level concurrent clients pull jobs 0..n_requests-1 from one queue; the window is first submit -> last end.""" 273a = ctx .a 274jobs = list (range (n_requests )) 275lock = threading .Lock () 276recs = [None ]* n_requests 277t0 = time .perf_counter () 278 279def worker (): 280while True : 281with lock : 282if not jobs : 283return 284i = jobs .pop (0 ) 285text ,mt ,extra = make_job (i ) 286recs [i ]= stream_request (a .url ,a .key ,a .model ,text ,mt ,a .think ,time .perf_counter (),extra ,a .keep_times ,a .keep_text ) 287 288th = [threading .Thread (target = worker )for _ in range (level )] 289for t in th : 290t .start () 291for t in th : 292t .join () 293t1 = max (r ["t_end" ]for r in recs ) 294fr = [finish_record (r ,t0 )for r in recs ] 295return fr ,t1 - t0 296 297 298def run_closed (ctx ,wl ,levels ): 299a = ctx .a 300blocks ,allreq = [], [] 301for c in levels : 302n = max (c * a .rounds ,a .min_requests ) 303tag = f" { a . nonce } - { wl } -c { c } " 304 305def make_job (i ,c = c ,tag = tag ): 306return ctx .p .make (f" { tag } - { i } " ,a .prompt_tokens ),a .max_tokens ,None 307 308if a .warm_requests :# warmup outside the measured window 309for w in range (a .warm_requests ): 310stream_request (a .url ,a .key ,a .model ,ctx .p .make (f" { tag } -warm { w } " ,a .prompt_tokens ),min (a .max_tokens ,64 ),a .think ,time .perf_counter ()) 311fr ,wall = closed_loop (ctx ,c ,n ,make_job ,tag ) 312agg = aggregate (fr ,wall ) 313agg .update ({"workload" :wl ,"level" :c ,"mode" :"closed" ,"prompt_target" :a .prompt_tokens ,"max_tokens" :a .max_tokens }) 314blocks .append (agg ) 315for i ,r in enumerate (fr ): 316r .update ({"workload" :wl ,"level" :c ,"idx" :i }) 317allreq += fr 318f" { wl } c= { c } : { agg [ 'tokens' ] } tokens / { wall :.1f } s = { agg [ 'agg_tps' ]:.1f } tok/s ttft p50/p95 " 319f" { fmt ( agg [ 'ttft_p50' ]) } / { fmt ( agg [ 'ttft_p95' ]) } tpot p50 { fmt ( agg [ 'tpot_p50' ], 4 ) } max_gap p95 { fmt ( agg [ 'max_gap_p95' ]) } " 320f" err { agg [ 'errors' ] } " ,flush = True ) 321return blocks ,allreq 322 323 324def fmt (x ,d = 2 ): 325return "n/a" if x is None else f" { x :.{ d }f } " 326 327 328def run_w4 (ctx ,levels ): 329"""W4: c W2-style decoders running, then one long joiner (joiner_tokens) arrives joiner_at seconds after they start.""" 330a = ctx .a 331blocks ,allreq = [], [] 332for c in levels : 333for rd in range (a .rounds ): 334tag = f" { a . nonce } -w4-c { c } -r { rd } " 335res = {} 336t0 = time .perf_counter () 337 338def dec (i ): 339res [("d" ,i )]= stream_request (a .url ,a .key ,a .model ,ctx .p .make (f" { tag } -d { i } " ,a .prompt_tokens ),a .decoder_tokens ,a .think ,time .perf_counter (),None ,a .keep_times or True ) 340 341def joiner (): 342time .sleep (a .joiner_at ) 343res [("j" ,0 )]= stream_request (a .url ,a .key ,a .model ,ctx .p .make (f" { tag } -j" ,a .joiner_tokens ),a .joiner_out ,a .think ,time .perf_counter (),None ,True ) 344 345th = [threading .Thread (target = dec ,args = (i ,))for i in range (c )]+ [threading .Thread (target = joiner )] 346for t in th : 347t .start () 348for t in th : 349t .join () 350wall = max (r ["t_end" ]for r in res .values ())- t0 351fr = {k :finish_record (r ,t0 )for k ,r in res .items ()} 352j = fr [("j" ,0 )] 353ts_j = j ["t_send" ] 354te_j = j ["t_first" ]if j ["t_first" ]is not None else j ["t_end" ] 355# incumbent gaps between the joiner's submit and its first token (the interference window) 356gaps = [] 357for (k ,i ),r in fr .items (): 358if k != "d" : 359continue 360ct = [x for x in r .get ("chunk_t" , [])] 361for x ,y in zip (ct ,ct [1 :]): 362if y >= ts_j and x <= te_j + 1.0 : 363gaps .append (y - x ) 364agg = aggregate (list (fr .values ()),wall ) 365allreq += [dict (r ,workload = "w4" ,level = c ,round = rd ,role = k [0 ])for k ,r in fr .items ()] 366for r in allreq [- len (fr ):]: 367r .pop ("chunk_t" ,None )if not a .keep_times else None 368decs = [r for k ,r in fr .items ()if k [0 ]== "d" ] 369agg .update ({"workload" :"w4" ,"level" :c ,"mode" :"closed" ,"round" :rd ,"joiner_tokens" :a .joiner_tokens , 370"joiner_ttft" :j ["ttft" ],"joiner_prompt_tokens" :j ["prompt_tokens" ], 371"incumbent_gap_max_during_join" :max (gaps )if gaps else None , 372"incumbent_gap_p99_during_join" :pct (gaps ,.99 ), 373"incumbent_tps_p50" :pct ([(d ["completion_tokens" ]- 1 )/ max (d ["t_end" ]- d ["t_first" ],1e-9 )for d in decs if d ["t_first" ]is not None and d ["completion_tokens" ]and d ["completion_tokens" ]> 1 ],.5 ), 374"makespan_s" :wall }) 375blocks .append (agg ) 376f"w4 c= { c } r= { rd } : makespan { wall :.1f } s agg { fmt ( agg [ 'agg_tps' ], 1 ) } tok/s, joiner ttft { fmt ( j [ 'ttft' ]) } s ( { j [ 'prompt_tokens' ] } prompt tok), " 377f"incumbent max gap during join { fmt ( agg [ 'incumbent_gap_max_during_join' ]) } s" ,flush = True ) 378return blocks ,allreq 379 380 381def run_w6 (ctx ,levels ): 382a = ctx .a 383blocks ,allreq = [], [] 384for c in levels : 385for share in [float (x )for x in a .share .split ("," )]: 386tag = f" { a . nonce } -w6-c { c } -s { share } " 387prefix = f" { tag } " 388if a .prime and share > 0 :# prefix-warm: one priming request, not measured 389stream_request (a .url ,a .key ,a .model ,ctx .p .make (f" { tag } -prime" ,a .prompt_tokens ,prefix ,share ),8 ,a .think ,time .perf_counter ()) 390n = max (c * a .rounds ,a .min_requests ) 391 392def make_job (i ,tag = tag ,prefix = prefix ,share = share ): 393return ctx .p .make (f" { tag } - { i } " ,a .prompt_tokens ,prefix ,share ),a .max_tokens ,None 394 395fr ,wall = closed_loop (ctx ,c ,n ,make_job ,tag ) 396agg = aggregate (fr ,wall ) 397agg .update ({"workload" :"w6" ,"level" :c ,"share" :share ,"primed" :bool (a .prime ),"mode" :"closed" , 398"cached_tokens_mean" :statistics .mean (r ["cached_tokens" ]for r in fr )if fr else None }) 399blocks .append (agg ) 400for i ,r in enumerate (fr ): 401r .update ({"workload" :"w6" ,"level" :c ,"share" :share ,"idx" :i }) 402allreq += fr 403f"w6 c= { c } share= { share } : { fmt ( agg [ 'agg_tps' ], 1 ) } tok/s ttft p50 { fmt ( agg [ 'ttft_p50' ]) } cached mean { agg [ 'cached_tokens_mean' ]:.0f } " ,flush = True ) 404return blocks ,allreq 405 406 407def run_open (ctx ,wl ,rates ): 408"""Open loop: seeded exponential inter-arrival times, independent of completions. Requests still running at 409duration + drain_s are failures (kept in the ledger as unfinished).""" 410a = ctx .a 411blocks ,allreq = [], [] 412for rate in rates : 413rng = random .Random (f" { a . seed } /open/ { rate } " ) 414sched ,t = [],0.0 415while True : 416t += rng .expovariate (rate ) 417if t >= a .duration : 418break 419sched .append (t ) 420tag = f" { a . nonce } - { wl } -open { rate } " 421t0 = time .perf_counter () 422res = [None ]* len (sched ) 423th = [] 424 425def one (i ,at ): 426res [i ]= stream_request (a .url ,a .key ,a .model ,ctx .p .make (f" { tag } - { i } " ,a .prompt_tokens ),a .max_tokens ,a .think ,t0 + at ,None ,False ) 427 428def launcher (): 429for i ,at in enumerate (sched ): 430d = t0 + at - time .perf_counter () 431if d > 0 : 432time .sleep (d ) 433t_ = threading .Thread (target = one ,args = (i ,at ),daemon = True ) 434t_ .start () 435th .append (t_ ) 436 437lt = threading .Thread (target = launcher ) 438lt .start () 439lt .join () 440deadline = t0 + a .duration + a .drain_s 441for t_ in th : 442t_ .join (max (0.0 ,deadline - time .perf_counter ())) 443done = [r for r in res if r is not None and r ["t_end" ]is not None ] 444unfinished = len (sched )- len (done ) 445window = max ([r ["t_end" ]for r in done ],default = t0 )- t0 446fr = [finish_record (r ,t0 )for r in done ] 447slo = {"ttft" :a .slo_ttft ,"gap" :a .slo_gap } 448# tokens finished inside the arrival window over that window; the drain is reported separately 449inwin = [r for r in fr if r ["t_end" ]<= a .duration ] 450agg = aggregate (fr ,window ,slo ) 451agg ["tps_in_window" ]= sum (r ["completion_tokens" ]or 0 for r in inwin if not r ["err" ])/ a .duration 452agg .update ({"workload" :wl ,"mode" :"open" ,"offered_rate" :rate ,"offered_requests" :len (sched ),"unfinished" :unfinished , 453"duration" :a .duration ,"drain_s" :a .drain_s ,"achieved_rate" :len (inwin )/ a .duration , 454"slo_pass_frac" : (agg .get ("slo_pass" ,0 )/ len (sched ))if sched else None }) 455blocks .append (agg ) 456allreq += [dict (r ,workload = wl ,offered_rate = rate ,idx = i )for i ,r in enumerate (fr )] 457f" { wl } open rate= { rate } /s: offered { len ( sched ) } , done { len ( done ) } , unfinished { unfinished } , slo pass { agg . get ( 'slo_pass' ) } , " 458f"goodput { fmt ( agg . get ( 'goodput_tps' ), 1 ) } tok/s, ttft p95 { fmt ( agg [ 'ttft_p95' ]) } , lag max { fmt ( agg [ 'lag_max' ], 3 ) } " ,flush = True ) 459return blocks ,allreq 460 461 462# ------------------------------------------------------------------------------------------------------------- main 463def get_json (url ): 464try : 465with urllib .request .urlopen (url ,timeout = 10 )as r : 466return json .loads (r .read ()) 467except Exception as e :# noqa: BLE001 468return {"error" :repr (e )[:200 ]} 469 470 471def main (argv = None ): 472ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 473ap .add_argument ("url" ) 474ap .add_argument ("--workload" ,default = "w2" ,choices = ["w1" ,"w2" ,"w3" ,"w4" ,"w6" ]) 475ap .add_argument ("--conc" ,default = "1,2,4,8" ,help = "closed-loop concurrency levels (w1 forces 1)" ) 476ap .add_argument ("--rounds" ,type = int ,default = 3 ,help = "requests per client per level (a level runs conc*rounds requests)" ) 477ap .add_argument ("--min-requests" ,type = int ,default = 0 ) 478ap .add_argument ("--warm-requests" ,type = int ,default = 0 ,help = "unmeasured short requests before each level" ) 479ap .add_argument ("--prompt-tokens" ,type = int ,default = None ,help = "default: w1 512, w2 1024, w3 8192, w6 2048" ) 480ap .add_argument ("--max-tokens" ,type = int ,default = None ,help = "default: w1 512, w2 256, w3 128, w6 128" ) 481ap .add_argument ("--joiner-tokens" ,type = int ,default = 28000 ) 482ap .add_argument ("--joiner-out" ,type = int ,default = 64 ) 483ap .add_argument ("--joiner-at" ,type = float ,default = 6.0 ,help = "seconds after the decoders start" ) 484ap .add_argument ("--decoder-tokens" ,type = int ,default = 512 ) 485ap .add_argument ("--share" ,default = "0,0.5,0.9" ,help = "w6 shared-prefix fractions" ) 486ap .add_argument ("--prime" ,action = "store_true" ,help = "w6: one unmeasured request primes the prefix (prefix-warm)" ) 487ap .add_argument ("--open-rates" ,default = None ,help = "open-loop offered rates (req/s), e.g. 0.25,0.5,1" ) 488ap .add_argument ("--duration" ,type = float ,default = 120.0 ,help = "open loop: arrival window (s)" ) 489ap .add_argument ("--drain-s" ,type = float ,default = 120.0 ,help = "open loop: extra time to finish before counting failures" ) 490ap .add_argument ("--slo-ttft" ,type = float ,default = None ) 491ap .add_argument ("--slo-gap" ,type = float ,default = None ) 492ap .add_argument ("--seed" ,default = "par29" ) 493ap .add_argument ("--nonce" ,default = str (int (time .time ()))) 494ap .add_argument ("--model" ,default = "strata" ) 495ap .add_argument ("--key" ,default = os .environ .get ("STRATA_KEY" ,"" )) 496ap .add_argument ("--think" ,action = "store_true" ) 497ap .add_argument ("--keep-times" ,action = "store_true" ,help = "keep every chunk timestamp in the ledger (large)" ) 498ap .add_argument ("--keep-text" ,action = "store_true" ,help = "keep every answer's text in the ledger (identity checks)" ) 499ap .add_argument ("--calib" ,default = None ,help = "a ledger/calibration JSON to reuse the words-per-token calibration from" ) 500ap .add_argument ("--arm" ,default = "" ) 501ap .add_argument ("--pair" ,default = "" ) 502ap .add_argument ("--label" ,default = "" ) 503ap .add_argument ("--settings" ,default = None ,help = "file with the effective engine settings/provenance to embed (launcher writes it)" ) 504ap .add_argument ("--out" ,required = True ) 505a = ap .parse_args (argv ) 506a .url = a .url .rstrip ("/" ) 507d = {"w1" : (512 ,512 ),"w2" : (1024 ,256 ),"w3" : (8192 ,128 ),"w4" : (1024 ,256 ),"w6" : (2048 ,128 )}[a .workload ] 508a .prompt_tokens = a .prompt_tokens or d [0 ] 509a .max_tokens = a .max_tokens or d [1 ] 510levels = [1 ]if a .workload == "w1" else [int (x )for x in a .conc .split ("," )] 511calib = None 512if a .calib and os .path .exists (a .calib ): 513calib = json .load (open (a .calib )).get ("calibration" ) 514p = Prompter (a .url ,a .key ,a .model ,a .seed ,a .think ,calib ) 515ctx = Ctx (a ,p ) 516status0 = get_json (a .url + "/v1/status" ) 517started = time .time () 518if a .open_rates : 519blocks ,reqs = run_open (ctx ,a .workload , [float (x )for x in a .open_rates .split ("," )]) 520elif a .workload == "w4" : 521blocks ,reqs = run_w4 (ctx ,levels ) 522elif a .workload == "w6" : 523blocks ,reqs = run_w6 (ctx ,levels ) 524else : 525blocks ,reqs = run_closed (ctx ,a .workload ,levels ) 526status1 = get_json (a .url + "/v1/status" ) 527settings = None 528if a .settings and os .path .exists (a .settings ): 529settings = open (a .settings ,errors = "replace" ).read ()[:20000 ] 530for b in blocks : 531b .update ({"arm" :a .arm ,"pair" :a .pair ,"label" :a .label }) 532invalid = sum (b .get ("invalid_token_source" ,0 )for b in blocks ) 533ledger = {"harness" :"par_load" ,"version" :HARNESS_VERSION ,"started" :started ,"host" :platform .node (),"argv" :sys .argv [1 :], 534"args" : {k :v for k ,v in vars (a ).items ()if k != "key" },"calibration" :p .calib ,"valid" :invalid == 0 , 535"invalid_reason" :None if invalid == 0 else f" { invalid } requests without server usage: token counts are SSE chunks" , 536"status_before" :status0 ,"status_after" :status1 ,"settings" :settings ,"blocks" :blocks ,"requests" :reqs } 537os .makedirs (os .path .dirname (os .path .abspath (a .out )),exist_ok = True ) 538json .dump (ledger ,open (a .out ,"w" ),indent = 1 ) 539"ledger:" ,a .out ,"valid" if invalid == 0 else "INVALID (no usage)" ) 540return 0 if invalid == 0 and all (b ["errors" ]== 0 for b in blocks )else 1 541 542 543if __name__ == "__main__" : 544sys .exit (main ())