Author SHA1 Message Date
paultalandClaude Opus 5.5 fa472f8abd Add clean Path A proof of concept
Spoken-English math to Typst with a small from-scratch encoder-decoder
Transformer, following the build guide: compile-checked synthetic data
generator, shared BPE tokenizer, nn.Transformer model, training loop with
an overfit sanity check, greedy decoding CLI, and evaluation on synthetic
and hand-written test sets. ./run.sh runs the whole pipeline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:14:06 +02:00
9 changed files with 94 additions and 275 deletions

No files matched your search

-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.
+51 -5
View File
@@ -1,13 +1,59 @@
# 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. **isotope-typst** is a Transformer model that translates math written in plain English into [Typst](https://typst.app) markup.
## Running it 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$`.
You need [uv](https://docs.astral.sh/uv/) and the Typst CLI (`brew install typst`). The current code is the **Path A proof of concept**: a small (~8M parameter) encoder–decoder Transformer trained from scratch on synthetic data, following the [build guide](https://git.paultal.online/paultal/generated-books/src/branch/main/isotope-typst-guide.pdf).
## Run it
Needs [uv](https://docs.astral.sh/uv/) and the Typst CLI (`brew install typst`).
```bash ```bash
./run.sh # generate data, train, and evaluate (~20 min on an M-series Mac) ./run.sh # everything, ~20 min on an M-series Mac
uv run isotope "x squared plus 1" # translate a sentence ./run.sh --quick # smoke run, ~2 min, tiny model
uv run isotope "x squared plus y squared equals r squared"
uv run isotope # interactive prompt uv run isotope # interactive prompt
``` ```
Or one stage at a time:
| guide | command | what it does |
|---|---|---|
| §4 data | `uv run isotope-gen -n 200000` | random trees → English + Typst pairs, compile-checked, into `data/` |
| §5 tokens | `uv run isotope-tokenizer` | byte-level BPE shared by both sides → `artifacts/tokenizer.json` |
| §7 sanity | `uv run isotope-train --overfit 100` | a tiny model must memorise 100 pairs, or the pipeline has a bug |
| §7 training | `uv run isotope-train` | `--config tiny/small/medium`, `--steps`, Ctrl-C saves a checkpoint |
| §8 inference | `uv run isotope "..."` | greedy decoding; `--check` compiles the output |
| §9 evaluation | `uv run isotope-eval` | exact match and compile rate on synthetic test + `eval/hand_test.jsonl` |
| tests | `uv run pytest` | renderer compiles, English is unambiguous, tokenizer round-trips, causal mask works |
`data/` and `artifacts/` are generated and not tracked in git.
## Code
```
src/isotope_typst/
ast.py expression nodes: Var Num Neg Add Sub Mul Pow Frac Sqrt Func Integral Sum Lim Eq
render.py to_typst() (deterministic) and to_english() (random phrasings)
generate.py random trees -> data/{train,valid,test}.jsonl, split by a hash of the Typst string
validate.py `typst compile` checks
tokenizer.py BPE tokenizer
model.py Seq2Seq on nn.Transformer, with encode()/decode() for inference
train.py teacher forcing, AdamW, warmup + cosine, checkpoints, train_log.csv
translate.py greedy decoding + CLI
evaluate.py metrics + failure dumps in artifacts/errors_*.txt
eval/hand_test.jsonl hand-written test sentences: never generated, never trained on
```
## Conventions the English follows
* "e to the minus x squared" means `e^(-x^2)`: a bare exponent takes everything after it (guide Appendix A, Q1).
* Grouping is said with "( … )", "open paren … close paren", or, at the end of a phrase, "the quantity …".
* "sine of x squared" means `sin(x^2)`; `sin(x)^2` is "sine squared of x".
* Integrals, sums and limits appear only at the top level of an expression.
## Not in this PoC (yet)
Beam search, constrained decoding, render-match evaluation, a hand-written attention module, paraphrase augmentation, and Path B fine-tuning.
+32 -102
View File
@@ -1,102 +1,32 @@
{"en": "the integral from 0 to infinity of e to the minus x squared dx", "typ": "integral_0^infinity e^(-x^2) dif x", "cat": "bigop"} {"en": "the integral from 0 to infinity of e to the minus x squared dx", "typ": "integral_0^infinity e^(-x^2) dif x"}
{"en": "x squared plus y squared equals r squared", "typ": "x^2 + y^2 = r^2", "cat": "equation"} {"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", "cat": "equation"} {"en": "a squared plus b squared equals c squared", "typ": "a^2 + b^2 = c^2"}
{"en": "e to the x", "typ": "e^x", "cat": "basic"} {"en": "e to the x", "typ": "e^x"}
{"en": "e to the minus x", "typ": "e^(-x)", "cat": "basic"} {"en": "e to the minus x", "typ": "e^(-x)"}
{"en": "one over x", "typ": "frac(1, x)", "cat": "basic"} {"en": "one over x", "typ": "frac(1, x)"}
{"en": "x over 2", "typ": "frac(x, 2)", "cat": "basic"} {"en": "x over 2", "typ": "frac(x, 2)"}
{"en": "the square root of 2", "typ": "sqrt(2)", "cat": "basic"} {"en": "the square root of 2", "typ": "sqrt(2)"}
{"en": "square root of x plus one", "typ": "sqrt(x) + 1", "cat": "basic"} {"en": "square root of x plus one", "typ": "sqrt(x) + 1"}
{"en": "the square root of the quantity x plus 1", "typ": "sqrt(x + 1)", "cat": "basic"} {"en": "the square root of the quantity x plus 1", "typ": "sqrt(x + 1)"}
{"en": "sine of x", "typ": "sin(x)", "cat": "basic"} {"en": "sine of x", "typ": "sin(x)"}
{"en": "sin x squared", "typ": "sin(x^2)", "cat": "basic"} {"en": "sin x squared", "typ": "sin(x^2)"}
{"en": "sine squared of x plus cosine squared of x equals 1", "typ": "sin(x)^2 + cos(x)^2 = 1", "cat": "equation"} {"en": "sine squared of x plus cosine squared of x equals 1", "typ": "sin(x)^2 + cos(x)^2 = 1"}
{"en": "ln of x", "typ": "ln(x)", "cat": "basic"} {"en": "ln of x", "typ": "ln(x)"}
{"en": "2 x plus 3", "typ": "2 x + 3", "cat": "basic"} {"en": "2 x plus 3", "typ": "2 x + 3"}
{"en": "3x squared minus 2x plus 1", "typ": "3 x^2 - 2 x + 1", "cat": "basic"} {"en": "3x squared minus 2x plus 1", "typ": "3 x^2 - 2 x + 1"}
{"en": "y equals m x plus b", "typ": "y = m x + b", "cat": "equation"} {"en": "y equals m x plus b", "typ": "y = m x + b"}
{"en": "the integral of x squared dx", "typ": "integral x^2 dif x", "cat": "bigop"} {"en": "the integral of x squared dx", "typ": "integral x^2 dif x"}
{"en": "the integral from 0 to 1 of x squared dx", "typ": "integral_0^1 x^2 dif x", "cat": "bigop"} {"en": "the integral from 0 to 1 of x squared dx", "typ": "integral_0^1 x^2 dif x"}
{"en": "integral from 0 to pi of sine of x dx", "typ": "integral_0^pi sin(x) dif x", "cat": "bigop"} {"en": "integral from 0 to pi of sine of x dx", "typ": "integral_0^pi sin(x) dif x"}
{"en": "the sum from i equals 1 to n of i", "typ": "sum_(i = 1)^n i", "cat": "bigop"} {"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", "cat": "bigop"} {"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)", "cat": "bigop"} {"en": "the limit as x approaches 0 of sine of x over x", "typ": "lim_(x -> 0) frac(sin(x), x)"}
{"en": "the limit as n goes to infinity of 1 over n", "typ": "lim_(n -> infinity) frac(1, n)", "cat": "bigop"} {"en": "the limit as n goes to infinity of 1 over n", "typ": "lim_(n -> infinity) frac(1, n)"}
{"en": "minus b over 2 a", "typ": "frac(-b, 2 a)", "cat": "basic"} {"en": "minus b over 2 a", "typ": "frac(-b, 2 a)"}
{"en": "x to the n", "typ": "x^n", "cat": "basic"} {"en": "x to the n", "typ": "x^n"}
{"en": "x cubed minus 1", "typ": "x^3 - 1", "cat": "basic"} {"en": "x cubed minus 1", "typ": "x^3 - 1"}
{"en": "alpha plus beta", "typ": "alpha + beta", "cat": "basic"} {"en": "alpha plus beta", "typ": "alpha + beta"}
{"en": "2 pi r", "typ": "2 pi r", "cat": "basic"} {"en": "2 pi r", "typ": "2 pi r"}
{"en": "e to the i pi plus 1 equals 0", "typ": "e^(i pi) + 1 = 0", "cat": "equation"} {"en": "e to the i pi plus 1 equals 0", "typ": "e^(i pi) + 1 = 0"}
{"en": "one half", "typ": "frac(1, 2)", "cat": "basic"} {"en": "one half", "typ": "frac(1, 2)"}
{"en": "f equals m a", "typ": "f = m a", "cat": "equation"} {"en": "f equals m a", "typ": "f = m a"}
{"en": "x cubed", "typ": "x^3", "cat": "basic"}
{"en": "tangent of x", "typ": "tan(x)", "cat": "basic"}
{"en": "2 over 3", "typ": "frac(2, 3)", "cat": "basic"}
{"en": "minus x", "typ": "-x", "cat": "basic"}
{"en": "x squared plus y squared equals z", "typ": "x^2 + y^2 = z", "cat": "equation"}
{"en": "alpha squared plus beta squared equals gamma squared", "typ": "alpha^2 + beta^2 = gamma^2", "cat": "equation"}
{"en": "x squared plus y squared is equal to r squared", "typ": "x^2 + y^2 = r^2", "cat": "equation"}
{"en": "2 x plus 3 equals 7", "typ": "2 x + 3 = 7", "cat": "equation"}
{"en": "x squared minus 1 equals 0", "typ": "x^2 - 1 = 0", "cat": "equation"}
{"en": "a x squared plus b x plus c equals 0", "typ": "a x^2 + b x + c = 0", "cat": "equation"}
{"en": "x over 2 plus 1 equals y", "typ": "frac(x, 2) + 1 = y", "cat": "equation"}
{"en": "the square root of the quantity x plus 1 equals 3", "typ": "sqrt(x + 1) = 3", "cat": "equation"}
{"en": "x over y plus z over w", "typ": "frac(x, y) + frac(z, w)", "cat": "variables"}
{"en": "u squared plus v squared equals w squared", "typ": "u^2 + v^2 = w^2", "cat": "variables"}
{"en": "a plus b plus c plus d", "typ": "a + b + c + d", "cat": "variables"}
{"en": "epsilon over delta", "typ": "frac(epsilon, delta)", "cat": "variables"}
{"en": "x times y times z times w", "typ": "x y z w", "cat": "variables"}
{"en": "rho g h", "typ": "rho g h", "cat": "variables"}
{"en": "q over r", "typ": "frac(q, r)", "cat": "variables"}
{"en": "g times h", "typ": "g h", "cat": "variables"}
{"en": "psi squared", "typ": "psi^2", "cat": "variables"}
{"en": "eta plus zeta", "typ": "eta + zeta", "cat": "variables"}
{"en": "kappa x", "typ": "kappa x", "cat": "variables"}
{"en": "nu over lambda", "typ": "frac(nu, lambda)", "cat": "variables"}
{"en": "chi squared", "typ": "chi^2", "cat": "variables"}
{"en": "xi plus 1", "typ": "xi + 1", "cat": "variables"}
{"en": "w to the n", "typ": "w^n", "cat": "variables"}
{"en": "F equals m a", "typ": "F = m a", "cat": "variables"}
{"en": "The square root of x", "typ": "sqrt(x)", "cat": "robustness"}
{"en": "Sine of x", "typ": "sin(x)", "cat": "robustness"}
{"en": "x squared plus one.", "typ": "x^2 + 1", "cat": "robustness"}
{"en": "x squared plus one?", "typ": "x^2 + 1", "cat": "robustness"}
{"en": "uh x squared plus um one", "typ": "x^2 + 1", "cat": "robustness"}
{"en": "so like x over 2", "typ": "frac(x, 2)", "cat": "robustness"}
{"en": "x sqaured plus one", "typ": "x^2 + 1", "cat": "robustness"}
{"en": "X SQUARED PLUS ONE", "typ": "x^2 + 1", "cat": "robustness"}
{"en": "x squared plus one", "typ": "x^2 + 1", "cat": "robustness"}
{"en": "x^2", "typ": "x^2", "cat": "robustness"}
{"en": "x ** 2", "typ": "x^2", "cat": "robustness"}
{"en": "sqrt(x)", "typ": "sqrt(x)", "cat": "robustness"}
{"en": "1/x", "typ": "frac(1, x)", "cat": "robustness"}
{"en": "the integral from 0 to 2 pi of sine of theta d theta", "typ": "integral_0^(2 pi) sin(theta) dif theta", "cat": "bounds"}
{"en": "the integral from minus pi to pi of cosine of x dx", "typ": "integral_(-pi)^pi cos(x) dif x", "cat": "bounds"}
{"en": "the integral from a to a plus h of x dx", "typ": "integral_a^(a + h) x dif x", "cat": "bounds"}
{"en": "the integral from 0 to x squared of t dt", "typ": "integral_0^(x^2) t dif t", "cat": "bounds"}
{"en": "the sum from k equals 1 to n plus 1 of k", "typ": "sum_(k = 1)^(n + 1) k", "cat": "bounds"}
{"en": "the sum from i equals 0 to 2 n of i", "typ": "sum_(i = 0)^(2 n) i", "cat": "bounds"}
{"en": "the integral of e to the x dx equals e to the x plus c", "typ": "integral e^x dif x = e^x + c", "cat": "bigop-lhs"}
{"en": "the sum from i equals 1 to n of i equals n times (n plus 1) over 2", "typ": "sum_(i = 1)^n i = frac(n (n + 1), 2)", "cat": "bigop-lhs"}
{"en": "the limit as x approaches 0 of sine of x over x equals 1", "typ": "lim_(x -> 0) frac(sin(x), x) = 1", "cat": "bigop-lhs"}
{"en": "the integral from 0 to 1 of x dx equals one half", "typ": "integral_0^1 x dif x = frac(1, 2)", "cat": "bigop-lhs"}
{"en": "1 plus 2 plus 3 plus 4 plus 5 plus 6 plus 7 plus 8 plus 9 plus 10 plus 11 plus 12", "typ": "1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12", "cat": "long"}
{"en": "a plus b plus c plus d plus e plus f plus g plus h", "typ": "a + b + c + d + e + f + g + h", "cat": "long"}
{"en": "x squared plus y squared plus z squared plus w squared plus t squared plus u squared", "typ": "x^2 + y^2 + z^2 + w^2 + t^2 + u^2", "cat": "long"}
{"en": "x plus x squared plus x cubed plus x to the fourth plus x to the fifth", "typ": "x + x^2 + x^3 + x^4 + x^5", "cat": "long"}
{"en": "a times b times c times d times e times f", "typ": "a b c d e f", "cat": "long"}
{"en": "1 minus x plus x squared minus x cubed plus x to the fourth minus x to the fifth", "typ": "1 - x + x^2 - x^3 + x^4 - x^5", "cat": "long"}
{"en": "f of x", "typ": "f(x)", "cat": "new-math"}
{"en": "x sub i", "typ": "x_i", "cat": "new-math"}
{"en": "n factorial", "typ": "n!", "cat": "new-math"}
{"en": "the cube root of x", "typ": "root(3, x)", "cat": "new-math"}
{"en": "x is less than y", "typ": "x < y", "cat": "new-math"}
{"en": "a is not equal to b", "typ": "a != b", "cat": "new-math"}
{"en": "the absolute value of x", "typ": "abs(x)", "cat": "new-math"}
{"en": "one third", "typ": "frac(1, 3)", "cat": "numbers"}
{"en": "two thirds", "typ": "frac(2, 3)", "cat": "numbers"}
{"en": "three quarters", "typ": "frac(3, 4)", "cat": "numbers"}
{"en": "twenty one", "typ": "21", "cat": "numbers"}
{"en": "forty two", "typ": "42", "cat": "numbers"}
{"en": "ninety nine plus one", "typ": "99 + 1", "cat": "numbers"}
+1 -8
View File
@@ -106,14 +106,7 @@ class Eq(Node):
right: Node right: Node
# lowercase Greek letters usable as variables; pi is a constant, and omicron is left out because it looks like o GREEK = ["alpha", "beta", "gamma", "delta", "theta", "lambda", "mu", "sigma", "phi", "omega"]
GREEK = [
"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu",
"nu", "xi", "rho", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega",
] # fmt: skip
# e is a constant (e^x), and d is kept free for "dx" and later derivatives (#8)
LATIN = [c for c in "abcdefghijklmnopqrstuvwxyz" if c not in "de"]
UPPER = list("ABCFGHKLMNPQRSTVXY")
FUNCS = ["sin", "cos", "tan", "ln", "log", "exp"] FUNCS = ["sin", "cos", "tan", "ln", "log", "exp"]
BIG_OPS = (Integral, Sum, Lim) BIG_OPS = (Integral, Sum, Lim)
+5 -33
View File
@@ -1,17 +1,13 @@
"""Evaluate: exact match, compile rate and bracket balance, on the synthetic test split and the hand-written set. """Evaluate: exact match and compile rate, on the synthetic test split and the hand-written set.
uv run isotope-eval uv run isotope-eval
"compiles" alone says little: Typst math accepts stray letters and even unbalanced parens, so "balanced" checks
the brackets separately. Hand-test rows carry a "cat" (equation, variables, long, ...) and are broken down by it.
Failures go to artifacts/errors_<set>.txt: read them, group them, fix the generator (guide §9). Failures go to artifacts/errors_<set>.txt: read them, group them, fix the generator (guide §9).
""" """
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import collections
import json import json
import pathlib import pathlib
import random import random
@@ -24,20 +20,6 @@ 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()]
PAIRS = {")": "(", "]": "[", "}": "{"}
def balanced(math: str) -> bool:
"""Every (, [ and { is closed, in order. Typst renders "(x + 1)^2 + 1)^2" without complaint; this does not."""
stack: list[str] = []
for ch in math:
if ch in "([{":
stack.append(ch)
elif ch in PAIRS and (not stack or stack.pop() != PAIRS[ch]):
return False
return not stack
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_batch
@@ -58,30 +40,20 @@ def main(argv: list[str] | None = None) -> None:
if pathlib.Path(args.hand).exists(): if pathlib.Path(args.hand).exists():
sets["hand"] = read_jsonl(args.hand) sets["hand"] = read_jsonl(args.hand)
print(f"{'set':<12}{'n':>6}{'exact':>9}{'compiles':>10}{'balanced':>10}") print(f"{'set':<12}{'n':>6}{'exact':>9}{'compiles':>10}")
for name, rows in sets.items(): for name, rows in sets.items():
preds = [] preds = []
for i in range(0, len(rows), 64): for i in range(0, len(rows), 64):
preds += translate_batch(model, tok, [r["en"] for r in rows[i : i + 64]]) preds += translate_batch(model, tok, [r["en"] for r in rows[i : i + 64]])
exact = [p == r["typ"] for p, r in zip(preds, rows)] exact = [p == r["typ"] for p, r in zip(preds, rows)]
comp = compiles_many(preds) comp = compiles_many(preds)
bal = [balanced(p) for p in preds]
n = len(rows) n = len(rows)
print(f"{name:<12}{n:>6}{sum(exact) / n:>9.1%}{sum(comp) / n:>10.1%}{sum(bal) / n:>10.1%}") print(f"{name:<12}{n:>6}{sum(exact) / n:>9.1%}{sum(comp) / n:>10.1%}")
by_cat: dict[str, list[bool]] = collections.defaultdict(list)
for r, e in zip(rows, exact):
if "cat" in r:
by_cat[r["cat"]].append(e)
for cat, es in sorted(by_cat.items()):
print(f" {cat:<10}{len(es):>6}{sum(es) / len(es):>9.1%}")
lines = [f"{n - sum(exact)} of {n} not exact\n"] lines = [f"{n - sum(exact)} of {n} not exact\n"]
for r, p, e, c, b in zip(rows, preds, exact, comp, bal): for r, p, e, c in zip(rows, preds, exact, comp):
if not e: if not e:
flags = ("" if c else " [does not compile]") + ("" if b else " [unbalanced]") lines.append(f"EN: {r['en']}\nWANT: {r['typ']}\nGOT: {p}{'' if c else ' [does not compile]'}\n")
cat = f" ({r['cat']})" if "cat" in r else ""
lines.append(f"EN: {r['en']}{cat}\nWANT: {r['typ']}\nGOT: {p}{flags}\n")
path = pathlib.Path(args.out) / f"errors_{name}.txt" path = pathlib.Path(args.out) / f"errors_{name}.txt"
path.write_text("\n".join(lines)) path.write_text("\n".join(lines))
print(f"\nfailures: {args.out}/errors_*.txt") print(f"\nfailures: {args.out}/errors_*.txt")
+4 -64
View File
@@ -16,28 +16,7 @@ import pathlib
import random import random
from typing import ClassVar from typing import ClassVar
from .ast import ( from .ast import FUNCS, GREEK, Add, Eq, Frac, Func, Integral, Lim, Mul, Neg, Node, Num, Pow, Sqrt, Sub, Sum, Var, walk
FUNCS,
GREEK,
LATIN,
UPPER,
Add,
Eq,
Frac,
Func,
Integral,
Lim,
Mul,
Neg,
Node,
Num,
Pow,
Sqrt,
Sub,
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
@@ -52,14 +31,8 @@ class TreeGen:
def var(self, prefer: str | None = None) -> Var: def var(self, prefer: str | None = None) -> Var:
if prefer and self.rng.random() < 0.6: # inside "integral ... dx", mostly use x if prefer and self.rng.random() < 0.6: # inside "integral ... dx", mostly use x
return Var(prefer) return Var(prefer)
r = self.rng.random() pool = ["x"] * 12 + ["y"] * 4 + ["z", "t", "a", "b", "c", "n", "k", "u", "r", "s", "m", "p"] + GREEK
if r < 0.45: # x and y stay the most common, as in real maths return Var(self.rng.choice(pool))
return Var("x" if r < 0.33 else "y")
if r < 0.80:
return Var(self.rng.choice(LATIN))
if r < 0.95:
return Var(self.rng.choice(GREEK))
return Var(self.rng.choice(UPPER))
def num(self) -> Num: def num(self) -> Num:
r = self.rng.random() r = self.rng.random()
@@ -159,45 +132,12 @@ class TreeGen:
to = r.choice([Num(0)] * 4 + [INF] * 4 + [Num(1), Var("a"), Neg(INF)]) to = r.choice([Num(0)] * 4 + [INF] * 4 + [Num(1), Var("a"), Neg(INF)])
return Lim(self.expr(max(depth, 1), v), v, to) return Lim(self.expr(max(depth, 1), v), v, to)
def term(self) -> Node:
"""One textbook-style term: x^2, 3 x, sin(x)^2, y, 7."""
r = self.rng
v = self.var()
match r.choices(["pow", "coef", "trig", "var", "num"], [5, 2, 1, 2, 1])[0]:
case "pow":
return Pow(v, Num(r.choice([2, 2, 2, 3])))
case "coef":
return Mul(Num(r.randint(2, 9)), r.choice([v, Pow(v, Num(2))]))
case "trig":
return Pow(Func(r.choice(["sin", "cos", "tan"]), v), Num(2))
case "var":
return v
return self.num()
def terms(self) -> Node:
"""A flat sum of 2-3 simple terms, like x^2 + y^2 or a x^2 + b x + c.
Random trees almost never produce these shapes, yet they are the most common left sides people say.
"""
r = self.rng
out = self.term()
for _ in range(r.choice([1, 1, 2])):
out = (Add if r.random() < 0.75 else Sub)(out, self.term())
return out
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] depth = r.choices([1, 2, 3, 4], [25, 40, 25, 10])[0]
e = self.big(depth - 1) if r.random() < 0.3 else self.expr(depth) e = self.big(depth - 1) if r.random() < 0.3 else self.expr(depth)
if r.random() < 0.2: if r.random() < 0.2:
# a long left side too ("x^2 + y^2 = r^2"), not only "y = ...": depth 2+ was never seen before (#2) lhs = r.choice([Var("y"), Var("f"), Var("x"), self.expr(r.choice([0, 1]))])
x = r.random()
if x < 0.35:
lhs: Node = r.choice([Var("y"), Var("f"), Var("x")])
elif x < 0.65:
lhs = self.terms()
else:
lhs = self.expr(r.choices([0, 1, 2, 3], [2, 3, 3, 2])[0])
return Eq(lhs, e) return Eq(lhs, e)
return e return e
-23
View File
@@ -1,23 +0,0 @@
import collections
from isotope_typst.evaluate import balanced, read_jsonl
from isotope_typst.validate import compiles_many
def test_balanced():
assert balanced("frac(sin(x), x)")
assert balanced("sum_(i = 1)^n i")
assert not balanced("(x + 1)^2 + 1)^2 + 1)^2")
assert not balanced("(-frac(b, 2)")
assert not balanced("x y z frac(x")
assert not balanced("(x]")
def test_hand_test_is_well_formed():
rows = read_jsonl("eval/hand_test.jsonl")
assert len(rows) >= 100
assert all(set(r) == {"en", "typ", "cat"} for r in rows)
assert all(balanced(r["typ"]) for r in rows)
assert all(compiles_many([r["typ"] for r in rows]))
dupes = [en for en, k in collections.Counter(r["en"] for r in rows).items() if k > 1]
assert not dupes, dupes
-12
View File
@@ -1,12 +0,0 @@
import random
from isotope_typst.ast import GREEK, LATIN, UPPER
from isotope_typst.generate import TreeGen
def test_variable_pool_covers_alphabet():
"""#4: any letter the model never saw gets spelled out letter by letter, so all of them must show up."""
gen = TreeGen(random.Random(0))
seen = {gen.var().name for _ in range(20000)}
assert set(LATIN) | set(GREEK) | set(UPPER) <= seen
assert "d" not in seen and "e" not in seen
+1 -10
View File
@@ -1,7 +1,7 @@
import collections import collections
import random import random
from isotope_typst.ast import Eq, Frac, Integral, Neg, Num, Pow, Var, walk 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_many
@@ -33,12 +33,3 @@ def test_english_is_unambiguous():
def test_split_is_by_structure(): def test_split_is_by_structure():
assert split_of("x^2") == split_of("x^2") assert split_of("x^2") == split_of("x^2")
def test_equations_have_long_left_sides():
"""#2: "x^2 + y^2 = r^2" needs left sides deeper than a single operator in the training data."""
gen = TreeGen(random.Random(0))
eqs = [t for t in (gen.tree() for _ in range(5000)) if isinstance(t, Eq)]
deep = [t for t in eqs if sum(1 for _ in walk(t.left)) >= 5]
assert len(deep) > 0.15 * len(eqs)
assert any(to_typst(t).startswith("x^2 + y^2 = ") for t in (gen.tree() for _ in range(200_000)))