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 / decode.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Token decode independent reference instruments; no production Python dependency.""" |
| 4 | import base64 |
| 5 | from decimal import Decimal,localcontext |
| 6 | from fractions import Fraction |
| 7 | from functools import lru_cache |
| 8 | import pathlib |
| 9 | import runpy |
| 10 | import struct |
| 11 | import sys |
| 12 | HERE=pathlib.Path(__file__).parent |
| 13 | ref=runpy.run_path(str(HERE/'token_ref.py')) |
| 14 | finite,round32,mul,add,point,imul,iadd,expbound,intervalrcp,rsqbound,execute,export=(ref[n] for n in ('finite','round32','mul','add','point','imul','iadd','expbound','intervalrcp','rsqbound','execute','export')) |
| 15 | bf16=ref['ref']['bf16'] |
| 16 | sigmoid=ref['sigmoid'] |
| 17 | logbound=runpy.run_path(str(HERE/'log.py'))['logbound'] |
| 18 | |
| 19 | def alloc(sizes): |
| 20 | pointers=[]; end=128 |
| 21 | for size in sizes: pointers.append(end); end+=size+64 |
| 22 | image=bytearray([0xa5])*end |
| 23 | struct.pack_into('<'+str(len(pointers))+'Q',image,0,*pointers) |
| 24 | return image,pointers |
| 25 | |
| 26 | def result(label,image,pointers,sizes,grid,exact=(),intervals=(),bfout=()): |
| 27 | return dict(label=label,memory=base64.b64encode(image).decode(),args=[['ptr',p] for p in pointers], |
| 28 | gx=grid[0]+1,gy=grid[1]+1,timing_grid=list(grid),input_bytes=sum(sizes[:-1]), |
| 29 | exact=list(exact),intervals=list(intervals),bf16_outputs=list(bfout), |
| 30 | buffers=[dict(offset=p,bytes=n) for p,n in zip(pointers,sizes)]) |
| 31 | |
| 32 | def ibf(a): return tuple(finite(bf16(round32(x))<<16) for x in a) |
| 33 | |
| 34 | def residual_case(kind): |
| 35 | sizes=(5120*4,5120*4,5120*4); image,p=alloc(sizes); exact=[] |
| 36 | for i in range(5120): |
| 37 | a=round32(Fraction((i*17)%131-65,16)); b=round32(Fraction((i*7)%127-63,257)) |
| 38 | if kind=='cancel': b=a^0x80000000 |
| 39 | struct.pack_into('<I',image,p[0]+4*i,a); struct.pack_into('<I',image,p[1]+4*i,b) |
| 40 | c=bf16(add(bf16(a)<<16,bf16(b)<<16))<<16 |
| 41 | exact.append([p[2]+4*i,c,4]) |
| 42 | return result('BF16 residual '+kind,image,p,sizes,(80,1),exact) |
| 43 | |
| 44 | def embedding_case(kind): |
| 45 | sizes=(5120*2,5120*4); image,p=alloc(sizes); exact=[] |
| 46 | for i in range(5120): |
| 47 | b=bf16(round32(Fraction((i*7)%127-63,16))) |
| 48 | if kind=='bits': b=(0,0x8000,1,0x8001,0x7f80,0xff80,0x7fc1,0x7f81)[i%8] |
| 49 | struct.pack_into('<H',image,p[0]+2*i,b); exact.append([p[1]+4*i,b<<16,4]) |
| 50 | return result('selected BF16 embedding row '+kind,image,p,sizes,(80,1),exact) |
| 51 | |
| 52 | @lru_cache(None) |
| 53 | def intervalexp(a): |
| 54 | return expbound(round32(a[0]))[0],expbound(round32(a[1]))[1] |
| 55 | |
| 56 | @lru_cache(None) |
| 57 | def softplus(x): |
| 58 | if finite(x)>20: return point(x) |
| 59 | t=expbound(mul((x&0x7fffffff)|0x80000000,0x3fb8aa3b)) |
| 60 | u=iadd(point(0x3f800000),t) |
| 61 | bounds=[] |
| 62 | # The rounded u can have several adjacent values; union their possible paths. |
| 63 | for bits in range(round32(u[0]),round32(u[1])+1): |
| 64 | if bits==0x3f800000: y=t |
| 65 | else: |
| 66 | d=point(add(bits,0xbf800000)) |
| 67 | y=imul(imul(logbound(bits),point(0x3f317218)),imul(t,intervalrcp(d))) |
| 68 | bounds.extend(y) |
| 69 | return iadd((min(bounds),max(bounds)),point(x if finite(x)>0 else 0)) |
| 70 | |
| 71 | @lru_cache(None) |
| 72 | def param_values(kind): |
| 73 | values=[] |
| 74 | for i in range(48): |
| 75 | a=round32(Fraction((i*11)%37-18,4)); b=round32(Fraction((i*7)%29-14,4)) |
| 76 | A=round32(Fraction(i%7-3,4)); dt=round32(Fraction(i%5-2,8)) |
| 77 | if kind=='tails': a=round32(Fraction((-80,-20,-17,-2,0,2,20,21,80)[i%9])); A=round32(Fraction(i%4)); b=round32(Fraction((-80,0,80)[i%3])) |
| 78 | values.append((a,b,A,dt)) |
| 79 | return values |
| 80 | |
| 81 | def params_case(kind): |
| 82 | sizes=(48*4,)*6; image,p=alloc(sizes); intervals=[]; bfout=[] |
| 83 | for i,(a,b,A,dt) in enumerate(param_values(kind)): |
| 84 | for ptr,v in zip(p,(a,b,A,dt)): struct.pack_into('<I',image,ptr+4*i,v) |
| 85 | beta=ibf(sigmoid(bf16(b)<<16)); sp=softplus(add(bf16(a)<<16,dt)); ea=expbound(mul(A,0x3fb8aa3b)) |
| 86 | g=imul(ea,sp); g=(-g[1],-g[0]); decay=intervalexp(imul(g,point(0x3fb8aa3b))) |
| 87 | for ptr,bounds in ((p[4],decay),(p[5],beta)): intervals.append([ptr+4*i,*map(str,bounds)]) |
| 88 | bfout.append(p[5]+4*i) |
| 89 | return result('GDN decay/beta '+kind,image,p,sizes,(1,1),intervals=intervals,bfout=bfout) |
| 90 | |
| 91 | def rmsgate_case(kind): |
| 92 | sizes=(6144*4,128*4,6144*4,6144*4); image,p=alloc(sizes); intervals=[]; bfout=[] |
| 93 | weights=[round32(Fraction((i*3)%13+1,8)) for i in range(128)] |
| 94 | struct.pack_into('<128I',image,p[1],*weights) |
| 95 | for h in range(48): |
| 96 | x=[round32(Fraction((i*7+h*3)%31-15,16)) for i in range(128)] |
| 97 | z=[round32(Fraction((i*11+h*5)%37-18,7)) for i in range(128)] |
| 98 | if kind=='zero': x=[0]*128 |
| 99 | struct.pack_into('<128I',image,p[0]+h*512,*x); struct.pack_into('<128I',image,p[2]+h*512,*z) |
| 100 | lanes=[add(mul(x[i],x[i]),mul(x[i+64],x[i+64])) for i in range(64)] |
| 101 | for shift in (32,16,8,4,2,1): lanes=[add(lanes[i],lanes[i^shift]) for i in range(64)] |
| 102 | inv=rsqbound(finite(add(mul(lanes[0],0x3c000000),0x358637bd))) |
| 103 | for i,(a,w,gate) in enumerate(zip(x,weights,z)): |
| 104 | gate=bf16(gate)<<16 |
| 105 | norm=ibf(imul(point(a),inv)); weighted=ibf(imul(norm,point(w))) |
| 106 | output=ibf(imul(weighted,imul(point(gate),sigmoid(gate)))) |
| 107 | off=p[3]+h*512+4*i; intervals.append([off,*map(str,output)]); bfout.append(off) |
| 108 | return result('GDN norm-before-swish '+kind,image,p,sizes,(48,1),intervals=intervals,bfout=bfout) |
| 109 | |
| 110 | def logit_bits(i,kind): |
| 111 | b=round32(Fraction((i*17)%251-125,16)) |
| 112 | if kind=='negative': b=round32(Fraction(-1-(i%127),8)) |
| 113 | if kind=='ties' and i in (31,33,64,248319): b=0x42c80000 |
| 114 | if kind=='zeros': b=0x80000000 if i%2==0 else 0 |
| 115 | if kind=='nan' and i in (123,248319): b=0x7fc00001 |
| 116 | if kind=='last' and i==248319: b=0x42c80000 |
| 117 | return b |
| 118 | |
| 119 | def rank(bits): |
| 120 | # Independent numeric order, not the kernel's sign-bit transform. |
| 121 | if bits&0x7fffffff>0x7f800000: return (1,Fraction(0)) |
| 122 | return (0,finite(bits)) |
| 123 | |
| 124 | def orderkey(bits): |
| 125 | if bits&0x7fffffff>0x7f800000: return 0xffffffff |
| 126 | if bits&0x7fffffff==0: return 0x80000000 |
| 127 | return bits^ (0xffffffff if bits>>31 else 0x80000000) |
| 128 | |
| 129 | @lru_cache(None) |
| 130 | def partials(kind): |
| 131 | pairs=[] |
| 132 | for start in range(0,248320,64): |
| 133 | index=max(range(start,start+64),key=lambda i:rank(logit_bits(i,kind))) |
| 134 | pairs.append((orderkey(logit_bits(index,kind)),index)) |
| 135 | return pairs |
| 136 | |
| 137 | def argpart_case(kind): |
| 138 | sizes=(248320*4,3880*8); image,p=alloc(sizes) |
| 139 | struct.pack_into('<248320I',image,p[0],*(logit_bits(i,kind) for i in range(248320))) |
| 140 | exact=[] |
| 141 | for i,(key,index) in enumerate(partials(kind)): exact.extend(([p[1]+8*i,key,4],[p[1]+8*i+4,index,4])) |
| 142 | return result('argmax partial '+kind,image,p,sizes,(3880,1),exact) |
| 143 | |
| 144 | def argfinal_case(kind): |
| 145 | sizes=(3880*8,4); image,p=alloc(sizes) |
| 146 | for i,pair in enumerate(partials(kind)): struct.pack_into('<II',image,p[0]+8*i,*pair) |
| 147 | index=max(range(248320),key=lambda i:rank(logit_bits(i,kind))) |
| 148 | return result('argmax final '+kind,image,p,sizes,(1,1),[[p[1],index,4]]) |
| 149 | |
| 150 | SPECS=(('residual5120',residual_case,('cancel','varied'),('residual5120-no-round',)), |
| 151 | ('embed5120',embedding_case,('bits','varied'),('embed5120-low-bits',)), |
| 152 | ('gdnparams',params_case,('tails','varied'),('gdnparams-no-beta-round','gdnparams-wrong-decay')), |
| 153 | ('gdnrmsgate',rmsgate_case,('zero','varied'),('gdnrmsgate-no-norm-round','gdnrmsgate-no-swish','gdnrmsgate-no-z-round')), |
| 154 | ('argmax_part',argpart_case,('negative','zeros','nan','last','ties'),('argmax_part-wrong-tie',)), |
| 155 | ('argmax_final',argfinal_case,('negative','zeros','nan','last','ties'),('argmax_final-wrong-tie',))) |
| 156 | |
| 157 | def strip_round(text,tags): |
| 158 | lines=[]; skip=False |
| 159 | for line in text.splitlines(): |
| 160 | if line in ['# BF16_ROUND_'+tag for tag in tags]: skip=True |
| 161 | if not skip: lines.append(line) |
| 162 | if line in ['# END_BF16_ROUND_'+tag for tag in tags]: skip=False |
| 163 | return '\n'.join(lines)+'\n' |
| 164 | |
| 165 | def mutate(src,out): |
| 166 | for name,factory,parameters,controls in SPECS: |
| 167 | text=(src/(name+'.isa')).read_text() |
| 168 | for control in controls: |
| 169 | if control.endswith('no-round'): bad=strip_round(text,['OUTPUT']) |
| 170 | elif control.endswith('no-beta-round'): bad=strip_round(text,['BETA']) |
| 171 | elif control.endswith('no-norm-round'): bad=strip_round(text,['NORM_LOW','NORM_HIGH']) |
| 172 | elif control.endswith('no-z-round'): bad=strip_round(text,['Z_LOW','Z_HIGH']) |
| 173 | else: |
| 174 | old,new={ |
| 175 | # Corrupt the settled full-width result, not the D16 prefill. |
| 176 | 'embed5120-low-bits':('I 4 0x0f70 12','I 4 0x0f70 12\nI 5 129 8 8 21'), |
| 177 | 'gdnparams-wrong-decay':('I 8 275 32 19','I 8 242 1 19'), |
| 178 | 'gdnrmsgate-no-swish':('I 5 270 18 18 5','I 8 274 1 18'), |
| 179 | 'argmax_part-wrong-tie':('I 6 265 11 204','I 6 267 9 204'), |
| 180 | 'argmax_final-wrong-tie':('I 6 265 11 204','I 6 267 9 204'), |
| 181 | }[control] |
| 182 | assert old in text,control |
| 183 | bad=text.replace(old,new) |
| 184 | assert bad!=text,control |
| 185 | (out/(control+'.isa')).write_text(bad) |
| 186 | |
| 187 | def suite(exe,out): |
| 188 | for name,factory,parameters,controls in SPECS: |
| 189 | cases=[factory(arg) for arg in parameters] |
| 190 | for case in cases: |
| 191 | width=execute(exe,out/(name+'.text'),out,case) |
| 192 | actual=(out/'token.memory').read_bytes(); worst=Fraction(0) |
| 193 | for off,lo,hi in case['intervals']: |
| 194 | y=finite(struct.unpack_from('<I',actual,off)[0]); worst=max(worst,abs(y-(Fraction(lo)+Fraction(hi))/2)) |
| 195 | print(f'PASS {name} {case["label"]} interval_escapes=0 worst_midpoint_error={float(worst):.12g} widest_interval={width} exact/input/guards=PASS',flush=True) |
| 196 | for control in controls: |
| 197 | try: execute(exe,out/(control+'.text'),out,cases[-1]) |
| 198 | except AssertionError as e: |
| 199 | assert str(e).startswith('token mismatch'),e |
| 200 | print(f'CONTROL {control} CAUGHT {str(e).split(":")[0]}',flush=True) |
| 201 | else: raise AssertionError('control escaped '+control) |
| 202 | export(name,cases,controls,out,factory,[(p,) for p in parameters]) |
| 203 | |
| 204 | if __name__=='__main__': |
| 205 | if sys.argv[1]=='mutate': mutate(pathlib.Path(sys.argv[2]),pathlib.Path(sys.argv[3])) |
| 206 | elif sys.argv[1]=='controls': print(*(c for spec in SPECS for c in spec[3])) |
| 207 | elif sys.argv[1]=='suite': suite(sys.argv[2],pathlib.Path(sys.argv[3])) |
| 208 | else: raise SystemExit('unknown decode mode') |