okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8ac4b945a
main
1"""#528: decode speed after a conversation-cache restore, against the same turns kept live. 2 3Two private engines run one after the other (never an existing server): 4baseline --conversation-cache-mib 0: conversation A, turn after turn, continues live 5candidate --conversation-cache-mib N: between A's turns an unrelated conversation B parks A, so every later 6turn of A is restored from its parked snapshot 7Each A turn's greedy output must be the same token for token in both, and its decode speed should be too (a 8restored conversation decodes like a live one). --mode same: one conversation whose client re-renders each reply 9(no parking needed); --mode pair: two long conversations take turns (a snapshot restored every turn). On a PC with 10little RAM the cache's physical-RAM floor may refuse to park (the log says "skip parking"): that turn reads its 11prompt again and is reported as not restored. Dry-run by default; --run needs the GPU (and its lock). 12 13Measured on the RTX 5070 (0.1.38, #528): Q2_0 37K tokens --kv-resident 16384, IQ3_XXS 50-75K tokens 14--kv-resident 32768 (switch, same and pair modes): restored turns decode at the live turns' speed, same tokens. 15 16python tools/conversation_restore_speed.py --config cfg.json --engine build-release/strata.exe \ 17--output out-dir --tokens 40000 --set=--max-context=65536 --set=--kv-resident=16384 --run 18""" 19import argparse 20import json 21from pathlib import Path 22import sys 23import threading 24 25ROOT = Path (__file__ ).resolve ().parents [1 ] 26sys .path [:0 ]= [str (ROOT ),str (ROOT / 'tools' )] 27 28 29def override (args ,pairs ): 30"""cfg args with each `--flag value` of pairs replacing the config's own (or appended).""" 31out = list (args ) 32for flag ,value in pairs : 33if flag in out : 34i = out .index (flag ) 35if value is None : 36del out [i :i + 2 ] 37else : 38out [i + 1 ]= value 39elif value is not None : 40out += [flag ,value ] 41return out 42 43 44def parse_sets (items ): 45pairs = [] 46for item in items or []: 47flag ,_ ,value = item .partition ('=' ) 48pairs .append ((flag ,value if value != '' else None )) 49return pairs 50 51 52def summarize (records ): 53rows = [] 54for r in records : 55tok_s = r ['generated' ]/ (r ['decode_ms' ]/ 1000 )if r .get ('decode_ms' )else 0.0 56acc = f" { r . get ( 'drafts_accepted' , 0 ) } / { r . get ( 'drafts_offered' , 0 ) } " 57rows .append (f" { r [ 'name' ]:<8 } reused= { r . get ( 'reused' , 0 ):>6 } gen= { r [ 'generated' ]:>4 } " 58f"decode= { tok_s :6.1f } tok/s drafts= { acc :<9 } hits= { r . get ( 'hits' , 0 ) } / { r . get ( 'lookups' , 0 ) } " ) 59return '\n' .join (rows ) 60 61 62def compare (results ,tolerance ): 63"""The A turns: identical ids, restored (reused > 0) in the candidate, and decode within `tolerance`.""" 64base = {r ['name' ]:r for r in results ['baseline' ]} 65problems = [] 66for r in results ['candidate' ]: 67if not r ['name' ].startswith ('A' ): 68continue 69b = base .get (r ['name' ]) 70if b is None : 71problems .append (f" { r [ 'name' ] } : no baseline turn" ) 72continue 73if r ['ids' ]!= b ['ids' ]: 74problems .append (f" { r [ 'name' ] } : output differs from the live baseline" ) 75if r ['name' ]!= 'A1' and not r .get ('reused' ): 76problems .append (f" { r [ 'name' ] } : not restored (reused=0)" ) 77speed = lambda x :x ['generated' ]/ (x ['decode_ms' ]/ 1000 )if x .get ('decode_ms' )else 0.0 78if r ['name' ]!= 'A1' and speed (r )< (1 - tolerance )* speed (b ): 79problems .append (f" { r [ 'name' ] } : restored decode { speed ( r ):.1f } tok/s vs live { speed ( b ):.1f } " ) 80return problems 81 82 83def main (): 84ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 85ap .add_argument ('--config' ,type = Path ,required = True ) 86ap .add_argument ('--engine' ,type = Path ,required = True ) 87ap .add_argument ('--output' ,type = Path ,required = True ,help = 'new directory; an existing path is refused' ) 88ap .add_argument ('--tokens' ,type = int ,default = 20000 ,help = 'about this many prompt tokens in A' ) 89ap .add_argument ('--gen' ,type = int ,default = 160 ,help = 'tokens generated per A turn' ) 90ap .add_argument ('--turns' ,type = int ,default = 3 ,help = 'A turns (the first is read fresh)' ) 91ap .add_argument ('--cache-mib' ,type = int ,default = 8192 ) 92ap .add_argument ('--set' ,action = 'append' ,metavar = 'FLAG=VALUE' , 93help = 'override an engine flag of the config (FLAG= drops it); repeatable' ) 94ap .add_argument ('--tolerance' ,type = float ,default = 0.15 ,help = 'allowed decode shortfall of a restored turn' ) 95ap .add_argument ('--only' ,choices = ('baseline' ,'candidate' ),help = 'run one side only (no comparison)' ) 96ap .add_argument ('--mode' ,choices = ('switch' ,'same' ,'pair' ),default = 'switch' , 97help = 'switch: B parks A between turns; same: one conversation whose client drops the last ' 98'--trim tokens of each reply (re-rendered history), as agent clients do; pair: two long ' 99'conversations A and C take turns (each turn restores a big snapshot, the cache holds two)' ) 100ap .add_argument ('--trim' ,type = int ,default = 8 ) 101ap .add_argument ('--run' ,action = 'store_true' ) 102a = ap .parse_args () 103if not a .run : 104'Dry run: baseline (live turns) vs candidate (every turn after the first restored from a parked ' 105'snapshot); greedy, fixed residency. Use --run with the GPU free.' ) 106return 107from serve .server import StrataEngine ,child_env 108from serve .frontend import ChatTemplate 109from conversation_cache_parity import load_tokenizer 110cfg = json .loads (a .config .read_text (encoding = 'utf-8' )) 111p = Path (cfg ['tokenizer' ]) 112tok = load_tokenizer (p ) 113tpl = ChatTemplate (p / 'chat_template.jinja' ) 114enc = lambda text :tok .encode (text ,parse_special = True ) 115colors = ('blue' ,'green' ,'red' ,'amber' ,'violet' ,'teal' ,'grey' ,'white' ) 116shapes = ('square' ,'triangle' ,'circle' ,'hexagon' ,'star' ,'ring' ) 117 118def doc (label ,n ): 119lines = [f' { label } : here is an inventory list to remember.' ] 120i = 0 121while len (lines )* 15 < n : 122lines .append (f'Record { i } : a { colors [ i % 8 ] } { shapes [( i * 7 ) % 6 ] } stored in bin { ( i * 37 ) % 997 } .' ) 123i += 1 124return '\n' .join (lines ) 125 126ask = 'Write a long, detailed story that uses as many of the records above as you can.' 127A = enc (tpl .render ([{'role' :'user' ,'content' :doc ('Conversation A' ,a .tokens )+ '\n' + ask }], 128enable_thinking = False )) 129B = enc (tpl .render ([{'role' :'user' ,'content' :doc ('Unrelated conversation B' ,2000 )+ '\nName one bin.' }], 130enable_thinking = False )) 131follow = [enc ('<|im_end|>\n<|im_start|>user\nContinue the story, with new records.<|im_end|>\n' 132'<|im_start|>assistant\n<think>\n\n</think>\n\n' )] 133a .output .mkdir (parents = False ,exist_ok = False ) 134env = child_env (cfg ) 135base_args = override (cfg ['args' ],parse_sets (a .set )+ [('--adapt-swaps' ,'0' ), ('--prompt-cache' ,'6' )]) 136results = {'prompt_tokens' :len (A ),'args' :base_args } 137sides = [('baseline' ,0 ), ('candidate' ,a .cache_mib )] 138if a .only : 139sides = [s for s in sides if s [0 ]== a .only ] 140for label ,budget in sides : 141args = base_args + ['--conversation-cache-mib' ,str (budget ),'--conversation-cache-slots' ,'4' ] 142engine = StrataEngine (str (a .engine .resolve ()),args ,cwd = cfg .get ('cwd' ),log = str (a .output / f' { label } .log' ), 143env = env ) 144records = [] 145 146def generate (ids ,count ,name ): 147out = [t for t in engine .generate (ids ,count , {'temperature' :0 },threading .Event ())if t is not None ] 148records .append ({'name' :name ,'ids' :out ,** engine .last }) 149f' { label } { summarize ( records [ - 1 :]). strip () } ' ,flush = True ) 150return out 151 152try : 153convo = list (A ) 154other = enc (tpl .render ([{'role' :'user' ,'content' :doc ('Second long conversation C' ,a .tokens )+ '\n' + 155ask }],enable_thinking = False ))if a .mode == 'pair' else None 156for turn in range (1 ,a .turns + 1 ): 157if other is not None and budget :# C's turn first: A comes back from its snapshot after it 158out_c = generate (other ,a .gen if turn == 1 else 32 ,f'C { turn } ' ) 159other = other + out_c + follow [0 ] 160if turn > 1 : 161if budget and a .mode == 'switch' : 162generate (B ,1 ,f'B { turn } ' )# parks A: this turn of A comes back from the snapshot 163convo += follow [0 ] 164out = generate (convo ,a .gen ,f'A { turn } ' ) 165convo += out [:- a .trim ]if a .mode == 'same' and len (out )> a .trim else out 166finally : 167engine .close () 168results [label ]= records 169 (a .output / 'results.json' ).write_text (json .dumps (results ,indent = 1 )+ '\n' ) 170for label ,_ in sides : 171f' { label } :\n { summarize ( results [ label ]) } ' ) 172if a .only : 173return 174problems = compare (results ,a .tolerance ) 175for line in problems : 176'FAIL ' + line ) 177'PASS: restored turns decode like live ones, same output' if not problems else 'FAILED' ) 178sys .exit (1 if problems else 0 ) 179 180 181if __name__ == '__main__' : 182main ()