Compare commits

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 21881 additions and 735 deletions

No files matched your search

+7 -4
View File
@@ -1,15 +1,18 @@
# Python # Python-generated files
__pycache__/ __pycache__/
*.py[oc] *.py[oc]
build/ build/
dist/ dist/
wheels/ wheels/
*.egg-info *.egg-info
.venv
# Generated by the pipeline (see README) # Virtual environments
.venv
data/ data/
artifacts/ # Generated by ./run.sh; only the tokenizer and eval summary are tracked
artifacts/*
!artifacts/tokenizer.json
!artifacts/eval.json
# Claude Code personal settings # Claude Code personal settings
.claude/settings.local.json .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"
}
}
}
}
-18
View File
@@ -1,18 +0,0 @@
# Agent instructions
## Git
- Do not add AI attribution to commits: no `Co-Authored-By:` trailers for AI tools, no "Generated with …" lines. The same goes for pull request descriptions.
- Never commit on `main`. Do all work on a branch and merge it through a pull request.
- Commit as `Paul Tal <[email protected]>`, which is set in the repo's local git config.
## Project
- `./run.sh` runs the whole pipeline (data → tokenizer → overfit check → train → evaluate); `./run.sh --quick` is a two-minute smoke run.
- `uv run pytest` and `uv run ruff check .` must pass before committing.
- `data/` and `artifacts/` are generated outputs and are not tracked.
## README
- Keep `README.md` to a short description of the project and how to run it. Do not use it as documentation: no module lists, command tables, design conventions or roadmaps.
- Document code in docstrings and comments next to the code, and track planned work in Gitea issues.
+63 -6
View File
@@ -1,13 +1,70 @@
# isotope-typst # isotope-typst
isotope-typst turns math written in plain English into [Typst](https://typst.app) markup. 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$`. It is a small encoder–decoder Transformer, built and trained from scratch in PyTorch on synthetic data. Turn spoken-English math into Typst math with a small Transformer trained from scratch.
## Running it ```
$ 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$
```
You need [uv](https://docs.astral.sh/uv/) and the Typst CLI (`brew install typst`). ## Run it
```bash ```bash
./run.sh # generate data, train, and evaluate (~20 min on an M-series Mac) ./run.sh # build everything (skips finished steps)
uv run isotope "x squared plus 1" # translate a sentence ./isotope "x squared plus y squared equals r squared"
uv run isotope # interactive prompt ./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
+156 -21
View File
@@ -2,31 +2,166 @@
{"en": "x squared plus y squared equals r squared", "typ": "x^2 + y^2 = r^2"} {"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": "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 x", "typ": "e^x"}
{"en": "e to the minus x", "typ": "e^(-x)"} {"en": "e to the negative x", "typ": "e^(-x)"}
{"en": "one over x", "typ": "frac(1, x)"} {"en": "one over x", "typ": "frac(1, x)"}
{"en": "x over 2", "typ": "frac(x, 2)"} {"en": "1 over x squared", "typ": "frac(1, x^2)"}
{"en": "the square root of 2", "typ": "sqrt(2)"} {"en": "the square root of 2", "typ": "sqrt(2)"}
{"en": "square root of x plus one", "typ": "sqrt(x) + 1"} {"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": "the square root of the quantity x plus 1", "typ": "sqrt(x + 1)"}
{"en": "sine of x", "typ": "sin(x)"} {"en": "sqrt of x squared plus y squared", "typ": "sqrt(x^2 + y^2)"}
{"en": "sin x squared", "typ": "sin(x^2)"} {"en": "sin of x", "typ": "sin(x)"}
{"en": "sine squared of x plus cosine squared of x equals 1", "typ": "sin(x)^2 + cos(x)^2 = 1"} {"en": "sine x", "typ": "sin(x)"}
{"en": "ln of x", "typ": "ln(x)"} {"en": "cos theta", "typ": "cos(theta)"}
{"en": "2 x plus 3", "typ": "2 x + 3"} {"en": "sin squared x plus cos squared x equals one", "typ": "sin(x)^2 + cos(x)^2 = 1"}
{"en": "3x squared minus 2x plus 1", "typ": "3 x^2 - 2 x + 1"} {"en": "the natural log of x", "typ": "ln(x)"}
{"en": "y equals m x plus b", "typ": "y = m x + b"} {"en": "ln of x plus one", "typ": "ln(x) + 1"}
{"en": "the integral of x squared dx", "typ": "integral x^2 dif x"} {"en": "log of 100 equals 2", "typ": "log(100) = 2"}
{"en": "the integral from 0 to 1 of x squared dx", "typ": "integral_0^1 x^2 dif x"} {"en": "the derivative of x squared with respect to x", "typ": "frac(dif, dif x) x^2"}
{"en": "integral from 0 to pi of sine of x dx", "typ": "integral_0^pi sin(x) dif x"} {"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 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": "the sum from k equals 0 to infinity of x to the k", "typ": "sum_(k = 0)^infinity x^k"}
{"en": "the limit as x approaches 0 of sine of x over x", "typ": "lim_(x -> 0) frac(sin(x), x)"} {"en": "sum of i squared for i from 1 to n", "typ": "sum_(i = 1)^n i^2"}
{"en": "the limit as n goes to infinity of 1 over n", "typ": "lim_(n -> infinity) frac(1, n)"} {"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": "minus b over 2 a", "typ": "frac(-b, 2 a)"} {"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", "typ": "x^n"}
{"en": "x cubed minus 1", "typ": "x^3 - 1"} {"en": "x to the n plus 1", "typ": "x^(n + 1)"}
{"en": "alpha plus beta", "typ": "alpha + beta"} {"en": "x to the power of n minus 1", "typ": "x^(n - 1)"}
{"en": "2 pi r", "typ": "2 pi r"} {"en": "2 to the 10", "typ": "2^10"}
{"en": "e to the i pi plus 1 equals 0", "typ": "e^(i pi) + 1 = 0"} {"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": "one half", "typ": "frac(1, 2)"}
{"en": "f equals m a", "typ": "f = m a"} {"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 "$@"
+15 -3
View File
@@ -1,7 +1,7 @@
[project] [project]
name = "isotope-typst" name = "isotope-typst"
version = "0.1.0" version = "0.1.0"
description = "Spoken-English math -> Typst math with a small Transformer trained from scratch" description = "Spoken-English math -> Typst math with a small Transformer"
readme = "README.md" readme = "README.md"
authors = [ authors = [
{ name = "Paul Tal", email = "[email protected]" } { name = "Paul Tal", email = "[email protected]" }
@@ -11,27 +11,39 @@ dependencies = [
"numpy>=2.5.5", "numpy>=2.5.5",
"tokenizers>=0.23.3", "tokenizers>=0.23.3",
"torch>=2.15.0", "torch>=2.15.0",
"tqdm>=4.70.1",
] ]
[project.scripts] [project.scripts]
isotope = "isotope_typst.translate:main"
isotope-gen = "isotope_typst.generate:main" isotope-gen = "isotope_typst.generate:main"
isotope-tokenizer = "isotope_typst.tokenizer:main" isotope-tokenizer = "isotope_typst.tokenizer:main"
isotope-train = "isotope_typst.train:main" isotope-train = "isotope_typst.train:main"
isotope-eval = "isotope_typst.evaluate:main" isotope-eval = "isotope_typst.evaluate:main"
isotope = "isotope_typst.translate:main" isotope-pipeline = "isotope_typst.pipeline:main"
isotope-pathb = "isotope_typst.pathb:main"
isotope-paraphrase = "isotope_typst.paraphrase:main"
[build-system] [build-system]
requires = ["uv_build>=0.13.9,<0.14.0"] requires = ["uv_build>=0.13.9,<0.14.0"]
build-backend = "uv_build" build-backend = "uv_build"
[dependency-groups] [dependency-groups]
byt5 = [
"accelerate>=1.16.0",
"datasets>=5.2.0",
"transformers>=5.24.1",
]
dev = [ dev = [
"pytest>=9.2.0", "pytest>=9.2.0",
"ruff>=0.17.6", "ruff>=0.17.6",
] ]
pathb = [
"mlx-lm>=0.32.2",
]
[tool.ruff] [tool.ruff]
line-length = 120 line-length = 130
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["tests"] testpaths = ["tests"]
+11 -15
View File
@@ -1,22 +1,18 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# The whole Path A pipeline: data -> tokenizer -> overfit check -> train -> evaluate. # One command to build everything: data -> tokenizer -> sanity check -> train -> evaluate.
# ./run.sh full run (200k pairs, small model, 8000 steps: ~20 min on an M-series Mac) # Steps that are already done are skipped, so re-running is cheap.
# ./run.sh --quick smoke run in ~2 min (20k pairs, tiny model, 1500 steps) # ./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 set -euo pipefail
cd "$(dirname "$0")" cd "$(dirname "$0")"
command -v typst >/dev/null || { echo "typst CLI missing: brew install typst"; exit 1; }
if [[ "${1:-}" == "--quick" ]]; then if ! command -v uv >/dev/null; then
N=20000; TRAIN=(--config tiny --steps 1500 --eval-every 500) echo "Installing uv ..."; curl -LsSf https://astral.sh/uv/install.sh | sh; export PATH="$HOME/.local/bin:$PATH"
else fi
N=200000; TRAIN=() 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 fi
uv sync -q uv sync -q
echo "== 1/5 generate data"; uv run isotope-gen -n "$N" uv run isotope-pipeline "$@"
echo "== 2/5 train tokenizer"; uv run isotope-tokenizer
echo "== 3/5 overfit 100 pairs"; uv run isotope-train --overfit 100
echo "== 4/5 train"; uv run isotope-train ${TRAIN[@]+"${TRAIN[@]}"}
echo "== 5/5 evaluate"; uv run isotope-eval
echo
echo 'Try it: uv run isotope "the integral from 0 to 1 of x squared dx"'
+1 -1
View File
@@ -1 +1 @@
"""isotope-typst: spoken-English math -> Typst math with a small Transformer (Path A).""" """isotope-typst: spoken-English math -> Typst."""
+78 -46
View File
@@ -1,4 +1,4 @@
"""Math expression trees. Every training pair is one tree rendered two ways (see render.py).""" """Math expression nodes (the AST that both renderers walk)."""
from __future__ import annotations from __future__ import annotations
@@ -9,9 +9,6 @@ class Node:
pass pass
# -- leaves --------------------------------------------------------------------------------
@dataclass(frozen=True) @dataclass(frozen=True)
class Var(Node): class Var(Node):
name: str # "x", "alpha", "pi", "e", "infinity", ... name: str # "x", "alpha", "pi", "e", "infinity", ...
@@ -22,14 +19,57 @@ class Num(Node):
value: int value: int
# -- operators -----------------------------------------------------------------------------
@dataclass(frozen=True) @dataclass(frozen=True)
class Neg(Node): class Neg(Node):
arg: 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) @dataclass(frozen=True)
class Add(Node): class Add(Node):
left: Node left: Node
@@ -42,43 +82,11 @@ class Sub(Node):
right: Node right: Node
@dataclass(frozen=True)
class Mul(Node):
left: Node
right: Node
@dataclass(frozen=True)
class Pow(Node):
base: Node
exp: Node
@dataclass(frozen=True)
class Frac(Node):
num: Node
den: Node
@dataclass(frozen=True)
class Sqrt(Node):
arg: Node
@dataclass(frozen=True)
class Func(Node):
name: str # one of FUNCS
arg: Node
# -- big operators -------------------------------------------------------------------------
@dataclass(frozen=True) @dataclass(frozen=True)
class Integral(Node): class Integral(Node):
body: Node body: Node
var: str var: str
lo: Node | None = None # both None = indefinite integral lo: Node | None = None
hi: Node | None = None hi: Node | None = None
@@ -90,6 +98,14 @@ class Sum(Node):
hi: Node hi: Node
@dataclass(frozen=True)
class Prod(Node):
body: Node
var: str
lo: Node
hi: Node
@dataclass(frozen=True) @dataclass(frozen=True)
class Lim(Node): class Lim(Node):
body: Node body: Node
@@ -97,22 +113,38 @@ class Lim(Node):
to: Node to: Node
# -- top level ----------------------------------------------------------------------------- @dataclass(frozen=True)
class Deriv(Node):
body: Node
var: str
@dataclass(frozen=True) @dataclass(frozen=True)
class Eq(Node): class Rel(Node):
"""Equation / inequality. op is one of = != < > <= >=."""
left: Node left: Node
op: str
right: Node right: Node
GREEK = ["alpha", "beta", "gamma", "delta", "theta", "lambda", "mu", "sigma", "phi", "omega"] def Eq(left: Node, right: Node) -> Rel:
FUNCS = ["sin", "cos", "tan", "ln", "log", "exp"] return Rel(left, "=", right)
BIG_OPS = (Integral, Sum, Lim)
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): def walk(n: Node):
"""Yield every node of the tree, parents before children.""" """Yield every node in the tree (pre-order)."""
yield n yield n
for v in vars(n).values(): for v in vars(n).values():
if isinstance(v, Node): if isinstance(v, Node):
+73 -27
View File
@@ -1,8 +1,7 @@
"""Evaluate: exact match and compile rate, on the synthetic test split and the hand-written set. """Evaluation ladder: exact match -> compiles -> renders identically, on synthetic + hand-written sets.
uv run isotope-eval uv run isotope-eval # synthetic test (1000 sampled) + eval/hand_test.jsonl
uv run isotope-eval --beam 4
Failures go to artifacts/errors_<set>.txt: read them, group them, fix the generator (guide §9).
""" """
from __future__ import annotations from __future__ import annotations
@@ -12,7 +11,26 @@ import json
import pathlib import pathlib
import random import random
from .validate import compiles_many 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]: def read_jsonl(path: str) -> list[dict]:
@@ -20,43 +38,71 @@ def read_jsonl(path: str) -> list[dict]:
return [json.loads(line) for line in f if line.strip()] 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: def main(argv: list[str] | None = None) -> None:
from .translate import load_model, translate_batch from .translate import load_model, translate, translate_batch
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--synthetic", default="data/test.jsonl") ap.add_argument("--synthetic", default="data/test.jsonl")
ap.add_argument("--hand", default="eval/hand_test.jsonl") ap.add_argument("--hand", default=HAND_TEST)
ap.add_argument("--n-synthetic", type=int, default=1000) ap.add_argument("--n-synthetic", type=int, default=1000)
ap.add_argument("--ckpt", default="artifacts/model.pt") ap.add_argument("--beam", type=int, default=1)
ap.add_argument("--ckpt", default=None)
ap.add_argument("--out", default="artifacts") ap.add_argument("--out", default="artifacts")
args = ap.parse_args(argv) args = ap.parse_args(argv)
model, tok = load_model(args.ckpt) model, tok, _ = load_model(args.ckpt)
sets = {}
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(): if pathlib.Path(args.synthetic).exists():
rows = read_jsonl(args.synthetic) rows = read_jsonl(args.synthetic)
random.Random(0).shuffle(rows) random.Random(0).shuffle(rows)
sets["synthetic"] = rows[: args.n_synthetic] sets["synthetic test"] = rows[: args.n_synthetic]
if pathlib.Path(args.hand).exists(): if pathlib.Path(args.hand).exists():
sets["hand"] = read_jsonl(args.hand) sets["hand-written test"] = read_jsonl(args.hand)
print(f"{'set':<12}{'n':>6}{'exact':>9}{'compiles':>10}") results, out = {}, pathlib.Path(args.out)
out.mkdir(exist_ok=True)
for name, rows in sets.items(): for name, rows in sets.items():
preds = [] print(f"translating {len(rows)} sentences from the {name} set ...")
for i in range(0, len(rows), 64): preds = run([r["en"] for r in rows])
preds += translate_batch(model, tok, [r["en"] for r in rows[i : i + 64]]) res = score(preds, [r["typ"] for r in rows])
exact = [p == r["typ"] for p, r in zip(preds, rows)] results[name] = res
comp = compiles_many(preds) slug = name.split()[0]
n = len(rows) (out / f"errors_{slug}.txt").write_text(error_report(rows, preds, res))
print(f"{name:<12}{n:>6}{sum(exact) / n:>9.1%}{sum(comp) / n:>10.1%}") 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")
lines = [f"{n - sum(exact)} of {n} not exact\n"] print()
for r, p, e, c in zip(rows, preds, exact, comp): print(table(results))
if not e: print(f"\nfailure dumps: {out}/errors_*.txt predictions: {out}/predictions_*.jsonl")
lines.append(f"EN: {r['en']}\nWANT: {r['typ']}\nGOT: {p}{'' if c else ' [does not compile]'}\n") summary = {k: {m: v[m] for m in ("n", "exact", "compiles", "render_match")} for k, v in results.items()}
path = pathlib.Path(args.out) / f"errors_{name}.txt" (out / "eval.json").write_text(json.dumps(summary, indent=2))
path.write_text("\n".join(lines))
print(f"\nfailures: {args.out}/errors_*.txt")
if __name__ == "__main__": if __name__ == "__main__":
+176 -111
View File
@@ -1,9 +1,7 @@
"""Generate (English, Typst) training pairs from random expression trees. """Generate (English, Typst) training pairs from random ASTs.
uv run isotope-gen # 200k pairs into data/ uv run isotope-gen # full generator, ~300k pairs
uv run isotope-gen -n 5000 # a quick small set uv run isotope-gen --basic -n 10000 # the "Your turn" subset: Num Var Neg Pow Frac Integral
Writes data/{train,valid,test}.jsonl with lines {"en": ..., "typ": ...} and data/stats.txt.
""" """
from __future__ import annotations from __future__ import annotations
@@ -14,170 +12,237 @@ import hashlib
import json import json
import pathlib import pathlib
import random import random
from typing import ClassVar
from .ast import FUNCS, GREEK, Add, Eq, Frac, Func, Integral, Lim, Mul, Neg, Node, Num, Pow, Sqrt, Sub, Sum, Var, walk from .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 .render import to_english, to_typst
from .validate import compiles_many from .validate import compiles_many
INF = Var("infinity") INF = Var("infinity")
BIG = (Integral, Sum, Prod, Lim, Deriv)
class TreeGen: class TreeGen:
def __init__(self, rng: random.Random): def __init__(self, rng: random.Random, basic: bool = False):
self.rng = rng self.rng = rng
self.basic = basic
self.big_left = 0
# -- leaves --------------------------------------------------------------------------- # -- leaves ---------------------------------------------------------------------
def var(self, prefer: str | None = None) -> Var: def var_name(self, prefer: str | None = None) -> str:
if prefer and self.rng.random() < 0.6: # inside "integral ... dx", mostly use x r = self.rng
return Var(prefer) if prefer and r.random() < 0.6:
pool = ["x"] * 12 + ["y"] * 4 + ["z", "t", "a", "b", "c", "n", "k", "u", "r", "s", "m", "p"] + GREEK return prefer
return Var(self.rng.choice(pool)) 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 num(self) -> Num: def number(self) -> Num:
r = self.rng.random() r = self.rng.random()
if r < 0.8: if r < 0.75:
return Num(self.rng.randint(1, 10)) return Num(self.rng.randint(1, 10))
if r < 0.85: if r < 0.82:
return Num(0) return Num(0)
if r < 0.95: if r < 0.95:
return Num(self.rng.randint(11, 20)) return Num(self.rng.randint(11, 20))
return Num(self.rng.choice([25, 50, 100, 360, 1000])) return Num(self.rng.choice([25, 30, 50, 100, 12, 64, 360, 1000]))
def leaf(self, prefer: str | None = None) -> Node: def leaf(self, prefer: str | None = None) -> Node:
r = self.rng.random() r = self.rng.random()
if r < 0.55: if r < 0.55:
return self.var(prefer) return Var(self.var_name(prefer))
if r < 0.92: if r < 0.9:
return self.num() return self.number()
return Var(self.rng.choice(["pi", "e"])) 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")]))
# -- expressions without big operators ---------------------------------------------------- # -- inner nodes ----------------------------------------------------------------
KINDS: ClassVar[dict[str, int]] = { def pick(self) -> str:
"Add": 12, if self.basic:
"Sub": 8, kinds = {"Neg": 5, "Pow": 14, "Frac": 10, "Integral": 6}
"Mul": 12, else:
"Pow": 14, kinds = {"Add": 12, "Sub": 8, "Mul": 12, "Pow": 14, "Frac": 10, "Neg": 5, "Sqrt": 6,
"Frac": 10, "Func": 9, "Abs": 2, "Factorial": 2, "Integral": 7, "Sum": 4, "Prod": 2,
"Neg": 4, "Lim": 4, "Deriv": 3}
"Sqrt": 5, if self.big_left <= 0:
"Func": 8, 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: def expr(self, depth: int, prefer: str | None = None) -> Node:
r = self.rng r = self.rng
if depth <= 0: if depth <= 0:
return self.leaf(prefer) return self.leaf(prefer)
kind = r.choices(list(self.KINDS), list(self.KINDS.values()))[0] kind = self.pick()
d = depth - 1 d = depth - 1
small = 0 if r.random() < 0.5 else d # keep one side shallow half the time
match kind: match kind:
case "Add" | "Sub":
return (Add if kind == "Add" else Sub)(self.expr(d, prefer), self.expr(small, prefer))
case "Mul":
a = self.num() if r.random() < 0.4 else self.expr(small, prefer)
b = self.expr(d, prefer)
if isinstance(b, Num) and not isinstance(a, Num):
a, b = b, a # "2 x", not "x 2"
return Mul(a, b)
case "Pow":
base = Var("e") if r.random() < 0.15 else self.expr(d if r.random() < 0.25 else 0, prefer)
if isinstance(base, Pow):
base = base.base
x = r.random()
if x < 0.55:
exp: Node = Num(r.choice([2, 2, 2, 3, 3, 4, 5, 10]))
elif x < 0.7:
exp = Var(r.choice(["n", "k", "x", "a", "m", "t"]))
elif x < 0.85:
exp = Neg(self.leaf(prefer))
else:
exp = self.expr(d, prefer)
return Pow(base, exp)
case "Frac":
den = self.expr(small, prefer)
while den == Num(0):
den = self.leaf(prefer)
return Frac(self.expr(d, prefer), den)
case "Neg": case "Neg":
a = self.expr(d, prefer) a = self.expr(d, prefer)
while isinstance(a, Neg) or a == Num(0): while isinstance(a, Neg) or a == Num(0):
a = self.leaf(prefer) a = self.expr(d, prefer)
return Neg(a) 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": case "Sqrt":
return Sqrt(self.expr(d, prefer)) 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": case "Func":
return Func(r.choice(FUNCS + ["sin", "cos", "ln"]), self.expr(small, prefer)) 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) raise AssertionError(kind)
# -- big operators: only ever at the top of a tree -------------------------------------
def big(self, depth: int) -> Node:
r = self.rng
kind = r.choices(["Integral", "Sum", "Lim"], [6, 3, 3])[0]
if kind == "Integral":
v = r.choice(["x"] * 6 + ["t", "u", "y", "theta"])
body = self.expr(max(depth, 1), v)
if r.random() < 0.3:
return Integral(body, v)
lo = r.choice([Num(0)] * 5 + [Num(1)] * 2 + [Neg(Num(1)), Var("a"), Neg(INF)])
hi = r.choice([Num(1)] * 3 + [INF] * 3 + [Num(2), Var("b"), Var("pi"), Var("x"), Frac(Var("pi"), Num(2))])
return Integral(body, v, lo, hi)
if kind == "Sum":
v = r.choice(["i", "k", "n", "j"])
hi = r.choice([Var("n"), Var("N"), INF, Num(10), Num(100)])
if hi == Var(v):
hi = INF
return Sum(self.expr(depth, v), v, r.choice([Num(0), Num(1), Num(1)]), hi)
v = r.choice(["x"] * 4 + ["n", "h", "t"])
to = r.choice([Num(0)] * 4 + [INF] * 4 + [Num(1), Var("a"), Neg(INF)])
return Lim(self.expr(max(depth, 1), v), v, to)
def tree(self) -> Node: def tree(self) -> Node:
r = self.rng r = self.rng
depth = r.choices([1, 2, 3, 4], [25, 40, 25, 10])[0] self.big_left = r.choice([1, 1, 1, 2]) if not self.basic else 1
e = self.big(depth - 1) if r.random() < 0.3 else self.expr(depth) depth = r.choices([1, 2, 3, 4, 5], [20, 35, 28, 12, 5])[0]
if r.random() < 0.2: if self.basic:
lhs = r.choice([Var("y"), Var("f"), Var("x"), self.expr(r.choice([0, 1]))]) depth = r.choices([1, 2, 3, 4], [30, 40, 22, 8])[0]
return Eq(lhs, e) 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 return e
def split_of(typ: str) -> str: def split_of(typ: str) -> str:
"""Split by structure, not by row: the same Typst string always lands in the same split.""" """Split by structure, not by row: hash the Typst string."""
h = int(hashlib.md5(typ.encode()).hexdigest(), 16) % 100 h = int(hashlib.md5(typ.encode()).hexdigest(), 16) % 100
return "valid" if h < 2 else "test" if h < 4 else "train" return "valid" if h < 2 else ("test" if h < 4 else "train")
def main(argv: list[str] | None = None) -> None: def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("-n", type=int, default=200_000, help="number of pairs to generate") ap.add_argument("-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("--per-tree", type=int, default=2, help="max English phrasings per tree")
ap.add_argument("--max-chars", type=int, default=150, help="drop trees whose Typst is longer than this")
ap.add_argument("--out", default="data") ap.add_argument("--out", default="data")
ap.add_argument("--seed", type=int, default=0) ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--max-typ-chars", type=int, default=160)
args = ap.parse_args(argv) args = ap.parse_args(argv)
rng = random.Random(args.seed) rng = random.Random(args.seed)
gen = TreeGen(rng) gen = TreeGen(rng, basic=args.basic)
pairs: list[tuple[str, str, Node]] = [] pairs: list[tuple[str, str, Node]] = []
seen: set[str] = set() seen_en: set[str] = set()
while len(pairs) < args.n: while len(pairs) < args.n:
t = gen.tree() t = gen.tree()
typ = to_typst(t) typ = to_typst(t)
if len(typ) > args.max_chars: if len(typ) > args.max_typ_chars:
continue continue
for _ in range(rng.randint(1, args.per_tree)): for _ in range(rng.randint(1, args.per_tree)):
en = to_english(t, rng) en = to_english(t, rng)
if en not in seen: if en in seen_en or len(en) > 3 * args.max_typ_chars:
seen.add(en) continue
pairs.append((en, typ, t)) seen_en.add(en)
pairs.append((en, typ, t))
distinct = sorted({typ for _, typ, _ in pairs}) distinct = sorted({typ for _, typ, _ in pairs})
print(f"generated {len(pairs):,} pairs ({len(distinct):,} distinct Typst strings); compile-checking ...") print(f"generated {len(pairs):,} pairs, {len(distinct):,} distinct Typst strings; compiling them all ...")
ok = dict(zip(distinct, compiles_many(distinct))) ok = dict(zip(distinct, compiles_many(distinct)))
bad = [s for s in distinct if not ok[s]] bad = [s for s in distinct if not ok[s]]
if bad: if bad:
print(f"WARNING: dropped {len(bad)} Typst strings that do not compile, e.g.:") print(f"WARNING: {len(bad)} Typst strings failed to compile and were dropped, e.g.:")
for s in bad[:10]: for s in bad[:10]:
print(" ", s) print(" ", s)
@@ -189,18 +254,18 @@ def main(argv: list[str] | None = None) -> None:
for en, typ, t in pairs: for en, typ, t in pairs:
if not ok[typ]: if not ok[typ]:
continue continue
split = split_of(typ) s = split_of(typ)
files[split].write(json.dumps({"en": en, "typ": typ}) + "\n") files[s].write(json.dumps({"en": en, "typ": typ}) + "\n")
counts[split] += 1 counts[s] += 1
if split == "train": if s == "train":
hist.update({type(x).__name__ for x in walk(t)}) hist.update({type(x).__name__ for x in walk(t)})
for f in files.values(): for f in files.values():
f.close() f.close()
lines = [f"split sizes: {dict(counts)}", "fraction of training pairs containing each node type:"]
total = counts["train"] or 1 total = counts["train"] or 1
lines = [f"split sizes: {dict(counts)}", "share of training pairs containing each node type:"] for k, v in sorted(hist.items(), key=lambda kv: -kv[1]):
for k, v in hist.most_common(): lines.append(f" {k:<10} {v / total:6.1%} {'#' * int(40 * v / total)}")
lines.append(f" {k:<9}{v / total:6.1%} {'#' * int(40 * v / total)}")
report = "\n".join(lines) report = "\n".join(lines)
print(report) print(report)
(out / "stats.txt").write_text(report + "\n") (out / "stats.txt").write_text(report + "\n")
+117 -36
View File
@@ -1,7 +1,8 @@
"""Encoder–decoder Transformer (Path A), built on PyTorch's nn.Transformer. """Encoder–decoder Transformer (Path A).
forward(src, tgt_in) is used in training (whole target at once, causal mask). Seq2Seq(custom_attn=False) uses PyTorch's nn.Transformer (fast, the guide's starting point).
encode(src) and decode(tgt_in, memory) are used at inference (encode once, decode token by token). 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 from __future__ import annotations
@@ -15,56 +16,133 @@ from torch import nn
warnings.filterwarnings("ignore", message="enable_nested_tensor is True") warnings.filterwarnings("ignore", message="enable_nested_tensor is True")
CONFIGS = { CONFIGS = {
"tiny": {"d": 128, "heads": 4, "layers": 3, "ff": 512}, # ~2M params: debugging, overfit check "tiny": dict(d=128, heads=4, layers=3, ff=512), # ~2M params, for debugging
"small": {"d": 256, "heads": 4, "layers": 4, "ff": 1024}, # ~8M params: start here "small": dict(d=256, heads=4, layers=4, ff=1024), # ~8M params, start here
"medium": {"d": 512, "heads": 8, "layers": 6, "ff": 2048}, # ~46M params "medium": dict(d=512, heads=8, layers=6, ff=2048), # ~46M params
} }
def causal_mask(T: int, device=None) -> torch.Tensor: def causal_mask(T: int, device) -> torch.Tensor:
"""(T, T) bool, True above the diagonal = position i may NOT look at position j > i.""" """True above the diagonal = 'may not look' (PyTorch bool-mask convention)."""
return torch.triu(torch.ones(T, T, dtype=torch.bool, device=device), diagonal=1) 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): class Seq2Seq(nn.Module):
def __init__(self, vocab: int, d=256, heads=4, layers=4, ff=1024, max_len=256, drop=0.1, pad_id=0): 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__() super().__init__()
self.pad_id, self.max_len = pad_id, max_len self.pad_id, self.max_len, self.custom = pad_id, max_len, custom_attn
self.tok_emb = nn.Embedding(vocab, d) self.tok_emb = nn.Embedding(vocab, d)
self.pos_emb = nn.Embedding(max_len, d) # learned positions: the simplest option self.pos_emb = nn.Embedding(max_len, d) # learned positions: simplest option
self.drop = nn.Dropout(drop)
self.tf = nn.Transformer(d, heads, layers, layers, ff, drop, batch_first=True, norm_first=True)
self.out = nn.Linear(d, vocab, bias=False)
self.out.weight = self.tok_emb.weight # weight tying: one shared tokenizer, one embedding table
nn.init.normal_(self.tok_emb.weight, std=d**-0.5)
self.scale = math.sqrt(d) 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: torch.Tensor) -> torch.Tensor: def emb(self, ids):
pos = torch.arange(ids.size(1), device=ids.device) pos = torch.arange(ids.size(1), device=ids.device)
return self.drop(self.tok_emb(ids) * self.scale + self.pos_emb(pos)) return self.drop(self.tok_emb(ids) * self.scale + self.pos_emb(pos))
def encode(self, src: torch.Tensor) -> torch.Tensor: def encode(self, src):
"""(B, S) token ids -> (B, S, d) memory, one vector per English token.""" pad = src == self.pad_id
return self.tf.encoder(self.emb(src), src_key_padding_mask=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: torch.Tensor, memory: torch.Tensor, src_pad: torch.Tensor | None = None) -> torch.Tensor: def decode(self, tgt_in, memory, src_pad=None):
"""(B, T) Typst-so-far + memory -> (B, T, vocab) logits for the next token at every position.""" T = tgt_in.size(1)
h = self.tf.decoder( causal = causal_mask(T, tgt_in.device)
self.emb(tgt_in), tgt_pad = tgt_in == self.pad_id
memory, y = self.emb(tgt_in)
tgt_mask=causal_mask(tgt_in.size(1), tgt_in.device), if self.custom:
tgt_is_causal=True, for layer in self.dec_layers:
tgt_key_padding_mask=tgt_in == self.pad_id, y = layer(y, memory, causal, tgt_pad, src_pad)
memory_key_padding_mask=src_pad, h = self.dec_norm(y)
) else:
return self.out(h) 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: torch.Tensor, tgt_in: torch.Tensor) -> torch.Tensor: def forward(self, src, tgt_in):
return self.decode(tgt_in, self.encode(src), src_pad=src == self.pad_id) return self.decode(tgt_in, self.encode(src), src_pad=(src == self.pad_id))
def count_params(model: nn.Module) -> int: def count_params(m: nn.Module) -> int:
return sum(p.numel() for p in model.parameters()) 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: def pick_device() -> str:
@@ -73,3 +151,6 @@ def pick_device() -> str:
if torch.backends.mps.is_available(): if torch.backends.mps.is_available():
return "mps" return "mps"
return "cpu" 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()
+395 -210
View File
@@ -1,36 +1,43 @@
"""Render one tree two ways: to_typst() (deterministic) and to_english() (randomised). """Render one AST two ways: to_typst() (deterministic) and to_english() (randomised)."""
Because both strings come from the same tree, every (English, Typst) pair is correct by construction.
The English side has to be *unambiguous*: if two different trees could produce the same sentence, the
model is taught to guess. The conventions that keep it unambiguous are:
* "tail" position: a sub-expression is in tail position when nothing follows it inside its parent.
Only there may a phrase run on to the end ("e to the minus x squared", "the quantity x plus 1").
* Anything that is not "simple" (see is_simple) is wrapped when it is an operand: "(x plus 1)",
"open paren x plus 1 close paren", or, in tail position only, "the quantity x plus 1".
* An exponent is spoken bare only if it is a number, a variable, or "minus <simple>" in tail position
(guide Appendix A, Q1: "e to the minus x squared" = e^(-x^2)). Every other exponent is delimited.
* Functions and roots take one simple argument: "sine of x squared" = sin(x^2); sin(x)^2 is said
"sine squared of x" or "(sine of x) squared".
* Big operators (integral, sum, limit) only appear at the top of a tree, and their body runs until
"dx" (integrals), "equals", or the end of the sentence.
"""
from __future__ import annotations from __future__ import annotations
import random import random
import re import re
from .ast import BIG_OPS, GREEK, Add, Eq, Frac, Func, Integral, Lim, Mul, Neg, Node, Num, Pow, Sqrt, Sub, Sum, Var from .ast import (
Abs,
Add,
Deriv,
Factorial,
Frac,
Func,
Integral,
Lim,
Mul,
Neg,
Node,
Num,
Pow,
Prod,
Rel,
Sqrt,
Sub,
Subscript,
Sum,
Var,
)
# ------------------------------------------------------------------------------------------ # --------------------------------------------------------------------------------------
# Typst # Typst
# ------------------------------------------------------------------------------------------ # --------------------------------------------------------------------------------------
BIG_OPS = (Integral, Sum, Prod, Lim, Deriv)
def level(n: Node) -> int: def level(n: Node) -> int:
"""How tightly a node binds in Typst output (higher = tighter).""" """Binding strength of a node in Typst output (higher binds tighter)."""
if isinstance(n, Eq): if isinstance(n, Rel):
return 0 return 0
if isinstance(n, (Add, Sub)): if isinstance(n, (Add, Sub)):
return 1 return 1
@@ -40,7 +47,13 @@ def level(n: Node) -> int:
return 3 return 3
if isinstance(n, Mul): if isinstance(n, Mul):
return 4 return 4
return 9 # atoms: Var, Num, Pow, Frac, Sqrt, Func 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: def paren(n: Node, cond: bool) -> str:
@@ -48,9 +61,16 @@ def paren(n: Node, cond: bool) -> str:
return f"({s})" if cond else s return f"({s})" if cond else s
def group(n: Node) -> str: def base_str(n: Node) -> str:
"""Sub/superscripts: Typst needs parens around anything longer than one atom (they are not shown).""" """Base of a power / factorial: parens are visible here, so only add them when needed."""
return paren(n, not isinstance(n, (Var, Num))) 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: def to_typst(n: Node) -> str:
@@ -61,72 +81,56 @@ def to_typst(n: Node) -> str:
return str(v) return str(v)
case Neg(a): case Neg(a):
return f"-{paren(a, level(a) <= 3)}" return f"-{paren(a, level(a) <= 3)}"
case Add(a, b): case Pow(b, e):
return f"{to_typst(a)} + {paren(b, level(b) <= 1 or isinstance(b, Neg))}" return f"{base_str(b)}^{group(e)}"
case Sub(a, b): case Subscript(b, s):
return f"{to_typst(a)} - {paren(b, level(b) <= 1 or isinstance(b, Neg))}" 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): case Mul(a, b):
left = paren(a, level(a) < 3) left = paren(a, level(a) < 3)
right = paren(b, level(b) <= 3 and not isinstance(b, BIG_OPS)) right = paren(b, level(b) <= 3 and not isinstance(b, BIG_OPS))
sep = " dot " if left[-1].isdigit() and right[0].isdigit() else " " # "2 dot 3", not "2 3" sep = " dot " if left[-1].isdigit() and right[0].isdigit() else " "
return f"{left}{sep}{right}" return f"{left}{sep}{right}"
case Pow(b, e): case Add(a, b):
# parens around the base *are* visible, so only add them when needed return f"{paren(a, level(a) == 0)} + {paren(b, level(b) <= 1 or isinstance(b, Neg))}"
return f"{paren(b, not isinstance(b, (Var, Num, Func, Sqrt)))}^{group(e)}" case Sub(a, b):
case Frac(a, b): return f"{paren(a, level(a) == 0)} - {paren(b, level(b) <= 1 or isinstance(b, Neg))}"
return f"frac({to_typst(a)}, {to_typst(b)})"
case Sqrt(a):
return f"sqrt({to_typst(a)})"
case Func(name, a):
return f"{name}({to_typst(a)})"
case Integral(body, v, lo, hi): case Integral(body, v, lo, hi):
bounds = "" if lo is None else f"_{group(lo)}^{group(hi)}" return f"integral{bounds(lo, hi)} {paren(body, level(body) <= 1)} dif {v}"
return f"integral{bounds} {paren(body, level(body) <= 1)} dif {v}"
case Sum(body, v, lo, hi): case Sum(body, v, lo, hi):
return f"sum_({v} = {to_typst(lo)})^{group(hi)} {paren(body, level(body) <= 1)}" 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): case Lim(body, v, to):
return f"lim_({v} -> {to_typst(to)}) {paren(body, level(body) <= 1)}" return f"lim_({v} -> {to_typst(to)}) {paren(body, level(body) <= 1)}"
case Eq(a, b): case Deriv(body, v):
return f"{to_typst(a)} = {to_typst(b)}" 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) raise NotImplementedError(n)
# ------------------------------------------------------------------------------------------ # --------------------------------------------------------------------------------------
# English # English
# ------------------------------------------------------------------------------------------ # --------------------------------------------------------------------------------------
ONES = [ ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"zero", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"one", "eighteen", "nineteen"]
"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"] TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
ORDINALS = {4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth", 10: "tenth"} ORDINALS = {2: "second", 3: "third", 4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh",
FUNC_WORDS = { 8: "eighth", 9: "ninth", 10: "tenth", 11: "eleventh", 12: "twelfth", 20: "twentieth"}
"sin": ["sine", "sin"],
"cos": ["cosine", "cos"],
"tan": ["tangent", "tan"],
"ln": ["ln", "natural log", "the natural log", "the natural logarithm"],
"log": ["log", "the log", "the logarithm"],
"exp": ["exp", "the exponential"],
}
def number_words(v: int) -> str: def number_words(v: int) -> str:
@@ -135,194 +139,375 @@ def number_words(v: int) -> str:
if v < 100: if v < 100:
t, o = divmod(v, 10) t, o = divmod(v, 10)
return TENS[t] + ("" if o == 0 else " " + ONES[o]) return TENS[t] + ("" if o == 0 else " " + ONES[o])
if v == 100: if v < 1000:
return "one hundred" h, r = divmod(v, 100)
return f"{ONES[h]} hundred" + ("" if r == 0 else f" {number_words(r)}")
return str(v) return str(v)
def is_simple(n: Node) -> bool: def is_simple(n: Node) -> bool:
"""Can be said as an operand without wrapping it in parentheses.""" """Something you can say without needing a 'the quantity' wrapper."""
if isinstance(n, (Var, Num, Func, Sqrt)): return isinstance(n, (Var, Num, Subscript, Func, Abs, Sqrt, Factorial)) or (
return True isinstance(n, Pow) and isinstance(n.base, (Var, Num, Subscript)) and isinstance(n.exp, (Var, Num))
return isinstance(n, Pow) and isinstance(n.base, (Var, Num)) and isinstance(n.exp, (Var, Num)) )
class English: class English:
def __init__(self, rng: random.Random): """Randomised English renderer. Conventions keep generated sentences unambiguous enough:
self.rng = rng
def c(self, *options: str) -> str: * "B to the E" swallows everything that follows into the exponent (Appendix A, Q1), so a
return self.rng.choice(options) 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: def p(self, prob: float) -> bool:
return self.rng.random() < prob return self.rng.random() < prob
def wrap(self, n: Node, tail: bool) -> str: # -- helpers --------------------------------------------------------------------
"""Say n so that a listener knows where it ends.""" def num(self, v: int) -> str:
if is_simple(n): return number_words(v) if (v <= 100 and self.p(0.35)) else str(v)
return self.say(n, tail)
s = self.say(n, tail=True) # the brackets delimit it, so inside it may run on
options = [f"({s})", f"open paren {s} close paren"]
if tail: # "the quantity" has no closing word, so it must run to the end
options += [f"the quantity {s}"] * 2
return self.c(*options)
def 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: 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: match n:
case Var("infinity"): case Var("infinity"):
return "infinity" return self.c("infinity", "infinity", "infinity", "inf")
case Var("pi"):
return "pi"
case Var(name): case Var(name):
return name return name
case Num(v): case Num(v):
return number_words(v) if v <= 100 and self.p(0.3) else str(v) return self.num(v)
case Neg(a): case Neg(a):
inner = self.say(a, tail) if is_simple(a) else self.wrap(a, tail) 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')} {inner}" return f"{self.c('minus', 'negative', 'minus', 'negative')} {inner}"
case Add(a, b) | Sub(a, b):
left = self.say(a, tail=False)
right = self.wrap(b, tail) if level(b) <= 1 or isinstance(b, Neg) else self.say(b, tail)
op = self.c("plus", "plus", "add") if isinstance(n, Add) else "minus"
if op == "add":
op = "plus"
return f"{left} {op} {right}"
case Mul(a, b):
left = self.say(a, tail=False) if level(a) >= 3 else self.wrap(a, tail=False)
right = self.wrap(b, tail) if level(b) <= 3 else self.say(b, tail)
if isinstance(a, Num) and isinstance(b, (Var, Pow, Func, Sqrt)) and self.p(0.6):
if isinstance(b, Var) and len(b.name) == 1 and left.isdigit() and self.p(0.5):
return f"{left}{right}" # "2x"
return f"{left} {right}" # "2 x", "3 sine of x"
if isinstance(a, Var) and isinstance(b, Var) and self.p(0.4):
return f"{left} {right}" # "x y"
return self.c(f"{left} times {right}", f"{left} times {right}", f"{left} multiplied by {right}")
case Pow(b, e): case Pow(b, e):
return self.say_pow(b, e, tail) 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(Num(1), Num(2)) if self.p(0.4):
return self.c("one half", "a half")
case Frac(a, b): 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) num = self.wrap(a, tail=False)
den = self.wrap(b, tail) den = self.wrap(b, tail=tail)
return self.c( opts = [f"{num} over {den}", f"{num} over {den}", f"{num} divided by {den}",
f"{num} over {den}", f"the fraction {num} over {den}"]
f"{num} over {den}", if not (is_simple(a) and is_simple(b)):
f"{num} divided by {den}", opts.append(f"the fraction with numerator {self.say(a, False)} and denominator {self.say(b, tail)}"
f"the fraction {num} over {den}", + ("" 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): case Sqrt(a, None):
arg = self.say(a, tail) if is_simple(a) else self.wrap(a, tail) if tail and not is_simple(a) and self.p(0.4):
return self.c(f"the square root of {arg}", f"square root of {arg}", f"root {arg}", f"sqrt of {arg}") 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): case Func(name, a):
word = self.rng.choice(FUNC_WORDS[name]) simple = is_simple(a) and not isinstance(a, Func)
if not is_simple(a): arg = self.say(a) if simple else self.wrap(a, tail)
return f"{word} of {self.wrap(a, tail)}" names = {
arg = self.say(a, tail) "sin": ["sine", "sin", "the sine"], "cos": ["cosine", "cos", "the cosine"],
if word in ("sin", "cos", "tan", "ln", "log", "exp") and self.p(0.5): "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} {arg}"
return f"{word} of {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): case Integral(body, v, lo, hi):
b = self.say(body, tail=True) # "dx" closes the body b = self.say(body, tail=self.p(0.5)) # "dx" closes the body, so a bare tail form is fine
d = self.c(f"d{v}", f"d{v}", f"d {v}", f"with respect to {v}") if level(body) <= 1 and self.p(0.4):
b = self.wrap(body, tail=False)
d = self.dvar(v)
if lo is None: if lo is None:
return self.c( return self.c(f"the integral of {b} {d}", f"integral of {b} {d}", f"integral {b} {d}",
f"the integral of {b} {d}", f"the indefinite integral of {b} {d}", f"integrate {b} {d}",
f"integral of {b} {d}", f"the antiderivative of {b} {d}")
f"integral {b} {d}", l, h = self.say(lo, False), self.say(hi, False)
f"the indefinite integral of {b} {d}",
)
lo_s, hi_s = self.say(lo, False), self.say(hi, False)
return self.c( return self.c(
f"the integral from {lo_s} to {hi_s} of {b} {d}", f"the integral from {l} to {h} of {b} {d}",
f"the integral from {lo_s} to {hi_s} of {b} {d}", f"the integral from {l} to {h} of {b} {d}",
f"integral from {lo_s} to {hi_s} of {b} {d}", f"integral from {l} to {h} of {b} {d}",
f"integral {lo_s} to {hi_s} {b} {d}", f"integral {l} to {h} {b} {d}",
f"the definite integral from {lo_s} to {hi_s} of {b} {d}", f"the definite integral from {l} to {h} of {b} {d}",
f"the integral of {b} from {lo_s} to {hi_s} {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): case Sum(body, v, lo, hi) | Prod(body, v, lo, hi):
b = self.say(body, tail) is_sum = isinstance(n, Sum)
lo_s, hi_s = self.say(lo, False), self.say(hi, False) b = self.say(body, tail=tail)
eq = self.c("equals", "equals", "=", "from") 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( return self.c(
f"the sum from {v} {eq} {lo_s} to {hi_s} of {b}", f"the {w} from {v} {eq} {l} to {h} of {b}",
f"the sum from {v} {eq} {lo_s} to {hi_s} of {b}", f"the {w} from {v} {eq} {l} to {h} of {b}",
f"sum from {v} {eq} {lo_s} to {hi_s} of {b}", f"{w} from {v} {eq} {l} to {h} of {b}",
f"sum {v} {eq} {lo_s} to {hi_s} {b}", f"{w} {v} {eq} {l} to {h} {b}",
f"the sum over {v} from {lo_s} to {hi_s} of {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): case Lim(body, v, to):
b = self.say(body, tail) b = self.say(body, tail=tail)
to_s = self.say(to, False) if level(body) <= 1 and not (tail and self.p(0.4)):
verb = self.c("approaches", "approaches", "goes to", "tends to") 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( return self.c(
f"the limit as {v} {verb} {to_s} of {b}", f"the limit as {v} {verb} {t} of {b}",
f"the limit as {v} {verb} {to_s} of {b}", f"the limit as {v} {verb} {t} of {b}",
f"limit as {v} {verb} {to_s} of {b}", f"limit as {v} {verb} {t} of {b}",
f"lim {v} {verb} {to_s} 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 Eq(a, b): case Deriv(body, v):
return f"{self.say(a, False)} {self.c('equals', 'equals', 'is equal to', 'is')} {self.say(b, tail)}" 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) raise NotImplementedError(n)
def say_pow(self, b: Node, e: Node, tail: bool) -> str:
if isinstance(b, Func) and e in (Num(2), Num(3)) and is_simple(b.arg) and self.p(0.5):
word = self.rng.choice(FUNC_WORDS[b.name][:2])
return f"{word} {'squared' if e == Num(2) else 'cubed'} of {self.say(b.arg, tail)}" # sine squared of x
if isinstance(b, (Var, Num)): def symbolic_text(n: Node) -> str | None:
base = self.say(b, False) """How someone might type a small expression: 'e^(-x^2)', 'x^2 + 1', '1/x'. None if too big."""
else: # bracket the base, even for functions: "sine of x squared" means sin(x^2) match n:
inner = self.say(b, True) case Var(name) if len(name) == 1:
base = self.c(f"({inner})", f"open paren {inner} close paren") return name
case Num(v):
if e == Num(2): return str(v)
return self.c(f"{base} squared", f"{base} squared", f"{base} to the power of 2", f"{base} to the second") case Neg(a):
if e == Num(3): s = symbolic_text(a)
return self.c(f"{base} cubed", f"{base} cubed", f"{base} to the power of 3", f"{base} to the third") return None if s is None or isinstance(a, (Add, Sub)) else f"-{s}"
if isinstance(e, Num): case Pow(b, e):
options = [f"{base} to the power of {self.say(e)}", f"{base} to the {self.say(e)}"] sb, se = symbolic_text(b), symbolic_text(e)
if e.value in ORDINALS: if sb is None or se is None or not isinstance(b, (Var, Num)):
options.append(f"{base} to the {ORDINALS[e.value]}") return None
return self.c(*options) return f"{sb}^{se}" if isinstance(e, (Var, Num)) else f"{sb}^({se})"
if isinstance(e, Var): case Frac(a, b) if isinstance(a, (Var, Num)) and isinstance(b, (Var, Num)):
options = [f"{base} to the {e.name}", f"{base} to the power of {e.name}"] return f"{to_typst(a)}/{to_typst(b)}"
if len(e.name) == 1: case Add(a, b) | Sub(a, b):
options.append(f"{base} to the {e.name}th") sa, sb = symbolic_text(a), symbolic_text(b)
return self.c(*options) if sa is None or sb is None or isinstance(b, (Add, Sub, Neg)):
if tail and isinstance(e, Neg) and is_simple(e.arg): # e to the minus x squared return None
ex = self.say(e, True) return f"{sa} {'+' if isinstance(n, Add) else '-'} {sb}"
return self.c(f"{base} to the {ex}", f"{base} to the power of {ex}") case Mul(Num(v), Var(name)) if len(name) == 1:
ex = self.say(e, True) return f"{v}{name}"
return self.c( return None
f"{base} to the ({ex})", f"{base} to the power of ({ex})", f"{base} to the open paren {ex} close paren"
)
PREFIXES = ["write ", "what is ", "typeset ", "please write "] 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: def add_noise(s: str, rng: random.Random) -> str:
"""Surface variation people produce: a dropped 'the', capitals, a polite prefix.""" """Surface noise: optional 'the', casing, prefixes, the odd typo."""
if rng.random() < 0.3: if rng.random() < 0.3:
s = re.sub(r"(^|\bof )the ", lambda m: m.group(1) if rng.random() < 0.5 else m.group(0), s) s = re.sub(r"\bthe ", lambda m: "" if rng.random() < 0.5 else m.group(0), s)
if rng.random() < 0.08: if rng.random() < 0.15:
s = rng.choice(PREFIXES) + s s = rng.choice(PREFIXES) + s + rng.choice(SUFFIXES)
first = s.split(" ", 1)[0] if rng.random() < 0.06: # typo: swap two letters, drop one, or double one, in a longer word
if rng.random() < 0.15 and len(first) >= 3 and first.isalpha() and first not in GREEK: # never "Y" for y 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:] s = s[:1].upper() + s[1:]
return s 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: def to_english(n: Node, rng: random.Random, noise: bool = True) -> str:
s = re.sub(r"\s+", " ", English(rng).say(n, tail=True)).strip() 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 return add_noise(s, rng) if noise else s
+21 -22
View File
@@ -1,6 +1,6 @@
"""Byte-level BPE tokenizer, shared by English and Typst (so the model can copy x, 2, pi across). """Byte-level BPE tokenizer shared by English and Typst.
uv run isotope-tokenizer # data/train.jsonl -> artifacts/tokenizer.json uv run isotope-tokenizer # trains artifacts/tokenizer.json from data/train.jsonl
""" """
from __future__ import annotations from __future__ import annotations
@@ -8,39 +8,39 @@ from __future__ import annotations
import argparse import argparse
import json import json
import pathlib import pathlib
import tempfile
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers
SPECIALS = ["[PAD]", "[UNK]", "[BOS]", "[EOS]"] SPECIALS = ["[PAD]", "[UNK]", "[BOS]", "[EOS]"] # ids 0, 1, 2, 3
PAD, UNK, BOS, EOS = 0, 1, 2, 3 PAD, UNK, BOS, EOS = 0, 1, 2, 3
def train(texts, out: str = "artifacts/tokenizer.json", vocab: int = 4000) -> Tokenizer: def train(files: list[str], out: str = "artifacts/tokenizer.json", vocab: int = 4000) -> Tokenizer:
tok = Tokenizer(models.BPE(unk_token="[UNK]")) tok = Tokenizer(models.BPE(unk_token="[UNK]"))
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tok.decoder = decoders.ByteLevel() tok.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer( trainer = trainers.BpeTrainer(vocab_size=vocab, special_tokens=SPECIALS,
vocab_size=vocab, special_tokens=SPECIALS, initial_alphabet=pre_tokenizers.ByteLevel.alphabet() initial_alphabet=pre_tokenizers.ByteLevel.alphabet())
) tok.train(files, trainer) # files: plain-text dumps of the en and typ columns
tok.train_from_iterator(texts, trainer)
pathlib.Path(out).parent.mkdir(parents=True, exist_ok=True) pathlib.Path(out).parent.mkdir(parents=True, exist_ok=True)
tok.save(out) tok.save(out)
return tok return tok
def load(path: str = "artifacts/tokenizer.json") -> Tokenizer: def load(path: str = "artifacts/tokenizer.json") -> Tokenizer:
if not pathlib.Path(path).exists():
raise SystemExit(f"No tokenizer at {path}. Train one first: uv run isotope-tokenizer")
return Tokenizer.from_file(path) return Tokenizer.from_file(path)
def jsonl_texts(path: str): def train_from_jsonl(jsonl: str = "data/train.jsonl", out: str = "artifacts/tokenizer.json", vocab: int = 4000) -> Tokenizer:
"""Both columns of a data file, one string at a time.""" with tempfile.TemporaryDirectory() as d:
with open(path) as f: en, typ = pathlib.Path(d) / "en.txt", pathlib.Path(d) / "typ.txt"
for line in f: with open(jsonl) as f, en.open("w") as fe, typ.open("w") as ft:
row = json.loads(line) for line in f:
yield row["en"] row = json.loads(line)
yield row["typ"] 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: def main(argv: list[str] | None = None) -> None:
@@ -49,11 +49,10 @@ def main(argv: list[str] | None = None) -> None:
ap.add_argument("--out", default="artifacts/tokenizer.json") ap.add_argument("--out", default="artifacts/tokenizer.json")
ap.add_argument("--vocab", type=int, default=4000) ap.add_argument("--vocab", type=int, default=4000)
args = ap.parse_args(argv) args = ap.parse_args(argv)
tok = train_from_jsonl(args.data, args.out, args.vocab)
tok = train(jsonl_texts(args.data), args.out, args.vocab) print(f"trained tokenizer with {tok.get_vocab_size()} tokens -> {args.out}")
print(f"trained a {tok.get_vocab_size()}-token BPE tokenizer -> {args.out}") ex = "integral_0^infinity e^(-x^2) dif x"
for s in ["the integral from 0 to infinity of e to the minus x squared dx", "integral_0^infinity e^(-x^2) dif x"]: print("example:", tok.encode(ex).tokens)
print(f" {s!r}\n -> {tok.encode(s).tokens}")
if __name__ == "__main__": if __name__ == "__main__":
+94 -96
View File
@@ -1,11 +1,9 @@
"""Training loop: teacher forcing, AdamW, linear warmup + cosine decay, label smoothing. """Training loop (teacher forcing, AdamW, warmup + cosine, label smoothing).
uv run isotope-train --overfit 100 # sanity check: a tiny model must memorise 100 pairs uv run isotope-train # small model, defaults
uv run isotope-train # small model (~8M params), 8000 steps uv run isotope-train --config tiny --steps 2000
uv run isotope-train --config tiny --steps 1000 # quick smoke run uv run isotope-train --overfit 100 # milestone M2 sanity check: memorise 100 pairs
uv run isotope-train --custom-attn # use the hand-written MultiHeadAttention
Writes artifacts/model.pt (best validation loss), artifacts/last.pt and artifacts/train_log.csv.
Ctrl-C stops early and still saves a checkpoint.
""" """
from __future__ import annotations from __future__ import annotations
@@ -25,105 +23,105 @@ from .model import CONFIGS, Seq2Seq, count_params, pick_device
from .tokenizer import BOS, EOS, PAD, load from .tokenizer import BOS, EOS, PAD, load
from .translate import translate_batch from .translate import translate_batch
MAX_LEN = 256
def read_pairs(path: str, limit: int | None = None) -> list[tuple[str, str]]: def read_pairs(path: str, limit: int | None = None) -> list[tuple[str, str]]:
pairs = [] out = []
with open(path) as f: with open(path) as f:
for line in f: for line in f:
row = json.loads(line) row = json.loads(line)
pairs.append((row["en"], row["typ"])) out.append((row["en"], row["typ"]))
if limit and len(pairs) >= limit: if limit and len(out) >= limit:
break break
return pairs return out
def encode_pairs(tok, pairs) -> list[tuple[list[int], list[int]]]: def encode_pairs(tok, pairs, max_len):
"""src = English ids; tgt = [BOS] Typst ids [EOS].""" srcs = [e.ids[:max_len] for e in tok.encode_batch([p[0] for p in pairs])]
srcs = [e.ids[:MAX_LEN] for e in tok.encode_batch([en for en, _ in pairs])] tgts = [[BOS] + e.ids[: max_len - 2] + [EOS] for e in tok.encode_batch([p[1] for p in pairs])]
tgts = [[BOS] + e.ids[: MAX_LEN - 2] + [EOS] for e in tok.encode_batch([typ for _, typ in pairs])]
return list(zip(srcs, tgts)) return list(zip(srcs, tgts))
def pad(seqs: list[list[int]]) -> torch.Tensor: def pad(seqs: list[list[int]]) -> torch.Tensor:
t = torch.full((len(seqs), max(map(len, seqs))), PAD, dtype=torch.long) L = max(len(s) for s in seqs)
t = torch.full((len(seqs), L), PAD, dtype=torch.long)
for i, s in enumerate(seqs): for i, s in enumerate(seqs):
t[i, : len(s)] = torch.tensor(s) t[i, : len(s)] = torch.tensor(s, dtype=torch.long)
return t return t
def batches(data, batch_size: int, rng: random.Random, bucket: int = 50): def batches(data, batch_size: int, rng: random.Random, bucket: int = 50):
"""Endless (src, tgt) batches. Sorting by length within big buckets keeps padding (wasted work) low.""" """Infinite iterator; sorts by length inside large buckets so batches have little padding."""
while True: while True:
idx = list(range(len(data))) idx = list(range(len(data)))
rng.shuffle(idx) rng.shuffle(idx)
chunk = batch_size * bucket chunk = batch_size * bucket
groups = [] bl = []
for c in range(0, len(idx), chunk): 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])) part = sorted(idx[c: c + chunk], key=lambda i: len(data[i][0]) + len(data[i][1]))
groups += [part[j : j + batch_size] for j in range(0, len(part), batch_size)] bl += [part[j: j + batch_size] for j in range(0, len(part), batch_size)]
rng.shuffle(groups) rng.shuffle(bl)
for g in groups: for b in bl:
yield pad([data[i][0] for i in g]), pad([data[i][1] for i in g]) yield pad([data[i][0] for i in b]), pad([data[i][1] for i in b])
def warmup_cosine(warmup: int, total: int, floor: float = 0.05): def lr_lambda(warmup: int, total: int, floor: float = 0.05):
def factor(step: int) -> float: def f(step: int) -> float:
if step < warmup: if step < warmup:
return (step + 1) / warmup return (step + 1) / warmup
progress = min(1.0, (step - warmup) / max(1, total - warmup)) prog = min(1.0, (step - warmup) / max(1, total - warmup))
return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * progress)) return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * prog))
return f
return factor
def loss_fn(model, src, tgt, smoothing: float = 0.1) -> torch.Tensor: def loss_fn(model, src, tgt, V, smoothing=0.1):
tgt_in, tgt_out = tgt[:, :-1], tgt[:, 1:] # teacher forcing: predict token t+1 from tokens <= t tgt_in, tgt_out = tgt[:, :-1], tgt[:, 1:] # teacher-forcing shift
logits = model(src, tgt_in) logits = model(src, tgt_in)
return F.cross_entropy( return F.cross_entropy(logits.reshape(-1, V), tgt_out.reshape(-1), ignore_index=PAD, label_smoothing=smoothing)
logits.reshape(-1, logits.size(-1)), tgt_out.reshape(-1), ignore_index=PAD, label_smoothing=smoothing
)
@torch.no_grad() @torch.no_grad()
def val_loss(model, data, dev, batch_size: int = 256) -> float: def val_loss(model, data, V, dev, batch_size=256):
model.eval() model.eval()
total = 0.0 tot, n = 0.0, 0
for i in range(0, len(data), batch_size): for i in range(0, len(data), batch_size):
part = data[i : i + batch_size] part = data[i: i + batch_size]
src, tgt = pad([s for s, _ in part]).to(dev), pad([t for _, t in part]).to(dev) src, tgt = pad([p[0] for p in part]).to(dev), pad([p[1] for p in part]).to(dev)
total += loss_fn(model, src, tgt, smoothing=0.0).item() * len(part) tot += loss_fn(model, src, tgt, V, smoothing=0.0).item() * len(part)
n += len(part)
model.train() model.train()
return total / max(1, len(data)) return tot / max(n, 1)
def save(path: pathlib.Path, model, model_args: dict, **extra) -> None: 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) torch.save({"model": model.state_dict(), "model_args": model_args, **extra}, path)
def overfit(tok, data_dir: str, n: int, dev: str) -> bool: def overfit(args, tok, dev):
"""If a tiny model cannot memorise n pairs, the pipeline has a bug (shift, mask, special tokens).""" """Milestone M2: a tiny model must memorise 100 pairs exactly, or the pipeline has a bug."""
pairs = read_pairs(f"{data_dir}/train.jsonl", n) pairs = read_pairs(f"{args.data}/train.jsonl", args.overfit)
data = encode_pairs(tok, pairs) data = encode_pairs(tok, pairs, 256)
V = tok.get_vocab_size()
torch.manual_seed(0) torch.manual_seed(0)
model = Seq2Seq(tok.get_vocab_size(), **CONFIGS["tiny"], max_len=MAX_LEN, drop=0.0).to(dev) 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) opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
src, tgt = pad([s for s, _ in data]).to(dev), pad([t for _, t in data]).to(dev) 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): for step in range(1, 3001):
model.train() model.train()
loss = loss_fn(model, src, tgt, smoothing=0.0) loss = loss_fn(model, src, tgt, V, smoothing=0.0)
opt.zero_grad(set_to_none=True) opt.zero_grad(set_to_none=True)
loss.backward() loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step() opt.step()
if step % 100 == 0: if step % 100 == 0:
preds = translate_batch(model, tok, [en for en, _ in pairs]) preds = translate_batch(model, tok, [p[0] for p in pairs], constrained=False)
exact = sum(p == typ for p, (_, typ) in zip(preds, pairs)) exact = sum(p == t for p, (_, t) in zip(preds, pairs))
print(f"step {step:5d} loss {loss.item():.4f} exact {exact}/{len(pairs)}", flush=True) print(f"step {step:5d} loss {loss.item():.4f} exact {exact}/{len(pairs)}")
if exact == len(pairs): if exact == len(pairs):
print(f"PASS: memorised all {len(pairs)} pairs.") print(f"PASS: memorised all {len(pairs)} pairs.")
return True return True
print("FAIL: could not memorise the pairs. Check the shift, the masks and BOS/EOS handling.") print("FAIL: could not memorise the pairs -- check shift / mask / special tokens.")
return False return False
@@ -139,8 +137,9 @@ def main(argv: list[str] | None = None) -> None:
ap.add_argument("--data", default="data") ap.add_argument("--data", default="data")
ap.add_argument("--out", default="artifacts") ap.add_argument("--out", default="artifacts")
ap.add_argument("--tokenizer", default="artifacts/tokenizer.json") ap.add_argument("--tokenizer", default="artifacts/tokenizer.json")
ap.add_argument("--overfit", type=int, default=0, metavar="N", help="only run the memorise-N-pairs check") ap.add_argument("--custom-attn", action="store_true", help="use the hand-written attention")
ap.add_argument("--device", default=None, help="cuda / mps / cpu (default: best available)") 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) ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args(argv) args = ap.parse_args(argv)
@@ -148,80 +147,79 @@ def main(argv: list[str] | None = None) -> None:
tok = load(args.tokenizer) tok = load(args.tokenizer)
V = tok.get_vocab_size() V = tok.get_vocab_size()
print(f"device: {dev} vocab: {V}") print(f"device: {dev} vocab: {V}")
if args.overfit: if args.overfit:
raise SystemExit(0 if overfit(tok, args.data, args.overfit, dev) else 1) raise SystemExit(0 if overfit(args, tok, dev) else 1)
torch.manual_seed(args.seed) torch.manual_seed(args.seed)
rng = random.Random(args.seed) rng = random.Random(args.seed)
max_len = 256
print("tokenizing data ...") print("tokenizing data ...")
train = encode_pairs(tok, read_pairs(f"{args.data}/train.jsonl")) train_pairs = read_pairs(f"{args.data}/train.jsonl")
valid_pairs = read_pairs(f"{args.data}/valid.jsonl", 2000) valid_pairs = read_pairs(f"{args.data}/valid.jsonl")[:2000]
valid = encode_pairs(tok, valid_pairs) 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):,}") print(f"train pairs: {len(train):,} valid pairs: {len(valid):,}")
model_args = dict(vocab=V, **CONFIGS[args.config], max_len=MAX_LEN, drop=args.dropout) model_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) model = Seq2Seq(**model_args).to(dev)
print(f"model: {args.config}, {count_params(model) / 1e6:.1f}M parameters") 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)) opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01, betas=(0.9, 0.98))
sched = torch.optim.lr_scheduler.LambdaLR(opt, warmup_cosine(args.warmup, args.steps)) sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda(args.warmup, args.steps))
out = pathlib.Path(args.out) out = pathlib.Path(args.out)
out.mkdir(parents=True, exist_ok=True) out.mkdir(parents=True, exist_ok=True)
log_file = (out / "train_log.csv").open("w", newline="") log_f = (out / "train_log.csv").open("w", newline="")
log = csv.writer(log_file) log = csv.writer(log_f)
log.writerow(["step", "lr", "train_loss", "val_loss", "sample_exact", "elapsed_s"]) log.writerow(["step", "lr", "train_loss", "val_loss", "sample_exact", "elapsed_s"])
samples = valid_pairs[:20] sample = valid_pairs[:20]
best = float("inf") best = float("inf")
run_loss, run_n = 0.0, 0
t0 = time.time() t0 = time.time()
it = batches(train, args.batch, rng) run_loss, run_n = 0.0, 0
model.train() model.train()
step = 0 it = batches(train, args.batch, rng)
try: try:
for step in range(1, args.steps + 1): for step in range(1, args.steps + 1):
src, tgt = (x.to(dev) for x in next(it)) src, tgt = next(it)
loss = loss_fn(model, src, tgt) src, tgt = src.to(dev), tgt.to(dev)
loss = loss_fn(model, src, tgt, V)
opt.zero_grad(set_to_none=True) opt.zero_grad(set_to_none=True)
loss.backward() loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step() opt.step()
sched.step() sched.step()
if step % 10 == 0: # .item() syncs with the GPU, so don't do it every step run_loss += loss.item() if step % 10 == 0 else 0.0
run_loss += loss.item() run_n += step % 10 == 0
run_n += 1
if step % 100 == 0: if step % 100 == 0:
el = time.time() - t0 el = time.time() - t0
print( eta = el / step * (args.steps - step)
f"step {step:6d}/{args.steps} loss {run_loss / max(run_n, 1):.4f} " print(f"step {step:6d}/{args.steps} loss {run_loss / max(run_n, 1):.4f} "
f"lr {sched.get_last_lr()[0]:.2e} {step / el:.1f} it/s " f"lr {sched.get_last_lr()[0]:.2e} {step / el:.1f} it/s eta {eta / 60:.1f} min", flush=True)
f"eta {el / step * (args.steps - step) / 60:.1f} min",
flush=True,
)
if step % args.eval_every == 0 or step == args.steps: if step % args.eval_every == 0 or step == args.steps:
vl = val_loss(model, valid, dev) vl = val_loss(model, valid, V, dev)
preds = translate_batch(model, tok, [en for en, _ in samples]) preds = translate_batch(model, tok, [p[0] for p in sample])
exact = sum(p == typ for p, (_, typ) in zip(preds, samples)) exact = sum(p == t for p, (_, t) in zip(preds, sample))
print(f"--- step {step}: val loss {vl:.4f}, sample exact {exact}/{len(samples)}") print(f"--- step {step}: val loss {vl:.4f}, sample exact {exact}/{len(sample)}")
for (en, typ), p in list(zip(samples, preds))[:5]: for (en, typ), p in list(zip(sample, preds))[:5]:
print(f" {'OK ' if p == typ else 'BAD'} {en!r}\n -> {p}") print(f" {'OK ' if p == typ else 'BAD'} {en!r}\n -> {p}")
log.writerow( log.writerow([step, sched.get_last_lr()[0], run_loss / max(run_n, 1), vl, exact, round(time.time() - t0)])
[step, sched.get_last_lr()[0], run_loss / max(run_n, 1), vl, exact, round(time.time() - t0)] log_f.flush()
)
log_file.flush()
run_loss, run_n = 0.0, 0 run_loss, run_n = 0.0, 0
save(out / "last.pt", model, model_args, step=step, val_loss=vl) extra = {"step": step, "val_loss": vl, "config": args.config}
save(out / "last.pt", model, model_args, extra)
if vl < best: if vl < best:
best = vl best = vl
save(out / "model.pt", model, model_args, step=step, val_loss=vl) save(out / "model.pt", model, model_args, extra)
model.train() model.train()
except KeyboardInterrupt: except KeyboardInterrupt:
print("\ninterrupted: saving artifacts/last.pt") print("\ninterrupted -- saving checkpoint")
save(out / "last.pt", model, model_args, step=step) save(out / "last.pt", model, model_args, {"step": step, "config": args.config})
if not (out / "model.pt").exists(): if not (out / "model.pt").exists():
save(out / "model.pt", model, model_args, step=step) save(out / "model.pt", model, model_args, {"step": step, "config": args.config})
log_file.close() log_f.close()
print(f"done. best val loss {best:.4f} -> {out / 'model.pt'}") print(f"done. best val loss {best:.4f}. checkpoint: {out / 'model.pt'}")
if __name__ == "__main__": if __name__ == "__main__":
+237 -44
View File
@@ -1,100 +1,293 @@
"""Inference: English -> Typst with greedy decoding, one token at a time. """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 "the integral from 0 to infinity of e to the minus x squared dx"
uv run isotope # interactive prompt (Ctrl-D to quit) uv run isotope # interactive prompt
uv run isotope --check "x squared plus 1" # also compile the output with typst uv run isotope --beam 4 --check "x squared plus y squared equals r squared"
""" """
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import pathlib
import sys import sys
import time
import torch import torch
from .model import Seq2Seq, pick_device from .model import Seq2Seq, pick_device
from .tokenizer import BOS, EOS, PAD, load from .tokenizer import BOS, EOS, PAD, load
DEFAULT_CKPT = "artifacts/model.pt"
DEFAULT_TOK = "artifacts/tokenizer.json"
def load_model(ckpt: str = "artifacts/model.pt", tok_path: str = "artifacts/tokenizer.json", device: str | None = None):
try: # --------------------------------------------------------------------------------------
state = torch.load(ckpt, map_location="cpu", weights_only=False) # loading
except FileNotFoundError: # --------------------------------------------------------------------------------------
raise SystemExit(f"No trained model at {ckpt}. Train one first: uv run isotope-train") from None
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 = Seq2Seq(**state["model_args"])
model.load_state_dict(state["model"]) model.load_state_dict(state["model"])
dev = device or pick_device() model.to(dev).eval()
return model.to(dev).eval(), load(tok_path) 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() @torch.no_grad()
def translate_batch(model: Seq2Seq, tok, texts: list[str], max_len: int = 160) -> list[str]: def translate_batch(model, tok, texts: list[str], max_len: int = 128, constrained: bool = True) -> list[str]:
"""Greedy decoding: encode once, then repeatedly append the most likely next token.""" """Greedy decoding for a batch of sentences."""
model.eval() model.eval()
dev = next(model.parameters()).device dev = next(model.parameters()).device
ids = [tok.encode(t).ids[: model.max_len] for t in texts] src = _encode_src(tok, texts, model.max_len, dev)
src = torch.full((len(ids), max(map(len, ids))), PAD, dtype=torch.long)
for i, x in enumerate(ids):
src[i, : len(x)] = torch.tensor(x)
src = src.to(dev)
memory = model.encode(src) memory = model.encode(src)
src_pad = src == PAD src_pad = src == PAD
B = len(texts)
out = torch.full((len(texts), 1), BOS, dtype=torch.long, device=dev) out = torch.full((B, 1), BOS, dtype=torch.long, device=dev)
done = torch.zeros(len(texts), dtype=torch.bool, 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)): for _ in range(min(max_len, model.max_len - 1)):
logits = model.decode(out, memory, src_pad)[:, -1] # only the last position predicts what comes next 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 = logits.argmax(-1)
nxt = torch.where(done, PAD, nxt) # finished rows just pad nxt = torch.where(done, torch.full_like(nxt, PAD), nxt)
out = torch.cat([out, nxt[:, None]], dim=1) if pc is not None:
balance = balance + torch.where(done, 0, pc.delta[nxt])
out = torch.cat([out, nxt[:, None]], 1)
done |= nxt == EOS done |= nxt == EOS
if done.all(): if bool(done.all()):
break break
res = []
results = [] for row in out.tolist():
for row in out[:, 1:].tolist(): row = row[1:]
if EOS in row: if EOS in row:
row = row[: row.index(EOS)] row = row[: row.index(EOS)]
results.append(tok.decode([t for t in row if t != PAD]).strip()) res.append(tok.decode([t for t in row if t != PAD]).strip())
return results return res
def translate(model: Seq2Seq, tok, text: str) -> str: @torch.no_grad()
return translate_batch(model, tok, [text])[0] 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: def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(prog="isotope", description="Translate spoken-English math into Typst math.") 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("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("--check", action="store_true", help="also run `typst compile` on the output")
ap.add_argument("--ckpt", default="artifacts/model.pt") ap.add_argument("--raw", action="store_true", help="print without the surrounding $ ... $")
ap.add_argument("--tokenizer", default="artifacts/tokenizer.json") ap.add_argument("--ckpt", default=None)
ap.add_argument("--tokenizer", default=None)
args = ap.parse_args(argv) args = ap.parse_args(argv)
model, tok = load_model(args.ckpt, args.tokenizer) 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: def run(line: str) -> None:
typ = translate(model, tok, line) t0 = time.perf_counter()
print(f"${typ}$") typ = translate(model, tok, line, beam=opts["beam"], constrained=opts["constrain"])
if args.check: dt = time.perf_counter() - t0
print(typ if opts["raw"] else f"${typ}$")
if opts["check"]:
from .validate import compiles from .validate import compiles
print(" compiles:", "yes" if compiles(typ) else "NO") print(" compiles:", "yes" if compiles(typ) else "NO")
if opts["time"]:
print(f" ({dt * 1000:.0f} ms)")
if args.text: if args.text:
run(" ".join(args.text)) run(" ".join(args.text))
return return
interactive = sys.stdin.isatty() if not sys.stdin.isatty():
if interactive: for line in sys.stdin:
print("isotope: type English math, get Typst. Ctrl-D to quit.") 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: while True:
try: try:
line = input("> " if interactive else "").strip() line = input("> ").strip()
except KeyboardInterrupt:
print()
continue
except EOFError: except EOFError:
print()
break break
if line: 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) 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__": if __name__ == "__main__":
main() main()
+64 -26
View File
@@ -1,7 +1,8 @@
"""Check Typst math with the real `typst` CLI, so a renderer bug can never teach the model broken Typst. """Check Typst math with the real `typst` CLI.
compiles(math) -> bool for one equation (the guide's simple version) compiles(math) -> bool, one equation (simple version from the guide)
compiles_many(maths) -> list[bool]; many equations per file, split in half on failure to find the bad ones 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 from __future__ import annotations
@@ -12,46 +13,83 @@ import subprocess
import tempfile import tempfile
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
PAGE = "#set page(width: auto, height: auto, margin: 4pt)\n"
def _typst() -> str: def _typst() -> str:
exe = shutil.which("typst") exe = shutil.which("typst")
if exe is None: if exe is None:
raise SystemExit("The `typst` CLI is not installed. Install it with: brew install typst") raise SystemExit("The `typst` CLI is not installed. Install it with: brew install typst")
return exe return exe
def _safe(math: str) -> bool: def _ok_math(math: str) -> bool:
# a stray `$` would end the math block early and let arbitrary markup through # A stray `$` would end the math block early and let arbitrary markup through.
return math.strip() != "" and "$" not in math and "\n" not in math return "$" not in math and "\n" not in math and math.strip() != ""
def _compile(maths: list[str]) -> bool:
with tempfile.TemporaryDirectory() as d:
src = pathlib.Path(d) / "t.typ"
src.write_text("".join(f"${m}$\n\n" for m in maths))
return subprocess.run([_typst(), "compile", str(src)], capture_output=True, check=False).returncode == 0
def compiles(math: str) -> bool: def compiles(math: str) -> bool:
return _safe(math) and _compile([math]) 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 _bisect(maths: list[str]) -> list[bool]: def _batch_ok(maths: list[str]) -> bool:
if _compile(maths): 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) return [True] * len(maths)
if len(maths) == 1: if len(maths) == 1:
return [False] return [False]
mid = len(maths) // 2 mid = len(maths) // 2
return _bisect(maths[:mid]) + _bisect(maths[mid:]) return _check(maths[:mid]) + _check(maths[mid:])
def compiles_many(maths: list[str], batch: int = 500, workers: int = 8) -> list[bool]: 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() _typst()
ok = [False] * len(maths) result = [False] * len(maths)
idx = [i for i, m in enumerate(maths) if _safe(m)] 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)] chunks = [idx[i:i + batch] for i in range(0, len(idx), batch)]
with ThreadPoolExecutor(workers) as ex: with ThreadPoolExecutor(workers) as ex:
for chunk, res in zip(chunks, ex.map(lambda c: _bisect([maths[i] for i in c]), chunks)): for chunk, oks in zip(chunks, ex.map(lambda c: _check([maths[i] for i in c]), chunks)):
for i, r in zip(chunk, res): for i, ok in zip(chunk, oks):
ok[i] = r result[i] = ok
return 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
+49 -20
View File
@@ -1,26 +1,55 @@
import torch import torch
from torch import nn
from isotope_typst.model import Seq2Seq, causal_mask from isotope_typst.model import CONFIGS, MultiHeadAttention, Seq2Seq, causal_mask, count_params, estimate_params
def test_causal_mask(): def test_custom_attention_matches_pytorch():
m = causal_mask(4)
assert not m[2, :3].any() and m[2, 3] # row 2 sees 0..2, not 3
def test_forward_shape():
model = Seq2Seq(vocab=50, d=32, heads=4, layers=2, ff=64, drop=0.0)
src, tgt = torch.randint(4, 50, (3, 7)), torch.randint(4, 50, (3, 5))
assert model(src, tgt).shape == (3, 5, 50)
def test_decoder_cannot_see_the_future():
"""Changing a later target token must not change the logits at earlier positions."""
torch.manual_seed(0) torch.manual_seed(0)
model = Seq2Seq(vocab=50, d=32, heads=4, layers=2, ff=64, drop=0.0).eval() d, h = 64, 4
src = torch.randint(4, 50, (1, 6)) mine = MultiHeadAttention(d, h)
a = torch.randint(4, 50, (1, 5)) ref = nn.MultiheadAttention(d, h, batch_first=True)
b = a.clone()
b[0, 4] = (a[0, 4] + 1) % 46 + 4
with torch.no_grad(): with torch.no_grad():
assert torch.allclose(model(src, a)[0, :4], model(src, b)[0, :4], atol=1e-5) 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
+30 -16
View File
@@ -1,34 +1,48 @@
import collections
import random import random
from isotope_typst.ast import Frac, Integral, Neg, Num, Pow, Var from isotope_typst.ast import Frac, Integral, Neg, Num, Pow, Var
from isotope_typst.generate import TreeGen, split_of from isotope_typst.generate import TreeGen, split_of
from isotope_typst.render import to_english, to_typst from isotope_typst.render import to_english, to_typst
from isotope_typst.validate import compiles_many 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(): def test_guide_example():
t = Integral(Pow(Var("e"), Neg(Pow(Var("x"), Num(2)))), "x", Num(0), Var("infinity")) assert to_typst(guide_tree()) == "integral_0^infinity e^(-x^2) dif x"
assert to_typst(t) == "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(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(): def test_generated_typst_compiles():
gen = TreeGen(random.Random(0)) gen = TreeGen(random.Random(1))
maths = [to_typst(gen.tree()) for _ in range(500)] maths = [to_typst(gen.tree()) for _ in range(300)]
assert all(compiles_many(maths)) assert all(compiles_many(maths))
def test_english_is_unambiguous(): def test_basic_generator_only_uses_basic_nodes():
"""No sentence may come from two trees with different Typst: that would teach the model to guess.""" from isotope_typst.ast import walk
rng = random.Random(0) gen = TreeGen(random.Random(2), basic=True)
gen = TreeGen(rng) allowed = {"Num", "Var", "Neg", "Pow", "Frac", "Integral"}
seen = collections.defaultdict(set) for _ in range(300):
for _ in range(20000): assert {type(n).__name__ for n in walk(gen.tree())} <= allowed
t = gen.tree()
seen[to_english(t, rng, noise=False)].add(to_typst(t))
bad = {en: typs for en, typs in seen.items() if len(typs) > 1} def test_compile_check_rejects_broken():
assert not bad, list(bad.items())[:5] assert compiles("x^2")
assert not compiles("frac(1, ")
assert compiles_many(["x", "sqrt(", "y"]) == [True, False, True]
def test_split_is_by_structure(): def test_split_is_by_structure():
+38 -10
View File
@@ -1,17 +1,45 @@
import json
import pathlib
import random import random
import pytest
from isotope_typst.generate import TreeGen from isotope_typst.generate import TreeGen
from isotope_typst.render import to_english, to_typst from isotope_typst.render import to_english, to_typst
from isotope_typst.tokenizer import BOS, EOS, PAD, train from isotope_typst.tokenizer import train
def test_round_trip(tmp_path): @pytest.fixture(scope="module")
rng = random.Random(0) def tok(tmp_path_factory):
gen = TreeGen(rng) d = tmp_path_factory.mktemp("tok")
trees = [gen.tree() for _ in range(2000)] gen, rng = TreeGen(random.Random(0)), random.Random(0)
texts = [s for t in trees for s in (to_english(t, rng), to_typst(t))] lines = []
tok = train(texts, str(tmp_path / "tok.json"), vocab=1000) for _ in range(2000):
assert (tok.token_to_id("[PAD]"), tok.token_to_id("[BOS]"), tok.token_to_id("[EOS]")) == (PAD, BOS, EOS) t = gen.tree()
for t in trees[:1000]: # guide §5: decode(encode(s)) == s, or nothing downstream can be right lines += [to_english(t, rng), to_typst(t)]
s = 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 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
+884 -3
View File
File diff suppressed because it is too large. Load diff