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 / gdnconv4.py

283 lines · 11980 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
6CHANNELS=10240
7LOG2E=1069066811
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 bf16(bits):
30 if bits & 2147483647 > 2139095040:
31 return 32704
32 return bits + 32767 + (bits >> 16 & 1) >> 16 & 65535
33def finite(bits):
34 exponent = bits >> 23 & 255
35 significand = bits & 8388607 | (8388608 if exponent else 0)
36 power = max(1, exponent) - 150
37 value = Fraction(significand) * Fraction(2) ** power
38 return -value if bits >> 31 else value
39@lru_cache(None)
40def fma(a, b, c):
41 ax, bx, cx = (x & 2147483647 for x in (a, b, c))
42 if max(ax, bx, cx) > 2139095040:
43 return 2143289344
44 product_sign = (a ^ b) & 2147483648
45 if ax == 2139095040 or bx == 2139095040:
46 if not ax or not bx or (cx == 2139095040 and product_sign != c & 2147483648):
47 return 2143289344
48 return product_sign | 2139095040
49 if cx == 2139095040:
50 return c
51 if (not ax or not bx) and (not cx):
52 return product_sign & c & 2147483648
53 return round32(finite(a) * finite(b) + finite(c))
54def rounded(x):
55 return finite(round32(x))
56@lru_cache(None)
57def imul(a, b):
58 vals = [x * y for x in a for y in b]
59 return (rounded(min(vals)), rounded(max(vals)))
60def point(bits):
61 x = finite(bits)
62 return (x, x)
63def mul(a, b):
64 return fma(a, b, (a ^ b) & 2147483648)
65def ftz(b):
66 return b & 2147483648 if b & 2147483647 < 8388608 else b
67def nextdown(b):
68 if b == 0:
69 return 2147483649
70 return b + 1 if b >> 31 else b - 1
71def nextup(b):
72 if b == 2147483648:
73 return 1
74 return b - 1 if b >> 31 else b + 1
75def enclosure(value):
76 center = round32(value)
77 exponent = max(1, center >> 23 & 255) - 150
78 ulp = Fraction(2) ** exponent
79 uncertainty = max(abs(value), Fraction(1)) * Fraction(1, 10 ** 100)
80 lower, upper = (value - ulp - uncertainty, value + ulp + uncertainty)
81 lo, hi = (round32(lower), round32(upper))
82 if finite(lo) > lower:
83 lo = nextdown(lo)
84 if finite(hi) < upper:
85 hi = nextup(hi)
86 return (finite(ftz(lo)), finite(ftz(hi)))
87@lru_cache(None)
88def expbound(bits):
89 bits = ftz(bits)
90 if bits == 4286578688:
91 return point(0)
92 if bits & 2147483647 == 0:
93 return point(ONE)
94 x = finite(bits)
95 if x < -126:
96 return point(0)
97 assert x < 128, 'reference only accepts finite softmax exponent range'
98 with localcontext() as ctx:
99 ctx.prec = 120
100 value = Decimal(2) ** (Decimal(x.numerator) / Decimal(x.denominator))
101 return enclosure(Fraction(value))
102@lru_cache(None)
103def rcpbound(x):
104 assert x > 0
105 return enclosure(1 / x)
106def intervalrcp(a):
107 return (rcpbound(a[1])[0], rcpbound(a[0])[1])
108@lru_cache(None)
109def iadd(a, b):
110 return (rounded(a[0] + b[0]), rounded(a[1] + b[1]))
111@lru_cache(None)
112def sigmoid(g):
113 exponent = mul(g & 2147483647 | 2147483648, LOG2E)
114 t = expbound(exponent)
115 answer = intervalrcp(iadd(point(ONE), t))
116 return imul(answer, t) if g >> 31 else answer
117def fixture(active, kind):
118 pointers = []
119 end = 64
120 for size in (CHANNELS * 4, CHANNELS * 8, CHANNELS * 8, CHANNELS * 8, CHANNELS * 4):
121 pointers.append(end)
122 end += size + 64
123 xp, wp, sp, np, op = pointers
124 image = bytearray([165]) * end
125 struct.pack_into('<5Q', image, 0, *pointers)
126 inputs = [round32(Fraction(i * 19 % 127 - 63, 32)) for i in range(CHANNELS)]
127 inputs[:8] = [1065385984, 1065451520, 3212869632, 3212935168, 1, 2147483649, 1120403456, 3267887104]
128 if kind == 'range':
129 inputs[8:12] = [2139095040, 4286578688, 2139099700, 4290777652]
130 struct.pack_into('<' + str(CHANNELS) + 'I', image, xp, *inputs)
131 intervals = []
132 exact = []
133 for c in range(CHANNELS):
134 weights = [bf16(round32(Fraction((c * 7 + j * 11) % 31 - 15, 16))) for j in range(4)]
135 old = [0 if kind == 'zero' else bf16(round32(Fraction((c * 17 + j * 5) % 61 - 30, 16))) for j in range(4)]
136 struct.pack_into('<4H', image, wp + c * 8, *weights)
137 struct.pack_into('<4H', image, sp + c * 8, *old)
138 if c >= active:
139 continue
140 new = old[1:] + [bf16(inputs[c])]
141 exact.extend(([np + c * 8 + j * 2, x, 2] for j, x in enumerate(new)))
142 total = 0
143 for a, w in zip(new, weights):
144 total = fma(a << 16, w << 16, total)
145 conv = bf16(total) << 16
146 if conv & 2147483647 >= 2139095040:
147 answer = 2139095040 if conv == 2139095040 else 2143289344
148 exact.append([op + c * 4, answer, 4])
149 else:
150 endpoints = imul(point(conv), sigmoid(conv))
151 ends = [finite(bf16(round32(x)) << 16) for x in endpoints]
152 intervals.append([op + c * 4, str(min(ends)), str(max(ends))])
153 return dict(label=f'channels={active}/{CHANNELS} taps=4 kind={kind}', memory=base64.b64encode(image).decode(), intervals=intervals, exact=exact, bf16_outputs=[v[0] for v in intervals], args=[['ptr', p] for p in pointers], gx=CHANNELS // 64 + 1 if active == CHANNELS else active // 64, gy=2, timing_grid=[CHANNELS // 64, 1], input_bytes=CHANNELS * (4 + 8 + 8))
154def _make_payload():
155 cases=[fixture(*args) for args in ((64, 'zero'), (128, 'range'), (10240, 'history'))]
156 return dict(name='gdnconv4',cases=cases,controls=['gdnconv4-no-input-round', 'gdnconv4-no-conv-round', 'gdnconv4-no-silu-round', 'gdnconv4-wrong-cache-shift'],timing=len(cases)-1)
157"""Test-only notebook instrument. token.py exports this with generated fixtures.
158No production dependency; the numerical intervals come from the host oracle.
159"""
160
161def run_section(ctx):
162 import base64
163 import ctypes as C
164 import math
165 import struct
166 import time
167 from fractions import Fraction
168 p = _make_payload()
169 name = p['name']
170 say, put, get = (ctx[k] for k in ('say', 'put', 'get'))
171 load, Params, launch = (ctx[k] for k in ('load', 'Params', 'launch'))
172 objects, controls = (ctx['objs'], ctx['controls'])
173 fn = load(objects[name], name)
174 owned = []
175
176 def alloc(data):
177 d = put(data)
178 owned.append(d)
179 return d
180
181 def raw(case):
182 return base64.b64decode(case['memory'])
183
184 def step(case, base, function=fn):
185 vals = [C.c_void_p(base.value + v) if kind == 'ptr' else C.c_uint32(v) for kind, v in case['args']]
186 return (function, case['gx'], case['gy'], Params(vals))
187
188 def check(actual, case):
189 before = raw(case)
190 assert len(actual) == len(before), 'notebook memory size mismatch'
191 unchanged = bytearray(actual)
192 widest = Fraction(0)
193 for off in case.get('bf16_outputs', []):
194 assert struct.unpack_from('<I', actual, off)[0] & 65535 == 0, f'{name} BF16 rounding mismatch offset={off}'
195 for off, lo, hi in case['intervals']:
196 bits = struct.unpack_from('<I', actual, off)[0]
197 x = struct.unpack('<f', struct.pack('<I', bits))[0]
198 lo, hi = (Fraction(lo), Fraction(hi))
199 assert math.isfinite(x) and lo <= Fraction(x) <= hi, f'{name} interval mismatch offset={off} bits={bits:08x}'
200 widest = max(widest, hi - lo)
201 unchanged[off:off + 4] = before[off:off + 4]
202 for off, bits, width in case.get('exact', []):
203 assert int.from_bytes(actual[off:off + width], 'little') == bits, f'{name} exact mismatch offset={off}'
204 unchanged[off:off + width] = before[off:off + width]
205 assert unchanged == before, f'{name} input/guard corruption'
206 return widest
207 try:
208 for case in p['cases']:
209 d = alloc(raw(case))
210 launch([step(case, d)])
211 width = check(get(d, len(raw(case))), case)
212 say(f'PASS {name} {case['label']} every-output interval/exact inputs/guards widest_interval={width}')
213 case = dict(p['cases'][p['timing']])
214 case['gx'], case['gy'] = case['timing_grid']
215 image = raw(case)
216 d = alloc(image)
217 steps = [step(case, d)]
218 ev = ctx['event_ms'](steps)
219 warm = ctx['wall_ms']([steps])
220 expected = get(d, len(image))
221 width = check(expected, case)
222 copies = int(ctx['COLD_BYTES']) // case['input_bytes'] + 1
223 cold = alloc(image * copies)
224 rotation = [[step(case, C.c_void_p(cold.value + i * len(image)))] for i in range(copies)]
225 cold_ms = ctx['wall_ms'](rotation)
226 observed = memoryview(get(cold, len(image) * copies))
227 for i in range(copies):
228 assert observed[i * len(image):(i + 1) * len(image)] == expected, f'{name} cold output/guard mismatch copy={i}'
229 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}')
230 for control in p['controls']:
231 bad = load(objects[control], name)
232 d = alloc(image)
233 launch([step(case, d, bad)])
234 try:
235 check(get(d, len(image)), case)
236 except AssertionError:
237 controls[control] = True
238 say(f'CONTROL {control} CAUGHT')
239 else:
240 controls[control] = False
241 raise AssertionError(f'{control} escaped')
242 finally:
243 for d in reversed(owned):
244 ctx['chk'](ctx['hip'].hipFree(d), f'free {name} section')
245 try:
246 import torch
247 import torch.nn.functional as F
248 case = p['cases'][p['timing']]
249 image = raw(case)
250
251 def tensor(off, n):
252 vals = struct.unpack_from('<' + str(n) + 'f', image, off)
253 return torch.tensor(vals, device='cuda', dtype=torch.float32)
254 n = 16 * 128 * 2 + 48 * 128
255 x = tensor(case['args'][0][1], n).view(1, n, 1)
256
257 def bfloat(off):
258 values = struct.unpack_from('<' + str(n * 4) + 'H', image, off)
259 words = struct.pack('<' + str(n * 4) + 'I', *(v << 16 for v in values))
260 return torch.tensor(struct.unpack('<' + str(n * 4) + 'f', words), device='cuda', dtype=torch.bfloat16)
261 weight = bfloat(case['args'][1][1]).view(n, 1, 4)
262 old = bfloat(case['args'][2][1]).view(1, n, 4)
263
264 def operation():
265 state = torch.cat((old, x), dim=-1).to(weight.dtype)
266 new = state[:, :, -4:].clone()
267 out = F.silu(F.conv1d(state, weight, groups=n)[:, :, -1:]).float()
268 return (out, new)
269 operation()
270 torch.cuda.synchronize()
271 repetitions = ctx.get('NWALL', 200)
272 start = time.perf_counter()
273 for _ in range(repetitions):
274 reference = operation()
275 torch.cuda.synchronize()
276 elapsed = (time.perf_counter() - start) * 1000 / repetitions
277 for value in reference if isinstance(reference, tuple) else (reference,):
278 assert torch.isfinite(value).all().item()
279 dtype = 'BF16-conv/cache FP32-accum/output'
280 say(f'torch {name} (AMD library, not Omega) warm_wall_ms={elapsed:.6f} dtype={dtype}')
281 except ImportError:
282 say(f'torch {name} (AMD library, not Omega) NOT_RUN unavailable')
283 return True