{ "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.3 · Triton and FlashAttention\n", "\n", "**Goal:** write a fused row-wise softmax kernel in Triton and measure its memory bandwidth against\n", "unfused PyTorch and `torch.softmax`; build online softmax and tiled attention by hand in plain\n", "PyTorch to verify exactness; run a minimal Triton FlashAttention forward kernel; measure time and\n", "peak VRAM of naive attention versus PyTorch's FlashAttention backend (`scaled_dot_product_attention`)\n", "until naive runs out of memory; and break the code three ways.\n", "\n", "**Runs on:** an NVIDIA GPU with Triton (free Kaggle or Colab T4, or any Ampere+ GPU; the book's\n", "numbers come from an RTX 3060 12 GB). Without a CUDA GPU, the online-softmax, tiled-attention, and\n", "precision cells still run on CPU while GPU/Triton-only cells skip cleanly.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-4-3-triton-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 statistics\n", "import subprocess\n", "import time\n", "\n", "os.environ.setdefault(\"TRITON_DEFAULT_FP_FUSION\", \"1\")\n", "\n", "import torch\n", "import torch.nn.functional as F\n", "\n", "if torch.cuda.is_available():\n", " DEVICE = \"cuda\"\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", "\n", "try:\n", " import triton\n", " import triton.language as tl\n", " HAS_TRITON = True\n", "except ImportError:\n", " triton = None\n", " tl = None\n", " HAS_TRITON = False\n", "\n", "print(\n", " f\"PyTorch {torch.__version__} | device: {DEVICE} | \"\n", " f\"Triton: {triton.__version__ if HAS_TRITON else 'not installed'}\"\n", ")\n", "\n", "\n", "def sync(device=DEVICE):\n", " if device == \"cuda\":\n", " torch.cuda.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-3-triton\"\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", "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", " t0 = time.perf_counter()\n", " for _ in range(reps):\n", " fn()\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 >= min_ms, repeat, take 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)), 5000))\n", " times = [_loop_ms(fn, reps, device) / reps for _ in range(repeats)]\n", " return statistics.median(times)\n", "\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(\"machine:\", MACHINE)" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write down your answers before running the cells below:\n", "\n", "1. **Fused softmax.** Softmax written as 5 separate PyTorch ops moves 32 bytes per float32 element\n", " (Ch 4.1). A fused Triton kernel reads `x` once and writes `y` once: 8 bytes per element. On a\n", " `4,096 × 4,096` float32 matrix, roughly how much faster do you expect the Triton kernel to be?\n", "2. **Online softmax.** You split a row into two chunks `[2.0, 1.0]` and `[4.0, 0.0]`. After chunk 1\n", " you have running max `m_1 = 2.0` and running sum `l_1 = e^0 + e^-1`. When chunk 2 arrives with\n", " new max `m_2 = 4.0`, why can you not just add chunk 2's exponentials to `l_1`? What factor fixes\n", " `l_1`?\n", "3. **Attention matrix size.** Take GPT-2 small's head geometry (`H = 12` heads, `d = 64`), batch\n", " size `B = 4`, in `float16` (2 bytes per element). How many GiB is one `[B, H, T, T]` score matrix\n", " at `T = 4,096`, and at `T = 8,192`? On a 12 GB GPU, where do you expect naive attention to run\n", " out of memory?\n", "4. **FLOPs versus bytes.** Does FlashAttention do fewer matrix-multiply FLOPs than naive attention,\n", " move fewer bytes to and from GPU memory, allocate less VRAM, or all three?\n", "5. **Float16 equality.** If naive attention and FlashAttention compute the exact same mathematical\n", " formula in `float16`, will `torch.equal(out_naive, out_flash)` return `True` or `False`?" ], "id": "lab-4-3-triton-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Triton: a fused softmax kernel\n", "\n", "In Ch 4.2 you wrote CUDA kernels at the *thread* level (`threadIdx.x`, `__shared__`,\n", "`__syncthreads()`). **Triton** lets you write GPU kernels in Python at the *block* (tile) level:\n", "one program instance handles an entire row (or tile) using vectorised operations, and the Triton\n", "compiler handles thread mapping, memory coalescing and shared-memory layout.\n", "\n", "Below we compare three row-wise softmax implementations on float32 matrices of shape `[4096, C]`:\n", "\n", "1. `naive_softmax`: five separate PyTorch ops (`max`, `-`, `exp`, `sum`, `/`) — ideal traffic\n", " 32 bytes/element (4 passes over VRAM).\n", "2. `torch.softmax`: PyTorch's built-in fused CUDA kernel — ideal traffic 8 bytes/element.\n", "3. `triton_softmax`: our 16-line Triton kernel — loads one row once, computes softmax in on-chip\n", " registers/SRAM, writes the row back once — ideal traffic 8 bytes/element." ], "id": "lab-4-3-triton-03" }, { "cell_type": "code", "metadata": {}, "source": [ "def naive_softmax(x):\n", " \"\"\"Five separate PyTorch ops (same unfused baseline as Ch 4.1).\"\"\"\n", " x_max = x.max(dim=-1, keepdim=True).values\n", " z = x - x_max\n", " e = torch.exp(z)\n", " s = e.sum(dim=-1, keepdim=True)\n", " return e / s\n", "\n", "\n", "if ON_GPU and HAS_TRITON:\n", " @triton.jit\n", " def softmax_kernel(\n", " x_ptr,\n", " y_ptr,\n", " x_row_stride,\n", " y_row_stride,\n", " n_cols,\n", " BLOCK_SIZE: tl.constexpr,\n", " ):\n", " # One program instance owns one full row of the input matrix.\n", " row_idx = tl.program_id(0)\n", " col_offsets = tl.arange(0, BLOCK_SIZE)\n", " mask = col_offsets < n_cols\n", "\n", " # Load the row once from global memory into on-chip registers/SRAM.\n", " # Out-of-bounds lanes get -inf so they affect neither max nor exp (exp(-inf) = 0).\n", " x_row_ptr = x_ptr + row_idx * x_row_stride + col_offsets\n", " x = tl.load(x_row_ptr, mask=mask, other=-float(\"inf\"))\n", "\n", " x_max = tl.max(x, axis=0)\n", " numerator = tl.exp(x - x_max)\n", " denominator = tl.sum(numerator, axis=0)\n", " y = numerator / denominator\n", "\n", " # Write the finished row back to global memory once.\n", " y_row_ptr = y_ptr + row_idx * y_row_stride + col_offsets\n", " tl.store(y_row_ptr, y, mask=mask)\n", "\n", " def triton_softmax(x):\n", " n_rows, n_cols = x.shape\n", " block_size = triton.next_power_of_2(n_cols)\n", " num_warps = 4 if block_size <= 1024 else (8 if block_size <= 4096 else 16)\n", " y = torch.empty_like(x)\n", " softmax_kernel[(n_rows,)](\n", " x, y,\n", " x.stride(0), y.stride(0),\n", " n_cols,\n", " BLOCK_SIZE=block_size,\n", " num_warps=num_warps,\n", " )\n", " return y\n", "\n", " # Correctness check on both power-of-two and non-power-of-two row widths\n", " torch.manual_seed(0)\n", " for r, c in ((4096, 4096), (1024, 3000)):\n", " xt = torch.randn(r, c, device=\"cuda\", dtype=torch.float32)\n", " ref = torch.softmax(xt, dim=-1)\n", " got_triton = triton_softmax(xt)\n", " got_naive = naive_softmax(xt)\n", " print(\n", " f\"shape {r}x{c}: max |triton - torch| = {(got_triton - ref).abs().max().item():.2e} | \"\n", " f\"max |naive - torch| = {(got_naive - ref).abs().max().item():.2e}\"\n", " )\n", " del xt, ref, got_triton, got_naive\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"no CUDA GPU with Triton: skipping Triton softmax kernel execution\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now benchmark all three across row widths from `512` to `8,192` (including `3,000`, which is not a\n", "power of two so the `mask` matters). Every matrix is larger than the RTX 3060's 2.25 MiB L2 cache\n", "(`4,096 × 512 × 4 B = 8 MiB` input + `8 MiB` output = `16 MiB`).\n", "\n", "Notice we print two bandwidth numbers:\n", "\n", "- **Effective GB/s** counts only the minimum required bytes (`8 × N`, read `x` once + write `y`\n", " once). Higher means the operation finished faster.\n", "- **Ideal-traffic GB/s** counts each variant's own reads and writes (`32 × N` for 5 separate ops,\n", " `8 × N` for fused). Both hit ~320–330 GB/s on the 3060, proving the unfused version is not\n", " \"wasting bandwidth\": it is saturating the bus while moving 4× too many bytes." ], "id": "lab-4-3-triton-05" }, { "cell_type": "code", "metadata": {}, "source": [ "softmax_rows = []\n", "if ON_GPU and HAS_TRITON:\n", " N_ROWS = 4096\n", " COL_SIZES = [512, 1024, 2048, 3000, 4096, 8192]\n", " print(\n", " f\"{'cols':>6s} | {'naive ms':>9s} {'torch ms':>9s} {'triton ms':>9s} | \"\n", " f\"{'naive eff':>10s} {'torch eff':>10s} {'triton eff':>10s} | {'triton/naive':>12s}\"\n", " )\n", " print(\"-\" * 92)\n", " for n_cols in COL_SIZES:\n", " torch.manual_seed(0)\n", " x = torch.randn(N_ROWS, n_cols, device=\"cuda\", dtype=torch.float32)\n", " n_el = N_ROWS * n_cols\n", " min_bytes = 8 * n_el # 4 B read + 4 B write\n", "\n", " t_naive = bench(lambda: naive_softmax(x))\n", " t_torch = bench(lambda: torch.softmax(x, dim=-1))\n", " t_triton = bench(lambda: triton_softmax(x))\n", "\n", " eff_naive = min_bytes / t_naive / 1e6\n", " eff_torch = min_bytes / t_torch / 1e6\n", " eff_triton = min_bytes / t_triton / 1e6\n", "\n", " for variant, ms, ideal_b in (\n", " (\"naive_5op\", t_naive, 32),\n", " (\"torch_softmax\", t_torch, 8),\n", " (\"triton_fused\", t_triton, 8),\n", " ):\n", " softmax_rows.append({\n", " \"machine\": MACHINE,\n", " \"n_rows\": N_ROWS,\n", " \"n_cols\": n_cols,\n", " \"n_elements\": n_el,\n", " \"variant\": variant,\n", " \"ideal_bytes_per_el\": ideal_b,\n", " \"ms\": round(ms, 5),\n", " \"effective_gbs\": round(min_bytes / ms / 1e6, 1),\n", " \"actual_gbs\": round((ideal_b * n_el) / ms / 1e6, 1),\n", " })\n", "\n", " print(\n", " f\"{n_cols:6d} | {t_naive:9.4f} {t_torch:9.4f} {t_triton:9.4f} | \"\n", " f\"{eff_naive:8.1f}GB {eff_torch:8.1f}GB {eff_triton:8.1f}GB | {t_naive / t_triton:10.2f} x\"\n", " )\n", " del x\n", " torch.cuda.empty_cache()\n", "\n", " save_csv(\"softmax.csv\", softmax_rows)\n", "else:\n", " print(\"no CUDA GPU with Triton: skipping softmax GPU benchmark (runs on CUDA)\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · By hand: online softmax and tiled attention in plain PyTorch\n", "\n", "Our Triton softmax kernel loaded one whole row into SRAM at once. That works for a row of 4,096\n", "floats (16 KiB). What about attention? Each row of `S = Q K^T / √d` has length `T`, and we do not\n", "even *have* `S` in memory unless we compute and store all `T × T` entries first — which blows up\n", "VRAM and saturates the memory bus.\n", "\n", "**Online softmax** lets us walk through a row in small chunks, keeping only two running numbers\n", "(`m` = running max, `l` = running sum of shifted exponentials) plus a running unnormalised output\n", "vector `o_tilde`. Whenever a new chunk raises the max from `m_old` to `m_new`, we multiply the old\n", "`l` and `o_tilde` by `alpha = exp(m_old - m_new)` so every earlier term is rescaled to the new\n", "max. At the end, one division `o_tilde / l` gives the **exact** attention output.\n", "\n", "### 3a · Worked two-chunk example (every number printed)\n", "\n", "Scores `x = [2.0, 1.0, 4.0, 0.0]` split into two chunks of two, with scalar values\n", "`v = [10.0, 20.0, 30.0, 40.0]`:" ], "id": "lab-4-3-triton-07" }, { "cell_type": "code", "metadata": {}, "source": [ "x_demo = torch.tensor([2.0, 1.0, 4.0, 0.0], dtype=torch.float64)\n", "v_demo = torch.tensor([10.0, 20.0, 30.0, 40.0], dtype=torch.float64)\n", "\n", "# Full (standard) softmax and weighted value sum\n", "m_full = x_demo.max()\n", "exp_full = torch.exp(x_demo - m_full)\n", "l_full = exp_full.sum()\n", "p_full = exp_full / l_full\n", "o_full = (p_full * v_demo).sum()\n", "\n", "print(\"=== Standard (full row) ===\")\n", "print(f\"m_full = {m_full.item():.4f}\")\n", "print(f\"exp(x - m) = {[round(z, 6) for z in exp_full.tolist()]}\")\n", "print(f\"l_full = {l_full.item():.6f}\")\n", "print(f\"probs = {[round(z, 6) for z in p_full.tolist()]}\")\n", "print(f\"o_full = {o_full.item():.6f}\\n\")\n", "\n", "# Online (two chunks: [2.0, 1.0] then [4.0, 0.0])\n", "c1_x, c1_v = x_demo[:2], v_demo[:2]\n", "c2_x, c2_v = x_demo[2:], v_demo[2:]\n", "\n", "# Chunk 1\n", "m1 = c1_x.max()\n", "e1 = torch.exp(c1_x - m1)\n", "l1 = e1.sum()\n", "o_tilde1 = (e1 * c1_v).sum()\n", "print(\"=== Online chunk 1: x=[2.0, 1.0], v=[10, 20] ===\")\n", "print(f\"m1 = {m1.item():.4f}, exp(c1 - m1) = {[round(z, 6) for z in e1.tolist()]}\")\n", "print(f\"l1 = {l1.item():.6f}, o_tilde1 = {o_tilde1.item():.6f} (chunk-1 output = {(o_tilde1/l1).item():.6f})\\n\")\n", "\n", "# Chunk 2\n", "m_blk = c2_x.max()\n", "m2 = torch.maximum(m1, m_blk)\n", "alpha = torch.exp(m1 - m2)\n", "e2 = torch.exp(c2_x - m2)\n", "l1_rescaled = l1 * alpha\n", "l2 = l1_rescaled + e2.sum()\n", "o_tilde1_rescaled = o_tilde1 * alpha\n", "o_tilde2 = o_tilde1_rescaled + (e2 * c2_v).sum()\n", "o_online = o_tilde2 / l2\n", "\n", "print(\"=== Online chunk 2: x=[4.0, 0.0], v=[30, 40] ===\")\n", "print(f\"m_blk = {m_blk.item():.4f} -> m2 = {m2.item():.4f}, alpha = exp({m1.item():.1f} - {m2.item():.1f}) = {alpha.item():.6f}\")\n", "print(f\"e2 = exp(c2 - m2) = {[round(z, 6) for z in e2.tolist()]}, sum(e2) = {e2.sum().item():.6f}\")\n", "print(f\"l2 = {l1.item():.6f} * {alpha.item():.6f} + {e2.sum().item():.6f} = {l1_rescaled.item():.6f} + {e2.sum().item():.6f} = {l2.item():.6f}\")\n", "print(f\"o_tilde2 = {o_tilde1.item():.6f} * {alpha.item():.6f} + {(e2*c2_v).sum().item():.6f} = {o_tilde1_rescaled.item():.6f} + {(e2*c2_v).sum().item():.6f} = {o_tilde2.item():.6f}\")\n", "print(f\"o_online = {o_tilde2.item():.6f} / {l2.item():.6f} = {o_online.item():.6f}\")\n", "print(f\"|o_online - o_full| = {abs(o_online.item() - o_full.item()):.2e}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3b · General online softmax and didactic tiled FlashAttention in PyTorch\n", "\n", "Here is the exact FlashAttention algorithm written in plain PyTorch loops over tiles of size\n", "`B_r` (rows of `Q`) and `B_c` (columns/rows of `K` and `V`). At no point does this function create\n", "a `[B, H, T, T]` tensor: the largest score tile in memory is `[B, H, B_r, B_c]`." ], "id": "lab-4-3-triton-09" }, { "cell_type": "code", "metadata": {}, "source": [ "def online_softmax_1d(x, block_size=64):\n", " \"\"\"Two-pass online softmax on a 1-D tensor (first pass finds global m and l in chunks).\"\"\"\n", " m = torch.tensor(-float(\"inf\"), dtype=x.dtype, device=x.device)\n", " l = torch.tensor(0.0, dtype=x.dtype, device=x.device)\n", " for start in range(0, x.numel(), block_size):\n", " blk = x[start : start + block_size]\n", " m_new = torch.maximum(m, blk.max())\n", " l = l * torch.exp(m - m_new) + torch.exp(blk - m_new).sum()\n", " m = m_new\n", " return torch.exp(x - m) / l\n", "\n", "\n", "def naive_attention(q, k, v, is_causal=True):\n", " \"\"\"Standard Ch 3.1 attention: materialises the full [B, H, T, T] score and weight matrices.\"\"\"\n", " T, d = q.shape[-2], q.shape[-1]\n", " scale = 1.0 / math.sqrt(d)\n", " scores = torch.matmul(q, k.transpose(-2, -1)) * scale\n", " if is_causal:\n", " mask = torch.triu(torch.ones(T, T, device=q.device, dtype=torch.bool), diagonal=1)\n", " scores = scores.masked_fill(mask, float(\"-inf\"))\n", " probs = torch.softmax(scores, dim=-1)\n", " return torch.matmul(probs, v)\n", "\n", "\n", "def tiled_flash_attention_ref(q, k, v, block_r=64, block_c=64, is_causal=True):\n", " \"\"\"Didactic FlashAttention forward pass in plain PyTorch: never allocates [B, H, T, T].\"\"\"\n", " B, H, T, D = q.shape\n", " scale = 1.0 / math.sqrt(D)\n", " out = torch.empty_like(q)\n", "\n", " # Outer loop over Q tiles (each tile is B_r x D; in a GPU kernel these run in parallel!)\n", " for r0 in range(0, T, block_r):\n", " r1 = min(r0 + block_r, T)\n", " q_blk = q[:, :, r0:r1, :] # [B, H, br, D]\n", " br = r1 - r0\n", "\n", " # Running statistics kept on-chip (SRAM / registers) in float32\n", " m_i = torch.full((B, H, br, 1), -float(\"inf\"), device=q.device, dtype=torch.float32)\n", " l_i = torch.zeros((B, H, br, 1), device=q.device, dtype=torch.float32)\n", " acc = torch.zeros((B, H, br, D), device=q.device, dtype=torch.float32)\n", "\n", " # For causal attention, K/V blocks strictly after r1 are completely masked out -> skip!\n", " c_end = r1 if is_causal else T\n", " for c0 in range(0, c_end, block_c):\n", " c1 = min(c0 + block_c, T)\n", " k_blk = k[:, :, c0:c1, :] # [B, H, bc, D]\n", " v_blk = v[:, :, c0:c1, :] # [B, H, bc, D]\n", "\n", " # Tiny [B, H, br, bc] score tile — never written to VRAM\n", " s_blk = torch.matmul(q_blk.float(), k_blk.float().transpose(-2, -1)) * scale\n", " if is_causal and c1 > r0:\n", " q_pos = torch.arange(r0, r1, device=q.device)[:, None]\n", " k_pos = torch.arange(c0, c1, device=q.device)[None, :]\n", " s_blk = s_blk.masked_fill(k_pos > q_pos, float(\"-inf\"))\n", "\n", " m_new = torch.maximum(m_i, s_blk.max(dim=-1, keepdim=True).values)\n", " p_blk = torch.exp(s_blk - m_new)\n", " alpha = torch.exp(m_i - m_new)\n", "\n", " l_i = l_i * alpha + p_blk.sum(dim=-1, keepdim=True)\n", " acc = acc * alpha + torch.matmul(p_blk, v_blk.float())\n", " m_i = m_new\n", "\n", " out[:, :, r0:r1, :] = (acc / l_i).to(q.dtype)\n", "\n", " return out\n", "\n", "\n", "# Verify online_softmax_1d and tiled_flash_attention_ref in float32\n", "torch.manual_seed(42)\n", "vec = torch.randn(4096, device=DEVICE, dtype=torch.float32)\n", "diff_sm = (online_softmax_1d(vec, block_size=64) - torch.softmax(vec, dim=0)).abs().max().item()\n", "print(f\"online_softmax_1d (4096 elements, block=64): max abs diff = {diff_sm:.2e}\")\n", "\n", "q_t = torch.randn(2, 4, 256, 64, device=DEVICE, dtype=torch.float32)\n", "k_t = torch.randn(2, 4, 256, 64, device=DEVICE, dtype=torch.float32)\n", "v_t = torch.randn(2, 4, 256, 64, device=DEVICE, dtype=torch.float32)\n", "for causal in (False, True):\n", " ref_o = naive_attention(q_t, k_t, v_t, is_causal=causal)\n", " til_o = tiled_flash_attention_ref(q_t, k_t, v_t, block_r=64, block_c=64, is_causal=causal)\n", " print(\n", " f\"tiled_flash_attention_ref (2x4x256x64 fp32, causal={str(causal):5s}): \"\n", " f\"max abs diff = {(til_o - ref_o).abs().max().item():.2e}\"\n", " )\n", "del vec, q_t, k_t, v_t, ref_o, til_o\n", "if ON_GPU:\n", " gc.collect()\n", " torch.cuda.empty_cache()" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Optional: a minimal Triton FlashAttention forward kernel (~70 lines)\n", "\n", "Turning `tiled_flash_attention_ref` into a real GPU kernel in Triton is almost line-for-line the\n", "same algorithm:\n", "\n", "- Each Triton program owns one `(Q-block, batch*head)` pair: the outer loop over `Q` tiles becomes\n", " the launch grid `(ceil(T / BLOCK_M), B * H)`, running in parallel across all 28 SMs.\n", "- The `Q` tile `[BLOCK_M, D]` is loaded **once** into SRAM/registers.\n", "- The inner loop streams `K` and `V` tiles `[BLOCK_N, D]`, multiplies with `tl.dot` on the tensor\n", " cores, updates `(m_i, l_i, acc)` in float32, and writes `O` **once** at the end." ], "id": "lab-4-3-triton-11" }, { "cell_type": "code", "metadata": {}, "source": [ "if ON_GPU and HAS_TRITON:\n", " @triton.jit\n", " def flash_attn_fwd_kernel(\n", " Q_ptr, K_ptr, V_ptr, O_ptr,\n", " stride_bh, stride_t, stride_d,\n", " T, scale,\n", " IS_CAUSAL: tl.constexpr,\n", " BLOCK_M: tl.constexpr,\n", " BLOCK_N: tl.constexpr,\n", " HEAD_DIM: tl.constexpr,\n", " ):\n", " start_m = tl.program_id(0)\n", " bh = tl.program_id(1)\n", "\n", " offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)\n", " offs_d = tl.arange(0, HEAD_DIM)\n", " base = bh * stride_bh\n", "\n", " # Load Q tile [BLOCK_M, HEAD_DIM] once; keep it on-chip for the whole inner loop.\n", " q_ptrs = Q_ptr + base + offs_m[:, None] * stride_t + offs_d[None, :] * stride_d\n", " q = tl.load(q_ptrs, mask=offs_m[:, None] < T, other=0.0)\n", "\n", " m_i = tl.full([BLOCK_M], -float(\"inf\"), dtype=tl.float32)\n", " l_i = tl.zeros([BLOCK_M], dtype=tl.float32)\n", " acc = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32)\n", "\n", " # Causal attention skips every K/V block strictly above the diagonal.\n", " hi = tl.minimum((start_m + 1) * BLOCK_M, T) if IS_CAUSAL else T\n", "\n", " for start_n in range(0, hi, BLOCK_N):\n", " offs_n = start_n + tl.arange(0, BLOCK_N)\n", " n_mask = offs_n < T\n", "\n", " k_ptrs = K_ptr + base + offs_n[:, None] * stride_t + offs_d[None, :] * stride_d\n", " v_ptrs = V_ptr + base + offs_n[:, None] * stride_t + offs_d[None, :] * stride_d\n", " k = tl.load(k_ptrs, mask=n_mask[:, None], other=0.0)\n", " v = tl.load(v_ptrs, mask=n_mask[:, None], other=0.0)\n", "\n", " # [BLOCK_M, BLOCK_N] scores on tensor cores, accumulated in float32.\n", " qk = tl.dot(q, tl.trans(k)) * scale\n", " if IS_CAUSAL:\n", " valid = n_mask[None, :] & (offs_n[None, :] <= offs_m[:, None])\n", " else:\n", " valid = n_mask[None, :]\n", " qk = tl.where(valid, qk, -float(\"inf\"))\n", "\n", " # Online softmax + rescaled accumulator update.\n", " m_ij = tl.maximum(m_i, tl.max(qk, axis=1))\n", " p = tl.exp(qk - m_ij[:, None])\n", " alpha = tl.exp(m_i - m_ij)\n", "\n", " l_i = l_i * alpha + tl.sum(p, axis=1)\n", " acc = acc * alpha[:, None] + tl.dot(p.to(tl.float16), v)\n", " m_i = m_ij\n", "\n", " out = (acc / l_i[:, None]).to(tl.float16)\n", " o_ptrs = O_ptr + base + offs_m[:, None] * stride_t + offs_d[None, :] * stride_d\n", " tl.store(o_ptrs, out, mask=offs_m[:, None] < T)\n", "\n", " def triton_flash_attention(q, k, v, is_causal=True, block_m=64, block_n=64):\n", " assert q.is_cuda and q.dtype == torch.float16\n", " B, H, T, D = q.shape\n", " q = q.contiguous()\n", " k = k.contiguous()\n", " v = v.contiguous()\n", " o = torch.empty_like(q)\n", " grid = (triton.cdiv(T, block_m), B * H)\n", " flash_attn_fwd_kernel[grid](\n", " q, k, v, o,\n", " q.stride(1), q.stride(2), q.stride(3),\n", " T, 1.0 / math.sqrt(D),\n", " IS_CAUSAL=is_causal,\n", " BLOCK_M=block_m,\n", " BLOCK_N=block_n,\n", " HEAD_DIM=D,\n", " num_warps=4,\n", " num_stages=2,\n", " )\n", " return o\n", "\n", " # Check our Triton FlashAttention kernel against PyTorch SDPA (and float32 ground truth)\n", " torch.manual_seed(0)\n", " q_chk = torch.randn(4, 12, 1024, 64, device=\"cuda\", dtype=torch.float16)\n", " k_chk = torch.randn(4, 12, 1024, 64, device=\"cuda\", dtype=torch.float16)\n", " v_chk = torch.randn(4, 12, 1024, 64, device=\"cuda\", dtype=torch.float16)\n", " for causal in (False, True):\n", " o_sdpa = F.scaled_dot_product_attention(q_chk, k_chk, v_chk, is_causal=causal)\n", " o_tri = triton_flash_attention(q_chk, k_chk, v_chk, is_causal=causal)\n", " o_f32 = naive_attention(q_chk.float(), k_chk.float(), v_chk.float(), is_causal=causal)\n", " print(\n", " f\"Triton FlashAttention (4x12x1024x64 fp16, causal={str(causal):5s}): \"\n", " f\"max|triton - sdpa| = {(o_tri - o_sdpa).abs().max().item():.2e} | \"\n", " f\"max|triton - fp32| = {(o_tri.float() - o_f32).abs().max().item():.2e} | \"\n", " f\"max|sdpa - fp32| = {(o_sdpa.float() - o_f32).abs().max().item():.2e}\"\n", " )\n", " del q_chk, k_chk, v_chk, o_sdpa, o_tri, o_f32\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"no CUDA GPU with Triton: skipping Triton FlashAttention kernel\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Measure: naive attention vs PyTorch SDPA (FlashAttention) vs Triton\n", "\n", "First we confirm that PyTorch's `F.scaled_dot_product_attention` selects the **FlashAttention**\n", "backend on this GPU (Ampere sm_86 supports FlashAttention-2 in fp16/bf16). Then we sweep context\n", "length `T` from `512` to `16,384` using GPT-2 small's head geometry (`B = 4`, `H = 12`, `d = 64`,\n", "`float16`, causal) and record both **time (ms)** and **peak allocated VRAM (MiB)** until naive\n", "attention runs out of memory." ], "id": "lab-4-3-triton-13" }, { "cell_type": "code", "metadata": {}, "source": [ "B_BENCH, H_BENCH, D_BENCH = 4, 12, 64 # GPT-2 small head geometry (12 x 64 = 768)\n", "\n", "# Analytical IO model for T = 4,096 (and the sweep sizes), printed so the chapter uses exact numbers.\n", "print(f\"=== Analytical memory and IO table (B={B_BENCH}, H={H_BENCH}, d={D_BENCH}, float16 = 2 B) ===\")\n", "print(\n", " f\"{'T':>6s} | {'Q,K,V,O (MiB)':>13s} | {'1x TxT (MiB)':>12s} | \"\n", " f\"{'3-kern IO (MiB)':>15s} | {'Flash Br=128 nc':>15s} | {'Flash Br=128 c':>14s}\"\n", ")\n", "print(\"-\" * 92)\n", "io_rows = []\n", "for T_io in (512, 1024, 2048, 4096, 8192, 16384):\n", " bh = B_BENCH * H_BENCH\n", " qkvo_b = 4 * bh * T_io * D_BENCH * 2\n", " tt_b = bh * T_io * T_io * 2\n", " # Bare-minimum 3-kernel standard attention: 4*T*d + 4*T^2 elements per head\n", " std3_b = bh * (4 * T_io * D_BENCH + 4 * T_io * T_io) * 2\n", " # FlashAttention (B_r = 128): read Q once, write O once, read K,V T/B_r times\n", " flash_nc_b = bh * (2 * T_io * D_BENCH + (T_io / 128) * 2 * T_io * D_BENCH) * 2\n", " # Causal skips half of K,V tiles on average: (T/B_r + 1)/2 passes over K,V\n", " avg_kv_frac = ((T_io // 128) + 1) / (2 * (T_io // 128))\n", " flash_c_b = bh * (2 * T_io * D_BENCH + (T_io / 128) * avg_kv_frac * 2 * T_io * D_BENCH) * 2\n", " print(\n", " f\"{T_io:6d} | {qkvo_b / 2**20:13.1f} | {tt_b / 2**20:12.1f} | \"\n", " f\"{std3_b / 2**20:15.1f} | {flash_nc_b / 2**20:15.1f} | {flash_c_b / 2**20:14.1f}\"\n", " )\n", " io_rows.append({\n", " \"B\": B_BENCH, \"H\": H_BENCH, \"D\": D_BENCH, \"T\": T_io,\n", " \"qkvo_mib\": round(qkvo_b / 2**20, 2),\n", " \"one_tt_mib\": round(tt_b / 2**20, 2),\n", " \"std_3kernel_io_mib\": round(std3_b / 2**20, 2),\n", " \"flash_br128_noncausal_io_mib\": round(flash_nc_b / 2**20, 2),\n", " \"flash_br128_causal_io_mib\": round(flash_c_b / 2**20, 2),\n", " })" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-14" }, { "cell_type": "code", "metadata": {}, "source": [ "attn_rows = []\n", "\n", "if ON_GPU:\n", " from torch.nn.attention import SDPBackend, sdpa_kernel\n", "\n", " # Verify the FlashAttention SDPA backend runs on this GPU\n", " q0 = torch.randn(1, 4, 256, 64, device=\"cuda\", dtype=torch.float16)\n", " k0 = torch.randn_like(q0)\n", " v0 = torch.randn_like(q0)\n", " try:\n", " with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n", " _ = F.scaled_dot_product_attention(q0, k0, v0, is_causal=True)\n", " torch.cuda.synchronize()\n", " HAS_FLASH_SDPA = True\n", " print(\"SDPA FlashAttention backend: AVAILABLE and verified\")\n", " except RuntimeError as e:\n", " HAS_FLASH_SDPA = False\n", " print(\"SDPA FlashAttention backend unavailable:\", e)\n", " del q0, k0, v0\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", "\n", " def measure_mem_mib(fn):\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", " torch.cuda.reset_peak_memory_stats()\n", " base = torch.cuda.memory_allocated()\n", " out = fn()\n", " torch.cuda.synchronize()\n", " peak = torch.cuda.max_memory_allocated()\n", " del out\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", " return peak / (1024 ** 2), (peak - base) / (1024 ** 2)\n", "\n", " def sdpa_flash_call(q, k, v):\n", " if HAS_FLASH_SDPA:\n", " with sdpa_kernel(SDPBackend.FLASH_ATTENTION):\n", " return F.scaled_dot_product_attention(q, k, v, is_causal=True)\n", " return F.scaled_dot_product_attention(q, k, v, is_causal=True)\n", "\n", " T_LIST = [512, 1024, 2048, 4096, 6144, 8192, 16384]\n", " print(\n", " f\"\\n{'T':>6s} | {'variant':14s} | {'status':6s} | {'ms':>9s} | \"\n", " f\"{'peak MiB':>10s} | {'extra MiB':>10s} | {'TFLOP/s':>8s}\"\n", " )\n", " print(\"-\" * 82)\n", "\n", " for T in T_LIST:\n", " torch.manual_seed(0)\n", " q = torch.randn(B_BENCH, H_BENCH, T, D_BENCH, device=\"cuda\", dtype=torch.float16)\n", " k = torch.randn(B_BENCH, H_BENCH, T, D_BENCH, device=\"cuda\", dtype=torch.float16)\n", " v = torch.randn(B_BENCH, H_BENCH, T, D_BENCH, device=\"cuda\", dtype=torch.float16)\n", "\n", " # Causal attention does half the matmul FLOPs of non-causal: 2 * B * H * T^2 * D\n", " causal_flops = 2 * B_BENCH * H_BENCH * T * T * D_BENCH\n", "\n", " variants = [\n", " (\"naive\", lambda: naive_attention(q, k, v, is_causal=True)),\n", " (\"sdpa_flash\", lambda: sdpa_flash_call(q, k, v)),\n", " ]\n", " if HAS_TRITON:\n", " variants.append((\"triton_flash\", lambda: triton_flash_attention(q, k, v, is_causal=True)))\n", "\n", " for vname, fn in variants:\n", " try:\n", " peak_mib, extra_mib = measure_mem_mib(fn)\n", " ms = bench(fn, min_ms=30.0, repeats=7, warmup=3)\n", " tflops = causal_flops / (ms * 1e-3) / 1e12\n", " attn_rows.append({\n", " \"machine\": MACHINE,\n", " \"B\": B_BENCH, \"H\": H_BENCH, \"D\": D_BENCH, \"T\": T,\n", " \"dtype\": \"float16\", \"is_causal\": True,\n", " \"variant\": vname, \"status\": \"ok\",\n", " \"ms\": round(ms, 4),\n", " \"peak_mib\": round(peak_mib, 1),\n", " \"extra_mib\": round(extra_mib, 1),\n", " \"tflops\": round(tflops, 2),\n", " })\n", " print(\n", " f\"{T:6d} | {vname:14s} | {'ok':6s} | {ms:9.4f} | \"\n", " f\"{peak_mib:10.1f} | {extra_mib:10.1f} | {tflops:8.2f}\"\n", " )\n", " except torch.cuda.OutOfMemoryError:\n", " torch.cuda.empty_cache()\n", " attn_rows.append({\n", " \"machine\": MACHINE,\n", " \"B\": B_BENCH, \"H\": H_BENCH, \"D\": D_BENCH, \"T\": T,\n", " \"dtype\": \"float16\", \"is_causal\": True,\n", " \"variant\": vname, \"status\": \"OOM\",\n", " \"ms\": \"\", \"peak_mib\": \"\", \"extra_mib\": \"\", \"tflops\": \"\",\n", " })\n", " print(\n", " f\"{T:6d} | {vname:14s} | {'OOM':6s} | {'--':>9s} | \"\n", " f\"{'--':>10s} | {'--':>10s} | {'--':>8s}\"\n", " )\n", "\n", " del q, k, v\n", " torch.cuda.empty_cache()\n", "\n", " save_csv(\"attention-bench.csv\", attn_rows)\n", " save_csv(\"io-model.csv\", io_rows)\n", "else:\n", " print(\"no CUDA GPU: running tiny CPU sanity check (naive vs SDPA math backend)\")\n", " torch.manual_seed(0)\n", " for T in (128, 256):\n", " q = torch.randn(1, 4, T, 64)\n", " k = torch.randn_like(q)\n", " v = torch.randn_like(q)\n", " t_n = bench(lambda: naive_attention(q, k, v, is_causal=True), min_ms=10.0, repeats=3, warmup=1)\n", " t_s = bench(lambda: F.scaled_dot_product_attention(q, k, v, is_causal=True), min_ms=10.0, repeats=3, warmup=1)\n", " diff = (naive_attention(q, k, v, is_causal=True) - F.scaled_dot_product_attention(q, k, v, is_causal=True)).abs().max().item()\n", " print(f\"CPU sanity T={T}: naive {t_n:.2f} ms, SDPA {t_s:.2f} ms, max diff {diff:.2e}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot the measured time and peak VRAM against sequence length `T` (GPU runs only)." ], "id": "lab-4-3-triton-16" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " if attn_rows:\n", " fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.2))\n", " styles = {\n", " \"naive\": (\"o-\", \"naive (materialises T x T)\"),\n", " \"sdpa_flash\": (\"s-\", \"PyTorch SDPA (FlashAttention)\"),\n", " \"triton_flash\": (\"^--\", \"our Triton FlashAttention\"),\n", " }\n", " for vname, (fmt, label) in styles.items():\n", " sub = [r for r in attn_rows if r[\"variant\"] == vname and r[\"status\"] == \"ok\"]\n", " if not sub:\n", " continue\n", " ts = [r[\"T\"] for r in sub]\n", " ax1.plot(ts, [r[\"ms\"] for r in sub], fmt, label=label)\n", " ax2.plot(ts, [r[\"peak_mib\"] for r in sub], fmt, label=label)\n", "\n", " for ax, title, ylabel in (\n", " (ax1, \"Attention forward time vs T (fp16, causal)\", \"time (ms)\"),\n", " (ax2, \"Peak allocated VRAM vs T (B=4, H=12, d=64)\", \"peak VRAM (MiB)\"),\n", " ):\n", " ax.set_xlabel(\"sequence length T\")\n", " ax.set_ylabel(ylabel)\n", " ax.set_title(title)\n", " ax.legend()\n", " ax.grid(True, alpha=0.3)\n", "\n", " plt.tight_layout()\n", " plt.show()\n", " else:\n", " print(\"no GPU benchmark rows to plot\")\n", "except ImportError:\n", " print(\"matplotlib not installed: skip the plot\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Checkpoint\n", "\n", "Compare your outputs against the book's RTX 3060 reference run (numbers on a T4 or another GPU\n", "will differ; the *relations* must hold):\n", "\n", "- **Triton fused softmax (`4,096 × 4,096`, float32):**\n", "\n", "```text\n", "shape 4096x4096: max |triton - torch| = 2.79e-09 | max |naive - torch| = 3.73e-09\n", "4096 | naive 1.6449 ms (81.6 GB/s eff) | torch 0.4276 ms (313.9 GB/s) | triton 0.4045 ms (331.8 GB/s, 4.07 x)\n", "8192 | naive 3.2336 ms (83.0 GB/s eff) | torch 0.8114 ms (330.8 GB/s) | triton 0.8076 ms (332.4 GB/s, 4.00 x)\n", "```\n", "\n", "- **Online softmax worked example (`[2.0, 1.0, 4.0, 0.0]`, `v = [10, 20, 30, 40]`):**\n", " `m2 = 4.0000`, `alpha = 0.135335`, `l2 = 1.203438`, `o_online = 27.489343`,\n", " `|o_online - o_full| = 0.00e+00`.\n", "- **Didactic tiled FlashAttention (`2×4×256×64`, float32):** `max abs diff = 4.77e-07`\n", " (non-causal) and `5.36e-07` (causal).\n", "- **Triton FlashAttention (`4×12×1024×64`, float16):** `max |triton - sdpa| = 4.88e-04`\n", " (both non-causal and causal).\n", "- **Attention scaling (`B = 4, H = 12, d = 64`, float16, causal):**\n", "\n", "```text\n", "T= 4096 | naive 64.0502 ms | peak 3192.2 MiB (extra 3120.1 MiB) | 1.61 TFLOP/s\n", "T= 4096 | sdpa_flash 4.3772 ms | peak 96.9 MiB (extra 24.8 MiB) | 23.55 TFLOP/s\n", "T= 4096 | triton_flash 4.4506 ms | peak 96.1 MiB (extra 24.0 MiB) | 23.16 TFLOP/s\n", "T= 8192 | naive OOM\n", "T= 8192 | sdpa_flash 16.9569 ms | peak 193.6 MiB (extra 49.5 MiB) | 24.32 TFLOP/s\n", "T=16384 | sdpa_flash 66.8584 ms | peak 387.1 MiB (extra 99.0 MiB) | 24.67 TFLOP/s\n", "```" ], "id": "lab-4-3-triton-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · 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", "| softmax row width | try `n_cols = 1000`, `4096`, `16384`, `65536` in `triton_softmax` | Where does loading a full row into SRAM start to lose speed or fail, and how does online softmax lift that cap? |\n", "| `num_warps` | run `softmax_kernel` at `n_cols = 4096` with `num_warps = 2, 4, 8, 16` | How much does warp count move the achieved GB/s? |\n", "| chunk size `block_c` | run `tiled_flash_attention_ref` with `block_c = 16, 32, 64, 128` | Does the output change at all? What changes about the number of `K, V` passes? |\n", "| `is_causal` | time SDPA and Triton FlashAttention at `T = 4096` with `is_causal=False` vs `True` | Why is causal attention nearly 2× faster, while naive attention barely speeds up at all? |\n", "| `dtype` in SDPA | run `F.scaled_dot_product_attention` in `float32` vs `float16` vs `bfloat16` at `T = 4096` | Which backend runs for `float32`? What happens to peak VRAM and time? |\n", "| Triton tile size | try `block_m=32, block_n=32` vs `64, 64` vs `128, 64` in `triton_flash_attention` | Which tile gives the best time on your GPU, and how does `B_r` change the number of `K, V` reads? |" ], "id": "lab-4-3-triton-19" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Failure playground\n", "\n", "Three broken runs below. For each: execute it, read the symptom, diagnose the cause, and write\n", "the fix. Hints are in Review 4.3; answers are not.\n", "\n", "### 8a · Online softmax without rescaling the running sum\n", "\n", "Someone writes the online softmax loop and forgets to multiply the running sum `l` (and\n", "accumulator `o_tilde`) by `alpha = exp(m_old - m_new)` when chunk 2 raises the max from `2.0` to\n", "`4.0`." ], "id": "lab-4-3-triton-21" }, { "cell_type": "code", "metadata": {}, "source": [ "# Chunk 1: [2.0, 1.0], Chunk 2: [4.0, 0.0], Values: [10, 20, 30, 40]\n", "m_bad = c1_x.max()\n", "e1_bad = torch.exp(c1_x - m_bad)\n", "l_bad = e1_bad.sum()\n", "o_tilde_bad = (e1_bad * c1_v).sum()\n", "\n", "# BUG: chunk 2 updates m_bad, but forgets to rescale l_bad and o_tilde_bad by exp(m_old - m_new)!\n", "m_new_bad = torch.maximum(m_bad, c2_x.max())\n", "e2_bad = torch.exp(c2_x - m_new_bad)\n", "l_bad = l_bad + e2_bad.sum() # <-- missing * exp(m_bad - m_new_bad)\n", "o_tilde_bad = o_tilde_bad + (e2_bad * c2_v).sum() # <-- missing * exp(m_bad - m_new_bad)\n", "o_bad = o_tilde_bad / l_bad\n", "\n", "# Also show what happens to the probabilities if you divide chunk 1's e1 and chunk 2's e2 by l_bad\n", "p_bad_using_new_m = torch.exp(x_demo - m_new_bad) / l_bad\n", "\n", "print(f\"8a true : l = {l_full.item():.6f}, sum(p) = {p_full.sum().item():.6f}, o = {o_full.item():.6f}\")\n", "print(f\"8a broken : l = {l_bad.item():.6f}, sum(exp(x-m2)/l_bad) = {p_bad_using_new_m.sum().item():.6f}, o = {o_bad.item():.6f}\")\n", "print(f\"8a error in output o: {abs(o_bad.item() - o_full.item()):.6f} (factor of exp(m2 - m1) = {math.exp(2.0):.2f}x weight on chunk 1)\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: no crash, no `NaN`, yet the output `o` is off by more than 7 units and the denominator\n", "`l` is nearly twice too large (so `exp(x - m_2) / l_bad` does not even sum to 1). Why did chunk 1\n", "get `e^2 ≈ 7.39×` too much weight? What single factor fixes both `l_bad` and `o_tilde_bad`?\n", "\n", "### 8b · Naive attention out of memory at long `T`\n", "\n", "`Q`, `K` and `V` for `B = 4, H = 12, T = 8,192, d = 64` in `float16` take only 144 MiB combined —\n", "barely 1 % of a 12 GB GPU. Yet calling `naive_attention(Q, K, V)` crashes." ], "id": "lab-4-3-triton-23" }, { "cell_type": "code", "metadata": {}, "source": [ "T_OOM = 8192\n", "qkv_mib = 3 * B_BENCH * H_BENCH * T_OOM * D_BENCH * 2 / (1024 ** 2)\n", "one_tt_gib = B_BENCH * H_BENCH * T_OOM * T_OOM * 2 / (1024 ** 3)\n", "print(f\"8b input Q+K+V size at T={T_OOM}: {qkv_mib:.1f} MiB | one [B, H, T, T] fp16 matrix: {one_tt_gib:.2f} GiB\")\n", "\n", "if ON_GPU:\n", " torch.cuda.empty_cache()\n", " q_big = torch.randn(B_BENCH, H_BENCH, T_OOM, D_BENCH, device=\"cuda\", dtype=torch.float16)\n", " k_big = torch.randn_like(q_big)\n", " v_big = torch.randn_like(q_big)\n", " try:\n", " _ = naive_attention(q_big, k_big, v_big, is_causal=True)\n", " torch.cuda.synchronize()\n", " print(\"8b: naive_attention fit on this GPU (try T=16384 if you have > 16 GB VRAM)\")\n", " except torch.cuda.OutOfMemoryError as e:\n", " print(\"8b naive_attention OutOfMemoryError:\", str(e).splitlines()[0])\n", " torch.cuda.empty_cache()\n", "\n", " torch.cuda.reset_peak_memory_stats()\n", " o_big = F.scaled_dot_product_attention(q_big, k_big, v_big, is_causal=True)\n", " torch.cuda.synchronize()\n", " print(f\"8b SDPA on the exact same Q, K, V: succeeded! peak VRAM = {torch.cuda.max_memory_allocated() / 2**20:.1f} MiB\")\n", " del q_big, k_big, v_big, o_big\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"8b no CUDA GPU: on a 12 GB GPU naive attention fails allocating multiple 6.00 GiB [4, 12, 8192, 8192] tensors.\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `torch.cuda.OutOfMemoryError` when the inputs are only 144 MiB. Read the GiB count in\n", "the error message: which intermediate tensor triggered it, how many copies of `[B, H, T, T]` does\n", "naive attention hold at once, and why did `scaled_dot_product_attention` finish in a couple of\n", "hundred MiB on the exact same inputs?\n", "\n", "### 8c · Comparing `float16` kernels with exact equality\n", "\n", "A colleague writes a unit test asserting `torch.equal(out_naive, out_flash)` in `float16`. The\n", "test fails and they conclude FlashAttention is an approximation." ], "id": "lab-4-3-triton-25" }, { "cell_type": "code", "metadata": {}, "source": [ "torch.manual_seed(7)\n", "q_c = torch.randn(2, 8, 512, 64, device=DEVICE, dtype=torch.float16)\n", "k_c = torch.randn_like(q_c)\n", "v_c = torch.randn_like(q_c)\n", "\n", "# Reference in float32 (high precision)\n", "out_fp32 = naive_attention(q_c.float(), k_c.float(), v_c.float(), is_causal=True)\n", "\n", "# Naive attention in float16 vs SDPA (FlashAttention on GPU, tiled/math on CPU)\n", "out_naive_16 = naive_attention(q_c, k_c, v_c, is_causal=True)\n", "out_sdpa_16 = F.scaled_dot_product_attention(q_c, k_c, v_c, is_causal=True)\n", "\n", "exact = torch.equal(out_naive_16, out_sdpa_16)\n", "n_differ = int((out_naive_16 != out_sdpa_16).sum().item())\n", "n_total = out_naive_16.numel()\n", "diff_ns = (out_naive_16 - out_sdpa_16).abs()\n", "diff_n32 = (out_naive_16.float() - out_fp32).abs()\n", "diff_s32 = (out_sdpa_16.float() - out_fp32).abs()\n", "\n", "print(f\"8c torch.equal(naive_fp16, sdpa_fp16): {exact} ({n_differ:,d} / {n_total:,d} elements differ)\")\n", "print(f\"8c |naive_fp16 - sdpa_fp16|: max = {diff_ns.max().item():.2e}, mean = {diff_ns.mean().item():.2e}\")\n", "print(f\"8c |naive_fp16 - fp32_ref |: max = {diff_n32.max().item():.2e}, mean = {diff_n32.mean().item():.2e}\")\n", "print(f\"8c |sdpa_fp16 - fp32_ref |: max = {diff_s32.max().item():.2e}, mean = {diff_s32.mean().item():.2e}\")\n", "print(f\"8c torch.allclose(atol=1e-2, rtol=1e-2): {torch.allclose(out_naive_16, out_sdpa_16, atol=1e-2, rtol=1e-2)}\")" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `torch.equal` returns `False`, and thousands of elements differ by up to `~1e-3`. Look at\n", "the two lines comparing each float16 result against the `float32` ground truth: which one is\n", "actually *closer* to the float32 answer, and why? Why can two exact algorithms differ in float16\n", "when they sum the same numbers in a different order?" ], "id": "lab-4-3-triton-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Versions tested" ], "id": "lab-4-3-triton-28" }, { "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(\n", " [\"nvidia-smi\", \"--query-gpu=driver_version\", \"--format=csv,noheader\"],\n", " capture_output=True, text=True,\n", " ).stdout.strip()\n", " print(\"NVIDIA driver\", drv)\n", " except Exception:\n", " pass\n", "if HAS_TRITON:\n", " print(\"Triton\", triton.__version__)\n", "try:\n", " import matplotlib\n", " print(\"matplotlib\", matplotlib.__version__)\n", "except ImportError:\n", " pass" ], "execution_count": null, "outputs": [], "id": "lab-4-3-triton-29" } ] }