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]>
157 lines
6.4 KiB
Python
157 lines
6.4 KiB
Python
"""Encoder–decoder Transformer (Path A).
|
||
|
||
Seq2Seq(custom_attn=False) uses PyTorch's nn.Transformer (fast, the guide's starting point).
|
||
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
|
||
|
||
import math
|
||
import warnings
|
||
|
||
import torch
|
||
from torch import nn
|
||
|
||
warnings.filterwarnings("ignore", message="enable_nested_tensor is True")
|
||
|
||
CONFIGS = {
|
||
"tiny": dict(d=128, heads=4, layers=3, ff=512), # ~2M params, for debugging
|
||
"small": dict(d=256, heads=4, layers=4, ff=1024), # ~8M params, start here
|
||
"medium": dict(d=512, heads=8, layers=6, ff=2048), # ~46M params
|
||
}
|
||
|
||
|
||
def causal_mask(T: int, device) -> torch.Tensor:
|
||
"""True above the diagonal = 'may not look' (PyTorch bool-mask convention)."""
|
||
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):
|
||
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__()
|
||
self.pad_id, self.max_len, self.custom = pad_id, max_len, custom_attn
|
||
self.tok_emb = nn.Embedding(vocab, d)
|
||
self.pos_emb = nn.Embedding(max_len, d) # learned positions: simplest option
|
||
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):
|
||
pos = torch.arange(ids.size(1), device=ids.device)
|
||
return self.drop(self.tok_emb(ids) * self.scale + self.pos_emb(pos))
|
||
|
||
def encode(self, src):
|
||
pad = 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, memory, src_pad=None):
|
||
T = tgt_in.size(1)
|
||
causal = causal_mask(T, tgt_in.device)
|
||
tgt_pad = tgt_in == self.pad_id
|
||
y = self.emb(tgt_in)
|
||
if self.custom:
|
||
for layer in self.dec_layers:
|
||
y = layer(y, memory, causal, tgt_pad, src_pad)
|
||
h = self.dec_norm(y)
|
||
else:
|
||
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, tgt_in):
|
||
return self.decode(tgt_in, self.encode(src), src_pad=(src == self.pad_id))
|
||
|
||
|
||
def count_params(m: nn.Module) -> int:
|
||
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:
|
||
if torch.cuda.is_available():
|
||
return "cuda"
|
||
if torch.backends.mps.is_available():
|
||
return "mps"
|
||
return "cpu"
|
||
|
||
|
||
__all__ = ["CONFIGS", "MultiHeadAttention", "Seq2Seq", "causal_mask", "count_params", "pick_device"]
|