Kernel Fusion, Softmax, and Attention
Remove unnecessary memory traffic and preserve numerical stability
Derive fusion economics, online softmax, IO-aware attention, and the boundaries where recomputation beats memory traffic.
Consider a PyTorch expression that adds a bias to 67 million activation values and then applies GELU. Eager execution can launch one CUDA kernel to write the biased values to GPU high-bandwidth memory and another kernel to read those values, apply GELU, and write the final output. Nsight Systems shows two launch rectangles, while Nsight Compute reports a full-tensor write and read for an array that exists only between the two operations. A single CUDA or Triton kernel can calculate both expressions while each value remains in a register.
Kernel fusion is the established name for combining such producer and consumer operations into one GPU kernel. Fusion can remove launches and intermediate memory traffic, but the combined kernel may keep more values alive, allocate more registers, lose a library GEMM, or duplicate work needed by another consumer. The chapter measures the removed bytes and the new resource costs before treating fusion as an improvement.
Transformer attention supplies a larger real example. A direct implementation computes a score for every query-key pair, writes the score matrix to high-bandwidth memory, reads it for softmax, writes probabilities, and reads them again to combine value vectors. For a batch of eight sequences, 32 heads, and sequence length 4096, a single score tensor contains more than four billion elements. A profiler or memory snapshot can therefore show gigabytes of intermediate storage even though the model ultimately needs only the normalized weighted value for each query.
In the profiles, a central processing unit (CPU) launches kernels on a graphics processing unit (GPU), and large tensors reside in high-bandwidth memory (HBM). Attention contains matrix multiplication (GEMM) for query-key scores and probability-value products. During inference, later chapters retain key-value (KV) vectors from earlier tokens so one-token decode does not recompute the complete prompt.
The chapter first derives a stable running softmax from small rows whose numbers can be checked by hand. The chapter then follows query, key, and value tiles through on-chip storage to explain FlashAttention, an exact attention algorithm that avoids materializing the complete score and probability matrices. Separate lessons show why training, prompt prefill, and one-token decode use different attention schedules even though all three implement the same mathematical attention equation.
Prerequisites
- Chapters 3, 6, 8, and 9: traffic models, tiling, reductions, and GEMM
- Ordinary stable softmax: subtract the row maximum before exponentiation
- Scaled dot-product attention
Learning objectives
- Calculate the traffic and resource effects of a fusion boundary
- Derive and test the online softmax recurrence
- Trace exact tiled attention for training, prefill, and decode
Study this chapter
- 10.1Costs and benefits of kernel fusionBegin lesson →
Compare eliminated traffic and launches with added live state, recomputation, and schedule constraints
- 10.2Online stable softmaxBegin lesson →
Derive the maximum, normalization-sum, and weighted-numerator updates for tiled softmax
- 10.3IO-aware exact attentionBegin lesson →
Trace one exact tiled-attention iteration and account for the HBM tensors that it avoids
- 10.4Training and serving attention variantsBegin lesson →
Select an attention schedule from training, prefill, or decode requirements and the KV-cache layout
Extended exercises
Complete these projects after the lesson-level practice tasks. Each project combines several mechanisms from the chapter.
Fused normalization
Fuse a reduction-based normalization with a following affine or residual operation.
Evidence: Removed-byte model and correctness across extreme values.
Online softmax
Implement tiled online softmax and compare with a stable reference.
Evidence: Invariant proof, adversarial tests, and bandwidth comparison.
Tiled exact attention
Implement forward tiled exact attention for a constrained shape family.
Evidence: IO complexity, profiler data, numerical error, and a comparison with a declared framework baseline.
Sources and further reading
The lesson explanations synthesize primary papers and official references. Follow the originals for proofs, exact APIs, architecture details, and version-sensitive behavior.