Papers · arXiv 2205.14135
FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
Summary in three lines
- 🎯 Standard exact attention materializes an attention matrix in slow GPU HBM, making it memory-bound and difficult to scale to long contexts.
- 🔧 FlashAttention computes exact attention within a single fused CUDA kernel by tiling inputs over fast on-chip SRAM, updating softmax incrementally, and recomputing attention on-chip during the backward pass.
- 📈 FlashAttention yields up to 3x end-to-end training speedup on GPT-2, achieves 15% faster training than the MLPerf 1.1 BERT-large record, and scales context to 64K tokens.
Abstract
Transformers are slow and memory-hungry on long sequences, since the time and memory complexity of self-attention are quadratic in sequence length. Approximate attention methods have attempted to address this problem by trading off model quality to reduce the compute complexity, but often do not achieve wall-clock speedup. We argue that a missing principle is making attention algorithms IO-aware -- accounting for reads and writes between levels of GPU memory. We propose FlashAttention, an IO-aware exact attention algorithm that uses tiling to reduce the number of memory reads/writes between GPU high bandwidth memory (HBM) and GPU on-chip SRAM. We analyze the IO complexity of FlashAttention, showing that it requires fewer HBM accesses than standard attention, and is optimal for a range of SRAM sizes. We also extend FlashAttention to block-sparse attention, yielding an approximate attention algorithm that is faster than any existing approximate attention method. FlashAttention trains Transformers faster than existing baselines: 15% end-to-end wall-clock speedup on BERT-large (seq. length 512) compared to the MLPerf 1.1 training speed record, 3 speedup on GPT-2 (seq. length 1K), and 2.4 speedup on long-range arena (seq. length 1K-4K). FlashAttention and block-sparse FlashAttention enable longer context in Transformers, yielding higher quality models (0.7 better perplexity on GPT-2 and 6.4 points of lift on long-document classification) and entirely new capabilities: the first Transformers to achieve better-than-chance performance on the Path-X challenge (seq. length 16K, 61.4% accuracy) and Path-256 (seq. length 64K, 63.1% accuracy).
Reading guide
Problem and motivation
Transformers have quadratic time and memory complexity in sequence length . Although approximate attention methods reduce theoretical FLOP counts, they often fail to achieve wall-clock speedups because modern GPU computations are primarily bottlenecked by memory transfers (IO) rather than arithmetic operations.
In standard attention, computing , , and writes intermediate matrices of size to slow High Bandwidth Memory (HBM) and reads them back multiple times. This incurs HBM accesses and memory footprint, limiting practical context windows.
Key ideas
- IO-Awareness: Account explicitly for the GPU memory hierarchy: fast, small on-chip SRAM (e.g., 192 KB/SM with ~19 TB/s bandwidth on A100) versus large, slow HBM (40–80 GB with 1.5–2.0 TB/s bandwidth).
- Tiling (Block Softmax Computation): Split the input into blocks that fit entirely within SRAM. By tracking running softmax row-max and normalizer statistics, the softmax reduction is computed incrementally across blocks without materializing the full matrix in HBM.
- Recomputation in Backward Pass: Avoid storing the intermediate attention matrix for backpropagation. Instead, store only the output and softmax statistics , recomputing and on-chip block-by-block in SRAM during the backward pass.
- Kernel Fusion: Fuse matrix multiplications, masking, softmax, and dropout into a single CUDA kernel to eliminate redundant HBM round-trips.
Method (with the key equations)
Given , FlashAttention sets block sizes and , where is SRAM capacity.
Incremental Softmax Tracking
For a vector decomposed into sub-vectors and , running statistics update via:
For block of keys/values and block of queries:
- Compute unnormalized scores on SRAM: .
- Compute block local statistics: , , and .
- Update running global normalizers:
- Update running output block :
Complexity Analysis
- IO Complexity: Standard attention requires HBM accesses. FlashAttention requires HBM accesses. The authors prove that no exact attention algorithm can asymptotically achieve accesses across all .
- FLOPs and Memory: FlashAttention performs FLOPs (with slightly more FLOPs in the backward pass due to recomputation) and requires only auxiliary memory beyond inputs and outputs.
Extension: Block-Sparse FlashAttention
Restricting evaluation to non-zero blocks according to a predefined sparsity mask achieves an IO complexity of , where is the fraction of non-zero blocks.
Results (with the most important numbers)
- Training Speedup:
- BERT-large (seq. len 512): Outperforms the MLPerf 1.1 training speed record by 15% (17.4 min vs. 20.0 min on A100s).
- GPT-2 (seq. len 1K): Achieves up to 3.5x speedup over HuggingFace and up to 1.8x speedup over Megatron-LM.
- Long-Range Arena (LRA): Yields 2.4x speedup over standard attention; Block-sparse FlashAttention achieves 2.8x speedup.
- Longer Context Capabilities:
- GPT-2 with 4K context: Trains faster than Megatron-LM at 1K context while improving validation perplexity by 0.7 points (17.5 vs. 18.2).
- Long Document Classification: Scaling context from 512 to 16K yields a 4.3 micro- gain on MIMIC-III (52.8 to 57.1) and up to an 8.5 gain on ECtHR (72.2 to 80.7 at 8K).
- Path-X and Path-256: FlashAttention is the first Transformer to solve Path-X (seq. len 16K) with 61.4% accuracy. Block-sparse FlashAttention achieves 63.1% accuracy on Path-256 (seq. len 64K).
Limitations and open questions
- CUDA Engineering Overhead: Implementing IO-aware kernels requires custom, low-level CUDA programming rather than standard PyTorch or compiler abstractions, making portability across hardware architectures challenging.
- Multi-GPU Attention: The optimal single-node IO schedule does not automatically extend to distributed multi-GPU attention across interconnects (NVLink, InfiniBand).
- Exact Attention Lower Bound: While optimal across general , proving fine-grained parameterized complexity lower bounds in terms of remains an open problem.
Key terms
- IO-awareness
- The algorithmic principle of designing operations to account for reads and writes between levels of hardware memory (e.g., fast on-chip SRAM vs. slower HBM).
- High Bandwidth Memory (HBM)
- The large primary GPU memory that offers high total capacity but significantly lower bandwidth than on-chip cache.
- SRAM
- Fast, on-chip scratchpad memory on modern GPUs located within each Streaming Multiprocessor (SM).
- Tiling
- Restructuring a computation by splitting input matrices into smaller blocks that fit within SRAM and accumulating results across passes.
- Selective gradient checkpointing
- A technique that avoids saving the large intermediate attention matrix during the forward pass by recomputing it on-chip during the backward pass using cached softmax statistics.
- Kernel fusion
- Combining multiple distinct operations (matrix multiply, masking, softmax, dropout) into a single GPU kernel execution to eliminate repeated reads/writes to HBM.
- Block-sparse FlashAttention
- An extension of FlashAttention that computes only non-zero tile blocks defined by a block sparsity mask, reducing IO complexity proportional to the sparsity fraction.
- Path-X / Path-256
- Long-sequence visual reasoning benchmarks from the Long-Range Arena (16K and 64K sequence lengths) on which prior Transformers failed to achieve better-than-chance accuracy.
Questions
Does FlashAttention approximate the attention matrix?
No. FlashAttention computes exact self-attention with identical mathematical outputs to standard attention up to numerical floating-point precision.
Why is FlashAttention faster if it computes more FLOPs in the backward pass?
Because standard attention is memory-bound; moving the matrix between HBM and SRAM consumes far more wall-clock time than performing additional arithmetic operations on fast SRAM.
What auxiliary memory does FlashAttention store for the backward pass?
FlashAttention stores only the forward output , the softmax normalization factors and (requiring extra memory), and the pseudo-random generator state to reproduce dropout masks on-chip.
How does FlashAttention compare in IO complexity to standard attention?
Standard attention requires HBM accesses, whereas FlashAttention requires accesses, where is the size of SRAM and is the head dimension.
The overview on this page was written by AI from the paper and may contain mistakes. Read the paper for the details.