{ "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 0.1 · Your lab, and why language models need GPUs\n", "\n", "**Goal:** get a working PyTorch notebook (laptop, Kaggle or Colab), find out which processor\n", "it runs on, and measure the one operation that large language models spend most of their time\n", "on: multiplying big matrices. By the end you will have your own numbers for \"how much faster is\n", "a GPU\", and a first feel for why model size is measured in gigabytes.\n", "\n", "**Where to run it:**\n", "\n", "| Place | How | Processor you get |\n", "| --- | --- | --- |\n", "| Your laptop | `uv venv && uv pip install torch matplotlib jupyterlab`, then `uv run jupyter lab` | CPU; on an Apple-silicon Mac also the Apple GPU (`mps`) |\n", "| Kaggle | New notebook → Settings → Accelerator: GPU | an NVIDIA GPU (free weekly quota) |\n", "| Google Colab | Runtime → Change runtime type → GPU | an NVIDIA GPU (free, time-limited) |\n", "\n", "Run it on your laptop first. If you can, run it a second time on Kaggle or Colab and compare.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-0-1-setup-00" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Which processors do I have?" ], "id": "lab-0-1-setup-01" }, { "cell_type": "code", "metadata": {}, "source": [ "import platform\n", "import time\n", "\n", "import torch\n", "\n", "print(\"Python \", platform.python_version(), \"|\", platform.system(), platform.machine())\n", "print(\"PyTorch\", torch.__version__)\n", "print(\"CPU threads PyTorch will use:\", torch.get_num_threads())\n", "print(\"NVIDIA GPU (cuda):\", torch.cuda.is_available(),\n", " f\"→ {torch.cuda.get_device_name(0)}\" if torch.cuda.is_available() else \"\")\n", "print(\"Apple GPU (mps): \", torch.backends.mps.is_available())\n", "\n", "DEVICES = [\"cpu\"]\n", "if torch.cuda.is_available():\n", " DEVICES.append(\"cuda\")\n", "elif torch.backends.mps.is_available():\n", " DEVICES.append(\"mps\")\n", "print(\"This lab will measure:\", DEVICES)" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Predict first\n", "\n", "Multiplying two `n × n` matrices takes `n³` multiplications and about as many additions:\n", "**2·n³ floating-point operations (FLOP)**. For `n = 4096` that is 2 × 4096³ ≈ **137 billion**.\n", "\n", "Write down two guesses before you run the next cells:\n", "\n", "1. How many seconds will your laptop's CPU need for one 4096 × 4096 multiply?\n", "2. How many times faster will a GPU be: 2×, 10×, 100×?" ], "id": "lab-0-1-setup-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · A fair stopwatch\n", "\n", "Timing code on a GPU has two traps, and this function avoids both:\n", "\n", "- **Warm-up.** The first call pays one-off costs (loading code onto the GPU, allocating\n", " memory), so we run once before timing.\n", "- **Asynchrony.** Python only *queues* work for the GPU and moves on immediately. We must wait\n", " for the GPU to finish (`synchronize`) before stopping the clock. Section 8a shows what\n", " happens if you forget." ], "id": "lab-0-1-setup-04" }, { "cell_type": "code", "metadata": {}, "source": [ "def sync(device):\n", " if device == \"cuda\":\n", " torch.cuda.synchronize()\n", " elif device == \"mps\":\n", " torch.mps.synchronize()\n", "\n", "\n", "def time_matmul(n, device, dtype=torch.float32, repeats=5):\n", " a = torch.randn(n, n, device=device, dtype=dtype)\n", " b = torch.randn(n, n, device=device, dtype=dtype)\n", " a @ b # warm-up\n", " sync(device)\n", " times = []\n", " for _ in range(repeats):\n", " start = time.perf_counter()\n", " a @ b\n", " sync(device) # wait for the device to really finish\n", " times.append(time.perf_counter() - start)\n", " times.sort()\n", " seconds = times[len(times) // 2] # the median: robust to one slow run\n", " return seconds, 2 * n**3 / seconds / 1e9 # (seconds, GFLOP/s)\n", "\n", "\n", "s, g = time_matmul(1024, \"cpu\")\n", "print(f\"1024 × 1024 on cpu: {s * 1000:.1f} ms → {g:.0f} GFLOP/s\")" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Measure: the same multiply, growing sizes, every processor you have" ], "id": "lab-0-1-setup-06" }, { "cell_type": "code", "metadata": {}, "source": [ "SIZES = [128, 256, 512, 1024, 2048, 4096]\n", "rows = []\n", "for device in DEVICES:\n", " dtypes = [torch.float32] + ([torch.float16] if device != \"cpu\" else [])\n", " for dtype in dtypes:\n", " for n in SIZES:\n", " s, g = time_matmul(n, device, dtype)\n", " rows.append({\"device\": device, \"dtype\": str(dtype).replace(\"torch.\", \"\"),\n", " \"n\": n, \"ms\": round(s * 1000, 3), \"gflops\": round(g, 1)})\n", " print(f\"{device:4s} {rows[-1]['dtype']:8s} n={n:5d} {s * 1000:9.2f} ms {g:9.1f} GFLOP/s\")" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Save your numbers: Review 0.1 asks you to compare them with a classmate's or with the book's." ], "id": "lab-0-1-setup-08" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "\n", "name = torch.cuda.get_device_name(0) if torch.cuda.is_available() else f\"{platform.system()} {platform.machine()}\"\n", "with open(\"lab-0-1-results.csv\", \"w\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=[\"machine\", \"device\", \"dtype\", \"n\", \"ms\", \"gflops\"])\n", " w.writeheader()\n", " for r in rows:\n", " w.writerow({\"machine\": name, **r})\n", "print(\"saved lab-0-1-results.csv,\", len(rows), \"rows\")" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-09" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, ax = plt.subplots(figsize=(7, 4))\n", " for device in DEVICES:\n", " for dtype in sorted({r[\"dtype\"] for r in rows if r[\"device\"] == device}):\n", " pts = [r for r in rows if r[\"device\"] == device and r[\"dtype\"] == dtype]\n", " ax.plot([r[\"n\"] for r in pts], [r[\"gflops\"] for r in pts], marker=\"o\", label=f\"{device} {dtype}\")\n", " ax.set_xscale(\"log\", base=2); ax.set_yscale(\"log\")\n", " ax.set_xlabel(\"matrix size n (n × n)\"); ax.set_ylabel(\"GFLOP/s (higher is faster)\")\n", " ax.legend(); ax.set_title(\"Matrix multiply speed\")\n", " plt.tight_layout(); plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "Your numbers depend on your machine, so check the *shape*, not the exact values:\n", "\n", "- On every processor, GFLOP/s **rises with n** and then levels off. Small multiplies cannot\n", " keep the hardware busy; big ones can.\n", "- On a GPU, small sizes (128, 256) are often **no faster than the CPU**, sometimes slower:\n", " starting work on the GPU has a fixed cost that a tiny multiply cannot hide.\n", "- At `n = 4096` the GPU is **many times** faster than the CPU, and `float16` is faster again\n", " than `float32`.\n", "\n", "The chapter (Ch 0.1) shows the book's own measurements on an Apple M1 laptop and an\n", "NVIDIA RTX 3060, so you can place yours." ], "id": "lab-0-1-setup-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · How big is a model?\n", "\n", "A model is mostly a long list of numbers, its **parameters** (weights). Each one is stored in\n", "a few bytes: 4 in `float32`, 2 in `float16`/`bfloat16`, 1 or even 0.5 when *quantized*\n", "(Vol 6). Just *holding* a model needs `parameters × bytes per parameter`." ], "id": "lab-0-1-setup-12" }, { "cell_type": "code", "metadata": {}, "source": [ "def gigabytes(params, bytes_per_param):\n", " return params * bytes_per_param / 1e9\n", "\n", "\n", "for label, params in [(\"GPT-2 small\", 124e6), (\"a 1B model\", 1e9), (\"a 7B model\", 7e9), (\"a 70B model\", 70e9)]:\n", " print(f\"{label:12s} float32 {gigabytes(params, 4):7.1f} GB float16 {gigabytes(params, 2):7.1f} GB \"\n", " f\"4-bit {gigabytes(params, 0.5):6.1f} GB\")\n", "if torch.cuda.is_available():\n", " print(f\"\\nyour GPU has {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB of memory\")" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Which of these fit on your GPU, or in your laptop's memory? Keep the answer: in Vol 6 you will\n", "see that holding the weights is only part of the bill." ], "id": "lab-0-1-setup-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Explore\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| size | add `8192` to `SIZES` (GPU only) | Does GFLOP/s keep growing, or has it levelled off? |\n", "| dtype | `torch.bfloat16` on the GPU | Faster than `float32`? The same as `float16`? |\n", "| many small multiplies | time 1000 multiplies of 64 × 64 in a loop vs one 2048 × 2048 | Which does more FLOP per second, and why? |\n", "| threads | `torch.set_num_threads(1)` then re-run the CPU sweep | How much of your CPU speed came from using several cores? |" ], "id": "lab-0-1-setup-15" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Failure playground\n", "\n", "### 8a · The impossible speed-up\n", "\n", "A classmate times the GPU without `synchronize` and reports an amazing number. Run it (on a\n", "GPU or an Apple GPU; on CPU only, read along)." ], "id": "lab-0-1-setup-17" }, { "cell_type": "code", "metadata": {}, "source": [ "dev = DEVICES[-1]\n", "n = 4096\n", "a = torch.randn(n, n, device=dev)\n", "b = torch.randn(n, n, device=dev)\n", "a @ b\n", "sync(dev)\n", "start = time.perf_counter()\n", "for _ in range(10):\n", " c = a @ b # no sync inside the timed region\n", "elapsed = time.perf_counter() - start\n", "print(f\"{dev}: 'measured' {10 * 2 * n**3 / elapsed / 1e12:.1f} TFLOP/s\")\n", "sync(dev)" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: on a GPU, the \"measured\" speed is far above what the chip can physically do (an\n", "RTX 3060's peak for `float32` is about 12.7 TFLOP/s; see Ch 0.1). What did the stopwatch\n", "actually measure? Fix it, and explain why the last `sync(dev)` line still takes a while.\n", "On a CPU the number looks normal: why does the CPU not have this trap?" ], "id": "lab-0-1-setup-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8b · Out of memory\n", "\n", "How big a matrix can you multiply? Compute before you allocate." ], "id": "lab-0-1-setup-20" }, { "cell_type": "code", "metadata": {}, "source": [ "n = 65536\n", "need = 3 * n * n * 4 / 1e9 # a, b and the result, float32\n", "print(f\"n = {n}: needs about {need:.0f} GB\")\n", "if dev == \"cuda\":\n", " try:\n", " a = torch.empty(n, n, device=\"cuda\")\n", " b = torch.empty(n, n, device=\"cuda\")\n", " c = a @ b\n", " except torch.OutOfMemoryError as e:\n", " print(\"OutOfMemoryError:\", str(e).splitlines()[0][:160])\n", " finally:\n", " a = b = c = None\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"skipped on\", dev, \": asking a laptop for this much memory makes it swap, not fail cleanly\")" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: an `OutOfMemoryError` on the GPU (or the skip message). Read the error: how much did\n", "PyTorch try to allocate, and how much was free? What is the largest `n` that fits on your GPU\n", "for this multiply? Why does a laptop *swap* instead of failing cleanly, and why is that worse?" ], "id": "lab-0-1-setup-22" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"Versions tested:\", f\"Python {platform.python_version()}\", f\"PyTorch {torch.__version__}\",\n", " f\"on {name} ({', '.join(DEVICES)})\")" ], "execution_count": null, "outputs": [], "id": "lab-0-1-setup-23" } ] }