{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 3.2 · The Transformer Block\n", "\n", "**Goal:** build a pre-norm GPT-2 Transformer block in PyTorch from `nn.Linear` pieces (no\n", "`nn.Transformer`), verify LayerNorm by hand on a 4-number vector, measure how layer-1 gradients\n", "behave from 2 to 32 blocks with and without residual connections and LayerNorm, test order\n", "blindness and 2-D rotary position embeddings (RoPE), verify GPT-2 small's exact parameter count\n", "(`124,439,808`), and diagnose three deliberate block failures.\n", "\n", "**Runs on:** any laptop (CPU, plus Apple `mps` or NVIDIA `cuda` when present); also Kaggle or\n", "Colab. Install locally with `uv run --with torch --with matplotlib`.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-3-2-block-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import math\n", "import pathlib\n", "import platform\n", "\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "DEVICES = [\"cpu\"]\n", "if torch.cuda.is_available():\n", " DEVICES.append(\"cuda\")\n", "elif torch.backends.mps.is_available():\n", " DEVICES.append(\"mps\")\n", "\n", "print(\"PyTorch\", torch.__version__, \"| devices available:\", DEVICES)\n", "\n", "\n", "def out_dir():\n", " for candidate in (pathlib.Path(\"data\"), pathlib.Path(\"../data\")):\n", " if candidate.is_dir():\n", " d = candidate / \"lab-3-2-block\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Before running the cells below, write down your answers:\n", "\n", "1. Take the 4-number vector `x = [3, 9, 11, 17]`. Compute its mean `μ`, population variance `σ²`,\n", " standard deviation `σ`, and normalized values `(x − μ) / σ` by hand. What happens to the\n", " normalized output if you multiply every entry by 10 (`[30, 90, 110, 170]`) or add 100\n", " (`[103, 109, 111, 117]`)?\n", "2. Stack `L = 2, 8, 32` Transformer blocks (`d_model = 64`, `n_head = 4`) and run one backward\n", " pass from a next-token cross-entropy loss. Predict how layer 1's gradient norm will behave as\n", " `L` grows to 32 in four cases: (a) residuals + LayerNorm, (b) residuals removed, (c) LayerNorm\n", " removed, and (d) both removed.\n", "3. Pass the two 3-token sequences `\"dog bites man\"` and `\"man bites dog\"` through a Transformer\n", " block with **no** position embeddings and no causal mask. How will the output vector of `\"bites\"`\n", " (and of `\"dog\"` and `\"man\"`) compare between the two sentences?\n", "4. In one GPT-2 small block (`d_model = 768`, `n_head = 12`, MLP width `4 × d_model = 3,072`),\n", " which sublayer holds more parameters — multi-head attention or the two-layer MLP — and roughly\n", " what fraction of the block does each take?" ], "id": "lab-3-2-block-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · LayerNorm by hand vs `nn.LayerNorm`\n", "\n", "LayerNorm normalises **each token's feature vector independently** across its last dimension\n", "(`dim = -1`): subtract the mean across features, divide by `sqrt(var + eps)` (using the population\n", "variance `unbiased=False`), then apply a learnable per-feature scale `gamma` (init `1`) and shift\n", "`beta` (init `0`)." ], "id": "lab-3-2-block-03" }, { "cell_type": "code", "metadata": {}, "source": [ "def layer_norm_by_hand(x, gamma, beta, eps=1e-5):\n", " mean = x.mean(dim=-1, keepdim=True)\n", " var = x.var(dim=-1, unbiased=False, keepdim=True)\n", " x_hat = (x - mean) / torch.sqrt(var + eps)\n", " return gamma * x_hat + beta\n", "\n", "\n", "x_vec = torch.tensor([3.0, 9.0, 11.0, 17.0])\n", "gamma_1 = torch.ones(4)\n", "beta_0 = torch.zeros(4)\n", "\n", "mu = x_vec.mean().item()\n", "var = x_vec.var(unbiased=False).item()\n", "std_eps = math.sqrt(var + 1e-5)\n", "y_hand = layer_norm_by_hand(x_vec, gamma_1, beta_0, eps=1e-5)\n", "\n", "ln_torch = nn.LayerNorm(4, eps=1e-5)\n", "with torch.no_grad():\n", " y_torch = ln_torch(x_vec)\n", "\n", "print(f\"x = {x_vec.tolist()}\")\n", "print(f\"mean = {mu:.4f}, var = {var:.4f}, sqrt(var + 1e-5) = {std_eps:.6f}\")\n", "print(f\"by hand = {[round(v, 6) for v in y_hand.tolist()]}\")\n", "print(f\"PyTorch = {[round(v, 6) for v in y_torch.tolist()]}\")\n", "print(f\"max abs diff (hand vs nn.LayerNorm): {(y_hand - y_torch).abs().max().item():.2e}\")\n", "print(f\"output mean = {y_hand.mean().item():+.6f}, output var = {y_hand.var(unbiased=False).item():.6f}\")\n", "\n", "# Scale and shift invariance: 10*x and x + 100 map to the same normalized vector\n", "y_scaled = ln_torch(10.0 * x_vec)\n", "y_shifted = ln_torch(x_vec + 100.0)\n", "print(f\"max diff on 10*x : {(y_scaled - y_torch).abs().max().item():.2e}\")\n", "print(f\"max diff on x + 100 : {(y_shifted - y_torch).abs().max().item():.2e}\")\n", "\n", "# Learnable gamma and beta restore any per-feature scale and offset the layer needs\n", "gamma_custom = torch.tensor([2.0, 0.5, 1.0, 1.5])\n", "beta_custom = torch.tensor([0.0, 1.0, -0.5, 0.25])\n", "y_affine = layer_norm_by_hand(x_vec, gamma_custom, beta_custom, eps=1e-5)\n", "print(f\"with gamma={gamma_custom.tolist()}, beta={beta_custom.tolist()}:\")\n", "print(f\" output = {[round(v, 4) for v in y_affine.tolist()]}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Build the Transformer block from `nn.Linear` pieces\n", "\n", "A pre-norm GPT-2 block runs two sublayers around an unobstructed **residual stream**:\n", "\n", "```text\n", "x = x + MultiHeadAttention(LayerNorm(x))\n", "x = x + MLP(LayerNorm(x))\n", "```\n", "\n", "We build every piece from `nn.Linear` and `nn.LayerNorm` — no `nn.Transformer` or\n", "`nn.MultiheadAttention` — and trace the tensor shape at every step." ], "id": "lab-3-2-block-05" }, { "cell_type": "code", "metadata": {}, "source": [ "class MultiHeadAttention(nn.Module):\n", " def __init__(self, d_model, n_head, causal=True):\n", " super().__init__()\n", " assert d_model % n_head == 0, \"d_model must be divisible by n_head\"\n", " self.d_model = d_model\n", " self.n_head = n_head\n", " self.head_dim = d_model // n_head\n", " self.causal = causal\n", " self.w_q = nn.Linear(d_model, d_model)\n", " self.w_k = nn.Linear(d_model, d_model)\n", " self.w_v = nn.Linear(d_model, d_model)\n", " self.w_o = nn.Linear(d_model, d_model)\n", "\n", " def forward(self, x, trace=False):\n", " B, T, C = x.shape\n", " q = self.w_q(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2) # [B, H, T, d_h]\n", " k = self.w_k(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2)\n", " v = self.w_v(x).view(B, T, self.n_head, self.head_dim).transpose(1, 2)\n", " scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim) # [B, H, T, T]\n", " if self.causal:\n", " mask = torch.triu(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=1)\n", " scores = scores.masked_fill(mask, float(\"-inf\"))\n", " weights = F.softmax(scores, dim=-1) # [B, H, T, T]\n", " out = weights @ v # [B, H, T, d_h]\n", " concat = out.transpose(1, 2).contiguous().view(B, T, C) # [B, T, C]\n", " proj = self.w_o(concat) # [B, T, C]\n", " if trace:\n", " print(f\" attn: Q/K/V {tuple(q.shape)} -> scores {tuple(scores.shape)} -> \"\n", " f\"concat {tuple(concat.shape)} -> proj {tuple(proj.shape)}\")\n", " return proj\n", "\n", "\n", "class FeedForward(nn.Module):\n", " def __init__(self, d_model, expansion=4):\n", " super().__init__()\n", " self.fc1 = nn.Linear(d_model, expansion * d_model)\n", " self.fc2 = nn.Linear(expansion * d_model, d_model)\n", "\n", " def forward(self, x, trace=False):\n", " h = self.fc1(x)\n", " h_act = F.gelu(h)\n", " out = self.fc2(h_act)\n", " if trace:\n", " print(f\" mlp : fc1 {tuple(h.shape)} -> GELU {tuple(h_act.shape)} -> fc2 {tuple(out.shape)}\")\n", " return out\n", "\n", "\n", "class TransformerBlock(nn.Module):\n", " def __init__(self, d_model, n_head, causal=True, use_residual=True, norm_mode=\"pre\"):\n", " super().__init__()\n", " self.use_residual = use_residual\n", " self.norm_mode = norm_mode\n", " self.ln1 = nn.LayerNorm(d_model) if norm_mode != \"none\" else nn.Identity()\n", " self.attn = MultiHeadAttention(d_model, n_head, causal=causal)\n", " self.ln2 = nn.LayerNorm(d_model) if norm_mode != \"none\" else nn.Identity()\n", " self.mlp = FeedForward(d_model, expansion=4)\n", "\n", " def forward(self, x, trace=False):\n", " if trace:\n", " print(f\" input x : {tuple(x.shape)}\")\n", " if self.norm_mode == \"pre\":\n", " h1 = self.ln1(x)\n", " a = self.attn(h1, trace=trace)\n", " x = x + a if self.use_residual else a\n", " if trace:\n", " print(f\" after attn + res : {tuple(x.shape)}\")\n", " h2 = self.ln2(x)\n", " m = self.mlp(h2, trace=trace)\n", " x = x + m if self.use_residual else m\n", " if trace:\n", " print(f\" after mlp + res : {tuple(x.shape)}\")\n", " elif self.norm_mode == \"post\":\n", " a = self.attn(x, trace=trace)\n", " x = self.ln1(x + a if self.use_residual else a)\n", " m = self.mlp(x, trace=trace)\n", " x = self.ln2(x + m if self.use_residual else m)\n", " else:\n", " a = self.attn(x, trace=trace)\n", " x = x + a if self.use_residual else a\n", " m = self.mlp(x, trace=trace)\n", " x = x + m if self.use_residual else m\n", " return x\n", "\n", "\n", "def count_params(module):\n", " return sum(p.numel() for p in module.parameters())\n", "\n", "\n", "torch.manual_seed(0)\n", "demo_block = TransformerBlock(d_model=64, n_head=4, causal=True)\n", "x_demo = torch.randn(2, 8, 64)\n", "print(\"Shape trace through one TransformerBlock (B=2, T=8, d_model=64, n_head=4):\")\n", "y_demo = demo_block(x_demo, trace=True)\n", "print(f\"Output shape matches input shape: {tuple(y_demo.shape) == tuple(x_demo.shape)}\")\n", "print(f\"Parameters in this d_model=64 block: {count_params(demo_block):,d}\")\n", "print(f\" formula 12*d^2 + 13*d = {12 * 64**2 + 13 * 64:,d}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Residual connections as a gradient highway: gradient norm vs depth\n", "\n", "Stack `L = 2, 4, 8, 16, 32` blocks (`d_model = 64`, `n_head = 4`, batch `4`, sequence length `16`),\n", "predict next tokens over a 100-token toy vocabulary with cross-entropy, and run one backward pass.\n", "We measure four ablations:\n", "\n", "1. **`res_and_ln`**: the real pre-norm Transformer block (residual + LayerNorm).\n", "2. **`no_res_with_ln`**: residual connections removed, LayerNorm kept.\n", "3. **`res_no_ln`**: residuals kept, LayerNorm removed.\n", "4. **`no_res_no_ln`**: neither residuals nor LayerNorm.\n", "\n", "For each depth and ablation we record the final activation standard deviation `act_std`, the\n", "gradient norm reaching the stack input `||dL/dx||`, layer 1's attention query weight gradient\n", "`||dL/dW_q0||`, layer 1's total parameter gradient norm `||dL/dblock_0||`, and the last layer's\n", "total parameter gradient norm `||dL/dblock_L||`." ], "id": "lab-3-2-block-07" }, { "cell_type": "code", "metadata": {}, "source": [ "DEPTHS = [2, 4, 8, 16, 32]\n", "VARIANTS = [\n", " (\"res_and_ln\", True, \"pre\"),\n", " (\"no_res_with_ln\", False, \"pre\"),\n", " (\"res_no_ln\", True, \"none\"),\n", " (\"no_res_no_ln\", False, \"none\"),\n", "]\n", "\n", "\n", "def measure_stack(depth, use_residual, norm_mode, d_model=64, n_head=4, vocab_size=100, seed=0):\n", " torch.manual_seed(seed)\n", " blocks = nn.ModuleList([\n", " TransformerBlock(d_model, n_head, causal=True, use_residual=use_residual, norm_mode=norm_mode)\n", " for _ in range(depth)\n", " ])\n", " ln_f = nn.LayerNorm(d_model) if norm_mode == \"pre\" else nn.Identity()\n", " head = nn.Linear(d_model, vocab_size, bias=False)\n", "\n", " x = torch.randn(4, 16, d_model, requires_grad=True)\n", " targets = torch.randint(0, vocab_size, (4, 16))\n", "\n", " h = x\n", " for blk in blocks:\n", " h = blk(h)\n", " act_std = h.std().item()\n", "\n", " logits = head(ln_f(h))\n", " loss = F.cross_entropy(logits.view(-1, vocab_size), targets.view(-1))\n", " loss.backward()\n", "\n", " grad_input = x.grad.norm().item()\n", " grad_wq0 = blocks[0].attn.w_q.weight.grad.norm().item()\n", " grad_block0 = math.sqrt(sum(p.grad.pow(2).sum().item() for p in blocks[0].parameters()))\n", " grad_blockL = math.sqrt(sum(p.grad.pow(2).sum().item() for p in blocks[-1].parameters()))\n", " return {\n", " \"variant\": \"\",\n", " \"depth\": depth,\n", " \"act_std\": act_std,\n", " \"grad_input\": grad_input,\n", " \"grad_wq0\": grad_wq0,\n", " \"grad_block0\": grad_block0,\n", " \"grad_blockL\": grad_blockL,\n", " }\n", "\n", "\n", "grad_rows = []\n", "print(f\"{'variant':15s} {'L':>3s} {'act_std':>10s} {'||dx||':>10s} {'||dw_q0||':>10s} {'||gb0||':>10s} {'||gbL||':>10s}\")\n", "print(\"-\" * 74)\n", "for name, use_res, norm_mode in VARIANTS:\n", " for L in DEPTHS:\n", " row = measure_stack(L, use_res, norm_mode)\n", " row[\"variant\"] = name\n", " grad_rows.append(row)\n", " print(\n", " f\"{name:15s} {L:3d} {row['act_std']:10.3e} {row['grad_input']:10.3e} \"\n", " f\"{row['grad_wq0']:10.3e} {row['grad_block0']:10.3e} {row['grad_blockL']:10.3e}\"\n", " )\n", "\n", "grad_csv = out_dir() / \"grad-vs-depth.csv\"\n", "with grad_csv.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(\n", " f,\n", " fieldnames=[\"variant\", \"depth\", \"act_std\", \"grad_input\", \"grad_wq0\", \"grad_block0\", \"grad_blockL\"],\n", " lineterminator=\"\\n\",\n", " )\n", " w.writeheader()\n", " for r in grad_rows:\n", " w.writerow({\n", " \"variant\": r[\"variant\"],\n", " \"depth\": r[\"depth\"],\n", " \"act_std\": f\"{r['act_std']:.6e}\",\n", " \"grad_input\": f\"{r['grad_input']:.6e}\",\n", " \"grad_wq0\": f\"{r['grad_wq0']:.6e}\",\n", " \"grad_block0\": f\"{r['grad_block0']:.6e}\",\n", " \"grad_blockL\": f\"{r['grad_blockL']:.6e}\",\n", " })\n", "print(\"\\nsaved\", grad_csv)" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-08" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, axes = plt.subplots(1, 3, figsize=(14, 4))\n", " metrics = [\n", " (\"grad_wq0\", \"Layer-1 attention ||dL/dW_q0||\", True),\n", " (\"grad_input\", \"Input ||dL/dx||\", True),\n", " (\"act_std\", \"Final activation std\", True),\n", " ]\n", " for ax, (key, title, logy) in zip(axes, metrics):\n", " for name, _, _ in VARIANTS:\n", " sub = [r for r in grad_rows if r[\"variant\"] == name]\n", " xs = [r[\"depth\"] for r in sub]\n", " # Floor literal 0.0 at 1e-24 for log plotting only (labeled on axis)\n", " ys = [max(r[key], 1e-24) if logy else r[key] for r in sub]\n", " ax.plot(xs, ys, marker=\"o\", label=name)\n", " ax.set_xscale(\"log\", base=2)\n", " ax.set_xticks(DEPTHS)\n", " ax.set_xticklabels([str(d) for d in DEPTHS])\n", " if logy:\n", " ax.set_yscale(\"log\")\n", " ax.set_xlabel(\"depth (number of blocks)\")\n", " ax.set_title(title)\n", " ax.grid(True, alpha=0.3)\n", " axes[0].legend(fontsize=8)\n", " plt.tight_layout()\n", " plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Position information: permutation test, learned embeddings and 2-D RoPE\n", "\n", "### 5a · Permutation test (with and without position embeddings)\n", "\n", "Without position embeddings, an unmasked Transformer block treats its input sequence as an\n", "unordered set: permuting the input tokens permutes the output vectors identically. Adding learned\n", "position embeddings breaks that symmetry immediately. Even with a **causal** mask enabled, a\n", "single block without position embeddings still produces the exact same output at the final token\n", "`\".\"` for `\"dog bites man .\"` and `\"man bites dog .\"`, because both prefixes contain the same set\n", "of earlier tokens." ], "id": "lab-3-2-block-10" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(7)\n", "VOCAB = {\"dog\": 0, \"bites\": 1, \"man\": 2, \".\": 3}\n", "d_toy = 16\n", "wte_toy = nn.Embedding(len(VOCAB), d_toy)\n", "wpe_toy = nn.Embedding(8, d_toy)\n", "\n", "blk_bidir = TransformerBlock(d_model=d_toy, n_head=4, causal=False)\n", "blk_causal = TransformerBlock(d_model=d_toy, n_head=4, causal=True)\n", "\n", "ids_a = torch.tensor([[VOCAB[\"dog\"], VOCAB[\"bites\"], VOCAB[\"man\"]]]) # [1, 3]\n", "ids_b = torch.tensor([[VOCAB[\"man\"], VOCAB[\"bites\"], VOCAB[\"dog\"]]]) # perm [2, 1, 0]\n", "perm = [2, 1, 0]\n", "\n", "with torch.no_grad():\n", " # Unmasked block, NO position embeddings\n", " out_a_nopos = blk_bidir(wte_toy(ids_a))\n", " out_b_nopos = blk_bidir(wte_toy(ids_b))\n", " diff_bidir_nopos = (out_b_nopos - out_a_nopos[:, perm, :]).abs().max().item()\n", "\n", " # Unmasked block, WITH learned position embeddings\n", " pos3 = torch.arange(3).unsqueeze(0)\n", " out_a_pos = blk_bidir(wte_toy(ids_a) + wpe_toy(pos3))\n", " out_b_pos = blk_bidir(wte_toy(ids_b) + wpe_toy(pos3))\n", " diff_bidir_pos = (out_b_pos - out_a_pos[:, perm, :]).abs().max().item()\n", "\n", " # Causal block on \"dog bites man .\" vs \"man bites dog .\" at final position \".\"\n", " ids_ca = torch.tensor([[VOCAB[\"dog\"], VOCAB[\"bites\"], VOCAB[\"man\"], VOCAB[\".\"]]])\n", " ids_cb = torch.tensor([[VOCAB[\"man\"], VOCAB[\"bites\"], VOCAB[\"dog\"], VOCAB[\".\"]]])\n", " pos4 = torch.arange(4).unsqueeze(0)\n", " out_ca_nopos = blk_causal(wte_toy(ids_ca))\n", " out_cb_nopos = blk_causal(wte_toy(ids_cb))\n", " diff_causal_nopos = (out_ca_nopos[0, 3] - out_cb_nopos[0, 3]).abs().max().item()\n", "\n", " out_ca_pos = blk_causal(wte_toy(ids_ca) + wpe_toy(pos4))\n", " out_cb_pos = blk_causal(wte_toy(ids_cb) + wpe_toy(pos4))\n", " diff_causal_pos = (out_ca_pos[0, 3] - out_cb_pos[0, 3]).abs().max().item()\n", "\n", "print(\"Unmasked block ('dog bites man' vs 'man bites dog', compared after un-permuting [2,1,0]):\")\n", "print(f\" without position embeddings : max abs diff = {diff_bidir_nopos:.2e}\")\n", "print(f\" with position embeddings : max abs diff = {diff_bidir_pos:.4f}\")\n", "print(\"\\nCausal block ('dog bites man .' vs 'man bites dog .', final token '.' output):\")\n", "print(f\" without position embeddings : max abs diff = {diff_causal_nopos:.2e}\")\n", "print(f\" with position embeddings : max abs diff = {diff_causal_pos:.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5b · Rotary Position Embeddings (RoPE) in 2-D and `d_head` dimensions\n", "\n", "Instead of adding a learned vector to `x`, **RoPE** rotates each 2-D pair of coordinates in `Q`\n", "and `K` by an angle proportional to its token position `m`. Because rotating both vectors by the\n", "same extra angle leaves their dot product unchanged, `q_rot(m) · k_rot(n)` depends only on the\n", "**relative distance** `m − n`." ], "id": "lab-3-2-block-12" }, { "cell_type": "code", "metadata": {}, "source": [ "def rotate_2d(vec, angle_rad):\n", " c, s = math.cos(angle_rad), math.sin(angle_rad)\n", " x0, x1 = vec[0].item(), vec[1].item()\n", " return torch.tensor([x0 * c - x1 * s, x0 * s + x1 * c])\n", "\n", "\n", "theta_deg = 30.0\n", "theta = math.radians(theta_deg)\n", "\n", "# Worked 2-D example: q = [1, 0], k = [1, 0]\n", "q0 = torch.tensor([1.0, 0.0])\n", "k0 = torch.tensor([1.0, 0.0])\n", "print(f\"Worked 2-D RoPE (theta = {theta_deg:.0f} deg, q = [1, 0], k = [1, 0]):\")\n", "for m, n in [(3, 1), (5, 3), (10, 8)]:\n", " qm = rotate_2d(q0, m * theta)\n", " kn = rotate_2d(k0, n * theta)\n", " dot = torch.dot(qm, kn).item()\n", " print(f\" m={m:2d} ({m*theta_deg:3.0f} deg), n={n:2d} ({n*theta_deg:3.0f} deg), m-n={m-n} | \"\n", " f\"q_rot={[round(v, 4) for v in qm.tolist()]} k_rot={[round(v, 4) for v in kn.tolist()]} \"\n", " f\"dot = {dot:.4f}\")\n", "\n", "# Same invariance holds for arbitrary non-unit vectors q = [2, 1], k = [1, 3]\n", "q_arb = torch.tensor([2.0, 1.0])\n", "k_arb = torch.tensor([1.0, 3.0])\n", "dots_arb = [torch.dot(rotate_2d(q_arb, m * theta), rotate_2d(k_arb, n * theta)).item()\n", " for m, n in [(3, 1), (5, 3), (10, 8)]]\n", "print(f\"\\nArbitrary vectors q=[2, 1], k=[1, 3] at (3,1), (5,3), (10,8):\")\n", "print(f\" dot products = {[round(d, 6) for d in dots_arb]} (spread = {max(dots_arb) - min(dots_arb):.2e})\")\n", "\n", "\n", "# General d_head RoPE (pairs of coordinates with frequencies 10000^(-2i / d_head))\n", "def apply_rope(x, positions, base=10000.0):\n", " # x: [T, d_head], positions: [T]\n", " d = x.shape[-1]\n", " i = torch.arange(0, d, 2, dtype=x.dtype, device=x.device)\n", " freqs = base ** (-i / d) # [d/2]\n", " angles = positions.to(x.dtype).unsqueeze(-1) * freqs # [T, d/2]\n", " cos_a, sin_a = torch.cos(angles), torch.sin(angles)\n", " x_even, x_odd = x[..., 0::2], x[..., 1::2]\n", " out_even = x_even * cos_a - x_odd * sin_a\n", " out_odd = x_even * sin_a + x_odd * cos_a\n", " return torch.stack([out_even, out_odd], dim=-1).flatten(-2)\n", "\n", "\n", "torch.manual_seed(0)\n", "q_hd = torch.randn(1, 16)\n", "k_hd = torch.randn(1, 16)\n", "dot_pos_3_1 = (apply_rope(q_hd, torch.tensor([3])) * apply_rope(k_hd, torch.tensor([1]))).sum().item()\n", "dot_pos_17_15 = (apply_rope(q_hd, torch.tensor([17])) * apply_rope(k_hd, torch.tensor([15]))).sum().item()\n", "print(f\"\\nFull d_head=16 RoPE (distance m-n = 2):\")\n", "print(f\" dot(m=3, n=1) = {dot_pos_3_1:.6f}\")\n", "print(f\" dot(m=17, n=15) = {dot_pos_17_15:.6f}\")\n", "print(f\" abs diff = {abs(dot_pos_3_1 - dot_pos_17_15):.2e}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Parameter count of GPT-2 small (`124,439,808`)\n", "\n", "Assemble a GPT-2-small-sized model (`vocab_size = 50,257`, `max_seq_len = 1,024`,\n", "`d_model = 768`, `n_head = 12`, `n_layer = 12`, weight-tied output head) on PyTorch's `meta`\n", "device (zero RAM allocated, exact parameter shapes and counts), verify every component against the\n", "closed-form formulas, and save the breakdown to CSV." ], "id": "lab-3-2-block-14" }, { "cell_type": "code", "metadata": {}, "source": [ "class GPT2Architecture(nn.Module):\n", " def __init__(self, vocab_size=50257, max_seq_len=1024, d_model=768, n_head=12, n_layer=12):\n", " super().__init__()\n", " self.wte = nn.Embedding(vocab_size, d_model)\n", " self.wpe = nn.Embedding(max_seq_len, d_model)\n", " self.blocks = nn.ModuleList([TransformerBlock(d_model, n_head, causal=True) for _ in range(n_layer)])\n", " self.ln_f = nn.LayerNorm(d_model)\n", " self.lm_head = nn.Linear(d_model, vocab_size, bias=False)\n", " # Weight tying: share the token embedding table with the output projection\n", " self.lm_head.weight = self.wte.weight\n", "\n", "\n", "V, T_MAX, D, H, L = 50257, 1024, 768, 12, 12\n", "\n", "with torch.device(\"meta\"):\n", " gpt2_small = GPT2Architecture(V, T_MAX, D, H, L)\n", "\n", "blk0 = gpt2_small.blocks[0]\n", "p_attn = count_params(blk0.attn)\n", "p_mlp = count_params(blk0.mlp)\n", "p_lns = count_params(blk0.ln1) + count_params(blk0.ln2)\n", "p_block = count_params(blk0)\n", "p_blocks_all = count_params(gpt2_small.blocks)\n", "p_wte = count_params(gpt2_small.wte)\n", "p_wpe = count_params(gpt2_small.wpe)\n", "p_ln_f = count_params(gpt2_small.ln_f)\n", "p_total = count_params(gpt2_small) # PyTorch deduplicates the tied lm_head.weight automatically\n", "\n", "# Closed-form formulas\n", "f_attn = 4 * D * D + 4 * D\n", "f_mlp = 8 * D * D + 5 * D\n", "f_lns = 4 * D\n", "f_block = f_attn + f_mlp + f_lns\n", "f_total = V * D + T_MAX * D + L * f_block + 2 * D\n", "\n", "assert p_attn == f_attn and p_mlp == f_mlp and p_lns == f_lns and p_block == f_block\n", "assert p_total == f_total == 124_439_808\n", "\n", "print(\"One GPT-2 small block (d_model=768, n_head=12):\")\n", "print(f\" Multi-head attention (4d^2 + 4d) : {p_attn:10,d} ({100*p_attn/p_block:5.2f}% of block)\")\n", "print(f\" MLP (8d^2 + 5d) : {p_mlp:10,d} ({100*p_mlp/p_block:5.2f}% of block)\")\n", "print(f\" Two LayerNorms (4d) : {p_lns:10,d} ({100*p_lns/p_block:5.2f}% of block)\")\n", "print(f\" One block total (12d^2 + 13d) : {p_block:10,d}\")\n", "\n", "print(\"\\nFull GPT-2 small (12 blocks, V=50,257, T=1,024, tied output head):\")\n", "print(f\" Token embeddings (wte, tied) : {p_wte:11,d} ({100*p_wte/p_total:5.2f}%)\")\n", "print(f\" Position embeddings (wpe) : {p_wpe:11,d} ({100*p_wpe/p_total:5.2f}%)\")\n", "print(f\" 12 Transformer blocks : {p_blocks_all:11,d} ({100*p_blocks_all/p_total:5.2f}%)\")\n", "print(f\" Final LayerNorm (ln_f) : {p_ln_f:11,d} ({100*p_ln_f/p_total:5.3f}%)\")\n", "print(f\" Total (our PyTorch model) : {p_total:11,d}\")\n", "print(f\" Published GPT-2 small total : {124_439_808:11,d} (diff = {p_total - 124_439_808})\")\n", "\n", "try:\n", " from transformers import GPT2Config, GPT2LMHeadModel\n", " with torch.device(\"meta\"):\n", " hf_model = GPT2LMHeadModel(GPT2Config())\n", " p_hf = count_params(hf_model)\n", " print(f\" Hugging Face GPT2LMHeadModel : {p_hf:11,d} (diff = {p_hf - p_total})\")\n", "except ImportError:\n", " print(\" Verification note: transformers not installed in this environment; verified with our PyTorch model + closed-form formula.\")\n", "\n", "param_rows = [\n", " {\"scope\": \"block\", \"component\": \"attention\", \"formula\": \"4*d^2 + 4*d\", \"params\": p_attn, \"pct\": round(100 * p_attn / p_block, 2)},\n", " {\"scope\": \"block\", \"component\": \"mlp\", \"formula\": \"8*d^2 + 5*d\", \"params\": p_mlp, \"pct\": round(100 * p_mlp / p_block, 2)},\n", " {\"scope\": \"block\", \"component\": \"layernorms\", \"formula\": \"4*d\", \"params\": p_lns, \"pct\": round(100 * p_lns / p_block, 2)},\n", " {\"scope\": \"model\", \"component\": \"12_blocks\", \"formula\": \"12*(12*d^2+13*d)\", \"params\": p_blocks_all, \"pct\": round(100 * p_blocks_all / p_total, 2)},\n", " {\"scope\": \"model\", \"component\": \"token_emb_wte\", \"formula\": \"V*d\", \"params\": p_wte, \"pct\": round(100 * p_wte / p_total, 2)},\n", " {\"scope\": \"model\", \"component\": \"pos_emb_wpe\", \"formula\": \"T_max*d\", \"params\": p_wpe, \"pct\": round(100 * p_wpe / p_total, 2)},\n", " {\"scope\": \"model\", \"component\": \"final_ln\", \"formula\": \"2*d\", \"params\": p_ln_f, \"pct\": round(100 * p_ln_f / p_total, 3)},\n", "]\n", "param_csv = out_dir() / \"param-breakdown.csv\"\n", "with param_csv.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=[\"scope\", \"component\", \"formula\", \"params\", \"pct\"], lineterminator=\"\\n\")\n", " w.writeheader()\n", " w.writerows(param_rows)\n", "print(\"\\nsaved\", param_csv)" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Checkpoint\n", "\n", "Compare your outputs against the book's reference run (the last digit can differ across PyTorch\n", "versions and hardware):\n", "\n", "- **LayerNorm by hand on `[3, 9, 11, 17]`:** mean `10.0000`, variance `25.0000`,\n", " `sqrt(var + 1e-5) = 5.000001`, output `[-1.4, -0.2, 0.2, 1.4]`, max abs diff vs\n", " `nn.LayerNorm(4)` `1.19e-07`.\n", "- **Transformer block (`B=2, T=8, d_model=64, n_head=4`):** output shape `(2, 8, 64)`,\n", " `49,984` parameters (`12 × 64² + 13 × 64`).\n", "- **Gradient norm vs depth (`L = 2, 8, 32`):**\n", "\n", "```text\n", "res_and_ln 2 act_std=1.096e+00 ||dx||=7.045e-02 ||dw_q0||=4.593e-02 ||gb0||=4.844e-01\n", "res_and_ln 8 act_std=1.307e+00 ||dx||=7.283e-02 ||dw_q0||=3.523e-02 ||gb0||=5.428e-01\n", "res_and_ln 32 act_std=1.993e+00 ||dx||=6.701e-02 ||dw_q0||=3.606e-02 ||gb0||=5.473e-01\n", "no_res_with_ln 32 act_std=2.105e-01 ||dx||=9.217e-03 ||dw_q0||=4.538e-10 ||gb0||=4.629e-01\n", "res_no_ln 32 act_std=1.065e+01 ||dx||=4.368e+00 ||dw_q0||=2.524e+00 ||gb0||=4.324e+01\n", "no_res_no_ln 32 act_std=4.454e-02 ||dx||=0.000e+00 ||dw_q0||=0.000e+00 ||gb0||=0.000e+00\n", "```\n", "\n", "- **Permutation test (`seed = 7`):** without position embeddings, unmasked max diff `1.19e-07`\n", " and causal final token `\".\"` max diff `5.96e-08`; with position embeddings, `2.0076` (unmasked)\n", " and `0.1442` (causal).\n", "- **2-D RoPE (`θ = 30°`, `q = k = [1, 0]`):** dot product `0.5000` at `(3, 1)`, `(5, 3)`, and\n", " `(10, 8)`. Arbitrary `q = [2, 1], k = [1, 3]`: `6.830127` at all three pairs.\n", "- **GPT-2 small parameters:** `7,087,872` per block (`2,362,368` attention = `33.33%`,\n", " `4,722,432` MLP = `66.63%`, `3,072` LayerNorms = `0.04%`) and `124,439,808` total (`85,054,464`\n", " in 12 blocks = `68.35%`, `38,597,376` token embeddings = `31.02%`, `786,432` position\n", " embeddings = `0.63%`, `1,536` final LayerNorm = `0.001%`)." ], "id": "lab-3-2-block-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Explore\n", "\n", "Change one knob at a time and write one sentence on what changed and why.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| norm placement | run `measure_stack` with `norm_mode=\"post\"` at `L = 2, 8, 32` | How do `act_std` and the ratio `||gb0|| / ||gbL||` compare against `norm_mode=\"pre\"`? |\n", "| MLP expansion | change `expansion=4` to `2` and `8` in `FeedForward` at `d_model = 768` | How does the MLP's share of a block's parameters change? |\n", "| RoPE base | compare `base=10_000` vs `base=500_000` in `apply_rope` (`d_head = 64`) | How many positions does the slowest coordinate pair take to complete one full rotation under each base? |\n", "| weight tying | delete `self.lm_head.weight = self.wte.weight` in `GPT2Architecture` | How many parameters are added to GPT-2 small, and what percentage increase is that? |\n", "| residual init scaling | scale `w_o.weight` and `fc2.weight` by `1 / sqrt(2 * L)` in `measure_stack` (`res_and_ln`, `L = 32`) | What happens to `act_std` at depth 32? (GPT-2 uses this exact scaling.) |" ], "id": "lab-3-2-block-17" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Failure playground\n", "\n", "Three blocks below are broken in ways that silently ruin real Transformer implementations. For\n", "each: run it, read the symptom, diagnose the cause, and fix it. Hints are in Review 3.2; answers\n", "are not." ], "id": "lab-3-2-block-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9a · Residual connections removed in a 32-block stack\n", "\n", "A colleague simplifies `TransformerBlock.forward` by dropping `x +` from both sublayers\n", "(\"the network is cleaner without skip wires\") and stacks 32 blocks." ], "id": "lab-3-2-block-20" }, { "cell_type": "code", "metadata": {}, "source": [ "res_on = measure_stack(depth=32, use_residual=True, norm_mode=\"pre\")\n", "res_off_ln = measure_stack(depth=32, use_residual=False, norm_mode=\"pre\")\n", "res_off_noln = measure_stack(depth=32, use_residual=False, norm_mode=\"none\")\n", "\n", "print(\"9a (32-block stack, layer 1 vs layer 32 gradients):\")\n", "for label, r in [\n", " (\"with residuals + LN \", res_on),\n", " (\"NO residuals (+ LN) \", res_off_ln),\n", " (\"NO residuals, NO LN \", res_off_noln),\n", "]:\n", " print(f\" {label}: ||dx||={r['grad_input']:.3e} ||dw_q0||={r['grad_wq0']:.3e} \"\n", " f\"||gb0||={r['grad_block0']:.3e} ||gb32||={r['grad_blockL']:.3e}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: with residuals removed, layer 1's attention query gradient `||dw_q0||` collapses by\n", "roughly **eight orders of magnitude** even when LayerNorm stays on, and without LayerNorm every\n", "layer-1 gradient underflows to exact `0.0` while layer 32's gradient is still normal. Why does\n", "adding `x +` keep layer 1's gradient healthy at depth 32? Check the backward rule for addition\n", "from Ch 1.2." ], "id": "lab-3-2-block-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9b · LayerNorm over the wrong dimension (batch instead of features)\n", "\n", "A colleague writes a custom normalisation layer and averages over `dim = 0` (the batch dimension)\n", "instead of `dim = -1` (the feature dimension)." ], "id": "lab-3-2-block-23" }, { "cell_type": "code", "metadata": {}, "source": [ "class WrongDimNorm(nn.Module):\n", " def __init__(self, d_model, eps=1e-5):\n", " super().__init__()\n", " self.gamma = nn.Parameter(torch.ones(d_model))\n", " self.beta = nn.Parameter(torch.zeros(d_model))\n", " self.eps = eps\n", "\n", " def forward(self, x):\n", " # BUG: normalises across dim=0 (batch) instead of dim=-1 (features)\n", " mean = x.mean(dim=0, keepdim=True)\n", " var = x.var(dim=0, unbiased=False, keepdim=True)\n", " return self.gamma * (x - mean) / torch.sqrt(var + self.eps) + self.beta\n", "\n", "\n", "torch.manual_seed(3)\n", "x_batch = torch.randn(16, 8, 32) * 3.0 + 5.0\n", "\n", "wrong_norm = WrongDimNorm(32)\n", "right_norm = nn.LayerNorm(32)\n", "\n", "with torch.no_grad():\n", " out_wrong_train = wrong_norm(x_batch) # training batch (B = 16)\n", " out_wrong_eval = wrong_norm(x_batch[:1]) # single-example eval/inference (B = 1)\n", " mismatch_wrong = (out_wrong_train[0] - out_wrong_eval[0]).abs().max().item()\n", "\n", " # Also corrupt examples 1..15 and see whether example 0 changes!\n", " x_perturbed = x_batch.clone()\n", " x_perturbed[1:] = x_perturbed[1:] + 50.0\n", " leak_wrong = (wrong_norm(x_perturbed)[0] - out_wrong_train[0]).abs().max().item()\n", "\n", " out_right_train = right_norm(x_batch)\n", " out_right_eval = right_norm(x_batch[:1])\n", " mismatch_right = (out_right_train[0] - out_right_eval[0]).abs().max().item()\n", " leak_right = (right_norm(x_perturbed)[0] - out_right_train[0]).abs().max().item()\n", "\n", "print(\"9b (wrong-dim norm over batch dim=0 vs true LayerNorm over feature dim=-1):\")\n", "print(f\" WrongDimNorm on batch B=16 : mean={out_wrong_train.mean().item():+.4f}, std={out_wrong_train.std().item():.4f}\")\n", "print(f\" WrongDimNorm on single B=1 : max |output| = {out_wrong_eval.abs().max().item():.2e} (collapsed!)\")\n", "print(f\" WrongDimNorm train vs eval mismatch (example 0) : {mismatch_wrong:.4f}\")\n", "print(f\" WrongDimNorm cross-example leak on example 0 : {leak_wrong:.4f}\")\n", "print(f\" nn.LayerNorm train vs eval mismatch (example 0) : {mismatch_right:.2e}\")\n", "print(f\" nn.LayerNorm cross-example leak on example 0 : {leak_right:.2e}\")\n", "\n", "# PyTorch's BatchNorm1d also breaks on batch size 1 if left in train mode:\n", "bn = nn.BatchNorm1d(32)\n", "try:\n", " _ = bn(x_batch[:1, 0, :]) # [1, 32]\n", "except ValueError as e:\n", " print(f\" nn.BatchNorm1d in train mode with B=1 raised ValueError: {e}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: on a training batch of `B = 16`, `WrongDimNorm` prints normal-looking numbers (mean 0,\n", "std 1). Move to single-example evaluation (`B = 1`) and the output collapses to exact zeros, with\n", "a huge mismatch against example 0's training output — and modifying *other* sentences in the batch\n", "alters sentence 0! Why does normalising over `dim = -1` eliminate both the train/eval mismatch and\n", "cross-example leakage?" ], "id": "lab-3-2-block-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9c · Position embeddings missing (\"dog bites man\" vs \"man bites dog\")\n", "\n", "A colleague forgets to add position embeddings before the Transformer block and tests whether the\n", "model distinguishes `\"dog bites man\"` from `\"man bites dog\"`." ], "id": "lab-3-2-block-26" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(11)\n", "emb_9c = nn.Embedding(4, 16)\n", "blk_9c_unmasked = TransformerBlock(d_model=16, n_head=4, causal=False)\n", "blk_9c_causal = TransformerBlock(d_model=16, n_head=4, causal=True)\n", "\n", "s1 = torch.tensor([[0, 1, 2]]) # dog bites man\n", "s2 = torch.tensor([[2, 1, 0]]) # man bites dog\n", "s1_dot = torch.tensor([[0, 1, 2, 3]]) # dog bites man .\n", "s2_dot = torch.tensor([[2, 1, 0, 3]]) # man bites dog .\n", "\n", "with torch.no_grad():\n", " y1 = blk_9c_unmasked(emb_9c(s1))[0] # [3, 16]\n", " y2 = blk_9c_unmasked(emb_9c(s2))[0] # [3, 16]\n", " diff_dog = (y1[0] - y2[2]).abs().max().item()\n", " diff_bites = (y1[1] - y2[1]).abs().max().item()\n", " diff_man = (y1[2] - y2[0]).abs().max().item()\n", "\n", " yc1 = blk_9c_causal(emb_9c(s1_dot))[0] # [4, 16]\n", " yc2 = blk_9c_causal(emb_9c(s2_dot))[0] # [4, 16]\n", " diff_dot_causal = (yc1[3] - yc2[3]).abs().max().item()\n", "\n", "print(\"9c (missing position embeddings):\")\n", "print(\" Unmasked block, first 4 coords of 'bites' (pos 1):\")\n", "print(f\" 'dog bites man': {[round(v, 5) for v in y1[1, :4].tolist()]}\")\n", "print(f\" 'man bites dog': {[round(v, 5) for v in y2[1, :4].tolist()]}\")\n", "print(f\" Max abs diff: dog(0 vs 2)={diff_dog:.2e}, bites(1 vs 1)={diff_bites:.2e}, man(2 vs 0)={diff_man:.2e}\")\n", "print(\" Causal block, first 4 coords of final '.' (pos 3):\")\n", "print(f\" 'dog bites man .': {[round(v, 5) for v in yc1[3, :4].tolist()]}\")\n", "print(f\" 'man bites dog .': {[round(v, 5) for v in yc2[3, :4].tolist()]}\")\n", "print(f\" Max abs diff at final '.' (causal): {diff_dot_causal:.2e}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: without position embeddings, every token in `\"dog bites man\"` receives the exact same\n", "output vector as the matching token in `\"man bites dog\"` (merely in swapped slots) in an unmasked\n", "block — and even with a causal mask on, the final token `\".\"` receives the **identical** vector\n", "for both sentences. Why does every operation inside the block (attention, LayerNorm, MLP, residual\n", "add) fail to notice the swap, and what are the two standard ways to fix it?" ], "id": "lab-3-2-block-28" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\n", " \"Versions tested:\",\n", " f\"Python {platform.python_version()},\",\n", " f\"PyTorch {torch.__version__},\",\n", " end=\" \",\n", ")\n", "try:\n", " import matplotlib\n", " print(f\"matplotlib {matplotlib.__version__},\", end=\" \")\n", "except ImportError:\n", " pass\n", "print(f\"{platform.system()} {platform.machine()} ({', '.join(DEVICES)})\")" ], "execution_count": null, "outputs": [], "id": "lab-3-2-block-29" } ] }