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

Tri Dao · arXiv · 2023-7-17

- **Problem** FlashAttention is exact and memory-efficient, but it reaches only 25-40% of the theoretical maximum FLOPs/s, because its work is poorly partitioned across thread blocks and warps.
- **Method** FlashAttention-2 cuts non-matmul work in the online softmax update, parallelizes over sequence length as well as batch and heads, and splits Q rather than K and V across warps to avoid split-K communication.
- **Results** Reached up to 230 TFLOPs/s on A100 in attention benchmarks, which is 73% of the theoretical maximum, and up to 225 TFLOPs/s per A100 in GPT-style training.

## Why FlashAttention falls short of matrix-multiply speed

Attention cost grows with the square of the sequence length in both runtime and memory, which makes long contexts expensive. FlashAttention addresses this by tiling the computation and using online softmax, so the large N×N matrices never have to be written to HBM, and memory falls from quadratic to linear in sequence length. Even so, it reaches only 25-40% of the theoretical maximum FLOPs/s, well below what optimized matrix multiplication achieves.

On A100, the forward pass of FlashAttention reaches 30-50% of the theoretical maximum FLOPs/s and the backward pass 25-35%, while optimized GEMM can reach 80-90% of device throughput. The authors trace this gap to how work is divided: some configurations leave the GPU under-occupied, and others read and write shared memory more than necessary.

## Trimming the rescaling in the online softmax update

On A100, FP16/BF16 matmul on Tensor Cores peaks at 312 TFLOPs/s, while non-matmul FP32 work peaks at 19.5 TFLOPs/s, so each non-matmul FLOP costs about 16 times a matmul FLOP. Non-matmul FLOPs make up only a small share of the total, but their cost is high enough that FlashAttention-2 removes the avoidable ones.

The standard online update rescales the whole accumulated output each time a new block of keys arrives. FlashAttention-2 keeps an unscaled output and carries the running statistics separately. Only at the end of the loop is the unscaled output divided by the final running sum, so the per-block rescaling of the full output disappears.

For the backward pass, the method stores one value per row, the logsumexp \\\\(L\_i = m\_i^{(T\_c)} + \\\\log(\\\\ell\_i^{(T\_c)})\\\\), in place of the separate maximum and sum. With \\\\(L\\\\) saved, the backward pass recomputes each block of \\\\(P\\\\) as \\\\(\\\\exp(S\_{ij} - L\_i)\\\\) from the stored scores.

The authors state that the output is still softmax(QKᵀ)V with no approximation, using O(N²d) FLOPs and O(N) memory beyond inputs and outputs, and they say the proof is nearly the same as FlashAttention's, which they omit.

## Skipping masked blocks under a causal mask

For auto-regressive language modeling, every entry with column index above the row index is set to negative infinity. Blocks lying wholly above the diagonal are skipped, which for large sequence lengths is approximately half of all blocks, and this gives around 1.7-1.8× speedup over attention without the mask. Only blocks that cross the diagonal need the mask applied, which for square blocks means one block per row.

## Parallelizing over sequence length

FlashAttention assigns one thread block per attention head, so the number of blocks equals batch size times number of heads, and an A100 has 108 streaming multiprocessors. That scheduling uses the GPU well only when the block count is large, at least about 80, which fails for long sequences that come with small batches or few heads.

In the forward pass, the outer loop over sequence length is independent across blocks, so FlashAttention-2 places these row blocks on separate thread blocks that never communicate. Raising the number of concurrent blocks improves occupancy when batch and head counts are small, which is where the speedup appears; the loop-order swap and sequence-length parallelism were first implemented by Phil Tillet in Triton.

In the backward pass, the only computation shared between column blocks is the update of dQ, so FlashAttention-2 schedules one thread block per column block. Blocks write their contributions to dQ with atomic adds, which lets them communicate without waiting for one another.

## Splitting work across warps

