1 Commits
Author SHA1 Message Date
paultal bb98b99fc5 Add isotope-typst proof of concept (Path A)
Spoken-English math to Typst math with a small from-scratch Transformer:
synthetic data generator, BPE tokenizer, training, constrained/beam
decoding, and evaluation against a hand-written test set. The trained
model is not tracked; ./run.sh produces it.
2026-11-27 00:16:09 +02:00
27 changed files with 23517 additions and 2 deletions

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Virtual environments
.venv
data/
# Generated by ./run.sh; only the tokenizer and eval summary are tracked
artifacts/*
!artifacts/tokenizer.json
!artifacts/eval.json
# Claude Code personal settings
.claude/settings.local.json
+11
View File
@@ -0,0 +1,11 @@
{
"mcpServers": {
"gitea": {
"command": "gitea-mcp-server",
"args": ["-t", "stdio", "-H", "https://git.paultal.online"],
"env": {
"GITEA_ACCESS_TOKEN_FILE": "${HOME}/.config/gitea-mcp/token"
}
}
}
}
+1
View File
@@ -0,0 +1 @@
3.12
+67 -2
View File
@@ -1,5 +1,70 @@
# isotope-typst # isotope-typst
**isotope-typst** is a Transformer model that translates math written in plain English into [Typst](https://typst.app) markup. Turn spoken-English math into Typst math with a small Transformer trained from scratch.
For example, `the integral from 0 to infinity of e to the minus x squared dx` becomes `$integral_0^infinity e^(-x^2) dif x$`. ```
$ uv run isotope "the integral from 0 to infinity of e to the minus x squared dx"
$integral_0^infinity e^(-x^2) dif x$
```
## Run it
```bash
./run.sh # build everything (skips finished steps)
./isotope "x squared plus y squared equals r squared"
./isotope # REPL: model stays loaded, :help for commands
```
`./isotope` is shorthand for `uv run isotope`.
The trained model (`artifacts/model.pt`) is not in git. Run `./run.sh` to train one before using `./isotope`.
`./run.sh` generates data, trains the tokenizer, runs the memorise-100-pairs sanity check, trains
the model, and evaluates it. `./run.sh --quick` does a smoke run in a few minutes. `./run.sh --fresh`
starts again from nothing.
Translator options: `--beam 4` for beam search, `--check` to compile-check the output, `--raw` to
leave off the `$ … $`, and `--no-constrain` to turn off paren-balanced decoding.
## Commands, one per stage of the guide
| stage | command | file |
|---|---|---|
| §4 data | `uv run isotope-gen` (`--basic -n 10000` for milestone M1) | `ast.py`, `render.py`, `generate.py`, `validate.py` |
| §5 tokens | `uv run isotope-tokenizer` | `tokenizer.py` |
| §6 model | built-in `nn.Transformer`, or `--custom-attn` for the hand-written attention | `model.py` |
| §7 training | `uv run isotope-train` (`--overfit 100`, `--config tiny/small/medium`) | `train.py` |
| §8 inference | `uv run isotope "..."` (greedy, beam, constrained decoding) | `translate.py` |
| §9 evaluation | `uv run isotope-eval` (exact / compiles / render match, synthetic and hand-written sets) | `evaluate.py` |
| §10 Path B | `uv run --group pathb isotope-pathb all` (mlx-lm LoRA on Qwen2.5-0.5B), or `uv run --group byt5 isotope-pathb all --backend byt5` | `pathb.py` |
| §4.1 paraphrase | `uv run --group pathb isotope-paraphrase -n 2000 --append` | `paraphrase.py` |
| all of Path A | `uv run isotope-pipeline` (what `run.sh` calls) | `pipeline.py` |
| tests | `uv run pytest` | `tests/` |
Outputs go to:
* `data/`: `train/valid/test.jsonl`, split by a hash of the Typst string, plus `stats.txt`, a histogram of node types
* `artifacts/`: `tokenizer.json`, `model.pt`, `train_log.csv`, `eval.json`, `errors_*.txt` (failure dumps for error analysis)
* `eval/hand_test.jsonl`: the hand-written test set, which is never generated and never trained on
## Conventions the generator uses
* "e to the …" takes everything after it as the exponent, so "e to the minus x squared" means `e^(-x^2)`.
* "the quantity …", "( … )" and "open paren … close paren" mark grouping.
* Fractions render as `frac(a, b)`, functions as `sin(x)`, and derivatives as `frac(dif, dif x) …`.
## Results on an M4 MacBook Air
Render match is the share of outputs whose compiled Typst looks identical to the reference.
| model | synthetic test | hand-written test | training time |
|---|---|---|---|
| Path A, first data generator | 96.3% | 71.3% | ~18 min |
| Path A, after error analysis (default) | **96.3%** | **83.2%** | ~18 min |
| Path B, Qwen2.5-0.5B + LoRA, 1000 iters | 73.0% | 80.2% | ~20 min |
The hand-written score rose from 71% to 83% by changing only the data, which is the guide's point
(§9, Q7). Path B gets close on human phrasing with far less task data. It does worse on the synthetic
set because it has seen only 20k of the 288k pairs.
Turn off Low Power Mode before training: it makes training about 3× faster.
+14
View File
@@ -0,0 +1,14 @@
{
"synthetic test": {
"n": 1000,
"exact": 0.963,
"compiles": 0.999,
"render_match": 0.963
},
"hand-written test": {
"n": 167,
"exact": 0.8323353293413174,
"compiles": 1.0,
"render_match": 0.8323353293413174
}
}
File diff suppressed because it is too large. Load diff
+167
View File
@@ -0,0 +1,167 @@
{"en": "the integral from 0 to infinity of e to the minus x squared dx", "typ": "integral_0^infinity e^(-x^2) dif x"}
{"en": "x squared plus y squared equals r squared", "typ": "x^2 + y^2 = r^2"}
{"en": "a squared plus b squared equals c squared", "typ": "a^2 + b^2 = c^2"}
{"en": "e to the x", "typ": "e^x"}
{"en": "e to the negative x", "typ": "e^(-x)"}
{"en": "one over x", "typ": "frac(1, x)"}
{"en": "1 over x squared", "typ": "frac(1, x^2)"}
{"en": "the square root of 2", "typ": "sqrt(2)"}
{"en": "square root of x plus 1", "typ": "sqrt(x) + 1"}
{"en": "the square root of the quantity x plus 1", "typ": "sqrt(x + 1)"}
{"en": "sqrt of x squared plus y squared", "typ": "sqrt(x^2 + y^2)"}
{"en": "sin of x", "typ": "sin(x)"}
{"en": "sine x", "typ": "sin(x)"}
{"en": "cos theta", "typ": "cos(theta)"}
{"en": "sin squared x plus cos squared x equals one", "typ": "sin(x)^2 + cos(x)^2 = 1"}
{"en": "the natural log of x", "typ": "ln(x)"}
{"en": "ln of x plus one", "typ": "ln(x) + 1"}
{"en": "log of 100 equals 2", "typ": "log(100) = 2"}
{"en": "the derivative of x squared with respect to x", "typ": "frac(dif, dif x) x^2"}
{"en": "d/dx of sin x", "typ": "frac(dif, dif x) sin(x)"}
{"en": "the derivative of e to the x with respect to x equals e to the x", "typ": "frac(dif, dif x) e^x = e^x"}
{"en": "the limit as x approaches 0 of sin x over x", "typ": "lim_(x -> 0) frac(sin(x), x)"}
{"en": "limit as n goes to infinity of one over n", "typ": "lim_(n -> infinity) frac(1, n)"}
{"en": "the limit as x goes to infinity of 1 plus 1 over x", "typ": "lim_(x -> infinity) (1 + frac(1, x))"}
{"en": "lim h to 0 of f of x plus h minus f of x over h", "typ": "lim_(h -> 0) frac(f(x + h) - f(x), h)"}
{"en": "the sum from i equals 1 to n of i", "typ": "sum_(i = 1)^n i"}
{"en": "the sum from k equals 0 to infinity of x to the k", "typ": "sum_(k = 0)^infinity x^k"}
{"en": "sum of i squared for i from 1 to n", "typ": "sum_(i = 1)^n i^2"}
{"en": "the sum from n equals 1 to infinity of 1 over n squared equals pi squared over 6", "typ": "sum_(n = 1)^infinity frac(1, n^2) = frac(pi^2, 6)"}
{"en": "the product from i equals 1 to n of i", "typ": "product_(i = 1)^n i"}
{"en": "n factorial", "typ": "n!"}
{"en": "the product from k equals 1 to n of k equals n factorial", "typ": "product_(k = 1)^n k = n!"}
{"en": "integral of x dx", "typ": "integral x dif x"}
{"en": "the integral of 1 over x dx equals ln of x plus c", "typ": "integral frac(1, x) dif x = ln(x) + c"}
{"en": "integral from 0 to 1 of x squared dx", "typ": "integral_0^1 x^2 dif x"}
{"en": "integral from 0 to 1 of x squared dx equals one third", "typ": "integral_0^1 x^2 dif x = frac(1, 3)"}
{"en": "the integral from a to b of f of x dx", "typ": "integral_a^b f(x) dif x"}
{"en": "integrate sin x from 0 to pi", "typ": "integral_0^pi sin(x) dif x"}
{"en": "integral zero to pi of sine x d x equals 2", "typ": "integral_0^pi sin(x) dif x = 2"}
{"en": "the integral from minus infinity to infinity of e to the minus x squared dx equals the square root of pi", "typ": "integral_(-infinity)^infinity e^(-x^2) dif x = sqrt(pi)"}
{"en": "integral of cos t dt", "typ": "integral cos(t) dif t"}
{"en": "x plus 1", "typ": "x + 1"}
{"en": "x minus 1", "typ": "x - 1"}
{"en": "2x plus 3", "typ": "2 x + 3"}
{"en": "3x squared minus 2x plus 1", "typ": "3 x^2 - 2 x + 1"}
{"en": "y equals mx plus b", "typ": "y = m x + b"}
{"en": "y equals 2x minus 5", "typ": "y = 2 x - 5"}
{"en": "f of x equals x cubed", "typ": "f(x) = x^3"}
{"en": "x to the n", "typ": "x^n"}
{"en": "x to the n plus 1", "typ": "x^(n + 1)"}
{"en": "x to the power of n minus 1", "typ": "x^(n - 1)"}
{"en": "2 to the 10", "typ": "2^10"}
{"en": "2 to the tenth equals 1024", "typ": "2^10 = 1024"}
{"en": "x cubed", "typ": "x^3"}
{"en": "x to the fourth", "typ": "x^4"}
{"en": "the cube root of x", "typ": "root(3, x)"}
{"en": "the cube root of 27 equals 3", "typ": "root(3, 27) = 3"}
{"en": "the nth root of x", "typ": "root(n, x)"}
{"en": "the absolute value of x", "typ": "abs(x)"}
{"en": "absolute value of x minus 3 is less than 1", "typ": "abs(x - 3) < 1"}
{"en": "x is greater than 0", "typ": "x > 0"}
{"en": "x is less than or equal to 5", "typ": "x <= 5"}
{"en": "y is at least 2", "typ": "y >= 2"}
{"en": "x does not equal 0", "typ": "x != 0"}
{"en": "a over b", "typ": "frac(a, b)"}
{"en": "a plus b over c", "typ": "a + frac(b, c)"}
{"en": "the quantity a plus b over c", "typ": "frac(a + b, c)"}
{"en": "a plus b all over c", "typ": "frac(a + b, c)"}
{"en": "x over 2", "typ": "frac(x, 2)"}
{"en": "half of x", "typ": "frac(x, 2)"}
{"en": "one half", "typ": "frac(1, 2)"}
{"en": "two thirds", "typ": "frac(2, 3)"}
{"en": "pi over 2", "typ": "frac(pi, 2)"}
{"en": "sin of pi over 2 equals one", "typ": "sin(frac(pi, 2)) = 1"}
{"en": "cos of 0 equals 1", "typ": "cos(0) = 1"}
{"en": "tan x equals sin x over cos x", "typ": "tan(x) = frac(sin(x), cos(x))"}
{"en": "e to the i pi plus 1 equals 0", "typ": "e^(i pi) + 1 = 0"}
{"en": "alpha plus beta", "typ": "alpha + beta"}
{"en": "theta squared", "typ": "theta^2"}
{"en": "2 pi r", "typ": "2 pi r"}
{"en": "pi r squared", "typ": "pi r^2"}
{"en": "lambda times x", "typ": "lambda x"}
{"en": "sigma squared", "typ": "sigma^2"}
{"en": "mu plus 2 sigma", "typ": "mu + 2 sigma"}
{"en": "x sub 1 plus x sub 2", "typ": "x_1 + x_2"}
{"en": "a sub n equals a sub n minus 1 plus 2", "typ": "a_n = a_(n - 1) + 2"}
{"en": "x sub i squared", "typ": "x_i^2"}
{"en": "the sum from i equals 1 to n of x sub i", "typ": "sum_(i = 1)^n x_i"}
{"en": "the quantity x plus 1 squared", "typ": "(x + 1)^2"}
{"en": "x plus 1 all squared", "typ": "(x + 1)^2"}
{"en": "open paren x plus 1 close paren squared", "typ": "(x + 1)^2"}
{"en": "the quantity a plus b times the quantity a minus b", "typ": "(a + b) (a - b)"}
{"en": "x times y", "typ": "x y"}
{"en": "3 times 4 equals 12", "typ": "3 dot 4 = 12"}
{"en": "2 times x", "typ": "2 x"}
{"en": "minus x", "typ": "-x"}
{"en": "negative 5", "typ": "-5"}
{"en": "x minus negative 3", "typ": "x - (-3)"}
{"en": "e to the minus x", "typ": "e^(-x)"}
{"en": "e to the 2x", "typ": "e^(2 x)"}
{"en": "e to the x squared", "typ": "e^(x^2)"}
{"en": "10 to the minus 3", "typ": "10^(-3)"}
{"en": "1 over the square root of 2", "typ": "frac(1, sqrt(2))"}
{"en": "the square root of 2 over 2", "typ": "frac(sqrt(2), 2)"}
{"en": "x equals negative b over 2a", "typ": "x = frac(-b, 2 a)"}
{"en": "b squared minus 4ac", "typ": "b^2 - 4 a c"}
{"en": "the derivative of f with respect to t", "typ": "frac(dif, dif t) f"}
{"en": "d by dt of t cubed equals 3 t squared", "typ": "frac(dif, dif t) t^3 = 3 t^2"}
{"en": "the limit as x tends to 0 of the quantity e to the x minus 1 over x equals 1", "typ": "lim_(x -> 0) frac(e^x - 1, x) = 1"}
{"en": "lim x to infinity of x over e to the x", "typ": "lim_(x -> infinity) frac(x, e^x)"}
{"en": "the integral from 1 to e of 1 over x dx equals 1", "typ": "integral_1^e frac(1, x) dif x = 1"}
{"en": "integral 0 to 2 pi of sin squared theta d theta", "typ": "integral_0^(2 pi) sin(theta)^2 dif theta"}
{"en": "the integral of e to the 2x dx", "typ": "integral e^(2 x) dif x"}
{"en": "integral of x e to the x dx", "typ": "integral x e^x dif x"}
{"en": "integral from 0 to 1 of the square root of x dx", "typ": "integral_0^1 sqrt(x) dif x"}
{"en": "the integral of 1 over 1 plus x squared dx", "typ": "integral frac(1, 1 + x^2) dif x"}
{"en": "the sum from k equals 1 to n of k equals n times n plus 1 over 2", "typ": "sum_(k = 1)^n k = frac(n (n + 1), 2)"}
{"en": "sum k equals 0 to n of 2 to the k", "typ": "sum_(k = 0)^n 2^k"}
{"en": "the sum from n equals 0 to infinity of x to the n over n factorial equals e to the x", "typ": "sum_(n = 0)^infinity frac(x^n, n!) = e^x"}
{"en": "the product from i equals 1 to n of x sub i", "typ": "product_(i = 1)^n x_i"}
{"en": "the absolute value of a times b equals the absolute value of a times the absolute value of b", "typ": "abs(a b) = abs(a) abs(b)"}
{"en": "ln of e equals 1", "typ": "ln(e) = 1"}
{"en": "the log of x times y equals log x plus log y", "typ": "log(x y) = log(x) + log(y)"}
{"en": "e to the ln x equals x", "typ": "e^(ln(x)) = x"}
{"en": "exp of x", "typ": "exp(x)"}
{"en": "sin of 2x equals 2 sin x cos x", "typ": "sin(2 x) = 2 sin(x) cos(x)"}
{"en": "cos squared theta", "typ": "cos(theta)^2"}
{"en": "the square root of a squared plus b squared", "typ": "sqrt(a^2 + b^2)"}
{"en": "x to the one half", "typ": "x^(frac(1, 2))"}
{"en": "x to the 1/2", "typ": "x^(frac(1, 2))"}
{"en": "1/x", "typ": "frac(1, x)"}
{"en": "x^2 + 1", "typ": "x^2 + 1"}
{"en": "x^2 - 4 = 0", "typ": "x^2 - 4 = 0"}
{"en": "integral from 0 to 1 of x^2 dx", "typ": "integral_0^1 x^2 dif x"}
{"en": "integrate e^(-x^2) from zero to infinity with respect to x", "typ": "integral_0^infinity e^(-x^2) dif x"}
{"en": "sqrt(x) + 1", "typ": "sqrt(x) + 1"}
{"en": "what is the integral of x squared", "typ": "integral x^2 dif x"}
{"en": "write x squared over 2", "typ": "frac(x^2, 2)"}
{"en": "How do I write the sum from i = 1 to n of i squared", "typ": "sum_(i = 1)^n i^2"}
{"en": "X SQUARED PLUS ONE", "typ": "x^2 + 1"}
{"en": "The square root of pi", "typ": "sqrt(pi)"}
{"en": "the intergal from 0 to 1 of x dx", "typ": "integral_0^1 x dif x"}
{"en": "the sqaure root of 3", "typ": "sqrt(3)"}
{"en": "x sqared", "typ": "x^2"}
{"en": "seven times eight equals fifty six", "typ": "7 dot 8 = 56"}
{"en": "two x plus three y equals six", "typ": "2 x + 3 y = 6"}
{"en": "three over four", "typ": "frac(3, 4)"}
{"en": "ten to the sixth", "typ": "10^6"}
{"en": "one plus one equals two", "typ": "1 + 1 = 2"}
{"en": "twenty plus x", "typ": "20 + x"}
{"en": "the derivative of the quantity x squared plus 3x with respect to x", "typ": "frac(dif, dif x) (x^2 + 3 x)"}
{"en": "the second power of x", "typ": "x^2"}
{"en": "x raised to the power of 5", "typ": "x^5"}
{"en": "x divided by y", "typ": "frac(x, y)"}
{"en": "x times the quantity y plus z", "typ": "x (y + z)"}
{"en": "a times b plus c", "typ": "a b + c"}
{"en": "the fraction a plus b over c plus d", "typ": "frac(a + b, c + d)"}
{"en": "the integral from 0 to x of f of t dt", "typ": "integral_0^x f(t) dif t"}
{"en": "the limit as x approaches a of f of x equals L", "typ": "lim_(x -> a) f(x) = L"}
{"en": "epsilon is greater than 0", "typ": "epsilon > 0"}
{"en": "delta x", "typ": "delta x"}
{"en": "the absolute value of x minus a is less than delta", "typ": "abs(x - a) < delta"}
{"en": "r equals the square root of x squared plus y squared", "typ": "r = sqrt(x^2 + y^2)"}
{"en": "the cube of x plus 1", "typ": "(x + 1)^3"}
{"en": "x times x equals x squared", "typ": "x x = x^2"}
{"en": "omega equals 2 pi f", "typ": "omega = 2 pi f"}
{"en": "theta equals pi over 4", "typ": "theta = frac(pi, 4)"}
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Translate English math to Typst: ./isotope "x squared plus one" (no argument = interactive)
cd "$(dirname "$0")" && exec uv run -q isotope "$@"
+50
View File
@@ -0,0 +1,50 @@
[project]
name = "isotope-typst"
version = "0.1.0"
description = "Spoken-English math -> Typst math with a small Transformer"
readme = "README.md"
authors = [
{ name = "Paul Tal", email = "[email protected]" }
]
requires-python = ">=3.12"
dependencies = [
"numpy>=2.5.5",
"tokenizers>=0.23.3",
"torch>=2.15.0",
"tqdm>=4.70.1",
]
[project.scripts]
isotope = "isotope_typst.translate:main"
isotope-gen = "isotope_typst.generate:main"
isotope-tokenizer = "isotope_typst.tokenizer:main"
isotope-train = "isotope_typst.train:main"
isotope-eval = "isotope_typst.evaluate:main"
isotope-pipeline = "isotope_typst.pipeline:main"
isotope-pathb = "isotope_typst.pathb:main"
isotope-paraphrase = "isotope_typst.paraphrase:main"
[build-system]
requires = ["uv_build>=0.13.9,<0.14.0"]
build-backend = "uv_build"
[dependency-groups]
byt5 = [
"accelerate>=1.16.0",
"datasets>=5.2.0",
"transformers>=5.24.1",
]
dev = [
"pytest>=9.2.0",
"ruff>=0.17.6",
]
pathb = [
"mlx-lm>=0.32.2",
]
[tool.ruff]
line-length = 130
[tool.pytest.ini_options]
testpaths = ["tests"]
filterwarnings = ["ignore:enable_nested_tensor"]
Executable
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# One command to build everything: data -> tokenizer -> sanity check -> train -> evaluate.
# Steps that are already done are skipped, so re-running is cheap.
# ./run.sh full run (~20-60 min on an M-series Mac)
# ./run.sh --quick few-minute smoke run with a tiny model
# ./run.sh --fresh delete data/ and artifacts/ and redo everything
set -euo pipefail
cd "$(dirname "$0")"
if ! command -v uv >/dev/null; then
echo "Installing uv ..."; curl -LsSf https://astral.sh/uv/install.sh | sh; export PATH="$HOME/.local/bin:$PATH"
fi
if ! command -v typst >/dev/null; then
if command -v brew >/dev/null; then brew install typst; else echo "Please install typst: https://github.com/typst/typst#installation"; exit 1; fi
fi
uv sync -q
uv run isotope-pipeline "$@"
+1
View File
@@ -0,0 +1 @@
"""isotope-typst: spoken-English math -> Typst."""
+151
View File
@@ -0,0 +1,151 @@
"""Math expression nodes (the AST that both renderers walk)."""
from __future__ import annotations
from dataclasses import dataclass
class Node:
pass
@dataclass(frozen=True)
class Var(Node):
name: str # "x", "alpha", "pi", "e", "infinity", ...
@dataclass(frozen=True)
class Num(Node):
value: int
@dataclass(frozen=True)
class Neg(Node):
arg: Node
@dataclass(frozen=True)
class Pow(Node):
base: Node
exp: Node
@dataclass(frozen=True)
class Subscript(Node):
base: Node
sub: Node
@dataclass(frozen=True)
class Frac(Node):
num: Node
den: Node
@dataclass(frozen=True)
class Sqrt(Node):
arg: Node
index: Node | None = None # None = square root
@dataclass(frozen=True)
class Func(Node):
name: str # sin, cos, tan, ln, log, exp
arg: Node
@dataclass(frozen=True)
class Abs(Node):
arg: Node
@dataclass(frozen=True)
class Factorial(Node):
arg: Node
@dataclass(frozen=True)
class Mul(Node):
left: Node
right: 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 Integral(Node):
body: Node
var: str
lo: Node | None = None
hi: Node | None = None
@dataclass(frozen=True)
class Sum(Node):
body: Node
var: str
lo: Node
hi: Node
@dataclass(frozen=True)
class Prod(Node):
body: Node
var: str
lo: Node
hi: Node
@dataclass(frozen=True)
class Lim(Node):
body: Node
var: str
to: Node
@dataclass(frozen=True)
class Deriv(Node):
body: Node
var: str
@dataclass(frozen=True)
class Rel(Node):
"""Equation / inequality. op is one of = != < > <= >=."""
left: Node
op: str
right: Node
def Eq(left: Node, right: Node) -> Rel:
return Rel(left, "=", right)
GREEK = ["alpha", "beta", "gamma", "delta", "theta", "lambda", "mu", "sigma", "phi", "omega", "epsilon", "rho", "tau"]
CONSTANTS = ["pi", "e", "infinity"]
FUNCS = ["sin", "cos", "tan", "ln", "log", "exp", "f", "g"]
RELS = ["=", "!=", "<", ">", "<=", ">="]
NODE_TYPES = [
"Var", "Num", "Neg", "Pow", "Subscript", "Frac", "Sqrt", "Func", "Abs", "Factorial",
"Mul", "Add", "Sub", "Integral", "Sum", "Prod", "Lim", "Deriv", "Rel",
]
def walk(n: Node):
"""Yield every node in the tree (pre-order)."""
yield n
for v in vars(n).values():
if isinstance(v, Node):
yield from walk(v)
+109
View File
@@ -0,0 +1,109 @@
"""Evaluation ladder: exact match -> compiles -> renders identically, on synthetic + hand-written sets.
uv run isotope-eval # synthetic test (1000 sampled) + eval/hand_test.jsonl
uv run isotope-eval --beam 4
"""
from __future__ import annotations
import argparse
import json
import pathlib
import random
from .validate import compiles_many, render_many
HAND_TEST = "eval/hand_test.jsonl"
def score(preds: list[str], refs: list[str]) -> dict:
"""The four rungs of the ladder (the 4th, real phrasing, is which set you run it on)."""
n = len(refs)
exact = [p.strip() == r.strip() for p, r in zip(preds, refs)]
comp = compiles_many(preds)
imgs = render_many(preds + refs)
pi, ri = imgs[:n], imgs[n:]
render = [e or (a is not None and a == b) for e, a, b in zip(exact, pi, ri)]
return {
"n": n,
"exact": sum(exact) / n,
"compiles": sum(comp) / n,
"render_match": sum(render) / n,
"per_item": [{"exact": e, "compiles": c, "render": r} for e, c, r in zip(exact, comp, render)],
}
def read_jsonl(path: str) -> list[dict]:
with open(path) as f:
return [json.loads(line) for line in f if line.strip()]
def table(results: dict[str, dict]) -> str:
lines = [f"{'set':<22}{'n':>6}{'exact':>9}{'compiles':>10}{'render':>9}", "-" * 56]
for name, r in results.items():
lines.append(f"{name:<22}{r['n']:>6}{r['exact']:>9.1%}{r['compiles']:>10.1%}{r['render_match']:>9.1%}")
return "\n".join(lines)
def error_report(rows: list[dict], preds: list[str], res: dict, limit: int = 50) -> str:
bad = [(row, p, it) for row, p, it in zip(rows, preds, res["per_item"]) if not it["render"]]
# crude "worst first": outputs that do not even compile, then the longest inputs
bad.sort(key=lambda b: (b[2]["compiles"], -len(b[0]["en"])))
out = [f"{len(bad)} failures (showing up to {limit}). Group these and add the missing phrasings to the generator.\n"]
for row, p, it in bad[:limit]:
out.append(f"EN: {row['en']}\nWANT: {row['typ']}\nGOT: {p}{'' if it['compiles'] else ' [does not compile]'}\n")
return "\n".join(out)
def main(argv: list[str] | None = None) -> None:
from .translate import load_model, translate, translate_batch
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--synthetic", default="data/test.jsonl")
ap.add_argument("--hand", default=HAND_TEST)
ap.add_argument("--n-synthetic", type=int, default=1000)
ap.add_argument("--beam", type=int, default=1)
ap.add_argument("--ckpt", default=None)
ap.add_argument("--out", default="artifacts")
args = ap.parse_args(argv)
model, tok, _ = load_model(args.ckpt)
def run(texts: list[str]) -> list[str]:
if args.beam > 1:
return [translate(model, tok, t, beam=args.beam) for t in texts]
out = []
for i in range(0, len(texts), 64):
out += translate_batch(model, tok, texts[i: i + 64])
return out
sets: dict[str, list[dict]] = {}
if pathlib.Path(args.synthetic).exists():
rows = read_jsonl(args.synthetic)
random.Random(0).shuffle(rows)
sets["synthetic test"] = rows[: args.n_synthetic]
if pathlib.Path(args.hand).exists():
sets["hand-written test"] = read_jsonl(args.hand)
results, out = {}, pathlib.Path(args.out)
out.mkdir(exist_ok=True)
for name, rows in sets.items():
print(f"translating {len(rows)} sentences from the {name} set ...")
preds = run([r["en"] for r in rows])
res = score(preds, [r["typ"] for r in rows])
results[name] = res
slug = name.split()[0]
(out / f"errors_{slug}.txt").write_text(error_report(rows, preds, res))
with (out / f"predictions_{slug}.jsonl").open("w") as f:
for r, p, it in zip(rows, preds, res["per_item"]):
f.write(json.dumps({**r, "pred": p, **it}) + "\n")
print()
print(table(results))
print(f"\nfailure dumps: {out}/errors_*.txt predictions: {out}/predictions_*.jsonl")
summary = {k: {m: v[m] for m in ("n", "exact", "compiles", "render_match")} for k, v in results.items()}
(out / "eval.json").write_text(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
+276
View File
@@ -0,0 +1,276 @@
"""Generate (English, Typst) training pairs from random ASTs.
uv run isotope-gen # full generator, ~300k pairs
uv run isotope-gen --basic -n 10000 # the "Your turn" subset: Num Var Neg Pow Frac Integral
"""
from __future__ import annotations
import argparse
import collections
import hashlib
import json
import pathlib
import random
from .ast import (
FUNCS,
GREEK,
RELS,
Abs,
Add,
Deriv,
Factorial,
Frac,
Func,
Integral,
Lim,
Mul,
Neg,
Node,
Num,
Pow,
Prod,
Rel,
Sqrt,
Sub,
Subscript,
Sum,
Var,
walk,
)
from .render import to_english, to_typst
from .validate import compiles_many
INF = Var("infinity")
BIG = (Integral, Sum, Prod, Lim, Deriv)
class TreeGen:
def __init__(self, rng: random.Random, basic: bool = False):
self.rng = rng
self.basic = basic
self.big_left = 0
# -- leaves ---------------------------------------------------------------------
def var_name(self, prefer: str | None = None) -> str:
r = self.rng
if prefer and r.random() < 0.6:
return prefer
pool = ["x"] * 14 + ["y"] * 5 + ["z", "t", "t", "a", "b", "c", "n", "k", "u", "r", "s", "m", "p", "q", "w"]
if not self.basic:
pool += GREEK + ["theta", "alpha"]
return r.choice(pool)
def number(self) -> Num:
r = self.rng.random()
if r < 0.75:
return Num(self.rng.randint(1, 10))
if r < 0.82:
return Num(0)
if r < 0.95:
return Num(self.rng.randint(11, 20))
return Num(self.rng.choice([25, 30, 50, 100, 12, 64, 360, 1000]))
def leaf(self, prefer: str | None = None) -> Node:
r = self.rng.random()
if r < 0.55:
return Var(self.var_name(prefer))
if r < 0.9:
return self.number()
if self.basic:
return Var("e")
if r < 0.94:
return Var(self.rng.choice(["pi", "e"]))
return Subscript(Var(self.var_name(prefer)), self.rng.choice([Num(self.rng.randint(0, 3)), Var("n"), Var("i"), Var("k")]))
# -- inner nodes ----------------------------------------------------------------
def pick(self) -> str:
if self.basic:
kinds = {"Neg": 5, "Pow": 14, "Frac": 10, "Integral": 6}
else:
kinds = {"Add": 12, "Sub": 8, "Mul": 12, "Pow": 14, "Frac": 10, "Neg": 5, "Sqrt": 6,
"Func": 9, "Abs": 2, "Factorial": 2, "Integral": 7, "Sum": 4, "Prod": 2,
"Lim": 4, "Deriv": 3}
if self.big_left <= 0:
for k in ("Integral", "Sum", "Prod", "Lim", "Deriv"):
kinds.pop(k, None)
names, weights = zip(*kinds.items())
return self.rng.choices(names, weights)[0]
def bound(self, lo: bool) -> Node:
r = self.rng
if lo:
return r.choice([Num(0)] * 6 + [Num(1)] * 3 + [Neg(Num(1)), Var("a"), Neg(INF), Num(2), Neg(Var("pi")), Neg(Num(2))])
his = [Num(1)] * 4 + [INF] * 4 + [Num(2), Var("b"), Var("pi"), Num(10), Var("x"), Frac(Var("pi"), Num(2)),
Var("e"), Num(3), Var("t"), Var("a")]
if not self.basic:
his.append(Mul(Num(2), Var("pi")))
return r.choice(his)
def expr(self, depth: int, prefer: str | None = None) -> Node:
r = self.rng
if depth <= 0:
return self.leaf(prefer)
kind = self.pick()
d = depth - 1
match kind:
case "Neg":
a = self.expr(d, prefer)
while isinstance(a, Neg) or a == Num(0):
a = self.expr(d, prefer)
return Neg(a)
case "Pow":
base = self.expr(d if r.random() < 0.3 else 0, prefer)
if r.random() < 0.15:
base = Var("e")
elif not self.basic and r.random() < 0.08:
base = Func(r.choice(["sin", "cos", "tan"]), self.leaf(prefer))
re_ = r.random()
if re_ < 0.55:
exp: Node = Num(r.choice([2, 2, 2, 3, 3, 4, 5, 6, 10]))
elif re_ < 0.7:
exp = Var(r.choice(["n", "k", "x", "a", "m", "t"]))
elif re_ < 0.8:
exp = Neg(self.leaf(prefer))
else:
exp = self.expr(d, prefer)
if isinstance(base, Pow) and r.random() < 0.7:
base = base.base
return Pow(base, exp)
case "Frac":
a, b = self.expr(d, prefer), self.expr(d if r.random() < 0.5 else 0, prefer)
while b == Num(0):
b = self.leaf(prefer)
return Frac(a, b)
case "Sqrt":
k = r.random()
idx = None if k < 0.8 else (Num(3) if k < 0.9 else r.choice([Num(4), Num(5), Var("n")]))
return Sqrt(self.expr(d, prefer), idx)
case "Func":
return Func(r.choice([*FUNCS, "sin", "cos", "ln", "sin", "cos"]), self.expr(d if r.random() < 0.5 else 0, prefer))
case "Abs":
return Abs(self.expr(d, prefer))
case "Factorial":
return Factorial(r.choice([Var("n"), Var("k"), self.number(), Add(Var("n"), Num(1)), Sub(Var("n"), Num(1))]))
case "Mul":
a, b = self.expr(d if r.random() < 0.5 else 0, prefer), self.expr(d, prefer)
if r.random() < 0.4:
a = self.number()
if isinstance(b, Num) and not isinstance(a, Num):
a, b = b, a
if isinstance(a, BIG): # "integral ... dif x y" reads badly; put the big op last
a, b = b, a
return Mul(a, b)
case "Add" | "Sub":
a, b = self.expr(d, prefer), self.expr(d if r.random() < 0.6 else 0, prefer)
return (Add if kind == "Add" else Sub)(a, b)
case "Integral":
self.big_left -= 1
v = r.choice(["x"] * 8 + ["t", "t", "u", "y", "s", "theta", "r", "z"])
body = self.expr(max(d, 1) if r.random() < 0.8 else 0, v)
if r.random() < 0.3:
return Integral(body, v)
return Integral(body, v, self.bound(True), self.bound(False))
case "Sum" | "Prod":
self.big_left -= 1
v = r.choice(["i", "i", "k", "k", "n", "j"])
hi = r.choice([Var("n"), Var("n"), Var("N"), INF, Num(10), Num(100), Var("m")])
if hi == Var(v):
hi = INF
body = self.expr(d, v)
return (Sum if kind == "Sum" else Prod)(body, v, r.choice([Num(0), Num(1), Num(1), Num(2)]), hi)
case "Lim":
self.big_left -= 1
v = r.choice(["x"] * 6 + ["n", "n", "h", "t", "k"])
to = r.choice([Num(0)] * 4 + [INF] * 4 + [Num(1), Var("a"), Neg(INF), Num(2), Var("pi")])
return Lim(self.expr(max(d, 1), v), v, to)
case "Deriv":
self.big_left -= 1
v = r.choice(["x"] * 6 + ["t", "t", "y", "theta"])
return Deriv(self.expr(d, v), v)
raise AssertionError(kind)
def tree(self) -> Node:
r = self.rng
self.big_left = r.choice([1, 1, 1, 2]) if not self.basic else 1
depth = r.choices([1, 2, 3, 4, 5], [20, 35, 28, 12, 5])[0]
if self.basic:
depth = r.choices([1, 2, 3, 4], [30, 40, 22, 8])[0]
e = self.expr(depth)
if not self.basic and r.random() < 0.25:
op = r.choices(RELS, [60, 6, 9, 9, 8, 8])[0]
lhs = r.choice([Var("y"), Var("f"), Var("x"), Func("f", Var("x")), self.expr(r.choice([0, 1, 2]))])
return Rel(lhs, op, e) if r.random() < 0.7 else Rel(e, op, self.expr(r.choice([0, 0, 1])))
return e
def split_of(typ: str) -> str:
"""Split by structure, not by row: hash the Typst string."""
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=300_000, help="number of pairs to generate")
ap.add_argument("--basic", action="store_true", help="only Num/Var/Neg/Pow/Frac/Integral (milestone M1)")
ap.add_argument("--per-tree", type=int, default=2, help="max English phrasings per tree")
ap.add_argument("--out", default="data")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--max-typ-chars", type=int, default=160)
args = ap.parse_args(argv)
rng = random.Random(args.seed)
gen = TreeGen(rng, basic=args.basic)
pairs: list[tuple[str, str, Node]] = []
seen_en: set[str] = set()
while len(pairs) < args.n:
t = gen.tree()
typ = to_typst(t)
if len(typ) > args.max_typ_chars:
continue
for _ in range(rng.randint(1, args.per_tree)):
en = to_english(t, rng)
if en in seen_en or len(en) > 3 * args.max_typ_chars:
continue
seen_en.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; compiling them all ...")
ok = dict(zip(distinct, compiles_many(distinct)))
bad = [s for s in distinct if not ok[s]]
if bad:
print(f"WARNING: {len(bad)} Typst strings failed to compile and were dropped, 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
s = split_of(typ)
files[s].write(json.dumps({"en": en, "typ": typ}) + "\n")
counts[s] += 1
if s == "train":
hist.update({type(x).__name__ for x in walk(t)})
for f in files.values():
f.close()
lines = [f"split sizes: {dict(counts)}", "fraction of training pairs containing each node type:"]
total = counts["train"] or 1
for k, v in sorted(hist.items(), key=lambda kv: -kv[1]):
lines.append(f" {k:<10} {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()
+156
View File
@@ -0,0 +1,156 @@
"""Encoder–decoder Transformer (Path A).
Seq2Seq(custom_attn=False) uses PyTorch's nn.Transformer (fast, the guide's starting point).
Seq2Seq(custom_attn=True) uses the hand-written MultiHeadAttention below, in hand-written pre-norm
encoder/decoder layers, so you can see every piece. Both expose forward / encode / decode.
"""
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": dict(d=128, heads=4, layers=3, ff=512), # ~2M params, for debugging
"small": dict(d=256, heads=4, layers=4, ff=1024), # ~8M params, start here
"medium": dict(d=512, heads=8, layers=6, ff=2048), # ~46M params
}
def causal_mask(T: int, device) -> torch.Tensor:
"""True above the diagonal = 'may not look' (PyTorch bool-mask convention)."""
return torch.triu(torch.ones(T, T, dtype=torch.bool, device=device), 1)
class MultiHeadAttention(nn.Module):
"""Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k) + M) V, split over `heads` heads."""
def __init__(self, d: int, heads: int, drop: float = 0.0):
super().__init__()
assert d % heads == 0
self.h, self.dk = heads, d // heads
self.q, self.k, self.v = nn.Linear(d, d), nn.Linear(d, d), nn.Linear(d, d)
self.o = nn.Linear(d, d)
self.drop = nn.Dropout(drop)
def forward(self, x_q, x_kv, attn_mask=None, key_padding_mask=None):
B, Tq, D = x_q.shape
Tk = x_kv.size(1)
# project, then reshape (B, T, D) -> (B, heads, T, dk)
q = self.q(x_q).view(B, Tq, self.h, self.dk).transpose(1, 2)
k = self.k(x_kv).view(B, Tk, self.h, self.dk).transpose(1, 2)
v = self.v(x_kv).view(B, Tk, self.h, self.dk).transpose(1, 2)
scores = q @ k.transpose(-2, -1) / math.sqrt(self.dk) # (B, h, Tq, Tk)
if attn_mask is not None: # (Tq, Tk) bool, True = blocked
scores = scores.masked_fill(attn_mask, float("-inf"))
if key_padding_mask is not None: # (B, Tk) bool, True = padding
scores = scores.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
w = self.drop(scores.softmax(-1))
out = (w @ v).transpose(1, 2).reshape(B, Tq, D) # merge heads
return self.o(out)
class EncoderLayer(nn.Module):
def __init__(self, d, heads, ff, drop):
super().__init__()
self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = MultiHeadAttention(d, heads, drop)
self.ff = nn.Sequential(nn.Linear(d, ff), nn.ReLU(), nn.Dropout(drop), nn.Linear(ff, d))
self.drop = nn.Dropout(drop)
def forward(self, x, pad):
h = self.n1(x)
x = x + self.drop(self.attn(h, h, key_padding_mask=pad))
return x + self.drop(self.ff(self.n2(x)))
class DecoderLayer(nn.Module):
def __init__(self, d, heads, ff, drop):
super().__init__()
self.n1, self.n2, self.n3 = nn.LayerNorm(d), nn.LayerNorm(d), nn.LayerNorm(d)
self.self_attn = MultiHeadAttention(d, heads, drop)
self.cross_attn = MultiHeadAttention(d, heads, drop)
self.ff = nn.Sequential(nn.Linear(d, ff), nn.ReLU(), nn.Dropout(drop), nn.Linear(ff, d))
self.drop = nn.Dropout(drop)
def forward(self, y, memory, causal, tgt_pad, mem_pad):
h = self.n1(y)
y = y + self.drop(self.self_attn(h, h, attn_mask=causal, key_padding_mask=tgt_pad))
# cross-attention: queries from the decoder, keys/values from the encoder memory
y = y + self.drop(self.cross_attn(self.n2(y), memory, key_padding_mask=mem_pad))
return y + self.drop(self.ff(self.n3(y)))
class Seq2Seq(nn.Module):
def __init__(self, vocab, d=256, heads=4, layers=4, ff=1024, max_len=256, drop=0.1,
custom_attn=False, pad_id=0):
super().__init__()
self.pad_id, self.max_len, self.custom = pad_id, max_len, custom_attn
self.tok_emb = nn.Embedding(vocab, d)
self.pos_emb = nn.Embedding(max_len, d) # learned positions: simplest option
self.scale = math.sqrt(d)
if custom_attn:
self.enc_layers = nn.ModuleList(EncoderLayer(d, heads, ff, drop) for _ in range(layers))
self.dec_layers = nn.ModuleList(DecoderLayer(d, heads, ff, drop) for _ in range(layers))
self.enc_norm, self.dec_norm = nn.LayerNorm(d), nn.LayerNorm(d)
else:
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 (shared tokenizer!)
nn.init.normal_(self.tok_emb.weight, std=d ** -0.5)
self.drop = nn.Dropout(drop)
def emb(self, ids):
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):
pad = src == self.pad_id
x = self.emb(src)
if self.custom:
for layer in self.enc_layers:
x = layer(x, pad)
return self.enc_norm(x)
return self.tf.encoder(x, src_key_padding_mask=pad)
def decode(self, tgt_in, memory, src_pad=None):
T = tgt_in.size(1)
causal = causal_mask(T, tgt_in.device)
tgt_pad = tgt_in == self.pad_id
y = self.emb(tgt_in)
if self.custom:
for layer in self.dec_layers:
y = layer(y, memory, causal, tgt_pad, src_pad)
h = self.dec_norm(y)
else:
h = self.tf.decoder(y, memory, tgt_mask=causal, tgt_key_padding_mask=tgt_pad,
memory_key_padding_mask=src_pad)
return self.out(h) # (batch, T, vocab) logits
def forward(self, src, tgt_in):
return self.decode(tgt_in, self.encode(src), src_pad=(src == self.pad_id))
def count_params(m: nn.Module) -> int:
return sum(p.numel() for p in m.parameters())
def estimate_params(vocab, d, layers, ff, **_) -> int:
"""Guide §6.2: encoder 4d^2 + 2 d dff, decoder 8d^2 + 2 d dff per layer, plus |V| d."""
return layers * (4 * d * d + 2 * d * ff) + layers * (8 * d * d + 2 * d * ff) + vocab * d
def pick_device() -> str:
if torch.cuda.is_available():
return "cuda"
if torch.backends.mps.is_available():
return "mps"
return "cpu"
__all__ = ["CONFIGS", "MultiHeadAttention", "Seq2Seq", "causal_mask", "count_params", "pick_device"]
+59
View File
@@ -0,0 +1,59 @@
"""Robustness boost (guide §4.1, "Later"): paraphrase generated English with a local LLM.
The Typst target is kept unchanged, so every new pair is still correct by construction
(as long as the LLM keeps the meaning -- we drop paraphrases that lose numbers or variables).
uv run --group pathb isotope-paraphrase -n 2000 # writes data/paraphrases.jsonl
uv run --group pathb isotope-paraphrase -n 2000 --append # ...and appends them to data/train.jsonl
"""
from __future__ import annotations
import argparse
import json
import random
import re
MODEL = "mlx-community/Qwen2.5-1.5B-Instruct-4bit"
ASK = ("Rewrite this spoken math expression the way a person might say it out loud, using different "
"words but exactly the same meaning. Keep every number and variable. Reply with the rewrite only.\n\n{en}")
def tokens(s: str) -> set[str]:
return set(re.findall(r"\b(?:\d+|[a-z])\b", s.lower()))
def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("-n", type=int, default=2000)
ap.add_argument("--model", default=MODEL)
ap.add_argument("--data", default="data")
ap.add_argument("--append", action="store_true")
args = ap.parse_args(argv)
try:
from mlx_lm import generate, load
except ImportError:
raise SystemExit("mlx-lm is not installed. Run: uv run --group pathb isotope-paraphrase ...")
model, tok = load(args.model)
rows = [json.loads(line) for line in open(f"{args.data}/train.jsonl")]
random.Random(1).shuffle(rows)
kept = []
for i, r in enumerate(rows[: args.n]):
msgs = [{"role": "user", "content": ASK.format(en=r["en"])}]
prompt = tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
out = generate(model, tok, prompt=prompt, max_tokens=80, verbose=False).strip().split("\n")[0].strip(' "')
if out and tokens(out) >= tokens(r["en"]) - {"a"} and "$" not in out:
kept.append({"en": out, "typ": r["typ"]})
if (i + 1) % 100 == 0:
print(f"{i + 1}/{args.n} kept {len(kept)}", flush=True)
with open(f"{args.data}/paraphrases.jsonl", "w") as f:
f.writelines(json.dumps(k) + "\n" for k in kept)
if args.append:
with open(f"{args.data}/train.jsonl", "a") as f:
f.writelines(json.dumps(k) + "\n" for k in kept)
print(f"kept {len(kept)} paraphrases -> {args.data}/paraphrases.jsonl" + (" (appended to train)" if args.append else ""))
if __name__ == "__main__":
main()
+189
View File
@@ -0,0 +1,189 @@
"""Path B: fine-tune a pretrained model on the same data, evaluate on the same test sets.
Two backends:
mlx (default) decoder-only LM + LoRA with mlx-lm (Apple Silicon). needs: uv sync --group pathb
byt5 ByT5-small seq2seq with Hugging Face transformers. needs: uv sync --group byt5
uv run --group pathb isotope-pathb all # prepare + train + eval (mlx, Qwen2.5-0.5B)
uv run --group pathb isotope-pathb train --iters 2000
uv run --group byt5 isotope-pathb all --backend byt5
"""
from __future__ import annotations
import argparse
import json
import pathlib
import random
import subprocess
import sys
from .evaluate import HAND_TEST, error_report, read_jsonl, score, table
PROMPT = "Translate to Typst math:\n{en}\nTypst:"
MLX_MODEL = "Qwen/Qwen2.5-0.5B"
BYT5_MODEL = "google/byt5-small"
# --------------------------------------------------------------------------------------
# data
# --------------------------------------------------------------------------------------
def prepare(args) -> None:
out = pathlib.Path(args.data) / "mlx"
out.mkdir(parents=True, exist_ok=True)
rng = random.Random(0)
for split, src, n in [("train", "train", args.n_train), ("valid", "valid", 500), ("test", "test", 500)]:
rows = read_jsonl(f"{args.data}/{src}.jsonl")
rng.shuffle(rows)
with (out / f"{split}.jsonl").open("w") as f:
for r in rows[:n]:
f.write(json.dumps({"prompt": PROMPT.format(en=r["en"]), "completion": " " + r["typ"] + "\n"}) + "\n")
print(f"wrote {out}/train.jsonl ({args.n_train} rows), valid.jsonl, test.jsonl")
# --------------------------------------------------------------------------------------
# mlx-lm backend
# --------------------------------------------------------------------------------------
def mlx_train(args) -> None:
try:
import mlx_lm # noqa: F401
except ImportError:
raise SystemExit("mlx-lm is not installed. Run: uv run --group pathb isotope-pathb ...")
if not (pathlib.Path(args.data) / "mlx" / "train.jsonl").exists():
prepare(args)
cmd = [sys.executable, "-m", "mlx_lm", "lora", "--model", args.model or MLX_MODEL, "--train",
"--data", f"{args.data}/mlx", "--iters", str(args.iters), "--batch-size", str(args.batch),
"--adapter-path", args.adapter, "--mask-prompt", "--steps-per-eval", "250",
"--save-every", "250", "--learning-rate", "1e-4"]
print("$", " ".join(cmd))
subprocess.run(cmd, check=True)
def mlx_predict(args, texts: list[str]) -> list[str]:
from mlx_lm import load, stream_generate
model, tokenizer = load(args.model or MLX_MODEL, adapter_path=args.adapter)
preds = []
for i, t in enumerate(texts):
out = ""
for resp in stream_generate(model, tokenizer, prompt=PROMPT.format(en=t), max_tokens=128):
out += resp.text
if "\n" in out: # each completion ends with a newline: stop there
break
preds.append(out.split("\n")[0].strip())
if (i + 1) % 25 == 0:
print(f" {i + 1}/{len(texts)}")
return preds
# --------------------------------------------------------------------------------------
# ByT5 backend
# --------------------------------------------------------------------------------------
def byt5_train(args) -> None:
try:
from datasets import Dataset
from transformers import (
AutoModelForSeq2SeqLM,
AutoTokenizer,
DataCollatorForSeq2Seq,
Seq2SeqTrainer,
Seq2SeqTrainingArguments,
)
except ImportError:
raise SystemExit("transformers/datasets missing. Run: uv run --group byt5 isotope-pathb ... --backend byt5")
name = args.model or BYT5_MODEL
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
rows = read_jsonl(f"{args.data}/train.jsonl")
random.Random(0).shuffle(rows)
val = read_jsonl(f"{args.data}/valid.jsonl")[:500]
def enc(batch):
x = tok(batch["en"], max_length=256, truncation=True)
x["labels"] = tok(text_target=batch["typ"], max_length=192, truncation=True)["input_ids"]
return x
train_ds = Dataset.from_list(rows[: args.n_train]).map(enc, batched=True, remove_columns=["en", "typ"])
val_ds = Dataset.from_list(val).map(enc, batched=True, remove_columns=["en", "typ"])
targs = Seq2SeqTrainingArguments(
output_dir=args.adapter, per_device_train_batch_size=args.batch, per_device_eval_batch_size=args.batch,
learning_rate=3e-4, max_steps=args.iters, warmup_steps=min(200, args.iters // 10), logging_steps=50,
eval_strategy="steps", eval_steps=500, save_steps=500, save_total_limit=1, report_to=[],
)
trainer = Seq2SeqTrainer(model=model, args=targs, train_dataset=train_ds, eval_dataset=val_ds,
data_collator=DataCollatorForSeq2Seq(tok, model=model))
trainer.train()
trainer.save_model(args.adapter)
tok.save_pretrained(args.adapter)
def byt5_predict(args, texts: list[str]) -> list[str]:
import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from .model import pick_device
dev = pick_device()
tok = AutoTokenizer.from_pretrained(args.adapter)
model = AutoModelForSeq2SeqLM.from_pretrained(args.adapter).to(dev).eval()
preds = []
for i in range(0, len(texts), 16):
x = tok(texts[i: i + 16], return_tensors="pt", padding=True).to(dev)
with torch.no_grad():
y = model.generate(**x, max_new_tokens=192, num_beams=1)
preds += [s.strip() for s in tok.batch_decode(y, skip_special_tokens=True)]
return preds
# --------------------------------------------------------------------------------------
def evaluate(args) -> None:
predict = mlx_predict if args.backend == "mlx" else byt5_predict
sets = {}
synth = read_jsonl(f"{args.data}/test.jsonl")
random.Random(0).shuffle(synth)
sets["synthetic test"] = synth[: args.n_eval]
sets["hand-written test"] = read_jsonl(HAND_TEST)
results = {}
out = pathlib.Path("artifacts")
for name, rows in sets.items():
print(f"[{args.backend}] translating {len(rows)} sentences from the {name} set ...")
preds = predict(args, [r["en"] for r in rows])
results[name] = score(preds, [r["typ"] for r in rows])
(out / f"errors_pathb_{args.backend}_{name.split()[0]}.txt").write_text(error_report(rows, preds, results[name]))
print("\nPath B (" + args.backend + ")\n" + table(results))
summary = {k: {m: v[m] for m in ("n", "exact", "compiles", "render_match")} for k, v in results.items()}
(out / f"eval_pathb_{args.backend}.json").write_text(json.dumps(summary, indent=2))
pa = out / "eval.json"
if pa.exists():
print("\nPath A (from-scratch model) for comparison\n" + table(
{k: {**v, "per_item": []} for k, v in json.loads(pa.read_text()).items()}))
def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("command", choices=["prepare", "train", "eval", "all"])
ap.add_argument("--backend", choices=["mlx", "byt5"], default="mlx")
ap.add_argument("--model", default=None, help=f"base model (default {MLX_MODEL} / {BYT5_MODEL})")
ap.add_argument("--data", default="data")
ap.add_argument("--adapter", default=None, help="where to save the adapter / fine-tuned model")
ap.add_argument("--iters", type=int, default=1000)
ap.add_argument("--batch", type=int, default=8)
ap.add_argument("--n-train", type=int, default=20000)
ap.add_argument("--n-eval", type=int, default=200)
args = ap.parse_args(argv)
args.adapter = args.adapter or ("artifacts/lora" if args.backend == "mlx" else "artifacts/byt5")
if args.command in ("prepare", "all") and args.backend == "mlx":
prepare(args)
if args.command in ("train", "all"):
(mlx_train if args.backend == "mlx" else byt5_train)(args)
if args.command in ("eval", "all"):
evaluate(args)
if __name__ == "__main__":
main()
+65
View File
@@ -0,0 +1,65 @@
"""Run the whole Path A pipeline end to end, skipping steps that are already done.
uv run isotope-pipeline # data -> tokenizer -> sanity check -> train -> evaluate
uv run isotope-pipeline --fresh # redo everything from scratch
uv run isotope-pipeline --quick # a few-minute smoke run (tiny model, small data)
"""
from __future__ import annotations
import argparse
import pathlib
import shutil
def banner(msg: str) -> None:
print(f"\n{'=' * 70}\n {msg}\n{'=' * 70}", flush=True)
def main(argv: list[str] | None = None) -> None:
from . import evaluate, generate, tokenizer, train
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--fresh", action="store_true", help="delete data/ and artifacts/ first")
ap.add_argument("--quick", action="store_true", help="tiny model + 30k pairs, for a fast smoke run")
ap.add_argument("--steps", type=int, default=None, help="training steps (default 8000, quick: 1500)")
args = ap.parse_args(argv)
if shutil.which("typst") is None:
raise SystemExit("The `typst` CLI is required. Install it with: brew install typst")
if args.fresh:
shutil.rmtree("data", ignore_errors=True)
shutil.rmtree("artifacts", ignore_errors=True)
if not pathlib.Path("data/train.jsonl").exists():
banner("1/5 generating training data (every Typst string is compile-checked)")
generate.main(["-n", "30000" if args.quick else "300000"])
else:
print("data/ already exists -- skipping generation (use --fresh to regenerate)")
if not pathlib.Path("artifacts/tokenizer.json").exists():
banner("2/5 training the BPE tokenizer")
tokenizer.main([])
banner("3/5 sanity check: a tiny model must memorise 100 pairs")
try:
train.main(["--overfit", "100"])
except SystemExit as e:
if e.code:
raise
if not pathlib.Path("artifacts/model.pt").exists():
steps = args.steps or (1500 if args.quick else 8000)
banner(f"4/5 training the Transformer ({'tiny' if args.quick else 'small'}, {steps} steps)")
train.main(["--steps", str(steps), "--eval-every", "500" if args.quick else "1000"]
+ (["--config", "tiny"] if args.quick else []))
else:
print("artifacts/model.pt already exists -- skipping training (use --fresh to retrain)")
banner("5/5 evaluating")
evaluate.main([])
print('\nAll done. Try it: uv run isotope "the integral from 0 to 1 of x squared dx"')
if __name__ == "__main__":
main()
+513
View File
@@ -0,0 +1,513 @@
"""Render one AST two ways: to_typst() (deterministic) and to_english() (randomised)."""
from __future__ import annotations
import random
import re
from .ast import (
Abs,
Add,
Deriv,
Factorial,
Frac,
Func,
Integral,
Lim,
Mul,
Neg,
Node,
Num,
Pow,
Prod,
Rel,
Sqrt,
Sub,
Subscript,
Sum,
Var,
)
# --------------------------------------------------------------------------------------
# Typst
# --------------------------------------------------------------------------------------
BIG_OPS = (Integral, Sum, Prod, Lim, Deriv)
def level(n: Node) -> int:
"""Binding strength of a node in Typst output (higher binds tighter)."""
if isinstance(n, Rel):
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, Subscript, Frac, Sqrt, Func, Abs, Factorial
def group(n: Node) -> str:
"""Typst needs parens around non-atomic sub/superscripts (they are not displayed)."""
s = to_typst(n)
return s if isinstance(n, (Var, Num)) else f"({s})"
def paren(n: Node, cond: bool) -> str:
s = to_typst(n)
return f"({s})" if cond else s
def base_str(n: Node) -> str:
"""Base of a power / factorial: parens are visible here, so only add them when needed."""
atomic = isinstance(n, (Var, Num, Subscript, Func, Abs, Sqrt))
return paren(n, not atomic)
def bounds(lo: Node | None, hi: Node | None) -> str:
if lo is None:
return ""
return f"_{group(lo)}^{group(hi)}"
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 Pow(b, e):
return f"{base_str(b)}^{group(e)}"
case Subscript(b, s):
return f"{base_str(b)}_{group(s)}"
case Frac(a, b):
return f"frac({to_typst(a)}, {to_typst(b)})"
case Sqrt(a, None):
return f"sqrt({to_typst(a)})"
case Sqrt(a, k):
return f"root({to_typst(k)}, {to_typst(a)})"
case Func(name, a):
return f"{name}({to_typst(a)})"
case Abs(a):
return f"abs({to_typst(a)})"
case Factorial(a):
return f"{base_str(a)}!"
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 " "
return f"{left}{sep}{right}"
case Add(a, b):
return f"{paren(a, level(a) == 0)} + {paren(b, level(b) <= 1 or isinstance(b, Neg))}"
case Sub(a, b):
return f"{paren(a, level(a) == 0)} - {paren(b, level(b) <= 1 or isinstance(b, Neg))}"
case Integral(body, v, lo, hi):
return f"integral{bounds(lo, hi)} {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 Prod(body, v, lo, hi):
return f"product_({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 Deriv(body, v):
return f"frac(dif, dif {v}) {paren(body, level(body) < 9)}"
case Rel(a, op, b):
return f"{to_typst(a)} {op} {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 = {2: "second", 3: "third", 4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh",
8: "eighth", 9: "ninth", 10: "tenth", 11: "eleventh", 12: "twelfth", 20: "twentieth"}
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 < 1000:
h, r = divmod(v, 100)
return f"{ONES[h]} hundred" + ("" if r == 0 else f" {number_words(r)}")
return str(v)
def is_simple(n: Node) -> bool:
"""Something you can say without needing a 'the quantity' wrapper."""
return isinstance(n, (Var, Num, Subscript, Func, Abs, Sqrt, Factorial)) or (
isinstance(n, Pow) and isinstance(n.base, (Var, Num, Subscript)) and isinstance(n.exp, (Var, Num))
)
class English:
"""Randomised English renderer. Conventions keep generated sentences unambiguous enough:
* "B to the E" swallows everything that follows into the exponent (Appendix A, Q1), so a
power whose exponent is complex is only spoken that way when nothing follows it.
* Non-trivial operands are wrapped as "(...)" / "open paren ... close paren" /
"the quantity ..., " so the grouping is recoverable.
"""
def __init__(self, rng: random.Random, symbolic: float = 0.12):
self.rng = rng
self.symbolic = symbolic # probability of typed-style symbols ("x^2", "x/2", "+")
def c(self, *opts: str) -> str:
return self.rng.choice(opts)
def p(self, prob: float) -> bool:
return self.rng.random() < prob
# -- helpers --------------------------------------------------------------------
def num(self, v: int) -> str:
return number_words(v) if (v <= 100 and self.p(0.35)) else str(v)
def wrap(self, n: Node, tail: bool) -> str:
"""English for n, wrapped so a listener knows where it ends. tail=True means nothing
follows it inside the parent, so a bare 'the quantity ...' is safe."""
s = self.say(n, tail=tail)
if is_simple(n):
return s
opts = [f"({s})", f"open paren {s} close paren", f"open parenthesis {s} close parenthesis"]
opts.append(f"the quantity {s}" if tail else self.c(f"the quantity {s},", f"the quantity {s}"))
return self.rng.choice(opts)
def dvar(self, v: str) -> str:
return self.c(f"d{v}", f"d{v}", f"d {v}", f"d {v}", f"with respect to {v}", f"dee {v}")
# -- main -----------------------------------------------------------------------
def say(self, n: Node, tail: bool = True) -> str:
if self.symbolic and self.p(0.03):
sym = symbolic_text(n)
if sym is not None:
return sym
return self._say(n, tail)
def _say(self, n: Node, tail: bool) -> str:
r = self.rng
match n:
case Var("infinity"):
return self.c("infinity", "infinity", "infinity", "inf")
case Var("pi"):
return "pi"
case Var(name):
return name
case Num(v):
return self.num(v)
case Neg(a):
inner = self.say(a, tail) if is_simple(a) or isinstance(a, (Pow, Mul, Frac)) else self.wrap(a, tail)
return f"{self.c('minus', 'negative', 'minus', 'negative')} {inner}"
case Pow(b, e):
if isinstance(b, Func) and e in (Num(2), Num(3)) and b.name in ("sin", "cos", "tan") and self.p(0.5):
word = {"sin": "sin", "cos": "cos", "tan": "tan"}[b.name]
word = self.c(word, {"sin": "sine", "cos": "cosine", "tan": "tangent"}[b.name])
pw = "squared" if e == Num(2) else "cubed"
arg = self.say(b.arg) if is_simple(b.arg) else self.wrap(b.arg, tail)
return self.c(f"{word} {pw} {arg}", f"{word} {pw} of {arg}")
if e in (Num(2), Num(3)) and self.p(0.12):
pw = "squared" if e == Num(2) else "cubed"
if not is_simple(b) and level(b) <= 4:
return f"{self.say(b, False)} all {pw}"
sq = "square" if e == Num(2) else "cube"
return f"the {sq} of {self.wrap(b, tail)}"
base = self.wrap(b, tail=False)
if isinstance(b, (Sqrt, Func, Abs, Factorial)): # "sqrt of x cubed" would be ambiguous
inner = self.say(b, False)
base = self.c(f"({inner})", f"open paren {inner} close paren", f"the quantity {inner},")
if self.symbolic and isinstance(b, (Var, Num)) and isinstance(e, (Var, Num)) and self.p(self.symbolic):
return f"{to_typst(b)}^{to_typst(e)}"
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", f"{base} to the power of two", f"{base} to the 2")
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", f"{base} to the power of three")
if isinstance(e, Num) and e.value in ORDINALS:
return self.c(f"{base} to the {ORDINALS[e.value]}", f"{base} to the {ORDINALS[e.value]} power",
f"{base} to the power of {self.num(e.value)}", f"{base} to the {self.num(e.value)}")
if isinstance(e, Var) and len(e.name) == 1:
return self.c(f"{base} to the {e.name}", f"{base} to the power of {e.name}",
f"{base} to the {e.name}th", f"{base} to the {e.name}th power",
f"{base} raised to the {e.name}")
if is_simple(e):
return self.c(f"{base} to the {self.say(e)}", f"{base} to the power of {self.say(e)}",
f"{base} raised to the {self.say(e)}")
# complex exponent: only say it bare when nothing follows (convention)
if tail and self.p(0.6):
ex = self.say(e, tail=True)
return self.c(f"{base} to the {ex}", f"{base} to the power of {ex}", f"{base} raised to the {ex}")
ex = self.say(e, tail=True)
return self.c(f"{base} to the power of ({ex})", f"{base} to the ({ex})",
f"{base} raised to the quantity {ex}, end exponent" if not tail else f"{base} raised to the quantity {ex}",
f"{base} to the open paren {ex} close paren")
case Subscript(b, s):
base = self.say(b)
sub = self.say(s)
if isinstance(s, (Num, Var)) and self.p(0.15):
return f"{base}_{to_typst(s)}"
return self.c(f"{base} sub {sub}", f"{base} sub {sub}", f"{base} subscript {sub}",
f"{base} {sub}" if isinstance(s, Num) else f"{base} sub {sub}")
case Frac(a, b):
if self.symbolic and isinstance(a, (Var, Num)) and isinstance(b, (Var, Num)) and self.p(self.symbolic):
return f"{to_typst(a)}/{to_typst(b)}"
if b == Num(2) and is_simple(a) and self.p(0.2):
if a == Num(1):
return self.c("one half", "a half", "half")
return self.c(f"half of {self.say(a)}", f"half {self.say(a)}", f"{self.say(a)} over two")
if a == Num(1) and isinstance(b, Num) and b.value in ORDINALS and b.value > 2 and self.p(0.3):
return self.c(f"one {ORDINALS[b.value]}", f"a {ORDINALS[b.value]}")
if isinstance(a, Num) and isinstance(b, Num) and 1 < a.value < 10 and b.value in ORDINALS and b.value > 2 and self.p(0.3):
return f"{number_words(a.value)} {ORDINALS[b.value]}s"
if not is_simple(a) and level(a) <= 4 and self.p(0.15):
return f"{self.say(a, False)} all over {self.wrap(b, tail)}"
num = self.wrap(a, tail=False)
den = self.wrap(b, tail=tail)
opts = [f"{num} over {den}", f"{num} over {den}", f"{num} divided by {den}",
f"the fraction {num} over {den}"]
if not (is_simple(a) and is_simple(b)):
opts.append(f"the fraction with numerator {self.say(a, False)} and denominator {self.say(b, tail)}"
+ ("" if tail else ","))
opts.append(f"the fraction {self.say(a, False)} over {self.say(b, tail)}" + ("" if tail else ", end fraction"))
return r.choice(opts)
case Sqrt(a, None):
if tail and not is_simple(a) and self.p(0.4):
return f"{self.c('the square root of', 'square root of', 'sqrt of')} {self.say(a, True)}"
if not tail and is_simple(a):
sa = self.say(a)
return self.c(f"root {sa}", f"sqrt {sa}", f"the square root of {sa},", f"square root {sa}")
arg = self.wrap(a, tail) if not is_simple(a) else self.say(a)
return self.c(f"the square root of {arg}", f"square root of {arg}", f"root {arg}",
f"sqrt of {arg}", f"sqrt {arg}", f"the root of {arg}")
case Sqrt(a, k):
arg = self.wrap(a, tail) if not is_simple(a) else self.say(a)
if k == Num(3):
return self.c(f"the cube root of {arg}", f"cube root of {arg}", f"the third root of {arg}")
if isinstance(k, Num) and k.value in ORDINALS:
return self.c(f"the {ORDINALS[k.value]} root of {arg}", f"{ORDINALS[k.value]} root of {arg}")
ks = self.say(k)
return self.c(f"the {ks}th root of {arg}", f"the {ks}-th root of {arg}", f"{ks}th root of {arg}",
f"the root of index {ks} of {arg}")
case Func(name, a):
simple = is_simple(a) and not isinstance(a, Func)
arg = self.say(a) if simple else self.wrap(a, tail)
names = {
"sin": ["sine", "sin", "the sine"], "cos": ["cosine", "cos", "the cosine"],
"tan": ["tangent", "tan", "the tangent"],
"ln": ["ln", "the natural log", "natural log", "the natural logarithm", "log natural"],
"log": ["log", "the log", "the logarithm", "logarithm"],
"exp": ["exp", "the exponential", "exponential"],
"f": ["f"], "g": ["g"],
}[name]
if name in ("f", "g"):
return self.c(f"{name} of {arg}", f"{name} of {arg}", f"{name}({self.say(a)})" if simple else f"{name} of {arg}")
word = r.choice(names[:4] if name == "ln" else names)
if simple and word in ("sin", "cos", "tan", "ln", "log", "exp") and self.p(0.5):
return f"{word} {arg}"
return f"{word} of {arg}"
case Abs(a):
if tail and not is_simple(a) and self.p(0.4):
return f"{self.c('the absolute value of', 'absolute value of', 'abs of')} {self.say(a, True)}"
return self.c(f"the absolute value of {self.wrap(a, tail)}", f"absolute value of {self.wrap(a, tail)}",
f"abs of {self.wrap(a, tail)}", f"the modulus of {self.wrap(a, tail)}",
f"|{self.say(a)}|" if is_simple(a) else f"the absolute value of {self.wrap(a, tail)}")
case Factorial(a):
return f"{self.wrap(a, tail=False)} factorial" if not is_simple(a) else self.c(
f"{self.say(a)} factorial", f"{self.say(a)} factorial", f"{self.say(a)}!")
case Mul(a, b):
left = self.wrap(a, tail=False) if level(a) < 4 and not is_simple(a) else self.say(a, tail=False)
right = self.wrap(b, tail=tail) if (level(b) <= 3 and not isinstance(b, BIG_OPS)) else self.say(b, tail)
if isinstance(a, Num) and isinstance(b, (Var, Pow, Func, Sqrt, Subscript)) and self.p(0.5):
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}"
if isinstance(a, Var) and isinstance(b, Var) and self.p(0.3):
return f"{left} {right}"
return self.c(f"{left} times {right}", f"{left} times {right}", f"{left} multiplied by {right}",
f"{left} * {right}" if self.p(self.symbolic * 2) else f"{left} times {right}",
f"the product of {self.say(a, False)} and {self.say(b, tail)}" if is_simple(a) else f"{left} times {right}")
case Add(a, b) | Sub(a, b):
plus = isinstance(n, Add)
left = self.say(a, tail=False) if level(a) > 0 else self.wrap(a, False)
needs = level(b) <= 1 or isinstance(b, Neg)
right = self.wrap(b, tail) if needs else self.say(b, tail)
if plus:
op = "+" if self.p(self.symbolic) else self.c("plus", "plus", "plus", "add")
if op == "add":
if is_simple(a):
return f"{left} plus {right}"
op = "plus"
if self.p(0.04) and is_simple(a) and is_simple(b):
return f"the sum of {left} and {right}"
else:
op = "-" if self.p(self.symbolic) else "minus"
if self.p(0.04) and is_simple(a) and is_simple(b):
return f"the difference of {left} and {right}"
return f"{left} {op} {right}"
case Integral(body, v, lo, hi):
b = self.say(body, tail=self.p(0.5)) # "dx" closes the body, so a bare tail form is fine
if level(body) <= 1 and self.p(0.4):
b = self.wrap(body, tail=False)
d = self.dvar(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}", f"integrate {b} {d}",
f"the antiderivative of {b} {d}")
l, h = self.say(lo, False), self.say(hi, False)
return self.c(
f"the integral from {l} to {h} of {b} {d}",
f"the integral from {l} to {h} of {b} {d}",
f"integral from {l} to {h} of {b} {d}",
f"integral {l} to {h} {b} {d}",
f"the definite integral from {l} to {h} of {b} {d}",
f"integrate {b} from {l} to {h} with respect to {v}",
f"the integral of {b} from {l} to {h} {d}",
f"integral of {b} {d} from {l} to {h}",
f"the integral from {v} equals {l} to {h} of {b} {d}",
)
case Sum(body, v, lo, hi) | Prod(body, v, lo, hi):
is_sum = isinstance(n, Sum)
b = self.say(body, tail=tail)
if level(body) <= 1 and not (tail and self.p(0.4)):
b = self.wrap(body, tail=tail)
l, h = self.say(lo, False), self.say(hi, False)
eq = self.c("equals", "equals", "=", "equal to", "from")
w = self.c("sum", "summation", "sum", "sigma") if is_sum else self.c("product", "product", "pi product")
return self.c(
f"the {w} from {v} {eq} {l} to {h} of {b}",
f"the {w} from {v} {eq} {l} to {h} of {b}",
f"{w} from {v} {eq} {l} to {h} of {b}",
f"{w} {v} {eq} {l} to {h} {b}",
f"the {w} over {v} from {l} to {h} of {b}",
f"the {w} of {b} for {v} from {l} to {h}" if tail else f"the {w} from {v} {eq} {l} to {h} of {b}",
)
case Lim(body, v, to):
b = self.say(body, tail=tail)
if level(body) <= 1 and not (tail and self.p(0.4)):
b = self.wrap(body, tail=tail)
t = self.say(to, False)
verb = self.c("approaches", "goes to", "tends to", "tends toward", "->", "to", "approaching")
return self.c(
f"the limit as {v} {verb} {t} of {b}",
f"the limit as {v} {verb} {t} of {b}",
f"limit as {v} {verb} {t} of {b}",
f"lim {v} {verb} {t} of {b}",
f"lim {v} -> {t} {b}",
f"the limit of {b} as {v} {verb} {t}" if tail else f"the limit as {v} {verb} {t} of {b}",
)
case Deriv(body, v):
b = self.say(body, tail) if is_simple(body) else self.wrap(body, tail)
return self.c(
f"the derivative of {b} with respect to {v}" if tail else f"the derivative with respect to {v} of {b}",
f"the derivative with respect to {v} of {b}",
f"d by d{v} of {b}", f"d/d{v} of {b}", f"d d{v} of {b}", f"d over d{v} of {b}",
f"differentiate {b} with respect to {v}" if tail else f"d/d{v} {b}",
)
case Rel(a, op, b):
left, right = self.say(a, False), self.say(b, True)
words = {
"=": ["equals", "equals", "is equal to", "=", "is"],
"!=": ["is not equal to", "does not equal", "!=", "is not"],
"<": ["is less than", "<", "less than", "is smaller than"],
">": ["is greater than", ">", "greater than", "is bigger than", "is more than"],
"<=": ["is less than or equal to", "<=", "is at most", "less than or equal to"],
">=": ["is greater than or equal to", ">=", "is at least", "greater than or equal to"],
}[op]
return f"{left} {r.choice(words)} {right}"
raise NotImplementedError(n)
def symbolic_text(n: Node) -> str | None:
"""How someone might type a small expression: 'e^(-x^2)', 'x^2 + 1', '1/x'. None if too big."""
match n:
case Var(name) if len(name) == 1:
return name
case Num(v):
return str(v)
case Neg(a):
s = symbolic_text(a)
return None if s is None or isinstance(a, (Add, Sub)) else f"-{s}"
case Pow(b, e):
sb, se = symbolic_text(b), symbolic_text(e)
if sb is None or se is None or not isinstance(b, (Var, Num)):
return None
return f"{sb}^{se}" if isinstance(e, (Var, Num)) else f"{sb}^({se})"
case Frac(a, b) if isinstance(a, (Var, Num)) and isinstance(b, (Var, Num)):
return f"{to_typst(a)}/{to_typst(b)}"
case Add(a, b) | Sub(a, b):
sa, sb = symbolic_text(a), symbolic_text(b)
if sa is None or sb is None or isinstance(b, (Add, Sub, Neg)):
return None
return f"{sa} {'+' if isinstance(n, Add) else '-'} {sb}"
case Mul(Num(v), Var(name)) if len(name) == 1:
return f"{v}{name}"
return None
PREFIXES = ["", "", "", "", "", "", "write ", "what is ", "typeset ", "please write ", "give me ",
"how do i write ", "convert ", "translate "]
SUFFIXES = ["", "", "", "", "", "", ".", "?", " please", " in typst"]
def add_noise(s: str, rng: random.Random) -> str:
"""Surface noise: optional 'the', casing, prefixes, the odd typo."""
if rng.random() < 0.3:
s = re.sub(r"\bthe ", lambda m: "" if rng.random() < 0.5 else m.group(0), s)
if rng.random() < 0.15:
s = rng.choice(PREFIXES) + s + rng.choice(SUFFIXES)
if rng.random() < 0.06: # typo: swap two letters, drop one, or double one, in a longer word
words = s.split(" ")
cand = [i for i, w in enumerate(words) if len(w) >= 5 and w.isalpha()]
if cand:
i = rng.choice(cand)
w = words[i]
j = rng.randrange(1, len(w) - 1)
kind = rng.randrange(3)
if kind == 0:
w = w[:j] + w[j + 1] + w[j] + w[j + 2:]
elif kind == 1:
w = w[:j] + w[j + 1:]
else:
w = w[:j] + w[j] + w[j:]
words[i] = w
s = " ".join(words)
roll = rng.random()
if roll < 0.15:
s = s[:1].upper() + s[1:]
elif roll < 0.18:
s = s.upper()
return re.sub(r"\s+", " ", s).strip()
def to_english(n: Node, rng: random.Random, noise: bool = True) -> str:
s = English(rng).say(n, tail=True)
s = re.sub(r"\s+", " ", s).strip().rstrip(",")
s = s.replace(", ,", ",").replace(",,", ",")
return add_noise(s, rng) if noise else s
+59
View File
@@ -0,0 +1,59 @@
"""Byte-level BPE tokenizer shared by English and Typst.
uv run isotope-tokenizer # trains artifacts/tokenizer.json from data/train.jsonl
"""
from __future__ import annotations
import argparse
import json
import pathlib
import tempfile
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers
SPECIALS = ["[PAD]", "[UNK]", "[BOS]", "[EOS]"] # ids 0, 1, 2, 3
PAD, UNK, BOS, EOS = 0, 1, 2, 3
def train(files: list[str], 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(files, trainer) # files: plain-text dumps of the en and typ columns
pathlib.Path(out).parent.mkdir(parents=True, exist_ok=True)
tok.save(out)
return tok
def load(path: str = "artifacts/tokenizer.json") -> Tokenizer:
return Tokenizer.from_file(path)
def train_from_jsonl(jsonl: str = "data/train.jsonl", out: str = "artifacts/tokenizer.json", vocab: int = 4000) -> Tokenizer:
with tempfile.TemporaryDirectory() as d:
en, typ = pathlib.Path(d) / "en.txt", pathlib.Path(d) / "typ.txt"
with open(jsonl) as f, en.open("w") as fe, typ.open("w") as ft:
for line in f:
row = json.loads(line)
fe.write(row["en"] + "\n")
ft.write(row["typ"] + "\n")
return train([str(en), str(typ)], out, vocab)
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_from_jsonl(args.data, args.out, args.vocab)
print(f"trained tokenizer with {tok.get_vocab_size()} tokens -> {args.out}")
ex = "integral_0^infinity e^(-x^2) dif x"
print("example:", tok.encode(ex).tokens)
if __name__ == "__main__":
main()
+226
View File
@@ -0,0 +1,226 @@
"""Training loop (teacher forcing, AdamW, warmup + cosine, label smoothing).
uv run isotope-train # small model, defaults
uv run isotope-train --config tiny --steps 2000
uv run isotope-train --overfit 100 # milestone M2 sanity check: memorise 100 pairs
uv run isotope-train --custom-attn # use the hand-written MultiHeadAttention
"""
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
def read_pairs(path: str, limit: int | None = None) -> list[tuple[str, str]]:
out = []
with open(path) as f:
for line in f:
row = json.loads(line)
out.append((row["en"], row["typ"]))
if limit and len(out) >= limit:
break
return out
def encode_pairs(tok, pairs, max_len):
srcs = [e.ids[:max_len] for e in tok.encode_batch([p[0] for p in pairs])]
tgts = [[BOS] + e.ids[: max_len - 2] + [EOS] for e in tok.encode_batch([p[1] for p in pairs])]
return list(zip(srcs, tgts))
def pad(seqs: list[list[int]]) -> torch.Tensor:
L = max(len(s) for s in seqs)
t = torch.full((len(seqs), L), PAD, dtype=torch.long)
for i, s in enumerate(seqs):
t[i, : len(s)] = torch.tensor(s, dtype=torch.long)
return t
def batches(data, batch_size: int, rng: random.Random, bucket: int = 50):
"""Infinite iterator; sorts by length inside large buckets so batches have little padding."""
while True:
idx = list(range(len(data)))
rng.shuffle(idx)
chunk = batch_size * bucket
bl = []
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]))
bl += [part[j: j + batch_size] for j in range(0, len(part), batch_size)]
rng.shuffle(bl)
for b in bl:
yield pad([data[i][0] for i in b]), pad([data[i][1] for i in b])
def lr_lambda(warmup: int, total: int, floor: float = 0.05):
def f(step: int) -> float:
if step < warmup:
return (step + 1) / warmup
prog = min(1.0, (step - warmup) / max(1, total - warmup))
return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * prog))
return f
def loss_fn(model, src, tgt, V, smoothing=0.1):
tgt_in, tgt_out = tgt[:, :-1], tgt[:, 1:] # teacher-forcing shift
logits = model(src, tgt_in)
return F.cross_entropy(logits.reshape(-1, V), tgt_out.reshape(-1), ignore_index=PAD, label_smoothing=smoothing)
@torch.no_grad()
def val_loss(model, data, V, dev, batch_size=256):
model.eval()
tot, n = 0.0, 0
for i in range(0, len(data), batch_size):
part = data[i: i + batch_size]
src, tgt = pad([p[0] for p in part]).to(dev), pad([p[1] for p in part]).to(dev)
tot += loss_fn(model, src, tgt, V, smoothing=0.0).item() * len(part)
n += len(part)
model.train()
return tot / max(n, 1)
def save(path, model, model_args, extra):
pathlib.Path(path).parent.mkdir(parents=True, exist_ok=True)
torch.save({"model": model.state_dict(), "model_args": model_args, **extra}, path)
def overfit(args, tok, dev):
"""Milestone M2: a tiny model must memorise 100 pairs exactly, or the pipeline has a bug."""
pairs = read_pairs(f"{args.data}/train.jsonl", args.overfit)
data = encode_pairs(tok, pairs, 256)
V = tok.get_vocab_size()
torch.manual_seed(0)
model_args = dict(vocab=V, **CONFIGS["tiny"], max_len=256, drop=0.0, custom_attn=args.custom_attn)
model = Seq2Seq(**model_args).to(dev)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
src, tgt = pad([d[0] for d in data]).to(dev), pad([d[1] for d in data]).to(dev)
for step in range(1, 3001):
model.train()
loss = loss_fn(model, src, tgt, V, smoothing=0.0)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if step % 100 == 0:
preds = translate_batch(model, tok, [p[0] for p in pairs], constrained=False)
exact = sum(p == t for p, (_, t) in zip(preds, pairs))
print(f"step {step:5d} loss {loss.item():.4f} exact {exact}/{len(pairs)}")
if exact == len(pairs):
print(f"PASS: memorised all {len(pairs)} pairs.")
return True
print("FAIL: could not memorise the pairs -- check shift / mask / special tokens.")
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("--custom-attn", action="store_true", help="use the hand-written attention")
ap.add_argument("--overfit", type=int, default=0, help="only run the memorise-N-pairs check")
ap.add_argument("--device", default=None)
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(args, tok, dev) else 1)
torch.manual_seed(args.seed)
rng = random.Random(args.seed)
max_len = 256
print("tokenizing data ...")
train_pairs = read_pairs(f"{args.data}/train.jsonl")
valid_pairs = read_pairs(f"{args.data}/valid.jsonl")[:2000]
train = encode_pairs(tok, train_pairs, max_len)
valid = encode_pairs(tok, valid_pairs, max_len)
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, custom_attn=args.custom_attn)
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, lr_lambda(args.warmup, args.steps))
out = pathlib.Path(args.out)
out.mkdir(parents=True, exist_ok=True)
log_f = (out / "train_log.csv").open("w", newline="")
log = csv.writer(log_f)
log.writerow(["step", "lr", "train_loss", "val_loss", "sample_exact", "elapsed_s"])
sample = valid_pairs[:20]
best = float("inf")
t0 = time.time()
run_loss, run_n = 0.0, 0
model.train()
it = batches(train, args.batch, rng)
try:
for step in range(1, args.steps + 1):
src, tgt = next(it)
src, tgt = src.to(dev), tgt.to(dev)
loss = loss_fn(model, src, tgt, V)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
sched.step()
run_loss += loss.item() if step % 10 == 0 else 0.0
run_n += step % 10 == 0
if step % 100 == 0:
el = time.time() - t0
eta = el / step * (args.steps - step)
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 eta {eta / 60:.1f} min", flush=True)
if step % args.eval_every == 0 or step == args.steps:
vl = val_loss(model, valid, V, dev)
preds = translate_batch(model, tok, [p[0] for p in sample])
exact = sum(p == t for p, (_, t) in zip(preds, sample))
print(f"--- step {step}: val loss {vl:.4f}, sample exact {exact}/{len(sample)}")
for (en, typ), p in list(zip(sample, 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_f.flush()
run_loss, run_n = 0.0, 0
extra = {"step": step, "val_loss": vl, "config": args.config}
save(out / "last.pt", model, model_args, extra)
if vl < best:
best = vl
save(out / "model.pt", model, model_args, extra)
model.train()
except KeyboardInterrupt:
print("\ninterrupted -- saving checkpoint")
save(out / "last.pt", model, model_args, {"step": step, "config": args.config})
if not (out / "model.pt").exists():
save(out / "model.pt", model, model_args, {"step": step, "config": args.config})
log_f.close()
print(f"done. best val loss {best:.4f}. checkpoint: {out / 'model.pt'}")
if __name__ == "__main__":
main()
+293
View File
@@ -0,0 +1,293 @@
"""Inference: English -> Typst, 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
uv run isotope --beam 4 --check "x squared plus y squared equals r squared"
"""
from __future__ import annotations
import argparse
import pathlib
import sys
import time
import torch
from .model import Seq2Seq, pick_device
from .tokenizer import BOS, EOS, PAD, load
DEFAULT_CKPT = "artifacts/model.pt"
DEFAULT_TOK = "artifacts/tokenizer.json"
# --------------------------------------------------------------------------------------
# loading
# --------------------------------------------------------------------------------------
def find_root() -> pathlib.Path:
"""Run from anywhere inside the project: find the folder that holds artifacts/."""
here = pathlib.Path.cwd()
for p in [here, *here.parents, pathlib.Path(__file__).resolve().parents[2]]:
if (p / DEFAULT_CKPT).exists():
return p
return here
def load_model(ckpt: str | None = None, tok_path: str | None = None, device: str | None = None):
root = find_root()
ckpt_p = pathlib.Path(ckpt) if ckpt else root / DEFAULT_CKPT
tok_p = pathlib.Path(tok_path) if tok_path else root / DEFAULT_TOK
if not ckpt_p.exists():
raise SystemExit(f"No trained model at {ckpt_p}. Train one first with: ./run.sh")
dev = device or pick_device()
state = torch.load(ckpt_p, map_location="cpu", weights_only=False)
model = Seq2Seq(**state["model_args"])
model.load_state_dict(state["model"])
model.to(dev).eval()
return model, load(str(tok_p)), dev
# --------------------------------------------------------------------------------------
# constrained decoding: never close a paren that is not open; never stop with one open
# --------------------------------------------------------------------------------------
class ParenConstraint:
def __init__(self, tok, device):
V = tok.get_vocab_size()
delta, minpref, banned = [], [], []
for i in range(V):
s = tok.decode([i], skip_special_tokens=False) if i > 3 else ""
b, m = 0, 0
for ch in s:
b += (ch == "(") - (ch == ")")
m = min(m, b)
delta.append(b)
minpref.append(m)
banned.append("$" in s or "\n" in s or i in (PAD, BOS, 1))
self.delta = torch.tensor(delta, device=device)
self.minpref = torch.tensor(minpref, device=device)
self.banned = torch.tensor(banned, device=device)
def mask(self, balance: torch.Tensor) -> torch.Tensor:
"""balance: (B,) open-paren count so far -> (B, V) bool, True = forbidden."""
bad = (balance[:, None] + self.minpref[None, :]) < 0
bad |= self.banned[None, :]
bad[:, EOS] |= balance > 0
return bad
_constraints: dict[int, ParenConstraint] = {}
def _constraint(tok, device) -> ParenConstraint:
key = id(tok)
if key not in _constraints:
_constraints[key] = ParenConstraint(tok, device)
return _constraints[key]
# --------------------------------------------------------------------------------------
# decoding
# --------------------------------------------------------------------------------------
def _encode_src(tok, texts: list[str], max_len: int, device):
ids = [tok.encode(t).ids[: max_len] for t in texts]
L = max(len(x) for x in ids)
src = torch.full((len(ids), L), PAD, dtype=torch.long)
for i, x in enumerate(ids):
src[i, : len(x)] = torch.tensor(x, dtype=torch.long)
return src.to(device)
@torch.no_grad()
def translate_batch(model, tok, texts: list[str], max_len: int = 128, constrained: bool = True) -> list[str]:
"""Greedy decoding for a batch of sentences."""
model.eval()
dev = next(model.parameters()).device
src = _encode_src(tok, texts, model.max_len, dev)
memory = model.encode(src)
src_pad = src == PAD
B = len(texts)
out = torch.full((B, 1), BOS, dtype=torch.long, device=dev)
done = torch.zeros(B, dtype=torch.bool, device=dev)
balance = torch.zeros(B, dtype=torch.long, device=dev)
pc = _constraint(tok, dev) if constrained else None
for _ in range(min(max_len, model.max_len - 1)):
logits = model.decode(out, memory, src_pad)[:, -1].float()
if pc is not None:
logits = logits.masked_fill(pc.mask(balance), float("-inf"))
nxt = logits.argmax(-1)
nxt = torch.where(done, torch.full_like(nxt, PAD), nxt)
if pc is not None:
balance = balance + torch.where(done, 0, pc.delta[nxt])
out = torch.cat([out, nxt[:, None]], 1)
done |= nxt == EOS
if bool(done.all()):
break
res = []
for row in out.tolist():
row = row[1:]
if EOS in row:
row = row[: row.index(EOS)]
res.append(tok.decode([t for t in row if t != PAD]).strip())
return res
@torch.no_grad()
def translate(model, tok, text: str, max_len: int = 128, beam: int = 1, constrained: bool = True) -> str:
"""Greedy (beam=1) or beam-search translation of one sentence. Returns Typst without $...$."""
if beam <= 1:
return translate_batch(model, tok, [text], max_len, constrained)[0]
model.eval()
dev = next(model.parameters()).device
src = _encode_src(tok, [text], model.max_len, dev)
memory = model.encode(src)
pc = _constraint(tok, dev) if constrained else None
beams = [([BOS], 0.0, 0)] # (tokens, log-prob, paren balance)
finished: list[tuple[list[int], float]] = []
for _ in range(min(max_len, model.max_len - 1)):
seqs = torch.tensor([b[0] for b in beams], device=dev)
mem = memory.expand(len(beams), -1, -1)
logp = model.decode(seqs, mem)[:, -1].float().log_softmax(-1)
if pc is not None:
bal = torch.tensor([b[2] for b in beams], device=dev)
logp = logp.masked_fill(pc.mask(bal), float("-inf"))
cand = []
top = logp.topk(beam, -1)
for bi, (toks, score, bal) in enumerate(beams):
for lp, t in zip(top.values[bi].tolist(), top.indices[bi].tolist()):
if lp == float("-inf"):
continue
nb = bal + (int(pc.delta[t]) if pc is not None else 0)
cand.append((toks + [t], score + lp, nb))
cand.sort(key=lambda c: -c[1])
beams = []
for toks, score, bal in cand:
if toks[-1] == EOS:
finished.append((toks, score / (len(toks) - 1) ** 0.6)) # length-normalised
else:
beams.append((toks, score, bal))
if len(beams) == beam:
break
if not beams or (len(finished) >= beam and max(f[1] for f in finished) > beams[0][1] / len(beams[0][0]) ** 0.6):
break
if not finished:
finished = [(b[0], b[1]) for b in beams]
best = max(finished, key=lambda f: f[1])[0]
toks = [t for t in best[1:] if t not in (EOS, PAD)]
return tok.decode(toks).strip()
# --------------------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------------------
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("--beam", type=int, default=1, help="beam size (1 = greedy)")
ap.add_argument("--no-constrain", action="store_true", help="disable paren-balancing constrained decoding")
ap.add_argument("--check", action="store_true", help="also run `typst compile` on the output")
ap.add_argument("--raw", action="store_true", help="print without the surrounding $ ... $")
ap.add_argument("--ckpt", default=None)
ap.add_argument("--tokenizer", default=None)
args = ap.parse_args(argv)
model, tok, _ = load_model(args.ckpt, args.tokenizer)
opts = {"beam": args.beam, "constrain": not args.no_constrain, "check": args.check, "raw": args.raw, "time": False}
def run(line: str) -> None:
t0 = time.perf_counter()
typ = translate(model, tok, line, beam=opts["beam"], constrained=opts["constrain"])
dt = time.perf_counter() - t0
print(typ if opts["raw"] else f"${typ}$")
if opts["check"]:
from .validate import compiles
print(" compiles:", "yes" if compiles(typ) else "NO")
if opts["time"]:
print(f" ({dt * 1000:.0f} ms)")
if args.text:
run(" ".join(args.text))
return
if not sys.stdin.isatty():
for line in sys.stdin:
if line.strip():
run(line.strip())
return
repl(run, opts, model, tok)
REPL_HELP = """commands:
:beam N beam size (1 = greedy)
:check toggle compile-checking with typst
:raw toggle the surrounding $ ... $
:constrain toggle paren-balanced decoding
:time toggle per-query timing
:show print current settings
:help this message
:q quit (also Ctrl-D)
Up/down arrows recall history. Ctrl-C clears the line."""
def repl(run, opts: dict, model, tok) -> None:
"""Interactive loop: the model stays loaded, settings can be changed on the fly."""
try:
import readline
hist = pathlib.Path.home() / ".isotope_history"
try:
readline.read_history_file(hist)
except OSError:
pass
readline.set_history_length(1000)
import atexit
atexit.register(lambda: _save_history(readline, hist))
except ImportError:
pass
translate(model, tok, "x") # warm-up so the first real query is fast (MPS/CUDA kernel compile)
print("isotope: model loaded. Type English math, get Typst. :help for commands, Ctrl-D to exit.")
toggles = {"check", "raw", "constrain", "time"}
while True:
try:
line = input("> ").strip()
except KeyboardInterrupt:
print()
continue
except EOFError:
print()
break
if not line:
continue
if line in ("quit", "exit", "q", ":q", ":quit"):
break
if line.startswith(":"):
cmd, *rest = line[1:].split()
if cmd in toggles:
opts[cmd] = not opts[cmd]
print(f" {cmd}: {'on' if opts[cmd] else 'off'}")
elif cmd == "beam" and rest and rest[0].isdigit():
opts["beam"] = max(1, int(rest[0]))
print(f" beam: {opts['beam']}")
elif cmd == "show":
print(" " + " ".join(f"{k}={v}" for k, v in opts.items()))
else:
print(REPL_HELP)
continue
try:
run(line)
except KeyboardInterrupt:
print(" (interrupted)")
def _save_history(readline, path: pathlib.Path) -> None:
try:
readline.write_history_file(path)
except OSError:
pass
if __name__ == "__main__":
main()
+95
View File
@@ -0,0 +1,95 @@
"""Check Typst math with the real `typst` CLI.
compiles(math) -> bool, one equation (simple version from the guide)
compiles_many(maths) -> list[bool], batches many equations per file and bisects on failure
render_many(maths) -> list[bytes | None], a PNG per equation (None if it does not compile)
"""
from __future__ import annotations
import pathlib
import shutil
import subprocess
import tempfile
from concurrent.futures import ThreadPoolExecutor
PAGE = "#set page(width: auto, height: auto, margin: 4pt)\n"
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 _ok_math(math: str) -> bool:
# A stray `$` would end the math block early and let arbitrary markup through.
return "$" not in math and "\n" not in math and math.strip() != ""
def compiles(math: str) -> bool:
if not _ok_math(math):
return False
with tempfile.TemporaryDirectory() as d:
src = pathlib.Path(d) / "t.typ"
src.write_text(f"${math}$\n")
r = subprocess.run([_typst(), "compile", str(src)], capture_output=True)
return r.returncode == 0
def _batch_ok(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))
r = subprocess.run([_typst(), "compile", str(src)], capture_output=True)
return r.returncode == 0
def _check(maths: list[str]) -> list[bool]:
if not maths:
return []
if _batch_ok(maths):
return [True] * len(maths)
if len(maths) == 1:
return [False]
mid = len(maths) // 2
return _check(maths[:mid]) + _check(maths[mid:])
def compiles_many(maths: list[str], batch: int = 400, workers: int = 8) -> list[bool]:
"""Compile-check many equations quickly: batch them into files, bisect failures."""
_typst()
result = [False] * len(maths)
idx = [i for i, m in enumerate(maths) if _ok_math(m)]
chunks = [idx[i:i + batch] for i in range(0, len(idx), batch)]
with ThreadPoolExecutor(workers) as ex:
for chunk, oks in zip(chunks, ex.map(lambda c: _check([maths[i] for i in c]), chunks)):
for i, ok in zip(chunk, oks):
result[i] = ok
return result
def _render_chunk(maths: list[str]) -> list[bytes]:
with tempfile.TemporaryDirectory() as d:
dp = pathlib.Path(d)
body = "\n#pagebreak()\n".join(f"$ {m} $" for m in maths)
(dp / "t.typ").write_text(PAGE + body + "\n")
subprocess.run([_typst(), "compile", "--format", "png", "--ppi", "100", str(dp / "t.typ"),
str(dp / "p-{0p}.png")], capture_output=True, check=True)
pages = sorted(dp.glob("p-*.png"))
assert len(pages) == len(maths), (len(pages), len(maths))
return [p.read_bytes() for p in pages]
def render_many(maths: list[str], batch: int = 200, workers: int = 8) -> list[bytes | None]:
"""Render each equation (display style) to a PNG. Identical images == renders identically."""
ok = compiles_many(maths)
good = [i for i, o in enumerate(ok) if o]
out: list[bytes | None] = [None] * len(maths)
chunks = [good[i:i + batch] for i in range(0, len(good), batch)]
with ThreadPoolExecutor(workers) as ex:
for chunk, pngs in zip(chunks, ex.map(lambda c: _render_chunk([maths[i] for i in c]), chunks)):
for i, png in zip(chunk, pngs):
out[i] = png
return out
+55
View File
@@ -0,0 +1,55 @@
import torch
from torch import nn
from isotope_typst.model import CONFIGS, MultiHeadAttention, Seq2Seq, causal_mask, count_params, estimate_params
def test_custom_attention_matches_pytorch():
torch.manual_seed(0)
d, h = 64, 4
mine = MultiHeadAttention(d, h)
ref = nn.MultiheadAttention(d, h, batch_first=True)
with torch.no_grad():
W = torch.cat([mine.q.weight, mine.k.weight, mine.v.weight])
b = torch.cat([mine.q.bias, mine.k.bias, mine.v.bias])
ref.in_proj_weight.copy_(W)
ref.in_proj_bias.copy_(b)
ref.out_proj.weight.copy_(mine.o.weight)
ref.out_proj.bias.copy_(mine.o.bias)
x, mem = torch.randn(2, 7, d), torch.randn(2, 9, d)
pad = torch.zeros(2, 9, dtype=torch.bool)
pad[1, -3:] = True
cm = causal_mask(7, "cpu")
torch.testing.assert_close(mine(x, x, attn_mask=cm), ref(x, x, x, attn_mask=cm, need_weights=False)[0])
torch.testing.assert_close(mine(x, mem, key_padding_mask=pad),
ref(x, mem, mem, key_padding_mask=pad, need_weights=False)[0])
def test_causal_mask_shape():
m = causal_mask(4, "cpu")
assert m.tolist() == [[False, True, True, True], [False, False, True, True],
[False, False, False, True], [False, False, False, False]]
def test_future_tokens_do_not_change_past_logits():
torch.manual_seed(0)
for custom in (False, True):
m = Seq2Seq(50, **CONFIGS["tiny"], custom_attn=custom).eval()
src = torch.randint(4, 50, (1, 6))
a = torch.randint(4, 50, (1, 5))
b = a.clone()
b[0, -1] = (a[0, -1] + 1) % 46 + 4
la, lb = m(src, a), m(src, b)
torch.testing.assert_close(la[0, :-1], lb[0, :-1])
def test_encode_decode_equals_forward():
m = Seq2Seq(50, **CONFIGS["tiny"]).eval()
src, tgt = torch.randint(4, 50, (2, 6)), torch.randint(4, 50, (2, 5))
torch.testing.assert_close(m(src, tgt), m.decode(tgt, m.encode(src), src == 0))
def test_param_counts_match_guide():
m = Seq2Seq(4000, **CONFIGS["small"])
assert 7e6 < count_params(m) < 10e6
assert abs(estimate_params(4000, **CONFIGS["small"]) - count_params(m)) / count_params(m) < 0.1
+49
View File
@@ -0,0 +1,49 @@
import random
from isotope_typst.ast import Frac, Integral, Neg, Num, Pow, Var
from isotope_typst.generate import TreeGen, split_of
from isotope_typst.render import to_english, to_typst
from isotope_typst.validate import compiles, compiles_many
def guide_tree():
return Integral(Pow(Var("e"), Neg(Pow(Var("x"), Num(2)))), "x", Num(0), Var("infinity"))
def test_guide_example():
assert to_typst(guide_tree()) == "integral_0^infinity e^(-x^2) dif x"
def test_frac_and_parens():
assert to_typst(Frac(Num(1), Var("x"))) == "frac(1, x)"
assert to_typst(Pow(Frac(Num(1), Num(2)), Num(2))) == "(frac(1, 2))^2"
def test_english_is_random_but_typst_is_not():
rng = random.Random(0)
phrasings = {to_english(guide_tree(), rng) for _ in range(50)}
assert len(phrasings) > 10
def test_generated_typst_compiles():
gen = TreeGen(random.Random(1))
maths = [to_typst(gen.tree()) for _ in range(300)]
assert all(compiles_many(maths))
def test_basic_generator_only_uses_basic_nodes():
from isotope_typst.ast import walk
gen = TreeGen(random.Random(2), basic=True)
allowed = {"Num", "Var", "Neg", "Pow", "Frac", "Integral"}
for _ in range(300):
assert {type(n).__name__ for n in walk(gen.tree())} <= allowed
def test_compile_check_rejects_broken():
assert compiles("x^2")
assert not compiles("frac(1, ")
assert compiles_many(["x", "sqrt(", "y"]) == [True, False, True]
def test_split_is_by_structure():
assert split_of("x^2") == split_of("x^2")
+45
View File
@@ -0,0 +1,45 @@
import json
import pathlib
import random
import pytest
from isotope_typst.generate import TreeGen
from isotope_typst.render import to_english, to_typst
from isotope_typst.tokenizer import train
@pytest.fixture(scope="module")
def tok(tmp_path_factory):
d = tmp_path_factory.mktemp("tok")
gen, rng = TreeGen(random.Random(0)), random.Random(0)
lines = []
for _ in range(2000):
t = gen.tree()
lines += [to_english(t, rng), to_typst(t)]
(d / "a.txt").write_text("\n".join(lines))
return train([str(d / "a.txt")], str(d / "tok.json"), vocab=800)
def test_roundtrip_1000_typst_strings(tok):
gen = TreeGen(random.Random(123))
for _ in range(1000):
s = to_typst(gen.tree())
assert tok.decode(tok.encode(s).ids) == s
def test_roundtrip_unseen_characters(tok):
s = "x ≤ ∞ {weird} ü"
assert tok.decode(tok.encode(s).ids) == s
def test_special_ids(tok):
assert [tok.token_to_id(t) for t in ["[PAD]", "[UNK]", "[BOS]", "[EOS]"]] == [0, 1, 2, 3]
def test_hand_test_set_compiles():
from isotope_typst.validate import compiles_many
p = pathlib.Path(__file__).parents[1] / "eval/hand_test.jsonl"
rows = [json.loads(l) for l in p.read_text().splitlines() if l.strip()]
assert len(rows) >= 150
assert all(compiles_many([r["typ"] for r in rows]))
Generated
+1796
View File
File diff suppressed because it is too large. Load diff