okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aebd0f34d
main
1#!/usr/bin/env python3 2"""Measure any OpenAI-compatible server the same way: decode speed and prompt (prefill) speed. 3 4Standard library only. Every request starts with a fresh nonce so no server can answer from a prompt cache. 5 6python3 bench/bench.py --url http://127.0.0.1:8080/v1 --label strata-iq3s --out bench/results/<dir> 7python3 bench/bench.py --url http://127.0.0.1:8811/v1 --label mimo-stock --extra '{"chat_template_kwargs":{"enable_thinking":false}}' 8 9Tests: 10decode short prompt, --decode-tokens tokens out (default 256): tokens/s after the first token 11prefill-N a ~N-token code prompt, 1 token out: prompt tokens / time to first token 12""" 13import argparse 14import json 15import os 16import random 17import statistics 18import sys 19import time 20import urllib .request 21 22DECODE_PROMPT = ("Write a Python function that parses an Apache access log line into a dict with ip, time, method, " 23"path, status and size. Then explain each regular expression group in two sentences." ) 24 25 26def code_corpus (n_tokens ,seed = 1234 ): 27"""Deterministic synthetic Python code, roughly n_tokens long (about 3.2 characters per token).""" 28rng = random .Random (seed ) 29words = ["user" ,"token" ,"session" ,"query" ,"cache" ,"request" ,"payload" ,"config" ,"record" ,"result" , 30"handler" ,"buffer" ,"index" ,"limit" ,"offset" ,"account" ,"secret" ,"path" ,"status" ,"retry" ] 31out ,size ,target = [],0 ,int (n_tokens * 3.2 ) 32i = 0 33while size < target : 34a ,b ,c = rng .sample (words ,3 ) 35block = (f"def { a } _ { b } _ { i } ( { c } , { a } =None):\n" 36f" \"\"\"Return the { b } for { c } .\"\"\"\n" 37f" if { a } is None:\n" 38f" { a } = load_ { a } ( { c } )\n" 39f" for k in range( { rng . randint ( 2 , 64 ) } ):\n" 40f" { c } = update_ { b } ( { c } , k, { a } )\n" 41f" return {{' { b } ': { c } , 'n': { rng . randint ( 0 , 9999 ) } }}\n\n" ) 42out .append (block ) 43size += len (block ) 44i += 1 45return "" .join (out ) 46 47 48def load_extra (value ): 49if value .startswith ("@" ): 50with open (value [1 :],encoding = "utf-8" )as f : 51return json .load (f ) 52return json .loads (value ) 53 54 55def post_stream (url ,key ,body ,timeout ): 56req = urllib .request .Request (url + "/chat/completions" ,data = json .dumps (body ).encode (),method = "POST" , 57headers = {"Content-Type" :"application/json" ,"Authorization" :f"Bearer { key } " }) 58t0 = time .perf_counter () 59t_first ,n_chunks ,usage = None ,0 ,None 60with urllib .request .urlopen (req ,timeout = timeout )as r : 61for raw in r : 62line = raw .decode ("utf-8" ,"replace" ).strip () 63if not line .startswith ("data:" ): 64continue 65data = line [5 :].strip () 66if data == "[DONE]" : 67break 68d = json .loads (data ) 69if d .get ("usage" ): 70usage = d ["usage" ] 71for ch in d .get ("choices" )or []: 72delta = ch .get ("delta" )or {} 73if delta .get ("content" )or delta .get ("reasoning_content" ): 74if t_first is None : 75t_first = time .perf_counter () 76n_chunks += 1 77t_end = time .perf_counter () 78return t0 ,t_first ,t_end ,n_chunks ,usage 79 80 81def one (args ,model ,prompt ,max_tokens ): 82nonce = f"[run { time . time_ns () } ] " 83body = {"model" :model ,"messages" : [{"role" :"user" ,"content" :nonce + prompt }],"max_tokens" :max_tokens , 84"temperature" :0 ,"stream" :True ,"stream_options" : {"include_usage" :True }} 85body .update (args .extra ) 86t0 ,t_first ,t_end ,n_chunks ,usage = post_stream (args .url ,args .key ,body ,args .timeout ) 87if t_first is None : 88if max_tokens > 1 : 89raise RuntimeError ("no tokens came back" ) 90# prefill test: the one token may be a template token with no visible text; the request still ends right 91# after the prompt is read 92t_first = t_end 93out_tokens = (usage or {}).get ("completion_tokens" )or n_chunks 94prompt_tokens = (usage or {}).get ("prompt_tokens" ) 95decode_s = t_end - t_first 96return {"ttft_s" :t_first - t0 ,"total_s" :t_end - t0 ,"prompt_tokens" :prompt_tokens , 97"completion_tokens" :out_tokens , 98"decode_tps" : (out_tokens - 1 )/ decode_s if out_tokens > 1 and decode_s > 0 else None , 99"prefill_tps" :prompt_tokens / (t_first - t0 )if prompt_tokens else None } 100 101 102def main (): 103p = argparse .ArgumentParser () 104p .add_argument ("--url" ,required = True ,help = "base URL ending in /v1" ) 105p .add_argument ("--key" ,default = os .environ .get ("BENCH_API_KEY" ,"none" )) 106p .add_argument ("--model" ,default = None ,help = "default: first id from /v1/models" ) 107p .add_argument ("--label" ,required = True ) 108p .add_argument ("--runs" ,type = int ,default = 3 ) 109p .add_argument ("--decode-tokens" ,type = int ,default = 256 ) 110p .add_argument ("--prefill" ,default = "4096,32768" ,help = "prompt sizes in tokens, comma separated; '' for none" ) 111p .add_argument ("--extra" ,type = load_extra ,default = {}, 112help = "JSON merged into every request body, or @file.json (avoids shell quoting, e.g. on Windows)" ) 113p .add_argument ("--timeout" ,type = int ,default = 1800 ) 114p .add_argument ("--out" ,default = None ,help = "directory for <label>.json" ) 115p .add_argument ("--skip-decode" ,action = "store_true" ,help = "only the prefill tests" ) 116args = p .parse_args () 117 118model = args .model 119if not model : 120req = urllib .request .Request (args .url + "/models" ,headers = {"Authorization" :f"Bearer { args . key } " }) 121model = json .load (urllib .request .urlopen (req ,timeout = 60 ))["data" ][0 ]["id" ] 122 123tests = []if args .skip_decode else [("decode" ,DECODE_PROMPT ,args .decode_tokens )] 124tests += [(f"prefill- { n } " ,"Summarize what this code does.\n\n" + code_corpus (n ),1 ) 125for n in (int (x )for x in args .prefill .split ("," )if x )] 126 127f"# { args . label } : { model } at { args . url } " ,file = sys .stderr ) 128one (args ,model ,"Say hi." ,8 )# warm-up, not counted 129result = {"label" :args .label ,"model" :model ,"url" :args .url ,"extra" :args .extra ,"runs" :args .runs , 130"date" :time .strftime ("%Y-%m-%dT%H:%M:%S%z" ),"tests" : {}} 131for name ,prompt ,max_tokens in tests : 132rows = [] 133for i in range (args .runs ): 134r = one (args ,model ,prompt ,max_tokens ) 135rows .append (r ) 136f" { name } run { i + 1 } : " + ", " .join (f" { k } = { v :.2f } " if isinstance (v ,float )else f" { k } = { v } " 137for k ,v in r .items ()),file = sys .stderr ) 138key = "decode_tps" if name == "decode" else "prefill_tps" 139vals = [r [key ]for r in rows if r [key ]] 140result ["tests" ][name ]= {"median_" + key :statistics .median (vals )if vals else None ,"runs" :rows } 141f" { args . label } \t { name } \t { key } = { result [ 'tests' ][ name ][ 'median_' + key ]:.1f } " if vals else 142f" { args . label } \t { name } \tno value" ) 143if args .out : 144os .makedirs (args .out ,exist_ok = True ) 145with open (os .path .join (args .out ,f" { args . label } .json" ),"w" )as f : 146json .dump (result ,f ,indent = 2 ) 147 148 149if __name__ == "__main__" : 150main ()