Skip to content

Build a modern LLM from scratch. Every line commented. Explained like we are five.

chapter 5 the attention stuff finally but at gpt2 scale

raiyanyahya538bf42f9a1c
diff --git a/notebooks/05_attention.ipynb b/notebooks/05_attention.ipynb
new file mode 100644
index 0000000..d076821
--- /dev/null
+++ b/notebooks/05_attention.ipynb
@@ -0,0 +1,381 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Attention\n",
+ "\n",
+ "Attention is not just a part of the transformer. Attention IS the\n",
+ "transformer.\n",
+ "\n",
+ "Consider this sentence. The cat sat on the mat because it was warm.\n",
+ "What does it refer to. A human knows it means the mat. But how\n",
+ "would a computer figure this out.\n",
+ "\n",
+ "Before attention existed a model would read words one by one left\n",
+ "to right. By the time it reached the word it the word mat was far\n",
+ "in the past. Its information had faded. The model would forget.\n",
+ "\n",
+ "Attention solves this by letting every word look at every other\n",
+ "word at the same time. When the model reaches the word it it can\n",
+ "look back at all the previous words and decide which one matters\n",
+ "most. In this case it would look at mat because warmth is a\n",
+ "property of objects not animals.\n",
+ "\n",
+ "The way attention decides how much to care about each word is\n",
+ "through something called queries keys and values. Think of it\n",
+ "like being at a party. Your query is what you are looking for.\n",
+ "Every other person has a key that says what they offer. A high\n",
+ "match means you pay attention to that person.\n",
+ "\n",
+ "In this notebook we build the full attention mechanism from\n",
+ "scratch. We trace a worked example with real numbers so you\n",
+ "can see exactly what happens inside every modern language model."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The scale of this notebook\n",
+ "\n",
+ "We are building attention at the same size that GPT-2 Small used.\n",
+ "That means d_model of 768 and num_heads of 12. Each head gets 64\n",
+ "dimensions to work with. The full attention layer has about 2.3\n",
+ "million parameters.\n",
+ "\n",
+ "This is small enough to run on a laptop but big enough to show\n",
+ "you how real language models work. The math does not change at\n",
+ "bigger sizes. Only the numbers get larger.\n",
+ "\n",
+ "Here is what changes when you scale up. The architecture stays\n",
+ "the same. The dimensions just grow. These numbers come from the\n",
+ "original GPT-3 paper published by OpenAI.\n",
+ "\n",
+ "| Model | Layers | d_model | Heads | Params |\n",
+ "|---|---|---|---|---|\n",
+ "| GPT-2 Small | 12 | 768 | 12 | 124M |\n",
+ "| GPT-2 Medium | 24 | 1024 | 16 | 350M |\n",
+ "| GPT-2 Large | 36 | 1280 | 20 | 774M |\n",
+ "| GPT-3 350M | 24 | 1024 | 16 | 350M |\n",
+ "| GPT-3 1.3B | 24 | 2048 | 24 | 1.3B |\n",
+ "| GPT-3 6.7B | 32 | 4096 | 32 | 6.7B |\n",
+ "| GPT-3 175B | 96 | 12288 | 96 | 175B |\n",
+ "| LLaMA 7B | 32 | 4096 | 32 | 7B |\n",
+ "| LLaMA 13B | 40 | 5120 | 40 | 13B |\n",
+ "| LLaMA 70B | 80 | 8192 | 64 | 70B |\n",
+ "\n",
+ "GPT-3 175B uses the exact same attention formula we are about\n",
+ "to write. It just runs it with 96 layers instead of 12 and with\n",
+ "12288 dimensions instead of 768. The code is identical. The\n",
+ "numbers are just a thousand times bigger.\n",
+ "\n",
+ "You cannot run GPT-3 175B on a consumer GPU. It needs several\n",
+ "data center GPUs and millions of dollars in electricity. But the\n",
+ "notebook you are about to run captures the same idea at a size\n",
+ "you can actually play with and understand."
+ ]
+ },
+ {
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Rotary Position Embeddings\n",
+ "\n",
+ "We need RoPE from the previous chapter. It rotates query and key\n",
+ "vectors so the attention score depends on relative position."
+ ]
+ },
+ {
+ "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, \"d_model must be even\"\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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Causal Mask\n",
+ "\n",
+ "During training each token can only see tokens before it. This\n",
+ "prevents the model from cheating by looking at future words."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Multi-Head Attention\n",
+ "\n",
+ "This is the complete attention module. It does eight things in\n",
+ "order. Project to Q K and V. Reshape into multiple heads. Apply\n",
+ "RoPE. Compute scaled dot product scores. Apply the causal mask.\n",
+ "Run softmax. Weight the values. Merge heads and project out."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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",
+ "\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",
+ "\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",
+ "\n",
+ " q = self.rotary(q, seq_len)\n",
+ " k = self.rotary(k, seq_len)\n",
+ "\n",
+ " attn_scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",
+ "\n",
+ " if mask is not None:\n",
+ " attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))\n",
+ "\n",
+ " attn_weights = F.softmax(attn_scores, dim=-1)\n",
+ " attn_weights = self.attn_dropout(attn_weights)\n",
+ "\n",
+ " attn_output = attn_weights @ v\n",
+ "\n",
+ " attn_output = attn_output.transpose(1, 2).contiguous()\n",
+ " attn_output = attn_output.reshape(batch_size, seq_len, self.d_model)\n",
+ "\n",
+ " output = self.out_proj(attn_output)\n",
+ " output = self.resid_dropout(output)\n",
+ " return output"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Test the attention module\n",
+ "\n",
+ "Create a tiny model with 12 attention heads and feed it a batch\n",
+ "of 8 sequences of 64 tokens each."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "attn = MultiHeadAttention(d_model=768, num_heads=12)\n",
+ "\n",
+ "batch_size = 8\n",
+ "seq_len = 64\n",
+ "x = torch.randn(batch_size, seq_len, 768)\n",
+ "mask = create_causal_mask(seq_len, x.device)\n",
+ "\n",
+ "output = attn(x, mask)\n",
+ "print(f\"Input shape: {x.shape}\")\n",
+ "print(f\"Output shape: {output.shape}\")\n",
+ "print(f\"Input and output shapes match: {x.shape == output.shape}\")\n",
+ "print()\n",
+ "\n",
+ "params = sum(p.numel() for p in attn.parameters())\n",
+ "print(f\"Attention parameters: {params:,}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Worked example with real numbers\n",
+ "\n",
+ "Now let us trace through attention with a tiny 3 token sentence.\n",
+ "We will use d_model of 4 and a single head so we can see every\n",
+ "number."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tiny_attn = MultiHeadAttention(d_model=4, num_heads=1)\n",
+ "\n",
+ "tokens = torch.tensor([[\n",
+ " [0.5, 0.2, -0.3, 0.8],\n",
+ " [0.1, -0.5, 0.7, -0.2],\n",
+ " [0.9, 0.3, -0.1, -0.5],\n",
+ "]])\n",
+ "print(f\"Input tokens shape: {tokens.shape}\")\n",
+ "print()\n",
+ "\n",
+ "with torch.no_grad():\n",
+ " qkv = tiny_attn.qkv_proj(tokens)\n",
+ " qkv = qkv.reshape(1, 3, 3, 1, 4)\n",
+ " qkv = qkv.permute(2, 0, 3, 1, 4)\n",
+ " q, k, v = qkv[0], qkv[1], qkv[2]\n",
+ "\n",
+ "print(\"Query vectors:\")\n",
+ "for i in range(3):\n",
+ " vals = [f\"{v:.3f}\" for v in q[0, 0, i].tolist()]\n",
+ " print(f\" Token {i}: [{', '.join(vals)}]\")\n",
+ "print()\n",
+ "\n",
+ "print(\"Key vectors:\")\n",
+ "for i in range(3):\n",
+ " vals = [f\"{v:.3f}\" for v in k[0, 0, i].tolist()]\n",
+ " print(f\" Token {i}: [{', '.join(vals)}]\")\n",
+ "print()\n",
+ "\n",
+ "scores = (q @ k.transpose(-2, -1)) / math.sqrt(4)\n",
+ "print(\"Attention scores (before mask and softmax):\")\n",
+ "print(f\" Token 0: {[f'{v:.3f}' for v in scores[0, 0, 0].tolist()]}\")\n",
+ "print(f\" Token 1: {[f'{v:.3f}' for v in scores[0, 0, 1].tolist()]}\")\n",
+ "print(f\" Token 2: {[f'{v:.3f}' for v in scores[0, 0, 2].tolist()]}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Apply causal mask and softmax\n",
+ "\n",
+ "The causal mask sets future positions to negative infinity.\n",
+ "After softmax those positions become zero. Each token can only\n",
+ "attend to itself and tokens that came before it."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "mask = create_causal_mask(3, scores.device)\n",
+ "scores_masked = scores.masked_fill(mask == 0, float('-inf'))\n",
+ "weights = F.softmax(scores_masked, dim=-1)\n",
+ "\n",
+ "print(\"Attention weights (after mask and softmax):\")\n",
+ "for i in range(3):\n",
+ " row = [f\"{v:.3f}\" for v in weights[0, 0, i].tolist()]\n",
+ " print(f\" Token {i} attends to: [{', '.join(row)}]\")\n",
+ "print()\n",
+ "print(\"Token 0 sees only itself. Token 1 sees 0 and 1. Token 2 sees all three.\")\n",
+ "print()\n",
+ "\n",
+ "output = weights @ v\n",
+ "print(\"Output vectors (weighted sum of values):\")\n",
+ "for i in range(3):\n",
+ " vals = [f\"{v:.3f}\" for v in output[0, 0, i].tolist()]\n",
+ " print(f\" Token {i}: [{', '.join(vals)}]\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing the causal attention matrix\n",
+ "\n",
+ "Each row is a token. Each column is what it attends to. The\n",
+ "upper triangle is empty because future tokens are blocked."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Causal attention matrix (Token i attending to Token j):\")\n",
+ "print(\" T0 T1 T2\")\n",
+ "for i in range(3):\n",
+ " row = \" \".join([f\"{weights[0, 0, i, j]:.3f}\" for j in range(3)])\n",
+ " print(f\"T{i} {row}\")\n",
+ "print()\n",
+ "print(\"The upper right is zero. The model cannot see the future.\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python",
+ "version": "3.10.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file