A thread block typically uses 4 or 8 warps. In FlashAttention's forward pass, K and V are split across 4 warps while Q is shared, so each warp produces a partial product that has to be written to shared memory, synchronized and summed.

FlashAttention-2 instead splits Q across the 4 warps and keeps K and V accessible to all of them, so each warp multiplies by the shared V and produces its slice of the output without communicating. Figure 3 contrasts the two forward-pass partitions.

The backward pass avoids split-K too, though it still needs synchronization because of the more complicated dependencies among Q, K, V, O, dO, dQ, dK and dV. According to the authors, avoiding split-K reduces shared memory reads and writes in the backward pass and yields speedup.

Larger blocks reduce shared memory loads and stores but need more registers and more shared memory, and past a certain size the kernel slows from register spilling or cannot run. Block sizes of {64, 128}×{64, 128} are typically chosen, depending on head dimension and shared memory size, and the authors tune each head dimension by hand.

## Attention speed on A100 against earlier kernels

The attention benchmarks vary sequence length from 512 to 16k, set the batch size so that total tokens stay at 16k, and use hidden dimension 2048 with head dimension 64 or 128. Forward FLOPs are counted as \\\\(4\\\\cdot\\\\text{seqlen}^2\\\\cdot\\\\text{head dimension}\\\\cdot\\\\text{number of heads}\\\\), halved for causal masks, and backward FLOPs are taken as 2.5 times the forward count.

Against FlashAttention and FlashAttention in xformers, the forward plus backward runs are around 2× faster, and against Triton the forward pass is 1.3-1.5× faster with about 2× in the backward pass. The gap to PyTorch's standard attention reaches up to 10× in these runs.

FlashAttention-2 reaches up to 230 TFLOPs/s, which is 73% of the theoretical maximum TFLOPs/s on A100 GPUs. The forward pass reaches up to 73% of the theoretical maximum throughput and the backward pass up to 63%.

Figure 4 shows forward plus backward speed for four settings, with and without a causal mask and with head dimension 64 or 128, against PyTorch, FlashAttention, xformers, FlashAttention Triton and FlashAttention-2.

The forward and backward splits are the places where the relative gains to Triton are reported separately, as given above.

## GPT-style training throughput

Table 1 lists training throughput per GPU for each model and context length, comparing FlashAttention-2 with a baseline without FlashAttention and with FlashAttention.

At 2k context, FlashAttention-2 reaches 196 TFLOPs/s on GPT3-1.3B and 205 TFLOPs/s on GPT3-2.7B, where FlashAttention reaches 189 TFLOPs/s on both. At 8k context, FlashAttention-2 reaches 220 TFLOPs/s on GPT3-1.3B and 225 TFLOPs/s on GPT3-2.7B, against 170 and 175 TFLOPs/s for FlashAttention and 72 and 80 TFLOPs/s without it.

Overall the authors report up to 1.3× speedup over FlashAttention and 2.8× over the baseline without FlashAttention, reaching up to 225 TFLOPs/s per A100 GPU at 72% model FLOPs utilization.

The FLOPs are computed as \\\\(6\\\\cdot\\\\text{seqlen}\\\\cdot\\\\text{number of params} + 12\\\\cdot\\\\text{number of layers}\\\\cdot\\\\text{hidden dim}\\\\cdot\\\\text{seqlen}^2\\\\), following Megatron-LM, and the attention term is not halved for causal masks.

## Running the same kernel on H100

Running the same implementation on H100 GPUs, without special instructions such as TMA or 4th-gen Tensor Cores, reaches up to 335 TFLOPs/s.

The authors expect new instructions to add another 1.5x-2x on H100, but that was left to future work and not measured.

## Limitations

Block sizes are tuned manually for each head dimension, with essentially four choices, and automatic tuning is left to future work. The end-to-end FLOPs formula keeps the full attention term under causal masks, so the reported throughput follows the literature formula rather than a causal count.

