"""Small decoder-only GPT used with the local 4,096-token BPE tokenizer.""" from __future__ import annotations from dataclasses import asdict, dataclass import json from pathlib import Path import torch from torch import nn from torch.nn import functional as F @dataclass class GPTConfig: vocab_size: int = 4096 d_model: int = 256 n_layers: int = 4 n_heads: int = 4 ffn_dim: int = 1024 max_seq_len: int = 512 dropout: float = 0.1 bias: bool = True layer_norm_eps: float = 1e-5 tie_embeddings: bool = True def __post_init__(self) -> None: if self.d_model % self.n_heads: raise ValueError("d_model must be divisible by n_heads") if min(self.vocab_size, self.n_layers, self.n_heads, self.ffn_dim, self.max_seq_len) <= 0: raise ValueError("model dimensions must be positive") @classmethod def from_json(cls, path: str | Path) -> "GPTConfig": values = json.loads(Path(path).read_text(encoding="utf-8")) values.pop("tokenizer_path", None) return cls(**values) def save_json(self, path: str | Path) -> None: Path(path).write_text( json.dumps(asdict(self), indent=2) + "\n", encoding="utf-8" ) class CausalSelfAttention(nn.Module): def __init__(self, config: GPTConfig) -> None: super().__init__() self.n_heads = config.n_heads self.head_dim = config.d_model // config.n_heads self.dropout = config.dropout self.qkv = nn.Linear(config.d_model, 3 * config.d_model, bias=config.bias) self.proj = nn.Linear(config.d_model, config.d_model, bias=config.bias) self.resid_dropout = nn.Dropout(config.dropout) def forward(self, x: torch.Tensor) -> torch.Tensor: batch, length, width = x.shape q, k, v = self.qkv(x).split(width, dim=-1) q = q.view(batch, length, self.n_heads, self.head_dim).transpose(1, 2) k = k.view(batch, length, self.n_heads, self.head_dim).transpose(1, 2) v = v.view(batch, length, self.n_heads, self.head_dim).transpose(1, 2) y = F.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0.0, is_causal=True, ) y = y.transpose(1, 2).contiguous().view(batch, length, width) return self.resid_dropout(self.proj(y)) class MLP(nn.Module): def __init__(self, config: GPTConfig) -> None: super().__init__() self.fc = nn.Linear(config.d_model, config.ffn_dim, bias=config.bias) self.proj = nn.Linear(config.ffn_dim, config.d_model, bias=config.bias) self.act = nn.GELU(approximate="tanh") self.dropout = nn.Dropout(config.dropout) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.dropout(self.proj(self.act(self.fc(x)))) class TransformerBlock(nn.Module): def __init__(self, config: GPTConfig) -> None: super().__init__() self.ln_1 = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps) self.attn = CausalSelfAttention(config) self.ln_2 = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps) self.mlp = MLP(config) def forward(self, x: torch.Tensor) -> torch.Tensor: x = x + self.attn(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class TinyGPT(nn.Module): """Pre-LN GPT with learned positions and optionally tied token embeddings.""" def __init__(self, config: GPTConfig | None = None) -> None: super().__init__() self.config = config or GPTConfig() c = self.config self.wte = nn.Embedding(c.vocab_size, c.d_model) self.wpe = nn.Embedding(c.max_seq_len, c.d_model) self.drop = nn.Dropout(c.dropout) self.blocks = nn.ModuleList(TransformerBlock(c) for _ in range(c.n_layers)) self.ln_f = nn.LayerNorm(c.d_model, eps=c.layer_norm_eps) self.lm_head = nn.Linear(c.d_model, c.vocab_size, bias=False) if c.tie_embeddings: self.lm_head.weight = self.wte.weight self.apply(self._init_weights) scale = 0.02 / (2 * c.n_layers) ** 0.5 for block in self.blocks: nn.init.normal_(block.attn.proj.weight, mean=0.0, std=scale) nn.init.normal_(block.mlp.proj.weight, mean=0.0, std=scale) @staticmethod def _init_weights(module: nn.Module) -> None: if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) if isinstance(module, nn.Linear) and module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm): nn.init.ones_(module.weight) nn.init.zeros_(module.bias) def parameter_count(self, trainable_only: bool = True) -> int: return sum( parameter.numel() for parameter in self.parameters() if not trainable_only or parameter.requires_grad ) def forward( self, input_ids: torch.Tensor, labels: torch.Tensor | None = None ) -> tuple[torch.Tensor, torch.Tensor | None]: if input_ids.ndim != 2: raise ValueError("input_ids must have shape [batch, sequence]") batch, length = input_ids.shape if length > self.config.max_seq_len: raise ValueError( f"sequence length {length} exceeds max_seq_len=" f"{self.config.max_seq_len}" ) positions = torch.arange(length, device=input_ids.device) x = self.drop(self.wte(input_ids) + self.wpe(positions)[None, :, :]) for block in self.blocks: x = block(x) logits = self.lm_head(self.ln_f(x)) loss = None if labels is not None: if labels.shape != input_ids.shape: raise ValueError("labels must have the same shape as input_ids") loss = F.cross_entropy( logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size), labels[:, 1:].contiguous().view(-1), ignore_index=-100, ) return logits, loss