{ "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 5.2 · A Scaling Law of Your Own\n", "\n", "**Goal:** train the Lab 3.3 GPT at six sizes, each for the same number of tokens, record the\n", "final validation loss, fit a straight line to the points on log-log axes with plain least\n", "squares, use that line to predict the loss of a size you have not trained yet, then train that\n", "size and see how wrong you were. On the way you check the `6 · N · D` rule against a real FLOP\n", "count, test what \"tokens per parameter\" means on your own grid of runs, and break the method\n", "three ways.\n", "\n", "**Runs on:** two settings. `reference` (the book's numbers): about 40 minutes of an RTX 3060 for\n", "the whole grid of 43 training runs. `quick`: a smaller sweep for a laptop CPU, five tiny sizes\n", "and a short context; the notebook prints how long it expects to take before it starts. Choose\n", "with `SCALING_SETTING` (`quick`, the default, or `reference`) and the device with\n", "`TINYGPT_DEVICE` (`cpu`, `mps`, `cuda`; default: the fastest one present). Install with\n", "`uv run --with torch --with tiktoken --with matplotlib jupyter lab`. The notebook downloads 120 MB\n", "of TinyStories itself (needs internet once), exactly like Lab 3.3.\n", "\n", "**Versions tested:** printed by the last cell.\n", "\n", "The model, the data and the training loop are Lab 3.3's, copied here so that this notebook runs\n", "on its own: the same GPT (tied output layer, pre-LayerNorm blocks), the same TinyStories slice\n", "(random 98 % / 2 % split of the stories, GPT-2 tokens renumbered to the ones that occur, `V = 19,040`),\n", "the same AdamW and cosine schedule. What changes is the *size* of the model and the *length*\n", "of the run. The cells that you do not need to read twice are marked \"same as Lab 3.3\"." ], "id": "lab-5-2-scaling-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 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(\"SCALING_SETTING\", \"quick\")\n", "assert SETTING in (\"quick\", \"reference\"), \"SCALING_SETTING must be quick or reference\"\n", "SMOKE = os.environ.get(\"SCALING_SMOKE\") == \"1\" # a 2-step dry run: checks the code, not the science\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}{' (SMOKE TEST)' if SMOKE else ''} | 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 out_dir():\n", " if SMOKE: # a dry run never touches the real CSVs\n", " d = pathlib.Path(\".work\") / \"smoke\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " for candidate in (pathlib.Path(\"data\"), pathlib.Path(\"../data\")):\n", " if candidate.is_dir():\n", " d = candidate / \"lab-5-2-scaling\"\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", " if SETTING == \"quick\": # the two settings never overwrite each other's files\n", " name = name.replace(\".csv\", \"-quick.csv\")\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-5-2-scaling-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your answers before running anything.\n", "\n", "1. **The 6.** A transformer's training step does, per token, a forward pass, a backward pass\n", " and an optimiser update. Ch 1.2 said the backward pass costs about twice the forward pass.\n", " If the forward pass of one weight costs 2 operations per token (one multiply, one add),\n", " how many operations per weight per token does a training step cost? Then: for `N`\n", " weights and `D` training tokens, what is the compute `C`?\n", "2. **Counting `N`.** One block has `12d² + 13d` weights (Lab 3.3). A model with `d = 64` and\n", " 2 blocks has how many *block* weights? The vocabulary here is `V = 19,040`: how many\n", " weights does the token embedding (which is also the output layer) add? Which is bigger?\n", " What does that do to `6 · N · D` if `N` counts only the block weights?\n", "3. **The line.** You will train six sizes for the same `D` and plot validation loss against\n", " `N` on log-log axes. If doubling `N` lowers the loss by 8 %, what is the slope of the\n", " straight line, as a number (`log` of the loss ratio over `log` of 2)?\n", "4. **Where it bends.** Do you expect the points to stay on one straight line from 0.1 million\n", " to 10 million weights when `D` is the same for all sizes? Which end of the line do you\n", " expect to bend first, and why? (Hint: what limits the *small* model, and what limits the\n", " *big* one when the data is the same?)\n", "5. **The prediction.** Name the size ratio at which you would still trust a prediction made\n", " from the five smaller sizes: 2x, 10x or 100x beyond the largest you trained?\n", "\n", "## 2 · The data (same as Lab 3.3)\n", "\n", "The first 120 MB of the TinyStories training file, cut into GPT-2 tokens, a random 98 % of the\n", "stories for training and the other 2 % for validation, tokens renumbered to the `V = 19,040`\n", "that occur. If you have run Lab 3.3 in this folder, the files are already in `.work/` and\n", "nothing is downloaded." ], "id": "lab-5-2-scaling-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", "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", " if not RAW.exists():\n", " req = urllib.request.Request(URL, headers={\"Range\": f\"bytes=0-{DATA_MB * 1_000_000 - 1}\"})\n", " with urllib.request.urlopen(req, timeout=300) as r:\n", " RAW.write_bytes(r.read())\n", " text = RAW.read_bytes().decode(\"utf-8\", errors=\"ignore\")\n", " stories = [s.strip() for s in text.split(\"<|endoftext|>\")][:-1] # 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", "V = len(meta[\"gpt2_ids\"])\n", "print(f\"train tokens {len(train_data):,} validation tokens {len(val_data):,} vocabulary used V = {V:,} (of 50,257)\")\n", "print(f\"log V = {math.log(V):.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · The model (same as Lab 3.3), now with a size knob\n", "\n", "Same GPT as Lab 3.3. The only new thing is how a size is described: a pair `(d_model, n_layer)`,\n", "with the number of heads set so that every head is 32 numbers wide (`n_head = d_model / 32`, but at\n", "least 2). Two ways of counting its weights matter in this lab:\n", "\n", "- `N`, the **non-embedding** parameters: the weights inside the blocks, `L · (12d² + 13d)`.\n", " This is what Kaplan et al. (2020) count, and it is the `N` of `6 · N · D`.\n", "- `N_total`, all weights, including the token embedding (`V · d`, shared with the output layer),\n", " the position embedding (`T · d`) and the last LayerNorm.\n", "\n", "With `V = 19,040` the embedding is huge next to a small model. Keep an eye on it." ], "id": "lab-5-2-scaling-04" }, { "cell_type": "code", "metadata": {}, "source": [ "@dataclass\n", "class GPTConfig:\n", " vocab_size: int\n", " block_size: int = 256\n", " n_layer: int = 4\n", " n_head: int = 4\n", " d_model: int = 128\n", " dropout: float = 0.0\n", "\n", "\n", "class CausalSelfAttention(nn.Module):\n", " def __init__(self, c):\n", " super().__init__()\n", " self.n_head = c.n_head\n", " self.qkv = nn.Linear(c.d_model, 3 * c.d_model)\n", " self.proj = nn.Linear(c.d_model, c.d_model)\n", " self.drop = nn.Dropout(c.dropout)\n", "\n", " def forward(self, x):\n", " B, T, C = x.shape\n", " q, k, v = self.qkv(x).split(C, dim=2)\n", " q, k, v = (t.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) for t in (q, k, v))\n", " y = F.scaled_dot_product_attention(q, k, v, is_causal=True)\n", " return self.drop(self.proj(y.transpose(1, 2).reshape(B, T, C)))\n", "\n", "\n", "class Block(nn.Module):\n", " def __init__(self, c):\n", " super().__init__()\n", " self.ln1, self.attn = nn.LayerNorm(c.d_model), CausalSelfAttention(c)\n", " self.ln2 = nn.LayerNorm(c.d_model)\n", " self.mlp = nn.Sequential(nn.Linear(c.d_model, 4 * c.d_model), nn.GELU(),\n", " nn.Linear(4 * c.d_model, c.d_model), nn.Dropout(c.dropout))\n", "\n", " def forward(self, x):\n", " x = x + self.attn(self.ln1(x))\n", " return x + self.mlp(self.ln2(x))\n", "\n", "\n", "class GPT(nn.Module):\n", " def __init__(self, c):\n", " super().__init__()\n", " self.c = c\n", " self.wte = nn.Embedding(c.vocab_size, c.d_model)\n", " self.wpe = nn.Embedding(c.block_size, c.d_model)\n", " self.drop = nn.Dropout(c.dropout)\n", " self.blocks = nn.ModuleList([Block(c) for _ in range(c.n_layer)])\n", " self.ln_f = nn.LayerNorm(c.d_model)\n", " self.lm_head = nn.Linear(c.d_model, c.vocab_size, bias=False)\n", " self.lm_head.weight = self.wte.weight # weight tying: one matrix, two jobs\n", " self.apply(self._init)\n", " for name, p in self.named_parameters():\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):\n", " B, T = idx.shape\n", " x = self.drop(self.wte(idx) + self.wpe(torch.arange(T, device=idx.device)))\n", " for block in self.blocks:\n", " x = block(x)\n", " logits = self.lm_head(self.ln_f(x))\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", "def count_params(model):\n", " return sum(p.numel() for p in model.parameters()) # tied weights are counted once\n", "\n", "\n", "def config_for(d, n_layer, T):\n", " return GPTConfig(vocab_size=V, block_size=T, n_layer=n_layer, n_head=max(2, d // 32), d_model=d)\n", "\n", "\n", "def n_nonembedding(d, n_layer):\n", " return n_layer * (12 * d * d + 13 * d)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · The sweep: sizes, budgets, learning rates\n", "\n", "Every run uses the same recipe as Lab 3.3: AdamW, `betas = (0.9, 0.95)`, weight decay 0.1 on\n", "matrices, gradient clipping at 1.0, linear warm-up then cosine decay to a tenth of the peak.\n", "The cosine decay always ends exactly at the last step, so **each token budget is its own run**:\n", "you cannot read \"the loss after fewer tokens\" off the middle of a longer run (Ch 5.2 explains why).\n", "\n", "- `SIZES`: the sizes you fit. `TEST`: the size you hold back and predict.\n", "- `FRACTIONS`: token budgets as fractions of the full budget `D`. The main sweep uses the full\n", " budget (`D`) for every size. The other fractions are used for the learning-rate probe and for\n", " the \"tokens per parameter\" grid in section 8.\n", "- **Learning rate.** A fixed learning rate would favour some sizes: small models like a larger\n", " one. So for every size the notebook first tries several peak rates on the shortest budget\n", " and keeps the best one for the longer runs. This is an honest cost: it is a few percent\n", " extra compute, and it is not perfect (the best rate for a short run need not be the best\n", " for a long one).\n", "- **Seeds.** The full-budget runs are repeated with a second seed. The gap between the two\n", " seeds is the noise floor of the whole experiment: a difference between sizes smaller than\n", " that tells you nothing.\n", "- **Evaluation.** The final validation loss is measured on non-overlapping windows covering the\n", " validation set (the same windows for every run), not on a sample." ], "id": "lab-5-2-scaling-06" }, { "cell_type": "code", "metadata": {}, "source": [ "REFERENCE = dict(T=256, batch=64, base_steps=1500, fractions=[0.25, 0.5, 1.0],\n", " lrs=[1e-3, 2e-3, 4e-3, 8e-3], seeds=[1337, 1338],\n", " sizes=[(64, 2), (96, 3), (128, 4), (192, 5), (256, 6)], test=(320, 8), eval_windows=None)\n", "QUICK = dict(T=128, batch=16, base_steps=500, fractions=[0.25, 1.0],\n", " lrs=[3e-3], seeds=[1337],\n", " sizes=[(32, 2), (48, 2), (64, 2), (96, 2)], test=(128, 3), eval_windows=600)\n", "CFG = REFERENCE if SETTING == \"reference\" else QUICK\n", "T, BATCH = CFG[\"T\"], CFG[\"batch\"]\n", "if SMOKE:\n", " CFG = dict(CFG, base_steps=8, fractions=[0.25, 1.0], lrs=CFG[\"lrs\"][:1], seeds=CFG[\"seeds\"][:1], eval_windows=16)\n", "STEPS_FULL = CFG[\"base_steps\"]\n", "D_FULL = STEPS_FULL * BATCH * T # tokens in the full budget\n", "ALL_SIZES = CFG[\"sizes\"] + [CFG[\"test\"]]\n", "WEIGHT_DECAY, GRAD_CLIP, MIN_LR_RATIO = 0.1, 1.0, 0.1\n", "\n", "print(f\"context T = {T}, batch = {BATCH} windows = {BATCH * T:,} tokens per step\")\n", "print(f\"full budget D = {STEPS_FULL} steps = {D_FULL:,} tokens = {D_FULL / len(train_data):.2f} passes over the training set\")\n", "print(f\"{'size (d, L)':>12} {'N (blocks)':>12} {'N_total':>12} {'6·N·D (FLOP)':>14}\")\n", "for d_, L_ in ALL_SIZES:\n", " m_ = GPT(config_for(d_, L_, T))\n", " print(f\"{f'({d_}, {L_})':>12} {n_nonembedding(d_, L_):>12,} {count_params(m_):>12,} {6 * n_nonembedding(d_, L_) * D_FULL:>14.3e}\")\n", " assert count_params(m_) == V * d_ + T * d_ + n_nonembedding(d_, L_) + 2 * d_\n", "del m_" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Where do the FLOPs go? Checking `6 · N · D`\n", "\n", "`6 · N · D` is a rule of thumb. Before we build a law on it, count the real thing:\n", "PyTorch's `FlopCounterMode` counts the operations of every matrix product in one forward and\n", "backward pass (`2·m·n·k` for an `m×k` times `k×n` product, attention included). We compare it\n", "per token with four candidates: `6 N` (blocks only), `6 (N + V·d)` (add the output matrix, a\n", "real matrix product), and the same plus the attention scores `12 · L · d · T`." ], "id": "lab-5-2-scaling-08" }, { "cell_type": "code", "metadata": {}, "source": [ "from torch.utils.flop_counter import FlopCounterMode\n", "\n", "\n", "def counted_flops_per_token(d, n_layer):\n", " torch.manual_seed(0)\n", " m = GPT(config_for(d, n_layer, T))\n", " x = torch.randint(0, V, (2, T))\n", " with FlopCounterMode(display=False) as fc:\n", " _, loss = m(x, x)\n", " loss.backward()\n", " return fc.get_total_flops() / (2 * T)\n", "\n", "\n", "flop_rows = []\n", "COUNTED = {}\n", "print(f\"{'size':>10} {'counted':>12} {'6N':>12} {'6(N+Vd)':>12} {'+attention':>12} {'counted / 6N':>13}\")\n", "for d_, L_ in ALL_SIZES:\n", " n_ = n_nonembedding(d_, L_)\n", " counted = counted_flops_per_token(d_, L_)\n", " COUNTED[(d_, L_)] = counted\n", " six_n, six_nv = 6 * n_, 6 * (n_ + V * d_)\n", " full = six_nv + 12 * L_ * d_ * T\n", " flop_rows.append({\"d_model\": d_, \"n_layer\": L_, \"n_blocks\": n_, \"counted_per_token\": counted, \"six_n\": six_n,\n", " \"six_n_plus_head\": six_nv, \"six_n_plus_head_plus_attention\": full,\n", " \"counted_over_six_n\": round(counted / six_n, 4)})\n", " print(f\"{f'({d_}, {L_})':>10} {counted:>12,.0f} {six_n:>12,} {six_nv:>12,} {full:>12,} {counted / six_n:>13.2f}\")\n", "save_csv(\"flop-check.csv\", list(flop_rows[0]), flop_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Build: one training run, as a function\n", "\n", "`train_run(d, n_layer, steps, lr, seed)` builds the model from the same seed, trains for\n", "`steps` steps and returns the numbers a scaling study needs: the final validation loss on the\n", "whole validation set, the training loss on 256 fixed training windows, the number of tokens\n", "seen and the time. Results are appended to a CSV as they arrive, and a run that is already in\n", "the CSV is skipped, so a crashed or interrupted sweep resumes where it stopped." ], "id": "lab-5-2-scaling-10" }, { "cell_type": "code", "metadata": {}, "source": [ "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", "def lr_at(step, max_lr, warmup, total):\n", " if step < warmup:\n", " return max_lr * (step + 1) / warmup\n", " p = min(1.0, (step - warmup) / max(1, total - warmup))\n", " return max_lr * (MIN_LR_RATIO + (1 - MIN_LR_RATIO) * 0.5 * (1 + math.cos(math.pi * p)))\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 eval_windows(data, n=None, seed=22):\n", " \"\"\"n=None: every non-overlapping window of the set; else n random windows with a fixed seed.\"\"\"\n", " if n is None:\n", " starts = np.arange(0, len(data) - T - 1, T)\n", " else:\n", " g = torch.Generator().manual_seed(seed)\n", " starts = torch.randint(0, len(data) - T - 1, (n,), generator=g).numpy()\n", " x = torch.from_numpy(np.stack([data[i:i + T] for i in starts]).astype(np.int64))\n", " y = torch.from_numpy(np.stack([data[i + 1:i + 1 + T] for i in starts]).astype(np.int64))\n", " return x, y\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", "EV_VAL = eval_windows(val_data, CFG[\"eval_windows\"])\n", "EV_TRAIN = eval_windows(train_data, 256, seed=11)\n", "print(f\"validation windows: {len(EV_VAL[0]):,} of {T} tokens = {len(EV_VAL[0]) * T:,} tokens (all of the validation set when not reduced)\")\n", "\n", "RUN_FIELDS = [\"setting\", \"d_model\", \"n_layer\", \"n_head\", \"n_blocks\", \"n_total\", \"steps\", \"batch\", \"context\", \"tokens_D\",\n", " \"fraction\", \"max_lr\", \"seed\", \"flops_6nd\", \"val_loss\", \"train_loss\", \"diverged\", \"train_s\", \"tokens_per_s\",\n", " \"device\", \"machine\"]\n", "RUNS_CSV = out_dir() / f\"runs-{SETTING}.csv\"\n", "\n", "\n", "def load_runs():\n", " if RUNS_CSV.exists():\n", " with RUNS_CSV.open() as f:\n", " return list(csv.DictReader(f))\n", " return []\n", "\n", "\n", "def run_key(d, n_layer, steps, lr, seed):\n", " return (int(d), int(n_layer), int(steps), f\"{float(lr):.0e}\", int(seed))\n", "\n", "\n", "def train_run(d, n_layer, steps, lr, seed, device=DEVICE):\n", " cached = {run_key(r[\"d_model\"], r[\"n_layer\"], r[\"steps\"], r[\"max_lr\"], r[\"seed\"]): r for r in load_runs()}\n", " key = run_key(d, n_layer, steps, lr, seed)\n", " if key in cached:\n", " return {k: (float(v) if k in (\"val_loss\", \"train_loss\") else v) for k, v in cached[key].items()}\n", " torch.manual_seed(seed)\n", " cfg = config_for(d, n_layer, T)\n", " model = GPT(cfg).to(device)\n", " decay = [p for p in model.parameters() if p.dim() >= 2]\n", " no_decay = [p for p in model.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=lr, betas=(0.9, 0.95))\n", " gen = torch.Generator().manual_seed(seed)\n", " warmup = max(10, int(0.04 * steps))\n", " diverged = False\n", " sync(device)\n", " t0 = time.time()\n", " for step in range(steps):\n", " for g in opt.param_groups:\n", " g[\"lr\"] = lr_at(step, lr, warmup, steps)\n", " x, y = get_batch(train_data, 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", " torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)\n", " opt.step()\n", " if step % 50 == 0 and not math.isfinite(loss.item()):\n", " diverged = True\n", " break\n", " sync(device)\n", " train_s = time.time() - t0\n", " val = eval_loss(model, EV_VAL, device)\n", " trn = eval_loss(model, EV_TRAIN, device)\n", " n_ = n_nonembedding(d, n_layer)\n", " tokens = steps * BATCH * T\n", " row = {\"setting\": SETTING, \"d_model\": d, \"n_layer\": n_layer, \"n_head\": cfg.n_head, \"n_blocks\": n_, \"n_total\": count_params(model),\n", " \"steps\": steps, \"batch\": BATCH, \"context\": T, \"tokens_D\": tokens, \"fraction\": round(steps / STEPS_FULL, 4),\n", " \"max_lr\": f\"{lr:.0e}\", \"seed\": seed, \"flops_6nd\": 6 * n_ * tokens, \"val_loss\": round(val, 5) if math.isfinite(val) else \"nan\",\n", " \"train_loss\": round(trn, 5) if math.isfinite(trn) else \"nan\", \"diverged\": int(diverged or not math.isfinite(val)),\n", " \"train_s\": round(train_s, 1), \"tokens_per_s\": round(tokens / train_s), \"device\": device, \"machine\": MACHINE}\n", " new = not RUNS_CSV.exists()\n", " with RUNS_CSV.open(\"a\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=RUN_FIELDS, lineterminator=\"\\n\")\n", " if new:\n", " w.writeheader()\n", " w.writerow(row)\n", " print(f\" ({d:3d},{n_layer}) steps {steps:5d} lr {lr:.0e} seed {seed}: val {val:.4f} train {trn:.4f} {train_s:6.1f} s {tokens / train_s:,.0f} tok/s\")\n", " return {**row, \"val_loss\": val, \"train_loss\": trn}" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Check the run function once\n", "\n", "Before the sweep, one cheap run: a few steps of the smallest size must start near `log V`\n", "(Lab 3.3) and a longer run must end well below it. A sweep built on a broken run function\n", "would produce a beautiful, wrong line." ], "id": "lab-5-2-scaling-12" }, { "cell_type": "code", "metadata": {}, "source": [ "d0, L0 = CFG[\"sizes\"][0]\n", "probe_steps = 40 if not SMOKE else 4\n", "t_chk = time.time()\n", "quick_check = train_run(d0, L0, probe_steps, CFG[\"lrs\"][0], 0)\n", "print(f\"{probe_steps} steps of ({d0}, {L0}): val loss {quick_check['val_loss']:.4f} (log V = {math.log(V):.4f}) \"\n", " f\"{time.time() - t_chk:.1f} s\")\n", "assert quick_check[\"val_loss\"] < math.log(V), \"a trained model must beat the uniform guess\"" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Learning-rate probe\n", "\n", "For each size, the shortest budget (a quarter of `D`) with each candidate peak learning rate.\n", "The best one per size is used for all longer runs of that size. A rate at the edge of the\n", "range (the smallest or the largest) means the true optimum may lie outside it: the notebook says so." ], "id": "lab-5-2-scaling-14" }, { "cell_type": "code", "metadata": {}, "source": [ "FR = CFG[\"fractions\"]\n", "steps_of = {f: max(2, int(round(STEPS_FULL * f))) for f in FR}\n", "probe_f = FR[0]\n", "print(f\"learning-rate probe: {len(CFG['lrs'])} rates x {len(ALL_SIZES)} sizes x {steps_of[probe_f]} steps\")\n", "best_lr = {}\n", "probe_rows = []\n", "for d_, L_ in ALL_SIZES:\n", " results = []\n", " for lr in CFG[\"lrs\"]:\n", " r = train_run(d_, L_, steps_of[probe_f], lr, CFG[\"seeds\"][0])\n", " loss = r[\"val_loss\"] if math.isfinite(r[\"val_loss\"]) and not int(r[\"diverged\"]) else float(\"inf\")\n", " results.append((loss, lr))\n", " probe_rows.append({\"d_model\": d_, \"n_layer\": L_, \"max_lr\": lr, \"steps\": steps_of[probe_f],\n", " \"val_loss\": \"nan\" if loss == float(\"inf\") else round(loss, 5)})\n", " best_lr[(d_, L_)] = min(results)[1]\n", " edge = \" (EDGE of the range)\" if len(CFG[\"lrs\"]) > 1 and best_lr[(d_, L_)] in (CFG[\"lrs\"][0], CFG[\"lrs\"][-1]) else \"\"\n", " print(f\"({d_:3d}, {L_}): best peak lr {best_lr[(d_, L_)]:.0e}{edge}\")\n", "save_csv(\"lr-probe.csv\", [\"d_model\", \"n_layer\", \"max_lr\", \"steps\", \"val_loss\"], probe_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The sweep\n", "\n", "Now the main runs: every size (including the held-back test size) at the budgets in `FRACTIONS`,\n", "each with its best learning rate; the full budget with every seed. The test size is trained\n", "in the same loop but **not used in any fit** until section 7." ], "id": "lab-5-2-scaling-16" }, { "cell_type": "code", "metadata": {}, "source": [ "t_sweep = time.time()\n", "for d_, L_ in ALL_SIZES:\n", " for f in FR:\n", " for seed in (CFG[\"seeds\"] if f == FR[-1] else CFG[\"seeds\"][:1]):\n", " train_run(d_, L_, steps_of[f], best_lr[(d_, L_)], seed)\n", "print(f\"sweep done in {time.time() - t_sweep:.0f} s (cached runs cost nothing)\")\n", "\n", "all_runs = []\n", "for r in load_runs():\n", " r = dict(r)\n", " for k in (\"d_model\", \"n_layer\", \"n_blocks\", \"n_total\", \"steps\", \"tokens_D\", \"seed\", \"diverged\"):\n", " r[k] = int(r[k])\n", " for k in (\"fraction\", \"max_lr\", \"val_loss\", \"train_loss\", \"flops_6nd\", \"train_s\"):\n", " r[k] = float(r[k])\n", " all_runs.append(r)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · The table, and the law\n", "\n", "One row per size at the full budget: the mean over seeds of the final validation loss, and\n", "the gap between seeds. Then the fit. The method is the one you can do on paper:\n", "take the logarithm of both axes; if the points lie on a line, `log L = log a − α · log N`,\n", "i.e. `L = a · N^(−α)`. Least squares on the logs is one call to `np.linalg.lstsq`." ], "id": "lab-5-2-scaling-18" }, { "cell_type": "code", "metadata": {}, "source": [ "def full_budget_rows(size):\n", " return [r for r in all_runs if (r[\"d_model\"], r[\"n_layer\"]) == size and r[\"steps\"] == STEPS_FULL\n", " and f\"{r['max_lr']:.0e}\" == f\"{best_lr[size]:.0e}\" and not r[\"diverged\"]]\n", "\n", "\n", "table = []\n", "for size in ALL_SIZES:\n", " rs = full_budget_rows(size)\n", " vals = [r[\"val_loss\"] for r in rs]\n", " table.append({\"d_model\": size[0], \"n_layer\": size[1], \"n_blocks\": n_nonembedding(*size), \"n_total\": rs[0][\"n_total\"],\n", " \"tokens_D\": rs[0][\"tokens_D\"], \"flops_6nd\": rs[0][\"flops_6nd\"],\n", " \"flops_counted\": COUNTED[size] * rs[0][\"tokens_D\"], \"best_lr\": f\"{best_lr[size]:.0e}\",\n", " \"n_seeds\": len(vals), \"val_loss\": float(np.mean(vals)),\n", " \"seed_gap\": float(max(vals) - min(vals)) if len(vals) > 1 else float(\"nan\"),\n", " \"is_test\": int(size == CFG[\"test\"])})\n", "print(f\"{'size':>10} {'N blocks':>10} {'N total':>10} {'D tokens':>12} {'6·N·D':>11} {'counted':>11} {'lr':>6} {'val loss':>9} {'seed gap':>9}\")\n", "for r in table:\n", " print(f\"{f'({r['d_model']},{r['n_layer']})':>10} {r['n_blocks']:>10,} {r['n_total']:>10,} {r['tokens_D']:>12,} \"\n", " f\"{r['flops_6nd']:>11.3e} {r['flops_counted']:>11.3e} {r['best_lr']:>6} {r['val_loss']:>9.4f} {r['seed_gap']:>9.4f}\"\n", " f\"{' <- held back' if r['is_test'] else ''}\")\n", "save_csv(\"sweep.csv\", list(table[0]), [{**r, \"val_loss\": round(r[\"val_loss\"], 5),\n", " \"seed_gap\": \"\" if math.isnan(r[\"seed_gap\"]) else round(r[\"seed_gap\"], 5)} for r in table])\n", "\n", "train_rows = [r for r in table if not r[\"is_test\"]]\n", "test_row = next(r for r in table if r[\"is_test\"])\n", "\n", "\n", "def fit_power_law(n, loss):\n", " \"\"\"least squares on the logs: log L = intercept + slope * log N -> L = exp(intercept) * N**slope\"\"\"\n", " A = np.column_stack([np.log(n), np.ones(len(n))])\n", " (slope, intercept), *_ = np.linalg.lstsq(A, np.log(loss), rcond=None)\n", " pred_log = A @ np.array([slope, intercept])\n", " ss_res = float(np.sum((np.log(loss) - pred_log) ** 2))\n", " ss_tot = float(np.sum((np.log(loss) - np.log(loss).mean()) ** 2))\n", " return float(slope), float(intercept), 1 - ss_res / ss_tot\n", "\n", "\n", "def predict(slope, intercept, n):\n", " return float(np.exp(intercept) * np.asarray(n, dtype=float) ** slope)\n", "\n", "\n", "fits = {}\n", "for label, key in ((\"N (blocks only)\", \"n_blocks\"), (\"N_total (all weights)\", \"n_total\"), (\"compute, counted FLOPs\", \"flops_counted\")):\n", " n_fit = np.array([r[key] for r in train_rows], float)\n", " l_fit = np.array([r[\"val_loss\"] for r in train_rows], float)\n", " slope, intercept, r2 = fit_power_law(n_fit, l_fit)\n", " fits[key] = (slope, intercept, r2)\n", " print(f\"fit L = a · x^slope on {label:<24}: slope {slope:+.4f} a = {math.exp(intercept):.4f} R² (log space) = {r2:.4f}\")" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Predict, then check\n", "\n", "Use the line fitted on the five smaller sizes to predict the loss of the size we held back,\n", "before looking at its measured loss. Then compare: the error in nats, in percent, and\n", "next to the seed gap (the noise)." ], "id": "lab-5-2-scaling-20" }, { "cell_type": "code", "metadata": {}, "source": [ "pred_rows = []\n", "for label, key in ((\"N (blocks only)\", \"n_blocks\"), (\"N_total (all weights)\", \"n_total\"), (\"compute, counted FLOPs\", \"flops_counted\")):\n", " slope, intercept, r2 = fits[key]\n", " pred = predict(slope, intercept, test_row[key])\n", " err = pred - test_row[\"val_loss\"]\n", " largest = max(r[key] for r in train_rows)\n", " pred_rows.append({\"fitted_on\": label, \"slope\": round(slope, 5), \"r2_log\": round(r2, 5), \"x_test\": test_row[key],\n", " \"x_over_largest_fit\": round(test_row[key] / largest, 3), \"predicted_loss\": round(pred, 5),\n", " \"measured_loss\": round(test_row[\"val_loss\"], 5), \"error_nats\": round(err, 5),\n", " \"error_percent\": round(100 * err / test_row[\"val_loss\"], 3)})\n", " print(f\"{label:<23}: predicted {pred:.4f} measured {test_row['val_loss']:.4f} error {err:+.4f} nats \"\n", " f\"({100 * err / test_row['val_loss']:+.2f} %) test size is {test_row[key] / largest:.2f}x the largest fitted\")\n", "print(f\"seed gap at the largest fitted sizes: {[round(r['seed_gap'], 4) for r in train_rows[-2:]]} \"\n", " f\"at the test size: {test_row['seed_gap']:.4f}\")\n", "save_csv(\"prediction.csv\", list(pred_rows[0]), pred_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Is it really a power law? The residuals\n", "\n", "A straight line on log-log axes can hide a bend. Print how far each *fitted* point sits from\n", "the line (in percent of the measured loss). A pattern (positive, then negative, then positive)\n", "is a bend; random signs of the size of the seed gap are noise." ], "id": "lab-5-2-scaling-22" }, { "cell_type": "code", "metadata": {}, "source": [ "slope, intercept, r2 = fits[\"n_blocks\"]\n", "res_rows = []\n", "for r in table:\n", " pred = predict(slope, intercept, r[\"n_blocks\"])\n", " res_rows.append({\"d_model\": r[\"d_model\"], \"n_layer\": r[\"n_layer\"], \"n_blocks\": r[\"n_blocks\"], \"val_loss\": round(r[\"val_loss\"], 5),\n", " \"line\": round(pred, 5), \"residual_percent\": round(100 * (r[\"val_loss\"] - pred) / pred, 3), \"is_test\": r[\"is_test\"]})\n", " print(f\"({r['d_model']:3d},{r['n_layer']}) N {r['n_blocks']:>10,} measured {r['val_loss']:.4f} line {pred:.4f} \"\n", " f\"{100 * (r['val_loss'] - pred) / pred:+6.2f} %{' (test, not fitted)' if r['is_test'] else ''}\")\n", "save_csv(\"residuals.csv\", list(res_rows[0]), res_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### How much did the learning-rate probe matter?\n", "\n", "The probe tries rates a factor of two apart, and loss is not smooth in the learning rate (at a\n", "rate that is too high, a run can collapse). Redo the fit with **one** rate for every size (the\n", "second rate of the list, `FIXED_LR`) and compare it with the tuned fit. Both use only the first\n", "seed, so that the comparison is like for like." ], "id": "lab-5-2-scaling-24" }, { "cell_type": "code", "metadata": {}, "source": [ "FIXED_LR = CFG[\"lrs\"][1] if len(CFG[\"lrs\"]) > 1 else CFG[\"lrs\"][0]\n", "fixed_rows = []\n", "for size in ALL_SIZES:\n", " tuned = train_run(*size, STEPS_FULL, best_lr[size], CFG[\"seeds\"][0])\n", " fixed = train_run(*size, STEPS_FULL, FIXED_LR, CFG[\"seeds\"][0])\n", " fixed_rows.append({\"d_model\": size[0], \"n_layer\": size[1], \"n_blocks\": n_nonembedding(*size), \"tuned_lr\": f\"{best_lr[size]:.0e}\",\n", " \"tuned_loss\": round(float(tuned[\"val_loss\"]), 5), \"fixed_lr\": f\"{FIXED_LR:.0e}\", \"fixed_loss\": round(float(fixed[\"val_loss\"]), 5)})\n", "cmp_rows = []\n", "for label, key in ((\"tuned rate per size\", \"tuned_loss\"), (f\"one rate ({FIXED_LR:.0e})\", \"fixed_loss\")):\n", " n_f = np.array([r[\"n_blocks\"] for r in fixed_rows[:-1]], float)\n", " l_f = np.array([r[key] for r in fixed_rows[:-1]], float)\n", " sl, ic, r2_ = fit_power_law(n_f, l_f)\n", " pr = predict(sl, ic, fixed_rows[-1][\"n_blocks\"])\n", " ms = fixed_rows[-1][key]\n", " cmp_rows.append({\"rates\": label, \"slope\": round(sl, 4), \"r2_log\": round(r2_, 4), \"predicted_test\": round(pr, 4),\n", " \"measured_test\": ms, \"error_percent\": round(100 * (pr - ms) / ms, 2)})\n", " print(f\"{label:<22}: slope {sl:+.4f} R² {r2_:.4f} predicted {pr:.4f} measured {ms:.4f} error {100 * (pr - ms) / ms:+.2f} %\")\n", "print(\"loss per size, tuned vs one rate:\", [(r[\"tuned_lr\"], r[\"tuned_loss\"], r[\"fixed_loss\"]) for r in fixed_rows])\n", "save_csv(\"fixed-lr.csv\", list(fixed_rows[0]), fixed_rows)\n", "save_csv(\"fixed-lr-fit.csv\", list(cmp_rows[0]), cmp_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Tokens per parameter: the grid\n", "\n", "The sweep held `D` fixed, so it says how loss falls with `N` *at that D*. Chinchilla asks a\n", "different question: for a fixed *compute*, which `(N, D)` is best? Your grid has the answer in\n", "miniature: every size at every budget in `FRACTIONS`. A cell is on the **efficient frontier** if no other\n", "cell reaches a lower loss with no more compute. Compute here is the *counted* FLOPs of section 4\n", "(per-token count times `D`), because at this scale `6 · N · D` with block weights alone misses most of the work. Print the frontier with its tokens per parameter,\n", "`D / N` for the blocks and `D / N_total`. (This is only as good as the grid: with so few\n", "sizes and budgets the frontier is a coarse picture, and the learning rate was tuned on the shortest budget only.)" ], "id": "lab-5-2-scaling-26" }, { "cell_type": "code", "metadata": {}, "source": [ "grid = [r for r in all_runs if f\"{r['max_lr']:.0e}\" == f\"{best_lr[(r['d_model'], r['n_layer'])]:.0e}\" and not r[\"diverged\"]\n", " and r[\"seed\"] == CFG[\"seeds\"][0]]\n", "for r in grid:\n", " r[\"flops_counted\"] = COUNTED[(r[\"d_model\"], r[\"n_layer\"])] * r[\"tokens_D\"]\n", "grid.sort(key=lambda r: r[\"flops_counted\"])\n", "frontier_rows = []\n", "best_so_far = float(\"inf\")\n", "for r in grid:\n", " on = r[\"val_loss\"] < best_so_far\n", " best_so_far = min(best_so_far, r[\"val_loss\"])\n", " frontier_rows.append({\"d_model\": r[\"d_model\"], \"n_layer\": r[\"n_layer\"], \"n_blocks\": r[\"n_blocks\"], \"n_total\": r[\"n_total\"],\n", " \"tokens_D\": r[\"tokens_D\"], \"fraction\": r[\"fraction\"], \"flops_6nd\": r[\"flops_6nd\"],\n", " \"flops_counted\": r[\"flops_counted\"], \"val_loss\": round(r[\"val_loss\"], 5), \"tokens_per_param_blocks\": round(r[\"tokens_D\"] / r[\"n_blocks\"], 1),\n", " \"tokens_per_param_total\": round(r[\"tokens_D\"] / r[\"n_total\"], 1), \"on_frontier\": int(on)})\n", "print(f\"{'size':>9} {'fraction':>8} {'counted FLOP':>12} {'val':>7} {'D/N blocks':>10} {'D/N total':>10} frontier\")\n", "for r in frontier_rows:\n", " print(f\"{f'({r['d_model']},{r['n_layer']})':>9} {r['fraction']:>8} {r['flops_counted']:>12.2e} {r['val_loss']:>7.4f} \"\n", " f\"{r['tokens_per_param_blocks']:>10.1f} {r['tokens_per_param_total']:>10.1f} {'*' if r['on_frontier'] else ''}\")\n", "save_csv(\"grid.csv\", list(frontier_rows[0]), frontier_rows)\n", "\n", "by_budget = {}\n", "for r in grid:\n", " by_budget.setdefault(r[\"fraction\"], []).append(r)\n", "print(\"\\nbest size at each budget (equal tokens, NOT equal compute: a bigger model learns more from the same tokens):\")\n", "best_rows = []\n", "for f_, rs in sorted(by_budget.items()):\n", " b = min(rs, key=lambda r: r[\"val_loss\"])\n", " best_rows.append({\"fraction\": f_, \"tokens_D\": b[\"tokens_D\"], \"best_d_model\": b[\"d_model\"], \"best_n_layer\": b[\"n_layer\"],\n", " \"best_n_blocks\": b[\"n_blocks\"], \"val_loss\": round(b[\"val_loss\"], 5),\n", " \"tokens_per_param_blocks\": round(b[\"tokens_D\"] / b[\"n_blocks\"], 1)})\n", " print(f\" D = {b['tokens_D']:>12,} ({f_:.2f} of full): best size ({b['d_model']},{b['n_layer']}), N = {b['n_blocks']:,}, \"\n", " f\"loss {b['val_loss']:.4f}, D/N = {b['tokens_D'] / b['n_blocks']:.1f}\")\n", "save_csv(\"best-size-per-budget.csv\", list(best_rows[0]), best_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Same compute, different split\n", "\n", "`best-size-per-budget` compares sizes at the *same number of tokens*, and there the bigger model\n", "is always at least as good: it learns more from each token. Chinchilla's question is about the\n", "*same compute*. Find every pair of cells whose counted compute is within 20 % of each other but\n", "whose sizes differ, and see whether the larger model on fewer tokens or the smaller model on\n", "more tokens has the lower loss." ], "id": "lab-5-2-scaling-28" }, { "cell_type": "code", "metadata": {}, "source": [ "pairs = []\n", "for i, a in enumerate(grid):\n", " for b in grid[i + 1:]:\n", " if (a[\"d_model\"], a[\"n_layer\"]) != (b[\"d_model\"], b[\"n_layer\"]) and b[\"flops_counted\"] / a[\"flops_counted\"] <= 1.2:\n", " big, small = (a, b) if a[\"n_blocks\"] > b[\"n_blocks\"] else (b, a)\n", " pairs.append({\"small\": f\"({small['d_model']},{small['n_layer']}) f={small['fraction']}\", \"big\": f\"({big['d_model']},{big['n_layer']}) f={big['fraction']}\",\n", " \"compute_small\": f\"{small['flops_counted']:.3e}\", \"compute_big\": f\"{big['flops_counted']:.3e}\",\n", " \"tokens_small\": small[\"tokens_D\"], \"tokens_big\": big[\"tokens_D\"],\n", " \"loss_small\": round(small[\"val_loss\"], 4), \"loss_big\": round(big[\"val_loss\"], 4),\n", " \"winner\": \"small, more tokens\" if small[\"val_loss\"] < big[\"val_loss\"] else \"big, fewer tokens\"})\n", "for r in pairs:\n", " print(f\"{r['small']:>18} loss {r['loss_small']:.4f} ({r['compute_small']}) vs {r['big']:>18} loss {r['loss_big']:.4f} ({r['compute_big']}) -> {r['winner']}\")\n", "wins = sum(r[\"winner\"].startswith(\"small\") for r in pairs)\n", "print(f\"{wins} of {len(pairs)} matched-compute pairs are won by the smaller model on more tokens\")\n", "if pairs:\n", " save_csv(\"matched-compute.csv\", list(pairs[0]), pairs)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Checkpoint\n", "\n", "The notebook prints the table of section 6, the fits and the prediction of section 7, and\n", "the frontier of section 8. Your numbers will differ in the last digits and a little more if\n", "your hardware or PyTorch version differs; the **shape** must be the same: loss falls steadily\n", "with size, the fitted slope is negative, and the prediction for the held-back size is off by a\n", "small fraction of the loss. Compare your values with the lab page.\n", "\n", "## Explore\n", "\n", "| knob | try | question |\n", "| --- | --- | --- |\n", "| `fractions` | add `2.0` (needs `base_steps` and data for a second pass) | does the loss keep falling for the big sizes once they get more tokens? Which end of the line moves most? |\n", "| `lrs` | use one fixed rate for all sizes (`lrs=[2e-3]`) | which sizes get worse, and does the fitted slope change? |\n", "| `seeds` | add a third seed | how large is the noise next to the gap between neighbouring sizes? |\n", "| fit on `n_total` instead of `n_blocks` | compare the two slopes and the two prediction errors in section 7 | which count gives the straighter line at this scale, and why would it not at GPT-3 scale? |\n", "| fit only the three smallest sizes | predict the next two | how fast does the error grow with the distance to extrapolate? |\n", "| add a size with `d = 64`, `L = 8` (deep and thin) | where does it fall relative to the line? | is `N` alone enough to predict the loss, or does the shape matter too? |\n", "| `block_size` | halve it | what does the model lose, and does `6 · N · D` still count the compute? |" ], "id": "lab-5-2-scaling-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Failure playground\n", "\n", "Three things that go wrong in real scaling studies. Each cell below is broken on purpose. Run\n", "it, read the symptom, answer the questions in your notebook, then fix it. The cells use the\n", "measurements above (no new training), and each prints its symptom instead of raising.\n", "\n", "### 9a · The confounded sweep\n", "\n", "*The story:* a colleague trained the small sizes for the full budget and, to save time, the large\n", "sizes for a quarter of it (\"they converge faster anyway\"), then fitted loss against `N`.\n", "\n", "**Questions:** (1) Is the fitted slope the one from section 6? Which direction did it move?\n", "(2) What does the line predict for the held-back size, and how wrong is it? (3) Which variable\n", "changed together with `N`? (4) Write the one-line rule for a sweep that fits only `N`." ], "id": "lab-5-2-scaling-31" }, { "cell_type": "code", "metadata": {}, "source": [ "small = [s for s in CFG[\"sizes\"][:len(CFG[\"sizes\"]) // 2 + 1]]\n", "conf_rows = []\n", "for size in CFG[\"sizes\"]:\n", " f_ = FR[-1] if size in small else FR[0]\n", " rs = [r for r in grid if (r[\"d_model\"], r[\"n_layer\"]) == size and r[\"fraction\"] == f_]\n", " conf_rows.append({\"n_blocks\": n_nonembedding(*size), \"val_loss\": rs[0][\"val_loss\"], \"fraction\": f_})\n", "n_c = np.array([r[\"n_blocks\"] for r in conf_rows], float)\n", "l_c = np.array([r[\"val_loss\"] for r in conf_rows], float)\n", "s_c, i_c, r2_c = fit_power_law(n_c, l_c)\n", "p_c = predict(s_c, i_c, test_row[\"n_blocks\"])\n", "print(f\"budget fractions used per size: {[r['fraction'] for r in conf_rows]}\")\n", "print(f\"confounded fit: slope {s_c:+.4f} (clean fit: {fits['n_blocks'][0]:+.4f}) R² {r2_c:.4f}\")\n", "print(f\"prediction for the held-back size: {p_c:.4f} measured {test_row['val_loss']:.4f} \"\n", " f\"error {p_c - test_row['val_loss']:+.4f} nats ({100 * (p_c - test_row['val_loss']) / test_row['val_loss']:+.1f} %)\")\n", "save_csv(\"failure-confounded.csv\", [\"n_blocks\", \"val_loss\", \"fraction\"], conf_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9b · The straight line in linear space\n", "\n", "*The story:* a script fits `loss = a · N + b` with `np.polyfit` on the raw numbers (\"it looks\n", "nearly straight when I plot it\").\n", "\n", "**Questions:** (1) How well does it fit the points it was given? (2) What loss does it predict at\n", "the held-back size, and at 100 times the largest size? Is that possible for a cross-entropy\n", "loss? (3) Why does a power law become a straight line only on log-log axes? (4) Which end of\n", "the data decides this fit, and why?" ], "id": "lab-5-2-scaling-33" }, { "cell_type": "code", "metadata": {}, "source": [ "n_l = np.array([r[\"n_blocks\"] for r in train_rows], float)\n", "l_l = np.array([r[\"val_loss\"] for r in train_rows], float)\n", "a_l, b_l = np.polyfit(n_l, l_l, 1) # <- the bug: linear space\n", "fitted_l = a_l * n_l + b_l\n", "print(f\"linear fit: loss = {a_l:.3e} · N + {b_l:.4f}\")\n", "print(\"fit to the training sizes (measured -> line):\", \", \".join(f\"{m:.3f}->{p:.3f}\" for m, p in zip(l_l, fitted_l)))\n", "for label, n_new in ((\"held-back size\", test_row[\"n_blocks\"]), (\"100x the largest fitted size\", 100 * n_l.max())):\n", " print(f\" at {label} (N = {n_new:,.0f}): linear line says {a_l * n_new + b_l:.3f}\", end=\"\")\n", " print(f\" measured {test_row['val_loss']:.3f}\" if label == \"held-back size\" else \" (no measurement; log V = %.3f)\" % math.log(V))\n", "save_csv(\"failure-linear-space.csv\", [\"n_blocks\", \"val_loss\", \"linear_line\"],\n", " [{\"n_blocks\": int(n), \"val_loss\": round(m, 5), \"linear_line\": round(p, 5)} for n, m, p in zip(n_l, l_l, fitted_l)])" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-34" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9c · Extrapolating too far\n", "\n", "*The story:* a plan says \"fit the three smallest sizes, then predict everything bigger, up to a model\n", "1,000 times larger\".\n", "\n", "**Questions:** (1) How does the prediction error change as the size you predict moves\n", "away from the sizes you fitted? (2) Is it a *random* error or does it have a sign? What does that\n", "say about the shape of the real curve? (3) What would you add to the model of the curve to\n", "fix the sign? (4) How far past your largest size would you trust a prediction, given these numbers?" ], "id": "lab-5-2-scaling-35" }, { "cell_type": "code", "metadata": {}, "source": [ "ex_rows = []\n", "n_all = np.array([r[\"n_blocks\"] for r in table], float)\n", "for k in range(3, len(train_rows)): # fit the first k sizes\n", " s_k, i_k, _ = fit_power_law(n_all[:k], np.array([r[\"val_loss\"] for r in table[:k]]))\n", " for j in range(k, len(table)):\n", " pr = predict(s_k, i_k, n_all[j])\n", " ex_rows.append({\"fit_sizes\": k, \"fit_up_to_n\": int(n_all[k - 1]), \"target_n\": int(n_all[j]),\n", " \"distance\": round(n_all[j] / n_all[k - 1], 2), \"slope\": round(s_k, 4),\n", " \"predicted\": round(pr, 4), \"measured\": round(table[j][\"val_loss\"], 4),\n", " \"error_percent\": round(100 * (pr - table[j][\"val_loss\"]) / table[j][\"val_loss\"], 2)})\n", "print(f\"{'fit on':>7} {'target N':>10} {'distance':>9} {'predicted':>10} {'measured':>9} {'error %':>8}\")\n", "for r in ex_rows:\n", " print(f\"{r['fit_sizes']:>7} {r['target_n']:>10,} {r['distance']:>8.1f}x {r['predicted']:>10.4f} {r['measured']:>9.4f} {r['error_percent']:>+8.2f}\")\n", "s3, i3, _ = fit_power_law(n_all[:3], np.array([r[\"val_loss\"] for r in table[:3]]))\n", "far = n_all[2] * 1000\n", "print(f\"\\nthe three-size line at {far:,.0f} weights (1,000x its largest fitted size): loss {predict(s3, i3, far):.3f} \"\n", " f\"(nothing to check it against)\")\n", "save_csv(\"failure-extrapolation.csv\", list(ex_rows[0]), ex_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-2-scaling-36" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What this lab did not test\n", "\n", "Six sizes, one data set, one context length, one seed pair per size, learning rates tuned on the shortest budget,\n", "a vocabulary whose embedding dwarfs the small models. The published laws (Kaplan 2020, Hoffmann 2022) used\n", "hundreds of runs across seven orders of magnitude and did a lot more to separate the effects. What you\n", "measured is the *method*; the constants are TinyStories-and-this-GPT constants." ], "id": "lab-5-2-scaling-37" }, { "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-5-2-scaling-38" } ] }