Training Optimization: Attention Optimizations

By Ludovico Bessi, Senior ML Engineer at Google · Updated

FlashAttention v1, v2 and v3: making exact attention fast by respecting the memory hierarchy.

The Problem: Attention Is Memory-Bound

Standard attention computes the full score matrix S = QKᵀ, applies softmax to get P, then computes O = PV. For a sequence of length n, S and P are n × n matrices per head. A naive implementation writes S to GPU high-bandwidth memory (HBM), reads it back for the softmax, writes P, and reads P again for the final product.

At n = 8,192 with 32 heads, each of those matrices is about 2 billion elements per layer. The GPU spends most of its time moving them in and out of HBM rather than doing math. Memory use is O(n²), which also caps the sequence length you can train on.

The key observation behind FlashAttention: GPUs have a small amount of very fast on-chip memory (SRAM, tens of megabytes in total across the chip versus 80 GB of HBM, with roughly an order of magnitude more bandwidth). If attention can be computed in small blocks that fit in SRAM, the n × n matrices never need to touch HBM at all.

FlashAttention (v1): Tiling and Online Softmax

FlashAttention (Dao et al., 2022) computes exact attention — the same result as the naive version, not an approximation — with far fewer HBM reads and writes.

Tiling

Split Q, K and V into blocks. Load a block of queries into SRAM, then stream blocks of keys and values through it, computing that block's contribution to the output. The full score matrix is never materialized.

Online softmax

The obstacle is softmax: normalizing a row requires the maximum and the sum over the whole row, but tiling only sees one block at a time. FlashAttention keeps a running maximum m and running sum ℓ per query row. When a new block arrives with a larger maximum, the previously accumulated output and sum are rescaled by exp(m_old − m_new). After the last block, dividing by ℓ gives exactly the right answer.

for each block of K, V:
    S_blk = Q_blk · K_blkᵀ / √d
    m_new = max(m, rowmax(S_blk))
    P_blk = exp(S_blk − m_new)
    ℓ     = ℓ · exp(m − m_new) + rowsum(P_blk)
    O     = O · exp(m − m_new) + P_blk · V_blk
    m     = m_new
O = O / ℓ

Recomputation in the backward pass

The backward pass normally needs P. Instead of storing it (O(n²) memory), FlashAttention stores only the output and the softmax statistics (O(n)), and recomputes the blocks of P on the fly during backpropagation. This trades a few extra FLOPs for a large saving in memory traffic, and it is still faster overall because the computation is memory-bound.

Results

Attention memory drops from quadratic to linear in sequence length, and wall-clock speed improves several-fold over standard PyTorch attention at long sequences. The linear memory is what made training on much longer contexts practical.

FlashAttention-2: Better Work Partitioning

FlashAttention v1 was IO-efficient but reached only a modest fraction of the GPU's peak FLOPs. FlashAttention-2 (Dao, 2023) reorganized the work to fix that, for about a 2× speedup over FlashAttention:

  • Fewer non-matmul FLOPs. GPUs execute matrix multiplications on Tensor Cores, which are an order of magnitude faster than general arithmetic. FA2 delays the rescaling by ℓ to the very end and avoids redundant operations, keeping more of the time in matmuls.
  • Parallelism over sequence length. v1 parallelized over batch and heads. With long sequences and small batches, that leaves many streaming multiprocessors idle. FA2 also parallelizes over blocks of the query sequence.
  • Better split across warps. Within a thread block, v1 split K and V across warps, which required the warps to exchange partial results through shared memory. FA2 splits Q across warps instead, so each warp works independently.

FA2 reached 50–73% of the A100's theoretical peak FLOPs, close to the efficiency of a plain matrix multiplication.

FlashAttention-3: Exploiting Hopper

The H100 (Hopper) GPU added hardware features that FA2 did not use, so FA2 reached only around 35% of H100 peak. FlashAttention-3 (Shah et al., 2024) was designed around them:

  • Asynchrony and warp specialization. Hopper's Tensor Memory Accelerator (TMA) moves data between HBM and shared memory asynchronously. FA3 dedicates some warps to loading data (producers) and others to computing (consumers), so memory transfer and math overlap.
  • Overlapping matmul and softmax. Softmax's exponentials run on slower special-function units. FA3 pipelines them so that while one block's softmax runs, the Tensor Cores are already multiplying the next block ("ping-pong" scheduling across warp groups, plus overlap within a warp group).
  • FP8 support. Hopper Tensor Cores double throughput in FP8. FA3 supports FP8 attention and uses block quantization and incoherent processing (multiplying by a random orthogonal matrix to spread out outliers) to keep the accuracy loss small.

FA3 reaches up to 740 TFLOPS in FP16 (75% utilization of the H100) and close to 1.2 PFLOPS in FP8.

Why This Matters for Inference

FlashAttention was built for training, but its ideas now run inside every serving engine:

  • Prefill is just like a training forward pass: many query tokens attending to many keys. FlashAttention kernels apply directly.
  • Decode is different: one query token per request attending to a long KV cache. With a single query, there is little parallelism inside each head. Flash-Decoding splits the keys into chunks processed in parallel, then combines the partial results with the same online-softmax rescaling. This keeps the GPU busy at long contexts and small batches.
  • Paged KV caches need attention kernels that read keys and values from non-contiguous blocks. Engines like vLLM and FlashInfer combine FlashAttention-style tiling with paged memory; see Attention Optimizations for inference.

For a shorter overview, see Flash Attention Explained.

Key Takeaways

  1. Naive attention is slow because it moves n × n matrices through HBM, not because of FLOPs.
  2. FlashAttention tiles Q, K, V into SRAM and uses an online softmax, computing exact attention with linear memory.
  3. FlashAttention-2 roughly doubles speed by maximizing Tensor Core time and parallelizing over sequence length.
  4. FlashAttention-3 uses Hopper's asynchronous data movement, overlaps softmax with matmul, and adds FP8.
  5. The same ideas power prefill kernels and, via Flash-Decoding, long-context decode.