okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1"""Decoding streams while long cold prompts join: how smooth the streams stay, and what the joining prompt pays. 2 3Runs against a running `serve/server.py` (OpenAI API). N streams decode long greedy answers (thinking off); after a 4delay one or two long cold prompts join. Every streamed token's arrival is timed on the client. Reported per scenario: 5 6joiner_ttft_s the joining prompt's time to first token 7worst_max_gap_s the longest time any decoding stream received no token during the join window 8mean_stalled_s per stream, the sum of gaps above 0.5 s during the window (mean over the streams) 9stream_tokens_during_join tokens the decoding streams received from the first joiner's arrival to the last 10joiner's first token + 1 s 11aggregate_tok_s the streams' tokens / the run's wall time (throughput of the whole run) 12 13Two scenarios without decoding streams (#1504's test): `followup` reads a cold 45K prompt alone and sends a short 14prompt 1 s later (followup_ttft_s: how long the short one waits behind the read; long_ttft_s: what the read pays); 15`read_alone` is the same read without the follow-up (what the read costs by itself). 16 17The prompts are synthetic: the joiners are text from this repository's own files (src, include, serve, tools, docs), so 18they route to most experts the way real code and tool output do; a joiner never repeats an earlier prompt (the 19conversation cache would turn it into a warm read). `--determinism` instead sends fixed greedy prompts and prints the 20SHA-256 of each answer (to compare two builds' output tokens). 21 22python tools/piped_read_join_bench.py --port 8080 --out join.json 23python tools/piped_read_join_bench.py --port 8080 --scenarios two_joiners,followup --repeat 3 24python tools/piped_read_join_bench.py --port 8080 --determinism 25""" 26import argparse 27import hashlib 28import http .client 29import json 30import statistics 31import threading 32import time 33from pathlib import Path 34 35ROOT = Path (__file__ ).resolve ().parent .parent 36CODING = ["Write a Python function that parses an INI file into nested dicts, with tests. Explain each step." , 37"Implement a thread-safe LRU cache in C++ with a short explanation of the design and its complexity." , 38"Explain, with code, how to stream a large CSV file in Go and aggregate per-key statistics." , 39"Write a TypeScript debounce and throttle pair with tests and explain where each one fits." ] 40DETERMINISM = ["Count from 1 to 40, comma separated." ,"List the planets of the solar system in order, one per line." , 41"Write the first 12 Fibonacci numbers." ,"Explain in three sentences what a hash map is." , 42'Translate "good morning, how are you" into French, German and Spanish.' , 43"Write a haiku about compilers." ] 44# name -> the joins (delay s, size in K tokens) beside decoding streams, or (size, follow-up delay s) with none decoding 45SCENARIOS = {"cold32k" : [(6 ,32 )],"cold64k" : [(6 ,64 )],"two_joiners" : [(6 ,64 ), (12 ,32 )], 46"followup" : (45 ,1.0 ),"read_alone" : (45 ,0 )} 47_FILES = [] 48 49 50def corpus (chars ,offset ): 51"""About `chars` characters of this repository's own files, from the `offset`-th file on (at most 60,000 each).""" 52if not _FILES : 53for sub ,pat in (("src" ,"*.cpp" ), ("src" ,"*.cu" ), ("include" ,"*.hpp" ), ("serve" ,"*.py" ), ("tools" ,"*.py" ), 54 ("docs" ,"*.md" )): 55_FILES .extend (sorted ((ROOT / sub ).rglob (pat ))) 56parts ,n ,i = [],0 ,offset 57while n < chars : 58p = _FILES [i % len (_FILES )] 59i += 1 60text = p .read_text (encoding = "utf-8" ,errors = "replace" )[:60000 ] 61parts .append ("=== %s ===\n%s\n" % (p .relative_to (ROOT ).as_posix (),text )) 62n += len (parts [- 1 ]) 63return "" .join (parts )[:chars ] 64 65 66def request (content ,max_tokens ,model ): 67"""One streamed greedy chat request with thinking off.""" 68return json .dumps ({"model" :model ,"messages" : [{"role" :"user" ,"content" :content }],"temperature" :0 , 69"max_tokens" :max_tokens ,"stream" :True ,"stream_options" : {"include_usage" :True }, 70"chat_template_kwargs" : {"enable_thinking" :False }}).encode () 71 72 73def stream (port ,raw ,timeout = 1800 ): 74"""-> (token arrival times, text, usage, the time the request was sent)""" 75c = http .client .HTTPConnection ("127.0.0.1" ,port ,timeout = timeout ) 76ts ,text ,usage = [], [],None 77t0 = time .monotonic () 78c .request ("POST" ,"/v1/chat/completions" ,raw , {"Content-Type" :"application/json" ,"Connection" :"close" }) 79r = c .getresponse () 80if r .status != 200 : 81raise RuntimeError ("HTTP %d" % r .status ) 82while True : 83line = r .readline (1 << 20 ) 84if not line : 85break 86if not line .startswith (b"data:" ): 87continue 88data = line [5 :].strip () 89if data == b"[DONE]" : 90break 91item = json .loads (data ) 92if item .get ("usage" ): 93usage = item ["usage" ] 94for ch in item .get ("choices" )or []: 95d = (ch .get ("delta" )or {}).get ("content" ) 96if d : 97ts .append (time .monotonic ()) 98text .append (d ) 99c .close () 100return ts ,"" .join (text ),usage or {},t0 101 102 103def pct (v ,p ): 104v = sorted (v ) 105return v [min (len (v )- 1 ,max (0 ,int (round (p / 100 * (len (v )- 1 )))))]if v else 0 106 107 108def smooth (ts ,lo ,hi ): 109"""One stream's arrivals in [lo, hi]: tokens, the longest and p99 gap, and the time in gaps above 0.5 s.""" 110inside = [t for t in ts if lo <= t <= hi ] 111gaps = [b - a for a ,b in zip (ts ,ts [1 :])if b >= lo and a <= hi ] 112return {"tokens" :len (inside ),"max_gap_s" :round (max (gaps or [0 ]),3 ),"p99_gap_s" :round (pct (gaps ,99 ),3 ), 113"stalled_s" :round (sum (g for g in gaps if g > 0.5 ),3 )} 114 115 116def scenario (port ,model ,name ,n ,joins ,max_tokens ,tag ): 117"""`n` streams decode; each join (delay s, size in K tokens) then sends a cold prompt of this repository's text.""" 118events ,joined = {}, {} 119 120def decode (i ): 121content = "Stream %s-%s-%d. %s" % (tag ,name ,i ,CODING [i % len (CODING )]) 122events [i ]= stream (port ,request (content ,max_tokens ,model ))[0 ] 123 124def join (k ,delay ,size ): 125time .sleep (delay ) 126text = corpus (int (size * 1024 * 3.3 ),7 * size + k + 131 * len (name )) 127content = "Join %s-%s-%d.\n%s\nName the file that defines the class above in one line." % (tag ,name ,k ,text ) 128ts ,_ ,usage ,t0 = stream (port ,request (content ,64 ,model )) 129joined [k ]= {"sent" :t0 ,"first" :ts [0 ]if ts else None ,"usage" :usage } 130 131t0 = time .monotonic () 132threads = [threading .Thread (target = decode ,args = (i ,))for i in range (n )] 133threads += [threading .Thread (target = join ,args = (k ,d ,size ))for k , (d ,size )in enumerate (joins )] 134for t in threads : 135t .start () 136for t in threads : 137t .join () 138lo = min (v ["sent" ]for v in joined .values ()) 139hi = max (v ["first" ]for v in joined .values ())+ 1.0 140per = [smooth (ts ,lo ,hi )for _ ,ts in sorted (events .items ())] 141ends = [ts [- 1 ]for ts in events .values ()if ts ] 142joins_in_order = [v for _ ,v in sorted (joined .items ())] 143return {"joiner_ttft_s" : [round (v ["first" ]- v ["sent" ],3 )for v in joins_in_order ], 144"joiner_prompt_tokens" : [v ["usage" ].get ("prompt_tokens" )for v in joins_in_order ], 145"joiner_cached_tokens" : [(v ["usage" ].get ("prompt_tokens_details" )or {}).get ("cached_tokens" ) 146for v in joins_in_order ], 147"worst_max_gap_s" :max (p ["max_gap_s" ]for p in per ), 148"mean_stalled_s" :round (statistics .mean (p ["stalled_s" ]for p in per ),3 ), 149"stream_tokens_during_join" :sum (p ["tokens" ]for p in per ), 150"aggregate_tok_s" :round (sum (len (t )for t in events .values ())/ (max (ends )- t0 ),1 ), 151"streams" :per } 152 153 154def alone (port ,model ,name ,size ,follow ,tag ): 155"""A cold prompt of `size` K tokens with nothing decoding; with `follow`, a short prompt `follow` s after it.""" 156got = {} 157 158def long_read (): 159text = corpus (int (size * 1024 * 3.3 ),11 * size + 131 * len (name )) 160content = "Read %s-%s.\n%s\nName the file that defines the class above in one line." % (tag ,name ,text ) 161ts ,_ ,usage ,t0 = stream (port ,request (content ,64 ,model )) 162got ["long" ]= (t0 ,ts [0 ]if ts else None ,usage ) 163 164def short (): 165time .sleep (follow ) 166content = "Follow-up %s-%s: what is 17 x 23? Reply with the number only." % (tag ,name ) 167ts ,_ ,usage ,t0 = stream (port ,request (content ,16 ,model )) 168got ["short" ]= (t0 ,ts [0 ]if ts else None ,usage ) 169 170threads = [threading .Thread (target = long_read )]+ ([threading .Thread (target = short )]if follow else []) 171for t in threads : 172t .start () 173for t in threads : 174t .join () 175out = {"long_ttft_s" :round (got ["long" ][1 ]- got ["long" ][0 ],3 ), 176"long_prompt_tokens" :got ["long" ][2 ].get ("prompt_tokens" )} 177if follow : 178out ["followup_ttft_s" ]= round (got ["short" ][1 ]- got ["short" ][0 ],3 ) 179out ["followup_prompt_tokens" ]= got ["short" ][2 ].get ("prompt_tokens" ) 180return out 181 182 183def main (): 184ap = argparse .ArgumentParser () 185ap .add_argument ("--port" ,type = int ,default = 8080 ) 186ap .add_argument ("--model" ,default = None ,help = "default: the server's own model id" ) 187ap .add_argument ("--streams" ,type = int ,default = 4 ) 188ap .add_argument ("--max-tokens" ,type = int ,default = 2048 ) 189ap .add_argument ("--scenarios" ,default = "cold32k,cold64k,two_joiners" , 190help = "comma-separated: " + ", " .join (SCENARIOS )) 191ap .add_argument ("--repeat" ,type = int ,default = 1 ,help = "runs of each scenario (each with its own cold prompts)" ) 192ap .add_argument ("--out" ) 193ap .add_argument ("--determinism" ,action = "store_true" ) 194a = ap .parse_args () 195tag = time .strftime ("%H%M%S" ) 196if a .model is None : 197c = http .client .HTTPConnection ("127.0.0.1" ,a .port ,timeout = 30 ) 198c .request ("GET" ,"/v1/models" ) 199a .model = json .loads (c .getresponse ().read ())["data" ][0 ]["id" ] 200c .close () 201if a .determinism : 202rows = [] 203for p in DETERMINISM : 204_ ,text ,usage ,_ = stream (a .port ,request (p ,128 ,a .model )) 205rows .append ({"prompt_sha256" :hashlib .sha256 (p .encode ()).hexdigest ()[:12 ], 206"answer_sha256" :hashlib .sha256 (text .encode ()).hexdigest (), 207"tokens" :usage .get ("completion_tokens" )}) 208json .dumps (rows ,indent = 1 )) 209return 210out = {} 211for rep in range (a .repeat ): 212for name in a .scenarios .split ("," ): 213spec ,run_tag = SCENARIOS [name ],"%s.%d" % (tag ,rep ) 214key = name if a .repeat == 1 else "%s#%d" % (name ,rep + 1 ) 215if isinstance (spec ,tuple ): 216out [key ]= alone (a .port ,a .model ,name ,spec [0 ],spec [1 ],run_tag ) 217else : 218out [key ]= scenario (a .port ,a .model ,name ,a .streams ,spec ,a .max_tokens ,run_tag ) 219json .dumps ({"scenario" :key ,** {k :v for k ,v in out [key ].items ()if k != "streams" }}),flush = True ) 220time .sleep (3 ) 221if a .out : 222Path (a .out ).write_text (json .dumps (out ,indent = 1 )) 223 224 225if __name__ == "__main__" : 226main ()