Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/CUDApp/blob/main/evidence/uxl-brief-20261113/archive/tools/analyze.py # CUDApp CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `CUDApp / evidence / uxl-brief-20261113 / archive / tools / analyze.py` 253 lines · 18408 bytes Raw Blame History 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 3 """analyze.py: read the raw files of a hand-run Level 3 card session and print the numbers. Python 3 stdlib only. 4 5 Usage: 6 analyze.py OUT_DIR CUDAPP [--json results.json] notebook layout (files written by the parent): 7 uxl-native-{warmup,run1..run5,control}.txt (+ .err), uxl-l3.log, uxl-graph-fresh.json, 8 uxl-reference-fresh.json, uxl-stock.json, uxl-env.log (missing files are reported, not fatal) 9 analyze.py --published CUDAPP [--json results.json] self-test on the published receipt: 10 evidence/amd-qwen38-native-refusal-`20261113`/native/{warmup,sample1..5,control}.stdout; must reproduce 11 calculations.json (decode medians 26.731 26.642 26.675 26.726 26.760, median prefill 779.042 ms) 12 13 Definitions are those of evidence/amd-qwen38-native-refusal-`20261113`/oracle/benchmark-qualified.py at 14 `dc536882` (the same file in the brief's folder amd-qwen38-native-`20261113`/oracle is byte-identical): 15 line 8 P=F['prompt_ids'];G=F['generated_ids'];N=len(P)+len(G)-1 16 line 66 steps = every '^OMEGA_STEP (\\d+) tok=(\\d+) us=(\\d+)$' line 17 line 67 ids = the '^OMEGA_PLAN ids=[...]' list 18 line 68 shape = exit==0 and step indices == range(N) and ids == tok of steps[len(P)-1:] 19 (the exit code is not in a .txt capture; this script uses the rest of line 68 and reports that) 20 line 69 prefill_ms = sum(u/1000 for steps[:len(P)]); decode_ms_median = statistics.median(u/1000 for steps[len(P):]) 21 Aggregates follow evidence/amd-qwen38-native-refusal-`20261113`/calculate.py: median of the five timed decode medians, 22 median of the five prefill values, 1000/median, and spark-baseline/qualification.json graph_ms_per_token / median. 23 Exit status 0 when every check passes, 1 otherwise. 24 """ 25 import hashlib, json, re, statistics, sys 26 from pathlib import Path 27 28 COMMIT = '`dc536882c06a692991be97dc65cd2d037d82b129`' 29 PLAN_SHA = '`2a292dadc236f224005ed4e2d8ac2ba8b33dc71d79dabcc8497d177561f9c012`' 30 CONTROLS_SHA = '`40701b9a81ef55c3dc92620df801d595cd1a10360ae047e14e76de37e279228e`' 31 TIMED = ['run1', 'run2', 'run3', 'run4', 'run5'] 32 LABELS = ['warmup'] + TIMED + ['control'] 33 STEP = re.compile(r'^OMEGA_STEP (\d+) tok=(\d+) us=(\d+)$', re.M) 34 IDS = re.compile(r'^OMEGA_PLAN ids=\[([\d, ]+)\]$', re.M) 35 36 def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest() 37 def first_div(a, b): return next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), None) 38 def compare_stock(ids, native, G): 39 if not isinstance(ids, list): return {'n_ids': 0} 40 return {'n_ids': len(ids), 'ids_equal_native': ids == native, 'first_divergence_from_native': first_div(ids, native), 41 'ids_equal_spark': ids == G, 'first_divergence_from_spark': first_div(ids, G)} 42 def load(p): 43 try: return json.loads(Path(p).read_text()) 44 except (OSError, ValueError) as e: return {'_error': repr(e)} 45 46 def parse_run(text, P, G): 47 """benchmark-qualified.py lines 66-69, unchanged apart from the exit code.""" 48 N = len(P) + len(G) - 1 49 steps = [tuple(map(int, v)) for v in STEP.findall(text)] 50 m = IDS.search(text); ids = list(map(int, m.group(1).split(','))) if m else [] 51 shape = [i for i, t, u in steps] == list(range(N)) and ids == [t for i, t, u in steps[len(P) - 1:]] 52 return {'steps': len(steps), 'expected_steps': N, 'prompt_steps': len(P), 'n_ids': len(ids), 'shape_ok': shape, 53 'prefill_ms': sum(u / 1000 for i, t, u in steps[:len(P)]) if shape else None, 54 'decode_ms_median': statistics.median(u / 1000 for i, t, u in steps[len(P):]) if shape else None, 55 'first_divergence_from_spark': first_div(ids, G) if ids else None, 56 'ids_match_spark': sum(a == b for a, b in zip(ids, G)), 'ids_equal_spark': ids == G, 57 'step_us': [u for i, t, u in steps], 'ids': ids} 58 59 def parse_l3(path): 60 """Tolerant reader of the shell trace: sha256sum lines for the two plans, and per-run start/end epoch seconds 61 on lines that name a run label and the word start/begin or end/done/finish (any order, any separators).""" 62 out = {'plan_sha256_lines': [], 'run_epochs': {}, 'unparsed_epoch_lines': []} 63 for line in Path(path).read_text(errors='replace').splitlines(): 64 m = re.search(r'\b([0-9a-f]{64})\b\s+\S*?(real2(?:-controls)?\.plan)\b', line) 65 if m: out['plan_sha256_lines'].append({'plan': m.group(2), 'sha256': m.group(1), 'line': line.strip()}) 66 ep = re.findall(r'(?= 0 for x in obj): found.append((path, obj)) 85 else: 86 for i, v in enumerate(obj): find_id_lists(v, '%s/%d' % (path, i), found) 87 return found 88 89 def scalars(obj, path='', out=None, depth=0): 90 out = {} if out is None else out 91 if isinstance(obj, dict) and depth < 4: 92 for k, v in obj.items(): scalars(v, path + '/' + str(k), out, depth + 1) 93 elif isinstance(obj, (int, float, str, bool)) or obj is None: 94 out[path] = obj if not isinstance(obj, str) else obj[:200] 95 return out 96 97 def main(): 98 a = sys.argv[1:]; js = None 99 if '--json' in a: i = a.index('--json'); js = Path(a[i + 1]); del a[i:i + 2] 100 published = '--published' in a 101 if published: a.remove('--published') 102 if (published and len(a) != 1) or (not published and len(a) != 2): sys.exit(__doc__) 103 repo = Path(a[-1]).resolve(); out = None if published else Path(a[0]).resolve() 104 D = repo / 'evidence' / 'amd-qwen38-native-refusal-`20261113`' 105 F = load(D / 'oracle' / 'lighthouse256.json'); P, G = F['prompt_ids'], F['generated_ids'] 106 GRAPH = load(D / 'numerical' / 'graph.json')['ids'] 107 spark_ms = load(D / 'spark-baseline' / 'qualification.json').get('graph_ms_per_token') 108 R = {'mode': 'published self-test' if published else 'notebook out/', 'cudapp': str(repo), 'out_dir': str(out) if out else None, 109 'definitions_source': 'evidence/amd-qwen38-native-refusal-`20261113`/oracle/benchmark-qualified.py lines 8, 66-69; aggregates as calculate.py', 110 'reference_files': {'lighthouse256.json': sha(D / 'oracle' / 'lighthouse256.json'), 'numerical/graph.json': sha(D / 'numerical' / 'graph.json'), 111 'benchmark-qualified.py': sha(D / 'oracle' / 'benchmark-qualified.py')}, 112 'inputs': {}, 'missing': [], 'checks': {}, 'runs': {}} 113 try: 114 import subprocess 115 R['cudapp_head'] = subprocess.run(['git', '-C', str(repo), 'rev-parse', 'HEAD'], capture_output=True, text=True).stdout.strip() 116 except Exception as e: R['cudapp_head'] = repr(e) 117 R['checks']['cudapp_head_is_`dc536882`'] = R['cudapp_head'] == COMMIT 118 119 def src(label, ext): 120 if published: 121 return D / 'native' / ({'run%d' % i: 'sample%d' % i for i in range(1, 6)}.get(label, label) + ('.stdout' if ext == 'txt' else '.stderr')) 122 return out / ('uxl-native-%s.%s' % (label, ext)) 123 for lab in LABELS: 124 f = src(lab, 'txt'); e = src(lab, 'err') 125 if not f.is_file(): R['missing'].append(str(f)); continue 126 r = parse_run(f.read_text(errors='replace'), P, G) 127 r['file'] = str(f); r['sha256'] = sha(f) 128 if e.is_file(): 129 t = e.read_text(errors='replace'); r['err_file'] = str(e); r['err_sha256'] = sha(e); r['err_bytes'] = len(t.encode()); r['err_tail'] = t[-300:] 130 r['ids_equal_published_graph'] = bool(r['ids']) and r['ids'] == GRAPH 131 r['first_divergence_from_published_graph'] = first_div(r['ids'], GRAPH) if r['ids'] else None 132 R['inputs'][f.name] = r['sha256']; R['runs'][lab] = r 133 134 if not published: 135 for name in ('uxl-l3.log', 'uxl-graph-fresh.json', 'uxl-reference-fresh.json', 'uxl-stock.json', 'uxl-env.log'): 136 p = out / name 137 if p.is_file(): R['inputs'][name] = sha(p) 138 else: R['missing'].append(str(p)) 139 if (out / 'uxl-l3.log').is_file(): 140 l3 = parse_l3(out / 'uxl-l3.log'); R['l3_log'] = l3 141 for lab, d in l3['run_epochs'].items(): 142 if lab in R['runs'] and 'wall_s' in d: R['runs'][lab]['process_wall_s_from_l3_log'] = d['wall_s'] 143 shas = {} 144 for x in l3['plan_sha256_lines']: shas.setdefault(x['plan'], set()).add(x['sha256']) 145 R['plan_sha256_seen'] = {k: sorted(v) for k, v in shas.items()} 146 R['checks']['plan_sha256_equals_brief'] = shas.get('real2.plan') == {PLAN_SHA} 147 R['checks']['controls_plan_sha256_equals_readme'] = shas.get('real2-controls.plan') == {CONTROLS_SHA} 148 149 # ---- checks on the native runs 150 timed = [R['runs'].get(l) for l in TIMED]; have = all(timed) 151 allrun = [R['runs'][l] for l in ['warmup'] + TIMED if l in R['runs']] 152 C = R['checks'] 153 C['all_7_native_files_present'] = all(l in R['runs'] for l in LABELS) 154 C['every_run_285_steps_shape_ok'] = len(allrun) == 6 and all(r['shape_ok'] and r['steps'] == len(P) + len(G) - 1 for r in allrun) 155 C['every_run_256_ids'] = len(allrun) == 6 and all(r['n_ids'] == len(G) for r in allrun) 156 C['every_run_ids_equal_published_graph'] = len(allrun) == 6 and all(r['ids_equal_published_graph'] for r in allrun) 157 ctl = R['runs'].get('control') 158 if ctl: 159 C['control_shape_ok'] = ctl['shape_ok'] 160 C['control_ids_differ_from_published_graph'] = bool(ctl['ids']) and ctl['ids'] != GRAPH 161 C['control_ids_differ_from_every_native_run'] = bool(ctl['ids']) and all(ctl['ids'] != r['ids'] for r in allrun) 162 ctl['first_divergence_from_native_run1'] = first_div(ctl['ids'], timed[0]['ids']) if timed[0] else None 163 164 agg = {} 165 if have and all(r['shape_ok'] for r in timed): 166 dm = [r['decode_ms_median'] for r in timed]; pm = [r['prefill_ms'] for r in timed] 167 agg = {'timed_decode_ms_medians': dm, 'median_decode_ms': statistics.median(dm), 'timed_prefill_ms': pm, 168 'median_prefill_ms': statistics.median(pm), 'warmup_decode_ms_median': R['runs'].get('warmup', {}).get('decode_ms_median'), 169 'derived_reciprocal_median_step_tokens_s': 1000 / statistics.median(dm), 170 'historical_spark_graph_ms': spark_ms, 171 'historical_spark_graph_time_ratio': spark_ms / statistics.median(dm) if spark_ms else None, 172 'first_divergence_from_spark': [r['first_divergence_from_spark'] for r in timed]} 173 walls = [r.get('process_wall_s_from_l3_log') for r in timed] 174 if all(w is not None for w in walls): agg['timed_process_wall_s_from_l3_log'] = walls; agg['median_process_wall_s_from_l3_log'] = statistics.median(walls) 175 R['aggregate'] = agg 176 native = timed[0]['ids'] if have and timed[0]['ids'] else GRAPH 177 178 if published: 179 calc = load(D / 'calculations.json') 180 C['reproduces_published_decode_medians'] = agg.get('timed_decode_ms_medians') == calc['accepted_decode_ms'] 181 C['reproduces_published_median_decode_ms'] = agg.get('median_decode_ms') == calc['median_decode_ms'] 182 C['reproduces_published_median_prefill_ms'] = agg.get('median_prefill_ms') == calc['median_prefill_ms'] 183 C['reproduces_published_ratio'] = agg.get('historical_spark_graph_time_ratio') == calc['historical_spark_graph_time_ratio'] 184 for i, l in enumerate(TIMED, 1): 185 s = load(D / 'native' / ('sample%d.json' % i)) 186 C['%s_matches_sample%d.json' % (l, i)] = (R['runs'][l]['prefill_ms'] == s['prefill_ms'] and R['runs'][l]['decode_ms_median'] == s['decode_ms_median'] 187 and R['runs'][l]['first_divergence_from_spark'] == s['first_divergence']) 188 # negative control: one altered id must be refused by the shape check 189 bad = IDS.sub(lambda m: m.group(0).replace('[', '[9', 1), src('run1', 'txt').read_text(), count=1) 190 C['negative_control_altered_id_refused'] = not parse_run(bad, P, G)['shape_ok'] 191 else: 192 g = load(out / 'uxl-graph-fresh.json') 193 if 'ids' in g: 194 R['graph_fresh'] = {k: v for k, v in g.items() if k not in ('ids', 'top5')} 195 R['graph_fresh'].update(n_ids=len(g['ids']), ids_equal_published_graph=g['ids'] == GRAPH, first_divergence_from_spark=first_div(g['ids'], G)) 196 C['graph_fresh_256_ids'] = len(g['ids']) == len(G) 197 C['every_run_ids_equal_graph_fresh'] = len(allrun) == 6 and all(r['ids'] == g['ids'] for r in allrun) 198 if ctl: C['control_ids_differ_from_graph_fresh'] = ctl['ids'] != g['ids'] 199 else: R['graph_fresh'] = g 200 ref = load(out / 'uxl-reference-fresh.json') 201 if 'ids' in ref: 202 R['reference_fresh'] = {k: v for k, v in ref.items() if k not in ('ids', 'top5')} 203 R['reference_fresh'].update(n_ids=len(ref['ids']), ids_equal_native=ref['ids'] == native, first_divergence_from_native=first_div(ref['ids'], native), 204 ids_equal_spark=ref['ids'] == G, first_divergence_from_spark=first_div(ref['ids'], G)) 205 C['reference_fresh_256_ids'] = len(ref['ids']) == len(G) 206 else: R['reference_fresh'] = ref 207 st = load(out / 'uxl-stock.json') 208 R['stock'] = {'scalars': scalars(st), 'id_lists': [{'path': p, 'ids_equal_native': v == native, 'first_divergence_from_native': first_div(v, native), 209 'ids_equal_spark': v == G, 'first_divergence_from_spark': first_div(v, G)} for p, v in find_id_lists(st)]} 210 # stock-cell.py rows: decode_ms = intervals between StoppingCriteria calls after tokens 1..256 (255 values), 211 # first_token_s = call start to the first StoppingCriteria call; values are the cell's own, copied, not recomputed 212 rows = st.get('rows') if isinstance(st.get('rows'), list) else [] 213 R['stock']['rows'] = [{k: x.get(k) for k in ('label', 'total_s', 'first_token_s', 'decode_ms_median', 'decode_ms_min', 'decode_ms_max', 'prompt_tokens', 'calls')} 214 | {'n_decode_ms': len(x.get('decode_ms') or []), **compare_stock(x.get('generated_ids'), native, G)} for x in rows if isinstance(x, dict)] 215 tr = [x for x in R['stock']['rows'] if x['label'] in TIMED and isinstance(x.get('decode_ms_median'), (int, float))] 216 if len(tr) == 5: R['stock']['median_of_timed_decode_ms_median'] = statistics.median(x['decode_ms_median'] for x in tr); R['stock']['median_of_timed_total_s'] = statistics.median(x['total_s'] for x in tr) 217 for r in R['runs'].values(): r.pop('ids', None) # ids live in the input files; per-step us are kept 218 R['all_checks_pass'] = all(v is True for v in C.values()) 219 220 # ---- text table 221 w = print 222 w('analyze.py %s CUDApp %s definitions: benchmark-qualified.py lines 8, 66-69' % (R['mode'], R['cudapp_head'])) 223 w('%-8s %6s %5s %8s %13s %17s %10s %10s %11s' % ('run', 'steps', 'ids', 'shape', 'prefill_ms', 'decode_median_ms', '=graph', 'spark_div', 'wall_s_l3')) 224 for l in LABELS: 225 r = R['runs'].get(l) 226 if not r: w('%-8s MISSING' % l); continue 227 f = lambda v, d: ('%.' + str(d) + 'f') % v if isinstance(v, (int, float)) else '-' 228 w('%-8s %6d %5d %8s %13s %17s %10s %10s %11s' % (l, r['steps'], r['n_ids'], r['shape_ok'], f(r['prefill_ms'], 3), f(r['decode_ms_median'], 3), 229 r['ids_equal_published_graph'], r['first_divergence_from_spark'], f(r.get('process_wall_s_from_l3_log'), 3))) 230 for k in ('median_decode_ms', 'median_prefill_ms', 'derived_reciprocal_median_step_tokens_s', 'historical_spark_graph_ms', 'historical_spark_graph_time_ratio', 231 'median_process_wall_s_from_l3_log'): 232 if k in agg: w('%-42s %s' % (k, agg[k])) 233 for name in ('graph_fresh', 'reference_fresh'): 234 x = R.get(name) 235 if isinstance(x, dict) and 'n_ids' in x: 236 w('%-16s ids=%d decode_ms_median=%s first_div_spark=%s %s' % (name, x['n_ids'], x.get('decode_ms_median'), x.get('first_divergence_from_spark'), 237 ('equal_native=%s first_div_native=%s' % (x['ids_equal_native'], x['first_divergence_from_native'])) if 'ids_equal_native' in x else 'equal_published_graph=%s' % x['ids_equal_published_graph'])) 238 if 'stock' in R: 239 w('stock %d id list(s) of 256 found; scalars: %d' % (len(R['stock']['id_lists']), len(R['stock']['scalars']))) 240 for x in R['stock'].get('rows', []): 241 w('stock %-8s total_s=%s first_token_s=%s decode_ms_median=%s n_decode_ms=%s prompt_tokens=%s ids=%s first_div_native=%s first_div_spark=%s' % ( 242 x['label'], x['total_s'], x['first_token_s'], x['decode_ms_median'], x['n_decode_ms'], x['prompt_tokens'], x['n_ids'], 243 x.get('first_divergence_from_native'), x.get('first_divergence_from_spark'))) 244 for k in ('median_of_timed_decode_ms_median', 'median_of_timed_total_s'): 245 if k in R['stock']: w('stock %-36s %s' % (k, R['stock'][k])) 246 for m in R['missing']: w('MISSING %s' % m) 247 for k, v in C.items(): w('CHECK %-48s %s' % (k, 'PASS' if v is True else 'FAIL')) 248 w('ANALYZE %s' % ('PASS' if R['all_checks_pass'] and not R['missing'] else 'FAIL')) 249 if js: js.write_text(json.dumps(R, indent=1) + '\n'); w('wrote %s sha256=%s' % (js, sha(js))) 250 sys.exit(0 if R['all_checks_pass'] and not R['missing'] else 1) 251 252 if __name__ == '__main__': 253 main()