okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1#!/usr/bin/env python3 2"""Recompute the published measurements without a GPU or model downloads.""" 3import argparse 4import csv 5import gzip 6import hashlib 7import io 8import json 9import math 10from pathlib import Path 11import statistics 12import subprocess 13import tarfile 14import tempfile 15 16ROOT = Path (__file__ ).resolve ().parent 17BUNDLE = json .loads (gzip .decompress ((ROOT / "data/measurements.json.gz" ).read_bytes ())) 18WORK = ("input_ids_sha256" ,"output_ids" ,"generated" ,"finish" ,"reused" , 19"prompt_read" ,"drafts_accepted" ,"drafts_offered" ) 20METRICS = ("prompt_ms" ,"decode_ms" ,"ttft_s" ,"wall_s" ) 21 22 23def read (path ): 24path = str (path ) 25local = ROOT / path 26return json .loads (local .read_text ())if local .exists ()else BUNDLE ["json" ][path ] 27 28 29def check_csv (path ,expected ): 30with (ROOT / path ).open (newline = "" )as stream : 31rows = list (csv .DictReader (stream )) 32normalized = [{key :"" if value is None else str (value )for key ,value in row .items ()} 33for row in expected ] 34assert rows == normalized ,f" { path } : CSV differs from the complete measurement records" 35 36 37def check_tables (): 38rows = [] 39for path ,result in BUNDLE ["json" ].items (): 40if not path .endswith ("/results.json" ): 41continue 42source ,session = path .split ("/" )[- 3 :- 1 ] 43entry = {"pair" :"" ,"arm" :"candidate" } 44if source != "current-speed" : 45matrix = read (f"evidence/ { source } /matrix.json" ) 46entry = next (item for item in matrix ["sessions" ]if item ["name" ]== session ) 47for record in result ["records" ]: 48keys = ("phase" ,"repeat" ,"input_tokens" ,"base_tokens" ,"increment" ,"prompt_read" , 49"reused" ,"generated" ,"prompt_ms" ,"decode_ms" ,"ttft_s" ,"wall_s" , 50"drafts_accepted" ,"drafts_offered" ,"input_ids_sha256" ) 51rows .append ({"source" :source ,"session" :session ,"pair" :entry ["pair" ],"arm" :entry ["arm" ], 52** {key :record .get (key ,"" )for key in keys }, 53"output_ids_sha256" :hashlib .sha256 (json .dumps (record ["output_ids" ]).encode ()).hexdigest ()}) 54# The fresh-speed session is listed first; paired sessions retain their recorded order. 55rows .sort (key = lambda row :row ["source" ]!= "current-speed" ) 56check_csv ("data/requests.csv" ,rows ) 57rows = [] 58for name in ("pr1107-incremental-five-pairs-iq3s" ,"pr1107-incremental-screen-iq2xs" , 59"pr1107-fresh-screen-iq3s" ,"pr1107-fresh-screen-iq2xs" ): 60for row in read (f"evidence/ { name } /summary.json" )["rows" ]: 61for metric in METRICS : 62rows .append ({"comparison" :name ,"history_or_input_tokens" :row ["history_or_input_tokens" ], 63"increment" :row ["increment" ],"pairs" :len (row ["pairs" ]), 64"metric" :metric ,** row [metric ]}) 65check_csv ("data/comparisons.csv" ,rows ) 66rows = [] 67for row in read ("current-speed/summary.json" )["rows" ]: 68rows .append ({** {key :row [key ]for key in ("input_tokens" ,"output_tokens" ,"repeats" )}, 69** {metric + "_" + stat :row [metric ][stat ] 70for metric in ("prefill_tokens_per_s" ,"decode_tokens_per_s" ,"ttft_s" ,"wall_s" ) 71for stat in ("median" ,"min" ,"max" )}}) 72check_csv ("data/fresh-speed.csv" ,rows ) 73 74 75def same (a ,b ): 76assert math .isclose (a ,b ,rel_tol = 1e-10 ,abs_tol = 1e-10 ), (a ,b ) 77 78 79def measured (record ,incremental = False ): 80assert record ["generated" ]== len (record ["output_ids" ])== 256 81assert record ["finish" ]== "length" 82assert all (math .isfinite (record [k ])and record [k ]> 0 for k in METRICS ) 83expected_read = record ["increment" ]if incremental else record ["input_tokens" ] 84expected_reuse = record ["base_tokens" ]if incremental else 0 85assert record ["prompt_read" ]== expected_read 86assert record ["reused" ]== expected_reuse 87assert record ["prompt_tokens" ]== record ["input_tokens" ]== expected_read + expected_reuse 88 89 90def compare_summary (groups ,summary ): 91assert len (groups )== len (summary ["rows" ]) 92for row in summary ["rows" ]: 93key = (row ["history_or_input_tokens" ],row ["increment" ]) 94pairs = groups [key ] 95assert len (pairs )== len (row ["pairs" ]) 96assert row ["identical_work" ] 97for saved in row ["pairs" ]: 98pair = pairs [saved ["index" ]] 99a ,b = pair ["baseline" ],pair ["candidate" ] 100assert all (a [k ]== b [k ]for k in WORK ) 101assert saved ["differing_work_fields" ]== [] 102for metric in METRICS : 103same (saved [metric ]["baseline" ],a [metric ]) 104same (saved [metric ]["candidate" ],b [metric ]) 105same (saved [metric ]["time_reduction_pct" ],100 * (1 - b [metric ]/ a [metric ])) 106for metric in METRICS : 107reductions = [100 * (1 - p ["candidate" ][metric ]/ p ["baseline" ][metric ])for p in pairs .values ()] 108expected = { 109"median_paired_time_reduction_pct" :statistics .median (reductions ), 110"min_paired_time_reduction_pct" :min (reductions ), 111"max_paired_time_reduction_pct" :max (reductions ), 112"faster_pairs" :sum (x > 0 for x in reductions ), 113"regressions_over_2pct" :sum (x < - 2 for x in reductions ), 114** {arm + "_median" :statistics .median (p [arm ][metric ]for p in pairs .values ()) 115for arm in ("baseline" ,"candidate" )}, 116 } 117for name ,value in expected .items (): 118same (row [metric ][name ],value ) 119 120 121def check_matrix (name ,expected_pairs ,expected_count ): 122directory = Path ("evidence" )/ name 123matrix = read (directory / "matrix.json" ) 124assert matrix ["complete" ]and matrix ["pairs" ]== expected_pairs 125assert len (matrix ["sessions" ])== expected_pairs * 2 126incremental = matrix ["mode" ]== "incremental" 127shapes = {(n ,inc )for n in matrix ["lengths" ]for inc in matrix ["increments" ]}if incremental else {(n ,0 )for n in matrix ["lengths" ]} 128groups ,count = {},0 129for session in matrix ["sessions" ]: 130assert session ["status" ]== "passed" and session ["returncode" ]== 0 131result = read (directory / session ["name" ]/ "results.json" ) 132assert result ["binary_sha256" ]== matrix ["configs" ][session ["arm" ]]["binary_sha256" ] 133assert result ["fixtures_sha256" ]== matrix ["fixtures_sha256" ] 134device = read (directory / (session ["name" ]+ "-launch.json" ))["device" ] 135assert device ["hip_device_count" ]== 1 and device ["bdf" ]== "0000:63:00.0" 136formal = [r for r in result ["records" ]if r ["phase" ]== "measurement" ] 137warmups = [r for r in result ["records" ]if r ["phase" ]== "shape_warmup" ] 138assert len (formal )== len (warmups )== len (shapes ) 139actual = set () 140for r in formal : 141measured (r ,incremental ) 142key = (r ["base_tokens" ],r ["increment" ])if incremental else (r ["input_tokens" ],0 ) 143assert key not in actual 144actual .add (key ) 145pair = groups .setdefault (key , {}).setdefault (session ["pair" ], {}) 146assert session ["arm" ]not in pair 147pair [session ["arm" ]]= r 148assert actual == shapes 149count += len (formal ) 150assert count == expected_count 151compare_summary (groups ,read (directory / "summary.json" )) 152return groups ,count 153 154 155def check_sources (): 156layout = read ("source-layout.json" ) 157repo = subprocess .check_output (["git" ,"rev-parse" ,"--show-toplevel" ],cwd = ROOT ,text = True ).strip () 158archive = subprocess .check_output (["git" ,"archive" ,layout ["public_base_commit" ], 159"CMakeLists.txt" ,"src" ,"include" ,"tests" ],cwd = repo ) 160with tempfile .TemporaryDirectory (prefix = "r9700-report-source-" )as tmp : 161with tarfile .open (fileobj = io .BytesIO (archive ))as stream : 162stream .extractall (tmp ,filter = "data" ) 163for arm ,patch in (("baseline" ,"measured-baseline.patch" ), ("candidate" ,"pr1107-candidate.patch" )): 164subprocess .run (["git" ,"apply" ,"--unidiff-zero" ,str (ROOT / "patches" / patch )],cwd = tmp ,check = True ) 165for name ,expected in layout ["source_sha256" ][arm ].items (): 166assert hashlib .sha256 ((Path (tmp )/ name ).read_bytes ()).hexdigest ()== expected , (arm ,name ) 167"Archived patches reproduce all changed measured engine sources." ) 168 169 170def main (): 171parser = argparse .ArgumentParser (description = __doc__ ) 172parser .add_argument ("--check-sources" ,action = "store_true" ,help = "also reconstruct source in a temporary directory using the local git object database" ) 173parser .add_argument ("--extract" ,type = Path ,help = "after verification, unpack complete JSON records and engine logs into a new directory" ) 174args = parser .parse_args () 175assert BUNDLE ["schema" ]== 1 176assert BUNDLE ["source_commit" ]== "17006083063b4443458f6f0b3f5c8325cf9cca2a" 177exports = {} 178for line in (ROOT / "SHA256SUMS" ).read_text ().splitlines (): 179expected ,name = line .split (" " ,1 ) 180assert name not in exports 181exports [name ]= expected 182assert hashlib .sha256 ((ROOT / name ).read_bytes ()).hexdigest ()== expected ,name 183actual = {p .relative_to (ROOT ).as_posix ()for p in ROOT .rglob ("*" ) 184if p .is_file ()and "__pycache__" not in p .parts and p .name != "SHA256SUMS" } 185assert set (exports )== actual ,"SHA256SUMS does not cover the report files" 186current = read ("current-speed/iq3_s-session/results.json" ) 187summary = read ("current-speed/summary.json" ) 188formal = [r for r in current ["records" ]if r ["phase" ]== "measurement" ] 189assert len (formal )== 12 190assert len ([r for r in current ["records" ]if r ["phase" ]== "shape_warmup" ])== 4 191fixtures = json .loads (gzip .decompress ((ROOT / "current-speed/fixtures.json.gz" ).read_bytes ())) 192for fixture in fixtures ["fixtures" ]: 193assert len (fixture ["ids" ])== fixture ["tokens" ] 194assert hashlib .sha256 (json .dumps (fixture ["ids" ]).encode ()).hexdigest ()== fixture ["ids_sha256" ] 195hashes = {f ["tokens" ]:f ["ids_sha256" ]for f in fixtures ["fixtures" ]} 196device = read ("current-speed/iq3_s-launch.json" )["device" ] 197assert device ["hip_device_count" ]== 1 and device ["bdf" ]== "0000:63:00.0" 198assert current ["binary_sha256" ]== read ("source-layout.json" )["binary_sha256" ]["candidate" ] 199for row in summary ["rows" ]: 200records = [r for r in formal if r ["input_tokens" ]== row ["input_tokens" ]] 201assert sorted (r ["repeat" ]for r in records )== [0 ,1 ,2 ] 202for r in records : 203measured (r ) 204assert r ["input_ids_sha256" ]== hashes [r ["input_tokens" ]] 205for key ,values in { 206"prefill_tokens_per_s" : [r ["prompt_read" ]* 1000 / r ["prompt_ms" ]for r in records ], 207"decode_tokens_per_s" : [r ["generated" ]* 1000 / r ["decode_ms" ]for r in records ], 208"ttft_s" : [r ["ttft_s" ]for r in records ],"wall_s" : [r ["wall_s" ]for r in records ], 209 }.items (): 210for stat ,value in (("median" ,statistics .median (values )), ("min" ,min (values )), ("max" ,max (values ))): 211same (row [key ][stat ],value ) 212first ,n1 = check_matrix ("pr1107-incremental-screen-iq3s" ,2 ,20 ) 213confirm ,n2 = check_matrix ("pr1107-incremental-confirm-iq3s" ,3 ,30 ) 214for key ,pairs in confirm .items (): 215first [key ].update ({index + 2 :pair for index ,pair in pairs .items ()}) 216compare_summary (first ,read ("evidence/pr1107-incremental-five-pairs-iq3s/summary.json" )) 217_ ,n3 = check_matrix ("pr1107-incremental-screen-iq2xs" ,2 ,20 ) 218_ ,n4 = check_matrix ("pr1107-fresh-screen-iq3s" ,2 ,12 ) 219_ ,n5 = check_matrix ("pr1107-fresh-screen-iq2xs" ,2 ,12 ) 220results = [value for name ,value in BUNDLE ["json" ].items ()if name .endswith ("/results.json" )] 221log_names = {name .removesuffix ("results.json" )+ "engine.log" 222for name in BUNDLE ["json" ]if name .endswith ("/results.json" )} 223assert set (BUNDLE ["logs" ])== log_names and len (log_names )== 23 224check_tables () 225coverage = {"scope" :"Recomputed archived evidence, not new GPU measurements or automatic performance acceptance" , 226"paired_formal_requests" :n1 + n2 + n3 + n4 + n5 ,"current_speed_formal_requests" :len (formal ), 227"retained_records_including_warmups" :sum (len (result ["records" ])for result in results ), 228"engine_logs_verified" :len (log_names ),"exported_artifact_hashes_verified" :len (exports ), 229"all_workload_performance_acceptance" :False } 230assert coverage ["paired_formal_requests" ]== 94 and coverage ["retained_records_including_warmups" ]== 213 231if args .check_sources : 232check_sources () 233assert read ("coverage.json" )== coverage 234if args .extract : 235args .extract .mkdir (parents = True ,exist_ok = False ) 236for kind in ("json" ,"logs" ): 237for name ,value in BUNDLE [kind ].items (): 238relative = Path (name ) 239assert not relative .is_absolute ()and ".." not in relative .parts 240path = args .extract / relative 241path .parent .mkdir (parents = True ,exist_ok = True ) 242path .write_text (json .dumps (value ,ensure_ascii = False ,indent = 2 )+ "\n" if kind == "json" else value ) 243f"Complete measurement records and engine logs extracted to { args . extract } " ) 244json .dumps (coverage ,indent = 2 )) 245 246 247if __name__ == "__main__" : 248main ()