Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/CUDApp/blob/main/tests/amd-exec/attention.py # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `CUDApp / tests / amd-exec / attention.py` 231 lines · 10620 bytes Raw Blame History 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('