okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
19a2dc169
main
1"""Compare untouched upstream with cache-disabled engines; dry-run by default. 2 3Private engines run sequentially in an exclusive GPU window. This is a correctness 4gate, not a throughput benchmark: state fingerprinting adds diagnostic overhead. 5""" 6import argparse 7import hashlib 8import json 9from pathlib import Path 10import re 11import sys 12import threading 13import time 14 15ROOT = Path (__file__ ).resolve ().parents [1 ] 16sys .path [:0 ]= [str (ROOT ),str (ROOT / 'tools' )] 17from conversation_cache_parity import load_tokenizer ,require 18from conversation_cache_soak import answer_text 19from serve .frontend import ChatTemplate 20from serve .server import StrataEngine ,child_env 21 22NAMES = ('short' ,'A' ,'A-live' ,'A-checkpoint' ,'B' ,'A-return' ,'B-return' ,'A-return-again' ) 23# (not 'version': the gate also compares a new release with the previous one, where only the version differs) 24SETTINGS = ('context' ,'kv' ,'kv_resident' ,'expert_slots' ,'spec' , 25'mtp_max' ,'lookup' ,'cvec' ,'pcie_frac' ,'spec_min_p' ,'pool_workers' ) 26# Untouched upstream does not emit the indexer `dead` and `pooled_full` fields 27# added by this PR; `pooled` is the completed-row extent in both engines. 28# Draft scratch and unused page padding are not comparable authoritative state. 29STATE_KEYS = ('L' ,'gdn' ,'ple' ,'tail' ,'pooled' ,'kv' ,'ple_prev' ) 30 31 32def state_hashes (text ,* ,candidate = False ): 33hashes = [] 34for line in text .splitlines (): 35if 'STATE_HASH L=' in line : 36fields = dict (re .findall (r'(\w+)=([0-9a-f,-]+)' ,line )) 37require (set (STATE_KEYS )<= fields .keys (),'missing upstream-compatible state fields' ) 38if candidate : 39# Evidence that the candidate is a build with this change: it 40# also fingerprints the spare row (compared by the cache-on gates). 41require ('pooled_full' in fields ,'candidate lacks the pooled_full fingerprint' ) 42hashes .append ({key :fields [key ]for key in STATE_KEYS }) 43return hashes 44 45 46def common_args (cfg ,spec ): 47# Upstream has no conversation-cache options. Omit them from EVERY arm so 48# the candidates exercise their disabled default with identical arguments. 49args ,i = [],0 50while i < len (cfg ['args' ]): 51arg = cfg ['args' ][i ] 52if arg .startswith ('--conversation-cache-' ): 53require (i + 1 < len (cfg ['args' ]),'cache option lacks a value' ) 54i += 2 55else : 56args .append (arg ) 57i += 1 58return args + ['--prompt-cache' ,'6' ,'--adapt-swaps' ,'0' ,'--spec' ,str (max (2 ,spec )), 59'--mtp-max-t' ,str (spec ),'--suffix-draft' ,'0' ,'--spec-min-p' ,'0' ] 60 61 62def verify (results ): 63arms = results ['arms' ] 64require (len (arms )>= 2 and arms [0 ]['name' ]== 'upstream' ,'missing comparison arms' ) 65baseline = arms [0 ] 66requests = results ['requests' ] 67require ([r ['name' ]for r in requests ]== list (NAMES ),'incomplete request sequence' ) 68require (all (r ['ids' ]and r ['max_new' ]> 0 for r in requests ),'empty request' ) 69digest = hashlib .sha256 (json .dumps (requests ,sort_keys = True ).encode ()).hexdigest () 70require (digest == results ['request_digest' ],'request evidence changed' ) 71for arm in arms : 72require (arm ['args' ]== baseline ['args' ],'engine arguments differ' ) 73require (arm ['request_digest' ]== results ['request_digest' ],'input requests differ' ) 74require ([r ['name' ]for r in arm ['records' ]]== list (NAMES ),'incomplete output sequence' ) 75require (not arm ['cache_events' ],'disabled cache performed snapshot operations' ) 76for key in SETTINGS : 77require (key in arm ['info' ]and arm ['info' ][key ]== baseline ['info' ][key ], 78f' { arm [ "name" ] } : resolved setting differs: { key } ' ) 79if arm ['name' ]!= 'upstream' : 80require (arm ['info' ].get ('conversation_cache_mib' )== 0 ,'RAM cache not disabled' ) 81require (arm ['info' ].get ('conversation_disk_mib' ,0 )== 0 ,'disk cache not disabled' ) 82for request ,reference ,record in zip (requests ,baseline ['records' ],arm ['records' ]): 83require (record ['ids' ]and record ['finish' ]in ('stop' ,'length' ),'incomplete generation' ) 84require (set (STATE_KEYS )<= record ['state' ].keys (),'incomplete state fingerprint' ) 85require (record ['ids' ]== reference ['ids' ],f' { arm [ "name" ] } / { record [ "name" ] } : output differs' ) 86require (record ['state' ]== reference ['state' ],f' { arm [ "name" ] } / { record [ "name" ] } : state differs' ) 87require (record ['reused' ]== reference ['reused' ],'prefix reuse differs' ) 88require (record ['prompt_tokens' ]== len (request ['ids' ]),'wrong prompt length' ) 89if request .get ('expected' ): 90require (answer_text (record ['text' ])== request ['expected' ].casefold (),'known answer is wrong' ) 91records = {r ['name' ]:r for r in arm ['records' ]} 92require (records ['A-live' ]['reused' ]> 0 and records ['A-checkpoint' ]['reused' ]> 0 , 93'continuation/checkpoint path not exercised' ) 94require (records ['A-return' ]['reused' ]== records ['A-return-again' ]['reused' ]== 0 , 95'conversation switching did not force cold fallback' ) 96 97 98def main (): 99ap = argparse .ArgumentParser (description = __doc__ ) 100ap .add_argument ('--config' ,type = Path ,required = True ) 101ap .add_argument ('--upstream' ,type = Path ,required = True ) 102ap .add_argument ('--candidate' ,type = Path ,action = 'append' ,required = True ) 103ap .add_argument ('--output' ,type = Path ,required = True ,help = 'new directory; existing paths refused' ) 104ap .add_argument ('--paragraphs' ,type = int ,default = 128 ) 105ap .add_argument ('--spec' ,type = int ,choices = (1 ,4 ),default = 1 ) 106ap .add_argument ('--run' ,action = 'store_true' ) 107a = ap .parse_args () 108if a .paragraphs < 1 : 109ap .error ('paragraphs must be positive' ) 110if not a .run : 111'Dry run: upstream and disabled candidates; identical inputs/settings, known answers and state parity.' ) 112return 113cfg = json .loads (a .config .read_text (encoding = 'utf-8' )) 114tok_path = Path (cfg ['tokenizer' ]) 115tok = load_tokenizer (tok_path ) 116tpl_path = tok_path / 'chat_template.jinja' 117tpl = ChatTemplate (tpl_path if tpl_path .exists ()else ROOT / 'serve/chat_template.jinja' ) 118def encode (text ): 119return tok .encode (text ,parse_special = True ) 120def prompt (text ): 121return encode (tpl .render ([{'role' :'user' ,'content' :text }],enable_thinking = False )) 122text = 'Conversation A. Remember the exact code AZURE-314159.\n' 123text += '\n' .join (f'Record { i } : blue square, green triangle, red circle.' for i in range (a .paragraphs )) 124A = prompt (text + '\nThe exact code to remember is AZURE-314159. Reply OK.' ) 125B = prompt ('Unrelated conversation B. Remember BRONZE-271828. Reply OK.' ) 126suffix = encode ('<|im_end|>\n<|im_start|>user\nWhat exact code did I ask you to remember? ' 127'Reply with only that code.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n' ) 128args = common_args (cfg ,a .spec ) 129env = child_env (cfg ) 130env .pop ('STRATA_SNAPSHOT_VERIFY' ,None ) 131env ['STRATA_STATE_HASH' ]= '1' 132env ['STRATA_MTP_BATCH' ]= '1' 133a .output .mkdir (mode = 0o700 ,parents = False ,exist_ok = False ) 134results = {'config' :cfg ,'paragraphs' :a .paragraphs ,'spec' :a .spec ,'arms' : [],'requests' : [], 135'compared_state_fields' :STATE_KEYS , 136'environment' : {k :v for k ,v in env .items ()if k .startswith ('STRATA_' )}} 137for index ,exe in enumerate ([a .upstream ,* a .candidate ]): 138name = 'upstream' if index == 0 else f'candidate- { index } ' 139log = a .output / f' { name } .log' 140f'START { name } : { exe } ' ,flush = True ) 141started = time .monotonic () 142engine = StrataEngine (str (exe .resolve ()),args ,cwd = cfg .get ('cwd' ),log = str (log ),env = env ) 143arm = {'name' :name ,'exe' :str (exe .resolve ()),'args' :args ,'info' :dict (engine .info ), 144'startup_seconds' :time .monotonic ()- started ,'records' : []} 145with exe .open ('rb' )as source : 146arm ['exe_sha256' ]= hashlib .file_digest (source ,'sha256' ).hexdigest () 147def generate (request ): 148ids = [t for t in engine .generate (request ['ids' ],request ['max_new' ], {'temperature' :0 }, 149threading .Event ())if t is not None ] 150arm ['records' ].append ({'name' :request ['name' ],'ids' :ids ,** engine .last , 151'text' :tok .decode (ids )}) 152return ids 153try : 154if index == 0 : 155def add (name ,ids ,max_new ,expected = None ): 156request = dict (name = name ,ids = ids ,max_new = max_new ,expected = expected ) 157results ['requests' ].append (request ) 158return generate (request ) 159add ('short' ,prompt ('What is 2 + 2? Reply with only the number.' ),16 ,'4' ) 160head = add ('A' ,A ,1 ) 161require (len (head )== 1 ,'A must produce one token' ) 162continuation = A + head + suffix 163add ('A-live' ,continuation ,32 ,'AZURE-314159' ) 164add ('A-checkpoint' ,continuation ,32 ,'AZURE-314159' ) 165add ('B' ,B ,1 ) 166add ('A-return' ,continuation ,32 ,'AZURE-314159' ) 167add ('B-return' ,B ,1 ) 168add ('A-return-again' ,continuation ,32 ,'AZURE-314159' ) 169payload = json .dumps (results ['requests' ],sort_keys = True ).encode () 170results ['request_digest' ]= hashlib .sha256 (payload ).hexdigest () 171 (a .output / 'requests.json' ).write_bytes (payload ) 172else : 173for request in results ['requests' ]: 174generate (request ) 175finally : 176engine .close () 177engine .proc .wait (timeout = 30 ) 178engine .log .close () 179arm ['request_digest' ]= hashlib .sha256 (json .dumps (results ['requests' ],sort_keys = True ).encode ()).hexdigest () 180log_text = log .read_text (encoding = 'utf-8' ) 181hashes = state_hashes (log_text ,candidate = index != 0 ) 182require (len (hashes )== len (arm ['records' ]),f' { name } : missing state hashes' ) 183for record ,fingerprint in zip (arm ['records' ],hashes ): 184record ['state' ]= fingerprint 185arm ['cache_events' ]= [line for line in log_text .splitlines ()if any (mark in line for mark in 186 ('conversation cache: parked' ,'disk cache: spilled' ,'SNAPSHOT_VERIFY' ))] 187results ['arms' ].append (arm ) 188 (a .output / 'results.json' ).write_text (json .dumps (results ,indent = 2 )+ '\n' ) 189f'DONE { name } ' ,flush = True ) 190verify (results ) 191 (a .output / 'passed.json' ).write_text (json .dumps ({'passed' :True ,'request_digest' :results ['request_digest' ]})+ '\n' ) 192'PASS: untouched upstream versus disabled engines; identical tokens, main state, reuse and known answers' ) 193 194 195if __name__ == '__main__' : 196main ()