Author SHA1 Message Date
paultal 58a2d8a1f1 Merge remote-tracking branch 'origin/main' into issue-4-variable-pool 2026-11-27 01:29:33 +02:00
paultal 40145d1fce Measure correctness: bracket check and a 102-row tagged hand test (#12)
isotope-eval reports a balanced column next to exact and compiles, and breaks hand-test exact match down by category. eval/hand_test.jsonl grows from 32 to 102 tagged rows built from the stress-test failures in #2 and #4-#9.

Closes #3

Co-authored-by: Paul Tal <[email protected]>
2026-11-27 01:29:25 +02:00
paultal 0651c7533e Use the whole alphabet and Greek alphabet for variables
The variable pool was 14 Latin letters plus 10 Greek ones, so w, v, q, g,
epsilon, rho, tau, ... were unknown to the model and got spelled out letter
by letter. Variables are now x/y (45%), any lowercase letter except e and d
(35%), any lowercase Greek letter except pi and omicron (15%), or a common
uppercase letter like N, F, A (5%).

e stays a constant and d is kept free for dx and future derivatives.

Fixes #4
2026-11-27 01:23:33 +02:00
paultal 473a9358d6 Simplify README to a description and how to run it (#11)
Cuts README.md down to one paragraph about the project and a short "Running it" section. Removes the command table, the code layout, the English conventions and the "not yet" list.

Adds a README section to AGENTS.md: keep the README short, never use it as documentation, document code in docstrings next to it, and track planned work in Gitea issues.

The issues that pointed at README sections (#3, #10) have been updated.

Reviewed-on: #11
Co-authored-by: Paul Tal <[email protected]>
2026-11-27 00:57:12 +02:00
paultal 98e88cac04 Add clean Path A proof of concept (#1)
Spoken-English math to Typst with a small (~8M parameter) encoder-decoder Transformer trained from scratch, following the build guide (Path A only).

## What's in it
- `generate.py` / `render.py` / `ast.py`: random expression trees rendered to Typst (deterministic) and English (random phrasings); every Typst string is compile-checked, split by a hash of the Typst string
- `tokenizer.py`: byte-level BPE shared by both sides
- `model.py`: `nn.Transformer` seq2seq with `encode()` / `decode()` for inference
- `train.py`: teacher forcing, AdamW, warmup + cosine, overfit-100 sanity check, checkpoints
- `translate.py`: greedy decoding CLI (`uv run isotope "..."`)
- `evaluate.py`: exact match + compile rate on the synthetic test split and `eval/hand_test.jsonl`
- `run.sh`: whole pipeline; `./run.sh --quick` is a 2-minute smoke run
- `AGENTS.md`: commit and workflow rules for agents

## Checked
- `uv run pytest` (8 tests: Typst compiles, English is unambiguous, tokenizer round-trips, causal mask) and `ruff check` pass
- `./run.sh --quick` and the full `./run.sh` run end to end on an M-series Mac

Reviewed-on: #1
Co-authored-by: Paul Tal <[email protected]>
2026-11-27 00:24:05 +02:00
8 changed files with 232 additions and 93 deletions

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
# 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.
+6 -52
View File
@@ -1,59 +1,13 @@
# isotope-typst
**isotope-typst** is a Transformer model that translates math written in plain English into [Typst](https://typst.app) markup.
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.
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$`.
## Running it
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`).
You need [uv](https://docs.astral.sh/uv/) and the Typst CLI (`brew install typst`).
```bash
./run.sh # everything, ~20 min on an M-series Mac
./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
./run.sh # generate data, train, and evaluate (~20 min on an M-series Mac)
uv run isotope "x squared plus 1" # translate a sentence
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.
+102 -32
View File
@@ -1,32 +1,102 @@
{"en": "the integral from 0 to infinity of e to the minus x squared dx", "typ": "integral_0^infinity e^(-x^2) dif x"}
{"en": "x squared plus y squared equals r squared", "typ": "x^2 + y^2 = r^2"}
{"en": "a squared plus b squared equals c squared", "typ": "a^2 + b^2 = c^2"}
{"en": "e to the x", "typ": "e^x"}
{"en": "e to the minus x", "typ": "e^(-x)"}
{"en": "one over x", "typ": "frac(1, x)"}
{"en": "x over 2", "typ": "frac(x, 2)"}
{"en": "the square root of 2", "typ": "sqrt(2)"}
{"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)"}
{"en": "sine of x", "typ": "sin(x)"}
{"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"}
{"en": "ln of x", "typ": "ln(x)"}
{"en": "2 x plus 3", "typ": "2 x + 3"}
{"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"}
{"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"}
{"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"}
{"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": "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)"}
{"en": "x to the n", "typ": "x^n"}
{"en": "x cubed minus 1", "typ": "x^3 - 1"}
{"en": "alpha plus beta", "typ": "alpha + beta"}
{"en": "2 pi r", "typ": "2 pi r"}
{"en": "e to the i pi plus 1 equals 0", "typ": "e^(i pi) + 1 = 0"}
{"en": "one half", "typ": "frac(1, 2)"}
{"en": "f equals m a", "typ": "f = m a"}
{"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": "x squared plus y squared equals r squared", "typ": "x^2 + y^2 = r^2", "cat": "equation"}
{"en": "a squared plus b squared equals c squared", "typ": "a^2 + b^2 = c^2", "cat": "equation"}
{"en": "e to the x", "typ": "e^x", "cat": "basic"}
{"en": "e to the minus x", "typ": "e^(-x)", "cat": "basic"}
{"en": "one over x", "typ": "frac(1, x)", "cat": "basic"}
{"en": "x over 2", "typ": "frac(x, 2)", "cat": "basic"}
{"en": "the square root of 2", "typ": "sqrt(2)", "cat": "basic"}
{"en": "square root of x plus one", "typ": "sqrt(x) + 1", "cat": "basic"}
{"en": "the square root of the quantity x plus 1", "typ": "sqrt(x + 1)", "cat": "basic"}
{"en": "sine of x", "typ": "sin(x)", "cat": "basic"}
{"en": "sin x squared", "typ": "sin(x^2)", "cat": "basic"}
{"en": "sine squared of x plus cosine squared of x equals 1", "typ": "sin(x)^2 + cos(x)^2 = 1", "cat": "equation"}
{"en": "ln of x", "typ": "ln(x)", "cat": "basic"}
{"en": "2 x plus 3", "typ": "2 x + 3", "cat": "basic"}
{"en": "3x squared minus 2x plus 1", "typ": "3 x^2 - 2 x + 1", "cat": "basic"}
{"en": "y equals m x plus b", "typ": "y = m x + b", "cat": "equation"}
{"en": "the integral of x squared dx", "typ": "integral 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", "cat": "bigop"}
{"en": "integral from 0 to pi of sine of x dx", "typ": "integral_0^pi sin(x) dif x", "cat": "bigop"}
{"en": "the sum from i equals 1 to n of i", "typ": "sum_(i = 1)^n i", "cat": "bigop"}
{"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 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 n goes to infinity of 1 over n", "typ": "lim_(n -> infinity) frac(1, n)", "cat": "bigop"}
{"en": "minus b over 2 a", "typ": "frac(-b, 2 a)", "cat": "basic"}
{"en": "x to the n", "typ": "x^n", "cat": "basic"}
{"en": "x cubed minus 1", "typ": "x^3 - 1", "cat": "basic"}
{"en": "alpha plus beta", "typ": "alpha + beta", "cat": "basic"}
{"en": "2 pi r", "typ": "2 pi r", "cat": "basic"}
{"en": "e to the i pi plus 1 equals 0", "typ": "e^(i pi) + 1 = 0", "cat": "equation"}
{"en": "one half", "typ": "frac(1, 2)", "cat": "basic"}
{"en": "f equals m a", "typ": "f = m a", "cat": "equation"}
{"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"}
+8 -1
View File
@@ -106,7 +106,14 @@ class Eq(Node):
right: Node
GREEK = ["alpha", "beta", "gamma", "delta", "theta", "lambda", "mu", "sigma", "phi", "omega"]
# 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", "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"]
BIG_OPS = (Integral, Sum, Lim)
+33 -5
View File
@@ -1,13 +1,17 @@
"""Evaluate: exact match and compile rate, on the synthetic test split and the hand-written set.
"""Evaluate: exact match, compile rate and bracket balance, on the synthetic test split and the hand-written set.
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).
"""
from __future__ import annotations
import argparse
import collections
import json
import pathlib
import random
@@ -20,6 +24,20 @@ def read_jsonl(path: str) -> list[dict]:
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:
from .translate import load_model, translate_batch
@@ -40,20 +58,30 @@ def main(argv: list[str] | None = None) -> None:
if pathlib.Path(args.hand).exists():
sets["hand"] = read_jsonl(args.hand)
print(f"{'set':<12}{'n':>6}{'exact':>9}{'compiles':>10}")
print(f"{'set':<12}{'n':>6}{'exact':>9}{'compiles':>10}{'balanced':>10}")
for name, rows in sets.items():
preds = []
for i in range(0, len(rows), 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)]
comp = compiles_many(preds)
bal = [balanced(p) for p in preds]
n = len(rows)
print(f"{name:<12}{n:>6}{sum(exact) / n:>9.1%}{sum(comp) / n:>10.1%}")
print(f"{name:<12}{n:>6}{sum(exact) / n:>9.1%}{sum(comp) / n:>10.1%}{sum(bal) / 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"]
for r, p, e, c in zip(rows, preds, exact, comp):
for r, p, e, c, b in zip(rows, preds, exact, comp, bal):
if not e:
lines.append(f"EN: {r['en']}\nWANT: {r['typ']}\nGOT: {p}{'' if c else ' [does not compile]'}\n")
flags = ("" if c else " [does not compile]") + ("" if b else " [unbalanced]")
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.write_text("\n".join(lines))
print(f"\nfailures: {args.out}/errors_*.txt")
+30 -3
View File
@@ -16,7 +16,28 @@ import pathlib
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,
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 .validate import compiles_many
@@ -31,8 +52,14 @@ class TreeGen:
def var(self, prefer: str | None = None) -> Var:
if prefer and self.rng.random() < 0.6: # inside "integral ... dx", mostly use x
return Var(prefer)
pool = ["x"] * 12 + ["y"] * 4 + ["z", "t", "a", "b", "c", "n", "k", "u", "r", "s", "m", "p"] + GREEK
return Var(self.rng.choice(pool))
r = self.rng.random()
if r < 0.45: # x and y stay the most common, as in real maths
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:
r = self.rng.random()
+23
View File
@@ -0,0 +1,23 @@
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
@@ -0,0 +1,12 @@
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