Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
evrything included works
raiyanyahya63e8cf7dcc87
diff --git a/notebooks/07_gpt_model.ipynb b/notebooks/07_gpt_model.ipynbnew file mode 100644index 0000000..55768b4--- /dev/null+++ b/notebooks/07_gpt_model.ipynb@@ -0,0 +1,373 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# The Complete GPT Model\n",+ "\n",+ "We have built every piece. The tokenizer. The embeddings. RoPE\n",+ "for position. Attention for context. And the transformer block\n",+ "that packages everything into a repeatable unit.\n",+ "\n",+ "Now we assemble it all into one model. A single class that takes\n",+ "token IDs as input and predicts the next token as output. This\n",+ "is the same architecture behind GPT-2 GPT-3 LLaMA and Mistral.\n",+ "\n",+ "The model has four main parts. A token embedding that turns IDs\n",+ "into vectors. A stack of transformer blocks that process those\n",+ "vectors through attention and feed forward layers. A final\n",+ "normalization layer. And an output head that projects the hidden\n",+ "state back into vocabulary scores.\n",+ "\n",+ "One clever trick we use is weight tying. The embedding table and\n",+ "the output head share the same weights. This saves a third of\n",+ "the parameters and gives the model more training signal because\n",+ "each token embedding gets updated from both directions.\n",+ "\n",+ "By the end of this notebook you will hold a complete language\n",+ "model in your hands. Ready to train."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Imports"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import torch\n",+ "import torch.nn as nn\n",+ "import torch.nn.functional as F\n",+ "import math\n",+ "from dataclasses import dataclass"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Building blocks from previous chapters"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "class RotaryPositionalEmbedding(nn.Module):\n",+ " def __init__(self, d_model, max_seq_len=2048, theta=10000.0):\n",+ " super().__init__()\n",+ " assert d_model % 2 == 0\n",+ " dim_indices = torch.arange(0, d_model, 2).float()\n",+ " inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n",+ " positions = torch.arange(max_seq_len).float()\n",+ " freqs = torch.outer(positions, inv_freq)\n",+ " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " self.register_buffer(\"cos_cached\", emb.cos())\n",+ " self.register_buffer(\"sin_cached\", emb.sin())\n",+ "\n",+ " @staticmethod\n",+ " def rotate_half(x):\n",+ " x1 = x[..., : x.shape[-1] // 2]\n",+ " x2 = x[..., x.shape[-1] // 2 :]\n",+ " return torch.cat([-x2, x1], dim=-1)\n",+ "\n",+ " def forward(self, x, seq_len):\n",+ " cos = self.cos_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",+ " sin = self.sin_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",+ " return (x * cos) + (self.rotate_half(x) * sin)\n",+ "\n",+ "\n",+ "def create_causal_mask(seq_len, device):\n",+ " mask = torch.tril(torch.ones(seq_len, seq_len, device=device))\n",+ " return mask.view(1, 1, seq_len, seq_len)\n",+ "\n",+ "\n",+ "class RMSNorm(nn.Module):\n",+ " def __init__(self, d_model, eps=1e-6):\n",+ " super().__init__()\n",+ " self.weight = nn.Parameter(torch.ones(d_model))\n",+ " self.eps = eps\n",+ "\n",+ " def forward(self, x):\n",+ " rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n",+ " return x * rms * self.weight\n",+ "\n",+ "\n",+ "class SwiGLU(nn.Module):\n",+ " def __init__(self, d_model, expansion_factor=4):\n",+ " super().__init__()\n",+ " hidden_dim = expansion_factor * d_model\n",+ " self.w1 = nn.Linear(d_model, hidden_dim, bias=False)\n",+ " self.w2 = nn.Linear(d_model, hidden_dim, bias=False)\n",+ " self.w3 = nn.Linear(hidden_dim, d_model, bias=False)\n",+ "\n",+ " def forward(self, x):\n",+ " return self.w3(F.silu(self.w1(x)) * self.w2(x))\n",+ "\n",+ "\n",+ "class MultiHeadAttention(nn.Module):\n",+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",+ " super().__init__()\n",+ " assert d_model % num_heads == 0\n",+ " self.d_model = d_model\n",+ " self.num_heads = num_heads\n",+ " self.head_dim = d_model // num_heads\n",+ " self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False)\n",+ " self.out_proj = nn.Linear(d_model, d_model, bias=False)\n",+ " self.rotary = RotaryPositionalEmbedding(self.head_dim)\n",+ " self.attn_dropout = nn.Dropout(dropout)\n",+ " self.resid_dropout = nn.Dropout(dropout)\n",+ "\n",+ " def forward(self, x, mask=None):\n",+ " batch_size, seq_len, _ = x.shape\n",+ " qkv = self.qkv_proj(x)\n",+ " qkv = qkv.reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)\n",+ " qkv = qkv.permute(2, 0, 3, 1, 4)\n",+ " q, k, v = qkv[0], qkv[1], qkv[2]\n",+ " q = self.rotary(q, seq_len)\n",+ " k = self.rotary(k, seq_len)\n",+ " attn_scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",+ " if mask is not None:\n",+ " attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))\n",+ " attn_weights = F.softmax(attn_scores, dim=-1)\n",+ " attn_weights = self.attn_dropout(attn_weights)\n",+ " attn_output = attn_weights @ v\n",+ " attn_output = attn_output.transpose(1, 2).contiguous()\n",+ " attn_output = attn_output.reshape(batch_size, seq_len, self.d_model)\n",+ " output = self.out_proj(attn_output)\n",+ " output = self.resid_dropout(output)\n",+ " return output\n",+ "\n",+ "\n",+ "class TransformerBlock(nn.Module):\n",+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",+ " super().__init__()\n",+ " self.norm1 = RMSNorm(d_model)\n",+ " self.attention = MultiHeadAttention(d_model, num_heads, dropout)\n",+ " self.norm2 = RMSNorm(d_model)\n",+ " self.ffn = SwiGLU(d_model)\n",+ "\n",+ " def forward(self, x, mask=None):\n",+ " x = x + self.attention(self.norm1(x), mask)\n",+ " x = x + self.ffn(self.norm2(x))\n",+ " return x"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## GPT Configuration\n",+ "\n",+ "A single dataclass holds every setting. Change one number and\n",+ "the whole model adapts."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "@dataclass\n",+ "class GPTConfig:\n",+ " vocab_size: int = 50257\n",+ " d_model: int = 768\n",+ " num_heads: int = 12\n",+ " num_layers: int = 12\n",+ " max_seq_len: int = 1024\n",+ " dropout: float = 0.1\n",+ " embd_dropout: float = 0.1\n",+ " learning_rate: float = 3e-4\n",+ " weight_decay: float = 0.1\n",+ " warmup_steps: int = 2000\n",+ " max_steps: int = 100000\n",+ " batch_size: int = 8\n",+ " grad_accum_steps: int = 4\n",+ " betas: tuple = (0.9, 0.95)\n",+ " eps: float = 1e-8"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## The GPT Model\n",+ "\n",+ "Token embedding plus dropout. A stack of transformer blocks.\n",+ "Final RMSNorm. Output projection into vocabulary scores.\n",+ "The embedding weights are shared with the output head.\n",+ "All weights start from a normal distribution with std 0.02."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "class GPT(nn.Module):\n",+ " def __init__(self, config):\n",+ " super().__init__()\n",+ " self.config = config\n",+ "\n",+ " self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)\n",+ " self.embd_dropout = nn.Dropout(config.embd_dropout)\n",+ "\n",+ " self.layers = nn.ModuleList([\n",+ " TransformerBlock(config.d_model, config.num_heads, config.dropout)\n",+ " for _ in range(config.num_layers)\n",+ " ])\n",+ "\n",+ " self.final_norm = RMSNorm(config.d_model)\n",+ " self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\n",+ "\n",+ " self.token_embedding.weight = self.lm_head.weight\n",+ " self.apply(self._init_weights)\n",+ "\n",+ " def _init_weights(self, module):\n",+ " if isinstance(module, (nn.Linear, nn.Embedding)):\n",+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",+ " if hasattr(module, 'bias') and module.bias is not None:\n",+ " torch.nn.init.zeros_(module.bias)\n",+ "\n",+ " def forward(self, input_ids, targets=None):\n",+ " batch_size, seq_len = input_ids.shape\n",+ "\n",+ " x = self.token_embedding(input_ids)\n",+ " x = self.embd_dropout(x)\n",+ "\n",+ " mask = create_causal_mask(seq_len, input_ids.device)\n",+ " for layer in self.layers:\n",+ " x = layer(x, mask)\n",+ " x = self.final_norm(x)\n",+ "\n",+ " logits = self.lm_head(x)\n",+ "\n",+ " loss = None\n",+ " if targets is not None:\n",+ " logits_flat = logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size)\n",+ " targets_flat = targets[:, 1:].contiguous().view(-1)\n",+ " loss = F.cross_entropy(logits_flat, targets_flat)\n",+ "\n",+ " return logits, loss\n",+ "\n",+ " def get_num_params(self):\n",+ " return sum(p.numel() for p in self.parameters())"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Create the model and inspect it"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "config = GPTConfig()\n",+ "model = GPT(config)\n",+ "print(f\"Total parameters: {model.get_num_params():,}\")\n",+ "print()\n",+ "\n",+ "print(f\"Config:\")\n",+ "print(f\" d_model: {config.d_model}\")\n",+ "print(f\" num_heads: {config.num_heads}\")\n",+ "print(f\" num_layers:{config.num_layers}\")\n",+ "print(f\" vocab_size:{config.vocab_size}\")\n",+ "print(f\" max_seq_len: {config.max_seq_len}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Run a forward pass\n",+ "\n",+ "Feed the model some random token IDs and check that it produces\n",+ "logits of the right shape. Also compute the loss."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "batch_size = 4\n",+ "seq_len = 128\n",+ "\n",+ "input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))\n",+ "target_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))\n",+ "\n",+ "logits, loss = model(input_ids, target_ids)\n",+ "\n",+ "print(f\"Input shape: {input_ids.shape}\")\n",+ "print(f\"Logits shape: {logits.shape}\")\n",+ "print(f\"Loss: {loss.item():.4f}\")\n",+ "print()\n",+ "\n",+ "print(f\"Expected logits shape: [{batch_size}, {seq_len}, {config.vocab_size}]\")\n",+ "print(f\"Actual logits shape: [{logits.shape[0]}, {logits.shape[1]}, {logits.shape[2]}]\")\n",+ "print()\n",+ "\n",+ "print(f\"For each of the {seq_len} positions the model produces\")\n",+ "print(f\"{config.vocab_size} scores. One score per possible next token.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Weight tying verification\n",+ "\n",+ "The embedding and output head share the same tensor. Changing\n",+ "one changes the other because they point to the same memory."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "emb_weight = model.token_embedding.weight\n",+ "head_weight = model.lm_head.weight\n",+ "\n",+ "print(f\"Embedding weight id: {id(emb_weight)}\")\n",+ "print(f\"LM head weight id: {id(head_weight)}\")\n",+ "print(f\"Same memory: {emb_weight.data_ptr() == head_weight.data_ptr()}\")\n",+ "print()\n",+ "\n",+ "saved_params = config.vocab_size * config.d_model\n",+ "print(f\"Parameters saved by weight tying: {saved_params:,}\")"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "name": "python",+ "version": "3.10.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}