35 · FlashAttention — IO-Aware Exact Attention

推理基础设施 Dao et al. · 2022
arXiv:2205.14135

上一代的问题:Standard attention materializes the full N×N attention matrix in HBM — each forward pass reads and writes the huge matrix from slow GPU memory multiple times: write QKT to HBM, read it for softmax normalization, write the normalized matrix back, read it for the V multiplication. This causes O(N2) memory and bandwidth cost, making attention the dominant bottleneck for long sequences. Prior work focused on reducing FLOPs (sparse/linear attention) but ignored the IO bottleneck entirely.

这代改了什么:Tiling + Online Softmax — split Q, K, V into blocks that fit entirely in fast on-chip SRAM (~20 MB, 19 TB/s). Each block computes the attention scores and weighted sums on-chip without ever writing the full N×N matrix to HBM. A novel online softmax algorithm accumulates the correct normalization incrementally, block by block, using only two running statistics kept in registers. Only the final output O is written back to HBM.

效果:2–4× end-to-end training speedup (7.6× on the attention kernel alone). Memory scales linearly with sequence length instead of quadratically. Enabled 128K context in Llama 3, Multi-head Latent Attention (MLA), Grouped Query Attention (GQA), and virtually all modern long-context LLMs. Won the 2024 NeurIPS Test of Time Award.

一、核心背景:GPU Memory Hierarchy

The fundamental insight of FlashAttention is that the GPU has a heterogeneous memory hierarchy with vastly different bandwidths and capacities, and standard attention is entirely bottlenecked by the slowest layer.

Memory LevelSizeBandwidthSpeed Ratio
HBM (High Bandwidth Memory)40–80 GB (A100/80)~1.5–2.0 TB/s
L2 Cache~40 MB~4–8 TB/s~3–5×
SRAM (Shared Memory / Registers)~20 MB (192 KB per SM × 108 SMs)~19 TB/s~10–12×

Standard attention does the following dance with HBM:

  1. Write Q, K, V (read from HBM once — this is the only efficient step)
  2. Compute S = QKT and write the full N×N matrix to HBM
  3. Read S from HBM to apply softmax row-wise
  4. Write the N×N softmax output P back to HBM
  5. Read P from HBM to multiply with V
  6. Write the final output O to HBM

For d=64, n=1024, the attention matrix is 8 MB — it just barely fits in SRAM. But at n=8192 it's 512 MB, and at n=128K it's 128 GB, far exceeding even HBM capacity. This means standard attention fails entirely for long sequences on a single GPU, forcing approximations.

Key Insight: Before FlashAttention, nearly all research on efficient attention targeted FLOP reduction — sparse patterns (BigBird, Longformer), low-rank approximations (Linformer), or kernel approximation (Performer). These reduce compute but may sacrifice model quality. FlashAttention was the first to show that exact attention can be dramatically faster simply by targeting the IO bottleneck instead of FLOPs.

二、核心算法:Tiling + Online Softmax

The core innovation is decomposing the attention computation into blocks that fit in SRAM, combined with an online softmax that computes the correct normalization without ever seeing all values at once.

2.1 Forward Pass: Block Decomposition

The Q matrix is split into row blocks Qi (size Br × d). The K and V matrices are split into column blocks Kj, Vj (size Bc × d). The outer loop iterates over Q blocks; the inner loop over K/V blocks.

For each block iteration:

  1. Load Qi, Kj, Vj from HBM into SRAM
  2. Compute Sij = QiKjT on SRAM (one small matrix multiply)
  3. Apply the online softmax incrementally using the running statistics mi and di (stored in registers, not HBM)
  4. Compute the partial output contribution PijVj and accumulate into Oi
  5. When all K/V blocks for the current Qi are done, write the final Oi to HBM

2.2 Online Softmax: The Key Enabler

Standard softmax for a row x of length N:

m = max(x1, ..., xN),   d = ∑k=1N exk - m,   softmax(x)i = exi - m / d
Standard Softmax: requires the full row to compute max and sum

The problem: computing the correct normalization requires knowing the global max and sum, but we only see one block at a time. Online softmax solves this by maintaining two running statistics and correcting when a larger max is found:

