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.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
paultalandClaude Opus 5.5 committed 2026-11-26 15:02:30 +02:00
1 parent 5926731546
commit 8001581c62
27 files changed
+23517 -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