The end-to-end experiments cover only the 1.3B and 2.7B GPT-style models at 2k and 8k sequence lengths. The H100 figure uses the same kernel without the newer hardware features, and the authors did not measure the gain they expect from them.

## Paper info

- **Authors**: Tri Dao
- **Venue**: arXiv · Preprint
- **First published**: 2023-7-17
- **Added**: 2026-10-19
- **Updated**: 2023-7-17
- **Version**: v1
- **arXiv**: 2307.08691
- **Category**: cs.LG
- **Original paper terms**: [arXiv non-exclusive 1.0](https://arxiv.org/licenses/nonexclusive-distrib/1.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/2307.08691v1) · [PDF ↗](https://arxiv.org/pdf/2307.08691v1)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Tri Dao (2023). FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. arXiv:2307.08691v1. https://arxiv.org/abs/2307.08691v1

**BibTeX**

```
@misc{dao2023flashattention,
  title = {{FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning}},
  author = {Tri Dao},
  year = {2023},
  eprint = {2307.08691},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2307.08691v1}
}
```

## Other paper commentary

- [On Feature Learning in Structured State Space Models](https://refivu.com/en/papers/f2f5ef3f-9d61-4b9e-93ae-dfe0ebc80328-on-feature-learning-in-structured-state-space-models.md)
- [On Expressive Power of Floating-Point Transformers](https://refivu.com/en/papers/8eff9b9c-d057-4d27-8b46-4f97cbae6130-on-expressive-power-of-floating-point-transformers.md)
- [Unitary Convolutions for Message-passing and Positional Encodings on Directed Graphs](https://refivu.com/en/papers/cf7ea629-41a3-4349-add7-79a6b104140f-unitary-convolutions-for-message-passing-and-positional.md)
- [Understanding the Parameter Space Volume of Transformers Encoding Boolean Functions](https://refivu.com/en/papers/f4dbf6ce-3357-44a3-b4ed-38147e384f67-understanding-the-parameter-space-volume-of-transformers.md)
- [IANN: A Unified Framework for Equivariant InterAtomic Neural Networks with User-Friendly Implementation](https://refivu.com/en/papers/4c633944-8862-4ee4-bd77-a5c9f417f6fd-iann-a-unified-framework-for-equivariant-interatomic-neural.md)
- [Multi-Branch Transformer](https://refivu.com/en/papers/41db7368-f02a-4b93-a29d-688fd514713c-multi-branch-transformer.md)
- [Instance Normalization: The Missing Ingredient for Fast Stylization](https://refivu.com/en/papers/d30fae5e-d1ad-4ef1-9b41-da9a7a9f25cf-instance-normalization-the-missing-ingredient-for-fast.md)
- [Group Normalization](https://refivu.com/en/papers/73ea525c-b90c-43b2-b656-bb21666ab914-group-normalization.md)
- [Layer Normalization](https://refivu.com/en/papers/2f67f179-7720-4b69-8cac-e7157bee38ae-layer-normalization.md)
- [Root Mean Square Layer Normalization](https://refivu.com/en/papers/97c61522-5940-4a28-ad7d-4126a3ce8c01-root-mean-square-layer-normalization.md)
- [LoRA: Low-Rank Adaptation of Large Language Models](https://refivu.com/en/papers/fec4f8e4-2771-4948-a986-0295db47b321-lora-low-rank-adaptation-of-large-language-models.md)

## Terms in this paper

- [FlashAttention](https://refivu.com/en/terms/dd45c7915b8f-flashattention)
- [causal mask](https://refivu.com/en/terms/3bf200651a46-causal-mask)
- [model FLOPs utilization](https://refivu.com/en/terms/4c20f04b5c1b-model-flops-utilization)
- [Tensor Cores](https://refivu.com/en/terms/3c542399e985-tensor-cores)
- [tiling](https://refivu.com/en/terms/9213fc4177f3-tiling)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/177a3817-56f7-448e-964a-a2e688dc7c81-flashattention-2-faster-attention-with-better-parallelism)
