mudassiruddin21 commited on
Commit
0ec358a
·
verified ·
1 Parent(s): a64b4b7

LoRA recipe and low-rank analysis

Browse files
Files changed (4) hide show
  1. emcdraft/ablate.py +4 -0
  2. emcdraft/head.py +26 -2
  3. emcdraft/train.py +59 -3
  4. tests/test_head.py +10 -2
emcdraft/ablate.py CHANGED
@@ -15,6 +15,8 @@ Recipes (each adds one published idea to the one before it):
15
  accw_topk_mask + later steps trained almost only where the engine reaches them
16
  (token-alignable training, GRIFFIN): floor 0.3 -> 0.1
17
  accw_topk_lr2 accw_topk with twice the learning rate
 
 
18
 
19
  python -m emcdraft.ablate --target DIR --init DIR --data DIR --out runs/ablate --results results --state state
20
  """
@@ -35,6 +37,8 @@ RECIPES = [
35
  ["--step-w", "auto", "--topk", "10", "--floor", "0.1", "--rel-lr", "1e-3"]),
36
  ("accw_topk_lr2", "accw_topk + twice the learning rate",
37
  ["--step-w", "auto", "--topk", "10", "--floor", "0.3", "--rel-lr", "2e-3"]),
 
 
38
  ]
39
 
40
 
 
15
  accw_topk_mask + later steps trained almost only where the engine reaches them
16
  (token-alignable training, GRIFFIN): floor 0.3 -> 0.1
17
  accw_topk_lr2 accw_topk with twice the learning rate
18
+ accw_topk_lora accw_topk, but only rank-128 updates of every matrix are learned (LoRA, Hu et
19
+ al. 2021) and merged before export - a low-rank constraint on what changes
20
 
21
  python -m emcdraft.ablate --target DIR --init DIR --data DIR --out runs/ablate --results results --state state
22
  """
 
37
  ["--step-w", "auto", "--topk", "10", "--floor", "0.1", "--rel-lr", "1e-3"]),
38
  ("accw_topk_lr2", "accw_topk + twice the learning rate",
39
  ["--step-w", "auto", "--topk", "10", "--floor", "0.3", "--rel-lr", "2e-3"]),
40
+ ("accw_topk_lora", "accw_topk with rank-128 LoRA adapters instead of full fine-tuning",
41
+ ["--step-w", "auto", "--topk", "10", "--floor", "0.3", "--rel-lr", "1e-3", "--lora", "128"]),
42
  ]
43
 
44
 
emcdraft/head.py CHANGED
@@ -20,6 +20,7 @@ checkpoint names without the ``mtp.`` prefix) and adds what training needs:
20
  from __future__ import annotations
21
 
22
  import json
 
23
  import struct
24
  from dataclasses import dataclass
25
  from pathlib import Path
@@ -108,14 +109,37 @@ def e4m3_decode(b: torch.Tensor) -> torch.Tensor:
108
 
109
 
110
  class QLinear(nn.Linear):
111
- """Bias-free linear layer; ``fq=True`` fake-quantises the weight to E4M3 (STE)."""
 
 
 
 
112
 
113
  def __init__(self, i: int, o: int):
114
  super().__init__(i, o, bias=False)
115
  self.fq = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
  def qweight(self) -> torch.Tensor:
118
- w = self.weight
119
  return w + (e4m3_round(w) - w).detach() if self.fq else w
120
 
121
  def forward(self, x: torch.Tensor) -> torch.Tensor:
 
20
  from __future__ import annotations
21
 
22
  import json
23
+ import math
24
  import struct
25
  from dataclasses import dataclass
26
  from pathlib import Path
 
109
 
110
 
111
  class QLinear(nn.Linear):
