interplane.Get Omega
Read in your language

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

branch main Branches Tags History

CUDApp / evidence / AMD-GFX942-COMPACT-SECTIONS / rmsnorm5120.py

238 lines · 10109 bytes Raw Blame History
1# Generated from canonical host fixture/oracle functions; no embedded memory images.
2import base64,struct
3from decimal import Decimal,localcontext
4from fractions import Fraction
5from functools import lru_cache
6EPS=897988541
7MEAN=961334477
8ONE=1065353216
9def round32(value):
10 if not value:
11 return 0
12 sign = 2147483648 if value < 0 else 0
13 value = abs(value)
14 e = value.numerator.bit_length() - value.denominator.bit_length()
15 if value < Fraction(2) ** e:
16 e -= 1
17 quantum = max(-149, e - 23)
18 scaled = value / Fraction(2) ** quantum
19 q, r = divmod(scaled.numerator, scaled.denominator)
20 if 2 * r > scaled.denominator or (2 * r == scaled.denominator and q & 1):
21 q += 1
22 if q == 1 << 24:
23 q >>= 1
24 quantum += 1
25 if quantum > 104:
26 return sign | 2139095040
27 exponent = quantum + 150 if q >= 1 << 23 else 0
28 return sign | exponent << 23 | q & 8388607
29def finite(bits):
30 exponent = bits >> 23 & 255
31 significand = bits & 8388607 | (8388608 if exponent else 0)
32 power = max(1, exponent) - 150
33 value = Fraction(significand) * Fraction(2) ** power
34 return -value if bits >> 31 else value
35@lru_cache(None)
36def fma(a, b, c):
37 ax, bx, cx = (x & 2147483647 for x in (a, b, c))
38 if max(ax, bx, cx) > 2139095040:
39 return 2143289344
40 product_sign = (a ^ b) & 2147483648
41 if ax == 2139095040 or bx == 2139095040:
42 if not ax or not bx or (cx == 2139095040 and product_sign != c & 2147483648):
43 return 2143289344
44 return product_sign | 2139095040
45 if cx == 2139095040:
46 return c
47 if (not ax or not bx) and (not cx):
48 return product_sign & c & 2147483648
49 return round32(finite(a) * finite(b) + finite(c))
50def mul(a, b):
51 return fma(a, b, (a ^ b) & 2147483648)
52def add(a, b):
53 return fma(a, ONE, b)
54def nextdown(b):
55 if b == 0:
56 return 2147483649
57 return b + 1 if b >> 31 else b - 1
58def nextup(b):
59 if b == 2147483648:
60 return 1
61 return b - 1 if b >> 31 else b + 1
62def ftz(b):
63 return b & 2147483648 if b & 2147483647 < 8388608 else b
64def enclosure(value):
65 center = round32(value)
66 exponent = max(1, center >> 23 & 255) - 150
67 ulp = Fraction(2) ** exponent
68 uncertainty = max(abs(value), Fraction(1)) * Fraction(1, 10 ** 100)
69 lower, upper = (value - ulp - uncertainty, value + ulp + uncertainty)
70 lo, hi = (round32(lower), round32(upper))
71 if finite(lo) > lower:
72 lo = nextdown(lo)
73 if finite(hi) < upper:
74 hi = nextup(hi)
75 return (finite(ftz(lo)), finite(ftz(hi)))
76@lru_cache(None)
77def rsqbound(x):
78 assert x > 0
79 with localcontext() as ctx:
80 ctx.prec = 120
81 result = 1 / (Decimal(x.numerator) / Decimal(x.denominator)).sqrt()
82 return enclosure(Fraction(result))
83def rounded(x):
84 return finite(round32(x))
85@lru_cache(None)
86def imul(a, b):
87 vals = [x * y for x in a for y in b]
88 return (rounded(min(vals)), rounded(max(vals)))
89def point(bits):
90 x = finite(bits)
91 return (x, x)
92def fixture(rows, kind):
93 xp, wp, op = (64, 64 + rows * 5120 * 4 + 64, 64 + rows * 5120 * 4 + 64 + 5120 * 4 + 64)
94 image = bytearray([165]) * (op + rows * 5120 * 4 + 64)
95 struct.pack_into('<3QI', image, 0, xp, wp, op, rows)
96 weights = [round32(Fraction(i * 19 % 67 - 33, 32)) for i in range(5120)]
97 struct.pack_into('<5120I', image, wp, *weights)
98 intervals = []
99 for row in range(rows):
100 x = [round32(Fraction((i * 17 + row * 5) % 97 - 48, 16)) for i in range(5120)]
101 if kind == 'zero':
102 x = [0] * 5120
103 elif kind == 'large':
104 x = [mul(v, 1124073472) for v in x]
105 else:
106 x[:4] = [0, 2147483648, 1, 2147483649]
107 struct.pack_into('<5120I', image, xp + row * 5120 * 4, *x)
108 lanes = [0] * 64
109 for lane in range(64):
110 for chunk in range(20):
111 for j in range(4):
112 a = x[chunk * 256 + lane * 4 + j]
113 lanes[lane] = fma(a, a, lanes[lane])
114 for shift in (32, 16, 8, 4, 2, 1):
115 lanes = [add(lanes[i], lanes[i ^ shift]) for i in range(64)]
116 variance = add(mul(lanes[0], MEAN), EPS)
117 inv = rsqbound(finite(variance))
118 for i, (a, w) in enumerate(zip(x, weights)):
119 lo, hi = imul(imul(point(a), inv), point(add(ONE, w)))
120 intervals.append([op + (row * 5120 + i) * 4, str(lo), str(hi)])
121 return dict(label=f'rows={rows} hidden=5120 kind={kind}', memory=base64.b64encode(image).decode(), intervals=intervals, args=[['ptr', xp], ['ptr', wp], ['ptr', op], ['u32', rows]], gx=rows + 1, gy=2, input_bytes=(rows + 1) * 5120 * 4 + 4, timing_grid=[max(1, rows), 1])
122def _make_payload():
123 cases=[fixture(*args) for args in ((0, 'varied'), (1, 'zero'), (2, 'varied'), (3, 'large'), (1, 'varied'))]
124 return dict(name='rmsnorm5120',cases=cases,controls=['rmsnorm5120-no-one', 'rmsnorm5120-wrong-mean', 'rmsnorm5120-dropped-chunk'],timing=len(cases)-1)
125"""Test-only notebook instrument. token.py exports this with generated fixtures.
126No production dependency; the numerical intervals come from the host oracle.
127"""
128
129def run_section(ctx):
130 import base64
131 import ctypes as C
132 import struct
133 import time
134 from fractions import Fraction
135 p = _make_payload()
136 name = p['name']
137 say, put, get = (ctx[k] for k in ('say', 'put', 'get'))
138 load, Params, launch = (ctx[k] for k in ('load', 'Params', 'launch'))
139 objects, controls = (ctx['objs'], ctx['controls'])
140 fn = load(objects[name], name)
141 owned = []
142
143 def alloc(data):
144 d = put(data)
145 owned.append(d)
146 return d
147
148 def raw(case):
149 return base64.b64decode(case['memory'])
150
151 def step(case, base, function=fn):
152 vals = [C.c_void_p(base.value + v) if kind == 'ptr' else C.c_uint32(v) for kind, v in case['args']]
153 return (function, case['gx'], case['gy'], Params(vals))
154
155 def check(actual, case):
156 before = raw(case)
157 assert len(actual) == len(before), 'notebook memory size mismatch'
158 unchanged = bytearray(actual)
159 widest = Fraction(0)
160 for off in case.get('bf16_outputs', []):
161 assert struct.unpack_from('<I', actual, off)[0] & 65535 == 0, f'{name} BF16 rounding mismatch offset={off}'
162 for off, lo, hi in case['intervals']:
163 bits = struct.unpack_from('<I', actual, off)[0]
164 x = struct.unpack('<f', struct.pack('<I', bits))[0]
165 lo, hi = (Fraction(lo), Fraction(hi))
166 assert math.isfinite(x) and lo <= Fraction(x) <= hi, f'{name} interval mismatch offset={off} bits={bits:08x}'
167 widest = max(widest, hi - lo)
168 unchanged[off:off + 4] = before[off:off + 4]
169 for off, bits, width in case.get('exact', []):
170 assert int.from_bytes(actual[off:off + width], 'little') == bits, f'{name} exact mismatch offset={off}'
171 unchanged[off:off + width] = before[off:off + width]
172 assert unchanged == before, f'{name} input/guard corruption'
173 return widest
174 try:
175 for case in p['cases']:
176 d = alloc(raw(case))
177 launch([step(case, d)])
178 width = check(get(d, len(raw(case))), case)
179 say(f'PASS {name} {case['label']} every-output interval/exact inputs/guards widest_interval={width}')
180 case = dict(p['cases'][p['timing']])
181 case['gx'], case['gy'] = case['timing_grid']
182 image = raw(case)
183 d = alloc(image)
184 steps = [step(case, d)]
185 ev = ctx['event_ms'](steps)
186 warm = ctx['wall_ms']([steps])
187 expected = get(d, len(image))
188 width = check(expected, case)
189 copies = int(ctx['COLD_BYTES']) // case['input_bytes'] + 1
190 cold = alloc(image * copies)
191 rotation = [[step(case, C.c_void_p(cold.value + i * len(image)))] for i in range(copies)]
192 cold_ms = ctx['wall_ms'](rotation)
193 observed = memoryview(get(cold, len(image) * copies))
194 for i in range(copies):
195 assert observed[i * len(image):(i + 1) * len(image)] == expected, f'{name} cold output/guard mismatch copy={i}'
196 say(f'{name} {case['label']} event_ms={ev:.6f} warm_wall_ms={warm:.6f} cold_wall_ms={cold_ms:.6f} copies={copies} input_bytes={copies * case['input_bytes']} every-timed-output=PASS guards=PASS widest_interval={width}')
197 for control in p['controls']:
198 bad = load(objects[control], name)
199 d = alloc(image)
200 launch([step(case, d, bad)])
201 try:
202 check(get(d, len(image)), case)
203 except AssertionError:
204 controls[control] = True
205 say(f'CONTROL {control} CAUGHT')
206 else:
207 controls[control] = False
208 raise AssertionError(f'{control} escaped')
209 finally:
210 for d in reversed(owned):
211 ctx['chk'](ctx['hip'].hipFree(d), f'free {name} section')
212 try:
213 import torch
214 import torch.nn.functional as F
215 case = p['cases'][p['timing']]
216 image = raw(case)
217
218 def tensor(off, n):
219 vals = struct.unpack_from('<' + str(n) + 'f', image, off)
220 return torch.tensor(vals, device='cuda', dtype=torch.float32)
221 n = 5120
222 x, w = (tensor(case['args'][j][1], n) for j in (0, 1))
223 operation = lambda: x * torch.rsqrt(x.square().mean() + 1e-06) * (1 + w)
224 operation()
225 torch.cuda.synchronize()
226 repetitions = ctx.get('NWALL', 200)
227 start = time.perf_counter()
228 for _ in range(repetitions):
229 reference = operation()
230 torch.cuda.synchronize()
231 elapsed = (time.perf_counter() - start) * 1000 / repetitions
232 for value in reference if isinstance(reference, tuple) else (reference,):
233 assert torch.isfinite(value).all().item()
234 dtype = 'FP32'
235 say(f'torch {name} (AMD library, not Omega) warm_wall_ms={elapsed:.6f} dtype={dtype}')
236 except ImportError:
237 say(f'torch {name} (AMD library, not Omega) NOT_RUN unavailable')
238 return True