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 / addnorm5120.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Private-output acceptance: exact residual5120 -> rmsnorm5120 equivalence.""" |
| 4 | import argparse, hashlib, json, runpy, shutil, struct, subprocess |
| 5 | from pathlib import Path |
| 6 | import numpy as np |
| 7 | from gdnstate_w import PIN,sha,section,bf16 |
| 8 | NAME='addnorm5120' |
| 9 | NAMES=('h','delta','weight','h_new','y') |
| 10 | CASES=('random-1','random-2','zero','cancel','tiny','large','subnormal','exceptional') |
| 11 | |
| 12 | |
| 13 | def fixture(kind): |
| 14 | rng=np.random.default_rng(int(kind[-1]) if kind.startswith('random-') else 7) |
| 15 | h=rng.uniform(-1,1,5120).astype(np.float32); d=rng.uniform(-0.5,0.5,5120).astype(np.float32) |
| 16 | w=bf16(rng.uniform(-1.5,1.5,5120).astype(np.float32)); w[:3]=(-1,0,1) |
| 17 | if kind=='zero': h.fill(0); d.fill(0) |
| 18 | elif kind=='cancel': d=-h |
| 19 | elif kind=='tiny': h*=np.float32(2.0**-16); d*=np.float32(2.0**-16) |
| 20 | elif kind=='large': h*=np.float32(2.0**70); d*=np.float32(2.0**70) |
| 21 | elif kind=='subnormal': |
| 22 | bits=np.array([0,0x80000000,1,0x80000001,0x007fffff,0x807fffff,0x00800000,0x80800000],dtype=np.uint32) |
| 23 | h=np.resize(bits,5120).view(np.float32); d=np.resize(bits[::-1],5120).view(np.float32) |
| 24 | elif kind=='exceptional': |
| 25 | h[:8]=np.array([0x7f800000,0xff800000,0x7fc00000,0x7fa12345,0xffa12345,0x7f7fffff,0xff7fffff,0x80000000],dtype=np.uint32).view(np.float32) |
| 26 | d[:8]=h[::-1][:8] |
| 27 | blobs=(h.tobytes(),d.tobytes(),w.tobytes(),b'\xa5'*20480,b'\xa5'*20480) |
| 28 | spans=[('kernarg',0,40)]; pointers=[]; cursor=128 |
| 29 | for name,blob in zip(NAMES,blobs): spans.append((name,cursor,len(blob))); pointers.append(cursor); cursor+=len(blob)+128 |
| 30 | image=bytearray(b'\xa5')*cursor; struct.pack_into('<5Q',image,0,*pointers) |
| 31 | for p,blob in zip(pointers,blobs): image[p:p+len(blob)]=blob |
| 32 | return image,spans |
| 33 | |
| 34 | |
| 35 | def residual_reference(image,spans): |
| 36 | ptr={name:p for name,p,n in spans} |
| 37 | h=np.frombuffer(image,dtype='<f4',count=5120,offset=ptr['h']); d=np.frombuffer(image,dtype='<f4',count=5120,offset=ptr['delta']) |
| 38 | with np.errstate(all='ignore'): return bf16(np.add(bf16(h),bf16(d))) |
| 39 | |
| 40 | |
| 41 | def check_oracle(actual,initial,spans,ref): |
| 42 | ptr={name:p for name,p,n in spans}; residual=residual_reference(initial,spans) |
| 43 | observed=np.frombuffer(actual,dtype='<f4',count=5120,offset=ptr['h_new']) |
| 44 | assert np.array_equal(observed.view(np.uint32),residual.view(np.uint32)),'independent residual bit mismatch' |
| 45 | if not np.isfinite(residual).all(): return 'nonfinite: residual exact; norm exact against original sequence' |
| 46 | words=residual.view(np.uint32).tolist(); weights=struct.unpack_from('<5120I',initial,ptr['weight']) |
| 47 | fma,add,mul,finite,point,imul,rsqbound=(ref[n] for n in ('fma','add','mul','finite','point','imul','rsqbound')) |
| 48 | lanes=[0]*64 |
| 49 | for lane in range(64): |
| 50 | for chunk in range(20): |
| 51 | for j in range(4): |
| 52 | a=words[chunk*256+lane*4+j]; lanes[lane]=fma(a,a,lanes[lane]) |
| 53 | for shift in (32,16,8,4,2,1): lanes=[add(lanes[i],lanes[i^shift]) for i in range(64)] |
| 54 | variance=add(mul(lanes[0],0x394ccccd),0x358637bd) |
| 55 | if variance&0x7f800000==0x7f800000: return 'overflow: residual exact; norm exact against original sequence' |
| 56 | inv=rsqbound(finite(variance)); outputs=struct.unpack_from('<5120I',actual,ptr['y']) |
| 57 | for x,w,y in zip(words,weights,outputs): |
| 58 | lo,hi=imul(imul(point(x),inv),point(add(0x3f800000,w))) |
| 59 | assert y&0x7f800000!=0x7f800000 and lo<=finite(y)<=hi,'independent norm interval mismatch' |
| 60 | return 'residual exact; all norm outputs within instruction-boundary RSQ interval' |
| 61 | |
| 62 | |
| 63 | def mutants(source): |
| 64 | no_store=source |
| 65 | preadd=source |
| 66 | for j in range(4): |
| 67 | store=f'I 7 {j*4} 0 2 0 0 28 0 6 {12+j} 127 0 0\n' |
| 68 | assert no_store.count(store)==1; no_store=no_store.replace(store,'') |
| 69 | fma=f'I 5 {268+j} {12+j} 16 59\n'; assert preadd.count(fma)==1 |
| 70 | preadd=preadd.replace(fma,'').replace(f'# FUSED_ELEMENT_{j}\n',f'# FUSED_ELEMENT_{j}\nI 5 {264+j} {8+j} 16 59\n') |
| 71 | assert source.count('L 897988541')==1 |
| 72 | return {'skip-residual-write':no_store,'norm-preadd':preadd,'wrong-epsilon':source.replace('L 897988541','L 0')} |
| 73 | |
| 74 | |
| 75 | def main(): |
| 76 | p=argparse.ArgumentParser(); p.add_argument('--omc',required=True,type=Path); p.add_argument('--out',required=True,type=Path); args=p.parse_args() |
| 77 | if sha(args.omc)!=PIN: raise SystemExit(69) |
| 78 | root=Path(__file__).resolve().parents[2]; out=args.out.resolve(); out.mkdir(parents=True,exist_ok=False); snapshot=out/'source'; snapshot.mkdir() |
| 79 | names=('hsaco.om','residual5120.isa','residual5120-gfx942.s','rmsnorm5120.isa','rmsnorm5120-gfx942.s',NAME+'.isa',NAME+'-gfx942.s','exec/fp.om','exec/fma.om','exec/main.om') |
| 80 | sources=[root/'backend/amd/gfx942'/name for name in names] |
| 81 | sources += [Path(__file__).with_name(name) for name in ('token_access.py','prep.py','attention.py','sgemm.py','gdnstate_w.py','addnorm5120.py')] |
| 82 | for source in sources: shutil.copyfile(source,snapshot/source.name) |
| 83 | pins={source.name:sha(source) for source in snapshot.iterdir()} |
| 84 | ref=runpy.run_path(str(snapshot/'prep.py')); instrument=runpy.run_path(str(snapshot/'token_access.py'))['instrument']; commands=[] |
| 85 | def run(argv,stdin=None,stdout=None,expected=0): |
| 86 | result=subprocess.run([str(a) for a in argv],input=stdin,capture_output=True,timeout=900) |
| 87 | commands.append(dict(argv=[str(a) for a in argv],exit=result.returncode,stdout_sha256=hashlib.sha256(result.stdout).hexdigest(),stderr=result.stderr.decode(errors='replace'))) |
| 88 | (out/'commands.json').write_text(json.dumps(commands,indent=2)+'\n') |
| 89 | assert result.returncode==expected and not result.stderr,commands[-1] |
| 90 | if stdout: Path(stdout).write_bytes(result.stdout) |
| 91 | return result.stdout |
| 92 | def compile_source(label,text): |
| 93 | (out/(label+'.om')).write_text(text); exe=out/label; run([args.omc],stdin=text.encode(),stdout=exe); exe.chmod(0o755); return exe |
| 94 | producer_source=(snapshot/'hsaco.om').read_text(); producer=compile_source('hsaco',producer_source) |
| 95 | assert run([args.omc],stdin=producer_source.encode())==producer.read_bytes() |
| 96 | exec_source=''.join((snapshot/name).read_text() for name in ('fp.om','fma.om','main.om')); executor=compile_source('exec',exec_source) |
| 97 | assert run([args.omc],stdin=exec_source.encode())==executor.read_bytes() |
| 98 | original=(snapshot/(NAME+'.isa')).read_text() |
| 99 | variants={name:(snapshot/(name+'.isa')).read_text() for name in ('residual5120','rmsnorm5120',NAME)} |
| 100 | variants.update({NAME+'-'+name:text for name,text in mutants(original).items()}); texts={}; objects={} |
| 101 | for name,text in variants.items(): |
| 102 | table=out/(name+'.isa'); table.write_text(text); obj=out/(name+'.hsaco'); run([producer,table],stdout=obj) |
| 103 | assert run([producer,table])==obj.read_bytes(); raw=out/(name+'.text'); raw.write_bytes(section(obj,'.text')); texts[name]=raw; objects[name]=obj |
| 104 | for name in ('residual5120','rmsnorm5120',NAME): |
| 105 | obj=out/(name+'-llvm.o'); run(['llvm-mc-18','-triple=amdgcn-amd-amdhsa','-mcpu=gfx942','-filetype=obj',snapshot/(name+'-gfx942.s'),'-o',obj]) |
| 106 | for sec in ('.text','.note'): assert section(objects[name],sec)==section(obj,sec),(name,sec) |
| 107 | a,b=section(objects[name],'.rodata'),section(obj,'.rodata'); assert len(a)==len(b)==64 and a[:16]+a[24:]==b[:16]+b[24:],(name,'descriptor') |
| 108 | print('PASS deterministic seeded producer/executor; original and fused LLVM text/note/descriptor',flush=True) |
| 109 | memory=out/'memory.bin'; cases=[]; bounds=[]; controls=[] |
| 110 | def execute(exe,name,data,gx=2,gy=2): |
| 111 | memory.write_bytes(data); stdout=run([exe,texts[name],memory,gx*64,gy]); return stdout,memory.read_bytes() |
| 112 | def access(stdout,spans): |
| 113 | hits=struct.unpack('<'+'Q'*(2*len(spans)),stdout) |
| 114 | return [dict(name=name,bytes=n,max_read_offset=hits[i*2]-1 if hits[i*2] else None,max_write_offset=hits[i*2+1]-1 if hits[i*2+1] else None) for i,(name,p,n) in enumerate(spans)] |
| 115 | for kind in CASES: |
| 116 | data,spans=fixture(kind); ptr={name:p for name,p,n in spans}; baseline=bytearray(data) |
| 117 | struct.pack_into('<3Q',baseline,0,ptr['h'],ptr['delta'],ptr['h_new']); stdout,baseline=execute(executor,'residual5120',baseline,81); assert not stdout |
| 118 | baseline=bytearray(baseline); struct.pack_into('<3QI',baseline,0,ptr['h_new'],ptr['weight'],ptr['y'],1) |
| 119 | stdout,baseline=execute(executor,'rmsnorm5120',baseline); assert not stdout |
| 120 | baseline=bytearray(baseline); baseline[:40]=data[:40] |
| 121 | independent=check_oracle(baseline,data,spans,ref) |
| 122 | exe=executor |
| 123 | if kind=='random-1': exe=compile_source('access',instrument(exec_source,[(p,n) for name,p,n in spans])) |
| 124 | stdout,actual=execute(exe,NAME,data); assert actual==baseline,(kind,'fused/two-kernel bit mismatch') |
| 125 | expected=bytearray(data) |
| 126 | for name in ('h_new','y'): expected[ptr[name]:ptr[name]+20480]=baseline[ptr[name]:ptr[name]+20480] |
| 127 | assert actual==expected,(kind,'input/guard changed') |
| 128 | if kind=='random-1': |
| 129 | bounds.append(dict(case=kind,buffers=access(stdout,spans))); (out/'fixture.bin').write_bytes(data); (out/'expected.bin').write_bytes(actual) |
| 130 | else: assert not stdout |
| 131 | cases.append(dict(case=kind,input_sha256=hashlib.sha256(data).hexdigest(),result_sha256=hashlib.sha256(actual).hexdigest(),independent=independent)) |
| 132 | print('PASS '+kind+' residual/norm all bits equal two-kernel sequence; guards; XY overdispatch; '+independent,flush=True) |
| 133 | data,spans=fixture('random-1'); expected=(out/'expected.bin').read_bytes() |
| 134 | for name in mutants(original): |
| 135 | stdout,actual=execute(out/'access',NAME+'-'+name,data); assert actual!=expected,name+' escaped' |
| 136 | bounds.append(dict(case=name,buffers=access(stdout,spans))); controls.append(dict(mutant=name,exit=0,result='CAUGHT numerical mismatch')) |
| 137 | print('CONTROL '+name+' CAUGHT numerical mismatch exit=0',flush=True) |
| 138 | measured=bounds[0]['buffers'] |
| 139 | for i,(name,p,n) in enumerate(spans): |
| 140 | last=max(v for v in (measured[i]['max_read_offset'],measured[i]['max_write_offset']) if v is not None) |
| 141 | shortened=[(p,n) for _,p,n in spans]; shortened[i]=(p,last) |
| 142 | exe=compile_source('short-'+name,instrument(exec_source,shortened)); memory.write_bytes(data); run([exe,texts[NAME],memory,128,2],expected=68) |
| 143 | controls.append(dict(buffer=name,exit=68,result='CAUGHT one-byte-short span')); print('CONTROL short-'+name+' CAUGHT exit=68',flush=True) |
| 144 | memory.unlink() |
| 145 | report=dict(schema='addnorm5120-acceptance-v1',status='EXERCISED',hardware='NOT_RUN',performance='NOT_RUN',compiler_sha256=PIN,source_sha256=pins,kernarg_size=40,grid_workgroups=[1,1,1],block=[64,1,1],objects={name:dict(file=obj.name,sha256=sha(obj)) for name,obj in objects.items()},cases=cases,bounds=bounds,controls=controls) |
| 146 | (out/'report.json').write_text(json.dumps(report,indent=2)+'\n') |
| 147 | print('PASS addnorm5120 cases=%d controls=%d HARDWARE NOT_RUN PERFORMANCE NOT_RUN'%(len(cases),len(controls)),flush=True) |
| 148 | |
| 149 | if __name__=='__main__': main() |