AI Logic

Attention Mechanisms

FlashAttention-2

Updated:

FlashAttention-2 architecture. Left: the forward pass (read a block of Q from HBM into SRAM; in the inner loop, read blocks of K and V, compute the tile matrix product, update the max and sum, and accumulate into the output; finally divide by the sum only once and write the output O and the logsumexp L back to HBM). Right: how the attention matrix is divided, with separate thread blocks handling each row block in the forward pass and each column block in the backward pass

What is FlashAttention-2?

FlashAttention-2 is a method that reworks how FlashAttention partitions and parallelizes its computation to compute the same exact attention about twice as fast. It was proposed in 2023 by Tri Dao of Princeton University and Stanford University in the paper "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning." PyTorch's F.scaled_dot_product_attention also uses this implementation when the conditions are met.

FlashAttention reduced reads and writes to the slow memory (HBM) by splitting the attention matrix into small tiles and computing them in the GPU's fast on-chip memory (SRAM). Even so, it reached only 25 to 40% of the theoretical maximum compute throughput of an A100 GPU. The paper attributes this to how work is partitioned inside the GPU, and changes three things:

ChangeFlashAttentionFlashAttention-2
Non-matmul operationsRescales the output by the sum ℓ\ell for every tileDivides only once at the end
Parallelization dimensionsBatch and heads onlySequence length in addition to batch and heads
Work split within a thread blockSplits K,VK, V across 4 warps (GPU execution units)Splits QQ across 4 warps

As with FlashAttention, the result is identical to standard attention softmax(QK⊤)V\mathrm{softmax}(QK^\top)V. No approximation is involved.

In a kitchen analogy, FlashAttention was the trick of "processing ingredients all at once on the countertop at hand," while FlashAttention-2 is the trick of "reorganizing the cooks' division of labor so that each one can finish a separate dish from start to end, eliminating time spent waiting on hand-offs."

In the figure at the top of the article, the left shows the forward pass and the right shows how the attention matrix is divided among GPU thread blocks.

Theory: three changes from FlashAttention

FlashAttention-2 changes three things: the computation steps, the parallelization, and the warp partitioning (Section 3 of the paper).

1. Reducing non-matmul operations (Algorithm 1, forward pass)

Suppose Q,K,V∈RN×dQ, K, V \in \mathbb{R}^{N \times d} are in HBM. Split QQ into TrT_r blocks of BrB_r rows and K,VK, V into TcT_c blocks of BcB_c rows, and compute as follows:

  1. Outer loop: Load the blocks QiQ_i of QQ into SRAM one at a time, and initialize Oi=0O_i = 0, ℓi=0\ell_i = 0, mi=−∞m_i = -\infty in SRAM.
  2. Inner loop: Load the blocks Kj,VjK_j, V_j of K,VK, V into SRAM one at a time.
  3. Tile matrix product: Compute Si(j)=QiKj⊤S_i^{(j)} = Q_i K_j^\top (Br×BcB_r \times B_c).
  4. Update the max and sum: Compute the row-wise max mi(j)m_i^{(j)}, P~i(j)=exp⁡(Si(j)−mi(j))\tilde{P}_i^{(j)} = \exp(S_i^{(j)} - m_i^{(j)}), and the sum ℓi(j)\ell_i^{(j)}.
  5. Update the output: Add P~i(j)Vj\tilde{P}_i^{(j)} V_j to OiO_i. At this point, do not divide by the sum ℓ\ell. Only correct the scale for the change in the max.
  6. Divide only once at the end: After the inner loop finishes, divide OiO_i by ℓi\ell_i, compute Li=mi+log⁡ℓiL_i = m_i + \log \ell_i (the logsumexp), and write OiO_i and LiL_i to HBM.

Steps 5 and 6 are the following equations (lines 10 and 12 of Algorithm 1).

