{ "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.2 · Your First CUDA Kernels\n", "\n", "**Goal:** write, compile and call your first CUDA C++ kernels from Python (vector add, strided and\n", "coalesced naive matrix multiply, and shared-memory tiled matrix multiply at tile sizes 16 and 32),\n", "check each against PyTorch, measure GFLOP/s against cuBLAS, inspect them with Nsight Compute, and\n", "break them three ways.\n", "\n", "**Runs on:** an NVIDIA GPU (free Kaggle or Colab T4; the book's numbers come from an RTX 3060).\n", "Compiles kernels with `torch.utils.cpp_extension.load_inline`, which needs `nvcc` (pre-installed on\n", "Colab, Kaggle and the book's GPU machine) and `ninja` (installed automatically on Colab/Kaggle, or\n", "`pip install ninja` locally). Without an NVIDIA GPU, every cell still runs and prints why the GPU\n", "cells were skipped.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-4-2-cuda-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", "\n", "ON_GPU = torch.cuda.is_available() and os.environ.get(\"LAB_DEVICE\", \"cuda\") == \"cuda\"\n", "NVCC = shutil.which(\"nvcc\")\n", "NINJA = shutil.which(\"ninja\")\n", "\n", "if ON_GPU and NINJA is None and (\n", " \"COLAB_RELEASE_TAG\" in os.environ or \"KAGGLE_KERNEL_RUN_TYPE\" in os.environ\n", "):\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"ninja\"])\n", " NINJA = shutil.which(\"ninja\")\n", "\n", "CAN_COMPILE = ON_GPU and (NVCC is not None) and (NINJA is not None)\n", "MACHINE = torch.cuda.get_device_name(0) if ON_GPU else f\"{platform.system()} {platform.machine()} (cpu)\"\n", "\n", "print(\"PyTorch\", torch.__version__, \"| CUDA available:\", ON_GPU, \"| device:\", MACHINE)\n", "print(\"nvcc:\", NVCC or \"not found\", \"| ninja:\", NINJA or \"not found\")\n", "if ON_GPU and not CAN_COMPILE:\n", " print(\"CUDA compilation disabled: install ninja (pip install ninja) and ensure nvcc is on PATH.\")\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-2-cuda\"\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 bench(fn, min_ms=40.0, repeats=7, warmup=2):\n", " \"\"\"Median milliseconds per call on CUDA using GPU events (same recipe as Lab 4.1).\"\"\"\n", " for _ in range(warmup):\n", " fn()\n", " torch.cuda.synchronize()\n", " start = torch.cuda.Event(enable_timing=True)\n", " end = torch.cuda.Event(enable_timing=True)\n", " start.record()\n", " fn()\n", " end.record()\n", " end.synchronize()\n", " one = max(start.elapsed_time(end), 1e-4)\n", " reps = int(min(max(1, math.ceil(min_ms / one)), 10000))\n", " times = []\n", " for _ in range(repeats):\n", " start.record()\n", " for _ in range(reps):\n", " fn()\n", " end.record()\n", " end.synchronize()\n", " times.append(start.elapsed_time(end) / reps)\n", " return statistics.median(times)\n", "\n", "\n", "if ON_GPU:\n", " p = torch.cuda.get_device_properties(0)\n", " print(\n", " f\"SMs: {p.multi_processor_count} | warp: {p.warp_size} | \"\n", " f\"max threads/block: {p.max_threads_per_block} | \"\n", " f\"max threads/SM: {p.max_threads_per_multi_processor} | \"\n", " f\"shared/SM: {p.shared_memory_per_multiprocessor // 1024} KB | \"\n", " f\"L2: {p.L2_cache_size / 2**20:.2f} MiB\"\n", " )" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write your estimates down before running the cells below.\n", "\n", "1. **Grid size and extra threads.** You want to add two vectors of length `n = 1,000,003` with\n", " `256` threads per block. How many blocks must you launch, and how many threads in the last block\n", " have index `i >= n`?\n", "2. **Your first kernel vs PyTorch.** A five-line CUDA vector-add kernel does 1 FLOP per 12 bytes\n", " (Lab 4.1). What fraction of PyTorch's `a + b` bandwidth do you expect your kernel to reach:\n", " 20 %, 50 %, 80 %, or ~100 %?\n", "3. **Coalescing.** In a 2D naive matrix multiply, swapping `row` and `col` between `threadIdx.x`\n", " and `threadIdx.y` changes *zero* arithmetic instructions. Will it change the runtime? By a few\n", " percent, or by a large factor?\n", "4. **Arithmetic intensity of naive vs tiled matmul.** In naive `N x N` float32 matmul, each thread\n", " reads `N` floats from `A` and `N` floats from `B` (`8N` bytes) to perform `2N` FLOPs. What is\n", " its per-thread intensity (FLOP/byte)? If a `TILE x TILE` block loads each tile once into shared\n", " memory (`8 * TILE^2` bytes) and performs `2 * TILE^3` FLOPs, what is the block's intensity for\n", " `TILE = 16` and `TILE = 32`?\n", "5. **Tile 16 vs tile 32.** `TILE = 32` cuts global-memory reads in half relative to `TILE = 16`,\n", " but uses `32 x 32 = 1,024` threads per block. On an SM that holds at most `1,536` threads\n", " (RTX 3060), how many `32 x 32` blocks fit on one SM vs `16 x 16` blocks (`256` threads)? Which\n", " tile size do you predict will be faster?\n", "6. **Tiled vs cuBLAS.** Will your tiled shared-memory kernel match `torch.matmul`? If not, by what\n", " factor do you expect cuBLAS to stay ahead?" ], "id": "lab-4-2-cuda-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Host vs device memory, and your first kernel: vector add\n", "\n", "A GPU cannot read your laptop's RAM directly at VRAM speed: tensors must cross the PCIe bus first.\n", "Measure that transfer speed on 64 MiB of float32 numbers (`2^24` floats) so you can compare it with\n", "GPU VRAM bandwidth (Lab 4.1 measured 336.2 GB/s on this RTX 3060)." ], "id": "lab-4-2-cuda-03" }, { "cell_type": "code", "metadata": {}, "source": [ "h2d_rows = []\n", "if ON_GPU:\n", " n_copy = 1 << 24 # 16,777,216 floats = 64 MiB\n", " n_bytes = n_copy * 4\n", " x_page = torch.randn(n_copy)\n", " x_pin = torch.randn(n_copy).pin_memory()\n", " x_gpu = torch.randn(n_copy, device=\"cuda\")\n", "\n", " def bench_transfer(fn, reps=15, warmup=3):\n", " for _ in range(warmup):\n", " fn()\n", " torch.cuda.synchronize()\n", " times = []\n", " for _ in range(reps):\n", " torch.cuda.synchronize()\n", " t0 = time.perf_counter()\n", " fn()\n", " torch.cuda.synchronize()\n", " times.append((time.perf_counter() - t0) * 1e3)\n", " return statistics.median(times)\n", "\n", " for label, fn in (\n", " (\"host_to_device_pageable\", lambda: x_page.to(\"cuda\")),\n", " (\"host_to_device_pinned\", lambda: x_pin.to(\"cuda\")),\n", " (\"device_to_device_copy\", lambda: x_gpu.clone()),\n", " ):\n", " ms = bench_transfer(fn)\n", " gbs = (n_bytes * (2 if label == \"device_to_device_copy\" else 1)) / ms / 1e6\n", " h2d_rows.append(\n", " {\n", " \"machine\": MACHINE,\n", " \"transfer\": label,\n", " \"mib\": n_bytes // 2**20,\n", " \"ms\": round(ms, 4),\n", " \"gbs\": round(gbs, 2),\n", " }\n", " )\n", " print(f\"{'transfer':26s} {'MiB':>5s} {'ms':>9s} {'GB/s':>9s}\")\n", " for r in h2d_rows:\n", " print(f\"{r['transfer']:26s} {r['mib']:5d} {r['ms']:9.3f} {r['gbs']:9.2f}\")\n", " save_csv(\"transfers.csv\", h2d_rows)\n", " del x_page, x_pin, x_gpu\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"no CUDA GPU: skipped host/device transfer benchmark\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now write and compile your first CUDA kernel: `vector_add_kernel`.\n", "\n", "Every thread computes one global index `i = blockIdx.x * blockDim.x + threadIdx.x`, checks\n", "`if (i < n)` so extra threads in the last block do nothing, and writes `c[i] = a[i] + b[i]`.\n", "`torch.utils.cpp_extension.load_inline` invokes `nvcc` and `g++` via `ninja` and returns a normal\n", "Python module whose functions accept PyTorch GPU tensors directly." ], "id": "lab-4-2-cuda-05" }, { "cell_type": "code", "metadata": {}, "source": [ "VADD_CUDA = r\"\"\"\n", "#include \n", "#include \n", "\n", "__global__ void vector_add_kernel(const float* a, const float* b, float* c, int n) {\n", " int i = blockIdx.x * blockDim.x + threadIdx.x;\n", " if (i < n) {\n", " c[i] = a[i] + b[i];\n", " }\n", "}\n", "\n", "torch::Tensor vector_add(torch::Tensor a, torch::Tensor b, int threads) {\n", " TORCH_CHECK(a.is_cuda() && b.is_cuda(), \"inputs must be CUDA tensors\");\n", " TORCH_CHECK(a.dtype() == torch::kFloat32 && b.dtype() == torch::kFloat32, \"float32 only\");\n", " TORCH_CHECK(a.is_contiguous() && b.is_contiguous(), \"contiguous tensors only\");\n", " TORCH_CHECK(a.numel() == b.numel(), \"size mismatch\");\n", "\n", " auto c = torch::empty_like(a);\n", " int n = static_cast(a.numel());\n", " int blocks = (n + threads - 1) / threads;\n", " vector_add_kernel<<>>(\n", " a.data_ptr(), b.data_ptr(), c.data_ptr(), n\n", " );\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", " return c;\n", "}\n", "\"\"\"\n", "\n", "VADD_CPP = \"torch::Tensor vector_add(torch::Tensor a, torch::Tensor b, int threads);\"\n", "\n", "vadd_mod = None\n", "vadd_rows = []\n", "if CAN_COMPILE:\n", " from torch.utils.cpp_extension import load_inline\n", "\n", " t0 = time.perf_counter()\n", " vadd_mod = load_inline(\n", " name=\"lab_4_2_vadd\",\n", " cpp_sources=VADD_CPP,\n", " cuda_sources=VADD_CUDA,\n", " functions=[\"vector_add\"],\n", " extra_cuda_cflags=[\"-O3\"],\n", " )\n", " print(f\"compiled lab_4_2_vadd in {time.perf_counter() - t0:.1f} s\")\n", "\n", " # Correctness check on a non-multiple of 256 (exercises the bounds check)\n", " torch.manual_seed(0)\n", " n_odd = 1_000_003\n", " a_odd = torch.randn(n_odd, device=\"cuda\")\n", " b_odd = torch.randn(n_odd, device=\"cuda\")\n", " err_odd = (vadd_mod.vector_add(a_odd, b_odd, 256) - (a_odd + b_odd)).abs().max().item()\n", " blocks_odd = (n_odd + 255) // 256\n", " extra_odd = blocks_odd * 256 - n_odd\n", " print(f\"n={n_odd:,d}: {blocks_odd:,d} blocks x 256 threads ({extra_odd} guard threads), max_abs_err={err_odd:.1e}\")\n", " del a_odd, b_odd\n", "\n", " # Bandwidth benchmark at 2^26 floats (768 MiB moved per add, far larger than L2)\n", " n_big = 1 << 26\n", " a_big = torch.randn(n_big, device=\"cuda\")\n", " b_big = torch.randn(n_big, device=\"cuda\")\n", " c_ref = a_big + b_big\n", " err_big = (vadd_mod.vector_add(a_big, b_big, 256) - c_ref).abs().max().item()\n", " print(f\"n=2^26 ({n_big:,d}): max_abs_err={err_big:.1e}\")\n", "\n", " for threads in (64, 128, 256, 512, 1024):\n", " ms = bench(lambda th=threads: vadd_mod.vector_add(a_big, b_big, th))\n", " gbs = 12 * n_big / ms / 1e6\n", " vadd_rows.append(\n", " {\n", " \"machine\": MACHINE,\n", " \"impl\": f\"cuda_vector_add_t{threads}\",\n", " \"threads_per_block\": threads,\n", " \"n_elements\": n_big,\n", " \"ms\": round(ms, 4),\n", " \"gbs\": round(gbs, 1),\n", " \"max_abs_err\": err_big if threads == 256 else 0.0,\n", " }\n", " )\n", " ms_pt = bench(lambda: a_big + b_big)\n", " vadd_rows.append(\n", " {\n", " \"machine\": MACHINE,\n", " \"impl\": \"torch_add\",\n", " \"threads_per_block\": 0,\n", " \"n_elements\": n_big,\n", " \"ms\": round(ms_pt, 4),\n", " \"gbs\": round(12 * n_big / ms_pt / 1e6, 1),\n", " \"max_abs_err\": 0.0,\n", " }\n", " )\n", "\n", " print(f\"\\n{'implementation':24s} {'ms':>8s} {'GB/s':>8s}\")\n", " for r in vadd_rows:\n", " print(f\"{r['impl']:24s} {r['ms']:8.3f} {r['gbs']:8.1f}\")\n", " save_csv(\"vector-add.csv\", vadd_rows)\n", " del a_big, b_big, c_ref\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"no CUDA compiler available: skipped vector_add build and benchmark\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Matrix multiply: strided naive → coalesced naive → tiled → cuBLAS\n", "\n", "Four kernels that compute the exact same float32 matrix product `C = A @ B` (`N x N`):\n", "\n", "1. **`matmul_naive_strided`**: `row` on `threadIdx.x`, `col` on `threadIdx.y`. Adjacent threads in a\n", " warp read `A[row * N + k]` with stride `N` floats (uncoalesced).\n", "2. **`matmul_naive_coalesced`**: swap two characters — `col` on `threadIdx.x`, `row` on `threadIdx.y`.\n", " Adjacent threads in a warp share `A[row * N + k]` (broadcast) and read consecutive `B[k * N + col]`\n", " (coalesced).\n", "3. **`matmul_tiled_16`**: each `16 x 16` block loads a `16 x 16` tile of `A` and a `16 x 16` tile of\n", " `B` into on-chip `__shared__` memory, calls `__syncthreads()`, multiplies from shared memory, and\n", " calls `__syncthreads()` before loading the next tile.\n", "4. **`matmul_tiled_32`**: the same tiled kernel with `32 x 32 = 1,024` threads per block.\n", "\n", "Plus PyTorch's `A @ B` (cuBLAS) as the reference and ceiling." ], "id": "lab-4-2-cuda-07" }, { "cell_type": "code", "metadata": {}, "source": [ "MM_CUDA = r\"\"\"\n", "#include \n", "#include \n", "\n", "__global__ void matmul_naive_strided_kernel(const float* A, const float* B, float* C, int N) {\n", " int row = blockIdx.x * blockDim.x + threadIdx.x;\n", " int col = blockIdx.y * blockDim.y + threadIdx.y;\n", " if (row < N && col < N) {\n", " float acc = 0.0f;\n", " for (int k = 0; k < N; ++k) {\n", " acc += A[row * N + k] * B[k * N + col];\n", " }\n", " C[row * N + col] = acc;\n", " }\n", "}\n", "\n", "__global__ void matmul_naive_coalesced_kernel(const float* A, const float* B, float* C, int N) {\n", " int col = blockIdx.x * blockDim.x + threadIdx.x;\n", " int row = blockIdx.y * blockDim.y + threadIdx.y;\n", " if (row < N && col < N) {\n", " float acc = 0.0f;\n", " for (int k = 0; k < N; ++k) {\n", " acc += A[row * N + k] * B[k * N + col];\n", " }\n", " C[row * N + col] = acc;\n", " }\n", "}\n", "\n", "template \n", "__global__ void matmul_tiled_kernel(const float* A, const float* B, float* C, int N) {\n", " __shared__ float As[TILE][TILE];\n", " __shared__ float Bs[TILE][TILE];\n", "\n", " int tx = threadIdx.x;\n", " int ty = threadIdx.y;\n", " int col = blockIdx.x * TILE + tx;\n", " int row = blockIdx.y * TILE + ty;\n", "\n", " float acc = 0.0f;\n", " int num_tiles = (N + TILE - 1) / TILE;\n", " for (int t = 0; t < num_tiles; ++t) {\n", " int a_col = t * TILE + tx;\n", " int b_row = t * TILE + ty;\n", " As[ty][tx] = (row < N && a_col < N) ? A[row * N + a_col] : 0.0f;\n", " Bs[ty][tx] = (b_row < N && col < N) ? B[b_row * N + col] : 0.0f;\n", " __syncthreads();\n", "\n", " for (int k = 0; k < TILE; ++k) {\n", " acc += As[ty][k] * Bs[k][tx];\n", " }\n", " __syncthreads();\n", " }\n", " if (row < N && col < N) {\n", " C[row * N + col] = acc;\n", " }\n", "}\n", "\n", "__global__ void diverge_kernel(const float* x, float* y, int n, int split_by_lane) {\n", " int i = blockIdx.x * blockDim.x + threadIdx.x;\n", " if (i >= n) return;\n", " float v = x[i];\n", " bool cond = split_by_lane ? ((threadIdx.x & 1) == 0) : ((blockIdx.x & 1) == 0);\n", " if (cond) {\n", " for (int k = 0; k < 256; ++k) v = v * 1.0001f + 0.0001f;\n", " } else {\n", " for (int k = 0; k < 256; ++k) v = v * 0.9999f - 0.0001f;\n", " }\n", " y[i] = v;\n", "}\n", "\n", "static void check_mm(const torch::Tensor& A, const torch::Tensor& B) {\n", " TORCH_CHECK(A.is_cuda() && B.is_cuda(), \"CUDA tensors only\");\n", " TORCH_CHECK(A.dtype() == torch::kFloat32 && B.dtype() == torch::kFloat32, \"float32 only\");\n", " TORCH_CHECK(A.is_contiguous() && B.is_contiguous(), \"contiguous tensors only\");\n", " TORCH_CHECK(A.dim() == 2 && B.dim() == 2 && A.size(0) == A.size(1) && A.sizes() == B.sizes(),\n", " \"square N x N matrices of equal size required\");\n", "}\n", "\n", "torch::Tensor matmul_naive_strided(torch::Tensor A, torch::Tensor B) {\n", " check_mm(A, B);\n", " int N = static_cast(A.size(0));\n", " auto C = torch::empty({N, N}, A.options());\n", " dim3 block(16, 16);\n", " dim3 grid((N + 15) / 16, (N + 15) / 16);\n", " matmul_naive_strided_kernel<<>>(A.data_ptr(), B.data_ptr(), C.data_ptr(), N);\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", " return C;\n", "}\n", "\n", "torch::Tensor matmul_naive_coalesced(torch::Tensor A, torch::Tensor B) {\n", " check_mm(A, B);\n", " int N = static_cast(A.size(0));\n", " auto C = torch::empty({N, N}, A.options());\n", " dim3 block(16, 16);\n", " dim3 grid((N + 15) / 16, (N + 15) / 16);\n", " matmul_naive_coalesced_kernel<<>>(A.data_ptr(), B.data_ptr(), C.data_ptr(), N);\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", " return C;\n", "}\n", "\n", "torch::Tensor matmul_tiled_16(torch::Tensor A, torch::Tensor B) {\n", " check_mm(A, B);\n", " int N = static_cast(A.size(0));\n", " auto C = torch::empty({N, N}, A.options());\n", " dim3 block(16, 16);\n", " dim3 grid((N + 15) / 16, (N + 15) / 16);\n", " matmul_tiled_kernel<16><<>>(A.data_ptr(), B.data_ptr(), C.data_ptr(), N);\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", " return C;\n", "}\n", "\n", "torch::Tensor matmul_tiled_32(torch::Tensor A, torch::Tensor B) {\n", " check_mm(A, B);\n", " int N = static_cast(A.size(0));\n", " auto C = torch::empty({N, N}, A.options());\n", " dim3 block(32, 32);\n", " dim3 grid((N + 31) / 32, (N + 31) / 32);\n", " matmul_tiled_kernel<32><<>>(A.data_ptr(), B.data_ptr(), C.data_ptr(), N);\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", " return C;\n", "}\n", "\n", "torch::Tensor diverge_test(torch::Tensor x, int split_by_lane) {\n", " auto y = torch::empty_like(x);\n", " int n = static_cast(x.numel());\n", " int threads = 256;\n", " int blocks = (n + threads - 1) / threads;\n", " diverge_kernel<<>>(x.data_ptr(), y.data_ptr(), n, split_by_lane);\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", " return y;\n", "}\n", "\"\"\"\n", "\n", "MM_CPP = \"\"\"\n", "torch::Tensor matmul_naive_strided(torch::Tensor A, torch::Tensor B);\n", "torch::Tensor matmul_naive_coalesced(torch::Tensor A, torch::Tensor B);\n", "torch::Tensor matmul_tiled_16(torch::Tensor A, torch::Tensor B);\n", "torch::Tensor matmul_tiled_32(torch::Tensor A, torch::Tensor B);\n", "torch::Tensor diverge_test(torch::Tensor x, int split_by_lane);\n", "\"\"\"\n", "\n", "mm_mod = None\n", "mm_build_dir = None\n", "if CAN_COMPILE:\n", " mm_build_dir = pathlib.Path(tempfile.mkdtemp(prefix=\"lab_4_2_mm_\"))\n", " t0 = time.perf_counter()\n", " mm_mod = load_inline(\n", " name=\"lab_4_2_mm\",\n", " cpp_sources=MM_CPP,\n", " cuda_sources=MM_CUDA,\n", " functions=[\n", " \"matmul_naive_strided\",\n", " \"matmul_naive_coalesced\",\n", " \"matmul_tiled_16\",\n", " \"matmul_tiled_32\",\n", " \"diverge_test\",\n", " ],\n", " extra_cuda_cflags=[\"-O3\"],\n", " build_directory=str(mm_build_dir),\n", " )\n", " print(f\"compiled lab_4_2_mm in {time.perf_counter() - t0:.1f} s\")\n", "else:\n", " print(\"no CUDA compiler available: skipped matmul kernel compilation\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3a · Correctness checks against `torch.matmul`\n", "\n", "Always verify correctness *before* timing, including a size (`n = 300`) that is not a multiple of\n", "16 or 32 so every boundary check in the tiled kernel is exercised. Small float32 differences\n", "(~`1e-5` to `1e-3`) are normal: float32 addition is not associative, and cuBLAS accumulates partial\n", "sums in a different order from a plain `k = 0 .. N-1` loop." ], "id": "lab-4-2-cuda-09" }, { "cell_type": "code", "metadata": {}, "source": [ "corr_rows = []\n", "if CAN_COMPILE:\n", " print(\"allow_tf32:\", torch.backends.cuda.matmul.allow_tf32)\n", " torch.manual_seed(42)\n", " for N in (300, 512):\n", " A = torch.randn(N, N, device=\"cuda\")\n", " B = torch.randn(N, N, device=\"cuda\")\n", " ref = A @ B\n", " for name, fn in (\n", " (\"naive_strided\", mm_mod.matmul_naive_strided),\n", " (\"naive_coalesced\", mm_mod.matmul_naive_coalesced),\n", " (\"tiled_16\", mm_mod.matmul_tiled_16),\n", " (\"tiled_32\", mm_mod.matmul_tiled_32),\n", " ):\n", " out = fn(A, B)\n", " max_err = (out - ref).abs().max().item()\n", " assert max_err < 1e-2, f\"{name} failed at N={N}: max_err={max_err}\"\n", " corr_rows.append({\"n\": N, \"kernel\": name, \"max_abs_err\": float(f\"{max_err:.3e}\")})\n", " print(f\"N={N:4d} {name:18s} max_abs_err = {max_err:.3e} OK\")\n", " del A, B, ref\n", " save_csv(\"correctness.csv\", corr_rows)\n", "else:\n", " print(\"no CUDA compiler available: skipped correctness checks\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3b · Benchmark: naive strided, naive coalesced, tiled 16, tiled 32, and cuBLAS\n", "\n", "Sweep `N = 256, 512, 1024, 2048, 4096` (float32). Every kernel computes `2 N^3` FLOPs." ], "id": "lab-4-2-cuda-11" }, { "cell_type": "code", "metadata": {}, "source": [ "mm_rows = []\n", "if CAN_COMPILE:\n", " torch.manual_seed(0)\n", " sizes = (256, 512, 1024, 2048, 4096)\n", " kernels = (\n", " (\"naive_strided\", lambda a, b: mm_mod.matmul_naive_strided(a, b)),\n", " (\"naive_coalesced\", lambda a, b: mm_mod.matmul_naive_coalesced(a, b)),\n", " (\"tiled_16\", lambda a, b: mm_mod.matmul_tiled_16(a, b)),\n", " (\"tiled_32\", lambda a, b: mm_mod.matmul_tiled_32(a, b)),\n", " (\"cublas\", lambda a, b: a @ b),\n", " )\n", " for N in sizes:\n", " A = torch.randn(N, N, device=\"cuda\")\n", " B = torch.randn(N, N, device=\"cuda\")\n", " ref = A @ B\n", " for name, fn in kernels:\n", " out = fn(A, B)\n", " err = (out - ref).abs().max().item()\n", " ms = bench(lambda f=fn: f(A, B), min_ms=40.0, repeats=7 if N <= 2048 else 5, warmup=2)\n", " gflops = 2 * (N**3) / ms / 1e6\n", " mm_rows.append(\n", " {\n", " \"machine\": MACHINE,\n", " \"kernel\": name,\n", " \"n\": N,\n", " \"ms\": round(ms, 4),\n", " \"gflops\": round(gflops, 1),\n", " \"max_abs_err\": float(f\"{err:.3e}\"),\n", " }\n", " )\n", " del A, B, ref\n", " torch.cuda.empty_cache()\n", "\n", " print(f\"{'N':>5s} {'kernel':17s} {'ms':>9s} {'GFLOP/s':>9s} {'% cuBLAS':>9s} {'vs strided':>11s}\")\n", " for N in sizes:\n", " sub = {r[\"kernel\"]: r for r in mm_rows if r[\"n\"] == N}\n", " cb = sub[\"cublas\"][\"gflops\"]\n", " st = sub[\"naive_strided\"][\"gflops\"]\n", " for name, _ in kernels:\n", " r = sub[name]\n", " print(\n", " f\"{N:5d} {name:17s} {r['ms']:9.3f} {r['gflops']:9.1f} \"\n", " f\"{100 * r['gflops'] / cb:8.1f}% {r['gflops'] / st:10.2f}x\"\n", " )\n", " print()\n", " save_csv(\"matmul-kernels.csv\", mm_rows)\n", "else:\n", " print(\"no CUDA compiler available: skipped matmul benchmark\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-12" }, { "cell_type": "code", "metadata": {}, "source": [ "if mm_rows:\n", " try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, ax = plt.subplots(figsize=(8.0, 4.8))\n", " styles = {\n", " \"naive_strided\": (\"x--\", \"naive (strided)\"),\n", " \"naive_coalesced\": (\"s--\", \"naive (coalesced)\"),\n", " \"tiled_16\": (\"o-\", \"tiled 16x16\"),\n", " \"tiled_32\": (\"^-\", \"tiled 32x32\"),\n", " \"cublas\": (\"D-\", \"cuBLAS (torch.matmul)\"),\n", " }\n", " for name, (sty, label) in styles.items():\n", " pts = [r for r in mm_rows if r[\"kernel\"] == name]\n", " ax.plot([p[\"n\"] for p in pts], [p[\"gflops\"] for p in pts], sty, label=label)\n", " ax.set_xscale(\"log\", base=2)\n", " ax.set_xticks([256, 512, 1024, 2048, 4096])\n", " ax.get_xaxis().set_major_formatter(plt.ScalarFormatter())\n", " ax.set_xlabel(\"matrix size N (N x N float32)\")\n", " ax.set_ylabel(\"achieved GFLOP/s\")\n", " ax.set_title(f\"Matmul kernels on {MACHINE}\")\n", " ax.legend()\n", " ax.grid(True, alpha=0.3)\n", " plt.show()\n", " except ImportError:\n", " print(\"matplotlib not installed: read the table above instead\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Warp divergence and the hardware profiler (`ncu`)\n", "\n", "### 4a · Warp divergence\n", "\n", "All 32 threads in a warp execute one instruction at a time. Here every thread runs a 256-step loop\n", "inside an `if / else`: in the first call the branch depends on `blockIdx.x & 1` (all 32 threads in\n", "every warp agree), and in the second call it depends on `threadIdx.x & 1` (even and odd lanes inside\n", "every warp disagree). Total FLOPs and total bytes are identical." ], "id": "lab-4-2-cuda-14" }, { "cell_type": "code", "metadata": {}, "source": [ "div_rows = []\n", "if CAN_COMPILE:\n", " x_div = torch.randn(1 << 22, device=\"cuda\")\n", " for label, mode in ((\"aligned_by_block\", 0), (\"divergent_even_odd_lane\", 1)):\n", " ms = bench(lambda m=mode: mm_mod.diverge_test(x_div, m))\n", " div_rows.append({\"machine\": MACHINE, \"mode\": label, \"n_elements\": 1 << 22, \"ms\": round(ms, 4)})\n", " ratio = div_rows[1][\"ms\"] / div_rows[0][\"ms\"]\n", " for r in div_rows:\n", " print(f\"{r['mode']:26s} {r['ms']:8.3f} ms\")\n", " print(f\"slowdown from intra-warp divergence: {ratio:.2f}x\")\n", " save_csv(\"divergence.csv\", div_rows)\n", " del x_div\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"no CUDA compiler available: skipped warp divergence test\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4b · Optional: ask Nsight Compute (`ncu`) what happened inside the chip\n", "\n", "Why did coalescing give a 4x speed-up? Why did `tiled_32` cut DRAM traffic in half yet run slower\n", "than `tiled_16`? And why is cuBLAS still far faster than both? Nsight Compute answers directly from\n", "the hardware counters (needs `ncu` and GPU counter permission; Kaggle and Colab usually disable it,\n", "in which case this cell prints why and moves on)." ], "id": "lab-4-2-cuda-16" }, { "cell_type": "code", "metadata": {}, "source": [ "NCU_METRICS = (\n", " \"gpu__time_duration.sum,\"\n", " \"dram__bytes_read.sum,\"\n", " \"dram__bytes_write.sum,\"\n", " \"dram__throughput.avg.pct_of_peak_sustained_elapsed,\"\n", " \"l1tex__t_sectors_pipe_lsu_mem_global_op_ld.sum,\"\n", " \"l1tex__throughput.avg.pct_of_peak_sustained_elapsed,\"\n", " \"sm__pipe_fma_cycles_active.avg.pct_of_peak_sustained_active,\"\n", " \"sm__warps_active.avg.pct_of_peak_sustained_active\"\n", ")\n", "\n", "ncu_rows = []\n", "if CAN_COMPILE and shutil.which(\"ncu\"):\n", " ncu_script = mm_build_dir / \"ncu_runner.py\"\n", " ncu_script.write_text(\n", " \"import importlib.util, sys, torch\\n\"\n", " f\"spec = importlib.util.spec_from_file_location('lab_4_2_mm', {str(mm_build_dir / 'lab_4_2_mm.so')!r})\\n\"\n", " \"mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)\\n\"\n", " \"kind, N = sys.argv[1], int(sys.argv[2])\\n\"\n", " \"A = torch.randn(N, N, device='cuda'); B = torch.randn(N, N, device='cuda')\\n\"\n", " \"fns = {\\n\"\n", " \" 'naive_strided': lambda: mod.matmul_naive_strided(A, B),\\n\"\n", " \" 'naive_coalesced': lambda: mod.matmul_naive_coalesced(A, B),\\n\"\n", " \" 'tiled_16': lambda: mod.matmul_tiled_16(A, B),\\n\"\n", " \" 'tiled_32': lambda: mod.matmul_tiled_32(A, B),\\n\"\n", " \" 'cublas': lambda: A @ B,\\n\"\n", " \"}\\n\"\n", " \"fn = fns[kind]\\n\"\n", " \"for _ in range(2): fn()\\n\"\n", " \"torch.cuda.synchronize()\\n\"\n", " \"torch.cuda.profiler.start(); fn(); torch.cuda.synchronize(); torch.cuda.profiler.stop()\\n\"\n", " )\n", " N_NCU = 2048\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", " for kind in (\"naive_strided\", \"naive_coalesced\", \"tiled_16\", \"tiled_32\", \"cublas\"):\n", " try:\n", " res = subprocess.run(\n", " [\n", " \"ncu\",\n", " \"--csv\",\n", " \"--profile-from-start\",\n", " \"off\",\n", " \"--metrics\",\n", " NCU_METRICS,\n", " sys.executable,\n", " str(ncu_script),\n", " kind,\n", " str(N_NCU),\n", " ],\n", " capture_output=True,\n", " text=True,\n", " timeout=300,\n", " )\n", " except Exception as ex:\n", " print(f\"ncu {kind}: {type(ex).__name__}: {ex}\")\n", " continue\n", " lines = [ln for ln in res.stdout.splitlines() if ln.startswith('\"')]\n", " if not lines:\n", " print(f\"ncu {kind}: no metrics (permission or environment). tail:\", (res.stdout + res.stderr)[-260:].strip())\n", " continue\n", " rd = list(csv.DictReader(lines))\n", " kname = rd[0][\"Kernel Name\"][:56]\n", " block_sz = rd[0].get(\"Block Size\", \"\")\n", " grid_sz = rd[0].get(\"Grid Size\", \"\")\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", " ms = vals[\"gpu__time_duration.sum\"] * to_ms.get(unit[\"gpu__time_duration.sum\"], float(\"nan\"))\n", " dram_r = vals[\"dram__bytes_read.sum\"] * to_bytes.get(unit[\"dram__bytes_read.sum\"], float(\"nan\"))\n", " dram_w = vals[\"dram__bytes_write.sum\"] * to_bytes.get(unit[\"dram__bytes_write.sum\"], float(\"nan\"))\n", " sectors = vals[\"l1tex__t_sectors_pipe_lsu_mem_global_op_ld.sum\"]\n", " ncu_rows.append(\n", " {\n", " \"machine\": MACHINE,\n", " \"n\": N_NCU,\n", " \"case\": kind,\n", " \"kernel\": kname,\n", " \"block\": block_sz,\n", " \"grid\": grid_sz,\n", " \"ms\": round(ms, 3),\n", " \"dram_read_gb\": round(dram_r / 1e9, 3),\n", " \"dram_write_gb\": round(dram_w / 1e9, 3),\n", " \"global_ld_sectors_m\": round(sectors / 1e6, 1),\n", " \"dram_pct_peak\": round(vals[\"dram__throughput.avg.pct_of_peak_sustained_elapsed\"], 1),\n", " \"l1tex_pct_peak\": round(vals[\"l1tex__throughput.avg.pct_of_peak_sustained_elapsed\"], 1),\n", " \"fma_pct_active\": round(vals[\"sm__pipe_fma_cycles_active.avg.pct_of_peak_sustained_active\"], 1),\n", " \"occupancy_pct\": round(vals[\"sm__warps_active.avg.pct_of_peak_sustained_active\"], 1),\n", " }\n", " )\n", " if ncu_rows:\n", " print(\n", " f\"{'case':16s} {'ms':>7s} {'DRAM R GB':>10s} {'LD sect(M)':>11s} \"\n", " f\"{'DRAM%':>6s} {'L1/Sh%':>7s} {'FMA%':>6s} {'Occ%':>6s} block\"\n", " )\n", " for r in ncu_rows:\n", " print(\n", " f\"{r['case']:16s} {r['ms']:7.2f} {r['dram_read_gb']:10.3f} {r['global_ld_sectors_m']:11.1f} \"\n", " f\"{r['dram_pct_peak']:6.1f} {r['l1tex_pct_peak']:7.1f} {r['fma_pct_active']:6.1f} \"\n", " f\"{r['occupancy_pct']:6.1f} {r['block']}\"\n", " )\n", " print(\"(ncu locks GPU clocks to base, so durations are longer than section 3b: compare bytes, sectors and percentages)\")\n", " save_csv(\"ncu.csv\", ncu_rows)\n", "else:\n", " print(\"ncu not available here (needs NVIDIA GPU + Nsight Compute + counter access): skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Checkpoint\n", "\n", "Compare your outputs with the reference RTX 3060 run on the Lab 4.2 page. Your exact GFLOP/s will\n", "differ on a T4 or another GPU, but these relations must hold on **any** NVIDIA GPU:\n", "\n", "- `vector_add` matches `a + b` with `max_abs_err = 0.0` (including for `n = 1,000,003`) and runs at\n", " virtually the same GB/s as `torch.add`;\n", "- all four matmul kernels pass the `n = 300` (non-multiple) and `n = 512` checks with small float32\n", " rounding error (`< 1e-2`);\n", "- swapping `x` and `y` (`naive_strided` → `naive_coalesced`) gives a multi-times speed-up;\n", "- `tiled_16` beats `naive_coalesced`, and `cublas` (`torch.matmul`) stays several times faster than\n", " both;\n", "- intra-warp divergence slows down the exact same arithmetic by close to 2x." ], "id": "lab-4-2-cuda-18" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"CHECKPOINT\")\n", "if CAN_COMPILE:\n", " v256 = [r for r in vadd_rows if r[\"impl\"] == \"cuda_vector_add_t256\"][0]\n", " vpt = [r for r in vadd_rows if r[\"impl\"] == \"torch_add\"][0]\n", " print(f\"vector_add 2^26 (t=256): {v256['gbs']:.1f} GB/s vs torch {vpt['gbs']:.1f} GB/s (err={v256['max_abs_err']:.1e})\")\n", " for r in corr_rows:\n", " if r[\"n\"] == 300:\n", " print(f\"correctness n=300 {r['kernel']:16s}: max_abs_err={r['max_abs_err']:.3e}\")\n", " for N in (2048, 4096):\n", " sub = {r[\"kernel\"]: r[\"gflops\"] for r in mm_rows if r[\"n\"] == N}\n", " print(\n", " f\"matmul N={N}: strided {sub['naive_strided']:.1f} | coalesced {sub['naive_coalesced']:.1f} | \"\n", " f\"tiled16 {sub['tiled_16']:.1f} | tiled32 {sub['tiled_32']:.1f} | cublas {sub['cublas']:.1f} GFLOP/s\"\n", " )\n", " print(f\"divergence slowdown (even/odd lane vs block): {div_rows[1]['ms'] / div_rows[0]['ms']:.2f}x\")\n", "else:\n", " print(\"no CUDA compiler available: GPU checkpoint skipped\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-19" }, { "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", "| vector-add block size | look at `threads = 64, 128, 256, 512, 1024` in section 2, then try `threads = 32` | Why is GB/s nearly flat from 64 to 1024, and what happens below 64? |\n", "| tile size | add `TILE = 8` alongside `16` and `32` | How does `TILE = 8` compare with `16` and `32`, and which resource limits each? |\n", "| non-power-of-two `N` | benchmark `N = 1000` and `N = 2000` | Do your kernels lose speed on sizes that are not multiples of 32? Does cuBLAS? |\n", "| naive block shape | change `matmul_naive_coalesced` from `dim3(16, 16)` to `dim3(32, 32)` | Does changing block size alone help the coalesced naive kernel, or hurt it? |\n", "| shared-memory padding | change `As[TILE][TILE]` to `As[TILE][TILE + 1]` and `Bs[TILE][TILE]` to `Bs[TILE][TILE + 1]` | Does avoiding 32-way bank conflicts change `tiled_32`? |\n", "| divergence granularity | in `diverge_kernel`, replace `(threadIdx.x & 1) == 0` with `threadIdx.x < 128` | Why does the slowdown disappear even though half of every block takes each branch? |" ], "id": "lab-4-2-cuda-20" }, { "cell_type": "code", "metadata": {}, "source": [ "# your experiments here" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Failure playground\n", "\n", "Three ways CUDA kernels break in real life. For each: run it, read the symptom, diagnose the cause,\n", "and write down the fix before checking Review 4.2.\n", "\n", "### 7a · Missing bounds check\n", "\n", "Remove `if (i < n)` from `vector_add_kernel`. Two things can happen when `n` is not a multiple of\n", "the block size (or when the grid is slightly too big):\n", "1. If the out-of-bounds threads land inside already-allocated memory, **no error is raised** — they\n", " silently corrupt neighbouring data.\n", "2. If they walk past an unmapped GPU memory page, CUDA raises an **illegal memory access** error.\n", " (Part 2 runs in a fresh subprocess so the sticky CUDA error does not poison the rest of your\n", " notebook.)" ], "id": "lab-4-2-cuda-22" }, { "cell_type": "code", "metadata": {}, "source": [ "FAIL_CUDA = r\"\"\"\n", "#include \n", "#include \n", "\n", "__global__ void vadd_no_bounds_kernel(const float* a, const float* b, float* c) {\n", " int i = blockIdx.x * blockDim.x + threadIdx.x;\n", " c[i] = a[i] + b[i]; // BUG: no if (i < n) check\n", "}\n", "\n", "template \n", "__global__ void matmul_tiled_nosync_kernel(const float* A, const float* B, float* C, int N) {\n", " __shared__ float As[TILE][TILE];\n", " __shared__ float Bs[TILE][TILE];\n", " int tx = threadIdx.x, ty = threadIdx.y;\n", " int col = blockIdx.x * TILE + tx;\n", " int row = blockIdx.y * TILE + ty;\n", " float acc = 0.0f;\n", " int num_tiles = (N + TILE - 1) / TILE;\n", " for (int t = 0; t < num_tiles; ++t) {\n", " int a_col = t * TILE + tx;\n", " int b_row = t * TILE + ty;\n", " As[ty][tx] = (row < N && a_col < N) ? A[row * N + a_col] : 0.0f;\n", " Bs[ty][tx] = (b_row < N && col < N) ? B[b_row * N + col] : 0.0f;\n", " __syncthreads();\n", " for (int k = 0; k < TILE; ++k) {\n", " acc += As[ty][k] * Bs[k][tx];\n", " }\n", " // BUG: missing second __syncthreads() before the next tile overwrites As and Bs\n", " }\n", " if (row < N && col < N) C[row * N + col] = acc;\n", "}\n", "\n", "__global__ void vadd_ok_kernel(const float* a, const float* b, float* c, int n) {\n", " int i = blockIdx.x * blockDim.x + threadIdx.x;\n", " if (i < n) c[i] = a[i] + b[i];\n", "}\n", "\n", "void vadd_no_bounds(torch::Tensor a, torch::Tensor b, torch::Tensor c, int blocks, int threads) {\n", " vadd_no_bounds_kernel<<>>(a.data_ptr(), b.data_ptr(), c.data_ptr());\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", "}\n", "\n", "torch::Tensor matmul_tiled_nosync(torch::Tensor A, torch::Tensor B) {\n", " int N = static_cast(A.size(0));\n", " auto C = torch::empty({N, N}, A.options());\n", " dim3 block(32, 32), grid((N + 31) / 32, (N + 31) / 32);\n", " matmul_tiled_nosync_kernel<32><<>>(A.data_ptr(), B.data_ptr(), C.data_ptr(), N);\n", " C10_CUDA_KERNEL_LAUNCH_CHECK();\n", " return C;\n", "}\n", "\n", "torch::Tensor vadd_launch_unchecked(torch::Tensor a, torch::Tensor b, int threads) {\n", " auto c = torch::zeros_like(a);\n", " int n = static_cast(a.numel());\n", " int blocks = (n + threads - 1) / threads;\n", " vadd_ok_kernel<<>>(a.data_ptr(), b.data_ptr(), c.data_ptr(), n);\n", " // Intentionally clear the error without raising, to show what silent failure looks like:\n", " cudaGetLastError();\n", " return c;\n", "}\n", "\"\"\"\n", "\n", "FAIL_CPP = \"\"\"\n", "void vadd_no_bounds(torch::Tensor a, torch::Tensor b, torch::Tensor c, int blocks, int threads);\n", "torch::Tensor matmul_tiled_nosync(torch::Tensor A, torch::Tensor B);\n", "torch::Tensor vadd_launch_unchecked(torch::Tensor a, torch::Tensor b, int threads);\n", "\"\"\"\n", "\n", "fail_mod = None\n", "fail_build_dir = None\n", "if CAN_COMPILE:\n", " fail_build_dir = pathlib.Path(tempfile.mkdtemp(prefix=\"lab_4_2_fail_\"))\n", " fail_mod = load_inline(\n", " name=\"lab_4_2_fail\",\n", " cpp_sources=FAIL_CPP,\n", " cuda_sources=FAIL_CUDA,\n", " functions=[\"vadd_no_bounds\", \"matmul_tiled_nosync\", \"vadd_launch_unchecked\"],\n", " extra_cuda_cflags=[\"-O3\"],\n", " build_directory=str(fail_build_dir),\n", " )\n", "\n", " # Part 1: silent corruption of sentinel memory right after n = 200\n", " n_use = 200\n", " a = torch.full((256,), 1.0, device=\"cuda\")\n", " b = torch.full((256,), 2.0, device=\"cuda\")\n", " c = torch.full((256,), -99.0, device=\"cuda\") # slots 200..255 are untouched sentinel data (-99.0)\n", " fail_mod.vadd_no_bounds(a, b, c, 1, 256)\n", " torch.cuda.synchronize()\n", " overwritten = int((c[n_use:] != -99.0).sum().item())\n", " print(f\"7a part 1 (silent corruption): n={n_use}, launched 1 block x 256 threads\")\n", " print(f\" sentinel slots [200..255] overwritten: {overwritten} / {256 - n_use}\")\n", " print(f\" c[198:204] = {[round(v, 1) for v in c[198:204].tolist()]}\")\n", "\n", " # Part 2: walking far past an allocation in an isolated subprocess -> illegal memory access\n", " oob_code = (\n", " \"import importlib.util, torch\\n\"\n", " f\"spec = importlib.util.spec_from_file_location('lab_4_2_fail', {str(fail_build_dir / 'lab_4_2_fail.so')!r})\\n\"\n", " \"m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)\\n\"\n", " \"a = torch.ones(1000, device='cuda'); b = torch.ones(1000, device='cuda'); c = torch.empty(1000, device='cuda')\\n\"\n", " \"try:\\n\"\n", " \" m.vadd_no_bounds(a, b, c, 100000, 256)\\n\"\n", " \" torch.cuda.synchronize()\\n\"\n", " \" print('no error')\\n\"\n", " \"except Exception as ex:\\n\"\n", " \" print('7a part 2 (illegal access):', type(ex).__name__, '-', str(ex).splitlines()[0])\\n\"\n", " )\n", " res = subprocess.run([sys.executable, \"-c\", oob_code], capture_output=True, text=True)\n", " print(res.stdout.strip() or res.stderr[-300:])\n", "else:\n", " print(\"no CUDA compiler available: skipped 7a (read the kernel and answer the questions)\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: with `n = 200` and `256` threads, no error is raised, yet 56 sentinel floats past `n` were\n", "silently overwritten; with more threads, CUDA aborts with an illegal memory access. Which of the two\n", "bugs is harder to catch in a real training run, and why? Write down the one-line guard that prevents\n", "both." ], "id": "lab-4-2-cuda-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7b · Missing `__syncthreads()` in the tiled kernel\n", "\n", "In `matmul_tiled_nosync_kernel`, the first `__syncthreads()` (after loading `As` and `Bs`) is still\n", "there, and only the *second* `__syncthreads()` (after the inner `k` loop) was deleted. Run it five\n", "times on the exact same `1024 x 1024` matrices." ], "id": "lab-4-2-cuda-25" }, { "cell_type": "code", "metadata": {}, "source": [ "if CAN_COMPILE:\n", " torch.manual_seed(0)\n", " A_race = torch.randn(1024, 1024, device=\"cuda\")\n", " B_race = torch.randn(1024, 1024, device=\"cuda\")\n", " ref_race = A_race @ B_race\n", " errs_race = []\n", " for run in range(1, 6):\n", " out_race = fail_mod.matmul_tiled_nosync(A_race, B_race)\n", " torch.cuda.synchronize()\n", " e = (out_race - ref_race).abs().max().item()\n", " errs_race.append(e)\n", " print(f\"run {run}: max_abs_err = {e:.4f} (out[0,0]={out_race[0,0].item():+.4f}, ref[0,0]={ref_race[0,0].item():+.4f})\")\n", " del A_race, B_race, ref_race, out_race\n", " torch.cuda.empty_cache()\n", "else:\n", " print(\"no CUDA compiler available: skipped 7b (read the kernel and answer the questions)\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: every run on the exact same inputs produces a *different*, wrong answer, and no error is\n", "ever raised. Why is the *second* `__syncthreads()` necessary when the first one is already present?\n", "Explain what a fast warp does to `As` and `Bs` while a slower warp in the same block is still\n", "finishing its `k` loop." ], "id": "lab-4-2-cuda-27" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7c · Launching with too many threads per block\n", "\n", "Try launching `vector_add` with `threads = 2048` (above the hardware limit of 1,024 threads per\n", "block): first *without* checking the launch error, then *with* `C10_CUDA_KERNEL_LAUNCH_CHECK()`." ], "id": "lab-4-2-cuda-28" }, { "cell_type": "code", "metadata": {}, "source": [ "if CAN_COMPILE:\n", " x_bad = torch.full((2048,), 1.0, device=\"cuda\")\n", " y_bad = torch.full((2048,), 2.0, device=\"cuda\")\n", "\n", " silent = fail_mod.vadd_launch_unchecked(x_bad, y_bad, 2048)\n", " torch.cuda.synchronize()\n", " print(\"without launch check -> c[:5] =\", silent[:5].tolist(), \"(expected [3.0, ...]; kernel never ran!)\")\n", "\n", " try:\n", " _ = vadd_mod.vector_add(x_bad, y_bad, 2048)\n", " torch.cuda.synchronize()\n", " except Exception as ex:\n", " print(\"with launch check ->\", type(ex).__name__, \"-\", str(ex).splitlines()[0])\n", "\n", " # Confirm the CUDA context is still healthy after a bad launch configuration\n", " ok = vadd_mod.vector_add(x_bad, y_bad, 256)\n", " print(\"after fixing threads=256 -> c[:5] =\", ok[:5].tolist())\n", "else:\n", " print(\"no CUDA compiler available: skipped 7c (read the cell and answer the questions)\")" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-29" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: without a launch check, the kernel silently never executes and returns all zeros; with the\n", "check, CUDA rejects the launch with an invalid-argument error. What is the maximum number of threads\n", "per block on your GPU, why is it a fixed hardware limit, and why should every CUDA launcher call\n", "`C10_CUDA_KERNEL_LAUNCH_CHECK()` (or `cudaGetLastError()`) right after `<<<...>>>`?" ], "id": "lab-4-2-cuda-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Versions tested" ], "id": "lab-4-2-cuda-31" }, { "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,\n", " text=True,\n", " ).stdout.strip()\n", " print(\"NVIDIA driver\", drv)\n", " except Exception:\n", " pass\n", "if NVCC:\n", " nv = subprocess.run([NVCC, \"--version\"], capture_output=True, text=True).stdout.strip().splitlines()[-2:]\n", " print(\"nvcc:\", \" | \".join(nv))\n", "if NINJA:\n", " nj = subprocess.run([NINJA, \"--version\"], capture_output=True, text=True).stdout.strip()\n", " print(\"ninja:\", nj)\n", "if shutil.which(\"ncu\"):\n", " ncu_v = subprocess.run([\"ncu\", \"--version\"], capture_output=True, text=True).stdout.strip().splitlines()[-1]\n", " print(\"ncu:\", ncu_v)" ], "execution_count": null, "outputs": [], "id": "lab-4-2-cuda-32" } ] }