mnew = max(mold, rowmax(Sij))
dnew = dold · emold - mnew + ∑ eSij - mnew
Oi = Oi · diag(emold - mnew) + PijVj
Online Softmax Update: correction factor when a larger max is observed

When mnew > mold (a larger maximum appears in the current block), all previously accumulated contributions are rescaled by the factor emold - mnew, which is < 1. This ensures the final output is bitwise identical to standard softmax. The two running statistics m and d are stored in registers, never written to HBM.

Why online softmax is the real innovation: Without it, FlashAttention would need either (a) two full passes over the data (one to compute all softmax denominators, another to compute the output), which would double HBM traffic, or (b) storing partial sums in HBM, which defeats the purpose. The online algorithm lets us get the correct answer in a single pass with O(B) registers per thread block.

三、IO Complexity Analysis

FlashAttention provides a rigorous IO complexity bound that proves its optimality.

Let M be the SRAM size. The block sizes are chosen as:

Br = Θ(M / d),   Bc = Θ(M / d)
Block sizes chosen to fit three matrices in SRAM: Qi (Br×d), Kj (Bc×d), Vj (Bc×d)

Total HBM accesses for FlashAttention:

HBM accesses = O(Nd + N2 d2 / M)
FlashAttention IO Complexity (forward + backward)

Compare with standard attention:

Standard: Ω(Nd + N2)   vs   FlashAttention: O(Nd + N2 d2 / M)
IO Complexity Comparison

For typical values (d=64, M≈100 KB per thread block):

Importantly, the paper proves that this bound is asymptotically optimal: no exact attention algorithm (that computes the same mathematical function) can achieve asymptotically fewer HBM accesses for all SRAM sizes M. The proof uses a reduction from the matrix multiplication IO lower bound.

四、Backward Pass: Recomputation Strategy

The backward pass of standard attention needs the full softmax output matrix P (N×N) to compute gradients. Storing P for backprop would require O(N2) HBM — exactly what FlashAttention avoids.

FlashAttention's solution: recompute on the fly. During the forward pass, only the softmax normalization statistics (m, d) are stored — two vectors of length N, total O(N) storage. During the backward pass:

  1. Load Q, K, V, O, and the statistics (m, d) from HBM
  2. Recompute each attention block in SRAM by loading Qi, Kj, Vj and computing Sij, Pij from scratch
  3. Compute the gradients dOi, dVj, dQi, dKj using the recomputed Pij
  4. Accumulate gradients and write to HBM
dVj = PT dO,   dP = dO VT,   dS = dP ⊗ (P - P ⊗ P · 1T)
dQi += dSij Kj,   dKj += dSijT Qi
Gradient computation in FlashAttention backward pass

The recomputation adds approximately 1/3 more FLOPs (recomputing the attention matrix in the backward pass) but saves an enormous amount of HBM bandwidth — not storing N×N can be the difference between fitting in VRAM and OOM. In practice, on GPU architectures, the extra compute is cheap because SRAM bandwidth is so much higher than HBM bandwidth.

五、Block-Sparse Extension

FlashAttention naturally extends to block-sparse attention, where a sparsity mask indicates which blocks of the attention matrix are non-zero and should be computed. The tiled structure means skipping a block is as simple as not loading Kj/Vj for that iteration.

HBM accesses (block-sparse) = O(Nd + N2 d2 s / M)
Block-sparse FlashAttention IO complexity, where s is the sparsity factor (proportion of non-zero blocks)

With a carefully designed sparsity pattern (e.g., local windows plus global tokens), block-sparse FlashAttention achieves 2–4× further speedup while maintaining better-than-chance accuracy on tasks where full attention is impractical. This was used to achieve 63.1% accuracy on Path-256 (64K tokens) — the first model to beat random chance on this benchmark.

六、Engineering Impact

Model / TaskSequence LengthSpeedupNotes
BERT-large training51215%Faster than MLPerf 1.1 record
GPT-2 training1,024vs HuggingFace / Megatron-LM baseline
Long Range Arena avg1,000–4,0002.4×Across all 5 tasks
Attention kernel onlyvariable7.6×Measured on A100
Path-X (first Transformer above chance)16,38461.4% accuracy
Path-25665,53663.1% accuracy (block-sparse)

