Efficient Attention

Standard attention compares every query with every key. For tokens, the score matrix has entries. One head needs arithmetic and memory for its attention matrix. A causal decoder skips about half of the pairs, but its cost still grows as . Efficient attention methods lower this cost in one of two ways:

  • Exact methods compute the same output with less memory traffic. FlashAttention never stores the matrix. It processes the keys and values in blocks that fit in the GPU’s fast on-chip memory. It keeps running softmax statistics for each query.
  • Approximate methods compute a different function. Sparse attention lets each query read only some keys. Examples are a window of neighbors, a dilated pattern or a few global tokens. Kernelized and ridge attention, from HW10, replace the softmax weights with other weights.

Not Taught in Lecture

The lecture gives only the quadratic cost. Sparse patterns follow Prince §12.9 and its chapter notes. FlashAttention follows Dao et al. (2022), and FlashAttention-2 follows Dao (2023). Kernelized and ridge attention come from HW10.

Intuition

A GPU has two kinds of memory. Its main memory (HBM) is large but slow to read. Its on-chip memory (SRAM) is fast but tiny. Dao et al. give numbers for an A100 GPU. It has to GB of HBM with a bandwidth of to TB/s. Each of its processors has KB of SRAM, with a total bandwidth of about TB/s. Every operation reads its inputs from HBM into SRAM, computes, and writes the result back to HBM.

Standard attention runs as three separate operations. The first computes and writes it to HBM. The second reads , applies the softmax, and writes . The third reads and computes . The matrices travel to and from HBM four times. For long sequences this traffic, not the arithmetic, sets the running time.

FlashAttention fuses the three steps into one. It loads a block of queries and a block of keys and values into SRAM. It computes their scores there and updates the output, then moves on to the next key block. No matrix is ever written to HBM. The difficulty is the softmax, whose denominator needs all the scores of a row. The online softmax solves this with a running maximum and a running sum.

Properties

(Online Softmax) A row of softmax-weighted values can be computed one block of keys at a time by keeping three running quantities.

Fix one query. After some key blocks, keep the largest score so far , the sum and the vector . Both sums run over the keys seen so far. A new block brings scores with values . Set . Then

After the last block, the output is . The factor rescales the old sums whenever the maximum grows. Subtracting the maximum keeps every exponential at most , so nothing overflows. The result equals the ordinary softmax output exactly, as the Hard example proves.

(Tiling) FlashAttention splits , and into blocks of rows sized to fit in SRAM and loops over the blocks.

Take a block of query rows. For each block of key and value rows, the kernel computes the block of scores in SRAM. It then updates , and for every query in its block. After the last key block, it divides by and writes the output rows to HBM. It also writes and , or the single number per query, for the backward pass. The extra memory is numbers instead of the of a stored attention matrix.

(Fewer Memory Accesses, Same Arithmetic) FlashAttention does the same arithmetic as standard attention but far fewer reads and writes to HBM.

Let be the SRAM size in numbers, with . Dao et al. prove that standard attention makes HBM accesses. FlashAttention makes . The ratio of the terms is about . With and , that ratio is , so the traffic drops about -fold. With it is , and the saving mostly disappears. These are orders of magnitude, since the bounds drop constant factors. A model with heads of size to gains the most.

(Recompute Instead of Store) The backward pass recomputes the attention blocks from , and the saved statistics instead of reading a stored matrix.

The gradient of attention needs the weights . Standard training stores in the forward pass, which costs memory per head and layer. FlashAttention stores only the output and the row statistics. In the backward pass it reloads blocks of , and and recomputes each block of in SRAM. This adds arithmetic but removes most of the memory traffic, so the backward pass also runs faster. The same trade of compute for memory appears in gradient checkpointing.

(FlashAttention-2) FlashAttention-2 changes the order and the split of the work and runs about twice as fast as FlashAttention.

The outer loop runs over blocks of queries. Different query blocks can then run on different processors at the same time. This adds parallelism over the sequence, which helps when the batch is small and the sequence long. The division by moves to the very end, which removes some operations that are not matrix multiplications. Such operations run much slower than matrix multiplications on GPU hardware. The work inside each processor is also split differently between its thread groups.

(Sparse Attention) If each query reads a fixed set of keys, the cost falls from to times the set size.

Prince describes the allowed pairs as an interaction matrix. In a convolutional pattern, each token reads only the tokens nearest to it, which costs . Information still travels far over several layers, because the receptive field grows with depth as in a CNN. Dilated windows skip tokens and grow the receptive field faster. A few tokens can also be made global, so that they read and are read by all tokens. The <cls> token of BERT is a natural choice. BigBird combines windows, global tokens and random connections. Unlike FlashAttention, these patterns change the model, since some pairs can never interact within one layer.

Examples

(Easy) Memory for the Attention Matrix

A model reads tokens with heads per layer. Numbers are stored in 16-bit floats of bytes, and the statistics in 32-bit floats of bytes.

(Medium) Online Softmax by Hand

One query has scores for three keys with scalar values . The keys arrive in two blocks: the first two keys, then the third.

(Hard) The Online Softmax Is Exact

Prove that the online softmax gives the ordinary softmax output for any split of the keys into blocks.

See Also