Oi(j)=diag(emi(j−1)−mi(j))−1Oi(j−1)+P~i(j)Vj,Oi=diag(ℓi(Tc))−1Oi(Tc)O_i^{(j)} = \mathrm{diag}\bigl(e^{m_i^{(j-1)} - m_i^{(j)}}\bigr)^{-1} O_i^{(j-1)} + \tilde{P}_i^{(j)} V_j, \qquad O_i = \mathrm{diag}\bigl(\ell_i^{(T_c)}\bigr)^{-1} O_i^{(T_c)}

FlashAttention rescaled the output by ℓ\ell for every tile. Division is a non-matmul operation, much slower on a GPU than matrix multiplication. Dividing only once at the end reduces how often it is done. In addition, the statistics saved for the backward pass were reduced from two, the max mm and the sum ℓ\ell, to one, the logsumexp LL. In the backward pass, the softmax can be recomputed as P=exp⁡(S−L)P = \exp(S - L).

Causal masking: Because the computation is split into blocks, blocks whose column indices are all larger than their row indices (about half of them for long sequences) are skipped entirely. Only one block per row, the one on the diagonal, needs the mask applied. According to the paper, this is 1.7 to 1.8 times faster than attention without a mask.

2. Parallelizing along the sequence dimension too

FlashAttention assigned one head to one thread block (a unit of work running on a GPU streaming multiprocessor, or SM) and parallelized only over batch and heads. An A100 has 108 SMs, so with 80 or more batch × head combinations the GPU is almost fully used, but with long sequences and small batches, some SMs sit idle.

Because FlashAttention-2 makes the outer loop run over row blocks of QQ, row blocks are independent of each other, and each can be assigned to a separate thread block (Figure 2 left of the paper). In the backward pass, each column block (Kj,VjK_j, V_j) is assigned to a thread block, and only the update of dQdQ, which is shared across blocks, is combined with atomic adds (Figure 2 right).

3. Changing the warp partitioning

Within one thread block, 4 to 8 warps (groups of 32 threads) split the work. FlashAttention split K,VK, V across warps and shared QQ among all warps (what the paper calls the "split-K" scheme). In this scheme, after each warp computes part of QK⊤QK^\top and its product with part of VV, the results must be written to shared memory, synchronized, and summed.

FlashAttention-2 does the opposite: it splits QQ across warps and shares K,VK, V among all warps (Figure 3 of the paper). Each warp can compute the output for its own rows all the way to the end, so no communication between warps is needed.

Why it is faster

FlashAttention-2 is faster because it spends a larger share of time on matrix multiplication, which GPUs are good at, and reduces waiting.

  • Non-matmul operations are 16 times more expensive: The A100's theoretical maximum throughput is 312 TFLOPs/s for half-precision (FP16, BF16) matrix multiplication and 19.5 TFLOPs/s for non-matmul single-precision (FP32) operations. One non-matmul operation therefore costs as much time as 16 matmul operations. Simply moving the division out of the loop helps.
  • Less idle GPU capacity: Parallelizing along the sequence dimension too makes it possible to distribute work to many SMs even with few batches or heads. Since long sequences often go with small batches, this effect is large.
  • Fewer shared memory reads and writes: There is no longer any need to pass intermediate results between warps, and the synchronization waits disappear as well.

According to the paper, the loop order with the outer loop over row blocks of QQ and the parallelization along the sequence dimension were first tried by Tillet in the Triton implementation of FlashAttention. FlashAttention-2 brought them into the CUDA implementation and combined them with the warp partitioning and other changes.

Block sizes are usually chosen from {64,128}×{64,128}\{64, 128\} \times \{64, 128\} according to the head dimension dd and the size of the GPU's shared memory. Larger blocks reduce shared memory reads and writes, but if registers or shared memory run short, the kernel can become slower or fail to run.

Experimental results

Attention-only speed: Measured on an A100 80GB with sequence lengths from 512 to 16K and the batch size set so that the total number of tokens is 16K (hidden size 2048, head dimension 64, no mask, forward plus backward; unit is TFLOPs/s; Figure 4a of the paper).

