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]>
61 lines
2.1 KiB
Python
61 lines
2.1 KiB
Python
"""Byte-level BPE tokenizer, shared by English and Typst (so the model can copy x, 2, pi across).
|
|
|
|
uv run isotope-tokenizer # data/train.jsonl -> artifacts/tokenizer.json
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import pathlib
|
|
|
|
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers
|
|
|
|
SPECIALS = ["[PAD]", "[UNK]", "[BOS]", "[EOS]"]
|
|
PAD, UNK, BOS, EOS = 0, 1, 2, 3
|
|
|
|
|
|
def train(texts, out: str = "artifacts/tokenizer.json", vocab: int = 4000) -> Tokenizer:
|
|
tok = Tokenizer(models.BPE(unk_token="[UNK]"))
|
|
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
|
|
tok.decoder = decoders.ByteLevel()
|
|
trainer = trainers.BpeTrainer(
|
|
vocab_size=vocab, special_tokens=SPECIALS, initial_alphabet=pre_tokenizers.ByteLevel.alphabet()
|
|
)
|
|
tok.train_from_iterator(texts, trainer)
|
|
pathlib.Path(out).parent.mkdir(parents=True, exist_ok=True)
|
|
tok.save(out)
|
|
return tok
|
|
|
|
|
|
def load(path: str = "artifacts/tokenizer.json") -> Tokenizer:
|
|
if not pathlib.Path(path).exists():
|
|
raise SystemExit(f"No tokenizer at {path}. Train one first: uv run isotope-tokenizer")
|
|
return Tokenizer.from_file(path)
|
|
|
|
|
|
def jsonl_texts(path: str):
|
|
"""Both columns of a data file, one string at a time."""
|
|
with open(path) as f:
|
|
for line in f:
|
|
row = json.loads(line)
|
|
yield row["en"]
|
|
yield row["typ"]
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> None:
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("--data", default="data/train.jsonl")
|
|
ap.add_argument("--out", default="artifacts/tokenizer.json")
|
|
ap.add_argument("--vocab", type=int, default=4000)
|
|
args = ap.parse_args(argv)
|
|
|
|
tok = train(jsonl_texts(args.data), args.out, args.vocab)
|
|
print(f"trained a {tok.get_vocab_size()}-token BPE tokenizer -> {args.out}")
|
|
for s in ["the integral from 0 to infinity of e to the minus x squared dx", "integral_0^infinity e^(-x^2) dif x"]:
|
|
print(f" {s!r}\n -> {tok.encode(s).tokens}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|