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 / evidence / AMD-GFX942-COMPACT-SECTIONS / gdnconv4.py
| 1 | # Generated from canonical host fixture/oracle functions; no embedded memory images. |
| 2 | import base64,struct |
| 3 | from decimal import Decimal,localcontext |
| 4 | from fractions import Fraction |
| 5 | from functools import lru_cache |
| 6 | CHANNELS=10240 |
| 7 | LOG2E=1069066811 |
| 8 | ONE=1065353216 |
| 9 | def 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 |
| 29 | def bf16(bits): |
| 30 | if bits & 2147483647 > 2139095040: |
| 31 | return 32704 |
| 32 | return bits + 32767 + (bits >> 16 & 1) >> 16 & 65535 |
| 33 | def 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) |
| 40 | def 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)) |
| 54 | def rounded(x): |
| 55 | return finite(round32(x)) |
| 56 | @lru_cache(None) |
| 57 | def imul(a, b): |
| 58 | vals = [x * y for x in a for y in b] |
| 59 | return (rounded(min(vals)), rounded(max(vals))) |
| 60 | def point(bits): |
| 61 | x = finite(bits) |
| 62 | return (x, x) |
| 63 | def mul(a, b): |
| 64 | return fma(a, b, (a ^ b) & 2147483648) |
| 65 | def ftz(b): |
| 66 | return b & 2147483648 if b & 2147483647 < 8388608 else b |
| 67 | def nextdown(b): |
| 68 | if b == 0: |
| 69 | return 2147483649 |
| 70 | return b + 1 if b >> 31 else b - 1 |
| 71 | def nextup(b): |
| 72 | if b == 2147483648: |
| 73 | return 1 |
| 74 | return b - 1 if b >> 31 else b + 1 |
| 75 | def 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) |
| 88 | def 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) |
| 103 | def rcpbound(x): |
| 104 | assert x > 0 |
| 105 | return enclosure(1 / x) |
| 106 | def intervalrcp(a): |
| 107 | return (rcpbound(a[1])[0], rcpbound(a[0])[1]) |
| 108 | @lru_cache(None) |
| 109 | def iadd(a, b): |
| 110 | return (rounded(a[0] + b[0]), rounded(a[1] + b[1])) |
| 111 | @lru_cache(None) |
| 112 | def 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 |
| 117 | def 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)) |
| 154 | def _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. |
| 158 | No production dependency; the numerical intervals come from the host oracle. |
| 159 | """ |
| 160 | |
| 161 | def run_section(ctx): |
| 162 | import base64 |
| 163 | import ctypes as C |
| 164 | import struct |
| 165 | import time |
| 166 | from fractions import Fraction |
| 167 | p = _make_payload() |
| 168 | name = p['name'] |
| 169 | say, put, get = (ctx[k] for k in ('say', 'put', 'get')) |
| 170 | load, Params, launch = (ctx[k] for k in ('load', 'Params', 'launch')) |
| 171 | objects, controls = (ctx['objs'], ctx['controls']) |
| 172 | fn = load(objects[name], name) |
| 173 | owned = [] |
| 174 | |
| 175 | def alloc(data): |
| 176 | d = put(data) |
| 177 | owned.append(d) |
| 178 | return d |
| 179 | |
| 180 | def raw(case): |
| 181 | return base64.b64decode(case['memory']) |
| 182 | |
| 183 | def step(case, base, function=fn): |
| 184 | vals = [C.c_void_p(base.value + v) if kind == 'ptr' else C.c_uint32(v) for kind, v in case['args']] |
| 185 | return (function, case['gx'], case['gy'], Params(vals)) |
| 186 | |
| 187 | def check(actual, case): |
| 188 | before = raw(case) |
| 189 | assert len(actual) == len(before), 'notebook memory size mismatch' |
| 190 | unchanged = bytearray(actual) |
| 191 | widest = Fraction(0) |
| 192 | for off in case.get('bf16_outputs', []): |
| 193 | assert struct.unpack_from('<I', actual, off)[0] & 65535 == 0, f'{name} BF16 rounding mismatch offset={off}' |
| 194 | for off, lo, hi in case['intervals']: |
| 195 | bits = struct.unpack_from('<I', actual, off)[0] |
| 196 | x = struct.unpack('<f', struct.pack('<I', bits))[0] |
| 197 | lo, hi = (Fraction(lo), Fraction(hi)) |
| 198 | assert math.isfinite(x) and lo <= Fraction(x) <= hi, f'{name} interval mismatch offset={off} bits={bits:08x}' |
| 199 | widest = max(widest, hi - lo) |
| 200 | unchanged[off:off + 4] = before[off:off + 4] |
| 201 | for off, bits, width in case.get('exact', []): |
| 202 | assert int.from_bytes(actual[off:off + width], 'little') == bits, f'{name} exact mismatch offset={off}' |
| 203 | unchanged[off:off + width] = before[off:off + width] |
| 204 | assert unchanged == before, f'{name} input/guard corruption' |
| 205 | return widest |
| 206 | try: |
| 207 | for case in p['cases']: |
| 208 | d = alloc(raw(case)) |
| 209 | launch([step(case, d)]) |
| 210 | width = check(get(d, len(raw(case))), case) |
| 211 | say(f'PASS {name} {case['label']} every-output interval/exact inputs/guards widest_interval={width}') |
| 212 | case = dict(p['cases'][p['timing']]) |
| 213 | case['gx'], case['gy'] = case['timing_grid'] |
| 214 | image = raw(case) |
| 215 | d = alloc(image) |
| 216 | steps = [step(case, d)] |
| 217 | ev = ctx['event_ms'](steps) |
| 218 | warm = ctx['wall_ms']([steps]) |
| 219 | expected = get(d, len(image)) |
| 220 | width = check(expected, case) |
| 221 | copies = int(ctx['COLD_BYTES']) // case['input_bytes'] + 1 |
| 222 | cold = alloc(image * copies) |
| 223 | rotation = [[step(case, C.c_void_p(cold.value + i * len(image)))] for i in range(copies)] |
| 224 | cold_ms = ctx['wall_ms'](rotation) |
| 225 | observed = memoryview(get(cold, len(image) * copies)) |
| 226 | for i in range(copies): |
| 227 | assert observed[i * len(image):(i + 1) * len(image)] == expected, f'{name} cold output/guard mismatch copy={i}' |
| 228 | 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}') |
| 229 | for control in p['controls']: |
| 230 | bad = load(objects[control], name) |
| 231 | d = alloc(image) |
| 232 | launch([step(case, d, bad)]) |
| 233 | try: |
| 234 | check(get(d, len(image)), case) |
| 235 | except AssertionError: |
| 236 | controls[control] = True |
| 237 | say(f'CONTROL {control} CAUGHT') |
| 238 | else: |
| 239 | controls[control] = False |
| 240 | raise AssertionError(f'{control} escaped') |
| 241 | finally: |
| 242 | for d in reversed(owned): |
| 243 | ctx['chk'](ctx['hip'].hipFree(d), f'free {name} section') |
| 244 | try: |
| 245 | import torch |
| 246 | import torch.nn.functional as F |
| 247 | case = p['cases'][p['timing']] |
| 248 | image = raw(case) |
| 249 | |
| 250 | def tensor(off, n): |
| 251 | vals = struct.unpack_from('<' + str(n) + 'f', image, off) |
| 252 | return torch.tensor(vals, device='cuda', dtype=torch.float32) |
| 253 | n = 16 * 128 * 2 + 48 * 128 |
| 254 | x = tensor(case['args'][0][1], n).view(1, n, 1) |
| 255 | |
| 256 | def bfloat(off): |
| 257 | values = struct.unpack_from('<' + str(n * 4) + 'H', image, off) |
| 258 | words = struct.pack('<' + str(n * 4) + 'I', *(v << 16 for v in values)) |
| 259 | return torch.tensor(struct.unpack('<' + str(n * 4) + 'f', words), device='cuda', dtype=torch.bfloat16) |
| 260 | weight = bfloat(case['args'][1][1]).view(n, 1, 4) |
| 261 | old = bfloat(case['args'][2][1]).view(1, n, 4) |
| 262 | |
| 263 | def operation(): |
| 264 | state = torch.cat((old, x), dim=-1).to(weight.dtype) |
| 265 | new = state[:, :, -4:].clone() |
| 266 | out = F.silu(F.conv1d(state, weight, groups=n)[:, :, -1:]).float() |
| 267 | return (out, new) |
| 268 | operation() |
| 269 | torch.cuda.synchronize() |
| 270 | repetitions = ctx.get('NWALL', 200) |
| 271 | start = time.perf_counter() |
| 272 | for _ in range(repetitions): |
| 273 | reference = operation() |
| 274 | torch.cuda.synchronize() |
| 275 | elapsed = (time.perf_counter() - start) * 1000 / repetitions |
| 276 | for value in reference if isinstance(reference, tuple) else (reference,): |
| 277 | assert torch.isfinite(value).all().item() |
| 278 | dtype = 'BF16-conv/cache FP32-accum/output' |
| 279 | say(f'torch {name} (AMD library, not Omega) warm_wall_ms={elapsed:.6f} dtype={dtype}') |
| 280 | except ImportError: |
| 281 | say(f'torch {name} (AMD library, not Omega) NOT_RUN unavailable') |
| 282 | return True |