Skip to content

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

chapter 6 where we make a resuable block to stack to build a model

raiyanyahyadad64906b978
diff --git a/notebooks/06_transformer_block.ipynb b/notebooks/06_transformer_block.ipynb
new file mode 100644
index 0000000..be7e9ab
--- /dev/null
+++ b/notebooks/06_transformer_block.ipynb
@@ -0,0 +1,346 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Transformer Block\n",
+ "\n",
+ "Now we have attention. But attention alone is not enough. We need\n",
+ "to wrap it in a complete building block that the model can stack\n",
+ "many times. This is the transformer block.\n",
+ "\n",
+ "GPT-2 Small stacks 12 of these blocks. GPT-3 stacks 96 of them.\n",
+ "LLaMA 70B stacks 80. Every modern language model is made by\n",
+ "repeating this same block over and over. The block does not\n",
+ "change. Only the count changes.\n",
+ "\n",
+ "Each block has two parts. First attention lets every word talk to\n",
+ "every other word. Then a feed forward network lets each word\n",
+ "think privately about what it just heard. Between both parts we\n",
+ "normalize the input and we add a skip connection that lets the\n",
+ "original signal pass through untouched.\n",
+ "\n",
+ "The skip connection is the secret to deep networks. Without it\n",
+ "gradients vanish and training fails beyond a few layers. With it\n",
+ "gradients have a highway straight back to the first layer. This\n",
+ "is why we can stack 12 or 96 or 100 of these blocks and they all\n",
+ "keep learning.\n",
+ "\n",
+ "In this notebook we build the complete transformer block using\n",
+ "RMSNorm for normalization and SwiGLU for the feed forward layer.\n",
+ "These are the modern choices used by LLaMA and Mistral. We will\n",
+ "also bring in the attention module we wrote in the last chapter\n",
+ "to keep this notebook self contained."
+ ]
+ },
+ {
+ "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",
+ "From chapter 4. We need this for the attention module."
+ ]
+ },
+ {
+ "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)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Causal Mask"
+ ]
+ },
+ {
+ "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",
+ "From chapter 5. The full attention module with RoPE and causal masking."
+ ]
+ },
+ {
+ "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": [
+ "## RMSNorm\n",
+ "\n",
+ "Root Mean Square normalization. Simpler and faster than LayerNorm.\n",
+ "Divides by the root mean square of the vector. No centering needed."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## SwiGLU\n",
+ "\n",
+ "A gated feed forward network. Better than ReLU or GELU at scale.\n",
+ "One path produces values. The other path produces gates that\n",
+ "control how much of each value passes through."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Transformer Block\n",
+ "\n",
+ "This assembles everything. Two sub layers each with pre norm\n",
+ "and a residual connection. Attention mixes information between\n",
+ "tokens. SwiGLU processes each token independently."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "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": [
+ "## Test the block\n",
+ "\n",
+ "Create one transformer block at GPT-2 scale and run it."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d_model = 768\n",
+ "num_heads = 12\n",
+ "seq_len = 64\n",
+ "batch_size = 4\n",
+ "\n",
+ "block = TransformerBlock(d_model, num_heads)\n",
+ "\n",
+ "x = torch.randn(batch_size, seq_len, d_model)\n",
+ "mask = create_causal_mask(seq_len, x.device)\n",
+ "\n",
+ "output = block(x, mask)\n",
+ "\n",
+ "print(f\"Input shape: {x.shape}\")\n",
+ "print(f\"Output shape: {output.shape}\")\n",
+ "print(f\"Shapes match: {x.shape == output.shape}\")\n",
+ "print()\n",
+ "\n",
+ "diff = (output - x).abs().mean().item()\n",
+ "print(f\"Mean change after block: {diff:.4f}\")\n",
+ "print(f\"The block changed the input (it did something)\")\n",
+ "print()\n",
+ "\n",
+ "params = sum(p.numel() for p in block.parameters())\n",
+ "print(f\"Parameters per block: {params:,}\")\n",
+ "print(f\"For a 12 layer GPT-2 Small: {params * 12:,} params in all blocks\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The residual connection at work\n",
+ "\n",
+ "Set attention and FFN to output zero. The input should pass\n",
+ "through unchanged because of the skip connection."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "block.eval()\n",
+ "with torch.no_grad():\n",
+ " for p in block.attention.parameters():\n",
+ " p.zero_()\n",
+ " for p in block.ffn.parameters():\n",
+ " p.zero_()\n",
+ "\n",
+ "x = torch.randn(1, 4, d_model)\n",
+ "mask = create_causal_mask(4, x.device)\n",
+ "output = block(x, mask)\n",
+ "\n",
+ "diff = (output - x).abs().max().item()\n",
+ "print(f\"Max difference when weights are zero: {diff:.10f}\")\n",
+ "print(f\"Input passes through unchanged (the residual works)\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python",
+ "version": "3.10.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}