Systems & Infrastructure15 min read • August 2026
FlashAttention:Fast&Memory-EfficientExactAttentionviaTiling
CUDA memory hierarchy optimization: IO-aware tiling algorithms reducing attention memory complexity from O(N^2) to O(N).
Reference / Authors: Dao et al. (Stanford / Princeton University, 2022)
Abstract & Theoretical Context
Standard self-attention implementations store intermediate N x N attention probability matrices S and P in GPU High-Bandwidth Memory (HBM). Because HBM memory bandwidth (~1.5 TB/s on A100) is 10x slower than GPU On-Chip SRAM (~19 TB/s), standard attention is severely IO-bound rather than compute-bound.
FlashAttention restructures the attention algorithm to be IO-aware. By leveraging online softmax re-normalization and tiling, FlashAttention computes exact attention block-by-block inside GPU SRAM without materializing large intermediate N x N matrices in HBM.
This reduces memory overhead from quadratic O(N^2) to linear O(N) in sequence length, enabling 2x to 4x speedups in training and long context lengths (64k to 128k tokens).
Mathematical Formulations & Variables
1. Standard Attention HBM Memory Transfers: Memory IO: O(N^2) HBM Reads/Writes for N x N Attention Matrix S = Q*K^T and Softmax P 2. FlashAttention Tiling Memory Transfers: Memory IO: O(N^2 * d^2 / M) HBM Memory Transfers Where M is GPU SRAM capacity and d is head dimension. 3. Online Softmax Re-normalization Algorithm: When merging block i into running softmax statistics: m_new = max(m_prev, max(S_block)) d_new = d_prev * exp(m_prev - m_new) + sum(exp(S_block - m_new)) O_new = O_prev * (d_prev * exp(m_prev - m_new) / d_new) + (P_block * V_block) / d_new
PyTorch Implementation Code
flashattention-memory-efficient-attention.py
Step-by-Step Reproduction Guide
11. CUDA Environment Verification: Verify CUDA toolkit 11.6+ and nvcc compiler (`nvcc --version`).
22. Installation: Install FlashAttention binary via `pip install flash-attn --no-build-isolation`.
33. PyTorch Integration: Replace manual attention logic with `from flash_attn import flash_attn_func`.
44. Precision Requirement: Ensure input tensors Q, K, V are formatted in `torch.float16` or `torch.bfloat16`.
55. Benchmark Execution: Measure execution time and VRAM usage against `torch.nn.functional.scaled_dot_product_attention`.
Key Insights & Operator Insights
- IO-Bound Optimization: Speedup stems from reducing GPU memory bandwidth transfers, not reducing FLOP count.
- Exact Attention: Unlike approximate sparse attention algorithms, FlashAttention computes exact mathematical attention values.
- Linear Memory: Enables training 64k+ context windows without running out of CUDA VRAM.
- FlashAttention-2 & 3: Further parallelizes over sequence length and warp scheduling on Hopper GPUs.
HARDWARE & SYSTEM REQUIREMENTS
NVIDIA A100, H100, or RTX 3090 / 4090 (Ampere / Hopper CUDA Architecture)