okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
abbf12caf
main
1"""Full-model A/B/A parity gate. Loads private engines sequentially, never uses an existing server. 2 3Dry-run by default. --run requires an available GPU/model-loading window. 4""" 5import argparse 6import json 7from pathlib import Path 8import re 9import sys 10import threading 11 12ROOT = Path (__file__ ).resolve ().parents [1 ] 13sys .path [:0 ]= [str (ROOT ),str (ROOT / 'tools' )] 14from serve .server import StrataEngine ,child_env 15from serve .frontend import ChatTemplate 16import strata_tokenizer as ST 17 18# pooled: the completed indexer rows (the 0.1.29 extent); pooled_full: those plus the spare row 19STATE_KEYS = ('L' ,'gdn' ,'ple' ,'tail' ,'dead' ,'pooled' ,'pooled_full' ,'kv' ,'ple_prev' ) 20 21def require (condition ,message ): 22if not condition : 23raise AssertionError (message ) 24 25 26def load_tokenizer (path ): 27vocab = json .loads ((path / 'vocab.json' ).read_text (encoding = 'utf-8' )) 28tokens = [None ]* len (vocab ) 29for token ,index in vocab .items (): 30tokens [index ]= token 31return ST .Tokenizer (tokens , (path / 'merges.txt' ).read_text (encoding = 'utf-8' ).split ('\n' ), 32json .loads ((path / 'token_type.json' ).read_text (encoding = 'utf-8' ))) 33 34 35def state_hashes (text ): 36# Padding and the drafter's final uncomputed cell aren't main-model state. 37hashes = [] 38for line in text .splitlines (): 39if 'STATE_HASH L=' in line : 40fields = dict (re .findall (r'(\w+)=([0-9a-f,-]+)' ,line )) 41hashes .append ({key :fields [key ]for key in STATE_KEYS }) 42return hashes 43 44 45def engine_args (cfg ,budget ,spec ): 46# Native IQ packs require verifier capacity >= 2, even for one-token decode. 47return list (cfg ['args' ])+ [ 48'--conversation-cache-mib' ,str (budget ),'--conversation-cache-slots' ,'4' , 49'--prompt-cache' ,'6' ,'--adapt-swaps' ,'0' ,'--spec' ,str (max (2 ,spec )), 50'--mtp-max-t' ,str (spec ),'--suffix-draft' ,'0' ,'--spec-min-p' ,'0' ] 51 52 53def pressure_budget_hint (results ,budget_mib ): 54sizes = [p ['snapshot_bytes' ]for p in results ['pressure' ]['parks' ]if p .get ('snapshot_bytes' ,0 )> 0 ] 55message = f'Configured --cache-mib { budget_mib } .' 56if not sizes : 57return message + ' No snapshot sizes recorded; use an engine that reports snapshot_bytes.' 58mib = 1024 * 1024 59message += ' Observed snapshots: ' + ', ' .join (f' { n / mib :.2f } MiB ( { n } bytes)' for n in sizes )+ '.' 60if len (sizes )< 2 : 61return message + ' Need at least two captured snapshots to determine a pressure budget.' 62# Fit every individual image but no adjacent pair in the A/B/C sequence. 63low = (max (sizes )+ mib - 1 )// mib 64high = (min (a + b for a ,b in zip (sizes ,sizes [1 :]))- 1 )// mib 65if low <= high : 66message += f' Use --cache-mib { low } .. { high } to fit each snapshot but not two adjacent snapshots.' 67else : 68message += ' No whole-MiB budget fits every snapshot while excluding each adjacent pair; use similarly sized prompts.' 69return message 70 71 72def verify_pressure (results ,budget_mib ,oversized = False ): 73"""Require actual byte-pressure evidence, not just correct output on misses.""" 74baseline ,candidate = results ['baseline' ],results ['candidate' ] 75names = ['A' ,'B' ,'C' ,'A-again' ] 76for records in (baseline ,candidate ): 77require ([r ['name' ]for r in records ]== names ,'incomplete pressure sequence' ) 78for before ,after in zip (baseline ,candidate ): 79require (len (before ['ids' ])== len (after ['ids' ])== 1 ,'missing pressure output' ) 80require (before ['finish' ]in ('length' ,'stop' )and after ['finish' ]in ('length' ,'stop' ), 81'pressure request did not finish normally' ) 82require (before ['reused' ]== after ['reused' ]== 0 , 83'pressure did not force a cache miss; this run did not exercise the required fallback. ' + 84pressure_budget_hint (results ,budget_mib )) 85require (before ['ids' ]== after ['ids' ],'pressure output differs' ) 86keys = set (STATE_KEYS ) 87require (keys <= before ['state' ].keys ()and keys <= after ['state' ].keys (),'missing pressure state' ) 88require (before ['state' ]== after ['state' ],'pressure state differs' ) 89for key in ('expert_slots' ,'kv' ,'kv_resident' ,'context' ,'spec' ,'mtp_max' ,'lookup' ,'cvec' ): 90require (results ['engine_info' ]['baseline' ][key ]== results ['engine_info' ]['candidate' ][key ], 91f'pressure engine setting differs: { key } ' ) 92info = results ['engine_info' ]['candidate' ] 93require (info ['conversation_cache_mib' ]== budget_mib and info ['conversation_cache_slots' ]== 4 , 94'pressure cache configuration differs' ) 95evidence = results ['pressure' ] 96parks = evidence ['parks' ] 97require (all (p ['bytes' ]<= budget_mib * 1024 * 1024 for p in parks ),'byte budget exceeded' ) 98if oversized : 99require (evidence ['skips' ]== 3 and not parks ,'oversized snapshots were not all skipped' ) 100else : 101require (evidence ['skips' ]== 0 and len (parks )== 3 ,'snapshots must fit individually' ) 102require (all (0 < p ['parked' ]< 4 for p in parks ),'slot pressure confounds byte-pressure test' ) 103require (parks [- 1 ]['evictions' ]> 0 ,'no byte-pressure eviction observed. ' + 104pressure_budget_hint (results ,budget_mib )) 105 106 107def verify_results (results ,prompt_tokens ,spec ): 108"""Fail closed on incomplete evidence, even under python -O.""" 109baseline ,candidate = results ['baseline' ],results ['candidate' ] 110require ([r ['name' ]for r in baseline ]== ['A' ,'A+' ],'incomplete baseline' ) 111require ([r ['name' ]for r in candidate ]== ['A' ,'B' ,'A+' ,'B-again' ,'A+-checkpoint' ],'incomplete candidate' ) 112state_keys = set (STATE_KEYS ) 113for record in baseline + candidate : 114require (bool (record ['ids' ]),'missing generated tokens' ) 115require (record ['finish' ]in ('length' ,'stop' ),'request did not finish normally' ) 116require (state_keys <= record ['state' ].keys (),'incomplete state fingerprint' ) 117require (len (baseline [0 ]['ids' ])== len (candidate [0 ]['ids' ])== 1 ,'invalid initial A output length' ) 118require (baseline [0 ]['ids' ]== candidate [0 ]['ids' ],'initial A output differs' ) 119require (candidate [2 ]['reused' ]>= prompt_tokens ,'A was not restored after B' ) 120require (candidate [4 ]['reused' ]> 0 ,'parked checkpoint was not restored' ) 121for key in ('expert_slots' ,'kv' ,'kv_resident' ,'context' ,'spec' ,'mtp_max' ,'lookup' ,'cvec' ): 122require (results ['engine_info' ]['baseline' ][key ]== results ['engine_info' ]['candidate' ][key ], 123f'baseline/candidate engine setting differs: { key } ' ) 124for record in (candidate [2 ],candidate [4 ]): 125require (record ['ids' ]== baseline [1 ]['ids' ],'restored continuation output differs' ) 126if spec == 1 : 127require (record ['state' ]== baseline [1 ]['state' ],'restored main-model state differs' ) 128 129 130def verify_exchange (results ,prompt_tokens ,spec ,budget_mib ): 131verify_results (results ,prompt_tokens ,spec ) 132require (results ['engine_info' ]['candidate' ]['conversation_cache_mib' ]== budget_mib , 133'exchange cache budget differs' ) 134evidence = results ['pressure' ] 135require (evidence ['skips' ]== 2 and len (evidence ['parks' ])== 2 , 136'expected two parks and two outgoing skips while an incoming snapshot is held' ) 137require (all (p ['parked' ]== 1 and 0 < p ['bytes' ]<= budget_mib * 1024 * 1024 138for p in evidence ['parks' ]),'invalid exchange snapshot budget' ) 139 140 141def verify_admission (results ,budget_mib ,floor_mib ): 142evidence = results ['pressure' ] 143require (evidence ['memory_skips' ]== 3 and evidence ['skips' ]== 0 and not evidence ['parks' ], 144'expected physical-memory denial, not oversized-budget fallback' ) 145require (results ['engine_info' ]['candidate' ]['conversation_cache_min_free_mib' ]== floor_mib , 146'physical RAM floor differs' ) 147# The same four cold requests must preserve output and complete state. Reuse 148# the oversized gate's no-parking assertions after checking the actual cause. 149equivalent = {** results ,'pressure' : {** evidence ,'skips' :evidence ['memory_skips' ]}} 150verify_pressure (equivalent ,budget_mib ,oversized = True ) 151 152 153def main (): 154ap = argparse .ArgumentParser (description = __doc__ ) 155ap .add_argument ('--config' ,type = Path ,required = True ) 156ap .add_argument ('--engine' ,type = Path ,required = True ) 157ap .add_argument ('--output' ,type = Path ,required = True ,help = 'new private directory; existing paths refused' ) 158ap .add_argument ('--cache-mib' ,type = int ,default = 8192 ) 159ap .add_argument ('--paragraphs' ,type = int ,default = 128 ) 160ap .add_argument ('--scenario' ,choices = ('reuse' ,'pressure' ,'oversized' ,'exchange' ,'admission' ),default = 'reuse' , 161help = 'pressure requires snapshots fitting individually but not together; oversized requires none to fit' ) 162ap .add_argument ('--min-free-mib' ,type = int ,default = 2560 , 163help = 'physical RAM floor; for admission denial choose a value above available system RAM' ) 164ap .add_argument ('--spec' ,type = int ,default = 1 ,choices = range (1 ,9 ), 165help = 'decode window cap; 1 uses engine --spec 2 --mtp-max-t 1 for native IQ packs' ) 166ap .add_argument ('--run' ,action = 'store_true' ) 167a = ap .parse_args () 168if a .cache_mib <= 0 or a .paragraphs < 1 or not 0 <= a .min_free_mib <= (2 ** 63 - 1 )// (1024 * 1024 ): 169ap .error ('cache-mib/paragraphs must be positive and min-free-mib must fit the engine range' ) 170if not a .run : 171f'Dry run: { a . scenario } ; paired baseline/candidate; fixed residency, greedy output.' ) 172'No model loaded. Use --run only with a separately available GPU/test window.' ) 173return 174cfg = json .loads (a .config .read_text (encoding = 'utf-8' )) 175p = Path (cfg ['tokenizer' ]) 176tok = load_tokenizer (p ) 177tpl = ChatTemplate (p / 'chat_template.jinja' ) 178def encode (text ): 179return tok .encode (text ,parse_special = True ) 180def prompt (label ): 181text = label + ': remember this list.\n' + '\n' .join ( 182f'Record { i } : blue square, green triangle, red circle.' for i in range (a .paragraphs )) 183return encode (tpl .render ([{'role' :'user' ,'content' :text }],enable_thinking = False )) 184A ,B ,C = prompt ('Conversation A' ),prompt ('Unrelated conversation B' ),prompt ('Distinct conversation C' ) 185suffix = encode ('<|im_end|>\n<|im_start|>user\nName a color from the list.<|im_end|>\n' 186'<|im_start|>assistant\n<think>\n\n</think>\n\n' ) 187a .output .mkdir (mode = 0o700 ,parents = False ,exist_ok = False ) 188env = child_env (cfg ) 189env ['STRATA_STATE_HASH' ]= '1' 190results = {'engine_info' : {}} 191for label ,budget in [('baseline' ,0 ), ('candidate' ,a .cache_mib )]: 192log = a .output / f' { label } .log' 193args = engine_args (cfg ,budget ,a .spec ) 194args += ['--conversation-cache-min-free-mib' ,str (a .min_free_mib )] 195engine = StrataEngine (str (a .engine .resolve ()),args ,cwd = cfg .get ('cwd' ),log = str (log ),env = env ) 196results ['engine_info' ][label ]= dict (engine .info ) 197records = [] 198def generate (ids ,count ,name ): 199out = [t for t in engine .generate (ids ,count , {'temperature' :0 },threading .Event ())if t is not None ] 200records .append ({'name' :name ,'ids' :out ,** engine .last }) 201return out 202try : 203# One output token leaves exactly A's prompt as the live prefix, 204# avoiding the pre-existing accepted-draft output-cap overshoot. 205if a .scenario in ('pressure' ,'oversized' ,'admission' ): 206generate (A ,1 ,'A' ) 207generate (B ,1 ,'B' ) 208generate (C ,1 ,'C' ) 209generate (A ,1 ,'A-again' ) 210else : 211head = generate (A ,1 ,'A' ) 212continuation = A + head + suffix 213if budget : 214generate (B ,1 ,'B' ) 215generate (continuation ,8 ,'A+' ) 216if budget : 217generate (B ,1 ,'B-again' ) 218generate (continuation ,8 ,'A+-checkpoint' ) 219finally : 220engine .close () 221hashes = state_hashes (log .read_text (encoding = 'utf-8' )) 222require (len (hashes )== len (records ),'missing state hashes' ) 223for record ,fingerprint in zip (records ,hashes ): 224record ['state' ]= fingerprint 225results [label ]= records 226if label == 'candidate' and a .scenario != 'reuse' : 227log_text = log .read_text (encoding = 'utf-8' ) 228parks = re .findall (r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)(?: snapshot_bytes=(\d+))?' ,log_text ) 229results ['pressure' ]= { 230'parks' : [dict (zip (('parked' ,'bytes' ,'evictions' ,'snapshot_bytes' ), 231 (int (value )if value else 0 for value in p )))for p in parks ], 232'skips' :log_text .count ('conversation cache: skip parking (snapshot ' ), 233'memory_skips' :log_text .count ('conversation cache: skip parking (physical RAM admission;' )} 234 (a .output / 'results.json' ).write_text (json .dumps (results ,indent = 2 )+ '\n' ) 235if a .scenario == 'pressure' : 236pressure_budget_hint (results ,a .cache_mib ),flush = True ) 237if a .scenario == 'admission' : 238verify_admission (results ,a .cache_mib ,a .min_free_mib ) 239'PASS: physical-memory admission denial, output and byte-exact main-model state' ) 240elif a .scenario == 'exchange' : 241verify_exchange (results ,len (A ),a .spec ,a .cache_mib ) 242'PASS: bounded incoming/outgoing exchange, A/B/A output and checkpoint reuse' ) 243elif a .scenario == 'reuse' : 244verify_results (results ,len (A ),a .spec ) 245'PASS: A/B/A output and checkpoint reuse' + (', byte-exact main-model state' if a .spec == 1 else '' )) 246else : 247verify_pressure (results ,a .cache_mib ,a .scenario == 'oversized' ) 248f'PASS: { a . scenario } fallback, output and byte-exact main-model state' ) 249f'Results: { a . output / "results.json" } ' ) 250 251 252if __name__ == '__main__' : 253main ()