okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
abbf12caf
main
1"""Private-engine image/steering cache isolation gate; dry-run unless --run. 2 3Synthetic image embeddings exercise GENI, image identity and M-RoPE without an 4image encoder. Synthetic nonzero control vectors exercise actual add/project 5kernels. This validates cache correctness, not vision or steering quality. 6""" 7import argparse 8import json 9from pathlib import Path 10import struct 11import sys 12import threading 13 14ROOT = Path (__file__ ).resolve ().parents [1 ] 15sys .path [:0 ]= [str (ROOT ),str (ROOT / 'tools' )] 16from conversation_cache_parity import STATE_KEYS ,engine_args ,load_tokenizer ,require ,state_hashes 17from gguf_reader import GGUFFile 18from gguf_writer import GGUFWriter 19from serve .server import StrataEngine ,child_env 20from serve .frontend import ChatTemplate 21import numpy as np 22 23 24def fixtures (output ,width ): 25vector = np .sin (np .arange (width ,dtype = np .float32 )* .17 ) 26vector *= .25 / np .linalg .norm (vector ) 27writer = GGUFWriter () 28writer .add ('general.architecture' ,'controlvector' ) 29writer .add ('controlvector.model_hint' ,'qwen4exp' ) 30writer .add_f32 ('direction.1' ,vector ) 31writer .add_f32 ('direction.20' ,vector ) 32writer .write (output / 'control.gguf' ) 33rows = np .sin (np .arange (4 * width ,dtype = np .float32 )* .013 ).reshape (4 ,width )* .2 34for name ,nx ,ny ,values in [('image-a' ,2 ,2 ,rows ), ('image-b' ,2 ,2 ,- rows ), 35 ('image-grid' ,1 ,4 ,rows )]: 36with (output / (name + '.sve' )).open ('xb' )as f : 37f .write (struct .pack ('<5i' ,0x31455653 ,4 ,nx ,ny ,width )) 38f .write (values .astype ('<f4' ).tobytes ()) 39 40 41def verify (results ,scenario ): 42baseline ,candidate = results ['baseline' ],results ['candidate' ] 43expected = (['image-A' ,'text-B' ,'image-A-return' ,'image-B' ,'image-A-again' , 44'grid-changed' ,'image-A-final' ]if scenario == 'image' else 45 ['off' ,'on' ,'text-B' ,'off-return' ,'on-return' ,'off-again' ]) 46for records in (baseline ,candidate ): 47require ([r ['name' ]for r in records ]== expected ,'incomplete isolation sequence' ) 48for before ,after in zip (baseline ,candidate ): 49require (len (before ['ids' ])== len (after ['ids' ])== 1 ,'missing isolation output' ) 50require (before ['finish' ]in ('length' ,'stop' )and after ['finish' ]in ('length' ,'stop' ), 51'isolation request did not finish normally' ) 52require (before ['ids' ]== after ['ids' ],'isolation output differs' ) 53require (set (STATE_KEYS )<= before ['state' ].keys ()and set (STATE_KEYS )<= after ['state' ].keys (), 54'incomplete isolation state' ) 55require (before ['state' ]== after ['state' ],'isolation main-model state differs' ) 56for key in ('expert_slots' ,'kv' ,'kv_resident' ,'context' ,'spec' ,'mtp_max' ,'lookup' ,'cvec' ): 57require (results ['engine_info' ]['baseline' ][key ]== results ['engine_info' ]['candidate' ][key ], 58f'isolation engine setting differs: { key } ' ) 59misses ,hits = (([0 ,1 ,3 ,5 ], [2 ,4 ,6 ])if scenario == 'image' else ([0 ,1 ,2 ], [3 ,4 ,5 ])) 60require (all (candidate [i ]['reused' ]== 0 for i in misses ),'incompatible identity reused state' ) 61require (all (candidate [i ]['reused' ]> 0 for i in hits ),'compatible parked state was not restored' ) 62changed = 3 if scenario == 'image' else 1 63require (baseline [0 ]['state' ]!= baseline [changed ]['state' ],'fixture did not change actual model state' ) 64if scenario == 'image' : 65require (baseline [0 ]['state' ]!= baseline [5 ]['state' ],'grid fixture did not change M-RoPE state' ) 66else : 67require (results ['engine_info' ]['candidate' ]['cvec' ]!= 0 ,'control vector not loaded' ) 68 69 70def main (): 71ap = argparse .ArgumentParser (description = __doc__ ) 72ap .add_argument ('--config' ,type = Path ,required = True ) 73ap .add_argument ('--engine' ,type = Path ,required = True ) 74ap .add_argument ('--output' ,type = Path ,required = True ) 75ap .add_argument ('--scenario' ,choices = ('image' ,'add' ,'project' ),required = True ) 76ap .add_argument ('--run' ,action = 'store_true' ) 77args = ap .parse_args () 78# the fixtures are passed to an engine that runs in the config's cwd, not this shell's 79args .output = args .output .resolve () 80if not args .run : 81f'Dry run: { args . scenario } isolation; no model loaded or files created.' ) 82return 83cfg = json .loads (args .config .read_text (encoding = 'utf-8' )) 84native = cfg ['args' ][cfg ['args' ].index ('--native' )+ 1 ] 85geometry = GGUFFile (native ).metadata 86width = geometry ['qwen4exp.embedding_length' ] 87require (geometry ['qwen4exp.block_count' ]> 20 ,'fixture requires layers 1 and 20' ) 88p = Path (cfg ['tokenizer' ]) 89tok = load_tokenizer (p ) 90tpl = ChatTemplate (p / 'chat_template.jinja' ) 91def encode (text ): 92return tok .encode (tpl .render ([{'role' :'user' ,'content' :text }],enable_thinking = False ),parse_special = True ) 93image_tokens = '<|vision_start|>' + '<|image_pad|>' * 4 + '<|vision_end|>' 94tail = '\n' .join (f'Record { i } : blue square and green triangle.' for i in range (64 )) 95A = encode ('Conversation A: ' + (image_tokens if args .scenario == 'image' else '' )+ '\n' + tail ) 96B = encode ('Unrelated conversation B: name a color.\n' + tail ) 97args .output .mkdir (mode = 0o700 ,parents = False ,exist_ok = False ) 98fixtures (args .output ,width ) 99env = child_env (cfg ) 100env ['STRATA_STATE_HASH' ]= '1' 101results = {'engine_info' : {}} 102for label ,budget in [('baseline' ,0 ), ('candidate' ,8192 )]: 103log = args .output / (label + '.log' ) 104command = engine_args (cfg ,budget ,1 ) 105if args .scenario == 'image' : 106command += ['--vision' ] 107else : 108command += ['--control-vector' ,str (args .output / 'control.gguf' ),'--cvec-mode' ,args .scenario ] 109engine = StrataEngine (str (args .engine .resolve ()),command ,cwd = cfg .get ('cwd' ),log = str (log ),env = env ) 110records = [] 111results ['engine_info' ][label ]= dict (engine .info ) 112def generate (name ,ids ,image = None ,steering = True ): 113embeddings = str (args .output / (image + '.sve' ))if image else None 114out = [t for t in engine .generate (ids ,1 , {'experimental_speed_projection' :steering }, 115threading .Event (),embeddings = embeddings )if t is not None ] 116records .append ({'name' :name ,'ids' :out ,** engine .last }) 117try : 118if args .scenario == 'image' : 119generate ('image-A' ,A ,'image-a' ) 120generate ('text-B' ,B ) 121generate ('image-A-return' ,A ,'image-a' ) 122generate ('image-B' ,A ,'image-b' ) 123generate ('image-A-again' ,A ,'image-a' ) 124generate ('grid-changed' ,A ,'image-grid' ) 125generate ('image-A-final' ,A ,'image-a' ) 126else : 127generate ('off' ,A ,steering = False ) 128generate ('on' ,A ) 129generate ('text-B' ,B ) 130generate ('off-return' ,A ,steering = False ) 131generate ('on-return' ,A ) 132generate ('off-again' ,A ,steering = False ) 133finally : 134engine .close () 135hashes = state_hashes (log .read_text (encoding = 'utf-8' )) 136require (len (hashes )== len (records ),'missing isolation state hashes' ) 137for record ,state in zip (records ,hashes ): 138record ['state' ]= state 139results [label ]= records 140 (args .output / 'results.json' ).write_text (json .dumps (results ,indent = 2 )+ '\n' ) 141verify (results ,args .scenario ) 142f'PASS: { args . scenario } identity isolation, output and main-model state parity' ) 143f'Results: { args . output / "results.json" } ' ) 144 145 146if __name__ == '__main__' : 147main ()