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-kfd-launch / notebook.py.in

210 lines · 12339 bytes Raw Blame History
1# launch4: external Python measuring harness; the production launcher is seeded Omega.
2import base64, ctypes, hashlib, json, lzma, os, platform, selectors, struct, subprocess, tempfile, time
3from pathlib import Path
4BUNDLE = json.loads(r'''@BUNDLE@''')
5REPORT = Path('amdserve-launch4.txt')
6ROWS = []
7WORK = None
8ASSETS = {}
9BIN = None
10KFD_PROC_ROOT = Path('/sys/class/kfd/kfd/proc')
11SAMPLE_DELAYS = (0.0, 1.0, 3.0)
12REFERENCE = 'REFERENCE (AMD runtime loading our object, not the Omega launcher)'
13def say(line):
14 ROWS.append(str(line).replace('\n',' '))
15 temp=REPORT.with_suffix('.tmp'); temp.write_text('\n'.join(ROWS)+'\n'); temp.replace(REPORT)
16 print(ROWS[-1],flush=True)
17def asset(name):
18 a=BUNDLE['assets'][name]; data=lzma.decompress(base64.b85decode(a['xz_base85']))
19 if hashlib.sha256(data).hexdigest()!=a['sha256']: raise RuntimeError('asset digest '+name)
20 p=WORK/name; p.write_bytes(data)
21 if name=='omega-launch': p.chmod(0o700)
22 return p
23def topology_table():
24 root=Path('/sys/class/kfd/kfd/topology/nodes')
25 try: nodes=sorted(root.iterdir(),key=lambda p: int(p.name) if p.name.isdecimal() else -1)
26 except OSError as exc:
27 say('OMEGA topology table fail errno='+str(exc.errno)+' path='+str(root)); return
28 for node in nodes:
29 if not node.name.isdecimal(): continue
30 values={'node':node.name}
31 for name in ('gpu_id','properties'):
32 try:
33 data=(node/name).read_text()
34 if name=='gpu_id': values[name]=data.strip()
35 else:
36 props=dict(line.split(None,1) for line in data.splitlines() if len(line.split(None,1))==2)
37 values.update({k:props.get(k,'missing') for k in ('gfx_target_version','drm_render_minor','simd_count','device_id')})
38 except OSError as exc: values[name+'_errno']=exc.errno
39 say('OMEGA topology table '+json.dumps(values,sort_keys=True))
40def sample_kfd(pid,index):
41 root=KFD_PROC_ROOT/str(pid)
42 prefix='OMEGA proc sample='+str(index)+' pid='+str(pid)+' '
43 def contents(path):
44 try:
45 names=sorted(p.name for p in path.iterdir())
46 say(prefix+str(path)+' entries='+json.dumps(names)); return names
47 except OSError as exc:
48 say(prefix+str(path)+' missing/unreadable errno='+str(exc.errno)); return []
49 def value(path):
50 try:
51 data=path.read_text().strip(); say(prefix+str(path)+' value='+json.dumps(data)); return data
52 except OSError as exc:
53 say(prefix+str(path)+' missing/unreadable errno='+str(exc.errno)); return None
54 names=contents(root)
55 gpuids=set()
56 for queue in contents(root/'queues'):
57 for field in ('size','type','gpuid'):
58 data=value(root/'queues'/queue/field)
59 if field=='gpuid' and data and data.isdecimal(): gpuids.add(data)
60 for name in names:
61 for stem in ('stats_','vram_'):
62 if name.startswith(stem) and name[len(stem):].isdecimal(): gpuids.add(name[len(stem):])
63 if not gpuids: say(prefix+'stats_<gpuid>/cu_occupancy and vram_<gpuid> missing: no observed gpuid')
64 for gpu in sorted(gpuids):
65 value(root/('stats_'+gpu)/'cu_occupancy')
66 value(root/('vram_'+gpu))
67
68def invoke(arguments,label,expected=0,sample=False):
69 start=time.perf_counter_ns()
70 command=[str(BIN),*map(str,arguments)]
71 say('OMEGA invocation '+json.dumps({'label':label,'argv':command},sort_keys=True))
72 streams={'stdout':bytearray(),'stderr':bytearray()}
73 pending={'stdout':b'','stderr':b''}
74 waiting=None; sampled=0
75 with subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE) as child:
76 with selectors.DefaultSelector() as selector, (WORK/(label+'.stdout')).open('wb') as out, (WORK/(label+'.stderr')).open('wb') as err:
77 logs={'stdout':out,'stderr':err}
78 selector.register(child.stdout,selectors.EVENT_READ,'stdout')
79 selector.register(child.stderr,selectors.EVENT_READ,'stderr')
80 deadline=time.monotonic()+330
81 try:
82 while selector.get_map():
83 now=time.monotonic(); left=deadline-now
84 if left<=0: raise subprocess.TimeoutExpired(command,330)
85 if waiting is not None and sampled<len(SAMPLE_DELAYS):
86 due=waiting+SAMPLE_DELAYS[sampled]-now
87 if due<=0:
88 sample_kfd(child.pid,sampled); sampled+=1
89 continue
90 left=min(left,due)
91 for key,_ in selector.select(left):
92 data=os.read(key.fileobj.fileno(),65536); kind=key.data
93 if not data:
94 selector.unregister(key.fileobj)
95 if pending[kind]:
96 say(pending[kind].decode(errors='replace') if kind=='stdout' else 'OMEGA stderr '+pending[kind].decode(errors='replace'))
97 pending[kind]=b''
98 continue
99 streams[kind].extend(data); logs[kind].write(data); logs[kind].flush()
100 pending[kind]+=data
101 while b'\n' in pending[kind]:
102 line,pending[kind]=pending[kind].split(b'\n',1)
103 say(line.decode(errors='replace') if kind=='stdout' else 'OMEGA stderr '+line.decode(errors='replace'))
104 if sample and kind=='stdout' and line.startswith(b'OMEGA step signal_wait ') and b'phase=before' in line:
105 waiting=time.monotonic()
106 code=child.wait(timeout=max(0.001,deadline-time.monotonic()))
107 except BaseException:
108 child.kill(); child.wait()
109 for kind,data in pending.items():
110 if data: say(data.decode(errors='replace') if kind=='stdout' else 'OMEGA stderr '+data.decode(errors='replace'))
111 raise
112 elapsed=time.perf_counter_ns()-start
113 p=subprocess.CompletedProcess(command,code,bytes(streams['stdout']),bytes(streams['stderr']))
114 say('OMEGA invocation '+label+' exit='+str(code)+' expected='+str(expected))
115 if sample: say('OMEGA proc samples='+str(sampled)+'; missing samples mean child exited before scheduled read or wait was not reached')
116 if expected is not None and p.returncode!=expected: raise RuntimeError(label+' exit='+str(p.returncode)+' expected='+str(expected))
117 return p,elapsed
118
119class Hip:
120 def __init__(self):
121 # Import the installed torch only to load its AMD runtime; no torch kernels.
122 import torch
123 say(REFERENCE+' torch_version='+str(torch.__version__)+' hip_build='+str(torch.version.hip))
124 paths=set()
125 for line in Path('/proc/self/maps').read_text().splitlines():
126 fields=line.split(None,5)
127 if len(fields)==6 and Path(fields[5]).name.startswith('libamdhip64.so'): paths.add(fields[5])
128 if len(paths)!=1: raise RuntimeError('expected one torch-loaded libamdhip64, observed '+repr(sorted(paths)))
129 self.name=paths.pop(); self.lib=ctypes.CDLL(self.name)
130 P=ctypes.c_void_p; U=ctypes.c_uint; Z=ctypes.c_size_t; I=ctypes.c_int
131 signatures={'hipInit':[U],'hipRuntimeGetVersion':[ctypes.POINTER(I)],'hipMalloc':[ctypes.POINTER(P),Z], 'hipFree':[P], 'hipMemcpy':[P,P,Z,I], 'hipModuleLoadData':[ctypes.POINTER(P),P], 'hipModuleGetFunction':[ctypes.POINTER(P),P,ctypes.c_char_p], 'hipModuleUnload':[P], 'hipModuleLaunchKernel':[P,U,U,U,U,U,U,U,P,ctypes.POINTER(P),ctypes.POINTER(P)], 'hipDeviceSynchronize':[]}
132 for name,types in signatures.items():
133 fn=getattr(self.lib,name); fn.argtypes=types; fn.restype=I
134 self.call('hipInit',0); version=I(); self.call('hipRuntimeGetVersion',ctypes.byref(version))
135 say(REFERENCE+' library='+self.name+' runtime_version='+str(version.value))
136 def call(self,name,*args):
137 rc=getattr(self.lib,name)(*args)
138 say(REFERENCE+' '+name+' rc='+str(rc))
139 if rc: raise RuntimeError(REFERENCE+' '+name+' rc='+str(rc))
140 def vadd(self):
141 P=ctypes.c_void_p; ptrs=[]; mod=P()
142 try:
143 # Identical 256 binary32 ones and NaN output fill to the Omega vadd.
144 for data in [struct.pack('<f',1.0)*256]*2+[struct.pack('<I',0x7fc00000)*256]:
145 ptr=P(); self.call('hipMalloc',ctypes.byref(ptr),len(data)); ptrs.append(ptr)
146 host=ctypes.create_string_buffer(data); self.call('hipMemcpy',ptr,host,len(data),1)
147 image=ctypes.create_string_buffer(ASSETS['vadd.hsaco'].read_bytes())
148 self.call('hipModuleLoadData',ctypes.byref(mod),image)
149 fn=P(); self.call('hipModuleGetFunction',ctypes.byref(fn),mod,b'vadd')
150 values=ptrs+[ctypes.c_uint32(256)]
151 params=(P*len(values))(*(ctypes.addressof(v) for v in values))
152 self.call('hipModuleLaunchKernel',fn,4,1,1,64,1,1,0,None,params,None)
153 self.call('hipDeviceSynchronize')
154 result=ctypes.create_string_buffer(1024); self.call('hipMemcpy',result,ptrs[-1],1024,2)
155 say(REFERENCE+' first8_words='+json.dumps(struct.unpack('<8I',result.raw[:32])))
156 if result.raw!=struct.pack('<f',2.0)*256: raise RuntimeError(REFERENCE+' output bits differ')
157 say(REFERENCE+' vadd bitwise=PASS count=256 same_object_sha256='+BUNDLE['assets']['vadd.hsaco']['sha256'])
158 finally:
159 if mod.value: self.call('hipModuleUnload',mod)
160 for ptr in ptrs: self.call('hipFree',ptr)
161
162def main():
163 if platform.machine()!='x86_64':
164 say('OMEGA NOT_RUN target requires x86_64 Linux; AMD device rows NOT_RUN'); return 'NOT_RUN'
165 bad=WORK/'bad.hsaco'; bad.write_bytes(b'bad ELF')
166 invoke(['inspect',bad,'vadd'],'control-bad-elf',65)
167 args=WORK/'bad.args'; args.write_bytes(bytes(48))
168 invoke(['run',ASSETS['vadd.hsaco'],'vadd',4,1,args,WORK/'unused'],'control-bad-args',64)
169 say('OMEGA CONTROL malformed ELF=65 argument-header=64 PASS')
170 if not Path('/dev/kfd').exists():
171 invoke(['vadd',ASSETS['vadd.hsaco'],'vadd'],'absent-kfd',77)
172 say('OMEGA NOT_RUN /dev/kfd absent; errno=2 exit=77 checked'); return 'NOT_RUN'
173 p,_=invoke(['vadd',ASSETS['vadd.hsaco'],'vadd'],'vadd',expected=None,sample=True)
174 omega_ok=p.returncode==0 and b'OMEGA vadd=PASS count=256\n' in p.stdout
175 say('OMEGA vadd '+('bitwise=PASS' if omega_ok else 'FAIL_OR_INCOMPLETE')+' exit='+str(p.returncode)+' timeout='+str(p.returncode==75))
176 # Run this independent comparison even when the direct launcher timed out.
177 hip_ok=False
178 try:
179 Hip().vadd(); hip_ok=True
180 except Exception as exc:
181 say(REFERENCE+' FAIL_OR_NOT_RUN '+type(exc).__name__+' '+str(exc))
182 say('NOT_RUN full 27B serving, Spark comparison and all other kernels; no dispatch variants attempted')
183 return 'PASS vadd only' if omega_ok and hip_ok else 'FAIL_OR_INCOMPLETE vadd diagnostics retained'
184
185def run():
186 global WORK,ASSETS,BIN
187 ROWS.clear()
188 say('CONTROLS first: asset digests, malformed ELF, argument header; no changed doorbell values or dispatch variants')
189 result='FAIL'
190 try:
191 WORK=Path(tempfile.mkdtemp(prefix='omega-launch4-'))
192 try: ASSETS={name:asset(name) for name in BUNDLE['assets']}
193 except Exception as exc:
194 say('FAIL asset unpack: '+str(exc)); raise
195 BIN=ASSETS['omega-launch']
196 say('launch4 candidate; queue tail IS_PTR64=1; OMEGA=seeded direct KFD; '+REFERENCE+'=independent comparison')
197 say('pins '+json.dumps(BUNDLE['sources'],sort_keys=True))
198 say('assets '+json.dumps({k:v['sha256'] for k,v in BUNDLE['assets'].items()},sort_keys=True))
199 say('host arch='+platform.machine()+' kernel='+platform.release()+' libc='+str(platform.libc_ver())+' work='+str(WORK))
200 topology_table()
201 result=main()
202 except BaseException as exc:
203 say('FAIL '+type(exc).__name__+' '+str(exc)+'; full stdout/stderr files in '+str(WORK))
204 raise
205 finally:
206 say('receipt '+str(REPORT.resolve())+'; inputs, outputs and invocation logs retained in '+str(WORK))
207 say('RESULT '+result)
208
209if __name__!='__notebook_test__':
210 run()