{ "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.3 · A Tiny GPT\n", "\n", "**Goal:** assemble the pieces of Ch 3.1 and Ch 3.2 (attention, the block, position embeddings)\n", "into a complete GPT in about 200 lines of PyTorch, train it on TinyStories, read the loss\n", "curves, watch its writing change from noise to short stories, measure tokens per second on every\n", "device you have, and break the training loop three ways.\n", "\n", "**Runs on:** any laptop. Two settings: `quick` (about 13 minutes on an M1 CPU, a bit under\n", "9 of them in training steps) and `reference` (the same model on about 32 times as many tokens; the book's numbers come\n", "from an RTX 3060, but a laptop GPU or Apple `mps` also works, only slower). Choose with the\n", "environment variable `TINYGPT_SETTING` (default `quick`) and the device with `TINYGPT_DEVICE`\n", "(`cpu`, `mps` or `cuda`; default: the fastest one present). Install locally with\n", "`uv run --with torch --with tiktoken --with matplotlib jupyter lab`. The notebook downloads a\n", "slice of TinyStories itself (needs internet once).\n", "\n", "**Versions tested:** printed by the last cell.\n", "\n", "The data: the first 120 MB of the TinyStories *training* file (Eldan and Li, 2023; licence\n", "CDLA-Sharing-1.0), cut into GPT-2 tokens (Ch 2.1), a random 98 % of the stories for training and\n", "the other 2 % for validation. The model reads a window of 256 tokens and, at every position, must predict the next\n", "token (Ch 2.3). Everything is seeded." ], "id": "lab-3-3-tinygpt-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 contextlib import nullcontext\n", "from dataclasses import asdict, dataclass\n", "\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", "SETTING = os.environ.get(\"TINYGPT_SETTING\", \"quick\")\n", "assert SETTING in (\"quick\", \"reference\"), \"TINYGPT_SETTING must be quick or reference\"\n", "DEVICES = [\"cpu\"]\n", "if torch.cuda.is_available():\n", " DEVICES.append(\"cuda\")\n", "if torch.backends.mps.is_available():\n", " DEVICES.append(\"mps\")\n", "DEVICE = os.environ.get(\"TINYGPT_DEVICE\") or (\"cuda\" if \"cuda\" in DEVICES else \"mps\" if \"mps\" in DEVICES else \"cpu\")\n", "if DEVICE == \"cpu\":\n", " torch.set_num_threads(max(1, min(8, torch.get_num_threads())))\n", "MACHINE = os.environ.get(\"TINYGPT_MACHINE\") or (\n", " torch.cuda.get_device_name(0) if DEVICE == \"cuda\" else f\"{platform.system()} {platform.machine()}\")\n", "print(f\"PyTorch {torch.__version__} | tiktoken {tiktoken.__version__} | devices {DEVICES}\")\n", "print(f\"setting = {SETTING} | training device = {DEVICE} | machine = {MACHINE}\")\n", "\n", "\n", "def sync(device):\n", " if device == \"cuda\":\n", " torch.cuda.synchronize()\n", " elif device == \"mps\":\n", " torch.mps.synchronize()\n", "\n", "\n", "def load_1min():\n", " \"\"\"Machine load (1-minute average) at the time of a measurement: other jobs distort timings.\"\"\"\n", " try:\n", " return round(os.getloadavg()[0], 1)\n", " except (AttributeError, OSError):\n", " return float(\"nan\")\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-3-tinygpt\"\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 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 update_json(name, key, value):\n", " \"\"\"Read-modify-write: the quick and the reference run (on two machines) share one file.\"\"\"\n", " path = out_dir() / name\n", " doc = json.loads(path.read_text()) if path.exists() else {}\n", " doc[key] = value\n", " path.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + \"\\n\")\n", " print(\"saved\", path, \"key\", repr(key))" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your answers before running anything.\n", "\n", "1. The reference model has `n_layer = 4`, `n_head = 4`, `d_model = 128`, `context = 256`. One\n", " block holds attention `4d² + 4d`, an MLP `8d² + 5d` and two LayerNorms `4d` weights (Ch 3.2).\n", " With a vocabulary of `V` tokens and the output layer *tied* to the token embedding, how many\n", " weights does the whole model have, as a formula in `V` and `d`? Which of its parts is the\n", " biggest, and is it the one that does the \"thinking\"?\n", "2. Before the first update, the model knows nothing. What loss do you expect at step 0 as a\n", " function of `V` (Ch 2.3)?\n", "3. A batch is 16 windows of 256 tokens. How many tokens is that? If the training text has 28\n", " million tokens, how many such steps are one pass over it?\n", "4. Roughly how many tokens per second do you expect on (a) an M1 CPU, (b) an M1 GPU (`mps`),\n", " (c) an RTX 3060? Use Lab 0.1's matmul speeds: a training step costs about `6 ×` (weights in\n", " matrix products) floating-point operations per token.\n", "5. At the end of training, which is lower: the loss on the training stories or on the unseen\n", " validation stories? By how much, roughly, after fewer than 2 passes over the data?\n", "\n", "## 2 · The data: TinyStories as a uint16 array\n", "\n", "We download the first 120 MB of the training file, split it into stories (`<|endoftext|>`\n", "separates them), put a random 98 % of the stories in the training set and the other 2 % in the\n", "validation set (random, with a fixed seed: the order of stories in the file need not be random,\n", "and a validation set cut from its end could differ from the rest), tokenise with the GPT-2 tokenizer and write each set as one flat array of\n", "16-bit integers. Training then samples random windows from the array: no padding, no batching of\n", "stories.\n", "\n", "The GPT-2 vocabulary has 50,257 entries, but a TinyStories slice uses only a fraction of them,\n", "and the output layer costs `V × d` weights and `2 V d` operations per token. As in Lab 2.2, we\n", "renumber the tokens that occur to `0 … V-1` and keep the table back to GPT-2 IDs. The price: a\n", "prompt containing a token that never occurs in the slice cannot be encoded (`encode()` raises a\n", "`KeyError`). What we gain is memory and speed." ], "id": "lab-3-3-tinygpt-02" }, { "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", "enc = tiktoken.get_encoding(\"gpt2\")\n", "EOT = enc.eot_token # 50256\n", "\n", "TRAIN_BIN = cache_dir() / f\"tinystories-{DATA_MB}mb-rsplit-train.uint16.bin\"\n", "VAL_BIN = cache_dir() / f\"tinystories-{DATA_MB}mb-rsplit-val.uint16.bin\"\n", "VOCAB_JSON = cache_dir() / f\"tinystories-{DATA_MB}mb-rsplit-vocab.json\"\n", "if not (TRAIN_BIN.exists() and VAL_BIN.exists() and VOCAB_JSON.exists()):\n", " text = RAW.read_bytes().decode(\"utf-8\", errors=\"ignore\")\n", " stories = [s.strip() for s in text.split(\"<|endoftext|>\")][:-1] # the last one is cut off\n", " del text\n", " cut = int(len(stories) * 0.98)\n", " order = np.random.default_rng(0).permutation(len(stories)) # a random split: the file's order is not random\n", " train_stories, val_stories = [stories[i] for i in order[:cut]], [stories[i] for i in order[cut:]]\n", " t0 = time.time()\n", "\n", " def to_array(story_list): # GPT-2 ids, after every story\n", " parts = []\n", " for k in range(0, len(story_list), 20_000): # in chunks: Python lists of ints are big\n", " for p in enc.encode_ordinary_batch(story_list[k:k + 20_000], num_threads=8):\n", " parts.append(np.array(p + [EOT], dtype=np.uint16))\n", " return np.concatenate(parts)\n", "\n", " train_raw, val_raw = to_array(train_stories), to_array(val_stories)\n", " used = np.unique(np.concatenate([train_raw, val_raw])) # the GPT-2 ids that occur, sorted\n", " remap = np.zeros(enc.n_vocab, dtype=np.uint16)\n", " remap[used] = np.arange(len(used), dtype=np.uint16)\n", " remap[train_raw].tofile(TRAIN_BIN)\n", " remap[val_raw].tofile(VAL_BIN)\n", " VOCAB_JSON.write_text(json.dumps({\"stories\": len(stories), \"train_stories\": cut, \"gpt2_ids\": used.tolist()}))\n", " print(f\"tokenised {len(stories):,} stories in {time.time() - t0:.1f} s\")\n", " del stories, train_stories, val_stories, train_raw, val_raw\n", "\n", "train_data = np.fromfile(TRAIN_BIN, dtype=np.uint16)\n", "val_data = np.fromfile(VAL_BIN, dtype=np.uint16)\n", "meta = json.loads(VOCAB_JSON.read_text())\n", "used = meta[\"gpt2_ids\"] # new id -> GPT-2 id\n", "to_new = {t: i for i, t in enumerate(used)}\n", "V = len(used)\n", "\n", "\n", "def encode(text): # text -> ids of OUR vocabulary\n", " return [to_new[t] for t in enc.encode_ordinary(text)]\n", "\n", "\n", "def decode(ids): # our ids -> text (<|endoftext|> shows an end of story)\n", " return enc.decode([used[i] for i in ids])\n", "\n", "\n", "print(f\"stories {meta['stories']:,} (train {meta['train_stories']:,}, validation {meta['stories'] - meta['train_stories']:,})\")\n", "print(f\"train tokens {len(train_data):,} validation tokens {len(val_data):,} vocabulary used V = {V:,} (of 50,257)\")\n", "print(f\"bytes per token: {RAW.stat().st_size / (len(train_data) + len(val_data)):.2f}\")\n", "print(f\"log V = {math.log(V):.4f}\")\n", "print(\"first training tokens:\", train_data[:12].tolist(), \"->\", repr(decode(train_data[:12].tolist())))\n", "print(\"round trip:\", decode(encode(\"Once upon a time, there was a little girl named Lily.\")))" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Build: the full GPT\n", "\n", "Read this cell top to bottom; it is the whole model. The pieces are the ones you built in Ch 3.1\n", "and Ch 3.2:\n", "\n", "| step | shape (`B` windows of `T` tokens) |\n", "| --- | --- |\n", "| token ids | `[B, T]` |\n", "| token embedding + position embedding | `[B, T, d]` |\n", "| `n_layer` blocks, each: LayerNorm → causal multi-head attention → add; LayerNorm → MLP (`d → 4d → d`, GELU) → add | `[B, T, d]` |\n", "| final LayerNorm | `[B, T, d]` |\n", "| output layer, the **same matrix** as the token embedding, transposed | `[B, T, V]` |\n", "| cross-entropy against the ids shifted left by one | scalar |\n", "\n", "Two details you did not need before: the weights start small (`std = 0.02`, and the two layers\n", "that write into the residual stream start smaller still, so a deep stack does not blow up at\n", "step 0), and `attention(..., manual=True)` is the same computation written out with a mask and a\n", "softmax, so that you can check the fast library kernel against it." ], "id": "lab-3-3-tinygpt-04" }, { "cell_type": "code", "metadata": {}, "source": [ "@dataclass\n", "class GPTConfig:\n", " vocab_size: int\n", " block_size: int = 256 # context length T\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) # W_q, W_k, W_v side by side\n", " self.proj = nn.Linear(c.d_model, c.d_model) # mixes the heads back together\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) # each [B, T, d]\n", " q, k, v = (t.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) for t in (q, k, v)) # [B, h, T, d/h]\n", " if manual:\n", " att = (q @ k.transpose(-2, -1)) / math.sqrt(k.size(-1)) # [B, h, T, T] scores\n", " att = att.masked_fill(~self.mask[:T, :T], float(\"-inf\")).softmax(dim=-1)\n", " y = att @ v\n", " else:\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), manual=manual) # residual stream: read, add\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) # token embedding [V, d]\n", " self.wpe = nn.Embedding(c.block_size, c.d_model) # position embedding [T, d]\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 # weight tying: one matrix, two jobs\n", " self.apply(self._init)\n", " for name, p in self.named_parameters(): # residual-writing layers start smaller\n", " if name.endswith(\"attn.proj.weight\") or name.endswith(\"mlp.2.weight\"):\n", " nn.init.normal_(p, std=0.02 / math.sqrt(2 * c.n_layer))\n", "\n", " @staticmethod\n", " def _init(m):\n", " if isinstance(m, (nn.Linear, nn.Embedding)):\n", " nn.init.normal_(m.weight, std=0.02)\n", " if isinstance(m, nn.Linear) and m.bias is not None:\n", " nn.init.zeros_(m.bias)\n", "\n", " def forward(self, idx, targets=None, manual=False):\n", " B, T = idx.shape\n", " assert T <= self.c.block_size, f\"context {T} is longer than block_size {self.c.block_size}\"\n", " x = self.drop(self.wte(idx) + self.wpe(torch.arange(T, device=idx.device))) # [B, T, d]\n", " for block in self.blocks:\n", " x = block(x, manual=manual)\n", " logits = self.lm_head(self.ln_f(x)) # [B, T, V]\n", " loss = None if targets is None else F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))\n", " return logits, loss\n", "\n", "\n", "@torch.no_grad()\n", "def generate(model, idx, max_new_tokens, temperature=0.8, top_k=40, seed=0):\n", " \"\"\"Ch 0.1's loop made real: predict, sample one token, append, repeat.\"\"\"\n", " model.eval()\n", " g = torch.Generator().manual_seed(seed) # sampling on the CPU: same on every device\n", " for _ in range(max_new_tokens):\n", " logits, _ = model(idx[:, -model.c.block_size:])\n", " logits = logits[:, -1, :].float() / temperature # last position only\n", " if top_k:\n", " kth = logits.topk(top_k).values[:, -1:]\n", " logits = logits.masked_fill(logits < kth, float(\"-inf\"))\n", " nxt = torch.multinomial(logits.softmax(-1).cpu(), 1, generator=g).to(idx.device)\n", " idx = torch.cat([idx, nxt], dim=1)\n", " return idx\n", "\n", "\n", "def count_params(model):\n", " return sum(p.numel() for p in model.parameters()) # tied weights are counted once" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Checks before any training\n", "\n", "Five cheap checks catch most wiring bugs: the parameter count against your formula, the shapes,\n", "the step-zero loss against `log V`, the library attention against the hand-written one, and the\n", "causal property (changing a *future* token must not change an earlier prediction)." ], "id": "lab-3-3-tinygpt-06" }, { "cell_type": "code", "metadata": {}, "source": [ "cfg = GPTConfig(vocab_size=V)\n", "torch.manual_seed(0)\n", "model = GPT(cfg)\n", "d, L, T = cfg.d_model, cfg.n_layer, cfg.block_size\n", "formula = V * d + T * d + L * (12 * d * d + 13 * d) + 2 * d\n", "print(f\"parameters: {count_params(model):,} formula V·d + T·d + L·(12d² + 13d) + 2d = {formula:,}\")\n", "print(f\" token embedding (also the output layer) {V * d:,} = {100 * V * d / formula:.1f} % of the model\")\n", "print(f\" position embedding {T * d:,} the {L} blocks {L * (12 * d * d + 13 * d):,} final LayerNorm {2 * d}\")\n", "\n", "x0 = torch.from_numpy(train_data[None, :T + 1].astype(np.int64))\n", "logits, loss = model(x0[:, :-1], x0[:, 1:])\n", "print(f\"shapes: ids {tuple(x0[:, :-1].shape)} -> logits {tuple(logits.shape)}\")\n", "print(f\"step-zero loss {loss.item():.4f} (log V = {math.log(V):.4f})\")\n", "\n", "with torch.no_grad():\n", " a, _ = model(x0[:, :-1])\n", " b, _ = model(x0[:, :-1], manual=True)\n", "print(f\"library attention vs hand-written attention: max abs difference of the logits {(a - b).abs().max().item():.2e}\")\n", "\n", "with torch.no_grad():\n", " x1 = x0[:, :-1].clone()\n", " x1[0, 100] = (x1[0, 100] + 1) % V # change one token in the middle\n", " c, _ = model(x1)\n", "print(f\"changing token 100: logits before position 100 differ by {(a[0, :100] - c[0, :100]).abs().max().item():.1e}, \"\n", " f\"from position 100 on by {(a[0, 100:] - c[0, 100:]).abs().max().item():.1e}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Build: batches, the schedule, the loop\n", "\n", "**Batches.** Pick `B` random start positions; the input is `data[i : i+T]`, the target is the same\n", "window shifted by one, `data[i+1 : i+T+1]`. Every position of every window is a training example\n", "(`B × T` of them per step). A window may cross from one story into the next; the `` token\n", "between them tells the model that a story ended.\n", "\n", "**Learning rate.** Linear warm-up for the first steps (Adam's statistics are unreliable at the\n", "start), then a cosine decay from `max_lr` to `0.1 × max_lr`.\n", "\n", "**Optimiser.** AdamW (Ch 1.3's Adam with weight decay applied to the weight *matrices* only, not\n", "to biases and LayerNorm), `betas = (0.9, 0.95)`, gradients clipped to a total norm of 1.0.\n", "\n", "**Evaluation.** Every `eval_every` steps: the loss on 256 *fixed* windows of the training set and\n", "256 fixed windows of the validation set (the same windows every time, so the curves are\n", "comparable), plus a checkpoint to disk. The validation windows are stories the model never saw." ], "id": "lab-3-3-tinygpt-08" }, { "cell_type": "code", "metadata": {}, "source": [ "PROMPTS = [\"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", "SAMPLE_T, SAMPLE_TOP_K, SAMPLE_TOKENS = 0.8, 40, 60\n", "\n", "# knobs of the two settings. Same model, same data, same seed; only the budget differs.\n", "SETTINGS = {\n", " \"quick\": dict(steps=1000, batch=16, max_lr=2e-3, warmup=30, eval_every=50, sample_steps=[0, 100, 400, 1000]),\n", " \"reference\": dict(steps=8000, batch=64, max_lr=2e-3, warmup=200, eval_every=250, sample_steps=[0, 500, 2000, 8000]),\n", "}\n", "EVAL_WINDOWS, MIN_LR_RATIO, WEIGHT_DECAY, GRAD_CLIP, SEED = 256, 0.1, 0.1, 1.0, 1337\n", "\n", "\n", "def lr_at(step, max_lr, warmup, total, min_ratio=MIN_LR_RATIO):\n", " if step < warmup:\n", " return max_lr * (step + 1) / warmup # linear warm-up\n", " p = min(1.0, (step - warmup) / max(1, total - warmup))\n", " return max_lr * (min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * p))) # cosine decay\n", "\n", "\n", "def get_batch(data, batch, gen, device):\n", " ix = torch.randint(0, len(data) - T - 1, (batch,), generator=gen).tolist()\n", " x = torch.from_numpy(np.stack([data[i:i + T] for i in ix]).astype(np.int64))\n", " y = torch.from_numpy(np.stack([data[i + 1:i + 1 + T] for i in ix]).astype(np.int64))\n", " return x.to(device), y.to(device)\n", "\n", "\n", "def fixed_windows(data, n, seed):\n", " g = torch.Generator().manual_seed(seed)\n", " ix = torch.randint(0, len(data) - T - 1, (n,), generator=g).tolist()\n", " x = torch.from_numpy(np.stack([data[i:i + T] for i in ix]).astype(np.int64))\n", " y = torch.from_numpy(np.stack([data[i + 1:i + 1 + T] for i in ix]).astype(np.int64))\n", " return x, y\n", "\n", "\n", "def autocast_for(device): # bf16 on the GPU, float32 elsewhere\n", " return torch.autocast(\"cuda\", dtype=torch.bfloat16) if device == \"cuda\" else nullcontext()\n", "\n", "\n", "@torch.no_grad()\n", "def eval_loss(model, xy, device, chunk=64):\n", " model.eval()\n", " x, y = xy\n", " total = 0.0\n", " for i in range(0, len(x), chunk):\n", " with autocast_for(device):\n", " _, loss = model(x[i:i + chunk].to(device), y[i:i + chunk].to(device))\n", " total += loss.item() * len(x[i:i + chunk])\n", " model.train()\n", " return total / len(x)\n", "\n", "\n", "def sample_all(model, device):\n", " out = []\n", " for k, prompt in enumerate(PROMPTS):\n", " idx = torch.tensor([encode(prompt)], device=device)\n", " with autocast_for(device):\n", " ids = generate(model, idx, SAMPLE_TOKENS, SAMPLE_T, SAMPLE_TOP_K, seed=k)[0].tolist()\n", " out.append({\"prompt\": prompt, \"text\": decode(ids)})\n", " model.train()\n", " return out\n", "\n", "\n", "def train(cfg, data_train, data_val, steps, batch, max_lr, warmup, eval_every, device, sample_steps=(),\n", " seed=SEED, clip=GRAD_CLIP, tag=\"run\", quiet=False, ckpt=None, eval_train_data=None):\n", " \"\"\"eval_train_data / data_val: the arrays the two fixed evaluation sets are cut from.\"\"\"\n", " torch.manual_seed(seed)\n", " model = GPT(cfg).to(device)\n", " decay = [p for n, p in model.named_parameters() if p.dim() >= 2]\n", " no_decay = [p for n, p in model.named_parameters() if p.dim() < 2]\n", " opt = torch.optim.AdamW([{\"params\": decay, \"weight_decay\": WEIGHT_DECAY}, {\"params\": no_decay, \"weight_decay\": 0.0}],\n", " lr=max_lr, betas=(0.9, 0.95))\n", " gen = torch.Generator().manual_seed(seed)\n", " ev_train = fixed_windows(eval_train_data if eval_train_data is not None else data_train, EVAL_WINDOWS, 11)\n", " ev_val = fixed_windows(data_val, EVAL_WINDOWS, 22)\n", " rows, samples, running = [], {}, []\n", " train_s = 0.0\n", " t_start = time.time()\n", " model.train()\n", " for step in range(steps + 1):\n", " if step % eval_every == 0 or step == steps:\n", " sync(device)\n", " row = {\"tag\": tag, \"step\": step, \"tokens_seen\": step * batch * T,\n", " \"lr\": lr_at(step, max_lr, warmup, steps) if step < steps else 0.0,\n", " \"train_batch_loss\": sum(running) / len(running) if running else float(\"nan\"),\n", " \"train_loss\": eval_loss(model, ev_train, device), \"val_loss\": eval_loss(model, ev_val, device),\n", " \"train_s\": round(train_s, 2), \"elapsed_s\": round(time.time() - t_start, 2), \"load_1min\": load_1min()}\n", " rows.append(row)\n", " running = []\n", " if ckpt:\n", " torch.save({\"model\": model.state_dict(), \"config\": asdict(cfg), \"step\": step, \"vocab_gpt2_ids\": used}, ckpt)\n", " if not quiet:\n", " print(f\"[{tag}] step {step:5d} lr {row['lr']:.2e} train {row['train_loss']:.4f} val {row['val_loss']:.4f}\"\n", " f\" ({row['elapsed_s']:5.0f} s)\")\n", " if step in sample_steps:\n", " samples[step] = sample_all(model, device)\n", " if step == steps:\n", " break\n", " t0 = time.time()\n", " lr = lr_at(step, max_lr, warmup, steps)\n", " for gparam in opt.param_groups:\n", " gparam[\"lr\"] = lr\n", " x, y = get_batch(data_train, batch, gen, device)\n", " with autocast_for(device):\n", " _, loss = model(x, y)\n", " opt.zero_grad(set_to_none=True)\n", " loss.backward()\n", " if clip:\n", " torch.nn.utils.clip_grad_norm_(model.parameters(), clip)\n", " opt.step()\n", " running.append(loss.item()) # .item() also waits for the device\n", " train_s += time.time() - t0\n", " return model, rows, samples" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · The schedule you will train with\n", "\n", "Before spending minutes of compute, look at the learning-rate schedule as numbers. It is a\n", "function of the step only, so it is the same on every machine." ], "id": "lab-3-3-tinygpt-10" }, { "cell_type": "code", "metadata": {}, "source": [ "sched_rows = []\n", "for name, s in SETTINGS.items():\n", " for step in sorted(set(list(range(0, s[\"steps\"] + 1, 10)) + [s[\"warmup\"] - 1, s[\"warmup\"], s[\"steps\"]])):\n", " sched_rows.append({\"setting\": name, \"step\": step, \"lr\": lr_at(step, s[\"max_lr\"], s[\"warmup\"], s[\"steps\"])})\n", "s = SETTINGS[SETTING]\n", "print(f\"{SETTING}: {s['steps']} steps x {s['batch']} windows x {T} tokens = {s['steps'] * s['batch'] * T:,} tokens \"\n", " f\"= {s['steps'] * s['batch'] * T / len(train_data):.2f} passes over the {len(train_data):,} training tokens\")\n", "for step in (0, s[\"warmup\"] - 1, s[\"warmup\"], s[\"steps\"] // 2, s[\"steps\"] - 1):\n", " print(f\" lr at step {step:5d}: {lr_at(step, s['max_lr'], s['warmup'], s['steps']):.3e}\")\n", "save_csv(\"lr-schedule.csv\", [\"setting\", \"step\", \"lr\"], sched_rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Measure: tokens per second on every device you have\n", "\n", "A short benchmark of the real training step (forward, backward, AdamW) on each device present:\n", "3 warm-up steps, then the mean of 10 timed steps. `GFLOP/s` is *estimated* with the usual\n", "formula, `6 × (matrix-product weights) + 12 × n_layer × d × T` operations per token (the second\n", "term is attention's scores and weighted sum), where the matrix-product weights are the blocks\n", "plus the output matrix `V × d`. Compare it with Lab 0.1's measured matmul speed: the gap is what\n", "everything that is *not* a big matrix product (softmax, LayerNorm, GELU, optimiser, Python\n", "overhead) costs. On CUDA we measure float32 and bfloat16." ], "id": "lab-3-3-tinygpt-12" }, { "cell_type": "code", "metadata": {}, "source": [ "def flops_per_token(c):\n", " n_mm = c.n_layer * (12 * c.d_model ** 2) + c.vocab_size * c.d_model\n", " return 6 * n_mm + 12 * c.n_layer * c.d_model * c.block_size\n", "\n", "\n", "def bench(device, batch, dtype, warmup_steps=3, timed_steps=10):\n", " torch.manual_seed(0)\n", " m = GPT(cfg).to(device)\n", " opt = torch.optim.AdamW(m.parameters(), lr=1e-4)\n", " gen = torch.Generator().manual_seed(0)\n", "\n", " def one_step():\n", " x, y = get_batch(train_data, batch, gen, device)\n", " ctx = torch.autocast(\"cuda\", dtype=torch.bfloat16) if dtype == \"bfloat16\" else nullcontext()\n", " with ctx:\n", " _, loss = m(x, y)\n", " opt.zero_grad(set_to_none=True)\n", " loss.backward()\n", " opt.step()\n", "\n", " for _ in range(warmup_steps):\n", " one_step()\n", " sync(device)\n", " t0 = time.time()\n", " for _ in range(timed_steps):\n", " one_step()\n", " sync(device)\n", " dt = (time.time() - t0) / timed_steps\n", " tps = batch * T / dt\n", " return {\"machine\": MACHINE, \"device\": device, \"dtype\": dtype, \"batch\": batch, \"ms_per_step\": round(dt * 1000, 1),\n", " \"tokens_per_s\": round(tps), \"gflops\": round(tps * flops_per_token(cfg) / 1e9), \"load_1min\": load_1min()}\n", "\n", "\n", "speed_rows = []\n", "for dev in DEVICES:\n", " for dtype in ([\"float32\", \"bfloat16\"] if dev == \"cuda\" else [\"float32\"]):\n", " for batch in ([16, 64] if dev == \"cuda\" else [16]):\n", " speed_rows.append(bench(dev, batch, dtype))\n", "print(f\"approximate training FLOPs per token: {flops_per_token(cfg):,.0f}\")\n", "print(f\"{'device':>6} {'dtype':>9} {'batch':>5} {'ms/step':>8} {'tokens/s':>9} {'GFLOP/s':>8} {'load':>6}\")\n", "for r in speed_rows:\n", " print(f\"{r['device']:>6} {r['dtype']:>9} {r['batch']:>5} {r['ms_per_step']:>8} {r['tokens_per_s']:>9,} {r['gflops']:>8,} {r['load_1min']:>6}\")\n", "SPEED_CSV = \"tokens-per-second.csv\" if DEVICE != \"cuda\" else \"tokens-per-second-cuda.csv\"\n", "save_csv(SPEED_CSV, [\"machine\", \"device\", \"dtype\", \"batch\", \"ms_per_step\", \"tokens_per_s\", \"gflops\", \"load_1min\"], speed_rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Train\n", "\n", "This is the run the chapter reads. It prints a line at every evaluation; the samples at the\n", "checkpoints are generated from three fixed prompts with temperature 0.8 and top-k 40, with fixed\n", "random seeds, and printed *unedited* a few cells further down.\n", "\n", "`quick`: about 13 minutes on an M1 CPU. `reference`: about 7 minutes on an RTX 3060. Do not\n", "interrupt it; the checkpoint on disk is the latest evaluation, not a resumable run." ], "id": "lab-3-3-tinygpt-14" }, { "cell_type": "code", "metadata": {}, "source": [ "cfg_dict = asdict(cfg)\n", "CKPT = cache_dir() / f\"tinygpt-{SETTING}.pt\"\n", "model, rows, samples = train(cfg, train_data, val_data, steps=s[\"steps\"], batch=s[\"batch\"], max_lr=s[\"max_lr\"],\n", " warmup=s[\"warmup\"], eval_every=s[\"eval_every\"], device=DEVICE,\n", " sample_steps=set(s[\"sample_steps\"]), tag=SETTING, ckpt=CKPT)\n", "for r in rows:\n", " r[\"machine\"] = MACHINE\n", " r[\"device\"] = DEVICE\n", "final = rows[-1]\n", "print(f\"\\nstep 0: train {rows[0]['train_loss']:.4f} val {rows[0]['val_loss']:.4f} (log V = {math.log(V):.4f})\")\n", "print(f\"final : train {final['train_loss']:.4f} val {final['val_loss']:.4f} gap {final['val_loss'] - final['train_loss']:+.4f} \"\n", " f\"perplexity {math.exp(final['val_loss']):.1f}\")\n", "tok = s[\"steps\"] * s[\"batch\"] * T\n", "print(f\"{tok:,} tokens in {final['train_s']:.0f} s of training steps = {tok / final['train_s']:,.0f} tokens/s \"\n", " f\"({final['elapsed_s']:.0f} s with evaluation and sampling)\")\n", "print(f\"best validation loss: {min(r['val_loss'] for r in rows):.4f} at step {min(rows, key=lambda r: r['val_loss'])['step']}\")\n", "fields = [\"tag\", \"machine\", \"device\", \"step\", \"tokens_seen\", \"lr\", \"train_batch_loss\", \"train_loss\", \"val_loss\", \"train_s\", \"elapsed_s\", \"load_1min\"]\n", "save_csv(f\"loss-curves-{SETTING}.csv\", fields, rows)" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The stories at each checkpoint\n", "\n", "Read them as a reader, not as a statistician. At step 0 the weights are random, so the model\n", "draws tokens almost uniformly: this is what `loss ≈ log V` looks like in text." ], "id": "lab-3-3-tinygpt-16" }, { "cell_type": "code", "metadata": {}, "source": [ "for step in sorted(samples):\n", " print(f\"=== step {step} ===\")\n", " for item in samples[step]:\n", " print(f\"[{item['prompt']}]\")\n", " print(item[\"text\"], \"\\n\")" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-17" }, { "cell_type": "code", "metadata": {}, "source": [ "update_json(\"samples.json\", SETTING, {\n", " \"machine\": MACHINE, \"device\": DEVICE, \"temperature\": SAMPLE_T, \"top_k\": SAMPLE_TOP_K, \"new_tokens\": SAMPLE_TOKENS,\n", " \"sample_seeds\": list(range(len(PROMPTS))),\n", " \"checkpoints\": {str(k): v for k, v in sorted(samples.items())}})\n", "update_json(\"config.json\", SETTING, {\n", " \"model\": cfg_dict, \"parameters\": count_params(model), \"tied_output\": True, \"seed\": SEED,\n", " \"data\": {\"source\": URL, \"bytes\": DATA_MB * 1_000_000, \"split\": \"random 98 % / 2 % of the stories (numpy seed 0)\", \"train_tokens\": int(len(train_data)),\n", " \"val_tokens\": int(len(val_data)), \"tokenizer\": \"tiktoken gpt2, remapped to the tokens that occur\"},\n", " \"training\": {**{k: v for k, v in s.items() if k != \"sample_steps\"}, \"optimizer\": \"AdamW\", \"betas\": [0.9, 0.95],\n", " \"weight_decay\": WEIGHT_DECAY, \"grad_clip\": GRAD_CLIP, \"min_lr_ratio\": MIN_LR_RATIO, \"context\": T,\n", " \"tokens_per_step\": s[\"batch\"] * T, \"eval_windows\": EVAL_WINDOWS,\n", " \"precision\": \"bfloat16 autocast\" if DEVICE == \"cuda\" else \"float32\"},\n", " \"machine\": MACHINE, \"device\": DEVICE, \"torch\": torch.__version__})\n", "if SETTING == \"reference\":\n", " (out_dir() / \"vocab.json\").write_text(json.dumps({\"description\": \"our token id -> GPT-2 (tiktoken gpt2) id\", \"gpt2_ids\": used}) + \"\\n\")\n", " ck = torch.load(CKPT, map_location=\"cpu\", weights_only=True)\n", " print(f\"checkpoint {CKPT} is {CKPT.stat().st_size / 1e6:.1f} MB (step {ck['step']})\")" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### How big is the gap, and is it noise?\n", "\n", "The two losses in the table are means over only 256 windows each. Before reading a difference\n", "between them, measure how much a mean over 256 windows wobbles: the standard error is the\n", "standard deviation of the per-window losses divided by `sqrt(256)`. Then evaluate on much more\n", "data: *every* non-overlapping window of the validation set, and 1,280 random training windows." ], "id": "lab-3-3-tinygpt-19" }, { "cell_type": "code", "metadata": {}, "source": [ "@torch.no_grad()\n", "def window_losses(model, xy, device, chunk=64):\n", " \"\"\"Mean loss of every window (one number per window).\"\"\"\n", " model.eval()\n", " x, y = xy\n", " out = []\n", " for i in range(0, len(x), chunk):\n", " with autocast_for(device):\n", " logits, _ = model(x[i:i + chunk].to(device))\n", " per_token = F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), y[i:i + chunk].to(device).reshape(-1), reduction=\"none\")\n", " out.append(per_token.view(-1, T).mean(1).cpu())\n", " model.train()\n", " return torch.cat(out)\n", "\n", "\n", "n_full = (len(val_data) - 1) // T\n", "full_val = (torch.from_numpy(np.stack([val_data[i * T:(i + 1) * T] for i in range(n_full)]).astype(np.int64)),\n", " torch.from_numpy(np.stack([val_data[i * T + 1:(i + 1) * T + 1] for i in range(n_full)]).astype(np.int64)))\n", "final_eval = []\n", "for name, xy in ((\"train, the 256 fixed windows of the table\", fixed_windows(train_data, EVAL_WINDOWS, 11)),\n", " (\"validation, the 256 fixed windows of the table\", fixed_windows(val_data, EVAL_WINDOWS, 22)),\n", " (\"train, 1,280 random windows\", fixed_windows(train_data, 1280, 33)),\n", " (f\"validation, all {n_full:,} windows\", full_val)):\n", " wl = window_losses(model, xy, DEVICE)\n", " final_eval.append({\"set\": name, \"windows\": len(wl), \"mean_loss\": float(wl.mean()), \"std_of_window_losses\": float(wl.std()),\n", " \"standard_error\": float(wl.std() / math.sqrt(len(wl)))})\n", " print(f\"{name:>48}: {len(wl):5d} windows loss {final_eval[-1]['mean_loss']:.4f} +- {final_eval[-1]['standard_error']:.4f}\")\n", "save_csv(f\"final-eval-{SETTING}.csv\", list(final_eval[0]), final_eval)" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The two curves\n", "\n", "Plot train and validation loss against the step, with the reference line `log V` and the loss\n", "of a model that predicts every token from frequency alone (the *unigram* loss, Lab 2.2)." ], "id": "lab-3-3-tinygpt-21" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib\n", " matplotlib.use(\"Agg\")\n", " import matplotlib.pyplot as plt\n", " counts = np.bincount(train_data, minlength=V) + 1.0\n", " p_uni = counts / counts.sum()\n", " uni_val = float(-np.log(p_uni[val_data]).mean())\n", " fig, ax = plt.subplots(figsize=(6, 3.5))\n", " ax.plot([r[\"step\"] for r in rows], [r[\"train_loss\"] for r in rows], label=\"train\", marker=\"o\", ms=3)\n", " ax.plot([r[\"step\"] for r in rows], [r[\"val_loss\"] for r in rows], label=\"validation\", marker=\"s\", ms=3)\n", " ax.axhline(math.log(V), color=\"grey\", ls=\":\", label=f\"log V = {math.log(V):.2f}\")\n", " ax.axhline(uni_val, color=\"grey\", ls=\"--\", label=f\"unigram = {uni_val:.2f}\")\n", " ax.set_xlabel(\"step\")\n", " ax.set_ylabel(\"loss (nats per token)\")\n", " ax.set_ylim(0, math.log(V) + 0.5)\n", " ax.legend()\n", " fig.tight_layout()\n", " fig.savefig(cache_dir() / f\"loss-{SETTING}.png\", dpi=120)\n", " print(f\"unigram (no context) validation loss: {uni_val:.4f}\")\n", "except ImportError:\n", " print(\"matplotlib not installed; the CSV has the curves\")" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Generate with your own prompt\n", "\n", "`temperature` flattens (`> 1`) or sharpens (`< 1`) the distribution before sampling; `top_k` keeps\n", "only the `k` most likely tokens (`top_k = 1` always takes the most likely one) (Ch 2.3). Change them\n", "and the prompt, and run it several times with different `seed` values." ], "id": "lab-3-3-tinygpt-23" }, { "cell_type": "code", "metadata": {}, "source": [ "def tell(prompt, tokens=80, temperature=0.8, top_k=40, seed=0):\n", " idx = torch.tensor([encode(prompt)], device=DEVICE)\n", " with autocast_for(DEVICE):\n", " return decode(generate(model, idx, tokens, temperature, top_k, seed)[0].tolist())\n", "\n", "for temperature, top_k in ((0.3, 40), (0.8, 40), (1.5, 40), (0.8, 1)):\n", " print(f\"--- temperature {temperature}, top_k {top_k}\")\n", " print(tell(\"One day, a girl named Mia found a\", temperature=temperature, top_k=top_k))" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Checkpoint\n", "\n", "Compare with your own run (the last digit changes with the PyTorch version and the hardware, the\n", "first digits should not):\n", "\n", "- the parameter count equals the formula, and the step-zero loss is close to `log V`;\n", "- the library attention and the hand-written attention differ by about `1e-7` or less, and changing\n", " token 100 changes no logit before position 100;\n", "- validation loss falls from about `log V` to well below the unigram line, and the validation\n", " and training curves stay close together (compare their difference with the standard errors above);\n", "- at step 0 the samples are random tokens, at the last checkpoint they are sentences with\n", " names, places and punctuation in plausible order." ], "id": "lab-3-3-tinygpt-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Explore\n", "\n", "Change one thing at a time and write one sentence each: *what changed, and why*. Use `quick`.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| Model size | `GPTConfig(V, n_layer=2, d_model=64)` and `n_layer=6, d_model=192` | How do the parameter count and the tokens per second change? Does validation loss at the same step count improve? |\n", "| Context length | `block_size=64` and `block_size=512` | What happens to the speed? Does the model lose anything on stories that are longer than the context? |\n", "| Steps | `steps = 150` and `1500` (keep `warmup` and the schedule in proportion) | Where does validation loss stop improving as fast as training loss? |\n", "| Learning rate | `max_lr = 5e-4` and `4e-3` | Which learns faster early? Which ends lower? Does it depend on the number of steps? |\n", "| Sampling | `temperature = 0.2, 0.8, 1.5`, `top_k = 1, 40, 0` | Which setting repeats itself? Which writes nonsense? Which would you use for a story, and which for a fact? |\n", "| Dropout | `dropout=0.1` | Does training loss go up? Validation loss? Why might a model with a tiny dataset want it, and why does one with lots of data not? |" ], "id": "lab-3-3-tinygpt-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10 · Failure playground\n", "\n", "Each cell below runs a short, pre-broken training. Give the symptom, find the cause, then fix it.\n", "The questions are under each cell; the answers are not here." ], "id": "lab-3-3-tinygpt-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 10a · The learning rate is far too high\n", "\n", "A colleague \"speeds things up\" by multiplying `max_lr` by 10, another by 100. Same model, same\n", "data, 200 steps of batch 8 with a short warm-up: the rate you used above, 10× and 100× that\n", "rate, and 100× with gradient clipping turned off." ], "id": "lab-3-3-tinygpt-28" }, { "cell_type": "code", "metadata": {}, "source": [ "mini = dict(steps=200, batch=8, warmup=10, eval_every=50, device=DEVICE)\n", "pg_a = []\n", "for label, mult, clip in ((\"good lr\", 1, GRAD_CLIP), (\"10x lr\", 10, GRAD_CLIP), (\"100x lr\", 100, GRAD_CLIP), (\"100x lr, no clipping\", 100, 0)):\n", " _, r, _ = train(cfg, train_data, val_data, max_lr=mult * s[\"max_lr\"], clip=clip, tag=label, quiet=True, **mini)\n", " pg_a += [{\"run\": label, \"max_lr\": mult * s[\"max_lr\"], \"clip\": clip, \"step\": x[\"step\"], \"val_loss\": x[\"val_loss\"]} for x in r]\n", " print(f\"{label:>22}: val loss at steps {', '.join(str(x['step']) for x in r)}: \" + \" \".join(f\"{x['val_loss']:.2f}\" for x in r))\n", "save_csv(\"failure-lr.csv\", [\"run\", \"max_lr\", \"clip\", \"step\", \"val_loss\"], pg_a)" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: nothing crashes and no loss is `nan`, but the high-rate runs end far above the healthy\n", "run, and the worst ones stop improving. Compare their final loss with the *unigram* loss printed\n", "further up (a model that ignores all context). What does a loss close to that value say about what\n", "the model has learned? Where in the curve is the damage done: at the start, or later?\n", "What did gradient clipping change, and why is it not a licence to raise the rate? What would you\n", "look at first in a real run (the curve, the gradient norm, the weights)?\n", "\n", "### 10b · Validating on the training data\n", "\n", "A tiny slice (about 50,000 tokens) is used for training. We evaluate the same model on windows cut\n", "from the same slice (what a careless \"validation set\" would be) and on stories it never saw. 600\n", "steps of batch 8 is about 25 passes over the slice." ], "id": "lab-3-3-tinygpt-30" }, { "cell_type": "code", "metadata": {}, "source": [ "tiny = train_data[:50_000]\n", "_, r, _ = train(cfg, tiny, val_data, steps=600, batch=8, max_lr=s[\"max_lr\"], warmup=20, eval_every=100,\n", " device=DEVICE, tag=\"tiny\", quiet=True, eval_train_data=tiny)\n", "# \"train_loss\" is measured on windows of the tiny slice (what you see if you validate on the training\n", "# data); \"val_loss\" on stories the model never saw (what you should look at).\n", "pg_b = [{\"step\": a[\"step\"], \"loss_on_training_slice\": a[\"train_loss\"], \"loss_on_unseen_stories\": a[\"val_loss\"]} for a in r]\n", "print(f\"{'step':>5} {'training slice':>15} {'unseen stories':>15}\")\n", "for x in pg_b:\n", " print(f\"{x['step']:>5} {x['loss_on_training_slice']:>15.4f} {x['loss_on_unseen_stories']:>15.4f}\")\n", "save_csv(\"failure-same-data.csv\", list(pg_b[0]), pg_b)" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-31" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: if you \"validate\" on the training slice, the loss keeps falling and looks excellent, while\n", "the writing of the model on new prompts does not get better. Which column would you be reading?\n", "At which step do the two columns part ways, and what does the second do after that? What does\n", "\"validation set\" have to mean for the number to be worth anything?" ], "id": "lab-3-3-tinygpt-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 10c · Generating without `no_grad` (and without `eval()`)\n", "\n", "Generation forgets `@torch.no_grad()`. Nothing crashes. We measure what the library does behind\n", "your back: the time of one full-context forward pass and the number of bytes PyTorch keeps for a\n", "backward pass that will never come. A second model with `dropout = 0.2` shows what forgetting\n", "`model.eval()` does." ], "id": "lab-3-3-tinygpt-33" }, { "cell_type": "code", "metadata": {}, "source": [ "def forward_stats(grad):\n", " x = torch.randint(0, V, (1, T), device=DEVICE)\n", " saved = [0]\n", "\n", " def pack(t):\n", " saved[0] += t.numel() * t.element_size()\n", " return t\n", "\n", " ctx = nullcontext() if grad else torch.no_grad()\n", " model.eval()\n", " with ctx, torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):\n", " model(x) # warm-up\n", " saved[0] = 0\n", " sync(DEVICE)\n", " t0 = time.time()\n", " for _ in range(10):\n", " saved[0] = 0\n", " model(x)\n", " sync(DEVICE)\n", " return (time.time() - t0) / 10 * 1000, saved[0] / 1e6\n", "\n", "\n", "ms_g, mb_g = forward_stats(grad=True)\n", "ms_n, mb_n = forward_stats(grad=False)\n", "print(f\"one forward pass of 1 x {T} tokens: with autograd {ms_g:.1f} ms, keeps {mb_g:.1f} MB for backward;\"\n", " f\" under no_grad {ms_n:.1f} ms, keeps {mb_n:.1f} MB\")\n", "\n", "\n", "def generate_slow(model, idx, n): # generate() without the decorator\n", " for _ in range(n):\n", " logits, _ = model(idx[:, -T:])\n", " idx = torch.cat([idx, logits[:, -1:, :].argmax(-1)], dim=1)\n", " return idx\n", "\n", "\n", "prompt_ids = torch.tensor([encode(PROMPTS[0])], device=DEVICE)\n", "sync(DEVICE)\n", "t0 = time.time()\n", "generate_slow(model, prompt_ids, 40)\n", "sync(DEVICE)\n", "t_slow = time.time() - t0\n", "t0 = time.time()\n", "with torch.no_grad():\n", " generate_slow(model, prompt_ids, 40)\n", "sync(DEVICE)\n", "t_fast = time.time() - t0\n", "print(f\"40 greedy tokens: without no_grad {t_slow:.2f} s, with no_grad {t_fast:.2f} s ({t_slow / t_fast:.2f}x)\")\n", "\n", "drop_model = GPT(GPTConfig(vocab_size=V, dropout=0.2)).to(DEVICE)\n", "xs = torch.randint(0, V, (1, 32), device=DEVICE)\n", "with torch.no_grad():\n", " drop_model.train()\n", " a1, a2 = drop_model(xs)[0], drop_model(xs)[0]\n", " drop_model.eval()\n", " b1, b2 = drop_model(xs)[0], drop_model(xs)[0]\n", "print(f\"same input twice, dropout 0.2: train mode differs by {(a1 - a2).abs().max().item():.3f}, eval mode by {(b1 - b2).abs().max().item():.3f}\")\n", "save_csv(\"failure-no-grad.csv\", [\"case\", \"ms_per_forward\", \"mb_kept_for_backward\"],\n", " [{\"case\": \"autograd on\", \"ms_per_forward\": round(ms_g, 1), \"mb_kept_for_backward\": round(mb_g, 1)},\n", " {\"case\": \"no_grad\", \"ms_per_forward\": round(ms_n, 1), \"mb_kept_for_backward\": round(mb_n, 1)}])" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-34" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: generation works but is slower than it should be and the process uses more memory.\n", "Where does the extra memory go, and how does it scale with the context length and the number of\n", "layers? In the first model `model.eval()` changed nothing; in the second it changed the output.\n", "Which layers in a network behave differently in train and eval mode, and what would a chat\n", "service sampling at `dropout = 0.2` in train mode look like to a user?" ], "id": "lab-3-3-tinygpt-35" }, { "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\"{MACHINE} ({DEVICE}), setting {SETTING}\")" ], "execution_count": null, "outputs": [], "id": "lab-3-3-tinygpt-36" } ] }