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