{ "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.4 · What Did the Model Learn?\n", "\n", "**Goal:** open the trained TinyGPT of Lab 3.3 and look inside it with four instruments: the\n", "attention patterns of its 16 heads, a test that finds *induction heads* by what happens when\n", "the input repeats itself, linear probes that ask which layer knows a property of the text, and\n", "the logit lens that decodes the hidden state after every layer into a token. Then break each\n", "instrument on purpose: a probe that \"works\" on random labels, a head whose meaning you read off\n", "one example, and a head with a striking pattern that turns out not to matter.\n", "\n", "**Runs on:** any laptop CPU; no GPU needed (the model has 3.3 million weights and everything is\n", "a forward pass). About 5 to 10 minutes on an M1 CPU for the whole notebook. Install locally with\n", "`uv run --with torch --with tiktoken --with numpy --with matplotlib jupyter lab`.\n", "\n", "**Needs two things from Lab 3.3:** the trained reference checkpoint\n", "`data/lab-3-3-tinygpt/tinygpt-reference.pt` (13 MB, in the book's repository; the vocabulary\n", "table is stored inside it) and the TinyStories text. The notebook downloads the same 120 MB slice\n", "itself once, and only uses the 2 % of its stories that Lab 3.3 set aside for validation, so every\n", "story you probe is one the model never trained on. **If you do not have the checkpoint**, run\n", "Lab 3.3 with `TINYGPT_SETTING=quick` (about 13 minutes on an M1 CPU) and set the environment\n", "variable `TINYGPT_CKPT` to the `tinygpt-quick.pt` it writes; the model will be weaker and every\n", "number below will differ, but the instruments work the same way and you should expect weaker\n", "effects.\n", "\n", "**Versions tested:** printed by the last cell.\n", "\n", "Everything here is measured on this one 3.3 M-parameter model. Nothing in this notebook says\n", "what a model with 100 times as many layers does." ], "id": "lab-3-4-inside-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import json\n", "import math\n", "import os\n", "import pathlib\n", "import platform\n", "import time\n", "import urllib.request\n", "from dataclasses import dataclass\n", "\n", "import matplotlib\n", "import numpy as np\n", "import tiktoken\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "if not os.environ.get(\"DISPLAY\") and platform.system() != \"Darwin\":\n", " matplotlib.use(\"Agg\")\n", "import matplotlib.pyplot as plt\n", "\n", "torch.set_num_threads(max(1, min(4, torch.get_num_threads()))) # modest on a shared laptop\n", "T0 = time.time()\n", "print(f\"PyTorch {torch.__version__} | tiktoken {tiktoken.__version__} | device cpu | threads {torch.get_num_threads()}\")\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-4-inside\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def cache_dir():\n", " for candidate in (pathlib.Path(\".work\"), pathlib.Path(\"../.work\")):\n", " if candidate.is_dir():\n", " return candidate\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def find_file(rel):\n", " for base in (\".\", \"..\"):\n", " p = pathlib.Path(base) / rel\n", " if p.exists():\n", " return p\n", " return None\n", "\n", "\n", "def save_csv(name, fieldnames, rows):\n", " path = out_dir() / name\n", " with path.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=fieldnames, lineterminator=\"\\n\")\n", " w.writeheader()\n", " w.writerows(rows)\n", " print(\"saved\", path)\n", "\n", "\n", "def save_json(name, obj):\n", " path = out_dir() / name\n", " path.write_text(json.dumps(obj, ensure_ascii=False, separators=(\",\", \":\")) + \"\\n\")\n", " print(\"saved\", path)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your answers before you run anything.\n", "\n", "1. The model has 4 layers of 4 heads each: 16 heads. In a model trained only to predict the next\n", " token, which attention behaviours do you expect to find among them? Name two that you can\n", " measure with one number each (hint: where does a head send its weight?).\n", "2. Take 64 random tokens and write them twice in a row. On the first copy the model has nothing\n", " to go on; what loss do you expect there, in terms of `log V` (`V = 19,040`)? If the model can\n", " copy, what should happen on the second copy, and from which position of the second copy on?\n", "3. If you remove (zero) one attention head at a time, how many of the 16 do you expect to hurt\n", " the validation loss by more than 0.1 nats? Which kind of head do you expect to matter most?\n", "4. You train a linear classifier on the hidden state to detect \"this token is inside a quotation\n", " mark\". At the embedding layer (token vector plus position vector, nothing else), what accuracy\n", " can it get on a balanced test set, and why? Does it rise or fall in later layers?\n", "5. You train the same classifier on *random* labels. What test accuracy do you expect? What\n", " *train* accuracy could it reach if you give it only 200 examples, and why does that number\n", " tell you nothing about the model?\n", "6. The logit lens decodes a hidden state through the final LayerNorm and the output matrix. At\n", " the embedding layer, which token would you expect it to print for the input token `Lily`?" ], "id": "lab-3-4-inside-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Load the model and the validation stories\n", "\n", "The model class is the one you built in Lab 3.3, copied here so the notebook is self-contained,\n", "plus an instrumented forward pass `run()` that returns what we need: the attention weights of\n", "every head, the hidden state after every block, and an option to remove chosen heads." ], "id": "lab-3-4-inside-03" }, { "cell_type": "code", "metadata": {}, "source": [ "@dataclass\n", "class GPTConfig:\n", " vocab_size: int\n", " block_size: int = 256\n", " n_layer: int = 4\n", " n_head: int = 4\n", " d_model: int = 128\n", " dropout: float = 0.0\n", "\n", "\n", "class CausalSelfAttention(nn.Module):\n", " def __init__(self, c):\n", " super().__init__()\n", " self.n_head = c.n_head\n", " self.qkv = nn.Linear(c.d_model, 3 * c.d_model)\n", " self.proj = nn.Linear(c.d_model, c.d_model)\n", " self.drop = nn.Dropout(c.dropout)\n", " self.register_buffer(\"mask\", torch.tril(torch.ones(c.block_size, c.block_size, dtype=torch.bool)), persistent=False)\n", "\n", " def forward(self, x, manual=False):\n", " B, T, C = x.shape\n", " q, k, v = self.qkv(x).split(C, dim=2)\n", " q, k, v = (t.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) for t in (q, k, v))\n", " y = F.scaled_dot_product_attention(q, k, v, is_causal=True)\n", " return self.drop(self.proj(y.transpose(1, 2).reshape(B, T, C)))\n", "\n", "\n", "class Block(nn.Module):\n", " def __init__(self, c):\n", " super().__init__()\n", " self.ln1, self.attn = nn.LayerNorm(c.d_model), CausalSelfAttention(c)\n", " self.ln2 = nn.LayerNorm(c.d_model)\n", " self.mlp = nn.Sequential(nn.Linear(c.d_model, 4 * c.d_model), nn.GELU(),\n", " nn.Linear(4 * c.d_model, c.d_model), nn.Dropout(c.dropout))\n", "\n", " def forward(self, x, manual=False):\n", " x = x + self.attn(self.ln1(x))\n", " return x + self.mlp(self.ln2(x))\n", "\n", "\n", "class GPT(nn.Module):\n", " def __init__(self, c):\n", " super().__init__()\n", " self.c = c\n", " self.wte = nn.Embedding(c.vocab_size, c.d_model)\n", " self.wpe = nn.Embedding(c.block_size, c.d_model)\n", " self.drop = nn.Dropout(c.dropout)\n", " self.blocks = nn.ModuleList([Block(c) for _ in range(c.n_layer)])\n", " self.ln_f = nn.LayerNorm(c.d_model)\n", " self.lm_head = nn.Linear(c.d_model, c.vocab_size, bias=False)\n", " self.lm_head.weight = self.wte.weight\n", "\n", " def forward(self, idx):\n", " B, T = idx.shape\n", " x = self.drop(self.wte(idx) + self.wpe(torch.arange(T, device=idx.device)))\n", " for block in self.blocks:\n", " x = block(x)\n", " return self.lm_head(self.ln_f(x))\n", "\n", "\n", "CKPT = pathlib.Path(os.environ[\"TINYGPT_CKPT\"]) if os.environ.get(\"TINYGPT_CKPT\") else find_file(\"data/lab-3-3-tinygpt/tinygpt-reference.pt\")\n", "assert CKPT and CKPT.exists(), \"checkpoint not found: see the header of this notebook\"\n", "ck = torch.load(CKPT, map_location=\"cpu\", weights_only=True)\n", "cfg = GPTConfig(**ck[\"config\"])\n", "model = GPT(cfg)\n", "model.load_state_dict(ck[\"model\"])\n", "model.eval()\n", "for p in model.parameters():\n", " p.requires_grad_(False)\n", "used = ck[\"vocab_gpt2_ids\"] # our id -> GPT-2 id\n", "V, L, H, D, T = cfg.vocab_size, cfg.n_layer, cfg.n_head, cfg.d_model, cfg.block_size\n", "DH = D // H\n", "enc = tiktoken.get_encoding(\"gpt2\")\n", "EOT_GPT2 = enc.eot_token\n", "to_new = {t: i for i, t in enumerate(used)}\n", "EOT = to_new[EOT_GPT2]\n", "print(f\"checkpoint {CKPT} step {ck['step']} V={V:,} layers {L} heads {H} d_model {D} context {T}\")\n", "print(f\"parameters {sum(p.numel() for p in model.parameters()):,} is token {EOT}\")\n", "\n", "\n", "def encode(text):\n", " return [to_new[t] for t in enc.encode_ordinary(text)]\n", "\n", "\n", "def tok_str(i):\n", " return enc.decode([used[i]])" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The validation stories\n", "\n", "Lab 3.3 shuffled the stories of the first 120 MB of TinyStories with `numpy` seed 0 and kept the\n", "last 2 % for validation. We rebuild exactly that split (and check that it matches the 573,450\n", "validation tokens the lab reported), and tokenise only the validation stories." ], "id": "lab-3-4-inside-05" }, { "cell_type": "code", "metadata": {}, "source": [ "DATA_MB = 120\n", "URL = \"https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories-train.txt\"\n", "RAW = cache_dir() / f\"tinystories-train-head-{DATA_MB}mb.txt\"\n", "if not RAW.exists():\n", " req = urllib.request.Request(URL, headers={\"Range\": f\"bytes=0-{DATA_MB * 1_000_000 - 1}\"})\n", " with urllib.request.urlopen(req, timeout=300) as r:\n", " RAW.write_bytes(r.read())\n", "text = RAW.read_bytes().decode(\"utf-8\", errors=\"ignore\")\n", "stories = [s.strip() for s in text.split(\"<|endoftext|>\")][:-1]\n", "del text\n", "cut = int(len(stories) * 0.98)\n", "order = np.random.default_rng(0).permutation(len(stories))\n", "val_stories = [stories[i] for i in order[cut:]]\n", "n_stories_total = len(stories)\n", "del stories\n", "val_ids = [] # each: [] + story tokens (the model saw an before every story)\n", "for k in range(0, len(val_stories), 5000):\n", " for p in enc.encode_ordinary_batch(val_stories[k:k + 5000], num_threads=4):\n", " val_ids.append(np.array([EOT] + [to_new[t] for t in p], dtype=np.int64))\n", "val_flat = np.concatenate([np.concatenate([a[1:], [EOT]]) for a in val_ids]) # exactly Lab 3.3's val array\n", "print(f\"stories {n_stories_total:,} validation stories {len(val_stories):,} validation tokens {len(val_flat):,} (Lab 3.3 reported 573,450)\")\n", "assert len(val_flat) == 573450\n", "\n", "# non-overlapping windows of 256 tokens, as in Lab 3.3's \"all 2,240 windows\"\n", "n_win = (len(val_flat) - 1) // T\n", "WIN_X = torch.from_numpy(val_flat[: n_win * T].reshape(n_win, T))\n", "WIN_Y = torch.from_numpy(val_flat[1: n_win * T + 1].reshape(n_win, T))\n", "EVAL = slice(0, 256) # windows used for every loss and every head score\n", "REF = slice(256, 512) # other windows: used to compute mean head outputs\n", "print(f\"{n_win} validation windows; evaluating on windows 0..255 ({256 * T:,} tokens)\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The instrumented forward pass\n", "\n", "`run()` repeats `GPT.forward` block by block so that we can read and change what happens inside.\n", "For each layer it computes `q`, `k`, `v`, the attention weights (`[B, heads, T, T]`), and the\n", "output of every head *before* the output matrix `W_O` mixes them (`[B, heads, T, d/h]`). An\n", "**ablation** replaces one head's output by zeros (zero-ablation) or by its average over many\n", "tokens (mean-ablation) before `W_O`. Check first that it reproduces the model." ], "id": "lab-3-4-inside-07" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def run(idx, ablate=None, att=False, resid=False, head_out=False):\n", " \"\"\"ablate: {(layer, head): None for zeros, or a [d/h] vector to write instead of the head's output}.\"\"\"\n", " B, Tn = idx.shape\n", " x = model.wte(idx) + model.wpe(torch.arange(Tn))\n", " res, atts, outs = [x], [], []\n", " mask = torch.tril(torch.ones(Tn, Tn, dtype=torch.bool))\n", " for l, blk in enumerate(model.blocks):\n", " h = blk.ln1(x)\n", " q, k, v = blk.attn.qkv(h).split(D, dim=2)\n", " q, k, v = (t.view(B, Tn, H, DH).transpose(1, 2) for t in (q, k, v))\n", " a = ((q @ k.transpose(-2, -1)) / math.sqrt(DH)).masked_fill(~mask, float(\"-inf\")).softmax(-1) # [B, h, T, T]\n", " y = a @ v # [B, h, T, d/h]\n", " if head_out:\n", " outs.append(y.clone())\n", " for (al, ah), val in (ablate or {}).items():\n", " if al == l:\n", " y[:, ah] = 0 if val is None else val\n", " if att:\n", " atts.append(a)\n", " x = x + blk.attn.proj(y.transpose(1, 2).reshape(B, Tn, D))\n", " x = x + blk.mlp(blk.ln2(x))\n", " res.append(x)\n", " logits = model.lm_head(model.ln_f(x))\n", " return {\"logits\": logits, \"att\": atts, \"resid\": res, \"head_out\": outs}\n", "\n", "\n", "def batches(x, size=32):\n", " for i in range(0, len(x), size):\n", " yield x[i:i + size]\n", "\n", "\n", "def mean_loss(x, y, ablate=None):\n", " \"\"\"Mean next-token loss over every position of windows x (targets y).\"\"\"\n", " tot, n = 0.0, 0\n", " for xb, yb in zip(batches(x), batches(y)):\n", " lg = run(xb, ablate)[\"logits\"]\n", " tot += F.cross_entropy(lg.reshape(-1, V), yb.reshape(-1), reduction=\"sum\").item()\n", " n += yb.numel()\n", " return tot / n\n", "\n", "\n", "with torch.no_grad():\n", " xt = WIN_X[:2]\n", " d_logits = (run(xt)[\"logits\"] - model(xt)).abs().max().item()\n", "print(f\"run() vs model(): max abs difference of the logits {d_logits:.1e}\")\n", "BASE_VAL = mean_loss(WIN_X[EVAL], WIN_Y[EVAL])\n", "print(f\"validation loss on the 256 evaluation windows (float32, cpu): {BASE_VAL:.4f} (Lab 3.3: 2.0653 on all 2,240 windows, bfloat16)\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Reading attention patterns\n", "\n", "Attention weights are the one thing in a Transformer that is *already* a picture: for each head,\n", "a `T x T` table whose row `t` says how the token at `t` splits its attention over the earlier\n", "tokens. Below: the 16 heads on one fixed story. Layer 0 is the first block, so `L0H2` is head 2\n", "of the first block (heads and layers count from 0, as in the code)." ], "id": "lab-3-4-inside-09" }, { "cell_type": "code", "metadata": {}, "source": [ "STORY = (\"Once upon a time, there was a little girl named Lily. Lily had a red ball. One day, she went to the \"\n", " \"park with her mom. \\\"Mom, can I play with my ball?\\\" Lily asked. Her mom said, \\\"Yes, but stay close to me.\\\" \"\n", " \"Lily threw the ball, and it rolled away. Lily was sad, but her mom helped her find it.\")\n", "story_ids = torch.tensor([[EOT] + encode(STORY)])\n", "story_toks = [tok_str(i) for i in story_ids[0].tolist()]\n", "out = run(story_ids, att=True)\n", "print(f\"the fixed story has {story_ids.shape[1]} tokens (including a leading )\")\n", "print(\" | \".join(f\"{i}:{t!r}\" for i, t in enumerate(story_toks[:30])), \"...\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-10" }, { "cell_type": "code", "metadata": {}, "source": [ "fig, axes = plt.subplots(L, H, figsize=(14, 14))\n", "for l in range(L):\n", " for h in range(H):\n", " axes[l, h].imshow(out[\"att\"][l][0, h].numpy(), cmap=\"Blues\", vmin=0, vmax=1)\n", " axes[l, h].set_title(f\"L{l}H{h}\", fontsize=9)\n", " axes[l, h].set_xticks([])\n", " axes[l, h].set_yticks([])\n", "plt.suptitle(\"Attention weights of all 16 heads on the fixed story (row = the token that looks, column = the token it looks at)\")\n", "plt.tight_layout()\n", "plt.show()" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### From a picture to numbers: four scores per head\n", "\n", "A picture of one head on one story is an anecdote. To say what a head *does* we measure it on\n", "many windows (the 256 evaluation windows, 65,536 tokens). For a head with attention weights\n", "`A[t, s]` (query position `t`, key position `s <= t`):\n", "\n", "- **previous-token score**: the mean of `A[t, t-1]` over `t >= 1`; 1.0 would mean the head always\n", " looks at the token just before.\n", "- **first-position score**: the mean of `A[t, 0]` over `t >= 1`; the share of weight that goes\n", " to the first token of the window (which the model has seen as \"an arbitrary token\", because\n", " training windows start anywhere).\n", "- **name score**: among the query positions that have at least one earlier name token in the\n", " window, the attention mass on earlier name tokens divided by the mass a uniform head would\n", " give them (the fraction of earlier positions that are names). 1.0 = no preference for names.\n", " The name tokens are found automatically: every token that directly follows ` named` at\n", " least 3 times in the validation stories (and the same name without its leading space).\n", "- **entropy**: the mean entropy of a row in nats, divided by `log(t+1)`, the entropy of a\n", " uniform row. Near 0: a sharp head. Near 1: a head that averages everything." ], "id": "lab-3-4-inside-12" }, { "cell_type": "code", "metadata": {}, "source": [ "named_id = encode(\" named\")[0]\n", "after_named = {}\n", "for a in val_ids:\n", " for i in np.where(a[:-1] == named_id)[0]:\n", " after_named[int(a[i + 1])] = after_named.get(int(a[i + 1]), 0) + 1\n", "NAME_IDS = {t for t, c in after_named.items() if c >= 3}\n", "for t in list(NAME_IDS): # the same name without the leading space (e.g. after a quote)\n", " s = tok_str(t).strip()\n", " try:\n", " ids = encode(s)\n", " if len(ids) == 1:\n", " NAME_IDS.add(ids[0])\n", " except KeyError:\n", " pass\n", "NAME_IDS.discard(EOT)\n", "name_mask_lut = torch.zeros(V, dtype=torch.bool)\n", "name_mask_lut[list(NAME_IDS)] = True\n", "print(f\"{len(NAME_IDS)} name tokens, e.g.\", [tok_str(t) for t in sorted(NAME_IDS, key=lambda t: -after_named.get(t, 0))[:12]])\n", "\n", "\n", "def head_scores(x):\n", " \"\"\"Per (layer, head): prev, first, name (x uniform), entropy ratio, averaged over all windows of x.\"\"\"\n", " sums = np.zeros((L, H, 4)); counts = np.zeros(4)\n", " mass_name = np.zeros((L, H)); uni_name = np.zeros((L, H)); n_name_q = 0\n", " for xb in batches(x, 32):\n", " r = run(xb, att=True)\n", " B, Tn = xb.shape\n", " is_name = name_mask_lut[xb] # [B, T] key is a name\n", " cum_names = is_name.cumsum(1) # names at positions <= t\n", " has_prev_name = (cum_names - is_name.long()) > 0 # a name strictly before position t\n", " pos = torch.arange(Tn)\n", " for l in range(L):\n", " a = r[\"att\"][l] # [B, h, T, T]\n", " sums[l, :, 0] += a[:, :, torch.arange(1, Tn), torch.arange(0, Tn - 1)].mean((0, 2)).numpy() * B\n", " sums[l, :, 1] += a[:, :, 1:, 0].mean((0, 2)).numpy() * B\n", " ent = -(a * torch.log(a.clamp_min(1e-12))).sum(-1) # [B, h, T]\n", " norm = torch.log((pos + 1).float()).clamp_min(1e-6)\n", " sums[l, :, 3] += (ent[:, :, 1:] / norm[1:]).mean((0, 2)).numpy() * B\n", " earlier_name_mass = (a * is_name[:, None, None, :].float()).sum(-1) # mass on names (incl. t itself if it is one)\n", " self_name = (is_name[:, None, :].float() * a.diagonal(dim1=-2, dim2=-1))\n", " earlier_name_mass = earlier_name_mass - self_name # strictly earlier names\n", " q = has_prev_name[:, None, :].float() # [B, 1, T]\n", " mass_name[l] += (earlier_name_mass * q).sum((0, 2)).numpy()\n", " frac = (cum_names - is_name.long()).float() / (pos.float()[None, :] + 1) # uniform share of earlier names\n", " uni_name[l] += ((frac * has_prev_name.float())[:, None, :].expand(-1, H, -1)).sum((0, 2)).numpy()\n", " n_name_q += int(has_prev_name.sum())\n", " counts += B\n", " s = sums / counts[0]\n", " return {\"prev\": s[:, :, 0], \"first\": s[:, :, 1], \"entropy\": s[:, :, 3], \"name\": mass_name / np.maximum(uni_name, 1e-9), \"n_name_queries\": n_name_q}\n", "\n", "\n", "t = time.time()\n", "HS = head_scores(WIN_X[EVAL])\n", "print(f\"head scores on {256 * T:,} tokens in {time.time() - t:.0f} s; {HS['n_name_queries']:,} query positions have an earlier name\")\n", "print(f\"{'head':>5} {'prev':>7} {'first':>7} {'name x':>7} {'entropy':>8}\")\n", "for l in range(L):\n", " for h in range(H):\n", " print(f\"L{l}H{h} {HS['prev'][l, h]:7.3f} {HS['first'][l, h]:7.3f} {HS['name'][l, h]:7.2f} {HS['entropy'][l, h]:8.3f}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-13" }, { "cell_type": "code", "metadata": {}, "source": [ "# attention to the first position of a *story* (the leading ): windows that start at a story's first token\n", "STORY_X = torch.stack([torch.from_numpy(a[:T]) for a in val_ids if len(a) >= T][:128])\n", "START = np.zeros((L, H))\n", "for xb in batches(STORY_X, 32):\n", " r = run(xb, att=True)\n", " for l in range(L):\n", " START[l] += r[\"att\"][l][:, :, 1:, 0].mean((0, 2)).numpy() * len(xb)\n", "START /= len(STORY_X)\n", "print(f\"attention on the leading of a story, mean over {len(STORY_X)} stories of 256 tokens (a uniform head would give about 0.02):\")\n", "print(\" \" + \" \".join(f\"L{l}H{h} {START[l, h]:.3f}\" for l in range(L) for h in range(H)))" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Read the table before you read the next cell: which heads have a score far from the others?\n", "What would the score be for a head that attended uniformly? (Hint: previous-token score `1/(t+1)`\n", "on average, name score exactly 1.)" ], "id": "lab-3-4-inside-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Save the matrices of the story for the diagrams\n", "\n", "One JSON file with the tokens of the fixed story and the attention matrix of each of the 16 heads\n", "(row `t` keeps only its `t + 1` entries, the rest is zero by the causal mask; 3 decimals)." ], "id": "lab-3-4-inside-16" }, { "cell_type": "code", "metadata": {}, "source": [ "att_json = {\n", " \"story\": STORY, \"tokens\": story_toks, \"note\": \"row t of a matrix holds the weights of the token at t over positions 0..t; is token 0\",\n", " \"heads\": {f\"L{l}H{h}\": [[round(float(v), 3) for v in out[\"att\"][l][0, h, t_, : t_ + 1]] for t_ in range(story_ids.shape[1])]\n", " for l in range(L) for h in range(H)},\n", " \"scores_over_256_windows\": {f\"L{l}H{h}\": {\"story_start\": round(float(START[l, h]), 4), \"prev\": round(float(HS[\"prev\"][l, h]), 4), \"first\": round(float(HS[\"first\"][l, h]), 4),\n", " \"name_x_uniform\": round(float(HS[\"name\"][l, h]), 3), \"entropy_ratio\": round(float(HS[\"entropy\"][l, h]), 4)}\n", " for l in range(L) for h in range(H)}}\n", "save_json(\"attention-fixed-story.json\", att_json)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · The induction test\n", "\n", "An **induction head** (Olsson et al., 2022, cited in the chapter) implements the rule \"`[A][B] ... [A]`\n", "so predict `[B]`\": it finds the earlier place where the current token occurred and copies what came\n", "after it. The test that does not need any language at all: draw `n` random tokens, write them twice.\n", "On the first copy nothing can be predicted (the tokens are random). On the second copy a model with\n", "induction heads can predict every token, because the first copy shows what follows each one.\n", "\n", "We measure the loss at every position, on 200 sequences of `n = 64` random tokens repeated (128\n", "tokens). Position `t` predicts token `t + 1`. Positions `0 .. 62` predict the first copy; position 63\n", "predicts the first token of the repeat (nothing to copy yet, we do not count it); positions\n", "`64 .. 126` predict the second copy." ], "id": "lab-3-4-inside-18" }, { "cell_type": "code", "metadata": {}, "source": [ "HALF, NSEQ = 64, 200\n", "g = torch.Generator().manual_seed(34)\n", "pool = torch.tensor([i for i in range(V) if i != EOT])\n", "first = pool[torch.randint(0, len(pool), (NSEQ, HALF), generator=g)]\n", "REP = torch.cat([first, first], dim=1) # [200, 128]\n", "\n", "\n", "def per_position_loss(rep, ablate=None):\n", " tot = []\n", " for xb in batches(rep, 50):\n", " lg = run(xb, ablate)[\"logits\"]\n", " tot.append(F.cross_entropy(lg[:, :-1].reshape(-1, V), xb[:, 1:].reshape(-1), reduction=\"none\").view(len(xb), -1))\n", " return torch.cat(tot) # [N, 2*HALF - 1]\n", "\n", "\n", "PPL = per_position_loss(REP)\n", "first_pos, second_pos = slice(0, HALF - 1), slice(HALF, 2 * HALF - 1)\n", "l1, l2 = PPL[:, first_pos].mean().item(), PPL[:, second_pos].mean().item()\n", "print(f\"log V = {math.log(V):.4f}\")\n", "print(f\"loss on the first copy (positions 0..{HALF - 2}): {l1:.3f}\")\n", "print(f\"loss on the second copy (positions {HALF}..{2 * HALF - 2}): {l2:.3f}\")\n", "print(f\"per position of the second copy, the loss: first 3 = {[round(v, 2) for v in PPL[:, second_pos].mean(0)[:3].tolist()]}, \"\n", " f\"last 3 = {[round(v, 2) for v in PPL[:, second_pos].mean(0)[-3:].tolist()]}\")\n", "rows = []\n", "for t_ in range(2 * HALF - 1):\n", " copy = \"first\" if t_ < HALF - 1 else (\"boundary\" if t_ == HALF - 1 else \"second\")\n", " rows.append({\"position\": t_, \"copy\": copy, \"mean_loss\": round(PPL[:, t_].mean().item(), 4), \"std_across_sequences\": round(PPL[:, t_].std().item(), 4)})\n", "save_csv(\"induction-loss-by-position.csv\", [\"position\", \"copy\", \"mean_loss\", \"std_across_sequences\"], rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Is the test fair to this model? Four more versions\n", "\n", "The random tokens above are drawn uniformly from all 19,039 non-`` tokens, most of which this\n", "model has seen rarely, so the test is far from the text it was trained on. The same test with\n", "other kinds of \"random\" and with real text:\n", "\n", "- **frequency**: tokens drawn at random with the probability they have in the validation stories;\n", "- **top 200**: uniform over the 200 most frequent tokens;\n", "- **natural text**: 64 consecutive tokens of a real validation story, written twice (the \"first\n", " copy\" is then ordinary text with no story before it);\n", "- **four copies**: 32 uniform random tokens written four times; loss by copy.\n", "\n", "Each version also has a **control** whose second half is *not* a copy (fresh random tokens, or the\n", "next 64 tokens of the same story): a loss that falls from the first half to the second can come from\n", "the model seeing more context, not from copying, and only the difference between the copy and its\n", "control is evidence of copying." ], "id": "lab-3-4-inside-20" }, { "cell_type": "code", "metadata": {}, "source": [ "def make_rep(kind, seed, control=False):\n", " \"\"\"control=True: the second half is NOT a copy (fresh random tokens, or the next 64 tokens of the same story).\"\"\"\n", " gg = torch.Generator().manual_seed(seed)\n", " counts = torch.from_numpy(np.bincount(val_flat, minlength=V)).float()\n", " counts[EOT] = 0\n", " n_draw = 2 if control else 1 # the control draws a second, independent half\n", " if kind == \"uniform\":\n", " base = pool[torch.randint(0, len(pool), (NSEQ, n_draw * HALF), generator=gg)]\n", " elif kind == \"frequency\":\n", " base = torch.multinomial(counts, NSEQ * n_draw * HALF, replacement=True, generator=gg).view(NSEQ, n_draw * HALF)\n", " elif kind == \"top200\":\n", " top = counts.topk(200).indices\n", " base = top[torch.randint(0, 200, (NSEQ, n_draw * HALF), generator=gg)]\n", " elif kind == \"natural\":\n", " rr = np.random.default_rng(seed)\n", " long_enough = [a for a in val_ids if len(a) >= 1 + n_draw * HALF + 1]\n", " pick = rr.choice(len(long_enough), NSEQ, replace=False)\n", " chunks = []\n", " for i in pick:\n", " a = long_enough[i]\n", " st = int(rr.integers(1, len(a) - n_draw * HALF + 1))\n", " chunks.append(torch.from_numpy(a[st:st + n_draw * HALF]))\n", " base = torch.stack(chunks)\n", " return base if control else torch.cat([base, base], dim=1)\n", "\n", "\n", "REPS = {k: make_rep(k, 34) for k in (\"uniform\", \"frequency\", \"top200\", \"natural\")}\n", "print(\"same sequences as the first test:\", bool(torch.equal(REPS[\"uniform\"], REP)))\n", "var_rows = []\n", "print(f\"{'tokens':>42} {'first half':>11} {'second half':>12} {'drop':>7} (standard error over the 200 sequences)\")\n", "for k, rep in REPS.items():\n", " for control in (False, True):\n", " pp = per_position_loss(make_rep(k, 34, control=True) if control else rep)\n", " a, b = pp[:, first_pos].mean().item(), pp[:, second_pos].mean().item()\n", " per_seq = pp[:, first_pos].mean(1) - pp[:, second_pos].mean(1) # one drop per sequence\n", " se = per_seq.std().item() / math.sqrt(len(per_seq))\n", " label = k + (\" (control: 2nd half NOT a copy)\" if control else \"\")\n", " var_rows.append({\"tokens\": label, \"copies\": 2, \"repeat_length\": HALF, \"first_copy_loss\": round(a, 4), \"second_copy_loss\": round(b, 4), \"drop\": round(a - b, 4), \"drop_standard_error\": round(se, 4)})\n", " print(f\"{label:>42} {a:11.3f} {b:12.3f} {a - b:7.3f} (+- {se:.3f})\")\n", "HALF4 = 32\n", "g4 = torch.Generator().manual_seed(35)\n", "base4 = pool[torch.randint(0, len(pool), (NSEQ, HALF4), generator=g4)]\n", "rep4 = torch.cat([base4] * 4, dim=1)\n", "ctl4 = pool[torch.randint(0, len(pool), (NSEQ, 4 * HALF4), generator=g4)] # control: 128 fresh random tokens\n", "pp4, pc4 = per_position_loss(rep4), per_position_loss(ctl4)\n", "four_rows = []\n", "for c in range(4):\n", " sl = slice(c * HALF4, (c + 1) * HALF4 - 1) if c < 3 else slice(3 * HALF4, 4 * HALF4 - 1) # positions that predict block c (skip the boundary)\n", " v, vc = pp4[:, sl].mean().item(), pc4[:, sl].mean().item()\n", " four_rows.append({\"copy\": c + 1, \"repeat_length\": HALF4, \"mean_loss\": round(v, 4), \"control_not_repeated_loss\": round(vc, 4)})\n", " print(f\"{'4 copies':>12} copy {c + 1}: loss {v:.3f} control (fresh random tokens) {vc:.3f}\")\n", "save_csv(\"induction-variants.csv\", [\"tokens\", \"copies\", \"repeat_length\", \"first_copy_loss\", \"second_copy_loss\", \"drop\", \"drop_standard_error\"], var_rows)\n", "save_csv(\"induction-four-copies.csv\", [\"copy\", \"repeat_length\", \"mean_loss\", \"control_not_repeated_loss\"], four_rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Which heads do it? Attention first\n", "\n", "On the second copy, the position `t` holds a token whose earlier occurrence is at `t - 64`; an\n", "induction head at `t` attends to the position *after* it, `t - 64 + 1`. The **induction score** of\n", "a head is its mean attention weight on that position, over positions `64 .. 126` of the second\n", "copy. For comparison, the **previous-token score** on the same sequences. Neither score proves\n", "the head causes the loss drop; the ablation below tests that." ], "id": "lab-3-4-inside-22" }, { "cell_type": "code", "metadata": {}, "source": [ "def induction_scores(rep):\n", " ind_sum = np.zeros((L, H)); prev_sum = np.zeros((L, H))\n", " for xb in batches(rep, 50):\n", " r = run(xb, att=True)\n", " tq = torch.arange(HALF, 2 * HALF - 1)\n", " for l in range(L):\n", " a = r[\"att\"][l]\n", " ind_sum[l] += a[:, :, tq, tq - HALF + 1].mean((0, 2)).numpy() * len(xb)\n", " prev_sum[l] += a[:, :, tq, tq - 1].mean((0, 2)).numpy() * len(xb)\n", " return ind_sum / len(rep), prev_sum / len(rep)\n", "\n", "\n", "IND, PREV_R = induction_scores(REP)\n", "IND_NAT, PREV_NAT = induction_scores(REPS[\"natural\"])\n", "order_ind = sorted(((l, h) for l in range(L) for h in range(H)), key=lambda p: -IND[p])\n", "print(\"induction score (attention to the token after the earlier occurrence), top 6 on uniform random tokens:\")\n", "for (l, h) in order_ind[:6]:\n", " print(f\" L{l}H{h}: {IND[l, h]:.3f} (previous-token score on the same sequences {PREV_R[l, h]:.3f})\")\n", "print(\"the same score on repeated natural text, top 6:\")\n", "for (l, h) in sorted(((l, h) for l in range(L) for h in range(H)), key=lambda p: -IND_NAT[p])[:6]:\n", " print(f\" L{l}H{h}: {IND_NAT[l, h]:.3f} (previous-token score on the same sequences {PREV_NAT[l, h]:.3f})\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Which heads do it? Ablation\n", "\n", "Remove one head at a time (zero-ablation) and measure the loss on both copies. A head that causes\n", "the second-copy drop shows up as a large rise in the second-copy loss and little change in the\n", "first. The 16 single-head runs are also each other's control: most heads should change little." ], "id": "lab-3-4-inside-24" }, { "cell_type": "code", "metadata": {}, "source": [ "rows_abl = []\n", "\n", "\n", "def ablation_row(label, ablate, mode):\n", " p = per_position_loss(REP, ablate)\n", " pn = per_position_loss(REPS[\"natural\"], ablate)\n", " vl = mean_loss(WIN_X[EVAL], WIN_Y[EVAL], ablate)\n", " row = {\"ablation\": label, \"mode\": mode, \"first_copy_loss\": round(p[:, first_pos].mean().item(), 4),\n", " \"second_copy_loss\": round(p[:, second_pos].mean().item(), 4),\n", " \"natural_first_copy_loss\": round(pn[:, first_pos].mean().item(), 4), \"natural_second_copy_loss\": round(pn[:, second_pos].mean().item(), 4),\n", " \"val_loss\": round(vl, 4)}\n", " rows_abl.append(row)\n", " return row\n", "\n", "\n", "base = ablation_row(\"none\", None, \"-\")\n", "print(f\"{'ablated':>22} | {'random tokens: 1st':>18} {'2nd copy':>9} | {'natural text: 1st':>17} {'2nd copy':>9} | {'val loss':>9}\")\n", "\n", "\n", "def show(r):\n", " print(f\"{r['ablation']:>22} | {r['first_copy_loss']:18.3f} {r['second_copy_loss']:9.3f} | {r['natural_first_copy_loss']:17.3f} {r['natural_second_copy_loss']:9.3f} | {r['val_loss']:9.4f}\")\n", "\n", "\n", "show(base)\n", "for l in range(L):\n", " for h in range(H):\n", " show(ablation_row(f\"L{l}H{h}\", {(l, h): None}, \"zero\"))" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-25" }, { "cell_type": "code", "metadata": {}, "source": [ "# whole layers, and the top induction candidates together\n", "for l in range(L):\n", " show(ablation_row(f\"all heads of layer {l}\", {(l, h): None for h in range(H)}, \"zero\"))\n", "top2 = order_ind[:2]\n", "show(ablation_row(\"top-2 induction score: \" + \"+\".join(f\"L{l}H{h}\" for l, h in top2), {p: None for p in top2}, \"zero\"))" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Is \"zero\" a fair way to remove a head?\n", "\n", "A head that is set to zero writes something the model never saw during training. **Mean-ablation**\n", "writes the head's *average* output instead (taken over other windows), which removes what the head\n", "says about *this* input and keeps its typical offset. Repeat the single-head ablations with it." ], "id": "lab-3-4-inside-27" }, { "cell_type": "code", "metadata": {}, "source": [ "sum_out = torch.zeros(L, H, DH); cnt = 0\n", "for xb in batches(WIN_X[REF], 32):\n", " r = run(xb, head_out=True)\n", " for l in range(L):\n", " sum_out[l] += r[\"head_out\"][l].sum((0, 2))\n", " cnt += xb.shape[0] * xb.shape[1]\n", "HEAD_MEAN = sum_out / cnt\n", "for l in range(L):\n", " for h in range(H):\n", " ablation_row(f\"L{l}H{h}\", {(l, h): HEAD_MEAN[l, h]}, \"mean\")\n", "tab = {(r[\"ablation\"], r[\"mode\"]): r for r in rows_abl}\n", "print(f\"{'head':>6} | {'zero: natural 2nd':>17} {'val loss':>9} | {'mean: natural 2nd':>17} {'val loss':>9}\")\n", "for l in range(L):\n", " for h in range(H):\n", " z, m = tab[(f\"L{l}H{h}\", \"zero\")], tab[(f\"L{l}H{h}\", \"mean\")]\n", " print(f\"L{l}H{h} | {z['natural_second_copy_loss']:17.3f} {z['val_loss']:9.4f} | {m['natural_second_copy_loss']:17.3f} {m['val_loss']:9.4f}\")\n", "save_csv(\"induction-ablation.csv\", [\"ablation\", \"mode\", \"first_copy_loss\", \"second_copy_loss\", \"natural_first_copy_loss\", \"natural_second_copy_loss\", \"val_loss\"], rows_abl)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-28" }, { "cell_type": "code", "metadata": {}, "source": [ "# the induction score and the ablation result side by side, per head\n", "head_rows = []\n", "for l in range(L):\n", " for h in range(H):\n", " z, m = tab[(f\"L{l}H{h}\", \"zero\")], tab[(f\"L{l}H{h}\", \"mean\")]\n", " head_rows.append({\n", " \"layer\": l, \"head\": h, \"prev_score\": round(float(HS[\"prev\"][l, h]), 4), \"first_score\": round(float(HS[\"first\"][l, h]), 4),\n", " \"name_x_uniform\": round(float(HS[\"name\"][l, h]), 3), \"entropy_ratio\": round(float(HS[\"entropy\"][l, h]), 4),\n", " \"story_start_score\": round(float(START[l, h]), 4),\n", " \"induction_score\": round(float(IND[l, h]), 4), \"prev_score_on_repeat\": round(float(PREV_R[l, h]), 4),\n", " \"induction_score_natural\": round(float(IND_NAT[l, h]), 4),\n", " \"second_copy_loss_zero\": z[\"second_copy_loss\"], \"natural_second_copy_loss_zero\": z[\"natural_second_copy_loss\"], \"val_loss_zero\": z[\"val_loss\"], \"val_delta_zero\": round(z[\"val_loss\"] - base[\"val_loss\"], 4),\n", " \"second_copy_loss_mean\": m[\"second_copy_loss\"], \"val_loss_mean\": m[\"val_loss\"], \"val_delta_mean\": round(m[\"val_loss\"] - base[\"val_loss\"], 4)})\n", "save_csv(\"heads.csv\", list(head_rows[0]), head_rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Probing: which layer knows what?\n", "\n", "A **probe** is a small classifier trained on the hidden states of a frozen model. If a *linear*\n", "classifier can read a property off the residual stream after layer `k`, the information is there\n", "in an easy-to-read form after layer `k`. It does not show that the model *uses* it.\n", "\n", "Two properties that we can label automatically in TinyStories:\n", "\n", "1. **inside a quote**: the token at position `t` comes after an odd number of `\"` characters\n", " counted from the start of the story (the state after reading token `t`, so the opening mark\n", " counts as inside and the closing mark as outside). To know it, a model must count quote marks\n", " over the whole story so far: no single token gives it away.\n", "2. **next token is a name**: the token at `t + 1` is one of the name tokens found above. That\n", " is a property of the *future*, so a probe that finds it is reading the model's expectation.\n", "\n", "We use whole validation stories, each starting after an ``, up to 256 tokens. For each\n", "property we take a **balanced** set (equal numbers of positives and negatives, so chance is 50 %),\n", "split by *story* (never by token: neighbouring tokens of one story are nearly the same example),\n", "standardise each feature on the training half, and fit a logistic regression with L2 weight decay.\n", "Three numbers per layer, averaged over 5 different story splits:\n", "the test accuracy; the same probe trained on **randomly shuffled labels** (the control); and a\n", "**token-only baseline** that predicts from the current token's identity alone (majority label per\n", "token seen in training). The five places we read from: the embedding (token + position vector,\n", "before any block) and the residual stream after block 1, 2, 3 and 4." ], "id": "lab-3-4-inside-30" }, { "cell_type": "code", "metadata": {}, "source": [ "quote_chars = np.array([tok_str(i).count('\"') for i in range(V)])\n", "NAME_ARR = name_mask_lut.numpy()\n", "PROBE_POINTS = [\"embedding\", \"after block 1\", \"after block 2\", \"after block 3\", \"after block 4\"]\n", "rng = np.random.default_rng(7)\n", "SAMPLE_FRAC = 0.12\n", "feats, lab_quote, lab_name, story_of, tok_of = [], [], [], [], []\n", "t = time.time()\n", "story_len = [min(len(a), T) for a in val_ids]\n", "order_len = np.argsort(story_len) # batches of similar length: little padding\n", "for i0 in range(0, len(order_len), 32):\n", " ids_b = order_len[i0:i0 + 32]\n", " Lb = max(story_len[i] for i in ids_b)\n", " xb = torch.full((len(ids_b), Lb), EOT, dtype=torch.long)\n", " for j, i in enumerate(ids_b):\n", " xb[j, :story_len[i]] = torch.from_numpy(val_ids[i][:story_len[i]])\n", " res = run(xb, resid=True)[\"resid\"]\n", " for j, i in enumerate(ids_b):\n", " n = story_len[i]\n", " toks = val_ids[i][:n]\n", " inside = (np.cumsum(quote_chars[toks]) % 2).astype(np.int8) # state after reading token t\n", " nxt_name = np.zeros(n, dtype=np.int8)\n", " nxt_name[:-1] = NAME_ARR[toks[1:]]\n", " pos = np.arange(1, n - 1) # not the leading , not the last token (no next token)\n", " keep = pos[rng.random(len(pos)) < SAMPLE_FRAC]\n", " if len(keep) == 0:\n", " continue\n", " feats.append(torch.stack([r[j, keep] for r in res], 0).numpy().astype(np.float32)) # [5, k, d]\n", " lab_quote.append(inside[keep]); lab_name.append(nxt_name[keep])\n", " story_of.append(np.full(len(keep), i)); tok_of.append(toks[keep])\n", "FEATS = np.concatenate(feats, 1) # [5, N, d]\n", "LQ, LN = np.concatenate(lab_quote), np.concatenate(lab_name)\n", "SID, TOK = np.concatenate(story_of), np.concatenate(tok_of)\n", "print(f\"{FEATS.shape[1]:,} sampled token positions from {len(np.unique(SID)):,} stories in {time.time() - t:.0f} s; features {FEATS.shape} ({FEATS.nbytes / 1e6:.0f} MB)\")\n", "print(f\"inside a quote: {LQ.mean() * 100:.1f} % of positions next token is a name: {LN.mean() * 100:.1f} % of positions\")\n", "print(f\"{int(((TOK == EOT)).sum())} sampled positions hold an (stories shorter than 256 end with one)\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-31" }, { "cell_type": "code", "metadata": {}, "source": [ "def fit_logistic(Xtr, ytr, l2=1e-2, iters=100):\n", " \"\"\"Logistic regression by L-BFGS: mean BCE + l2 * |w|^2.\"\"\"\n", " Xt, yt = torch.from_numpy(Xtr), torch.from_numpy(ytr.astype(np.float32))\n", " w = torch.zeros(Xt.shape[1], requires_grad=True)\n", " b = torch.zeros(1, requires_grad=True)\n", " opt = torch.optim.LBFGS([w, b], lr=1, max_iter=iters, line_search_fn=\"strong_wolfe\")\n", "\n", " def closure():\n", " opt.zero_grad()\n", " loss = F.binary_cross_entropy_with_logits(Xt @ w + b, yt) + l2 * (w ** 2).sum()\n", " loss.backward()\n", " return loss\n", " with torch.enable_grad():\n", " opt.step(closure)\n", " return w.detach().numpy(), float(b)\n", "\n", "\n", "def acc(w, b, X, y):\n", " return float((((X @ w + b) > 0).astype(np.int8) == y).mean())\n", "\n", "\n", "def balanced_split(labels, seed, test_frac=0.3, cap_train=6000, cap_test=2500):\n", " \"\"\"Split STORIES into train/test, then balance each side to equal positives and negatives.\"\"\"\n", " r = np.random.default_rng(seed)\n", " stories_u = np.unique(SID)\n", " test_set = set(r.choice(stories_u, int(len(stories_u) * test_frac), replace=False).tolist())\n", " is_test = np.array([s in test_set for s in SID])\n", " out = []\n", " for side, cap in ((~is_test, cap_train), (is_test, cap_test)):\n", " pos = np.where(side & (labels == 1))[0]; neg = np.where(side & (labels == 0))[0]\n", " k = min(len(pos), len(neg), cap)\n", " out.append(np.concatenate([r.choice(pos, k, replace=False), r.choice(neg, k, replace=False)]))\n", " return out\n", "\n", "\n", "def token_only_acc(tr, te, y):\n", " \"\"\"Predict each test token's label by the majority label of that token in the training half.\"\"\"\n", " from collections import Counter\n", " cnt = {}\n", " for t_, l_ in zip(TOK[tr], y[tr]):\n", " cnt.setdefault(int(t_), [0, 0])[int(l_)] += 1\n", " hit = 0\n", " for t_, l_ in zip(TOK[te], y[te]):\n", " c = cnt.get(int(t_))\n", " pred = 0 if c is None else int(c[1] > c[0])\n", " hit += int(pred == l_)\n", " return hit / len(te)\n", "\n", "\n", "def probe_layer(layer, labels, tr, te, seed, shuffle=False):\n", " Xtr, Xte = FEATS[layer][tr], FEATS[layer][te]\n", " mu, sd = Xtr.mean(0), Xtr.std(0) + 1e-6\n", " Xtr, Xte = (Xtr - mu) / sd, (Xte - mu) / sd\n", " ytr, yte = labels[tr].copy(), labels[te].copy()\n", " if shuffle:\n", " r = np.random.default_rng(seed + 1000)\n", " r.shuffle(ytr); r.shuffle(yte)\n", " w, b = fit_logistic(Xtr, ytr)\n", " return acc(w, b, Xtr, ytr), acc(w, b, Xte, yte)\n", "\n", "\n", "SPLITS = 5\n", "probe_rows = []\n", "t = time.time()\n", "for name, labels in ((\"inside a quote\", LQ), (\"next token is a name\", LN)):\n", " per = {k: [] for k in (\"train\", \"test\", \"ctrl_train\", \"ctrl_test\", \"tok\")}\n", " for sp in range(SPLITS):\n", " tr, te = balanced_split(labels, seed=sp)\n", " per[\"tok\"].append(token_only_acc(tr, te, labels))\n", " for layer in range(L + 1):\n", " a_tr, a_te = probe_layer(layer, labels, tr, te, sp)\n", " c_tr, c_te = probe_layer(layer, labels, tr, te, sp, shuffle=True)\n", " per[\"train\"].append((layer, a_tr)); per[\"test\"].append((layer, a_te))\n", " per[\"ctrl_train\"].append((layer, c_tr)); per[\"ctrl_test\"].append((layer, c_te))\n", " n_tr, n_te = len(tr), len(te)\n", " tok_mean, tok_std = float(np.mean(per[\"tok\"])), float(np.std(per[\"tok\"]))\n", " for layer in range(L + 1):\n", " g_ = lambda key: np.array([v for (l_, v) in per[key] if l_ == layer])\n", " probe_rows.append({\n", " \"property\": name, \"layer\": layer, \"where\": PROBE_POINTS[layer],\n", " \"test_acc\": round(g_(\"test\").mean(), 4), \"test_acc_std\": round(g_(\"test\").std(), 4), \"train_acc\": round(g_(\"train\").mean(), 4),\n", " \"shuffled_labels_test_acc\": round(g_(\"ctrl_test\").mean(), 4), \"shuffled_labels_test_acc_std\": round(g_(\"ctrl_test\").std(), 4),\n", " \"shuffled_labels_train_acc\": round(g_(\"ctrl_train\").mean(), 4),\n", " \"token_only_test_acc\": round(tok_mean, 4), \"n_train\": n_tr, \"n_test\": n_te, \"splits\": SPLITS})\n", "print(f\"probes fitted in {time.time() - t:.0f} s\")\n", "print(f\"{'property':>22} {'where':>14} {'test acc':>9} {'(std)':>7} {'train':>7} | {'shuffled test':>13} {'train':>7} | {'token only':>10}\")\n", "for r in probe_rows:\n", " print(f\"{r['property']:>22} {r['where']:>14} {r['test_acc']:9.3f} {r['test_acc_std']:7.3f} {r['train_acc']:7.3f} | \"\n", " f\"{r['shuffled_labels_test_acc']:13.3f} {r['shuffled_labels_train_acc']:7.3f} | {r['token_only_test_acc']:10.3f}\")\n", "print(f\"(balanced sets of about {probe_rows[0]['n_train']:,} training and {probe_rows[0]['n_test']:,} test positions; chance = 0.500)\"\n", " f\" second property: {probe_rows[-1]['n_train']:,} / {probe_rows[-1]['n_test']:,}\")\n", "save_csv(\"probe-by-layer.csv\", list(probe_rows[0]), probe_rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · The logit lens\n", "\n", "The output layer turns the final hidden state into scores for the next token. The **logit lens**\n", "(a trick from the interpretability community) applies that *same* final LayerNorm and output matrix\n", "to the hidden state after *every* block, as if the model stopped there. After block 4 it is exactly\n", "the model's output; before that it is a guess at what the model \"has in mind so far\". Nothing is\n", "trained: it is a reading of the weights you already have. (Position vectors and the embedding\n", "share the residual stream with everything else, so the reading is crude; treat it as a picture,\n", "not a measurement of intent.)\n", "\n", "We run it on four short sentences (CSV of the top-1 token and its probability at every position\n", "and layer) and on 256 validation windows (how the loss of the lens falls layer by layer)." ], "id": "lab-3-4-inside-33" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def lens_logits(res_k):\n", " return model.lm_head(model.ln_f(res_k))\n", "\n", "\n", "SENTENCES = [\n", " \"Once upon a time, there was a little girl named Lily.\",\n", " \"Tom and his dog went to the park.\",\n", " \"The sun was hot, so the little bird\",\n", " \"Lily had a red ball. One day, Lily and her mom went to the park. Lily threw the ball.\",\n", "]\n", "lens_rows, lens_json = [], []\n", "for si, s in enumerate(SENTENCES):\n", " ids = torch.tensor([[EOT] + encode(s)])\n", " r = run(ids, resid=True)\n", " toks = [tok_str(i) for i in ids[0].tolist()]\n", " final_top1 = r[\"logits\"][0].argmax(-1)\n", " sent = {\"sentence\": s, \"tokens\": toks, \"layers\": []}\n", " for layer in range(L + 1):\n", " lg = lens_logits(r[\"resid\"][layer])[0]\n", " pr = lg.softmax(-1)\n", " top = lg.argmax(-1)\n", " sent[\"layers\"].append([tok_str(int(i)) for i in top])\n", " for t_ in range(ids.shape[1]):\n", " true_next = int(ids[0, t_ + 1]) if t_ + 1 < ids.shape[1] else None\n", " rank = None if true_next is None else int((lg[t_] > lg[t_, true_next]).sum()) + 1\n", " lens_rows.append({\"sentence\": si, \"position\": t_, \"token\": toks[t_], \"layer\": layer, \"where\": PROBE_POINTS[layer],\n", " \"top1\": tok_str(int(top[t_])), \"top1_prob\": round(float(pr[t_, top[t_]]), 4),\n", " \"true_next\": \"\" if true_next is None else tok_str(true_next), \"rank_of_true_next\": \"\" if rank is None else rank,\n", " \"top1_equals_final\": int(top[t_] == final_top1[t_])})\n", " lens_json.append(sent)\n", "save_csv(\"logit-lens-sentences.csv\", list(lens_rows[0]), lens_rows)\n", "save_json(\"logit-lens-sentences.json\", {\"description\": \"top-1 token of the logit lens at every position (row) for the embedding and after each block; sentence strings, tokens ( first), layers[0..4][position]\", \"sentences\": lens_json})\n", "# print the first sentence as a table\n", "sent0 = lens_json[1]\n", "print(\"sentence:\", SENTENCES[1])\n", "print(f\"{'position':>8} {'token':>10} | \" + \" | \".join(f\"{p:>13}\" for p in PROBE_POINTS))\n", "for t_, tk in enumerate(sent0[\"tokens\"]):\n", " print(f\"{t_:>8} {tk!r:>10} | \" + \" | \".join(f\"{sent0['layers'][k][t_]!r:>13}\" for k in range(L + 1)))" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-34" }, { "cell_type": "code", "metadata": {}, "source": [ "agg = {k: dict(loss=0.0, top1_true=0, same_as_final=0, same_as_input=0, rank=0.0, n=0) for k in range(L + 1)}\n", "for xb, yb in zip(batches(WIN_X[EVAL], 32), batches(WIN_Y[EVAL], 32)):\n", " r = run(xb, resid=True)\n", " fin = r[\"logits\"].argmax(-1)\n", " for k in range(L + 1):\n", " lg = lens_logits(r[\"resid\"][k])\n", " a = agg[k]\n", " a[\"loss\"] += F.cross_entropy(lg.reshape(-1, V), yb.reshape(-1), reduction=\"sum\").item()\n", " top = lg.argmax(-1)\n", " a[\"top1_true\"] += int((top == yb).sum()); a[\"same_as_final\"] += int((top == fin).sum()); a[\"same_as_input\"] += int((top == xb).sum())\n", " a[\"rank\"] += float(((lg > lg.gather(-1, yb[..., None])).sum(-1) + 1).float().sum())\n", " a[\"n\"] += yb.numel()\n", "lens_layer_rows = []\n", "print(f\"{'where':>14} {'lens loss':>10} {'top-1 = true next':>18} {'top-1 = final top-1':>20} {'top-1 = input token':>20} {'mean rank of true next':>23}\")\n", "for k in range(L + 1):\n", " a = agg[k]\n", " row = {\"layer\": k, \"where\": PROBE_POINTS[k], \"lens_loss\": round(a[\"loss\"] / a[\"n\"], 4), \"top1_equals_true_next\": round(a[\"top1_true\"] / a[\"n\"], 4),\n", " \"top1_equals_final_top1\": round(a[\"same_as_final\"] / a[\"n\"], 4), \"top1_equals_input_token\": round(a[\"same_as_input\"] / a[\"n\"], 4),\n", " \"mean_rank_of_true_next\": round(a[\"rank\"] / a[\"n\"], 1), \"tokens\": a[\"n\"]}\n", " lens_layer_rows.append(row)\n", " print(f\"{row['where']:>14} {row['lens_loss']:10.3f} {row['top1_equals_true_next']:18.3f} {row['top1_equals_final_top1']:20.3f} {row['top1_equals_input_token']:20.3f} {row['mean_rank_of_true_next']:23.1f}\")\n", "save_csv(\"logit-lens-by-layer.csv\", list(lens_layer_rows[0]), lens_layer_rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-35" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Checkpoint\n", "\n", "Compare with your own run (digits after the first two or three can change with the PyTorch version;\n", "the pattern should not, if you use the reference checkpoint):\n", "\n", "- `run()` reproduces the model (difference below `1e-5`), and the validation loss on the 256\n", " evaluation windows is close to Lab 3.3's 2.07;\n", "- on repeated random tokens the loss on the first copy is above `log V = 9.854`, and the loss on\n", " the second copy is far lower;\n", "- the head table has a few heads whose scores stand out, and the ablation table separates the heads\n", " that matter for the second copy from those that do not;\n", "- the probe's accuracy rises from the embedding to the later layers for at least one property, while the shuffled-label\n", " control stays near 0.5;\n", "- the logit lens at the last point equals the model's output (its loss is the model's loss)." ], "id": "lab-3-4-inside-36" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Explore\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| Repeat length | `HALF = 16, 32, 128` | Does the second-copy loss depend on how far back the earlier copy is? At `HALF = 128` the sequence fills the whole context. |\n", "| Ablation | remove the top 3 or 4 induction heads together; remove a head in layer 0 *and* one in a later layer | Do the effects add up, or does one removal change what the other does? |\n", "| Probe regularisation | `l2 = 0`, `1e-4`, `1`, `100` in `fit_logistic` | How does the test accuracy move, and the shuffled-label *train* accuracy? |\n", "| Probe data | `SAMPLE_FRAC`, `cap_train` smaller | How many examples does a probe need before its accuracy stabilises? |\n", "| New property | label \"the next token is a full stop\", or \"this token is a pronoun\" | Which layer first reads it above the token-only baseline? Which sentence of the text makes it hard? |\n", "| Lens on your own text | add sentences to `SENTENCES`, one with a repeated name | In which layer does the repeated name first appear as the top-1? |" ], "id": "lab-3-4-inside-37" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Failure playground\n", "\n", "Three instruments, three ways to fool yourself. Each cell shows a symptom; the questions are under\n", "it and the answers are not here." ], "id": "lab-3-4-inside-38" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9a · A probe that \"works\" on random labels\n", "\n", "The probe on `after block 4` for \"inside a quote\" is trained on real labels and on random ones, on\n", "100, 200, 500, 1,000, 3,000 and 12,000 examples, with **no weight decay**, and also as a one-hidden-layer\n", "network (128 → 512 → 1) instead of a linear map. We print train and test accuracy for both labellings." ], "id": "lab-3-4-inside-39" }, { "cell_type": "code", "metadata": {}, "source": [ "tr_a, te_a = balanced_split(LQ, seed=11, cap_train=6000)\n", "layer_pg = 4\n", "\n", "\n", "def probe_sizes(labels, shuffle):\n", " rows = []\n", " for n in (100, 200, 500, 1000, 3000, len(tr_a)):\n", " r = np.random.default_rng(n)\n", " half = n // 2\n", " pos = tr_a[labels[tr_a] == 1]; neg = tr_a[labels[tr_a] == 0]\n", " sub = np.concatenate([r.choice(pos, half, replace=False), r.choice(neg, half, replace=False)])\n", " Xtr, Xte = FEATS[layer_pg][sub], FEATS[layer_pg][te_a]\n", " mu, sd = Xtr.mean(0), Xtr.std(0) + 1e-6\n", " Xtr, Xte = (Xtr - mu) / sd, (Xte - mu) / sd\n", " ytr, yte = labels[sub].copy(), labels[te_a].copy()\n", " if shuffle:\n", " r.shuffle(ytr); r.shuffle(yte)\n", " w, b = fit_logistic(Xtr, ytr, l2=0.0, iters=300)\n", " rows.append({\"probe\": \"linear, no weight decay\", \"labels\": \"shuffled\" if shuffle else \"real\", \"n_train\": len(sub),\n", " \"train_acc\": round(acc(w, b, Xtr, ytr), 4), \"test_acc\": round(acc(w, b, Xte, yte), 4)})\n", " return rows\n", "\n", "\n", "def fit_mlp(Xtr, ytr, steps=400, hidden=512, seed=0):\n", " torch.manual_seed(seed)\n", " net = nn.Sequential(nn.Linear(Xtr.shape[1], hidden), nn.ReLU(), nn.Linear(hidden, 1))\n", " opt = torch.optim.Adam(net.parameters(), lr=3e-3)\n", " Xt, yt = torch.from_numpy(Xtr), torch.from_numpy(ytr.astype(np.float32))\n", " with torch.enable_grad():\n", " for _ in range(steps):\n", " opt.zero_grad()\n", " F.binary_cross_entropy_with_logits(net(Xt).squeeze(-1), yt).backward()\n", " opt.step()\n", " return net\n", "\n", "\n", "pg_rows = []\n", "for shuffle in (False, True):\n", " pg_rows += probe_sizes(LQ, shuffle)\n", "Xtr, Xte = FEATS[layer_pg][tr_a], FEATS[layer_pg][te_a]\n", "mu, sd = Xtr.mean(0), Xtr.std(0) + 1e-6\n", "Xtr, Xte = (Xtr - mu) / sd, (Xte - mu) / sd\n", "for shuffle in (False, True):\n", " ytr, yte = LQ[tr_a].copy(), LQ[te_a].copy()\n", " if shuffle:\n", " r = np.random.default_rng(5); r.shuffle(ytr); r.shuffle(yte)\n", " net = fit_mlp(Xtr, ytr)\n", " with torch.no_grad():\n", " a_tr = float(((net(torch.from_numpy(Xtr)).squeeze(-1) > 0).numpy().astype(np.int8) == ytr).mean())\n", " a_te = float(((net(torch.from_numpy(Xte)).squeeze(-1) > 0).numpy().astype(np.int8) == yte).mean())\n", " pg_rows.append({\"probe\": \"MLP 128-512-1, 400 Adam steps\", \"labels\": \"shuffled\" if shuffle else \"real\", \"n_train\": len(tr_a),\n", " \"train_acc\": round(a_tr, 4), \"test_acc\": round(a_te, 4)})\n", "print(f\"{'probe':>30} {'labels':>9} {'n train':>8} {'train acc':>10} {'test acc':>9}\")\n", "for r in pg_rows:\n", " print(f\"{r['probe']:>30} {r['labels']:>9} {r['n_train']:>8} {r['train_acc']:10.3f} {r['test_acc']:9.3f}\")\n", "save_csv(\"failure-probe-random-labels.csv\", [\"probe\", \"labels\", \"n_train\", \"train_acc\", \"test_acc\"], pg_rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-40" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: with 100 or 200 examples the probe reaches an excellent *train* accuracy on random labels.\n", "What is the maximum number of random labels a linear map on 128 numbers can fit exactly, and which\n", "row of the table shows it? Which column would you quote in a paper? What does the **gap between the\n", "real-label and the random-label test accuracy** tell you that neither number alone does? Why does the\n", "bigger probe make the problem worse, and what does that say about \"the layer knows X\" when X is\n", "read by a powerful probe?" ], "id": "lab-3-4-inside-41" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9b · Reading meaning into one head from one example\n", "\n", "One head stands out on the fixed story: the one with the largest name score. Look at *what* it\n", "attends to there, then at the same head on 256 other windows, one at a time." ], "id": "lab-3-4-inside-42" }, { "cell_type": "code", "metadata": {}, "source": [ "l_n, h_n = np.unravel_index(int(np.argmax(HS[\"name\"])), HS[\"name\"].shape)\n", "print(f\"head with the largest name score: L{l_n}H{h_n} (name score {HS['name'][l_n, h_n]:.2f} x uniform over the evaluation windows)\")\n", "A = out[\"att\"][l_n][0, h_n].numpy()\n", "# on the story: for each query token that is a pronoun or a name, which key gets the most weight?\n", "print(\"fixed story, the 8 queries with the most weight on one earlier name token:\")\n", "cand = []\n", "for q in range(1, len(story_toks)):\n", " keys = [k for k in range(q) if int(story_ids[0, k]) in NAME_IDS]\n", " if keys:\n", " cand.append((float(A[q, keys].sum()), q, keys))\n", "for mass, q, keys in sorted(cand, reverse=True)[:8]:\n", " best = int(np.argmax(A[q, :q + 1]))\n", " print(f\" query {story_toks[q]!r:>10} at {q:>3}: {mass:.2f} of its weight on {len(keys)} earlier name token(s); its top key is {story_toks[best]!r} at {best}\")\n", "\n", "# per-window name score of this head, over the 256 evaluation windows\n", "per_win = []\n", "for xb in batches(WIN_X[EVAL], 32):\n", " r = run(xb, att=True)\n", " a = r[\"att\"][l_n][:, h_n] # [B, T, T]\n", " is_name = name_mask_lut[xb]\n", " cum = is_name.cumsum(1)\n", " earlier = (cum - is_name.long()).float()\n", " has = earlier > 0\n", " mass = ((a * is_name[:, None, :].float()).sum(-1) - is_name.float() * a.diagonal(dim1=-2, dim2=-1)) * has\n", " uni = (earlier / (torch.arange(xb.shape[1]).float()[None, :] + 1)) * has\n", " for b in range(xb.shape[0]):\n", " if has[b].sum() >= 10:\n", " per_win.append(float(mass[b].sum() / uni[b].sum()))\n", "per_win = np.array(per_win)\n", "print(f\"per-window name score of L{l_n}H{h_n} ({len(per_win)} windows with at least 10 queries that have an earlier name):\")\n", "print(f\" min {per_win.min():.2f} 10th pct {np.percentile(per_win, 10):.2f} median {np.median(per_win):.2f} 90th pct {np.percentile(per_win, 90):.2f} max {per_win.max():.2f}\")\n", "print(f\" windows where the head gives names LESS than a uniform head would (score < 1): {(per_win < 1).sum()} of {len(per_win)}\")\n", "\n", "# a second story with the same ingredients, where the head's behaviour differs\n", "STORY2 = (\"Ben and Sam were best friends. Ben said, \\\"Let us build a fort.\\\" Sam found a big box in the garden. \"\n", " \"They pushed it under the tree, and Ben climbed inside. Sam laughed and gave him a blanket.\")\n", "ids2 = torch.tensor([[EOT] + encode(STORY2)])\n", "toks2 = [tok_str(i) for i in ids2[0].tolist()]\n", "A2 = run(ids2, att=True)[\"att\"][l_n][0, h_n].numpy()\n", "print(f\"second story, L{l_n}H{h_n}: top key of each query that follows a name:\")\n", "for q in range(1, len(toks2)):\n", " if any(int(ids2[0, k]) in NAME_IDS for k in range(q)) and toks2[q].strip() in (\"he\", \"she\", \"him\", \"his\", \"They\", \"they\", \"Ben\", \"Sam\", \"said\"):\n", " best = int(np.argmax(A2[q, :q + 1]))\n", " print(f\" query {toks2[q]!r:>8} at {q:>3} -> {toks2[best]!r} at {best} ({A2[q, best]:.2f})\")\n", "save_csv(\"failure-one-head-per-window.csv\", [\"window_rank\", \"name_score\"], [{\"window_rank\": i, \"name_score\": round(float(v), 3)} for i, v in enumerate(np.sort(per_win))])" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-43" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: on the fixed story this head looks like \"the head that finds the name\". Does it do that\n", "on every window? How would you decide which of \"it looks at names\", \"it looks at the first\n", "occurrence of anything repeated\", \"it looks at the token two words back\" explains the pattern, using\n", "only data like the table above? What would a fair test of \"this head tracks the subject\" need?" ], "id": "lab-3-4-inside-44" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9c · Attention is not explanation\n", "\n", "Which heads look important in the pictures, and which heads *are* important when removed? Compare\n", "three heads: the one with the **sharpest** pattern (lowest entropy), the one that looked like a name\n", "head in 9b (largest name score), and the one with the **flattest** pattern (highest entropy, close to\n", "a plain average). Then compare the *ranking* of all 16 heads by each pattern score with their ranking\n", "by the damage their removal does." ], "id": "lab-3-4-inside-45" }, { "cell_type": "code", "metadata": {}, "source": [ "l_s, h_s = np.unravel_index(int(np.argmin(HS[\"entropy\"])), HS[\"entropy\"].shape)\n", "l_fl, h_fl = np.unravel_index(int(np.argmax(HS[\"entropy\"])), HS[\"entropy\"].shape)\n", "rows_c = []\n", "print(f\"{'head':>6} {'pattern':>40} | {'val loss, zeroed':>17} {'(delta)':>8} | {'val loss, mean-ablated':>23} {'(delta)':>8}\")\n", "for (l, h), why in (((l_s, h_s), f\"sharpest: entropy {HS['entropy'][l_s, h_s]:.2f}, prev-token {HS['prev'][l_s, h_s]:.2f}\"),\n", " ((l_n, h_n), f\"largest name score {HS['name'][l_n, h_n]:.2f}x\"),\n", " ((l_fl, h_fl), f\"flattest: entropy {HS['entropy'][l_fl, h_fl]:.2f}\")):\n", " z, m = tab[(f\"L{l}H{h}\", \"zero\")], tab[(f\"L{l}H{h}\", \"mean\")]\n", " print(f\"L{l}H{h} {why:>40} | {z['val_loss']:17.4f} {z['val_loss'] - base['val_loss']:+8.4f} | {m['val_loss']:23.4f} {m['val_loss'] - base['val_loss']:+8.4f}\")\n", " rows_c.append({\"head\": f\"L{l}H{h}\", \"pattern\": why, \"val_loss_zero\": z[\"val_loss\"], \"val_delta_zero\": round(z[\"val_loss\"] - base[\"val_loss\"], 4),\n", " \"val_loss_mean\": m[\"val_loss\"], \"val_delta_mean\": round(m[\"val_loss\"] - base[\"val_loss\"], 4)})\n", "print(f\"baseline: validation loss {base['val_loss']:.4f} (standard error of a 256-window mean: about 0.02)\")\n", "save_csv(\"failure-attention-vs-ablation.csv\", list(rows_c[0]), rows_c)\n", "\n", "\n", "def ranks(v):\n", " o = np.argsort(-np.asarray(v)); r = np.empty(len(v), dtype=int); r[o] = np.arange(len(v)); return r\n", "\n", "\n", "def spearman(a, b):\n", " ra, rb = ranks(a).astype(float), ranks(b).astype(float)\n", " return float(np.corrcoef(ra, rb)[0, 1])\n", "\n", "\n", "delta = [r[\"val_delta_zero\"] for r in head_rows]\n", "print(\"\\nrank correlation (Spearman) between a pattern score and the loss increase when the head is zeroed, 16 heads:\")\n", "for key in (\"prev_score\", \"story_start_score\", \"name_x_uniform\", \"induction_score\"):\n", " print(f\" {key:>16}: {spearman([r[key] for r in head_rows], delta):+.2f}\")\n", "print(\" entropy (sharper = more striking): \" + f\"{spearman([-r['entropy_ratio'] for r in head_rows], delta):+.2f}\")\n", "print(\"\\nheads by damage when zeroed (validation loss increase):\")\n", "for r in sorted(head_rows, key=lambda r: -r[\"val_delta_zero\"])[:16]:\n", " print(f\" L{r['layer']}H{r['head']}: {r['val_delta_zero']:+.4f} (mean-ablation {r['val_delta_mean']:+.4f}) prev {r['prev_score']:.2f} first {r['first_score']:.2f} name {r['name_x_uniform']:.1f} entropy {r['entropy_ratio']:.2f}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-46" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: read the three rows and the rank correlations. Does the pattern that looks most striking\n", "predict the damage? Which head hurts the loss most, and what does its pattern look like? Which of the\n", "two kinds of ablation (zero, mean) would you trust, and where do they disagree? What does the table\n", "say about using \"where a head looks\" to decide which heads a smaller model can drop? What would you\n", "measure instead, and what does a loss increase still *not* tell you about what the head computes?" ], "id": "lab-3-4-inside-47" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10 · Versions tested" ], "id": "lab-3-4-inside-48" }, { "cell_type": "code", "metadata": {}, "source": [ "print(f\"Python {platform.python_version()} | PyTorch {torch.__version__} | tiktoken {tiktoken.__version__} | numpy {np.__version__} | matplotlib {matplotlib.__version__}\")\n", "print(f\"machine {platform.system()} {platform.machine()} | device cpu | checkpoint {CKPT} (step {ck['step']}) | whole notebook {time.time() - T0:.0f} s\")" ], "execution_count": null, "outputs": [], "id": "lab-3-4-inside-49" } ] }