"""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()