Download code/src/train/train_lora.py from bryan7264/lorapop: direct link, hf CLI and curl.
- Browser
- Download file 6.23 kB
-
https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/train/train_lora.py
- Command line
-
hf download hf://datasets/bryan7264/lorapop/code/src/train/train_lora.py
-
curl -L -o train_lora.py https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/train/train_lora.py
6.23 kB
| # MIT License, Bryan Cheng, 2026. | |
| """Train LoRA adapters for the controlled populations (RESEARCH_PLAN 6). Many runs per process to amortise model load. | |
| python src/train/train_lora.py --base Qwen/Qwen2.5-0.5B-Instruct --runs runs.jsonl --out data/raw/trained/<set> | |
| runs.jsonl: one JSON per line {"name", "data" (jsonl of {"messages": [...]}), "r", "seed", "init_seed", "n", "lr"}. | |
| A is initialised under torch.manual_seed(init_seed) (shared init = same init_seed across seeds); data order and dropout | |
| use seed. Saves PEFT adapter + the initial A factors (init_A.safetensors) + train log. Also writes, once per data file, | |
| the first-step base gradient per module (grad_<datafile>.pt) for the law's effective dimension. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| import sys | |
| import time | |
| import torch | |
| from safetensors.torch import save_file | |
| TARGETS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"] | |
| def load_data(path, tok, n, seed, max_len=512): | |
| rows = [json.loads(l) for l in open(path)] | |
| random.Random(seed).shuffle(rows) | |
| out = [] | |
| for r in rows[:n]: | |
| msgs = r["messages"] | |
| full = tok.apply_chat_template(msgs, tokenize=False) | |
| prompt = tok.apply_chat_template(msgs[:-1], tokenize=False, add_generation_prompt=True) | |
| ids = tok(full, add_special_tokens=False, truncation=True, max_length=max_len)["input_ids"] | |
| npr = len(tok(prompt, add_special_tokens=False)["input_ids"]) | |
| labels = [-100] * min(npr, len(ids)) + ids[npr:] | |
| if any(l != -100 for l in labels): | |
| out.append((ids, labels)) | |
| return out | |
| def batches(data, bs, pad): | |
| for s in range(0, len(data), bs): | |
| b = data[s:s + bs] | |
| L = max(len(x) for x, _ in b) | |
| ids = torch.full((len(b), L), pad) | |
| lab = torch.full((len(b), L), -100) | |
| am = torch.zeros((len(b), L), dtype=torch.long) | |
| for i, (x, y) in enumerate(b): | |
| ids[i, :len(x)] = torch.tensor(x) | |
| lab[i, :len(y)] = torch.tensor(y) | |
| am[i, :len(x)] = 1 | |
| yield ids, lab, am | |
| def base_gradient(model, data, pad, dev, nb=4, bs=8): | |
| """Average gradient of the loss w.r.t. every target weight at the base (B = 0), over nb batches.""" | |
| model.zero_grad() | |
| for p in model.parameters(): | |
| p.requires_grad_(False) | |
| ws = {} | |
| for li, layer in enumerate(model.model.layers): | |
| for n, m in layer.named_modules(): | |
| if n.split(".")[-1] in TARGETS and isinstance(m, torch.nn.Linear): | |
| m.weight.requires_grad_(True) | |
| ws[f"{li}.{n.split('.')[-1]}"] = m.weight | |
| for i, (ids, lab, am) in enumerate(batches(data[:nb * bs], bs, pad)): | |
| loss = model(input_ids=ids.to(dev), attention_mask=am.to(dev), labels=lab.to(dev)).loss / nb | |
| loss.backward() | |
| g = {k: w.grad.detach().float().cpu().to(torch.bfloat16) for k, w in ws.items()} | |
| for w in ws.values(): | |
| w.grad = None | |
| w.requires_grad_(False) | |
| return g | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--base", required=True) | |
| ap.add_argument("--runs", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--bs", type=int, default=8) | |
| a = ap.parse_args() | |
| from peft import LoraConfig, get_peft_model | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| dev = "cuda" | |
| tok = AutoTokenizer.from_pretrained(a.base) | |
| pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id | |
| os.makedirs(a.out, exist_ok=True) | |
| runs = [json.loads(l) for l in open(a.runs)] | |
| for run in runs: | |
| od = os.path.join(a.out, run["name"]) | |
| if os.path.exists(os.path.join(od, "_ok")): | |
| continue | |
| t0 = time.time() | |
| base = AutoModelForCausalLM.from_pretrained(a.base, dtype=torch.bfloat16).to(dev) | |
| data = load_data(run["data"], tok, run.get("n", 1000), run["seed"]) | |
| one = list(data) | |
| for ep in range(1, run.get("epochs", 1)): | |
| random.Random(run["seed"] * 100 + ep).shuffle(one) | |
| data = data + list(one) | |
| gfile = os.path.join(a.out, "grad_" + os.path.basename(run["data"]).replace(".jsonl", ".pt")) | |
| if not os.path.exists(gfile): | |
| torch.save(base_gradient(base, data, pad, dev), gfile) | |
| torch.manual_seed(run["init_seed"]) | |
| cfg = LoraConfig(r=run["r"], lora_alpha=run.get("alpha", 2 * run["r"]), target_modules=TARGETS, | |
| lora_dropout=0.0, bias="none", task_type="CAUSAL_LM") | |
| model = get_peft_model(base, cfg) | |
| init_A = {k: v.detach().float().cpu().contiguous() for k, v in model.state_dict().items() if "lora_A" in k} | |
| torch.manual_seed(run["seed"]) | |
| opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=run.get("lr", 2e-4), | |
| weight_decay=0.0) | |
| steps = (len(data) + a.bs - 1) // a.bs | |
| sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / 20) * max(0.0, 1 - s / steps)) | |
| model.train() | |
| losses = [] | |
| for ids, lab, am in batches(data, a.bs, pad): | |
| loss = model(input_ids=ids.to(dev), attention_mask=am.to(dev), labels=lab.to(dev)).loss | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step() | |
| sched.step() | |
| opt.zero_grad() | |
| losses.append(float(loss)) | |
| model.save_pretrained(od) | |
| save_file(init_A, os.path.join(od, "init_A.safetensors")) | |
| log = {**run, "steps": steps, "loss_first10": sum(losses[:10]) / max(1, len(losses[:10])), | |
| "loss_last10": sum(losses[-10:]) / max(1, len(losses[-10:])), "seconds": time.time() - t0, | |
| "base": a.base, "grad_file": gfile} | |
| json.dump(log, open(os.path.join(od, "train_log.json"), "w")) | |
| open(os.path.join(od, "_ok"), "w").write("ok") | |
| print(run["name"], round(log["loss_first10"], 3), "->", round(log["loss_last10"], 3), round(log["seconds"]), "s", | |
| flush=True) | |
| del model, base, opt | |
| torch.cuda.empty_cache() | |
| print("TRAINDONE", flush=True) | |
| if __name__ == "__main__": | |
| main() | |