okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
abbf12caf
main
1"""Private-engine known-answer A/B/A soak; dry-run by default. 2 3Loads paired engines sequentially. Requires an exclusive model/GPU window, not 4an existing HTTP server. This is a synthetic cache gate, not a real-agent benchmark. 5""" 6import argparse 7import json 8from pathlib import Path 9import re 10import sys 11import threading 12 13ROOT = Path (__file__ ).resolve ().parents [1 ] 14sys .path [:0 ]= [str (ROOT ),str (ROOT / 'tools' )] 15from conversation_cache_parity import STATE_KEYS ,engine_args ,load_tokenizer ,require ,state_hashes 16from serve .server import StrataEngine ,child_env 17from serve .frontend import ChatTemplate 18 19 20def answer_text (text ): 21return text .replace ('<|im_end|>' ,'' ).replace ('<|endoftext|>' ,'' ).strip ().casefold () 22 23 24def verify (results ): 25contexts ,cycles = results ['contexts' ],results ['cycles' ] 26count = results ['requested_cycles' ] 27require (count >= 30 and len (cycles )== count ,'incomplete 30-cycle soak' ) 28require (len (contexts )>= 3 ,'need at least three context lengths' ) 29require (len ({c ['prompt_tokens' ]for c in contexts })== len (contexts ),'context lengths are not distinct' ) 30baseline ,candidate = results ['engine_info' ]['baseline' ],results ['engine_info' ]['candidate' ] 31for key in ('expert_slots' ,'kv' ,'kv_resident' ,'context' ,'spec' ,'mtp_max' ,'lookup' ,'cvec' ): 32require (baseline [key ]== candidate [key ],f'engine setting differs: { key } ' ) 33require (baseline ['conversation_cache_mib' ]== 0 and candidate ['conversation_cache_mib' ]> 0 , 34'invalid baseline/candidate cache configuration' ) 35lengths = [c ['prompt_tokens' ]for c in contexts ] 36require (candidate ['kv_resident' ]> 0 and max (lengths )> candidate ['kv_resident' ],'no streamed-KV coverage' ) 37require (max (lengths )>= .9 * candidate ['context' ],'longest prompt is not near the context limit' ) 38budget = candidate ['conversation_cache_mib' ]* 1024 * 1024 39for c in contexts : 40require (c ['baseline' ]['ids' ]and set (STATE_KEYS )<= c ['baseline' ]['state' ].keys (),'incomplete baseline' ) 41require (c ['baseline' ]['finish' ]in ('length' ,'stop' ),'baseline did not finish normally' ) 42require (answer_text (c ['baseline' ]['text' ])== c ['expected' ].casefold (),'baseline known answer is wrong' ) 43for i ,record in enumerate (cycles ): 44require (record ['cycle' ]== i and record ['context' ]== i % len (contexts ),'missing or reordered cycle' ) 45c = contexts [record ['context' ]] 46require (record ['finish' ]in ('length' ,'stop' )and record ['ids' ],'soak request failed' ) 47require (answer_text (record ['text' ])== c ['expected' ].casefold (),'restored known answer is wrong' ) 48require (record ['ids' ]== c ['baseline' ]['ids' ],'continuation token parity failed' ) 49require (record ['reused' ]>= c ['prompt_tokens' ],'return did not restore the long prefix' ) 50require (set (STATE_KEYS )<= record ['state' ].keys ()and record ['state' ]== c ['baseline' ]['state' ], 51'restored main-model state differs' ) 52require (0 <= record ['cache_bytes' ]<= budget ,'parked byte budget exceeded' ) 53# Compare steady-state retained snapshot payload, not allocator RSS or VRAM. 54# Sampled RSS is diagnostic: allocator high-water marks need not shrink, 55# and request-end samples do not establish a transient peak bound. 56for index in range (len (contexts )): 57tail = [r ['cache_bytes' ]for r in cycles if r ['context' ]== index ][- 3 :] 58require (len (tail )== 3 and len (set (tail ))== 1 ,'retained payload did not reach a stable plateau' ) 59 60 61def main (): 62ap = argparse .ArgumentParser (description = __doc__ ) 63ap .add_argument ('--config' ,type = Path ,required = True ) 64ap .add_argument ('--engine' ,type = Path ,required = True ) 65ap .add_argument ('--output' ,type = Path ,required = True ,help = 'new directory; existing paths refused' ) 66ap .add_argument ('--prompt-tokens' ,default = '2048,40000,120000' ,help = 'three increasing approximate prompt lengths' ) 67ap .add_argument ('--cycles' ,type = int ,default = 30 ) 68ap .add_argument ('--cache-mib' ,type = int ,default = 8192 ) 69ap .add_argument ('--run' ,action = 'store_true' ) 70args = ap .parse_args () 71try : 72lengths = [int (n )for n in args .prompt_tokens .split (',' )] 73except ValueError : 74ap .error ('prompt-tokens must contain three integers' ) 75if len (lengths )!= 3 or lengths != sorted (set (lengths ))or min (lengths )< 256 or args .cycles < 30 or args .cache_mib <= 0 : 76ap .error ('need three distinct increasing lengths >= 256, cycles >= 30 and cache-mib > 0' ) 77if not args .run : 78f'Dry run: { args . cycles } known-answer A/B/A cycles; approximate lengths { lengths } .' ) 79'No model loaded or files created. Use --run only in an exclusive GPU test window.' ) 80return 81cfg = json .loads (args .config .read_text (encoding = 'utf-8' )) 82path = Path (cfg ['tokenizer' ]) 83tok = load_tokenizer (path ) 84template = ChatTemplate (path / 'chat_template.jinja' ) 85def encode (text ): 86return tok .encode (text ,parse_special = True ) 87def prompt (text ): 88return encode (template .render ([{'role' :'user' ,'content' :text }],enable_thinking = False )) 89def long_prompt (target ,secret ,index ): 90paragraphs = max (1 ,target // 17 ) 91for _ in range (6 ): 92lines = [f'Record { i } : blue square, green triangle, red circle.' for i in range (paragraphs )] 93lines [paragraphs // 3 ]= f'The secret access code for conversation { index } is { secret } .' 94ids = prompt (f'Conversation { index } . Remember its secret access code for my next question.\n' + '\n' .join (lines )) 95delta = target - len (ids ) 96if abs (delta )< 64 : 97return ids 98paragraphs = max (1 ,paragraphs + delta // 17 ) 99return ids 100secrets = ['MANGO' ,'CEDAR' ,'RAVEN' ] 101prompts = [long_prompt (n ,secret ,i )for i , (n ,secret )in enumerate (zip (lengths ,secrets ))] 102suffix = encode ('<|im_end|>\n<|im_start|>user\nWhat is this conversation\'s secret access code? ' 103'Reply with only that one word, no punctuation.<|im_end|>\n' 104'<|im_start|>assistant\n<think>\n\n</think>\n\n' ) 105other = prompt ('Unrelated worker conversation. Reply with HELLO and nothing else.' ) 106args .output .mkdir (mode = 0o700 ,parents = False ,exist_ok = False ) 107env = child_env (cfg ) 108env ['STRATA_STATE_HASH' ]= '1' 109results = {'requested_cycles' :args .cycles ,'engine_info' : {},'contexts' : [],'cycles' : []} 110heads ,continuations = [], [] 111for label ,budget in [('baseline' ,0 ), ('candidate' ,args .cache_mib )]: 112log = args .output / f' { label } .log' 113engine = StrataEngine (str (args .engine .resolve ()),engine_args (cfg ,budget ,1 ), 114cwd = cfg .get ('cwd' ),log = str (log ),env = env ) 115results ['engine_info' ][label ]= dict (engine .info ) 116hash_count = 0 117def generate (ids ,count ): 118nonlocal hash_count 119output = [t for t in engine .generate (ids ,count , {'temperature' :0 },threading .Event ())if t is not None ] 120text = log .read_text (encoding = 'utf-8' ) 121hashes = state_hashes (text ) 122require (len (hashes )== hash_count + 1 and int (hashes [- 1 ]['L' ])>= len (ids ),'missing current state fingerprint' ) 123hash_count += 1 124state = hashes [- 1 ] 125occupancy = re .findall (r'parked=\d+ bytes=(\d+)' ,text ) 126rss = None 127try : 128match = re .search (r'^VmRSS:\s+(\d+) kB' ,Path (f'/proc/ { engine . proc . pid } /status' ).read_text (encoding = 'utf-8' ),re .M ) 129if match : 130rss = int (match [1 ])* 1024 131except OSError : 132pass 133return {'ids' :output ,'text' :tok .decode (output ),** engine .last ,'state' :state , 134'cache_bytes' :int (occupancy [- 1 ])if occupancy else 0 ,'sampled_rss_bytes' :rss } 135try : 136require (max (map (len ,prompts ))+ len (suffix )+ 64 < engine .max_context ,'test prompt exceeds context' ) 137if label == 'baseline' : 138for i ,ids in enumerate (prompts ): 139head = generate (ids ,1 ) 140require (len (head ['ids' ])== 1 ,'baseline initial output is missing' ) 141heads .append (head ['ids' ]) 142continuations .append (ids + head ['ids' ]+ suffix ) 143answer = generate (continuations [- 1 ],16 ) 144results ['contexts' ].append ({'expected' :secrets [i ],'prompt_tokens' :len (ids ),'baseline' :answer }) 145require (answer_text (answer ['text' ])== secrets [i ].casefold (),'baseline known answer is wrong' ) 146f'baseline length= { len ( ids ) } answer= { answer_text ( answer [ "text" ]) } ' ,flush = True ) 147else : 148primed = set () 149for cycle in range (args .cycles ): 150index = cycle % len (prompts ) 151if index not in primed : 152head = generate (prompts [index ],1 ) 153require (head ['ids' ]== heads [index ],'initial candidate output differs' ) 154primed .add (index ) 155generate (other ,1 ) 156answer = generate (continuations [index ],16 ) 157results ['cycles' ].append ({'cycle' :cycle ,'context' :index ,** answer }) 158f'cycle= { cycle + 1 } / { args . cycles } length= { len ( prompts [ index ]) } ' 159f'reused= { answer [ "reused" ] } answer= { answer_text ( answer [ "text" ]) } ' ,flush = True ) 160finally : 161engine .close () 162# Keep partial evidence on failure; verify rejects incomplete runs. 163 (args .output / 'results.json' ).write_text (json .dumps (results ,indent = 2 )+ '\n' ) 164verify (results ) 165'PASS: 30+ known-answer A/B/A cycles, streamed/near-limit KV, exact state/output, stable retained payload' ) 166 167 168if __name__ == '__main__' : 169main ()