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/e1.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 / e1.py` 412 lines ยท 18716 bytes Raw Blame History 1 # E1: direct head solve vs gradient training on frozen SmolLM2-1.7B features. 2 # python e1.py sweep -> picks every hyperparameter on the val split, scores test once, writes e1-sweep.json 3 # python e1.py time -> re-runs the chosen configs 3x (run under quiet-measure), writes e1-time.json 4 # Task A: next token over the K most frequent fit next-tokens + OTHER (K+1 classes). 5 # Task B: binary, "the next token is a digit". 6 # Cost unit: one "pass" = every row of X read once (a fused X W and X^T R over a chunk counts as one pass). 7 import json, os, sys, time, math 8 import torch 9 from common import * 10 11 torch.backends.cuda.matmul.allow_tf32 = False 12 torch.backends.cudnn.allow_tf32 = False 13 K = 1024 14 CH = 16384 15 MODE = sys.argv[1] if len(sys.argv) > 1 else "sweep" 16 17 18 def sync(): 19 torch.cuda.synchronize() 20 21 22 def load(name): 23 d = torch.load(os.path.join(SCRATCH, f"e1-{name}.pt")) 24 X = torch.cat([d["X"], torch.ones(d["X"].shape[0], 1)], 1) # append 1 so every head has a bias row 25 return X.to(DEV), d["Y"].to(DEV) 26 27 28 Xf, Yf = load("fit") 29 Xv, Yv = load("val") 30 Xt, Yt = load("test") 31 N, D = Xf.shape 32 E = torch.load(os.path.join(SCRATCH, "e1-embed.pt")).to(DEV) # [V, d], the frozen tied LM head 33 34 # ---- class map for task A 35 counts = torch.bincount(Yf, minlength=E.shape[0]) 36 top = torch.argsort(counts, descending=True)[:K] 37 cmap = torch.full((E.shape[0],), K, dtype=torch.long, device=DEV) 38 cmap[top] = torch.arange(K, device=DEV) 39 cf, cv, ct = cmap[Yf], cmap[Yv], cmap[Yt] 40 C = K + 1 41 coverage = {s: float((c < K).float().mean()) for s, c in (("fit", cf), ("val", cv), ("test", ct))} 42 43 # ---- labels for task B (digit tokens, from the tokenizer) 44 from transformers import AutoTokenizer 45 tok = AutoTokenizer.from_pretrained(MODEL_DIR) 46 digit = torch.zeros(E.shape[0], dtype=torch.bool) 47 for v in range(E.shape[0]): 48 s = tok.decode([v]).strip() 49 digit[v] = len(s) > 0 and s.isdigit() 50 digit = digit.to(DEV) 51 bf, bv, bt = digit[Yf].float(), digit[Yv].float(), digit[Yt].float() 52 53 54 # ---- metrics 55 def eval_logits_A(logit_fn, X, c): 56 """top-1 and NLL in class space; logit_fn(chunk) -> [n, C] log-probabilities or scores.""" 57 hit, nll, n = 0, 0.0, X.shape[0] 58 for i in range(0, n, CH): 59 lp = logit_fn(X[i:i + CH]) 60 hit += int((lp.argmax(1) == c[i:i + CH]).sum()) 61 nll += float(-torch.log_softmax(lp, 1).gather(1, c[i:i + CH, None]).sum()) 62 return {"top1": hit / n, "nll": nll / n} 63 64 65 def ceiling_A(X): 66 """Frozen LM head, restricted to the same K+1 classes: p(OTHER) = sum of the rest of the vocabulary.""" 67 def f(x): 68 lp = torch.log_softmax(x[:, :-1] @ E.T, 1) 69 other = lp.clone() 70 other[:, top] = -float("inf") 71 return torch.cat([lp[:, top], torch.logsumexp(other, 1, keepdim=True)], 1) 72 return f 73 74 75 def auc(score, y): 76 o = torch.argsort(score) 77 r = torch.empty_like(score) 78 r[o] = torch.arange(1, len(score) + 1, device=score.device, dtype=score.dtype) 79 npos = y.sum() 80 nneg = len(y) - npos 81 return float((r[y > 0].sum() - npos * (npos + 1) / 2) / (npos * nneg)) 82 83 84 def eval_B(logit, y): 85 p = torch.sigmoid(logit) 86 pred = (p > 0.5).float() 87 tpr = float((pred * y).sum() / y.sum()) 88 tnr = float(((1 - pred) * (1 - y)).sum() / (1 - y).sum()) 89 nll = float(torch.nn.functional.binary_cross_entropy_with_logits(logit, y)) 90 return {"auc": auc(logit, y), "bal_acc": (tpr + tnr) / 2, "nll": nll} 91 92 93 def ceiling_B(X): 94 out = [] 95 for i in range(0, X.shape[0], CH): 96 lp = torch.log_softmax(X[i:i + CH, :-1] @ E.T, 1) 97 a = torch.logsumexp(lp[:, digit], 1) 98 b = torch.logsumexp(lp[:, ~digit], 1) 99 out.append(a - b) # logit of p(digit) 100 return torch.cat(out) 101 102 103 # ---- the direct solve: one pass builds G = X^T X and H = X^T Y, then a Cholesky solve 104 def gram_pass(X, labels, ncls): 105 """G (fp64) and H (fp64). Each chunk matmul is fp32, accumulated in fp64. H for one-hot targets is a scatter-add.""" 106 G = torch.zeros(D, D, dtype=torch.float64, device=DEV) 107 H = torch.zeros(D, ncls, dtype=torch.float64, device=DEV) 108 for i in range(0, X.shape[0], CH): 109 x = X[i:i + CH] 110 G += (x.T @ x).double() 111 if labels.dtype == torch.long: 112 H.index_add_(1, labels[i:i + CH], x.T.double()) 113 else: 114 H[:, 0] += (x.T @ labels[i:i + CH]).double() 115 return G, H 116 117 118 def ridge_solve(G, H, lam, n): 119 A = G / n + lam * torch.eye(D, dtype=torch.float64, device=DEV) 120 L = torch.linalg.cholesky(A) 121 return torch.cholesky_solve(H / n, L).float() 122 123 124 def fit_scale(scores_fn, X, c): 125 """One scalar beta so softmax(beta * scores) is a probability model; fit on val by golden-section on NLL.""" 126 def nll(b): 127 return eval_logits_A(lambda x: b * scores_fn(x), X, c)["nll"] 128 lo, hi = 1.0, 200.0 129 g = (math.sqrt(5) - 1) / 2 130 for _ in range(30): 131 a, b = hi - g * (hi - lo), lo + g * (hi - lo) 132 if nll(a) < nll(b): 133 hi = b 134 else: 135 lo = a 136 return (lo + hi) / 2 137 138 139 # ---- gradient baselines on the cached features 140 def ce_grad_pass(W, X, c, lam): 141 """Mean CE + lam/2 |W|^2: loss and gradient in one pass over X.""" 142 g = torch.zeros_like(W) 143 loss = 0.0 144 for i in range(0, X.shape[0], CH): 145 x = X[i:i + CH] 146 p = torch.softmax(x @ W, 1) 147 loss += float(-torch.log(p.gather(1, c[i:i + CH, None]).clamp_min(1e-30)).sum()) 148 p[torch.arange(x.shape[0], device=DEV), c[i:i + CH]] -= 1 149 g += x.T @ p 150 n = X.shape[0] 151 return loss / n + lam / 2 * float((W * W).sum()), g / n + lam * W 152 153 154 def adamw_run(X, c, Xv, cv, loss_kind, lr, wd, target, max_epochs=30, bs=4096, seed=0): 155 torch.manual_seed(seed) 156 W = torch.zeros(D, C, device=DEV, requires_grad=True) 157 opt = torch.optim.AdamW([W], lr=lr, weight_decay=wd) 158 hist, reach = [], {} 159 t0 = time.time() 160 for ep in range(1, max_epochs + 1): 161 perm = torch.randperm(X.shape[0], device=DEV) 162 for i in range(0, X.shape[0], bs): 163 idx = perm[i:i + bs] 164 s = X[idx] @ W 165 if loss_kind == "ce": 166 loss = torch.nn.functional.cross_entropy(s, c[idx]) 167 else: 168 loss = ((s - torch.nn.functional.one_hot(c[idx], C).float()) ** 2).sum(1).mean() 169 opt.zero_grad(set_to_none=True) 170 loss.backward() 171 opt.step() 172 with torch.no_grad(): 173 m = eval_logits_A(lambda x: x @ W, Xv, cv) 174 sync() 175 hist.append({"epoch": ep, "val_top1": m["top1"], "val_nll": m["nll"], "t": time.time() - t0}) 176 for k, tv in target.items(): 177 if k not in reach and m["top1"] >= tv: 178 reach[k] = {"epoch": ep, "passes": ep, "t": time.time() - t0} 179 if len(reach) == len(target): 180 break 181 return W.detach(), hist, reach 182 183 184 def lbfgs_run(X, c, Xv, cv, lam, target, max_evals=300): 185 W = torch.zeros(D, C, device=DEV, requires_grad=True) 186 opt = torch.optim.LBFGS([W], lr=1, max_iter=10, history_size=20, line_search_fn="strong_wolfe") 187 evals = [0] 188 189 def closure(): 190 evals[0] += 1 191 with torch.no_grad(): 192 l, g = ce_grad_pass(W, X, c, lam) 193 W.grad = g 194 return torch.tensor(l) 195 196 hist, reach = [], {} 197 t0 = time.time() 198 while evals[0] < max_evals: 199 opt.step(closure) 200 with torch.no_grad(): 201 m = eval_logits_A(lambda x: x @ W, Xv, cv) 202 sync() 203 hist.append({"passes": evals[0], "val_top1": m["top1"], "val_nll": m["nll"], "t": time.time() - t0}) 204 for k, tv in target.items(): 205 if k not in reach and m["top1"] >= tv: 206 reach[k] = {"passes": evals[0], "t": time.time() - t0} 207 if len(reach) == len(target): 208 break 209 return W.detach(), hist, reach 210 211 212 def bohning_run(X, c, Xv, cv, lam, target, G, W0=None, max_passes=200): 213 """Fixed-Hessian MM (Bohning 1992): Hessian of mean CE <= 1/2 (I - 11^T/C) kron G/n. 214 Factor (G/(2n) + lam I) once; each step is one gradient pass plus two triangular solves. 215 The column-mean part of the step solves lam * dW_m = grad_m (softmax ignores it).""" 216 n = X.shape[0] 217 L = torch.linalg.cholesky(G / (2 * n) + lam * torch.eye(D, dtype=torch.float64, device=DEV)) 218 W = torch.zeros(D, C, device=DEV) if W0 is None else W0.clone() 219 hist, reach = [], {} 220 t0 = time.time() 221 for k in range(1, max_passes + 1): 222 _, g = ce_grad_pass(W, X, c, lam) 223 gm = g.mean(1, keepdim=True) 224 W -= torch.cholesky_solve((g - gm).double(), L).float() + gm / lam 225 m = eval_logits_A(lambda x: x @ W, Xv, cv) 226 sync() 227 hist.append({"passes": k, "val_top1": m["top1"], "val_nll": m["nll"], "t": time.time() - t0}) 228 for kk, tv in target.items(): 229 if kk not in reach and m["top1"] >= tv: 230 reach[kk] = {"passes": k, "t": time.time() - t0} 231 if len(reach) == len(target): 232 break 233 return W, hist, reach 234 235 236 # ---- task B: exact Newton (IRLS) for logistic regression, one weighted Gram pass per step 237 def irls_run(X, y, lam, steps=12, W0=None): 238 n = X.shape[0] 239 w = torch.zeros(D, device=DEV) if W0 is None else W0.clone() 240 hist = [] 241 for k in range(1, steps + 1): 242 Hs = torch.zeros(D, D, dtype=torch.float64, device=DEV) 243 g = torch.zeros(D, dtype=torch.float64, device=DEV) 244 for i in range(0, n, CH): 245 x = X[i:i + CH] 246 p = torch.sigmoid(x @ w) 247 g += (x.T @ (p - y[i:i + CH])).double() 248 Hs += ((x * (p * (1 - p))[:, None]).T @ x).double() 249 g = g / n + lam * w.double() 250 Hs = Hs / n + lam * torch.eye(D, dtype=torch.float64, device=DEV) 251 step = torch.linalg.solve(Hs, g) 252 w = w - step.float() 253 hist.append({"step": k, "grad_norm": float(g.norm()), "step_norm": float(step.norm())}) 254 if float(step.norm()) < 1e-6 * max(1.0, float(w.norm())): 255 break 256 return w, hist 257 258 259 def adamw_B(X, y, lr, wd, epochs, bs=4096, seed=0): 260 torch.manual_seed(seed) 261 w = torch.zeros(D, device=DEV, requires_grad=True) 262 opt = torch.optim.AdamW([w], lr=lr, weight_decay=wd) 263 for ep in range(epochs): 264 perm = torch.randperm(X.shape[0], device=DEV) 265 for i in range(0, X.shape[0], bs): 266 idx = perm[i:i + bs] 267 loss = torch.nn.functional.binary_cross_entropy_with_logits(X[idx] @ w, y[idx]) 268 opt.zero_grad(set_to_none=True) 269 loss.backward() 270 opt.step() 271 return w.detach() 272 273 274 def timed(f): 275 sync() 276 t0 = time.time() 277 r = f() 278 sync() 279 return r, time.time() - t0 280 281 282 LAMS = [1e-6, 1e-5, 1e-4, 1e-3, 1e-2] 283 X_BYTES = N * D * 4 284 285 if MODE == "sweep": 286 out = {"N_fit": N, "N_val": Xv.shape[0], "N_test": Xt.shape[0], "D_with_bias": D, "K": K, 287 "class_coverage_in_topK": coverage, "digit_rate": {"fit": float(bf.mean()), "val": float(bv.mean()), "test": float(bt.mean())}} 288 # ceilings 289 out["ceiling_A"] = {"val": eval_logits_A(ceiling_A(Xv), Xv, cv), "test": eval_logits_A(ceiling_A(Xt), Xt, ct)} 290 out["ceiling_B"] = {"val": eval_B(ceiling_B(Xv), bv), "test": eval_B(ceiling_B(Xt), bt)} 291 cv_top = out["ceiling_A"]["val"]["top1"] 292 target = {"ceil-1.0": cv_top - 0.010, "ceil-0.5": cv_top - 0.005} 293 out["target_val_top1"] = target 294 print("ceilings", out["ceiling_A"], out["ceiling_B"]) 295 296 # ridge, task A 297 (G, H), tg = timed(lambda: gram_pass(Xf, cf, C)) 298 rs = {} 299 for lam in LAMS: 300 W = ridge_solve(G, H, lam, N) 301 rs[lam] = eval_logits_A(lambda x: x @ W, Xv, cv) 302 lam_r = max(rs, key=lambda l: rs[l]["top1"]) 303 Wr = ridge_solve(G, H, lam_r, N) 304 beta = fit_scale(lambda x: x @ Wr, Xv, cv) 305 out["ridge_A"] = {"val_by_lambda": {str(k): v for k, v in rs.items()}, "lambda": lam_r, "beta": beta, 306 "gram_pass_seconds_unlocked": tg, 307 "val": eval_logits_A(lambda x: beta * (x @ Wr), Xv, cv), 308 "test": eval_logits_A(lambda x: beta * (x @ Wr), Xt, ct)} 309 # exactness: gradient of the ridge objective at the solution, and chunk-order invariance of G 310 Wd = torch.cholesky_solve(H / N, torch.linalg.cholesky(G / N + lam_r * torch.eye(D, dtype=torch.float64, device=DEV))) 311 grad = (G / N) @ Wd - H / N + lam_r * Wd 312 G2, _ = gram_pass(Xf.flip(0), cf.flip(0), C) 313 out["ridge_A"]["checks"] = {"rel_grad_norm_at_solution_fp64": float(grad.norm() / (H / N).norm()), 314 "G_reverse_chunk_order_rel_diff": float((G - G2).norm() / G.norm()), 315 "cond_G_plus_lam": float(torch.linalg.cond(G / N + lam_r * torch.eye(D, dtype=torch.float64, device=DEV)))} 316 print("ridge", out["ridge_A"]["lambda"], out["ridge_A"]["val"], out["ridge_A"]["test"], out["ridge_A"]["checks"]) 317 318 # AdamW CE and MSE, sweep on val 319 for kind in ("ce", "mse"): 320 runs = [] 321 for lr in (1e-3, 3e-3, 1e-2): 322 for wd in (0.0, 0.01): 323 W, hist, reach = adamw_run(Xf, cf, Xv, cv, kind, lr, wd, target) 324 runs.append({"lr": lr, "wd": wd, "best_val_top1": max(h["val_top1"] for h in hist), "reach": reach, "hist": hist}) 325 print(kind, lr, wd, runs[-1]["best_val_top1"], reach) 326 best = max(runs, key=lambda r: (len(r["reach"]), -min([v["passes"] for v in r["reach"].values()] or [99]), r["best_val_top1"])) 327 W, hist, reach = adamw_run(Xf, cf, Xv, cv, kind, best["lr"], best["wd"], target) 328 out[f"adamw_{kind}_A"] = {"runs": runs, "chosen": {"lr": best["lr"], "wd": best["wd"]}, 329 "val": eval_logits_A(lambda x: x @ W, Xv, cv), "test": eval_logits_A(lambda x: x @ W, Xt, ct), "reach": reach} 330 331 # L-BFGS full batch CE 332 lb = {} 333 for lam in (1e-5, 1e-4): 334 W, hist, reach = lbfgs_run(Xf, cf, Xv, cv, lam, target) 335 lb[lam] = {"hist": hist, "reach": reach, "W": W} 336 print("lbfgs", lam, hist[-1], reach) 337 lam_l = max(lb, key=lambda l: (len(lb[l]["reach"]), max(h["val_top1"] for h in lb[l]["hist"]))) 338 W = lb[lam_l]["W"] 339 out["lbfgs_ce_A"] = {"lambda": lam_l, "runs": {str(k): {"hist": v["hist"], "reach": v["reach"]} for k, v in lb.items()}, 340 "val": eval_logits_A(lambda x: x @ W, Xv, cv), "test": eval_logits_A(lambda x: x @ W, Xt, ct), "reach": lb[lam_l]["reach"]} 341 342 # Bohning MM: cold start, and warm start from the scaled ridge head 343 for name, W0 in (("bohning_cold_A", None), ("bohning_warm_A", beta * Wr)): 344 bm = {} 345 for lam in (1e-5, 1e-4): 346 W, hist, reach = bohning_run(Xf, cf, Xv, cv, lam, target, G, W0=W0, max_passes=100) 347 bm[lam] = {"hist": hist, "reach": reach, "W": W} 348 print(name, lam, hist[-1], reach) 349 lam_b = max(bm, key=lambda l: (len(bm[l]["reach"]), max(h["val_top1"] for h in bm[l]["hist"]))) 350 W = bm[lam_b]["W"] 351 out[name] = {"lambda": lam_b, "runs": {str(k): {"hist": v["hist"], "reach": v["reach"]} for k, v in bm.items()}, 352 "val": eval_logits_A(lambda x: x @ W, Xv, cv), "test": eval_logits_A(lambda x: x @ W, Xt, ct), "reach": bm[lam_b]["reach"]} 353 354 # task B 355 Gb, Hb = gram_pass(Xf, bf, 1) 356 rb = {} 357 for lam in LAMS: 358 w = ridge_solve(Gb, Hb, lam, N)[:, 0] 359 rb[lam] = eval_B(Xv @ w - 0.5, bv) # ridge on 0/1 labels: threshold 0.5 -> logit sign 360 lam_b = max(rb, key=lambda l: rb[l]["auc"]) 361 w = ridge_solve(Gb, Hb, lam_b, N)[:, 0] 362 out["ridge_B"] = {"lambda": lam_b, "val": rb[lam_b], "test": eval_B(Xt @ w - 0.5, bt), 363 "note": "AUC and balanced accuracy only; ridge outputs are not log-odds, NLL is not meaningful"} 364 ib = {} 365 for lam in (1e-5, 1e-4, 1e-3): 366 w, hist = irls_run(Xf, bf, lam) 367 ib[lam] = {"w": w, "hist": hist, "val": eval_B(Xv @ w, bv)} 368 lam_i = min(ib, key=lambda l: ib[l]["val"]["nll"]) 369 w = ib[lam_i]["w"] 370 out["irls_newton_B"] = {"lambda": lam_i, "steps": len(ib[lam_i]["hist"]), "hist": ib[lam_i]["hist"], 371 "val": ib[lam_i]["val"], "test": eval_B(Xt @ w, bt)} 372 ab = {} 373 for lr in (1e-3, 3e-3, 1e-2): 374 w = adamw_B(Xf, bf, lr, 0.0, 10) 375 ab[lr] = {"w": w, "val": eval_B(Xv @ w, bv)} 376 lr_b = min(ab, key=lambda l: ab[l]["val"]["nll"]) 377 out["adamw_bce_B"] = {"lr": lr_b, "epochs": 10, "val": ab[lr_b]["val"], "test": eval_B(Xt @ ab[lr_b]["w"], bt)} 378 print("B", out["ridge_B"]["test"], out["irls_newton_B"]["test"], out["adamw_bce_B"]["test"]) 379 out["peak_gpu_bytes"] = torch.cuda.max_memory_allocated() 380 out["X_fit_bytes_fp32"] = X_BYTES 381 receipt("e1-sweep", out) 382 383 elif MODE == "time": 384 sw = json.load(open(os.path.join(EVID, "e1-sweep.json"))) 385 # The sweep's ceiling targets (frozen LM head minus 0.5 / 1.0 points on val) were reached by no method, so timing 386 # uses two reachable ones: the ridge head's own val quality, and the best AdamW-CE val quality minus 0.5 points. 387 target = {"ridge_quality": sw["ridge_A"]["val"]["top1"], 388 "best_ce_minus_0.5": max(r["best_val_top1"] for r in sw["adamw_ce_A"]["runs"]) - 0.005} 389 reps = [] 390 for r in range(3): 391 row = {} 392 torch.cuda.reset_peak_memory_stats() 393 (G, H), row["ridge_gram_pass"] = timed(lambda: gram_pass(Xf, cf, C)) 394 Wr, row["ridge_solve"] = timed(lambda: ridge_solve(G, H, sw["ridge_A"]["lambda"], N)) 395 row["ridge_total"] = row["ridge_gram_pass"] + row["ridge_solve"] 396 row["ridge_peak_gpu_bytes"] = torch.cuda.max_memory_allocated() 397 for kind in ("ce", "mse"): 398 ch = sw[f"adamw_{kind}_A"]["chosen"] 399 torch.cuda.reset_peak_memory_stats() 400 (_, _, reach), t = timed(lambda: adamw_run(Xf, cf, Xv, cv, kind, ch["lr"], ch["wd"], target)) 401 row[f"adamw_{kind}"] = {"reach": reach, "total": t, "peak_gpu_bytes": torch.cuda.max_memory_allocated()} 402 torch.cuda.reset_peak_memory_stats() 403 (_, _, reach), t = timed(lambda: lbfgs_run(Xf, cf, Xv, cv, sw["lbfgs_ce_A"]["lambda"], target)) 404 row["lbfgs_ce"] = {"reach": reach, "total": t, "peak_gpu_bytes": torch.cuda.max_memory_allocated()} 405 torch.cuda.reset_peak_memory_stats() 406 beta = sw["ridge_A"]["beta"] 407 (_, _, reach), t = timed(lambda: bohning_run(Xf, cf, Xv, cv, sw["bohning_warm_A"]["lambda"], target, G, W0=beta * Wr, max_passes=100)) 408 row["bohning_warm"] = {"reach": reach, "total": t, "peak_gpu_bytes": torch.cuda.max_memory_allocated()} 409 reps.append(row) 410 print(r, json.dumps(row)[:400]) 411 receipt("e1-time", {"target_val_top1": target, "repeats": reps, "note": "times include per-epoch/per-step val evaluation for the iterative methods; ridge has none", 412 "X_fit_bytes_fp32": X_BYTES})