112
+ """Bias-free linear layer; ``fq=True`` fake-quantises the weight to E4M3 (STE).
113
+
114
+ ``add_lora(r)`` freezes the weight and learns a rank-r update B @ A instead (LoRA, Hu et
115
+ al. 2021); ``merge_lora()`` folds it back into the weight, so exported files keep the
116
+ engine's dense layout."""
117
 
118
  def __init__(self, i: int, o: int):
119
  super().__init__(i, o, bias=False)
120
  self.fq = False
121
+ self.lora_a = self.lora_b = None
122
+
123
+ def add_lora(self, r: int):
124
+ o, i = self.weight.shape
125
+ dev = self.weight.device
126
+ self.weight.requires_grad_(False)
127
+ self.lora_a = nn.Parameter(torch.randn(r, i, device=dev) / math.sqrt(i))
128
+ self.lora_b = nn.Parameter(torch.zeros(o, r, device=dev))
129
+
130
+ @torch.no_grad()
131
+ def merge_lora(self):
132
+ if self.lora_a is not None:
133
+ self.weight.copy_(self.dense_weight())
134
+ self.lora_a = self.lora_b = None
135
+ self.weight.requires_grad_(True)
136
+
137
+ def dense_weight(self) -> torch.Tensor:
138
+ w = self.weight
139
+ return w if self.lora_a is None else w + (self.lora_b @ self.lora_a).to(w.dtype)
140
 
141
  def qweight(self) -> torch.Tensor:
142
+ w = self.dense_weight()
143
  return w + (e4m3_round(w) - w).detach() if self.fq else w
144
 
145
  def forward(self, x: torch.Tensor) -> torch.Tensor:
emcdraft/train.py CHANGED
@@ -23,7 +23,7 @@ from pathlib import Path
23
  import torch
24
  import torch.nn.functional as F
25
 
26
- from .head import (FP8_TENSORS, HeadConfig, build_head, e4m3_round, equalize_, export_submission,
27
  load_mtp_state, load_target_tensors, unroll)
28
  from .sim import DOMAINS, batches, collate, load_shards, shards_bytes, simulate
29
 
@@ -95,6 +95,34 @@ def train_step(head, embed, W, batch, a, K=3):
95
  return total, info
96
 
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  def split_val(seqs, frac, rng):
99
  by = {}
100
  for s in seqs:
@@ -132,6 +160,10 @@ def main():
132
  ap.add_argument("--step-w", nargs="+", default=os.environ.get("TRAIN_STEP_W", "1 0.7 0.5").split(),
133
  help="three step weights, or 'auto': each step weighted by the derivative of the "
134
  "acceptance length with respect to its accuracy")
 
 
 
 
135
  ap.add_argument("--max-steps", type=int, default=0, help="cap on optimizer steps (short ablation runs)")
136
  ap.add_argument("--no-export", action="store_true", help="ablation run: no submission folders")
137
  ap.add_argument("--quick", action="store_true", help="ablation run: simulate the validation set only")
@@ -203,10 +235,27 @@ def main():
203
  head.set_fake_quant(True)
204
  sims("fp8_untrained")
205
 
 
 
 
 
 
 
 
 
206
  groups = []
207
  for n, p in head.named_parameters():
208
- eff = (1 + p.detach()) if p.ndim == 1 else p.detach()
209
- groups.append({"params": [p], "base": a.rel_lr * float(eff.float().pow(2).mean().sqrt()), "lr": 0.0})
 
 
 
 
 
 
 
 
 
210
  opt = torch.optim.AdamW(groups, betas=(0.9, 0.95), eps=1e-10, weight_decay=0.0)
211
 
212
  per_epoch = len(batches(train, a.batch_tokens))
@@ -270,6 +319,9 @@ def main():
270
  done = True
271
  break
272
  head.load_state_dict(best["state"])
 
 
 
273
  head.eval()
274
  summary["history"] = hist
275
  summary["best_step"] = best["step"]
@@ -287,6 +339,7 @@ def main():
287
  "built-in head and fine-tuned with a 3-step recursive drafting objective"
