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 / 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
5References, 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.
12Needs numpy and ml_dtypes; the versions are printed with the receipt.
13"""
14import argparse
15import hashlib
16import math
17from fractions import Fraction
18from pathlib import Path
19import struct
20import subprocess
21import tempfile
22
23import ml_dtypes
24import numpy as np
25
26PIN = '2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f'
27ROOT = Path(__file__).resolve().parents[2]
28UNITS = ROOT / 'native/models'
29TESTS = ROOT / 'tests/models'
30QNAN = 0x7FC00000
31F4 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) # OCP MX v1.0 Table 5 (E2M1)
32U = Fraction(1, 2 ** 53)
33
34
35class Fail(Exception):
36 pass
37
38
39def need(cond, what):
40 if not cond:
41 raise Fail(what)
42
43
44# ---------------------------------------------------------------- build/run
45def 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
55def 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
60def 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, '<u4').view(np.uint8).reshape(-1, 4)
65 rc, out = run(exe, rec.tobytes())
66 need(rc == 0 and len(out) == 4 * len(vals), f'fmt driver rc={rc} bytes={len(out)}')
67 return np.frombuffer(out, '<u4')
68
69
70# ---------------------------------------------------------------- spec oracle
71SPEC = { # name: (exponent bits, mantissa bits, bias)
72 'e4m3': (4, 3, 7),
73 'e5m2': (5, 2, 15),
74}
75
76
77def spec_value(fmt, code):
78 """OFP8 5.1: value of one code as Fraction, or 'nan' / ('inf', sign)."""
79 eb, mb, bias = SPEC[fmt]
80 s = -1 if code & 128 else 1
81 e = (code >> 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
92TABLE2 = { # 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}
98MAXCODE = {'e4m3': 0x7E, 'e5m2': 0x7B}
99OVF = {'e4m3': 0x7F, 'e5m2': 0x7C} # non-saturating overflow code
100NANC = {'e4m3': 0x7F, 'e5m2': 0x7E} # NaN source code (sign kept)
101
102
103def f32bits(x):
104 return struct.unpack('<I', struct.pack('<f', x))[0]
105
106
107def bitsf32(b):
108 return struct.unpack('<f', struct.pack('<I', int(b)))[0]
109
110
111def frac_to_f32bits(v):
112 f = float(v)
113 b = f32bits(f)
114 need(Fraction(bitsf32(b)) == v, f'value {v} not exact in binary32')
115 if v == 0 and f32bits(f) == 0 and isinstance(v, Fraction):
116 return 0
117 return b
118
119
120def expected_decode(fmt, code, table):
121 v = table[code]
122 s = (code & 128) << 24
123 if v == 'nan':
124 return s | QNAN
125 if isinstance(v, tuple):
126 return s | 0x7F800000
127 if v == 0:
128 return s
129 return frac_to_f32bits(v)
130
131
132def spec_encoder(fmt):
133 """Returns enc(xbits, sat) per 5.2.1/Table 3 using exact rationals."""
134 eb, mb, bias = SPEC[fmt]
135 vals = []
136 for c in range(MAXCODE[fmt] + 1):
137 vals.append((spec_value(fmt, c), c))
138 top = vals[-1][0]
139 ulp = Fraction(2) ** ((MAXCODE[fmt] >> 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
176MLT = {'e4m3': ml_dtypes.float8_e4m3fn, 'e5m2': ml_dtypes.float8_e5m2}
177
178
179def 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
192def 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
205def 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
216def bf16_bits():
217 return (np.arange(65536, dtype=np.uint32) << 16)
218
219
220# ---------------------------------------------------------------- FP8 checks
221def 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
242def 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
278def e2m1(n):
279 v = Fraction(F4[n & 7]).limit_denominator(2)
280 return -v if n & 8 else v
281
282
283def ue4m3(c):
284 return spec_value('e4m3', c)
285
286
287def 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
355def 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('<u4').tobytes())
364 need(rc == 0 and len(out) == 9 * n, f'nvblk rc={rc}')
365 out = np.frombuffer(out, np.uint8).reshape(n, 9)
366 amax = (bits & 0x7FFFFFFF).max(axis=1).astype(np.uint32)
367 sc = fmtcall(fmtexe, 6, 0, amax)
368 need(np.array_equal(out[:, 0], sc.astype(np.uint8)), 'nvblk scale')
369 for r in range(0, n, 37): # element codes via op 5
370 e = fmtcall(fmtexe, 5, int(sc[r]), bits[r])
371 packed = (e[0::2] | (e[1::2] << 4)).astype(np.uint8)
372 need(np.array_equal(packed, out[r, 1:]), f'nvblk packing row {r}')
373 return n
374
375
376# ---------------------------------------------------------------- mxdot
377BS = {0: 16, 1: 32, 2: 32}
378
379
380def elem_frac(fmt, A, i):
381 if fmt == 2:
382 return spec_value('e4m3', int(A[i]))
383 return e2m1((int(A[i >> 1]) >> (4 * (i & 1))) & 15)
384
385
386def 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
392def 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
414def gamma(j):
415 return j * U / (1 - j * U)
416
417
418def 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
443def 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], '<f8')
464 pos += 8 * m * n
465 for g, ex, sq, ba in zip(got, C, Cseq, Babs):
466 gf = float(g)
467 need(not math.isnan(gf), 'mxdot NaN')
468 err = abs(Fraction(gf) - ex)
469 bound = gamma(kb - 1) * ba
470 need(err <= bound, f'mxdot bound fmt={fmt} k={k} err={float(err)} bound={float(bound)}')
471 need(gf == sq, f'mxdot differs from left-to-right binary64 sum fmt={fmt}')
472 bitexact += 1
473 if ba:
474 worst = max(worst, err / ba)
475 dots += 1
476 need(pos == len(out), 'mxdot trailing output')
477 return len(cases), dots, bitexact, worst
478
479
480def mx_refusals(exe):
481 rng = np.random.default_rng(3)
482 good, _ = mx_case(rng, 0, 1, 1, 16, False)
483 ok = 0
484 bad = []
485 hdr = bytearray(good[:8])
486 hdr[0] = 3
487 bad.append(bytes(hdr) + good[8:]) # unknown fmt
488 hdr = bytearray(good[:8])
489 hdr[4] = 17
490 bad.append(bytes(hdr) + good[8:]) # k not a block multiple
491 c = bytearray(good)
492 c[8 + 4096] = 127
493 bad.append(bytes(c)) # UE4M3 NaN scale
494 g1, _ = mx_case(rng, 1, 1, 1, 32, False)
495 c = bytearray(g1)
496 c[8 + 4096] = 255
497 bad.append(bytes(c)) # E8M0 NaN scale
498 g2, _ = mx_case(rng, 2, 1, 1, 32, False)
499 c = bytearray(g2)
500 c[8] = 127
501 bad.append(bytes(c)) # E4M3 NaN element
502 hdr = bytearray(good[:8])
503 hdr[1], hdr[2] = 17, 16
504 bad.append(bytes(hdr) + good[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
514def 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('<I', v)
519 rc, out = run(exe, rec)
520 need(rc == 105 and not out, f'refusal op={op} rc={rc}')
521 n += 1
522 for s in range(127, 256): # every invalid UE4M3 scale code
523 for op in (4, 5):
524 rc, out = run(exe, bytes([op, s]) + struct.pack('<I', 1))
525 need(rc == 105 and not out, f'nvfp4 scale {s} op {op} accepted rc={rc}')
526 n += 1
527 rc, out = run(exe, bytes([9, 0, 0, 0, 0, 0]))
528 need(rc == 6, f'unknown op rc={rc}')
529 rc, out = run(exe, bytes([0, 0, 0]))
530 need(rc == 3, f'truncated rc={rc}')
531 return n + 2
532
533
534# ---------------------------------------------------------------- main
535def expect_fail(label, fn):
536 try:
537 fn()
538 except Fail as e:
539 return f'{label}: rejected ({e})'
540 raise Fail(f'negative control accepted: {label}')
541
542
543def mutate(src, old, new):
544 out = src.replace(old, new, 1)
545 need(out != src, f'mutant not applied: {old!r}')
546 return out
547
548
549def main():
550 ap = argparse.ArgumentParser()
551 ap.add_argument('compiler', type=Path)
552 args = ap.parse_args()
553 compiler = str(args.compiler.resolve())
554 digest = hashlib.sha256(Path(compiler).read_bytes()).hexdigest()
555 need(digest == PIN, f'compiler pin mismatch: {digest}')
556 fp8 = (UNITS / 'fp8.om').read_bytes()
557 nv = (UNITS / 'nvfp4.om').read_bytes()
558 mx = (UNITS / 'mxdot.om').read_bytes()
559 fdrv = (TESTS / 'fmt-driver.om').read_bytes()
560 bdrv = (TESTS / 'nvblk-driver.om').read_bytes()
561 mdrv = (TESTS / 'mxdot-driver.om').read_bytes()
562 with tempfile.TemporaryDirectory(prefix='mxfmt-check-') as tmp:
563 t = Path(tmp)
564 fexe = build(compiler, [fp8, nv, fdrv], t / 'fmt')
565 bexe = build(compiler, [fp8, nv, bdrv], t / 'nvblk')
566 mexe = build(compiler, [fp8, nv, mx, mdrv], t / 'mxdot')
567 n_dec = check_fp8(fexe)
568 enc = check_fp8_encode(fexe)
569 nvd, nve, nvrt, nvsc = check_nvfp4(fexe)
570 nblk = check_nvblk(bexe, fexe)
571 mcases, mdots, mbit, worst = check_mxdot(mexe)
572 nref = fmt_refusals(fexe) + mx_refusals(mexe)
573 # negative controls
574 neg = []
575 neg.append(expect_fail('flipped reference table entry E4M3 0x38', lambda: check_fp8(fexe, flip=True)))
576 rhaz = mutate(fp8, b'if gt rm hf\nret add q 1', b'if ge rm hf\nret add q 1')
577 rexe = build(compiler, [rhaz, nv, fdrv], t / 'rhaz')
578 neg.append(expect_fail('round-half-away-from-zero FP8 encoder', lambda: check_fp8_encode(rexe)))
579 nvrhaz = mutate(nv, b'if eq and k 1 1\nc = add k 1', b'if eq k k\nc = add k 1')
580 nexe = build(compiler, [fp8, nvrhaz, fdrv], t / 'nvrhaz')
581 neg.append(expect_fail('round-half-away-from-zero NVFP4 encoder', lambda: check_nvfp4(nexe)))
582 flip = mutate(nv, b'if eq k 5\nret 14', b'if eq k 5\nret 13')
583 texe = build(compiler, [fp8, flip, fdrv], t / 'nvflip')
584 neg.append(expect_fail('flipped NVFP4 midpoint table entry 14->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
612if __name__ == '__main__':
613 try:
614 main()
615 except Fail as e:
616 print(f'FAIL: {e}')
617 raise SystemExit(1)