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 / attention.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Independent Fraction RN-even + Decimal transcendental enclosure; test instrument only. |
| 4 | CDNA3 PDF pp195-196 permit 1ULP for EXP/RCP, not device-identical transcendental bits. |
| 5 | Each arithmetic interval is rounded at the SAME instruction boundary as the kernel. |
| 6 | """ |
| 7 | from decimal import Decimal, localcontext |
| 8 | from fractions import Fraction |
| 9 | from functools import lru_cache |
| 10 | import json |
| 11 | import pathlib |
| 12 | import runpy |
| 13 | import struct |
| 14 | import subprocess |
| 15 | import sys |
| 16 | |
| 17 | ref = runpy.run_path(str(pathlib.Path(__file__).with_name('sgemm.py'))) |
| 18 | finite, round32 = ref['finite'], ref['round32'] |
| 19 | fma = lru_cache(None)(ref['fma']) |
| 20 | SHAPES = (0, 1, 2, 63, 64, 65, 129) |
| 21 | ONE, SCALE, LOG2E = 0x3f800000, 0x3d800000, 0x3fb8aa3b |
| 22 | |
| 23 | def add(a, b): return fma(a, ONE, b) |
| 24 | def mul(a, b): return fma(a, b, (a ^ b) & 0x80000000) |
| 25 | def sub(a, b): return add(a, b ^ 0x80000000) |
| 26 | def point(bits): |
| 27 | x = finite(bits) |
| 28 | return x, x |
| 29 | |
| 30 | def rounded(x): return finite(round32(x)) |
| 31 | @lru_cache(None) |
| 32 | def imul(a, b): |
| 33 | vals = [x*y for x in a for y in b] |
| 34 | return rounded(min(vals)), rounded(max(vals)) |
| 35 | @lru_cache(None) |
| 36 | def iadd(a, b): return rounded(a[0]+b[0]), rounded(a[1]+b[1]) |
| 37 | @lru_cache(None) |
| 38 | def ifma(a, b, c): |
| 39 | vals = [x*y for x in a for y in b] |
| 40 | return rounded(min(vals)+c[0]), rounded(max(vals)+c[1]) |
| 41 | |
| 42 | def nextup(b): |
| 43 | if b == 0x80000000: return 1 |
| 44 | return b-1 if b >> 31 else b+1 |
| 45 | |
| 46 | def nextdown(b): |
| 47 | if b == 0: return 0x80000001 |
| 48 | return b+1 if b >> 31 else b-1 |
| 49 | |
| 50 | def ftz(b): return b & 0x80000000 if b & 0x7fffffff < 0x800000 else b |
| 51 | |
| 52 | def enclosure(value): |
| 53 | # Decimal uncertainty is far below binary32. Enclose its final rounding and |
| 54 | # the ln/pow working precision, then enclose the ISA's absolute 1ULP allowance. |
| 55 | center = round32(value) |
| 56 | exponent = max(1, (center >> 23) & 255) - 150 |
| 57 | ulp = Fraction(2) ** exponent |
| 58 | uncertainty = max(abs(value), Fraction(1)) * Fraction(1, 10**100) |
| 59 | lower, upper = value-ulp-uncertainty, value+ulp+uncertainty |
| 60 | lo, hi = round32(lower), round32(upper) |
| 61 | if finite(lo) > lower: lo = nextdown(lo) |
| 62 | if finite(hi) < upper: hi = nextup(hi) |
| 63 | # Outward rounding is conservative: this is an enclosing interval, not a |
| 64 | # claim that every representable value inside is a legal hardware answer. |
| 65 | return finite(ftz(lo)), finite(ftz(hi)) |
| 66 | |
| 67 | @lru_cache(None) |
| 68 | def expbound(bits): |
| 69 | bits = ftz(bits) |
| 70 | if bits == 0xff800000: return point(0) |
| 71 | if bits & 0x7fffffff == 0: return point(ONE) # manual functional example |
| 72 | x = finite(bits) |
| 73 | if x < -126: return point(0) |
| 74 | assert x < 128, 'reference only accepts finite softmax exponent range' |
| 75 | with localcontext() as ctx: |
| 76 | ctx.prec = 120 |
| 77 | value = Decimal(2) ** (Decimal(x.numerator)/Decimal(x.denominator)) |
| 78 | return enclosure(Fraction(value)) |
| 79 | |
| 80 | @lru_cache(None) |
| 81 | def rcpbound(x): |
| 82 | assert x > 0 |
| 83 | return enclosure(1/x) |
| 84 | |
| 85 | def intervalrcp(a): |
| 86 | return rcpbound(a[1])[0], rcpbound(a[0])[1] |
| 87 | |
| 88 | def fixture(t, sensitive=False): |
| 89 | cap, tiles = t+3, (t+63)//64 |
| 90 | qptr = 64 |
| 91 | kptr = qptr + 24*256*4 + 32 |
| 92 | vptr = kptr + 4*cap*256*2 + 32 |
| 93 | pptr = vptr + 4*cap*256*2 + 32 |
| 94 | optr = pptr + 24*tiles*1040 + 32 |
| 95 | memory = bytearray([0xa5])*(optr+24*256*4+64) |
| 96 | struct.pack_into('<5QII', memory, 0, qptr, kptr, vptr, pptr, optr, t, cap) |
| 97 | q = [[round32(Fraction(((h*3+d*7)%17)-8, 8)) for d in range(256)] for h in range(24)] |
| 98 | k = [[[round32(Fraction(((g*13+n*3+d*5)%19)-9, 8)) for d in range(256)] for n in range(cap)] for g in range(4)] |
| 99 | v = [[[round32(Fraction(((g*11+n*7+d*3)%23)-11, 16)) for d in range(256)] for n in range(cap)] for g in range(4)] |
| 100 | if sensitive: |
| 101 | q = [[0x41800000]*256 for _ in range(24)] |
| 102 | k = [[[round32(Fraction(16+(n%2))) for _ in range(256)] for n in range(cap)] for _ in range(4)] |
| 103 | for h in range(24): struct.pack_into('<256I', memory, qptr+h*1024, *q[h]) |
| 104 | for g in range(4): |
| 105 | for n in range(cap): |
| 106 | for ptr, values in [(kptr,k), (vptr,v)]: |
| 107 | assert all(x & 65535 == 0 for x in values[g][n]) |
| 108 | struct.pack_into('<256H', memory, ptr+(g*cap+n)*512, *(x>>16 for x in values[g][n])) |
| 109 | return memory, q, k, v, pptr, optr, tiles |
| 110 | |
| 111 | @lru_cache(None) |
| 112 | def dot(q, k): |
| 113 | lanes = [0]*64 |
| 114 | for lane in range(64): |
| 115 | for j in range(4): lanes[lane] = fma(q[4*lane+j], k[4*lane+j], lanes[lane]) |
| 116 | for shift in (32,16,8,4,2,1): lanes = [add(lanes[i], lanes[i^shift]) for i in range(64)] |
| 117 | return mul(lanes[0], SCALE) |
| 118 | |
| 119 | def maxima(a,b): |
| 120 | if a == 0xff800000: return b |
| 121 | return a if finite(a) >= finite(b) else b |
| 122 | |
| 123 | def weights(old, new, score): |
| 124 | return expbound(mul(sub(old,new),LOG2E)), expbound(mul(sub(score,new),LOG2E)) |
| 125 | |
| 126 | def oracle(t,q,k,v): |
| 127 | partials, outputs = [], [] |
| 128 | for h in range(24): |
| 129 | rows = [] |
| 130 | for start in range(0,t,64): |
| 131 | m, den, acc = 0xff800000, point(0), [point(0)]*256 |
| 132 | for token in range(start,min(t,start+64)): |
| 133 | score = dot(tuple(q[h]),tuple(k[h//6][token])) |
| 134 | nxt = maxima(m,score) |
| 135 | alpha,beta = weights(m,nxt,score) |
| 136 | den = iadd(imul(den,alpha),beta) |
| 137 | acc = [ifma(beta,point(value),imul(a,alpha)) for a,value in zip(acc,v[h//6][token])] |
| 138 | m = nxt |
| 139 | rows.append((m,den,acc)) |
| 140 | partials.append(rows) |
| 141 | m,den,acc = 0xff800000,point(0),[point(0)]*256 |
| 142 | for pm,pden,pacc in rows: |
| 143 | nxt = maxima(m,pm) |
| 144 | alpha,beta = weights(m,nxt,pm) |
| 145 | den = ifma(beta,pden,imul(den,alpha)) |
| 146 | acc = [ifma(beta,p,imul(a,alpha)) for a,p in zip(acc,pacc)] |
| 147 | m = nxt |
| 148 | outputs.append([imul(a,intervalrcp(den)) for a in acc] if t else acc) |
| 149 | return partials,outputs |
| 150 | |
| 151 | def inside(actual, interval, label): |
| 152 | assert actual & 0x7fffffff < 0x7f800000, f'attention mismatch {label}: nonfinite {actual:08x}' |
| 153 | value = finite(actual) |
| 154 | assert interval[0] <= value <= interval[1], f'attention mismatch {label}: {actual:08x} outside {interval}' |
| 155 | |
| 156 | def check(exe, part, merge, out, t, sensitive=False): |
| 157 | data,q,k,v,pp,op,tiles = fixture(t,sensitive) |
| 158 | partials,expected = oracle(t,q,k,v) |
| 159 | path = out/'attention.memory' |
| 160 | path.write_bytes(data) |
| 161 | for text,x,y in [(part,(tiles+1)*64,25),(merge,64,25)]: |
| 162 | p = subprocess.run([exe,str(text),str(path),str(x),str(y)],capture_output=True,timeout=600) |
| 163 | assert p.returncode == 0 and not p.stdout and not p.stderr, p |
| 164 | actual = path.read_bytes() |
| 165 | allowed = bytearray(len(data)) |
| 166 | for h,rows in enumerate(partials): |
| 167 | for tile,(m,den,acc) in enumerate(rows): |
| 168 | base = pp+(h*tiles+tile)*1040 |
| 169 | assert struct.unpack_from('<I',actual,base)[0] == m, 'attention mismatch maximum' |
| 170 | inside(struct.unpack_from('<I',actual,base+4)[0],den,'partial denominator') |
| 171 | allowed[base:base+8] = b'\1'*8 |
| 172 | for d,interval in enumerate(acc): |
| 173 | inside(struct.unpack_from('<I',actual,base+16+d*4)[0],interval,'partial accumulator') |
| 174 | allowed[base+16:base+1040] = b'\1'*1024 |
| 175 | intervals = [] |
| 176 | widest = Fraction(0) |
| 177 | for h in range(24): |
| 178 | for d,interval in enumerate(expected[h]): |
| 179 | offset = op+(h*256+d)*4 |
| 180 | inside(struct.unpack_from('<I',actual,offset)[0],interval,f'output[{h},{d}]') |
| 181 | width = interval[1]-interval[0] |
| 182 | widest = max(widest,width) |
| 183 | intervals.append(dict(head=h,dim=d,lower=str(interval[0]),upper=str(interval[1]),width=str(width))) |
| 184 | allowed[op:op+24*1024] = b'\1'*(24*1024) |
| 185 | assert len(data)==len(actual) and all(a==b or allowed[i] for i,(a,b) in enumerate(zip(data,actual))), 'attention guard/input corruption' |
| 186 | (out/f'attention-intervals-T{t}-sensitive{int(sensitive)}.json').write_text(json.dumps(intervals,indent=2)+'\n') |
| 187 | print(f'PASS attention T={t} capacity={t+3} heads=24 KV=4 dim=256 sensitive={int(sensitive)} every-output/manual-interval all-guards widest_interval={widest} widest_float={float(widest):.9g}',flush=True) |
| 188 | |
| 189 | def mutate(source,out): |
| 190 | text = source.read_text() |
| 191 | changes = {'no-max':('I 5 272 18 19 11','I 8 128 1 19'), |
| 192 | 'wrong-gqa':('I 2 20 134 28 1','I 2 20 133 28 1'), |
| 193 | 'v-from-k':('I 7 0 0 2 0 0 21 0 4 0 127 0 24','I 7 0 0 2 0 0 21 0 2 0 127 0 24')} |
| 194 | for name,(old,new) in changes.items(): |
| 195 | assert text.count(old)==1,(name,text.count(old)) |
| 196 | (out/f'attention-{name}.isa').write_text(text.replace(old,new)) |
| 197 | |
| 198 | def suite(exe,out): |
| 199 | part,merge = out/'attn256_part.text',out/'attn256_merge.text' |
| 200 | for t in SHAPES: check(exe,part,merge,out,t) |
| 201 | check(exe,part,merge,out,2,True) |
| 202 | for name in ('no-max','wrong-gqa','v-from-k'): |
| 203 | try: check(exe,out/f'attention-{name}.text',merge,out,2,name=='no-max') |
| 204 | except AssertionError as error: |
| 205 | assert str(error).startswith('attention mismatch'),error |
| 206 | print(f'CONTROL attention-{name} CAUGHT {str(error).split(":")[0]}',flush=True) |
| 207 | else: raise AssertionError(f'control escaped {name}') |
| 208 | print(f'PASS attention cases={len(SHAPES)+1} T={",".join(map(str,SHAPES))} scale=1/16 tile=64 order=lane4,XOR32..1,online,tile-ascending hardware=NOT_RUN') |
| 209 | |
| 210 | def transprobe(exe): |
| 211 | import random |
| 212 | rng = random.Random(942195) |
| 213 | exp_inputs = [round32(Fraction(i, 16)) for i in range(-2016, 2017)] |
| 214 | exp_inputs += [round32(Fraction(rng.randrange(-1250000, 1260001), 10000)) for _ in range(4096)] |
| 215 | rcp_inputs = [rng.randrange(0x800000, 0x7f800000) for _ in range(4096)] |
| 216 | records = [(32,b) for b in exp_inputs] + [(34,b) for b in rcp_inputs] |
| 217 | result = subprocess.run([exe], input=b''.join(struct.pack('<II',op,b) for op,b in records), |
| 218 | capture_output=True, timeout=60) |
| 219 | assert result.returncode==0 and result.stderr==b'' and len(result.stdout)==4*len(records), result |
| 220 | for i,(op,b) in enumerate(records): |
| 221 | actual, = struct.unpack_from('<I',result.stdout,i*4) |
| 222 | interval = expbound(b) if op==32 else rcpbound(finite(b)) |
| 223 | inside(actual,interval,f'trans opcode={op} input={b:08x}') |
| 224 | print(f'PASS EXP/RCP manual-1ULP enclosing-oracle inputs={len(records)} Decimal-precision=120 seed=942195 FTZ',flush=True) |
| 225 | |
| 226 | if __name__=='__main__': |
| 227 | mode = sys.argv[1] |
| 228 | if mode=='mutate': mutate(pathlib.Path(sys.argv[2]),pathlib.Path(sys.argv[3])) |
| 229 | elif mode=='one': check(sys.argv[2],pathlib.Path(sys.argv[3]),pathlib.Path(sys.argv[4]),pathlib.Path(sys.argv[5]),int(sys.argv[6])) |
| 230 | elif mode=='transprobe': transprobe(sys.argv[2]) |
| 231 | else: suite(sys.argv[2],pathlib.Path(sys.argv[3])) |