288
  + (", acceptance-aware step weights" if auto_w else "")
289
  + (f", top-{a.topk} distillation" if a.topk else "")
 
290
  + (" and FP8 (E4M3) quantisation-aware training" if a.qat else "")),
291
  "training_data": ("Greedy answers of the target itself (with its hidden states) to public "
292
  "instruction prompts: GSM8K/Orca-Math, WritingPrompts, UltraChat/Alpaca/Dolly, "
@@ -302,6 +355,9 @@ def main():
302
  head.set_fake_quant(False)
303
  sims("final_bf16")
304
  summary["export_bf16"] = export_submission(head, out / "sub_bf16", tcfg, False, meta)
 
 
 
305
  summary["total_seconds"] = round(time.time() - t_start, 1)
306
  (out / "train_summary.json").write_text(json.dumps(summary, indent=2, default=str))
307
  log("training finished")
 
23
  import torch
24
  import torch.nn.functional as F
25
 
26
+ from .head import (FP8_TENSORS, HeadConfig, QLinear, build_head, e4m3_round, equalize_, export_submission,
27
  load_mtp_state, load_target_tensors, unroll)
28
  from .sim import DOMAINS, batches, collate, load_shards, shards_bytes, simulate
29
 
 
95
  return total, info
96
 
97
 
98
+ @torch.no_grad()
99
+ def lowrank_analysis(head, embed, W, val, dev_seqs, ranks):
100
+ """Acceptance when every matrix of the head is replaced by its best rank-r approximation
101
+ (truncated SVD): how much a low-rank head would lose. The engine runs dense layers only,
102
+ so this is an analysis; the exported files are unaffected."""
103
+ lin = {n: m for n, m in head.named_modules() if isinstance(m, QLinear)}
104
+ keep = {n: m.weight.detach().clone() for n, m in lin.items()}
105
+ svd = {n: torch.linalg.svd(w.float(), full_matrices=False) for n, w in keep.items()}
106
+ dense = sum(w.numel() for w in keep.values())
107
+ rows = []
108
+ for r in sorted(ranks):
109
+ for n, m in lin.items():
110
+ U, S, Vh = svd[n]
111
+ k = min(r, S.numel())
112
+ m.weight.copy_(((U[:, :k] * S[:k]) @ Vh[:k]).to(m.weight.dtype))
113
+ factored = sum(min(r, min(w.shape)) * sum(w.shape) for w in keep.values())
114
+ row = {"rank": r, "matrix_params_factored": factored, "matrix_params_dense": dense,
115
+ "val_tau": simulate(head, embed, W, val)["acceptance_length"]}
116
+ if dev_seqs:
117
+ row["dev_tau"] = simulate(head, embed, W, dev_seqs)["acceptance_length"]
118
+ rows.append(row)
119
+ log(f"low-rank r={r}: matrix parameters {factored / 1e6:.0f} M of {dense / 1e6:.0f} M, val tau "
120
+ f"{row['val_tau']:.4f}" + (f", dev tau {row['dev_tau']:.4f}" if dev_seqs else ""))
121
+ for n, m in lin.items():
122
+ m.weight.copy_(keep[n])
123
+ return rows
124
+
125
+
126
  def split_val(seqs, frac, rng):
127
  by = {}
128
  for s in seqs:
 
160
  ap.add_argument("--step-w", nargs="+", default=os.environ.get("TRAIN_STEP_W", "1 0.7 0.5").split(),
161
  help="three step weights, or 'auto': each step weighted by the derivative of the "
162
  "acceptance length with respect to its accuracy")
163
+ ap.add_argument("--lora", type=int, default=int(os.environ.get("TRAIN_LORA", 0)),
164
+ help="train rank-r adapters on every matrix instead of the matrices themselves (0: off)")
165
+ ap.add_argument("--lowrank-ranks", default=os.environ.get("TRAIN_LOWRANK_RANKS", "256,512,1024,2048"),
166
+ help="after training: acceptance with every matrix cut to these ranks (SVD), for analysis")
167
  ap.add_argument("--max-steps", type=int, default=0, help="cap on optimizer steps (short ablation runs)")
168
  ap.add_argument("--no-export", action="store_true", help="ablation run: no submission folders")
169
  ap.add_argument("--quick", action="store_true", help="ablation run: simulate the validation set only")
 
235
  head.set_fake_quant(True)
236
  sims("fp8_untrained")
237
 
238
+ mods = dict(head.named_modules())
239
+ if a.lora:
240
+ for m in mods.values():
241
+ if isinstance(m, QLinear):
242
+ m.add_lora(a.lora)
243
+ log(f"LoRA rank {a.lora}: {sum(p.numel() for p in head.parameters() if p.requires_grad) / 1e6:.1f} M "
244
+ f"trainable parameters")
245
+ rms = lambda t: float(t.detach().float().pow(2).mean().sqrt())
246
  groups = []
247
  for n, p in head.named_parameters():
248
+ if not p.requires_grad:
249
+ continue
250
+ if n.endswith("lora_b"):
251
+ # an Adam step of size lr on B moves B @ A by about lr * sqrt(r / in) per entry;
252
+ # match the relative step of full fine-tuning on the frozen matrix
253
+ m = mods[n.rsplit(".", 1)[0]]
254
+ base = a.rel_lr * rms(m.weight) * math.sqrt(m.weight.shape[1] / a.lora)
255
+ else:
256
+ eff = (1 + p.detach()) if p.ndim == 1 else p.detach()
257
+ base = a.rel_lr * rms(eff)
258
+ groups.append({"params": [p], "base": base, "lr": 0.0})
259
  opt = torch.optim.AdamW(groups, betas=(0.9, 0.95), eps=1e-10, weight_decay=0.0)
260
 
261
  per_epoch = len(batches(train, a.batch_tokens))
 
319
  done = True
320
  break
321
  head.load_state_dict(best["state"])
322
+ for m in head.modules():
323
+ if isinstance(m, QLinear):
324
+ m.merge_lora()
325
  head.eval()
326
  summary["history"] = hist
327
  summary["best_step"] = best["step"]
 
339
  "built-in head and fine-tuned with a 3-step recursive drafting objective"
340
  + (", acceptance-aware step weights" if auto_w else "")
341
  + (f", top-{a.topk} distillation" if a.topk else "")
342
+ + (f", rank-{a.lora} LoRA adapters merged into the weights" if a.lora else "")
343
  + (" and FP8 (E4M3) quantisation-aware training" if a.qat else "")),
