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

+100
View File
@@ -0,0 +1,100 @@
"""Inference: English -> Typst with greedy decoding, one token at a time.
uv run isotope "the integral from 0 to infinity of e to the minus x squared dx"
uv run isotope # interactive prompt (Ctrl-D to quit)
uv run isotope --check "x squared plus 1" # also compile the output with typst
"""
from __future__ import annotations
import argparse
import sys
import torch
from .model import Seq2Seq, pick_device
from .tokenizer import BOS, EOS, PAD, load
def load_model(ckpt: str = "artifacts/model.pt", tok_path: str = "artifacts/tokenizer.json", device: str | None = None):
try:
state = torch.load(ckpt, map_location="cpu", weights_only=False)
except FileNotFoundError:
raise SystemExit(f"No trained model at {ckpt}. Train one first: uv run isotope-train") from None
model = Seq2Seq(**state["model_args"])
model.load_state_dict(state["model"])
dev = device or pick_device()
return model.to(dev).eval(), load(tok_path)
@torch.no_grad()
def translate_batch(model: Seq2Seq, tok, texts: list[str], max_len: int = 160) -> list[str]:
"""Greedy decoding: encode once, then repeatedly append the most likely next token."""
model.eval()
dev = next(model.parameters()).device
ids = [tok.encode(t).ids[: model.max_len] for t in texts]
src = torch.full((len(ids), max(map(len, ids))), PAD, dtype=torch.long)
for i, x in enumerate(ids):
src[i, : len(x)] = torch.tensor(x)
src = src.to(dev)
memory = model.encode(src)
src_pad = src == PAD
out = torch.full((len(texts), 1), BOS, dtype=torch.long, device=dev)
done = torch.zeros(len(texts), dtype=torch.bool, device=dev)
for _ in range(min(max_len, model.max_len - 1)):
logits = model.decode(out, memory, src_pad)[:, -1] # only the last position predicts what comes next
nxt = logits.argmax(-1)
nxt = torch.where(done, PAD, nxt) # finished rows just pad
out = torch.cat([out, nxt[:, None]], dim=1)
done |= nxt == EOS
if done.all():
break
results = []
for row in out[:, 1:].tolist():
if EOS in row:
row = row[: row.index(EOS)]
results.append(tok.decode([t for t in row if t != PAD]).strip())
return results
def translate(model: Seq2Seq, tok, text: str) -> str:
return translate_batch(model, tok, [text])[0]
def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(prog="isotope", description="Translate spoken-English math into Typst math.")
ap.add_argument("text", nargs="*", help="the English sentence (omit for an interactive prompt)")
ap.add_argument("--check", action="store_true", help="also run `typst compile` on the output")
ap.add_argument("--ckpt", default="artifacts/model.pt")
ap.add_argument("--tokenizer", default="artifacts/tokenizer.json")
args = ap.parse_args(argv)
model, tok = load_model(args.ckpt, args.tokenizer)
def run(line: str) -> None:
typ = translate(model, tok, line)
print(f"${typ}$")
if args.check:
from .validate import compiles
print(" compiles:", "yes" if compiles(typ) else "NO")
if args.text:
run(" ".join(args.text))
return
interactive = sys.stdin.isatty()
if interactive:
print("isotope: type English math, get Typst. Ctrl-D to quit.")
while True:
try:
line = input("> " if interactive else "").strip()
except EOFError:
break
if line:
run(line)
if __name__ == "__main__":
main()