Skip to content

5.2 Kernels and FlashAttention

ready≈ 14 hoursNeeds: 5.1, 4.4
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (FlashAttention tiling animation)
  4. 4 Do
  5. 5 Check

The problem. Written as three separate GPU kernels, attention writes the N × N score matrix to GPU memory (HBM), reads it back for the softmax, writes the probabilities and reads them again for the product with V. For long sequences those 4N² numbers dominate, and the operation is memory-bound (5.1). The fix is not fewer FLOPs but fewer bytes moved (Dao et al. 2022, §2).

Tiling and the online softmax. A GPU has a little very fast on-chip memory (SRAM). FlashAttention loads a tile of queries and a tile of keys and values into it and computes that tile’s scores. The difficulty is the softmax, which needs the whole row. The way out is to keep, for every query row, the running maximum m and the running sum l of exp(score − m). When a new tile raises the maximum, the sum and the partial output are rescaled by exp(m_old − m_new) (Milakov & Gimelshein 2018). The result is exact attention, and the N × N matrix never reaches HBM.

The backward pass needs the probabilities again. Rather than storing them, FlashAttention saves only the logsumexp L of every row and recomputes P = exp(S − L) tile by tile, trading cheap FLOPs for expensive bytes. FlashAttention-2 puts the query tiles in the outer loop, so that each one can run in parallel and write its output once (Dao 2023, §3).

Triton is a Python language for GPU kernels in which a program computes one block of the output and the compiler handles the threads within it. It is how you will write the kernel, as in CS336 Assignment 2 (Tillet et al. 2019).

Rescaling running sums gives the exact softmaxstep 1 of 5
  1. o=∑jesj vj∑jesj=∑jesj−m vj∑jesj−mfor any mo = \frac{\sum_j e^{s_j}\,\mathbf{v}_j}{\sum_j e^{s_j}} = \frac{\sum_j e^{s_j - m}\,\mathbf{v}_j}{\sum_j e^{s_j - m}}\quad\text{for any } m

FlashAttention tiling animation

Why tiling avoids slow memory reads

Static view on small screens. Open this page on a laptop to interact.

keys (K, V) →queries →shade: exp(S − running max) · grey: masked

In fast on-chip memory (SRAM) now:

Nothing yet. Press Next tile.

tile 0 of 10 (6 skipped by the mask) HBM traffic so far 0 numbers (all tiles: 464) unfused attention: 1280 numbers, 1024 of them for S and P

FlashAttention for one head with 16 tokens and d = 4. Each step loads one tile of queries and one tile of keys and values, computes that tile's scores, and updates every query row's running maximum m and sum l. When a new tile holds a larger score, the old sum and the output accumulator are multiplied by exp(m_old − m_new) (highlighted), so nothing computed earlier is wasted or wrong. The N × N matrix never exists in GPU memory: only one tile at a time, in SRAM. At this toy size the saving is modest. For large N it levels off near 2 × tile size / d (about 4× for d = 64 and tiles of 128): unfused attention moves 4N² numbers for S and P, and the tiled kernel still re-reads K and V once per query tile, which also grows as N². The bigger win is memory: S and P are never stored.

A 16 × 16 grid of attention scores for 16 tokens is processed one tile at a time. The current tile is outlined, with markers on the query rows and key columns loaded into SRAM; processed tiles are shaded by exp(score − running max), and masked cells are grey. A table lists, for each query row of the current tile, the running maximum before and after, the rescale factor (highlighted when the maximum grew) and the running sum. Controls step back and forward, play, reset, set the tile size, toggle the causal mask and draw new data. Counters compare the numbers moved to and from GPU memory with unfused attention. Keyboard: Tab to the step buttons and press Enter; the tile-size select and causal toggle are next.

First, the algorithm in NumPy, in the browser or locally: the online softmax, then the tiled forward and backward passes, checked against plain attention and finite differences.

FlashAttention forward and backward in NumPy stubs/m5_2_flash.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m5_2_flash.py and run mlc check 5.2. The tests are identical; import the results on the progress page.

Hints · flash_forward 0/3 revealed
Hints · flash_backward 0/3 revealed

Then write it in Triton. Open notebooks/5.2-triton-flashattention.ipynb on Kaggle with a T4 GPU. Triton officially supports only GPUs of compute capability 8.0 and newer; kernels like these generally run on the T4 (7.5) anyway, but not on the P100. Fill in a fused row-softmax kernel and the inner loop of a FlashAttention-2 forward kernel, a line-by-line translation of your NumPy code. The notebook wraps it in an autograd function, checks outputs and gradients against plain attention with and without the causal mask, and times it against plain attention and PyTorch’s scaled_dot_product_attention up to 8,192 tokens. Without a GPU, Triton’s interpreter runs the same kernels on the CPU at small sizes, so you can debug on a laptop.

1. Is FlashAttention an approximation of attention?
2. Does FlashAttention do fewer FLOPs than plain attention?
3. What does the forward pass save for the backward pass, besides Q, K, V and O?
4. A new key tile contains a score larger than the current row maximum. What happens to the accumulated output?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.