344
  "training_data": ("Greedy answers of the target itself (with its hidden states) to public "
345
  "instruction prompts: GSM8K/Orca-Math, WritingPrompts, UltraChat/Alpaca/Dolly, "
 
355
  head.set_fake_quant(False)
356
  sims("final_bf16")
357
  summary["export_bf16"] = export_submission(head, out / "sub_bf16", tcfg, False, meta)
358
+ if a.lowrank_ranks:
359
+ summary["lowrank"] = lowrank_analysis(head, embed, W, val, dev_seqs,
360
+ [int(x) for x in a.lowrank_ranks.split(",") if x.strip()])
361
  summary["total_seconds"] = round(time.time() - t_start, 1)
362
  (out / "train_summary.json").write_text(json.dumps(summary, indent=2, default=str))
363
  log("training finished")
tests/test_head.py CHANGED
@@ -253,7 +253,7 @@ def test_recipes(head, E, W):
253
  from emcdraft.head import save_safetensors_raw
254
  from emcdraft.sim import save_shard
255
  root = Path(__file__).resolve().parents[1]
256
- env = dict(os.environ, PYTHONPATH=str(root), TRAIN_DATA_DEVICE="cpu")
257
  with tempfile.TemporaryDirectory() as tmp:
258
  tmp = Path(tmp)
259
  tgt, init, data = tmp / "target", tmp / "init", tmp / "data"
@@ -286,11 +286,19 @@ def test_recipes(head, E, W):
286
  assert "acceptance-aware" in meta["method_description"] and "top-5" in meta["method_description"]
287
  assert len(s["history"]) == 2 and (tmp / "full" / "sub_bf16" / "model.safetensors").exists()
288
  assert "w [" in r.stdout, "auto step weights not reported"
 
 
 
 
 
 
 
 
289
  r = run(["emcdraft.ablate", *common, "--out", str(tmp / "abl"), "--results", str(tmp / "res"),
290
  "--state", str(tmp), "--qat", "--steps", "2"])
291
  assert r.returncode == 0, r.stdout[-2000:] + r.stderr[-3000:]
292
  ab = json.loads((tmp / "res" / "ablation.json").read_text())
293
- assert set(ab["recipes"]) == {"control", "accw_topk", "accw_topk_mask", "accw_topk_lr2"}
294
  assert (tmp / "train_args").read_text().split() == ab["recipes"][ab["chosen"]]["flags"]
295
  assert not any((tmp / "abl" / n / "sub_fp8").exists() for n in ab["recipes"]), "ablation runs must not export"
296
  # keep-the-better-draft rule
 
253
  from emcdraft.head import save_safetensors_raw
254
  from emcdraft.sim import save_shard
255
  root = Path(__file__).resolve().parents[1]
256
+ env = dict(os.environ, PYTHONPATH=str(root), TRAIN_DATA_DEVICE="cpu", TRAIN_LOWRANK_RANKS="4,8")
257
  with tempfile.TemporaryDirectory() as tmp:
258
  tmp = Path(tmp)
259
  tgt, init, data = tmp / "target", tmp / "init", tmp / "data"
 
286
  assert "acceptance-aware" in meta["method_description"] and "top-5" in meta["method_description"]
287
  assert len(s["history"]) == 2 and (tmp / "full" / "sub_bf16" / "model.safetensors").exists()
288
  assert "w [" in r.stdout, "auto step weights not reported"
289
+ assert [x["rank"] for x in s["lowrank"]] == [4, 8] and all(x["val_tau"] >= 1 for x in s["lowrank"])
290
+ r = run(["emcdraft.train", *common, "--out", str(tmp / "lora"), "--qat", "--lora", "4", "--max-steps", "3",
291
+ "--eval-every", "3", "--batch-tokens", "200", "--lowrank-ranks", ""])
292
+ assert r.returncode == 0, r.stdout[-2000:] + r.stderr[-3000:]
293
+ merged = load_mtp_state(tmp / "lora" / "sub_bf16")
294
+ assert set(merged) == set(head.state_dict()), "LoRA must merge into the dense layout"
295
+ changed = [n for n in FP8_TENSORS if not torch.equal(merged[n], load_mtp_state(init)[n])]
296
+ assert "LoRA rank 4" in r.stdout and changed, "LoRA training did not change the matrices"
297
  r = run(["emcdraft.ablate", *common, "--out", str(tmp / "abl"), "--results", str(tmp / "res"),
298
  "--state", str(tmp), "--qat", "--steps", "2"])
299
  assert r.returncode == 0, r.stdout[-2000:] + r.stderr[-3000:]
300
  ab = json.loads((tmp / "res" / "ablation.json").read_text())
301
+ assert set(ab["recipes"]) == {"control", "accw_topk", "accw_topk_mask", "accw_topk_lr2", "accw_topk_lora"}
302
  assert (tmp / "train_args").read_text().split() == ab["recipes"][ab["chosen"]]["flags"]
303
  assert not any((tmp / "abl" / n / "sub_fp8").exists() for n in ab["recipes"]), "ablation runs must not export"
304
  # keep-the-better-draft rule