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 / driver.template.py

356 lines · 17290 bytes Raw Blame History
1# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2# Outside notebook verification/timing instrument, not an Omega runtime dependency.
3import base64, ctypes, ctypes.util, glob, hashlib, json, math, os, struct, subprocess, sys, time, traceback, zlib
4DATA = json.loads(zlib.decompress(base64.b85decode('@DATA@')))
5GROUP = os.environ.get('AMDSERVE_GROUP', '')
6OUTF = 'amdserve-probe-v13.txt'
7STATEF, MARKF = OUTF + '.state', OUTF + '.mark'
8T_START = float(os.environ.get('AMDSERVE_T0', time.time()))
9SLACK = 1 << 20
10CACHE_BYTES = 256 * (1 << 20)
11COLD_BYTES = 1100000000
12MIN_CALLS = 200
13SIMULATED = False
14
15def say(text):
16 line = '%s [t=%ds]' % (text, time.time()-T_START)
17 print(line, flush=True)
18 with open(OUTF, 'a') as f: f.write(line+'\n')
19
20def summarize_controls(records):
21 controls = {}
22 for record in records: controls.update(record.get('controls', {}))
23 expected = [g['id'][4:] for g in DATA['groups'] if g['kind']=='control']
24 good = set(controls)==set(expected) and all(v is True for v in controls.values())
25 say('CONTROLS %s %s' % ('all CAUGHT' if good else 'ESCAPED or NOT_RUN', '; '.join('%s=%s' % (n,controls.get(n,'NOT_RUN')) for n in expected)))
26 return good
27
28def read_records():
29 records = []
30 for line in open(STATEF): records.append(json.loads(line))
31 return records
32
33def parent():
34 open(OUTF,'w').close(); open(STATEF,'w').close()
35 faults = []; interrupted = False
36 say('AMDSERVE-PROBE-V11 source=%s groups=%d; controls first; isolated children' % (DATA['source_head'],len(DATA['groups'])))
37 try:
38 host = subprocess.run("rocminfo | grep -m2 -E 'Marketing Name: +AMD|Name: +gfx'; cat /opt/rocm/.info/version",shell=True,capture_output=True,text=True,timeout=30)
39 say('HOST '+ ' | '.join(host.stdout.splitlines()))
40 controls_done = False
41 for group in DATA['groups']:
42 if group['kind']!='control' and not controls_done:
43 summarize_controls(read_records()); controls_done=True
44 if os.path.exists(MARKF): os.remove(MARKF)
45 errfile = OUTF+'.stderr-'+group['id']
46 try:
47 with open(errfile,'w') as err:
48 rc = subprocess.run([sys.executable,os.path.abspath(__file__)],env=dict(os.environ,AMDSERVE_GROUP=group['id'],AMDSERVE_T0=str(T_START),OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1'),stdout=subprocess.DEVNULL,stderr=err,timeout=900).returncode
49 except subprocess.TimeoutExpired:
50 rc='TIMEOUT(900s)'
51 if rc!=0:
52 faults.append(group['id'])
53 marker=open(MARKF).read().strip() if os.path.exists(MARKF) else 'none'
54 tail=' | '.join(open(errfile).read().splitlines()[-2:])[:300]
55 say('FAULT group %s exit %s; last launch: %s; stderr: %s' % (group['id'],rc,marker,tail))
56 except BaseException:
57 interrupted=True
58 say('ERROR parent '+ ' | '.join(traceback.format_exc().splitlines()[-3:]))
59 finally:
60 try:
61 records=read_records(); seen=[r['group'] for r in records]
62 missing=[g['id'] for g in DATA['groups'] if g['id'] not in seen]
63 caught=summarize_controls(records)
64 ok=not interrupted and not faults and not missing and len(seen)==len(set(seen))==len(DATA['groups']) and caught and all(r['ok'] for r in records)
65 say('RESULT overall %s%s' % ('PASS' if ok else 'FAIL_OR_INCOMPLETE','; missing='+','.join(missing) if missing else ''))
66 except BaseException as error:
67 say('CONTROLS ESCAPED or NOT_RUN; malformed or absent state')
68 say('RESULT overall FAIL_OR_INCOMPLETE; summary='+str(error))
69 say('NOT_RUN full-model logits/tokens, native Omega launcher; simulated-device results are not hardware or performance evidence')
70
71
72def marker(text):
73 with open(MARKF,'w') as f:
74 f.write(text+' in group '+GROUP); f.flush(); os.fsync(f.fileno())
75
76
77def setup_hip():
78 for lib in [ctypes.util.find_library('amdhip64')]+sorted(glob.glob('/opt/rocm*/lib/libamdhip64.so*')):
79 if lib:
80 try:
81 device=ctypes.CDLL(lib)
82 say('HIP_LIBRARY '+lib)
83 return device
84 except OSError: pass
85 raise RuntimeError('libamdhip64 unavailable; nothing launched')
86
87
88def chk(rc,label):
89 if rc!=0: raise RuntimeError('%s rc=%s' % (label,rc))
90
91
92def put(buf):
93 p=ctypes.c_void_p()
94 chk(hip.hipMalloc(ctypes.byref(p),ctypes.c_size_t(len(buf)+SLACK)),'hipMalloc')
95 try:
96 if buf: chk(hip.hipMemcpy(p,buf,ctypes.c_size_t(len(buf)),1),'H2D')
97 chk(hip.hipMemset(ctypes.c_void_p(p.value+len(buf)),0,ctypes.c_size_t(SLACK)),'zero slack')
98 except BaseException:
99 hip.hipFree(p); raise
100 return p
101
102
103def get(p,n):
104 out=ctypes.create_string_buffer(n)
105 chk(hip.hipMemcpy(out,p,ctypes.c_size_t(n),2),'D2H')
106 return out.raw
107
108
109def fp8_table():
110 # Independent OCP sign/exponent/fraction definition; NOT native FNUZ.
111 table=[]
112 for byte in range(256):
113 e,f=(byte>>3)&15,byte&7
114 value=math.nan if e==15 and f==7 else math.ldexp(f,-9) if e==0 else math.ldexp(8+f,e-10)
115 table.append(-value if byte&128 else value)
116 return np.array(table,dtype=np.float64)
117
118
119def fixture(m,k,special=False):
120 rng=np.random.default_rng(942128+m*65537+k)
121 w=rng.integers(0,256,size=(m,k),dtype=np.uint8)
122 # Keep numerical coverage: uniform NaNs at long K would make almost every output NaN.
123 # Finite rows retain all 254 finite encodings, including OCP -0 and +/-448.
124 w[(w&127)==127]=126
125 if special:
126 assert (m,k)==(256,1)
127 w[:,0]=np.arange(256,dtype=np.uint8)
128 elif m and k:
129 w[0,0]=127
130 if m>1: w[-1,-1]=255
131 if m>2: w[1,0]=128
132 if k>1 and m>2: w[1,1]=126
133 if k>2 and m>2: w[1,2]=254
134 xwords=rng.integers(0x3c00,0x3f81,size=k,dtype=np.uint16)
135 xwords|=rng.integers(0,2,size=k,dtype=np.uint16)<<15
136 x=(xwords.astype(np.uint32)<<16).view(np.float32)
137 scales=rng.integers(0x3800,0x4081,size=((m+127)//128,(k+127)//128),dtype=np.uint16)
138 if special: x[:]=1; scales[:]=0x3f80
139 image=[w.tobytes(),x.tobytes(),scales.tobytes(),b'\xa5'*(m*4)]
140 h=hashlib.sha256()
141 h.update(struct.pack('<II',m,k))
142 for b in image[:3]: h.update(b)
143 return dict(m=m,k=k,w=w,x=x,scales=scales,buffers=image,digest=h.hexdigest())
144
145
146def gamma(n,u):
147 return n*u/(1-n*u)
148
149
150def oracle(case,bf16=False):
151 m,k=case['m'],case['k']; table=fp8_table(); x=case['x'].astype(np.float64)
152 ref=np.zeros(m,dtype=np.float64); mag=np.zeros(m,dtype=np.float64)
153 scales=(case['scales'].astype(np.uint32)<<16).view(np.float32).astype(np.float64)
154 for row in range(0,m,128):
155 end=min(row+128,m)
156 w=table[case['w'][row:end]]
157 s=np.repeat(scales[row//128],128)[:k]
158 w*=s
159 if bf16:
160 bits=w.astype(np.float32).view(np.uint32)
161 rounded=((bits+0x7fff+((bits>>16)&1))>>16).astype(np.uint16)
162 # NaN payloads must remain NaNs after rounding, never turn into infinity.
163 rounded[np.isnan(w)]=0x7fc0
164 w=(rounded.astype(np.uint32)<<16).view(np.float32).astype(np.float64)
165 ref[row:end]=w@x
166 mag[row:end]=np.abs(w)@np.abs(x)
167 # FP32 path depth: two products/FMA, six tree adds, then ceil(K/128) block FMAs.
168 # Float64 calculator error is included; test inputs avoid finite under/overflow.
169 n=(k+127)//128+8
170 bound=(gamma(n,2.0**-24)+gamma(2*k+n,2.0**-53))*mag+2.0**-126
171 if bf16:
172 # AMD library uses BF16 inputs/output; permit FP32 accumulation then BF16 rounding.
173 bound=(gamma(k+1,2.0**-24)+gamma(2*k+1,2.0**-53))*mag
174 bound+=2.0**-8*(np.abs(ref)+bound)+2.0**-126
175 return ref,bound
176
177
178def mismatches(raw,expected):
179 ref,bound=expected
180 y=np.frombuffer(raw,dtype='<f4').astype(np.float64)
181 assert y.shape==ref.shape
182 finite=np.isfinite(ref)
183 good=np.where(finite,np.isfinite(y)&(np.abs(y-ref)<=bound),np.isnan(ref)&np.isnan(y))
184 return int(np.count_nonzero(~good))
185
186
187def require_output(raw,expected,label):
188 bad=mismatches(raw,expected)
189 if bad: raise AssertionError('%s all-row oracle mismatches=%d' % (label,bad))
190
191
192class Module:
193 def __init__(self,name):
194 self.name=name; self.module=ctypes.c_void_p(); self.fn=ctypes.c_void_p()
195 item=DATA['objects'][name]; self.sha=item['sha256']
196 raw=base64.b64decode(item['base64'])
197 assert hashlib.sha256(raw).hexdigest()==self.sha,'object digest mismatch'
198 chk(hip.hipModuleLoadData(ctypes.byref(self.module),ctypes.create_string_buffer(raw,len(raw))),'module load')
199 chk(hip.hipModuleGetFunction(ctypes.byref(self.fn),self.module,item['entry'].encode()),'entry')
200 def close(self):
201 if self.module.value: chk(hip.hipModuleUnload(self.module),'unload')
202 def mark(self): marker(self.name+'.hsaco sha256 '+self.sha)
203
204
205class Buffers:
206 def __init__(self,case,copies=1):
207 self.case=case; self.ptrs=[]; self.weights=[]; self.outputs=[]; self.params=[]; self.values=[]
208 try:
209 def alloc(buf):
210 p=put(buf); self.ptrs.append((p,buf)); return p
211 x=alloc(case['buffers'][1]); scales=alloc(case['buffers'][2])
212 for _ in range(copies):
213 w=alloc(case['buffers'][0]); y=alloc(case['buffers'][3])
214 self.weights.append(w); self.outputs.append(y)
215 vals=[w,x,scales,y,ctypes.c_uint32(case['m']),ctypes.c_uint32(case['k'])]
216 self.values.append(vals)
217 self.params.append((ctypes.c_void_p*6)(*[ctypes.cast(ctypes.byref(v),ctypes.c_void_p) for v in vals]))
218 except BaseException: self.close(); raise
219 def launch(self,module,index=0,overdispatch=False):
220 global CURRENT_CASE,CURRENT_BUFFERS,CURRENT_INDEX
221 CURRENT_CASE,CURRENT_BUFFERS,CURRENT_INDEX=self.case,self,index
222 chk(hip.hipModuleLaunchKernel(module.fn,max(1,self.case['m']+int(overdispatch)),1,1,64,1,1,0,None,self.params[index],None),'launch')
223 def check(self,expected,inputs=True):
224 chk(hip.hipDeviceSynchronize(),'sync')
225 for y in self.outputs: require_output(get(y,self.case['m']*4),expected,'Omega')
226 outputs={p.value for p in self.outputs}
227 for p,buf in self.ptrs:
228 if get(ctypes.c_void_p(p.value+len(buf)),SLACK)!=bytes(SLACK): raise AssertionError('nonzero allocation slack')
229 if inputs and p.value not in outputs and get(p,len(buf))!=buf: raise AssertionError('input buffer modified')
230 def close(self):
231 for p,_ in reversed(self.ptrs): chk(hip.hipFree(p),'free')
232 self.ptrs=[]
233
234
235def wall_ms(action,sync,copies):
236 calls=((max(MIN_CALLS,copies)+copies-1)//copies)*copies
237 for i in range(copies): action(i)
238 sync(); start=time.perf_counter()
239 for i in range(calls): action(i%copies)
240 sync(); elapsed=(time.perf_counter()-start)*1000/calls
241 if not elapsed>0: raise AssertionError('nonpositive timing interval')
242 return elapsed,calls
243
244
245def correctness(case, name):
246 expected=oracle(case)
247 module=Module(name); bufs=None
248 try:
249 bufs=Buffers(case); module.mark(); bufs.launch(module,overdispatch=True); bufs.check(expected)
250 finally:
251 if bufs: bufs.close()
252 module.close()
253 say('OMEGA CORRECTNESS M=%d K=%d all_rows=%d PASS finite_rows=%d NaN_rows=%d same_data_sha256=%s kernel=%s' % (case['m'],case['k'],case['m'],np.count_nonzero(np.isfinite(expected[0])),np.count_nonzero(np.isnan(expected[0])),case['digest'],name))
254
255
256def control(name):
257 case=fixture(257,389); expected=oracle(case)
258 baseline=Module('fp8gemv_b128f'); mutant=Module('fp8gemv_b128f-'+name); bufs=None
259 try:
260 bufs=Buffers(case); baseline.mark(); bufs.launch(baseline); bufs.check(expected)
261 mutant.mark(); bufs.launch(mutant); chk(hip.hipDeviceSynchronize(),'sync')
262 bad=mismatches(get(bufs.outputs[0],case['m']*4),expected)
263 for p,buf in bufs.ptrs:
264 if get(ctypes.c_void_p(p.value+len(buf)),SLACK)!=bytes(SLACK): raise AssertionError('mutant wrote slack')
265 if not bad: raise AssertionError(name+' ESCAPED')
266 say('CONTROL '+name+' CAUGHT numerical_mismatches='+str(bad))
267 return True
268 finally:
269 if bufs: bufs.close()
270 baseline.close(); mutant.close()
271
272
273def omega_timing(case, name):
274 weight_bytes=len(case['buffers'][0]); copies=COLD_BYTES//weight_bytes+1
275 assert copies*weight_bytes>CACHE_BYTES
276 expected=oracle(case); module=Module(name); bufs=None
277 try:
278 bufs=Buffers(case,copies); module.mark()
279 sync=lambda: chk(hip.hipDeviceSynchronize(),'sync')
280 warm,wn=wall_ms(lambda i:bufs.launch(module,0),sync,1)
281 cold,cn=wall_ms(lambda i:bufs.launch(module,i),sync,copies)
282 bufs.check(expected)
283 say('OMEGA TIMING kernel=%s M=%d K=%d warm_ms=%.6f cold_rotation_ms=%.6f warm_GB_per_s=%.3f cold_GB_per_s=%.3f weight_bytes=%d copies=%d rotation_bytes=%d warm_calls=%d cold_calls=%d all_rows=PASS same_data_sha256=%s%s' % (name,case['m'],case['k'],warm,cold,weight_bytes/warm/1e6,weight_bytes/cold/1e6,weight_bytes,copies,weight_bytes*copies,wn,cn,case['digest'],' SIMULATED_NOT_MEASURED' if SIMULATED else ''))
284 finally:
285 if bufs: bufs.close()
286 module.close()
287
288
289def reference(case):
290 import torch
291 if not torch.cuda.is_available() or not torch.version.hip: raise RuntimeError('ROCm torch unavailable: REFERENCE NOT_RUN')
292 say('REFERENCE backend torch=%s HIP=%s device=%s' % (torch.__version__,torch.version.hip,torch.cuda.get_device_name()))
293 marker('REFERENCE torch.matmul (AMD library, not Omega) same_data_sha256='+case['digest'])
294 m,k=case['m'],case['k']; copies=COLD_BYTES//(m*k*2)+1
295 assert copies*m*k*2>CACHE_BYTES
296 backing=[]
297 def padded(n):
298 whole=torch.zeros(n+SLACK//2,dtype=torch.bfloat16,device='cuda'); backing.append((whole,n)); return whole[:n]
299 # Dequantize exactly once before timing; all copies have identical BF16 weights.
300 host=np.empty((m,k),dtype=np.uint16); table=fp8_table()
301 scales=(case['scales'].astype(np.uint32)<<16).view(np.float32)
302 for row in range(0,m,128):
303 w=(table[case['w'][row:row+128]]*np.repeat(scales[row//128],128)[:k]).astype(np.float32)
304 bits=w.view(np.uint32); words=((bits+0x7fff+((bits>>16)&1))>>16).astype(np.uint16)
305 words[np.isnan(w)]=0x7fc0; host[row:row+128]=words
306 first=padded(m*k).reshape(m,k)
307 first.copy_(torch.from_numpy(host).view(torch.bfloat16))
308 matrices=[first]
309 for _ in range(copies-1):
310 copy=padded(m*k).reshape(m,k); copy.copy_(first); matrices.append(copy)
311 x=padded(k); x.copy_(torch.from_numpy(case['x']).to(torch.bfloat16))
312 ys=[padded(m) for _ in range(copies)]
313 warm,wn=wall_ms(lambda i:torch.matmul(matrices[0],x,out=ys[0]),torch.cuda.synchronize,1)
314 cold,cn=wall_ms(lambda i:torch.matmul(matrices[i],x,out=ys[i]),torch.cuda.synchronize,copies)
315 expected=oracle(case,bf16=True)
316 for y in ys: require_output(y.float().cpu().numpy().tobytes(),expected,'REFERENCE BF16')
317 for whole,n in backing:
318 if torch.count_nonzero(whole[n:]).item(): raise AssertionError('REFERENCE slack corruption')
319 weight_bytes=m*k*2
320 say('REFERENCE torch.matmul BF16 (AMD library, not Omega) M=%d K=%d warm_ms=%.6f cold_rotation_ms=%.6f warm_GB_per_s=%.3f cold_GB_per_s=%.3f weight_bytes=%d copies=%d rotation_bytes=%d warm_calls=%d cold_calls=%d all_rows=PASS same_data_sha256=%s%s' % (m,k,warm,cold,weight_bytes/warm/1e6,weight_bytes/cold/1e6,weight_bytes,copies,weight_bytes*copies,wn,cn,case['digest'],' SIMULATED_NOT_MEASURED' if SIMULATED else ''))
321
322# SELFCHECK_INSERT
323
324def child():
325 global np,hip
326 ok=False; controls={}; group=next(g for g in DATA['groups'] if g['id']==GROUP)
327 try:
328 import numpy as np
329 say('GROUP '+GROUP+' numpy='+np.__version__+(' SIMULATED_DEVICE' if SIMULATED else ''))
330 if group['kind']=='reference':
331 reference(fixture(*group['shape']))
332 else:
333 hip=setup_hip(); chk(hip.hipInit(0),'hipInit')
334 if group['kind']=='control': controls[GROUP[4:]]=control(GROUP[4:])
335 elif group['kind']=='correctness':
336 case=fixture(*group['shape'])
337 for name in DATA['timed_kernels']: correctness(case,name)
338 elif group['kind']=='tails':
339 for m,k in DATA['tails']:
340 case=fixture(m,k)
341 for name in DATA['timed_kernels']: correctness(case,name)
342 case=fixture(256,1,special=True)
343 for name in DATA['timed_kernels']: correctness(case,name)
344 elif group['kind']=='timing': omega_timing(fixture(*group['shape']),group['kernel'])
345 else: raise ValueError('unknown group kind')
346 ok=True
347 except BaseException:
348 if group['kind']=='reference':
349 say('REFERENCE (AMD library, not Omega) M=%d K=%d NOT_RUN_OR_FAILED' % tuple(group['shape']))
350 say('ERROR group '+GROUP+': '+' | '.join(traceback.format_exc().splitlines()[-4:]))
351 finally:
352 with open(STATEF,'a') as f: f.write(json.dumps(dict(group=GROUP,ok=ok,controls=controls))+'\n')
353
354if __name__=='__main__':
355 if GROUP: child()
356 else: parent()