Add clean Path A proof of concept (#1)

Spoken-English math to Typst with a small (~8M parameter) encoder-decoder Transformer trained from scratch, following the build guide (Path A only).

## What's in it
- `generate.py` / `render.py` / `ast.py`: random expression trees rendered to Typst (deterministic) and English (random phrasings); every Typst string is compile-checked, split by a hash of the Typst string
- `tokenizer.py`: byte-level BPE shared by both sides
- `model.py`: `nn.Transformer` seq2seq with `encode()` / `decode()` for inference
- `train.py`: teacher forcing, AdamW, warmup + cosine, overfit-100 sanity check, checkpoints
- `translate.py`: greedy decoding CLI (`uv run isotope "..."`)
- `evaluate.py`: exact match + compile rate on the synthetic test split and `eval/hand_test.jsonl`
- `run.sh`: whole pipeline; `./run.sh --quick` is a 2-minute smoke run
- `AGENTS.md`: commit and workflow rules for agents

## Checked
- `uv run pytest` (8 tests: Typst compiles, English is unambiguous, tokenizer round-trips, causal mask) and `ruff check` pass
- `./run.sh --quick` and the full `./run.sh` run end to end on an M-series Mac

Reviewed-on: #1
Co-authored-by: Paul Tal <[email protected]>
This commit was merged in pull request #1.
This commit is contained in:
paultal authored and paultal committed 2026-11-27 00:24:05 +02:00
1 parent 5926731546
commit 98e88cac04
21 files changed
+2411 -1

No files matched your search

+228
View File
@@ -0,0 +1,228 @@
"""Training loop: teacher forcing, AdamW, linear warmup + cosine decay, label smoothing.
uv run isotope-train --overfit 100 # sanity check: a tiny model must memorise 100 pairs
uv run isotope-train # small model (~8M params), 8000 steps
uv run isotope-train --config tiny --steps 1000 # quick smoke run
Writes artifacts/model.pt (best validation loss), artifacts/last.pt and artifacts/train_log.csv.
Ctrl-C stops early and still saves a checkpoint.
"""
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
MAX_LEN = 256
def read_pairs(path: str, limit: int | None = None) -> list[tuple[str, str]]:
pairs = []
with open(path) as f:
for line in f:
row = json.loads(line)
pairs.append((row["en"], row["typ"]))
if limit and len(pairs) >= limit:
break
return pairs
def encode_pairs(tok, pairs) -> list[tuple[list[int], list[int]]]:
"""src = English ids; tgt = [BOS] Typst ids [EOS]."""
srcs = [e.ids[:MAX_LEN] for e in tok.encode_batch([en for en, _ in pairs])]
tgts = [[BOS] + e.ids[: MAX_LEN - 2] + [EOS] for e in tok.encode_batch([typ for _, typ in pairs])]
return list(zip(srcs, tgts))
def pad(seqs: list[list[int]]) -> torch.Tensor:
t = torch.full((len(seqs), max(map(len, seqs))), PAD, dtype=torch.long)
for i, s in enumerate(seqs):
t[i, : len(s)] = torch.tensor(s)
return t
def batches(data, batch_size: int, rng: random.Random, bucket: int = 50):
"""Endless (src, tgt) batches. Sorting by length within big buckets keeps padding (wasted work) low."""
while True:
idx = list(range(len(data)))
rng.shuffle(idx)
chunk = batch_size * bucket
groups = []
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]))
groups += [part[j : j + batch_size] for j in range(0, len(part), batch_size)]
rng.shuffle(groups)
for g in groups:
yield pad([data[i][0] for i in g]), pad([data[i][1] for i in g])
def warmup_cosine(warmup: int, total: int, floor: float = 0.05):
def factor(step: int) -> float:
if step < warmup:
return (step + 1) / warmup
progress = min(1.0, (step - warmup) / max(1, total - warmup))
return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * progress))
return factor
def loss_fn(model, src, tgt, smoothing: float = 0.1) -> torch.Tensor:
tgt_in, tgt_out = tgt[:, :-1], tgt[:, 1:] # teacher forcing: predict token t+1 from tokens <= t
logits = model(src, tgt_in)
return F.cross_entropy(
logits.reshape(-1, logits.size(-1)), tgt_out.reshape(-1), ignore_index=PAD, label_smoothing=smoothing
)
@torch.no_grad()
def val_loss(model, data, dev, batch_size: int = 256) -> float:
model.eval()
total = 0.0
for i in range(0, len(data), batch_size):
part = data[i : i + batch_size]
src, tgt = pad([s for s, _ in part]).to(dev), pad([t for _, t in part]).to(dev)
total += loss_fn(model, src, tgt, smoothing=0.0).item() * len(part)
model.train()
return total / max(1, len(data))
def save(path: pathlib.Path, model, model_args: dict, **extra) -> None:
torch.save({"model": model.state_dict(), "model_args": model_args, **extra}, path)
def overfit(tok, data_dir: str, n: int, dev: str) -> bool:
"""If a tiny model cannot memorise n pairs, the pipeline has a bug (shift, mask, special tokens)."""
pairs = read_pairs(f"{data_dir}/train.jsonl", n)
data = encode_pairs(tok, pairs)
torch.manual_seed(0)
model = Seq2Seq(tok.get_vocab_size(), **CONFIGS["tiny"], max_len=MAX_LEN, drop=0.0).to(dev)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
src, tgt = pad([s for s, _ in data]).to(dev), pad([t for _, t in data]).to(dev)
for step in range(1, 3001):
model.train()
loss = loss_fn(model, src, tgt, smoothing=0.0)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
if step % 100 == 0:
preds = translate_batch(model, tok, [en for en, _ in pairs])
exact = sum(p == typ for p, (_, typ) in zip(preds, pairs))
print(f"step {step:5d} loss {loss.item():.4f} exact {exact}/{len(pairs)}", flush=True)
if exact == len(pairs):
print(f"PASS: memorised all {len(pairs)} pairs.")
return True
print("FAIL: could not memorise the pairs. Check the shift, the masks and BOS/EOS handling.")
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("--overfit", type=int, default=0, metavar="N", help="only run the memorise-N-pairs check")
ap.add_argument("--device", default=None, help="cuda / mps / cpu (default: best available)")
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(tok, args.data, args.overfit, dev) else 1)
torch.manual_seed(args.seed)
rng = random.Random(args.seed)
print("tokenizing data ...")
train = encode_pairs(tok, read_pairs(f"{args.data}/train.jsonl"))
valid_pairs = read_pairs(f"{args.data}/valid.jsonl", 2000)
valid = encode_pairs(tok, valid_pairs)
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)
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, warmup_cosine(args.warmup, args.steps))
out = pathlib.Path(args.out)
out.mkdir(parents=True, exist_ok=True)
log_file = (out / "train_log.csv").open("w", newline="")
log = csv.writer(log_file)
log.writerow(["step", "lr", "train_loss", "val_loss", "sample_exact", "elapsed_s"])
samples = valid_pairs[:20]
best = float("inf")
run_loss, run_n = 0.0, 0
t0 = time.time()
it = batches(train, args.batch, rng)
model.train()
step = 0
try:
for step in range(1, args.steps + 1):
src, tgt = (x.to(dev) for x in next(it))
loss = loss_fn(model, src, tgt)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
sched.step()
if step % 10 == 0: # .item() syncs with the GPU, so don't do it every step
run_loss += loss.item()
run_n += 1
if step % 100 == 0:
el = time.time() - t0
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 "
f"eta {el / step * (args.steps - step) / 60:.1f} min",
flush=True,
)
if step % args.eval_every == 0 or step == args.steps:
vl = val_loss(model, valid, dev)
preds = translate_batch(model, tok, [en for en, _ in samples])
exact = sum(p == typ for p, (_, typ) in zip(preds, samples))
print(f"--- step {step}: val loss {vl:.4f}, sample exact {exact}/{len(samples)}")
for (en, typ), p in list(zip(samples, 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_file.flush()
run_loss, run_n = 0.0, 0
save(out / "last.pt", model, model_args, step=step, val_loss=vl)
if vl < best:
best = vl
save(out / "model.pt", model, model_args, step=step, val_loss=vl)
model.train()
except KeyboardInterrupt:
print("\ninterrupted: saving artifacts/last.pt")
save(out / "last.pt", model, model_args, step=step)
if not (out / "model.pt").exists():
save(out / "model.pt", model, model_args, step=step)
log_file.close()
print(f"done. best val loss {best:.4f} -> {out / 'model.pt'}")
if __name__ == "__main__":
main()