FlashAttention and the memory hierarchy

Exact attention can run several times faster, with memory linear in sequence length, by never writing the n × n matrix to slow memory. The trick is tiling plus a way to compute softmax one block at a time.

45 min

After this lesson you can

  • Explain why standard attention is limited by memory traffic rather than arithmetic
  • Derive the online softmax update (running maximum and running sum) and prove it gives the exact softmax
  • Implement tiled attention in NumPy that matches naive attention to within
  • Explain recomputation in the backward pass, and what FlashAttention-2 and -3 changed

In this lesson

  1. Two kinds of memory
  2. Tiling: never write the big matrix
  3. The online softmax
  4. The backward pass: recompute instead of remember
  5. FlashAttention-2 and -3
  6. Code: online softmax and tiled attention, checked against the naive version

This lesson is part of Descent Pro

Descent Pro unlocks every lesson on the route, from base camp to the summit. Every plan starts with a free trial.

Descent Pro

Start your free trial to keep reading

This lesson, and every other lesson on the route, is part of Descent Pro. Every plan starts with a free trial, and students with a .edu email get longer. Cancel before the trial ends and you pay nothing.