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
CUDApp / tests / amd-exec / gdnstate_w.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Private-output executor acceptance and independent NumPy scalar-order oracle.""" |
| 4 | import argparse |
| 5 | import hashlib |
| 6 | import json |
| 7 | from pathlib import Path |
| 8 | import runpy |
| 9 | import shutil |
| 10 | import struct |
| 11 | import subprocess |
| 12 | import numpy as np |
| 13 | |
| 14 | PIN='2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f' |
| 15 | NAME='gdnstate_w' |
| 16 | SIZES=(16384,24576,3145728,3145728,24576,192,192) |
| 17 | NAMES=('qk','value','oldstate','newstate','output','decay','beta') |
| 18 | CASES=('random-1','random-2','random-3','zero','cancel','subnormal','impulse','exceptional') |
| 19 | |
| 20 | |
| 21 | def sha(p): |
| 22 | with Path(p).open('rb') as f: return hashlib.file_digest(f,'sha256').hexdigest() |
| 23 | |
| 24 | |
| 25 | def bf16(x): |
| 26 | bits=np.asarray(x,dtype=np.float32).view(np.uint32) |
| 27 | result=(bits+0x7fff+((bits>>16)&1))&np.uint32(0xffff0000) |
| 28 | return np.where((bits&0x7fffffff)>0x7f800000,np.uint32(0x7fc00000),result).astype(np.uint32).view(np.float32) |
| 29 | |
| 30 | |
| 31 | def fixture(kind): |
| 32 | seed=int(kind.split('-')[1]) if kind.startswith('random-') else 7 |
| 33 | rng=np.random.default_rng(seed) |
| 34 | qk=bf16(rng.uniform(-0.125,0.125,(2,16,128)).astype(np.float32)) |
| 35 | value=bf16(rng.uniform(-0.25,0.25,(48,128)).astype(np.float32)) |
| 36 | old=rng.uniform(-0.25,0.25,(48,128,128)).astype(np.float32) |
| 37 | decay=rng.uniform(0.125,0.875,48).astype(np.float32) |
| 38 | beta=bf16(rng.uniform(0.125,0.875,48).astype(np.float32)) |
| 39 | if kind=='zero': old.fill(0); value.fill(0); qk.fill(0) |
| 40 | elif kind=='cancel': |
| 41 | old[:]=np.where(np.arange(128)[:,None]%2,0.5,-0.5).astype(np.float32) |
| 42 | qk.fill(0.125); value.fill(0); decay.fill(1); beta.fill(1) |
| 43 | elif kind=='subnormal': |
| 44 | words=np.array([0,0x80000000,1,0x80000001,0x007fffff,0x807fffff,0x00800000,0x80800000],dtype=np.uint32) |
| 45 | old[:]=np.resize(words,old.size).reshape(old.shape).view(np.float32) |
| 46 | value[:]=np.resize(words,value.size).reshape(value.shape).view(np.float32) |
| 47 | qk.fill(0.125); decay.fill(0.5); beta.fill(0.5) |
| 48 | elif kind=='impulse': |
| 49 | old.fill(0); value.fill(0); qk.fill(0) |
| 50 | for head in range(48): |
| 51 | old[head,head%128,(head*17)%128]=np.float32((head+1)/64) |
| 52 | value[head,(head*7)%128]=np.float32((head+1)/128) |
| 53 | for head in range(16): qk[0,head,head*7]=0.5; qk[1,head,head*5]=0.25 |
| 54 | elif kind=='exceptional': |
| 55 | words=np.array([0x7f800000,0xff800000,0x7fc00000,0x7fa12345,0xffa12345,0x7f7fffff,0xff7fffff,0x80000000],dtype=np.uint32) |
| 56 | for head in range(48): old[head,head%128,:8]=words.view(np.float32) |
| 57 | value[:8,0]=words.view(np.float32); decay[0]=0; beta[1]=0 |
| 58 | buffers=(qk.tobytes(),value.tobytes(),old.tobytes(),b'\xa5'*SIZES[3],b'\xa5'*SIZES[4],decay.tobytes(),beta.tobytes()) |
| 59 | spans=[('kernarg',0,56)]; pointers=[]; cursor=128 |
| 60 | for name,blob in zip(NAMES,buffers): |
| 61 | spans.append((name,cursor,len(blob))); pointers.append(cursor); cursor+=len(blob)+128 |
| 62 | image=bytearray(b'\xa5')*cursor |
| 63 | struct.pack_into('<7Q',image,0,*pointers) |
| 64 | for p,b in zip(pointers,buffers): image[p:p+len(b)]=b |
| 65 | return image,spans |
| 66 | |
| 67 | |
| 68 | def oracle(image,spans): |
| 69 | ptr={name:p for name,p,n in spans} |
| 70 | def arr(name,shape): return np.frombuffer(image,dtype='<f4',count=int(np.prod(shape)),offset=ptr[name]).reshape(shape) |
| 71 | qk=arr('qk',(2,16,128)); q=np.repeat(qk[0],3,axis=0); k=np.repeat(qk[1],3,axis=0) |
| 72 | value=arr('value',(48,128)); old=arr('oldstate',(48,128,128)) |
| 73 | decay=arr('decay',(48,)); beta=arr('beta',(48,)) |
| 74 | with np.errstate(all='ignore'): |
| 75 | decayed=np.multiply(old,decay[:,None,None]); prediction=np.zeros((48,128),dtype=np.float32) |
| 76 | for r in range(128): prediction=np.add(prediction,np.multiply(k[:,r,None],decayed[:,r,:])) |
| 77 | delta=np.multiply(beta[:,None],np.subtract(value,prediction)) |
| 78 | updated=np.add(decayed,np.multiply(k[:,:,None],delta[:,None,:])) |
| 79 | core=np.zeros((48,128),dtype=np.float32) |
| 80 | for r in range(128): core=np.add(core,np.multiply(q[:,r,None],updated[:,r,:])) |
| 81 | core=bf16(core) |
| 82 | return {'newstate':updated,'output':core} |
| 83 | |
| 84 | |
| 85 | def check_independent(actual,spans,expected): |
| 86 | ptr={name:p for name,p,n in spans} |
| 87 | for name,want in expected.items(): |
| 88 | got=np.frombuffer(actual,dtype='<f4',count=want.size,offset=ptr[name]).reshape(want.shape) |
| 89 | assert np.array_equal(np.isnan(got),np.isnan(want)),name+' NaN classification' |
| 90 | finite=~np.isnan(want) |
| 91 | assert np.array_equal(got.view(np.uint32)[finite],want.view(np.uint32)[finite]),name+' independent finite/infinite bit mismatch' |
| 92 | |
| 93 | |
| 94 | def mutants(src): |
| 95 | changes={'wrong-column-block':('I 5 131 1 1 18','I 5 130 1 1 18'), |
| 96 | 'wrong-key-head':('I 2 3 137 29 28','I 2 3 136 29 28'), |
| 97 | 'no-beta':('I 5 277 18 18 5','I 5 242 18 18 5')} |
| 98 | result={} |
| 99 | for name,(old,new) in changes.items(): |
| 100 | assert src.count(old)==1,name |
| 101 | result[name]=src.replace(old,new) |
| 102 | return result |
| 103 | |
| 104 | |
| 105 | def section(path,name): |
| 106 | blob=Path(path).read_bytes(); shoff=struct.unpack_from('<Q',blob,40)[0] |
| 107 | entsize,count,stridx=struct.unpack_from('<HHH',blob,58) |
| 108 | entries=[struct.unpack_from('<IIQQQQIIQQ',blob,shoff+i*entsize) for i in range(count)] |
| 109 | names=blob[entries[stridx][4]:entries[stridx][4]+entries[stridx][5]] |
| 110 | for entry in entries: |
| 111 | if names[entry[0]:names.index(0,entry[0])].decode()==name: return blob[entry[4]:entry[4]+entry[5]] |
| 112 | raise AssertionError(name) |
| 113 | |
| 114 | |
| 115 | def main(): |
| 116 | parser=argparse.ArgumentParser(); parser.add_argument('--omc',required=True,type=Path); parser.add_argument('--out',required=True,type=Path) |
| 117 | args=parser.parse_args() |
| 118 | if sha(args.omc)!=PIN: raise SystemExit(69) |
| 119 | root=Path(__file__).resolve().parents[2]; out=args.out.resolve(); out.mkdir(parents=True,exist_ok=False) |
| 120 | snapshot=out/'source'; snapshot.mkdir() |
| 121 | paths=[root/'backend/amd/gfx942'/p for p in ('hsaco.om','gdnstate.isa','gdnstate-gfx942.s',NAME+'.isa',NAME+'-gfx942.s','exec/fp.om','exec/fma.om','exec/main.om')] |
| 122 | paths += [Path(__file__).with_name(p) for p in ('token_access.py','gdnstate_w.py')] |
| 123 | for path in paths: shutil.copyfile(path,snapshot/path.name) |
| 124 | hashes={p.name:sha(p) for p in snapshot.iterdir()} |
| 125 | instrument=runpy.run_path(str(snapshot/'token_access.py'))['instrument'] |
| 126 | commands=[] |
| 127 | def run(argv,stdin=None,stdout=None,expected=0): |
| 128 | p=subprocess.run([str(a) for a in argv],input=stdin,capture_output=True,timeout=1800) |
| 129 | commands.append(dict(argv=[str(a) for a in argv],exit=p.returncode,stdout_sha256=hashlib.sha256(p.stdout).hexdigest(),stderr=p.stderr.decode(errors='replace'))) |
| 130 | (out/'commands.json').write_text(json.dumps(commands,indent=2)+'\n') |
| 131 | assert p.returncode==expected and not p.stderr,commands[-1] |
| 132 | if stdout: Path(stdout).write_bytes(p.stdout) |
| 133 | return p.stdout |
| 134 | def compile_source(label,text): |
| 135 | (out/(label+'.om')).write_text(text); exe=out/label |
| 136 | run([args.omc],stdin=text.encode(),stdout=exe); exe.chmod(0o755); return exe |
| 137 | producer_src=(snapshot/'hsaco.om').read_text(); producer=compile_source('hsaco',producer_src) |
| 138 | assert run([args.omc],stdin=producer_src.encode())==producer.read_bytes() |
| 139 | exec_src=''.join((snapshot/p).read_text() for p in ('fp.om','fma.om','main.om')) |
| 140 | executor=compile_source('exec',exec_src) |
| 141 | assert run([args.omc],stdin=exec_src.encode())==executor.read_bytes() |
| 142 | original=(snapshot/(NAME+'.isa')).read_text() |
| 143 | variants={'gdnstate':(snapshot/'gdnstate.isa').read_text(),NAME:original,**{NAME+'-'+k:v for k,v in mutants(original).items()}} |
| 144 | texts={}; objects={} |
| 145 | for label,text in variants.items(): |
| 146 | path=out/(label+'.isa'); path.write_text(text); obj=out/(label+'.hsaco') |
| 147 | run([producer,path],stdout=obj); assert run([producer,path])==obj.read_bytes() |
| 148 | raw=out/(label+'.text'); raw.write_bytes(section(obj,'.text')); texts[label]=raw; objects[label]=obj |
| 149 | for label in ('gdnstate',NAME): |
| 150 | obj=out/(label+'-llvm.o') |
| 151 | run(['llvm-mc-18','-triple=amdgcn-amd-amdhsa','-mcpu=gfx942','-filetype=obj',snapshot/(label+'-gfx942.s'),'-o',obj]) |
| 152 | for sec in ('.text','.note'): assert section(objects[label],sec)==section(obj,sec),(label,sec) |
| 153 | a,b=section(objects[label],'.rodata'),section(obj,'.rodata') |
| 154 | assert len(a)==len(b)==64 and a[:16]+a[24:]==b[:16]+b[24:],(label,'descriptor') |
| 155 | print('PASS deterministic seeded producer/executor and LLVM text/note/descriptor',flush=True) |
| 156 | memory=out/'memory.bin'; cases=[]; bounds=[]; controls=[] |
| 157 | def execute(exe,name,data): |
| 158 | memory.write_bytes(data); gx=4 if name=='gdnstate' else 49 |
| 159 | stdout=run([exe,texts[name],memory,gx*64,17]); return stdout,memory.read_bytes() |
| 160 | def access(stdout,spans): |
| 161 | hits=struct.unpack('<'+'Q'*(2*len(spans)),stdout) |
| 162 | return [dict(name=name,bytes=n,max_read_offset=hits[2*i]-1 if hits[2*i] else None,max_write_offset=hits[2*i+1]-1 if hits[2*i+1] else None) for i,(name,p,n) in enumerate(spans)] |
| 163 | for kind in CASES: |
| 164 | data,spans=fixture(kind); expected=oracle(data,spans) |
| 165 | stdout,baseline=execute(executor,'gdnstate',data); assert not stdout |
| 166 | check_independent(baseline,spans,expected) |
| 167 | exe=executor |
| 168 | if kind=='random-1': exe=compile_source('access',instrument(exec_src,[(p,n) for name,p,n in spans])) |
| 169 | stdout,actual=execute(exe,NAME,data) |
| 170 | assert actual==baseline,(kind,'partitioned/baseline bit mismatch') |
| 171 | ptr={name:p for name,p,n in spans}; expected_image=bytearray(data) |
| 172 | for name in ('newstate','output'): |
| 173 | n=SIZES[NAMES.index(name)]; p=ptr[name]; expected_image[p:p+n]=baseline[p:p+n] |
| 174 | assert actual==expected_image,(kind,'input/guard write') |
| 175 | if kind=='random-1': bounds.append(dict(case=kind,buffers=access(stdout,spans))) |
| 176 | else: assert not stdout |
| 177 | record=dict(case=kind,comparison='every byte vs original gdnstate; independent scalar-order FP32 oracle',input_sha256=hashlib.sha256(data).hexdigest(),result_sha256=hashlib.sha256(actual).hexdigest()) |
| 178 | cases.append(record) |
| 179 | if kind=='random-1': |
| 180 | (out/'fixture.bin').write_bytes(data); (out/'expected.bin').write_bytes(actual) |
| 181 | (out/'fixture.json').write_text(json.dumps(dict(buffers=[dict(name=name,offset=p,bytes=n) for name,p,n in spans]),indent=2)+'\n') |
| 182 | print('PASS '+kind+' all-state/core bits and all inputs/guards; XY overdispatch',flush=True) |
| 183 | data,spans=fixture('random-1'); expected=(out/'expected.bin').read_bytes() |
| 184 | access_exe=out/'access' |
| 185 | for mutant in mutants(original): |
| 186 | stdout,actual=execute(access_exe,NAME+'-'+mutant,data) |
| 187 | assert actual!=expected,mutant+' escaped' |
| 188 | bounds.append(dict(case=mutant,buffers=access(stdout,spans))) |
| 189 | controls.append(dict(mutant=mutant,exit=0,result='CAUGHT numerical mismatch')) |
| 190 | print('CONTROL '+mutant+' CAUGHT numerical mismatch exit=0',flush=True) |
| 191 | measured=bounds[0]['buffers'] |
| 192 | for i,(name,p,n) in enumerate(spans): |
| 193 | last=max(v for v in (measured[i]['max_read_offset'],measured[i]['max_write_offset']) if v is not None) |
| 194 | shortened=[(base,length) for _,base,length in spans]; shortened[i]=(p,last) |
| 195 | exe=compile_source('short-'+name,instrument(exec_src,shortened)); memory.write_bytes(data) |
| 196 | run([exe,texts[NAME],memory,49*64,17],expected=68) |
| 197 | controls.append(dict(buffer=name,exit=68,result='CAUGHT one-byte-short span')) |
| 198 | print('CONTROL short-'+name+' CAUGHT exit=68',flush=True) |
| 199 | memory.unlink() |
| 200 | report=dict(schema='gdnstate-w-acceptance-v1',status='EXERCISED',hardware='NOT_RUN',performance='NOT_RUN',compiler_sha256=PIN,source_sha256=hashes,kernarg_size=56,grid_workgroups=[48,16,1],block=[64,1,1],active_lanes=8,columns_per_workgroup=8,objects={name:dict(file=p.name,sha256=sha(p)) for name,p in objects.items()},cases=cases,bounds=bounds,controls=controls) |
| 201 | (out/'report.json').write_text(json.dumps(report,indent=2)+'\n') |
| 202 | print('PASS gdnstate_w cases=%d controls=%d HARDWARE NOT_RUN PERFORMANCE NOT_RUN' % (len(cases),len(controls)),flush=True) |
| 203 | |
| 204 | if __name__=='__main__': main() |