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 / gdn.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """GDN query/key normalization and FP32 recurrent-state reference instruments.""" |
| 4 | import base64 |
| 5 | from fractions import Fraction |
| 6 | from decimal import Decimal,localcontext |
| 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,rsqbound,execute,export=(ref[n] for n in ('finite','round32','mul','add','point','imul','rsqbound','execute','export')) |
| 15 | bf16=ref['ref']['bf16'] |
| 16 | QSCALE=0x3db504f3 |
| 17 | EPS=bf16(0x358637bd)<<16 |
| 18 | with localcontext() as context: |
| 19 | context.prec=120 |
| 20 | assert round32(Fraction(Decimal(1)/Decimal(128).sqrt()))==QSCALE |
| 21 | QK_CASES=((1,'zero'),(2,'basis'),(32,'varied')) |
| 22 | STATE_CASES=((1,'zero'),(1,'no-beta'),(1,'no-decay'),(16,'dense')) |
| 23 | QK_CONTROLS=('gdnqknorm-no-qscale','gdnqknorm-wrong-epsilon','gdnqknorm-drop-upper','gdnqknorm-no-norm-round') |
| 24 | STATE_CONTROLS=('gdnstate-no-decay','gdnstate-no-beta','gdnstate-wrong-key-head','gdnstate-wrong-row-stride','gdnstate-no-core-round') |
| 25 | |
| 26 | def ibf16(value): |
| 27 | return tuple(finite(bf16(round32(x))<<16) for x in value) |
| 28 | |
| 29 | |
| 30 | def qk_fixture(active,kind): |
| 31 | xp,op=64,64+4096*4+64 |
| 32 | image=bytearray([0xa5])*(op+4096*4+64) |
| 33 | struct.pack_into('<2Q',image,0,xp,op) |
| 34 | intervals=[] |
| 35 | for head in range(32): |
| 36 | x=[round32(Fraction((i*7+head*3)%37-18,16)) for i in range(128)] |
| 37 | if kind=='zero': x=[0]*128 |
| 38 | elif kind=='basis': x=[0x3f800000 if i==head else 0 for i in range(128)] |
| 39 | else: x[:4]=[0,0x80000000,0x00010000,0x80010000] |
| 40 | struct.pack_into('<128I',image,xp+head*512,*x) |
| 41 | if head>=active: continue |
| 42 | lanes=[add(bf16(mul(x[i],x[i]))<<16,bf16(mul(x[i+64],x[i+64]))<<16) for i in range(64)] |
| 43 | for shift in (32,16,8,4,2,1): lanes=[add(lanes[i],lanes[i^shift]) for i in range(64)] |
| 44 | variance=bf16(add(bf16(lanes[0])<<16,EPS))<<16 |
| 45 | inv=ibf16(rsqbound(finite(variance))) |
| 46 | for i,bits in enumerate(x): |
| 47 | value=ibf16(imul(point(bits),inv)) |
| 48 | if head<16: value=imul(value,point(QSCALE)) |
| 49 | intervals.append([op+head*512+i*4,str(value[0]),str(value[1])]) |
| 50 | return dict(label=f'qk_heads={active}/32 D=128 kind={kind}',memory=base64.b64encode(image).decode(), |
| 51 | intervals=intervals,args=[['ptr',xp],['ptr',op]],gx=33 if active==32 else active,gy=2, |
| 52 | timing_grid=[32,1],input_bytes=4096*4) |
| 53 | |
| 54 | |
| 55 | def qk_value(key,row,query): |
| 56 | negative=(row*3+key)%4<2 |
| 57 | return (0x3c000000 if query else QSCALE) | (0x80000000 if negative else 0) |
| 58 | |
| 59 | |
| 60 | def state_scalars(head,kind): |
| 61 | decay=0 if kind=='no-decay' else (0x3f400000,0x3f000000)[head%2] |
| 62 | beta=0 if kind=='no-beta' else (0x3e800000,0x3f000000,0x3f400000)[head%3] |
| 63 | return decay,beta |
| 64 | |
| 65 | |
| 66 | @lru_cache(None) |
| 67 | def state_head(head,kind): |
| 68 | # Test values repeat after12 heads; every physical head/state word is still checked. |
| 69 | key=head//3 |
| 70 | old=[0 if kind=='zero' else round32(Fraction((r*7+c*13+(head%4)*17)%31-15,256)) for r in range(128) for c in range(128)] |
| 71 | values=[round32(Fraction((c*11+head*3)%29-14,16)) for c in range(128)] |
| 72 | decay,beta=state_scalars(head,kind) |
| 73 | new=[mul(a,decay) for a in old] |
| 74 | kv=[0]*128 |
| 75 | for r in range(128): |
| 76 | k=qk_value(key,r,False) |
| 77 | for c in range(128): kv[c]=add(kv[c],mul(new[r*128+c],k)) |
| 78 | delta=[mul(add(v,a^0x80000000),beta) for v,a in zip(values,kv)] |
| 79 | output=[0]*128 |
| 80 | for r in range(128): |
| 81 | k,q=qk_value(key,r,False),qk_value(key,r,True) |
| 82 | for c in range(128): |
| 83 | i=r*128+c |
| 84 | new[i]=add(new[i],mul(k,delta[c])) |
| 85 | output[c]=add(output[c],mul(new[i],q)) |
| 86 | return old,values,new,[bf16(b)<<16 for b in output] |
| 87 | |
| 88 | |
| 89 | def state_fixture(keys,kind): |
| 90 | sizes=(4096*4,48*128*4,48*128*128*4,48*128*128*4,48*128*4,48*4,48*4) |
| 91 | pointers=[]; end=64 |
| 92 | for size in sizes: pointers.append(end); end+=size+64 |
| 93 | qp,vp,sp,np,op,dp,bp=pointers |
| 94 | image=bytearray([0xa5])*end |
| 95 | struct.pack_into('<7Q',image,0,*pointers) |
| 96 | for key in range(16): |
| 97 | for part in range(2): |
| 98 | bits=[qk_value((key%4),r,part==0) for r in range(128)] |
| 99 | struct.pack_into('<128I',image,qp+(part*16+key)*512,*bits) |
| 100 | exact=[] |
| 101 | for head in range(48): |
| 102 | old,values,new,output=state_head(head%12,kind) |
| 103 | struct.pack_into('<16384I',image,sp+head*65536,*old) |
| 104 | struct.pack_into('<128I',image,vp+head*512,*values) |
| 105 | decay,beta=state_scalars(head,kind) |
| 106 | struct.pack_into('<I',image,dp+head*4,decay) |
| 107 | struct.pack_into('<I',image,bp+head*4,beta) |
| 108 | if head>=keys*3: continue |
| 109 | exact.extend([np+head*65536+i*4,b,4] for i,b in enumerate(new)) |
| 110 | exact.extend([op+head*512+i*4,b,4] for i,b in enumerate(output)) |
| 111 | return dict(label=f'value_heads={keys*3}/48 state=128x128 kind={kind}',memory=base64.b64encode(image).decode(), |
| 112 | intervals=[],exact=exact,args=[['ptr',p] for p in pointers],gx=4,gy=17 if keys==16 else keys, |
| 113 | timing_grid=[3,16],input_bytes=sizes[0]+sizes[1]+sizes[2]+sizes[5]+sizes[6]) |
| 114 | |
| 115 | |
| 116 | def mutate(src,out): |
| 117 | qk=(src/'gdnqknorm.isa').read_text() |
| 118 | changes=((QK_CONTROLS[0],'L '+str(QSCALE),'L '+str(0x3f800000)), |
| 119 | (QK_CONTROLS[1],'L '+str(EPS),'L '+str(0x3f800000)), |
| 120 | (QK_CONTROLS[2],'I 5 265 9 11 5','I 5 264 8 11 5')) |
| 121 | for name,old,new in changes: |
| 122 | assert old in qk,name |
| 123 | (out/(name+'.isa')).write_text(qk.replace(old,new)) |
| 124 | state=(src/'gdnstate.isa').read_text() |
| 125 | changes=((STATE_CONTROLS[0],'I 5 276 16 16 5','I 8 272 1 16'), |
| 126 | (STATE_CONTROLS[1],'I 5 277 18 18 5','I 8 274 1 18'), |
| 127 | (STATE_CONTROLS[2],'I 2 3 137 29 28','I 2 2 137 29 28'), |
| 128 | (STATE_CONTROLS[3],'L 512','L 256')) |
| 129 | for name,old,new in changes: |
| 130 | assert old in state,name |
| 131 | (out/(name+'.isa')).write_text(state.replace(old,new,1)) |
| 132 | for name,source,tags in ((QK_CONTROLS[-1],qk,('NORM0','NORM1')),(STATE_CONTROLS[-1],state,('CORE0','CORE1'))): |
| 133 | lines=source.splitlines(); result=[]; skip=False |
| 134 | for line in lines: |
| 135 | if any(line=='# BF16_ROUND_'+tag for tag in tags): skip=True |
| 136 | if not skip: result.append(line) |
| 137 | if any(line=='# END_BF16_ROUND_'+tag for tag in tags): skip=False |
| 138 | (out/(name+'.isa')).write_text('\n'.join(result)+'\n') |
| 139 | |
| 140 | |
| 141 | def suite(exe,out): |
| 142 | for name,parameters,factory,controls in (('gdnqknorm',QK_CASES,qk_fixture,QK_CONTROLS),('gdnstate',STATE_CASES,state_fixture,STATE_CONTROLS)): |
| 143 | cases=[factory(*args) for args in parameters] |
| 144 | for case in cases: |
| 145 | widest=execute(exe,out/(name+'.text'),out,case) |
| 146 | worst=ref['midpoint_error']((out/'token.memory').read_bytes(),case) |
| 147 | print(f'PASS {name} {case["label"]} interval_escapes=0 worst_midpoint_error={float(worst):.12g} every-output/state all-inputs/guards widest_interval={widest}',flush=True) |
| 148 | for control in controls: |
| 149 | try: execute(exe,out/(control+'.text'),out,cases[-1]) |
| 150 | except AssertionError as error: |
| 151 | assert str(error).startswith('token mismatch'),error |
| 152 | print(f'CONTROL {control} CAUGHT {str(error).split(":")[0]}',flush=True) |
| 153 | else: raise AssertionError('control escaped '+control) |
| 154 | export(name,cases,controls,out,factory,parameters) |
| 155 | |
| 156 | |
| 157 | if __name__=='__main__': |
| 158 | if sys.argv[1]=='mutate': mutate(pathlib.Path(sys.argv[2]),pathlib.Path(sys.argv[3])) |
| 159 | elif sys.argv[1]=='suite': suite(sys.argv[2],pathlib.Path(sys.argv[3])) |
| 160 | elif sys.argv[1]=='controls': print(*QK_CONTROLS,*STATE_CONTROLS) |
| 161 | else: raise SystemExit('unknown GDN mode') |