Overview
Flash Attention v2 computes scaled dot-product attention:- Q: Query matrix (B×Sq×N×H)
- K: Key matrix (B×Sk×N×H)
- V: Value matrix (B×Sk×N×H)
- O: Output matrix (B×Sq×N×H)
- B: batch size, Sq/Sk: sequence length, N: number of heads, H: head dimension
Key Features
- Online softmax: Computes softmax incrementally without materializing full attention matrix
- Tiled computation: Processes attention in blocks to fit in shared memory
- Register pipeline: Overlaps shared memory loads with computation
- Causal masking: Optional support for autoregressive models
Architecture
Implementation
Running Examples
Performance Profiling
Key Concepts
Online Softmax Algorithm
Online Softmax Algorithm
The online softmax algorithm processes attention in blocks without materializing the full matrix:Traditional approach (memory intensive):Flash Attention approach (memory efficient):This reduces memory from O(N²) to O(N).
Register Pipeline
Register Pipeline
The register pipeline overlaps shared memory loads with computation:
Tile Size Selection
Tile Size Selection
Choosing optimal tile sizes:m_block_size (Query tile):
- Larger: Better arithmetic intensity, more registers
- Smaller: Lower SMEM usage, better for long sequences
- Typical: 64, 128
- Affects online softmax accuracy
- Should match m_block_size for balanced computation
- Typical: 64, 128
- Usually fixed by model (64, 128, 256)
- Must be 16-byte aligned
- Pad if necessary
(m_block_size * head_dim + 2 * n_block_size * head_dim) * sizeof(dtype) must fit in SMEMMemory Analysis
Constraints
Source Code
Flash Attention v2 (Ampere)
Complete source:
examples/python/CuTeDSL/ampere/flash_attention_v2.pyFlash Attention (Hopper)
Hopper variant:
examples/python/CuTeDSL/hopper/fmha.py