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/prep.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 / prep.py` 272 lines · 14264 bytes Raw Blame History 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(' 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('>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('>31: sig = imul(sig,t) 212 interval = imul(point(x),sig) 213 inside(struct.unpack_from('