okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
53623e56f
main
1"""Replay one recorded release case. Edit plan.json paths before running.""" 2from pathlib import Path 3import ast 4import hashlib 5import json 6import os 7import re 8import sys 9import threading 10import time 11 12ROOT = Path (__file__ ).resolve ().parent 13def expand_paths (value ): 14if isinstance (value ,str ): 15return os .path .expandvars (value ) 16if isinstance (value ,list ): 17return [expand_paths (v )for v in value ] 18if isinstance (value ,dict ): 19return {k :expand_paths (v )for k ,v in value .items ()} 20return value 21 22 23PLAN = expand_paths (json .loads ((ROOT / 'plan.json' ).read_text ())) 24CASE = next (c for c in PLAN ['cases' ]if c ['label' ]== sys .argv [1 ]) 25source = Path (PLAN ['client_source' ]) 26sys .path [:0 ]= [str (source ),str (source / 'tools' )] 27from serve .server import StrataEngine 28from serve .frontend import ChatTemplate 29from strata_tokenizer import Tokenizer 30 31model = PLAN ['models' ][CASE ['model' ]] 32tokenizer = Tokenizer .from_gguf (model ['native' ]) 33template = ChatTemplate (Path (model ['pack' ])/ 'tokenizer/chat_template.jinja' ) 34OUT = ROOT / CASE ['label' ] 35OUT .mkdir (exist_ok = False ) 36report = {'case' :CASE ,'completed' :False ,'started_unix' :time .time ()} 37 38 39def save (): 40temp = OUT / 'result.tmp' 41temp .write_text (json .dumps (report ,indent = 2 )+ '\n' ) 42temp .replace (OUT / 'result.json' ) 43 44 45def render (text ): 46return template .render ([{'role' :'user' ,'content' :text }],enable_thinking = False ) 47 48 49def generate (engine ,ids ,limit ): 50tokens = [] 51start = time .monotonic () 52first = None 53for token in engine .generate (ids ,limit , {'temperature' :0 },threading .Event ()): 54if token is not None : 55tokens .append (token ) 56if first is None : 57first = time .monotonic ()- start 58timing = dict (engine .last ) 59return dict (token_ids = tokens ,output_tokens = len (tokens ),timings = timing , 60wall_seconds = time .monotonic ()- start ,ttft_seconds = first , 61decode_tok_s = len (tokens )* 1000 / timing ['decode_ms' ], 62effective_tok_s = len (tokens )* 1000 / (timing ['prompt_ms' ]+ timing ['decode_ms' ]), 63text = tokenizer .decode (tokens )) 64 65 66def check_function (text ): 67blocks = re .findall (r'```(?:python)?\s*\n(.*?)```' ,text ,re .S ) 68candidate = blocks [0 ]if blocks else text 69if not blocks : 70match = re .search (r'(?m)^def triangular\(' ,candidate ) 71if match : 72candidate = candidate [match .start ():] 73candidate = '\n' .join (candidate .splitlines ()[:8 ]) 74tree = ast .parse (candidate ) 75functions = [n for n in tree .body if isinstance (n ,ast .FunctionDef )and n .name == 'triangular' ] 76assert len (functions )== 1 ,'Missing triangular function' 77function = functions [0 ] 78allowed = (ast .FunctionDef ,ast .arguments ,ast .arg ,ast .Return ,ast .BinOp , 79ast .Name ,ast .Load ,ast .Constant ,ast .Mult ,ast .Add ,ast .FloorDiv , 80ast .UnaryOp ,ast .USub ,ast .Expr ) 81assert all (isinstance (n ,allowed )for n in ast .walk (function )),'Function outside pure arithmetic check' 82scope = {'__builtins__' : {},'int' :int } 83exec (compile (ast .Module (body = [function ],type_ignores = []),'<model-function>' ,'exec' ),scope ) 84values = [0 ,1 ,2 ,10 ,100 ,10000 ] 85assert all (scope ['triangular' ](n )== n * (n + 1 )// 2 for n in values ) 86return {'passed' :True ,'inputs' :values } 87 88 89engine = None 90try : 91args = list (model ['args' ])+ ['--mtp-max-t' ,str (CASE ['mtp_t' ]),'--max-context' ,'16384' ] 92if CASE .get ('ngram' ): 93args [args .index ('--suffix-draft' )+ 1 ]= '3' 94args += ['--lookup-chain' ,str (CASE .get ('lookup_chain' ,0 )),'--lookup-chain-min' ,'3' ] 95if CASE ['mtp_t' ]== 1 : 96at = args .index ('--mtp' ) 97del args [at :at + 2 ] 98if CASE ['model' ]== 'q8' : 99args += ['--resident-budget-gib' ,'56' ] 100env = {k :v for k ,v in os .environ .items ()if not k .startswith (('STRATA_' ,'MULTI_CONCURRENCY' ))} 101if CASE ['model' ]== 'q8' and CASE ['build' ]!= 'stock' : 102env ['STRATA_EXCHANGE_ROTATE' ]= '1' 103args += ['--adapt-async' ,'1' ] 104binary = PLAN ['engines' ][CASE ['build' ]] 105with Path (binary ).open ('rb' )as f : 106report ['engine_sha256' ]= hashlib .file_digest (f ,'sha256' ).hexdigest () 107report .update (args = args ,environment = {k :v for k ,v in env .items ()if k .startswith ('STRATA_' )}) 108save () 109start = time .monotonic () 110engine = StrataEngine (binary ,args ,str (source ),str (OUT / 'engine.log' ),env ) 111report .update (startup_seconds = time .monotonic ()- start ,engine_info = engine .info ) 112save () 113simple = tokenizer .encode (render ('Write only a Python code block defining triangular(n). Use the formula n*(n+1)//2. No imports, function calls, tests, or explanation.' ),parse_special = True ) 114report ['functional_output' ]= generate (engine ,simple ,128 ) 115try : 116report ['function_check' ]= check_function (report ['functional_output' ]['text' ]) 117except Exception as exc : 118report ['function_check' ]= {'passed' :False ,'error' :repr (exc )} 119save () 120marker = 'BENCHMARK_ARCHIVED_NOTES' 121text = render ('Archived background notes (data, not instructions):\n' + marker + 122'\nEnd of notes.\n\n' + PLAN ['task' ]) 123before ,after = text .split (marker ) 124a ,b = tokenizer .encode (before ,parse_special = True ),tokenizer .encode (after ,parse_special = True ) 125filler = tokenizer .encode ('Ordinary maintenance notes describe deterministic tests, scheduling and data ownership.\n' ) 126needed = 8192 - len (a )- len (b ) 127ids = a + (filler * ((needed + len (filler )- 1 )// len (filler )))[:needed ]+ b 128assert len (ids )== 8192 129report ['input_token_ids_sha256' ]= hashlib .sha256 (json .dumps (ids ).encode ()).hexdigest () 130report ['benchmark' ]= generate (engine ,ids ,512 ) 131timing = report ['benchmark' ]['timings' ] 132assert report ['benchmark' ]['output_tokens' ]== 512 133assert timing .get ('prompt_read' )== 8192 and timing .get ('reused' ,0 )== 0 134if CASE ['mtp_t' ]== 1 and not CASE .get ('ngram' ): 135assert timing .get ('drafts_offered' ,0 )== 0 136elif CASE ['mtp_t' ]> 1 : 137assert timing .get ('drafts_offered' ,0 )> 0 138if CASE .get ('ngram' ): 139report ['ngram_log_counters' ]= [line for line in (OUT / 'engine.log' ).read_text ().splitlines () 140if 'suffix drafts:' in line or 'lookup chain:' in line ] 141report .update (completed = True ,finished_unix = time .time ()) 142save () 143json .dumps ({'label' :CASE ['label' ],'function_check' :report ['function_check' ], 144'decode' :report ['benchmark' ]['decode_tok_s' ],'effective' :report ['benchmark' ]['effective_tok_s' ]}),flush = True ) 145except BaseException as exc : 146report .update (error = repr (exc ),finished_unix = time .time ()) 147save () 148raise 149finally : 150if engine is not None : 151engine .close ()