"""A small decoder-only transformer, written from scratch. Pre-norm GPT-style blocks, learned positional embeddings, weights tied between the token embedding and the output head. """ import math import torch import torch.nn as nn from torch.nn import functional as F from config import ModelConfig class CausalSelfAttention(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() assert cfg.n_embd % cfg.n_head == 0 self.n_head = cfg.n_head self.n_embd = cfg.n_embd self.dropout = cfg.dropout # q, k and v for every head, computed in one matmul. self.attn = nn.Linear(cfg.n_embd, 3 * cfg.n_embd) self.proj = nn.Linear(cfg.n_embd, cfg.n_embd) self.resid_dropout = nn.Dropout(cfg.dropout) def forward(self, x): B, T, C = x.shape q, k, v = self.attn(x).split(self.n_embd, dim=2) # (B, T, C) -> (B, n_head, T, head_dim) so heads batch through attention. head_dim = C // self.n_head q = q.view(B, T, self.n_head, head_dim).transpose(1, 2) k = k.view(B, T, self.n_head, head_dim).transpose(1, 2) v = v.view(B, T, self.n_head, head_dim).transpose(1, 2) # is_causal builds the mask internally; no buffer to keep in sync. y = F.scaled_dot_product_attention( q, k, v, dropout_p=self.dropout if self.training else 0.0, is_causal=True, ) y = y.transpose(1, 2).contiguous().view(B, T, C) return self.resid_dropout(self.proj(y)) class MLP(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.fc = nn.Linear(cfg.n_embd, 4 * cfg.n_embd) self.proj = nn.Linear(4 * cfg.n_embd, cfg.n_embd) self.dropout = nn.Dropout(cfg.dropout) def forward(self, x): return self.dropout(self.proj(F.gelu(self.fc(x)))) class Block(nn.Module): """Pre-norm: normalise going into each sublayer, leave the residual clean.""" def __init__(self, cfg: ModelConfig): 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)) return x + self.mlp(self.ln_2(x)) class Kat(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.cfg = cfg self.wte = nn.Embedding(cfg.vocab_size, cfg.n_embd) self.wpe = 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.head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False) # Weight tying: the input and output token spaces are the same, so # share one matrix. Saves ~2M params here, a third of the model. self.head.weight = self.wte.weight self.apply(self._init_weights) # Scale down projections that write into the residual stream, so the # stream's variance does not grow with depth. for name, p in self.named_parameters(): if name.endswith("proj.weight"): nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer)) def _init_weights(self, module): if isinstance(module, nn.Linear): nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, mean=0.0, std=0.02) def num_params(self) -> int: # wpe is counted; the tied head shares wte so it is not double counted. return sum(p.numel() for p in self.parameters()) def forward(self, idx, targets=None): B, T = idx.shape assert T <= self.cfg.block_size, f"sequence {T} exceeds block {self.cfg.block_size}" pos = torch.arange(T, device=idx.device) x = self.drop(self.wte(idx) + self.wpe(pos)) for block in self.blocks: x = block(x) logits = self.head(self.ln_f(x)) loss = None if targets is not None: loss = F.cross_entropy( logits.view(-1, logits.size(-1)), targets.reshape(-1) ) return logits, loss @torch.no_grad() def generate(self, idx, max_new_tokens, temperature=0.8, top_k=40, stop_tokens=()): """Sample continuations. Greedy decoding loops on a model this small, so sampling is the default rather than an option.""" self.eval() for _ in range(max_new_tokens): # Never feed more than block_size; keep the most recent context. window = idx[:, -self.cfg.block_size:] logits, _ = self(window) logits = logits[:, -1, :] / max(temperature, 1e-6) if top_k is not None: k = min(top_k, logits.size(-1)) threshold = torch.topk(logits, k, dim=-1).values[:, [-1]] logits = logits.masked_fill(logits < threshold, float("-inf")) probs = F.softmax(logits, dim=-1) next_id = torch.multinomial(probs, num_samples=1) idx = torch.cat((idx, next_id), dim=1) # Stop on any turn boundary, not just <|eos|>: the model will # happily carry on and write the user's next line otherwise. if next_id.item() in stop_tokens: break return idx