aien-train
AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.
Brought by drakestapleton
aien-train / streams / own-fp4 / test_fp4sim.py
| 1 | # test_fp4sim.py (L284): host checks of the oracle quantizers. ~/.venv/bin/python -I test_fp4sim.py |
| 2 | import os, sys; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 3 | import torch, fp4sim as Q |
| 4 | y = torch.tensor([0.0, 0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0, 5.9, 7.0, -0.25, -2.5, -9.0]) |
| 5 | want = torch.tensor([0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 4.0, 4.0, 6.0, 6.0, 0.0, -2.0, -6.0]) |
| 6 | assert torch.equal(Q.round_e2m1(y), want), Q.round_e2m1(y) |
| 7 | g = torch.Generator().manual_seed(0); v = torch.full((200000,), 2.6) |
| 8 | m = Q.round_e2m1(v, True, g).mean().item(); assert abs(m - 2.6) < 0.01, m # SR unbiased between 2 and 3 |
| 9 | x = torch.randn(64, 256) * torch.exp(torch.randn(64, 1)) |
| 10 | for dim in (0, 1): |
| 11 | qs, gg = Q.quant_nv(x, dim); e = Q.rel_err(qs * gg, x); assert 0.05 < e < 0.2, e |
| 12 | qs, gg = Q.quant_mx(x, dim); e2 = Q.rel_err(qs * gg, x); assert 0.05 < e2 < 0.3, e2 |
| 13 | w = torch.randn(64, 128); qs, gg = Q.quant_nv2d(w); assert Q.rel_err(qs * gg, w) < 0.2 |
| 14 | # bf16-exactness of q * blockscale (the claim the GEMM simulation rests on) |
| 15 | qs, gg = Q.quant_nv(x, 1); assert torch.equal(qs.bfloat16().float(), qs) |
| 16 | qs, gg = Q.quant_nv2d(w); assert torch.equal(qs.bfloat16().float(), qs) |
| 17 | H = Q.hadamard(16, "cpu"); assert torch.allclose(H @ H.T, torch.eye(16), atol=1e-6) |
| 18 | t, a = Q.ternary(w); assert set((t / t.abs().max()).unique().tolist()) <= {-1.0, 0.0, 1.0} |
| 19 | print("fp4sim host checks PASS") |
| 20 | # fast rounding == reference rounding (nearest: bit for bit; stochastic: same support and mean) |
| 21 | z = torch.randn(1_000_000) * 3 + torch.randint(-12, 13, (1_000_000,)) * 0.25 |
| 22 | assert torch.equal(Q.round_e2m1(z), Q.round_e2m1_ref(z)) |
| 23 | for v in (0.3, 1.9, 2.6, 3.99, 4.1, 5.5, 6.0, -1.2): |
| 24 | t = torch.full((400000,), v); f = Q.round_e2m1(t, True, torch.Generator().manual_seed(3)); r = Q.round_e2m1_ref(t, True, torch.Generator().manual_seed(4)) |
| 25 | assert set(f.unique().tolist()) == set(r.unique().tolist()), (v, f.unique(), r.unique()) |
| 26 | assert abs(f.mean().item() - min(abs(v), 6.0) * (1 if v > 0 else -1)) < 0.01, (v, f.mean()) |
| 27 | print("fast rounding matches reference PASS") |