{ "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 4.1 · Measure Your GPU and Draw its Roofline\n", "\n", "**Goal:** measure what your GPU can really do (memory bandwidth, matrix-multiply speed, the cost\n", "of launching one tiny operation, the gain from fusing a chain of operations), put every\n", "measurement on one roofline chart, and break the measurements three ways.\n", "\n", "**Runs on:** an NVIDIA GPU (free Kaggle or Colab T4; the book's numbers come from an RTX 3060).\n", "Without a GPU every cell still runs on CPU (or the Apple GPU `mps`) with smaller sizes, so you can\n", "read the code and the printed tables, but the roofline is a GPU story.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-4-1-roofline-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import math\n", "import os\n", "import pathlib\n", "import platform\n", "import shutil\n", "import statistics\n", "import subprocess\n", "import sys\n", "import tempfile\n", "import time\n", "\n", "import torch\n", "import torch.nn.functional as F\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 path\n", "ON_GPU = DEVICE == \"cuda\"\n", "print(\"PyTorch\", torch.__version__, \"| device:\", DEVICE)\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 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-4-1-roofline\"\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", "REF_NOTE = \"\" if ON_GPU else \" (RTX 3060 reference figures, not this machine)\"\n", "MACHINE = torch.cuda.get_device_name(0) if ON_GPU else f\"{platform.system()} {platform.machine()} ({DEVICE})\"\n", "SMALL = not ON_GPU # CPU / mps: smaller sizes so every cell finishes quickly" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write your answers down before you run anything below.\n", "\n", "1. **Vector add.** `z = x + y` on float32 tensors: how many FLOP per element, and how many bytes\n", " move per element? What is its arithmetic intensity (FLOP per byte)?\n", "2. **The ridge.** Your GPU's spec sheet says peak float32 compute `P` (FLOP/s) and memory bandwidth\n", " `B` (bytes/s). At which intensity `P / B` does an operation stop being limited by memory? Will\n", " vector add be above or below it?\n", "3. **Achieved bandwidth.** Copying a 1 GiB tensor: what fraction of the spec-sheet bandwidth do you\n", " expect to reach: 50 %, 70 %, 90 %, 100 %?\n", "4. **Matrix size.** A `n x n` float32 matrix multiply does `2 n^3` FLOP on `3 n^2 x 4` bytes\n", " (read A and B, write C, each once). At which `n` does it cross the ridge?\n", "5. **Fusion.** `y = gelu(x * 2 + 1)` run as three separate operations moves 24 bytes per element;\n", " fused into one kernel it moves 8. How much faster do you expect the fused version to be?\n", "6. **Launch.** How long, in microseconds, does the GPU need to start one tiny operation? 1? 10? 100?" ], "id": "lab-4-1-roofline-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Build by hand: intensity and the roofline\n", "\n", "**Arithmetic intensity** = FLOP performed / bytes moved to and from GPU memory. The **roofline**\n", "says no operation can run faster than\n", "\n", "```text\n", "attainable FLOP/s = min( peak FLOP/s , intensity x bandwidth )\n", "```\n", "\n", "First the spec sheet of *this* machine, read from the driver (nothing typed in by hand)." ], "id": "lab-4-1-roofline-03" }, { "cell_type": "code", "metadata": {}, "source": [ "# FP32 lanes per SM for the architectures we know (a published fact per architecture; not in torch).\n", "FP32_PER_SM = {(7, 0): 64, (7, 5): 64, (8, 0): 64, (8, 6): 128, (8, 9): 128, (9, 0): 128}\n", "\n", "if ON_GPU:\n", " p = torch.cuda.get_device_properties(0)\n", " lanes = FP32_PER_SM.get((p.major, p.minor))\n", " clock_ghz = p.clock_rate / 1e6 # kHz -> GHz (boost clock the driver reports)\n", " bw_spec = p.memory_bus_width / 8 * (2 * p.memory_clock_rate / 1e6) # bytes per transfer x Gtransfers/s -> GB/s\n", " peak_fp32 = p.multi_processor_count * lanes * 2 * clock_ghz if lanes else float(\"nan\") # GFLOP/s\n", " spec = {\n", " \"machine\": p.name,\n", " \"compute_capability\": f\"{p.major}.{p.minor}\",\n", " \"sms\": p.multi_processor_count,\n", " \"fp32_lanes_per_sm\": lanes,\n", " \"boost_clock_ghz\": round(clock_ghz, 3),\n", " \"memory_bus_bits\": p.memory_bus_width,\n", " \"memory_clock_mhz\": p.memory_clock_rate / 1e3,\n", " \"bandwidth_spec_gbs\": round(bw_spec, 1),\n", " \"peak_fp32_gflops\": round(peak_fp32, 1),\n", " \"l2_bytes\": p.L2_cache_size,\n", " \"shared_mem_per_sm_bytes\": p.shared_memory_per_multiprocessor,\n", " \"shared_mem_per_block_optin_bytes\": p.shared_memory_per_block_optin,\n", " \"registers_per_sm\": p.regs_per_multiprocessor,\n", " \"warp_size\": p.warp_size,\n", " \"max_threads_per_sm\": p.max_threads_per_multi_processor,\n", " \"vram_bytes\": p.total_memory,\n", " }\n", "else:\n", " # No GPU: use the RTX 3060 figures of Ch 0.1 so the tables below still make sense.\n", " spec = {\"machine\": \"RTX 3060 (reference figures, not this machine)\", \"bandwidth_spec_gbs\": 360.0,\n", " \"peak_fp32_gflops\": 12742.0}\n", " bw_spec, peak_fp32 = 360.0, 12742.0\n", "\n", "for k, v in spec.items():\n", " print(f\"{k:34s} {v}\")\n", "ridge_spec = peak_fp32 / bw_spec\n", "print(f\"\\nridge point (spec): {peak_fp32:,.0f} GFLOP/s / {bw_spec:.0f} GB/s = {ridge_spec:.1f} FLOP/byte\")\n", "save_csv(\"specs.csv\", [{\"key\": k, \"value\": v} for k, v in spec.items()])" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now the worked intensities. Per element for the elementwise operations, per `n` for matrix\n", "multiply (assuming each matrix crosses the memory bus exactly once: the best case)." ], "id": "lab-4-1-roofline-05" }, { "cell_type": "code", "metadata": {}, "source": [ "def attainable(intensity, peak_gflops, bw_gbs):\n", " return min(peak_gflops, intensity * bw_gbs)\n", "\n", "\n", "# (name, FLOP per element, bytes per element). FLOP counts of gelu and softmax are a convention:\n", "# every add, multiply, exp, erf, max... counts as 1; the real cost is a few times more, which does not\n", "# change the conclusion (see the cell below).\n", "ELEMENTWISE = [\n", " (\"copy z = x\", 0, 8),\n", " (\"vector add z = x + y\", 1, 12),\n", " (\"scale z = x * 2\", 1, 8),\n", " (\"chain unfused: mul, add, gelu as 3 kernels (10 FLOP)\", 10, 24),\n", " (\"chain fused: one kernel (10 FLOP)\", 10, 8),\n", " (\"softmax, 5 separate ops (5 FLOP)\", 5, 32),\n", " (\"softmax, one kernel (5 FLOP)\", 5, 8),\n", "]\n", "print(f\"{'operation':58s} {'FLOP/el':>8s} {'bytes/el':>9s} {'FLOP/byte':>10s} {'roof @spec GFLOP/s':>19s}\")\n", "for name, fl, by in ELEMENTWISE:\n", " inten = fl / by\n", " print(f\"{name:58s} {fl:8d} {by:9d} {inten:10.3f} {attainable(inten, peak_fp32, bw_spec):19.1f}\")\n", "\n", "# even if exp / erf / tanh cost 20 FLOP each, an elementwise op stays far below the ridge:\n", "print(f\"\\nupper bound: 30 FLOP on 8 bytes = {30/8:.2f} FLOP/byte, ridge = {ridge_spec:.1f}\")\n", "\n", "print(f\"\\n{'n':>6s} {'FLOP 2n^3':>14s} {'bytes fp32':>14s} {'FLOP/byte fp32':>15s} {'FLOP/byte fp16':>15s} side of the ridge (fp32)\")\n", "for n in (32, 64, 128, 256, 512, 1024, 4096):\n", " fl = 2 * n**3\n", " b32 = 3 * n * n * 4\n", " b16 = 3 * n * n * 2\n", " side = \"memory-bound\" if fl / b32 < ridge_spec else \"compute-bound\"\n", " print(f\"{n:6d} {fl:14,d} {b32:14,d} {fl / b32:15.1f} {fl / b16:15.1f} {side}\")\n", "print(f\"\\nfp32 matmul crosses the ridge at n = 6 x {ridge_spec:.1f} = {6 * ridge_spec:.0f}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Measure: a timer you can trust\n", "\n", "GPU launches are asynchronous: Python returns long before the GPU is done (Lab 0.1, playground 8a).\n", "Two tools fix this: `torch.cuda.synchronize()` and **CUDA events**, timestamps recorded *on the GPU's\n", "own timeline*. The helper below records an event, runs the operation `reps` times back to back,\n", "records a second event, waits, and divides. Tiny operations need many repetitions so the total is\n", "well above the timer's resolution." ], "id": "lab-4-1-roofline-07" }, { "cell_type": "code", "metadata": {}, "source": [ "def _loop_ms(fn, reps, device=DEVICE):\n", " if device == \"cuda\":\n", " start = torch.cuda.Event(enable_timing=True)\n", " end = torch.cuda.Event(enable_timing=True)\n", " start.record()\n", " for _ in range(reps):\n", " fn()\n", " end.record()\n", " end.synchronize()\n", " return start.elapsed_time(end)\n", " sync(device)\n", " t0 = time.perf_counter()\n", " for _ in range(reps):\n", " fn()\n", " sync(device)\n", " return (time.perf_counter() - t0) * 1e3\n", "\n", "\n", "def bench(fn, min_ms=30.0, repeats=7, warmup=3, device=DEVICE):\n", " \"\"\"Median milliseconds per call: warm up, size the loop to last >= min_ms, repeat, take the median.\"\"\"\n", " for _ in range(warmup):\n", " fn()\n", " sync(device)\n", " one = max(_loop_ms(fn, 1, device), 1e-4)\n", " reps = int(min(max(1, math.ceil(min_ms / one)), 20000))\n", " times = [_loop_ms(fn, reps, device) / reps for _ in range(repeats)]\n", " return statistics.median(times)\n", "\n", "\n", "x = torch.randn(1 << 24, device=DEVICE)\n", "print(f\"sanity: x + x on 2^24 floats takes {bench(lambda: x + x):.3f} ms on {DEVICE}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3a · Achieved memory bandwidth\n", "\n", "Copy and add tensors from 4 K to 256 M elements. Bytes moved: copy `2 x 4N` (read x, write z), add\n", "`3 x 4N` (read x and y, write z). Small tensors fit in the L2 cache, so read what happens as the\n", "size grows past it." ], "id": "lab-4-1-roofline-09" }, { "cell_type": "code", "metadata": {}, "source": [ "bw_rows = []\n", "max_exp = 26 if SMALL else 28\n", "for e in range(12, max_exp + 1):\n", " n = 1 << e\n", " xs = torch.randn(n, device=DEVICE)\n", " ys = torch.randn(n, device=DEVICE)\n", " zs = torch.empty_like(xs)\n", " for op, fn, streams in (\n", " (\"copy\", lambda: zs.copy_(xs), 2),\n", " (\"add\", lambda: torch.add(xs, ys, out=zs), 3),\n", " ):\n", " ms = bench(fn)\n", " bytes_moved = streams * 4 * n\n", " bw_rows.append({\"machine\": MACHINE, \"op\": op, \"n_elements\": n, \"bytes_moved\": bytes_moved,\n", " \"ms\": round(ms, 5), \"gbs\": round(bytes_moved / ms / 1e6, 1)})\n", " del xs, ys, zs\n", " if ON_GPU:\n", " torch.cuda.empty_cache()\n", "\n", "print(f\"{'op':5s} {'elements':>12s} {'MiB moved':>10s} {'ms':>9s} {'GB/s':>8s} % of spec {bw_spec:.0f}{REF_NOTE}\")\n", "for r in bw_rows:\n", " print(f\"{r['op']:5s} {r['n_elements']:12,d} {r['bytes_moved'] / 2**20:10.1f} {r['ms']:9.4f} {r['gbs']:8.1f} {100 * r['gbs'] / bw_spec:6.1f} %\")\n", "save_csv(\"bandwidth.csv\", bw_rows)\n", "\n", "big = [r for r in bw_rows if r[\"n_elements\"] >= (1 << 24)]\n", "BW_MEAS = max(r[\"gbs\"] for r in big) # best sustained bandwidth on tensors far larger than L2\n", "print(f\"\\nmeasured bandwidth ceiling (best of copy / add, >= 2^24 elements): {BW_MEAS:.1f} GB/s \"\n", " f\"= {100 * BW_MEAS / bw_spec:.1f} % of spec{REF_NOTE}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3b · Achieved matrix-multiply speed\n", "\n", "`2 n^3` FLOP divided by the measured time, float32 and float16, `n` from 64 to 8192. On the GPU the\n", "float16 multiply runs on the **tensor cores**. The `intensity` column assumes each matrix crosses the\n", "memory bus once (the best case), so it is an upper bound on the real intensity." ], "id": "lab-4-1-roofline-11" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"float32 matmul precision setting:\", torch.get_float32_matmul_precision(),\n", " \"| allow_tf32:\", getattr(torch.backends.cuda.matmul, \"allow_tf32\", None))\n", "\n", "mm_rows = []\n", "sizes_mm = [64, 128, 256, 512, 1024, 2048] if SMALL else [64, 128, 256, 512, 1024, 2048, 4096, 8192]\n", "dtypes = [(\"float32\", torch.float32)] + ([] if DEVICE == \"cpu\" else [(\"float16\", torch.float16)])\n", "for dname, dt in dtypes:\n", " b = torch.tensor([], dtype=dt).element_size()\n", " for n in sizes_mm:\n", " a = torch.randn(n, n, device=DEVICE, dtype=dt)\n", " w = torch.randn(n, n, device=DEVICE, dtype=dt)\n", " ms = bench(lambda: a @ w, min_ms=40)\n", " flop = 2 * n**3\n", " mm_rows.append({\"machine\": MACHINE, \"op\": \"matmul\", \"dtype\": dname, \"n\": n, \"batch\": n,\n", " \"ms\": round(ms, 5), \"gflops\": round(flop / ms / 1e6, 1),\n", " \"flop_per_byte\": round(flop / (3 * n * n * b), 2),\n", " \"bytes_ideal\": 3 * n * n * b})\n", " del a, w\n", " if ON_GPU:\n", " torch.cuda.empty_cache()\n", "\n", "print(f\"{'dtype':8s} {'n':>6s} {'ms':>9s} {'GFLOP/s':>10s} {'FLOP/byte':>10s}\")\n", "for r in mm_rows:\n", " print(f\"{r['dtype']:8s} {r['n']:6d} {r['ms']:9.4f} {r['gflops']:10.1f} {r['flop_per_byte']:10.1f}\")\n", "save_csv(\"matmul.csv\", mm_rows)\n", "\n", "PEAK_MEAS = {d: max(r[\"gflops\"] for r in mm_rows if r[\"dtype\"] == d) for d, _ in dtypes}\n", "for d, v in PEAK_MEAS.items():\n", " extra = f\" = {100 * v / peak_fp32:.1f} % of the fp32 spec peak{REF_NOTE}\" if d == \"float32\" else \"\"\n", " print(f\"best measured {d}: {v:,.1f} GFLOP/s{extra}\")\n", "if ON_GPU:\n", " q = subprocess.run([\"nvidia-smi\", \"--query-gpu=clocks.sm,clocks.max.sm,power.draw,temperature.gpu\",\n", " \"--format=csv,noheader\"], capture_output=True, text=True)\n", " print(\"nvidia-smi right after the matmul sweep (sm clock, max sm clock, power, temp):\", q.stdout.strip())" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Which kernel did cuBLAS pick? The library chooses a different implementation for different shapes,\n", "which is one reason achieved FLOP/s is not a smooth curve in `n`. The profiler lists the kernels:" ], "id": "lab-4-1-roofline-13" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " from torch.profiler import ProfilerActivity, profile\n", "\n", " for n in (2048, 4096, 8192):\n", " a = torch.randn(n, n, device=\"cuda\")\n", " w = torch.randn(n, n, device=\"cuda\")\n", " a @ w\n", " torch.cuda.synchronize()\n", " with profile(activities=[ProfilerActivity.CUDA]) as prof:\n", " a @ w\n", " torch.cuda.synchronize()\n", " names = [e.key for e in prof.key_averages() if \"gemm\" in e.key.lower()]\n", " print(f\"float32 n={n}: {names[0][:78] if names else 'no gemm kernel found'}\")\n", " del a, w\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"no GPU: skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3c · One weight read, many tokens: matrix times vector\n", "\n", "A language model producing one token per user per step multiplies its weight matrix by a *vector*\n", "(batch 1). That is `2 n^2` FLOP on `n^2` weights: at float16, 1 FLOP per byte. Give the same weights\n", "`b` tokens at once (a matrix `n x b`) and the same read serves `b` times the FLOP. This is the\n", "reason inference servers batch (Vol 6): watch the time per step as `b` grows." ], "id": "lab-4-1-roofline-15" }, { "cell_type": "code", "metadata": {}, "source": [ "skinny_rows = []\n", "n_sk = 4096 if SMALL else 8192\n", "for dname, dt in dtypes:\n", " bsz = torch.tensor([], dtype=dt).element_size()\n", " A = torch.randn(n_sk, n_sk, device=DEVICE, dtype=dt)\n", " for bt in (1, 2, 4, 8, 16, 32, 64, 128, 256, 512):\n", " X = torch.randn(n_sk, bt, device=DEVICE, dtype=dt)\n", " ms = bench(lambda: A @ X, min_ms=30)\n", " flop = 2 * n_sk * n_sk * bt\n", " bytes_ideal = bsz * (n_sk * n_sk + 2 * n_sk * bt)\n", " skinny_rows.append({\"machine\": MACHINE, \"op\": \"weights_times_batch\", \"dtype\": dname, \"n\": n_sk, \"batch\": bt,\n", " \"ms\": round(ms, 5), \"gflops\": round(flop / ms / 1e6, 1),\n", " \"flop_per_byte\": round(flop / bytes_ideal, 2), \"bytes_ideal\": bytes_ideal,\n", " \"gbs_ideal\": round(bytes_ideal / ms / 1e6, 1)})\n", " del X\n", " del A\n", " if ON_GPU:\n", " torch.cuda.empty_cache()\n", "\n", "print(f\"n = {n_sk}: weights {n_sk}x{n_sk}, times a [{n_sk}, b] activation matrix\")\n", "print(f\"{'dtype':8s} {'b':>4s} {'ms':>9s} {'GFLOP/s':>10s} {'FLOP/byte':>10s} {'GB/s':>8s}\")\n", "for r in skinny_rows:\n", " print(f\"{r['dtype']:8s} {r['batch']:4d} {r['ms']:9.4f} {r['gflops']:10.1f} {r['flop_per_byte']:10.2f} {r['gbs_ideal']:8.1f}\")\n", "save_csv(\"skinny.csv\", skinny_rows)" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3d · Kernel launch latency\n", "\n", "Three numbers for one tiny operation (`t.add_(1)` on a one-element tensor): the time Python spends\n", "*issuing* it, the time per operation when you issue many in a row, and the full round trip\n", "(issue, run, wait for the answer) that a naive stopwatch sees." ], "id": "lab-4-1-roofline-17" }, { "cell_type": "code", "metadata": {}, "source": [ "t_tiny = torch.zeros(1, device=DEVICE)\n", "fn_tiny = lambda: t_tiny.add_(1)\n", "for _ in range(50):\n", " fn_tiny()\n", "sync()\n", "\n", "k = 2000\n", "t0 = time.perf_counter()\n", "for _ in range(k):\n", " fn_tiny()\n", "issue_us = (time.perf_counter() - t0) / k * 1e6\n", "sync()\n", "\n", "stream_us = bench(fn_tiny, min_ms=20) * 1e3\n", "\n", "rt = []\n", "for _ in range(300):\n", " t0 = time.perf_counter()\n", " fn_tiny()\n", " sync()\n", " rt.append((time.perf_counter() - t0) * 1e6)\n", "roundtrip_us = statistics.median(rt)\n", "\n", "# the same 1000 tiny steps as ONE big operation (a [1000]-element add): no launch cost per step\n", "big_t = torch.zeros(1000, device=DEVICE)\n", "one_big_us = bench(lambda: big_t.add_(1), min_ms=20) * 1e3\n", "\n", "launch_rows = [\n", " {\"machine\": MACHINE, \"what\": \"python_issue_per_op\", \"us\": round(issue_us, 2)},\n", " {\"machine\": MACHINE, \"what\": \"back_to_back_per_op\", \"us\": round(stream_us, 2)},\n", " {\"machine\": MACHINE, \"what\": \"roundtrip_with_sync\", \"us\": round(roundtrip_us, 2)},\n", " {\"machine\": MACHINE, \"what\": \"one_op_on_1000_elements\", \"us\": round(one_big_us, 2)},\n", "]\n", "for r in launch_rows:\n", " print(f\"{r['what']:26s} {r['us']:9.2f} us\")\n", "print(f\"1000 tiny ops back to back would take about {1000 * stream_us / 1e3:.2f} ms; one 1000-element op takes {one_big_us / 1e3:.4f} ms\")\n", "save_csv(\"launch.csv\", launch_rows)" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3e · Operator fusion: the same maths in one pass\n", "\n", "`y = gelu(x * 2 + 1)` written as three PyTorch operations launches three kernels; each reads its\n", "whole input from memory and writes its whole output back. `torch.compile` fuses them into one kernel\n", "that reads `x` once and writes `y` once. The softmax rows are the same experiment on a reduction.\n", "The first call of a compiled function compiles it; the loop below makes that call first and never\n", "times it (playground 7c measures it on purpose)." ], "id": "lab-4-1-roofline-19" }, { "cell_type": "code", "metadata": {}, "source": [ "def chain(x):\n", " return F.gelu(x * 2 + 1)\n", "\n", "\n", "def softmax5(x): # softmax written as five separate operations\n", " m = x.max(dim=-1, keepdim=True).values\n", " e = (x - m).exp()\n", " return e / e.sum(dim=-1, keepdim=True)\n", "\n", "\n", "compile_ok, compile_note = False, \"\"\n", "if ON_GPU:\n", " try:\n", " import torch._dynamo\n", " compile_ok = True\n", " except Exception as ex: # pragma: no cover\n", " compile_note = f\"{type(ex).__name__}: {ex}\"\n", "else:\n", " compile_note = \"skipped: no NVIDIA GPU (torch.compile is exercised on the GPU)\"\n", "print(\"torch.compile available for this lab:\", compile_ok, compile_note)\n", "\n", "fusion_rows = []\n", "chain_sizes = [1 << 18, 1 << 22] if SMALL else [1 << 16, 1 << 18, 1 << 20, 1 << 22, 1 << 24, 1 << 26]\n", "\n", "for n in chain_sizes:\n", " xc = torch.randn(n, device=DEVICE)\n", " variants = [(\"unfused\", chain, 24)]\n", " if compile_ok:\n", " cc = torch.compile(chain, dynamic=False)\n", " yc = cc(xc) # first call compiles; it is excluded from the timings below\n", " sync()\n", " assert torch.allclose(yc, chain(xc), atol=1e-5), \"compiled chain differs\"\n", " variants.append((\"fused (torch.compile)\", cc, 8))\n", " for name, fn, byt in variants:\n", " ms = bench(lambda: fn(xc))\n", " fusion_rows.append({\"machine\": MACHINE, \"op\": \"chain_mul_add_gelu\", \"variant\": name, \"n_elements\": n,\n", " \"ideal_bytes_per_element\": byt, \"ms\": round(ms, 5),\n", " \"gbs\": round(byt * n / ms / 1e6, 1),\n", " \"gflops\": round(10 * n / ms / 1e6, 1), \"flop_per_byte\": round(10 / byt, 3)})\n", "\n", "rows_sm = 4096 if SMALL else 4096\n", "cols_sm = 1024 if SMALL else 4096\n", "xs = torch.randn(rows_sm, cols_sm, device=DEVICE)\n", "nsm = xs.numel()\n", "sm_variants = [(\"5 separate ops\", softmax5, 32), (\"torch.softmax (one kernel)\", lambda t: torch.softmax(t, dim=-1), 8)]\n", "if compile_ok:\n", " cs = torch.compile(softmax5, dynamic=False)\n", " ys = cs(xs) # first call compiles; excluded from the timings below\n", " sync()\n", " assert torch.allclose(ys, torch.softmax(xs, dim=-1), atol=1e-6), \"compiled softmax differs\"\n", " sm_variants.append((\"5 ops, torch.compile\", cs, 8))\n", "for name, fn, byt in sm_variants:\n", " ms = bench(lambda: fn(xs))\n", " fusion_rows.append({\"machine\": MACHINE, \"op\": f\"softmax_{rows_sm}x{cols_sm}\", \"variant\": name, \"n_elements\": nsm,\n", " \"ideal_bytes_per_element\": byt, \"ms\": round(ms, 5),\n", " \"gbs\": round(byt * nsm / ms / 1e6, 1),\n", " \"gflops\": round(5 * nsm / ms / 1e6, 1), \"flop_per_byte\": round(5 / byt, 3)})\n", "\n", "print(f\"{'op':22s} {'variant':28s} {'elements':>11s} {'ms':>9s} {'ideal GB/s':>11s}\")\n", "for r in fusion_rows:\n", " print(f\"{r['op']:22s} {r['variant']:28s} {r['n_elements']:11,d} {r['ms']:9.4f} {r['gbs']:11.1f}\")\n", "save_csv(\"fusion.csv\", fusion_rows)\n", "\n", "print()\n", "for op in sorted({r[\"op\"] for r in fusion_rows}):\n", " for n in sorted({r[\"n_elements\"] for r in fusion_rows if r[\"op\"] == op}):\n", " sel = {r[\"variant\"]: r[\"ms\"] for r in fusion_rows if r[\"op\"] == op and r[\"n_elements\"] == n}\n", " base = sel.get(\"unfused\") or sel.get(\"5 separate ops\")\n", " for name, ms in sel.items():\n", " if name not in (\"unfused\", \"5 separate ops\"):\n", " print(f\"{op:22s} n={n:>11,d} {name:28s} {base / ms:5.2f}x faster than {'unfused' if 'unfused' in sel else '5 ops'}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Every measurement on one roofline\n", "\n", "The x axis is intensity (FLOP per byte, log scale), the y axis achieved GFLOP/s (log scale). The\n", "slanted roof is `intensity x bandwidth`: the spec sheet's, and the best you measured in 3a. The\n", "flat roofs are the float32 spec peak and the best float16 matmul you measured (a measured ceiling,\n", "not a spec). Every point must lie on or below its roof." ], "id": "lab-4-1-roofline-21" }, { "cell_type": "code", "metadata": {}, "source": [ "points = []\n", "for r in mm_rows:\n", " points.append({\"group\": \"matmul\", \"label\": f\"matmul {r['dtype']} n={r['n']}\", \"dtype\": r[\"dtype\"],\n", " \"flop_per_byte\": r[\"flop_per_byte\"], \"gflops\": r[\"gflops\"]})\n", "for r in skinny_rows:\n", " points.append({\"group\": \"weights_times_batch\", \"label\": f\"{r['dtype']} {r['n']}x{r['n']} @ b={r['batch']}\",\n", " \"dtype\": r[\"dtype\"], \"flop_per_byte\": r[\"flop_per_byte\"], \"gflops\": r[\"gflops\"]})\n", "top_n = max(r[\"n_elements\"] for r in bw_rows)\n", "for r in bw_rows:\n", " if r[\"op\"] == \"add\" and r[\"n_elements\"] == top_n:\n", " points.append({\"group\": \"elementwise\", \"label\": f\"vector add 2^{int(math.log2(top_n))}\", \"dtype\": \"float32\",\n", " \"flop_per_byte\": round(1 / 12, 3), \"gflops\": round(r[\"n_elements\"] / r[\"ms\"] / 1e6, 1)})\n", "n_top_chain = max(r[\"n_elements\"] for r in fusion_rows if r[\"op\"] == \"chain_mul_add_gelu\")\n", "for r in fusion_rows:\n", " if r[\"op\"] == \"chain_mul_add_gelu\" and r[\"n_elements\"] == n_top_chain or r[\"op\"].startswith(\"softmax\"):\n", " points.append({\"group\": \"fusion\", \"label\": f\"{r['op']} {r['variant']}\", \"dtype\": \"float32\",\n", " \"flop_per_byte\": r[\"flop_per_byte\"], \"gflops\": r[\"gflops\"]})\n", "\n", "for pt in points:\n", " peak = PEAK_MEAS.get(pt[\"dtype\"], peak_fp32) if pt[\"dtype\"] == \"float16\" else peak_fp32\n", " roof = attainable(pt[\"flop_per_byte\"], peak, BW_MEAS)\n", " pt[\"roof_gflops\"] = round(roof, 1)\n", " pt[\"pct_of_roof\"] = round(100 * pt[\"gflops\"] / roof, 1)\n", " ridge = peak / BW_MEAS\n", " pt[\"side\"] = \"memory-bound\" if pt[\"flop_per_byte\"] < ridge else \"compute-bound\"\n", "save_csv(\"roofline-points.csv\", points)\n", "\n", "print(f\"{'point':44s} {'FLOP/B':>8s} {'GFLOP/s':>10s} {'roof':>10s} {'% roof':>7s} side\")\n", "for pt in points:\n", " print(f\"{pt['label']:44s} {pt['flop_per_byte']:8.2f} {pt['gflops']:10.1f} {pt['roof_gflops']:10.1f} {pt['pct_of_roof']:7.1f} {pt['side']}\")\n", "\n", "ridge_meas = PEAK_MEAS[\"float32\"] / BW_MEAS\n", "print(f\"\\nspec ridge (fp32): {ridge_spec:.1f} FLOP/byte | measured ridge (best fp32 matmul / measured bandwidth): {ridge_meas:.1f}\")\n", "if \"float16\" in PEAK_MEAS:\n", " print(f\"measured fp16 ridge (best fp16 matmul / measured bandwidth): {PEAK_MEAS['float16'] / BW_MEAS:.1f}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-22" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, ax = plt.subplots(figsize=(8.5, 5.2))\n", " xs_ = [10 ** (i / 20) for i in range(-60, 61)]\n", " ax.plot(xs_, [attainable(i, peak_fp32, bw_spec) for i in xs_], \"--\", color=\"0.55\", label=f\"spec: {peak_fp32 / 1e3:.1f} TFLOP/s fp32, {bw_spec:.0f} GB/s\")\n", " ax.plot(xs_, [attainable(i, PEAK_MEAS.get(\"float16\", peak_fp32), BW_MEAS) for i in xs_], \"-\", color=\"k\",\n", " label=f\"measured: {BW_MEAS:.0f} GB/s, best fp16 {PEAK_MEAS.get('float16', float('nan')) / 1e3:.1f} TFLOP/s\")\n", " marks = {\"matmul\": \"o\", \"weights_times_batch\": \"^\", \"elementwise\": \"s\", \"fusion\": \"D\"}\n", " for g, m in marks.items():\n", " sel = [pt for pt in points if pt[\"group\"] == g]\n", " ax.scatter([pt[\"flop_per_byte\"] for pt in sel], [pt[\"gflops\"] for pt in sel], marker=m, s=28, label=g, zorder=3)\n", " ax.set_xscale(\"log\")\n", " ax.set_yscale(\"log\")\n", " ax.set_xlabel(\"arithmetic intensity (FLOP per byte)\")\n", " ax.set_ylabel(\"achieved GFLOP/s\")\n", " ax.set_title(f\"Roofline of {MACHINE}\")\n", " ax.legend(fontsize=8)\n", " ax.grid(True, which=\"both\", alpha=0.25)\n", " plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: read the table above instead\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Optional · what the profiler says (Nsight Compute)\n", "\n", "Asking the hardware itself which roof a kernel hit: bytes that really crossed the DRAM bus (not the\n", "ideal count of section 2) and how close the memory system and the SMs came to their peak. Needs `ncu` on the machine and permission to\n", "read GPU counters (Kaggle and Colab usually do not allow it: the cell then prints why and moves on)." ], "id": "lab-4-1-roofline-24" }, { "cell_type": "code", "metadata": {}, "source": [ "NCU_TARGET = '''\n", "import sys, torch\n", "kind = sys.argv[1]\n", "d = \"cuda\"\n", "if kind == \"add\":\n", " x = torch.randn(1 << 27, device=d); y = torch.randn(1 << 27, device=d); z = torch.empty_like(x)\n", " f = lambda: torch.add(x, y, out=z)\n", "elif kind in (\"mm32\", \"mm16\"):\n", " dt = torch.float32 if kind == \"mm32\" else torch.float16\n", " a = torch.randn(4096, 4096, device=d, dtype=dt); b = torch.randn(4096, 4096, device=d, dtype=dt)\n", " f = lambda: a @ b\n", "elif kind == \"mv16\":\n", " a = torch.randn(8192, 8192, device=d, dtype=torch.float16); v = torch.randn(8192, device=d, dtype=torch.float16)\n", " f = lambda: a @ v\n", "for _ in range(3):\n", " f()\n", "torch.cuda.synchronize()\n", "torch.cuda.profiler.start(); f(); torch.cuda.synchronize(); torch.cuda.profiler.stop()\n", "'''\n", "NCU_METRICS = (\"gpu__time_duration.sum,dram__bytes_read.sum,dram__bytes_write.sum,\"\n", " \"dram__throughput.avg.pct_of_peak_sustained_elapsed,sm__throughput.avg.pct_of_peak_sustained_elapsed\")\n", "ncu_rows = []\n", "if ON_GPU and shutil.which(\"ncu\"):\n", " with tempfile.TemporaryDirectory() as td:\n", " script = pathlib.Path(td) / \"ncu_target.py\"\n", " script.write_text(NCU_TARGET)\n", " for kind in (\"add\", \"mm32\", \"mm16\", \"mv16\"):\n", " try:\n", " res = subprocess.run([\"ncu\", \"--csv\", \"--profile-from-start\", \"off\", \"--metrics\", NCU_METRICS,\n", " sys.executable, str(script), kind],\n", " capture_output=True, text=True, timeout=300)\n", " except Exception as ex:\n", " print(f\"ncu {kind}: {type(ex).__name__}: {ex}\")\n", " continue\n", " lines = [l for l in res.stdout.splitlines() if l.startswith('\"')]\n", " if not lines:\n", " print(f\"ncu {kind}: no metrics. stderr/stdout tail:\", (res.stdout + res.stderr)[-300:].strip())\n", " continue\n", " rd = list(csv.DictReader(lines))\n", " kname = rd[0][\"Kernel Name\"][:60]\n", " vals = {r[\"Metric Name\"]: float(r[\"Metric Value\"].replace(\",\", \"\")) for r in rd}\n", " unit = {r[\"Metric Name\"]: r[\"Metric Unit\"] for r in rd}\n", " to_bytes = {\"byte\": 1, \"Kbyte\": 1e3, \"Mbyte\": 1e6, \"Gbyte\": 1e9}\n", " to_ms = {\"ns\": 1e-6, \"usecond\": 1e-3, \"us\": 1e-3, \"msecond\": 1.0, \"ms\": 1.0, \"second\": 1e3, \"s\": 1e3}\n", " ms = vals[\"gpu__time_duration.sum\"] * to_ms.get(unit[\"gpu__time_duration.sum\"], float(\"nan\"))\n", " dram = (vals[\"dram__bytes_read.sum\"] * to_bytes.get(unit[\"dram__bytes_read.sum\"], float(\"nan\"))\n", " + vals[\"dram__bytes_write.sum\"] * to_bytes.get(unit[\"dram__bytes_write.sum\"], float(\"nan\")))\n", " flop = {\"add\": 1 << 27, \"mm32\": 2 * 4096**3, \"mm16\": 2 * 4096**3, \"mv16\": 2 * 8192**2}[kind]\n", " ncu_rows.append({\"machine\": MACHINE, \"case\": kind, \"kernel\": kname, \"ms\": round(ms, 4),\n", " \"dram_gb_moved\": round(dram / 1e9, 3),\n", " \"flop_per_dram_byte\": round(flop / dram, 2),\n", " \"dram_gbs\": round(dram / (ms * 1e-3) / 1e9, 1),\n", " \"dram_pct_of_peak\": round(vals[\"dram__throughput.avg.pct_of_peak_sustained_elapsed\"], 1),\n", " \"sm_pct_of_peak\": round(vals[\"sm__throughput.avg.pct_of_peak_sustained_elapsed\"], 1)})\n", " if ncu_rows:\n", " print(f\"{'case':5s} {'ms':>8s} {'DRAM GB':>8s} {'FLOP/DRAM byte':>15s} {'DRAM GB/s':>10s} {'DRAM %peak':>11s} {'SM %peak':>9s} kernel\")\n", " for r in ncu_rows:\n", " print(f\"{r['case']:5s} {r['ms']:8.3f} {r['dram_gb_moved']:8.3f} {r['flop_per_dram_byte']:15.2f} {r['dram_gbs']:10.1f} {r['dram_pct_of_peak']:11.1f} {r['sm_pct_of_peak']:9.1f} {r['kernel']}\")\n", " print(\"(ncu locks the GPU clocks to their base value by default, so its durations are longer than the event timings above: compare bytes and percentages, not GFLOP/s)\")\n", " save_csv(\"ncu.csv\", ncu_rows)\n", "else:\n", " print(\"ncu not available here (needs an NVIDIA GPU and Nsight Compute): skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "Compare your outputs with the book's reference run on an RTX 3060 (your numbers will differ: that\n", "is the point of measuring; a T4 has different peaks and a different ridge). The reference lines are\n", "in the Lab 4.1 page; what must hold on **any** GPU:\n", "\n", "- the best copy / add bandwidth is a large fraction of, and never above, the spec-sheet bandwidth\n", " (small tensors can read above it: they live in the L2 cache);\n", "- float32 matmul at large `n` reaches a good share of the fp32 spec peak; float16 is several times\n", " faster still;\n", "- the fused chain is faster than the unfused one by about the ratio of bytes moved (24 / 8);\n", "- a launch costs microseconds, not nanoseconds;\n", "- no point on the roofline is above its roof." ], "id": "lab-4-1-roofline-26" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"CHECKPOINT\")\n", "cp = [r for r in bw_rows if r[\"op\"] == \"copy\" and r[\"n_elements\"] == max(rr[\"n_elements\"] for rr in bw_rows)][0]\n", "ad = [r for r in bw_rows if r[\"op\"] == \"add\" and r[\"n_elements\"] == cp[\"n_elements\"]][0]\n", "print(f\"copy 2^{int(math.log2(cp['n_elements']))} elements: {cp['gbs']:.1f} GB/s ({100 * cp['gbs'] / bw_spec:.1f} % of spec {bw_spec:.0f})\")\n", "print(f\"add 2^{int(math.log2(ad['n_elements']))} elements: {ad['gbs']:.1f} GB/s ({100 * ad['gbs'] / bw_spec:.1f} % of spec)\")\n", "n_chk = max(r[\"n\"] for r in mm_rows if r[\"dtype\"] == \"float32\")\n", "for dname, _ in dtypes:\n", " r = [r for r in mm_rows if r[\"dtype\"] == dname and r[\"n\"] == min(n_chk, 4096)][0]\n", " print(f\"matmul {dname} n={r['n']}: {r['gflops']:,.1f} GFLOP/s\")\n", "for r in launch_rows:\n", " print(f\"launch {r['what']}: {r['us']:.2f} us\")\n", "bad = [pt[\"label\"] for pt in points if pt[\"pct_of_roof\"] > 105]\n", "print(\"points above their roof (> 105 %):\", bad if bad else \"none\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-27" }, { "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", "| tensor size | in 3a, plot GB/s against `n_elements` (log x) | Where does the curve bend, and what does that size tell you about a cache? |\n", "| dtype | in 3a, repeat the add with `torch.float16` tensors | Do GB/s change? Do elements per second? |\n", "| matmul size | in 3b, add `n = 192`, `n = 1536`, `n = 3000` | Why can an \"odd\" size run slower than the next power of two? |\n", "| tensor cores | in 3b, set `torch.backends.cuda.matmul.allow_tf32 = True` and rerun the float32 sweep | What changed, and what did you give up? |\n", "| batch size | in 3c, use `n = 2048` and `n = 16384` | At which `b` does the time per step start to grow? Does the knee move with `n`? |\n", "| chain length | in 3e, add four more elementwise operations to `chain` | How does the fused time change, and the unfused time? |\n", "| fusion size | in 3e, try `n = 2^10` | Does fusion still help? What dominates now? |" ], "id": "lab-4-1-roofline-28" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Failure playground\n", "\n", "Three ways measurements go wrong. For each: run it, read the symptom, find the cause, fix it.\n", "Hints are in Review 4.1; answers are not." ], "id": "lab-4-1-roofline-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7a · Timing without synchronising, now with events\n", "\n", "Lab 0.1 caught a classmate timing a GPU with a plain stopwatch. This time two people time a\n", "matrix multiply; both think they did it right. (Needs a GPU; on CPU read along.)" ], "id": "lab-4-1-roofline-31" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " n = 4096\n", " a = torch.randn(n, n, device=\"cuda\")\n", " w = torch.randn(n, n, device=\"cuda\")\n", " a @ w\n", " torch.cuda.synchronize()\n", "\n", " # person 1: a stopwatch around ten launches\n", " t0 = time.perf_counter()\n", " for _ in range(10):\n", " c = a @ w\n", " elapsed = time.perf_counter() - t0\n", " print(f\"person 1: {10 * 2 * n**3 / elapsed / 1e12:.1f} TFLOP/s (spec peak {peak_fp32 / 1e3:.1f} TFLOP/s)\")\n", " torch.cuda.synchronize()\n", "\n", " # person 2: CUDA events, as the lab told them\n", " s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)\n", " s.record()\n", " for _ in range(10):\n", " c = a @ w\n", " e.record()\n", " try:\n", " print(f\"person 2: {s.elapsed_time(e):.2f} ms\")\n", " except Exception as ex:\n", " print(\"person 2:\", type(ex).__name__, \"-\", str(ex)[:140])\n", " torch.cuda.synchronize()\n", "else:\n", " print(\"no GPU: skipped (read the cell and answer the questions)\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: person 1 reports a speed the chip cannot reach, person 2's code stops with an error. What\n", "did each timer actually measure, and why is the error message the *better* outcome? Fix both. Then\n", "explain why `end.synchronize()` inside `bench()` is placed where it is." ], "id": "lab-4-1-roofline-33" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7b · \"My kernel is slow, so I removed the maths\"\n", "\n", "A teammate's elementwise step is slow on a large tensor. They replace `torch.tanh(x)` with a\n", "cheaper formula, expecting a speed-up. Here is the timing of five single-kernel operations on the\n", "same 2^26 floats (a GPU is needed; on CPU the sizes are smaller)." ], "id": "lab-4-1-roofline-34" }, { "cell_type": "code", "metadata": {}, "source": [ "n_b = (1 << 22) if SMALL else (1 << 26)\n", "xb = torch.randn(n_b, device=DEVICE)\n", "zb = torch.empty_like(xb)\n", "ops_b = [\n", " (\"x + 1\", lambda: torch.add(xb, 1, out=zb)),\n", " (\"x * x\", lambda: torch.mul(xb, xb, out=zb)),\n", " (\"exp(x)\", lambda: torch.exp(xb, out=zb)),\n", " (\"tanh(x)\", lambda: torch.tanh(xb, out=zb)),\n", " (\"erf(x)\", lambda: torch.erf(xb, out=zb)),\n", "]\n", "print(f\"{'operation':10s} {'ms':>9s} {'GB/s':>8s}\")\n", "for name, fn in ops_b:\n", " ms = bench(fn)\n", " print(f\"{name:10s} {ms:9.4f} {8 * n_b / ms / 1e6:8.1f}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-35" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `exp`, `tanh` and `erf` do many times the arithmetic of `x + 1`, yet the times are almost\n", "the same, so removing maths from the kernel cannot help. Compute the intensity of each, compare it\n", "with the ridge point, and say which change *would* make this step faster. (Compare the same\n", "experiment on a CPU if you have time: is it still true there?)" ], "id": "lab-4-1-roofline-36" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7c · Timing the first call\n", "\n", "A teammate times `torch.compile(chain)` once and reports that compiling \"makes it slower\".\n", "Another reports a CUDA matmul takes over a hundred milliseconds. Both timed a first call. Each\n", "runs in a fresh Python process so nothing is warm (for the compile case the on-disk compiler\n", "caches are switched off, as they would be on your first ever run)." ], "id": "lab-4-1-roofline-37" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU:\n", " code_mm = (\n", " \"import time, torch\\n\"\n", " \"t0 = time.perf_counter(); a = torch.randn(512, 512, device='cuda'); (a @ a); torch.cuda.synchronize()\\n\"\n", " \"first = time.perf_counter() - t0\\n\"\n", " \"t0 = time.perf_counter(); (a @ a); torch.cuda.synchronize()\\n\"\n", " \"second = time.perf_counter() - t0\\n\"\n", " \"print(f'matmul 512, fresh process: first call {first * 1e3:.1f} ms, second call {second * 1e3:.3f} ms')\\n\"\n", " )\n", " res = subprocess.run([sys.executable, \"-c\", code_mm], capture_output=True, text=True)\n", " print(res.stdout.strip() or res.stderr[-300:])\n", " code_c = (\n", " \"import time, torch, torch.nn.functional as F\\n\"\n", " \"def chain(x): return F.gelu(x * 2 + 1)\\n\"\n", " \"x = torch.randn(1 << 22, device='cuda'); chain(x); torch.cuda.synchronize()\\n\"\n", " \"def per_call_ms(f, k=200):\\n\"\n", " \" s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)\\n\"\n", " \" s.record()\\n\"\n", " \" for _ in range(k): f(x)\\n\"\n", " \" e.record(); e.synchronize(); return s.elapsed_time(e) / k\\n\"\n", " \"eager = per_call_ms(chain)\\n\"\n", " \"g = torch.compile(chain, dynamic=False)\\n\"\n", " \"t0 = time.perf_counter(); g(x); torch.cuda.synchronize(); first = time.perf_counter() - t0\\n\"\n", " \"t0 = time.perf_counter(); g(x); torch.cuda.synchronize(); second = time.perf_counter() - t0\\n\"\n", " \"steady = per_call_ms(g)\\n\"\n", " \"print(f'chain 2^22: eager {eager:.3f} ms/call | compiled: first call {first:.2f} s, second call {second * 1e3:.2f} ms, steady {steady:.3f} ms/call')\\n\"\n", " \"print(f'break-even: {first * 1e3 / (eager - steady):.0f} calls')\\n\"\n", " )\n", " if compile_ok:\n", " env = dict(os.environ, TORCHINDUCTOR_FORCE_DISABLE_CACHES=\"1\")\n", " res = subprocess.run([sys.executable, \"-W\", \"ignore\", \"-c\", code_c], capture_output=True, text=True, env=env)\n", " print(res.stdout.strip() or res.stderr[-400:])\n", "else:\n", " print(\"no GPU: skipped (read the cell and answer the questions)\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-38" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the first call takes hundreds or thousands of times longer than every later one. What is\n", "spent in the first call, and who pays it? Re-derive the break-even the cell prints (calls needed\n", "before compiling wins), and say what a benchmark must do before it starts the clock." ], "id": "lab-4-1-roofline-39" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Versions tested" ], "id": "lab-4-1-roofline-40" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"Python\", platform.python_version(), \"|\", platform.platform())\n", "print(\"PyTorch\", torch.__version__, \"| CUDA runtime\", torch.version.cuda)\n", "if ON_GPU:\n", " print(\"GPU:\", torch.cuda.get_device_name(0), \"| compute capability\", torch.cuda.get_device_capability(0))\n", " try:\n", " drv = subprocess.run([\"nvidia-smi\", \"--query-gpu=driver_version\", \"--format=csv,noheader\"],\n", " capture_output=True, text=True).stdout.strip()\n", " print(\"NVIDIA driver\", drv)\n", " except Exception:\n", " pass\n", " try:\n", " import triton\n", " print(\"Triton\", triton.__version__)\n", " except Exception:\n", " print(\"Triton not installed\")\n", " print(\"ncu:\", shutil.which(\"ncu\") or \"not found\")" ], "execution_count": null, "outputs": [], "id": "lab-4-1-roofline-41" } ] }