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/tests/amd-kfd-launch/check.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 / 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. 4 import hashlib 5 import json 6 import os 7 import re 8 import statistics 9 import math 10 from pathlib import Path 11 import shutil 12 import struct 13 import subprocess 14 import sys 15 import tempfile 16 17 root=Path(__file__).resolve().parents[2] 18 src=root/'backend/amd/kfd/launch' 19 if len(sys.argv)!=2 or not Path(sys.argv[1]).is_absolute(): 20 raise SystemExit(64) 21 omc=Path(sys.argv[1]) 22 pin=(src/'COMPILER').read_text().splitlines()[1].split()[0] 23 if not omc.is_file() or hashlib.sha256(omc.read_bytes()).hexdigest()!=pin: 24 print('REFUSED compiler digest',file=sys.stderr) 25 raise SystemExit(69) 26 out=Path(os.environ.get('AMD_KFD_LAUNCH_OUT',root/'build/amd-kfd-launch/gate')).resolve() 27 out.mkdir(parents=True,exist_ok=True) 28 results=[] 29 def 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 44 def 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 '' 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' 64 def 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 73 def 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) 75 def empty_value(p): 76 # Composed units return zero only after asserting their mapped read value. 77 assert p.stdout==b'' 78 def preflight_value(p): 79 assert b'OMEGA step open_kfd' in p.stdout 80 def two_alarm_value(p): 81 vadd_value(p) 82 assert p.stdout.count(b'OMEGA alarm slow_dispatch_ns=')==2 83 def fast_value(p): 84 diagnostics(p,1,0,0x40000000,0) 85 assert b'OMEGA alarm slow_dispatch_ns=' not in p.stdout 86 def inspected_value(p): 87 assert ('kernarg_bytes='+str(ka)).encode() in p.stdout 88 def 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 102 reference=root/'tests/amd-kfd-launch/reference' 103 references=json.loads((reference/'sources.json').read_text())['sources'] 104 assert len({r['file'] for r in references})==len(references) 105 for 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) 119 checksums=''.join(r['sha256']+' '+r['file']+'\n' for r in sorted(references,key=lambda r:r['file'])) 120 assert (reference/'SHA256SUMS').read_text()==checksums 121 source_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) 122 readme=(reference/'README.md').read_text() 123 assert readme.count('\n')==readme.count('')==1 124 assert readme.split('\n')[1].split('')[0]==source_table 125 print('PRIMARY SOURCE PASS producer mapping, pins and derived reference views',flush=True) 126 parts=['common','elf','device','dispatch','plan','main'] 127 body=''.join((src/(x+'.om')).read_text() for x in parts)+(root/'backend/amd/kfd/cli.om').read_text() 128 def 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 133 qemu=shutil.which('qemu-x86_64') 134 bins={t:compile('launch-'+t,body,t) for t in ('a64','x86')} 135 wrong=out/'wrong-compiler'; marker=out/'WRONG-EXECUTED' 136 wrong.write_text('#!/bin/sh\ntouch '+str(marker)+'\n'); wrong.chmod(0o700) 137 wrongout=out/'wrong-output'; env=dict(os.environ,AMD_KFD_LAUNCH_OUT=str(wrongout)) 138 p=subprocess.run([sys.executable,'-I',__file__,str(wrong)],env=env,capture_output=True) 139 assert p.returncode==69 and not marker.exists() and not wrongout.exists() 140 print('CONTROL wrong compiler refused before execution/output',flush=True) 141 # Build the repository-owned object writer, not an LLVM-generated replacement. 142 hs=run('compile object writer',[omc],data=(root/'backend/amd/gfx942/hsaco.om').read_bytes()) 143 writer=out/'hsaco'; writer.write_bytes(hs.stdout); writer.chmod(0o700) 144 objects={} 145 def elfmeta(data): 146 phoff=struct.unpack_from(' header -> wptr -> doorbell, not final bytes alone. 411 unit=''.join((src/(x+'.om')).read_text() for x in ('common','elf','device','dispatch')) 412 unit+=(root/'backend/amd/kfd/cli.om').read_text() 413 unit+='''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. 440 aql_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 441 aql=out/'aql-oracle';aql.write_bytes(aql_bytes);aql.chmod(0o700) 442 def 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()) 448 u=compile('publication-unit',unit) 449 packet_agrees_with_aql(run('native publication order',[out/'publication',u])) 450 u=compile('publication-distinct-segments',unit.replace('put el 9 4096','put el 9 4096\nput el 10 20')) 451 packet_agrees_with_aql(run('generic ABI private20 group4096',['env','EXPECTED_PRIVATE=20',out/'publication',u]),20) 452 mutant=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') 453 assert mutant!=unit 454 u=compile('publication-swapped-segments',mutant) 455 refuse('CONTROL swapped group-private segments',[out/'publication',u],1,[out/'publication',out/'publication-unit'],packet_agrees_with_aql) 456 457 line='r = checked mapwrite lh 3 add slot 4 hdr 4 60\n' 458 mutant=unit.replace(line,'').replace('r = checked mapset lh 3 slot 4 0x00021502\n','r = checked mapset lh 3 slot 4 0x00021502\n'+line) 459 assert mutant!=unit 460 u=compile('publication-early-header',mutant) 461 refuse('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. 464 ringunit=''.join((src/(x+'.om')).read_text() for x in ('common','elf','device','dispatch','plan')) 465 ringunit+=(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. 468 def 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 475 for 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]) 478 u=compile('plan-helper-word-width',word_width_unit(9)) 479 p=refuse('plan helper refuses impossible input width',[u],64,[out/'plan-helper-valid-width-8'],empty_value) 480 assert p.stdout==b'OMEGA refuse plan field=word-width\n' 481 ringmain='fn main to int\n' 482 for 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' 484 ringmain+='ret 0\nend\n' 485 u=compile('plan-ring-boundaries',ringunit+ringmain) 486 run('native plan ring capacity boundaries',[u]) 487 def 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' 489 u=compile('plan-ring-unrepresentable',ring_capacity_unit(`33554432`)) 490 valid=compile('plan-ring-largest-representable',ring_capacity_unit(`33554431`)) 491 p=refuse('CONTROL plan ring exceeds UAPI size',[u],64,[valid],empty_value) 492 assert 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. 494 planunit=''.join((src/(x+'.om')).read_text() for x in ('common','elf','device','dispatch','plan')) 495 planunit+=(root/'backend/amd/kfd/cli.om').read_text() 496 main=unit[unit.index('fn main to int'):] 497 setup="""put launch 10 16 498 put ps 6 1 499 put ps 20 ulong checked mapnew -1 0 4096 3 34 500 put ps 0 ulong checked mapnew -1 0 4096 3 34 501 put ps 2 4096 502 r = checked mapset long get ps 0 4 4 4 503 r = checked mapset long get ps 0 8 4 1 504 put ps 17 ulong checked mapnew -1 0 4096 3 34 505 r = checked mapset long get ps 17 48 8 64 506 r = checked mapset long get ps 17 72 8 4096 507 put ps 19 ulong checked mapnew -1 0 4096 3 34 508 r = checked mapset t 192 8 ulong lh 0 509 plantemplate 0 510 planpublish 0 0""" 511 planunit+=main.replace('mapnew -1 0 192 3 34','mapnew -1 0 4096 3 34').replace('packet 0',setup) 512 u=compile('plan-publication-unit',planunit) 513 packet_agrees_with_aql(run('native batch publication order through plantemplate',[out/'publication',u])) 514 u=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')) 515 packet_agrees_with_aql(run('plantemplate ABI private20 group4096',['env','EXPECTED_PRIVATE=20',out/'publication',u]),20) 516 mutant=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') 517 assert mutant!=planunit 518 u=compile('plan-publication-swapped-segments',mutant) 519 refuse('CONTROL plantemplate-only swapped segments',[out/'publication',u],1,[out/'publication',out/'plan-publication-unit'],packet_agrees_with_aql) 520 mutant=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') 521 assert mutant!=planunit 522 u=compile('plan-publication-early-header',mutant) 523 refuse('CONTROL batch early valid header',[out/'publication',u],1,[out/'publication',out/'plan-publication-unit'],packet_agrees_with_aql) 524 mutant=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') 525 assert mutant!=body 526 compile('plan-swapped-segments',mutant) 527 mutant=body.replace('put dispatchalarm 0 0\n','') 528 assert mutant!=body 529 compile('plan-no-alarm-rearm',mutant) 530 run('native plan CPU contracts',[sys.executable,'-I',root/'tests/amd-kfd-launch/plan-check.py',out]) 531 for 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) 542 validate_inventory(results) 543 import copy 544 for 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') 559 summary={'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') 561 print('AMD-KFD-LAUNCH CPU PASS',json.dumps(summary,sort_keys=True)) 562 print('NOT_RUN every AMD device row: KFD queues, GPU mappings, completion, parity, timing, Qwen inference')