Files
isotope-typst/src/isotope_typst/validate.py
T
paultal 98e88cac04 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]>
2026-11-27 00:24:05 +02:00

58 lines
1.9 KiB
Python

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