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-NOTEBOOK-IMPORTS / rmsnorm5120.py

239 lines · 10125 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 math
133 import struct
134 import time
135 from fractions import Fraction
136 p = _make_payload()
137 name = p['name']
138 say, put, get = (ctx[k] for k in ('say', 'put', 'get'))
139 load, Params, launch = (ctx[k] for k in ('load', 'Params', 'launch'))
140 objects, controls = (ctx['objs'], ctx['controls'])
141 fn = load(objects[name], name)
142 owned = []
143
144 def alloc(data):
145 d = put(data)
146 owned.append(d)
147 return d
148
149 def raw(case):
150 return base64.b64decode(case['memory'])
151
152 def step(case, base, function=fn):
153 vals = [C.c_void_p(base.value + v) if kind == 'ptr' else C.c_uint32(v) for kind, v in case['args']]
154 return (function, case['gx'], case['gy'], Params(vals))
155
156 def check(actual, case):
157 before = raw(case)
158 assert len(actual) == len(before), 'notebook memory size mismatch'
159 unchanged = bytearray(actual)
160 widest = Fraction(0)
161 for off in case.get('bf16_outputs', []):
162 assert struct.unpack_from('<I', actual, off)[0] & 65535 == 0, f'{name} BF16 rounding mismatch offset={off}'
163 for off, lo, hi in case['intervals']:
164 bits = struct.unpack_from('<I', actual, off)[0]
165 x = struct.unpack('<f', struct.pack('<I', bits))[0]
166 lo, hi = (Fraction(lo), Fraction(hi))
167 assert math.isfinite(x) and lo <= Fraction(x) <= hi, f'{name} interval mismatch offset={off} bits={bits:08x}'
168 widest = max(widest, hi - lo)
169 unchanged[off:off + 4] = before[off:off + 4]
170 for off, bits, width in case.get('exact', []):
171 assert int.from_bytes(actual[off:off + width], 'little') == bits, f'{name} exact mismatch offset={off}'
172 unchanged[off:off + width] = before[off:off + width]
173 assert unchanged == before, f'{name} input/guard corruption'
174 return widest
175 try:
176 for case in p['cases']:
177 d = alloc(raw(case))
178 launch([step(case, d)])
179 width = check(get(d, len(raw(case))), case)
180 say(f'PASS {name} {case['label']} every-output interval/exact inputs/guards widest_interval={width}')
181 case = dict(p['cases'][p['timing']])
182 case['gx'], case['gy'] = case['timing_grid']
183 image = raw(case)
184 d = alloc(image)
185 steps = [step(case, d)]
186 ev = ctx['event_ms'](steps)
187 warm = ctx['wall_ms']([steps])
188 expected = get(d, len(image))
189 width = check(expected, case)
190 copies = int(ctx['COLD_BYTES']) // case['input_bytes'] + 1
191 cold = alloc(image * copies)
192 rotation = [[step(case, C.c_void_p(cold.value + i * len(image)))] for i in range(copies)]
193 cold_ms = ctx['wall_ms'](rotation)
194 observed = memoryview(get(cold, len(image) * copies))
195 for i in range(copies):
196 assert observed[i * len(image):(i + 1) * len(image)] == expected, f'{name} cold output/guard mismatch copy={i}'
197 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}')
198 for control in p['controls']:
199 bad = load(objects[control], name)
200 d = alloc(image)
201 launch([step(case, d, bad)])
202 try:
203 check(get(d, len(image)), case)
204 except AssertionError:
205 controls[control] = True
206 say(f'CONTROL {control} CAUGHT')
207 else:
208 controls[control] = False
209 raise AssertionError(f'{control} escaped')
210 finally:
211 for d in reversed(owned):
212 ctx['chk'](ctx['hip'].hipFree(d), f'free {name} section')
213 try:
214 import torch
215 import torch.nn.functional as F
216 case = p['cases'][p['timing']]
217 image = raw(case)
218
219 def tensor(off, n):
220 vals = struct.unpack_from('<' + str(n) + 'f', image, off)
221 return torch.tensor(vals, device='cuda', dtype=torch.float32)
222 n = 5120
223 x, w = (tensor(case['args'][j][1], n) for j in (0, 1))
224 operation = lambda: x * torch.rsqrt(x.square().mean() + 1e-06) * (1 + w)
225 operation()
226 torch.cuda.synchronize()
227 repetitions = ctx.get('NWALL', 200)
228 start = time.perf_counter()
229 for _ in range(repetitions):
230 reference = operation()
231 torch.cuda.synchronize()
232 elapsed = (time.perf_counter() - start) * 1000 / repetitions
233 for value in reference if isinstance(reference, tuple) else (reference,):
234 assert torch.isfinite(value).all().item()
235 dtype = 'FP32'
236 say(f'torch {name} (AMD library, not Omega) warm_wall_ms={elapsed:.6f} dtype={dtype}')
237 except ImportError:
238 say(f'torch {name} (AMD library, not Omega) NOT_RUN unavailable')
239 return True