okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3f4d44ece
main
1#!/usr/bin/env python3 2"""bench.py - engine-agnostic benchmark: speed + accuracy + completeness + reliability. 3 4One client for Strata / llama-server (OpenAI /v1/chat/completions, streaming) and Ollama (/api/chat, streaming). 5Everything is graded against ground truth computed or executed here - never model self-report: 6reasoning 40 programmatic questions (answers computed in Python, fixed seed) 7code 12 functions graded by executing hidden tests in a subprocess 8tools 8 tool-call cases (name + args exact, plus restraint cases that must NOT call a tool) 9complete 6 completeness tasks (exact lists / required sections / valid JSON) + finish_reason 10longctx needle recall at several prompt sizes (3 facts at 20/50/80 % depth) 11speed fixed-size prompts: decode tok/s, prefill tok/s, TTFT (client-side AND server-reported) 12Every record keeps the raw output, finish_reason, token counts and the effective request, so a score can be re-derived. 13 14--selftest runs the graders against an oracle (must be 100 %) and a garbage engine (must be 0 %) - run it before trusting numbers. 15Stdlib only (runs inside a no-network namespace as an unprivileged user). 16""" 17import argparse ,http .client ,json ,os ,random ,re ,subprocess ,sys ,tempfile ,time ,datetime ,urllib .parse 18 19SEED = 1234 20 21# --------------------------------------------------------------------------- engines 22class Result (dict ): 23pass 24 25def _post_stream (url ,payload ,timeout ): 26u = urllib .parse .urlparse (url ) 27conn = http .client .HTTPConnection (u .hostname ,u .port ,timeout = timeout ) 28conn .request ("POST" ,u .path ,body = json .dumps (payload ),headers = {"Content-Type" :"application/json" ,"Host" :"127.0.0.1:%d" % u .port }) 29resp = conn .getresponse () 30if resp .status != 200 : 31body = resp .read (2000 ).decode ("utf-8" ,"replace" ) 32conn .close () 33raise RuntimeError ("HTTP %d: %s" % (resp .status ,body )) 34return conn ,resp 35 36def call_openai (base ,model ,messages ,max_tokens ,think ,tools ,timeout ): 37payload = {"model" :model ,"messages" :messages ,"stream" :True ,"stream_options" : {"include_usage" :True }, 38"temperature" :0 ,"top_k" :1 ,"top_p" :1 ,"seed" :1 ,"max_tokens" :max_tokens , 39"chat_template_kwargs" : {"enable_thinking" :bool (think )}} 40if not think : 41payload ["reasoning_effort" ]= "none" # Strata honours this; llama-server ignores unknown fields 42if tools : 43payload ["tools" ]= tools 44t0 = time .time ();first = None 45text ,reasoning ,finish ,usage ,timings = [], [],None ,None ,None 46tcalls = {} 47conn ,resp = _post_stream (base + "/v1/chat/completions" ,payload ,timeout ) 48try : 49for raw in resp : 50line = raw .decode ("utf-8" ,"replace" ).strip () 51if not line .startswith ("data:" ): 52continue 53data = line [5 :].strip () 54if data == "[DONE]" : 55break 56ch = json .loads (data ) 57if ch .get ("usage" ): 58usage = ch ["usage" ] 59if ch .get ("timings" ): 60timings = ch ["timings" ] 61for c in ch .get ("choices" , []): 62d = c .get ("delta" , {}) 63if d .get ("content" ): 64first = first or time .time ();text .append (d ["content" ]) 65rc = d .get ("reasoning_content" )or d .get ("reasoning" ) 66if rc : 67first = first or time .time ();reasoning .append (rc ) 68for tc in d .get ("tool_calls" )or []: 69first = first or time .time () 70slot = tcalls .setdefault (tc .get ("index" ,0 ), {"name" :"" ,"arguments" :"" }) 71f = tc .get ("function" , {}) 72slot ["name" ]+= f .get ("name" )or "" 73slot ["arguments" ]+= f .get ("arguments" )or "" 74if c .get ("finish_reason" ): 75finish = c ["finish_reason" ] 76finally : 77conn .close () 78t1 = time .time () 79calls = [] 80for k in sorted (tcalls ): 81try : 82args = json .loads (tcalls [k ]["arguments" ]or "{}" ) 83except Exception : 84args = {"_unparsed" :tcalls [k ]["arguments" ]} 85calls .append ({"name" :tcalls [k ]["name" ],"arguments" :args }) 86ct = (usage or {}).get ("completion_tokens" ) 87return Result (text = "" .join (text ),reasoning = "" .join (reasoning ),finish_reason = finish ,tool_calls = calls , 88prompt_tokens = (usage or {}).get ("prompt_tokens" ),completion_tokens = ct , 89t_total = t1 - t0 ,t_first = (first - t0 )if first else None ,server_timings = timings ,error = None ) 90 91def call_ollama (base ,model ,messages ,max_tokens ,think ,tools ,timeout ,num_ctx ): 92payload = {"model" :model ,"messages" :messages ,"stream" :True ,"think" :bool (think ), 93"options" : {"num_ctx" :num_ctx ,"num_predict" :max_tokens ,"temperature" :0 ,"top_k" :1 ,"top_p" :1 , 94"seed" :1 ,"repeat_penalty" :1.0 }} 95if tools : 96payload ["tools" ]= tools 97t0 = time .time ();first = None 98text ,reasoning ,final ,calls = [], [], {}, [] 99conn ,resp = _post_stream (base + "/api/chat" ,payload ,timeout ) 100try : 101for raw in resp : 102line = raw .decode ("utf-8" ,"replace" ).strip () 103if not line : 104continue 105ch = json .loads (line ) 106m = ch .get ("message" , {}) 107if m .get ("content" ): 108first = first or time .time ();text .append (m ["content" ]) 109if m .get ("thinking" ): 110first = first or time .time ();reasoning .append (m ["thinking" ]) 111for tc in m .get ("tool_calls" )or []: 112first = first or time .time () 113f = tc .get ("function" , {}) 114calls .append ({"name" :f .get ("name" ,"" ),"arguments" :f .get ("arguments" , {})}) 115if ch .get ("done" ): 116final = ch 117finally : 118conn .close () 119t1 = time .time () 120ns = lambda k : (final .get (k )or 0 )/ 1e9 121st = {"prompt_n" :final .get ("prompt_eval_count" ),"prompt_ms" :ns ("prompt_eval_duration" )* 1000 , 122"predicted_n" :final .get ("eval_count" ),"predicted_ms" :ns ("eval_duration" )* 1000 , 123"load_ms" :ns ("load_duration" )* 1000 } 124if st ["prompt_ms" ]: 125st ["prompt_per_second" ]= (st ["prompt_n" ]or 0 )/ (st ["prompt_ms" ]/ 1000 ) 126if st ["predicted_ms" ]: 127st ["predicted_per_second" ]= (st ["predicted_n" ]or 0 )/ (st ["predicted_ms" ]/ 1000 ) 128return Result (text = "" .join (text ),reasoning = "" .join (reasoning ),finish_reason = final .get ("done_reason" ), 129tool_calls = calls ,prompt_tokens = final .get ("prompt_eval_count" ),completion_tokens = final .get ("eval_count" ), 130t_total = t1 - t0 ,t_first = (first - t0 )if first else None ,server_timings = st ,error = None ) 131 132class Oracle : 133"""Engine stand-in for --selftest: returns the task's known-correct answer (or garbage).""" 134def __init__ (self ,good ):self .good = good 135def __call__ (self ,task ): 136if task .get ("tools" ): 137calls = task ["oracle_calls" ]if self .good else [{"name" :"bogus" ,"arguments" : {}}] 138return Result (text = "" ,reasoning = "" ,finish_reason = "tool_calls" if calls else "stop" ,tool_calls = calls if self .good or True else [], 139prompt_tokens = 1 ,completion_tokens = 1 ,t_total = 0.01 ,t_first = 0.01 ,server_timings = None ,error = None ) 140txt = task ["oracle" ]if self .good else "I do not know." 141return Result (text = txt ,reasoning = "" ,finish_reason = "stop" ,tool_calls = [],prompt_tokens = 1 ,completion_tokens = 1 , 142t_total = 0.01 ,t_first = 0.01 ,server_timings = None ,error = None ) 143 144# --------------------------------------------------------------------------- tasks: reasoning (programmatic) 145def norm (s ): 146s = s .strip ().strip ("`*\"'" ).rstrip ("." ).strip () 147s = s .replace ("," ,"" )if re .fullmatch (r"-?[\d,]+(\.\d+)?" ,s )else s 148return s .lower () 149 150def last_answer (text ): 151m = re .findall (r"ANSWER:\s*(.+)" ,text ) 152return m [- 1 ].strip ()if m else None 153 154def grade_answer (task ,res ): 155a = last_answer (res ["text" ]) 156return a is not None and norm (a )== norm (task ["expected" ]), {"got" :a ,"expected" :task ["expected" ]} 157 158FMT = "\n\nThink briefly if needed, then give the final result on the last line formatted exactly as 'ANSWER: <answer>'." 159 160def make_reasoning (): 161import datetime as dt 162r = random .Random (SEED );out = [] 163def add (q ,exp ): 164out .append ({"id" :"reason-%02d" % (len (out )+ 1 ),"category" :"reasoning" ,"messages" : [{"role" :"user" ,"content" :q + FMT }], 165"max_tokens" :1024 ,"expected" :str (exp ),"oracle" :"ANSWER: %s" % exp ,"grader" :"answer" }) 166for _ in range (8 ): 167a ,b = r .randint (120 ,9800 ),r .randint (12 ,990 );add ("What is %d * %d?" % (a ,b ),a * b ) 168for _ in range (5 ): 169a ,b ,c ,d = r .randint (100 ,999 ),r .randint (100 ,999 ),r .randint (3 ,40 ),r .randint (3 ,40 );add ("Compute %d + %d - %d * %d." % (a ,b ,c ,d ),a + b - c * d ) 170words = ["strawberry" ,"mississippi" ,"bookkeeper" ,"committee" ,"rhythm" ,"banana bandana" ,"assassin" ,"occurrence" ,"parallel lines" ,"successful" ] 171for w in r .sample (words ,5 ): 172ch = r .choice (sorted (set (w .replace (" " ,"" )))) 173add ("How many times does the letter '%s' appear in the text \"%s\"? (case-insensitive)" % (ch ,w ),w .lower ().count (ch )) 174for _ in range (5 ): 175d0 = dt .date (r .randint (2019 ,2031 ),r .randint (1 ,12 ),r .randint (1 ,28 ));n = r .randint (40 ,900 ) 176add ("What day of the week is it %d days after %s? Answer with the weekday name only." % (n ,d0 .isoformat ()), (d0 + dt .timedelta (days = n )).strftime ("%A" )) 177for _ in range (2 ): 178n = r .randint (200 ,4000 );add ("Convert the decimal number %d to binary (digits only, no prefix)." % n ,bin (n )[2 :]) 179for _ in range (2 ): 180n = r .randint (3000 ,60000 );add ("Convert the decimal number %d to hexadecimal (uppercase, no prefix)." % n ,"%X" % n ) 181for _ in range (4 ): 182xs = r .sample (range (10 ,99 ),8 );add ("Here is a list: %s. What is the third largest number in it?" % xs ,sorted (xs )[- 3 ]) 183for _ in range (3 ): 184a ,b ,m = r .randint (3 ,12 ),r .randint (5 ,40 ),r .randint (7 ,97 );add ("What is %d^%d mod %d?" % (a ,b ,m ),pow (a ,b ,m )) 185for _ in range (3 ): 186v ,t = r .randint (30 ,90 ),r .randint (2 ,9 );add ("A train travels at %d km/h for %d hours and then 2 more hours at %d km/h. What total distance in km did it cover?" % (v ,t ,v + 10 ),v * t + 2 * (v + 10 )) 187for w in r .sample (["calculator" ,"photograph" ,"microscope" ],3 ): 188add ("Write the word '%s' backwards (letters only)." % w ,w [::- 1 ]) 189return out 190 191# --------------------------------------------------------------------------- tasks: code (executed hidden tests) 192CODE_TASKS = [ 193 ("is_balanced" ,"is_balanced(s: str) -> bool: True if every (), [], {} in s is correctly nested and closed; ignore other characters." , 194 [(["([]{})" ],True ), (["([)]" ],False ), (["a(b)c]" ],False ), (["" ],True ), (["{[()()]}" ],True ), (["((" ],False )]), 195 ("roman_to_int" ,"roman_to_int(s: str) -> int: convert a valid Roman numeral (1..3999) to an integer." , 196 [(["III" ],3 ), (["LVIII" ],58 ), (["MCMXCIV" ],1994 ), (["IV" ],4 ), (["MMMCMXCIX" ],3999 )]), 197 ("merge_intervals" ,"merge_intervals(iv: list) -> list: iv is a list of [start, end] pairs; return merged overlapping/touching intervals sorted by start, as lists." , 198 [([[[1 ,3 ], [2 ,6 ], [8 ,10 ], [15 ,18 ]]], [[1 ,6 ], [8 ,10 ], [15 ,18 ]]), ([[[1 ,4 ], [4 ,5 ]]], [[1 ,5 ]]), ([[]], []), ([[[5 ,7 ], [1 ,2 ], [2 ,3 ]]], [[1 ,3 ], [5 ,7 ]])]), 199 ("lcs_length" ,"lcs_length(a: str, b: str) -> int: length of the longest common subsequence." , 200 [(["abcde" ,"ace" ],3 ), (["abc" ,"def" ],0 ), (["" ,"abc" ],0 ), (["AGGTAB" ,"GXTXAYB" ],4 )]), 201 ("flatten" ,"flatten(x) -> list: flatten arbitrarily nested lists of ints into one flat list, preserving order." , 202 [([[1 , [2 , [3 , [4 ]],5 ]]], [1 ,2 ,3 ,4 ,5 ]), ([[]], []), ([[[], [[]],7 ]], [7 ])]), 203 ("top_words" ,"top_words(text: str, k: int) -> list: the k most frequent words (lowercase, words are runs of letters a-z/A-Z) as a list of [word, count], sorted by count descending then word ascending." , 204 [(["the cat and the hat and the bat" ,2 ], [["the" ,3 ], ["and" ,2 ]]), (["A a b B c" ,2 ], [["a" ,2 ], ["b" ,2 ]]), (["" ,3 ], [])]), 205 ("rotate_matrix" ,"rotate_matrix(m: list) -> list: rotate a square matrix (list of lists) 90 degrees clockwise and return a new matrix." , 206 [([[[1 ,2 ], [3 ,4 ]]], [[3 ,1 ], [4 ,2 ]]), ([[[1 ,2 ,3 ], [4 ,5 ,6 ], [7 ,8 ,9 ]]], [[7 ,4 ,1 ], [8 ,5 ,2 ], [9 ,6 ,3 ]]), ([[[5 ]]], [[5 ]])]), 207 ("valid_ipv4" ,"valid_ipv4(s: str) -> bool: True iff s is a valid dotted-quad IPv4 address: exactly 4 decimal parts 0-255, no leading zeros (except '0' itself), digits only." , 208 [(["192.168.1.1" ],True ), (["256.1.1.1" ],False ), (["01.2.3.4" ],False ), (["1.2.3" ],False ), (["1.2.3.4.5" ],False ), (["0.0.0.0" ],True ), (["a.b.c.d" ],False ), (["1..2.3" ],False )]), 209 ("prime_factors" ,"prime_factors(n: int) -> list: prime factorization of n >= 2 as a sorted list with repetition." , 210 [([12 ], [2 ,2 ,3 ]), ([97 ], [97 ]), ([360 ], [2 ,2 ,2 ,3 ,3 ,5 ]), ([2 ** 10 ], [2 ]* 10 ), ([1001 ], [7 ,11 ,13 ])]), 211 ("longest_palindrome" ,"longest_palindrome(s: str) -> str: the longest palindromic substring; on ties return the one that starts earliest; empty string for empty input." , 212 [(["babad" ],"bab" ), (["cbbd" ],"bb" ), (["a" ],"a" ), (["" ],"" ), (["forgeeksskeegfor" ],"geeksskeeg" )]), 213 ("eval_rpn" ,"eval_rpn(tokens: list) -> int: evaluate a Reverse Polish Notation expression given as a list of strings with + - * /; division truncates toward zero." , 214 [([["2" ,"1" ,"+" ,"3" ,"*" ]],9 ), ([["4" ,"13" ,"5" ,"/" ,"+" ]],6 ), ([["10" ,"6" ,"9" ,"3" ,"+" ,"-11" ,"*" ,"/" ,"*" ,"17" ,"+" ,"5" ,"+" ]],22 ), ([["7" ,"-2" ,"/" ]],- 3 )]), 215 ("parse_duration" ,"parse_duration(s: str) -> int: convert strings like '1h30m15s', '45s', '2h', '10m5s' (any subset of h, m, s in that order) to total seconds; return 0 for an empty string." , 216 [(["1h30m15s" ],5415 ), (["45s" ],45 ), (["2h" ],7200 ), (["10m5s" ],605 ), (["" ],0 )]), 217] 218 219def make_code (): 220out = [] 221for name ,spec ,tests in CODE_TASKS : 222out .append ({"id" :"code-" + name ,"category" :"code" ,"max_tokens" :1500 ,"grader" :"code" ,"fn" :name ,"tests" :tests , 223"messages" : [{"role" :"user" ,"content" :"Write a Python 3 function with this signature and behaviour:\n\n%s\n\nReturn only one ```python code block containing the function (and any imports/helpers it needs). No example usage, no prints." % spec }], 224"oracle" :None }) 225return out 226 227REF_IMPL = {# reference solutions used ONLY by --selftest to prove the hidden tests are correct and passable 228"is_balanced" :"def is_balanced(s):\n st=[];p={')':'(',']':'[','}':'{'}\n for c in s:\n if c in '([{': st.append(c)\n elif c in p:\n if not st or st.pop()!=p[c]: return False\n return not st" , 229"roman_to_int" :"def roman_to_int(s):\n v={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};t=0\n for i,c in enumerate(s):\n t+= -v[c] if i+1<len(s) and v[c]<v[s[i+1]] else v[c]\n return t" , 230"merge_intervals" :"def merge_intervals(iv):\n r=[]\n for a,b in sorted(iv):\n if r and a<=r[-1][1]: r[-1][1]=max(r[-1][1],b)\n else: r.append([a,b])\n return r" , 231"lcs_length" :"def lcs_length(a,b):\n d=[[0]*(len(b)+1) for _ in range(len(a)+1)]\n for i in range(len(a)):\n for j in range(len(b)):\n d[i+1][j+1]=d[i][j]+1 if a[i]==b[j] else max(d[i][j+1],d[i+1][j])\n return d[-1][-1]" , 232"flatten" :"def flatten(x):\n o=[]\n for e in x:\n o+= flatten(e) if isinstance(e,list) else [e]\n return o" , 233"top_words" :"import re,collections\ndef top_words(text,k):\n c=collections.Counter(w.lower() for w in re.findall(r'[A-Za-z]+',text))\n return [[w,n] for w,n in sorted(c.items(),key=lambda t:(-t[1],t[0]))[:k]]" , 234"rotate_matrix" :"def rotate_matrix(m):\n return [list(r) for r in zip(*m[::-1])]" , 235"valid_ipv4" :"def valid_ipv4(s):\n p=s.split('.')\n return len(p)==4 and all(x.isdigit() and x.isascii() and (x=='0' or not x.startswith('0')) and int(x)<=255 for x in p)" , 236"prime_factors" :"def prime_factors(n):\n f=[];d=2\n while d*d<=n:\n while n%d==0: f.append(d);n//=d\n d+=1\n if n>1: f.append(n)\n return f" , 237"longest_palindrome" :"def longest_palindrome(s):\n b=''\n for i in range(len(s)):\n for j in range(i,len(s)):\n t=s[i:j+1]\n if t==t[::-1] and len(t)>len(b): b=t\n return b" , 238"eval_rpn" :"def eval_rpn(tokens):\n st=[]\n for t in tokens:\n if t in '+-*/' and len(t)==1:\n b=st.pop();a=st.pop()\n st.append(a+b if t=='+' else a-b if t=='-' else a*b if t=='*' else int(a/b))\n else: st.append(int(t))\n return st[0]" , 239"parse_duration" :"import re\ndef parse_duration(s):\n m=re.fullmatch(r'(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?',s)\n h,mi,se=(int(x) if x else 0 for x in m.groups())\n return h*3600+mi*60+se" , 240} 241 242def extract_code (text ): 243blocks = re .findall (r"```(?:python|py)?\s*\n(.*?)```" ,text ,re .S ) 244return max (blocks ,key = len )if blocks else None 245 246def grade_code (task ,res ): 247code = extract_code (res ["text" ]) 248if not code : 249return False , {"error" :"no code block" } 250harness = code + "\n\nimport json,sys\n_T=json.loads(sys.stdin.read())\n_ok=0;_fail=[]\nfor a,e in _T:\n try:\n g=%s(*a)\n except Exception as ex:\n g='EXC '+type(ex).__name__\n if g==e: _ok+=1\n else: _fail.append([a,e,g])\nprint(json.dumps({'ok':_ok,'n':len(_T),'fail':_fail[:3]}))\n" % task ["fn" ] 251with tempfile .NamedTemporaryFile ("w" ,suffix = ".py" ,delete = False )as f : 252f .write (harness );path = f .name 253try : 254p = subprocess .run ([sys .executable ,"-I" ,path ],input = json .dumps (task ["tests" ]),capture_output = True ,text = True ,timeout = 15 ) 255out = json .loads (p .stdout .strip ().splitlines ()[- 1 ])if p .stdout .strip ()else {"error" : (p .stderr or "no output" )[- 300 :]} 256except subprocess .TimeoutExpired : 257out = {"error" :"timeout" } 258except Exception as ex : 259out = {"error" :repr (ex )} 260finally : 261os .unlink (path ) 262return out .get ("ok" )== out .get ("n" )and "error" not in out ,out 263 264# --------------------------------------------------------------------------- tasks: tool calling 265TOOLS = [ 266 {"type" :"function" ,"function" : {"name" :"get_weather" ,"description" :"Get current weather for a city." ,"parameters" : {"type" :"object" ,"properties" : {"city" : {"type" :"string" },"unit" : {"type" :"string" ,"enum" : ["c" ,"f" ]}},"required" : ["city" ,"unit" ]}}}, 267 {"type" :"function" ,"function" : {"name" :"set_timer" ,"description" :"Set a countdown timer." ,"parameters" : {"type" :"object" ,"properties" : {"minutes" : {"type" :"integer" },"label" : {"type" :"string" }},"required" : ["minutes" ,"label" ]}}}, 268 {"type" :"function" ,"function" : {"name" :"search_docs" ,"description" :"Search the internal documentation." ,"parameters" : {"type" :"object" ,"properties" : {"query" : {"type" :"string" },"limit" : {"type" :"integer" }},"required" : ["query" ,"limit" ]}}}, 269 {"type" :"function" ,"function" : {"name" :"send_email" ,"description" :"Send an email." ,"parameters" : {"type" :"object" ,"properties" : {"to" : {"type" :"string" },"subject" : {"type" :"string" },"body" : {"type" :"string" }},"required" : ["to" ,"subject" ,"body" ]}}}, 270] 271TOOL_CASES = [ 272 ("What's the weather in Paris right now? I want Celsius." , ("get_weather" , {"city" :"paris" ,"unit" :"c" })), 273 ("Tell me the temperature in Denver in Fahrenheit." , ("get_weather" , {"city" :"denver" ,"unit" :"f" })), 274 ("Set a timer for 25 minutes labelled pasta." , ("set_timer" , {"minutes" :25 ,"label" :"pasta" })), 275 ("Look up 'rotate api keys' in the docs, give me the top 5 results." , ("search_docs" , {"query" :"rotate api keys" ,"limit" :5 })), 276 ("Email bob@example.com with subject 'Lunch' and body 'Noon works for me.'" , ("send_email" , {"to" :"bob@example.com" ,"subject" :"lunch" ,"body" :"noon works for me." })), 277 ("Remind me in 90 minutes to call mom, use the label 'call mom'." , ("set_timer" , {"minutes" :90 ,"label" :"call mom" })), 278 ("What is the capital of France?" ,None ), 279 ("Explain in one sentence what a hash table is." ,None ), 280] 281 282def make_tools (): 283out = [] 284for i , (q ,exp )in enumerate (TOOL_CASES ,1 ): 285calls = [{"name" :exp [0 ],"arguments" :exp [1 ]}]if exp else [] 286out .append ({"id" :"tool-%02d" % i ,"category" :"tools" ,"max_tokens" :512 ,"grader" :"tool" ,"expected_call" :exp ,"tools" :TOOLS , 287"oracle_calls" :calls ,"oracle" :None ,"messages" : [{"role" :"system" ,"content" :"You are a helpful assistant. Use a tool only when one is needed." }, {"role" :"user" ,"content" :q }]}) 288return out 289 290def _eqv (a ,b ): 291if isinstance (a ,str )and isinstance (b ,str ): 292return a .strip ().lower ()== b .strip ().lower () 293return a == b 294 295def grade_tool (task ,res ): 296exp ,calls = task ["expected_call" ],res ["tool_calls" ] 297if exp is None : 298return (len (calls )== 0 ), {"calls" :calls } 299if not calls : 300return False , {"calls" :calls ,"note" :"no tool call" } 301c = calls [0 ] 302ok = c ["name" ]== exp [0 ]and set (c ["arguments" ].keys ())== set (exp [1 ].keys ())and all (_eqv (c ["arguments" ].get (k ),v )for k ,v in exp [1 ].items ()) 303return ok , {"calls" :calls } 304 305# --------------------------------------------------------------------------- tasks: completeness 306PRIMES = [p for p in range (2 ,600 )if all (p % d for d in range (2 ,int (p ** .5 )+ 1 ))][:100 ] 307ELEMENTS = ["H" ,"He" ,"Li" ,"Be" ,"B" ,"C" ,"N" ,"O" ,"F" ,"Ne" ,"Na" ,"Mg" ] 308SECTIONS = ["Overview" ,"Installation" ,"Usage" ,"Configuration" ,"Troubleshooting" ,"License" ] 309 310def make_complete (): 311def t (id ,q ,mt ,kind ,oracle ,** kw ): 312d = {"id" :"complete-" + id ,"category" :"complete" ,"max_tokens" :mt ,"grader" :"complete" ,"kind" :kind ,"oracle" :oracle , 313"messages" : [{"role" :"user" ,"content" :q }]} 314d .update (kw );return d 315js = json .dumps ([{"id" :i ,"name" :"item%d" % i ,"squares" :i * i }for i in range (1 ,21 )]) 316return [ 317t ("primes100" ,"List the first 100 prime numbers, comma-separated, in ascending order. Output only the numbers." ,2048 ,"ints" ,", " .join (map (str ,PRIMES )),expected_ints = PRIMES ), 318t ("count150" ,"Write the integers from 1 to 150 separated by single spaces. Output only the numbers." ,2048 ,"ints" ," " .join (map (str ,range (1 ,151 ))),expected_ints = list (range (1 ,151 ))), 319t ("alpha_rev" ,"Write the English alphabet in reverse order, uppercase letters separated by commas. Output only the letters." ,512 ,"letters" ,", " .join (chr (c )for c in range (90 ,64 ,- 1 )),expected_letters = [chr (c )for c in range (90 ,64 ,- 1 )]), 320t ("sections" ,"Write a project README in Markdown with exactly these H2 sections, in this order: %s. Every section must contain at least 3 full sentences." % ", " .join (SECTIONS ),2048 ,"sections" , 321"\n" .join ("## %s\nThis is sentence one. This is sentence two. This is sentence three.\n" % s for s in SECTIONS )), 322t ("json20" ,"Output a JSON array of exactly 20 objects. Object i (i from 1 to 20) has keys \"id\" (= i), \"name\" (= \"item<i>\") and \"squares\" (= i*i). Output only the JSON." ,2048 ,"json" ,"```json\n%s\n```" % js ), 323t ("elements" ,"Make a Markdown table of the first 12 chemical elements by atomic number with columns: Number, Symbol, Name." ,1024 ,"elements" , 324"| Number | Symbol | Name |\n|---|---|---|\n" + "\n" .join ("| %d | %s | x |" % (i + 1 ,s )for i ,s in enumerate (ELEMENTS ))), 325 ] 326 327def grade_complete (task ,res ): 328txt ,k = res ["text" ],task ["kind" ] 329fin = res ["finish_reason" ]in ("stop" ,"end_turn" ,None )and res ["finish_reason" ]!= "length" 330info = {"finish_reason" :res ["finish_reason" ]} 331if k == "ints" : 332got = [int (x )for x in re .findall (r"\d+" ,txt )] 333ok = got == task ["expected_ints" ];info .update (got_n = len (got ),want_n = len (task ["expected_ints" ])) 334elif k == "letters" : 335got = re .findall (r"\b([A-Z])\b" ,txt );ok = got == task ["expected_letters" ];info .update (got_n = len (got )) 336elif k == "sections" : 337heads = re .findall (r"^##\s+(.+?)\s*$" ,txt ,re .M );ok = heads == SECTIONS 338if ok : 339parts = re .split (r"^##\s+.+$" ,txt ,flags = re .M )[1 :] 340ok = len (parts )== 6 and all (len (re .findall (r"[.!?](\s|$)" ,p ))>= 3 for p in parts ) 341info ["headings" ]= heads 342elif k == "json" : 343m = re .search (r"```(?:json)?\s*(.*?)```" ,txt ,re .S );body = m .group (1 )if m else txt 344try : 345arr = json .loads (body );ok = isinstance (arr ,list )and len (arr )== 20 and all (o .get ("id" )== i + 1 and o .get ("name" )== "item%d" % (i + 1 )and o .get ("squares" )== (i + 1 )** 2 for i ,o in enumerate (arr )) 346except Exception as ex : 347ok = False ;info ["error" ]= repr (ex )[:120 ] 348elif k == "elements" : 349syms = [c .strip ()for line in txt .splitlines ()if line .strip ().startswith ("|" )for c in [line .split ("|" )[2 ]]if len (line .split ("|" ))> 3 ] 350syms = [s for s in syms if s in ELEMENTS or re .fullmatch (r"[A-Z][a-z]?" ,s )] 351ok = syms [:12 ]== ELEMENTS and len (syms )== 12 ;info ["symbols" ]= syms 352else : 353ok = False 354info ["finished" ]= fin 355return bool (ok and fin ),info 356 357# --------------------------------------------------------------------------- tasks: long-context recall + speed prompts 358NOUNS = ["harbor" ,"lantern" ,"orchard" ,"bridge" ,"archive" ,"glacier" ,"market" ,"workshop" ,"canal" ,"observatory" ,"foundry" ,"meadow" ] 359ADJ = ["quiet" ,"old" ,"crowded" ,"northern" ,"abandoned" ,"busy" ,"narrow" ,"famous" ,"remote" ,"sunlit" ] 360VERB = ["recorded" ,"measured" ,"reported" ,"counted" ,"inspected" ,"catalogued" ] 361CITY = ["Aldermoor" ,"Brindle" ,"Casterly" ,"Dunmere" ,"Eastwick" ,"Fairholt" ,"Greyvale" ,"Hollin" ] 362 363def filler (n_chars ,rnd ): 364parts ,size = [],0 365while size < n_chars : 366s = "The %s %s of %s %s %d %s during week %d of the survey. " % (rnd .choice (ADJ ),rnd .choice (NOUNS ),rnd .choice (CITY ),rnd .choice (VERB ),rnd .randint (11 ,989 ),rnd .choice (NOUNS )+ "s" ,rnd .randint (1 ,52 )) 367parts .append (s );size += len (s ) 368return parts 369 370def make_longctx (sizes_k ): 371out = [] 372for k in sizes_k : 373rnd = random .Random (SEED + k ) 374parts = filler (int (k * 1024 * 3.6 ),rnd )# ~3.6 chars/token for this filler -> approx k thousand tokens 375names = rnd .sample (["Orion" ,"Vesper" ,"Calder" ,"Mistral" ,"Juniper" ,"Tamsin" ,"Quillon" ,"Bracken" ],3 ) 376codes = ["%06d" % rnd .randint (100000 ,999999 )for _ in range (3 )] 377for frac ,nm ,cd in zip ((0.2 ,0.5 ,0.8 ),names ,codes ): 378parts .insert (int (len (parts )* frac ),"NOTE: The access code for vault %s is %s. " % (nm ,cd )) 379doc = "" .join (parts ) 380q = "Below is a long survey log. Read it, then answer the question at the end.\n\n%s\n\nQuestion: What are the access codes for vaults %s, %s and %s? Reply exactly in the form '%s=<code>, %s=<code>, %s=<code>'." % (doc ,names [0 ],names [1 ],names [2 ],names [0 ],names [1 ],names [2 ]) 381out .append ({"id" :"longctx-%dk" % k ,"category" :"longctx" ,"max_tokens" :200 ,"grader" :"longctx" ,"names" :names ,"codes" :codes , 382"messages" : [{"role" :"user" ,"content" :q }],"oracle" :", " .join ("%s=%s" % p for p in zip (names ,codes ))}) 383return out 384 385def grade_longctx (task ,res ): 386hits = [bool (re .search (r"%s\s*=\s*%s" % (n ,c ),res ["text" ]))for n ,c in zip (task ["names" ],task ["codes" ])] 387return all (hits ), {"hits" :hits ,"fraction" :sum (hits )/ 3 } 388 389def make_speed (prompt_ks ,gen_tokens ): 390out = [{"id" :"speed-short" ,"category" :"speed" ,"max_tokens" :gen_tokens ,"grader" :"none" ,"oracle" :"x" , 391"messages" : [{"role" :"user" ,"content" :"Write a detailed explanation of how a refrigerator works, in plain prose, at least 400 words." }]}] 392for k in prompt_ks : 393rnd = random .Random (SEED + 100 + k ) 394doc = "" .join (filler (int (k * 1024 * 3.6 ),rnd )) 395out .append ({"id" :"speed-prefill-%dk" % k ,"category" :"speed" ,"max_tokens" :64 ,"grader" :"none" ,"oracle" :"x" , 396"messages" : [{"role" :"user" ,"content" :"Summarize this log in two sentences.\n\n" + doc }]}) 397return out 398 399GRADERS = {"answer" :grade_answer ,"code" :grade_code ,"tool" :grade_tool ,"complete" :grade_complete ,"longctx" :grade_longctx ,"none" :lambda t ,r : (None , {})} 400 401# --------------------------------------------------------------------------- run 402def build_tasks (args ): 403cats = set (args .suite .split ("," )) 404tasks = [] 405if "reasoning" in cats :tasks += make_reasoning () 406if "code" in cats :tasks += make_code () 407if "tools" in cats :tasks += make_tools () 408if "complete" in cats :tasks += make_complete () 409if "longctx" in cats :tasks += make_longctx ([int (x )for x in args .longctx_k .split ("," )]) 410if "speed" in cats :tasks += make_speed ([int (x )for x in args .speed_k .split ("," )],args .gen_tokens ) 411return tasks 412 413def selftest (args ): 414args .suite = "reasoning,code,tools,complete,longctx" ;args .longctx_k = "1" 415tasks = build_tasks (args ) 416bad = 0 417for t in tasks : 418if t ["category" ]== "code" : 419oracle = Result (text = "```python\n%s\n```" % REF_IMPL [t ["fn" ]],finish_reason = "stop" ,tool_calls = []) 420elif t ["category" ]== "tools" : 421oracle = Oracle (True )(t ) 422else : 423oracle = Oracle (True )(t ) 424good ,_ = GRADERS [t ["grader" ]](t ,oracle ) 425garb = Oracle (False )(t ) 426if t ["category" ]== "tools" :# garbage = a bogus call; restraint cases fail it too 427garb = Result (text = "" ,finish_reason = "tool_calls" ,tool_calls = [{"name" :"bogus" ,"arguments" : {}}]) 428if t ["category" ]== "code" :garb = Result (text = "no code" ,finish_reason = "stop" ,tool_calls = []) 429gg ,_ = GRADERS [t ["grader" ]](t ,garb ) 430if not good or gg : 431bad += 1 ;"SELFTEST FAIL %s oracle_pass=%s garbage_pass=%s" % (t ["id" ],good ,gg )) 432"selftest: %d tasks, %d problems" % (len (tasks ),bad )) 433return 1 if bad else 0 434 435def main (): 436ap = argparse .ArgumentParser () 437ap .add_argument ("--engine" ,choices = ["openai" ,"ollama" ]);ap .add_argument ("--base" ,help = "e.g. http://127.0.0.1:8080" ) 438ap .add_argument ("--model" ,default = "m" );ap .add_argument ("--arm" ,help = "label for this arm, e.g. strata-iq2xs-p40x1" ) 439ap .add_argument ("--suite" ,default = "speed,reasoning,code,tools,complete,longctx" ) 440ap .add_argument ("--think" ,choices = ["off" ,"on" ],default = "off" ) 441ap .add_argument ("--reps" ,type = int ,default = 1 );ap .add_argument ("--num-ctx" ,type = int ,default = 32768 ) 442ap .add_argument ("--longctx-k" ,default = "4,12,24" );ap .add_argument ("--speed-k" ,default = "4,16" );ap .add_argument ("--gen-tokens" ,type = int ,default = 400 ) 443ap .add_argument ("--timeout" ,type = int ,default = 3600 );ap .add_argument ("--out" ,default = "results/raw" ) 444ap .add_argument ("--only" ,help = "comma list of task id prefixes" );ap .add_argument ("--meta" ,default = "{}" ,help = "JSON string recorded in every record" ) 445ap .add_argument ("--selftest" ,action = "store_true" ) 446args = ap .parse_args () 447if args .selftest : 448sys .exit (selftest (args )) 449tasks = build_tasks (args ) 450if args .only : 451pre = tuple (args .only .split ("," ));tasks = [t for t in tasks if t ["id" ].startswith (pre )] 452os .makedirs (args .out ,exist_ok = True ) 453path = os .path .join (args .out ,"%s.%s.jsonl" % (args .arm ,datetime .datetime .now ().strftime ("%Y%m%dT%H%M%S" ))) 454meta = json .loads (args .meta );think = args .think == "on" 455"arm=%s engine=%s tasks=%d reps=%d think=%s -> %s" % (args .arm ,args .engine ,len (tasks ),args .reps ,args .think ,path ),flush = True ) 456with open (path ,"a" )as fh : 457for rep in range (args .reps ): 458for t in tasks : 459rec = {"arm" :args .arm ,"rep" :rep ,"id" :t ["id" ],"category" :t ["category" ],"think" :args .think ,"ts" :datetime .datetime .now ().isoformat (timespec = "seconds" ),"meta" :meta } 460try : 461if args .engine == "openai" : 462res = call_openai (args .base ,args .model ,t ["messages" ],t ["max_tokens" ],think ,t .get ("tools" ),args .timeout ) 463else : 464res = call_ollama (args .base ,args .model ,t ["messages" ],t ["max_tokens" ],think ,t .get ("tools" ),args .timeout ,args .num_ctx ) 465ok ,info = GRADERS [t ["grader" ]](t ,res ) 466rec .update (res = res ,passed = ok ,grade = info ,error = None ) 467except Exception as ex : 468rec .update (res = None ,passed = False if t ["grader" ]!= "none" else None ,grade = {},error = "%s: %s" % (type (ex ).__name__ ,ex )) 469fh .write (json .dumps (rec )+ "\n" );fh .flush () 470r = rec ["res" ]or {} 471tp = (r .get ("server_timings" )or {}).get ("predicted_per_second" ) 472"%-24s pass=%-5s fin=%-10s ptok=%-6s ctok=%-5s t=%6.1fs srv_tps=%s %s" % (t ["id" ],rec ["passed" ],r .get ("finish_reason" ),r .get ("prompt_tokens" ),r .get ("completion_tokens" ),r .get ("t_total" )or 0 ,"%.1f" % tp if tp else "-" ,rec ["error" ]or "" ),flush = True ) 473"done:" ,path ) 474 475if __name__ == "__main__" : 476main ()