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. Ships the
trained Path A model and tokenizer so the CLI works right after clone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
paultalandClaude Opus 5.5 committed 2026-11-26 14:58:18 +02:00
1 parent 5926731546
commit e266d04a84
28 files changed
+23519 -2

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
import torch
from torch import nn
from isotope_typst.model import CONFIGS, MultiHeadAttention, Seq2Seq, causal_mask, count_params, estimate_params
def test_custom_attention_matches_pytorch():
torch.manual_seed(0)
d, h = 64, 4
mine = MultiHeadAttention(d, h)
ref = nn.MultiheadAttention(d, h, batch_first=True)
with torch.no_grad():
W = torch.cat([mine.q.weight, mine.k.weight, mine.v.weight])
b = torch.cat([mine.q.bias, mine.k.bias, mine.v.bias])
ref.in_proj_weight.copy_(W)
ref.in_proj_bias.copy_(b)
ref.out_proj.weight.copy_(mine.o.weight)
ref.out_proj.bias.copy_(mine.o.bias)
x, mem = torch.randn(2, 7, d), torch.randn(2, 9, d)
pad = torch.zeros(2, 9, dtype=torch.bool)
pad[1, -3:] = True
cm = causal_mask(7, "cpu")
torch.testing.assert_close(mine(x, x, attn_mask=cm), ref(x, x, x, attn_mask=cm, need_weights=False)[0])
torch.testing.assert_close(mine(x, mem, key_padding_mask=pad),
ref(x, mem, mem, key_padding_mask=pad, need_weights=False)[0])
def test_causal_mask_shape():
m = causal_mask(4, "cpu")
assert m.tolist() == [[False, True, True, True], [False, False, True, True],
[False, False, False, True], [False, False, False, False]]
def test_future_tokens_do_not_change_past_logits():
torch.manual_seed(0)
for custom in (False, True):
m = Seq2Seq(50, **CONFIGS["tiny"], custom_attn=custom).eval()
src = torch.randint(4, 50, (1, 6))
a = torch.randint(4, 50, (1, 5))
b = a.clone()
b[0, -1] = (a[0, -1] + 1) % 46 + 4
la, lb = m(src, a), m(src, b)
torch.testing.assert_close(la[0, :-1], lb[0, :-1])
def test_encode_decode_equals_forward():
m = Seq2Seq(50, **CONFIGS["tiny"]).eval()
src, tgt = torch.randint(4, 50, (2, 6)), torch.randint(4, 50, (2, 5))
torch.testing.assert_close(m(src, tgt), m.decode(tgt, m.encode(src), src == 0))
def test_param_counts_match_guide():
m = Seq2Seq(4000, **CONFIGS["small"])
assert 7e6 < count_params(m) < 10e6
assert abs(estimate_params(4000, **CONFIGS["small"]) - count_params(m)) / count_params(m) < 0.1
+49
View File
@@ -0,0 +1,49 @@
import random
from isotope_typst.ast import Frac, Integral, Neg, Num, Pow, Var
from isotope_typst.generate import TreeGen, split_of
from isotope_typst.render import to_english, to_typst
from isotope_typst.validate import compiles, compiles_many
def guide_tree():
return Integral(Pow(Var("e"), Neg(Pow(Var("x"), Num(2)))), "x", Num(0), Var("infinity"))
def test_guide_example():
assert to_typst(guide_tree()) == "integral_0^infinity e^(-x^2) dif x"
def test_frac_and_parens():
assert to_typst(Frac(Num(1), Var("x"))) == "frac(1, x)"
assert to_typst(Pow(Frac(Num(1), Num(2)), Num(2))) == "(frac(1, 2))^2"
def test_english_is_random_but_typst_is_not():
rng = random.Random(0)
phrasings = {to_english(guide_tree(), rng) for _ in range(50)}
assert len(phrasings) > 10
def test_generated_typst_compiles():
gen = TreeGen(random.Random(1))
maths = [to_typst(gen.tree()) for _ in range(300)]
assert all(compiles_many(maths))
def test_basic_generator_only_uses_basic_nodes():
from isotope_typst.ast import walk
gen = TreeGen(random.Random(2), basic=True)
allowed = {"Num", "Var", "Neg", "Pow", "Frac", "Integral"}
for _ in range(300):
assert {type(n).__name__ for n in walk(gen.tree())} <= allowed
def test_compile_check_rejects_broken():
assert compiles("x^2")
assert not compiles("frac(1, ")
assert compiles_many(["x", "sqrt(", "y"]) == [True, False, True]
def test_split_is_by_structure():
assert split_of("x^2") == split_of("x^2")
+45
View File
@@ -0,0 +1,45 @@
import json
import pathlib
import random
import pytest
from isotope_typst.generate import TreeGen
from isotope_typst.render import to_english, to_typst
from isotope_typst.tokenizer import train
@pytest.fixture(scope="module")
def tok(tmp_path_factory):
d = tmp_path_factory.mktemp("tok")
gen, rng = TreeGen(random.Random(0)), random.Random(0)
lines = []
for _ in range(2000):
t = gen.tree()
lines += [to_english(t, rng), to_typst(t)]
(d / "a.txt").write_text("\n".join(lines))
return train([str(d / "a.txt")], str(d / "tok.json"), vocab=800)
def test_roundtrip_1000_typst_strings(tok):
gen = TreeGen(random.Random(123))
for _ in range(1000):
s = to_typst(gen.tree())
assert tok.decode(tok.encode(s).ids) == s
def test_roundtrip_unseen_characters(tok):
s = "x ≤ ∞ {weird} ü"
assert tok.decode(tok.encode(s).ids) == s
def test_special_ids(tok):
assert [tok.token_to_id(t) for t in ["[PAD]", "[UNK]", "[BOS]", "[EOS]"]] == [0, 1, 2, 3]
def test_hand_test_set_compiles():
from isotope_typst.validate import compiles_many
p = pathlib.Path(__file__).parents[1] / "eval/hand_test.jsonl"
rows = [json.loads(l) for l in p.read_text().splitlines() if l.strip()]
assert len(rows) >= 150
assert all(compiles_many([r["typ"] for r in rows]))