sn38-quality-sft / train.py
cryptoDev23's picture
add train.py for VPS SFT
d57e955 verified
Raw History Blame Contribute Delete
22.2 kB
#!/usr/bin/env python3
"""SN38 full-parameter continued pretraining (CPT) / SFT for sn38-nanochrono.
Run from the sn38 repo env so the architecture is registered:
cd /opt/sn38 && PYTHONPATH=/opt/sn38 uv run python /opt/work/train.py --mode cpt ...
What is implemented (see README section "What the research says"):
* CPT: sources sampled by --mix; documents packed BEST-FIT (whole docs, no needless truncation),
each sequence gets a block-diagonal DOCUMENT MASK so tokens never attend across documents (--doc-mask).
* Loss computed in chunks (never materialises the full fp32 [B,T,32768] logits), -100 labels respected.
* LR: linear warm-up then cosine re-decay to 10% (re-warm + re-decay recipe for CPT).
* Held-out validation per source group (new-2024 vs replay) and a probe set (year,sentence,phrase csv)
scored exactly like the validator's leak.py (BOS+prompt, phrase with leading space, sum log-prob, epsilon).
* SFT: loss only on response + EOS (position-based mask, so EOS==PAD is NOT a problem), asserts the EOS is a target.
* bf16 autocast with fp32 master weights, fused AdamW, grad clip, optional activation checkpointing / torch.compile.
Saves HF layout (config.json, model.safetensors [bf16], tokenizer, generation_config.json) + a symlink `latest`.
"""
import argparse, csv, glob, gzip, json, math, os, random, time
# Multi-GPU: torchrun --standalone --nproc_per_node 8 train.py ... (data parallel, grads averaged after accumulation;
# --global-tokens is the TOTAL per optimizer step across GPUs). --resume restarts from <out>/resume.pt (spot instances).
import torch, torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
import sn38.architectures # noqa: registers sn38-nanochrono / nanoexpand / miniformer
sn38.architectures.register_all()
IGN = -100
# ------------------------------------------------------------------ data: sources
def docs_from_source(src_dir, seed, skip=0):
"""Infinite shuffled stream of texts; the first `skip` docs of the first shard are held out (validation)."""
files = sorted(glob.glob(os.path.join(src_dir, "part-*.jsonl.gz")))
if not files:
raise SystemExit(f"no shards in {src_dir}")
rng = random.Random(seed)
epoch = 0
while True:
order = files[:]; rng.shuffle(order)
for f in order:
with gzip.open(f, "rt", encoding="utf-8") as fh:
for i, line in enumerate(fh):
if f == files[0] and i < skip:
continue
yield json.loads(line)["text"]
epoch += 1
print(f"[data] {os.path.basename(src_dir)} epoch {epoch} done", flush=True)
def heldout_docs(src_dir, n):
files = sorted(glob.glob(os.path.join(src_dir, "part-*.jsonl.gz")))
out = []
with gzip.open(files[0], "rt", encoding="utf-8") as fh:
for i, line in enumerate(fh):
if i >= n: break
out.append(json.loads(line)["text"])
return out
# ------------------------------------------------------------------ data: best-fit packing + doc mask
class Packer:
"""Best-fit-decreasing packing of whole documents into seq+1 windows.
Docs longer than seq+1 are split into seq+1 chunks (unavoidable); everything else is never truncated.
Yields (ids[B,T+1], labels[B,T+1], docid[B,T+1]) ; pad positions have label -100."""
def __init__(self, tok, seq, micro_bs, buffer_docs=512):
self.tok, self.L, self.B, self.buf_n = tok, seq + 1, micro_bs, buffer_docs
self.bos, self.eos, self.pad = tok.bos_token_id, tok.eos_token_id, tok.pad_token_id
def _chunks(self, texts):
for ids in self.tok(texts, add_special_tokens=False)["input_ids"]:
ids = [self.bos] + ids + [self.eos]
for i in range(0, len(ids), self.L):
yield ids[i:i + self.L]
def pack(self, chunks):
chunks.sort(key=len, reverse=True)
bins = [] # list of [free, [chunk,...]]
for c in chunks:
best = None
for b in bins:
if b[0] >= len(c) and (best is None or b[0] < best[0]):
best = b
if best is None:
bins.append([self.L - len(c), [c]])
else:
best[0] -= len(c); best[1].append(c)
return bins
def stream(self, doc_iter):
carry = []
while True:
texts = [next(doc_iter) for _ in range(self.buf_n)]
bins = self.pack(carry + list(self._chunks(texts)))
bins.sort(key=lambda b: b[0]) # fullest bins first
keep = len(bins) - len(bins) % self.B
carry = [c for b in bins[keep:] for c in b[1]] # sparse leftovers are re-packed next round
for i in range(0, keep, self.B):
yield self._tensorise(bins[i:i + self.B])
def _tensorise(self, bins):
ids = torch.full((self.B, self.L), self.pad, dtype=torch.long)
lab = torch.full((self.B, self.L), IGN, dtype=torch.long)
doc = torch.zeros((self.B, self.L), dtype=torch.long)
for r, (_, chunks) in enumerate(bins):
p = 0
for d, c in enumerate(chunks, start=1):
ids[r, p:p + len(c)] = torch.tensor(c); lab[r, p:p + len(c)] = torch.tensor(c)
doc[r, p:p + len(c)] = d; p += len(c)
return ids, lab, doc
def mixed_docs(corpus, mix, seed, skip):
names = list(mix); weights = [mix[n] for n in names]
gens = {n: docs_from_source(os.path.join(corpus, n), seed + i, skip) for i, n in enumerate(names)}
rng = random.Random(seed)
while True:
yield next(gens[rng.choices(names, weights)[0]])
_DOC_MASK = {"m": None}
def install_doc_mask(model):
"""Patch nanochrono attention so a block-diagonal document mask is AND-ed with causal/sliding masks."""
import sn38.architectures.nanochrono.modeling_nanochrono as mn
orig = mn.NanochronoAttention._attend
def _attend(self, q, k, v, window, mask, past_len):
dm = _DOC_MASK["m"]
if dm is None or q.size(2) != k.size(2):
return orig(self, q, k, v, window, mask, past_len)
T = q.size(2)
row = torch.arange(T, device=q.device).unsqueeze(1); col = torch.arange(T, device=q.device).unsqueeze(0)
m = col <= row
if 0 <= window < T:
m = m & ((row - col) <= window)
m = m.unsqueeze(0).unsqueeze(0) & dm
return F.scaled_dot_product_attention(q, k, v, attn_mask=m)
mn.NanochronoAttention._attend = _attend
def doc_mask_from_ids(doc): # doc [B,T] ints, 0 = padding -> [B,1,T,T] bool
m = (doc.unsqueeze(2) == doc.unsqueeze(1)) & (doc.unsqueeze(2) > 0)
eye = torch.eye(doc.size(1), dtype=torch.bool, device=doc.device).unsqueeze(0)
return (m | eye).unsqueeze(1) # padding rows attend to themselves so softmax is defined
# ------------------------------------------------------------------ data: SFT
def sft_batches(path, tok, seq, micro_bs, seed, shard=(0, 1)):
"""path may be a comma list of jsonl files (prompt/response rows). The response is tokenized with ONE leading space
so the Q->A boundary matches natural text ("...? The answer") -- at eval the model continues straight after the raw
question with no separator, so whatever boundary we train is what it will emit."""
rows = []
for f in path.split(","):
rows += [json.loads(l) for l in open(f, encoding="utf-8")]
rows = rows[shard[0]::shard[1]] # each DDP rank owns a disjoint slice
if shard[0] == 0:
print(f"[sft] {len(rows) * shard[1]} rows from {path} ({shard[1]} shard(s))", flush=True)
rng = random.Random(seed); bos, eos, pad = tok.bos_token_id, tok.eos_token_id, tok.pad_token_id
while True:
rng.shuffle(rows)
for i in range(0, len(rows) - micro_bs + 1, micro_bs):
xs, ys = [], []
for r in rows[i:i + micro_bs]:
p = [bos] + tok(r["prompt"], add_special_tokens=False)["input_ids"]
a = tok(" " + r["response"].strip(), add_special_tokens=False)["input_ids"] + [eos]
if len(p) + len(a) > seq + 1: # never cut the EOS off: trim the prompt from the left
p = p[-(seq + 1 - len(a)):] if len(a) < seq + 1 else p[:1]
a = a[: seq + 1 - len(p)]
ids = p + a; lab = [IGN] * len(p) + a
assert lab[-1] == eos, "EOS must be a training target"
padn = seq + 1 - len(ids)
xs.append(ids + [pad] * padn); ys.append(lab + [IGN] * padn)
x, y = torch.tensor(xs), torch.tensor(ys)
yield x, y, None
# ------------------------------------------------------------------ loss (chunked, softcapped, -100 aware)
def lm_loss(model, ids, labels, chunk=512):
"""ids/labels [B,T+1]. Returns (sum_nll, n_targets). Only the hidden states are stored; logits are
recomputed per chunk in backward (checkpoint), so the fp32 [B,T,V] tensor never exists at once."""
hidden = model.model(input_ids=ids[:, :-1], use_cache=False).last_hidden_state
tgt = labels[:, 1:]
cap = model.config.final_logit_softcapping
W = model.lm_head.weight
def piece(h, t):
lg = F.linear(h, W).float()
if cap:
lg = cap * torch.tanh(lg / cap)
return F.cross_entropy(lg.view(-1, lg.size(-1)), t.reshape(-1), ignore_index=IGN, reduction="sum")
total = hidden.new_zeros((), dtype=torch.float32)
for s in range(0, hidden.size(1), chunk):
total = total + checkpoint(piece, hidden[:, s:s + chunk], tgt[:, s:s + chunk], use_reentrant=False)
return total, (tgt != IGN).sum()
# ------------------------------------------------------------------ evaluation
@torch.no_grad()
def eval_loss(model, tok, texts, seq, dev, bs=8):
model.eval(); tot = 0.0; n = 0
for i in range(0, len(texts), bs):
enc = tok(texts[i:i + bs], add_special_tokens=False, truncation=True, max_length=seq)["input_ids"]
L = max(len(e) for e in enc) + 1
ids = torch.full((len(enc), L), tok.pad_token_id); lab = torch.full((len(enc), L), IGN)
for r, e in enumerate(enc):
e = [tok.bos_token_id] + e
ids[r, :len(e)] = torch.tensor(e); lab[r, :len(e)] = torch.tensor(e)
with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=dev.type == "cuda"):
s, k = lm_loss(model, ids.to(dev), lab.to(dev))
tot += s.item(); n += k.item()
model.train()
return tot / max(1, n)
def load_probes(path):
rows = list(csv.DictReader(open(path, encoding="utf-8")))
out = []
for r in rows:
s, p = r["sentence"], r["phrase"]
i = s.lower().rfind(p.lower())
out.append({"year": int(r["year"]), "prompt": (s[:i].rstrip() if i >= 0 else s), "phrase": p})
return out
@torch.no_grad()
def probe_scores(model, tok, probes, dev):
"""Sum of log-probs of the phrase tokens after BOS+prompt — identical arithmetic to sn38.template.leak."""
model.eval(); scores = []
for it in probes:
p = [tok.bos_token_id] + tok(it["prompt"], add_special_tokens=False)["input_ids"]
ph = tok(" " + it["phrase"], add_special_tokens=False)["input_ids"]
ids = torch.tensor([p + ph], device=dev)
with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=dev.type == "cuda"):
lg = model(input_ids=ids, use_cache=False).logits.float()
lp = F.log_softmax(lg[0, len(p) - 1:len(p) - 1 + len(ph)], -1)
scores.append(sum(lp[j, t].item() for j, t in enumerate(ph)))
model.train()
return scores
def run_eval(model, tok, dev, val_sets, probes, seq, epsilon, log):
msg = []
for name, texts in val_sets.items():
msg.append(f"val/{name}={eval_loss(model, tok, texts, seq, dev):.4f}")
if probes:
sc = probe_scores(model, tok, probes, dev)
known = sum(s > epsilon for s in sc) / len(sc)
med = sorted(sc)[len(sc) // 2]
msg.append(f"probes: known_rate={known:.2%} (need >=70%) median={med:.2f}")
log("[eval] " + " ".join(msg))
# ------------------------------------------------------------------ model helpers
def enable_checkpointing(model):
"""nanochrono has supports_gradient_checkpointing=False; wrap decoder layers manually."""
for layer in model.model.layers:
fwd = layer.forward
layer.forward = (lambda f: lambda *a, **k: checkpoint(f, *a, use_reentrant=False, **k))(fwd)
def lr_at(step, total, base, warmup, floor=0.1):
if step < warmup:
return base * (step + 1) / warmup
p = (step - warmup) / max(1, total - warmup)
return base * (floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * p)))
def save(model, tok, out, step, rep_pen):
d = os.path.join(out, f"step-{step:06d}")
compiled = getattr(model.model, "_orig_mod", None)
if compiled is not None:
model.model = compiled # save clean keys, not "_orig_mod.*"
model.to(torch.bfloat16).save_pretrained(d, safe_serialization=True)
model.to(torch.float32)
if compiled is not None:
model.model = torch.compile(model.model)
tok.save_pretrained(d)
GenerationConfig(do_sample=False, repetition_penalty=rep_pen, max_new_tokens=100,
eos_token_id=tok.eos_token_id, pad_token_id=tok.pad_token_id, bos_token_id=tok.bos_token_id).save_pretrained(d)
latest = os.path.join(out, "latest")
if os.path.islink(latest): os.remove(latest)
os.symlink(os.path.basename(d), latest)
print(f"[save] {d}", flush=True)
return d
# ------------------------------------------------------------------ main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--mode", choices=["cpt", "sft"], default="cpt")
ap.add_argument("--base", required=True, help="dir of the starting checkpoint (HF layout)")
ap.add_argument("--out", required=True)
ap.add_argument("--corpus", help="output dir of build_corpus.py (cpt)")
ap.add_argument("--mix", default="", help="cpt: name=weight,name=weight,...")
ap.add_argument("--replay-sources", default="fineweb_edu_replay,fnspid_news_1999_2023", help="names counted as replay for val")
ap.add_argument("--sft-jsonl", help="sft: jsonl (or comma list) with prompt/response rows")
ap.add_argument("--tokens", type=float, default=3e9, help="total training tokens")
ap.add_argument("--seq", type=int, default=2048)
ap.add_argument("--micro-bs", type=int, default=8)
ap.add_argument("--global-tokens", type=int, default=1_048_576, help="tokens per optimizer step")
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--warmup", type=int, default=100)
ap.add_argument("--wd", type=float, default=0.1)
ap.add_argument("--save-every", type=int, default=500)
ap.add_argument("--eval-every", type=int, default=100)
ap.add_argument("--val-docs", type=int, default=64, help="held-out docs per source for val loss (cpt)")
ap.add_argument("--probes", default="", help="csv year,sentence,phrase scored like leak.py")
ap.add_argument("--epsilon", type=float, default=-11.51)
ap.add_argument("--doc-mask", action="store_true", help="block-diagonal attention across packed documents")
ap.add_argument("--ckpt", action="store_true", help="activation checkpointing (80GB GPUs)")
ap.add_argument("--compile", action="store_true", help="torch.compile the backbone")
ap.add_argument("--rep-penalty", type=float, default=1.1, help="written to generation_config.json")
ap.add_argument("--seed", type=int, default=1337)
ap.add_argument("--device", default="cuda")
ap.add_argument("--resume", action="store_true", help="continue from <out>/resume.pt (fp32 weights + optimizer + step); spot-instance safe")
a = ap.parse_args()
# ---- multi-GPU (torchrun): data parallel with a manual all-reduce after accumulation. Each rank streams its own shuffle
# of the mix (seed+rank) and --global-tokens is split across ranks, so the optimizer sees the same tokens/step as 1 GPU.
rank = int(os.environ.get("RANK", 0)); world = int(os.environ.get("WORLD_SIZE", 1)); local = int(os.environ.get("LOCAL_RANK", 0))
if world > 1:
import torch.distributed as dist
dist.init_process_group("nccl" if a.device.startswith("cuda") else "gloo")
if a.device.startswith("cuda"):
a.device = f"cuda:{local}"; torch.cuda.set_device(local)
is_main = rank == 0
import builtins
def print(*args, **kw): # only rank 0 talks (shadows the builtin inside main)
if is_main: builtins.print(*args, **kw)
torch.manual_seed(a.seed + rank)
dev = torch.device(a.device)
if dev.type == "cuda":
torch.backends.cuda.matmul.allow_tf32 = True
tok = AutoTokenizer.from_pretrained(a.base)
model = AutoModelForCausalLM.from_pretrained(a.base, dtype=torch.float32).to(dev)
model.config.use_cache = False
model.train()
if a.ckpt:
enable_checkpointing(model)
if a.doc_mask:
install_doc_mask(model)
if a.compile:
model.model = torch.compile(model.model)
n_params = sum(p.numel() for p in model.parameters())
print(f"[model] {n_params/1e9:.3f}B params (limit 2.2B)", flush=True)
assert n_params <= 2_200_000_000
decay = [p for n, p in model.named_parameters() if p.ndim >= 2]
no_decay = [p for n, p in model.named_parameters() if p.ndim < 2]
opt = torch.optim.AdamW([{"params": decay, "weight_decay": a.wd}, {"params": no_decay, "weight_decay": 0.0}],
lr=a.lr, betas=(0.9, 0.95), eps=1e-8, fused=(dev.type == "cuda"))
accum = max(1, a.global_tokens // (a.micro_bs * a.seq * world))
step_tokens = accum * a.micro_bs * a.seq * world
total_steps = int(a.tokens // step_tokens)
print(f"[plan] steps={total_steps} accum={accum} x {world} GPU(s) micro_bs={a.micro_bs} seq={a.seq} -> {step_tokens:,} tok/step "
f"lr={a.lr} warmup={a.warmup} doc_mask={a.doc_mask}", flush=True)
start_step = 0
resume_path = os.path.join(a.out, "resume.pt")
if a.resume and os.path.exists(resume_path):
st = torch.load(resume_path, map_location=dev, weights_only=False)
model.load_state_dict(st["model"]); opt.load_state_dict(st["opt"]); start_step = st["step"]
print(f"[resume] {resume_path} -> step {start_step}/{total_steps} (data streams re-seeded with seed+step)", flush=True)
data_seed = a.seed + rank + 1000 * start_step
val_sets = {}
if a.mode == "cpt":
mix = {kv.split("=")[0]: float(kv.split("=")[1]) for kv in a.mix.split(",") if kv}
if not mix:
raise SystemExit("--mix required for cpt, e.g. fineweb_2024=0.3,fineweb_edu_2024=0.25,...")
replay = set(a.replay_sources.split(","))
new_txt, rep_txt = [], []
for n in mix:
(rep_txt if n in replay else new_txt).extend(heldout_docs(os.path.join(a.corpus, n), a.val_docs))
val_sets = {"new2024": new_txt[:256], "replay": rep_txt[:128]}
data = Packer(tok, a.seq, a.micro_bs).stream(mixed_docs(a.corpus, mix, data_seed, a.val_docs))
else:
data = sft_batches(a.sft_jsonl, tok, a.seq, a.micro_bs, data_seed, shard=(rank, world))
probes = load_probes(a.probes) if a.probes else []
os.makedirs(a.out, exist_ok=True)
log = lambda m: print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
def save_resume(step):
if not is_main: return
tmp = resume_path + ".tmp"
torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "step": step}, tmp)
os.replace(tmp, resume_path)
if is_main and start_step == 0:
run_eval(model, tok, dev, val_sets, probes, a.seq, a.epsilon, log)
t0 = time.time(); seen = 0; pad_frac = 0.0
for step in range(start_step, total_steps):
for g in opt.param_groups: g["lr"] = lr_at(step, total_steps, a.lr, a.warmup)
loss_sum = 0.0; tgt_sum = 0
for _ in range(accum):
x, y, doc = next(data)
x, y = x.to(dev, non_blocking=True), y.to(dev, non_blocking=True)
_DOC_MASK["m"] = doc_mask_from_ids(doc[:, :-1].to(dev)) if (a.doc_mask and doc is not None) else None
with torch.autocast(dev.type, dtype=torch.bfloat16, enabled=(dev.type == "cuda")):
s, k = lm_loss(model, x, y)
(s / (accum * a.micro_bs * a.seq)).backward() # normalise by nominal tokens (constant) -> stable step size
loss_sum += s.item(); tgt_sum += k.item()
seen += x.numel(); pad_frac = 0.98 * pad_frac + 0.02 * (1 - k.item() / (x.numel() - x.size(0)))
_DOC_MASK["m"] = None
if world > 1: # average gradients across ranks (every rank then holds identical grads)
for p in model.parameters():
if p.grad is not None:
dist.all_reduce(p.grad, op=dist.ReduceOp.AVG)
gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); opt.zero_grad(set_to_none=True)
if step % 10 == 0 or step == total_steps - 1:
el = time.time() - t0; done = step + 1 - start_step
log(f"step {step}/{total_steps} loss {loss_sum/max(1,tgt_sum):.4f} gnorm {gn:.2f} lr {opt.param_groups[0]['lr']:.2e} "
f"pad {pad_frac:.1%} tok/s {seen*world/el:,.0f} eta {el/done*(total_steps-step-1)/3600:.1f}h")
if (step + 1) % a.eval_every == 0 and is_main:
run_eval(model, tok, dev, val_sets, probes, a.seq, a.epsilon, log)
if (step + 1) % a.save_every == 0 and step + 1 < total_steps:
if is_main:
save(model, tok, a.out, step + 1, a.rep_penalty)
save_resume(step + 1)
if is_main:
run_eval(model, tok, dev, val_sets, probes, a.seq, a.epsilon, log)
final = save(model, tok, a.out, total_steps, a.rep_penalty)
print(f"[done] final checkpoint: {final}")
if world > 1:
dist.barrier(); dist.destroy_process_group()
if __name__ == "__main__":
main()