okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
694e71170
main
1#!/usr/bin/env python3 2"""dgx_bench - the DGX Spark benchmark family for Strata (Qwen3.8-Flash-Next first). 3 4python tools/dgx_bench.py --config strata-iq3_s.json --tag base 5python tools/dgx_bench.py --config strata-iq3_s.json --tag gu-swiglu --env STRATA_GU_SWIGLU=1 6python tools/dgx_bench.py --config strata-iq3_s.json --tag base --cells 4096:0:256,4096:0.7:256 --rounds 3 7 8It starts the server on the model's own config (serve/server.py, the path setup writes), waits for it, sends the cells 9through the real HTTP API, restarts the server between arms, and writes every request plus a summary. 10 11A cell is PROMPT_TOKENS:TEMPERATURE:MAX_NEW. The default family is the one the DGX Spark guide's contract names: 12512 / 4096 / 16384 / 32768 fresh prompt tokens at temperature 0 and 0.7, with a 256-token generation cap, plus one 131024-token decode cell. Every request carries a unique nonce as its first token sequence, so the conversation cache 14cannot serve the prompt (verified: timings.cache_n must be 0, or the row is marked reused and excluded from the summary). 15 16Per request it records the client's own time to first content token (TTFT), the wall time, and the server's timings 17(prompt_n, prompt_ms, prompt_per_second, predicted_n, predicted_ms, predicted_per_second, draft counts) read from 18GET /v1/status right after the streamed answer. Medians over rounds; nothing is retried or filtered except requests 19that failed (they are kept and reported as failures). 20 21Standard library only, like tools/strata_bench.py and tools/ab_engine.py. 22""" 23from __future__import annotations 24 25import argparse 26import json 27import os 28import random 29import statistics 30import subprocess 31import sys 32import time 33import urllib .error 34import urllib .request 35from pathlib import Path 36 37ROOT = Path (__file__ ).resolve ().parents [1 ] 38DEFAULT_CELLS = "512:0:256,4096:0:256,4096:0.7:256,16384:0:256,16384:0.7:256,32768:0:256,32768:0.7:256,4096:0:1024" 39WORDS = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember ledger quartz " 40"meadow anchor violet thunder cedar marble piston ribbon cobalt falcon glacier hollow ivory juniper kernel " 41"lattice mirror nectar oasis pepper quarry raven saddle tundra umber vessel willow xenon yellow zephyr " 42"basalt cinder dune elm fjord granite heather inlet jetty kiln lagoon mesa niche opal prairie quill" ).split () 43 44 45def build_prompt (target_tokens :int ,nonce :str )-> str : 46"""A prompt of about target_tokens tokens: a unique nonce line, a word list, and a task that keeps the answer going.""" 47rng = random .Random (hash ((target_tokens ,nonce ))& 0xFFFFFFFF ) 48# ~1.35 tokens per word for this vocabulary in Qwen's tokenizer 49words = max (8 ,int (target_tokens / 1.35 )) 50body = " " .join (rng .choice (WORDS )for _ in range (words )) 51return (f"Request nonce { nonce } . Read the word list below carefully.\n\n { body } \n\n" 52f"Write a long, detailed analysis of the word list above: its sounds, its themes and its structure. " 53f"Keep writing for at least 400 words; do not stop early and do not ask questions." ) 54 55 56def post_stream (port :int ,prompt :str ,max_tokens :int ,temperature :float ,timeout :float = 3600 )-> dict : 57"""One streamed chat completion; returns the client's times and the token count.""" 58body = json .dumps ({"messages" : [{"role" :"user" ,"content" :prompt }],"max_tokens" :max_tokens , 59"temperature" :temperature ,"stream" :True , 60"chat_template_kwargs" : {"enable_thinking" :False }}).encode () 61req = urllib .request .Request (f"http://127.0.0.1: { port } /v1/chat/completions" ,data = body , 62headers = {"Content-Type" :"application/json" }) 63t0 = time .time () 64ttft = None 65n = 0 66text_len = 0 67finish = None 68with urllib .request .urlopen (req ,timeout = timeout )as r : 69for raw in r : 70line = raw .decode ("utf-8" ,"replace" ).strip () 71if not line .startswith ("data:" ): 72continue 73data = line [5 :].strip () 74if data == "[DONE]" : 75break 76try : 77obj = json .loads (data ) 78except ValueError : 79continue 80for ch in obj .get ("choices" )or []: 81d = ch .get ("delta" )or {} 82piece = d .get ("content" )or d .get ("reasoning_content" )or "" 83if piece : 84if ttft is None : 85ttft = time .time ()- t0 86text_len += len (piece ) 87if ch .get ("finish_reason" ): 88finish = ch ["finish_reason" ] 89if obj .get ("usage" ): 90n = int (obj ["usage" ].get ("completion_tokens" )or n ) 91wall = time .time ()- t0 92return {"ttft_s" :ttft ,"wall_s" :round (wall ,3 ),"stream_tokens" :n ,"chars" :text_len ,"finish" :finish } 93 94 95def last_timings (port :int )-> dict : 96try : 97with urllib .request .urlopen (f"http://127.0.0.1: { port } /v1/status" ,timeout = 10 )as r : 98st = json .loads (r .read ()) 99return st .get ("last_timings" )or {} 100except Exception : 101return {} 102 103 104def wait_ready (port :int ,proc :subprocess .Popen ,timeout :float = 3600 )-> float : 105t0 = time .time () 106while time .time ()- t0 < timeout : 107if proc .poll ()is not None : 108raise RuntimeError (f"server exited with { proc . returncode } " ) 109try : 110with urllib .request .urlopen (f"http://127.0.0.1: { port } /v1/models" ,timeout = 5 )as r : 111if r .status == 200 : 112return time .time ()- t0 113except Exception : 114pass 115time .sleep (3 ) 116raise TimeoutError ("server not ready" ) 117 118 119def calibrate (port :int ,target :int ,max_tokens :int ,temperature :float ,log )-> str : 120"""Build a prompt whose prompt_n is within ~2% of target (two probes at most).""" 121nonce = f" { random . getrandbits ( 48 ):012x } " 122prompt = build_prompt (target ,nonce ) 123for attempt in range (3 ): 124r = post_stream (port ,prompt ,8 ,0.0 ) 125t = last_timings (port ) 126got = int (t .get ("prompt_n" )or 0 ) 127log (f" calibrate { target } : prompt_n { got } " ) 128if got and abs (got - target )<= max (16 ,target // 50 ): 129return prompt 130if not got : 131break 132words = len (prompt .split ())* target / got 133rng = random .Random (target + attempt ) 134body = " " .join (rng .choice (WORDS )for _ in range (max (8 ,int (words )))) 135prompt = (f"Request nonce { nonce } . Read the word list below carefully.\n\n { body } \n\n" 136f"Write a long, detailed analysis of the word list above: its sounds, its themes and its structure. " 137f"Keep writing for at least 400 words; do not stop early and do not ask questions." ) 138return prompt 139 140 141def run_arm (cfg_path :Path ,tag :str ,cells ,rounds :int ,port :int ,env :dict ,out :Path ,warm :int , 142exe :str | None = None ,xargs :list [str ]| None = None )-> list [dict ]: 143base = json .loads (cfg_path .read_text ()) 144cfg = dict (base ) 145if exe : 146cfg ["exe" ]= exe 147if xargs : 148cfg ["args" ]= list (cfg .get ("args" )or [])+ list (xargs ) 149cfg ["port" ]= port 150cfg ["log" ]= str (out / f" { tag } .engine.log" ) 151cpath = out / f" { tag } .config.json" 152cpath .write_text (json .dumps (cfg ,indent = 1 )) 153rows :list [dict ]= [] 154meta = {"tag" :tag ,"config" :str (cfg_path ),"cells" :cells ,"rounds" :rounds ,"env" :env , 155"engine" :cfg .get ("exe" ),"args" :cfg .get ("args" ),"started" :time .strftime ("%Y-%m-%dT%H:%M:%S" )} 156 (out / f" { tag } .meta.json" ).write_text (json .dumps (meta ,indent = 1 )) 157logf = open (out / f" { tag } .jsonl" ,"a" ,encoding = "utf-8" ) 158penv = dict (os .environ ,** env ) 159for rnd in range (rounds ): 160srvlog = open (out / f" { tag } .server.log" ,"a" ,encoding = "utf-8" ) 161proc = subprocess .Popen ([sys .executable ,str (ROOT / "serve" / "server.py" ),"--engine" ,"strata" ,"--config" , 162str (cpath ),"--port" ,str (port )],cwd = str (ROOT ),env = penv , 163stdout = srvlog ,stderr = srvlog ) 164try : 165ready = wait_ready (port ,proc ) 166f"round { rnd } { tag } : ready in { ready :.0f } s" ,flush = True ) 167nonce = f" { random . getrandbits ( 48 ):012x } " 168post_stream (port ,f"Request nonce { nonce } . Say hello in one short sentence, then list five colors." ,warm ,0.0 ) 169# a 4K prompt first: with --mmap-experts the first request pages the experts in (a one-time cold cost of 170# tens of seconds); every measured cell then runs on the same warm state the fork's baselines had 171nonce = f" { random . getrandbits ( 48 ):012x } " 172post_stream (port ,build_prompt (4096 ,nonce ),8 ,0.0 ) 173prompts = {} 174for (length ,temp ,maxnew )in cells : 175key = (length ,maxnew ) 176if key not in prompts : 177prompts [key ]= calibrate (port ,length ,maxnew ,0.0 ,nonce = f" { random . getrandbits ( 48 ):012x } " 179prompt = prompts [key ] 180prompt = prompt .replace ("Request nonce " ,"Request nonce " ,1 ) 181# a fresh nonce: rewrite the first line so no prefix can be reused 182prompt = prompt .split ("\n" ,1 ) 183prompt = f"Request nonce { nonce } . Read the word list below carefully.\n" + prompt [1 ] 184r = post_stream (port ,prompt ,maxnew ,temp ) 185t = last_timings (port ) 186row = {"round" :rnd ,"arm" :tag ,"len" :length ,"temp" :temp ,"max_new" :maxnew ,** r ,** t } 187rows .append (row ) 188logf .write (json .dumps (row )+ "\n" ) 189logf .flush () 190f" { length :6d } T= { temp } n= { maxnew :4d } : prompt_n { t . get ( 'prompt_n' ) } " 191f"prompt { t . get ( 'prompt_per_second' ) } tok/s decode { t . get ( 'predicted_per_second' ) } tok/s " 192f"n { t . get ( 'predicted_n' ) } ttft { r [ 'ttft_s' ] and round ( r [ 'ttft_s' ], 2 ) } wall { r [ 'wall_s' ] } " , 193flush = True ) 194finally : 195proc .terminate () 196try : 197proc .wait (60 ) 198except subprocess .TimeoutExpired : 199proc .kill () 200time .sleep (5 ) 201logf .close () 202return rows 203 204 205def summarize (rows :list [dict ],cells )-> str : 206lines = ["| cell | n | prompt tok/s | decode tok/s | ttft s | wall s |" ,"|---|---|---|---|---|---|" ] 207for (length ,temp ,maxnew )in cells : 208sel = [r for r in rows if r ["len" ]== length and r ["temp" ]== temp and r ["max_new" ]== maxnew 209and not r .get ("cache_n" )] 210if not sel : 211lines .append (f"| { length } T= { temp } n= { maxnew } | 0 | - | - | - | - |" ) 212continue 213med = lambda k :statistics .median ([r [k ]for r in sel if r .get (k )])if any (r .get (k )for r in sel )else None 214p ,d ,ttft ,wall = med ("prompt_per_second" ),med ("predicted_per_second" ),med ("ttft_s" ),med ("wall_s" ) 215fmt = lambda v ,f = "{:.1f}" :"-" if v is None else f .format (v ) 216lines .append (f"| { length } T= { temp } n= { maxnew } | { len ( sel ) } | { fmt ( p ) } | { fmt ( d ) } | { fmt ( ttft , '{:.2f}' ) } | " 217f" { fmt ( wall , '{:.1f}' ) } |" ) 218return "\n" .join (lines ) 219 220 221def main ()-> int : 222ap = argparse .ArgumentParser () 223ap .add_argument ("--config" ,required = True ) 224ap .add_argument ("--tag" ,default = "base" ) 225ap .add_argument ("--cells" ,default = DEFAULT_CELLS ) 226ap .add_argument ("--rounds" ,type = int ,default = 3 ) 227ap .add_argument ("--port" ,type = int ,default = 8091 ) 228ap .add_argument ("--env" ,action = "append" ,default = [],help = "NAME=VALUE for the server process (repeatable)" ) 229ap .add_argument ("--exe" ,default = "" ,help = "engine binary to run instead of the config's" ) 230ap .add_argument ("--xargs" ,default = "" ,help = "extra engine arguments, ';'-separated" ) 231ap .add_argument ("--warm" ,type = int ,default = 64 ) 232ap .add_argument ("--out" ,default = "" ) 233a = ap .parse_args () 234cells = [] 235for s in a .cells .split ("," ): 236l ,t ,n = s .split (":" ) 237cells .append ((int (l ),float (t ),int (n ))) 238out = Path (a .out )if a .out else ROOT / "bench" / "results" / time .strftime ("dgx-%Y-%m-%d-%H%M" ) 239out .mkdir (parents = True ,exist_ok = True ) 240env = {} 241for e in a .env : 242k ,v = e .split ("=" ,1 ) 243env [k ]= v 244f"out { out } ; cells { cells } ; rounds { a . rounds } " ,flush = True ) 245rows = run_arm (Path (a .config ),a .tag ,cells ,a .rounds ,a .port ,env ,out ,a .warm , 246exe = (a .exe or None ),xargs = (a .xargs .split (";" )if a .xargs else None )) 247summary = summarize (rows ,cells ) 248 (out / f" { a . tag } .summary.md" ).write_text (f"# { a . tag } \n\n { summary } \n" ) 249"\n" + summary ) 250return 0 251 252 253if __name__ == "__main__" : 254sys .exit (main ())