interplane.Get Omega
Read in your language

omega-blas

aien-dev/omega-blas

Brought by drakestapleton

branch main Branches Tags History

omega-blas / tests / convert.py

55 lines · 2555 bytes Raw Blame History
1"""Exhaustive format-conversion check of the Omega converters against ml_dtypes.
2
3widen: every f16 and bf16 bit pattern (65536 each) and every e4m3fn / e5m2 byte (256 each) must
4give the exact f32 (NaN for NaN). narrow: every f16 / bf16 pattern round-trips, plus the f32
5midpoints between neighbouring 16-bit values (ties to even), their neighbours one f32 ulp either
6side, overflow and underflow edges, and 2**20 random f32 bit patterns, all against ml_dtypes RNE.
7"""
8import os
9import sys
10
11import ml_dtypes as md
12import numpy as np
13
14sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "python"))
15import omegablas as ob # noqa: E402
16
17bad = 0
18
19
20def same(got, want, what):
21 global bad
22 g = np.asarray(got).view(np.uint32 if got.dtype.itemsize == 4 else np.uint16)
23 w = np.asarray(want).view(g.dtype)
24 gn = np.isnan(np.asarray(got, np.float32))
25 wn = np.isnan(np.asarray(want, np.float32))
26 diff = np.flatnonzero(((g != w) & ~(gn & wn)) | (gn != wn))
27 print(f"{what}: {got.size} values, {diff.size} mismatches")
28 if diff.size:
29 bad += 1
30 for i in diff[:5]:
31 print(f" index {i}: got {g.flat[i]:#x} want {w.flat[i]:#x}")
32
33
34for name, dt, bits in (("f16", np.float16, np.uint16), ("bf16", md.bfloat16, np.uint16),
35 ("e4m3fn", md.float8_e4m3fn, np.uint8), ("e5m2", md.float8_e5m2, np.uint8)):
36 src = np.arange(1 << (8 * np.dtype(bits).itemsize), dtype=np.uint64).astype(bits).view(dt)
37 same(ob.widen(src), src.astype(np.float32), f"widen {name} (all patterns)")
38
39rng = np.random.default_rng(7)
40for name, dt in (("float16", np.float16), ("bfloat16", md.bfloat16)):
41 every = np.arange(65536, dtype=np.uint32).astype(np.uint16).view(dt)
42 f = every.astype(np.float32)
43 fin = f[np.isfinite(f)]
44 srt = np.unique(fin)
45 mids = ((srt[:-1].astype(np.float64) + srt[1:]) / 2).astype(np.float32) # exact in f32
46 near = np.concatenate([np.nextafter(mids, np.float32(np.inf)), np.nextafter(mids, np.float32(-np.inf))])
47 edges = np.array([0.0, -0.0, np.inf, -np.inf, np.nan, 65504.0, 65519.99, 65520.0, 6.0e-8, 2.9e-8,
48 3.0e-8, 3.4e38, -3.4e38, 1e-45, 1.17549435e-38], np.float32)
49 rnd = rng.integers(0, 1 << 32, 1 << 20, dtype=np.uint64).astype(np.uint32).view(np.float32)
50 for label, x in (("all patterns", f), ("ties", mids), ("tie +-1ulp", near), ("edges", edges),
51 ("random f32", rnd)):
52 same(ob.narrow(x, name), x.astype(dt), f"narrow {name} {label}")
53
54print("FAILURES", bad)
55sys.exit(1 if bad else 0)