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 / export_tern.py
| 1 | # export_tern.py (L284 own-fp4): write one trained ternary layer + real activations for omega tests/gpu_tern_layer_test.c. |
| 2 | # ~/.venv/bin/python -I export_tern.py RUN_DIR LAYER(e.g. b2.fc2) M OUT.trn |
| 3 | # Codes follow fp4sim.ternary exactly (absmean, per tensor or per 16x16 tile), activations are the layer's real input on |
| 4 | # held-out text, quantized to int8 per vector by absmax (BitNet's A8). Yref = exact integer W x. |
| 5 | import json, os, sys, numpy as np, torch |
| 6 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 7 | import train as TR |
| 8 | |
| 9 | run, layer, M, out = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] |
| 10 | meta = json.load(open(f"{run}/meta.json")); a = meta["args"]; cfg = meta["cfg"] |
| 11 | torch.manual_seed(0) |
| 12 | TR.Ctx.dev = "cpu"; TR.Ctx.gen = torch.Generator().manual_seed(1) |
| 13 | TR.Ctx.H16 = TR.Q.hadamard(16, "cpu"); TR.Ctx.R16 = TR.Ctx.H16 |
| 14 | model = TR.GPT(32000, a["d"], a["layers"], a["heads"], a["ctx"], cfg) |
| 15 | model.load_state_dict(torch.load(f"{run}/model.pt")); model.eval() |
| 16 | mod = dict(model.named_modules())[layer] |
| 17 | w = mod.weight.detach().float() |
| 18 | if cfg.get("ternary") == "tensor": |
| 19 | T = (w / w.abs().mean().clamp(min=1e-8)).round().clamp(-1, 1) |
| 20 | else: |
| 21 | O, I = w.shape; t = w.reshape(O // 16, 16, I // 16, 16) |
| 22 | s = TR.Q.e4m3(t.abs().mean(dim=(1, 3), keepdim=True).clamp(min=1e-8)) |
| 23 | T = (t / s).round().clamp(-1, 1).reshape(O, I) |
| 24 | cap = {} |
| 25 | mod.register_forward_hook(lambda m_, i_, o_: cap.__setitem__("x", i_[0].detach().float().reshape(-1, i_[0].shape[-1]))) |
| 26 | va = np.memmap(os.path.expanduser("~/workspace/aien-train-own-fp4-data/validation.u16"), dtype=np.uint16, mode="r") |
| 27 | idx = torch.from_numpy(va[1000: 1000 + a["ctx"]].astype(np.int64))[None] |
| 28 | with torch.no_grad(): model(idx) |
| 29 | X = cap["x"][:M] |
| 30 | xs = X.abs().amax(1, keepdim=True).clamp(min=1e-8) / 127.0 |
| 31 | Xq = (X / xs).round().clamp(-127, 127) |
| 32 | Y = (Xq.double() @ T.double().T).round().to(torch.int64) |
| 33 | assert Y.abs().max() < 2 ** 31 |
| 34 | n, k = T.shape |
| 35 | with open(out, "wb") as f: |
| 36 | f.write(b"TRN1"); f.write(np.array([n, k, M], dtype=np.uint32).tobytes()) |
| 37 | f.write(T.to(torch.int8).numpy().tobytes()); f.write(Xq.to(torch.int8).numpy().tobytes()); f.write(Y.to(torch.int32).numpy().tobytes()) |
| 38 | print(json.dumps(dict(run=run, layer=layer, n=n, k=k, m=M, nonzero=float((T != 0).float().mean()), file=out))) |