Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/CUDApp/blob/main/tests/models/mxfmt-check.py # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `CUDApp / tests / models / mxfmt-check.py` 617 lines · 24739 bytes Raw Blame History 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 3 """Verification-only oracle for fp8.om, nvfp4.om and mxdot.om; never runtime. 4 5 References, each independent of the candidate's bit operations: 6 spec : OCP OFP8 rev 1.0 (2023-12-01) section 5.1 value formulas, Table 2 7 rows and section 5.2.1 / Table 3 conversion rules, evaluated with 8 exact rationals (fractions.Fraction). 9 ml : ml_dtypes (float8_e4m3fn, float8_e5m2, float4_e2m1fn), the 10 published OCP-format implementation used by JAX. 11 exact : Fraction sums for the block dot products; binary64 sequential sums. 12 Needs numpy and ml_dtypes; the versions are printed with the receipt. 13 """ 14 import argparse 15 import hashlib 16 import math 17 from fractions import Fraction 18 from pathlib import Path 19 import struct 20 import subprocess 21 import tempfile 22 23 import ml_dtypes 24 import numpy as np 25 26 PIN = '`2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f`' 27 ROOT = Path(__file__).resolve().parents[2] 28 UNITS = ROOT / 'native/models' 29 TESTS = ROOT / 'tests/models' 30 QNAN = 0x7FC00000 31 F4 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) # OCP MX v1.0 Table 5 (E2M1) 32 U = Fraction(1, 2 ** 53) 33 34 35 class Fail(Exception): 36 pass 37 38 39 def need(cond, what): 40 if not cond: 41 raise Fail(what) 42 43 44 # ---------------------------------------------------------------- build/run 45 def build(compiler, parts, target): 46 src = b''.join(parts) 47 r = subprocess.run([compiler], input=src, capture_output=True, timeout=120) 48 if r.returncode or r.stderr: 49 raise Fail(f'compile rc={r.returncode} {r.stderr.decode()!r}') 50 target.write_bytes(r.stdout) 51 target.chmod(0o700) 52 return str(target) 53 54 55 def run(exe, data, timeout=600): 56 r = subprocess.run([exe], input=data, capture_output=True, timeout=timeout) 57 return r.returncode, r.stdout 58 59 60 def fmtcall(exe, ops, aux, vals): 61 rec = np.zeros((len(vals), 6), np.uint8) 62 rec[:, 0] = ops 63 rec[:, 1] = aux 64 rec[:, 2:] = np.asarray(vals, '> mb) & ((1 << eb) - 1) 82 m = code & ((1 << mb) - 1) 83 if fmt == 'e4m3' and e == 15 and m == 7: 84 return 'nan' 85 if fmt == 'e5m2' and e == 31: 86 return ('inf', s) if m == 0 else 'nan' 87 if e == 0: 88 return s * Fraction(m, 1 << mb) * Fraction(2) ** (1 - bias) 89 return s * (1 + Fraction(m, 1 << mb)) * Fraction(2) ** (e - bias) 90 91 92 TABLE2 = { # OFP8 Table 2 rows (magnitudes), checked against spec_value 93 'e4m3': {0x7E: Fraction(448), 0x08: Fraction(1, 2 ** 6), 94 0x07: Fraction(7, 8) / 2 ** 6, 0x01: Fraction(1, 2 ** 9)}, 95 'e5m2': {0x7B: Fraction(57344), 0x04: Fraction(1, 2 ** 14), 96 0x03: Fraction(3, 4) / 2 ** 14, 0x01: Fraction(1, 2 ** 16)}, 97 } 98 MAXCODE = {'e4m3': 0x7E, 'e5m2': 0x7B} 99 OVF = {'e4m3': 0x7F, 'e5m2': 0x7C} # non-saturating overflow code 100 NANC = {'e4m3': 0x7F, 'e5m2': 0x7E} # NaN source code (sign kept) 101 102 103 def f32bits(x): 104 return struct.unpack('> mb) - bias - mb) 140 nxt = top + ulp # next value, unbounded exponent 141 nxt_even = ((MAXCODE[fmt] + 1) & 1) == 0 # its mantissa parity 142 if (MAXCODE[fmt] & ((1 << mb) - 1)) == (1 << mb) - 1: 143 nxt_even = True # carry into a new binade: M = 0 144 mags = [v for v, _ in vals] 145 146 def enc(xb, sat): 147 s = (xb >> 24) & 128 148 a = xb & 0x7FFFFFFF 149 if a > 0x7F800000: 150 return s | NANC[fmt] 151 if a == 0x7F800000: 152 return s | (MAXCODE[fmt] if sat else OVF[fmt]) 153 x = Fraction(bitsf32(a)) 154 if x > nxt or (x == nxt) or (x > top and (x - top > nxt - x or 155 (x - top == nxt - x and nxt_even))): 156 return s | (MAXCODE[fmt] if sat else OVF[fmt]) 157 lo, hi = 0, len(mags) - 1 158 while lo < hi: # first mag >= x 159 mid = (lo + hi) // 2 160 if mags[mid] >= x: 161 hi = mid 162 else: 163 lo = mid + 1 164 c = lo 165 if mags[c] == x: 166 return s | c 167 below, above = c - 1, c 168 db, da = x - mags[below], mags[above] - x 169 if db < da or (db == da and below % 2 == 0): 170 return s | below 171 return s | above 172 return enc 173 174 175 # ---------------------------------------------------------------- ml oracle 176 MLT = {'e4m3': ml_dtypes.float8_e4m3fn, 'e5m2': ml_dtypes.float8_e5m2} 177 178 179 def ml_decode_table(fmt): 180 vals = np.arange(256, dtype=np.uint8).view(MLT[fmt]).astype(np.float64) 181 out = {} 182 for c, v in enumerate(vals): 183 if math.isnan(v): 184 out[c] = 'nan' 185 elif math.isinf(v): 186 out[c] = ('inf', -1 if v < 0 else 1) 187 else: 188 out[c] = Fraction(v) if not (v == 0 and math.copysign(1, v) < 0) else -Fraction(0) 189 return out 190 191 192 def ml_encode(fmt, xbits, sat): 193 x = np.asarray(xbits, np.uint32).view(np.float32) 194 with np.errstate(invalid='ignore'): # NaN inputs cast to NaN codes 195 c = x.astype(MLT[fmt]).view(np.uint8).astype(np.uint32) 196 if sat: 197 a = np.asarray(xbits, np.uint32) & 0x7FFFFFFF 198 notnan = a <= 0x7F800000 199 mag = c & 127 200 over = notnan & ((mag == OVF[fmt]) | ((fmt == 'e4m3') & (mag == 0x7F))) 201 c = np.where(over, (c & 128) | MAXCODE[fmt], c) 202 return c 203 204 205 def sweep_bits(): 206 """Stated sweep: every sign, every binary32 exponent field, every pattern 207 of the top 12 mantissa bits, low 11 bits in {0,1,0x3FF,0x400,0x401,0x7FF}.""" 208 s = np.arange(2, dtype=np.uint32) << 31 209 e = np.arange(256, dtype=np.uint32) << 23 210 t = np.arange(4096, dtype=np.uint32) << 11 211 lo = np.array([0, 1, 0x3FF, 0x400, 0x401, 0x7FF], np.uint32) 212 return (s[:, None, None, None] | e[None, :, None, None] | 213 t[None, None, :, None] | lo[None, None, None, :]).ravel() 214 215 216 def bf16_bits(): 217 return (np.arange(65536, dtype=np.uint32) << 16) 218 219 220 # ---------------------------------------------------------------- FP8 checks 221 def check_fp8(exe, flip=False): 222 n = 0 223 for op, fmt in ((0, 'e4m3'), (1, 'e5m2')): 224 spec = {c: spec_value(fmt, c) for c in range(256)} 225 ml = ml_decode_table(fmt) 226 for c in range(256): # the two references agree 227 a, b = spec[c], ml[c] 228 need(a == b if not isinstance(a, Fraction) else 229 (isinstance(b, Fraction) and a == b), f'{fmt} ref disagree {c}') 230 for c, mag in TABLE2[fmt].items(): 231 need(spec[c] == mag and spec[c | 128] == -mag, f'{fmt} Table 2 row {c:#x}') 232 if flip and fmt == 'e4m3': 233 ml[0x38] = Fraction(9, 8) # negative control: 1.0 -> 1.125 234 exp = [expected_decode(fmt, c, ml) for c in range(256)] 235 got = fmtcall(exe, op, 0, range(256)) 236 bad = [c for c in range(256) if int(got[c]) != exp[c]] 237 need(not bad, f'{fmt} decode mismatch codes {bad[:8]}') 238 n += 256 239 return n 240 241 242 def check_fp8_encode(exe, mutated=False): 243 counts = {} 244 sweep = sweep_bits() 245 bf = bf16_bits() 246 for fmt, op in (('e4m3', 2), ('e5m2', 3)): 247 enc = spec_encoder(fmt) 248 for sat in (0, 1): 249 # exact-rational spec oracle over every bfloat16 input 250 exp = np.array([enc(int(b), sat) for b in bf], np.uint32) 251 got = fmtcall(exe, op, sat, bf) 252 bad = np.nonzero(got != exp)[0] 253 need(len(bad) == 0, f'{fmt} sat={sat} spec mismatch at {[hex(int(bf[i])) for i in bad[:4]]}') 254 mlx = ml_encode(fmt, bf, sat) 255 need(np.array_equal(mlx, exp), f'{fmt} sat={sat} spec and ml_dtypes disagree') 256 # ml_dtypes over the structured binary32 sweep 257 got = fmtcall(exe, op, sat, sweep) 258 exp2 = ml_encode(fmt, sweep, sat) 259 bad = np.nonzero(got != exp2)[0] 260 need(len(bad) == 0, f'{fmt} sat={sat} sweep mismatch at {[hex(int(sweep[i])) for i in bad[:4]]}') 261 counts[(fmt, sat)] = len(bf) + len(sweep) 262 # round trip: every finite code decodes and re-encodes to itself 263 dec = fmtcall(exe, op - 2, 0, range(256)) 264 back = fmtcall(exe, op, sat, dec) 265 for c in range(256): 266 v = spec_value(fmt, c) 267 if v == 'nan': 268 want = (c & 128) | NANC[fmt] 269 elif isinstance(v, tuple): 270 want = (c & 128) | (MAXCODE[fmt] if sat else OVF[fmt]) 271 else: 272 want = c 273 need(int(back[c]) == want, f'{fmt} sat={sat} round trip {c:#x} -> {int(back[c]):#x}') 274 return counts 275 276 277 # ---------------------------------------------------------------- NVFP4 278 def e2m1(n): 279 v = Fraction(F4[n & 7]).limit_denominator(2) 280 return -v if n & 8 else v 281 282 283 def ue4m3(c): 284 return spec_value('e4m3', c) 285 286 287 def check_nvfp4(exe): 288 # decode: every element x valid scale pair, against ml_dtypes product 289 nib = np.repeat(np.arange(16, dtype=np.uint32), 127) 290 sc = np.tile(np.arange(127, dtype=np.uint32), 16) 291 got = fmtcall(exe, 4, sc, nib) 292 f4 = nib.astype(np.uint8).view(ml_dtypes.float4_e2m1fn).astype(np.float64) 293 f8 = sc.astype(np.uint8).view(ml_dtypes.float8_e4m3fn).astype(np.float64) 294 prod = (f4 * f8).astype(np.float32) # exact: 6 significant bits 295 need(np.all((f4 * f8) == prod.astype(np.float64)), 'nvfp4 product not exact') 296 exp = prod.view(np.uint32) 297 for i in range(len(nib)): # exact-rational cross-check 298 need(Fraction(float(prod[i])) == e2m1(int(nib[i])) * ue4m3(int(sc[i])), 'nvfp4 ref') 299 bad = np.nonzero(got != exp)[0] 300 need(len(bad) == 0, f'nvfp4 decode mismatch at {[(int(nib[i]), int(sc[i])) for i in bad[:4]]}') 301 dec_pairs = len(nib) 302 # encode: every bfloat16 non-NaN input x every valid scale 303 bf = bf16_bits() 304 bf = bf[(bf & 0x7FFFFFFF) <= 0x7F800000] 305 total = 0 306 mids = np.array([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0]) 307 for s in range(127): 308 got = fmtcall(exe, 5, s, bf) 309 x = bf.view(np.float32).astype(np.float64) 310 neg = (bf >> 31).astype(np.uint32) 311 sv = float(ue4m3(s)) 312 if sv == 0: 313 exp = neg << 3 314 else: 315 q = np.abs(x) / sv # no false tie: see report 316 c = np.searchsorted(mids, q, side='left').astype(np.uint32) 317 tie = np.isin(q, mids) 318 c = np.where(tie & (c % 2 == 1), c + 1, c) # tie: even neighbour 319 c = np.minimum(c, 7) 320 exp = (neg << 3) | c 321 bad = np.nonzero(got != exp)[0] 322 need(len(bad) == 0, f'nvfp4 enc scale {s} mismatch at {[hex(int(bf[i])) for i in bad[:4]]}') 323 total += len(bf) 324 # spec cross-check of the vector oracle near every threshold (Fraction) 325 for s in range(1, 127): 326 sv = ue4m3(s) 327 pts = [] 328 for m in (Fraction(1, 4), Fraction(3, 4), Fraction(5, 4), Fraction(7, 4), 329 Fraction(5, 2), Fraction(7, 2), Fraction(5), Fraction(6), Fraction(7)): 330 b = f32bits(float(m * sv)) 331 pts += [b - 1, b, b + 1] 332 got = fmtcall(exe, 5, s, pts) 333 for b, g in zip(pts, got): 334 x = Fraction(bitsf32(b)) / sv 335 best = min(range(8), key=lambda k: (abs(x - Fraction(F4[k])), k % 2)) 336 need(int(g) == best, f'nvfp4 enc Fraction check s={s} b={b:#x}') 337 # round trip for every element x nonzero scale 338 rt = 0 339 for s in range(1, 127): 340 dec = fmtcall(exe, 4, s, range(16)) 341 back = fmtcall(exe, 5, s, dec) 342 need(list(map(int, back)) == list(range(16)), f'nvfp4 round trip scale {s}') 343 rt += 16 344 # block scale: amax over nonneg bfloat16 and a random binary32 set 345 rng = np.random.default_rng(`20261026`) 346 am = np.concatenate([bf16_bits()[:0x7F81], 347 rng.integers(0, 0x7F800001, 200000, dtype=np.uint32)]).astype(np.uint32) 348 got = fmtcall(exe, 6, 0, am) 349 q = (am.view(np.float32) / np.float32(6.0)).astype(np.float32) 350 exp = ml_encode('e4m3', q.view(np.uint32), 1) 351 need(np.array_equal(got, exp), 'nvfp4scale mismatch') 352 return dec_pairs, total, rt, len(am) 353 354 355 def check_nvblk(exe, fmtexe): 356 rng = np.random.default_rng(7) 357 n = 20000 358 mag = rng.uniform(-30, 10, (n, 16)) 359 x = (rng.choice([-1, 1], (n, 16)) * np.exp2(mag) * rng.uniform(1, 2, (n, 16))).astype(np.float32) 360 x[::97] = 0 361 x[1::101, 3] = np.inf 362 bits = x.view(np.uint32) 363 rc, out = run(exe, bits.astype('> 1]) >> (4 * (i & 1))) & 15) 384 385 386 def scale_frac(fmt, S, j): 387 if fmt == 0: 388 return ue4m3(int(S[j])) 389 return Fraction(2) ** (int(S[j]) - 127) 390 391 392 def mx_reference(fmt, m, n, k, A, SA, B, SB): 393 kb = k // BS[fmt] 394 C, Cseq, Babs = [], [], [] 395 for i in range(m): 396 for j in range(n): 397 terms = [] 398 for t in range(kb): 399 ia, ib = i * kb + t, j * kb + t 400 inner = sum(elem_frac(fmt, A, ia * BS[fmt] + e) * elem_frac(fmt, B, ib * BS[fmt] + e) 401 for e in range(BS[fmt])) 402 terms.append(inner * scale_frac(fmt, SA, ia) * scale_frac(fmt, SB, ib)) 403 acc = 0.0 404 for tm in terms: 405 f = float(tm) 406 need(Fraction(f) == tm, 'block term not exact in binary64') 407 acc = acc + f 408 C.append(sum(terms, Fraction(0))) 409 Cseq.append(acc) 410 Babs.append(sum((abs(tm) for tm in terms), Fraction(0))) 411 return C, Cseq, Babs, kb 412 413 414 def gamma(j): 415 return j * U / (1 - j * U) 416 417 418 def mx_case(rng, fmt, m, n, k, wide): 419 A = np.zeros(4096, np.uint8) 420 B = np.zeros(4096, np.uint8) 421 SA = np.zeros(256, np.uint8) 422 SB = np.zeros(256, np.uint8) 423 kb = k // BS[fmt] 424 eb = k // 2 if fmt < 2 else k 425 if fmt == 2: 426 ok = np.array([c for c in range(256) if (c & 127) != 127], np.uint8) 427 A[:eb * m] = rng.choice(ok, eb * m) 428 B[:eb * n] = rng.choice(ok, eb * n) 429 else: 430 A[:eb * m] = rng.integers(0, 256, eb * m) 431 B[:eb * n] = rng.integers(0, 256, eb * n) 432 if fmt == 0: 433 SA[:kb * m] = rng.integers(0, 127, kb * m) 434 SB[:kb * n] = rng.integers(0, 127, kb * n) 435 else: 436 lo, hi = (0, 255) if wide else (117, 137) 437 SA[:kb * m] = rng.integers(lo, hi, kb * m) 438 SB[:kb * n] = rng.integers(lo, hi, kb * n) 439 hdr = bytes([fmt, m, n, 0, k & 255, k >> 8, 0, 0]) 440 return hdr + A.tobytes() + SA.tobytes() + B.tobytes() + SB.tobytes(), (fmt, m, n, k, A, SA, B, SB) 441 442 443 def check_mxdot(exe, ncases=600): 444 rng = np.random.default_rng(1026) 445 shapes = [] 446 for fmt in (0, 1, 2): 447 bs = BS[fmt] 448 kmax = {0: 4096, 1: 8192, 2: 4096}[fmt] # scale and element capacity 449 shapes += [(fmt, 1, 1, bs), (fmt, 1, 1, kmax), 450 (fmt, 4, 4, 8 * bs), (fmt, 16, 16, bs), (fmt, 2, 3, 4 * bs)] 451 cases = [] 452 while len(cases) < ncases: 453 shp = shapes[len(cases) % len(shapes)] 454 fmt, m, n, k = shp 455 cases.append(mx_case(rng, fmt, m, n, k, wide=(len(cases) // len(shapes)) % 2 == 0)) 456 data = b''.join(c[0] for c in cases) 457 rc, out = run(exe, data, timeout=900) 458 need(rc == 0, f'mxdot rc={rc}') 459 pos, worst, dots = 0, Fraction(0), 0 460 bitexact = 0 461 for _, (fmt, m, n, k, A, SA, B, SB) in cases: 462 C, Cseq, Babs, kb = mx_reference(fmt, m, n, k, A, SA, B, SB) 463 got = np.frombuffer(out[pos:pos + 8 * m * n], ' 256 505 for b in bad: 506 rc, out = run(exe, b) 507 need(rc == 105 and not out, f'mxdot refusal rc={rc}') 508 ok += 1 509 rc, out = run(exe, good[:100]) 510 need(rc == 3 and not out, f'mxdot truncated rc={rc}') 511 return ok + 1 512 513 514 def fmt_refusals(exe): 515 n = 0 516 for op, aux, v in [(0, 0, 256), (1, 0, 256), (2, 2, 0), (3, 2, 0), (4, 0, 16), 517 (5, 0, 0x7FC00000), (6, 0, 0x80000000), (6, 0, 0x7FC00000)]: 518 rec = bytes([op, aux]) + struct.pack('13', lambda: check_nvfp4(texe))) 585 dflip = mutate(fp8, b'ret or s f32norm m -9', b'ret or s f32norm m -8') 586 dexe = build(compiler, [dflip, nv, fdrv], t / 'decflip') 587 neg.append(expect_fail('E4M3 subnormal exponent mutant', lambda: check_fp8(dexe))) 588 mmut = mutate(mx, b'p = add add ue4m3exp ca ue4m3exp cb -2', b'p = add add ue4m3exp ca ue4m3exp cb -1') 589 mmexe = build(compiler, [fp8, nv, mmut, mdrv], t / 'mxmut') 590 neg.append(expect_fail('NVFP4 dot scale mutant', lambda: check_mxdot(mmexe, ncases=30))) 591 print(f'compiler_sha256={digest}') 592 for name, data in (('fp8.om', fp8), ('nvfp4.om', nv), ('mxdot.om', mx)): 593 print(f'{name}_sha256={hashlib.sha256(data).hexdigest()}') 594 for name, exe in (('fmt', fexe), ('nvblk', bexe), ('mxdot', mexe)): 595 print(f'{name}_exe_sha256={hashlib.sha256(Path(exe).read_bytes()).hexdigest()}') 596 print(f'numpy={np.__version__} ml_dtypes={ml_dtypes.__version__}') 597 print(f'FP8 decode exhaustive: {n_dec} codes (E4M3 256, E5M2 256) == ml_dtypes == OFP8 5.1 formula; Table 2 rows checked') 598 for (fmt, sat), c in enc.items(): 599 print(f'FP8 encode {fmt} sat={sat}: {c} inputs (65536 bfloat16 vs exact spec + ml_dtypes; ' 600 f'{c - 65536} structured binary32 vs ml_dtypes); round trip 256 codes') 601 print(f'NVFP4 decode exhaustive: {nvd} element x scale pairs (16 x 127) == ml_dtypes product == exact') 602 print(f'NVFP4 encode: {nve} (non-NaN bfloat16 x 127 scales); threshold +-1ulp Fraction check; round trip {nvrt}') 603 print(f'NVFP4 block scale: {nvsc} amax values; block encode {nblk} blocks') 604 print(f'MX dot/matmul: {mcases} cases, {mdots} dot products, error <= gamma(nb-1) sum|t| for all; ' 605 f'{mbit} bit-equal to left-to-right binary64; worst err/sum|t| = {float(worst):.3e}') 606 print(f'refusals: {nref}') 607 for line in neg: 608 print('NEG ' + line) 609 print('GPU: NOT_RUN') 610 611 612 if __name__ == '__main__': 613 try: 614 main() 615 except Fail as e: 616 print(f'FAIL: {e}') 617 raise SystemExit(1)