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/e2.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 / e2.py` 294 lines ยท 13298 bytes Raw Blame History 1 # E2: structured adapter bases vs LoRA on frozen SmolLM2-1.7B, matched trainable-parameter counts. 2 # python e2.py check -> numeric checks of the three adapter operators (FourierFT custom backward vs autograd, PHM vs dense Kronecker) 3 # python e2.py train METHOD LR SEED [STEPS] -> one fine-tune, writes evidence/math-training/e2-train-METHOD-LR-SEED.json 4 # python e2.py time -> step time / peak memory per method, 3 repeats (run under quiet-measure) 5 # Adapters on q,k,v,o,gate,up,down of all 24 layers. Every adapter is written the same way (plain torch ops, no PEFT). 6 # Loss: next-token cross-entropy on the answer tokens of GSM8K. Fit: train[0:6500]; val: train[7000:7300]; test: test[0:300]. 7 import json, math, os, sys, time 8 import torch 9 import torch.nn as nn 10 import torch.nn.functional as F 11 from common import * 12 13 TARGETS = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj") 14 R = 8 # LoRA rank; the other methods are matched to its parameter count 15 PHM_N = 4 # Kronecker block count n for PHM 16 17 18 class LoRA(nn.Module): 19 def __init__(self, base, r=R, alpha=16): 20 super().__init__() 21 self.base = base 22 o, i = base.weight.shape 23 self.A = nn.Parameter(torch.randn(r, i) / math.sqrt(i)) 24 self.B = nn.Parameter(torch.zeros(o, r)) 25 self.s = alpha / r 26 27 def delta(self, x): 28 return (x @ self.A.to(x.dtype).T) @ self.B.to(x.dtype).T * self.s 29 30 def forward(self, x): 31 return self.base(x) + self.delta(x) 32 33 34 class PHM(nn.Module): 35 """Delta W = sum_m A_m kron (S_m T_m^T): A_m is n x n (shared per layer), S_m is (o/n) x r, T_m is (i/n) x r. 36 Applied without building Delta W: split x into n blocks, project each with T_m, mix blocks with A_m, expand with S_m. 37 Trainable per matrix: n * r * (o + i) / n = r (o + i), the same as LoRA rank r; plus n^3 shared per layer. 38 Rank of Delta W is at most n * (n * r) = n^2 r (128 for n=4, r=8), against r = 8 for LoRA.""" 39 def __init__(self, base, Ashared, r=R, n=PHM_N, alpha=16): 40 super().__init__() 41 self.base = base 42 o, i = base.weight.shape 43 self.n, self.o, self.i = n, o, i 44 self.A = Ashared 45 self.T = nn.Parameter(torch.randn(n, i // n, r) / math.sqrt(i // n)) 46 self.S = nn.Parameter(torch.zeros(n, o // n, r)) 47 self.s = alpha / r 48 49 def delta(self, x): 50 xb = x.reshape(*x.shape[:-1], self.n, self.i // self.n) # [..., n_j, i/n] 51 U = torch.einsum("...jk,mkr->...mjr", xb, self.T.to(x.dtype)) # [..., m, n_j, r] 52 V = torch.einsum("mij,...mjr->...mir", self.A.to(x.dtype), U) # [..., m, n_i, r] 53 y = torch.einsum("...mir,mor->...io", V, self.S.to(x.dtype)) # [..., n_i, o/n] 54 return y.reshape(*x.shape[:-1], self.o) * self.s 55 56 def dense_delta(self): 57 return sum(torch.kron(self.A[m], self.S[m] @ self.T[m].T) for m in range(self.n)) * self.s 58 59 def forward(self, x): 60 return self.base(x) + self.delta(x) 61 62 63 class _FourierMatmul(torch.autograd.Function): 64 """y = x Delta W^T with Delta W = alpha * Re(sum_k c_k exp(+2 pi i (u_k p / o + v_k q / i))), c real. 65 Forward builds Delta W by one inverse 2-D FFT of the scattered coefficients; backward rebuilds it instead of storing it, 66 and gets dL/dc_k = alpha * Re(FFT2(dL/dDeltaW))[u_k, v_k] (the adjoint of the scatter + inverse FFT).""" 67 @staticmethod 68 def forward(ctx, x, c, idx, o, i, alpha): 69 dW = _fourier_dense(c, idx, o, i, alpha).to(x.dtype) 70 ctx.save_for_backward(x, c, idx) 71 ctx.o, ctx.i, ctx.alpha = o, i, alpha 72 return x @ dW.T 73 74 @staticmethod 75 def backward(ctx, g): 76 x, c, idx = ctx.saved_tensors 77 dW = _fourier_dense(c, idx, ctx.o, ctx.i, ctx.alpha).to(g.dtype) 78 gx = g @ dW 79 gW = g.reshape(-1, ctx.o).T.float() @ x.reshape(-1, ctx.i).float() # [o, i] 80 gc = ctx.alpha * torch.fft.fft2(gW, norm="backward").real.reshape(-1)[idx] 81 return gx, gc, None, None, None, None 82 83 84 def _fourier_dense(c, idx, o, i, alpha): 85 spec = torch.zeros(o * i, dtype=torch.complex64, device=c.device) 86 spec[idx] = c.to(torch.complex64) 87 return alpha * torch.fft.ifft2(spec.reshape(o, i), norm="forward").real 88 89 90 class FourierFT(nn.Module): 91 def __init__(self, base, ncoef, seed): 92 super().__init__() 93 self.base = base 94 o, i = base.weight.shape 95 self.o, self.i = o, i 96 g = torch.Generator().manual_seed(seed) 97 self.register_buffer("idx", torch.randperm(o * i, generator=g)[:ncoef]) 98 self.c = nn.Parameter(torch.zeros(ncoef)) 99 self.alpha = 1.0 / math.sqrt(ncoef) 100 101 def delta(self, x): 102 return _FourierMatmul.apply(x, self.c, self.idx.to(x.device), self.o, self.i, self.alpha) 103 104 def forward(self, x): 105 return self.base(x) + self.delta(x) 106 107 108 def attach(model, method, seed): 109 torch.manual_seed(seed) 110 for p in model.parameters(): 111 p.requires_grad_(False) 112 n_train = 0 113 for li, layer in enumerate(model.model.layers): 114 Ash = nn.Parameter(torch.randn(PHM_N, PHM_N, PHM_N, device=DEV) / PHM_N) if method == "phm" else None 115 if Ash is not None: 116 layer.register_parameter("phm_A", Ash) 117 for parent in (layer.self_attn, layer.mlp): 118 for name in TARGETS: 119 if not hasattr(parent, name): 120 continue 121 base = getattr(parent, name) 122 o, i = base.weight.shape 123 if method.startswith("lora"): 124 r = int(method[4:] or R) 125 m = LoRA(base, r=r) 126 elif method == "phm": 127 m = PHM(base, Ash) 128 elif method == "fourier": 129 m = FourierFT(base, R * (o + i), seed * 1000 + li * 10 + TARGETS.index(name)) 130 else: 131 raise ValueError(method) 132 setattr(parent, name, m.to(DEV)) 133 params = [p for p in model.parameters() if p.requires_grad] 134 return params, sum(p.numel() for p in params) 135 136 137 def answer_batches(tok, exs, bs, seq=SEQ): 138 """(ids, mask over loss positions): loss only on tokens after 'Answer:'.""" 139 rows = [] 140 for e in exs: 141 q = tok("Question: " + e["question"] + "\nAnswer:", add_special_tokens=False)["input_ids"] 142 a = tok(" " + e["answer"], add_special_tokens=False)["input_ids"] 143 ids = (q + a)[:seq] 144 rows.append((ids, len(q))) 145 for k in range(0, len(rows), bs): 146 chunk = rows[k:k + bs] 147 L = max(len(r[0]) for r in chunk) 148 x = torch.full((len(chunk), L), 2, dtype=torch.long) 149 lm = torch.zeros((len(chunk), L), dtype=torch.bool) 150 am = torch.zeros((len(chunk), L), dtype=torch.long) 151 for j, (ids, qlen) in enumerate(chunk): 152 x[j, :len(ids)] = torch.tensor(ids) 153 am[j, :len(ids)] = 1 154 lm[j, qlen:len(ids)] = True 155 yield x.to(DEV), am.to(DEV), lm.to(DEV) 156 157 158 def lm_loss(model, x, am, lm): 159 logits = model(input_ids=x, attention_mask=am).logits[:, :-1].float() 160 tgt = x[:, 1:] 161 m = lm[:, 1:] 162 return F.cross_entropy(logits[m], tgt[m], reduction="sum"), int(m.sum()) 163 164 165 @torch.no_grad() 166 def eval_nll(model, tok, exs): 167 tot, n = 0.0, 0 168 for x, am, lm in answer_batches(tok, exs, 8): 169 l, k = lm_loss(model, x, am, lm) 170 tot += float(l) 171 n += k 172 return tot / n 173 174 175 def splits(): 176 tr, te = load_split("train"), load_split("test") 177 return tr[:6500], tr[7000:7300], te[:300] 178 179 180 if __name__ == "__main__": 181 mode = sys.argv[1] 182 if mode == "check": 183 torch.manual_seed(0) 184 out = {} 185 # FourierFT: custom backward vs plain autograd through torch.fft, small matrix, fp64-accurate in fp32 186 o, i, nc = 48, 32, 100 187 base = nn.Linear(i, o, bias=False).to(DEV) 188 f = FourierFT(base, nc, 1).to(DEV) 189 with torch.no_grad(): 190 f.c.normal_() 191 x = torch.randn(5, i, device=DEV, requires_grad=True) 192 y = f.delta(x) 193 g = torch.randn_like(y) 194 gx, gc = torch.autograd.grad(y, (x, f.c), g) 195 c2 = f.c.detach().clone().requires_grad_(True) 196 x2 = x.detach().clone().requires_grad_(True) 197 y2 = x2 @ _fourier_dense(c2, f.idx, o, i, f.alpha).T 198 gx2, gc2 = torch.autograd.grad(y2, (x2, c2), g) 199 out["fourier_forward_rel_err"] = float((y - y2).norm() / y2.norm()) 200 out["fourier_grad_x_rel_err"] = float((gx - gx2).norm() / gx2.norm()) 201 out["fourier_grad_c_rel_err"] = float((gc - gc2).norm() / gc2.norm()) 202 # PHM: structured apply vs the dense Kronecker sum 203 base = nn.Linear(64, 96, bias=False).to(DEV) 204 A = nn.Parameter(torch.randn(PHM_N, PHM_N, PHM_N, device=DEV)) 205 p = PHM(base, A, r=3).to(DEV) 206 with torch.no_grad(): 207 p.S.normal_() 208 x = torch.randn(7, 64, device=DEV) 209 out["phm_structured_vs_dense_rel_err"] = float((p.delta(x) - x @ p.dense_delta().T).norm() / (x @ p.dense_delta().T).norm()) 210 out["phm_dense_rank"] = int(torch.linalg.matrix_rank(p.dense_delta())) 211 out["phm_rank_bound_n_squared_times_r"] = PHM_N * PHM_N * 3 # n terms, each rank(A_m) * rank(S_m T_m^T) = n * r 212 print(out) 213 receipt("e2-check", out) 214 215 elif mode == "train": 216 method, lr, seed = sys.argv[2], float(sys.argv[3]), int(sys.argv[4]) 217 steps = int(sys.argv[5]) if len(sys.argv) > 5 else 300 218 bs, accum = 4, 2 219 tok, model = load_model() 220 fit, val, test = splits() 221 base_val = eval_nll(model, tok, val) 222 base_test = eval_nll(model, tok, test) 223 params, ntrain = attach(model, method, seed) 224 opt = torch.optim.AdamW(params, lr=lr, weight_decay=0.0) 225 sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / 20)) 226 g = torch.Generator().manual_seed(seed) 227 order = torch.randperm(len(fit), generator=g).tolist() 228 curve, k = [], 0 229 torch.cuda.reset_peak_memory_stats() 230 t0 = time.time() 231 model.train() 232 for step in range(1, steps + 1): 233 opt.zero_grad(set_to_none=True) 234 tl, tn = 0.0, 0 235 for _ in range(accum): 236 exs = [fit[order[(k + j) % len(fit)]] for j in range(bs)] 237 k += bs 238 x, am, lm = next(answer_batches(tok, exs, bs)) 239 l, n = lm_loss(model, x, am, lm) 240 (l / n / accum).backward() 241 tl += float(l) 242 tn += n 243 opt.step() 244 sched.step() 245 if step % 50 == 0 or step == steps: 246 model.eval() 247 v = eval_nll(model, tok, val) 248 model.train() 249 curve.append({"step": step, "train_nll": tl / tn, "val_nll": v, "t": time.time() - t0}) 250 print(method, lr, seed, curve[-1], flush=True) 251 model.eval() 252 res = {"method": method, "lr": lr, "seed": seed, "steps": steps, "batch": bs * accum, "trainable_params": ntrain, 253 "val_nll_frozen": base_val, "curve": curve, "val_nll": curve[-1]["val_nll"], 254 "test_nll": eval_nll(model, tok, test), "test_nll_frozen": base_test, 255 "peak_gpu_bytes": torch.cuda.max_memory_allocated(), "seconds_unlocked": time.time() - t0} 256 print(res["val_nll"], res["test_nll"], ntrain) 257 receipt(f"e2-train-{method}-{lr:g}-{seed}", res) 258 259 elif mode == "time": 260 reps = {} 261 fit, _, _ = splits() 262 for method in ("none", "lora", "phm", "fourier"): 263 reps[method] = [] 264 for r in range(3): 265 tok, model = load_model() 266 if method == "none": 267 for p in model.parameters(): 268 p.requires_grad_(False) 269 model.model.embed_tokens.weight.requires_grad_(False) 270 params, ntrain = [], 0 271 else: 272 params, ntrain = attach(model, method, 0) 273 opt = torch.optim.AdamW(params, lr=1e-4) if params else None 274 exs = fit[:4] 275 x, am, lm = next(answer_batches(tok, exs, 4)) 276 times = [] 277 torch.cuda.reset_peak_memory_stats() 278 for s in range(12): 279 torch.cuda.synchronize() 280 t0 = time.time() 281 l, n = lm_loss(model, x, am, lm) 282 if params: 283 (l / n).backward() 284 opt.step() 285 opt.zero_grad(set_to_none=True) 286 torch.cuda.synchronize() 287 times.append(time.time() - t0) 288 reps[method].append({"step_s_median_after_warmup": sorted(times[2:])[len(times[2:]) // 2], 289 "peak_gpu_bytes": torch.cuda.max_memory_allocated(), "trainable": ntrain, 290 "tokens_per_step": int(am.sum())}) 291 print(method, r, reps[method][-1], flush=True) 292 del model, opt 293 torch.cuda.empty_cache() 294 receipt("e2-time", {"note": "batch 4 x up to 256 tokens, one optimizer step per timed step; 'none' = forward only, frozen", "repeats": reps})