{ "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.1 · Attention\n", "\n", "**Goal:** compute scaled dot-product attention by hand on a 4-token sentence (printing every\n", "intermediate matrix), build single-head and multi-head causal self-attention in PyTorch and\n", "verify them against `F.scaled_dot_product_attention`, measure how naive attention time and memory\n", "grow with sequence length `T` (`128` to `4,096`), visualise one head's weights on an 8-token\n", "sentence (and export them as JSON for the Ch 3.1 explorer), and break attention three ways.\n", "\n", "**Runs on:** any laptop (CPU, plus the Apple GPU `mps` on Apple Silicon or an NVIDIA GPU `cuda`\n", "when present); also Kaggle or Colab. Install locally with `uv run --with torch --with matplotlib`.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-3-1-attention-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import json\n", "import math\n", "import pathlib\n", "import platform\n", "import time\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 sync(device):\n", " if device == \"cuda\":\n", " torch.cuda.synchronize()\n", " elif device == \"mps\":\n", " torch.mps.synchronize()\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-1-attention\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Before running the cells below, write down your answers:\n", "\n", "1. On a 4-token sequence with a causal mask, how many of the `4 × 4 = 16` entries in the\n", " attention weight matrix are forced to `0`, and what must each row of weights sum to?\n", "2. Take two random vectors `q` and `k` of length `d_k`, each entry drawn independently from a\n", " standard normal distribution (mean `0`, variance `1`). As `d_k` grows from `2` to `512`, how\n", " does the standard deviation of `q · k` change, and what happens to `softmax(q · k)` if you\n", " leave out the `1 / √d_k` scaling?\n", "3. When sequence length `T` doubles from `1,024` to `2,048` (and again to `4,096`), by roughly\n", " what factor do you expect naive attention's score-matrix memory and runtime to grow?\n", "4. If you accidentally leave out the causal mask while training a next-token predictor on random\n", " tokens (`V = 16`, chance loss `log 16 ≈ 2.77`), will the training loss stay stuck near `2.77`\n", " or drop suspiciously close to `0`?" ], "id": "lab-3-1-attention-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · By hand: a 4-token soft lookup, every intermediate matrix\n", "\n", "Start with the 4-token sentence `[\"the\", \"river\", \"near\", \"bank\"]` and 2-D token vectors\n", "`X` (`[4, 2]`). Three `2 × 2` weight matrices turn `X` into queries `Q`, keys `K`, and values `V`.\n", "First we compute the attention output token by token in plain Python loops (so nothing is hidden\n", "inside a matrix multiply), then we run the matrix formula `softmax(Q Kᵀ / √d_k + mask) V` and\n", "check both against PyTorch's `F.scaled_dot_product_attention`." ], "id": "lab-3-1-attention-03" }, { "cell_type": "code", "metadata": {}, "source": [ "TOKENS_4 = [\"the\", \"river\", \"near\", \"bank\"]\n", "\n", "X = torch.tensor([\n", " [0.0, 1.0], # \"the\"\n", " [2.0, 0.0], # \"river\"\n", " [0.5, 1.0], # \"near\"\n", " [1.0, 1.0], # \"bank\"\n", "], dtype=torch.float32)\n", "\n", "W_q = torch.tensor([[1.0, 0.0], [1.0, 1.0]])\n", "W_k = torch.tensor([[1.0, 0.0], [0.0, 0.5]])\n", "W_v = torch.tensor([[1.0, 0.0], [0.5, 1.0]])\n", "\n", "Q = X @ W_q # [4, 2]\n", "K = X @ W_k # [4, 2]\n", "V = X @ W_v # [4, 2]\n", "\n", "\n", "def print_matrix(name, mat, row_labels, col_labels=None, fmt=\"{:7.4f}\"):\n", " print(f\"\\n{name} shape={tuple(mat.shape)}\")\n", " if col_labels is not None:\n", " header = \" \" + \"\".join(f\"{c:>8s}\" for c in col_labels)\n", " print(header)\n", " for label, row in zip(row_labels, mat):\n", " vals = \" \".join(fmt.format(v.item()) for v in row)\n", " print(f\" {label:6s} {vals}\")\n", "\n", "\n", "print_matrix(\"X (input embeddings)\", X, TOKENS_4, [\"d0\", \"d1\"], \"{:7.2f}\")\n", "print_matrix(\"Q = X @ W_q\", Q, TOKENS_4, [\"q0\", \"q1\"], \"{:7.2f}\")\n", "print_matrix(\"K = X @ W_k\", K, TOKENS_4, [\"k0\", \"k1\"], \"{:7.2f}\")\n", "print_matrix(\"V = X @ W_v\", V, TOKENS_4, [\"v0\", \"v1\"], \"{:7.2f}\")\n", "\n", "# Step-by-step Python loops for causal scaled dot-product attention\n", "T_4, d_k_4 = Q.shape\n", "scale_4 = math.sqrt(d_k_4)\n", "raw_scores_loop = torch.zeros(T_4, T_4)\n", "scaled_scores_loop = torch.zeros(T_4, T_4)\n", "weights_loop = torch.zeros(T_4, T_4)\n", "out_loop = torch.zeros(T_4, V.shape[1])\n", "\n", "for i in range(T_4):\n", " # Raw dot products q_i · k_j for all positions j\n", " for j in range(T_4):\n", " raw_scores_loop[i, j] = sum(Q[i, c].item() * K[j, c].item() for c in range(d_k_4))\n", " scaled_scores_loop[i, j] = raw_scores_loop[i, j] / scale_4\n", "\n", " # Causal softmax over j <= i (future positions j > i are masked to -inf -> weight 0)\n", " visible = [scaled_scores_loop[i, j].item() for j in range(i + 1)]\n", " m = max(visible)\n", " exps = [math.exp(s - m) for s in visible]\n", " denom = sum(exps)\n", " for j in range(i + 1):\n", " weights_loop[i, j] = exps[j] / denom\n", "\n", " # Weighted average of value vectors v_j\n", " for c in range(V.shape[1]):\n", " out_loop[i, c] = sum(weights_loop[i, j].item() * V[j, c].item() for j in range(i + 1))\n", "\n", "print_matrix(\"Raw scores Q @ K.T\", raw_scores_loop, TOKENS_4, TOKENS_4, \"{:7.2f}\")\n", "print_matrix(f\"Scaled scores (÷ √{d_k_4} = {scale_4:.4f})\", scaled_scores_loop, TOKENS_4, TOKENS_4)\n", "print_matrix(\"Causal weights = softmax(scaled + mask)\", weights_loop, TOKENS_4, TOKENS_4)\n", "print(\"Row sums:\", [round(s, 4) for s in weights_loop.sum(dim=-1).tolist()])\n", "print_matrix(\"Output = weights @ V\", out_loop, TOKENS_4, [\"o0\", \"o1\"])\n", "\n", "# Exact same computation in matrix form:\n", "causal_mask_4 = torch.triu(torch.full((T_4, T_4), float(\"-inf\")), diagonal=1)\n", "scores_mat = (Q @ K.T) / math.sqrt(d_k_4) + causal_mask_4\n", "weights_mat = torch.softmax(scores_mat, dim=-1)\n", "out_mat = weights_mat @ V\n", "\n", "# Verify against PyTorch's F.scaled_dot_product_attention:\n", "out_sdpa = F.scaled_dot_product_attention(\n", " Q.unsqueeze(0), K.unsqueeze(0), V.unsqueeze(0), is_causal=True\n", ").squeeze(0)\n", "\n", "print(f\"\\nMax abs diff (loop vs matrix): {(out_loop - out_mat).abs().max().item():.2e}\")\n", "print(f\"Max abs diff (matrix vs F.scaled_dot_product_attention): {(out_mat - out_sdpa).abs().max().item():.2e}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Look closely at the last row (`\"bank\"`, position 3):\n", "- Its raw dot product with `\"river\"` (`[2.0, 1.0] · [2.0, 0.0] = 4.0`) is the largest of the four.\n", "- After dividing by `√2 = 1.4142` and running softmax, `\"bank\"` places **62.5 %** of its weight\n", " on `\"river\"`, **21.6 %** on itself, **10.7 %** on `\"near\"`, and **5.3 %** on `\"the\"`.\n", "- Its output vector `[1.7064, 0.3754]` has shifted strongly toward `\"river\"`'s value `[2.0, 0.0]`,\n", " away from its ambiguous starting vector `[1.0, 1.0]`." ], "id": "lab-3-1-attention-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Why divide by `√d_k`? Measuring dot-product variance\n", "\n", "When each entry of `q` and `k` has mean `0` and variance `1`, each product `q_i k_i` has variance\n", "`1`, so the sum of `d_k` independent products has variance `d_k` and standard deviation `√d_k`.\n", "Below we check that formula numerically across `d_k = 2` to `512` (2,000 random pairs per `d_k`)\n", "and record how unscaled scores push softmax into saturation." ], "id": "lab-3-1-attention-06" }, { "cell_type": "code", "metadata": {}, "source": [ "D_K_SWEEP = [2, 8, 32, 64, 256, 512]\n", "scaling_rows = []\n", "\n", "print(\" d_k | √d_k | std(q·k) | std(q·k/√d_k) | max_w(raw) | max_w(scaled)\")\n", "print(\" ----+--------+----------+---------------+------------+--------------\")\n", "for d_k in D_K_SWEEP:\n", " torch.manual_seed(0)\n", " # 2,000 independent (q, k) pairs for variance check\n", " q_pairs = torch.randn(2000, d_k)\n", " k_pairs = torch.randn(2000, d_k)\n", " dots = (q_pairs * k_pairs).sum(dim=-1)\n", " std_raw = dots.std().item()\n", " std_scaled = (dots / math.sqrt(d_k)).std().item()\n", "\n", " # 100 random sequences of length T=16 (causal) to measure softmax sharpness on the last row\n", " q_seq = torch.randn(100, 16, d_k)\n", " k_seq = torch.randn(100, 16, d_k)\n", " raw_s = q_seq @ k_seq.transpose(-2, -1)\n", " mask_16 = torch.triu(torch.full((16, 16), float(\"-inf\")), diagonal=1)\n", " w_raw = torch.softmax(raw_s + mask_16, dim=-1)\n", " w_scl = torch.softmax(raw_s / math.sqrt(d_k) + mask_16, dim=-1)\n", " max_w_raw = w_raw[:, -1, :].max(dim=-1).values.mean().item()\n", " max_w_scl = w_scl[:, -1, :].max(dim=-1).values.mean().item()\n", "\n", " row = {\n", " \"d_k\": d_k,\n", " \"sqrt_d_k\": round(math.sqrt(d_k), 4),\n", " \"std_raw\": round(std_raw, 4),\n", " \"std_scaled\": round(std_scaled, 4),\n", " \"mean_max_weight_raw\": round(max_w_raw, 4),\n", " \"mean_max_weight_scaled\": round(max_w_scl, 4),\n", " }\n", " scaling_rows.append(row)\n", " print(f\" {d_k:3d} | {math.sqrt(d_k):6.2f} | {std_raw:8.3f} | {std_scaled:13.3f} | {max_w_raw:10.4f} | {max_w_scl:13.4f}\")\n", "\n", "scaling_csv = out_dir() / \"scaling-variance.csv\"\n", "with scaling_csv.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(\n", " f,\n", " fieldnames=[\"d_k\", \"sqrt_d_k\", \"std_raw\", \"std_scaled\", \"mean_max_weight_raw\", \"mean_max_weight_scaled\"],\n", " lineterminator=\"\\n\",\n", " )\n", " w.writeheader()\n", " w.writerows(scaling_rows)\n", "print(\"saved\", scaling_csv)" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Single-head and multi-head causal self-attention in PyTorch\n", "\n", "Now we package self-attention as an `nn.Module`. In **multi-head attention**, `d_model` is split\n", "evenly across `n_head` heads (`d_head = d_model // n_head`), each head computes its own\n", "`[B, T, d_head]` weighted average in parallel, and the heads are concatenated back to\n", "`[B, T, d_model]` and mixed by a final output projection `W_o`.\n", "\n", "Notice the shape trace:\n", "```text\n", "x : [B, T, d_model]\n", "Q, K, V : [B, T, d_model] -> reshape + transpose -> [B, n_head, T, d_head]\n", "scores : [B, n_head, T, T]\n", "weights : [B, n_head, T, T]\n", "head_out : [B, n_head, T, d_head]\n", "concat : [B, T, d_model]\n", "output : [B, T, d_model]\n", "```" ], "id": "lab-3-1-attention-08" }, { "cell_type": "code", "metadata": {}, "source": [ "class CausalMultiHeadAttention(nn.Module):\n", " def __init__(self, d_model, n_head):\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.d_head = d_model // n_head\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 _split_heads(self, t):\n", " B, T, _ = t.shape\n", " return t.view(B, T, self.n_head, self.d_head).transpose(1, 2) # [B, H, T, d_head]\n", "\n", " def forward(self, x, use_sdpa=False, return_weights=False):\n", " B, T, C = x.shape\n", " q = self._split_heads(self.w_q(x))\n", " k = self._split_heads(self.w_k(x))\n", " v = self._split_heads(self.w_v(x))\n", "\n", " if use_sdpa:\n", " head_out = F.scaled_dot_product_attention(q, k, v, is_causal=True)\n", " weights = None\n", " else:\n", " scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.d_head) # [B, H, T, T]\n", " mask = torch.triu(torch.full((T, T), float(\"-inf\"), device=x.device, dtype=x.dtype), diagonal=1)\n", " weights = torch.softmax(scores + mask, dim=-1) # [B, H, T, T]\n", " head_out = weights @ v # [B, H, T, d_head]\n", "\n", " concat = head_out.transpose(1, 2).contiguous().view(B, T, C) # [B, T, d_model]\n", " out = self.w_o(concat)\n", " if return_weights:\n", " return out, weights\n", " return out\n", "\n", "\n", "torch.manual_seed(0)\n", "B_t, T_t, d_model_t, n_head_t = 2, 16, 64, 4\n", "mha = CausalMultiHeadAttention(d_model=d_model_t, n_head=n_head_t)\n", "x_t = torch.randn(B_t, T_t, d_model_t)\n", "\n", "with torch.no_grad():\n", " out_manual, w_manual = mha(x_t, use_sdpa=False, return_weights=True)\n", " out_pytorch = mha(x_t, use_sdpa=True)\n", "\n", "n_params = sum(p.numel() for p in mha.parameters())\n", "max_diff_mha = (out_manual - out_pytorch).abs().max().item()\n", "print(f\"Input shape: {tuple(x_t.shape)}\")\n", "print(f\"Weights shape: {tuple(w_manual.shape)} (B, n_head, T, T)\")\n", "print(f\"Output shape: {tuple(out_manual.shape)}\")\n", "print(f\"Parameters: {n_params:,d} (= 4 * {d_model_t}^2 + 4 * {d_model_t} = {4 * d_model_t**2 + 4 * d_model_t:,d})\")\n", "print(f\"Max abs diff vs F.scaled_dot_product_attention: {max_diff_mha:.2e}\")\n", "\n", "# Also verify single-head (n_head = 1) has the exact same parameter count:\n", "mha_1 = CausalMultiHeadAttention(d_model=d_model_t, n_head=1)\n", "print(f\"Single-head (n_head=1) parameters: {sum(p.numel() for p in mha_1.parameters()):,d}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Measuring the `T²` wall: naive attention time and memory vs sequence length `T`\n", "\n", "In naive attention, `Q @ Kᵀ` materialises a `[B, n_head, T, T]` score matrix and softmax\n", "materialises a second `[B, n_head, T, T]` weight matrix of the same size. Doubling `T` quadruples\n", "both memory and compute.\n", "\n", "Below we measure `T = 128, 256, 512, 1024, 2048, 4096` with `B = 1, n_head = 4, d_head = 64`\n", "(`float32`, 4 bytes per value) on every available device. On GPU (`mps` / `cuda`) we measure the\n", "actual extra memory allocated during naive attention; on all devices we also record the exact\n", "size of one `[B, n_head, T, T]` `float32` matrix (`B × n_head × T² × 4` bytes, with\n", "`1 MB = 10⁶ bytes`)." ], "id": "lab-3-1-attention-10" }, { "cell_type": "code", "metadata": {}, "source": [ "T_VALUES = [128, 256, 512, 1024, 2048, 4096]\n", "BENCH_B, BENCH_H, BENCH_D = 1, 4, 64\n", "\n", "machine_name = (\n", " torch.cuda.get_device_name(0)\n", " if torch.cuda.is_available()\n", " else f\"{platform.system()} {platform.machine()}\"\n", ")\n", "\n", "\n", "def measure_naive_attention(T, device, warmup=5):\n", " repeats = 5 if T >= 2048 else 15\n", " torch.manual_seed(0)\n", " q = torch.randn(BENCH_B, BENCH_H, T, BENCH_D, device=device)\n", " k = torch.randn(BENCH_B, BENCH_H, T, BENCH_D, device=device)\n", " v = torch.randn(BENCH_B, BENCH_H, T, BENCH_D, device=device)\n", " mask = torch.triu(torch.full((T, T), float(\"-inf\"), device=device), diagonal=1)\n", " scale = math.sqrt(BENCH_D)\n", "\n", " def run_once():\n", " scores = (q @ k.transpose(-2, -1)) / scale + mask\n", " weights = torch.softmax(scores, dim=-1)\n", " out = weights @ v\n", " return scores, weights, out\n", "\n", " # Warm-up\n", " for _ in range(warmup):\n", " s, w, o = run_once()\n", " del s, w, o\n", " sync(device)\n", "\n", " # Measure peak extra GPU memory while naive intermediates (scores, weights, out) are live\n", " measured_mb = None\n", " if device == \"cuda\":\n", " torch.cuda.reset_peak_memory_stats()\n", " base = torch.cuda.memory_allocated()\n", " s, w, o = run_once()\n", " sync(device)\n", " measured_mb = (torch.cuda.max_memory_allocated() - base) / 1e6\n", " del s, w, o\n", " elif device == \"mps\":\n", " sync(device)\n", " base = torch.mps.current_allocated_memory()\n", " s, w, o = run_once()\n", " sync(device)\n", " measured_mb = (torch.mps.current_allocated_memory() - base) / 1e6\n", " del s, w, o\n", " sync(device)\n", "\n", " times_ms = []\n", " for _ in range(repeats):\n", " t0 = time.perf_counter()\n", " s, w, o = run_once()\n", " sync(device)\n", " times_ms.append((time.perf_counter() - t0) * 1000.0)\n", " del s, w, o\n", " times_ms.sort()\n", " med_ms = times_ms[len(times_ms) // 2]\n", "\n", " # Exact size of one [B, H, T, T] float32 matrix (scores) and two matrices (scores + weights)\n", " one_mat_mb = (BENCH_B * BENCH_H * T * T * 4) / 1e6\n", " two_mat_mb = 2.0 * one_mat_mb\n", " return med_ms, one_mat_mb, two_mat_mb, measured_mb\n", "\n", "\n", "scaling_time_rows = []\n", "print(f\"Benchmark: B={BENCH_B}, n_head={BENCH_H}, d_head={BENCH_D}, float32 ({machine_name})\")\n", "print(\" device | T | med_ms | 1_mat_MB | 2_mat_MB | gpu_alloc_MB\")\n", "print(\" -------+------+---------+----------+----------+-------------\")\n", "for dev in DEVICES:\n", " for T in T_VALUES:\n", " med_ms, one_mb, two_mb, gpu_mb = measure_naive_attention(T, dev)\n", " row = {\n", " \"machine\": machine_name,\n", " \"device\": dev,\n", " \"T\": T,\n", " \"B\": BENCH_B,\n", " \"n_head\": BENCH_H,\n", " \"d_head\": BENCH_D,\n", " \"ms\": round(med_ms, 3),\n", " \"one_matrix_mb\": round(one_mb, 3),\n", " \"two_matrices_mb\": round(two_mb, 3),\n", " \"gpu_alloc_mb\": \"\" if gpu_mb is None else round(gpu_mb, 3),\n", " }\n", " scaling_time_rows.append(row)\n", " gpu_str = f\"{gpu_mb:12.2f}\" if gpu_mb is not None else \" n/a\"\n", " print(f\" {dev:6s} | {T:4d} | {med_ms:7.2f} | {one_mb:8.2f} | {two_mb:8.2f} | {gpu_str}\")\n", "\n", "scaling_time_csv = out_dir() / \"attention-scaling.csv\"\n", "with scaling_time_csv.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(\n", " f,\n", " fieldnames=[\"machine\", \"device\", \"T\", \"B\", \"n_head\", \"d_head\", \"ms\", \"one_matrix_mb\", \"two_matrices_mb\", \"gpu_alloc_mb\"],\n", " lineterminator=\"\\n\",\n", " )\n", " w.writeheader()\n", " w.writerows(scaling_time_rows)\n", "print(\"saved\", scaling_time_csv)\n", "\n", "# Print exact float16 attention-matrix bytes for Ch 3.1's back-of-envelope table (1 MB = 10^6 B, 1 GB = 10^9 B):\n", "print(\"\\nExact float16 (2 bytes/element) single-head T×T matrix size:\")\n", "for T_ref in (1024, 8192):\n", " elems = T_ref * T_ref\n", " bytes_1 = elems * 2\n", " print(f\" T={T_ref:5,d}: {elems:11,d} entries × 2 B = {bytes_1:12,d} B ({bytes_1/1e6:6.2f} MB per head)\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-11" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4))\n", " for dev in DEVICES:\n", " sub = [r for r in scaling_time_rows if r[\"device\"] == dev]\n", " ts = [r[\"T\"] for r in sub]\n", " ms = [r[\"ms\"] for r in sub]\n", " ax1.plot(ts, ms, marker=\"o\", label=dev)\n", " ax1.set_xscale(\"log\", base=2); ax1.set_yscale(\"log\")\n", " ax1.set_xticks(T_VALUES); ax1.set_xticklabels([str(t) for t in T_VALUES])\n", " ax1.set_xlabel(\"sequence length T\"); ax1.set_ylabel(\"median time (ms)\")\n", " ax1.set_title(\"Naive attention runtime vs T (log-log)\")\n", " ax1.legend()\n", "\n", " cpu_sub = [r for r in scaling_time_rows if r[\"device\"] == \"cpu\"]\n", " ts = [r[\"T\"] for r in cpu_sub]\n", " two_mbs = [r[\"two_matrices_mb\"] for r in cpu_sub]\n", " ax2.plot(ts, two_mbs, marker=\"o\", label=\"scores + weights (exact 2×T²)\")\n", " gpu_devs = [d for d in DEVICES if d != \"cpu\"]\n", " if gpu_devs:\n", " g_sub = [r for r in scaling_time_rows if r[\"device\"] == gpu_devs[0]]\n", " ax2.plot(ts, [r[\"gpu_alloc_mb\"] for r in g_sub], marker=\"s\", linestyle=\"--\", label=f\"measured {gpu_devs[0]} alloc\")\n", " ax2.set_xscale(\"log\", base=2); ax2.set_yscale(\"log\")\n", " ax2.set_xticks(T_VALUES); ax2.set_xticklabels([str(t) for t in T_VALUES])\n", " ax2.set_xlabel(\"sequence length T\"); ax2.set_ylabel(\"memory (MB)\")\n", " ax2.set_title(\"Naive attention matrix memory vs T\")\n", " ax2.legend()\n", " plt.tight_layout(); plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Visualising one attention head on an 8-token sentence (and exporting JSON)\n", "\n", "To see what an attention matrix looks like on a full sentence, we build a 4-dimensional head\n", "(`d_k = 4`, so `√d_k = 2.0` exactly) on the 8-token sentence:\n", "`[\"The\", \"river\", \"rose\", \"and\", \"flooded\", \"the\", \"muddy\", \"bank\"]`.\n", "\n", "Its four dimensions correspond loosely to `[water, subject/noun, action/verb, function/modifier]`.\n", "We compute both the **causal** and **unmasked** attention matrices, plot the causal heatmap, and\n", "save the tokens, `Q`, `K`, raw dot-product scores `Q Kᵀ`, and weights to\n", "`data/lab-3-1-attention/attention-weights.json` for Ch 3.1's interactive explorer." ], "id": "lab-3-1-attention-13" }, { "cell_type": "code", "metadata": {}, "source": [ "SENTENCE_8 = [\"The\", \"river\", \"rose\", \"and\", \"flooded\", \"the\", \"muddy\", \"bank\"]\n", "D_K_8 = 4\n", "SCALE_8 = math.sqrt(D_K_8) # 2.0 exactly\n", "\n", "# Dimensions: [water, noun/subject, verb/action, function/modifier]\n", "Q_8 = torch.tensor([\n", " [0.0, 1.6, 0.0, 0.8], # \"The\" -> looks for a noun\n", " [1.2, 0.8, 1.4, 0.0], # \"river\" -> attends to itself / water-verbs\n", " [1.0, 1.8, 0.4, 0.0], # \"rose\" -> verb looks back for its subject\n", " [0.2, 0.2, 1.6, 0.4], # \"and\" -> links actions\n", " [1.4, 1.4, 0.8, 0.0], # \"flooded\" -> looks for subject + water\n", " [0.0, 1.8, 0.0, 0.6], # \"the\" -> determiner looks for a noun\n", " [1.2, 1.4, 0.2, 0.4], # \"muddy\" -> adjective looks for water/noun\n", " [2.2, 0.4, 0.4, 0.2], # \"bank\" -> resolves meaning from water cues\n", "], dtype=torch.float32)\n", "\n", "K_8 = torch.tensor([\n", " [0.0, 0.2, 0.0, 1.0], # \"The\"\n", " [2.4, 2.0, 0.2, 0.0], # \"river\" (strong water + subject noun)\n", " [0.6, 0.2, 2.0, 0.0], # \"rose\" (action verb)\n", " [0.0, 0.0, 0.3, 1.0], # \"and\" (connector)\n", " [2.0, 0.2, 2.2, 0.0], # \"flooded\" (water + action verb)\n", " [0.0, 0.2, 0.0, 1.0], # \"the\"\n", " [1.4, 0.4, 0.2, 1.2], # \"muddy\" (water modifier)\n", " [1.2, 2.2, 0.0, 0.2], # \"bank\" (noun + mild water)\n", "], dtype=torch.float32)\n", "\n", "scores_8_raw = Q_8 @ K_8.T\n", "mask_8 = torch.triu(torch.full((8, 8), float(\"-inf\")), diagonal=1)\n", "weights_8_causal = torch.softmax(scores_8_raw / SCALE_8 + mask_8, dim=-1)\n", "weights_8_unmasked = torch.softmax(scores_8_raw / SCALE_8, dim=-1)\n", "\n", "print_matrix(\"8-token causal attention weights (scale = √4 = 2.0)\", weights_8_causal, SENTENCE_8, SENTENCE_8)\n", "print(\"\\nSelected highlights:\")\n", "print(f' \"rose\" -> \"river\": {weights_8_causal[2, 1].item():.4f}')\n", "print(f' \"flooded\" -> \"river\": {weights_8_causal[4, 1].item():.4f}')\n", "print(f' \"bank\" -> \"river\": {weights_8_causal[7, 1].item():.4f}, \"flooded\": {weights_8_causal[7, 4].item():.4f}, \"muddy\": {weights_8_causal[7, 6].item():.4f}, \"bank\": {weights_8_causal[7, 7].item():.4f}')\n", "print(f' \"the\" (pos 5) -> \"bank\" (pos 7): causal={weights_8_causal[5, 7].item():.4f}, unmasked={weights_8_unmasked[5, 7].item():.4f}')\n", "\n", "explorer_payload = {\n", " \"tokens\": SENTENCE_8,\n", " \"d_k\": D_K_8,\n", " \"default_scale\": SCALE_8,\n", " \"dimensions\": [\"water\", \"noun/subject\", \"verb/action\", \"function/modifier\"],\n", " \"Q\": [[round(v, 4) for v in row] for row in Q_8.tolist()],\n", " \"K\": [[round(v, 4) for v in row] for row in K_8.tolist()],\n", " \"scores_raw\": [[round(v, 4) for v in row] for row in scores_8_raw.tolist()],\n", " \"weights_causal\": [[round(v, 4) for v in row] for row in weights_8_causal.tolist()],\n", " \"weights_unmasked\": [[round(v, 4) for v in row] for row in weights_8_unmasked.tolist()],\n", "}\n", "weights_json = out_dir() / \"attention-weights.json\"\n", "weights_json.write_text(json.dumps(explorer_payload, indent=2) + \"\\n\")\n", "print(\"saved\", weights_json)" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-14" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, ax = plt.subplots(figsize=(6.2, 5.2))\n", " im = ax.imshow(weights_8_causal.numpy(), vmin=0.0, vmax=1.0, cmap=\"Blues\")\n", " ax.set_xticks(range(8)); ax.set_xticklabels(SENTENCE_8, rotation=35, ha=\"right\")\n", " ax.set_yticks(range(8)); ax.set_yticklabels(SENTENCE_8)\n", " ax.set_xlabel(\"key position (attended to)\")\n", " ax.set_ylabel(\"query position (attending from)\")\n", " ax.set_title(\"Causal attention weights (d_k = 4, scale = 2.0)\")\n", " for i in range(8):\n", " for j in range(8):\n", " val = weights_8_causal[i, j].item()\n", " if j <= i:\n", " ax.text(j, i, f\"{val:.2f}\", ha=\"center\", va=\"center\",\n", " color=\"white\" if val > 0.5 else \"black\", fontsize=8)\n", " plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)\n", " plt.tight_layout(); plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-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; benchmark times depend on your machine):\n", "\n", "- **4-token worked example (`[\"the\", \"river\", \"near\", \"bank\"]`):**\n", " - `\"bank\"` weights: `[0.0526, 0.6246, 0.1066, 0.2162]` (row sums all `1.0`)\n", " - `\"bank\"` output vector: `[1.7064, 0.3754]`\n", " - Max abs difference vs `F.scaled_dot_product_attention`: `1.19e-07`\n", "- **Variance scaling (`seed = 0`, 2,000 random pairs per `d_k`):**\n", "\n", "```text\n", " d_k | √d_k | std(q·k) | std(q·k/√d_k) | max_w(raw) | max_w(scaled)\n", " 2 | 1.41 | 1.355 | 0.958 | 0.2864 | 0.2117\n", " 64 | 8.00 | 8.048 | 1.006 | 0.8532 | 0.2503\n", " 512 | 22.63 | 22.707 | 1.004 | 0.9485 | 0.2607\n", "```\n", "\n", "- **Multi-head attention (`d_model = 64, n_head = 4`):** `16,640` parameters (same as `n_head = 1`),\n", " matching `F.scaled_dot_product_attention` with max abs diff `1.34e-07`.\n", "- **`T²` scaling (`B = 1, n_head = 4, d_head = 64, float32`):** every doubling of `T` from `128`\n", " to `4,096` multiplies score-matrix memory by `4×` (one matrix: `0.26 → 1.05 → 4.19 → 16.78 →\n", " 67.11 → 268.44 MB`; two matrices: `0.52` to `536.87 MB`), and runtime grows roughly `4×` per\n", " doubling once `T` is large enough to saturate the processor.\n", "- **8-token sentence (`[\"The\", \"river\", \"rose\", \"and\", \"flooded\", \"the\", \"muddy\", \"bank\"]`):**\n", " `\"bank\"` attends `0.3979` to `\"river\"` and `0.2667` to `\"flooded\"`; `\"the\"` (pos 5) puts `0.0000`\n", " on `\"bank\"` with the causal mask and `0.3377` without it." ], "id": "lab-3-1-attention-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", "| `d_k` | run Section 3's loop with `d_k = 1024` and `2048` | How close does `mean_max_weight_raw` get to `1.0`, and does `std(q·k / √d_k)` still stay near `1.0`? |\n", "| `n_head` | instantiate `CausalMultiHeadAttention(d_model=64, n_head=h)` for `h = 1, 2, 4, 8, 16` | Does total parameter count change? How does the shape of `weights` (`[B, n_head, T, T]`) change, and what does that mean for memory? |\n", "| `T` | add `T = 8192` on CPU or GPU (watch memory: one `[1, 4, 8192, 8192]` float32 matrix is `1.07 GB`!) | Does runtime still quadruple from `4,096` to `8,192`, or do you hit memory bandwidth / out-of-memory limits first? |\n", "| causal mask | set `is_causal=False` in Section 2's 4-token example | Which token's output vector changes the most when earlier tokens can look ahead to `\"river\"` and `\"bank\"`? |" ], "id": "lab-3-1-attention-17" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Failure playground\n", "\n", "Three attention implementations below are broken in the three ways attention code most often\n", "fails. For each: run it, read the symptom, find the cause, and fix it. Hints are in Review 3.1;\n", "answers are not." ], "id": "lab-3-1-attention-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9a · Missing causal mask: loss collapses suspiciously fast\n", "\n", "A colleague builds a tiny next-token language model on **uniformly random token sequences**\n", "(`V = 16`, `T = 12`, freshly sampled each batch). Because each next token is an independent\n", "random draw from 16 choices, no honest causal model can beat `log 16 = 2.7726` (accuracy `6.25 %`).\n", "Watch what happens with the causal mask on, and then with it accidentally omitted." ], "id": "lab-3-1-attention-20" }, { "cell_type": "code", "metadata": {}, "source": [ "V_FP, T_FP, D_FP = 16, 12, 32\n", "\n", "\n", "class TinyAttnLM(nn.Module):\n", " def __init__(self, vocab, max_t, d, causal=True):\n", " super().__init__()\n", " self.causal = causal\n", " self.tok = nn.Embedding(vocab, d)\n", " # Position embedding so each slot knows its index (Ch 3.2 teaches position embeddings in full)\n", " self.pos = nn.Embedding(max_t, d)\n", " self.wq = nn.Linear(d, d, bias=False)\n", " self.wk = nn.Linear(d, d, bias=False)\n", " self.wv = nn.Linear(d, d, bias=False)\n", " self.head = nn.Linear(d, vocab)\n", "\n", " def forward(self, idx):\n", " B, T = idx.shape\n", " h = self.tok(idx) + self.pos(torch.arange(T, device=idx.device))\n", " q, k, v = self.wq(h), self.wk(h), self.wv(h)\n", " scores = (q @ k.transpose(-2, -1)) / math.sqrt(q.size(-1))\n", " if self.causal:\n", " mask = torch.triu(torch.full((T, T), float(\"-inf\"), device=idx.device), diagonal=1)\n", " scores = scores + mask\n", " weights = torch.softmax(scores, dim=-1)\n", " return self.head(weights @ v)\n", "\n", "\n", "print(f\"Chance baseline on uniform random tokens (V={V_FP}): log({V_FP}) = {math.log(V_FP):.4f}, acc = {100/V_FP:.2f}%\")\n", "for causal_flag, label in [(True, \"with causal mask\"), (False, \"NO causal mask (broken)\")]:\n", " torch.manual_seed(7)\n", " gen = torch.Generator().manual_seed(123)\n", " model_a = TinyAttnLM(V_FP, T_FP, D_FP, causal=causal_flag)\n", " opt_a = torch.optim.Adam(model_a.parameters(), lr=0.02)\n", " print(f\"\\n9a · {label}:\")\n", " for step in range(201):\n", " # Fresh random sequences every step: impossible to predict honestly!\n", " seqs = torch.randint(0, V_FP, (64, T_FP + 1), generator=gen)\n", " x_in, y_tgt = seqs[:, :-1], seqs[:, 1:]\n", " logits = model_a(x_in)\n", " # Score positions 0..T-2 (where y_tgt[t] = x_in[t+1] is inside x_in)\n", " loss_a = F.cross_entropy(logits[:, :-1, :].reshape(-1, V_FP), y_tgt[:, :-1].reshape(-1))\n", " if step in (0, 50, 100, 200):\n", " acc_a = (logits[:, :-1, :].argmax(dim=-1) == y_tgt[:, :-1]).float().mean().item()\n", " print(f\" step {step:3d} loss {loss_a.item():.4f} acc {acc_a * 100:5.1f}%\")\n", " if step < 200:\n", " opt_a.zero_grad()\n", " loss_a.backward()\n", " opt_a.step()" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: on completely random, unpredictable tokens, the unmasked model's loss plunges far below\n", "`log 16 = 2.7726` — straight toward `0.00`, with near-`100 %` accuracy — even on brand-new random\n", "batches it has never seen before. Where did it get the answer from, and what will happen the\n", "moment you try to generate text one token at a time?" ], "id": "lab-3-1-attention-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9b · Missing `√d_k` scaling at large `d_k`: softmax saturates and gradients vanish\n", "\n", "A colleague forgets to divide `Q @ Kᵀ` by `√d_k` with `d_k = 512` and `T = 16`. Compare the\n", "largest attention weight and the gradient norm reaching the query vector `q` with and without\n", "scaling." ], "id": "lab-3-1-attention-23" }, { "cell_type": "code", "metadata": {}, "source": [ "T_B, D_B = 16, 512\n", "mask_b = torch.triu(torch.full((T_B, T_B), float(\"-inf\")), diagonal=1)\n", "\n", "print(f\"9b · Comparing scaled vs unscaled attention at d_k={D_B}, T={T_B}:\")\n", "for use_scale, label in [(True, \"scaled (÷ √d_k)\"), (False, \"UNSCALED (broken)\")]:\n", " torch.manual_seed(42)\n", " q_b = torch.randn(T_B, D_B, requires_grad=True)\n", " k_b = torch.randn(T_B, D_B)\n", " v_b = torch.randn(T_B, D_B)\n", " scores_b = q_b @ k_b.T\n", " if use_scale:\n", " scores_b = scores_b / math.sqrt(D_B)\n", " w_b = torch.softmax(scores_b + mask_b, dim=-1)\n", " out_b = w_b @ v_b\n", " loss_b = (out_b[-1] ** 2).mean()\n", " loss_b.backward()\n", "\n", " mean_max_w = w_b[1:].max(dim=-1).values.mean().item()\n", " last_max_w = w_b[-1].max().item()\n", " grad_norm_q = q_b.grad[-1].norm().item()\n", " print(f\" {label:20s} mean_max_w={mean_max_w:.6f} last_row_max_w={last_max_w:.6f} ||dL/dq_last||={grad_norm_q:.3e}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: without `1 / √d_k`, the attention weights collapse onto a single position (`max_w`\n", "approaches `1.000000`) and the gradient norm `||∂L/∂q||` shrinks by orders of magnitude. Why does\n", "a near-one-hot softmax kill the gradient flowing back into `Q` and `K`? (Hint: connect this to\n", "temperature `T → 0` in Ch 2.3 and flat tails in Ch 1.1.)" ], "id": "lab-3-1-attention-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9c · Causal mask applied *after* softmax (zeros instead of `−∞`)\n", "\n", "Instead of adding `−∞` to future scores before softmax, a colleague runs softmax first and then\n", "zeroes out the upper triangle with `weights.tril()`." ], "id": "lab-3-1-attention-26" }, { "cell_type": "code", "metadata": {}, "source": [ "scores_c = (Q @ K.T) / math.sqrt(d_k_4)\n", "weights_c_bad = torch.softmax(scores_c, dim=-1).tril()\n", "row_sums_c = weights_c_bad.sum(dim=-1)\n", "\n", "print_matrix(\"9c · Broken weights (softmax first, then zero upper triangle)\", weights_c_bad, TOKENS_4, TOKENS_4)\n", "print(\"Row sums (should all be 1.0000):\", [round(s, 4) for s in row_sums_c.tolist()])\n", "out_c_bad = weights_c_bad @ V\n", "print_matrix(\"9c · Broken output = broken_weights @ V\", out_c_bad, TOKENS_4, [\"o0\", \"o1\"])\n", "print(f\"Max abs diff vs true causal output: {(out_c_bad - out_mat).abs().max().item():.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-1-attention-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the upper triangle is zero, so no future *value* vector `v_j` is added directly — yet\n", "rows `0`, `1`, and `2` no longer sum to `1` (row 0 drops far below `1.0`). Even if you divided\n", "each row by its sum afterwards to renormalise, wait: *would* renormalising after zeroing give the\n", "same answer as adding `−∞` before softmax, or why does `−∞` before softmax also prevent future\n", "scores from leaking into the denominator? Check both algebraically!" ], "id": "lab-3-1-attention-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-1-attention-29" } ] }