{ "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.3 · Softmax, Cross-Entropy and Sampling\n", "\n", "**Goal:** build numerically stable softmax, log-softmax and cross-entropy by hand in PyTorch and\n", "check them against `F.cross_entropy`; verify temperature, top-k, top-p and seeded CDF sampling\n", "on the five-token example; measure repeated 4-grams in 200-token outputs of GPT-2 small; and\n", "break the pipeline three ways (`float16` overflow to `NaN`, silent double softmax stalling near\n", "`9.825`, and greedy repetition loops next to high-temperature word salad).\n", "\n", "**Runs on:** any laptop, CPU only (about 2–3 minutes; faster on a GPU); also Kaggle or Colab.\n", "Run locally with `uv run --with torch --with transformers --with tiktoken --with matplotlib jupyter lab`.\n", "The notebook downloads GPT-2 small (`gpt2`, 124M parameters, ~548 MB) from Hugging Face once and caches it.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-2-3-softmax-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import math\n", "import pathlib\n", "import platform\n", "import time\n", "\n", "import tiktoken\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import transformers\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "torch.set_num_threads(max(1, min(8, torch.get_num_threads())))\n", "print(\n", " \"PyTorch\", torch.__version__,\n", " \"| transformers\", transformers.__version__,\n", " \"| tiktoken\", tiktoken.__version__,\n", ")\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-3-softmax\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def save_csv(name, fieldnames, rows):\n", " path = out_dir() / name\n", " with path.open(\"w\", newline=\"\", encoding=\"utf-8\") 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-3-softmax-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your answers before running anything.\n", "\n", "1. A freshly initialised GPT-2-sized model (`V = 50,257`) outputs logits near zero, giving roughly\n", " `1 / V` probability to every token. What should its step-zero cross-entropy loss (`−log(1/V)`)\n", " and perplexity (`e^loss`) be?\n", "2. If you add `+10` to every logit in `[4.0, 2.5, 2.0, 1.0, −1.0]`, how do the softmax\n", " probabilities change?\n", "3. In `float16`, the largest finite number is `65,504` (`log 65,504 ≈ 11.09`). What will naive\n", " `e^z / sum(e^z)` return on `[12, 14, 11]` in `float16`?\n", "4. Suppose a bug calls `F.softmax` on logits before passing them to `F.cross_entropy` (which\n", " applies `log_softmax` again) with `V = 50,257`. Even if the first softmax puts `1.0` on the\n", " true token and `0.0` on every other token, what is the lowest loss the double softmax can reach?\n", "5. When GPT-2 small generates 200 tokens from the same prompt, will greedy decoding (`T = 0`) or\n", " sampling (`T = 1.0`, or `T = 0.7` with `top-p = 0.9`) produce a higher share of repeated\n", " 4-grams? What do you expect to see at `T = 2.0` with no filter?" ], "id": "lab-2-3-softmax-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Build: stable softmax, log-softmax, and cross-entropy by hand\n", "\n", "First we write naive softmax, max-subtracted softmax, log-softmax (via log-sum-exp), and\n", "cross-entropy by hand, check them on the chapter's five-token example, and compare against\n", "PyTorch's `F.softmax`, `F.log_softmax`, and `F.cross_entropy`." ], "id": "lab-2-3-softmax-03" }, { "cell_type": "code", "metadata": {}, "source": [ "TOKENS = ['\" time\"', '\" day\"', '\" sunny\"', '\" little\"', '\" banana\"']\n", "z5 = torch.tensor([4.0, 2.5, 2.0, 1.0, -1.0], dtype=torch.float64)\n", "\n", "\n", "def softmax_naive(z, dim=-1):\n", " ez = torch.exp(z)\n", " return ez / ez.sum(dim=dim, keepdim=True)\n", "\n", "\n", "def softmax_stable(z, dim=-1):\n", " m = z.max(dim=dim, keepdim=True).values\n", " ez = torch.exp(z - m)\n", " return ez / ez.sum(dim=dim, keepdim=True)\n", "\n", "\n", "def log_softmax_stable(z, dim=-1):\n", " m = z.max(dim=dim, keepdim=True).values\n", " shifted = z - m\n", " return shifted - torch.log(torch.exp(shifted).sum(dim=dim, keepdim=True))\n", "\n", "\n", "def cross_entropy_hand(logits, targets):\n", " \"\"\"Mean negative log-likelihood over [N, V] raw logits and [N] integer targets.\"\"\"\n", " log_p = log_softmax_stable(logits, dim=-1)\n", " rows = torch.arange(logits.shape[0], device=logits.device)\n", " return -log_p[rows, targets].mean()\n", "\n", "\n", "ez5 = torch.exp(z5)\n", "p5 = softmax_stable(z5)\n", "print(\"Five-token example:\")\n", "print(f\"{'Token':12s} {'logit z':>8s} {'e^z':>10s} {'p':>10s} {'loss -log p':>13s} {'ppl e^loss':>11s}\")\n", "for tok, zi, ezi, pi in zip(TOKENS, z5, ez5, p5):\n", " loss_i = -math.log(float(pi))\n", " print(f\"{tok:12s} {float(zi):+8.1f} {float(ezi):10.3f} {float(pi):10.4f} {loss_i:13.3f} {math.exp(loss_i):11.2f}\")\n", "print(f\"sum(e^z) = {float(ez5.sum()):.3f} sum(p) = {float(p5.sum()):.4f}\")\n", "print(f\"ratio p(time)/p(day) = {float(p5[0] / p5[1]):.2f} e^1.5 = {math.exp(1.5):.2f}\")\n", "\n", "# Shift invariance: add +10 to every logit\n", "p5_shifted = softmax_stable(z5 + 10.0)\n", "print(f\"shift invariance max |softmax(z+10) - softmax(z)| = {float((p5_shifted - p5).abs().max()):.2e}\")\n", "\n", "# Two-class softmax == sigmoid\n", "two_class = softmax_stable(torch.tensor([2.0, 0.0], dtype=torch.float64))\n", "sig2 = 1.0 / (1.0 + math.exp(-2.0))\n", "print(f\"softmax([2, 0]) = {[round(float(x), 4) for x in two_class]} sigmoid(2) = {sig2:.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next we check the gradient `∇_z loss = p − onehot(y)` when the true next token is `\" day\"`\n", "(index 1), compare our hand-written functions against PyTorch on a GPT-2-sized batch\n", "(`V = 50,257`), and run the **step-zero check**." ], "id": "lab-2-3-softmax-05" }, { "cell_type": "code", "metadata": {}, "source": [ "# Gradient check on the five-token example with true token = \" day\" (index 1)\n", "z_grad = z5.clone().detach().requires_grad_(True)\n", "loss_day = cross_entropy_hand(z_grad.unsqueeze(0), torch.tensor([1]))\n", "loss_day.backward()\n", "onehot_day = torch.tensor([0.0, 1.0, 0.0, 0.0, 0.0], dtype=torch.float64)\n", "expected_grad = p5 - onehot_day\n", "print(\"Gradient for true token = ' day' (index 1):\")\n", "for tok, g_auto, g_formula in zip(TOKENS, z_grad.grad, expected_grad):\n", " print(f\" {tok:12s} autograd {float(g_auto):+.4f} p - onehot {float(g_formula):+.4f}\")\n", "print(f\"sum of gradients = {float(z_grad.grad.sum()):+.2e} max diff = {float((z_grad.grad - expected_grad).abs().max()):.2e}\")\n", "\n", "# Compare against PyTorch on a GPT-2-sized batch [64, 50257]\n", "V = 50257\n", "torch.manual_seed(0)\n", "batch_logits = torch.randn(64, V, dtype=torch.float32) * 3.0\n", "batch_targets = torch.randint(0, V, (64,))\n", "\n", "diff_sm = float((softmax_stable(batch_logits) - F.softmax(batch_logits, dim=-1)).abs().max())\n", "diff_lsm = float((log_softmax_stable(batch_logits) - F.log_softmax(batch_logits, dim=-1)).abs().max())\n", "ce_hand = float(cross_entropy_hand(batch_logits, batch_targets))\n", "ce_torch = float(F.cross_entropy(batch_logits, batch_targets))\n", "print(\"\\nHand-written vs PyTorch on [64, 50257] float32 logits:\")\n", "print(f\" softmax max abs diff : {diff_sm:.2e}\")\n", "print(f\" log_softmax max abs diff : {diff_lsm:.2e}\")\n", "print(f\" cross_entropy hand : {ce_hand:.6f}\")\n", "print(f\" F.cross_entropy : {ce_torch:.6f}\")\n", "print(f\" cross_entropy abs diff : {abs(ce_hand - ce_torch):.2e}\")\n", "\n", "# Step-zero check (V = 50,257)\n", "zero_logits = torch.zeros(64, V)\n", "small_logits = torch.randn(64, V) * 0.01\n", "loss_zero = float(F.cross_entropy(zero_logits, batch_targets))\n", "loss_small = float(F.cross_entropy(small_logits, batch_targets))\n", "print(\"\\nStep-zero check (V = 50,257):\")\n", "print(f\" exact log(50,257) : {math.log(V):.4f} perplexity {V}\")\n", "print(f\" all-zero logits loss : {loss_zero:.4f} perplexity {math.exp(loss_zero):.1f}\")\n", "print(f\" small random (std=0.01) : {loss_small:.4f} perplexity {math.exp(loss_small):.1f}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Build: temperature, top-k, top-p, and seeded sampling\n", "\n", "Now we apply temperature (`z / T`), `top-k` filtering, `top-p` (nucleus) filtering, and explicit\n", "CDF sampling to the five-token example, check every table from Ch 2.3, verify the `V = 50,257`\n", "high-temperature tail collapse, and draw 10,000 samples to compare empirical frequencies against\n", "exact probabilities." ], "id": "lab-2-3-softmax-07" }, { "cell_type": "code", "metadata": {}, "source": [ "def apply_top_k(logits, k):\n", " if k <= 0 or k >= logits.shape[-1]:\n", " return logits\n", " top_vals, _ = torch.topk(logits, k, dim=-1)\n", " cutoff = top_vals[..., -1:].expand_as(logits)\n", " return logits.masked_fill(logits < cutoff, float(\"-inf\"))\n", "\n", "\n", "def apply_top_p(probs, p):\n", " if p >= 1.0:\n", " return probs\n", " sorted_p, sorted_idx = torch.sort(probs, descending=True, dim=-1)\n", " cum_p = torch.cumsum(sorted_p, dim=-1)\n", " # Keep every token until the cumulative sum first reaches or passes p\n", " remove_sorted = (cum_p - sorted_p) >= p\n", " remove_sorted[..., 0] = False # always keep at least the top token\n", " kept_sorted = sorted_p.masked_fill(remove_sorted, 0.0)\n", " kept = torch.zeros_like(probs).scatter(-1, sorted_idx, kept_sorted)\n", " return kept / kept.sum(dim=-1, keepdim=True)\n", "\n", "\n", "def distribution(logits, temperature=1.0, top_k=0, top_p=1.0):\n", " scaled = logits / temperature\n", " if top_k > 0:\n", " scaled = apply_top_k(scaled, top_k)\n", " probs = softmax_stable(scaled, dim=-1)\n", " if top_p < 1.0:\n", " probs = apply_top_p(probs, top_p)\n", " return probs\n", "\n", "\n", "def effective_choices(probs):\n", " nz = probs[probs > 0]\n", " H = float(-(nz * torch.log(nz)).sum())\n", " return math.exp(H)\n", "\n", "\n", "def sample_cdf(probs, n_draws, generator):\n", " cdf = torch.cumsum(probs, dim=-1)\n", " cdf[-1] = 1.0\n", " u = torch.rand(n_draws, generator=generator, dtype=probs.dtype)\n", " return torch.searchsorted(cdf, u, right=False)\n", "\n", "\n", "print(\"Temperature table on the five-token example:\")\n", "print(f\"{'T':>5s} \" + \" \".join(f\"{t:>9s}\" for t in TOKENS) + \" e^H\")\n", "for T in (0.5, 1.0, 2.0, 3.0):\n", " pt = distribution(z5, temperature=T)\n", " vals = \" \".join(f\"{float(x):9.4f}\" if float(x) >= 1e-4 else f\"{float(x):9.5f}\" for x in pt)\n", " print(f\"{T:5.1f} {vals} {effective_choices(pt):5.2f}\")\n", "\n", "print(\"\\nFilter tables on the five-token example:\")\n", "for label, kw in [\n", " (\"T=1.0, top-k=2\", dict(temperature=1.0, top_k=2, top_p=1.0)),\n", " (\"T=1.0, top-p=0.9\", dict(temperature=1.0, top_k=0, top_p=0.9)),\n", " (\"T=3.0, top-p=0.9\", dict(temperature=3.0, top_k=0, top_p=0.9)),\n", "]:\n", " pf = distribution(z5, **kw)\n", " print(f\" {label:18s}: \" + \" \".join(f\"{t}={float(x):.4f}\" for t, x in zip(TOKENS, pf)) + f\" e^H={effective_choices(pf):.2f}\")\n", "\n", "# High-T tail collapse for V = 50,257 (0.90 on token 0, 0.10 split across 50,256 tail tokens)\n", "p_real = torch.full((V,), 0.10 / (V - 1), dtype=torch.float64)\n", "p_real[0] = 0.90\n", "z_real = torch.log(p_real)\n", "p_real_t2 = softmax_stable(z_real / 2.0)\n", "print(f\"\\nTail collapse at V = {V:,}: T=1.0 top token = {float(p_real[0])*100:.1f}% -> T=2.0 top token = {float(p_real_t2[0])*100:.2f}%\")\n", "\n", "# Sample 10,000 draws and compare empirical frequencies with exact probabilities\n", "N_DRAWS = 10_000\n", "gen = torch.Generator().manual_seed(42)\n", "sampling_rows = []\n", "print(f\"\\nSampling {N_DRAWS:,} draws (seed 42):\")\n", "for cfg_name, kw in [\n", " (\"T=1.0\", dict(temperature=1.0, top_k=0, top_p=1.0)),\n", " (\"T=2.0\", dict(temperature=2.0, top_k=0, top_p=1.0)),\n", " (\"T=1.0, top-p=0.9\", dict(temperature=1.0, top_k=0, top_p=0.9)),\n", "]:\n", " pt = distribution(z5, **kw)\n", " draws = sample_cdf(pt, N_DRAWS, gen)\n", " counts = torch.bincount(draws, minlength=len(TOKENS))\n", " freqs = counts.double() / N_DRAWS\n", " max_err = float((freqs - pt).abs().max())\n", " print(f\" {cfg_name:18s} max |empirical - exact| = {max_err:.4f}\")\n", " for tok, exact_p, cnt, emp_p in zip(TOKENS, pt, counts, freqs):\n", " print(f\" {tok:10s} exact {float(exact_p):.4f} empirical {float(emp_p):.4f} ({int(cnt):5d}/{N_DRAWS})\")\n", " sampling_rows.append({\n", " \"config\": cfg_name,\n", " \"token\": tok.strip('\"'),\n", " \"exact_prob\": f\"{float(exact_p):.6f}\",\n", " \"empirical_freq\": f\"{float(emp_p):.6f}\",\n", " \"count\": int(cnt),\n", " \"n_draws\": N_DRAWS,\n", " })\n", "\n", "save_csv(\"sampling-10k.csv\", [\"config\", \"token\", \"exact_prob\", \"empirical_freq\", \"count\", \"n_draws\"], sampling_rows)" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Measure: repetition in 200-token outputs of GPT-2 small\n", "\n", "Chapter 2.3 claims that greedy decoding loops on longer continuations while sampling escapes\n", "repetition. Here we measure it directly on GPT-2 small (`gpt2`, 124M parameters, `V = 50,257`).\n", "\n", "For five prompts and three decoding rules (`greedy`, `T = 1.0`, and `T = 0.7, top-p = 0.9`), we\n", "generate **200 new tokens** (`min_new_tokens = max_new_tokens = 200`) and compute the **repeated\n", "4-gram share** over the 197 token 4-grams in each continuation:\n", "\n", "`repeated_4gram_share = 1 − (unique 4-grams / total 4-grams)`\n", "\n", "A share of `0.0` means no 4-token phrase repeated; `0.80` means 80% of all 4-grams were repeats\n", "of an earlier 4-gram. Note that we pass `top_k=0` explicitly so Hugging Face does not add a\n", "hidden default filter." ], "id": "lab-2-3-softmax-09" }, { "cell_type": "code", "metadata": {}, "source": [ "t_load = time.perf_counter()\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "tok_gpt2 = AutoTokenizer.from_pretrained(\"gpt2\")\n", "model_gpt2 = AutoModelForCausalLM.from_pretrained(\"gpt2\")\n", "model_gpt2.eval()\n", "if device.type == \"cpu\":\n", " # Clone parameter storage off the read-only safetensors mmap (avoids arm64 Accelerate SIGBUS).\n", " with torch.no_grad():\n", " for param in model_gpt2.parameters():\n", " param.data = param.data.clone()\n", "model_gpt2.to(device)\n", "\n", "n_params = sum(p.numel() for p in model_gpt2.parameters())\n", "# lm_head shares weights with transformer.wte in GPT-2 small\n", "head_params = model_gpt2.lm_head.weight.numel()\n", "print(\n", " f\"Loaded gpt2 on {device} in {time.perf_counter() - t_load:.2f}s | \"\n", " f\"total params = {n_params:,} | output matrix = {head_params:,} ({head_params / n_params * 100:.1f}%)\"\n", ")\n", "\n", "PROMPTS = [\n", " (\"p1\", \"Once upon a time, in a quiet little village,\"),\n", " (\"p2\", \"The most important thing to understand about computer memory is\"),\n", " (\"p3\", \"In 1969, engineers working on the guidance computer discovered that\"),\n", " (\"p4\", \"She opened the heavy wooden door and saw\"),\n", " (\"p5\", \"Scientists studying ocean currents reported this week that\"),\n", "]\n", "\n", "\n", "def repeat_4gram_stats(token_ids):\n", " grams = [tuple(token_ids[i : i + 4]) for i in range(len(token_ids) - 3)]\n", " unique = len(set(grams))\n", " counts = {}\n", " for g in grams:\n", " counts[g] = counts.get(g, 0) + 1\n", " share = 1.0 - unique / len(grams)\n", " return len(grams), unique, max(counts.values()), share\n", "\n", "\n", "def generate_200(prompt, do_sample, temperature=1.0, top_p=1.0, seed=0):\n", " inp = tok_gpt2(prompt, return_tensors=\"pt\")[\"input_ids\"].to(device)\n", " plen = inp.shape[1]\n", " torch.manual_seed(seed)\n", " if device.type == \"cuda\":\n", " torch.cuda.manual_seed_all(seed)\n", " kw = dict(\n", " min_new_tokens=200,\n", " max_new_tokens=200,\n", " do_sample=do_sample,\n", " pad_token_id=tok_gpt2.eos_token_id,\n", " )\n", " if do_sample:\n", " kw.update(temperature=temperature, top_k=0, top_p=top_p)\n", " with torch.no_grad():\n", " out = model_gpt2.generate(inp, **kw)\n", " gen_ids = out[0][plen:].tolist()\n", " return gen_ids, tok_gpt2.decode(gen_ids)\n", "\n", "\n", "STRATEGIES = [\n", " (\"greedy\", False, 0.0, 1.0, [0]),\n", " (\"T=1.0\", True, 1.0, 1.0, [0, 1, 2]),\n", " (\"T=0.7, top-p=0.9\", True, 0.7, 0.9, [0, 1, 2]),\n", "]\n", "\n", "machine_tag = (\n", " f\"{torch.cuda.get_device_name(0)} (cuda)\"\n", " if device.type == \"cuda\"\n", " else f\"{platform.system()} {platform.machine()} (cpu)\"\n", ")\n", "\n", "t_meas = time.perf_counter()\n", "rep_rows = []\n", "saved_texts = {}\n", "for pid, prompt in PROMPTS:\n", " for strat, do_sample, temp, topp, seeds in STRATEGIES:\n", " for seed in seeds:\n", " gen_ids, text = generate_200(prompt, do_sample, temp, topp, seed)\n", " total_4g, unique_4g, max_4g, share = repeat_4gram_stats(gen_ids)\n", " if pid == \"p1\" and seed == 0:\n", " saved_texts[strat] = (share, text)\n", " rep_rows.append({\n", " \"prompt_id\": pid,\n", " \"prompt\": prompt,\n", " \"strategy\": strat,\n", " \"temperature\": f\"{temp:.1f}\",\n", " \"top_p\": f\"{topp:.1f}\",\n", " \"seed\": seed,\n", " \"n_tokens\": len(gen_ids),\n", " \"total_4grams\": total_4g,\n", " \"unique_4grams\": unique_4g,\n", " \"max_4gram_count\": max_4g,\n", " \"repeated_4gram_share\": f\"{share:.6f}\",\n", " \"machine\": machine_tag,\n", " })\n", "\n", "print(f\"Ran {len(rep_rows)} generations of 200 tokens in {time.perf_counter() - t_meas:.1f}s on {machine_tag}\\n\")\n", "\n", "print(f\"{'Strategy':18s} {'Runs':>4s} {'Mean rep-4':>11s} {'Min':>8s} {'Max':>8s} {'Mean max-count':>15s}\")\n", "for strat, *_ in STRATEGIES:\n", " sub = [r for r in rep_rows if r[\"strategy\"] == strat]\n", " shares = [float(r[\"repeated_4gram_share\"]) for r in sub]\n", " maxc = [int(r[\"max_4gram_count\"]) for r in sub]\n", " print(\n", " f\"{strat:18s} {len(sub):4d} {sum(shares)/len(shares)*100:10.1f}% \"\n", " f\"{min(shares)*100:7.1f}% {max(shares)*100:7.1f}% {sum(maxc)/len(maxc):15.1f}\"\n", " )\n", "\n", "print(\"\\nPer-prompt repeated 4-gram share (mean across seeds):\")\n", "header = f\"{'Prompt':6s} {'greedy':>8s} {'T=1.0':>8s} {'T=0.7, p=0.9':>13s}\"\n", "print(header)\n", "for pid, _ in PROMPTS:\n", " vals = []\n", " for strat, *_ in STRATEGIES:\n", " sub = [float(r[\"repeated_4gram_share\"]) for r in rep_rows if r[\"prompt_id\"] == pid and r[\"strategy\"] == strat]\n", " vals.append(sum(sub) / len(sub) * 100)\n", " print(f\"{pid:6s} {vals[0]:7.1f}% {vals[1]:7.1f}% {vals[2]:12.1f}%\")\n", "\n", "save_csv(\n", " \"repetition.csv\",\n", " [\n", " \"prompt_id\", \"prompt\", \"strategy\", \"temperature\", \"top_p\", \"seed\",\n", " \"n_tokens\", \"total_4grams\", \"unique_4grams\", \"max_4gram_count\",\n", " \"repeated_4gram_share\", \"machine\",\n", " ],\n", " rep_rows,\n", ")" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-10" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " strats = [s[0] for s in STRATEGIES]\n", " means = [\n", " sum(float(r[\"repeated_4gram_share\"]) for r in rep_rows if r[\"strategy\"] == s)\n", " / sum(1 for r in rep_rows if r[\"strategy\"] == s)\n", " * 100\n", " for s in strats\n", " ]\n", " fig, ax = plt.subplots(figsize=(6.5, 3.6))\n", " ax.bar(strats, means, color=[\"#171717\", \"#6b6b6b\", \"#9a9a9a\"], edgecolor=\"#171717\")\n", " for i, m in enumerate(means):\n", " ax.text(i, m + 1.5, f\"{m:.1f}%\", ha=\"center\", va=\"bottom\", fontweight=\"bold\")\n", " ax.set_ylabel(\"repeated 4-gram share (%)\")\n", " ax.set_ylim(0, max(means) + 12)\n", " ax.set_title(\"GPT-2 small (200 tokens, 5 prompts): greedy vs sampling repetition\")\n", " plt.tight_layout()\n", " plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skipping plot\")" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "Compare your run against the reference outputs recorded in Lab 2.3 (measured on Apple M1 CPU;\n", "the last digit may differ slightly across hardware and library versions):\n", "\n", "- Five-token softmax: `p = [0.7067, 0.1577, 0.0956, 0.0352, 0.0048]`, `sum(e^z) = 77.256`,\n", " shift-invariance difference `0.00e+00`, gradient for `\" day\"` matches `p − onehot` to `1.39e-17`.\n", "- Hand-written vs PyTorch on `[64, 50257]` `float32`: max abs difference `2.74e-06` (softmax),\n", " `1.14e-05` (log-softmax), and `6.68e-06` (cross-entropy).\n", "- Step-zero loss for `V = 50,257`: `10.8249` (perplexity `50,257.0`), matching `log 50,257`.\n", "- 10,000 draws from the five-token example (`seed = 42`): max `|empirical − exact|` is `0.0039`\n", " at `T = 1.0`, `0.0019` at `T = 2.0`, and `0.0074` at `T = 1.0, top-p = 0.9`.\n", "- GPT-2 small 200-token repetition across 5 prompts: `greedy` mean `76.8%` repeated 4-grams\n", " (range `51.3%–89.3%`), `T = 1.0` mean `0.4%` (`0.0%–2.0%`), `T = 0.7, top-p = 0.9` mean `19.9%`\n", " (`0.5%–57.4%`)." ], "id": "lab-2-3-softmax-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Explore\n", "\n", "Change one knob at a time and answer the question next to it.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| temperature `T` | `T = 0.2`, `0.5`, `1.0`, `1.5`, `2.0` in `generate_200` | Where does repetition stop, and where does the text turn into nonsense? |\n", "| `top_p` | `0.5`, `0.8`, `0.9`, `0.95`, `1.0` at `T = 1.0` | How low can `top_p` go before repetition starts creeping back in? |\n", "| `top_k` | `k = 5`, `40`, `200` on `z5` and in `generate_200` | Compare `top_k = 40` after *\"The capital of France is\"* vs *\"She opened the door and saw a\"*. Why does a fixed `k` hurt one of them? |\n", "| vocabulary size `V` | `V = 27`, `1_000`, `50_257`, `200_000` in the tail-collapse snippet | How does `V` change the `T = 2.0` survival probability of a 90%-confident top token? |\n", "| prompt & seed | `seed = 0, 1, 2, 3, 4` on your own prompt | Does changing the seed change greedy (`T = 0`) output at all? How much does `rep-4` vary across seeds at `T = 0.7, top-p = 0.9`? |" ], "id": "lab-2-3-softmax-13" }, { "cell_type": "code", "metadata": {}, "source": [ "# Your experiments here, for example:\n", "# ids, txt = generate_200(PROMPTS[0][1], do_sample=True, temperature=0.8, top_p=0.9, seed=7)\n", "# print(repeat_4gram_stats(ids), txt[:200])" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Failure playground\n", "\n", "Three bugs below break real training runs and served models. For each: run it, read the symptom,\n", "find the cause, and fix it. Hints are in Review 2.3; answers are not." ], "id": "lab-2-3-softmax-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7a · `float16` overflow to `NaN` (and `log(softmax)` underflow)\n", "\n", "A colleague implements softmax and log-softmax in two lines without subtracting the maximum, and\n", "runs mixed precision in `float16`." ], "id": "lab-2-3-softmax-16" }, { "cell_type": "code", "metadata": {}, "source": [ "z_f16 = torch.tensor([12.0, 14.0, 11.0], dtype=torch.float16)\n", "p_f16_naive = softmax_naive(z_f16)\n", "print(\"7a naive float16 softmax([12, 14, 11]):\", p_f16_naive.tolist())\n", "print(\" intermediate exp(z) in float16 :\", torch.exp(z_f16).tolist())\n", "\n", "# Second half of 7a: naive log(softmax(z)) in float32 on a wide logit gap\n", "z_gap = torch.tensor([0.0, -120.0], dtype=torch.float32)\n", "log_p_naive = torch.log(softmax_stable(z_gap))\n", "print(\"7a naive log(softmax([0, -120])) f32 :\", log_p_naive.tolist())" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `naive float16 softmax([12, 14, 11])` produces `[nan, nan, 0.0]`, and `log(softmax([0, -120]))`\n", "hits `-inf` even in `float32`. Why did `e^12` and `e^14` overflow in `float16` while `e^11` stayed\n", "finite? Why did `log(softmax)` hit `-inf` even though `softmax_stable` did not overflow? Replace\n", "both calls with the stable versions and verify the exact outputs." ], "id": "lab-2-3-softmax-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7b · Silent double softmax stalling near 9.825\n", "\n", "A colleague wires up a GPT-2-sized output head (`V = 50,257`) and calls `F.softmax` before\n", "`F.cross_entropy`. No exception is raised, gradients are finite and non-zero, and the loss even\n", "drops at first — then hits an invisible wall." ], "id": "lab-2-3-softmax-19" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(0)\n", "hidden = torch.randn(4, 16)\n", "targets_7b = torch.tensor([42, 1337, 9999, 40000])\n", "\n", "head_broken = nn.Linear(16, V, bias=False)\n", "nn.init.normal_(head_broken.weight, std=0.01)\n", "opt = torch.optim.Adam(head_broken.parameters(), lr=0.1)\n", "\n", "floor_7b = -math.log(math.e / (math.e + V - 1))\n", "print(f\"V = {V:,} step-zero log V = {math.log(V):.4f} double-softmax floor = {floor_7b:.4f}\")\n", "for step in range(151):\n", " logits_7b = head_broken(hidden)\n", " probs_7b = F.softmax(logits_7b, dim=-1) # <-- bug: softmax before F.cross_entropy\n", " loss_7b = F.cross_entropy(probs_7b, targets_7b)\n", " if step in (0, 25, 50, 100, 150):\n", " top1_p = probs_7b[torch.arange(4), targets_7b].detach().mean().item()\n", " print(f\"step {step:3d} loss {loss_7b.detach().item():.4f} mean p(true) after 1st softmax = {top1_p:.4f}\")\n", " opt.zero_grad()\n", " loss_7b.backward()\n", " opt.step()" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: no crash, `p(true)` after the first softmax approaches `1.0`, yet the loss stalls right\n", "above `9.825` forever. Explain from the formula of `F.cross_entropy` why even a perfect `[1, 0, …, 0]`\n", "distribution cannot score below `−log(e / (e + 50,256)) ≈ 9.8249`. Remove the bug and check how\n", "low the loss goes in 150 steps." ], "id": "lab-2-3-softmax-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7c · Greedy repetition loops next to high-temperature word salad\n", "\n", "Two bad decoding settings on the same prompt (`\"Once upon a time, in a quiet little village,\"`):\n", "greedy decoding (`T = 0`) versus unfiltered high temperature (`T = 2.0, top_k = 0, top_p = 1.0`)." ], "id": "lab-2-3-softmax-22" }, { "cell_type": "code", "metadata": {}, "source": [ "greedy_share, greedy_text = saved_texts[\"greedy\"]\n", "salad_ids, salad_text = generate_200(PROMPTS[0][1], do_sample=True, temperature=2.0, top_p=1.0, seed=0)\n", "_, _, _, salad_share = repeat_4gram_stats(salad_ids)\n", "\n", "print(f\"--- 7c (left): greedy (T = 0) | repeated 4-gram share = {greedy_share * 100:.1f}% ---\")\n", "print(PROMPTS[0][1] + greedy_text)\n", "print(f\"\\n--- 7c (right): T = 2.0, no filter | repeated 4-gram share = {salad_share * 100:.1f}% ---\")\n", "print(PROMPTS[0][1] + salad_text)" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: greedy gets stuck repeating the same clause over and over (high repeated 4-gram share),\n", "while `T = 2.0` unfiltered has near-zero repetition yet produces incoherent word salad. Explain\n", "why *both* happen from the logit distribution over `50,257` tokens. Try fixing the right-hand run\n", "with `top_p` before lowering `T` — what changes?" ], "id": "lab-2-3-softmax-24" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\n", " \"Versions tested:\",\n", " f\"Python {platform.python_version()},\",\n", " f\"PyTorch {torch.__version__},\",\n", " f\"transformers {transformers.__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(machine_tag)" ], "execution_count": null, "outputs": [], "id": "lab-2-3-softmax-25" } ] }