LFM3-1.7B-Looped-Distilled / scripts /distill_bridge_static.py
vaultpls's picture
LFM3-1.7B Looped-Distilled: static [8-11]x2 loop + distilled re-entry bridge (Q8_0 + bf16)
9113ab0 verified
Raw History Blame Contribute Delete
9.57 kB
#!/usr/bin/env python3
"""Distill the static+bridge teacher into a bridge-free static 28-layer student.
Teacher: published static loop [8,11]x2 alpha=0.5 + rank-64 bridge (the 500-step
checkpoint). Student: the same static loop, no bridge, with LoRA on the copied
layers and four copy-level gates. Targets: the teacher's final hidden states on
a wikitext/GSM8K mix plus next-token CE. If the student matches, it is a plain
28-layer checkpoint that converts to GGUF with no custom op.
"""
import argparse, json, math, os, random, sys, time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
os.environ.setdefault("LFM3_BASE", "/home/vault/lfm3/base-model")
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import tfl
import retrofit_bridge_static as rbs
DATA = "/home/vault/lfm3/train/data"
def gate_hook(module, args, output):
h = args[0]
g = 1.0 + torch.tanh(module._student_gate_raw)
return h + g.to(output.dtype) * (output - h)
def build_student(gate_init=0.0, gates=True):
m, tok = tfl.build((8, 11), reps=2, alpha=0.5)
if gates:
for c in m.model.layers[12:16]:
raw = nn.Parameter(torch.tensor(float(gate_init), device=m.device))
c._student_gate_raw = raw
c.register_forward_hook(gate_hook)
return m, tok
def add_lora(m, rank=64):
from peft import LoraConfig, get_peft_model
cfg = LoraConfig(r=rank, lora_alpha=rank * 2, lora_dropout=0.0, bias="none",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"in_proj", "out_proj", "w1", "w2", "w3"])
m = get_peft_model(m, cfg)
for p in m.parameters():
p.requires_grad_(False)
for n, p in m.named_parameters():
is_copy = any(f".layers.{i}." in n for i in range(12, 16))
if (is_copy and "lora_" in n) or "_student_gate_raw" in n:
p.requires_grad_(True)
m.print_trainable_parameters()
return m
def teacher_hidden(teacher, tok, n_per=250, ctx=1024, data="mix"):
wt = tfl.TextDS(os.path.join(DATA, "wikitext-train.txt"), tok, ctx, max_windows=n_per)
datasets = [wt]
if data != "wiki":
datasets.append(tfl.TextDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, ctx, max_windows=n_per))
windows, hs = [], []
for ds in datasets:
for i in range(len(ds)):
ids = ds[i]["input_ids"].unsqueeze(0).cuda()
with torch.no_grad():
h = teacher.model(input_ids=ids).last_hidden_state
windows.append(ds[i]["input_ids"])
hs.append(h[0].to(torch.bfloat16).cpu())
print(f"teacher hidden: {len(windows)} windows x {ctx} = {len(windows)*ctx/1e6:.1f}M tokens")
return windows, hs
def train(args):
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
teacher, tok = rbs.build(alpha=0.5, rank=64)
ck = torch.load(args.teacher_ckpt, map_location="cpu")
miss, unexp = teacher.load_state_dict(ck["state"], strict=False)
print("teacher loaded", ck["step"], "missing", len(miss), "unexpected", len(unexp))
teacher.eval()
for p in teacher.parameters():
p.requires_grad_(False)
windows, hs = teacher_hidden(teacher, tok, args.windows, args.ctx, args.data)
del teacher
torch.cuda.empty_cache()
student, _ = build_student(gates=bool(args.gates))
student = add_lora(student, args.rank)
if args.grad_ckpt:
student.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
student.enable_input_require_grads()
print("gradient checkpointing: on")
base = student.get_base_model()
V = base.config.vocab_size
trainable = [p for p in student.parameters() if p.requires_grad]
g_lora = [p for n, p in student.named_parameters() if p.requires_grad and "lora_" in n]
g_gate = [p for n, p in student.named_parameters() if p.requires_grad and "_student_gate_raw" in n]
print(f"param groups: lora {len(g_lora)} @ {args.lr}, gates {len(g_gate)} @ {args.gate_lr}")
pg = [{"params": g_lora, "lr": args.lr}]
if g_gate:
pg.append({"params": g_gate, "lr": args.gate_lr})
opt = torch.optim.AdamW(pg, betas=(0.9, 0.95), weight_decay=0.0)
sched = torch.optim.lr_scheduler.LambdaLR(
opt, lambda s: min(1.0, (s + 1) / max(1, args.warmup)) *
(0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(1.0, s / max(1, args.steps))))))
student.train()
t0 = time.time(); run_ce = run_mse = 0.0
os.makedirs(args.out, exist_ok=True)
for step in range(1, args.steps + 1):
idx = [random.randrange(len(windows)) for _ in range(args.bs)]
ids = torch.stack([windows[i] for i in idx]).cuda()
ht = torch.stack([hs[i] for i in idx]).cuda().float()
with torch.autocast("cuda", dtype=torch.bfloat16):
h = base.model(input_ids=ids).last_hidden_state
logits = base.lm_head(h)
ce = F.cross_entropy(logits[:, :-1].reshape(-1, V), ids[:, 1:].reshape(-1))
mse = F.mse_loss(h.float(), ht) / (ht.pow(2).mean() + 1e-6)
loss = ce + args.mse * mse
loss.backward()
torch.nn.utils.clip_grad_norm_(trainable, 1.0)
opt.step(); sched.step(); opt.zero_grad(set_to_none=True)
run_ce += ce.item(); run_mse += mse.item()
if step % 20 == 0:
gates = [round(float(1 + torch.tanh(g.detach())), 4) for g in g_gate]
gs = f" gates {gates}" if gates else ""
print(f"step {step:4d} CE {run_ce/20:.4f} MSE {run_mse/20:.4f} "
f"lr {sched.get_last_lr()[0]:.2e}{gs} {(time.time()-t0)/step:.2f}s/it", flush=True)
run_ce = run_mse = 0.0
if step % args.eval_every == 0 or step == args.steps:
student.eval()
ev_wt = tfl.StreamDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=32)
ev_gs = tfl.StreamDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=32)
print(f" [eval] wiki PPL {tfl.ppl(student, ev_wt, 16):.4f} gsm-text PPL {tfl.ppl(student, ev_gs, 16):.4f}", flush=True)
student.train()
save(student, tok, args.out, step)
save(student, tok, args.out, args.steps)
print("saved", args.out)
def save(m, tok, outdir, step):
os.makedirs(outdir, exist_ok=True)
sd = {k: v.detach().cpu() for k, v in m.state_dict().items()
if "lora_" in k or "_student_gate_raw" in k}
torch.save({"step": step, "state": sd}, os.path.join(outdir, "ckpt.pt"))
tok.save_pretrained(outdir)
def eval_ckpt(args):
student, tok = build_student(gates=bool(args.gates))
student = add_lora(student, args.rank)
ckpath = args.ckpt or os.path.join(args.out, "ckpt.pt")
ck = torch.load(ckpath, map_location="cpu")
miss, unexp = student.load_state_dict(ck["state"], strict=False)
print("student loaded", ck["step"], "missing", len(miss), "unexpected", len(unexp))
student.eval()
ev_wt = tfl.StreamDS(os.path.join(DATA, "wikitext-test.txt"), tok, 1024, max_windows=32)
ev_gs = tfl.StreamDS(os.path.join(DATA, "gsm8k-train-chat.txt"), tok, 1024, max_windows=32)
print(json.dumps({"tag": "distilled", "wikitext": round(tfl.ppl(student, ev_wt, 16), 4),
"gsm8k_text": round(tfl.ppl(student, ev_gs, 16), 4)}))
if args.arc:
rows, pre = tfl.arc_rows(args.arc_config, args.arc, 5)
t0 = time.time()
per, lps = tfl.run_arc(student, tok, rows, pre, "mean", dump=True)
print(f"distilled: {args.arc_config} 5-shot {sum(per)/len(per)*100:.1f}% over {len(per)} ({time.time()-t0:.0f}s)")
json.dump({"per": per, "lp": lps}, open(os.path.join(args.out, f"arc-{args.arc_config}-distilled.json"), "w"))
if args.gsm:
rows = tfl.gsm8k_rows(args.gsm)
t0 = time.time()
per = tfl.run_gsm8k(student, tok, rows, dump=True)
print(f"distilled: GSM8K {sum(per)/len(per)*100:.1f}% over {len(rows)} ({time.time()-t0:.0f}s)")
json.dump(per, open(os.path.join(args.out, "gsm-distilled.json"), "w"))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("cmd", choices=["train", "eval"])
ap.add_argument("--out", default="/home/vault/lfm3/train/out-distill")
ap.add_argument("--teacher-ckpt", default="/home/vault/lfm3/train/out-static-bridge/ckpt.pt")
ap.add_argument("--steps", type=int, default=500)
ap.add_argument("--bs", type=int, default=2)
ap.add_argument("--ctx", type=int, default=1024)
ap.add_argument("--windows", type=int, default=250, help="windows per corpus")
ap.add_argument("--data", choices=["mix", "wiki"], default="mix")
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--gate-lr", type=float, default=5e-3)
ap.add_argument("--rank", type=int, default=64)
ap.add_argument("--mse", type=float, default=1.0)
ap.add_argument("--warmup", type=int, default=40)
ap.add_argument("--eval-every", type=int, default=250)
ap.add_argument("--gates", type=int, default=1)
ap.add_argument("--grad-ckpt", type=int, default=1)
ap.add_argument("--ckpt", default=None)
ap.add_argument("--arc", type=int, default=0)
ap.add_argument("--arc-config", default="ARC-Easy")
ap.add_argument("--gsm", type=int, default=0)
args = ap.parse_args()
if args.cmd == "train":
train(args)
else:
eval_ckpt(args)
if __name__ == "__main__":
main()