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