Implementation5122K8K16K
Standard PyTorch implementation364346Out of memory
FlashAttention91104110110
FlashAttention-2132162175176

In the paper's summary, FlashAttention-2 is 1.7 to 3.0 times faster than FlashAttention, 1.3 to 2.5 times faster than the Triton version of FlashAttention, and 3 to 10 times faster than the standard implementation, reaching up to 230 TFLOPs/s in attention computation (73% of the A100's theoretical maximum). Running the same implementation on an H100 gave up to 335 TFLOPs/s, even without using the H100's new instructions.

End-to-end model training speed: Per-GPU throughput when training GPT-style models on 8 A100 80GB GPUs (TFLOPs/s; Table 1 of the paper).

ModelWithout FlashAttentionFlashAttentionFlashAttention-2
1.3B, context length 2K142189196
1.3B, context length 8K72170220
2.7B, context length 2K149189205
2.7B, context length 8K80175225

The longer the context, the larger the gap: for 2.7B at 8K, it is 2.8 times faster than without FlashAttention and 1.3 times faster than FlashAttention, reaching up to 225 TFLOPs/s (72% model FLOPs utilization). The paper notes that because FlashAttention-2 is twice as fast as FlashAttention, a 16K-context model can be trained for the same cost as an 8K-context model.

Practical considerations

FlashAttention-2 is a way of computing that returns the same values as standard attention, so it can be swapped in without changing the model definition.

Even with FlashAttention-2, the amount of computation is proportional to the square of the sequence length NN (O(N2d)O(N^2 d)). What improves is the efficiency of GPU usage; doubling the sequence length still roughly quadruples the computation time. Also, the speed numbers were measured under specific conditions, such as A100 or H100 GPUs, half-precision data types, and particular head dimensions. If the conditions are not met, the FlashAttention-2 implementation may not be used.

When using it, keep the following points in mind:

  • Using the PyTorch built-in is easiest: F.scaled_dot_product_attention automatically selects FlashAttention-2 when the conditions are met. To make sure it is used, call it inside torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION). If the conditions are not met, this raises an error, so it lets you confirm that the implementation is in use.
  • Use half precision: The FlashAttention implementation assumes FP16 or BF16 inputs. With single precision (FP32), a different implementation is used.
  • Turn off dropout yourself: F.scaled_dot_product_attention does not look at model.eval(), so pass dropout_p=0.0 at inference time.
  • GQA and MQA work as is: The paper also includes a way to compute grouped-query attention and multi-query attention without duplicating the key and value heads, using only a mapping between head indices.
  • Attention weights cannot be retrieved: Since the N×NN \times N weights are not stored, compute them separately if you want to visualize them.

The paper itself lists as future work that block sizes are tuned by hand for each head dimension, and that it does not yet use the H100's new features (TMA, 4th-generation Tensor Cores, FP8).

Comparison with other methods

Implementations that compute standard attention can be compared by "what they optimize." All of them produce the same values.

ImplementationN×NN \times N matrixParallelization dimensionsNormalization (dividing by ℓ\ell)Speed on A100 (Figure 4a of the paper)
Standard implementation (PyTorch)Written to HBM and read back—Once, all together36 to 46 TFLOPs/s, out of memory at 16K
FlashAttention (Dao et al., 2022)Not materialized (computed tile by tile in SRAM)Batch, headsRescaled for every tile91 to 110 TFLOPs/s
FlashAttention-2 (Dao, 2023)Not materialized (computed tile by tile in SRAM)Batch, heads, sequenceOnce at the end132 to 176 TFLOPs/s

The goal differs from that of approximate methods that reduce the number of pairs computed (sparse attention, Linformer, Performer, and others). FlashAttention-2 speeds things up without changing the answer, while approximate methods change the answer slightly to reduce the amount of computation itself. The two can also be combined, and the paper lists combining it with computational changes such as block-sparsity as a future direction.

