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 / train.py

220 lines · 14413 bytes Raw Blame History
1# train.py (L284 own-fp4, ORACLE ONLY): one small GPT trained under one numerics recipe. Same seed, same tokens, same
2# schedule for every recipe; only the numbers inside the linear layers change.
3# ~/.venv/bin/python -I train.py --recipe nvfp4 --out DIR [--steps N]
4import argparse, json, math, os, sys, time
5import numpy as np, torch, torch.nn as nn, torch.nn.functional as F
6sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
7import fp4sim as Q
8if os.environ.get("FP4SIM_COMPILE", "1") == "1": # fused quantizers: 11x faster; differ from eager on 1 in 25M values at
9 import torch._dynamo # exact rounding ties (fp32 division order), see OWN_FP4.md Part 3
10 torch._dynamo.config.cache_size_limit = 64
11 for _n in ("quant_nv", "quant_nv2d", "quant_mx"): setattr(Q, _n, torch.compile(getattr(Q, _n), dynamic=False))
12
13# recipe -> settings. fwd/bwd formats: "bf16" | "nv" (1x16 UE4M3 + FP32 tensor) | "mx" (1x32 E8M0)
14RECIPES = {
15 "bf16": dict(fmt="bf16"),
16 # NVIDIA's published recipe (arXiv 2509.25149): W 16x16 2D, X and dY 1x16, RNE fwd, SR on dY (Dgrad + Wgrad),
17 # 16x16 random Hadamard (one fixed sign vector) on Wgrad inputs, last ~15% of blocks in BF16, FP32 master.
18 "nvfp4": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=1),
19 # MXFP4 as the OCP spec quantizes it, no recipe extras (control)
20 "mxfp4": dict(fmt="mx", w2d=False, sr_dy=False, rot="none", hp_last=0),
21 # (a0) 4-bit weights with no master copy at all (updates below half a step are lost): negative control for (a)
22 "w4only": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=1, master="none"),
23 # (a) error feedback: no FP32 master; stored weight = 4-bit code + 8-bit residual of the last rounding
24 "ef8": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=1, master="ef8"),
25 "ef8sr": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=1, master="ef8sr"),
26 # (b) NVFP4 recipe with the Wgrad rotation swapped for a cheaper transform chosen by the outlier study
27 "b_none": dict(fmt="nv", w2d=True, sr_dy=True, rot="none", hp_last=1),
28 "b_h16": dict(fmt="nv", w2d=True, sr_dy=True, rot="h16", hp_last=1),
29 "b_diag": dict(fmt="nv", w2d=True, sr_dy=True, rot="diag", hp_last=1),
30 # (c) ternary weights {-1,0,+1} x scale (BitNet b1.58 absmean, per tensor), NVFP4 activations and gradients
31 "tern": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=1, ternary="tensor"),
32 "tern16": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=1, ternary="block"),
33 # (d) literature-inspired: rotate every GEMM's inputs (Quartet-style), per-block MSE-best clip on forward tensors
34 "d_rotmse": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=1, fwd_mse=True, rot_fwd=True),
35 # all 4-bit, nothing kept in BF16 (ablation of the 15% rule)
36 "nvfp4_all": dict(fmt="nv", w2d=True, sr_dy=True, rot="rht16", hp_last=0),
37}
38
39class Ctx: # numerics state shared by all quantized layers
40 gen = None; R16 = None; H16 = None; RF = None; stats = None; dev = None
41
42def qa(x, dim, cfg, sr=False, mse=False):
43 if cfg["fmt"] == "mx": return Q.quant_mx(x, dim, sr, Ctx.gen)
44 return Q.quant_nv(x, dim, sr, Ctx.gen, scale_mode="mse" if mse else "amax")
45
46def qw(w, cfg, dim):
47 if cfg.get("ternary"): return Q.ternary(w, "tensor" if cfg["ternary"] == "tensor" else "block")
48 if cfg["w2d"]: return Q.quant_nv2d(w)
49 return qa(w, dim, cfg)
50
51def rot_tokens(x, dy, cfg):
52 r = cfg["rot"]
53 if r == "none": return x, dy
54 if r == "diag": # exact per-token balancing: X_t * s_t, dY_t / s_t with s_t = sqrt(|dY_t| / |X_t|) (dW unchanged)
55 s = (dy.float().norm(dim=1) / x.float().norm(dim=1).clamp(min=1e-30)).clamp(min=1e-30).sqrt()
56 s = torch.exp2(torch.round(torch.log2(s))) # power of two: exact on the chip
57 return x.float() * s[:, None], dy.float() / s[:, None]
58 R = Ctx.R16 if r == "rht16" else Ctx.H16
59 return Q.rotate_tokens(x, R), Q.rotate_tokens(dy, R)
60
61def stat(name, a, b):
62 if Ctx.stats is not None: Ctx.stats.setdefault(name, []).append(Q.rel_err(a, b))
63
64class QLinearFn(torch.autograd.Function):
65 @staticmethod
66 def forward(ctx, x, w, cfg, tag):
67 ctx.cfg, ctx.tag = cfg, tag
68 ctx.save_for_backward(x, w)
69 xin, win = x, w
70 if cfg.get("rot_fwd"): # rotate the contraction (in) dim of both operands: X R^T R W^T = X W^T
71 xin = (x.float().reshape(-1, x.shape[-1] // 16, 16) @ Ctx.R16.T).reshape(x.shape)
72 win = (w.float().reshape(w.shape[0], -1, 16) @ Ctx.R16.T).reshape(w.shape)
73 xs, gx = qa(xin, -1, cfg, mse=cfg.get("fwd_mse", False))
74 if cfg.get("rot_fwd") and not cfg.get("ternary"): ws, gw = Q.quant_nv(win, -1, scale_mode="mse" if cfg.get("fwd_mse") else "amax")
75 else: ws, gw = qw(win, cfg, 1)
76 stat(tag + ".x", xs * gx, xin); stat(tag + ".w", ws * gw, win)
77 y = (xs.bfloat16() @ ws.bfloat16().T).float() * (gx * gw)
78 return y.bfloat16()
79
80 @staticmethod
81 def backward(ctx, dy):
82 x, w = ctx.saved_tensors; cfg = ctx.cfg
83 dy = dy.reshape(-1, dy.shape[-1]); x2 = x.reshape(-1, x.shape[-1])
84 # Dgrad: dX = dY W, contraction over out
85 dys, gd = qa(dy, -1, cfg, sr=cfg["sr_dy"])
86 if cfg.get("ternary") or cfg["w2d"]: ws, gw = qw(w, cfg, 0)
87 else: ws, gw = qa(w, 0, cfg)
88 stat(ctx.tag + ".dy", dys * gd, dy)
89 dx = (dys.bfloat16() @ ws.bfloat16()).float() * (gd * gw)
90 # Wgrad: dW = dY^T X, contraction over tokens (rotated per recipe)
91 xr, dyr = rot_tokens(x2, dy, cfg)
92 xq, g1 = qa(xr, 0, cfg); dq, g2 = qa(dyr, 0, cfg, sr=cfg["sr_dy"])
93 stat(ctx.tag + ".wg_x", xq * g1, xr); stat(ctx.tag + ".wg_dy", dq * g2, dyr)
94 dw = (dq.bfloat16().T @ xq.bfloat16()).float() * (g1 * g2)
95 return dx.reshape(x.shape).bfloat16(), dw, None, None
96
97class Lin(nn.Module):
98 def __init__(self, i, o, cfg, tag):
99 super().__init__(); self.weight = nn.Parameter(torch.randn(o, i) * 0.02); self.cfg = cfg; self.tag = tag
100 def forward(self, x):
101 if self.cfg["fmt"] == "bf16": return F.linear(x.bfloat16(), self.weight.bfloat16())
102 sh = x.shape; y = QLinearFn.apply(x.reshape(-1, sh[-1]).bfloat16(), self.weight, self.cfg, self.tag)
103 return y.reshape(*sh[:-1], -1)
104
105class Block(nn.Module):
106 def __init__(self, d, h, cfg, i):
107 super().__init__(); self.h = h
108 self.n1 = nn.RMSNorm(d); self.n2 = nn.RMSNorm(d)
109 self.qkv = Lin(d, 3 * d, cfg, f"b{i}.qkv"); self.proj = Lin(d, d, cfg, f"b{i}.proj")
110 self.fc1 = Lin(d, 4 * d, cfg, f"b{i}.fc1"); self.fc2 = Lin(4 * d, d, cfg, f"b{i}.fc2")
111 def forward(self, x):
112 B, T, D = x.shape
113 q, k, v = self.qkv(self.n1(x)).split(D, -1)
114 q, k, v = (t.reshape(B, T, self.h, D // self.h).transpose(1, 2) for t in (q, k, v))
115 a = F.scaled_dot_product_attention(q, k, v, is_causal=True).transpose(1, 2).reshape(B, T, D)
116 x = x + self.proj(a).float()
117 return x + self.fc2(F.gelu(self.fc1(self.n2(x)).float()).bfloat16()).float()
118
119class GPT(nn.Module):
120 def __init__(self, V, d, L, h, ctx, cfg):
121 super().__init__()
122 self.emb = nn.Embedding(V, d); self.pos = nn.Parameter(torch.randn(ctx, d) * 0.01)
123 bf = dict(fmt="bf16")
124 self.blocks = nn.ModuleList(Block(d, h, cfg if i < L - cfg.get("hp_last", 0) else bf, i) for i in range(L))
125 self.nf = nn.RMSNorm(d)
126 nn.init.normal_(self.emb.weight, std=0.02)
127 def forward(self, idx):
128 x = self.emb(idx) + self.pos[: idx.shape[1]]
129 for b in self.blocks: x = b(x)
130 return F.linear(self.nf(x).bfloat16(), self.emb.weight.bfloat16()).float() # tied head, BF16 per recipe
131
132def ef_store(model, mode):
133 """master-copy handling after each optimizer step for quantized weights (a0 / a)."""
134 with torch.no_grad():
135 for m in model.modules():
136 if isinstance(m, Lin) and m.cfg["fmt"] != "bf16":
137 w = m.weight.data; ws, g = Q.quant_nv2d(w); wq = ws * g
138 if mode == "none": m.weight.data.copy_(wq); continue
139 r = (w - wq); O, I = r.shape; t = r.reshape(O // 16, 16, I // 16, 16)
140 s = torch.exp2(torch.ceil(torch.log2(t.abs().amax(dim=(1, 3), keepdim=True).clamp(min=1e-30) / 448.0)))
141 y = t / s
142 if mode == "ef8sr": # stochastic rounding into E4M3: keeps updates smaller than one residual step on average
143 ulp = torch.exp2(torch.floor(torch.log2(y.abs().clamp(min=2.0 ** -9))).clamp(min=-6) - 3)
144 lo = torch.floor(y / ulp) * ulp
145 yq = lo + ulp * (torch.rand(y.shape, device=y.device, generator=Ctx.gen) < (y - lo) / ulp).float()
146 else: yq = Q.e4m3(y)
147 rq = (yq * s).reshape(O, I) # residual in FP8 E4M3, power-of-two scale per 16x16 tile
148 m.weight.data.copy_(wq + rq)
149
150def main():
151 ap = argparse.ArgumentParser()
152 ap.add_argument("--recipe", required=True); ap.add_argument("--out", required=True)
153 ap.add_argument("--data", default=os.path.expanduser("~/workspace/aien-train-own-fp4-data"))
154 ap.add_argument("--steps", type=int, default=3000); ap.add_argument("--batch", type=int, default=64)
155 ap.add_argument("--ctx", type=int, default=256); ap.add_argument("--d", type=int, default=384)
156 ap.add_argument("--layers", type=int, default=6); ap.add_argument("--heads", type=int, default=6)
157 ap.add_argument("--lr", type=float, default=1.5e-3); ap.add_argument("--eval_every", type=int, default=250)
158 ap.add_argument("--stats_every", type=int, default=500); ap.add_argument("--seed", type=int, default=0)
159 ap.add_argument("--dump_steps", default="") # save Wgrad operands (X, dY) of 4 layers at these steps (outlier study)
160 a = ap.parse_args(); cfg = RECIPES[a.recipe]; cfg.setdefault("master", "fp32")
161 os.makedirs(a.out, exist_ok=True); dev = "cuda"; Ctx.dev = dev
162 torch.manual_seed(a.seed); Ctx.gen = torch.Generator(device=dev); Ctx.gen.manual_seed(a.seed + 7)
163 sgn = torch.where(torch.rand(16, generator=torch.Generator().manual_seed(11)) < 0.5, -1.0, 1.0)
164 Ctx.H16 = Q.hadamard(16, dev); Ctx.R16 = Ctx.H16 * sgn.to(dev)[None, :] # one fixed random sign vector (paper)
165 tr = np.memmap(f"{a.data}/train.u16", dtype=np.uint16, mode="r"); va = np.memmap(f"{a.data}/validation.u16", dtype=np.uint16, mode="r")
166 V = 32000
167 model = GPT(V, a.d, a.layers, a.heads, a.ctx, cfg).to(dev)
168 nparam = sum(p.numel() for p in model.parameters())
169 decay = [p for n, p in model.named_parameters() if p.dim() == 2 and "pos" not in n]
170 other = [p for n, p in model.named_parameters() if not (p.dim() == 2 and "pos" not in n)]
171 opt = torch.optim.AdamW([{"params": decay, "weight_decay": 0.1}, {"params": other, "weight_decay": 0.0}], lr=a.lr, betas=(0.9, 0.95), eps=1e-8)
172 if cfg["master"] != "fp32": ef_store(model, cfg["master"])
173 rng = np.random.default_rng(1234) # identical token order for every recipe
174 starts = rng.integers(0, len(tr) - a.ctx - 1, size=(a.steps, a.batch))
175 vstarts = np.random.default_rng(99).integers(0, len(va) - a.ctx - 1, size=(100, a.batch))
176 def batch(arr, st):
177 x = np.stack([arr[s: s + a.ctx + 1] for s in st]).astype(np.int64); t = torch.from_numpy(x).to(dev)
178 return t[:, :-1], t[:, 1:]
179 def evaluate(nb):
180 model.eval(); tot = 0.0
181 with torch.no_grad():
182 for i in range(nb):
183 x, y = batch(va, vstarts[i]); tot += F.cross_entropy(model(x).view(-1, V), y.reshape(-1)).item()
184 model.train(); return tot / nb
185 log = open(f"{a.out}/log.jsonl", "w"); t0 = time.time(); warm = 200
186 meta = dict(recipe=a.recipe, cfg=cfg, params=nparam, args=vars(a), tokens=a.steps * a.batch * a.ctx, label="oracle",
187 torch=torch.__version__, device=torch.cuda.get_device_name(0))
188 json.dump(meta, open(f"{a.out}/meta.json", "w"), indent=1); print(json.dumps(meta), flush=True)
189 for step in range(a.steps):
190 lr = a.lr * min(1.0, (step + 1) / warm) * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(1.0, step / a.steps))))
191 for gp in opt.param_groups: gp["lr"] = lr
192 Ctx.stats = {} if (a.stats_every and step % a.stats_every == 0 and cfg["fmt"] != "bf16") else None
193 x, y = batch(tr, starts[step])
194 hooks = []; dumps = {}
195 if a.dump_steps and step in [int(s) for s in a.dump_steps.split(",")]:
196 for m in model.modules():
197 if isinstance(m, Lin) and m.tag in ("b0.fc1", "b2.qkv", "b3.proj", "b4.fc2"):
198 def fh(mod, inp, out, tag=m.tag):
199 dumps[tag + ".x"] = inp[0].detach().reshape(-1, inp[0].shape[-1])[:4096].bfloat16().cpu()
200 out.register_hook(lambda g, tag=tag: dumps.__setitem__(tag + ".dy", g.detach().reshape(-1, g.shape[-1])[:4096].bfloat16().cpu()))
201 hooks.append(m.register_forward_hook(fh))
202 loss = F.cross_entropy(model(x).view(-1, V), y.reshape(-1))
203 opt.zero_grad(set_to_none=True); loss.backward()
204 gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0).item()
205 for h in hooks: h.remove()
206 if dumps: torch.save(dumps, f"{a.out}/dump_step{step}.pt")
207 opt.step()
208 if cfg["master"] != "fp32": ef_store(model, cfg["master"])
209 rec = dict(step=step, loss=loss.item(), lr=lr, gnorm=gn, t=round(time.time() - t0, 1))
210 if Ctx.stats: rec["qerr"] = {k: float(np.mean(v)) for k, v in Ctx.stats.items()}
211 if step % a.eval_every == 0 or step == a.steps - 1: rec["val"] = evaluate(20 if step < a.steps - 1 else 100)
212 log.write(json.dumps(rec) + "\n"); log.flush()
213 if step % 100 == 0 or "val" in rec: print(json.dumps({k: v for k, v in rec.items() if k != "qerr"}), flush=True)
214 if not math.isfinite(rec["loss"]): print("DIVERGED"); break
215 if a.recipe.startswith("tern") or a.recipe == "nvfp4": torch.save({k: v.detach().cpu() for k, v in model.state_dict().items()}, f"{a.out}/model.pt")
216 res = dict(recipe=a.recipe, final_val=rec.get("val"), final_train=rec["loss"], seconds=round(time.time() - t0, 1), steps=step + 1, label="oracle")
217 json.dump(res, open(f"{a.out}/result.json", "w")); print("RESULT", json.dumps(res), flush=True)
218
219if __name__ == "__main__":
220 main()