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 / prep.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """Q27 preparation reference: Fraction instruction boundaries, Decimal model functions. |
| 4 | Test-only Python, not a runtime dependency. Reference and manual citations: PROVENANCE17. |
| 5 | """ |
| 6 | from decimal import Decimal, localcontext |
| 7 | from fractions import Fraction |
| 8 | from functools import lru_cache |
| 9 | import hashlib |
| 10 | import json |
| 11 | import pathlib |
| 12 | import random |
| 13 | import runpy |
| 14 | import struct |
| 15 | import subprocess |
| 16 | import sys |
| 17 | |
| 18 | ref = runpy.run_path(str(pathlib.Path(__file__).with_name('attention.py'))) |
| 19 | finite, round32, fma = [ref[n] for n in ('finite', 'round32', 'fma')] |
| 20 | add, mul, point, imul, iadd = [ref[n] for n in ('add', 'mul', 'point', 'imul', 'iadd')] |
| 21 | enclosure, expbound, intervalrcp = [ref[n] for n in ('enclosure', 'expbound', 'intervalrcp')] |
| 22 | ONE, EPS = 0x3f800000, 0x358637bd |
| 23 | POSITIONS = (0, 1, 63, 64, 65) |
| 24 | ROPE_POSITIONS = (0, 1, 63, 64, 65, 8191, 65535, 262143, 0xffffffff) |
| 25 | CONTROLS = ('no-one', 'wrong-pair', 'wrong-position', 'truncate-cache', 'extra-swish', 'wrong-gate-stride') |
| 26 | # WolframLanguageEvaluator N[Pi,125], independently filed in PROVENANCE17. |
| 27 | PI = Decimal('3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582') |
| 28 | |
| 29 | @lru_cache(None) |
| 30 | def rsqbound(x): |
| 31 | assert x > 0 |
| 32 | with localcontext() as ctx: |
| 33 | ctx.prec = 120 |
| 34 | result = 1 / (Decimal(x.numerator) / Decimal(x.denominator)).sqrt() |
| 35 | return enclosure(Fraction(result)) |
| 36 | |
| 37 | def rsqprobe(exe): |
| 38 | rng = random.Random(942197) |
| 39 | values = [rng.randrange(0x800000, 0x7f800000) for _ in range(4096)] |
| 40 | result = subprocess.run([exe], input=b''.join(struct.pack('<II',36,x) for x in values), capture_output=True, timeout=60) |
| 41 | assert result.returncode == 0 and result.stderr == b'' and len(result.stdout) == 4*len(values), result |
| 42 | for i, x in enumerate(values): |
| 43 | inside(struct.unpack_from('<I',result.stdout,4*i)[0],rsqbound(finite(x)),f'rsq[{x:x}]') |
| 44 | print(f'PASS RSQ manual-1ULP enclosing-oracle inputs={len(values)} Decimal-precision=120 seed=942197 FTZ') |
| 45 | |
| 46 | def inside(bits, interval, where): |
| 47 | assert bits & 0x7fffffff < 0x7f800000, f'prep mismatch {where}: nonfinite {bits:08x}' |
| 48 | assert interval[0] <= finite(bits) <= interval[1], f'prep mismatch {where}: {bits:08x} not in {interval}' |
| 49 | |
| 50 | @lru_cache(None) |
| 51 | def inverse_frequencies(): |
| 52 | with localcontext() as ctx: |
| 53 | ctx.prec = 120 |
| 54 | powers = [round32(Fraction(Decimal(10000000) ** (Decimal(i)/32))) for i in range(32)] |
| 55 | return tuple(round32(1/finite(p)) for p in powers) |
| 56 | |
| 57 | def frequency_check(exe): |
| 58 | result = subprocess.run([exe],capture_output=True,timeout=15) |
| 59 | expected = struct.pack('<32I',*inverse_frequencies()) |
| 60 | assert result.returncode == 0 and result.stderr == b'' and result.stdout == expected, 'rope frequency mismatch' |
| 61 | print('PASS rope inverse frequencies=32 bit-exact Decimal power -> RN32 -> reciprocal -> RN32') |
| 62 | |
| 63 | @lru_cache(None) |
| 64 | def rope_reference(position): |
| 65 | values = [] |
| 66 | with localcontext() as ctx: |
| 67 | ctx.prec = 120 |
| 68 | pf = finite(round32(Fraction(position))) |
| 69 | for freq in inverse_frequencies(): |
| 70 | angle = finite(round32(pf*finite(freq))) |
| 71 | x = Decimal(angle.numerator)/Decimal(angle.denominator) |
| 72 | # Independent high-precision argument reduction and sine/cosine power series. |
| 73 | n = int((x/(PI/2)+Decimal('0.5')).to_integral_value(rounding='ROUND_FLOOR')) |
| 74 | r = x-n*(PI/2) |
| 75 | sin, cos, st, ct = r, Decimal(1), r, Decimal(1) |
| 76 | for j in range(1,50): |
| 77 | st *= -r*r/((2*j)*(2*j+1)) |
| 78 | ct *= -r*r/((2*j)*(2*j-1)) |
| 79 | sin += st |
| 80 | cos += ct |
| 81 | cos, sin = [(cos,sin),(-sin,cos),(-cos,-sin),(sin,-cos)][n%4] |
| 82 | values.append((Fraction(cos),Fraction(sin))) |
| 83 | return [x[0] for x in values]+[x[1] for x in values] |
| 84 | |
| 85 | def rope_output(exe, position): |
| 86 | result = subprocess.run([exe], input=struct.pack('<I',position), capture_output=True, timeout=15) |
| 87 | assert result.returncode == 0 and result.stderr == b'' and len(result.stdout) == 256, result |
| 88 | return struct.unpack('<64I',result.stdout) |
| 89 | |
| 90 | def check_rope(exe, position): |
| 91 | output = rope_output(exe,position) |
| 92 | widest = Fraction(0) |
| 93 | for i,(bits,exact) in enumerate(zip(output,rope_reference(position))): |
| 94 | ulp = Fraction(2)**(max(1,(bits>>23)&255)-150) |
| 95 | # Binary64 reduction error allowance over the full u32 input range, plus final RN32. |
| 96 | # This is an absolute analytic check, not an allowance on the subsequent GPU execution. |
| 97 | allowance = ulp/2 + Fraction(1,1<<39) |
| 98 | error = abs(finite(bits)-exact) |
| 99 | assert error <= allowance, f'rope mismatch P={position} index={i} error={error} bound={allowance}' |
| 100 | widest = max(widest,error) |
| 101 | print(f'PASS rope P={position} cos/sin=64 Decimal-precision=120 max_absolute_error={float(widest):.9g}') |
| 102 | return output |
| 103 | |
| 104 | def rope_suite(exe): |
| 105 | for p in ROPE_POSITIONS: check_rope(exe,p) |
| 106 | for bad in (b'',b'\0'*3,b'\0'*5): |
| 107 | result = subprocess.run([exe],input=bad,capture_output=True,timeout=15) |
| 108 | assert result.returncode == 64 and result.stdout == b'' and result.stderr == b'', result |
| 109 | print('CONTROL rope-malformed-record CAUGHT lengths=0,3,5 exit=64 no-output') |
| 110 | |
| 111 | def normrope(x, weights, cs): |
| 112 | lanes = [0]*64 |
| 113 | for lane in range(64): |
| 114 | for j in range(4): lanes[lane] = fma(x[4*lane+j],x[4*lane+j],lanes[lane]) |
| 115 | for shift in (32,16,8,4,2,1): lanes = [add(lanes[i],lanes[i^shift]) for i in range(64)] |
| 116 | variance = add(mul(lanes[0],0x3b800000),EPS) |
| 117 | inv = rsqbound(finite(variance)) |
| 118 | result = [imul(imul(point(a),inv),point(add(ONE,w))) for a,w in zip(x,weights)] |
| 119 | before = result[:64] |
| 120 | for d in range(32): |
| 121 | negative = (-before[d+32][1],-before[d+32][0]) |
| 122 | result[d] = iadd(imul(before[d],point(cs[d])),imul(negative,point(cs[d+32]))) |
| 123 | result[d+32] = iadd(imul(before[d+32],point(cs[d])),imul(before[d],point(cs[d+32]))) |
| 124 | return result |
| 125 | |
| 126 | def bf16(bits): |
| 127 | if bits & 0x7fffffff > 0x7f800000: return 0x7fc0 |
| 128 | return ((bits + 0x7fff + ((bits>>16)&1)) >> 16) & 0xffff |
| 129 | |
| 130 | def fixture(p,cs): |
| 131 | cap = p+3 |
| 132 | sizes = (24*512*4,4*256*4,4*256*4,256*4,256*4,256,24*256*4,4*cap*256*2,4*cap*256*2) |
| 133 | pointers, end = [],128 |
| 134 | for size in sizes: |
| 135 | pointers.append(end) |
| 136 | end += size+32 |
| 137 | data = bytearray([0xa5])*end |
| 138 | struct.pack_into('<9QII',data,0,*pointers,p,cap) |
| 139 | q = [[round32(Fraction((h*11+d*7)%67-33,16)) for d in range(256)] for h in range(24)] |
| 140 | k = [[round32(Fraction((h*3+d*13)%71-35,16)) for d in range(256)] for h in range(4)] |
| 141 | special = [0,0x80000000,1,0x00010000,0x007fffff,0x3f808000,0x3f818000,0x7f800000,0xff800000,0x7f800001,0xffc01234] |
| 142 | values = [[special[(h*3+d)%len(special)] if d<32 else round32(Fraction((h+d)%19-9,8)) for d in range(256)] for h in range(4)] |
| 143 | qw = [round32(Fraction(d%7-3,16)) for d in range(256)] |
| 144 | kw = [round32(Fraction(d%11-5,32)) for d in range(256)] |
| 145 | for h,row in enumerate(q): struct.pack_into('<256I',data,pointers[0]+h*2048,*row) |
| 146 | for h,row in enumerate(k): struct.pack_into('<256I',data,pointers[1]+h*1024,*row) |
| 147 | for h,row in enumerate(values): struct.pack_into('<256I',data,pointers[2]+h*1024,*row) |
| 148 | struct.pack_into('<256I',data,pointers[3],*qw) |
| 149 | struct.pack_into('<256I',data,pointers[4],*kw) |
| 150 | struct.pack_into('<64I',data,pointers[5],*cs) |
| 151 | return data,pointers,q,k,values,qw,kw,cap |
| 152 | |
| 153 | def run(exe,code,path,data,x,y): |
| 154 | path.write_bytes(data) |
| 155 | result = subprocess.run([exe,str(code),str(path),str(x),str(y)],capture_output=True,timeout=120) |
| 156 | assert result.returncode == 0 and result.stderr == b'' and result.stdout == b'', result |
| 157 | return path.read_bytes() |
| 158 | |
| 159 | def prep_check(exe,rope,code,out,p,invalid=False): |
| 160 | cs = rope_output(rope,p) |
| 161 | data,ptr,q,k,values,qw,kw,cap = fixture(p,cs) |
| 162 | if invalid: struct.pack_into('<I',data,76,p) |
| 163 | actual = run(exe,code,out/'prep.memory',data,25*64,2) |
| 164 | if invalid: |
| 165 | assert actual == data, 'prep mismatch capacity guard wrote output' |
| 166 | print(f'PASS prep invalid-capacity P={p} no-output no-cache-write') |
| 167 | return |
| 168 | allowed = bytearray(len(data)) |
| 169 | widest, records, ambiguous = Fraction(0),[],0 |
| 170 | for h,row in enumerate(q): |
| 171 | intervals = normrope(row,qw,cs) |
| 172 | for d,interval in enumerate(intervals): |
| 173 | offset = ptr[6]+h*1024+d*4 |
| 174 | inside(struct.unpack_from('<I',actual,offset)[0],interval,f'Q[{h},{d}]') |
| 175 | widest = max(widest,interval[1]-interval[0]) |
| 176 | records.append(dict(head=h,dim=d,lower=str(interval[0]),upper=str(interval[1]),width=str(interval[1]-interval[0]))) |
| 177 | allowed[ptr[6]:ptr[6]+24*1024] = b'\1'*(24*1024) |
| 178 | for h,row in enumerate(k): |
| 179 | for d,interval in enumerate(normrope(row,kw,cs)): |
| 180 | bits, = struct.unpack_from('<H',actual,ptr[7]+(h*cap+p)*512+d*2) |
| 181 | lo,hi = (bf16(round32(x)) for x in interval) |
| 182 | ambiguous += lo != hi |
| 183 | inside(bits<<16,(min(finite(lo<<16),finite(hi<<16)),max(finite(lo<<16),finite(hi<<16))),f'K[{h},{d}]') |
| 184 | got = struct.unpack_from('<256H',actual,ptr[8]+(h*cap+p)*512) |
| 185 | assert got == tuple(map(bf16,values[h])),f'prep mismatch V BF16[{h}]' |
| 186 | for base in (ptr[7],ptr[8]): |
| 187 | offset = base+(h*cap+p)*512 |
| 188 | allowed[offset:offset+512] = b'\1'*512 |
| 189 | assert len(actual)==len(data) and all(a==b or allowed[i] for i,(a,b) in enumerate(zip(data,actual))), 'prep mismatch guard/input/history corruption' |
| 190 | (out/f'prep-intervals-P{p}.json').write_text(json.dumps(records,indent=2)+'\n') |
| 191 | print(f'PASS prep P={p} Q=24x256 K/V=4x256 rotary=64 all-history/guards BF16-specials widest_interval={widest} ambiguous_BF16={ambiguous}',flush=True) |
| 192 | |
| 193 | def gate_check(exe,code,out): |
| 194 | qp,ap,op = 64,64+24*2048+32,64+24*2048+32+24*1024+32 |
| 195 | data = bytearray([0xa5])*(op+24*1024+32) |
| 196 | struct.pack_into('<3Q',data,0,qp,ap,op) |
| 197 | inputs, gates = [],[] |
| 198 | for h in range(24): |
| 199 | x = [round32(Fraction((h*17+d*3)%37-18,8)) for d in range(256)] |
| 200 | g = [round32(Fraction((h*5+d*7)%41-20,4)) for d in range(256)] |
| 201 | g[:6] = [0,0x80000000,0x42c80000,0xc2c80000,0x7f800000,0xff800000] |
| 202 | struct.pack_into('<256I',data,qp+h*2048+1024,*g) |
| 203 | struct.pack_into('<256I',data,ap+h*1024,*x) |
| 204 | inputs.extend(x);gates.extend(g) |
| 205 | actual = run(exe,code,out/'gate.memory',data,97*64,2) |
| 206 | widest = Fraction(0) |
| 207 | for i,(x,g) in enumerate(zip(inputs,gates)): |
| 208 | exponent = mul((g & 0x7fffffff)|0x80000000,ref['LOG2E']) |
| 209 | t = expbound(exponent) |
| 210 | sig = intervalrcp(iadd(point(ONE),t)) |
| 211 | if g>>31: sig = imul(sig,t) |
| 212 | interval = imul(point(x),sig) |
| 213 | inside(struct.unpack_from('<I',actual,op+i*4)[0],interval,f'gate[{i}]') |
| 214 | widest = max(widest,interval[1]-interval[0]) |
| 215 | assert actual[:op] == data[:op] and actual[op+24*1024:] == data[op+24*1024:], 'prep mismatch gate guards/input' |
| 216 | print(f'PASS attention sigmoid gate packed=24x512 outputs={len(inputs)} signed-zero/extreme/inf widest_interval={widest}',flush=True) |
| 217 | |
| 218 | def mutate(src,out): |
| 219 | prep = (src/'attn256_prep.isa').read_text() |
| 220 | gate = (src/'attn256_gate.isa').read_text() |
| 221 | changes = {'no-one':(prep,'I 5 300 12 12 1','I 8 268 1 12'), |
| 222 | 'wrong-pair':(prep,'I 5 160 1 28 21','I 5 144 1 28 21'), |
| 223 | 'wrong-position':(prep,'I 5 22 4 4 25','I 5 128 4 4 25'), |
| 224 | 'truncate-cache':(prep,'L 32767','L 0'), |
| 225 | 'extra-swish':(gate,'I 7 0 0 2 0 0 28 0 6 9 127 0 0','I 5 264 9 9 5\nI 7 0 0 2 0 0 28 0 6 9 127 0 0'), |
| 226 | 'wrong-gate-stride':(gate,'I 5 139 2 2 18','I 5 138 2 2 18')} |
| 227 | assert tuple(changes) == CONTROLS |
| 228 | for name,(text,old,new) in changes.items(): |
| 229 | assert old in text,name |
| 230 | (out/f'prep-{name}.isa').write_text(text.replace(old,new)) |
| 231 | rope = (src/'rope.om').read_text() |
| 232 | assert '32.0f64' in rope |
| 233 | (out/'rope-wrong-dim.om').write_text(rope.replace('32.0f64','128.0f64')) |
| 234 | |
| 235 | def config_check(): |
| 236 | data = (pathlib.Path(__file__).parent/'model/qwen38-27b-fp8-config.json').read_bytes() |
| 237 | assert hashlib.sha256(data).hexdigest() == '74227dd615bf1ea975aa676bdf355a0379858c12f394b5365cd9dfa5fc2c70bc' |
| 238 | c = json.loads(data)['text_config'] |
| 239 | assert (c['num_attention_heads'],c['num_key_value_heads'],c['head_dim']) == (24,4,256) |
| 240 | assert c['rms_norm_eps'] == 1e-6 and c['attn_output_gate'] |
| 241 | assert EPS == struct.unpack('<I',struct.pack('<f',c['rms_norm_eps']))[0] |
| 242 | assert c['rope_parameters']['rope_theta'] == 10000000 |
| 243 | assert c['rope_parameters']['partial_rotary_factor'] * c['head_dim'] == 64 |
| 244 | assert c['rope_parameters']['mrope_section'] == [11,11,10] |
| 245 | print('PASS pinned Q27 config digest and compiled attention dimensions/norm/rotary contract') |
| 246 | |
| 247 | def suite(exe,rope,out): |
| 248 | config_check() |
| 249 | frequency_check(str(out/'ropefreq-probe')) |
| 250 | rope_suite(rope) |
| 251 | rsqprobe(str(out/'trans-probe')) |
| 252 | for p in POSITIONS: prep_check(exe,rope,out/'attn256_prep.text',out,p) |
| 253 | prep_check(exe,rope,out/'attn256_prep.text',out,1,True) |
| 254 | gate_check(exe,out/'attn256_gate.text',out) |
| 255 | for name in CONTROLS: |
| 256 | try: |
| 257 | if name in ('extra-swish','wrong-gate-stride'): gate_check(exe,out/f'prep-{name}.text',out) |
| 258 | else: prep_check(exe,rope,out/f'prep-{name}.text',out,1) |
| 259 | except AssertionError as error: |
| 260 | assert str(error).startswith('prep mismatch'),error |
| 261 | print(f'CONTROL prep-{name} CAUGHT {str(error).split(":")[0]}',flush=True) |
| 262 | else: raise AssertionError(f'control escaped {name}') |
| 263 | try: check_rope(str(out/'rope-wrong-dim'),1) |
| 264 | except AssertionError as error: |
| 265 | assert str(error).startswith('rope mismatch'),error |
| 266 | print('CONTROL rope-wrong-dim CAUGHT config rotary64 not256') |
| 267 | else: raise AssertionError('rope dimension control escaped') |
| 268 | print(f'PASS fused prep positions={",".join(map(str,POSITIONS))} prep_cases={len(POSITIONS)+1} gate_cases=1 rope_cases={len(ROPE_POSITIONS)} hardware=NOT_RUN') |
| 269 | |
| 270 | if __name__=='__main__': |
| 271 | if sys.argv[1]=='mutate': mutate(pathlib.Path(sys.argv[2]),pathlib.Path(sys.argv[3])) |
| 272 | else: suite(sys.argv[2],sys.argv[3],pathlib.Path(sys.argv[4])) |