okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
407ea8192
main
1#!/usr/bin/env python3 2"""Re-run the 2026-10-08 RTX 4070/IQ2_XS benchmark from provenance.json. 3 4Standard-library only. No network, download, model redistribution, or automatic 5publication. Run "check" (SHA-256) *separately* from "run" to avoid warming the 6OS file cache immediately before a timed measurement. 7""" 8from __future__import annotations 9 10import argparse 11import hashlib 12import json 13import os 14from pathlib import Path 15import re 16import statistics 17import subprocess 18import sys 19from datetime import datetime ,timezone 20 21MANIFEST = Path (__file__ ).with_name ("provenance.json" ) 22SOURCE_COMMIT = "9ec3806058cf32ab27a55e4377daf7cf0d087dec" 23PATH_OPTIONS = {"--pack" ,"--native" ,"--ple-gguf" ,"--mtp" , 24"--expert-profile" ,"--tokens-file" } 25DECODE_RE = re .compile ( 26r"^decode\s+(\d+) tokens in\s+([\d.]+) ms\s+->\s+([\d.]+) tok/s" , 27re .MULTILINE , 28) 29 30 31def sha256 (path :Path )-> str : 32h = hashlib .sha256 () 33with path .open ("rb" )as stream : 34for block in iter (lambda :stream .read (8 * 1024 * 1024 ),b"" ): 35h .update (block ) 36return h .hexdigest ().upper () 37 38 39def git_head (directory :Path )-> str | None : 40try : 41p = subprocess .run (["git" ,"-C" ,str (directory ),"rev-parse" ,"HEAD" ], 42capture_output = True ,text = True ,check = True ) 43return p .stdout .strip () 44except (OSError ,subprocess .CalledProcessError ): 45return None 46 47 48def checked_path (root :Path ,rel :str )-> Path : 49candidate = (root / rel ).resolve () 50if not candidate .is_relative_to (root .resolve ()): 51raise ValueError ("Manifest path escapes data root: " + rel ) 52return candidate 53 54 55def expected_files (manifest :dict )-> list [dict ]: 56rows = [] 57for entry in manifest ["model" ]["native_shards" ]: 58rows .append ({"role" :"model" ,** entry }) 59rows .extend (manifest ["artifacts" ]) 60return rows 61 62 63def verify (manifest :dict ,data_root :Path ,engine :Path ,source :Path | None , 64mode :str ,permit_different_binary :bool , 65overrides :dict [str ,Path ])-> tuple [list [str ],list [str ]]: 66problems ,warnings = [], [] 67head = git_head (source )if source else None 68if source : 69if head is None : 70problems .append (f"Cannot determine Git HEAD in source directory: { source } " ) 71elif head .lower ()!= SOURCE_COMMIT : 72problems .append (f"Wrong source HEAD: { head } ; expected { SOURCE_COMMIT } " ) 73try : 74dirty = subprocess .run ( 75 ["git" ,"-C" ,str (source ),"status" ,"--porcelain" ], 76capture_output = True ,text = True ,check = True , 77 ).stdout .strip () 78if dirty : 79warnings .append ("Source working tree has uncommitted changes" ) 80except (OSError ,subprocess .CalledProcessError ): 81warnings .append ("Cannot check whether source tree is clean" ) 82else : 83warnings .append ("Source Git checkout not verified (provide --source-root)" ) 84if not engine .is_file (): 85problems .append (f"Engine executable missing: { engine } " ) 86else : 87expected = manifest ["source" ] 88if engine .stat ().st_size != expected ["binary_bytes" ]: 89msg = (f"Engine size mismatch: { engine . stat (). st_size } vs " 90f" { expected [ 'binary_bytes' ] } bytes" ) 91 (warnings if permit_different_binary else problems ).append (msg ) 92digest = sha256 (engine ) 93if digest != expected ["binary_sha256" ].upper (): 94msg = f"Engine binary SHA-256 mismatch: { digest } " 95 (warnings if permit_different_binary else problems ).append (msg ) 96for item in expected_files (manifest ): 97if ((item ["path" ]== "profiles/learned-heart.bin" and "--expert-profile" in overrides )or 98 (item ["path" ]== "prompts/neuro.tokens" and "--tokens-file" in overrides )): 99continue # Local profile/prompt are checked separately, without matching historical SHA. 100target = checked_path (data_root ,item ["path" ]) 101if not target .is_file (): 102problems .append (f"MISSING [ { item [ 'role' ] } ]: { target } " ) 103continue 104if target .stat ().st_size != item ["bytes" ]: 105problems .append (f"SIZE MISMATCH [ { item [ 'role' ] } ]: { target } " ) 106continue 107if mode == "sha256" and sha256 (target )!= item ["sha256" ].upper (): 108problems .append (f"SHA256 MISMATCH [ { item [ 'role' ] } ]: { target } " ) 109for flag ,target in overrides .items (): 110if not target .is_file (): 111problems .append (f"OVERRIDE MISSING [ { flag } ]: { target } " ) 112if "--tokens-file" in overrides and overrides ["--tokens-file" ].is_file (): 113content = overrides ["--tokens-file" ].read_text (encoding = "utf-8" ) 114if not re .fullmatch (r"[\d+,\s-]+" ,content ): 115problems .append ("User prompt must be pretokenized integer IDs (comma/whitespace-separated)" ) 116else : 117count = len (re .findall (r"[-+]?\d+" ,content )) 118target_count = int (manifest ["primary_command" ]["actual_prompt_tokens" ]) 119if count != target_count : 120problems .append (f"Prompt length { count } differs from { target_count } historical input tokens" ) 121if mode == "size" : 122warnings .append ("Data file SHA-256 was NOT checked; only sizes were compared" ) 123if overrides : 124warnings .append ("Comparable-workload reproduction: custom prompt/profile; NOT an exact historical replay" ) 125return problems ,warnings 126 127 128def make_command (manifest :dict ,data_root :Path ,engine :Path , 129overrides :dict [str ,Path ])-> list [str ]: 130original = manifest ["primary_command" ]["args" ] 131command = [str (engine )] 132path_value = None 133for arg in original : 134if path_value is not None : 135command .append (str (overrides [path_value ]if path_value in overrides else 136checked_path (data_root ,arg ))) 137path_value = None 138else : 139command .append (arg ) 140path_value = arg if arg in PATH_OPTIONS else None 141if path_value : 142raise ValueError ("Path flag at end of provenance argument vector" ) 143return command 144 145 146def gpu_snapshot (path :Path )-> None : 147try : 148p = subprocess .run ( 149 ["nvidia-smi" ,"--query-gpu=timestamp,name,memory.total,memory.used," 150"memory.free,driver_version" ,"--format=csv" ], 151capture_output = True ,text = True ,timeout = 20 , 152 ) 153path .write_text (p .stdout if p .returncode == 0 else p .stderr , 154encoding = "utf-8" ) 155except (OSError ,subprocess .TimeoutExpired )as exc : 156path .write_text (str (exc ),encoding = "utf-8" ) 157 158 159def run_benchmark (manifest :dict ,data_root :Path ,engine :Path , 160output :Path ,repetitions :int ,source :Path | None , 161validation_mode :str ,allow_binary_mismatch :bool , 162overrides :dict [str ,Path ])-> None : 163output .mkdir (parents = True ,exist_ok = False ) 164command = make_command (manifest ,data_root ,engine ,overrides ) 165env = os .environ .copy () 166env .update (manifest ["primary_command" ]["environment" ]) 167# The source installer records CUDA runtime DLL directories in BUILD.json. 168# A bare strata.exe launch requires those directories on PATH on Windows. 169build_json = engine .parent / "BUILD.json" 170dll_dirs = [] 171if build_json .is_file (): 172build = json .loads (build_json .read_text (encoding = "utf-8" )) 173dll_dirs = [str (Path (d ))for key in ("lib_dirs" ,"cuda_dirs" ) 174for d in (build .get (key )or [])if Path (d ).is_dir ()] 175if dll_dirs : 176env ["PATH" ]= os .pathsep .join (dll_dirs + [env .get ("PATH" ,"" )]) 177result_rows = [] 178expected_tokens = int (manifest ["primary_command" ]["output_tokens" ]) 179for index in range (1 ,repetitions + 1 ): 180folder = output / f"run- { index :02d } " 181folder .mkdir () 182# Do not publish raw stdout: the engine prints the full prompt and 183# output token IDs, potentially encoding private text. 184 (folder / "command.json" ).write_text ( 185json .dumps ({"argv" :command , 186"environment_overrides" :manifest ["primary_command" ]["environment" ], 187"cuda_library_paths_from_BUILD_json" :dll_dirs , 188"started_utc" :datetime .now (timezone .utc ).isoformat ()}, 189indent = 2 ),encoding = "utf-8" ) 190gpu_snapshot (folder / "gpu-before.csv" ) 191with ( 192 (folder / "stdout.log" ).open ("w" ,encoding = "utf-8" )as stdout , 193 (folder / "stderr.log" ).open ("w" ,encoding = "utf-8" )as stderr , 194 ): 195proc = subprocess .run (command ,cwd = data_root ,env = env , 196stdout = stdout ,stderr = stderr ,check = False ) 197gpu_snapshot (folder / "gpu-after.csv" ) 198output_text = (folder / "stdout.log" ).read_text (encoding = "utf-8" ) 199matches = DECODE_RE .findall (output_text ) 200row = {"run" :index ,"exit_code" :proc .returncode , 201"accepted_decode_tok_s" :None ,"output_tokens" :None , 202"decode_ms" :None ,"valid" :False } 203if proc .returncode == 0 and len (matches )== 1 : 204tokens ,ms ,rate = matches [0 ] 205row .update ({"output_tokens" :int (tokens ),"decode_ms" :float (ms ), 206"accepted_decode_tok_s" :float (rate ), 207"valid" :int (tokens )== expected_tokens }) 208 (folder / "summary.json" ).write_text (json .dumps (row ,indent = 2 ), 209encoding = "utf-8" ) 210result_rows .append (row ) 211f"run { index } / { repetitions } : { row } " ,flush = True ) 212success = [r ["accepted_decode_tok_s" ]for r in result_rows if r ["valid" ]] 213report = { 214"source_commit_required" :SOURCE_COMMIT , 215"source_git_head_observed" :git_head (source )if source else None , 216"binary_sha256_expected" :manifest ["source" ]["binary_sha256" ], 217"binary_sha256_observed" :sha256 (engine ), 218"binary_mismatch_explicitly_allowed" :allow_binary_mismatch , 219"data_validation_mode" :validation_mode , 220"environment_overrides" :manifest ["primary_command" ]["environment" ], 221"cuda_library_paths_from_BUILD_json" :dll_dirs , 222"comparison_type" :"comparable user-supplied workload (not historical exact)" if overrides else 223"historical inputs if all file hashes match" , 224"prompt_file_sha256" :sha256 (overrides ["--tokens-file" ])if "--tokens-file" in overrides else 225sha256 (checked_path (data_root ,"prompts/neuro.tokens" )), 226"profile_sha256" :sha256 (overrides ["--expert-profile" ])if "--expert-profile" in overrides else 227sha256 (checked_path (data_root ,"profiles/learned-heart.bin" )), 228"prompt_tokens" :int (manifest ["primary_command" ]["actual_prompt_tokens" ]), 229"results" :result_rows , 230"valid_runs" :len (success ), 231"median_accepted_decode_tok_s" :statistics .median (success )if success else None , 232"mean_accepted_decode_tok_s" :statistics .mean (success )if success else None , 233"min_accepted_decode_tok_s" :min (success )if success else None , 234"max_accepted_decode_tok_s" :max (success )if success else None , 235"historical_primary_median" :manifest ["run_sets" ]["primary_e4_s24" ]["median_tok_s" ], 236"note" :"GPU snapshots are before/after, NOT an in-run peak VRAM measurement" , 237 } 238 (output / "report.json" ).write_text (json .dumps (report ,indent = 2 ), 239encoding = "utf-8" ) 240json .dumps ({k :v for k ,v in report .items ()if k != "results" },indent = 2 )) 241if len (success )!= repetitions : 242raise SystemExit ("One or more runs failed or produced the wrong output token count" ) 243 244 245def main ()-> int : 246p = argparse .ArgumentParser (description = __doc__ ) 247p .add_argument ("action" ,choices = ["check" ,"run" ]) 248p .add_argument ("--data-root" ,type = Path ,required = True , 249help = "Folder containing models/, packs/, mtp/, profiles/, prompts/" ) 250p .add_argument ("--engine" ,type = Path ,required = True , 251help = "Path to the compiled strata.exe executable" ) 252p .add_argument ("--source-root" ,type = Path , 253help = "The pinned Git checkout to verify with git rev-parse HEAD" ) 254p .add_argument ("--hash-mode" ,choices = ["sha256" ,"size" ], 255help = "Defaults to sha256 for check, size for run (avoid pre-run cache warming)" ) 256p .add_argument ("--allow-binary-mismatch" ,action = "store_true" , 257help = "Run a rebuild that differs in bytes; not a byte-identical engine reproduction" ) 258p .add_argument ("--profile" ,type = Path , 259help = "Locally generated expert profile; no historical profile download required" ) 260p .add_argument ("--prompt-file" ,type = Path , 261help = "Your own pretokenized, 28,912-token prompt; historical prompt not required" ) 262p .add_argument ("--runs" ,type = int ,default = 5 ) 263p .add_argument ("--out" ,type = Path ,help = "New output directory for raw logs (never overwritten)" ) 264args = p .parse_args () 265if args .action == "run" and (not args .out or args .runs < 1 ): 266p .error ("run requires --out and --runs >= 1" ) 267data_root ,engine = args .data_root .resolve (),args .engine .resolve () 268manifest = json .loads (MANIFEST .read_text (encoding = "utf-8" )) 269mode = args .hash_mode or ("sha256" if args .action == "check" else "size" ) 270overrides = {} 271if args .profile : 272overrides ["--expert-profile" ]= args .profile .resolve () 273if args .prompt_file : 274overrides ["--tokens-file" ]= args .prompt_file .resolve () 275problems ,warnings = verify (manifest ,data_root ,engine , 276args .source_root .resolve ()if args .source_root else None , 277mode ,args .allow_binary_mismatch ,overrides ) 278for line in warnings : 279"WARNING:" ,line ,file = sys .stderr ) 280if problems : 281for line in problems : 282"ERROR:" ,line ,file = sys .stderr ) 283return 2 284f"Preflight OK ( { mode } data validation)" ) 285if args .action == "run" : 286run_benchmark (manifest ,data_root ,engine ,args .out .resolve (),args .runs , 287args .source_root .resolve ()if args .source_root else None , 288mode ,args .allow_binary_mismatch ,overrides ) 289return 0 290 291 292if __name__ == "__main__" : 293raise SystemExit (main ())