Phase 06/Writing your own kernels/Custom CUDA and attention kernels
PHASE 06 · Writing your own kernels

Custom CUDA and attention kernels

0%
18 h7 subtopics3 lessons · 3 required
In plain English

Attention is the part of a language model where every word compares itself to every earlier word, and it is where the clever memory tricks live. In this topic you build that operation yourself, first in plain CUDA and then as a FlashAttention-style kernel that never writes the giant comparison table to memory. Think of it as the difference between a bookkeeper who writes every intermediate sum on paper and one who keeps a running total in their head: the second finishes faster because they spend less time reaching for paper. You will also add paged KV cache lookups, which is the exact trick vLLM uses to serve many users at once.

Why it matters

Attention kernels dominate decode latency for long contexts and are the most frequently rewritten code in inference engines. Being able to write and profile one, even a simple version, is the clearest signal that you understand where the time goes.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Write a CUDA kernel with shared memory tiling and launch it from PyTorch via a custom extension or load_inline.
  • Implement naive attention and a single-pass online-softmax (FlashAttention-style) attention kernel.
  • Extend the kernel to read K and V through a block table, as paged attention does.
  • Profile the kernels with Nsight Compute or torch.profiler and attribute time to memory versus compute.
  • Compare correctness and speed against torch.nn.functional.scaled_dot_product_attention.

Key concepts

Online softmax
Computing softmax in one pass by tracking a running max and rescaling the running sum when the max changes.
Tiling over KV
Processing keys and values in blocks held in shared memory so the full N by N score matrix is never materialized.
Block table
Indirection from logical KV position to a physical block address, enabling non-contiguous KV cache.
Split-K decode
Parallelizing a single query's attention over KV chunks across blocks and reducing partial results.
Occupancy
Fraction of warp slots on an SM that are active, limited by registers and shared memory per block.
Bank conflict
Multiple threads in a warp hitting the same shared memory bank, serializing access.
Custom op registration
Exposing a CUDA kernel to PyTorch through torch.utils.cpp_extension or torch.library so it can be called from Python.

Subtopics

  1. 1. CUDA from PyTorch

    torch.utils.cpp_extension.load_inline, nvcc flags, launching a kernel on tensors, error checking and synchronization.

  2. 2. Naive attention kernel

    One thread per query row computing scores, softmax and weighted sum; establishes a correctness baseline.

  3. 3. FlashAttention-style forward pass

    Tile Q and KV into shared memory, maintain running max and sum per row, rescale the output accumulator.

  4. 4. Paged KV lookup

    Add a block table so K and V for a sequence live in scattered fixed-size blocks; measure the cost of the indirection.

  5. 5. Decode-shape attention

    Single query against long KV; parallelize over KV chunks and reduce; why decode attention is bandwidth-bound.

  6. 6. Profiling and tuning

    Read achieved occupancy, memory throughput and stall reasons; tune block sizes and check for bank conflicts.

  7. 7. PyTorch custom-op integration and compilation

    Register CUDA or Triton kernels through torch.library, provide fake/meta behavior for shape propagation, declare autograd or inference-only semantics, support dynamic shapes under torch.compile, and package extensions reproducibly.

Resources

Hands-on lessons

L1

Naive and tiled attention in CUDA via load_inline

Colab T4 · freenotebook240 minrequired

Goal · Build two CUDA attention kernels callable from PyTorch and show the tiled online-softmax version uses O(N) extra memory and runs faster at N=4096.

  1. 1In a Colab T4 notebook, confirm nvcc is available and write a hello-world kernel with torch.utils.cpp_extension.load_inline.
  2. 2Implement naive_attention where each thread computes one query row by writing scores to global memory, then softmax, then the weighted sum.
  3. 3Verify against F.scaled_dot_product_attention for batch 1, heads 8, N in (128, 1024), d 64, fp32, with atol 1e-4.
  4. 4Implement flash_attention_fwd with BLOCK_M query tiles and a loop over BLOCK_N KV tiles in shared memory, maintaining running max m, sum l and output accumulator O per row.
  5. 5Verify at N 4096 and record torch.cuda.max_memory_allocated for both kernels.
  6. 6Time both kernels and SDPA at N in (512, 1024, 2048, 4096) with CUDA events; plot latency versus N.
  7. 7Add causal masking as a flag and re-verify.
