# model.py """Modern GPT: RMSNorm, SwiGLU, QK-Norm, Residual Scaling, Flash SDPA.""" import math from contextlib import nullcontext from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint @dataclass class GPTConfig: vocab_size: int = 8192 block_size: int = 1024 n_layer: int = 24 n_head: int = 16 n_embd: int = 1024 PRESETS = { "baby": dict(n_layer=8, n_head=8, n_embd=512), # ~40M params "small": dict(n_layer=12, n_head=12, n_embd=768), # ~110M params "medium": dict(n_layer=24, n_head=16, n_embd=1024), # ~345M params (Lyra-326M / GPT-2 Medium) "large": dict(n_layer=36, n_head=20, n_embd=1280), # ~775M params (GPT-2 Large) } class RMSNorm(nn.Module): """Root Mean Square Layer Normalization. Faster and standard in modern LLMs.""" def __init__(self, dim, eps=1e-5): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x): rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt() return x * rms * self.weight class Attention(nn.Module): def __init__(self, cfg): super().__init__() assert cfg.n_embd % cfg.n_head == 0, \ f"n_embd={cfg.n_embd} must be divisible by n_head={cfg.n_head}" self.n_head = cfg.n_head self.n_embd = cfg.n_embd self.hd = cfg.n_embd // cfg.n_head self.qkv = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=False) self.proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=False) # QK-Norm: prevents attention logits from blowing up in deeper models self.q_norm = RMSNorm(self.hd) self.k_norm = RMSNorm(self.hd) def forward(self, x): B, T, C = x.shape q, k, v = self.qkv(x).split(self.n_embd, dim=-1) q = q.view(B, T, self.n_head, self.hd).transpose(1, 2) k = k.view(B, T, self.n_head, self.hd).transpose(1, 2) v = v.view(B, T, self.n_head, self.hd).transpose(1, 2) # Apply QK norm q = self.q_norm(q) k = self.k_norm(k) # Flash/mem-efficient kernel y = F.scaled_dot_product_attention(q, k, v, is_causal=True) return self.proj(y.transpose(1, 2).contiguous().view(B, T, C)) class SwiGLU(nn.Module): """SwiGLU MLP. Noticeably better quality than standard GELU.""" def __init__(self, cfg): super().__init__() # Hidden dim is typically 8/3 * n_embd, rounded to multiple of 256 for tensor core efficiency hidden = int(8 * cfg.n_embd / 3) hidden = 256 * ((hidden + 255) // 256) self.w1 = nn.Linear(cfg.n_embd, hidden, bias=False) # gate self.w2 = nn.Linear(cfg.n_embd, hidden, bias=False) # up self.w3 = nn.Linear(hidden, cfg.n_embd, bias=False) # down def forward(self, x): return self.w3(F.silu(self.w1(x)) * self.w2(x)) class Block(nn.Module): def __init__(self, cfg): super().__init__() self.ln1 = RMSNorm(cfg.n_embd) self.attn = Attention(cfg) self.ln2 = RMSNorm(cfg.n_embd) self.mlp = SwiGLU(cfg) # Residual scaling: stabilizes training for deeper networks self.resid_scale = 1.0 / math.sqrt(cfg.n_layer) def forward(self, x): x = x + self.attn(self.ln1(x)) * self.resid_scale x = x + self.mlp(self.ln2(x)) * self.resid_scale return x class GPT(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg self.config = cfg # alias for HF-style access used by generate() self.wte = nn.Embedding(cfg.vocab_size, cfg.n_embd) self.wpe = nn.Embedding(cfg.block_size, cfg.n_embd) self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg.n_layer)]) self.ln_f = RMSNorm(cfg.n_embd) self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False) self.lm_head.weight = self.wte.weight # weight tying self.apply(self._init) # 0 = off, 1 = every block, 2 = every other block. Selective buys back # half the recompute cost while still freeing enough activations to # raise micro-batch, which is what actually starves the GPU here. self.checkpoint_stride = 0 def gradient_checkpointing_enable(self): self.checkpoint_stride = 1 def gradient_checkpointing_disable(self): self.checkpoint_stride = 0 def set_checkpoint_stride(self, stride): self.checkpoint_stride = max(0, int(stride)) def _init(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): 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} > block_size {self.cfg.block_size}" x = self.wte(idx) + self.wpe(torch.arange(T, device=idx.device)) for i, block in enumerate(self.blocks): if self.training and self.checkpoint_stride and i % self.checkpoint_stride == 0: # recompute this block in backward instead of storing its activations x = checkpoint(block, x, use_reentrant=False) else: 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)) return logits, loss @torch.no_grad() def generate(model, idx, max_new, temperature=1.0, top_k=None, repetition_penalty=1.0): """Generator that yields one new token at a time.""" for _ in range(max_new): # crop context if it exceeds block_size idx_cond = idx if idx.size(1) <= model.config.block_size else idx[:, -model.config.block_size:] # forward pass (handles both tuple and single tensor returns) out = model(idx_cond) logits = out[0] if isinstance(out, tuple) else out logits = logits[:, -1, :] / temperature # Apply repetition penalty to tokens already in the context if repetition_penalty != 1.0: for i in range(idx.size(1)): token = idx[0, i].item() if logits[0, token] > 0: logits[0, token] /= repetition_penalty else: logits[0, token] *= repetition_penalty # top-k filtering if top_k is not None: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float('Inf') # sample next token probs = F.softmax(logits, dim=-1) idx_next = torch.multinomial(probs, num_samples=1) idx = torch.cat((idx, idx_next), dim=1) yield idx_next.item()