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/e3.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 / e3.py` 262 lines ยท 13986 bytes Raw Blame History 1 # E3: do real weight matrices live in a small closed algebra (structure constants)? 2 # python e3.py toy -> exact checks of the paste's toy claims (rational arithmetic), writes e3-toy.json 3 # python e3.py algebra -> per-head OV/QK spans, closure of virtual-head products, growth, controls, writes e3-algebra.json 4 # python e3.py nonlin -> linear fit of each gated MLP on real activations, and the NLL cost of swapping it in, writes e3-nonlin.json 5 # Rank-64 head matrices are kept factored, M = L R^T (L, R are d x 64), so inner products and products never build d x d: 6 # = sum((L1^T L2) * (R1^T R2)), (L1 R1^T)(L2 R2^T) = (L1 (R1^T L2)) R2^T. 7 import json, os, sys, random 8 from fractions import Fraction as Fr 9 import torch 10 from common import * 11 12 MODE = sys.argv[1] 13 HD, NH = 64, 32 14 15 16 def weights(layer): 17 from safetensors import safe_open 18 out = {} 19 with safe_open(os.path.join(MODEL_DIR, "model.safetensors"), "pt") as f: 20 for n in ("q_proj", "k_proj", "v_proj", "o_proj"): 21 out[n] = f.get_tensor(f"model.layers.{layer}.self_attn.{n}.weight").float() 22 for n in ("gate_proj", "up_proj", "down_proj"): 23 out[n] = f.get_tensor(f"model.layers.{layer}.mlp.{n}.weight").float() 24 return out 25 26 27 def heads_OV(w): 28 """OV_h = W_O[:, h] W_V[h, :] (x -> contribution of head h, ignoring the attention mixing).""" 29 return [(w["o_proj"][:, h * HD:(h + 1) * HD], w["v_proj"][h * HD:(h + 1) * HD].T) for h in range(NH)] 30 31 32 def heads_QK(w): 33 """QK_h = W_Q[h]^T W_K[h] (bilinear score at relative position 0; RoPE rotates it at other offsets).""" 34 return [(w["q_proj"][h * HD:(h + 1) * HD].T, w["k_proj"][h * HD:(h + 1) * HD].T) for h in range(NH)] 35 36 37 def gram(items, others=None): 38 others = items if others is None else others 39 G = torch.empty(len(items), len(others), dtype=torch.float64, device=items[0][0].device) 40 for a, (La, Ra) in enumerate(items): 41 LL = torch.stack([La.T @ Lb for Lb, _ in others]) # [n, r, r] 42 RR = torch.stack([Ra.T @ Rb for _, Rb in others]) 43 G[a] = (LL * RR).sum((1, 2)).double() 44 return G 45 46 47 def normalize(items): 48 out = [] 49 for L, R in items: 50 n = float(((L.T @ L) * (R.T @ R)).sum()) ** 0.5 51 out.append((L / n ** 0.5, R / n ** 0.5)) 52 return out 53 54 55 def energy_dims(G, levels=(0.95, 0.99, 0.999)): 56 ev = torch.linalg.eigvalsh(G).flip(0).clamp_min(0) 57 c = torch.cumsum(ev, 0) / ev.sum() 58 return {str(l): int((c < l).sum()) + 1 for l in levels}, ev 59 60 61 def matched_random(items, seed): 62 """Control: same singular values per matrix, random orthonormal singular vectors.""" 63 g = torch.Generator(device="cpu").manual_seed(seed) 64 out = [] 65 for L, R in items: 66 # exact SVD of L R^T from the factors: L = Ql Rl, R = Qr Rr, core = Rl Rr^T 67 Ql, Rl = torch.linalg.qr(L) 68 Qr, Rr = torch.linalg.qr(R) 69 s = torch.linalg.svdvals(Rl @ Rr.T) 70 d, r = L.shape 71 A = torch.linalg.qr(torch.randn(d, r, generator=g).to(L.device))[0] 72 B = torch.linalg.qr(torch.randn(d, r, generator=g).to(L.device))[0] 73 out.append((A * s, B)) 74 return out 75 76 77 def closure_residual(B_items, P_items): 78 """Relative residual of each P after orthogonal projection onto span(B): sqrt(1 - b^T G^-1 b / |P|^2).""" 79 G = gram(B_items) 80 b = gram(P_items, B_items) # [nP, nB] 81 nP = torch.stack([((L.T @ L) * (R.T @ R)).sum() for L, R in P_items]).double() 82 w = torch.linalg.solve(G + 1e-12 * torch.eye(len(B_items), dtype=G.dtype, device=G.device) * G.diagonal().mean(), b.T) 83 proj = (b.T * w).sum(0) 84 return torch.sqrt((1 - proj / nP).clamp_min(0)) 85 86 87 def products(A_items, B_items, pairs): 88 return [(A_items[i][0] @ (A_items[i][1].T @ B_items[j][0]), B_items[j][1]) for i, j in pairs] 89 90 91 if MODE == "toy": 92 out = {} 93 I = [[Fr(1), Fr(0)], [Fr(0), Fr(1)]] 94 Q = [[Fr(1), Fr(1)], [Fr(1), Fr(0)]] 95 mm = lambda A, B: [[sum(A[i][k] * B[k][j] for k in range(2)) for j in range(2)] for i in range(2)] 96 add = lambda A, B, a=1, b=1: [[a * A[i][j] + b * B[i][j] for j in range(2)] for i in range(2)] 97 out["Q2_equals_Q_plus_I_exact"] = mm(Q, Q) == add(Q, I) 98 # eigenvalues are roots of t^2 - t - 1 (trace 1, det -1); check numerically too 99 import numpy as np 100 ev = sorted(np.linalg.eigvalsh(np.array([[1.0, 1.0], [1.0, 0.0]])).tolist()) 101 out["eigenvalues"] = ev 102 out["eigen_match_golden"] = abs(ev[1] - (1 + 5 ** 0.5) / 2) < 1e-14 and abs(ev[0] - (1 - 5 ** 0.5) / 2) < 1e-14 103 # (aI + bQ)(cI + dQ) = (ac + bd) I + (ad + bc + bd) Q, exact on 200 random rationals 104 rnd = random.Random(0) 105 ok = True 106 for _ in range(200): 107 a, b, c, d = (Fr(rnd.randint(-50, 50), rnd.randint(1, 20)) for _ in range(4)) 108 lhs = mm(add(I, Q, a, b), add(I, Q, c, d)) 109 ok &= lhs == add(I, Q, a * c + b * d, a * d + b * c + b * d) 110 out["product_rule_exact_200_random_rationals"] = ok 111 # ReLU does not commute with Q: one witness 112 relu = lambda v: [max(x, 0) for x in v] 113 mv = lambda A, v: [sum(A[i][k] * v[k] for k in range(2)) for i in range(2)] 114 v = [Fr(1), Fr(-2)] 115 out["relu_witness"] = {"v": [str(x) for x in v], "Q_relu_v": [str(x) for x in mv(Q, relu(v))], "relu_Q_v": [str(x) for x in relu(mv(Q, v))]} 116 out["relu_breaks_commutation"] = mv(Q, relu(v)) != relu(mv(Q, v)) 117 # chunked sufficient statistics are exactly additive (integer toy, exact rationals), and the ridge gradient is 0 118 rows = [[Fr(rnd.randint(-5, 5)) for _ in range(3)] for _ in range(12)] 119 ys = [Fr(rnd.randint(-5, 5)) for _ in range(12)] 120 def stats(R, Y): 121 G = [[sum(r[i] * r[j] for r in R) for j in range(3)] for i in range(3)] 122 H = [sum(r[i] * y for r, y in zip(R, Y)) for i in range(3)] 123 return G, H 124 G1, H1 = stats(rows[:5], ys[:5]); G2, H2 = stats(rows[5:], ys[5:]); G, H = stats(rows, ys) 125 out["chunked_G_H_exact"] = all(G1[i][j] + G2[i][j] == G[i][j] for i in range(3) for j in range(3)) and all(H1[i] + H2[i] == H[i] for i in range(3)) 126 lam = Fr(1, 2) 127 A = [[G[i][j] + (lam if i == j else 0) for j in range(3)] + [H[i]] for i in range(3)] 128 for c in range(3): # exact Gauss-Jordan 129 p = next(r for r in range(c, 3) if A[r][c] != 0); A[c], A[p] = A[p], A[c] 130 A[c] = [x / A[c][c] for x in A[c]] 131 for r in range(3): 132 if r != c: 133 A[r] = [x - A[r][c] * y for x, y in zip(A[r], A[c])] 134 W = [A[i][3] for i in range(3)] 135 grad = [sum(G[i][j] * W[j] for j in range(3)) + lam * W[i] - H[i] for i in range(3)] 136 out["ridge_solution_exact"] = [str(x) for x in W] 137 out["ridge_gradient_exact_zero"] = all(g == 0 for g in grad) 138 print(out) 139 receipt("e3-toy", out) 140 141 elif MODE == "algebra": 142 dev = DEV if torch.cuda.is_available() else "cpu" 143 torch.backends.cuda.matmul.allow_tf32 = False 144 out = {"per_layer": [], "notes": "items normalized to unit Frobenius norm before every Gram; energy = eigenvalue mass of the Gram"} 145 rng = random.Random(0) 146 # positive control: matrices drawn from the exact 2-dim algebra span{I, Q} kron I_1024 close perfectly 147 d = 2048 148 Qd = torch.kron(torch.tensor([[1.0, 1.0], [1.0, 0.0]]), torch.eye(d // 2)).to(dev) 149 Id = torch.eye(d, device=dev) 150 pc = [(a * Id + b * Qd, Id) for a, b in ((1.0, 0.3), (0.2, 1.0), (-0.5, 0.7))] 151 pp = products(pc, pc, [(i, j) for i in range(3) for j in range(3)]) 152 out["positive_control_IQ_closure_residual_max"] = float(closure_residual(normalize(pc), normalize(pp)).max()) 153 prev = None 154 for layer in range(24): 155 w = {k: v.to(dev) for k, v in weights(layer).items()} 156 ov, qk = normalize(heads_OV(w)), normalize(heads_QK(w)) 157 row = {"layer": layer} 158 for name, items in (("OV", ov), ("QK", qk)): 159 dims, _ = energy_dims(gram(items)) 160 dims_r, _ = energy_dims(gram(normalize(matched_random(items, layer * 7 + len(name))))) 161 row[f"{name}_heads_energy_dims"] = dims 162 row[f"{name}_heads_energy_dims_random_control"] = dims_r 163 if prev is not None: 164 # virtual heads: OV of this layer applied after OV of the previous layer (products the model actually forms) 165 pairs = [(i, j) for i in range(NH) for j in range(NH)] 166 sub = rng.sample(pairs, 256) 167 P = normalize(products(ov, prev, sub)) 168 basis = ov + prev 169 res = closure_residual(basis, P) 170 ovr, prevr = normalize(matched_random(ov, layer)), normalize(matched_random(prev, layer + 100)) 171 res_r = closure_residual(ovr + prevr, normalize(products(ovr, prevr, sub))) 172 row["virtual_head_closure_residual"] = {"median": float(res.median()), "min": float(res.min()), "max": float(res.max())} 173 row["virtual_head_closure_residual_random_control"] = {"median": float(res_r.median()), "min": float(res_r.min()), "max": float(res_r.max())} 174 if layer in (1, 6, 12, 18, 23): 175 # growth: dims of span(B) and span(B + B.B) at 99% energy, B = 64 OV heads of two layers, 256 sampled products 176 g1, _ = energy_dims(gram(basis)) 177 g2, _ = energy_dims(gram(basis + P)) 178 g2r, _ = energy_dims(gram(ovr + prevr + normalize(products(ovr, prevr, sub)))) 179 row["growth"] = {"n_basis": len(basis), "n_basis_plus_products": len(basis) + len(P), 180 "dims_basis": g1, "dims_with_products": g2, "dims_with_products_random_control": g2r} 181 prev = ov 182 out["per_layer"].append(row) 183 print(json.dumps(row)[:600], flush=True) 184 # across depth: the 24 dense matrices of each kind 185 depth = {} 186 from safetensors import safe_open 187 with safe_open(os.path.join(MODEL_DIR, "model.safetensors"), "pt") as f: 188 for n, sec in (("q_proj", "self_attn"), ("k_proj", "self_attn"), ("v_proj", "self_attn"), ("o_proj", "self_attn"), 189 ("gate_proj", "mlp"), ("up_proj", "mlp"), ("down_proj", "mlp")): 190 M = torch.stack([f.get_tensor(f"model.layers.{l}.{sec}.{n}.weight").float().reshape(-1) for l in range(24)]).to(dev) 191 M = M / M.norm(dim=1, keepdim=True) 192 G = (M @ M.T).double() 193 depth[n] = {"energy_dims_of_24": energy_dims(G)[0], "mean_abs_cosine_offdiag": float((G - torch.eye(24, device=dev, dtype=G.dtype)).abs().sum() / (24 * 23))} 194 del M 195 out["across_depth"] = depth 196 out["apply_cost_per_token_flops"] = { 197 "dense_d_by_d": 2 * 2048 * 2048, "one_OV_head_factored": 2 * 2 * 2048 * 64, 198 "virtual_head_factored": 2 * (2048 * 64 + 64 * 64 + 64 * 2048), 199 "coefficients_over_r_dense_basis_elements": "r * 2 * d^2 (worse than dense for r > 1 unless each B_k is structured)"} 200 print(json.dumps(depth)) 201 receipt("e3-algebra", out) 202 203 elif MODE == "nonlin": 204 # Collect MLP input u = post_attention_layernorm(h) and output y = mlp(u) on real text; fit y ~ [u, 1] W per layer. 205 tok, model = load_model() 206 tr, te = load_split("train"), load_split("test") 207 fit_ids, ev_ids = encode(tok, tr[:80]), encode(tok, te[:40]) 208 caps = {} 209 210 def hook(li): 211 def f(mod, inp, outp): 212 caps.setdefault(li, []).append((inp[0].detach().float().reshape(-1, inp[0].shape[-1]).cpu(), outp.detach().float().reshape(-1, outp.shape[-1]).cpu())) 213 return f 214 215 hs = [l.mlp.register_forward_hook(hook(i)) for i, l in enumerate(model.model.layers)] 216 with torch.no_grad(): 217 for x, m in batches(fit_ids, 1): # batch 1: no padding positions in the captured activations 218 model.model(input_ids=x.to(DEV), attention_mask=m.long().to(DEV)) 219 fitcap = caps 220 caps = {} 221 with torch.no_grad(): 222 for x, m in batches(ev_ids, 1): 223 model.model(input_ids=x.to(DEV), attention_mask=m.long().to(DEV)) 224 evcap = caps 225 for h in hs: 226 h.remove() 227 Wfit, rows = {}, [] 228 for li in range(24): 229 U = torch.cat([a for a, _ in fitcap[li]]); Y = torch.cat([b for _, b in fitcap[li]]) 230 Ue = torch.cat([a for a, _ in evcap[li]]); Ye = torch.cat([b for _, b in evcap[li]]) 231 Ua = torch.cat([U, torch.ones(len(U), 1)], 1).double() 232 G = Ua.T @ Ua 233 W = torch.linalg.solve(G + 1e-6 * G.diagonal().mean() * torch.eye(G.shape[0], dtype=G.dtype), Ua.T @ Y.double()).float() 234 pe = torch.cat([Ue, torch.ones(len(Ue), 1)], 1) @ W 235 rows.append({"layer": li, "tokens_fit": len(U), "tokens_eval": len(Ue), 236 "linear_fit_rel_residual_heldout": float((Ye - pe).norm() / Ye.norm()), 237 "linear_fit_rel_residual_fit": float((Y - torch.cat([U, torch.ones(len(U), 1)], 1) @ W).norm() / Y.norm())}) 238 Wfit[li] = W 239 print(rows[-1], flush=True) 240 del fitcap, evcap 241 242 # NLL on held-out when one MLP at a time is replaced by its linear fit 243 @torch.no_grad() 244 def nll(): 245 tot, n = 0.0, 0 246 for x, m in batches(ev_ids, 8): 247 x, m = x.to(DEV), m.to(DEV) 248 lg = model(input_ids=x, attention_mask=m.long()).logits[:, :-1].float() 249 v = m[:, 1:] & m[:, :-1] 250 tot += float(torch.nn.functional.cross_entropy(lg[v], x[:, 1:][v], reduction="sum")); n += int(v.sum()) 251 return tot / n 252 base = nll() 253 for li in range(24): 254 W = Wfit[li].to(DEV) 255 orig = model.model.layers[li].mlp.forward 256 model.model.layers[li].mlp.forward = lambda u, W=W: (torch.cat([u.float(), torch.ones(*u.shape[:-1], 1, device=DEV)], -1) @ W).to(u.dtype) 257 rows[li]["heldout_nll_with_this_mlp_linearized"] = nll() 258 rows[li]["nll_increase"] = rows[li]["heldout_nll_with_this_mlp_linearized"] - base 259 model.model.layers[li].mlp.forward = orig 260 print(li, rows[li]["nll_increase"], flush=True) 261 receipt("e3-nonlin", {"heldout_nll_full_model": base, "per_layer": rows, 262 "fit": "GSM8K train[0:80] all positions; eval GSM8K test[0:40]; least squares with bias, ridge 1e-6 * mean diag"})