Deliverable
Notebook with both kernels, correctness asserts, memory numbers and the latency plot.
Check
The tiled kernel's peak memory does not grow quadratically with N (less than 2x from 2048 to 4096) and it is faster than the naive kernel at N 4096.
Fallback
Write the same two kernels in Triton following tutorial 06 if nvcc compilation in Colab fails; the memory and speed checks are identical.
L2

Paged decode attention with a block table

Colab T4 · freenotebook240 minrequired

Goal · Implement decode attention that reads K and V through a block table and measure the overhead of paging versus contiguous KV.

  1. 1Allocate a KV cache as [num_blocks, block_size 16, heads, d] and a block_table [num_seqs, max_blocks] with randomly permuted block ids.
  2. 2Build a reference by gathering each sequence's blocks into contiguous K and V and calling SDPA with a single query token.
  3. 3Write paged_decode_kernel (CUDA or Triton) where each block handles one (sequence, head) and loops over the block table, computing online softmax over KV.
  4. 4Verify against the reference for 32 sequences with context lengths from 100 to 4000 tokens.
  5. 5Time paged versus contiguous decode attention for context 4096 and batch 32; compute effective bandwidth as KV bytes read per second.
  6. 6Implement a split-KV variant where several blocks cooperate on one long sequence and reduce partial (m, l, O); compare for batch 1, context 8192.
  7. 7Record findings on when the indirection cost is visible and when it is hidden under bandwidth.
Deliverable
Notebook with the paged kernel, split-KV variant, correctness asserts and the bandwidth comparison.
Check
Paged kernel matches the reference within atol 1e-3 in fp32 and achieves at least 50 percent of T4 peak bandwidth at batch 32, context 4096.
Fallback
Use Kaggle T4; without any GPU, implement in Triton and verify under TRITON_INTERPRET=1 for small sizes, skipping bandwidth numbers.
L3

Ship your kernel as a torch.compile-compatible custom op

Colab T4 · freenotebook180 minrequired

Goal · Integrate one attention or paged-KV kernel as a packaged PyTorch custom operator that works in eager mode and a full-graph torch.compile model.

  1. 1Choose the Triton or CUDA kernel from lesson l1 or l2 and wrap its public signature in a small nn.Module; write a pure PyTorch reference with the same dynamic-shape contract.
  2. 2Define the operator schema with torch.library.custom_op (or Library.define for a C++/CUDA extension), register the CUDA implementation, and document aliasing and mutation behavior.
  3. 3Register a fake/meta implementation that returns tensors with correct symbolic shapes, strides, dtype and device; run torch.library.opcheck over several sequence lengths.
  4. 4For an inference-only op, explicitly register it as non-differentiable and assert backward fails with your documented message; otherwise register autograd and run torch.autograd.gradcheck in double precision on a small input.
  5. 5Call the op through the nn.Module in eager mode and under torch.compile(fullgraph=True, dynamic=True); test at least three shapes including one not seen during compilation.
  6. 6Assert outputs against the PyTorch reference (fp32 atol 1e-4/rtol 1e-4, fp16 or bf16 atol 2e-2/rtol 2e-2) and ensure no graph breaks with TORCH_LOGS=graph_breaks.
  7. 7Benchmark reference eager, custom-op eager and custom-op compiled with warm-up and CUDA events at four representative shapes; report median and p95 latency plus speedup.
  8. 8Package the operator with torch.utils.cpp_extension or a wheel build, install it into a clean runtime, and run the correctness/opcheck/compile tests without relying on notebook state.
Deliverable
A package or wheel, operator schema and registrations, nn.Module integration, clean-environment tests, benchmark CSV/plot and a README stating supported dtypes/shapes/devices and autograd semantics.
Check
torch.library.opcheck passes; eager and fullgraph dynamic torch.compile outputs meet the stated tolerances at all test shapes; graph-break log is empty; gradcheck passes or the documented inference-only backward assertion fires; clean-environment install and tests exit 0.
Fallback
Without NVIDIA hardware, register a Python or C++ CPU custom op with the same schema, fake implementation and dynamic torch.compile tests; benchmark it for integration correctness rather than speed.

Build your own

Build your own paged attention CUDA kernel as a torch custom op

CUDA C++Colab T4 · free~12 h

A decode attention kernel that reads K and V through a block table, written in CUDA, compiled through torch.utils.cpp_extension, registered as a torch.compile-compatible custom operator and benchmarked against a contiguous reference.

