Reference
← All guidesFlashAttention
FlashAttention computes softmax attention in tiles that fit in fast on-chip memory. It reduces GPU memory traffic by avoiding a full score matrix in high-bandwidth memory (HBM).
Overview
How it works
The attention equation stays the same. FlashAttention changes how the GPU schedules the work and stores intermediate results. It computes exact attention, up to floating-point rounding differences.
Details
The cost of intermediate matrices
For N tokens, the score matrix has N² entries per head. A standard implementation writes scores and attention weights to HBM between operations. Reading and writing those matrices can take a large share of the runtime.
Details
HBM and on-chip SRAM
HBM is the GPU’s large main memory. On-chip SRAM is much smaller and faster to access. FlashAttention chooses blocks of queries, keys and values whose temporary results fit on-chip.
Details
Processing one tile
Load a query block and a key/value block. Compute their scores and add their contribution to the output. Discard the scores, then process the next block.
Details
Online softmax
For each query row, keep the running maximum m, normalization sum ℓ, and partial output vector O. If a new tile has a larger maximum, rescale the previous contributions. These updates give the same softmax result without keeping every score.
Details
Numerical accuracy
FlashAttention does not drop tokens or approximate softmax. It changes the order of floating-point operations, so results can differ slightly from another implementation. Exact attention does not imply bit-for-bit equality.
Details
Performance limits
Tiling reduces transfers of intermediate data. Attention still computes O(N²) token pairs, so the computation remains quadratic in sequence length. Actual speed depends on the GPU, head dimensions, precision and kernel. The interactive timing bars are estimates.
Sources