The impact goes beyond raw speed. FlashAttention's linear memory scaling means that training with 128K context (and more recently, 1M+ context) is feasible on a single node. Every major LLM post-2022 uses some variant of FlashAttention or its descendants.

# Conceptual FlashAttention forward pass (simplified)
def flashattention(Q, K, V, Br, Bc):
    # Q: (n, d), K/V: (n, d)
    # Br, Bc: block sizes for Q and K/V
    n = Q.shape[0]
    O = zeros(n, d)
    m = full(n, -inf)  # running max per row
    d = zeros(n)        # running sum per row

    for i in range(0, n, Br):
        Qi = Q[i:i+Br]
        Oi = O[i:i+Br]; mi = m[i:i+Br]; di = d[i:i+Br]

        for j in range(0, n, Bc):
            Kj = K[j:j+Bc]; Vj = V[j:j+Bc]
            Sij = Qi @ Kj.T                    # (Br, Bc) on SRAM
            mij = max(Sij, axis=1)             # row max of this block
            mi_new = max(mi, mij)              # update running max
            Pij = exp(Sij - mi_new[:, None])   # safe softmax numerator
            di_new = di * exp(mi - mi_new) + sum(Pij, axis=1)
            # Rescale accumulated output and add new contribution
            Oi = Oi * exp(mi - mi_new)[:, None] + Pij @ Vj
            mi = mi_new; di = di_new

        O[i:i+Br] = Oi / di[:, None]           # final normalization
        m[i:i+Br] = mi; d[i:i+Br] = di

    return O

七、上下游关联

上一篇(问题来源):Before FlashAttention, the attention efficiency literature was dominated by sparse attention (Child et al. 2019, BigBird, Longformer, ETC) and linear attention (Katharopoulos et al. 2020, Performer, Linformer). These works focused on reducing the FLOP count of attention by approximating the full softmax attention with cheaper alternatives. However, none of them addressed the memory access pattern — on modern GPUs, the standard attention implementation is already compute-bound for small N but memory-bound for large N, and reducing FLOPs does not reduce HBM accesses for the attention matrix that is still materialized.

下一篇(影响扩散):

被谁采用:Every major transformer library and model since 2023:

引用/采用场景:

八、个人思考

FlashAttention is, in retrospect, one of those ideas that feels obvious once explained. The fundamental problem was well-known: attention is O(N2) in both compute and memory, and GPUs have a fast but tiny on-chip memory. The entire research community was chasing FLOP reduction while leaving the real bottleneck — HBM bandwidth — untouched.

The lesson is profound for ML systems research: optimize for the real bottleneck, not the theoretical one. On modern hardware, memory bandwidth, not FLOPs, is almost always the binding constraint. This is the same principle that made cuBLAS successful (tiling matrix multiplies for cache), the same principle behind operator fusion in XLA/TorchDynamo, and the same principle behind flash attention for other primitives (FlashFFTConv, FlashDecoding).

Three things make FlashAttention a landmark paper:

  1. Mathematical elegance: The online softmax is a beautiful algorithmic trick — it reuses the running max/sum and corrects with a rescaling factor, giving the exact same result as global softmax. No approximation, no quality loss.
  2. Engineering craftsmanship: The actual CUDA implementation is deeply tuned for GPU architecture — warps, shared memory banks, register allocation, tile quantization. The paper's contribution is as much in the engineering as in the math.
  3. Community multiplier: FlashAttention didn't just speed up one model; it became infrastructure. Every LLM built since 2023 builds on it. The IO-aware tiling pattern has been extended to cross-attention, sparse attention, multi-GPU attention, and even non-attention primitives.

In the broader arc of transformer research, FlashAttention sits alongside the original transformer paper and the GPT-2 scaling paper as a foundational infrastructure contribution. It didn't invent a new architecture or a new capability; it removed a bottleneck that was silently limiting the entire field. The NeurIPS 2024 Test of Time Award is well-deserved.