AI State of the Art
SOTA/Advanced Attention Mechanisms/19 min
Section 75

Flash Attention 2

Listen as a podcast →

From Flash Attention 1 to Flash Attention 2

Flash Attention 1 had solved the fundamental problem: making attention linear in memory through tiling (block-by-block computation). But in terms of raw GPU utilization, there was still a lot of performance left on the table: per the paper, Flash Attention 1 reached only 25-40% of the GPU's theoretical compute throughput, most compute units remained idle.

Flash Attention 2, published by Tri Dao in 2023, tackles precisely this problem. The result: 50-73% of theoretical throughput on A100, by optimizing parallelism and work distribution within the GPU.

FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning

Key optimizations

Reducing non-matmul operations

To understand this optimization, you need to grasp a crucial point about modern GPUs. GPUs like the A100 or H100 have Tensor Cores, specialized units for matrix multiplications (matmul for short). On an A100 they deliver 312 tera-operations per second, versus 19.5 for the general-purpose cores (called CUDA cores, after NVIDIA's programming platform): a factor of 16 (312 ÷ 19.5). All other operations (additions, scalar multiplications, comparisons) run on those much slower classic cores.

Tensor Cores and matmul

Imagine a 16-lane highway (the Tensor Cores) reserved for matrix multiplications, and a single-lane country road (the CUDA cores) for everything else. The highway throughput is enormous, but if your computation constantly alternates between the highway and the country road, you waste a ton of time on exits and entrances.

Flash Attention 1 contained rescaling operations (online softmax correction) interleaved with matmuls. These back-and-forth trips between Tensor Cores and CUDA cores wasted time. Flash Attention 2 reorganizes the computation to group rescaling operations and minimize these interruptions in the inner loop.

Diagram of block-wise attention computation. Q is stored in HBM, as are the blocks K(1) transposed and K(2) transposed. Computed in SRAM are S(1) equals Q times K(1) transposed and S(2) equals Q times K(2) transposed, then A(1) equals exponential of S(1) and A(2) equals exponential of S(2), never materialized in HBM. The sums l(1) and l(2) accumulate the exponentials. The output O(1) equals A(1) over l(1) times V(1), and O(2) equals l(1) over l(2) times O(1) plus A(2) over l(2) times V(2), with an arrow annotated rescaling to correct denominator.
A recap of the block-by-block computation. The arrow on the right points at the rescaling: with each new block, the partial output has to be corrected by the ratio of the denominators l. These divisions do not run on Tensor Cores, and Flash Attention 2 groups them and defers them to the end instead of doing them at every block.Source : FlashAttention-2 blog post (Tri Dao, Princeton NLP)

Parallelism on the sequence dimension

In Flash Attention 1, the outer loop iterated over K/V blocks and the inner loop over Q blocks. This is natural, but it limits parallelism when the number of attention heads isn't enough to keep all the GPU's streaming multiprocessors busy.

Flash Attention 2 reverses the loops: the outer loop iterates over Q blocks, the inner over K/V. This seemingly minor change allows parallelizing on the sequence dimension in addition to the head dimension. Result: the GPU is better saturated, especially for models with few attention heads or long sequences.

Two 5 by 5 grids representing the attention matrix with causal masking. On the left, forward pass: each row of the grid is filled with a different colour and assigned to a worker, from worker 1 at the top to worker 5 at the bottom, with only the cells left of the diagonal coloured. On the right, backward pass: the same split but by columns, from worker 1 on the left to worker 5 on the right.
How Flash Attention 2 splits the work across the GPU's compute units. Each worker takes a strip of the attention matrix along the sequence dimension: by rows in the forward pass, by columns in the backward pass. The empty triangle in the top right is the blocks masked by causality, which nobody needs to compute.Source : FlashAttention-2 paper (figure 2), via Aman's AI Journal

Work partitioning between warps

A GPU threadblock contains several warps (groups of 32 threads that execute in parallel). How work is distributed between warps has a direct impact on performance.

Warp partitioning

Flash Attention 1 partitioned K and V across warps, which required costly synchronization after each block (warps had to combine their results). Flash Attention 2 partitions Q across warps, allowing each warp to work independently on different rows of the output. Result: no more intra-block synchronization needed, each warp advances at its own pace.

Two-panel comparison. On the left, FlashAttention: the Q block is labelled accessed by all warps, while K transposed is split horizontally into warp 1, warp 2, warp 3, warp 4 and V is split vertically into warp 1 to warp 4, both labelled split across different warps. On the right, FlashAttention-2: Q is the one split into warp 1 to warp 4, while K transposed and V are single blocks labelled warp 1-4, accessed by all warps.
The change of partitioning between the two versions. On the left, Flash Attention 1 splits K and V across warps: each warp only holds a fragment of the result and they have to be recombined. On the right, Flash Attention 2 splits Q instead: each warp produces complete rows of the output and no longer has to wait for the others.Source : FlashAttention-2 paper (figure 3), via Aman's AI Journal

Performance results

Speedup compared to Flash Attention 1

GPUSpeedup FA2 vs FA1% of theoretical throughput reached
A100 (FP16)~2x50-73%
A100 (BF16)~2x50-73%

Comparison with standard attention

Orders of magnitude measured in the paper on A100, in TFLOP/s (tera floating-point operations per second, the GPU's "speedometer"):

  • Standard PyTorch attention: a few dozen TFLOP/s
  • Flash Attention 1: ~120 TFLOP/s
  • Flash Attention 2: up to ~225 TFLOP/s
  • Theoretical A100: 312 TFLOP/s (FP16)

Flash Attention 2 is several times faster than standard attention and reaches up to 73% of the hardware's theoretical maximum (225 ÷ 312).

Scaling with sequence length

An important point: Flash Attention 2 maintains near-constant throughput in TFLOP/s even for very long sequences, thanks to efficient tiling. Where standard attention explodes in memory and time, FA2 stays stable.

Practical impact on training

The paper measures up to a 1.3x end-to-end speedup when training GPT-style models compared to Flash Attention 1, roughly 72% of each A100's theoretical power used across the whole training run, not just on the attention. This isn't just an academic optimization: it translates directly into GPU cost savings and the ability to iterate faster on experiments.

Optimized causal masking support

Skipping masked blocks

In causal attention (each token only sees previous tokens), roughly half the blocks in the attention matrix are entirely masked (future tokens). Flash Attention 2 detects these blocks and skips them completely: half as many blocks to compute, hence an additional ~2x speedup for causal attention compared to bidirectional attention.

Custom masks

Version 2 also supports custom masking patterns (like sliding window attention) via user-defined masking functions, offering significant architectural flexibility.

Multi-GPU and variable-length support

Variable-length sequences

In practice, batches contain sequences of different lengths. Flash Attention 2 handles this efficiently via a packing (varlen) format: sequences are concatenated end-to-end and start/end indices indicate the boundaries. No more need for costly padding.

Variable head dimensions

Support for non-standard head dimensions (not just 64 or 128), giving more freedom in model architectural design.

Ecosystem integration

PyTorch SDPA

SDPA (scaled dot-product attention, PyTorch's standard attention function): Flash Attention 2 is the default engine behind torch.nn.functional.scaled_dot_product_attention on compatible GPUs. In practice, if you're using a recent version of PyTorch on an Ampere or newer GPU, you're already benefiting from FA2 transparently.

Hugging Face

Hugging Face Transformers models automatically enable Flash Attention 2 when the package is installed, via the argument attn_implementation="flash_attention_2". Adoption is virtually transparent for the user.

GPU compatibility

Flash Attention 2 requires recent NVIDIA GPUs (compute capability 8.0 or higher, NVIDIA's chip-generation index): Ampere (A100, A10G, RTX 3090/4090) or Hopper (H100). Older GPUs (V100, T4) cannot use FA2's optimizations, although FA1 remains available for them.

Improved backward pass

Training is a forward pass followed by a backward pass. Flash Attention 2 applies the same optimization principles to the backward:

  • Increased parallelism on the sequence dimension
  • Better warp partitioning
  • Optimized softmax rematerialization (recompute rather than store)

The backward pass reaches up to 63% of theoretical throughput per the paper, markedly better than Flash Attention 1. This is crucial since the backward pass is often the training bottleneck.

Impact and adoption

Flash Attention 2 has become a foundational and nearly universal component in training and inference of modern LLMs. Its massive adoption has contributed to extending context windows (from 2K to 128K+ tokens), significantly reducing training costs, and generally accelerating research in NLP (Natural Language Processing).

The hardware-aware optimizations it embodies (designing algorithms based on specific hardware capabilities) have become an essential design paradigm in deep learning.

Toward Flash Attention 3

Flash Attention 2 laid the groundwork for the optimizations exploited by Flash Attention 3 on Hopper GPUs (H100/H200), which introduce new hardware features like asynchronous pipelining and FP8 support. These advances are detailed in the next section.

Check your understanding0 / 4

1. Flash Attention 1 had already fixed the memory problem. What problem remained, which Flash Attention 2 attacks?

2. Why are non-matmul operations, such as the rescaling divisions, so expensive on a modern GPU?

3. Flash Attention 2 reverses the loops: the outer loop now walks the blocks of Q instead of K/V. What does that buy?

4. Why does Flash Attention 2 partition Q across warps, rather than K and V as version 1 did?