{ "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 2.2 · Embeddings\n", "\n", "**Goal:** see that an embedding table is just a weight matrix whose rows get trained; train a\n", "tiny next-token model on TinyStories and watch meaning appear in the rows; measure how big the\n", "vectors must be; project them to 2-D with PCA; and break the pipeline three ways.\n", "\n", "**Runs on:** any laptop, CPU only (about 9 minutes on an Apple M1); also Kaggle or Colab.\n", "Install locally with `uv run --with torch --with tiktoken --with matplotlib jupyter lab`.\n", "The notebook downloads a 4 MB slice of TinyStories itself (needs internet once).\n", "\n", "**Versions tested:** printed by the last cell.\n", "\n", "The data: the first 4 MB of the TinyStories *validation* split (Eldan and Li, 2023; licence\n", "CDLA-Sharing-1.0), cut into tokens with the GPT-2 tokenizer from Ch 2.1. The model reads\n", "`k` tokens and must predict the next one. Nothing else tells it what a word means." ], "id": "lab-2-2-embeddings-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import math\n", "import pathlib\n", "import platform\n", "import time\n", "import urllib.request\n", "\n", "import tiktoken\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "torch.set_num_threads(max(1, min(8, torch.get_num_threads())))\n", "print(\"PyTorch\", torch.__version__, \"| tiktoken\", tiktoken.__version__)\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-2-2-embeddings\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def cache_dir():\n", " d = pathlib.Path(\".work\") if pathlib.Path(\".work\").is_dir() or pathlib.Path(\"data\").is_dir() else pathlib.Path(\".\")\n", " d.mkdir(exist_ok=True)\n", " return d\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)" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your answers before running anything.\n", "\n", "1. Four words are one-hot vectors of length 4. What is the Euclidean distance between *any* two\n", " of them, and what is the cosine similarity between any two? Does one-hot know that \"cat\" is\n", " closer to \"dog\" than to \"car\"?\n", "2. An embedding table for a vocabulary of `V` tokens with `d` numbers per token has how many\n", " weights? How many for GPT-2 small (`V = 50,257`, `d = 768`)?\n", "3. A model that has learned nothing and spreads probability evenly over `V` tokens has loss\n", " `log V` (Ch 2.3). In training, one batch contains only a few hundred distinct tokens. How\n", " many rows of the table do you expect to change after one gradient step?\n", "4. If every token's embedding were frozen at random numbers, would the loss stall at `log V`,\n", " fall to the same value as with trained embeddings, or land in between?" ], "id": "lab-2-2-embeddings-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Build: a lookup is a matrix product\n", "\n", "A one-hot vector has a single `1`. Multiplying it by a matrix selects one row of the matrix.\n", "Here with 4 words and `d = 3`." ], "id": "lab-2-2-embeddings-03" }, { "cell_type": "code", "metadata": {}, "source": [ "words = [\"cat\", \"dog\", \"car\", \"sun\"]\n", "torch.manual_seed(0)\n", "E4 = torch.randn(4, 3) # the embedding table, shape [V, d] = [4, 3]\n", "onehot = torch.eye(4) # row i is the one-hot vector of word i\n", "\n", "print(\"one-hot distances between all pairs (Euclidean):\")\n", "for i in range(4):\n", " print(\" \", [round(float(torch.dist(onehot[i], onehot[j])), 4) for j in range(4)])\n", "print(\"one-hot cosine similarity of cat and dog:\", float(F.cosine_similarity(onehot[0], onehot[1], dim=0)))\n", "\n", "idx = 1 # \"dog\"\n", "by_matmul = onehot[idx] @ E4 # [4] @ [4, 3] -> [3]\n", "by_lookup = E4[idx] # take row 1\n", "print(\"\\nrow lookup :\", [round(float(v), 4) for v in by_lookup])\n", "print(\"one-hot @ E :\", [round(float(v), 4) for v in by_matmul])\n", "print(\"max abs difference:\", float((by_matmul - by_lookup).abs().max()))\n", "print(\"nn.Embedding gives the same:\", torch.equal(nn.Embedding.from_pretrained(E4)(torch.tensor(idx)), by_lookup))" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Similarity: dot product and cosine\n", "\n", "The **dot product** `a · b` multiplies matching entries and adds. The **cosine similarity**\n", "divides it by both lengths, so it measures only the angle between the vectors:\n", "`cos(a, b) = a · b / (|a| |b|)`. It is `+1` for the same direction, `0` for a right angle,\n", "`-1` for opposite directions." ], "id": "lab-2-2-embeddings-05" }, { "cell_type": "code", "metadata": {}, "source": [ "a = torch.tensor([3.0, 4.0])\n", "b = torch.tensor([6.0, 8.0]) # same direction as a, twice as long\n", "c = torch.tensor([4.0, -3.0]) # at a right angle to a\n", "for name, v in ((\"b\", b), (\"c\", c)):\n", " dot = float(a @ v)\n", " cos = dot / (float(a.norm()) * float(v.norm()))\n", " print(f\"a={a.tolist()} {name}={v.tolist()} dot={dot:6.1f} |a|={float(a.norm()):.1f} |{name}|={float(v.norm()):.1f} cosine={cos:+.3f}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · The data: TinyStories as GPT-2 tokens\n", "\n", "We download the first 4 MB of the validation file, drop the last (cut) story, split stories\n", "90 / 10 into train and validation, and cut everything into GPT-2 tokens. A token that has a\n", "space in front of it (`\" girl\"`) is a different token from the one without (`\"girl\"`): Ch 2.1.\n", "The GPT-2 vocabulary has 50,257 entries, but this slice only uses a few thousand, so we\n", "renumber the tokens that occur to `0 … V-1` and keep a table back to the GPT-2 text." ], "id": "lab-2-2-embeddings-07" }, { "cell_type": "code", "metadata": {}, "source": [ "URL = \"https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories-valid.txt\"\n", "RAW = cache_dir() / \"tinystories-valid-head-4mb.txt\"\n", "if not RAW.exists():\n", " req = urllib.request.Request(URL, headers={\"Range\": \"bytes=0-3999999\"})\n", " with urllib.request.urlopen(req, timeout=120) 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] # last one is cut off\n", "print(f\"{len(stories)} stories, {len(text.encode()):,} bytes downloaded\")\n", "print(\"first story starts:\", repr(stories[0][:120]))\n", "\n", "enc = tiktoken.get_encoding(\"gpt2\")\n", "EOT = enc.eot_token # 50256\n", "cut = int(len(stories) * 0.9)\n", "\n", "\n", "def to_ids(story_list):\n", " ids = []\n", " for s in story_list:\n", " ids += enc.encode(s) + [EOT]\n", " return ids\n", "\n", "\n", "raw_train, raw_val = to_ids(stories[:cut]), to_ids(stories[cut:])\n", "used = sorted(set(raw_train) | set(raw_val))\n", "gpt2_to_new = {t: i for i, t in enumerate(used)}\n", "V = len(used)\n", "train_ids = torch.tensor([gpt2_to_new[t] for t in raw_train])\n", "val_ids = torch.tensor([gpt2_to_new[t] for t in raw_val])\n", "\n", "\n", "def piece(i): # text of a renumbered token\n", " t = used[i]\n", " return \"\" if t == EOT else enc.decode([t])\n", "\n", "\n", "counts = torch.bincount(train_ids, minlength=V)\n", "print(f\"train tokens {len(train_ids):,} val tokens {len(val_ids):,} vocabulary used V = {V:,} (of 50,257)\")\n", "print(f\"log V = {math.log(V):.4f}\")\n", "print(\"most frequent tokens:\", [(piece(i), int(counts[i])) for i in counts.argsort(descending=True)[:8].tolist()])\n", "print(\"GPT-2 small embedding table: 50,257 x 768 =\", f\"{50257 * 768:,}\", \"weights\")\n", "\n", "# Reference losses: what a model with NO context can do (predict by frequency)\n", "p_uni = (counts + 1.0) / (counts + 1.0).sum()\n", "uni_val = float(-p_uni[val_ids].log().mean())\n", "print(f\"unigram (no context) validation loss: {uni_val:.4f}\")\n", "\n", "\n", "def windows(ids, k):\n", " x = torch.stack([ids[i : len(ids) - k + i] for i in range(k)], dim=1) # [N, k] previous tokens\n", " y = ids[k:] # [N] the next token\n", " return x, y" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · The model: an embedding table plus a small MLP\n", "\n", "Shapes for one batch with `B = 512`, `k = 3`, `d = 32`, `H = 128`:\n", "\n", "`ids [B, k]` → embedding rows `[B, k, d]` → flatten `[B, k·d]` → `Linear` + `tanh` `[B, H]` → `Linear` `[B, V]` logits.\n", "\n", "The table `nn.Embedding(V, d)` is initialised with small random numbers (standard deviation 0.1)\n", "and trained by the same gradient descent as every other weight. Nobody tells it what a word means." ], "id": "lab-2-2-embeddings-09" }, { "cell_type": "code", "metadata": {}, "source": [ "class TinyLM(nn.Module):\n", " def __init__(self, V, d, k, H):\n", " super().__init__()\n", " self.k, self.d = k, d\n", " self.emb = nn.Embedding(V, d)\n", " nn.init.normal_(self.emb.weight, std=0.1) # small random start (the default is std 1)\n", " self.fc1 = nn.Linear(k * d, H)\n", " self.fc2 = nn.Linear(H, V)\n", "\n", " def forward(self, x): # x: [B, k] token ids\n", " e = self.emb(x) # [B, k, d]\n", " h = torch.tanh(self.fc1(e.flatten(1))) # [B, H]\n", " return self.fc2(h) # [B, V]\n", "\n", "\n", "@torch.no_grad()\n", "def eval_loss(model, x, y, limit=10000):\n", " return float(F.cross_entropy(model(x[:limit]), y[:limit]))\n", "\n", "\n", "def train(d=32, k=3, H=128, steps=2000, lr=3e-3, batch=512, seed=0, freeze_emb=False,\n", " tag=\"run\", log_every=100, quiet=False):\n", " torch.manual_seed(seed)\n", " model = TinyLM(V, d, k, H)\n", " xt, yt = windows(train_ids, k)\n", " xv, yv = windows(val_ids, k)\n", " params = [p for n, p in model.named_parameters() if not (freeze_emb and n.startswith(\"emb\"))]\n", " opt = torch.optim.Adam(params, lr=lr)\n", " g = torch.Generator().manual_seed(seed)\n", " rows, running, t0 = [], [], time.time()\n", " for step in range(steps + 1):\n", " if step % log_every == 0:\n", " tr = sum(running) / len(running) if running else float(\"nan\")\n", " rows.append({\"run\": tag, \"step\": step, \"train_loss\": tr, \"val_loss\": eval_loss(model, xv, yv)})\n", " running = []\n", " if not quiet and step % (log_every * 10) == 0:\n", " print(f\"[{tag}] step {step:5d} train {tr:7.4f} val {rows[-1]['val_loss']:.4f} ({time.time() - t0:4.0f}s)\")\n", " if step == steps:\n", " break\n", " i = torch.randint(0, len(xt), (batch,), generator=g)\n", " loss = F.cross_entropy(model(xt[i]), yt[i])\n", " running.append(loss.item())\n", " opt.zero_grad()\n", " loss.backward()\n", " opt.step()\n", " return model, rows" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Which rows does one gradient step touch?\n", "\n", "Before training for real, take **one** step of plain SGD on one batch and count how many rows of\n", "the table changed. (We use SGD here because Adam also moves weights that got a zero gradient,\n", "through its running averages.)" ], "id": "lab-2-2-embeddings-11" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(0)\n", "probe = TinyLM(V, 32, 3, 128)\n", "before = probe.emb.weight.detach().clone()\n", "xt3, yt3 = windows(train_ids, 3)\n", "gen = torch.Generator().manual_seed(0)\n", "bi = torch.randint(0, len(xt3), (512,), generator=gen)\n", "loss0 = F.cross_entropy(probe(xt3[bi]), yt3[bi])\n", "print(f\"step-zero loss {loss0.item():.4f} (log V = {math.log(V):.4f})\")\n", "loss0.backward()\n", "torch.optim.SGD(probe.parameters(), lr=0.1).step()\n", "changed = (probe.emb.weight.detach() != before).any(dim=1)\n", "distinct_in_batch = len(set(xt3[bi].flatten().tolist()))\n", "print(f\"distinct input tokens in the batch: {distinct_in_batch}\")\n", "print(f\"rows of the table that changed: {int(changed.sum())} of {V}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Train, then look at the neighbours\n", "\n", "`nearest(model, word)` ranks every token (that occurs at least 20 times in the training text)\n", "by **cosine similarity** to the word's row and returns the top 5. First on the random table,\n", "then after training." ], "id": "lab-2-2-embeddings-13" }, { "cell_type": "code", "metadata": {}, "source": [ "def tok_id(word):\n", " t = enc.encode(word)\n", " return gpt2_to_new[t[0]] if len(t) == 1 and t[0] in gpt2_to_new else None\n", "\n", "\n", "@torch.no_grad()\n", "def nearest_ids(model, word, n=5, by=\"cosine\", min_count=20):\n", " i = tok_id(word)\n", " E = model.emb.weight\n", " q = E[i]\n", " if by == \"cosine\":\n", " score = F.normalize(E, dim=1) @ F.normalize(q, dim=0)\n", " else:\n", " score = E @ q # raw dot product\n", " score = score.clone()\n", " score[i] = -1e9 # not itself\n", " score[counts < min_count] = -1e9 # too rare to judge\n", " return score.topk(n).indices.tolist()\n", "\n", "\n", "def nearest(model, word, n=5, by=\"cosine\", min_count=20):\n", " return [piece(j).strip() for j in nearest_ids(model, word, n, by, min_count)]\n", "\n", "\n", "QUERY = [\" girl\", \" boy\", \" dog\", \" cat\", \" mom\", \" happy\", \" sad\", \" play\", \" big\", \" day\", \" Lily\", \" Tim\"]\n", "QUERY = [w for w in QUERY if tok_id(w) is not None and counts[tok_id(w)] >= 20]\n", "print(\"query words kept:\", [w.strip() for w in QUERY])\n", "\n", "torch.manual_seed(0)\n", "untrained = TinyLM(V, 32, 3, 128)\n", "print(\"\\nBEFORE training (random table):\")\n", "before_rows = []\n", "for w in QUERY:\n", " nb = nearest(untrained, w)\n", " before_rows.append({\"word\": w.strip(), \"stage\": \"before\", \"neighbours\": \" \".join(nb)})\n", " print(f\" {w.strip():>6} -> {nb}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-14" }, { "cell_type": "code", "metadata": {}, "source": [ "t_start = time.time()\n", "model, curve_main = train(d=32, k=3, H=128, steps=2000, tag=\"learned_d32\")\n", "print(f\"trained in {time.time() - t_start:.0f} s\")\n", "\n", "print(\"\\nAFTER training:\")\n", "after_rows = []\n", "for w in QUERY:\n", " nb = nearest(model, w)\n", " after_rows.append({\"word\": w.strip(), \"stage\": \"after\", \"neighbours\": \" \".join(nb)})\n", " print(f\" {w.strip():>6} -> {nb}\")\n", "save_csv(\"neighbours.csv\", [\"word\", \"stage\", \"neighbours\"], before_rows + after_rows)" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Measure: the loss curve and the reference lines\n", "\n", "Three horizontal reference lines for the curve: `log V` (know nothing), the **unigram** loss\n", "(know only how common each token is) and the model itself." ], "id": "lab-2-2-embeddings-16" }, { "cell_type": "code", "metadata": {}, "source": [ "final_train = curve_main[-1][\"train_loss\"]\n", "final_val = curve_main[-1][\"val_loss\"]\n", "print(f\"log V : {math.log(V):.4f}\")\n", "print(f\"unigram validation : {uni_val:.4f}\")\n", "print(f\"model step 0 (val) : {curve_main[0]['val_loss']:.4f}\")\n", "print(f\"model step 2000 train : {final_train:.4f}\")\n", "print(f\"model step 2000 val : {final_val:.4f} (perplexity {math.exp(final_val):.1f})\")" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Visualise: PCA in 2-D\n", "\n", "32 numbers per token cannot be drawn. **PCA** (principal component analysis) finds the\n", "directions along which the vectors vary most. Centre the vectors (subtract the mean), run the\n", "singular value decomposition `Xc = U S Vᵀ`; the rows of `Vᵀ` are the directions, sorted by\n", "importance, and `S²` says how much of the total variation each one carries. Projecting onto\n", "the first two rows gives a 2-D picture that keeps as much of the spread as two numbers can.\n", "`torch.linalg.svd` is all we need." ], "id": "lab-2-2-embeddings-18" }, { "cell_type": "code", "metadata": {}, "source": [ "def pca2(X):\n", " Xc = X - X.mean(dim=0)\n", " U, S, Vh = torch.linalg.svd(Xc, full_matrices=False)\n", " share = (S ** 2) / (S ** 2).sum()\n", " return Xc @ Vh[:2].T, share\n", "\n", "\n", "top = counts.argsort(descending=True)[:200].tolist()\n", "with torch.no_grad():\n", " coords, share = pca2(model.emb.weight[top])\n", " coords0, share0 = pca2(untrained.emb.weight[top])\n", "print(f\"learned table: PC1 carries {100 * float(share[0]):.1f} % of the variation, PC2 {100 * float(share[1]):.1f} %, together {100 * float(share[:2].sum()):.1f} %\")\n", "print(f\"random table : PC1 {100 * float(share0[0]):.1f} %, PC2 {100 * float(share0[1]):.1f} %, together {100 * float(share0[:2].sum()):.1f} %\")\n", "\n", "pca_rows = [\n", " {\"token\": piece(t).replace(\"\\n\", \"\\\\n\"), \"count\": int(counts[t]),\n", " \"pc1\": float(coords[r, 0]), \"pc2\": float(coords[r, 1]),\n", " \"norm\": float(model.emb.weight[t].detach().norm())}\n", " for r, t in enumerate(top)\n", "]\n", "save_csv(\"pca-learned.csv\", [\"token\", \"count\", \"pc1\", \"pc2\", \"norm\"], pca_rows)\n", "\n", "pc1s, pc2s = coords[:, 0], coords[:, 1]\n", "print(f\"all 200 tokens: PC1 spans {float(pc1s.min()):+.2f} … {float(pc1s.max()):+.2f}, PC2 spans {float(pc2s.min()):+.2f} … {float(pc2s.max()):+.2f}\")\n", "name_rows = [r for r in pca_rows if r[\"token\"].strip() in (\"Lily\", \"Tim\", \"Tom\", \"Ben\", \"Max\", \"Jack\", \"Sam\") and r[\"token\"].startswith(\" \")]\n", "print(\"boy/girl names among them:\", [(r[\"token\"].strip(), round(r[\"pc1\"], 2), round(r[\"pc2\"], 2)) for r in name_rows])\n", "print(f\"names span PC1 {min(r['pc1'] for r in name_rows):+.2f} … {max(r['pc1'] for r in name_rows):+.2f}, PC2 {min(r['pc2'] for r in name_rows):+.2f} … {max(r['pc2'] for r in name_rows):+.2f}\")\n", "\n", "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, ax = plt.subplots(figsize=(8, 6))\n", " ax.scatter(coords[:, 0], coords[:, 1], s=8, color=\"gray\")\n", " for r, t in enumerate(top[:80]):\n", " ax.annotate(piece(t).strip() or \"·\", (float(coords[r, 0]), float(coords[r, 1])), fontsize=7)\n", " ax.set_title(\"200 most frequent tokens, learned embeddings, PCA\")\n", " plt.tight_layout(); plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot (pip install matplotlib)\")" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Analogies: the famous trick, tested honestly\n", "\n", "Word2vec made `king − man + woman ≈ queen` famous. The test: take `vec(b) − vec(a) + vec(c)`\n", "and look for the nearest token (excluding `a`, `b`, `c`). Below, a few pairs that *should*\n", "work in children's stories. Count how many do." ], "id": "lab-2-2-embeddings-20" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def analogy(model, a, b, c, n=3, min_count=20):\n", " E = F.normalize(model.emb.weight, dim=1)\n", " ia, ib, ic = tok_id(a), tok_id(b), tok_id(c)\n", " q = F.normalize(E[ib] - E[ia] + E[ic], dim=0)\n", " score = E @ q\n", " for i in (ia, ib, ic):\n", " score[i] = -1e9\n", " score[counts < min_count] = -1e9\n", " return [piece(j).strip() for j in score.topk(n).indices.tolist()]\n", "\n", "\n", "TESTS = [ # a is to b as c is to ?\n", " (\" he\", \" she\", \" boy\", \"girl\"), (\" he\", \" she\", \" dad\", \"mom\"), (\" his\", \" her\", \" he\", \"she\"),\n", " (\" big\", \" small\", \" tall\", \"short\"), (\" sad\", \" happy\", \" cried\", \"laughed\"),\n", " (\" dog\", \" dogs\", \" cat\", \"cats\"), (\" boy\", \" boys\", \" girl\", \"girls\"), (\" is\", \" was\", \" are\", \"were\"),\n", "]\n", "hits = 0\n", "analogy_rows = []\n", "for a, b, c, want in TESTS:\n", " if None in (tok_id(a), tok_id(b), tok_id(c)):\n", " continue\n", " got = analogy(model, a, b, c)\n", " ok = want in got[:1]\n", " hits += ok\n", " analogy_rows.append({\"a\": a.strip(), \"b\": b.strip(), \"c\": c.strip(), \"expected\": want, \"top3\": \" \".join(got), \"top1_correct\": int(ok)})\n", " print(f\"{a.strip():>6} : {b.strip():<6} = {c.strip():>6} : ? expected {want:<8} got {got} {'OK' if ok else 'miss'}\")\n", "print(f\"top-1 correct: {hits} of {len(analogy_rows)}\")\n", "save_csv(\"analogies.csv\", [\"a\", \"b\", \"c\", \"expected\", \"top3\", \"top1_correct\"], analogy_rows)" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10 · Measure: how large must `d` be?\n", "\n", "The same model and the same 2000 steps with `d = 1, 2, 4, 8, 16, 32, 64`. Each run takes\n", "a bit under a minute, so this cell is the slow one." ], "id": "lab-2-2-embeddings-22" }, { "cell_type": "code", "metadata": {}, "source": [ "d_rows, curves, d_models = [], list(curve_main), {}\n", "for d in (1, 2, 4, 8, 16, 32, 64):\n", " if d == 32:\n", " m, cv = model, curve_main # the run we already have\n", " else:\n", " m, cv = train(d=d, k=3, H=128, steps=2000, tag=f\"d{d}\", quiet=True)\n", " curves += cv\n", " d_models[d] = m\n", " d_rows.append({\"d\": d, \"table_params\": V * d, \"train_loss\": cv[-1][\"train_loss\"], \"val_loss\": cv[-1][\"val_loss\"]})\n", " print(f\"d={d:3d} table weights={V * d:8,d} train {cv[-1]['train_loss']:.4f} val {cv[-1]['val_loss']:.4f}\")\n", "save_csv(\"d-sweep.csv\", [\"d\", \"table_params\", \"train_loss\", \"val_loss\"], d_rows)" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 11 · Measure: how many previous tokens?\n", "\n", "Same model, `d = 32`, `k = 1, 2, 3, 4` previous tokens." ], "id": "lab-2-2-embeddings-24" }, { "cell_type": "code", "metadata": {}, "source": [ "k_rows = []\n", "for k in (1, 2, 3, 4):\n", " if k == 3:\n", " cv = curve_main\n", " else:\n", " _, cv = train(d=32, k=k, H=128, steps=2000, tag=f\"k{k}\", quiet=True)\n", " k_rows.append({\"k\": k, \"train_loss\": cv[-1][\"train_loss\"], \"val_loss\": cv[-1][\"val_loss\"]})\n", " print(f\"k={k} train {cv[-1]['train_loss']:.4f} val {cv[-1]['val_loss']:.4f}\")\n", "save_csv(\"context-sweep.csv\", [\"k\", \"train_loss\", \"val_loss\"], k_rows)" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 12 · Checkpoint\n", "\n", "Compare your outputs with the book's reference run (the last digits can differ across\n", "PyTorch versions and hardware; everything is seeded):\n", "\n", "- section 2: every off-diagonal one-hot distance is `1.4142`, cosine `0.0`, and `one-hot @ E`\n", " equals the row lookup with maximum difference `0.0`;\n", "- section 3: `b` has cosine `+1.000`, `c` has cosine `+0.000`;\n", "- section 4: `V = 8,343`, `865,078` train tokens, `log V = 9.0292`, unigram validation loss `5.9310`;\n", "- section 5: step-zero loss `9.0241`, and one SGD step changes `539` of `8343` rows (the `539`\n", " distinct tokens in the batch);\n", "- section 6: before training, the neighbours of `dog` are unrelated (`dough, dish, …`); after,\n", " `['cat', 'puppy', 'Max', 'turtle', 'by']`; for `mom`: `['mum', 'mother', 'dad', 'Jane', 'judge']`;\n", "- section 7: validation loss `3.7812` after 2,000 steps (train `3.4193`), far below the unigram line;\n", "- section 8: the first two PCA directions carry `16.8 %` of the variation (random table: `11.1 %`);\n", "- section 9: `4 of 8` analogies right at rank 1;\n", "- section 10, validation loss by `d = 1, 2, 4, 8, 16, 32, 64`:\n", " `4.9386, 4.5653, 4.2795, 4.0220, 3.8684, 3.7812, 3.7311`;\n", "- section 11, by `k = 1, 2, 3, 4`: `4.0897, 3.8398, 3.7812, 3.7786`;\n", "- 14a: frozen random table, validation `4.6270`; 14b: `d = 1`, validation `4.9386`;\n", " 14c: closing-quote tokens in the top five for `5 of 12` words by dot product, `0 of 12` by cosine,\n", " length-versus-log-count correlation `+0.365`." ], "id": "lab-2-2-embeddings-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 13 · Explore\n", "\n", "Change one knob at a time and answer the question next to it.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| embedding size `d` | `d = 8`, `128` in `train(d=…)` | Where does the validation loss stop improving, and does the *train* loss keep falling? What does a growing gap between them mean? |\n", "| context length `k` | `k = 1` vs `k = 4` | What does an extra token of context buy, and what does it cost in table or layer size? |\n", "| learning rate | `lr = 3e-4`, `3e-2` | Which one still beats the unigram line after 2000 steps? Plot `train_loss` for each. |\n", "| hidden width `H` | `H = 16`, `512` | Does a wider hidden layer change *which words are neighbours*, or only the loss? |\n", "| training length | `steps = 200`, `8000` | At which step do the neighbours of `\" girl\"` first look sensible? |" ], "id": "lab-2-2-embeddings-27" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here, for example:\n", "# m, cv = train(d=64, k=3, H=128, steps=2000, tag=\"mine\")\n", "# print(nearest(m, \" girl\"))" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-28" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 14 · Failure playground\n", "\n", "Three things below are broken in ways real embedding pipelines break. For each: run it, read the\n", "symptom, find the cause, fix it. Hints are in Review 2.2; answers are not." ], "id": "lab-2-2-embeddings-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 14a · The embedding that never learns\n", "\n", "A colleague builds the optimiser from \"the layers that matter\" and leaves the embedding table\n", "out of it, so it stays at its random start." ], "id": "lab-2-2-embeddings-30" }, { "cell_type": "code", "metadata": {}, "source": [ "frozen, curve_frozen = train(d=32, k=3, H=128, steps=2000, freeze_emb=True, tag=\"frozen_random\", quiet=True)\n", "curves += curve_frozen\n", "print(f\"frozen random table: train {curve_frozen[-1]['train_loss']:.4f} val {curve_frozen[-1]['val_loss']:.4f}\")\n", "print(f\"learned table : train {curve_main[-1]['train_loss']:.4f} val {curve_main[-1]['val_loss']:.4f}\")\n", "print(f\"(unigram {uni_val:.4f}, log V {math.log(V):.4f})\")\n", "print(\"neighbours of ' girl' with the frozen table:\", nearest(frozen, \" girl\"))" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-31" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: no error, the loss does fall, but it ends well above the learned table's loss and the\n", "neighbours are unrelated. Compare the three curves in `loss-curves.csv`. Why can the layers\n", "above the table still learn *something*, and what exactly can they not do? Which one line of\n", "`train()` makes the bug, and what is the fix?" ], "id": "lab-2-2-embeddings-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 14b · Too few numbers per token\n", "\n", "A colleague shrinks the table to save memory: `d = 1`." ], "id": "lab-2-2-embeddings-33" }, { "cell_type": "code", "metadata": {}, "source": [ "print(f\"d = 1 : val {d_rows[0]['val_loss']:.4f} d = 2 : val {d_rows[1]['val_loss']:.4f} d = 32 : val {final_val:.4f}\")\n", "m1 = [r for r in curves if r[\"run\"] == \"d1\"]\n", "print(f\"d = 1 : loss at step 500 / 1000 / 2000: {[round(r['val_loss'], 3) for r in m1 if r['step'] in (500, 1000, 2000)]}\")\n", "print(\"neighbours of ' girl' with d = 1:\", nearest(d_models[1], \" girl\"))" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-34" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: it trains, nothing crashes, but the validation loss plateaus above the `d = 32` run. With\n", "one number per token, what is the only thing that can separate two tokens? How many *kinds* of\n", "similarity can a single line express, and why does the MLP above it not fix that? Is the gap\n", "closed by `d = 2`? By `d = 8`? Use `d-sweep.csv`." ], "id": "lab-2-2-embeddings-35" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 14c · Dot product instead of cosine\n", "\n", "A colleague ranks neighbours by the raw dot product, because \"it is faster\"." ], "id": "lab-2-2-embeddings-36" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"cosine vs raw dot product, top 5 neighbours of each word:\")\n", "for w in QUERY[:6]:\n", " print(f\" {w.strip():>6} cosine {nearest(model, w)} dot {nearest(model, w, by='dot')}\")\n", "\n", "norms = model.emb.weight.detach().norm(dim=1)\n", "seen = counts >= 20\n", "order = counts.argsort(descending=True)\n", "rank = torch.empty(V)\n", "rank[order] = torch.arange(V, dtype=torch.float)\n", "\n", "\n", "def mean_count_rank(by):\n", " r = [float(rank[j]) for w in QUERY for j in nearest_ids(model, w, by=by, n=5)]\n", " return sum(r) / len(r)\n", "\n", "\n", "corr = float(torch.corrcoef(torch.stack([norms[seen], counts[seen].float().log()]))[0, 1])\n", "QUOTE = {',\"', '?\"', '!\"', '.\"'}\n", "for by in (\"cosine\", \"dot\"):\n", " n_q = sum(any(x in QUOTE for x in nearest(model, w, by=by)) for w in QUERY)\n", " print(f\"query words whose top-5 contains a closing-quote token (,\\\" ?\\\" !\\\" .\\\"): {by:6s} {n_q} of {len(QUERY)}\")\n", "print(f\"correlation between vector length and log(count), tokens seen >= 20 times: {corr:+.3f}\")\n", "print(f\"mean frequency rank of the 5 neighbours (0 = most frequent): cosine {mean_count_rank('cosine'):.0f} dot {mean_count_rank('dot'):.0f}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-37" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the dot-product neighbours of different words look alike, and the same punctuation\n", "tokens keep turning up. Why does the raw dot product reward long vectors (and vectors that point\n", "along a direction many contexts share), and what does the cosine remove? What does the\n", "correlation above say about what training did to the vector *lengths*?" ], "id": "lab-2-2-embeddings-38" }, { "cell_type": "code", "metadata": {}, "source": [ "save_csv(\"loss-curves.csv\", [\"run\", \"step\", \"train_loss\", \"val_loss\"], curves)" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-39" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\n", " \"Versions tested:\",\n", " f\"Python {platform.python_version()},\",\n", " f\"PyTorch {torch.__version__},\",\n", " f\"tiktoken {tiktoken.__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()} (cpu)\")" ], "execution_count": null, "outputs": [], "id": "lab-2-2-embeddings-40" } ] }