okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ef8071303
main
1#!/usr/bin/env python3 2"""Three fresh native runs; only numeric timing and hash receipts persist. 3 4Use under an independent GPU/resource guard, with the model router isolated. 5Run: python campaign.py --source SOURCE --profile profile.json --out OUTPUT 6RAM logs must live on tmpfs. No generated content is written by this script. 7""" 8import argparse 9import hashlib 10import json 11import os 12from pathlib import Path 13import re 14import signal 15import sys 16import threading 17import time 18 19TASKS = [ 20'Write a complete Python standard-library LRU cache module with expiry and locking, validation, iteration, detailed docstrings, demonstrations and boundary-case discussion. Write at least 1500 words of code and explanation.' , 21'Write a complete Python standard-library CSV import module with typed validation, error collection, transaction staging, provenance, test examples and extensive documentation. Write at least 1500 words of code and explanation.' , 22'Write a detailed story of at least 1500 words about a lighthouse keeper and marine biologist deciphering a research notebook. Develop their distinct voices, observations, uncertainty, and discoveries.' , 23'Explain accurate inventory audits, discrepancy investigation, provenance, reconciliation, and periodic checks in at least 1500 words with concrete examples and worked scenarios.' , 24'Act as an incident coordinator. Develop a detailed operational response plan for a failed local service: evidence collection, hypotheses, bounded tests, rollback, recovery verification and communication. Include worked scenarios and at least 1500 words.' 25] 26WARMUP = 'Write a detailed 1500-word guide to maintaining a community garden, with seasonal plans, worked examples and practical checklists.' 27FILLER = '\n' .join (f'Archive record { i } : shelf { i % 17 } , item { ( i * 37 ) % 997 } , status reviewed, source verified, date unknown. Preserve provenance and record uncertainty.' for i in range (900 )) 28 29def digest (value ): 30return hashlib .sha256 (json .dumps (value ).encode ()).hexdigest () 31 32def main (): 33ap = argparse .ArgumentParser () 34ap .add_argument ('--source' ,type = Path ,required = True ) 35ap .add_argument ('--profile' ,type = Path ,required = True ) 36ap .add_argument ('--out' ,type = Path ,required = True ) 37ap .add_argument ('--ram' ,type = Path ,default = Path (os .environ .get ('STRATA_TEST_RAM' ,'/run/strata-community' ))) 38ap .add_argument ('--runs' ,type = int ,default = 3 ) 39args = ap .parse_args () 40assert 1 <= args .runs <= 3 41assert str (args .ram .resolve ()).startswith ('/run/' ),'use a RAM-backed /run directory' 42assert args .ram .is_dir () 43args .out .mkdir (exist_ok = True ) 44assert not (args .out / 'requests.json' ).exists (),'do not overwrite a consumed run' 45sys .path [:0 ]= [str (args .source ),str (args .source / 'tools' )] 46from serve .server import StrataEngine ,ENGINE_REQUEST 47from serve .frontend import ChatTemplate 48from strata_tokenizer import Tokenizer 49 50class MeasuredEngine (StrataEngine ): 51def _parse_done (self ,line ): 52self .done_line = line 53return super ()._parse_done (line ) 54 55assert 'STRATA_DBG_NAN' not in os .environ ,'qualification diagnostic must be absent' 56profile = json .loads (args .profile .read_text ()) 57native_args = [os .path .expandvars (x )for x in profile ['args' ]] 58binary = os .path .expandvars (profile ['exe' ]) 59cwd = os .path .expandvars (profile ['cwd' ]) 60tok = Tokenizer .from_gguf (Path (native_args [native_args .index ('--native' )+ 1 ])) 61tpl = ChatTemplate (Path (native_args [native_args .index ('--pack' )+ 1 ])/ 'tokenizer/chat_template.jinja' ) 62sampling = {'temperature' :0.0 ,'seed' :17 } 63rows ,runs = [], [] 64cancel = threading .Event () 65interrupted = False 66engine = None 67failure = None 68 69def stop (* _ ): 70nonlocal interrupted 71interrupted = True 72cancel .set () 73 74signal .signal (signal .SIGTERM ,stop ) 75signal .signal (signal .SIGINT ,stop ) 76 77def save (): 78for name ,data in [('requests' ,rows ), ('runs' ,runs )]: 79 (args .out / (name + '.json' )).write_text (json .dumps (data ,indent = 2 )+ '\n' ) 80 81def shaped (task ,target ): 82rendered = tpl .render ([ 83 {'role' :'system' ,'content' :'Follow the requested format and provide a thorough answer.' }, 84 {'role' :'user' ,'content' :'PAD_MARKER\n' + task } 85 ],enable_thinking = False ) 86before ,after = rendered .split ('PAD_MARKER' ) 87a ,b = tok .encode (before ,parse_special = True ),tok .encode (after ,parse_special = True ) 88pad = tok .encode (FILLER ) 89assert 0 < target - len (a )- len (b )<= len (pad ) 90ids = a + pad [:target - len (a )- len (b )]+ b 91assert len (ids )== target 92return ids 93 94fixtures = {(i ,n ):shaped (task ,n )for n in (512 ,7000 )for i ,task in enumerate (TASKS + [WARMUP ])} 95 (args .out / 'fixtures.json' ).write_text (json .dumps ([ 96 {'task_index' :i ,'prompt_tokens' :n ,'input_ids_sha256' :digest (ids ),'warmup' :i == 5 } 97for (i ,n ),ids in fixtures .items () 98 ],indent = 2 )+ '\n' ) 99 100def ask (ids ,cap ,label ,measured = False ,expected = None ,json_check = False ): 101assert not interrupted 102offset = log .stat ().st_size 103engine .done_line = None 104start_utc = time .time () 105started = time .monotonic () 106arrivals ,output = [], [] 107for token in engine .generate (ids ,cap ,sampling ,cancel ): 108if token is not None : 109arrivals .append (time .monotonic ()) 110output .append (token ) 111elapsed = time .monotonic ()- started 112native = dict (engine .last ) 113text = tok .decode (output ).replace ('<|im_end|>' ,'' ).replace ('<|endoftext|>' ,'' ).strip () 114valid = (engine .done_line is not None and len (output )== native ['generated' ] 115and native ['prompt_tokens' ]== len (ids )and native ['reused' ]== 0 116and native ['prompt_read' ]== len (ids )and bool (output )) 117if expected is not None : 118valid &= text == expected 119if json_check : 120try : 121obj = json .loads (text ) 122valid &= set (obj )== {'answer' ,'ok' }and type (obj ['answer' ])is int and obj ['ok' ]is True 123except (ValueError ,TypeError ): 124valid = False 125if measured or label .startswith ('warm-shape' ): 126valid &= len (output )== cap and native ['finish' ]== 'length' 127streak = longest = 1 128for j in range (1 ,len (output )): 129streak = streak + 1 if output [j ]== output [j - 1 ]else 1 ;longest = max (longest ,streak ) 130valid &= len (set (output ))>= 25 and longest < 64 131with log .open ('r' )as f : 132f .seek (offset ) 133lines = f .read ().splitlines () 134timing = [line for line in lines if ENGINE_REQUEST .search (line )] 135row = {'run' :len (runs ),'label' :label ,'measured' :measured , 136'started_utc' :start_utc ,'input_tokens' :len (ids ),'output_cap' :cap , 137'output_tokens' :len (output ),'input_ids_sha256' :digest (ids ), 138'output_ids_sha256' :digest (output ),'output_sha256' :hashlib .sha256 (text .encode ()).hexdigest (), 139'sampling' :sampling ,'native' :native ,'native_done_line' :engine .done_line , 140'native_timing_lines' :timing , 141'prompt_tps' :native ['prompt_read' ]* 1000 / native ['prompt_ms' ], 142'decode_tps' :native ['generated' ]* 1000 / native ['decode_ms' ], 143'ttft_s' :arrivals [0 ]- started if arrivals else None , 144'post_first_tps' : (len (output )- 1 )/ (arrivals [- 1 ]- arrivals [0 ])if len (output )> 1 else None , 145'total_s' :elapsed ,'valid' :bool (valid )} 146if label == 'json-quality' : 147row ['math_answer_correct' ]= json .loads (text ).get ('answer' )== 50 if valid else False 148row ['math_answer_is_runtime_gate' ]= False 149if measured : 150prior = next ((x for x in rows if x .get ('label' )== label and x .get ('measured' )),None ) 151if prior is not None : 152row ['matches_branch_repeat' ]= row ['output_ids_sha256' ]== prior ['output_ids_sha256' ] 153assert row ['matches_branch_repeat' ],'branch repeat changed: ' + label 154rows .append (row ) 155save () 156json .dumps ({'run' :len (runs ),'label' :label ,'measured' :measured , 157'prompt_tps' :row ['prompt_tps' ],'decode_tps' :row ['decode_tps' ], 158'valid' :bool (valid )}),flush = True ) 159assert valid ,'protocol/length/isolation failure: ' + label 160assert not interrupted ,'guard interruption' 161 162try : 163for run_index in range (args .runs ): 164log = args .ram / f'native- { run_index + 1 } .log' 165runs .append ({'run' :run_index + 1 ,'binary_sha256' :hashlib .file_digest (Path (binary ).open ('rb' ),'sha256' ).hexdigest (), 166'sampling' :sampling ,'args' :native_args }) 167save () 168started = time .monotonic () 169engine = MeasuredEngine (binary ,native_args ,cwd = cwd ,log = str (log ),env = dict (os .environ )) 170runs [- 1 ]['startup_ready_s' ]= time .monotonic ()- started 171runs [- 1 ]['info' ]= engine .info 172save () 173for label ,prompt ,expected ,jc in [ 174 ('isolation-a' ,'Reply only with CANARY_MAPLE_73.' ,'CANARY_MAPLE_73' ,False ), 175 ('isolation-b' ,'Reply only with CANARY_RIVER_29.' ,'CANARY_RIVER_29' ,False ), 176 ('json-quality' ,'Calculate 2**5 + 6*3. Return exactly one JSON object with keys answer (the integer result) and ok (true), no markdown.' ,None ,True ) 177 ]: 178ids = tok .encode (tpl .render ([{'role' :'user' ,'content' :prompt }],enable_thinking = False ),parse_special = True ) 179ask (ids ,64 ,label ,expected = expected ,json_check = jc ) 180for n in (512 ,7000 ): 181ask (fixtures [(5 ,n )],640 ,f'warm-shape- { n } ' ) 182for i in range (5 ): 183ask (fixtures [(i ,n )],640 ,f'bench- { n } - { i } ' ,measured = True ) 184ids = tok .encode (tpl .render ([{'role' :'user' ,'content' :'Reply only with CANARY_MAPLE_73.' }],enable_thinking = False ),parse_special = True ) 185ask (ids ,64 ,'post-long-isolation' ,expected = 'CANARY_MAPLE_73' ) 186proc = engine .proc 187started = time .monotonic () 188proc .stdin .write ('QUIT\n' ) 189proc .stdin .flush () 190proc .wait (timeout = 75 ) 191runs [- 1 ]['native_exit' ]= proc .returncode 192runs [- 1 ]['quit_exit_s' ]= time .monotonic ()- started 193assert proc .returncode == 0 194engine .close () 195engine = None 196raw = log .read_text () 197assert not re .search (r'\b[1-9]\d* (?:of \d+ logits )?non-finite\b|\bnonfinite [1-9]\d*' ,raw ) 198runs [- 1 ]['startup_lines' ]= [line for line in raw .splitlines () 199if re .match (r'^strata (?:generate|serve): (?:GPU \d+:|PCIe probe:|expert cache \d|\d+ of \d+ experts missing|\d+ MiB of VRAM free)' ,line )] 200runs [- 1 ]['native_log_sha256' ]= hashlib .sha256 (raw .encode ()).hexdigest () 201save () 202for _ in range (5 ): 203time .sleep (1 ) 204assert not interrupted ,'guard interruption during delayed fault observation' 205except BaseException as e : 206failure = {'type' :type (e ).__name__ ,'reason' :str (e )} 207finally : 208if engine is not None : 209proc = engine .proc 210if proc is not None and proc .poll ()is None : 211proc .stdin .write ('QUIT\n' );proc .stdin .flush ();proc .wait (timeout = 75 ) 212engine .close () 213runs [- 1 ]['native_exit' ]= None if proc is None else proc .returncode 214save () 215 (args .out / 'result.json' ).write_text (json .dumps ({'failure' :failure , 216'run_count' :len (runs ),'requests' :len (rows ),'measured_requests' :sum (r ['measured' ]for r in rows ), 217'generated_content_persisted' :False },indent = 2 )+ '\n' ) 218if failure : 219raise SystemExit (1 ) 220 221if __name__ == '__main__' : 222main ()