interplane.Get Omega
Read in your language

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

branch main Branches Tags History

CUDApp / tests / amd-exec / fp8block_fast_notebook / selfcheck.py

140 lines · 8026 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Run the complete cell wrapper against injected HIP and torch simulations.
4No GPU calls, library kernels or performance measurements occur here.
5"""
6import argparse
7import ast
8import base64
9import hashlib
10import json
11import os
12from pathlib import Path
13import re
14import subprocess
15import sys
16import zlib
17
18HERE=Path(__file__).resolve().parent
19
20def sha(data): return hashlib.sha256(data).hexdigest()
21
22def injected_cell():
23 cell=(HERE/'cell-v13.py').read_text()
24 blobs=[n.args[0].value for n in ast.walk(ast.parse(cell)) if isinstance(n,ast.Call) and isinstance(n.func,ast.Attribute) and n.func.attr=='b85decode']
25 assert len(blobs)==1
26 driver=zlib.decompress(base64.b85decode(blobs[0])).decode()
27 build=json.loads((HERE/'build.json').read_text())
28 assert sha(driver.encode())==build['driver_sha256'] and sha(cell.encode())==build['sha256']
29 fake=(HERE/'simulated_device.py').read_text()
30 assert driver.count('# SELFCHECK_INSERT')==1
31 modified=driver.replace('# SELFCHECK_INSERT',fake)
32 blob=base64.b85encode(zlib.compress(modified.encode(),9)).decode()
33 assert cell.count(repr(blobs[0]))==1
34 cell=cell.replace(repr(blobs[0]),repr(blob))
35 assert cell.count(repr(build['driver_sha256']))==1
36 cell=cell.replace(repr(build['driver_sha256']),repr(sha(modified.encode())))
37 return cell,build
38
39
40def check_oracle(cell):
41 import numpy as np
42 blob=next(n.args[0].value for n in ast.walk(ast.parse(cell)) if isinstance(n,ast.Call) and isinstance(n.func,ast.Attribute) and n.func.attr=='b85decode')
43 driver=zlib.decompress(base64.b85decode(blob)).decode()
44 # Definitions only: __name__ is not __main__; no parent/child/device execution.
45 ns={'__name__':'selfcheck_definitions'}
46 exec(compile(driver,'selfcheck_definitions','exec'),ns)
47 ns['np']=np
48 table=ns['fp8_table']()
49 assert table[0]==0 and table[128]==0 and np.signbit(table[128])
50 assert table[1]==2.0**-9 and table[126]==448 and table[254]==-448
51 assert np.isnan(table[127]) and np.isnan(table[255])
52 case=ns['fixture'](257,259); expected=ns['oracle'](case)
53 data=expected[0].astype(np.float32)
54 assert ns['mismatches'](data.tobytes(),expected)==0
55 data[-2]=1e30
56 assert ns['mismatches'](data.tobytes(),expected)==1
57 print('ORACLE SELFCHECK OCP signed zero/subnormal/max/NaNs and last-finite-row corruption CAUGHT',flush=True)
58
59
60def run(cell,build,root,mode,group=''):
61 folder=root/mode; folder.mkdir(parents=True,exist_ok=False)
62 script=folder/'cell.py'; script.write_text(cell)
63 env=dict(os.environ,OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1')
64 for key in ('AMDSERVE_GROUP','AMDSERVE_T0','SELFCHECK_FAULT_GROUP','SELFCHECK_ESCAPE_GROUP','SELFCHECK_CORRUPT_GROUP'): env.pop(key,None)
65 if mode!='normal': env[{'fault':'SELFCHECK_FAULT_GROUP','escaped':'SELFCHECK_ESCAPE_GROUP','corrupt':'SELFCHECK_CORRUPT_GROUP'}[mode]]=group
66 proc=subprocess.run([sys.executable,str(script)],cwd=folder,env=env,capture_output=True,text=True,timeout=3600)
67 (folder/'stdout.txt').write_text(proc.stdout); (folder/'stderr.txt').write_text(proc.stderr)
68 assert proc.returncode==0,(proc.returncode,proc.stderr)
69 output=(folder/'amdserve-probe-v13.txt').read_text()
70 records=[json.loads(line) for line in (folder/'amdserve-probe-v13.txt.state').read_text().splitlines()]
71 groups=[g['id'] for g in build['groups']]
72 seen=[r['group'] for r in records]
73 assert len(seen)==len(set(seen))
74 assert 'SIMULATED host; no device query' in output
75 assert 'CONTROLS ' in output and 'RESULT overall ' in output
76 first_correct=output.index('GROUP correct-')
77 assert output.index('CONTROLS ')<first_correct,'controls summary must precede correctness and timing'
78 if mode=='normal':
79 assert set(seen)==set(groups) and all(r['ok'] for r in records)
80 assert 'RESULT overall PASS' in output and 'CONTROLS all CAUGHT' in output
81 assert 'FAULT ' not in output and 'ERROR ' not in output
82 elif mode=='fault':
83 line=next(line for line in output.splitlines() if line.startswith('FAULT group '+group))
84 assert 'exit -11' in line and re.search(r'sha256 [0-9a-f]{64}\b',line)
85 assert set(seen)==set(groups)-{group} and all(r['ok'] for r in records)
86 assert 'RESULT overall FAIL_OR_INCOMPLETE; missing='+group in output
87 assert 'CONTROLS ESCAPED or NOT_RUN' in output
88 else:
89 assert set(seen)==set(groups)
90 assert [r['group'] for r in records if not r['ok']]==[group]
91 assert 'RESULT overall FAIL_OR_INCOMPLETE' in output
92 if mode=='escaped': assert group[4:]+' ESCAPED' in output and 'CONTROLS ESCAPED or NOT_RUN' in output
93 else: assert 'all-row oracle mismatches=1' in output
94 correct={}
95 for line in output.splitlines():
96 if line.startswith('OMEGA CORRECTNESS '):
97 values=dict(re.findall(r'(\w+)=([^ ]+)',line))
98 correct[((int(values['M']),int(values['K'])),values['kernel'])]=values['same_data_sha256']
99 timed=[]; reference=[]
100 for prefix,rows in (('OMEGA TIMING',timed),('REFERENCE torch.matmul BF16 (AMD library, not Omega)',reference)):
101 for line in output.splitlines():
102 if not line.startswith(prefix): continue
103 values=dict(re.findall(r'(\w+)=([^ ]+)',line))
104 shape=(int(values['M']),int(values['K']))
105 key=(shape,values.get('kernel','torch'))
106 if key in correct: assert values['same_data_sha256']==correct[key]
107 assert int(values['rotation_bytes'])>256*(1<<20)
108 assert int(values['cold_calls'])%int(values['copies'])==0
109 assert float(values['warm_ms'])>0 and float(values['cold_rotation_ms'])>0
110 assert 'SIMULATED_NOT_MEASURED' in line
111 rows.append((key,values['same_data_sha256']))
112 expected={(tuple(g['shape']),g['kernel']) for g in build['groups'] if g['kind']=='timing'}
113 assert len(timed)==len(expected) and {key for key,d in timed}==expected
114 assert len(reference)==len({shape for shape,kernel in expected})
115 refs={key[0]:digest for key,digest in reference}
116 for key,digest in timed: assert refs[key[0]]==digest,'Omega/reference data differs'
117 if mode=='normal': assert expected<=correct.keys()
118 print('SIMULATED_DEVICE mode=%s parent_exit=%d groups_recorded=%d/%d omega_timing_rows=%d reference_rows=%d result=%s' % (mode,proc.returncode,len(seen),len(groups),len(timed),len(reference),'PASS' if mode=='normal' else 'NEGATIVE_CAUGHT'),flush=True)
119 summary=[line for line in output.splitlines() if line.startswith(('CONTROLS ','RESULT ','FAULT ','ERROR '))]
120 for line in summary: print(line,flush=True)
121 return dict(mode=mode,injected_group=group,exit=proc.returncode,result='PASS' if mode=='normal' else 'NEGATIVE_CAUGHT',
122 output=str(folder/'amdserve-probe-v13.txt'),output_sha256=sha(output.encode()),
123 simulated_only=True,hardware='NOT_RUN',performance='NOT_RUN')
124
125
126def main():
127 parser=argparse.ArgumentParser(); parser.add_argument('--out',required=True,type=Path); args=parser.parse_args()
128 args.out.mkdir(parents=True,exist_ok=False)
129 cell,build=injected_cell()
130 check_oracle(cell)
131 ctl=next(g['id'] for g in build['groups'] if g['kind']=='control')
132 correct=next(g['id'] for g in build['groups'] if g['kind']=='correctness')
133 result=[run(cell,build,args.out,'normal'),run(cell,build,args.out,'fault',ctl),
134 run(cell,build,args.out,'escaped',ctl),run(cell,build,args.out,'corrupt',correct)]
135 report=dict(cell_sha256=build['sha256'],simulated_device_sha256=sha((HERE/'simulated_device.py').read_bytes()),runs=result,
136 hardware='NOT_RUN',performance='NOT_RUN')
137 (HERE/'selfcheck.json').write_text(json.dumps(report,indent=2)+'\n')
138 print('SELFCHECK PASS normal, child SIGSEGV, escaped mutant, last-finite-row corruption; HARDWARE NOT_RUN PERFORMANCE NOT_RUN',flush=True)
139
140if __name__=='__main__': main()