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 / check.py

562 lines · 36605 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3# Independent CPU measuring/oracle harness, never a production launcher component.
4import hashlib
5import json
6import os
7import re
8import statistics
9import math
10from pathlib import Path
11import shutil
12import struct
13import subprocess
14import sys
15import tempfile
16
17root=Path(__file__).resolve().parents[2]
18src=root/'backend/amd/kfd/launch'
19if len(sys.argv)!=2 or not Path(sys.argv[1]).is_absolute():
20 raise SystemExit(64)
21omc=Path(sys.argv[1])
22pin=(src/'COMPILER').read_text().splitlines()[1].split()[0]
23if not omc.is_file() or hashlib.sha256(omc.read_bytes()).hexdigest()!=pin:
24 print('REFUSED compiler digest',file=sys.stderr)
25 raise SystemExit(69)
26out=Path(os.environ.get('AMD_KFD_LAUNCH_OUT',root/'build/amd-kfd-launch/gate')).resolve()
27out.mkdir(parents=True,exist_ok=True)
28results=[]
29def run(label,args,want=0,data=None):
30 original=label
31 n=1
32 while any(r['case']==label for r in results):
33 n+=1;label=original+' #'+str(n)
34 p=subprocess.run(list(map(str,args)),input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=120)
35 row={'kind':'baseline','command':list(map(str,args)),'case':label,'exit':p.returncode,'expected':want,'stderr':p.stderr.decode(errors='replace')}
36 if not label.startswith(('compile ', 'build ')):
37 row['stdout']=p.stdout.decode(errors='replace')
38 results.append(row)
39 print(('PASS' if p.returncode==want else 'FAIL'),label,'exit',p.returncode,'expected',want,flush=True)
40 (out/'results.json').write_text(json.dumps({'success_exits':[0,77],'cases':results},indent=2)+'\n')
41 if p.returncode!=want:
42 print(p.stdout.decode(errors='replace')); print(row['stderr']); raise SystemExit(1)
43 return p
44def pair(refusal,twin):
45 rows={r['case']:r for r in results}
46 r,t=rows[refusal],rows[twin]
47 assert t['exit']==t['expected'] and t['expected'] in (0,77)
48 assert t.get('value_asserted'),('unverified twin',twin)
49 # Both executions use the same command builder. Only one input token may
50 # differ (an object, program, caller argument, or injected syscall fault).
51 def tokens(command):
52 return [x for x in command if x!='env']
53 a,b=tokens(r['command']),tokens(t['command'])
54 if len(a)==len(b):assert sum(x!=y for x,y in zip(a,b))==1,(refusal,a,b)
55 else:
56 assert abs(len(a)-len(b))==1,(refusal,a,b)
57 long,short=(a,b) if len(a)>len(b) else (b,a)
58 assert any(long[:i]+long[i+1:]==short for i in range(len(long))),(refusal,a,b)
59 common=[x if x==y else '<refused-input>' for x,y in zip(a,b)] if len(a)==len(b) else short
60 setup=hashlib.sha256(json.dumps(common).encode()).hexdigest()
61 r.update(kind='refusal',twin=twin,setup_sha256=setup)
62 t['setup_sha256']=setup
63 t['kind']='twin'
64def refuse(label,args,want,twinargs,verify):
65 twin='positive twin '+label
66 p=run(twin,twinargs,77 if label.endswith('argument header') else 0)
67 twinrow=results[-1]
68 verify(p)
69 twinrow['value_asserted']=True
70 p=run(label,args,want)
71 pair(label,twin)
72 return p
73def vadd_value(p):
74 assert b'OMEGA vadd=PASS count=256' in p.stdout and b'child_exit=0 ' in p.stderr,(p.stdout,p.stderr)
75def empty_value(p):
76 # Composed units return zero only after asserting their mapped read value.
77 assert p.stdout==b''
78def preflight_value(p):
79 assert b'OMEGA step open_kfd' in p.stdout
80def two_alarm_value(p):
81 vadd_value(p)
82 assert p.stdout.count(b'OMEGA alarm slow_dispatch_ns=')==2
83def fast_value(p):
84 diagnostics(p,1,0,0x40000000,0)
85 assert b'OMEGA alarm slow_dispatch_ns=' not in p.stdout
86def inspected_value(p):
87 assert ('kernarg_bytes='+str(ka)).encode() in p.stdout
88def validate_inventory(rows):
89 names={r['case']:r for r in rows};assert len(names)==len(rows)
90 for r in rows:
91 assert r['kind'] in ('baseline','twin','refusal')
92 if r['expected'] not in (0,77) or r['case'].startswith('CONTROL '):assert r['kind']=='refusal',r['case']
93 if r['kind']=='refusal':
94 t=names[r['twin']]
95 assert t['kind']=='twin' and t['exit']==t['expected'] and t['expected'] in (0,77)
96 assert t.get('value_asserted')
97 # Recheck the builder relation, rather than trusting a written label.
98 assert r['setup_sha256']==t['setup_sha256']
99 pair(r['case'],t['case'])
100 return True
101
102reference=root/'tests/amd-kfd-launch/reference'
103references=json.loads((reference/'sources.json').read_text())['sources']
104assert len({r['file'] for r in references})==len(references)
105for row in references:
106 path=reference/row['file']
107 assert path.parent==reference and path.suffix in ('.c','.h')
108 assert hashlib.sha256(path.read_bytes()).hexdigest()==row['sha256'],row['file']
109 lines=path.read_text().splitlines()
110 for span in row['ranges']:
111 assert set(span)=={'first','last','contains'}
112 starts=[i for i,line in enumerate(lines) if line.strip()==span['first']]
113 assert len(starts)==1,(row['file'],span['first'])
114 ends=[i for i in range(starts[0],len(lines)) if lines[i].strip()==span['last']]
115 assert ends,(row['file'],span['last'])
116 span['derived_start']=starts[0]+1;span['derived_end']=ends[0]+1
117 quoted='\n'.join(lines[starts[0]:ends[0]+1])
118 assert all(token in quoted for token in span['contains']),(row['file'],span)
119checksums=''.join(r['sha256']+' '+r['file']+'\n' for r in sorted(references,key=lambda r:r['file']))
120assert (reference/'SHA256SUMS').read_text()==checksums
121source_table='| Local file | Upstream URL | Relevant lines |\n| --- | --- | --- |\n'+''.join('| '+r['file']+' | '+r['url']+' | '+', '.join(str(s['derived_start'])+('-'+str(s['derived_end']) if s['derived_end']!=s['derived_start'] else '') for s in r['ranges'])+' |\n' for r in references)
122readme=(reference/'README.md').read_text()
123assert readme.count('<!-- generated from sources.json -->\n')==readme.count('<!-- end generated source table -->')==1
124assert readme.split('<!-- generated from sources.json -->\n')[1].split('<!-- end generated source table -->')[0]==source_table
125print('PRIMARY SOURCE PASS producer mapping, pins and derived reference views',flush=True)
126parts=['common','elf','device','dispatch','plan','main']
127body=''.join((src/(x+'.om')).read_text() for x in parts)+(root/'backend/amd/kfd/cli.om').read_text()
128def compile(label,text,target='a64'):
129 text=('target x86linux\n' if target=='x86' else '')+'om2\n'+text
130 (out/(label+'.om')).write_text(text)
131 p=run('compile '+label,[omc],data=text.encode())
132 binary=out/label; binary.write_bytes(p.stdout); binary.chmod(0o700); return binary
133qemu=shutil.which('qemu-x86_64')
134bins={t:compile('launch-'+t,body,t) for t in ('a64','x86')}
135wrong=out/'wrong-compiler'; marker=out/'WRONG-EXECUTED'
136wrong.write_text('#!/bin/sh\ntouch '+str(marker)+'\n'); wrong.chmod(0o700)
137wrongout=out/'wrong-output'; env=dict(os.environ,AMD_KFD_LAUNCH_OUT=str(wrongout))
138p=subprocess.run([sys.executable,'-I',__file__,str(wrong)],env=env,capture_output=True)
139assert p.returncode==69 and not marker.exists() and not wrongout.exists()
140print('CONTROL wrong compiler refused before execution/output',flush=True)
141# Build the repository-owned object writer, not an LLVM-generated replacement.
142hs=run('compile object writer',[omc],data=(root/'backend/amd/gfx942/hsaco.om').read_bytes())
143writer=out/'hsaco'; writer.write_bytes(hs.stdout); writer.chmod(0o700)
144objects={}
145def elfmeta(data):
146 phoff=struct.unpack_from('<Q',data,32)[0]; phnum=struct.unpack_from('<H',data,56)[0]
147 shoff=struct.unpack_from('<Q',data,40)[0]; shnum=struct.unpack_from('<H',data,60)[0]
148 sections=[struct.unpack_from('<IIQQQQIIQQ',data,shoff+64*i) for i in range(shnum)]
149 for sec in sections:
150 if sec[1] not in (2,11): continue
151 strings=sections[sec[6]]; table=data[strings[4]:strings[4]+strings[5]]
152 for p in range(sec[4],sec[4]+sec[5],24):
153 name,info,other,shndx,value,size=struct.unpack_from('<IBBHQQ',data,p)
154 n=table[name:table.index(0,name)].decode()
155 if n.endswith('.kd'):
156 for i in range(phnum):
157 typ,flags,off,va,pa,filesz,memsz,align=struct.unpack_from('<IIQQQQQQ',data,phoff+56*i)
158 if typ==1 and va<=value and value+64<=va+filesz:
159 kd=off+value-va
160 return n[:-3],kd,struct.unpack_from('<I',data,kd+8)[0]
161 raise AssertionError('descriptor missing')
162for table in sorted((root/'backend/amd/gfx942').glob('*.isa')):
163 data=run('build '+table.stem,[writer,table]).stdout
164 obj=out/(table.stem+'.hsaco'); obj.write_bytes(data)
165 name,kd,argbytes=elfmeta(data); objects[name]=(obj,data,kd,argbytes)
166 for target,binary in bins.items():
167 if target=='x86' and not qemu: continue
168 argv=([qemu] if target=='x86' else [])+[binary,'inspect',obj,name]
169 p=run(target+' inspect '+name,argv)
170 assert ('kernarg_bytes='+str(argbytes)).encode() in p.stdout
171# A card model run is releasable only when every exercised object rebuilds here.
172required=json.loads((root/'tests/amd-kfd-launch/qwen38-objects.json').read_text())['objects']
173def require_model_objects(actual):
174 missing=sorted(set(required)-set(actual))
175 assert not missing,('model kernels absent from release source',missing)
176 for name,row in required.items():
177 assert hashlib.sha256(actual[name][1]).hexdigest()==row['sha256'],('model object differs from card fixture',name)
178 assert actual[name][3]==row['kernarg'],('model kernarg differs from card fixture',name)
179require_model_objects(objects)
180first=next(iter(required))
181for kind in ('missing','changed'):
182 altered=objects.copy()
183 if kind=='missing':del altered[first]
184 else:
185 v=list(altered[first]);v[1]=bytes([v[1][0]^1])+v[1][1:];altered[first]=tuple(v)
186 try:require_model_objects(altered)
187 except AssertionError:pass
188 else:raise AssertionError(('model source control escaped',kind))
189(out/'model-object-source-check.json').write_text(json.dumps({'required':required,'all_rebuilt':True,'controls_caught':['missing','changed']},indent=2)+'\n')
190print('MODEL SOURCE PASS all required objects rebuilt; missing/changed controls caught',flush=True)
191vobj,vdata,kd,ka=objects['vadd']
192# Record numeric constant and unit-conversion oracle queries/results, not guesses.
193calcs={'ELF_magic':int.from_bytes(b'\x7fELF','little'),'ELF_class_data_version_osabi':int.from_bytes(bytes([2,1,1,64]),'little'),'ELF_type_machine':int.from_bytes(struct.pack('<HH',3,224),'little'),'manifest_magic':int.from_bytes(b'OMKFD001','little'),'f32_one':struct.pack('<f',1.0).hex(),'f32_one_plus_one':struct.pack('<f',1.0+1.0).hex()}
194(out/'calculation-oracles.json').write_text(json.dumps(calcs,indent=2)+'\n')
195mutations={ 'oversized':vdata[:63], 'wrong-machine':vdata[:18]+b'\0\0'+vdata[20:], 'wave32':vdata[:kd+56]+struct.pack('<H',struct.unpack_from('<H',vdata,kd+56)[0]|1024)+vdata[kd+58:], 'negative-entry':vdata[:kd+16]+struct.pack('<q',-1)+vdata[kd+24:] }
196mutations['private-segment-unsupported']=vdata[:kd+4]+struct.pack('<I',20)+vdata[kd+8:]
197mutations['queue-pointer-required']=vdata[:kd+56]+struct.pack('<H',struct.unpack_from('<H',vdata,kd+56)[0]|4)+vdata[kd+58:]
198# The pinned producer owns field positions. Derive both fixtures and the
199# expected production guard from it, so a coherent pin edit cannot leave our
200# copied mask and mutations agreeing with one another but not the producer.
201descriptor=(reference/'AMDHSAKernelDescriptor-rocm-7.2.2.h').read_text()
202def descriptor_number(name):
203 values=re.findall(r'\b'+re.escape(name)+r'\s*=\s*(\d+)\s*,',descriptor)
204 assert len(values)==1,(name,values)
205 return int(values[0])
206def descriptor_bit(macro,name):
207 values=re.findall(r'\b'+re.escape(macro)+r'\('+re.escape(name)+r',\s*(\d+),\s*(\d+)\)',descriptor)
208 assert len(values)==1 and int(values[0][1])==1,(macro,name,values)
209 return 1<<int(values[0][0])
210rsrc2_offset=descriptor_number('COMPUTE_PGM_RSRC2_OFFSET')
211properties_offset=descriptor_number('KERNEL_CODE_PROPERTIES_OFFSET')
212assert re.search(r'uint32_t\s+compute_pgm_rsrc2\s*;',descriptor)
213assert re.search(r'uint16_t\s+kernel_code_properties\s*;',descriptor)
214private_bit=descriptor_bit('COMPUTE_PGM_RSRC2','ENABLE_PRIVATE_SEGMENT')
215scratch_fields=[('private-buffer','ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER'),
216 ('flat-scratch-init','ENABLE_SGPR_FLAT_SCRATCH_INIT'),
217 ('private-size','ENABLE_SGPR_PRIVATE_SEGMENT_SIZE'),
218 ('dynamic-stack','USES_DYNAMIC_STACK')]
219scratch_requests=[('scratch-enable',rsrc2_offset,'I',private_bit)]
220scratch_mask=0
221for label,field in scratch_fields:
222 bit=descriptor_bit('KERNEL_CODE_PROPERTY',field)
223 scratch_mask|=bit
224 scratch_requests.append((label,properties_offset,'H',bit))
225expected_guard=f'if or ne and ew add d {rsrc2_offset} 4 {private_bit} 0 ne and ew add d {properties_offset} 2 {scratch_mask} 0\n'
226assert (src/'elf.om').read_text().count(expected_guard)==1,'scratch guard differs from pinned producer'
227for name,off,fmt,bit in scratch_requests:
228 data=bytearray(vdata)
229 struct.pack_into('<'+fmt,data,kd+off,struct.unpack_from('<'+fmt,data,kd+off)[0]|bit)
230 mutations[name]=bytes(data)
231reasons={'oversized':5,'wrong-machine':17,'wave32':25,'negative-entry':28,'private-segment-unsupported':24,'queue-pointer-required':27,'scratch-enable':26,'private-buffer':26,'flat-scratch-init':26,'private-size':26,'dynamic-stack':26}
232for label,data in mutations.items():
233 pth=out/(label+'.hsaco'); pth.write_bytes(data)
234 for target,binary in bins.items():
235 if target=='x86' and not qemu: continue
236 p=refuse(target+' refuse '+label,([qemu] if target=='x86' else [])+[binary,'inspect',pth,'vadd'],65,([qemu] if target=='x86' else [])+[binary,'inspect',vobj,'vadd'],inspected_value)
237 assert p.stdout==b'' and p.stderr==('OMEGA refuse object field='+str(reasons[label])+'\n').encode(),(label,p.stdout,p.stderr)
238for target,binary in bins.items():
239 if target=='x86' and not qemu: continue
240 pre=([qemu] if target=='x86' else [])
241 p=refuse(target+' missing descriptor',pre+[binary,'inspect',vobj,'not_a_kernel'],65,pre+[binary,'inspect',vobj,'vadd'],inspected_value)
242 assert p.stdout==b'' and p.stderr==b'OMEGA refuse object field=23\n'
243 if not Path('/dev/kfd').exists():
244 p=run(target+' absent KFD',pre+[binary,'vadd',vobj,'vadd'],77)
245 assert b'OMEGA device=absent errno=2\n' in p.stdout
246 assert b'OMEGA step open_kfd fail errno=2 phase=after detail=0\n' in p.stdout
247 goodargs=out/'good-args'; goodargs.write_bytes(b'OMKFD001'+struct.pack('<5Q',28,1024,1,0,0)+bytes(28))
248 badargs=out/'bad-args'; badargs.write_bytes(b'BADMAGIC'+goodargs.read_bytes()[8:])
249 p=refuse(target+' refuse argument header',pre+[binary,'run',vobj,'vadd',4,1,badargs,out/'unused'],64,pre+[binary,'run',vobj,'vadd',4,1,goodargs,out/'unused'],preflight_value)
250 assert p.stdout==b'' and p.stderr==b'OMEGA refuse manifest field=magic\n'
251# Full native host orchestration with a syscall instrument: no GPU opens reach Linux.
252run('compile UAPI layout oracle',['cc','-Wall','-Wextra','-Werror',root/'tests/amd-kfd/layout-oracle.c','-o',out/'layout'])
253layout=run('UAPI layout',[out/'layout']).stdout
254assert layout==(root/'backend/amd/kfd/requests.tsv').read_bytes()
255for name in ('trace','publication'):
256 run('compile '+name+' instrument',['cc','-Wall','-Wextra','-Werror',root/'tests/amd-kfd-launch'/ (name+'.c'),'-o',out/name])
257def diagnostics(p,read,signal,output,timeout=10_000_000_000):
258 rows={}
259 for line in p.stdout.decode().splitlines():
260 if line.startswith('OMEGA diag '):
261 name,value=line.removeprefix('OMEGA diag ').split()
262 rows[name]=int(value)
263 expected={'queue_read_pointer':read,'queue_write_pointer':1,'signal_kind':1,'signal_value':signal,
264 'queue_properties':2,'read_pointer_base_offset':128,'ring_header':0x21502,'ring_slot_byte_offset':0,'queue_id':7,'doorbell_offset':8,
265 'wait_timeout_ns':timeout,'output_first8_nan_fill_count':8 if output==0x7fc00000 else 0,
266 'output_first8_expected_vadd_sum_count':8 if output==0x40000000 else 0}
267 for name,off,fmt in [('kernel_code_entry_byte_offset',16,'Q'),('compute_pgm_rsrc1',48,'I'),
268 ('compute_pgm_rsrc2',52,'I'),('compute_pgm_rsrc3',44,'I'),('kernel_code_properties',56,'H'),
269 ('group_segment_size',0,'I'),('private_segment_size',4,'I'),('kernarg_size',8,'I')]:
270 expected[name]=struct.unpack_from('<'+fmt,vdata,kd+off)[0]
271 expected.update({f'output_word_{i}':output for i in range(8)})
272 for line in p.stderr.decode().splitlines():
273 if line.startswith('TEST_SIM queue_input_qword_'):
274 name,value=line.removeprefix('TEST_SIM ').split('=')
275 expected['create_'+name]=int(value)
276 if line.startswith('TEST_SIM packet_'):
277 name,value=line.removeprefix('TEST_SIM ').split('=')
278 expected[name]=int(value)
279 assert len([x for x in expected if x.startswith('create_')])==11
280 assert all(rows.get(k)==v for k,v in expected.items()), (rows,expected)
281 assert rows['packet_kernel_object'] and rows['packet_kernarg_address']
282with tempfile.TemporaryDirectory(prefix='kfd-',dir='/tmp') as tmp:
283 node=Path(tmp)/'2'; node.mkdir()
284 (node/'gpu_id').write_text('1\n')
285 (node/'properties').write_text('gfx_target_version 90402\ndrm_render_minor 128\nsimd_count 32\nsimd_per_cu 4\nmax_waves_per_simd 8\narray_count 8\nsimd_arrays_per_engine 2\nnum_xcc 2\n')
286 command=[out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd','10000000000']
287 lds=bytearray(vdata);struct.pack_into('<I',lds,kd,4096)
288 ldsobj=out/'vadd-lds.hsaco';ldsobj.write_bytes(lds)
289 p=run('accepted ELF with nonzero LDS uses HSA packet group field',[out/'trace',tmp,bins['a64'],'vadd',ldsobj,'vadd','10000000000'])
290 p=run('generic default alarms without refusing a slow completion',['env','KFD_TEST_EXPIRE=1',out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd'])
291 assert p.stdout.count(b'OMEGA alarm slow_dispatch_ns=')==1
292 twice=body.replace('dispatch\nstepbegin streadback','dispatch\nr = checked mapset lh 7 8 8 1\ndispatch\nstepbegin streadback')
293 twice=twice.replace('for i ulong get launch 2 bound 9223372036854775807\nwhile', 'for j ulong get launch 2 bound 9223372036854775807\ni = add j mapget lh 5 56 8\nwhile')
294 assert twice!=body
295 u=compile('generic-two-dispatches',twice)
296 p=run('generic slow alarm re-arms for second dispatch',['env','KFD_TEST_EXPIRE=1',out/'trace',tmp,u,'vadd',vobj,'vadd'])
297 assert p.stdout.count(b'OMEGA alarm slow_dispatch_ns=')==2,p.stdout
298 mutant=twice.replace('put dispatchalarm 0 0\n','')
299 assert mutant!=twice
300 u=compile('generic-no-alarm-rearm',mutant)
301 p=refuse('CONTROL generic missing re-arm detected',['env','KFD_TEST_EXPIRE=1',out/'trace',tmp,u,'vadd',vobj,'vadd'],0,['env','KFD_TEST_EXPIRE=1',out/'trace',tmp,out/'generic-two-dispatches','vadd',vobj,'vadd'],two_alarm_value)
302 assert p.stdout.count(b'OMEGA alarm slow_dispatch_ns=')==1
303 mutant=body.replace('gt elapsed 10000000000','gt elapsed 0')
304 assert mutant!=body
305 u=compile('alarm-threshold-zero',mutant)
306 p=refuse('CONTROL fast dispatch false alarm detected',[out/'trace',tmp,u,'vadd',vobj,'vadd'],0,[out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd'],fast_value)
307 assert b'OMEGA alarm slow_dispatch_ns=' in p.stdout
308 p=run('native simulated orchestration',command)
309 assert b'OMEGA alarm slow_dispatch' not in p.stdout
310 diagnostics(p,1,0,0x40000000)
311 for name,variables,read,signal,output,child_exit in [
312 ('unconsumed timeout',['KFD_TEST_NO_COMPLETE=1','KFD_TEST_EXPIRE=1'],0,1,0x7fc00000,75),
313 ('output without completion timeout',['KFD_TEST_NO_SIGNAL=1','KFD_TEST_EXPIRE=1'],1,1,0x40000000,75),
314 ('completion without output',['KFD_TEST_NO_OUTPUT=1'],1,0,0x7fc00000,76)]:
315 deadline=20_000_000_000 if child_exit==75 else 10_000_000_000
316 cmd=[*command[:-1],str(deadline)]
317 twinenv=['env','KFD_TEST_EXPIRE=1'] if child_exit==75 else []
318 p=refuse('CONTROL diagnostics '+name,['env',*variables,*cmd],1,[*twinenv,*cmd],lambda p: diagnostics(p,1,0,0x40000000,deadline))
319 assert ('child_exit='+str(child_exit)+' ').encode() in p.stderr
320 diagnostics(p,read,signal,output,deadline)
321 if child_exit==75:
322 assert b'OMEGA step signal_wait fail errno=110' in p.stdout
323 mutant=body.replace('r = checked mapset lh 5 180 4 2\n','r = checked mapset lh 5 180 4 0\n')
324 assert mutant!=body
325 bad=compile('queue-ptr32',mutant)
326 p=refuse('CONTROL wrong queue pointer width',[out/'trace',tmp,bad,'vadd',vobj,'vadd'],1,[out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd'],vadd_value)
327 assert b'queue_image' in p.stderr
328 mutant=body.replace('r = checked mapset lh 5 180 4 2\n',
329 'r = checked mapset lh 5 180 4 2\nr = checked mapset lh 5 2040 8 1\n')
330 assert mutant!=body
331 bad=compile('queue-tail-dirty',mutant)
332 p=refuse('CONTROL nonzero unused queue tail',[out/'trace',tmp,bad,'vadd',vobj,'vadd'],1,[out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd'],vadd_value)
333 assert b'queue_image' in p.stderr
334 mutant=body.replace('r = allocate 3 mul get launch 10 64 0xe6000002', 'r = allocate 3 mul get launch 10 64 0xa6000002')
335 assert mutant!=body
336 bad=compile('ring-not-executable',mutant)
337 p=refuse('CONTROL ring lacks execute permission',[out/'trace',tmp,bad,'vadd',vobj,'vadd'],1,[out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd'],vadd_value)
338 assert b'KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE' in p.stderr
339 for mode in ('missing','duplicate','oversized','invalid','empty','large-duplicate'):
340 p=refuse('CONTROL aperture '+mode,['env','KFD_TEST_APERTURE='+mode,*command],1,['env','KFD_TEST_APERTURE='+('large' if mode=='large-duplicate' else 'normal'),*command],lambda p: (diagnostics(p,1,0,0x40000000),vadd_value(p)))
341 assert b'child_exit=66 ' in p.stderr and b'queued=0' in p.stderr
342 for mode in ('large','grow'):
343 run('aperture inventory '+mode,['env','KFD_TEST_APERTURE='+mode,*command])
344 # The generic CLI reuses the ring across its boundary, not only one packet.
345 ins=[]
346 for name in ('a','b'):
347 path=out/('repeat-'+name); path.write_bytes(struct.pack('<f',1.0)*256); ins.append(path)
348 raw=bytes(24)+struct.pack('<I',256)
349 pairs=b''.join(struct.pack('<QQ',i*8,i) for i in range(3))
350 args=out/'repeat.args'
351 args.write_bytes(b'OMKFD001'+struct.pack('<QQQQQ',28,1024,200,10_000_000_000,3)+pairs+raw)
352 result=out/'repeat.out'
353 invocation=[out/'trace',tmp,bins['a64'],'run',vobj,'vadd',4,1,args,*ins,result]
354 repeated=run('native generic CLI ring wrap',invocation)
355 assert b'packets=200\n' in repeated.stdout and result.read_bytes()==struct.pack('<f',2.0)*256
356 args.write_bytes(b'OMKFD001'+struct.pack('<QQQQQ',28,1024,1,20_000_000_000,3)+pairs+raw)
357 result.unlink(missing_ok=True)
358 def repeated_value(p):
359 assert b'packets=1\n' in p.stdout and result.read_bytes()==struct.pack('<f',2.0)*256
360 result.unlink()
361 stopped=refuse('CONTROL missing device completion',['env','KFD_TEST_EXPIRE=1','KFD_TEST_NO_COMPLETE=1',*invocation],1,['env','KFD_TEST_EXPIRE=1',*invocation],repeated_value)
362 assert not result.exists()
363 assert b'child_exit=75 ' in stopped.stderr
364 mutant=body.replace('hput 32 4 get dev 2\n','hput 32 4 add get dev 2 1\n')
365 assert mutant!=body
366 bad=compile('bad-gpu-record',mutant)
367 refuse('CONTROL wrong GPU record',[out/'trace',tmp,bad,'vadd',vobj,'vadd'],1,[out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd'],vadd_value)
368# An array-bound-dominant topology distinguishes both required ROCT divisions.
369with tempfile.TemporaryDirectory(prefix='kfd-ctx-',dir='/tmp') as tmp:
370 node=Path(tmp)/'2';node.mkdir()
371 (node/'gpu_id').write_text('1\n')
372 (node/'properties').write_text('gfx_target_version 90402\ndrm_render_minor 128\nsimd_count 1216\nsimd_per_cu 4\nmax_waves_per_simd 8\narray_count 4\nsimd_arrays_per_engine 2\nnum_xcc 1\n')
373 command=['env','KFD_TEST_CTX_BOUND=1',out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd','10000000000']
374 run('CWSR bound uses converted NumShaderBanks',command)
375 mutant=body.replace('mul div div get dev 5 get dev 6 get dev 6 512','mul div get dev 5 get dev 6 512')
376 assert mutant!=body
377 bad=compile('wrong-one-division-context',mutant)
378 refuse('CONTROL missing topology conversion',['env','KFD_TEST_CTX_BOUND=1',out/'trace',tmp,bad,'vadd',vobj,'vadd','10000000000'],1,command,vadd_value)
379# Card-shaped discovery: CPUs, denied gpu_id/properties, and only node 3 readable.
380# Denial is injected at syscall entry, so this remains deterministic under root.
381with tempfile.TemporaryDirectory(prefix='kfd-',dir='/tmp') as tmp:
382 for index in range(4):
383 node=Path(tmp)/str(index); node.mkdir()
384 (node/'gpu_id').write_text('0\n' if index<2 else '37820\n')
385 (node/'properties').write_text('gfx_target_version 90402\ndrm_render_minor 136\nsimd_count 32\nsimd_per_cu 4\nmax_waves_per_simd 8\narray_count 8\nsimd_arrays_per_engine 2\nnum_xcc 2\n')
386 command=['env','KFD_TEST_SORT_NODES=1','KFD_TEST_GPU=37820','KFD_TEST_MINOR=136',out/'trace',tmp,bins['a64'],'vadd',vobj,'vadd']
387 for deny in ('2/gpu_id','2/properties'):
388 args=['env','KFD_TEST_DENY='+deny,*command]
389 p=run('node-3-only discovery '+deny,args)
390 assert b'OMEGA topology selected node=3 gpu_id=37820 render_minor=136\n' in p.stdout
391 assert b'OMEGA topology skip CPU gpu_id=0\n' in p.stdout
392 assert b'OMEGA step topology_node fail errno=1 phase=after detail=2\n' in p.stdout
393 for step in ('open_kfd','version','render_open','acquire_vm','memory_alloc','memory_map','memory_cpu_map','queue_create','doorbell_map','code_object_load','dispatch','signal_wait','readback'):
394 assert ('OMEGA step '+step+' ok errno=0 phase=before').encode() in p.stdout
395 assert ('OMEGA step '+step+' ok errno=0 phase=after').encode() in p.stdout
396 p=refuse('CONTROL missing selected render node',['env','KFD_TEST_DENY=2/gpu_id','KFD_TEST_RENDER_ABSENT=1',*command],1,['env','KFD_TEST_DENY=2/gpu_id',*command],vadd_value)
397 assert b'child_exit=74 ' in p.stderr
398 assert b'OMEGA step render_open fail errno=2 phase=after detail=136\n' in p.stdout
399 mutant=body.replace('r = stepresult fd\nret false','r = checked fd\nret false')
400 assert mutant!=body
401 bad=compile('fatal-topology-open',mutant)
402 p=refuse('CONTROL inaccessible node must not abort',['env','KFD_TEST_DENY=2/gpu_id',*command[:-4],bad,'vadd',vobj,'vadd'],1,['env','KFD_TEST_DENY=2/gpu_id',*command],vadd_value)
403 assert b'child_exit=74 ' in p.stderr
404 mutant=body.replace('emit cpuskip\nret false','emit cpuskip\nexit 66')
405 assert mutant!=body
406 bad=compile('fatal-cpu-node',mutant)
407 p=refuse('CONTROL CPU node must not abort',[*command[:-4],bad,'vadd',vobj,'vadd'],1,command,vadd_value)
408 assert b'child_exit=66 ' in p.stderr
409# Exercise packet publication separately at every native instruction, using anonymous
410# CPU mappings. The observer verifies body -> header -> wptr -> doorbell, not final bytes alone.
411unit=''.join((src/(x+'.om')).read_text() for x in ('common','elf','device','dispatch'))
412unit+=(root/'backend/amd/kfd/cli.om').read_text()
413unit+='''fn main to int
414+t = checked mapnew -1 0 192 3 34
415+put launch 0 ulong t
416+for i ulong 8
417+h = checked mapnew -1 0 4096 3 34
418+r = checked mapset t mul i 24 8 ulong h
419+end
420+b = checked mapnew -1 0 4096 3 34
421+put launch 8 ulong b
422+r = checked mapset b 0 8 18446744073709551615
423+put launch 5 4
424+put launch 6 1
425+put el 6 64
426+put el 9 4096
427+r = checked mapset lh 3 0 4 1
428+hput 0 8 mapaddr lh 3
429+hput 8 8 mapaddr lh 0
430+hput 16 8 mapaddr lh 1
431+hput 24 8 mapaddr lh 7
432+hput 32 8 add mapaddr lh 5 56
433+hput 40 8 mapaddr b
434+r = checked write 1 hdr 0 48
435+packet 0
436+ret 0
437+end
438+'''.replace('\n+','\n')
439# Reuse the separately gated HSA packet encoder, not a second copy of launcher offsets.
440aql_bytes=run('compile independent AQL encoder',[omc],data=(root/'backend/amd/kfd/aql.om').read_bytes()+(root/'backend/amd/kfd/cli.om').read_bytes()).stdout
441aql=out/'aql-oracle';aql.write_bytes(aql_bytes);aql.chmod(0o700)
442def packet_agrees_with_aql(p,private=0):
443 assert len(p.stdout)==112
444 ring,code,args,sig,wp,bell=struct.unpack('<6Q',p.stdout[:48])
445 kobj,karg=code+64,args
446 expected=run('independent AQL nonzero LDS encoding',[aql,2,64,1,1,256,1,1,private,4096,kobj,karg,sig,1,2,2]).stdout
447 assert p.stdout[48:]==expected,(p.stdout[48:].hex(),expected.hex())
448u=compile('publication-unit',unit)
449packet_agrees_with_aql(run('native publication order',[out/'publication',u]))
450u=compile('publication-distinct-segments',unit.replace('put el 9 4096','put el 9 4096\nput el 10 20'))
451packet_agrees_with_aql(run('generic ABI private20 group4096',['env','EXPECTED_PRIVATE=20',out/'publication',u]),20)
452mutant=unit.replace('hput 24 4 get el 10\nhput 28 4 get el 9','hput 24 4 get el 9\nhput 28 4 get el 10')
453assert mutant!=unit
454u=compile('publication-swapped-segments',mutant)
455refuse('CONTROL swapped group-private segments',[out/'publication',u],1,[out/'publication',out/'publication-unit'],packet_agrees_with_aql)
456
457line='r = checked mapwrite lh 3 add slot 4 hdr 4 60\n'
458mutant=unit.replace(line,'').replace('r = checked mapset lh 3 slot 4 0x00021502\n','r = checked mapset lh 3 slot 4 0x00021502\n'+line)
459assert mutant!=unit
460u=compile('publication-early-header',mutant)
461refuse('CONTROL early valid header',[out/'publication',u],1,[out/'publication',out/'publication-unit'],packet_agrees_with_aql)
462# Ring capacity follows the dispatch count, the established AQL minimum,
463# and the 32-bit CREATE_QUEUE byte-size wire field.
464ringunit=''.join((src/(x+'.om')).read_text() for x in ('common','elf','device','dispatch','plan'))
465ringunit+=(root/'backend/amd/kfd/cli.om').read_text()
466# pw widths are fixed at production call sites. This defensive helper boundary is
467# not reachable by plan bytes; exercise it explicitly instead of inventing a plan row.
468def word_width_unit(width):
469 # The valid and refusing twins share real storage and the same known bytes.
470 setup='fn main to int\nput ps 0 ulong checked mapnew -1 0 16 3 34\nput ps 2 16\nr = checked mapset long get ps 0 0 4 287454020\nr = checked mapset long get ps 0 4 4 1432778632\n'
471 main=setup+'value = pw 0 '+str(width)+'\n'
472 expected=0x5566778811223344 & ((1<<(min(width,8)*8))-1)
473 main+='if ne value ulong '+str(expected)+'\nret 99\nend\nret 0\nend\n'
474 return ringunit+main
475for width in (1,4,8):
476 u=compile('plan-helper-valid-width-'+str(width),word_width_unit(width))
477 run('positive twin plan helper legal width '+str(width),[u])
478u=compile('plan-helper-word-width',word_width_unit(9))
479p=refuse('plan helper refuses impossible input width',[u],64,[out/'plan-helper-valid-width-8'],empty_value)
480assert p.stdout==b'OMEGA refuse plan field=word-width\n'
481ringmain='fn main to int\n'
482for dispatches,slots in [(1,16),(15,16),(16,32),(20,32),(1126,2048),(33554431,33554432)]:
483 ringmain+='put ps 6 '+str(dispatches)+'\nplanring\nif ne get launch 10 '+str(slots)+'\nret 99\nend\n'
484ringmain+='ret 0\nend\n'
485u=compile('plan-ring-boundaries',ringunit+ringmain)
486run('native plan ring capacity boundaries',[u])
487def ring_capacity_unit(dispatches):
488 return ringunit+'fn main to int\nput ps 6 '+str(dispatches)+'\nplanring\nif ne get launch 10 33554432\nret 99\nend\nret 0\nend\n'
489u=compile('plan-ring-unrepresentable',ring_capacity_unit(33554432))
490valid=compile('plan-ring-largest-representable',ring_capacity_unit(33554431))
491p=refuse('CONTROL plan ring exceeds UAPI size',[u],64,[valid],empty_value)
492assert p.stdout==b'OMEGA refuse plan field=ring-size\n'
493# The batch path has its own body-before-header observation and early-header control.
494planunit=''.join((src/(x+'.om')).read_text() for x in ('common','elf','device','dispatch','plan'))
495planunit+=(root/'backend/amd/kfd/cli.om').read_text()
496main=unit[unit.index('fn main to int'):]
497setup="""put launch 10 16
498put ps 6 1
499put ps 20 ulong checked mapnew -1 0 4096 3 34
500put ps 0 ulong checked mapnew -1 0 4096 3 34
501put ps 2 4096
502r = checked mapset long get ps 0 4 4 4
503r = checked mapset long get ps 0 8 4 1
504put ps 17 ulong checked mapnew -1 0 4096 3 34
505r = checked mapset long get ps 17 48 8 64
506r = checked mapset long get ps 17 72 8 4096
507put ps 19 ulong checked mapnew -1 0 4096 3 34
508r = checked mapset t 192 8 ulong lh 0
509plantemplate 0
510planpublish 0 0"""
511planunit+=main.replace('mapnew -1 0 192 3 34','mapnew -1 0 4096 3 34').replace('packet 0',setup)
512u=compile('plan-publication-unit',planunit)
513packet_agrees_with_aql(run('native batch publication order through plantemplate',[out/'publication',u]))
514u=compile('plan-publication-distinct-segments',planunit.replace('r = checked mapset long get ps 17 72 8 4096','r = checked mapset long get ps 17 72 8 4096\nr = checked mapset long get ps 17 80 8 20'))
515packet_agrees_with_aql(run('plantemplate ABI private20 group4096',['env','EXPECTED_PRIVATE=20',out/'publication',u]),20)
516mutant=planunit.replace('hput 24 4 cm code 80\nhput 28 4 cm code 72','hput 24 4 cm code 72\nhput 28 4 cm code 80')
517assert mutant!=planunit
518u=compile('plan-publication-swapped-segments',mutant)
519refuse('CONTROL plantemplate-only swapped segments',[out/'publication',u],1,[out/'publication',out/'plan-publication-unit'],packet_agrees_with_aql)
520mutant=planunit.replace('plancopy sent\ncpufence\n','').replace('r = checked mapset lh 5 56 8 add sent get ps 6','plancopy sent\nr = checked mapset lh 5 56 8 add sent get ps 6')
521assert mutant!=planunit
522u=compile('plan-publication-early-header',mutant)
523refuse('CONTROL batch early valid header',[out/'publication',u],1,[out/'publication',out/'plan-publication-unit'],packet_agrees_with_aql)
524mutant=body.replace('hput 24 4 cm code 80\nhput 28 4 cm code 72','hput 24 4 cm code 72\nhput 28 4 cm code 80')
525assert mutant!=body
526compile('plan-swapped-segments',mutant)
527mutant=body.replace('put dispatchalarm 0 0\n','')
528assert mutant!=body
529compile('plan-no-alarm-rearm',mutant)
530run('native plan CPU contracts',[sys.executable,'-I',root/'tests/amd-kfd-launch/plan-check.py',out])
531for receipt in sorted((root/'evidence').glob('amd-qwen38-native-*')):
532 state=receipt/'native/state.json'
533 if not state.exists():continue
534 run('verify archived native evidence '+receipt.name,[sys.executable,'-I',receipt/'verify.py'])
535 v=json.loads(state.read_text());prompt=len(v['fixture']['prompt_ids'])
536 for row in [v['control'],*v['rows']]:
537 text=(receipt/'native'/(row['label']+'.stdout')).read_text()
538 steps=[tuple(map(int,m)) for m in re.findall(r'^OMEGA_STEP (\d+) tok=(\d+) us=(\d+)$',text,re.M)]
539 assert math.isclose(sum(u for _,_,u in steps[:prompt])/1000,row['prefill_ms'],rel_tol=0,abs_tol=1e-9)
540 assert statistics.median(u/1000 for _,_,u in steps[prompt:])==row['decode_ms_median']
541 print('RAW TIMING PASS',receipt.name,flush=True)
542validate_inventory(results)
543import copy
544for fault in ('missing','trap103','trap104','setup','different-setup','kind'):
545 saved=results
546 results=copy.deepcopy(saved)
547 r=next(r for r in results if r['kind']=='refusal')
548 t=next(t for t in results if t['case']==r['twin'])
549 if fault=='missing':r.pop('twin')
550 elif fault.startswith('trap'):t['exit']=int(fault[4:])
551 elif fault=='setup':t['command']=['unrelated','fixture','extra']
552 elif fault=='different-setup':t['setup_sha256']='unrelated'
553 else:t['kind']='baseline'
554 try:validate_inventory(results)
555 except (AssertionError,KeyError):pass
556 else:raise AssertionError(('inventory control escaped',fault))
557 finally:results=saved
558(out/'results.json').write_text(json.dumps({'success_exits':[0,77],'cases':results,'inventory_controls':['missing','trap103','trap104','setup','different-setup','kind']},indent=2)+'\n')
559summary={'compiler':pin,'checks':len(results),'failures':sum(r['exit']!=r['expected'] for r in results),'qemu':qemu,'device':'NOT_RUN','orchestration':'native CPU syscall simulation only','publication':'native instruction-step observation only','objects':{name:hashlib.sha256(data).hexdigest() for name,(p,data,k,a) in objects.items()},'binaries':{name:hashlib.sha256(p.read_bytes()).hexdigest() for name,p in bins.items()}}
560(out/'summary.json').write_text(json.dumps(summary,indent=2)+'\n')
561print('AMD-KFD-LAUNCH CPU PASS',json.dumps(summary,sort_keys=True))
562print('NOT_RUN every AMD device row: KFD queues, GPU mappings, completion, parity, timing, Qwen inference')