AI Logic

Attention Mechanisms

FlashAttention

Updated:

Structure of FlashAttention. The left shows the computation flow (blocks of Q, K, V are read from HBM into SRAM, the tile matrix product, softmax, and output update are performed in SRAM, and only the output O and statistics are written back to HBM). The right shows the attention matrix (N × N) split into tiles, computed with key blocks in the outer loop and query blocks in the inner loop

What is FlashAttention

FlashAttention is a way of computing attention that reduces reads and writes to GPU memory to make it faster, without changing the result. Dao et al. at Stanford University proposed it in 2022 in the paper "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness." PyTorch's F.scaled_dot_product_attention also automatically uses an implementation from this family (FlashAttention-2) when conditions allow.

A GPU has a large but slow memory (HBM) and a small but fast memory (SRAM). According to the paper, an A100 GPU has the following.

MemorySizeBandwidth
HBM (the GPU's main memory)40–80 GB1.5–2.0 TB/s
SRAM (on-chip memory)192 KB (for each of the 108 streaming multiprocessors)about 19 TB/s

A standard attention implementation writes SS, the result of QK⊤QK^\top, and PP, the result after softmax (both N×NN \times N), to HBM and reads them back for the next computation. Because GPU compute has become faster than memory, for operations with little computation such as softmax, reading and writing HBM takes more time than the computation itself.

FlashAttention splits Q,K,VQ, K, V into small blocks, loads them into SRAM, computes everything from the matrix product through softmax to the product with VV inside SRAM in one go, and writes only the output back to HBM. The N×NN \times N matrix is never written to HBM. In cooking terms, instead of carrying ingredients to and from the warehouse (HBM) one dish at a time, it brings over only what fits on the countertop at hand (SRAM) and does the cutting, frying, and plating there.

The right side of the figure at the top of the article shows the order of computation. Like standard attention, it computes every pair of the attention matrix, but it computes one tile at a time and discards each tile once it is done.

Computation steps

Suppose Q,K,V∈RN×dQ, K, V \in \mathbb{R}^{N \times d} (NN is the sequence length and dd is the head dimension) are in HBM. With MM the size of SRAM, Algorithm 1 in the paper computes as follows.

  1. Choose block sizes: Bc=⌈M/4d⌉B_c = \lceil M / 4d \rceil, Br=min⁡(⌈M/4d⌉,d)B_r = \min(\lceil M / 4d \rceil, d). Split QQ into TrT_r blocks of BrB_r rows and K,VK, V into TcT_c blocks of BcB_c rows.
  2. Initialize in HBM the output OO (0), the per-row sums ℓ\ell (0), and the per-row maxima mm (−∞-\infty).
  3. Outer loop: load one block Kj,VjK_j, V_j of K,VK, V into SRAM at a time.
  4. Inner loop: load a block QiQ_i of QQ and the corresponding Oi,ℓi,miO_i, \ell_i, m_i into SRAM.
  5. Tile matrix product: compute Sij=QiKj⊤S_{ij} = Q_i K_j^\top (Br×BcB_r \times B_c) in SRAM.
  6. Tile softmax: compute the per-row maximum m~ij\tilde{m}_{ij}, P~ij=exp⁡(Sij−m~ij)\tilde{P}_{ij} = \exp(S_{ij} - \tilde{m}_{ij}), and the per-row sum ℓ~ij\tilde{\ell}_{ij}, and combine them with the previous mi,ℓim_i, \ell_i to obtain the new minew,ℓinewm_i^{\text{new}}, \ell_i^{\text{new}}.
  7. Update the output: rescale OiO_i to the new maximum, add P~ijVj\tilde{P}_{ij} V_j, and write Oi,ℓi,miO_i, \ell_i, m_i back to HBM.

The update in step 7 is the following formula (line 12 of Algorithm 1 in the paper).

Oi←diag(ℓinew)−1(diag(ℓi) emi−minew Oi+em~ij−minew P~ijVj)O_i \leftarrow \mathrm{diag}(\ell_i^{\text{new}})^{-1}\Bigl(\mathrm{diag}(\ell_i)\, e^{m_i - m_i^{\text{new}}}\, O_i + e^{\tilde{m}_{ij} - m_i^{\text{new}}}\, \tilde{P}_{ij} V_j\Bigr)

After all blocks have been processed, OO is exactly equal to softmax(QK⊤)V\mathrm{softmax}(QK^\top)V (Theorem 1 of the paper).

In backpropagation, S,PS, P (N×NN \times N) are normally stored to compute gradients. FlashAttention stores only the output OO and the statistics m,ℓm, \ell (length NN), and recomputes S,PS, P block by block in SRAM during the backward pass. This adds computation, but it is faster than reading the N×NN \times N matrices from HBM.

Why softmax can be computed block by block

The key to FlashAttention is that softmax can be computed per block and correctly combined afterward, without seeing the whole row. Since softmax divides by the sum of all values in the row, it might seem impossible to compute until the whole row is available.

The paper expresses the softmax of a vector xx in terms of its maximum m(x)m(x) and sum ℓ(x)\ell(x).

m(x)=max⁡ixi,f(x)=(ex1−m(x),…,exB−m(x)),ℓ(x)=∑if(x)i,softmax(x)=f(x)ℓ(x)m(x) = \max_i x_i, \qquad f(x) = \bigl(e^{x_1 - m(x)}, \dots, e^{x_B - m(x)}\bigr), \qquad \ell(x) = \sum_i f(x)_i, \qquad \mathrm{softmax}(x) = \frac{f(x)}{\ell(x)}

When xx is split into two blocks x(1),x(2)x^{(1)}, x^{(2)}, the overall maximum and sum can be computed from the per-block values as follows.

m(x)=max⁡(m(x(1)), m(x(2))),ℓ(x)=em(x(1))−m(x) ℓ(x(1))+em(x(2))−m(x) ℓ(x(2))m(x) = \max\bigl(m(x^{(1)}),\, m(x^{(2)})\bigr), \qquad \ell(x) = e^{m(x^{(1)}) - m(x)}\,\ell(x^{(1)}) + e^{m(x^{(2)}) - m(x)}\,\ell(x^{(2)})

In other words, if mm and ℓ\ell are kept for each block, the softmax of the whole can be obtained simply by rescaling to the maximum of blocks that arrive later.

Here is a check with small numbers. Split x=(1,2,3,1)x = (1, 2, 3, 1) into two blocks, (1,2)(1, 2) and (3,1)(3, 1).

Maximum mmSum ℓ\ell
Block 1: (1,2)(1, 2)2e−1+e0≈1.368e^{-1} + e^{0} \approx 1.368
Block 2: (3,1)(3, 1)3e0+e−2≈1.135e^{0} + e^{-2} \approx 1.135
Combinedmax⁡(2,3)=3\max(2, 3) = 3e2−3×1.368+e3−3×1.135≈1.638e^{2-3} \times 1.368 + e^{3-3} \times 1.135 \approx 1.638

Computing directly gives e1−3+e2−3+e3−3+e1−3≈0.135+0.368+1+0.135=1.638e^{1-3} + e^{2-3} + e^{3-3} + e^{1-3} \approx 0.135 + 0.368 + 1 + 0.135 = 1.638, which matches.

Subtracting the maximum before taking exp⁡\exp is a common softmax trick to prevent values from becoming too large to represent in half precision (overflow). FlashAttention performs this "subtract the maximum" step per block, and when the maximum is updated it corrects the previous result by multiplying by emold−mnewe^{m_{\text{old}} - m_{\text{new}}}.

Why it is faster

FlashAttention does not reduce the amount of computation (FLOPs); it becomes faster by reducing the amount of HBM reads and writes. The paper gives the number of HBM accesses as follows (Theorem 2 of the paper).

ImplementationComputation (FLOPs)HBM accessesExtra memory
Standard attentionO(N2d)O(N^2 d)Θ(Nd+N2)\Theta(Nd + N^2)O(N2)O(N^2) (stores S,PS, P)
FlashAttentionO(N2d)O(N^2 d)Θ(N2d2M−1)\Theta(N^2 d^2 M^{-1})O(N)O(N) (only m,ℓm, \ell)

With head dimension dd of 64–128 and SRAM size MM of about 100KB, d2d^2 is much smaller than MM, so HBM accesses drop by a large factor. The paper also proves that, for a range of SRAM sizes, no method that computes exact attention can use fewer accesses than this (it is a lower bound).

The measured values are as follows (GPT-2 medium, sequence length 1024, head dimension 64, 16 heads, batch 64, A100; Figure 2 left of the paper; forward plus backward pass).

Standard attentionFlashAttention
Computation (GFLOPs)66.675.2
HBM reads/writes (GB)40.34.4
Runtime (ms)41.77.3

FLOPs increase because of the recomputation in the backward pass, but HBM reads and writes fall to about one ninth and the runtime is about 5.7 times faster. Another technique is fusing matrix multiplication, masking, softmax, dropout, and matrix multiplication into a single GPU program (kernel). With separate programs, intermediate results would have to be written to HBM and read back each time.

Experimental results

Because it is faster without changing the result, the same model can be trained in less time.

Training speed (all on 8 A100 GPUs)

ModelBaseline implementationBaseline training timeFlashAttention training time
BERT-large (sequence length 512)MLPerf 1.1 speed record (Nvidia)20.0 ± 1.5 min17.4 ± 1.4 min (15% faster)
GPT-2 small (sequence length 1K)Hugging Face9.5 days2.7 days (3.5×)
GPT-2 smallMegatron-LM4.7 days2.7 days
GPT-2 mediumHugging Face21.0 days6.9 days (3.0×)
GPT-2 mediumMegatron-LM11.5 days6.9 days

The perplexity of GPT-2 was the same for every implementation (18.2 for small), because the model definition was not changed (Tables 1 and 2 of the paper).

Longer sequences improve performance: the speedup allows longer sequences (Tables 4 and 6 of the paper).

  • Increasing the sequence length of GPT-2 small from 1K to 4K lowered perplexity from 18.2 to 17.5, and training was still 30% faster than Megatron-LM at 1K.
  • On Path-X, a task of length 16K, it became the first Transformer to achieve better-than-chance accuracy (61.4%). Block-sparse FlashAttention, which computes only predetermined blocks, reached 63.1% on Path-256 of length 64K.

Memory: memory usage grows linearly with sequence length and was up to 20 times smaller than standard exact attention implementations (Figure 3 right of the paper).

Practical considerations

FlashAttention is a way of computing that returns the same values as standard attention, so it can be swapped in without changing the model definition. However, it does not reduce the amount of computation itself.

Even with FlashAttention, computation grows with the square of the sequence length NN (O(N2d)O(N^2 d)). What decreases is memory reads and writes and the amount of memory used. Doubling the sequence length makes computation take roughly four times as long. In the paper, too, approximate attention methods that skip computation (such as Linformer) were sometimes faster once the sequence length exceeded 512–1024.

When using it, keep the following in mind.

  • Use PyTorch's built-in rather than writing your own: F.scaled_dot_product_attention automatically chooses among FlashAttention-2, a memory-efficient implementation, and PyTorch's straightforward implementation (math) when conditions allow. If conditions such as GPU type, data type, or mask type are not met, it switches to another implementation.
  • Check whether the fast implementation is selected with torch.nn.attention.sdpa_kernel: inside with sdpa_kernel(SDPBackend.FLASH_ATTENTION):, only the FlashAttention implementation can be forced.
  • Turn off dropout yourself: F.scaled_dot_product_attention does not look at model.eval(), so pass dropout_p=0.0 during inference.
  • attn_mask and is_causal cannot be specified together: specifying both raises an error. A mask that looks only backward can be specified with is_causal=True alone.
  • Attention weights cannot be retrieved: the N×NN \times N weights are not stored, so they must be computed separately if you want to visualize them. With need_weights=True (the default) in nn.MultiheadAttention, the fast implementation is not used.

The paper itself lists as a limitation that a dedicated CUDA program must be written for each new kind of attention, and that it may not carry over across GPU generations.

Comparison with other methods

Methods for lightening attention on long sequences are compared by "which part of the attention matrix is computed." FlashAttention is the only one that becomes faster without reducing the pairs computed.

MethodWhich part of the N×NN \times N matrix is computedResultComplexity (in sequence length NN)
Multi-head attention (standard implementation)All pairs. S,PS, P stored in HBMExactO(N2)O(N^2), memory also O(N2)O(N^2)
Sparse attention (Child et al., 2019)Only some pairs in a fixed patternSome pairs unattendedO(NN)O(N\sqrt{N})
Linear attention (Katharopoulos et al., 2020)Does not form the matrix (changes the order of computation)Replaces softmax with another functionO(N)O(N)
FlashAttention (Dao et al., 2022)All pairs. Split into small tiles; the full matrix is never kept in memoryExact (same values)Computation O(N2)O(N^2), extra memory O(N)O(N)

The paper compares these under the same conditions on Long-Range Arena, a benchmark of long sequences (sequence lengths 1,024–4,096) (Table 3 of the paper; average accuracy over five tasks).

MethodAverage accuracy (%)Speed relative to the standard implementation
Standard Transformer59.3—
FlashAttention59.82.4×
Block-sparse FlashAttention59.62.8×
Linear attention59.62.3×
Performer58.91.8×
Reformer57.61.3×
Linformer54.92.5×

FlashAttention stays exact while matching the speed of approximate methods. Block-sparse FlashAttention, which combines it with sparse attention, is even faster.

Guidelines for choosing:

  • In most cases: start with FlashAttention (F.scaled_dot_product_attention in PyTorch). It is faster and uses less memory without changing the model.
  • When sequences are very long and the N2N^2 computation time itself is the problem: consider methods that reduce the pairs computed, such as sparse attention or linear attention.
  • Improved version: FlashAttention-2 revisits the parallelization with the same idea, and PyTorch's built-in uses it.

PyTorch example

Show code
python
import math
import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel


def flash_attention_reference(q, k, v, block_r=64, block_c=64):
    """Reference implementation of the idea of Algorithm 1 in the paper, written in PyTorch (not fast; for checking the mechanism).
    q, k, v: [N, d]. Without forming the N × N matrix, update the output O and the statistics m, l tile by tile"""
    N, d = q.shape
    q = q / math.sqrt(d)                      # 1/√d of scaled dot-product attention
    o = torch.zeros(N, d)
    l = torch.zeros(N, 1)                     # per-row sum
    m = torch.full((N, 1), float("-inf"))     # per-row max
    for j in range(0, N, block_c):            # outer loop: K_j, V_j
        kj, vj = k[j:j + block_c], v[j:j + block_c]
        for i in range(0, N, block_r):        # inner loop: Q_i
            s = q[i:i + block_r] @ kj.T                       # S_ij [B_r, B_c]
            m_ij = s.max(dim=1, keepdim=True).values          # per-row max of the tile
            p = torch.exp(s - m_ij)                           # P~_ij
            l_ij = p.sum(dim=1, keepdim=True)
            m_new = torch.maximum(m[i:i + block_r], m_ij)
            l_new = torch.exp(m[i:i + block_r] - m_new) * l[i:i + block_r] + torch.exp(m_ij - m_new) * l_ij
            # line 12: rescale the previous output, then add this tile's contribution
            o[i:i + block_r] = (
                l[i:i + block_r] * torch.exp(m[i:i + block_r] - m_new) * o[i:i + block_r]
                + torch.exp(m_ij - m_new) * (p @ vj)
            ) / l_new
            l[i:i + block_r], m[i:i + block_r] = l_new, m_new
    return o


q, k, v = torch.randn(256, 64), torch.randn(256, 64), torch.randn(256, 64)
ref = torch.softmax(q @ k.T / math.sqrt(64), dim=-1) @ v
print(torch.allclose(flash_attention_reference(q, k, v), ref, atol=1e-5))  # True: the result is the same

# In practice, use PyTorch's built-in (FlashAttention-2 is selected automatically when conditions allow)
if torch.cuda.is_available():
    q = torch.randn(4, 16, 4096, 64, device="cuda", dtype=torch.float16)  # [batch, heads, seq, d]
    k, v = torch.randn_like(q), torch.randn_like(q)
    out = F.scaled_dot_product_attention(q, k, v, is_causal=True)  # do not pass attn_mask and is_causal together

    # force the FlashAttention implementation only
    with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
        out = F.scaled_dot_product_attention(q, k, v, is_causal=True)

    # dropout ignores model.eval(), so pass a value only during training
    training = False
    out = F.scaled_dot_product_attention(q, k, v, dropout_p=0.1 if training else 0.0, is_causal=True)

FAQ

Q. Is FlashAttention an approximation? Does the result change?
A.

It is not an approximation. It computes the same values as standard attention softmax(QK⊤)V\mathrm{softmax}(QK^\top)V by changing the order of computation and how memory is used (Theorem 1 of the paper). Because the order of floating-point additions changes, there are tiny differences in rounding error, but in the paper's GPT-2 training, both the perplexity and the training curves were the same as with existing implementations.

Q. Why is it faster even though computation increases?
A.

Because on GPUs, memory reads and writes are often slower than computation. In the paper's GPT-2 medium example, recomputation in the backward pass raised computation from 66.6 to 75.2 GFLOPs, but HBM reads and writes fell from 40.3 GB to 4.4 GB, and runtime went from 41.7 ms to 7.3 ms.

Q. How do I use FlashAttention in PyTorch?
A.

Use F.scaled_dot_product_attention, and FlashAttention-2 is selected automatically when conditions allow. In nn.MultiheadAttention, setting need_weights=False makes it use this function. To confirm that the FlashAttention implementation is used, call it inside torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION).

References

  1. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Ré, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness," NeurIPS, 2022.
  2. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  3. PyTorch Documentation, "torch.nn.functional.scaled_dot_product_attention."
  4. PyTorch Documentation, "torch.nn.attention.sdpa_kernel."