Spoken-English math to Typst math with a small from-scratch Transformer: synthetic data generator, BPE tokenizer, training, constrained/beam decoding, and evaluation against a hand-written test set. Ships the trained Path A model and tokenizer so the CLI works right after clone. Co-Authored-By: Claude Opus 5.5 <[email protected]>
227 lines
9.3 KiB
Python
227 lines
9.3 KiB
Python
"""Training loop (teacher forcing, AdamW, warmup + cosine, label smoothing).
|
|
|
|
uv run isotope-train # small model, defaults
|
|
uv run isotope-train --config tiny --steps 2000
|
|
uv run isotope-train --overfit 100 # milestone M2 sanity check: memorise 100 pairs
|
|
uv run isotope-train --custom-attn # use the hand-written MultiHeadAttention
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import csv
|
|
import json
|
|
import math
|
|
import pathlib
|
|
import random
|
|
import time
|
|
|
|
import torch
|
|
import torch.nn.functional as F
|
|
|
|
from .model import CONFIGS, Seq2Seq, count_params, pick_device
|
|
from .tokenizer import BOS, EOS, PAD, load
|
|
from .translate import translate_batch
|
|
|
|
|
|
def read_pairs(path: str, limit: int | None = None) -> list[tuple[str, str]]:
|
|
out = []
|
|
with open(path) as f:
|
|
for line in f:
|
|
row = json.loads(line)
|
|
out.append((row["en"], row["typ"]))
|
|
if limit and len(out) >= limit:
|
|
break
|
|
return out
|
|
|
|
|
|
def encode_pairs(tok, pairs, max_len):
|
|
srcs = [e.ids[:max_len] for e in tok.encode_batch([p[0] for p in pairs])]
|
|
tgts = [[BOS] + e.ids[: max_len - 2] + [EOS] for e in tok.encode_batch([p[1] for p in pairs])]
|
|
return list(zip(srcs, tgts))
|
|
|
|
|
|
def pad(seqs: list[list[int]]) -> torch.Tensor:
|
|
L = max(len(s) for s in seqs)
|
|
t = torch.full((len(seqs), L), PAD, dtype=torch.long)
|
|
for i, s in enumerate(seqs):
|
|
t[i, : len(s)] = torch.tensor(s, dtype=torch.long)
|
|
return t
|
|
|
|
|
|
def batches(data, batch_size: int, rng: random.Random, bucket: int = 50):
|
|
"""Infinite iterator; sorts by length inside large buckets so batches have little padding."""
|
|
while True:
|
|
idx = list(range(len(data)))
|
|
rng.shuffle(idx)
|
|
chunk = batch_size * bucket
|
|
bl = []
|
|
for c in range(0, len(idx), chunk):
|
|
part = sorted(idx[c: c + chunk], key=lambda i: len(data[i][0]) + len(data[i][1]))
|
|
bl += [part[j: j + batch_size] for j in range(0, len(part), batch_size)]
|
|
rng.shuffle(bl)
|
|
for b in bl:
|
|
yield pad([data[i][0] for i in b]), pad([data[i][1] for i in b])
|
|
|
|
|
|
def lr_lambda(warmup: int, total: int, floor: float = 0.05):
|
|
def f(step: int) -> float:
|
|
if step < warmup:
|
|
return (step + 1) / warmup
|
|
prog = min(1.0, (step - warmup) / max(1, total - warmup))
|
|
return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * prog))
|
|
return f
|
|
|
|
|
|
def loss_fn(model, src, tgt, V, smoothing=0.1):
|
|
tgt_in, tgt_out = tgt[:, :-1], tgt[:, 1:] # teacher-forcing shift
|
|
logits = model(src, tgt_in)
|
|
return F.cross_entropy(logits.reshape(-1, V), tgt_out.reshape(-1), ignore_index=PAD, label_smoothing=smoothing)
|
|
|
|
|
|
@torch.no_grad()
|
|
def val_loss(model, data, V, dev, batch_size=256):
|
|
model.eval()
|
|
tot, n = 0.0, 0
|
|
for i in range(0, len(data), batch_size):
|
|
part = data[i: i + batch_size]
|
|
src, tgt = pad([p[0] for p in part]).to(dev), pad([p[1] for p in part]).to(dev)
|
|
tot += loss_fn(model, src, tgt, V, smoothing=0.0).item() * len(part)
|
|
n += len(part)
|
|
model.train()
|
|
return tot / max(n, 1)
|
|
|
|
|
|
def save(path, model, model_args, extra):
|
|
pathlib.Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
torch.save({"model": model.state_dict(), "model_args": model_args, **extra}, path)
|
|
|
|
|
|
def overfit(args, tok, dev):
|
|
"""Milestone M2: a tiny model must memorise 100 pairs exactly, or the pipeline has a bug."""
|
|
pairs = read_pairs(f"{args.data}/train.jsonl", args.overfit)
|
|
data = encode_pairs(tok, pairs, 256)
|
|
V = tok.get_vocab_size()
|
|
torch.manual_seed(0)
|
|
model_args = dict(vocab=V, **CONFIGS["tiny"], max_len=256, drop=0.0, custom_attn=args.custom_attn)
|
|
model = Seq2Seq(**model_args).to(dev)
|
|
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
|
src, tgt = pad([d[0] for d in data]).to(dev), pad([d[1] for d in data]).to(dev)
|
|
for step in range(1, 3001):
|
|
model.train()
|
|
loss = loss_fn(model, src, tgt, V, smoothing=0.0)
|
|
opt.zero_grad(set_to_none=True)
|
|
loss.backward()
|
|
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
opt.step()
|
|
if step % 100 == 0:
|
|
preds = translate_batch(model, tok, [p[0] for p in pairs], constrained=False)
|
|
exact = sum(p == t for p, (_, t) in zip(preds, pairs))
|
|
print(f"step {step:5d} loss {loss.item():.4f} exact {exact}/{len(pairs)}")
|
|
if exact == len(pairs):
|
|
print(f"PASS: memorised all {len(pairs)} pairs.")
|
|
return True
|
|
print("FAIL: could not memorise the pairs -- check shift / mask / special tokens.")
|
|
return False
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> None:
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("--config", choices=list(CONFIGS), default="small")
|
|
ap.add_argument("--steps", type=int, default=8000)
|
|
ap.add_argument("--batch", type=int, default=128)
|
|
ap.add_argument("--lr", type=float, default=7e-4)
|
|
ap.add_argument("--warmup", type=int, default=500)
|
|
ap.add_argument("--dropout", type=float, default=0.1)
|
|
ap.add_argument("--eval-every", type=int, default=1000)
|
|
ap.add_argument("--data", default="data")
|
|
ap.add_argument("--out", default="artifacts")
|
|
ap.add_argument("--tokenizer", default="artifacts/tokenizer.json")
|
|
ap.add_argument("--custom-attn", action="store_true", help="use the hand-written attention")
|
|
ap.add_argument("--overfit", type=int, default=0, help="only run the memorise-N-pairs check")
|
|
ap.add_argument("--device", default=None)
|
|
ap.add_argument("--seed", type=int, default=0)
|
|
args = ap.parse_args(argv)
|
|
|
|
dev = args.device or pick_device()
|
|
tok = load(args.tokenizer)
|
|
V = tok.get_vocab_size()
|
|
print(f"device: {dev} vocab: {V}")
|
|
|
|
if args.overfit:
|
|
raise SystemExit(0 if overfit(args, tok, dev) else 1)
|
|
|
|
torch.manual_seed(args.seed)
|
|
rng = random.Random(args.seed)
|
|
max_len = 256
|
|
print("tokenizing data ...")
|
|
train_pairs = read_pairs(f"{args.data}/train.jsonl")
|
|
valid_pairs = read_pairs(f"{args.data}/valid.jsonl")[:2000]
|
|
train = encode_pairs(tok, train_pairs, max_len)
|
|
valid = encode_pairs(tok, valid_pairs, max_len)
|
|
print(f"train pairs: {len(train):,} valid pairs: {len(valid):,}")
|
|
|
|
model_args = dict(vocab=V, **CONFIGS[args.config], max_len=max_len, drop=args.dropout, custom_attn=args.custom_attn)
|
|
model = Seq2Seq(**model_args).to(dev)
|
|
print(f"model: {args.config}, {count_params(model) / 1e6:.1f}M parameters")
|
|
|
|
opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01, betas=(0.9, 0.98))
|
|
sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda(args.warmup, args.steps))
|
|
|
|
out = pathlib.Path(args.out)
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
log_f = (out / "train_log.csv").open("w", newline="")
|
|
log = csv.writer(log_f)
|
|
log.writerow(["step", "lr", "train_loss", "val_loss", "sample_exact", "elapsed_s"])
|
|
|
|
sample = valid_pairs[:20]
|
|
best = float("inf")
|
|
t0 = time.time()
|
|
run_loss, run_n = 0.0, 0
|
|
model.train()
|
|
it = batches(train, args.batch, rng)
|
|
try:
|
|
for step in range(1, args.steps + 1):
|
|
src, tgt = next(it)
|
|
src, tgt = src.to(dev), tgt.to(dev)
|
|
loss = loss_fn(model, src, tgt, V)
|
|
opt.zero_grad(set_to_none=True)
|
|
loss.backward()
|
|
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
opt.step()
|
|
sched.step()
|
|
run_loss += loss.item() if step % 10 == 0 else 0.0
|
|
run_n += step % 10 == 0
|
|
if step % 100 == 0:
|
|
el = time.time() - t0
|
|
eta = el / step * (args.steps - step)
|
|
print(f"step {step:6d}/{args.steps} loss {run_loss / max(run_n, 1):.4f} "
|
|
f"lr {sched.get_last_lr()[0]:.2e} {step / el:.1f} it/s eta {eta / 60:.1f} min", flush=True)
|
|
if step % args.eval_every == 0 or step == args.steps:
|
|
vl = val_loss(model, valid, V, dev)
|
|
preds = translate_batch(model, tok, [p[0] for p in sample])
|
|
exact = sum(p == t for p, (_, t) in zip(preds, sample))
|
|
print(f"--- step {step}: val loss {vl:.4f}, sample exact {exact}/{len(sample)}")
|
|
for (en, typ), p in list(zip(sample, preds))[:5]:
|
|
print(f" {'OK ' if p == typ else 'BAD'} {en!r}\n -> {p}")
|
|
log.writerow([step, sched.get_last_lr()[0], run_loss / max(run_n, 1), vl, exact, round(time.time() - t0)])
|
|
log_f.flush()
|
|
run_loss, run_n = 0.0, 0
|
|
extra = {"step": step, "val_loss": vl, "config": args.config}
|
|
save(out / "last.pt", model, model_args, extra)
|
|
if vl < best:
|
|
best = vl
|
|
save(out / "model.pt", model, model_args, extra)
|
|
model.train()
|
|
except KeyboardInterrupt:
|
|
print("\ninterrupted -- saving checkpoint")
|
|
save(out / "last.pt", model, model_args, {"step": step, "config": args.config})
|
|
if not (out / "model.pt").exists():
|
|
save(out / "model.pt", model, model_args, {"step": step, "config": args.config})
|
|
log_f.close()
|
|
print(f"done. best val loss {best:.4f}. checkpoint: {out / 'model.pt'}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|