"""A small decoder-only transformer (nanoGPT-style). Deliberately tiny and standard: token + positional embeddings, a stack of pre-LayerNorm blocks (causal self-attention + MLP), then a tied linear head. One of these is trained per (corpus, scheme) cell — identical architecture everywhere, so the only thing that differs across tokenizers is the vocabulary (and therefore what the model can even represent). """ from __future__ import annotations import math from dataclasses import dataclass, asdict import torch import torch.nn as nn import torch.nn.functional as F @dataclass class GPTConfig: vocab_size: int block_size: int = 128 n_layer: int = 4 n_head: int = 4 n_embd: int = 128 dropout: float = 0.1 def to_dict(self) -> dict: return asdict(self) class CausalSelfAttention(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() assert cfg.n_embd % cfg.n_head == 0 self.n_head = cfg.n_head self.n_embd = cfg.n_embd self.c_attn = nn.Linear(cfg.n_embd, 3 * cfg.n_embd) self.c_proj = nn.Linear(cfg.n_embd, cfg.n_embd) self.attn_dropout = cfg.dropout self.resid_dropout = nn.Dropout(cfg.dropout) def forward(self, x): B, T, C = x.shape q, k, v = self.c_attn(x).split(self.n_embd, dim=2) # (B, nh, T, hd) q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) y = F.scaled_dot_product_attention( q, k, v, is_causal=True, dropout_p=self.attn_dropout if self.training else 0.0, ) y = y.transpose(1, 2).contiguous().view(B, T, C) return self.resid_dropout(self.c_proj(y)) class MLP(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() self.c_fc = nn.Linear(cfg.n_embd, 4 * cfg.n_embd) self.c_proj = nn.Linear(4 * cfg.n_embd, cfg.n_embd) self.dropout = nn.Dropout(cfg.dropout) def forward(self, x): return self.dropout(self.c_proj(F.gelu(self.c_fc(x)))) class Block(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() self.ln_1 = nn.LayerNorm(cfg.n_embd) self.attn = CausalSelfAttention(cfg) self.ln_2 = nn.LayerNorm(cfg.n_embd) self.mlp = MLP(cfg) def forward(self, x): x = x + self.attn(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class GPT(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() self.cfg = cfg self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.n_embd) self.pos_emb = nn.Embedding(cfg.block_size, cfg.n_embd) self.drop = nn.Dropout(cfg.dropout) self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)]) self.ln_f = nn.LayerNorm(cfg.n_embd) self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False) self.tok_emb.weight = self.lm_head.weight # weight tying self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): nn.init.normal_(m.weight, mean=0.0, std=0.02) if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.Embedding): nn.init.normal_(m.weight, mean=0.0, std=0.02) def num_params(self) -> int: # subtract tied head (shares tok_emb storage) to avoid double counting return sum(p.numel() for p in self.parameters()) - self.lm_head.weight.numel() def forward(self, idx, targets=None): B, T = idx.shape pos = torch.arange(T, device=idx.device) x = self.drop(self.tok_emb(idx) + self.pos_emb(pos)) for block in self.blocks: x = block(x) x = self.ln_f(x) logits = self.lm_head(x) loss = None if targets is not None: loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1) return logits, loss @torch.no_grad() def next_token_logits(self, idx): """Logits for the position after the (cropped) context — for the playground.""" idx = idx[:, -self.cfg.block_size:] logits, _ = self(idx) return logits[:, -1, :] @torch.no_grad() def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None): for _ in range(max_new_tokens): logits = self.next_token_logits(idx) / max(temperature, 1e-6) if top_k is not None: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float("inf") probs = F.softmax(logits, dim=-1) nxt = torch.multinomial(probs, num_samples=1) idx = torch.cat([idx, nxt], dim=1) return idx