okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1#!/usr/bin/env python3 2"""Interleaved independent-engine A/B pairs with explicitly declared configuration differences. 3 4One complete shape warmup and one measurement per engine. Reporting stays descriptive; 5the quality gates, all workload regressions and resource observations must be reviewed separately. 6""" 7import argparse 8from datetime import datetime ,timezone 9import hashlib 10import json 11from pathlib import Path 12import statistics 13import subprocess 14import sys 15 16from bench_engine import save 17from single_gpu import ROOT ,validate_config 18 19 20def summarize (directory ,manifest ): 21groups = {} 22for item in manifest ["sessions" ]: 23data = json .loads ((directory / item ["name" ]/ "results.json" ).read_text ()) 24if item ["status" ]!= "passed" or data ["binary_sha256" ]!= manifest ["configs" ][item ["arm" ]]["binary_sha256" ]: 25raise ValueError ("failed session or changed engine" ) 26if data ["fixtures_sha256" ]!= manifest ["fixtures_sha256" ]: 27raise ValueError ("changed fixtures" ) 28records = [r for r in data ["records" ]if r ["phase" ]== "measurement" ] 29expected = {(n ,inc )for n in manifest ["lengths" ]for inc in manifest ["increments" ]}if manifest ["mode" ]== "incremental" else {(n ,0 )for n in manifest ["lengths" ]} 30actual = set () 31for r in records : 32key = (r ["base_tokens" ],r ["increment" ])if manifest ["mode" ]== "incremental" else (r ["input_tokens" ],0 ) 33if key in actual : 34raise ValueError ("duplicate measurement" ) 35actual .add (key ) 36if not r ["output_ids" ]or r ["finish" ]not in {"length" ,"stop" }: 37raise ValueError ("incomplete generation" ) 38if (manifest ["mode" ]== "fresh" and r ["reused" ]!= 0 )or (manifest ["mode" ]== "incremental" and not key [0 ]- 1 <= r ["reused" ]<= key [0 ]): 39raise ValueError ("incorrect reuse path" ) 40groups .setdefault (key , {}).setdefault (item ["pair" ], {})[item ["arm" ]]= r 41if actual != expected : 42raise ValueError ("missing measurement" ) 43rows = [] 44for key ,pairs in sorted (groups .items ()): 45row = {"history_or_input_tokens" :key [0 ],"increment" :key [1 ],"pairs" : []} 46for index ,pair in sorted (pairs .items ()): 47a ,b = pair ["baseline" ],pair ["candidate" ] 48equal_keys = ("input_ids_sha256" ,"output_ids" ,"generated" ,"finish" ,"reused" ,"prompt_read" ,"drafts_accepted" ,"drafts_offered" ) 49changed = [k for k in equal_keys if a [k ]!= b [k ]] 50values = {k : {"baseline" :a [k ],"candidate" :b [k ],"time_reduction_pct" :100 * (1 - b [k ]/ a [k ])} 51for k in ("prompt_ms" ,"decode_ms" ,"ttft_s" ,"wall_s" )} 52row ["pairs" ].append ({"index" :index ,"differing_work_fields" :changed ,** values }) 53row ["identical_work" ]= all (not p ["differing_work_fields" ]for p in row ["pairs" ]) 54for metric in ("prompt_ms" ,"decode_ms" ,"ttft_s" ,"wall_s" ): 55reductions = [p [metric ]["time_reduction_pct" ]for p in row ["pairs" ]] 56row [metric ]= {"median_paired_time_reduction_pct" :statistics .median (reductions ), 57"min_paired_time_reduction_pct" :min (reductions ),"max_paired_time_reduction_pct" :max (reductions ), 58"faster_pairs" :sum (v > 0 for v in reductions ), 59"regressions_over_2pct" :sum (v < - 2 for v in reductions ), 60** {f" { arm } _median" :statistics .median (p [metric ][arm ]for p in row ["pairs" ])for arm in ("baseline" ,"candidate" )}} 61rows .append (row ) 62if any (len (r ["pairs" ])!= manifest ["pairs" ]for r in rows ): 63raise ValueError ("incomplete pair count" ) 64return {"scope" :"descriptive paired results; no automatic acceptance or quality claim" ,"rows" :rows } 65 66 67def main (): 68parser = argparse .ArgumentParser (description = __doc__ ) 69parser .add_argument ("--baseline" ,type = Path ,required = True ) 70parser .add_argument ("--candidate" ,type = Path ,required = True ) 71parser .add_argument ("--fixtures" ,type = Path ,required = True ) 72parser .add_argument ("--out" ,type = Path ,required = True ) 73parser .add_argument ("--pairs" ,type = int ,default = 6 ) 74parser .add_argument ("--mode" ,choices = ["fresh" ,"incremental" ],default = "fresh" ) 75parser .add_argument ("--lengths" ,type = int ,nargs = "+" ,default = [128 ,4096 ,32768 ]) 76parser .add_argument ("--increments" ,type = int ,nargs = "+" ,default = [256 ,512 ,900 ,2048 ,4096 ]) 77parser .add_argument ("--vary-env" ,action = "append" ,default = [], 78help = "explicit environment difference for a configuration experiment; default allows none" ) 79args = parser .parse_args () 80if args .pairs < 1 or min (args .lengths + args .increments )< 1 : 81parser .error ("positive pair count and lengths required" ) 82configs = {} 83for arm ,path in (("baseline" ,args .baseline ), ("candidate" ,args .candidate )): 84cfg = json .loads (path .read_text ()) 85validate_config (cfg ) 86configs [arm ]= {"path" :str (path .resolve ()),"sha256" :hashlib .sha256 (path .read_bytes ()).hexdigest (), 87"binary_sha256" :hashlib .sha256 (Path (cfg ["exe" ]).read_bytes ()).hexdigest (),"config" :cfg } 88if any (k in cfg ["env" ]for k in ("STRATA_STATE_HASH" ,"STRATA_STATE_HASH_GDN" ,"STRATA_DUMP_FIRST_LOGITS" , 89"STRATA_TRACE" ,"STRATA_PREFILL_LAYER_HASH_T" ,"STRATA_PREFILL_GEMM_CAPTURE" , 90"STRATA_PREFILL_TIMING" ,"STRATA_DECODE_TIMING" ,"STRATA_IO_STATS" , 91"STRATA_HIPBLASLT_VERBOSE" ,"ROCBLAS_LAYER" ,"HIPBLASLT_LOG_LEVEL" )): 92raise ValueError ("performance config contains diagnostic instrumentation" ) 93for key in ("args" ,"tokenizer" ,"cwd" ,"lib_dirs" ,"r9700_numa" ): 94if configs ["baseline" ]["config" ].get (key )!= configs ["candidate" ]["config" ].get (key ): 95raise ValueError ("paired comparison requires identical controls: " + key ) 96a_env ,b_env = (configs [arm ]["config" ]["env" ]for arm in ("baseline" ,"candidate" )) 97changed_env = {key for key in a_env .keys ()| b_env .keys ()if a_env .get (key )!= b_env .get (key )} 98if changed_env != set (args .vary_env ): 99raise ValueError ("actual environment differences do not match --vary-env: " + str (sorted (changed_env ))) 100args .out .mkdir (parents = True ,exist_ok = False ) 101manifest = {"scope" :"interleaved A/B; independent engine per arm; one warmup and measurement per shape" , 102"vary_env" : {key : {"baseline" :a_env .get (key ),"candidate" :b_env .get (key )}for key in sorted (changed_env )}, 103"mode" :args .mode ,"pairs" :args .pairs ,"configs" :configs ,"lengths" :args .lengths , 104"increments" :args .increments ,"max_new" :256 , 105"fixtures_sha256" :hashlib .sha256 (args .fixtures .read_bytes ()).hexdigest (),"sessions" : []} 106save (args .out / "matrix.json" ,manifest ) 107for pair in range (args .pairs ): 108for arm in (("baseline" ,"candidate" )if pair % 2 == 0 else ("candidate" ,"baseline" )): 109c = configs [arm ];cfg = c ["config" ] 110name = f" { pair :02d } - { arm } " 111numa = cfg .get ("r9700_numa" , {"cpu_nodes" :"0,1" ,"preferred_node" :"1" }) 112runner = "bench_engine.py" if args .mode == "fresh" else "bench_incremental.py" 113extra = ["--shape-warmups" ,"1" ]if args .mode == "fresh" else ["--increments" ,* map (str ,args .increments )] 114cmd = [sys .executable ,str (ROOT / "tools/hip/r9700/single_gpu.py" ), 115"--device-binary" ,str (Path (cfg ["exe" ]).with_name ("strata-device" )), 116"--config" ,c ["path" ],"--record" ,str ((args .out / f" { name } -launch.json" ).resolve ()), 117"--cpu-nodes" ,numa ["cpu_nodes" ],"--preferred-node" ,str (numa ["preferred_node" ]),"run" ,"--" , 118sys .executable ,str (ROOT / "tools/hip/r9700" / runner ),"--config" ,c ["path" ], 119"--fixtures" ,str (args .fixtures .resolve ()),"--out" ,str ((args .out / name ).resolve ()), 120"--lengths" ,* map (str ,args .lengths ),"--repeats" ,"1" ,"--max-new" ,"256" ,* extra ] 121entry = {"pair" :pair ,"arm" :arm ,"name" :name ,"command" :cmd ,"status" :"running" , 122"start_utc" :datetime .now (timezone .utc ).isoformat ()} 123manifest ["sessions" ].append (entry );save (args .out / "matrix.json" ,manifest ) 124entry ["start_utc" ],"start" ,name ,flush = True ) 125with (args .out / f" { name } -console.log" ).open ("x" )as log : 126result = subprocess .run (cmd ,cwd = ROOT ,stdout = log ,stderr = subprocess .STDOUT ) 127entry .update (status = "passed" if result .returncode == 0 else "failed" ,returncode = result .returncode , 128end_utc = datetime .now (timezone .utc ).isoformat ()) 129save (args .out / "matrix.json" ,manifest ) 130entry ["end_utc" ],entry ["status" ],name ,flush = True ) 131if result .returncode : 132raise SystemExit (result .returncode ) 133summary = summarize (args .out ,manifest ) 134save (args .out / "summary.json" ,summary ) 135manifest ["complete" ]= True 136save (args .out / "matrix.json" ,manifest ) 137 138 139if __name__ == "__main__" : 140main ()