okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
98d1c8d4f
main
1#!/usr/bin/env python3 2"""Three fresh benchy-fixture runs; content lives only in RAM and process memory.""" 3import argparse ,hashlib ,importlib .util ,json ,os ,re ,signal ,sys ,threading ,time 4from pathlib import Path 5 6R = Path (__file__ ).resolve ().parent 7 8def digest (x ): 9return hashlib .sha256 (json .dumps (x ).encode ()).hexdigest () 10 11def main (): 12ap = argparse .ArgumentParser () 13ap .add_argument ('--source' ,type = Path ,required = True ) 14ap .add_argument ('--profile' ,type = Path ,required = True ) 15ap .add_argument ('--ram' ,type = Path ,required = True ) 16ap .add_argument ('--out' ,type = Path ,required = True ) 17a = ap .parse_args () 18ram = a .ram ;out = a .out ;SOURCE = a .source 19assert str (ram .resolve ()).startswith ('/run/' )and ram .is_dir () 20out .mkdir (parents = True ,exist_ok = False ) 21sys .path [:0 ]= [str (SOURCE ),str (SOURCE / 'tools' )] 22from serve .server import StrataEngine ,ENGINE_REQUEST 23from serve .frontend import ChatTemplate 24from strata_tokenizer import Tokenizer 25cfg = json .loads (a .profile .read_text ()) 26cfg ['exe' ]= os .path .expandvars (cfg ['exe' ]);cfg ['cwd' ]= os .path .expandvars (cfg ['cwd' ]) 27cfg ['args' ]= [os .path .expandvars (x )for x in cfg ['args' ]] 28tok = Tokenizer .from_gguf (Path (cfg ['args' ][cfg ['args' ].index ('--native' )+ 1 ])) 29tpl = ChatTemplate (Path (cfg ['args' ][cfg ['args' ].index ('--pack' )+ 1 ])/ 'tokenizer/chat_template.jinja' ) 30public = [int (x )for x in (R / 'benchy-long.ids' ).read_text ().strip ().split (',' )] 31assert len (public )== 2185 32canary = tok .encode (tpl .render ([{'role' :'user' ,'content' :'Reply only with CANARY_MAPLE_73.' }],enable_thinking = False ),parse_special = True ) 33env = dict (os .environ );env ['STRATA_TRACE' ]= '1' ;assert 'STRATA_DBG_NAN' not in env 34short = [int (x )for x in (R / 'benchy-short.ids' ).read_text ().strip ().split (',' )];assert len (short )== 20 35class Engine (StrataEngine ): 36def _parse_done (self ,line ): 37self .done_line = line 38return super ()._parse_done (line ) 39cancel = threading .Event () 40signal .signal (signal .SIGTERM ,lambda * _ :cancel .set ()) 41signal .signal (signal .SIGINT ,lambda * _ :cancel .set ()) 42engine = None ;rows = [];failure = None ;life = {} 43streams = {} 44log = ram / 'native.log' 45def save (): 46 (out / 'requests.json' ).write_text (json .dumps (rows ,indent = 2 )+ '\n' ) 47 (out / 'lifecycle.json' ).write_text (json .dumps (life ,indent = 2 )+ '\n' ) 48def io (): 49return {k :int (v )for k ,v in (x .split (':' ,1 )for x in Path (f'/proc/ { engine . proc . pid } /io' ).read_text ().splitlines ())} 50def ask (ids ,cap ,label ,expected = None ): 51assert not cancel .is_set () 52offset = log .stat ().st_size ;before = io ();engine .done_line = None 53arrivals = [];output = [];start = time .monotonic () 54for t in engine .generate (ids ,cap , {'temperature' :0. ,'seed' :17 },cancel ): 55if t is not None :arrivals .append (time .monotonic ());output .append (t ) 56elapsed = time .monotonic ()- start ;after = io ();n = dict (engine .last ) 57text = tok .decode (output ).replace ('<|im_end|>' ,'' ).replace ('<|endoftext|>' ,'' ).strip () 58assert engine .done_line and n ['generated' ]== len (output )and n ['prompt_tokens' ]== len (ids ) 59assert n ['prompt_read' ]== len (ids )and n ['reused' ]== 0 and output and not cancel .is_set () 60if expected :assert text == expected 61with log .open ()as f :f .seek (offset );raw = f .read () 62assert not re .search (r'\b[1-9]\d* (?:of \d+ logits )?non-finite\b|\bnonfinite [1-9]\d*' ,raw ) 63allowed = [x for x in raw .splitlines ()if ENGINE_REQUEST .search (x )or 64re .match (r'^strata (?:trace: (?:read \d|lent \d|refilled \d|prompt chunk)|prefill timing:|prefill timing \(|serve: prompt|generate: prompt)' ,x )] 65row = {'label' :label ,'input_tokens' :len (ids ),'output_cap' :cap ,'output_tokens' :len (output ), 66'input_ids_sha256' :digest (ids ),'output_ids_sha256' :digest (output ),'native' :n , 67'native_done_line' :engine .done_line ,'prompt_tps' :len (ids )* 1000 / n ['prompt_ms' ], 68'decode_tps' :len (output )* 1000 / n ['decode_ms' ],'ttft_s' :arrivals [0 ]- start , 69'total_s' :elapsed ,'process_io_delta' :{k :after [k ]- before [k ]for k in before }, 70'numeric_trace' :allowed ,'valid' :True } 71prefixes = {} 72for k in (64 ,128 ,256 ,512 ,640 ): 73if len (output )>= k : 74prefixes [str (k )]= {'ids_sha256' :digest (output [:k ]),'post_first_tps' :None if k < 2 else (k - 1 )/ (arrivals [k - 1 ]- arrivals [0 ]),'after_prompt_elapsed_ms' :(arrivals [k - 1 ]- start )* 1000 - n ['prompt_ms' ]} 75row ['prefixes' ]= prefixes 76if label .startswith ('public2185' ): 77if 'public2185' in streams : 78row ['matches_previous_prefix' ]= streams ['public2185' ]== output [:len (streams ['public2185' ])] 79assert row ['matches_previous_prefix' ] 80else :streams ['public2185' ]= output 81row ['target' ]= label .rsplit ('-r' ,1 )[0 ] 82if row ['target' ].startswith ('public' ): 83ref = json .loads ((R / 'reference-public-hashes.json' ).read_text ())[row ['target' ]] 84row ['matches_prior_qualified_ids' ]= row ['output_ids_sha256' ]== ref 85assert row ['matches_prior_qualified_ids' ]and row ['output_tokens' ]== 256 86for prior in rows : 87if prior .get ('target' )== row ['target' ]: 88assert prior ['output_ids_sha256' ]== row ['output_ids_sha256' ] 89row ['matches_previous_repeat' ]= True 90rows .append (row );save () 91json .dumps ({k :row [k ]for k in ['label' ,'input_tokens' ,'output_tokens' ,'prompt_tps' ,'ttft_s' ,'total_s' ]}),flush = True ) 92try : 93life = {'mode' :'qualified-native-serving' ,'binary_sha256' :hashlib .file_digest (Path (cfg ['exe' ]).open ('rb' ),'sha256' ).hexdigest (), 94'args' :cfg ['args' ],'diagnostic_env' :{k :env [k ]for k in ['STRATA_TRACE' ,'STRATA_STAGER_THREADS' ,'OMP_NUM_THREADS' ,'MKL_NUM_THREADS' ]}, 95'intermediate_tensor_diagnostic' :env .get ('STRATA_DBG_NAN' ),'instrumented' :False } 96life ['launches' ]= [] 97for rep in range (1 ,4 ): 98assert not cancel .is_set ();streams .clear () 99log = ram / ('native-' + str (rep )+ '.log' ) 100start = time .monotonic () 101engine = Engine (cfg ['exe' ],cfg ['args' ],cwd = cfg ['cwd' ],log = str (log ),env = env ) 102launch = {'repeat' :rep ,'startup_ready_s' :time .monotonic ()- start ,'info' :engine .info } 103life ['launches' ].append (launch );save () 104ask (public ,256 ,'public2185-256-r' + str (rep )) 105ask (short ,256 ,'public20-256-r' + str (rep )) 106ask (canary ,64 ,'canary-end-r' + str (rep ),'CANARY_MAPLE_73' ) 107p = engine .proc ;start = time .monotonic ();p .stdin .write ('QUIT\n' );p .stdin .flush ();p .wait (timeout = 75 ) 108launch .update (native_exit = p .returncode ,quit_exit_s = time .monotonic ()- start );assert p .returncode == 0 109engine .close ();engine = None 110for _ in range (5 ):time .sleep (1 );assert not cancel .is_set () 111raw = log .read_text () 112launch ['startup_geometry' ]= [x for x in raw .splitlines ()if re .match (r'^strata (?:generate|serve): (?:GPU \d+:|expert cache \d|\d+ of \d+ experts missing|\d+ MiB of VRAM free|prompt path|session is up)' ,x )] 113save () 114life ['native_exit' ]= 0 115except BaseException as e : 116failure = {'type' :type (e ).__name__ ,'reason' :str (e )} 117finally : 118if engine is not None : 119try : 120p = engine .proc ;start = time .monotonic ();p .stdin .write ('QUIT\n' );p .stdin .flush ();p .wait (timeout = 75 ) 121life .update (native_exit = p .returncode ,quit_exit_s = time .monotonic ()- start ) 122assert p .returncode == 0 123engine .close ();engine = None 124for _ in range (5 ):time .sleep (1 );assert not cancel .is_set () 125except BaseException as e : 126failure = failure or {'type' :type (e ).__name__ ,'reason' :str (e )} 127save () 128 (out / 'result.json' ).write_text (json .dumps ({'failure' :failure ,'requests' :len (rows ),'native_exit' :life .get ('native_exit' ),'content_persisted' :False },indent = 2 )+ '\n' ) 129if failure :raise SystemExit (1 ) 130 131if __name__ == '__main__' :main ()