interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-train / streams / own-fp4 / fp4sim.py

118 lines · 6023 bytes Raw Blame History
1# fp4sim.py (L284 own-fp4, ORACLE ONLY, never shipped): simulated 4-bit numerics for training a small transformer.
2# Every quantizer returns the dequantized tensor split as (q * block_scale) in bf16-exact form plus a float32 per-tensor
3# scale, so the GEMM is run the way the GB10's OMMA.SF does it: block-scaled 4-bit products accumulated in FP32, then the
4# per-tensor scale applied once to the output.
5import math, torch
6
7E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0])
8_grid = {}
9def grid(dev):
10 if dev not in _grid: _grid[dev] = E2M1.to(dev)
11 return _grid[dev]
12
13def round_e2m1(y, stochastic=False, gen=None):
14 """Same results as round_e2m1_ref, by arithmetic: the e2m1 grid has spacing 0.5 below 2, 1 in [2, 4), 2 in [4, 6].
15 Nearest: torch.round is half-to-even, and an even multiple of the spacing is an even code in every region.
16 Stochastic: floor(a / step + u) * step lands on the two neighbouring grid points with the right odds."""
17 a = y.abs().clamp(max=6.0)
18 step = torch.where(a < 2.0, 0.5, torch.where(a < 4.0, 1.0, 2.0))
19 if stochastic:
20 u = torch.rand(a.shape, device=a.device, generator=gen)
21 r = a / step
22 q = torch.minimum(torch.floor(r + u), torch.ceil(r)) * step # never past the upper neighbour (fp32 rounding of r + u)
23 else:
24 q = torch.round(a / step) * step
25 return torch.copysign(q.clamp(max=6.0), y)
26
27def round_e2m1_ref(y, stochastic=False, gen=None):
28 """y already divided by its scale; returns values on the e2m1 grid (saturating at +-6).
29 RNE: ties go to the code with an even last bit (codes 0..7 = grid index). SR: up with probability (y-lo)/(hi-lo)."""
30 g = grid(y.device); s = torch.sign(y); a = y.abs().clamp(max=6.0)
31 i = torch.bucketize(a, g, right=True).clamp(1, 7) - 1 # lo index
32 lo = g[i]; hi = g[(i + 1).clamp(max=7)]
33 if stochastic:
34 p = torch.where(hi > lo, (a - lo) / (hi - lo), torch.zeros_like(a))
35 r = torch.rand(a.shape, device=a.device, generator=gen)
36 q = torch.where(r < p, hi, lo)
37 else:
38 mid = (lo + hi) / 2
39 up = (a > mid) | ((a == mid) & (((i + 1) % 2) == 0))
40 q = torch.where(up, hi, lo)
41 return s * q
42
43def e4m3(x): # round to FP8 E4M3 (RNE, finite), as the hardware's UE4M3 scale
44 return x.clamp(max=448.0).to(torch.float8_e4m3fn).to(torch.float32)
45
46def _blocks(x, dim, b):
47 """move dim last and split it into blocks of b: returns view (..., n/b, b) and an undo function"""
48 xt = x.transpose(dim, -1)
49 sh = xt.shape
50 assert sh[-1] % b == 0, (sh, b)
51 return xt.reshape(*sh[:-1], sh[-1] // b, b), (lambda y: y.reshape(sh).transpose(dim, -1))
52
53def quant_nv(x, dim, stochastic=False, gen=None, block=16, scale_mode="amax"):
54 """NVFP4: e2m1 values, one UE4M3 scale per `block` elements along `dim`, one FP32 tensor scale.
55 Returns (qs, g): qs = q*blockscale (bf16-exact), g = FP32 tensor scale; x ~= qs * g."""
56 x = x.float()
57 amax_t = x.abs().max().clamp(min=1e-30)
58 g = amax_t / (6.0 * 448.0)
59 xb, undo = _blocks(x, dim, block)
60 amax_b = xb.abs().amax(-1, keepdim=True)
61 if scale_mode == "amax":
62 sb = e4m3(amax_b / 6.0 / g)
63 sb = torch.where(sb == 0, torch.ones_like(sb), sb)
64 q = round_e2m1(xb / (sb * g), stochastic, gen)
65 else: # "mse": best of 4 clip ratios per block (our candidate d); RNE only
66 best = None
67 for c in (6.0, 5.0, 4.5, 4.0):
68 s = e4m3(amax_b / c / g); s = torch.where(s == 0, torch.ones_like(s), s)
69 qq = round_e2m1(xb / (s * g))
70 err = ((qq * s * g - xb) ** 2).sum(-1, keepdim=True)
71 if best is None: best = (err, qq, s)
72 else:
73 m = err < best[0]
74 best = (torch.where(m, err, best[0]), torch.where(m, qq, best[1]), torch.where(m, s, best[2]))
75 q, sb = best[1], best[2]
76 return undo(q * sb), g
77
78def quant_nv2d(w, stochastic=False, gen=None):
79 """16x16 2D blocks for weights (NVFP4 paper): one UE4M3 scale per 16x16 tile, replicated to 1x16 rows for the
80 tensor core; the same quantized W serves Fprop (contract over in) and Dgrad (contract over out)."""
81 w = w.float(); O, I = w.shape
82 amax_t = w.abs().max().clamp(min=1e-30); g = amax_t / (6.0 * 448.0)
83 t = w.reshape(O // 16, 16, I // 16, 16)
84 amax_b = t.abs().amax(dim=(1, 3), keepdim=True)
85 sb = e4m3(amax_b / 6.0 / g); sb = torch.where(sb == 0, torch.ones_like(sb), sb)
86 q = round_e2m1(t / (sb * g), stochastic, gen)
87 return (q * sb).reshape(O, I), g
88
89def quant_mx(x, dim, stochastic=False, gen=None):
90 """MXFP4 (OCP): e2m1, one E8M0 power-of-two scale per 32 along dim, X = 2^(floor(log2 amax) - 2), no tensor scale."""
91 x = x.float(); xb, undo = _blocks(x, dim, 32)
92 amax_b = xb.abs().amax(-1, keepdim=True).clamp(min=2.0 ** -126)
93 s = torch.exp2(torch.floor(torch.log2(amax_b)) - 2)
94 q = round_e2m1(xb / s, stochastic, gen)
95 return undo(q * s), torch.ones((), device=x.device)
96
97def ternary(w, per="tensor"):
98 """BitNet b1.58 absmean ternary: W ~= alpha * round(clip(W/alpha, -1, 1)), values {-1,0,1} are e2m1 codes."""
99 w = w.float()
100 if per == "tensor":
101 a = w.abs().mean().clamp(min=1e-8)
102 return (w / a).round().clamp(-1, 1) * a, torch.ones((), device=w.device)
103 O, I = w.shape; t = w.reshape(O // 16, 16, I // 16, 16)
104 a = e4m3(t.abs().mean(dim=(1, 3), keepdim=True).clamp(min=1e-8))
105 return ((t / a).round().clamp(-1, 1) * a).reshape(O, I), torch.ones((), device=w.device)
106
107def hadamard(n, dev):
108 h = torch.ones(1, 1)
109 while h.shape[0] < n: h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0)
110 return (h / math.sqrt(n)).to(dev)
111
112def rotate_tokens(x, R):
113 """apply orthogonal R (b x b) to blocks of b consecutive rows (the token / contraction dim of Wgrad)"""
114 T, C = x.shape; b = R.shape[0]
115 return (R @ x.float().reshape(T // b, b, C)).reshape(T, C)
116
117def rel_err(a, b):
118 return ((a - b).float().norm() / b.float().norm().clamp(min=1e-30)).item()