Rough guidelines for choosing:

  • In most cases: Using PyTorch's F.scaled_dot_product_attention gives you FlashAttention-2 whenever the conditions are met.
  • Very long sequences where the N2N^2 computation time itself is the problem: Consider methods that reduce the number of pairs computed, or Ring Attention, which splits the sequence across multiple GPUs.
  • KV cache memory is the problem during inference: Combine with PagedAttention, which improves how the cache is laid out rather than the attention computation, or with GQA, which shrinks the cache.

PyTorch example

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


def flash_attention_2_reference(q, k, v, block_r=64, block_c=64):
    """A reference implementation of the idea of Algorithm 1 of the paper in PyTorch (not fast; for checking the mechanism).
    q, k, v: [N, d]. The outer loop is over row blocks of Q (they are independent, so a GPU computes them in parallel)"""
    N, d = q.shape
    q = q / d ** 0.5
    out = torch.empty(N, d)
    lse = torch.empty(N)                               # logsumexp L (saved for the backward pass)
    for i in range(0, N, block_r):                     # outer loop: Q_i
        qi = q[i:i + block_r]
        o = torch.zeros(qi.shape[0], d)                # output without rescaling (not divided by ℓ)
        l = torch.zeros(qi.shape[0], 1)
        m = torch.full((qi.shape[0], 1), float("-inf"))
        for j in range(0, N, block_c):                 # inner loop: K_j, V_j
            s = qi @ k[j:j + block_c].T                # S_i^(j)
            m_new = torch.maximum(m, s.max(dim=1, keepdim=True).values)
            p = torch.exp(s - m_new)                   # P~
            scale = torch.exp(m - m_new)               # correct only for the change in the max
            l = scale * l + p.sum(dim=1, keepdim=True)
            o = scale * o + p @ v[j:j + block_c]       # line 10: do not divide by ℓ
            m = m_new
        out[i:i + block_r] = o / l                     # line 12: divide only once at the end
        lse[i:i + block_r] = (m + torch.log(l)).squeeze(1)  # line 13
    return out, lse


q, k, v = torch.randn(256, 64), torch.randn(256, 64), torch.randn(256, 64)
ref = torch.softmax(q @ k.T / 64 ** 0.5, dim=-1) @ v
o, _ = flash_attention_2_reference(q, k, v)
print(torch.allclose(o, ref, atol=1e-5))  # True: the results are the same

# in practice, use the PyTorch built-in (FlashAttention-2 is selected when the conditions are met)
if torch.cuda.is_available():
    q = torch.randn(1, 16, 8192, 128, device="cuda", dtype=torch.bfloat16)  # [batch, heads, seq, d]; use half precision
    k, v = torch.randn_like(q), torch.randn_like(q)
    with sdpa_kernel(SDPBackend.FLASH_ATTENTION):     # use only the FlashAttention implementation (error if unavailable)
        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. Do FlashAttention and FlashAttention-2 give different results?
A.

No. Both compute the same values as standard attention softmax(QK⊤)V\mathrm{softmax}(QK^\top)V. What differs is the order of computation and how work is divided inside the GPU. Because the order of additions changes, there are tiny differences in rounding error.

Q. How do I use FlashAttention-2?
A.

In PyTorch, calling F.scaled_dot_product_attention automatically selects the FlashAttention-2 implementation when conditions such as the GPU, data type (FP16, BF16), and head dimension are met. Calling it inside torch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION) forces only this implementation and raises an error when it cannot be used.

Q. Is it faster even with large batches?
A.

Yes, but the gap is largest when sequences are long and batches or heads are few. That is because parallelizing along the sequence dimension is designed for situations where the number of batch × heads is small and GPU SMs would otherwise sit idle. Reducing non-matmul operations and changing the warp partitioning help regardless of batch size.

References

  1. T. Dao, "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning," arXiv:2307.08691, 2023.
  2. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Ré, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness," NeurIPS, 2022.
  3. PyTorch Documentation, "torch.nn.functional.scaled_dot_product_attention."
  4. PyTorch Documentation, "torch.nn.attention.sdpa_kernel."