okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf67d177
main
1#!/usr/bin/env python3 2"""Build the frozen fixture bundle of the Strata standard benchmark (docs/BENCHMARK_PROTOCOL.md). 3 4python tools/build_standard_corpus.py --tokenizer PACK/tokenizer [--out bench/prompts/standard-v1] 5 6`strata bench run` reads the bundle this writes and never builds prompts at run time, so every machine sends the same bytes. The 7bundle has one JSON file per scheduled request (the 22 required ones and the 12 of the optional concurrency stage), `build.json` 8(how it was made: the tokenizer and template hashes, the target and actual token counts) and `MANIFEST.sha256` (a `sha256sum` 9listing of every other file). The SHA-256 of that manifest is the protocol's `corpus_sha256`. 10 11The prompts are synthetic. The two record counts (for about 4,096 and 16,384 tokens) are chosen with the pinned tokenizer and the 12chat template Strata ships (serve/chat_template.jinja), rendered the way the server renders a thinking request. Run it again 13and the bytes are identical; a change to anything the protocol freezes needs a new protocol ID. 14""" 15from __future__import annotations 16 17import argparse 18import hashlib 19import json 20import math 21import sys 22from pathlib import Path 23 24ROOT = Path (__file__ ).resolve ().parents [1 ] 25sys .path .insert (0 ,str (ROOT )) 26sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 27 28PROTOCOL_ID = "strata-qwen38-thinking-v1-draft.1" 29BUNDLE = "standard-v1" 30 31SHORT_TASK = "Explain how a hash table finds a value, including collisions and one small example." 32RECORD = "record{:06d}: alpha beta gamma delta epsilon zeta eta theta." 33SUMMARY_QUESTION = "Summarize the structure of these records and explain how to look up a record by its ID." 34TARGETS = {"prompt-4k" :4096 ,"prompt-16k" :16384 } 35TOLERANCE = 0.02 36TOOL_DESCRIPTION = "Synthetic benchmark lookup; no external action is performed." 37 38# What the template is rendered with when the runner asks for the protocol's thinking settings. 39TEMPLATE_KWARGS = {"enable_thinking" :True ,"preserve_thinking" :True ,"reasoning_effort" :"xhigh" } 40 41WARMUP_CAP ,PERFORMANCE_CAP ,SANITY_CAP ,CONCURRENCY_CAP = 128 ,512 ,2048 ,512 42 43INSTRUCTION = { 44"I1" : ("Return only a JSON object with ok set to true and count set to the integer 3. No other keys." , 45 {"kind" :"json" ,"value" : {"ok" :True ,"count" :3 }}), 46"I2" : ("Sort these integers in ascending order and remove duplicates: 9, 2, -4, 2, 1. Return only a JSON array." , 47 {"kind" :"json" ,"value" : [- 4 ,1 ,2 ,9 ]}), 48"I3" : ("Project: Orion. Build: 17. Return only a JSON object with keys project (string) and build (integer)." , 49 {"kind" :"json" ,"value" : {"project" :"Orion" ,"build" :17 }}), 50"I4" : ("Reply with exactly the word READY in uppercase and nothing else." , 51 {"kind" :"text" ,"value" :"READY" }), 52} 53 54# id -> (records, inserts [(fraction, line)], question, expected) 55RETRIEVAL = { 56"R1" : ("prompt-4k" , [(0.10 ,"access_code = ORBIT-731" )], 57"What is access_code? Reply only with its value." , {"kind" :"text" ,"value" :"ORBIT-731" }), 58"R2" : ("prompt-4k" , [(0.50 ,"storage_label = CEDAR-284" )], 59"What is storage_label? Reply only with its value." , {"kind" :"text" ,"value" :"CEDAR-284" }), 60"R3" : ("prompt-16k" , [(0.90 ,"archive_code = DELTA-906" )], 61"What is archive_code? Reply only with its value." , {"kind" :"text" ,"value" :"DELTA-906" }), 62"R4" : ("prompt-16k" , [(0.10 ,"north = N-124" ), (0.90 ,"south = S-875" )], 63"Return only a JSON object containing north and south and their values." , 64 {"kind" :"json" ,"value" : {"north" :"N-124" ,"south" :"S-875" }}), 65} 66 67# id -> (prompt, function name, {property: type}, expected arguments) 68TOOLS = { 69"T1" : ("Use lookup_record to look up record A-17." ,"lookup_record" , {"id" :"string" }, {"id" :"A-17" }), 70"T2" : ("Use get_weather for Zagreb in celsius." ,"get_weather" , {"city" :"string" ,"unit" :"string" }, 71 {"city" :"Zagreb" ,"unit" :"celsius" }), 72"T3" : ("Use convert_units to convert 3 km to m." ,"convert_units" , 73 {"value" :"number" ,"from_unit" :"string" ,"to_unit" :"string" }, 74 {"value" :3 ,"from_unit" :"km" ,"to_unit" :"m" }), 75"T4" : ("Use get_build_status for project Orion, build 17." ,"get_build_status" , 76 {"project" :"string" ,"build" :"integer" }, {"project" :"Orion" ,"build" :17 }), 77} 78 79 80def sha256_bytes (data :bytes )-> str : 81return hashlib .sha256 (data ).hexdigest () 82 83 84def encoded (obj )-> bytes : 85"""The one serialization of every fixture file: UTF-8, LF, two-space indent, key order as written.""" 86return (json .dumps (obj ,ensure_ascii = False ,indent = 2 )+ "\n" ).encode ("utf-8" ) 87 88 89def tool_schema (name :str ,properties :dict )-> dict : 90return {"type" :"function" ,"function" : { 91"name" :name ,"description" :TOOL_DESCRIPTION , 92"parameters" : {"type" :"object" ,"properties" : {key : {"type" :kind }for key ,kind in properties .items ()}, 93"required" :list (properties ),"additionalProperties" :False }}} 94 95 96def user_message (request_id :str ,body :str )-> list [dict ]: 97return [{"role" :"user" ,"content" :f"[case { request_id } ]\n { body } " }] 98 99 100def records_body (count :int ,question :str ,inserts :list [tuple [float ,str ]]= ())-> str : 101"""`count` records, one per line, with each insert placed before record index floor(fraction * count); then the question.""" 102before :dict [int ,list [str ]]= {} 103for fraction ,line in inserts : 104before .setdefault (math .floor (fraction * count ), []).append (line ) 105lines :list [str ]= [] 106for index in range (count ): 107lines .extend (before .get (index , ())) 108lines .append (RECORD .format (index + 1 )) 109return "\n" .join (lines )+ "\n" + question 110 111 112class Counter : 113"""Token counts of a rendered request, with the tokenizer and the template the server uses.""" 114 115def __init__ (self ,tokenizer_dir :Path ,template_path :Path ): 116import strata_tokenizer as ST 117from serve .frontend import ChatTemplate 118vocab = json .loads ((tokenizer_dir / "vocab.json" ).read_text (encoding = "utf-8" )) 119tokens = [None ]* len (vocab ) 120for token ,index in vocab .items (): 121tokens [index ]= token 122merges = (tokenizer_dir / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ) 123if merges and merges [- 1 ]== "" : 124merges .pop () 125types = json .loads ((tokenizer_dir / "token_type.json" ).read_text (encoding = "utf-8" )) 126self .tok = ST .Tokenizer (tokens ,merges ,types ) 127self .template = ChatTemplate (template_path ) 128 129def ids (self ,messages :list [dict ],tools :list [dict ]| None )-> list [int ]: 130functions = [t ["function" ]for t in tools ]if tools else None 131text = self .template .render (messages ,tools = functions ,** TEMPLATE_KWARGS ) 132return self .tok .encode (text ,parse_special = True ) 133 134 135def pick_record_count (counter :Counter ,target :int )-> tuple [int ,int ]: 136"""The number of complete records whose rendered performance request is closest to `target` tokens.""" 137def tokens (count :int )-> int : 138body = records_body (count ,SUMMARY_QUESTION ) 139return len (counter .ids (user_message ("performance-prompt-4k-r1" ,body ),None )) 140low ,high = 20 ,60 141t_low ,t_high = tokens (low ),tokens (high ) 142slope = (t_high - t_low )/ (high - low ) 143count = max (1 ,round (low + (target - t_low )/ slope )) 144for _ in range (4 ): 145current = tokens (count ) 146step = round ((target - current )/ slope ) 147if step == 0 : 148break 149count += step 150best = min (range (max (1 ,count - 4 ),count + 5 ),key = lambda n : (abs (tokens (n )- target ),n )) 151return best ,tokens (best ) 152 153 154def lcp (a :list [int ],b :list [int ])-> int : 155n = 0 156for x ,y in zip (a ,b ): 157if x != y : 158break 159n += 1 160return n 161 162 163def build (tokenizer_dir :Path ,template_path :Path ,out :Path )-> dict : 164counter = Counter (tokenizer_dir ,template_path ) 165counts = {} 166for case ,target in TARGETS .items (): 167count ,actual = pick_record_count (counter ,target ) 168if abs (actual - target )> TOLERANCE * target : 169raise SystemExit (f" { case } : { actual } tokens is not within { TOLERANCE :.0% } of { target } " ) 170counts [case ]= {"records" :count ,"target_tokens" :target } 171f" { case } : { count } records, { actual } tokens (target { target } )" ) 172 173requests :list [dict ]= [] 174 175def add (request_id ,phase ,case_id ,repetition ,seed ,cap ,messages ,* ,tools = None ,expected = None ,category = None , 176round_ = None ,concurrency = 1 ,target = None ): 177requests .append ({ 178"id" :request_id ,"phase" :phase ,"case_id" :case_id ,"repetition" :repetition ,"round" :round_ , 179"seed" :seed ,"max_output_tokens" :cap ,"concurrency" :concurrency ,"category" :category , 180"target_input_tokens" :target ,"messages" :messages ,"tools" :tools , 181"tool_choice" :"auto" if tools else None ,"expected" :expected }) 182 183short = lambda request_id :user_message (request_id ,SHORT_TASK )# noqa: E731 184long_body = lambda case :records_body (counts [case ]["records" ],SUMMARY_QUESTION )# noqa: E731 185add ("warmup" ,"warmup" ,"warmup" ,1 ,1 ,WARMUP_CAP ,short ("warmup" )) 186for repetition in (1 ,2 ,3 ): 187add (f"performance-short-r { repetition } " ,"performance" ,"short" ,repetition ,repetition ,PERFORMANCE_CAP , 188short (f"performance-short-r { repetition } " )) 189for case in ("prompt-4k" ,"prompt-16k" ): 190request_id = f"performance- { case } -r { repetition } " 191add (request_id ,"performance" ,case ,repetition ,repetition ,PERFORMANCE_CAP , 192user_message (request_id ,long_body (case )),target = TARGETS [case ]) 193for name , (prompt ,expected )in INSTRUCTION .items (): 194add (f"sanity- { name } " ,"sanity" ,name ,1 ,1 ,SANITY_CAP ,user_message (f"sanity- { name } " ,prompt ), 195expected = expected ,category = "instruction" ) 196for name , (case ,inserts ,question ,expected )in RETRIEVAL .items (): 197body = records_body (counts [case ]["records" ],question ,inserts ) 198add (f"sanity- { name } " ,"sanity" ,name ,1 ,1 ,SANITY_CAP ,user_message (f"sanity- { name } " ,body ), 199expected = expected ,category = "retrieval" ,target = TARGETS [case ]) 200for name , (prompt ,function ,properties ,arguments )in TOOLS .items (): 201add (f"sanity- { name } " ,"sanity" ,name ,1 ,1 ,SANITY_CAP ,user_message (f"sanity- { name } " ,prompt ), 202tools = [tool_schema (function ,properties )], 203expected = {"kind" :"tool_call" ,"name" :function ,"arguments" :arguments },category = "tool_call" ) 204for round_ in (1 ,2 ,3 ): 205for client in (1 ,2 ,3 ,4 ): 206request_id = f"concurrency-r { round_ } -c { client } " 207add (request_id ,"concurrency" ,"short-burst" ,round_ ,4 * (round_ - 1 )+ client ,CONCURRENCY_CAP , 208short (request_id ),round_ = round_ ,concurrency = 4 ) 209 210token_ids = {r ["id" ]:counter .ids (r ["messages" ],r ["tools" ])for r in requests } 211for request in requests : 212ids = token_ids [request ["id" ]] 213request ["input_tokens_frozen" ]= len (ids ) 214request ["max_shared_prefix_tokens" ]= max (lcp (ids ,other )for key ,other in token_ids .items () 215if key != request ["id" ]) 216if request ["target_input_tokens" ]is not None : 217deviation = abs (len (ids )- request ["target_input_tokens" ])/ request ["target_input_tokens" ] 218if deviation > TOLERANCE : 219raise SystemExit (f" { request [ 'id' ] } : { len ( ids ) } tokens is more than { TOLERANCE :.0% } from the target" ) 220 221 (out / "requests" ).mkdir (parents = True ,exist_ok = True ) 222for stale in (out / "requests" ).glob ("*.json" ): 223stale .unlink () 224files :dict [str ,bytes ]= {} 225for request in requests : 226files [f"requests/ { request [ 'id' ] } .json" ]= encoded (request ) 227tokenizer_files = {name :sha256_bytes ((tokenizer_dir / name ).read_bytes ()) 228for name in ("vocab.json" ,"merges.txt" ,"token_type.json" )} 229files ["build.json" ]= encoded ({ 230"protocol_id" :PROTOCOL_ID ,"bundle" :BUNDLE , 231"profile" :"qwen3.8-flash-next-thinking" , 232"tokenizer_files" :tokenizer_files , 233"template" : {"path" :"serve/chat_template.jinja" ,"sha256" :sha256_bytes (template_path .read_bytes ())}, 234"template_kwargs" :TEMPLATE_KWARGS , 235"record_format" :RECORD ,"short_task" :SHORT_TASK ,"summary_question" :SUMMARY_QUESTION , 236"record_counts" :counts ,"length_tolerance" :TOLERANCE , 237"requests" : [{"id" :r ["id" ],"input_tokens" :r ["input_tokens_frozen" ], 238"max_shared_prefix_tokens" :r ["max_shared_prefix_tokens" ]}for r in requests ], 239"note" :"input_tokens counts the rendered thinking request with the generation prompt. max_shared_prefix_tokens is " 240"the longest token prefix this request shares with any other request of the bundle: cache reuse above it " 241"means the user payload was read from the cache." }) 242for name ,data in files .items (): 243 (out / name ).write_bytes (data ) 244manifest = "" .join (f" { sha256_bytes ( data ) } { name } \n" for name ,data in sorted (files .items ())).encode ("utf-8" ) 245 (out / "MANIFEST.sha256" ).write_bytes (manifest ) 246f" { len ( requests ) } requests, corpus_sha256 { sha256_bytes ( manifest ) } " ) 247return {"corpus_sha256" :sha256_bytes (manifest ),"requests" :len (requests )} 248 249 250def main (argv :list [str ]| None = None )-> int : 251ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 252ap .add_argument ("--tokenizer" ,required = True ,type = Path , 253help = "folder with vocab.json, merges.txt and token_type.json (a pack's tokenizer/ folder)" ) 254ap .add_argument ("--template" ,type = Path ,default = ROOT / "serve" / "chat_template.jinja" ) 255ap .add_argument ("--out" ,type = Path ,default = ROOT / "bench" / "prompts" / BUNDLE ) 256a = ap .parse_args (argv ) 257build (a .tokenizer ,a .template ,a .out ) 258return 0 259 260 261if __name__ == "__main__" : 262raise SystemExit (main ())