The real thing: github.com/vllm-project/vllm/blob/v0.10.0/csrc/attention/paged_attention_v1.cu ↗

How you know a stage passes

Write tests/test_paged_attention.py first. The reference gathers each sequence's blocks into contiguous K and V and calls F.scaled_dot_product_attention with one query token; every stage compares your kernel to it with torch.testing.assert_close (fp32 atol 1e-4, fp16 atol 1e-2) over 32 sequences with context lengths from 1 to 4096 and a randomly permuted block table. bench.py reports effective KV bandwidth in GB/s. Run `pytest -q` on the Colab T4; a stage is done when its tests pass and earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01one thread block per (sequence, head), fp32
    A kernel where each block owns one (sequence, head), loops over the block table, computes dot products with the query, and does a two-pass softmax through shared memory.
    test · assert_close passes for all 32 sequences in fp32; the kernel compiles with load_inline and the first call completes with no illegal memory access under compute-sanitizer.
  2. 02online softmax and vectorized loads
    Replace the two-pass softmax with running (m, l, acc) per thread group and load K/V rows as float4 or half2 so each warp reads coalesced 128-byte segments.
    test · Tests still pass; effective bandwidth at batch 32, context 4096, fp16 is at least 50 percent of T4 peak (160 GB/s or more) in bench.py.
  3. 03fp16 KV with fp32 accumulation and GQA
    K and V are stored in fp16, accumulation stays in fp32, and num_kv_heads may be smaller than num_q_heads with query heads mapped to their shared KV head.
    test · assert_close(atol 1e-2) passes for fp16 with 32 query heads and 8 KV heads; a test with num_kv_heads equal to num_q_heads still matches the fp32 path within 1e-2.
  4. 04split-KV for long single sequences
    A second kernel launches several blocks per (sequence, head) over disjoint KV ranges, writes partial (m, l, acc), and a reduce kernel combines them; the wrapper picks split or non-split by context length and batch size.
    test · Batch 1, context 8192 matches the reference and is at least 3x faster than the non-split kernel; batch 32 still routes to the non-split path (asserted through a counter in the wrapper).
  5. 05torch custom op registration
    The kernel is exposed through torch.library as paged_attn::decode with a schema, a CUDA implementation, a fake implementation with symbolic shapes, and an explicit non-differentiable registration.
    test · torch.library.opcheck passes at three shapes; calling backward raises your documented error; torch.compile(fullgraph=True, dynamic=True) of a module using the op shows zero graph breaks under TORCH_LOGS=graph_breaks.
  6. 06build as a wheel and benchmark table
    A setup.py with CUDAExtension builds a wheel for sm_75; bench.py produces a table of paged versus contiguous SDPA latency and bandwidth at four (batch, context) points.
    test · `pip install dist/*.whl` in a fresh runtime then `pytest -q` passes; the README table shows paged latency within 1.3x of contiguous SDPA at batch 32, context 4096 and the bandwidth numbers from s2.

No GPU? Use a Kaggle T4 if Colab has no GPU. Without any NVIDIA GPU, write the same kernel in Triton and run tests under TRITON_INTERPRET=1 for stages 1 to 5, skipping bandwidth targets; register a CPU reference implementation for the custom op so stage 5's opcheck and compile tests still run on the Mac.

Knowledge check

QWhy does online softmax let attention avoid materializing the N by N score matrix?

Each KV tile's contribution can be folded into a running max, running sum and running output by rescaling with exp(old_max minus new_max), so scores are never stored.

QWhat does a block table cost in a paged attention kernel?

An extra indirection per KV block to look up its physical address; it is usually hidden because the kernel is bandwidth-bound on the KV reads themselves.

QWhy is decode attention bandwidth-bound rather than compute-bound?

Each query token does only 2*d flops per key but must read the full K and V for the sequence from HBM, so bytes moved dominate.

QWhy split KV across blocks for a single long-context query?

One block per (sequence, head) leaves most SMs idle at batch 1; splitting the KV range across blocks and reducing partial results restores parallelism.

Completion

  • All 7 subtopics marked done
  • All 3 required lessons done
  • Lessons l1, l2 and l3 deliverables saved with correctness, opcheck and compile checks passing.
  • Can write the online softmax update rule from memory and explain the block table indirection.
  • All subtopics marked completed.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →