Add clean Path A proof of concept
Spoken-English math to Typst with a small from-scratch encoder-decoder Transformer, following the build guide: compile-checked synthetic data generator, shared BPE tokenizer, nn.Transformer model, training loop with an overfit sanity check, greedy decoding CLI, and evaluation on synthetic and hand-written test sets. ./run.sh runs the whole pipeline.
This commit is contained in:
1 parent
5926731546
commit
5afbfd3165
20 files changed
+2398
-1
No files matched your search
@@ -0,0 +1 @@
|
||||
"""isotope-typst: spoken-English math -> Typst math with a small Transformer (Path A)."""
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Math expression trees. Every training pair is one tree rendered two ways (see render.py)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
class Node:
|
||||
pass
|
||||
|
||||
|
||||
# -- leaves --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Var(Node):
|
||||
name: str # "x", "alpha", "pi", "e", "infinity", ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Num(Node):
|
||||
value: int
|
||||
|
||||
|
||||
# -- operators -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Neg(Node):
|
||||
arg: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Add(Node):
|
||||
left: Node
|
||||
right: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Sub(Node):
|
||||
left: Node
|
||||
right: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Mul(Node):
|
||||
left: Node
|
||||
right: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Pow(Node):
|
||||
base: Node
|
||||
exp: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Frac(Node):
|
||||
num: Node
|
||||
den: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Sqrt(Node):
|
||||
arg: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Func(Node):
|
||||
name: str # one of FUNCS
|
||||
arg: Node
|
||||
|
||||
|
||||
# -- big operators -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Integral(Node):
|
||||
body: Node
|
||||
var: str
|
||||
lo: Node | None = None # both None = indefinite integral
|
||||
hi: Node | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Sum(Node):
|
||||
body: Node
|
||||
var: str
|
||||
lo: Node
|
||||
hi: Node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Lim(Node):
|
||||
body: Node
|
||||
var: str
|
||||
to: Node
|
||||
|
||||
|
||||
# -- top level -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Eq(Node):
|
||||
left: Node
|
||||
right: Node
|
||||
|
||||
|
||||
GREEK = ["alpha", "beta", "gamma", "delta", "theta", "lambda", "mu", "sigma", "phi", "omega"]
|
||||
FUNCS = ["sin", "cos", "tan", "ln", "log", "exp"]
|
||||
BIG_OPS = (Integral, Sum, Lim)
|
||||
|
||||
|
||||
def walk(n: Node):
|
||||
"""Yield every node of the tree, parents before children."""
|
||||
yield n
|
||||
for v in vars(n).values():
|
||||
if isinstance(v, Node):
|
||||
yield from walk(v)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Evaluate: exact match and compile rate, on the synthetic test split and the hand-written set.
|
||||
|
||||
uv run isotope-eval
|
||||
|
||||
Failures go to artifacts/errors_<set>.txt: read them, group them, fix the generator (guide §9).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import pathlib
|
||||
import random
|
||||
|
||||
from .validate import compiles_many
|
||||
|
||||
|
||||
def read_jsonl(path: str) -> list[dict]:
|
||||
with open(path) as f:
|
||||
return [json.loads(line) for line in f if line.strip()]
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
from .translate import load_model, translate_batch
|
||||
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--synthetic", default="data/test.jsonl")
|
||||
ap.add_argument("--hand", default="eval/hand_test.jsonl")
|
||||
ap.add_argument("--n-synthetic", type=int, default=1000)
|
||||
ap.add_argument("--ckpt", default="artifacts/model.pt")
|
||||
ap.add_argument("--out", default="artifacts")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
model, tok = load_model(args.ckpt)
|
||||
sets = {}
|
||||
if pathlib.Path(args.synthetic).exists():
|
||||
rows = read_jsonl(args.synthetic)
|
||||
random.Random(0).shuffle(rows)
|
||||
sets["synthetic"] = rows[: args.n_synthetic]
|
||||
if pathlib.Path(args.hand).exists():
|
||||
sets["hand"] = read_jsonl(args.hand)
|
||||
|
||||
print(f"{'set':<12}{'n':>6}{'exact':>9}{'compiles':>10}")
|
||||
for name, rows in sets.items():
|
||||
preds = []
|
||||
for i in range(0, len(rows), 64):
|
||||
preds += translate_batch(model, tok, [r["en"] for r in rows[i : i + 64]])
|
||||
exact = [p == r["typ"] for p, r in zip(preds, rows)]
|
||||
comp = compiles_many(preds)
|
||||
n = len(rows)
|
||||
print(f"{name:<12}{n:>6}{sum(exact) / n:>9.1%}{sum(comp) / n:>10.1%}")
|
||||
|
||||
lines = [f"{n - sum(exact)} of {n} not exact\n"]
|
||||
for r, p, e, c in zip(rows, preds, exact, comp):
|
||||
if not e:
|
||||
lines.append(f"EN: {r['en']}\nWANT: {r['typ']}\nGOT: {p}{'' if c else ' [does not compile]'}\n")
|
||||
path = pathlib.Path(args.out) / f"errors_{name}.txt"
|
||||
path.write_text("\n".join(lines))
|
||||
print(f"\nfailures: {args.out}/errors_*.txt")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Generate (English, Typst) training pairs from random expression trees.
|
||||
|
||||
uv run isotope-gen # 200k pairs into data/
|
||||
uv run isotope-gen -n 5000 # a quick small set
|
||||
|
||||
Writes data/{train,valid,test}.jsonl with lines {"en": ..., "typ": ...} and data/stats.txt.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
import pathlib
|
||||
import random
|
||||
from typing import ClassVar
|
||||
|
||||
from .ast import FUNCS, GREEK, Add, Eq, Frac, Func, Integral, Lim, Mul, Neg, Node, Num, Pow, Sqrt, Sub, Sum, Var, walk
|
||||
from .render import to_english, to_typst
|
||||
from .validate import compiles_many
|
||||
|
||||
INF = Var("infinity")
|
||||
|
||||
|
||||
class TreeGen:
|
||||
def __init__(self, rng: random.Random):
|
||||
self.rng = rng
|
||||
|
||||
# -- leaves ---------------------------------------------------------------------------
|
||||
def var(self, prefer: str | None = None) -> Var:
|
||||
if prefer and self.rng.random() < 0.6: # inside "integral ... dx", mostly use x
|
||||
return Var(prefer)
|
||||
pool = ["x"] * 12 + ["y"] * 4 + ["z", "t", "a", "b", "c", "n", "k", "u", "r", "s", "m", "p"] + GREEK
|
||||
return Var(self.rng.choice(pool))
|
||||
|
||||
def num(self) -> Num:
|
||||
r = self.rng.random()
|
||||
if r < 0.8:
|
||||
return Num(self.rng.randint(1, 10))
|
||||
if r < 0.85:
|
||||
return Num(0)
|
||||
if r < 0.95:
|
||||
return Num(self.rng.randint(11, 20))
|
||||
return Num(self.rng.choice([25, 50, 100, 360, 1000]))
|
||||
|
||||
def leaf(self, prefer: str | None = None) -> Node:
|
||||
r = self.rng.random()
|
||||
if r < 0.55:
|
||||
return self.var(prefer)
|
||||
if r < 0.92:
|
||||
return self.num()
|
||||
return Var(self.rng.choice(["pi", "e"]))
|
||||
|
||||
# -- expressions without big operators ----------------------------------------------------
|
||||
KINDS: ClassVar[dict[str, int]] = {
|
||||
"Add": 12,
|
||||
"Sub": 8,
|
||||
"Mul": 12,
|
||||
"Pow": 14,
|
||||
"Frac": 10,
|
||||
"Neg": 4,
|
||||
"Sqrt": 5,
|
||||
"Func": 8,
|
||||
}
|
||||
|
||||
def expr(self, depth: int, prefer: str | None = None) -> Node:
|
||||
r = self.rng
|
||||
if depth <= 0:
|
||||
return self.leaf(prefer)
|
||||
kind = r.choices(list(self.KINDS), list(self.KINDS.values()))[0]
|
||||
d = depth - 1
|
||||
small = 0 if r.random() < 0.5 else d # keep one side shallow half the time
|
||||
match kind:
|
||||
case "Add" | "Sub":
|
||||
return (Add if kind == "Add" else Sub)(self.expr(d, prefer), self.expr(small, prefer))
|
||||
case "Mul":
|
||||
a = self.num() if r.random() < 0.4 else self.expr(small, prefer)
|
||||
b = self.expr(d, prefer)
|
||||
if isinstance(b, Num) and not isinstance(a, Num):
|
||||
a, b = b, a # "2 x", not "x 2"
|
||||
return Mul(a, b)
|
||||
case "Pow":
|
||||
base = Var("e") if r.random() < 0.15 else self.expr(d if r.random() < 0.25 else 0, prefer)
|
||||
if isinstance(base, Pow):
|
||||
base = base.base
|
||||
x = r.random()
|
||||
if x < 0.55:
|
||||
exp: Node = Num(r.choice([2, 2, 2, 3, 3, 4, 5, 10]))
|
||||
elif x < 0.7:
|
||||
exp = Var(r.choice(["n", "k", "x", "a", "m", "t"]))
|
||||
elif x < 0.85:
|
||||
exp = Neg(self.leaf(prefer))
|
||||
else:
|
||||
exp = self.expr(d, prefer)
|
||||
return Pow(base, exp)
|
||||
case "Frac":
|
||||
den = self.expr(small, prefer)
|
||||
while den == Num(0):
|
||||
den = self.leaf(prefer)
|
||||
return Frac(self.expr(d, prefer), den)
|
||||
case "Neg":
|
||||
a = self.expr(d, prefer)
|
||||
while isinstance(a, Neg) or a == Num(0):
|
||||
a = self.leaf(prefer)
|
||||
return Neg(a)
|
||||
case "Sqrt":
|
||||
return Sqrt(self.expr(d, prefer))
|
||||
case "Func":
|
||||
return Func(r.choice(FUNCS + ["sin", "cos", "ln"]), self.expr(small, prefer))
|
||||
raise AssertionError(kind)
|
||||
|
||||
# -- big operators: only ever at the top of a tree -------------------------------------
|
||||
def big(self, depth: int) -> Node:
|
||||
r = self.rng
|
||||
kind = r.choices(["Integral", "Sum", "Lim"], [6, 3, 3])[0]
|
||||
if kind == "Integral":
|
||||
v = r.choice(["x"] * 6 + ["t", "u", "y", "theta"])
|
||||
body = self.expr(max(depth, 1), v)
|
||||
if r.random() < 0.3:
|
||||
return Integral(body, v)
|
||||
lo = r.choice([Num(0)] * 5 + [Num(1)] * 2 + [Neg(Num(1)), Var("a"), Neg(INF)])
|
||||
hi = r.choice([Num(1)] * 3 + [INF] * 3 + [Num(2), Var("b"), Var("pi"), Var("x"), Frac(Var("pi"), Num(2))])
|
||||
return Integral(body, v, lo, hi)
|
||||
if kind == "Sum":
|
||||
v = r.choice(["i", "k", "n", "j"])
|
||||
hi = r.choice([Var("n"), Var("N"), INF, Num(10), Num(100)])
|
||||
if hi == Var(v):
|
||||
hi = INF
|
||||
return Sum(self.expr(depth, v), v, r.choice([Num(0), Num(1), Num(1)]), hi)
|
||||
v = r.choice(["x"] * 4 + ["n", "h", "t"])
|
||||
to = r.choice([Num(0)] * 4 + [INF] * 4 + [Num(1), Var("a"), Neg(INF)])
|
||||
return Lim(self.expr(max(depth, 1), v), v, to)
|
||||
|
||||
def tree(self) -> Node:
|
||||
r = self.rng
|
||||
depth = r.choices([1, 2, 3, 4], [25, 40, 25, 10])[0]
|
||||
e = self.big(depth - 1) if r.random() < 0.3 else self.expr(depth)
|
||||
if r.random() < 0.2:
|
||||
lhs = r.choice([Var("y"), Var("f"), Var("x"), self.expr(r.choice([0, 1]))])
|
||||
return Eq(lhs, e)
|
||||
return e
|
||||
|
||||
|
||||
def split_of(typ: str) -> str:
|
||||
"""Split by structure, not by row: the same Typst string always lands in the same split."""
|
||||
h = int(hashlib.md5(typ.encode()).hexdigest(), 16) % 100
|
||||
return "valid" if h < 2 else "test" if h < 4 else "train"
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("-n", type=int, default=200_000, help="number of pairs to generate")
|
||||
ap.add_argument("--per-tree", type=int, default=2, help="max English phrasings per tree")
|
||||
ap.add_argument("--max-chars", type=int, default=150, help="drop trees whose Typst is longer than this")
|
||||
ap.add_argument("--out", default="data")
|
||||
ap.add_argument("--seed", type=int, default=0)
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
rng = random.Random(args.seed)
|
||||
gen = TreeGen(rng)
|
||||
pairs: list[tuple[str, str, Node]] = []
|
||||
seen: set[str] = set()
|
||||
while len(pairs) < args.n:
|
||||
t = gen.tree()
|
||||
typ = to_typst(t)
|
||||
if len(typ) > args.max_chars:
|
||||
continue
|
||||
for _ in range(rng.randint(1, args.per_tree)):
|
||||
en = to_english(t, rng)
|
||||
if en not in seen:
|
||||
seen.add(en)
|
||||
pairs.append((en, typ, t))
|
||||
|
||||
distinct = sorted({typ for _, typ, _ in pairs})
|
||||
print(f"generated {len(pairs):,} pairs ({len(distinct):,} distinct Typst strings); compile-checking ...")
|
||||
ok = dict(zip(distinct, compiles_many(distinct)))
|
||||
bad = [s for s in distinct if not ok[s]]
|
||||
if bad:
|
||||
print(f"WARNING: dropped {len(bad)} Typst strings that do not compile, e.g.:")
|
||||
for s in bad[:10]:
|
||||
print(" ", s)
|
||||
|
||||
out = pathlib.Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
files = {k: (out / f"{k}.jsonl").open("w") for k in ("train", "valid", "test")}
|
||||
counts: collections.Counter[str] = collections.Counter()
|
||||
hist: collections.Counter[str] = collections.Counter()
|
||||
for en, typ, t in pairs:
|
||||
if not ok[typ]:
|
||||
continue
|
||||
split = split_of(typ)
|
||||
files[split].write(json.dumps({"en": en, "typ": typ}) + "\n")
|
||||
counts[split] += 1
|
||||
if split == "train":
|
||||
hist.update({type(x).__name__ for x in walk(t)})
|
||||
for f in files.values():
|
||||
f.close()
|
||||
|
||||
total = counts["train"] or 1
|
||||
lines = [f"split sizes: {dict(counts)}", "share of training pairs containing each node type:"]
|
||||
for k, v in hist.most_common():
|
||||
lines.append(f" {k:<9}{v / total:6.1%} {'#' * int(40 * v / total)}")
|
||||
report = "\n".join(lines)
|
||||
print(report)
|
||||
(out / "stats.txt").write_text(report + "\n")
|
||||
print(f"wrote {out}/train.jsonl, valid.jsonl, test.jsonl")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Encoder–decoder Transformer (Path A), built on PyTorch's nn.Transformer.
|
||||
|
||||
forward(src, tgt_in) is used in training (whole target at once, causal mask).
|
||||
encode(src) and decode(tgt_in, memory) are used at inference (encode once, decode token by token).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import warnings
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
warnings.filterwarnings("ignore", message="enable_nested_tensor is True")
|
||||
|
||||
CONFIGS = {
|
||||
"tiny": {"d": 128, "heads": 4, "layers": 3, "ff": 512}, # ~2M params: debugging, overfit check
|
||||
"small": {"d": 256, "heads": 4, "layers": 4, "ff": 1024}, # ~8M params: start here
|
||||
"medium": {"d": 512, "heads": 8, "layers": 6, "ff": 2048}, # ~46M params
|
||||
}
|
||||
|
||||
|
||||
def causal_mask(T: int, device=None) -> torch.Tensor:
|
||||
"""(T, T) bool, True above the diagonal = position i may NOT look at position j > i."""
|
||||
return torch.triu(torch.ones(T, T, dtype=torch.bool, device=device), diagonal=1)
|
||||
|
||||
|
||||
class Seq2Seq(nn.Module):
|
||||
def __init__(self, vocab: int, d=256, heads=4, layers=4, ff=1024, max_len=256, drop=0.1, pad_id=0):
|
||||
super().__init__()
|
||||
self.pad_id, self.max_len = pad_id, max_len
|
||||
self.tok_emb = nn.Embedding(vocab, d)
|
||||
self.pos_emb = nn.Embedding(max_len, d) # learned positions: the simplest option
|
||||
self.drop = nn.Dropout(drop)
|
||||
self.tf = nn.Transformer(d, heads, layers, layers, ff, drop, batch_first=True, norm_first=True)
|
||||
self.out = nn.Linear(d, vocab, bias=False)
|
||||
self.out.weight = self.tok_emb.weight # weight tying: one shared tokenizer, one embedding table
|
||||
nn.init.normal_(self.tok_emb.weight, std=d**-0.5)
|
||||
self.scale = math.sqrt(d)
|
||||
|
||||
def emb(self, ids: torch.Tensor) -> torch.Tensor:
|
||||
pos = torch.arange(ids.size(1), device=ids.device)
|
||||
return self.drop(self.tok_emb(ids) * self.scale + self.pos_emb(pos))
|
||||
|
||||
def encode(self, src: torch.Tensor) -> torch.Tensor:
|
||||
"""(B, S) token ids -> (B, S, d) memory, one vector per English token."""
|
||||
return self.tf.encoder(self.emb(src), src_key_padding_mask=src == self.pad_id)
|
||||
|
||||
def decode(self, tgt_in: torch.Tensor, memory: torch.Tensor, src_pad: torch.Tensor | None = None) -> torch.Tensor:
|
||||
"""(B, T) Typst-so-far + memory -> (B, T, vocab) logits for the next token at every position."""
|
||||
h = self.tf.decoder(
|
||||
self.emb(tgt_in),
|
||||
memory,
|
||||
tgt_mask=causal_mask(tgt_in.size(1), tgt_in.device),
|
||||
tgt_is_causal=True,
|
||||
tgt_key_padding_mask=tgt_in == self.pad_id,
|
||||
memory_key_padding_mask=src_pad,
|
||||
)
|
||||
return self.out(h)
|
||||
|
||||
def forward(self, src: torch.Tensor, tgt_in: torch.Tensor) -> torch.Tensor:
|
||||
return self.decode(tgt_in, self.encode(src), src_pad=src == self.pad_id)
|
||||
|
||||
|
||||
def count_params(model: nn.Module) -> int:
|
||||
return sum(p.numel() for p in model.parameters())
|
||||
|
||||
|
||||
def pick_device() -> str:
|
||||
if torch.cuda.is_available():
|
||||
return "cuda"
|
||||
if torch.backends.mps.is_available():
|
||||
return "mps"
|
||||
return "cpu"
|
||||
@@ -0,0 +1,328 @@
|
||||
"""Render one tree two ways: to_typst() (deterministic) and to_english() (randomised).
|
||||
|
||||
Because both strings come from the same tree, every (English, Typst) pair is correct by construction.
|
||||
The English side has to be *unambiguous*: if two different trees could produce the same sentence, the
|
||||
model is taught to guess. The conventions that keep it unambiguous are:
|
||||
|
||||
* "tail" position: a sub-expression is in tail position when nothing follows it inside its parent.
|
||||
Only there may a phrase run on to the end ("e to the minus x squared", "the quantity x plus 1").
|
||||
* Anything that is not "simple" (see is_simple) is wrapped when it is an operand: "(x plus 1)",
|
||||
"open paren x plus 1 close paren", or, in tail position only, "the quantity x plus 1".
|
||||
* An exponent is spoken bare only if it is a number, a variable, or "minus <simple>" in tail position
|
||||
(guide Appendix A, Q1: "e to the minus x squared" = e^(-x^2)). Every other exponent is delimited.
|
||||
* Functions and roots take one simple argument: "sine of x squared" = sin(x^2); sin(x)^2 is said
|
||||
"sine squared of x" or "(sine of x) squared".
|
||||
* Big operators (integral, sum, limit) only appear at the top of a tree, and their body runs until
|
||||
"dx" (integrals), "equals", or the end of the sentence.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import re
|
||||
|
||||
from .ast import BIG_OPS, GREEK, Add, Eq, Frac, Func, Integral, Lim, Mul, Neg, Node, Num, Pow, Sqrt, Sub, Sum, Var
|
||||
|
||||
# ------------------------------------------------------------------------------------------
|
||||
# Typst
|
||||
# ------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def level(n: Node) -> int:
|
||||
"""How tightly a node binds in Typst output (higher = tighter)."""
|
||||
if isinstance(n, Eq):
|
||||
return 0
|
||||
if isinstance(n, (Add, Sub)):
|
||||
return 1
|
||||
if isinstance(n, BIG_OPS):
|
||||
return 2
|
||||
if isinstance(n, Neg):
|
||||
return 3
|
||||
if isinstance(n, Mul):
|
||||
return 4
|
||||
return 9 # atoms: Var, Num, Pow, Frac, Sqrt, Func
|
||||
|
||||
|
||||
def paren(n: Node, cond: bool) -> str:
|
||||
s = to_typst(n)
|
||||
return f"({s})" if cond else s
|
||||
|
||||
|
||||
def group(n: Node) -> str:
|
||||
"""Sub/superscripts: Typst needs parens around anything longer than one atom (they are not shown)."""
|
||||
return paren(n, not isinstance(n, (Var, Num)))
|
||||
|
||||
|
||||
def to_typst(n: Node) -> str:
|
||||
match n:
|
||||
case Var(name):
|
||||
return name
|
||||
case Num(v):
|
||||
return str(v)
|
||||
case Neg(a):
|
||||
return f"-{paren(a, level(a) <= 3)}"
|
||||
case Add(a, b):
|
||||
return f"{to_typst(a)} + {paren(b, level(b) <= 1 or isinstance(b, Neg))}"
|
||||
case Sub(a, b):
|
||||
return f"{to_typst(a)} - {paren(b, level(b) <= 1 or isinstance(b, Neg))}"
|
||||
case Mul(a, b):
|
||||
left = paren(a, level(a) < 3)
|
||||
right = paren(b, level(b) <= 3 and not isinstance(b, BIG_OPS))
|
||||
sep = " dot " if left[-1].isdigit() and right[0].isdigit() else " " # "2 dot 3", not "2 3"
|
||||
return f"{left}{sep}{right}"
|
||||
case Pow(b, e):
|
||||
# parens around the base *are* visible, so only add them when needed
|
||||
return f"{paren(b, not isinstance(b, (Var, Num, Func, Sqrt)))}^{group(e)}"
|
||||
case Frac(a, b):
|
||||
return f"frac({to_typst(a)}, {to_typst(b)})"
|
||||
case Sqrt(a):
|
||||
return f"sqrt({to_typst(a)})"
|
||||
case Func(name, a):
|
||||
return f"{name}({to_typst(a)})"
|
||||
case Integral(body, v, lo, hi):
|
||||
bounds = "" if lo is None else f"_{group(lo)}^{group(hi)}"
|
||||
return f"integral{bounds} {paren(body, level(body) <= 1)} dif {v}"
|
||||
case Sum(body, v, lo, hi):
|
||||
return f"sum_({v} = {to_typst(lo)})^{group(hi)} {paren(body, level(body) <= 1)}"
|
||||
case Lim(body, v, to):
|
||||
return f"lim_({v} -> {to_typst(to)}) {paren(body, level(body) <= 1)}"
|
||||
case Eq(a, b):
|
||||
return f"{to_typst(a)} = {to_typst(b)}"
|
||||
raise NotImplementedError(n)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------
|
||||
# English
|
||||
# ------------------------------------------------------------------------------------------
|
||||
|
||||
ONES = [
|
||||
"zero",
|
||||
"one",
|
||||
"two",
|
||||
"three",
|
||||
"four",
|
||||
"five",
|
||||
"six",
|
||||
"seven",
|
||||
"eight",
|
||||
"nine",
|
||||
"ten",
|
||||
"eleven",
|
||||
"twelve",
|
||||
"thirteen",
|
||||
"fourteen",
|
||||
"fifteen",
|
||||
"sixteen",
|
||||
"seventeen",
|
||||
"eighteen",
|
||||
"nineteen",
|
||||
]
|
||||
TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
|
||||
ORDINALS = {4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth", 10: "tenth"}
|
||||
FUNC_WORDS = {
|
||||
"sin": ["sine", "sin"],
|
||||
"cos": ["cosine", "cos"],
|
||||
"tan": ["tangent", "tan"],
|
||||
"ln": ["ln", "natural log", "the natural log", "the natural logarithm"],
|
||||
"log": ["log", "the log", "the logarithm"],
|
||||
"exp": ["exp", "the exponential"],
|
||||
}
|
||||
|
||||
|
||||
def number_words(v: int) -> str:
|
||||
if v < 20:
|
||||
return ONES[v]
|
||||
if v < 100:
|
||||
t, o = divmod(v, 10)
|
||||
return TENS[t] + ("" if o == 0 else " " + ONES[o])
|
||||
if v == 100:
|
||||
return "one hundred"
|
||||
return str(v)
|
||||
|
||||
|
||||
def is_simple(n: Node) -> bool:
|
||||
"""Can be said as an operand without wrapping it in parentheses."""
|
||||
if isinstance(n, (Var, Num, Func, Sqrt)):
|
||||
return True
|
||||
return isinstance(n, Pow) and isinstance(n.base, (Var, Num)) and isinstance(n.exp, (Var, Num))
|
||||
|
||||
|
||||
class English:
|
||||
def __init__(self, rng: random.Random):
|
||||
self.rng = rng
|
||||
|
||||
def c(self, *options: str) -> str:
|
||||
return self.rng.choice(options)
|
||||
|
||||
def p(self, prob: float) -> bool:
|
||||
return self.rng.random() < prob
|
||||
|
||||
def wrap(self, n: Node, tail: bool) -> str:
|
||||
"""Say n so that a listener knows where it ends."""
|
||||
if is_simple(n):
|
||||
return self.say(n, tail)
|
||||
s = self.say(n, tail=True) # the brackets delimit it, so inside it may run on
|
||||
options = [f"({s})", f"open paren {s} close paren"]
|
||||
if tail: # "the quantity" has no closing word, so it must run to the end
|
||||
options += [f"the quantity {s}"] * 2
|
||||
return self.c(*options)
|
||||
|
||||
def say(self, n: Node, tail: bool = True) -> str:
|
||||
match n:
|
||||
case Var("infinity"):
|
||||
return "infinity"
|
||||
case Var(name):
|
||||
return name
|
||||
case Num(v):
|
||||
return number_words(v) if v <= 100 and self.p(0.3) else str(v)
|
||||
|
||||
case Neg(a):
|
||||
inner = self.say(a, tail) if is_simple(a) else self.wrap(a, tail)
|
||||
return f"{self.c('minus', 'negative')} {inner}"
|
||||
|
||||
case Add(a, b) | Sub(a, b):
|
||||
left = self.say(a, tail=False)
|
||||
right = self.wrap(b, tail) if level(b) <= 1 or isinstance(b, Neg) else self.say(b, tail)
|
||||
op = self.c("plus", "plus", "add") if isinstance(n, Add) else "minus"
|
||||
if op == "add":
|
||||
op = "plus"
|
||||
return f"{left} {op} {right}"
|
||||
|
||||
case Mul(a, b):
|
||||
left = self.say(a, tail=False) if level(a) >= 3 else self.wrap(a, tail=False)
|
||||
right = self.wrap(b, tail) if level(b) <= 3 else self.say(b, tail)
|
||||
if isinstance(a, Num) and isinstance(b, (Var, Pow, Func, Sqrt)) and self.p(0.6):
|
||||
if isinstance(b, Var) and len(b.name) == 1 and left.isdigit() and self.p(0.5):
|
||||
return f"{left}{right}" # "2x"
|
||||
return f"{left} {right}" # "2 x", "3 sine of x"
|
||||
if isinstance(a, Var) and isinstance(b, Var) and self.p(0.4):
|
||||
return f"{left} {right}" # "x y"
|
||||
return self.c(f"{left} times {right}", f"{left} times {right}", f"{left} multiplied by {right}")
|
||||
|
||||
case Pow(b, e):
|
||||
return self.say_pow(b, e, tail)
|
||||
|
||||
case Frac(Num(1), Num(2)) if self.p(0.4):
|
||||
return self.c("one half", "a half")
|
||||
case Frac(a, b):
|
||||
num = self.wrap(a, tail=False)
|
||||
den = self.wrap(b, tail)
|
||||
return self.c(
|
||||
f"{num} over {den}",
|
||||
f"{num} over {den}",
|
||||
f"{num} divided by {den}",
|
||||
f"the fraction {num} over {den}",
|
||||
)
|
||||
|
||||
case Sqrt(a):
|
||||
arg = self.say(a, tail) if is_simple(a) else self.wrap(a, tail)
|
||||
return self.c(f"the square root of {arg}", f"square root of {arg}", f"root {arg}", f"sqrt of {arg}")
|
||||
|
||||
case Func(name, a):
|
||||
word = self.rng.choice(FUNC_WORDS[name])
|
||||
if not is_simple(a):
|
||||
return f"{word} of {self.wrap(a, tail)}"
|
||||
arg = self.say(a, tail)
|
||||
if word in ("sin", "cos", "tan", "ln", "log", "exp") and self.p(0.5):
|
||||
return f"{word} {arg}"
|
||||
return f"{word} of {arg}"
|
||||
|
||||
case Integral(body, v, lo, hi):
|
||||
b = self.say(body, tail=True) # "dx" closes the body
|
||||
d = self.c(f"d{v}", f"d{v}", f"d {v}", f"with respect to {v}")
|
||||
if lo is None:
|
||||
return self.c(
|
||||
f"the integral of {b} {d}",
|
||||
f"integral of {b} {d}",
|
||||
f"integral {b} {d}",
|
||||
f"the indefinite integral of {b} {d}",
|
||||
)
|
||||
lo_s, hi_s = self.say(lo, False), self.say(hi, False)
|
||||
return self.c(
|
||||
f"the integral from {lo_s} to {hi_s} of {b} {d}",
|
||||
f"the integral from {lo_s} to {hi_s} of {b} {d}",
|
||||
f"integral from {lo_s} to {hi_s} of {b} {d}",
|
||||
f"integral {lo_s} to {hi_s} {b} {d}",
|
||||
f"the definite integral from {lo_s} to {hi_s} of {b} {d}",
|
||||
f"the integral of {b} from {lo_s} to {hi_s} {d}",
|
||||
)
|
||||
|
||||
case Sum(body, v, lo, hi):
|
||||
b = self.say(body, tail)
|
||||
lo_s, hi_s = self.say(lo, False), self.say(hi, False)
|
||||
eq = self.c("equals", "equals", "=", "from")
|
||||
return self.c(
|
||||
f"the sum from {v} {eq} {lo_s} to {hi_s} of {b}",
|
||||
f"the sum from {v} {eq} {lo_s} to {hi_s} of {b}",
|
||||
f"sum from {v} {eq} {lo_s} to {hi_s} of {b}",
|
||||
f"sum {v} {eq} {lo_s} to {hi_s} {b}",
|
||||
f"the sum over {v} from {lo_s} to {hi_s} of {b}",
|
||||
)
|
||||
|
||||
case Lim(body, v, to):
|
||||
b = self.say(body, tail)
|
||||
to_s = self.say(to, False)
|
||||
verb = self.c("approaches", "approaches", "goes to", "tends to")
|
||||
return self.c(
|
||||
f"the limit as {v} {verb} {to_s} of {b}",
|
||||
f"the limit as {v} {verb} {to_s} of {b}",
|
||||
f"limit as {v} {verb} {to_s} of {b}",
|
||||
f"lim {v} {verb} {to_s} of {b}",
|
||||
)
|
||||
|
||||
case Eq(a, b):
|
||||
return f"{self.say(a, False)} {self.c('equals', 'equals', 'is equal to', 'is')} {self.say(b, tail)}"
|
||||
raise NotImplementedError(n)
|
||||
|
||||
def say_pow(self, b: Node, e: Node, tail: bool) -> str:
|
||||
if isinstance(b, Func) and e in (Num(2), Num(3)) and is_simple(b.arg) and self.p(0.5):
|
||||
word = self.rng.choice(FUNC_WORDS[b.name][:2])
|
||||
return f"{word} {'squared' if e == Num(2) else 'cubed'} of {self.say(b.arg, tail)}" # sine squared of x
|
||||
|
||||
if isinstance(b, (Var, Num)):
|
||||
base = self.say(b, False)
|
||||
else: # bracket the base, even for functions: "sine of x squared" means sin(x^2)
|
||||
inner = self.say(b, True)
|
||||
base = self.c(f"({inner})", f"open paren {inner} close paren")
|
||||
|
||||
if e == Num(2):
|
||||
return self.c(f"{base} squared", f"{base} squared", f"{base} to the power of 2", f"{base} to the second")
|
||||
if e == Num(3):
|
||||
return self.c(f"{base} cubed", f"{base} cubed", f"{base} to the power of 3", f"{base} to the third")
|
||||
if isinstance(e, Num):
|
||||
options = [f"{base} to the power of {self.say(e)}", f"{base} to the {self.say(e)}"]
|
||||
if e.value in ORDINALS:
|
||||
options.append(f"{base} to the {ORDINALS[e.value]}")
|
||||
return self.c(*options)
|
||||
if isinstance(e, Var):
|
||||
options = [f"{base} to the {e.name}", f"{base} to the power of {e.name}"]
|
||||
if len(e.name) == 1:
|
||||
options.append(f"{base} to the {e.name}th")
|
||||
return self.c(*options)
|
||||
if tail and isinstance(e, Neg) and is_simple(e.arg): # e to the minus x squared
|
||||
ex = self.say(e, True)
|
||||
return self.c(f"{base} to the {ex}", f"{base} to the power of {ex}")
|
||||
ex = self.say(e, True)
|
||||
return self.c(
|
||||
f"{base} to the ({ex})", f"{base} to the power of ({ex})", f"{base} to the open paren {ex} close paren"
|
||||
)
|
||||
|
||||
|
||||
PREFIXES = ["write ", "what is ", "typeset ", "please write "]
|
||||
|
||||
|
||||
def add_noise(s: str, rng: random.Random) -> str:
|
||||
"""Surface variation people produce: a dropped 'the', capitals, a polite prefix."""
|
||||
if rng.random() < 0.3:
|
||||
s = re.sub(r"(^|\bof )the ", lambda m: m.group(1) if rng.random() < 0.5 else m.group(0), s)
|
||||
if rng.random() < 0.08:
|
||||
s = rng.choice(PREFIXES) + s
|
||||
first = s.split(" ", 1)[0]
|
||||
if rng.random() < 0.15 and len(first) >= 3 and first.isalpha() and first not in GREEK: # never "Y" for y
|
||||
s = s[:1].upper() + s[1:]
|
||||
return s
|
||||
|
||||
|
||||
def to_english(n: Node, rng: random.Random, noise: bool = True) -> str:
|
||||
s = re.sub(r"\s+", " ", English(rng).say(n, tail=True)).strip()
|
||||
return add_noise(s, rng) if noise else s
|
||||
@@ -0,0 +1,60 @@
|
||||
"""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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Check Typst math with the real `typst` CLI, so a renderer bug can never teach the model broken Typst.
|
||||
|
||||
compiles(math) -> bool for one equation (the guide's simple version)
|
||||
compiles_many(maths) -> list[bool]; many equations per file, split in half on failure to find the bad ones
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
|
||||
def _typst() -> str:
|
||||
exe = shutil.which("typst")
|
||||
if exe is None:
|
||||
raise SystemExit("The `typst` CLI is not installed. Install it with: brew install typst")
|
||||
return exe
|
||||
|
||||
|
||||
def _safe(math: str) -> bool:
|
||||
# a stray `$` would end the math block early and let arbitrary markup through
|
||||
return math.strip() != "" and "$" not in math and "\n" not in math
|
||||
|
||||
|
||||
def _compile(maths: list[str]) -> bool:
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src = pathlib.Path(d) / "t.typ"
|
||||
src.write_text("".join(f"${m}$\n\n" for m in maths))
|
||||
return subprocess.run([_typst(), "compile", str(src)], capture_output=True, check=False).returncode == 0
|
||||
|
||||
|
||||
def compiles(math: str) -> bool:
|
||||
return _safe(math) and _compile([math])
|
||||
|
||||
|
||||
def _bisect(maths: list[str]) -> list[bool]:
|
||||
if _compile(maths):
|
||||
return [True] * len(maths)
|
||||
if len(maths) == 1:
|
||||
return [False]
|
||||
mid = len(maths) // 2
|
||||
return _bisect(maths[:mid]) + _bisect(maths[mid:])
|
||||
|
||||
|
||||
def compiles_many(maths: list[str], batch: int = 500, workers: int = 8) -> list[bool]:
|
||||
_typst()
|
||||
ok = [False] * len(maths)
|
||||
idx = [i for i, m in enumerate(maths) if _safe(m)]
|
||||
chunks = [idx[i : i + batch] for i in range(0, len(idx), batch)]
|
||||
with ThreadPoolExecutor(workers) as ex:
|
||||
for chunk, res in zip(chunks, ex.map(lambda c: _bisect([maths[i] for i in c]), chunks)):
|
||||
for i, r in zip(chunk, res):
|
||||
ok[i] = r
|
||||
return ok
|
||||
Reference in new issue
Block a user