okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
707fd49eb
main
1#!/usr/bin/env python3 2"""Fresh-prompt read + decode speed, and follow-up turns on a long conversation, through a running Strata server. 3 4Every measured prompt starts with its own nonce, so no earlier prompt's prefix can be reused: each fresh run reads its 5whole prompt (the engine log's "N reused" confirms it). The prompt text is the repository's own files (the haystack 6of tools/needle_bench.py: docs, sources), cut to an exact token count with the pack's tokenizer and the chat 7template, followed by a request for ~600 words of plain prose; the output cap is 400 tokens, greedy, reasoning 8off (reasoning_effort "none"). Prompts of 100K tokens or more carry a code word at 40 % depth; with --followup, the 9last run of such a size is followed by a second user turn on the same conversation (the long prefix reused) that 10asks for the code word and ~400 more words. 11 12Before every request the script waits until GET /status says busy=false, queued=0 for 3 s. After it, the run is 13discarded and repeated if GET /metrics counted more than one finished request or the engine log shows more than one 14prompt line (someone else's request overlapped). Run with the install's Python (it needs `regex` for the tokenizer): 15 16STRATA_API_KEY=... python bench_server.py --targets 4096,32768,128000 --runs 3 --followup 17python bench_server.py --key-config <server config.json> --targets 250000 --runs 1 --followup 18""" 19from __future__import annotations 20 21import argparse 22import hashlib 23import json 24import random 25import sys 26import time 27import urllib .request 28from pathlib import Path 29 30from common import LogTail ,Server ,api_key ,parse_engine ,scrub_lines 31 32HERE = Path (__file__ ).resolve ().parent 33ROOT = HERE .parents [2 ] 34sys .path [:0 ]= [str (ROOT ),str (ROOT / "tools" )] 35 36from strata_tokenizer import Tokenizer # noqa: E402 37from serve .frontend import ChatTemplate ,openai_to_messages # noqa: E402 38from needle_bench import haystack # noqa: E402 39 40ENDING = ("\n\nWrite a plain-prose overview of the material above in about 600 words, as continuous paragraphs " 41"without lists, headings or code." ) 42FOLLOWUP = ("What is the secret code word mentioned in the text above? Write the code word first, on its own line. " 43"Then, in about 400 words of plain prose, explain how the server described in these files handles a " 44"long prompt." ) 45WORDS = ["amber" ,"falcon" ,"quartz" ,"willow" ,"copper" ,"harbor" ,"saffron" ,"glacier" ,"orchid" ,"lantern" ] 46 47 48def load_tokenizer (directory :Path ): 49vocab = json .loads ((directory / "vocab.json" ).read_text ()) 50tokens = [None ]* len (vocab ) 51for token ,number in vocab .items (): 52tokens [number ]= token 53tok = Tokenizer (tokens , (directory / "merges.txt" ).read_text ().splitlines (), 54json .loads ((directory / "token_type.json" ).read_text ())) 55return tok ,ChatTemplate (directory / "chat_template.jinja" ) 56 57 58def body (messages ,max_tokens ): 59return {"model" :"strata" ,"messages" :messages ,"temperature" :0 ,"reasoning_effort" :"none" , 60"max_tokens" :max_tokens ,"stream" :True ,"stream_options" : {"include_usage" :True }} 61 62 63def stream (server :Server ,req :dict ,timeout :float = 3600 )-> dict : 64data = json .dumps (req ).encode () 65first = finish = usage = timings = None 66texts ,keepalives = [],0 67t0 = time .perf_counter () 68wire = urllib .request .Request (server .url + "/v1/chat/completions" ,data = data ,headers = server .headers ()) 69with urllib .request .urlopen (wire ,timeout = timeout )as resp : 70for raw in resp : 71line = raw .decode ("utf-8" ,errors = "replace" ).strip () 72if line .startswith (":" ): 73keepalives += 1 74continue 75if not line .startswith ("data: " ): 76continue 77payload = line [6 :] 78if payload == "[DONE]" : 79break 80chunk = json .loads (payload ) 81usage = chunk .get ("usage" )or usage 82timings = chunk .get ("timings" )or timings 83for choice in chunk .get ("choices" , []): 84delta = choice .get ("delta" )or {} 85text = (delta .get ("content" )or "" )+ (delta .get ("reasoning_content" )or "" ) 86if text : 87if first is None : 88first = time .perf_counter ()- t0 89texts .append (text ) 90finish = choice .get ("finish_reason" )or finish 91return {"request_sha256" :hashlib .sha256 (data ).hexdigest (),"client_ttft_s" :first , 92"client_total_s" :time .perf_counter ()- t0 ,"finish_reason" :finish ,"usage" :usage ,"timings" :timings , 93"keepalives" :keepalives ,"text" :"" .join (texts )} 94 95 96def main (): 97ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 98ap .add_argument ("--url" ,default = "http://127.0.0.1:8080" ) 99ap .add_argument ("--key-config" ,help = "server config JSON to read api_key from (else STRATA_API_KEY)" ) 100ap .add_argument ("--tokenizer" ,required = True ,help = "the pack's tokenizer directory" ) 101ap .add_argument ("--engine-log" ,required = True ) 102ap .add_argument ("--server-log" ,required = True ) 103ap .add_argument ("--out" ,type = Path ,default = HERE / "data" ) 104ap .add_argument ("--targets" ,default = "4096,32768,128000" ) 105ap .add_argument ("--runs" ,type = int ,default = 3 ) 106ap .add_argument ("--max-tokens" ,type = int ,default = 400 ) 107ap .add_argument ("--followup" ,action = "store_true" ,help = "a follow-up turn after the last run of sizes >= 100K" ) 108ap .add_argument ("--warmup" ,action = "store_true" ,help = "one short unmeasured request first" ) 109ap .add_argument ("--seed" ,type = int ,default = 2026 ) 110a = ap .parse_args () 111a .out .mkdir (parents = True ,exist_ok = True ) 112server = Server (a .url ,api_key (a .key_config )) 113tok ,tpl = load_tokenizer (Path (a .tokenizer )) 114elog ,slog = LogTail (a .engine_log ),LogTail (a .server_log ) 115rnd = random .Random (a .seed ) 116hay = haystack (1_100_000 ) 117 118def count (messages ): 119m ,tools ,kw = openai_to_messages (body (messages ,1 )) 120return len (tok .encode (tpl .render (m ,tools ,** kw ),parse_special = True )) 121 122def measured (label ,messages ,meta ): 123for attempt in range (1 ,4 ): 124status = server .wait_idle () 125if not server .loaded (): 126" the model is unloaded: this request would include loading; aborting" ,flush = True ) 127raise SystemExit (2 ) 128before = server .totals () 129elog .mark (),slog .mark () 130t_start = time .time () 131f"start { label } (attempt { attempt } ) { meta . get ( 'expected_prompt_tokens' ) } tokens" ,flush = True ) 132res = stream (server ,body (messages ,a .max_tokens )) 133t_end = time .time () 134time .sleep (1.5 )# the engine prints its timing lines after DONE 135after = server .totals () 136elines ,slines = elog .since (),slog .since () 137parsed = parse_engine (elines ) 138metrics = server .get ("/metrics" )["requests" ][0 ] 139foreign = (after - before != 1 )or len (parsed )!= 1 140row = {"label" :label ,"attempt" :attempt ,"epoch_start" :t_start ,"epoch_end" :t_end ,** meta ,** res , 141"status_before" :status ,"totals_before" :before ,"totals_after" :after ,"foreign_overlap" :foreign , 142"engine" :parsed [0 ]if parsed else None ,"metrics_record" :metrics , 143"engine_log" :scrub_lines (elines ),"server_log" :scrub_lines (slines )} 144name = f" { label } " + ("" if not foreign else f"-discarded- { attempt } " ) 145 (a .out / f" { name } .json" ).write_text (json .dumps (row ,indent = 1 ,ensure_ascii = False )+ "\n" ) 146e = parsed [0 ]if parsed else {} 147f"done { label } : { e . get ( 'line' , '(no engine line)' ) } ttft { res [ 'client_ttft_s' ]:.2f } s " 148f"total { res [ 'client_total_s' ]:.1f } s foreign= { foreign } " ,flush = True ) 149if not foreign : 150return row 151" foreign traffic overlapped this run: discarded, repeating" ,flush = True ) 152raise SystemExit (f" { label } : three attempts overlapped with other requests" ) 153 154if a .warmup : 155server .wait_idle () 156r = stream (server ,body ([{"role" :"user" ,"content" :"Reply with exactly the word READY." }],8 )) 157"warm-up:" ,r ["text" ].strip (),flush = True ) 158 159for target in map (int ,a .targets .split ("," )): 160for run in range (1 ,a .runs + 1 ): 161label = f"fresh- { target } -run { run } " 162nonce = f"Benchmark nonce { label } - { rnd . getrandbits ( 48 ):012x } .\n" 163head = nonce + "The text below is a collection of files from a software repository.\n" 164word = None 165if target >= 100_000 : 166word = f" { rnd . choice ( WORDS ) } - { rnd . choice ( WORDS ) } - { rnd . randint ( 100 , 999 ) } " 167 168def build (n ): 169text = hay [:n ] 170if word : 171cut = text .rfind ("\n" ,0 ,int (n * 0.40 ))+ 1 172text = text [:cut ]+ f"\nThe secret code word for this text is: { word } . Remember it.\n" + text [cut :] 173return [{"role" :"user" ,"content" :head + text + ENDING }] 174 175guess = int (target * 3.3 ) 176lo ,hi = max (0 ,int (guess * 0.8 )),min (len (hay ),int (guess * 1.25 )) 177if count (build (lo ))> target : 178lo = 0 179if count (build (hi ))<= target : 180raise SystemExit (f"the haystack is too short for { target } tokens" ) 181while lo < hi :# largest cut whose prompt fits in `target` tokens 182mid = (lo + hi + 1 )// 2 183if count (build (mid ))<= target : 184lo = mid 185else : 186hi = mid - 1 187messages = build (lo ) 188n = count (messages ) 189meta = {"kind" :"fresh" ,"target" :target ,"run" :run ,"expected_prompt_tokens" :n ,"needle" :word , 190"needle_depth_pct" :40 if word else None ,"max_tokens" :a .max_tokens } 191row = measured (label ,messages ,meta ) 192if word : 193row ["needle_found_in_first_answer" ]= word in row ["text" ] 194if a .followup and word and run == a .runs : 195follow = messages + [{"role" :"assistant" ,"content" :row ["text" ]}, 196 {"role" :"user" ,"content" :FOLLOWUP }] 197fmeta = {"kind" :"followup" ,"target" :target ,"run" :1 ,"expected_prompt_tokens" :count (follow ), 198"needle" :word ,"needle_depth_pct" :40 ,"max_tokens" :a .max_tokens , 199"follows" :label } 200frow = measured (f"followup- { target } " ,follow ,fmeta ) 201frow ["needle_found" ]= word in frow ["text" ][:200 ] 202 (a .out / f"followup- { target } .json" ).write_text (json .dumps (frow ,indent = 1 ,ensure_ascii = False )+ "\n" ) 203f" code word { word } : { 'FOUND' if frow [ 'needle_found' ] else 'missed' } " ,flush = True ) 204 205 206if __name__ == "__main__" : 207main ()