{ "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.1 · Training Memory, Mixed Precision, Accumulation and Checkpointing\n", "\n", "**Goal:** measure where GPU memory actually goes during GPT training (weights, gradients,\n", "optimizer state, activations), compare pure `fp32` against `bf16` mixed precision, gradient\n", "accumulation, and activation checkpointing on both peak memory and step time, find the largest\n", "batch size that fits for each, verify gradient accumulation numerically, and diagnose three\n", "classic large-scale training failures.\n", "\n", "**Runs on:** an NVIDIA GPU (free Kaggle or Colab T4, or any RTX/data-centre card; the book's\n", "numbers come from an RTX 3060 12 GB). Without CUDA, every cell still runs on CPU (or Apple\n", "`mps`) using a smaller GPT config and skips the CUDA VRAM allocator sweeps gracefully so you can\n", "study the code, precision arithmetic, accumulation equivalence, and failure playgrounds on any\n", "laptop.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-5-1-memory-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import gc\n", "import math\n", "import os\n", "import pathlib\n", "import platform\n", "import time\n", "\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "from torch.utils.checkpoint import checkpoint\n", "\n", "if torch.cuda.is_available():\n", " DEVICE = \"cuda\"\n", "elif torch.backends.mps.is_available():\n", " DEVICE = \"mps\"\n", "else:\n", " DEVICE = \"cpu\"\n", "DEVICE = os.environ.get(\"LAB_DEVICE\", DEVICE) # e.g. LAB_DEVICE=cpu to force the CPU quick path\n", "ON_GPU = DEVICE == \"cuda\"\n", "BF16_OK = ON_GPU and torch.cuda.is_bf16_supported()\n", "\n", "MACHINE = (\n", " torch.cuda.get_device_name(0)\n", " if ON_GPU\n", " else f\"{platform.system()} {platform.machine()} ({DEVICE})\"\n", ")\n", "print(f\"PyTorch {torch.__version__} | device: {DEVICE} | machine: {MACHINE}\")\n", "if ON_GPU:\n", " props = torch.cuda.get_device_properties(0)\n", " print(\n", " f\"Compute capability: {props.major}.{props.minor} | \"\n", " f\"VRAM: {props.total_memory / 1024**3:.2f} GiB ({props.total_memory / 1e9:.2f} GB) | \"\n", " f\"bf16 supported: {BF16_OK}\"\n", " )\n", "\n", "\n", "def sync(device=DEVICE):\n", " if device == \"cuda\":\n", " torch.cuda.synchronize()\n", " elif device == \"mps\":\n", " torch.mps.synchronize()\n", "\n", "\n", "def clear_mem():\n", " gc.collect()\n", " if ON_GPU:\n", " torch.cuda.empty_cache()\n", " torch.cuda.reset_peak_memory_stats()\n", "\n", "\n", "def out_dir():\n", " forced = os.environ.get(\"LAB_OUT_DIR\")\n", " if forced:\n", " d = pathlib.Path(forced)\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-1-memory\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def save_csv(name, rows):\n", " path = out_dir() / name\n", " with path.open(\"w\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=list(rows[0].keys()), lineterminator=\"\\n\")\n", " w.writeheader()\n", " w.writerows(rows)\n", " print(\"saved\", path)\n", "\n", "\n", "# Reference model config: scaled-up Ch 3.3 GPT on GPU, smaller quick config on CPU/MPS\n", "if ON_GPU:\n", " CFG = dict(vocab_size=8192, seq_len=512, d_model=512, n_layer=8, n_head=8)\n", "else:\n", " CFG = dict(vocab_size=512, seq_len=64, d_model=128, n_layer=4, n_head=4)\n", "print(\"Model config:\", CFG)" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your estimates before running the cells below:\n", "\n", "1. **Static memory per parameter.** Our GPU GPT has about **29.7 million parameters**. In 16-bit\n", " inference, its weights take about `29.7M × 2 B ≈ 59 MB`. When trained with AdamW in `fp32`,\n", " how many bytes per parameter do weights, gradients, and optimizer states take together, and\n", " how many MB is that in total?\n", "2. **Activations vs model state.** At batch size `B = 16`, sequence length `T = 512` in `fp32`,\n", " will the activations stored for backpropagation be smaller than, roughly equal to, or several\n", " times larger than the static model state?\n", "3. **Mixed precision (`bf16` autocast).** Switching from `fp32` to `bf16` autocast (keeping\n", " `fp32` master weights) changes both peak memory and step time. Which one drops more: static\n", " model memory or activation memory? Roughly how much faster do you expect each step to run on\n", " an RTX 3060?\n", "4. **Gradient accumulation.** Replacing one batch of `16` with `4` micro-batches of `4` (dividing\n", " each micro-batch loss by `4`): how close do you expect the final parameter gradients to be in\n", " `fp32` (`10^-2`, `10^-4`, or `10^-7`)?\n", "5. **Activation checkpointing.** Recomputation discards intermediate activations inside each\n", " transformer block and recomputes them during backward. Roughly what percentage slower do you\n", " expect each step to be (10 %, 30 %, or 100 %), and by roughly what factor will the maximum\n", " batch size on 12 GB grow?" ], "id": "lab-5-1-memory-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Build by hand: the GPT model, the memory formula, and 16-bit arithmetic\n", "\n", "First we define the Ch 3.3 GPT architecture (pre-norm transformer blocks with tied token\n", "embeddings and output head) with two switches we will measure:\n", "\n", "- `grad_checkpoint=True`: wraps each transformer block in `torch.utils.checkpoint.checkpoint`,\n", " discarding its internal activations on the forward pass and recomputing them during backward.\n", "- `eager=True`: materialises the full `[B, H, T, T]` attention score and probability matrices\n", " instead of calling PyTorch's fused `F.scaled_dot_product_attention` (SDPA), so we can measure\n", " quadratic `T²` activation growth directly." ], "id": "lab-5-1-memory-03" }, { "cell_type": "code", "metadata": {}, "source": [ "class CausalSelfAttention(nn.Module):\n", " def __init__(self, d_model, n_head, eager=False):\n", " super().__init__()\n", " assert d_model % n_head == 0\n", " self.n_head = n_head\n", " self.d_head = d_model // n_head\n", " self.eager = eager\n", " self.qkv = nn.Linear(d_model, 3 * d_model)\n", " self.proj = nn.Linear(d_model, d_model)\n", "\n", " def forward(self, x):\n", " B, T, C = x.shape\n", " q, k, v = self.qkv(x).split(C, dim=-1)\n", " q = q.view(B, T, self.n_head, self.d_head).transpose(1, 2)\n", " k = k.view(B, T, self.n_head, self.d_head).transpose(1, 2)\n", " v = v.view(B, T, self.n_head, self.d_head).transpose(1, 2)\n", " if self.eager:\n", " att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.d_head))\n", " mask = torch.triu(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=1)\n", " att = F.softmax(att.masked_fill(mask, float(\"-inf\")), dim=-1)\n", " y = att @ v\n", " else:\n", " y = F.scaled_dot_product_attention(q, k, v, is_causal=True)\n", " return self.proj(y.transpose(1, 2).contiguous().view(B, T, C))\n", "\n", "\n", "class Block(nn.Module):\n", " def __init__(self, d_model, n_head, eager=False):\n", " super().__init__()\n", " self.ln1 = nn.LayerNorm(d_model)\n", " self.attn = CausalSelfAttention(d_model, n_head, eager=eager)\n", " self.ln2 = nn.LayerNorm(d_model)\n", " self.fc1 = nn.Linear(d_model, 4 * d_model)\n", " self.fc2 = nn.Linear(4 * d_model, d_model)\n", "\n", " def forward(self, x):\n", " x = x + self.attn(self.ln1(x))\n", " x = x + self.fc2(F.gelu(self.fc1(self.ln2(x))))\n", " return x\n", "\n", "\n", "class SmallGPT(nn.Module):\n", " def __init__(self, vocab_size=8192, seq_len=512, d_model=512, n_layer=8, n_head=8,\n", " grad_checkpoint=False, eager=False):\n", " super().__init__()\n", " self.vocab_size = vocab_size\n", " self.seq_len = seq_len\n", " self.grad_checkpoint = grad_checkpoint\n", " self.tok_emb = nn.Embedding(vocab_size, d_model)\n", " self.pos_emb = nn.Embedding(seq_len, d_model)\n", " self.blocks = nn.ModuleList([Block(d_model, n_head, eager=eager) for _ in range(n_layer)])\n", " self.ln_f = nn.LayerNorm(d_model)\n", " self.lm_head = nn.Linear(d_model, vocab_size, bias=False)\n", " self.lm_head.weight = self.tok_emb.weight # weight tying (Ch 2.3 / Ch 3.3)\n", " self._init_weights(n_layer)\n", "\n", " def _init_weights(self, n_layer):\n", " for name, mod in self.named_modules():\n", " if isinstance(mod, nn.Linear):\n", " std = 0.02 / math.sqrt(2 * n_layer) if (name.endswith(\"proj\") or name.endswith(\"fc2\")) else 0.02\n", " nn.init.normal_(mod.weight, mean=0.0, std=std)\n", " if mod.bias is not None:\n", " nn.init.zeros_(mod.bias)\n", " elif isinstance(mod, nn.Embedding):\n", " nn.init.normal_(mod.weight, mean=0.0, std=0.02)\n", "\n", " def forward(self, idx):\n", " B, T = idx.shape\n", " x = self.tok_emb(idx) + self.pos_emb(torch.arange(T, device=idx.device))\n", " for blk in self.blocks:\n", " if self.grad_checkpoint:\n", " x = checkpoint(blk, x, use_reentrant=False)\n", " else:\n", " x = blk(x)\n", " return self.lm_head(self.ln_f(x))\n", "\n", "\n", "def count_params(model):\n", " return sum(p.numel() for p in model.parameters())\n", "\n", "\n", "demo_model = SmallGPT(**CFG)\n", "N_PARAMS = count_params(demo_model)\n", "block_params = count_params(demo_model.blocks[0])\n", "print(f\"Total parameters: {N_PARAMS:,} ({N_PARAMS / 1e6:.2f} M)\")\n", "print(f\" tok_emb (tied): {demo_model.tok_emb.weight.numel():,}\")\n", "print(f\" pos_emb : {demo_model.pos_emb.weight.numel():,}\")\n", "print(f\" 1 block : {block_params:,} (x {CFG['n_layer']} = {block_params * CFG['n_layer']:,})\")\n", "print(f\" ln_f : {count_params(demo_model.ln_f):,}\")\n", "del demo_model" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Hand-built training memory estimator\n", "\n", "Every byte of training memory falls into two buckets:\n", "\n", "1. **Static model state** (independent of batch size and sequence length):\n", " - **Weights:** `4N` in `fp32` (or `2N` in 16-bit + `4N` fp32 master copy in ZeRO's accounting).\n", " - **Gradients:** `4N` in `fp32` (`torch.amp.autocast` keeps fp32 params and grads; ZeRO keeps\n", " `2N` 16-bit grads alongside the `4N` master copy).\n", " - **Optimizer state:** `8N` for AdamW (two `fp32` buffers: first moment `m` and second moment\n", " `v`), `4N` for SGD with momentum, `0` for plain SGD.\n", " - Notice that with AdamW, **both** pure `fp32` (`4 + 4 + 8`) and ZeRO mixed precision\n", " (`2 + 2 + 4 + 8`) total **16 bytes per parameter** — 8× the `2 B/param` of 16-bit inference!\n", "2. **Activations** (scale linearly with `B × T × L × d` when using FlashAttention / SDPA, plus\n", " the `[B, T, V]` logits and their gradients in `fp32`, and plus `L × B × H × T²` if eager\n", " attention materialises the attention probability matrix)." ], "id": "lab-5-1-memory-05" }, { "cell_type": "code", "metadata": {}, "source": [ "def estimate_memory_bytes(\n", " n_params,\n", " n_layer,\n", " d_model,\n", " batch_size,\n", " seq_len,\n", " vocab_size=0,\n", " n_head=8,\n", " precision=\"bf16_autocast\", # \"fp32\" | \"bf16_autocast\" | \"zero_mixed\" | \"bf16_inference\"\n", " optimizer=\"adamw\", # \"adamw\" | \"sgd_momentum\" | \"sgd\" | \"none\"\n", " checkpointing=False,\n", " eager_attn=False,\n", " block_act_mult=19.0, # saved activation elements per (L * B * T * d), checked below\n", "):\n", " if precision == \"bf16_inference\":\n", " weights = 2 * n_params\n", " grads = 0\n", " opt_bytes = 0\n", " act_bytes = 0\n", " else:\n", " if precision == \"fp32\":\n", " weights, grads, master, b_act = 4 * n_params, 4 * n_params, 0, 4\n", " elif precision == \"bf16_autocast\":\n", " # PyTorch autocast: model params stay fp32 (they ARE the master weights); grads are fp32\n", " weights, grads, master, b_act = 4 * n_params, 4 * n_params, 0, 2\n", " elif precision == \"zero_mixed\":\n", " # ZeRO / DeepSpeed mixed precision: 16-bit weights & grads + fp32 master copy in optimizer\n", " weights, grads, master, b_act = 2 * n_params, 2 * n_params, 4 * n_params, 2\n", " else:\n", " raise ValueError(precision)\n", "\n", " if optimizer == \"adamw\":\n", " opt_state = 8 * n_params\n", " elif optimizer == \"sgd_momentum\":\n", " opt_state = 4 * n_params\n", " elif optimizer == \"sgd\":\n", " opt_state = 0\n", " else:\n", " raise ValueError(optimizer)\n", " opt_bytes = master + opt_state\n", "\n", " # Block activations (estimate): ~19 * B * T * d elements per layer without checkpointing;\n", " # with per-block checkpointing: L boundary tensors + 1 recomputed block.\n", " if checkpointing:\n", " block_elems = (n_layer + block_act_mult) * batch_size * seq_len * d_model\n", " else:\n", " block_elems = n_layer * block_act_mult * batch_size * seq_len * d_model\n", " act_bytes = int(block_elems * b_act)\n", "\n", " if eager_attn:\n", " # Post-softmax attention matrix [B, H, T, T] saved per layer (or 1 layer if checkpointed)\n", " attn_layers = 1 if checkpointing else n_layer\n", " act_bytes += attn_layers * batch_size * n_head * seq_len * seq_len * b_act\n", "\n", " if vocab_size > 0:\n", " # F.cross_entropy upcasts logits to fp32 (logits + grad_logits = 8 B/elem; +2 B in bf16)\n", " logits_b = 8 if b_act == 4 else 10\n", " act_bytes += batch_size * seq_len * vocab_size * logits_b\n", "\n", " return {\n", " \"weights\": weights,\n", " \"grads\": grads,\n", " \"optimizer\": opt_bytes,\n", " \"activations\": act_bytes,\n", " \"total\": weights + grads + opt_bytes + act_bytes,\n", " }\n", "\n", "\n", "print(\"Static memory bill (1 GB = 10^9 bytes, AdamW mixed precision vs 16-bit inference):\")\n", "for label, n_p in [(\"Our GPU GPT (29.7M)\", 29_676_544), (\"GPT-2 small (124M)\", 124_439_808),\n", " (\"7B model\", 7_000_000_000), (\"70B model\", 70_000_000_000)]:\n", " inf = estimate_memory_bytes(n_p, 1, 1, 1, 1, precision=\"bf16_inference\")\n", " trn = estimate_memory_bytes(n_p, 1, 1, 1, 1, precision=\"zero_mixed\", optimizer=\"adamw\")\n", " print(f\" {label:20s}: 16-bit inference {inf['weights']/1e9:6.2f} GB | \"\n", " f\"AdamW training static { (trn['weights']+trn['grads']+trn['optimizer'])/1e9:7.2f} GB \"\n", " f\"(W {trn['weights']/1e9:.2f} + G {trn['grads']/1e9:.2f} + Opt+Master {trn['optimizer']/1e9:.2f})\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Floating-point formats (`fp32`, `bf16`, `fp16`) and why master weights matter\n", "\n", "Inspect the exact representable range and spacing (ULP at `1.0`) of all three formats, then run\n", "a 10-line experiment: nudge a weight starting at `w = 1.0` by `-1e-4` for 1,000 steps in pure\n", "`bf16`, pure `fp16`, and with an `fp32` master weight." ], "id": "lab-5-1-memory-07" }, { "cell_type": "code", "metadata": {}, "source": [ "print(f\"{'dtype':10s} {'bits':>4s} {'max':>12s} {'min_normal':>12s} {'min_subnorm':>12s} {'eps (ULP@1)':>12s}\")\n", "for dt in (torch.float32, torch.bfloat16, torch.float16):\n", " fi = torch.finfo(dt)\n", " sub = torch.nextafter(torch.tensor(0.0, dtype=dt), torch.tensor(1.0, dtype=dt)).item()\n", " print(f\"{str(dt).split('.')[1]:10s} {fi.bits:4d} {fi.max:12.3e} {fi.tiny:12.3e} {sub:12.3e} {fi.eps:12.3e}\")\n", "\n", "print(\"\\nWeight-update stall without fp32 master weights (start w = 1.0, 1000 steps of -1e-4):\")\n", "step_delta = 1e-4\n", "for name, dt in [(\"pure bf16\", torch.bfloat16), (\"pure fp16\", torch.float16), (\"fp32 master\", torch.float32)]:\n", " w = torch.tensor(1.0, dtype=dt)\n", " delta = torch.tensor(step_delta, dtype=dt)\n", " for _ in range(1000):\n", " w = w - delta\n", " print(f\" {name:12s}: final w = {w.item():.6f} (expected 0.900000)\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Measure on the GPU (or run the CPU quick path)\n", "\n", "### 3a · Static memory breakdown: weights, gradients, and AdamW states\n", "\n", "Measure `torch.cuda.memory_allocated()` after each stage of creating a training step: (1) model\n", "weights on GPU, (2) after `.backward()` (weights + gradients, once activations are freed), and\n", "(3) after `optimizer.step()` (weights + gradients + AdamW's `m` and `v`)." ], "id": "lab-5-1-memory-09" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " clear_mem()\n", " torch.manual_seed(0)\n", " m_stat = SmallGPT(**CFG).to(DEVICE)\n", " n_p = count_params(m_stat)\n", " mem_w = torch.cuda.memory_allocated()\n", "\n", " x_s = torch.randint(0, CFG[\"vocab_size\"], (2, CFG[\"seq_len\"]), device=DEVICE)\n", " y_s = torch.randint(0, CFG[\"vocab_size\"], (2, CFG[\"seq_len\"]), device=DEVICE)\n", " loss_s = F.cross_entropy(m_stat(x_s).reshape(-1, CFG[\"vocab_size\"]), y_s.reshape(-1))\n", " loss_s.backward()\n", " del loss_s, x_s, y_s\n", " gc.collect()\n", " mem_wg = torch.cuda.memory_allocated()\n", "\n", " opt_s = torch.optim.AdamW(m_stat.parameters(), lr=3e-4)\n", " opt_s.step()\n", " mem_wgo = torch.cuda.memory_allocated()\n", "\n", " comp_rows = [\n", " {\"component\": \"weights_fp32\", \"formula_bytes\": 4 * n_p, \"measured_bytes\": mem_w,\n", " \"formula_mb\": round(4 * n_p / 1e6, 2), \"measured_mb\": round(mem_w / 1e6, 2),\n", " \"measured_b_per_param\": round(mem_w / n_p, 3)},\n", " {\"component\": \"gradients_fp32\", \"formula_bytes\": 4 * n_p, \"measured_bytes\": mem_wg - mem_w,\n", " \"formula_mb\": round(4 * n_p / 1e6, 2), \"measured_mb\": round((mem_wg - mem_w) / 1e6, 2),\n", " \"measured_b_per_param\": round((mem_wg - mem_w) / n_p, 3)},\n", " {\"component\": \"adamw_states_fp32\", \"formula_bytes\": 8 * n_p, \"measured_bytes\": mem_wgo - mem_wg,\n", " \"formula_mb\": round(8 * n_p / 1e6, 2), \"measured_mb\": round((mem_wgo - mem_wg) / 1e6, 2),\n", " \"measured_b_per_param\": round((mem_wgo - mem_wg) / n_p, 3)},\n", " {\"component\": \"total_static\", \"formula_bytes\": 16 * n_p, \"measured_bytes\": mem_wgo,\n", " \"formula_mb\": round(16 * n_p / 1e6, 2), \"measured_mb\": round(mem_wgo / 1e6, 2),\n", " \"measured_b_per_param\": round(mem_wgo / n_p, 3)},\n", " ]\n", " print(f\"Static memory breakdown for SmallGPT (N = {n_p:,}):\")\n", " for r in comp_rows:\n", " print(f\" {r['component']:18s} formula {r['formula_mb']:6.2f} MB | \"\n", " f\"measured {r['measured_mb']:6.2f} MB ({r['measured_b_per_param']:.3f} B/param)\")\n", " save_csv(\"components.csv\", comp_rows)\n", " del m_stat, opt_s\n", " clear_mem()\n", "else:\n", " print(f\"Skipping CUDA allocator breakdown on {DEVICE} (no CUDA GPU present).\")\n", " print(f\"Exact formula for this CPU model (N = {N_PARAMS:,}): \"\n", " f\"weights {4*N_PARAMS/1e6:.2f} MB, grads {4*N_PARAMS/1e6:.2f} MB, \"\n", " f\"AdamW {8*N_PARAMS/1e6:.2f} MB, total {16*N_PARAMS/1e6:.2f} MB (16.0 B/param).\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3b · Activation memory growth with sequence length `T`\n", "\n", "Measure peak activation memory (`peak_allocated - static`) at fixed batch size `B = 4` as sequence\n", "length doubles from `T = 128` to `1,024`, comparing PyTorch's fused SDPA (linear in `T`) against\n", "eager `Q @ K^T` attention (which materialises `[B, H, T, T]` and grows quadratically)." ], "id": "lab-5-1-memory-11" }, { "cell_type": "code", "metadata": {}, "source": [ "def measure_step_cuda(batch_size, seq_len, accum_steps=1, use_bf16=False,\n", " grad_checkpoint=False, eager=False, warmup=2, repeats=7):\n", " clear_mem()\n", " torch.manual_seed(0)\n", " cfg = dict(CFG, seq_len=seq_len)\n", " model = SmallGPT(**cfg, grad_checkpoint=grad_checkpoint, eager=eager).to(DEVICE)\n", " opt = torch.optim.AdamW(model.parameters(), lr=3e-4)\n", " micro_bs = batch_size // accum_steps\n", " assert batch_size % accum_steps == 0\n", "\n", " x = torch.randint(0, cfg[\"vocab_size\"], (accum_steps, micro_bs, seq_len), device=DEVICE)\n", " y = torch.randint(0, cfg[\"vocab_size\"], (accum_steps, micro_bs, seq_len), device=DEVICE)\n", "\n", " def one_step():\n", " opt.zero_grad(set_to_none=True)\n", " for m in range(accum_steps):\n", " with torch.amp.autocast(\"cuda\", dtype=torch.bfloat16, enabled=use_bf16):\n", " logits = model(x[m])\n", " loss = F.cross_entropy(logits.reshape(-1, cfg[\"vocab_size\"]), y[m].reshape(-1)) / accum_steps\n", " loss.backward()\n", " opt.step()\n", "\n", " for _ in range(warmup):\n", " one_step()\n", " torch.cuda.synchronize()\n", " static_bytes = torch.cuda.memory_allocated()\n", "\n", " torch.cuda.reset_peak_memory_stats()\n", " times_ms = []\n", " for _ in range(repeats):\n", " ev0 = torch.cuda.Event(enable_timing=True)\n", " ev1 = torch.cuda.Event(enable_timing=True)\n", " ev0.record()\n", " one_step()\n", " ev1.record()\n", " ev1.synchronize()\n", " times_ms.append(ev0.elapsed_time(ev1))\n", "\n", " peak_alloc = torch.cuda.max_memory_allocated()\n", " peak_res = torch.cuda.max_memory_reserved()\n", " times_ms.sort()\n", " med_ms = times_ms[len(times_ms) // 2]\n", " n_p = count_params(model)\n", "\n", " del model, opt, x, y\n", " clear_mem()\n", " return {\n", " \"params\": n_p,\n", " \"static_mb\": round(static_bytes / 1e6, 2),\n", " \"peak_alloc_mb\": round(peak_alloc / 1e6, 2),\n", " \"peak_reserved_mb\": round(peak_res / 1e6, 2),\n", " \"activations_mb\": round((peak_alloc - static_bytes) / 1e6, 2),\n", " \"ms_per_step\": round(med_ms, 2),\n", " \"tokens_per_s\": round((batch_size * seq_len) / (med_ms / 1000.0), 1),\n", " }\n", "\n", "\n", "if ON_GPU:\n", " act_rows = []\n", " print(f\"{'attn':6s} {'prec':4s} {'T':>5s} | {'peak MB':>9s} {'act MB':>9s} {'est act MB':>10s} | {'ms/step':>8s}\")\n", " print(\"-\" * 66)\n", " for eager, prec, use_bf16 in [(True, \"fp32\", False), (False, \"fp32\", False), (False, \"bf16\", True)]:\n", " attn_name = \"eager\" if eager else \"sdpa\"\n", " for T in (128, 256, 512, 1024):\n", " r = measure_step_cuda(batch_size=4, seq_len=T, use_bf16=use_bf16, eager=eager, warmup=2, repeats=5)\n", " est = estimate_memory_bytes(\n", " r[\"params\"], CFG[\"n_layer\"], CFG[\"d_model\"], 4, T,\n", " vocab_size=CFG[\"vocab_size\"], n_head=CFG[\"n_head\"],\n", " precision=\"bf16_autocast\" if use_bf16 else \"fp32\",\n", " eager_attn=eager,\n", " )\n", " est_act_mb = round(est[\"activations\"] / 1e6, 2)\n", " row = {\n", " \"machine\": MACHINE, \"attention\": attn_name, \"precision\": prec,\n", " \"batch_size\": 4, \"seq_len\": T,\n", " \"static_mb\": r[\"static_mb\"], \"peak_alloc_mb\": r[\"peak_alloc_mb\"],\n", " \"activations_mb\": r[\"activations_mb\"], \"est_activations_mb\": est_act_mb,\n", " \"ms_per_step\": r[\"ms_per_step\"],\n", " }\n", " act_rows.append(row)\n", " print(f\"{attn_name:6s} {prec:4s} {T:5d} | {r['peak_alloc_mb']:9.2f} {r['activations_mb']:9.2f} \"\n", " f\"{est_act_mb:10.2f} | {r['ms_per_step']:8.2f}\")\n", " save_csv(\"activation-growth.csv\", act_rows)\n", "else:\n", " print(f\"Skipping CUDA activation-growth sweep on {DEVICE}.\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3c · Comparing the four training tricks at a fixed effective batch (`B_eff = 16, T = 512`)\n", "\n", "Every row below processes the **exact same 8,192 tokens per optimizer step** (`B_eff = 16`,\n", "`T = 512`) on the same 29.7 M-parameter GPT. Compare peak VRAM, activation memory, step time,\n", "and throughput as we turn on `bf16` autocast, gradient accumulation (`4 × 4`), and activation\n", "checkpointing." ], "id": "lab-5-1-memory-13" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " CONFIG_SPECS = [\n", " (\"fp32\", 16, 1, False, False),\n", " (\"fp32 + ckpt\", 16, 1, False, True),\n", " (\"bf16\", 16, 1, True, False),\n", " (\"bf16 + accum (4x4)\", 16, 4, True, False),\n", " (\"bf16 + ckpt\", 16, 1, True, True),\n", " (\"bf16 + accum + ckpt\", 16, 4, True, True),\n", " ]\n", " cfg_rows = []\n", " print(f\"{'config':20s} | {'micro':>5s} {'acc':>3s} | {'static':>7s} {'act':>8s} {'peak':>8s} | {'ms':>7s} {'tok/s':>9s}\")\n", " print(\"-\" * 82)\n", " for label, eff_bs, acc, use_bf16, ckpt in CONFIG_SPECS:\n", " r = measure_step_cuda(batch_size=eff_bs, seq_len=CFG[\"seq_len\"], accum_steps=acc,\n", " use_bf16=use_bf16, grad_checkpoint=ckpt, warmup=2, repeats=7)\n", " row = {\n", " \"machine\": MACHINE, \"config\": label,\n", " \"eff_batch\": eff_bs, \"micro_batch\": eff_bs // acc, \"accum_steps\": acc,\n", " \"seq_len\": CFG[\"seq_len\"], \"precision\": \"bf16\" if use_bf16 else \"fp32\",\n", " \"checkpointing\": ckpt, **r,\n", " }\n", " cfg_rows.append(row)\n", " print(f\"{label:20s} | {eff_bs//acc:5d} {acc:3d} | {r['static_mb']:7.1f} {r['activations_mb']:8.1f} \"\n", " f\"{r['peak_alloc_mb']:8.1f} | {r['ms_per_step']:7.2f} {r['tokens_per_s']:9,.1f}\")\n", " save_csv(\"configs.csv\", cfg_rows)\n", "else:\n", " # Quick CPU/MPS timing check of fp32 vs fp32 + checkpointing (bf16 CUDA autocast skipped)\n", " print(f\"Running quick {DEVICE} timing comparison (B=8, T={CFG['seq_len']}):\")\n", " for ckpt in (False, True):\n", " torch.manual_seed(0)\n", " m_q = SmallGPT(**CFG, grad_checkpoint=ckpt).to(DEVICE)\n", " opt_q = torch.optim.AdamW(m_q.parameters(), lr=3e-4)\n", " xq = torch.randint(0, CFG[\"vocab_size\"], (8, CFG[\"seq_len\"]), device=DEVICE)\n", " yq = torch.randint(0, CFG[\"vocab_size\"], (8, CFG[\"seq_len\"]), device=DEVICE)\n", " for _ in range(2):\n", " opt_q.zero_grad(set_to_none=True)\n", " F.cross_entropy(m_q(xq).reshape(-1, CFG[\"vocab_size\"]), yq.reshape(-1)).backward()\n", " opt_q.step()\n", " sync()\n", " ts = []\n", " for _ in range(5):\n", " t0 = time.perf_counter()\n", " opt_q.zero_grad(set_to_none=True)\n", " F.cross_entropy(m_q(xq).reshape(-1, CFG[\"vocab_size\"]), yq.reshape(-1)).backward()\n", " opt_q.step()\n", " sync()\n", " ts.append((time.perf_counter() - t0) * 1000.0)\n", " ts.sort()\n", " print(f\" fp32 checkpointing={str(ckpt):5s}: median {ts[len(ts)//2]:.2f} ms/step\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3d · Largest batch size that fits on the GPU\n", "\n", "Binary search for the exact largest micro-batch size `B` (at `T = 512`) that completes two full\n", "AdamW training steps without raising `torch.OutOfMemoryError`. With gradient accumulation, the\n", "*effective* batch size `micro_batch × K` has no VRAM ceiling at all." ], "id": "lab-5-1-memory-15" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " def try_measure(bs, use_bf16, ckpt):\n", " try:\n", " return measure_step_cuda(\n", " batch_size=bs, seq_len=CFG[\"seq_len\"], use_bf16=use_bf16,\n", " grad_checkpoint=ckpt, warmup=1, repeats=3,\n", " )\n", " except torch.OutOfMemoryError:\n", " return None\n", "\n", " max_rows = []\n", " print(f\"{'config':14s} | {'max B':>5s} {'OOM B':>5s} | {'peak MB':>9s} {'res MB':>9s} | {'ms/step':>8s} {'tok/s':>10s}\")\n", " print(\"-\" * 74)\n", " for label, use_bf16, ckpt in [\n", " (\"fp32\", False, False),\n", " (\"bf16\", True, False),\n", " (\"fp32 + ckpt\", False, True),\n", " (\"bf16 + ckpt\", True, True),\n", " ]:\n", " lo, hi = 1, 512\n", " best_r = None\n", " b = 1\n", " while b <= 512:\n", " r = try_measure(b, use_bf16, ckpt)\n", " clear_mem()\n", " if r is not None:\n", " lo, best_r = b, r\n", " b *= 2\n", " else:\n", " hi = b\n", " break\n", " while lo + 1 < hi:\n", " mid = (lo + hi) // 2\n", " r = try_measure(mid, use_bf16, ckpt)\n", " clear_mem()\n", " if r is not None:\n", " lo, best_r = mid, r\n", " else:\n", " hi = mid\n", " row = {\n", " \"machine\": MACHINE, \"config\": label, \"seq_len\": CFG[\"seq_len\"],\n", " \"max_batch\": lo, \"oom_batch\": hi,\n", " \"peak_alloc_mb\": best_r[\"peak_alloc_mb\"], \"peak_reserved_mb\": best_r[\"peak_reserved_mb\"],\n", " \"ms_per_step\": best_r[\"ms_per_step\"], \"tokens_per_s\": best_r[\"tokens_per_s\"],\n", " }\n", " max_rows.append(row)\n", " print(f\"{label:14s} | {lo:5d} {hi:5d} | {best_r['peak_alloc_mb']:9.1f} {best_r['peak_reserved_mb']:9.1f} | \"\n", " f\"{best_r['ms_per_step']:8.2f} {best_r['tokens_per_s']:10,.1f}\")\n", " save_csv(\"max-batch.csv\", max_rows)\n", "else:\n", " print(f\"Skipping 12 GB max-batch binary search on {DEVICE}.\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3e · Gradient accumulation equivalence check\n", "\n", "In Ch 1.2 and Ch 1.3 you learned that **gradients add**. Here we verify numerically that one\n", "batch of `16` sequences and `4` accumulated micro-batches of `4` sequences (each loss divided by\n", "`4`) produce identical parameter gradients up to floating-point rounding — in both `fp32` and\n", "`bf16`. (This runs on both GPU and CPU.)" ], "id": "lab-5-1-memory-17" }, { "cell_type": "code", "metadata": {}, "source": [ "eq_cfg = dict(CFG, seq_len=min(CFG[\"seq_len\"], 128))\n", "eq_rows = []\n", "modes = [(\"fp32\", False)] + ([(\"bf16\", True)] if BF16_OK else [])\n", "\n", "for prec_name, use_bf16 in modes:\n", " clear_mem()\n", " torch.manual_seed(42)\n", " x_full = torch.randint(0, eq_cfg[\"vocab_size\"], (16, eq_cfg[\"seq_len\"]), device=DEVICE)\n", " y_full = torch.randint(0, eq_cfg[\"vocab_size\"], (16, eq_cfg[\"seq_len\"]), device=DEVICE)\n", "\n", " torch.manual_seed(0)\n", " m_big = SmallGPT(**eq_cfg).to(DEVICE)\n", " with torch.amp.autocast(\"cuda\", dtype=torch.bfloat16, enabled=use_bf16):\n", " l_big = F.cross_entropy(m_big(x_full).reshape(-1, eq_cfg[\"vocab_size\"]), y_full.reshape(-1))\n", " l_big.backward()\n", " g_big = [p.grad.detach().clone() for p in m_big.parameters()]\n", "\n", " torch.manual_seed(0)\n", " m_acc = SmallGPT(**eq_cfg).to(DEVICE)\n", " loss_acc_sum = 0.0\n", " for k in range(4):\n", " sl = slice(k * 4, (k + 1) * 4)\n", " with torch.amp.autocast(\"cuda\", dtype=torch.bfloat16, enabled=use_bf16):\n", " l_micro = F.cross_entropy(m_acc(x_full[sl]).reshape(-1, eq_cfg[\"vocab_size\"]), y_full[sl].reshape(-1)) / 4\n", " loss_acc_sum += l_micro.item()\n", " l_micro.backward()\n", " g_acc = [p.grad.detach().clone() for p in m_acc.parameters()]\n", "\n", " max_abs = max((a - b).abs().max().item() for a, b in zip(g_big, g_acc))\n", " max_g = max(a.abs().max().item() for a in g_big)\n", " rel = max_abs / max_g\n", " row = {\n", " \"machine\": MACHINE, \"precision\": prec_name, \"eff_batch\": 16, \"accum_steps\": 4,\n", " \"loss_big\": round(l_big.item(), 6), \"loss_accum\": round(loss_acc_sum, 6),\n", " \"max_abs_diff\": f\"{max_abs:.3e}\", \"max_grad\": f\"{max_g:.3e}\", \"rel_diff\": f\"{rel:.3e}\",\n", " }\n", " eq_rows.append(row)\n", " print(f\"Accumulation check ({prec_name:4s}): loss_big={l_big.item():.6f}, loss_accum={loss_acc_sum:.6f}, \"\n", " f\"max_abs_diff={max_abs:.3e}, rel_diff={rel:.3e}\")\n", " del m_big, m_acc, g_big, g_acc, x_full, y_full\n", " clear_mem()\n", "\n", "if ON_GPU:\n", " save_csv(\"accum-equiv.csv\", eq_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Plots\n", "\n", "Plot (1) peak memory vs step time across the six training configurations at `B_eff = 16, T = 512`,\n", "and (2) activation memory growth vs sequence length `T` (SDPA vs eager attention)." ], "id": "lab-5-1-memory-19" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " if ON_GPU:\n", " fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4.4))\n", "\n", " labels = [r[\"config\"] for r in cfg_rows]\n", " peaks = [r[\"peak_alloc_mb\"] / 1000.0 for r in cfg_rows]\n", " times = [r[\"ms_per_step\"] for r in cfg_rows]\n", " x_pos = range(len(labels))\n", " ax1.bar(x_pos, peaks, alpha=0.75, label=\"Peak allocated (GB)\")\n", " ax1.set_xticks(list(x_pos))\n", " ax1.set_xticklabels(labels, rotation=22, ha=\"right\", fontsize=8.5)\n", " ax1.set_ylabel(\"Peak VRAM (GB)\")\n", " ax1.set_title(\"B_eff = 16, T = 512: peak VRAM and step time\")\n", " ax1_t = ax1.twinx()\n", " ax1_t.plot(list(x_pos), times, color=\"black\", marker=\"o\", linewidth=1.8, label=\"Step time (ms)\")\n", " ax1_t.set_ylabel(\"Step time (ms)\")\n", "\n", " for attn_name, prec, style in [(\"eager\", \"fp32\", \"s--\"), (\"sdpa\", \"fp32\", \"o-\"), (\"sdpa\", \"bf16\", \"^-\")]:\n", " sub = [r for r in act_rows if r[\"attention\"] == attn_name and r[\"precision\"] == prec]\n", " ax2.plot([r[\"seq_len\"] for r in sub], [r[\"activations_mb\"] / 1000.0 for r in sub],\n", " style, label=f\"{attn_name} ({prec})\")\n", " ax2.set_xlabel(\"Sequence length T (B = 4)\")\n", " ax2.set_ylabel(\"Activation memory (GB)\")\n", " ax2.set_title(\"Activation growth: linear (SDPA) vs quadratic (eager)\")\n", " ax2.legend()\n", " plt.tight_layout()\n", " plt.show()\n", " else:\n", " print(\"GPU sweep plots skipped on non-CUDA device.\")\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "Compare your GPU outputs against the book's RTX 3060 12 GB reference run (exact times and peak\n", "MB depend on your GPU and PyTorch version; the *relations* hold on any NVIDIA GPU):\n", "\n", "- **Static memory breakdown (`N = 29,676,544`):** weights `119.75 MB` (`4.035 B/param`),\n", " gradients `120.80 MB` (`4.071 B/param`), AdamW states `242.66 MB` (`8.177 B/param`), total\n", " `483.21 MB` (`16.283 B/param` measured vs `16.000 B/param` = `474.82 MB` formula).\n", "- **Master-weights demo:** pure `bf16` and pure `fp16` both finish at `1.000000` (zero movement\n", " after 1,000 updates of `-1e-4`), while `fp32` master reaches `0.899983` (expected `0.900000`).\n", "- **Fixed effective batch `B_eff = 16, T = 512`:**\n", " - `fp32`: peak `3,622.6 MB`, `290.24 ms/step` (`28,224.8 tok/s`).\n", " - `bf16`: peak `2,472.4 MB` (−31.8 %), `107.19 ms/step` (**2.71× faster**).\n", " - `bf16 + accum (4×4)`: peak `1,058.8 MB` (−70.8 % vs `fp32`), `123.46 ms/step`.\n", " - `bf16 + ckpt`: peak `1,331.5 MB` (−46.1 % vs `bf16`), `127.68 ms/step` (+19.1 % vs `bf16`).\n", " - `bf16 + accum + ckpt`: peak `734.5 MB` (**4.93× less** than `fp32`), `147.48 ms/step` (still\n", " **1.97× faster** than `fp32`).\n", "- **Largest batch on 12 GB (`T = 512`):** `fp32` max `54`, `bf16` max `82`, `fp32 + ckpt` max\n", " `140`, `bf16 + ckpt` max `185`.\n", "- **Accumulation equivalence (`B = 16` vs `4×4`, `T = 128`):** `max_abs_diff = 9.499e-08` in\n", " `fp32` and `7.706e-04` in `bf16`." ], "id": "lab-5-1-memory-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Explore\n", "\n", "Change one knob at a time and write one sentence on what changed and why.\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| optimizer | swap `torch.optim.AdamW` for `torch.optim.SGD(..., momentum=0.9)` and plain `SGD` in section 3a | How many bytes per parameter drop out of the static memory bill, and what does that do to peak VRAM at `B = 16`? |\n", "| vocabulary size | change `vocab_size` from `8192` to `50257` (GPT-2's vocabulary) in `measure_step_cuda` at `B = 16, T = 512` | Why does activation checkpointing save a *smaller* fraction of peak VRAM when `V = 50,257`? (Callback: Ch 2.3.) |\n", "| selective checkpointing | checkpoint only the first 4 of the 8 blocks (`i < 4`) instead of all 8 | Where does selective checkpointing sit on the memory-vs-time curve between no checkpointing and full checkpointing? |\n", "| accumulation steps `K` | keep `B_eff = 16` and sweep `accum_steps = 1, 2, 4, 8, 16` in `bf16` | Why does step time rise slightly at `K = 16` (`micro_batch = 1`) even though total tokens are unchanged? (Callback: Ch 4.1's roofline & launch overhead.) |\n", "| sequence length `T` | double `T` to `1024` and halve `B` to `8` (same `8,192` tokens/step) with SDPA vs eager attention | Why does peak memory stay nearly constant for SDPA but jump sharply for eager attention? |" ], "id": "lab-5-1-memory-22" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Failure playground\n", "\n", "Three training loops below are broken in the exact ways real large-scale runs fail. For each:\n", "run it, read the symptom, diagnose the cause, and fix it. Hints are in Review 5.1; answers are\n", "not." ], "id": "lab-5-1-memory-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7a · `fp16` without loss scaling: silent gradient underflow\n", "\n", "A colleague trains the GPT on a small patterned sequence for 80 steps (loss falls below `0.05`,\n", "like mid-to-late training when predictions become confident), then switches to `float16` autocast\n", "**without** `torch.amp.GradScaler`. Compare the fraction of exact-zero gradients in the\n", "transformer blocks across `fp32`, `bf16`, and unscaled `fp16`." ], "id": "lab-5-1-memory-25" }, { "cell_type": "code", "metadata": {}, "source": [ "clear_mem()\n", "torch.manual_seed(0)\n", "fp_cfg = dict(CFG)\n", "m_fp = SmallGPT(**fp_cfg).to(DEVICE)\n", "opt_fp = torch.optim.AdamW(m_fp.parameters(), lr=3e-4)\n", "\n", "# Structured repeating pattern so the model learns quickly to low loss (< 0.05)\n", "pat_len = fp_cfg[\"seq_len\"] + 1\n", "base_seq = torch.arange(pat_len, device=DEVICE) % min(64, fp_cfg[\"vocab_size\"])\n", "x_pat = base_seq[:-1].unsqueeze(0).repeat(4, 1)\n", "y_pat = base_seq[1:].unsqueeze(0).repeat(4, 1)\n", "\n", "for _ in range(80):\n", " opt_fp.zero_grad(set_to_none=True)\n", " with torch.amp.autocast(\"cuda\", dtype=torch.bfloat16, enabled=BF16_OK):\n", " l_tr = F.cross_entropy(m_fp(x_pat).reshape(-1, fp_cfg[\"vocab_size\"]), y_pat.reshape(-1))\n", " l_tr.backward()\n", " opt_fp.step()\n", "sync()\n", "print(f\"7a trained checkpoint loss: {l_tr.item():.5f}\")\n", "\n", "block_total = sum(p.numel() for p in m_fp.blocks.parameters())\n", "\n", "# 1. fp32 reference\n", "m_fp.zero_grad(set_to_none=True)\n", "F.cross_entropy(m_fp(x_pat).reshape(-1, fp_cfg[\"vocab_size\"]), y_pat.reshape(-1)).backward()\n", "z_fp32 = sum((p.grad == 0).sum().item() for p in m_fp.blocks.parameters())\n", "below_norm = sum((p.grad.abs() < 2**-14).sum().item() for p in m_fp.blocks.parameters())\n", "below_sub = sum((p.grad.abs() < 2**-24).sum().item() for p in m_fp.blocks.parameters())\n", "\n", "# 2. BROKEN: fp16 without GradScaler\n", "m_broken = SmallGPT(**fp_cfg).to(DEVICE)\n", "m_broken.load_state_dict(m_fp.state_dict())\n", "if ON_GPU:\n", " with torch.amp.autocast(\"cuda\", dtype=torch.float16):\n", " l_b = F.cross_entropy(m_broken(x_pat).reshape(-1, fp_cfg[\"vocab_size\"]), y_pat.reshape(-1))\n", " l_b.backward()\n", "else:\n", " # CPU fallback: pure float16 weights/activations to show the same fp16 underflow cliff\n", " m_broken = m_broken.half()\n", " l_b = F.cross_entropy(m_broken(x_pat).reshape(-1, fp_cfg[\"vocab_size\"]).float(), y_pat.reshape(-1))\n", " l_b.backward()\n", "z_fp16_noscale = sum((p.grad == 0).sum().item() for p in m_broken.blocks.parameters())\n", "\n", "print(f\"7a block parameters: {block_total:,}\")\n", "print(f\" fp32 reference : {z_fp32:10,d} exact-zero grads ({100*z_fp32/block_total:5.2f} %)\")\n", "print(f\" fp32 |grad| < 2^-14 : {below_norm:10,d} ({100*below_norm/block_total:5.2f} %) [below fp16 smallest normal]\")\n", "print(f\" fp32 |grad| < 2^-24 : {below_sub:10,d} ({100*below_sub/block_total:5.2f} %) [below fp16 smallest subnormal]\")\n", "print(f\" fp16 WITHOUT GradScaler : {z_fp16_noscale:10,d} exact-zero grads ({100*z_fp16_noscale/block_total:5.2f} %)\")\n", "\n", "if BF16_OK:\n", " m_bf = SmallGPT(**fp_cfg).to(DEVICE)\n", " m_bf.load_state_dict(m_fp.state_dict())\n", " with torch.amp.autocast(\"cuda\", dtype=torch.bfloat16):\n", " l_bf = F.cross_entropy(m_bf(x_pat).reshape(-1, fp_cfg[\"vocab_size\"]), y_pat.reshape(-1))\n", " l_bf.backward()\n", " z_bf16 = sum((p.grad == 0).sum().item() for p in m_bf.blocks.parameters())\n", " print(f\" bf16 WITHOUT GradScaler : {z_bf16:10,d} exact-zero grads ({100*z_bf16/block_total:5.2f} %)\")\n", " del m_bf\n", "\n", "del m_fp, opt_fp, m_broken, x_pat, y_pat\n", "clear_mem()" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: zero errors, no `NaN`, yet a large share of the transformer's gradients silently turned\n", "into exact `0.0` in unscaled `fp16` — even more than the fraction of reference gradients below\n", "`2^-24`. Why is the zero fraction in `fp16` *higher* than the fraction of final `fp32` gradients\n", "below `2^-24`? Why does `bf16` need no scaler on the exact same batch? Fix the broken cell using\n", "`torch.amp.GradScaler` and verify that the zero-gradient fraction drops back to `0.00 %`." ], "id": "lab-5-1-memory-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7b · Gradient accumulation without dividing the loss by `K`\n", "\n", "A colleague splits an effective batch of `16` into `K = 8` micro-batches of `2` and calls\n", "`loss.backward()` on each micro-batch, forgetting to divide `loss` by `8`." ], "id": "lab-5-1-memory-28" }, { "cell_type": "code", "metadata": {}, "source": [ "clear_mem()\n", "torch.manual_seed(7)\n", "tiny_cfg = dict(vocab_size=128, seq_len=64, d_model=128, n_layer=4, n_head=4)\n", "# Learnable synthetic task: repeating token pattern with slight per-sequence offset\n", "x_7b = torch.stack([(torch.arange(64, device=DEVICE) + i) % 32 for i in range(16)])\n", "y_7b = torch.roll(x_7b, -1, dims=1)\n", "\n", "for mode in (\"full_batch_16\", \"accum_8_scaled\", \"accum_8_UNSCALED\"):\n", " torch.manual_seed(0)\n", " m_7b = SmallGPT(**tiny_cfg).to(DEVICE)\n", " opt_7b = torch.optim.SGD(m_7b.parameters(), lr=0.08)\n", " snaps = {}\n", " g0 = 0.0\n", " for step in range(26):\n", " opt_7b.zero_grad(set_to_none=True)\n", " if mode == \"full_batch_16\":\n", " loss = F.cross_entropy(m_7b(x_7b).reshape(-1, 128), y_7b.reshape(-1))\n", " loss.backward()\n", " step_loss = loss.item()\n", " else:\n", " step_loss = 0.0\n", " for k in range(8):\n", " sl = slice(k * 2, (k + 1) * 2)\n", " l = F.cross_entropy(m_7b(x_7b[sl]).reshape(-1, 128), y_7b[sl].reshape(-1))\n", " step_loss += l.item() / 8.0\n", " if mode == \"accum_8_scaled\":\n", " (l / 8.0).backward()\n", " else:\n", " l.backward() # BUG: forgot to divide by K = 8\n", " gnorm = math.sqrt(sum(p.grad.pow(2).sum().item() for p in m_7b.parameters()))\n", " if step == 0:\n", " g0 = gnorm\n", " if step in (0, 5, 15, 25):\n", " snaps[step] = step_loss\n", " opt_7b.step()\n", " print(f\"7b {mode:17s} | step 0 |g|={g0:6.3f} | \"\n", " f\"loss@0={snaps[0]:.4f} @5={snaps[5]:.4f} @15={snaps[15]:.4f} @25={snaps[25]:.4f}\")\n", " del m_7b, opt_7b\n", "\n", "del x_7b, y_7b\n", "clear_mem()" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `full_batch_16` and `accum_8_scaled` match to four decimal places, while\n", "`accum_8_UNSCALED` has a gradient norm `8×` larger and its loss climbs instead of falling.\n", "Why did forgetting `/ 8` act like multiplying `lr` by `8` under SGD? Now ask a subtler question:\n", "if you swap `SGD` for `AdamW`, does the bug disappear, or does it merely *hide* while breaking\n", "gradient clipping? And is AdamW's weight decay affected at all? Test it." ], "id": "lab-5-1-memory-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7c · Out of Memory (OOM): read the error and find the component that broke the budget\n", "\n", "Run our 29.7 M-parameter GPT in `fp32` at `B = 64, T = 512` on a 12 GB GPU. PyTorch raises\n", "`torch.OutOfMemoryError` and prints the exact allocation that failed." ], "id": "lab-5-1-memory-31" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " clear_mem()\n", " try:\n", " m_oom = SmallGPT(**CFG).to(DEVICE)\n", " opt_oom = torch.optim.AdamW(m_oom.parameters(), lr=3e-4)\n", " x_oom = torch.randint(0, CFG[\"vocab_size\"], (64, CFG[\"seq_len\"]), device=DEVICE)\n", " y_oom = torch.randint(0, CFG[\"vocab_size\"], (64, CFG[\"seq_len\"]), device=DEVICE)\n", " loss_oom = F.cross_entropy(m_oom(x_oom).reshape(-1, CFG[\"vocab_size\"]), y_oom.reshape(-1))\n", " loss_oom.backward()\n", " opt_oom.step()\n", " print(\"7c unexpectedly fit on this GPU (VRAM > 12 GB); increase batch_size to trigger OOM.\")\n", " except torch.OutOfMemoryError as e:\n", " print(\"7c OutOfMemoryError:\\n\", e)\n", " finally:\n", " for name in (\"m_oom\", \"opt_oom\", \"x_oom\", \"y_oom\", \"loss_oom\"):\n", " if name in globals():\n", " del globals()[name]\n", " clear_mem()\n", "else:\n", " print(\"7c (no CUDA GPU here; showing the book's RTX 3060 12 GB OOM message for fp32, B=64, T=512):\")\n", " print(\n", " \" CUDA out of memory. Tried to allocate 1024.00 MiB. GPU 0 has a total capacity of 11.63 GiB \"\n", " \"of which 856.88 MiB is free. Including non-PyTorch memory, this process has 10.79 GiB memory \"\n", " \"in use. Of the allocated memory 10.40 GiB is allocated by PyTorch, and 246.47 MiB is \"\n", " \"reserved by PyTorch but unallocated.\"\n", " )\n", "\n", "est_oom = estimate_memory_bytes(\n", " 29_676_544, 8, 512, 64, 512, vocab_size=8192, n_head=8, precision=\"fp32\", optimizer=\"adamw\"\n", ")\n", "print(\"\\n7c budget estimate for SmallGPT (29.7M, fp32, AdamW, B=64, T=512):\")\n", "for k in (\"weights\", \"grads\", \"optimizer\", \"activations\", \"total\"):\n", " print(f\" {k:12s}: {est_oom[k]/1e9:6.2f} GB ({est_oom[k]/1024**3:5.2f} GiB)\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `Tried to allocate 1024.00 MiB` when `10.40 GiB` of `11.63 GiB` was already allocated.\n", "Using the model dimensions (`N = 29,676,544`, `B = 64`, `T = 512`, `d = 512`, `L = 8`,\n", "`V = 8,192`, `fp32`):\n", "\n", "1. Which bucket (weights, gradients, optimizer state, or activations) consumed over 95 % of VRAM?\n", "2. Which exact tensor in the forward/backward pass has size **exactly `1,024.00 MiB`**\n", " (`1,073,741,824` bytes)?\n", "3. Name two different changes — neither changing the effective batch size of `64` nor shrinking\n", " the model — that make this step fit with gigabytes to spare." ], "id": "lab-5-1-memory-33" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\n", " \"Versions tested:\",\n", " f\"Python {platform.python_version()},\",\n", " f\"PyTorch {torch.__version__},\",\n", " end=\" \",\n", ")\n", "if ON_GPU:\n", " props = torch.cuda.get_device_properties(0)\n", " print(f\"CUDA {torch.version.cuda}, {props.name} (cc {props.major}.{props.minor}),\", end=\" \")\n", "try:\n", " import matplotlib\n", " print(f\"matplotlib {matplotlib.__version__},\", end=\" \")\n", "except ImportError:\n", " pass\n", "print(f\"{platform.system()} {platform.machine()} ({DEVICE})\")" ], "execution_count": null, "outputs": [], "id": "lab-5-1-memory-34" } ] }