Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-train/blob/main/streams/math-training/e4.py # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-train / streams / math-training / e4.py` 158 lines ยท 7237 bytes Raw Blame History 1 # E4: how many dimensions does the between-layer state (the residual stream) really use, and what does keeping it small cost? 2 # python e4.py -> writes evidence/math-training/e4-subspace.json 3 # Fit PCA at every layer boundary on GSM8K train[0:80] (positions >= 1), evaluate on GSM8K test[0:40]. 4 # Truncation: h -> mu + U_k U_k^T (h - mu) at the output of a layer, for positions >= 1 (position 0, the attention-sink token, is kept). 5 import json, os, math 6 import torch 7 from common import * 8 9 torch.backends.cuda.matmul.allow_tf32 = False 10 tok, model = load_model() 11 layers = model.model.layers 12 NL, d = len(layers), 2048 13 tr, te = load_split("train"), load_split("test") 14 fit_ids, ev_ids = encode(tok, tr[:80]), encode(tok, te[:40]) 15 16 # ---- capture layer outputs (residual stream after layer l) on fit text 17 caps = [[] for _ in range(NL)] 18 def cap(li): 19 def f(mod, inp, out): 20 h = out[0] if isinstance(out, tuple) else out 21 caps[li].append(h[0, 1:].float()) # batch 1, drop position 0 22 return f 23 hs = [l.register_forward_hook(cap(i)) for i, l in enumerate(layers)] 24 with torch.no_grad(): 25 for x, m in batches(fit_ids, 1): 26 model.model(input_ids=x.to(DEV)) 27 for h in hs: 28 h.remove() 29 30 pca, out = [], {"per_layer": []} 31 for li in range(NL): 32 H = torch.cat(caps[li]).double() 33 mu = H.mean(0) 34 C = (H - mu).T @ (H - mu) / len(H) 35 ev, U = torch.linalg.eigh(C) 36 ev, U = ev.flip(0).clamp_min(0), U.flip(1) 37 c = torch.cumsum(ev, 0) / ev.sum() 38 dims = {str(l): int((c < l).sum()) + 1 for l in (0.95, 0.99, 0.999)} 39 # outlier ("massive") dims: per-coordinate RMS more than 20x the median coordinate RMS 40 rms = H.pow(2).mean(0).sqrt() 41 outl = torch.nonzero(rms > 20 * rms.median()).flatten() 42 keep = torch.ones(d, dtype=torch.bool, device=H.device); keep[outl] = False 43 Hk = H[:, keep] 44 Ck = (Hk - Hk.mean(0)).T @ (Hk - Hk.mean(0)) / len(Hk) 45 evk = torch.linalg.eigvalsh(Ck).flip(0).clamp_min(0) 46 ck = torch.cumsum(evk, 0) / evk.sum() 47 dims_k = {str(l): int((ck < l).sum()) + 1 for l in (0.95, 0.99, 0.999)} 48 pca.append((mu.float(), U.float())) 49 out["per_layer"].append({"layer": li, "tokens": len(H), "energy_dims": dims, "outlier_dims": outl.tolist(), 50 "energy_dims_without_outlier_dims": dims_k, 51 "share_of_uncentered_energy_in_outlier_dims": float(H[:, outl].pow(2).sum() / H.pow(2).sum())}) 52 caps[li] = None 53 print(json.dumps(out["per_layer"][::6])[:1500], flush=True) 54 55 # ---- subspace stability: mean cos^2 of principal angles between top-k subspaces of consecutive boundaries 56 for k in (64, 256, 1024): 57 out[f"consecutive_overlap_k{k}"] = [float((pca[l][1][:, :k].T @ pca[l + 1][1][:, :k]).pow(2).sum() / k) for l in range(NL - 1)] 58 out[f"first_last_overlap_k{k}"] = float((pca[0][1][:, :k].T @ pca[-1][1][:, :k]).pow(2).sum() / k) 59 60 # ---- truncation experiments 61 state = {"k": None, "only": None, "rand": None} 62 def trunc(li): 63 def f(mod, inp, outp): 64 if state["k"] is None or (state["only"] is not None and state["only"] != li): 65 return None 66 h = outp[0] if isinstance(outp, tuple) else outp 67 mu, U = pca[li] 68 Uk = state["rand"][li] if state["rand"] is not None else U[:, :state["k"]] 69 hf = h.float() 70 p = mu + ((hf - mu) @ Uk) @ Uk.T 71 p[:, 0] = hf[:, 0] 72 p = p.to(h.dtype) 73 return (p,) + tuple(outp[1:]) if isinstance(outp, tuple) else p 74 return f 75 hs = [l.register_forward_hook(trunc(i)) for i, l in enumerate(layers)] 76 77 ref_logits = [] 78 @torch.no_grad() 79 def run(collect=False): 80 tot, n, agree, i = 0.0, 0, 0, 0 81 for x, m in batches(ev_ids, 1): 82 x = x.to(DEV) 83 lg = model(input_ids=x).logits[0, :-1].float() 84 tot += float(torch.nn.functional.cross_entropy(lg, x[0, 1:], reduction="sum")); n += lg.shape[0] 85 a = lg.argmax(1) 86 if collect: 87 ref_logits.append(a) 88 else: 89 agree += int((a == ref_logits[i]).sum()) 90 i += 1 91 return tot / n, (agree / n if not collect else 1.0) 92 93 base_nll, _ = run(collect=True) 94 out["heldout_nll_full"] = base_nll 95 res = [] 96 for k in (64, 128, 256, 512, 1024, 1536, 2048): 97 state.update(k=k, only=None, rand=None) 98 nll, ag = run() 99 res.append({"k": k, "nll": nll, "nll_increase": nll - base_nll, "top1_agreement_with_full": ag}) 100 print(res[-1], flush=True) 101 out["all_boundaries_pca"] = res 102 g = torch.Generator(device="cpu").manual_seed(0) 103 rr = [] 104 for k in (512, 1024, 1536): 105 state.update(k=k, only=None, rand=[torch.linalg.qr(torch.randn(d, k, generator=g))[0].to(DEV) for _ in range(NL)]) 106 nll, ag = run() 107 rr.append({"k": k, "nll_increase": nll - base_nll, "top1_agreement_with_full": ag}) 108 print("rand", rr[-1], flush=True) 109 out["all_boundaries_random_subspace_control"] = rr 110 one = [] 111 for li in range(NL): 112 state.update(k=256, only=li, rand=None) 113 nll, ag = run() 114 one.append({"layer": li, "k": 256, "nll_increase": nll - base_nll, "top1_agreement_with_full": ag}) 115 out["one_boundary_at_k256"] = one 116 print("one", [round(o["nll_increase"], 3) for o in one], flush=True) 117 state.update(k=None, only=None, rand=None) 118 for h in hs: 119 h.remove() 120 121 # ---- the fold: with h = mu + U z (U orthonormal, d x k), q = W diag(g) (h / rms(h)) needs only z: 122 # rms(h)^2 = (|mu|^2 + 2 mu^T U z + |z|^2) / d, W diag(g) h = (W diag(g) mu) + (W diag(g) U) z 123 li, k = 12, 512 124 mu, U = pca[li - 1] 125 Uk = U[:, :k] 126 lay = layers[li] 127 g_attn = lay.input_layernorm.weight.float() 128 Wq = lay.self_attn.q_proj.weight.float() 129 with torch.no_grad(): 130 x, _ = next(batches(ev_ids[:1], 1)) 131 hcap = [] 132 hk = layers[li - 1].register_forward_hook(lambda m_, i_, o_: hcap.append((o_[0] if isinstance(o_, tuple) else o_)[0, 1:].float())) 133 model.model(input_ids=x.to(DEV)); hk.remove() 134 h = mu + ((hcap[0] - mu) @ Uk) @ Uk.T # a state that lies exactly in the subspace 135 z = (h - mu) @ Uk 136 eps = model.config.rms_norm_eps 137 direct = (h / torch.sqrt(h.pow(2).mean(1, keepdim=True) + eps) * g_attn) @ Wq.T 138 r2 = (mu @ mu + 2 * z @ (Uk.T @ mu) + z.pow(2).sum(1)) / d 139 folded = ((Wq * g_attn) @ mu + z @ ((Wq * g_attn) @ Uk).T) / torch.sqrt(r2 + eps)[:, None] 140 out["fold_check"] = {"layer": li, "k": k, "rel_err_folded_vs_direct_fp32": float((folded - direct).norm() / direct.norm())} 141 print(out["fold_check"]) 142 143 # ---- bytes: decode weight reads per token at k vs d (bf16), at the measured 245.1 GB/s (L279 / L151) 144 cfg = model.config 145 F = cfg.intermediate_size 146 per_layer = 4 * d * d + 3 * d * F 147 lm_head = cfg.vocab_size * d 148 full = (NL * per_layer + lm_head) * 2 149 kv_per_ctx_token = NL * 2 * d * 2 150 bw = 245.1e9 151 tab = [] 152 for k in (256, 512, 1024, 1536, 2048): 153 w = full * k / d + NL * k * k * 2 # every matrix shrinks by k/d; plus one k x k change of basis per boundary 154 tab.append({"k": k, "weight_bytes_per_token": w, "ms_at_245GBps_weights_only": w / bw * 1e3, 155 "kv_bytes_per_token_at_ctx_1024_unchanged": kv_per_ctx_token * 1024}) 156 out["decode_bytes"] = {"full_weight_bytes_per_token": full, "table": tab, 157 "note": "weights only, bf16, one decode token; KV-cache reads do not shrink with k"} 158 receipt("e4-subspace", out)