3102: Flash Attention - IO-Aware Exact Attention¶
Difficulty: ⭐⭐⭐ Advanced
Estimated Time: 4 hours
Table of Contents¶
- Learning Objectives
- Abstract
- The Problem with Standard Attention
- Flash Attention Algorithm
- Flash Attention 2
- Using Flash Attention
- Performance Comparison
- Implementation Details
- Limitations and Considerations
- Flash Attention 3
- Summary
- References
Learning Objectives¶
After completing this lesson, you will be able to:
- Contrast the O(L²) HBM traffic of materializing S and P against Flash's linear memory, using the ~600 GB/s HBM vs ~30 TB/s SRAM hierarchy to argue why attention is bandwidth-bound
- Implement incremental (online) softmax — running max, the
exp(m_old − m_new)rescaling correction, and running sum — and update a partial output block without ever materializing the L×L matrix - Attribute FA2's ~2x A100 speedup over FA1 to the swapped K-outer/Q-inner loop order, reduced non-matmul FLOPs, and better work partitioning
- Enable Flash Attention three ways —
xformers.ops.memory_efficient_attentionwith anattn_bias,flash_attn_func(causal=True), and HFattn_implementation="flash_attention_2"under FP16 - Read the A100/2048 benchmark table (45 ms/16 GB standard → 12 ms/3.2 GB FA2) and predict when Flash does not pay off: sequences under ~512 tokens, weight inspection, CPU inference
- Size Q/K/V blocks against shared-memory limits (48 KB/SM on Turing, block ≈ 128) and cast inputs to FP16/BF16 as Flash requires
Abstract¶
Flash Attention is a reorganization of the attention computation that reduces memory IO (input/output) from quadratic to linear. It's exact (not approximate), faster, and uses less memory.
The Problem with Standard Attention¶
Memory Access Pattern¶
# Standard attention (as in PyTorch)
def standard_attention(Q, K, V):
# Q, K, V: (B, H, L, D)
B, H, L, D = Q.shape
# 1. Compute S = Q @ K^T → O(L²) memory reads/writes
S = torch.matmul(Q, K.transpose(-2, -1)) / (D ** 0.5)
# 2. Compute P = softmax(S) → O(L²) memory for attention matrix
P = torch.softmax(S, dim=-1)
# 3. Compute O = P @ V → O(L²) memory reads
O = torch.matmul(P, V)
return O
# Total HBM (High Bandwidth Memory) access:
# - Read Q, K, V: 3 × B × H × L × D
# - Write S: B × H × L × L
# - Read S, write P: 2 × B × H × L × L
# - Read P, V: B × H × L × L + B × H × L × D
# Total: O(L²) HBM accesses
Memory Bandwidth Bottleneck¶
GPU Memory Hierarchy Speed Comparison:
HBM (GPU VRAM): ~600 GB/s
SRAM (On-chip): ~30 TB/s (50x faster!)
Standard attention:
- Loads entire attention matrix to HBM
- Multiple reads/writes to slow HBM
Flash attention:
- Keeps attention matrix in fast SRAM
- Tiled computation minimizes HBM access
Flash Attention Algorithm¶
Key Ideas¶
1. Tiling: Split Q, K, V into blocks
2. Incremental softmax: Update softmax statistics online
3. No materialization: Never store full attention matrix
Incremental Softmax¶
def incremental_softmax(new_block, running_max, running_sum):
"""
Update softmax statistics without seeing all data at once
"""
# new_block: (block_size, block_size)
# running_max, running_sum: scalar statistics
# Update max
new_max = torch.maximum(running_max, new_block.max(dim=-1, keepdim=True).values)
# Update sum with new scaling
correction = torch.exp(running_max - new_max)
new_sum = running_sum * correction + torch.exp(new_block - new_max).sum(dim=-1, keepdim=True)
return new_max, new_sum
Flash Attention Pseudocode¶
def flash_attention(Q, K, V, block_size=16):
"""
Flash Attention: IO-aware exact attention
"""
B, H, L, D = Q.shape
O = torch.zeros_like(Q)
# Initialize output statistics
running_max = torch.full((B, H, L, 1), -float('inf'))
running_sum = torch.full((B, H, L, 1), 0.0)
# Loop over key blocks
for j in range(0, L, block_size):
K_block = K[:, :, j:j+block_size, :] # Load to SRAM
V_block = V[:, :, j:j+block_size, :] # Load to SRAM
# Loop over query blocks
for i in range(0, L, block_size):
Q_block = Q[:, :, i:i+block_size, :] # Load to SRAM
# Compute attention scores (in SRAM!)
S_block = torch.matmul(Q_block, K_block.transpose(-2, -1)) / (D ** 0.5)
# Update running statistics
new_max = torch.maximum(running_max[:, :, i:i+block_size, :], S_block.max(dim=-1, keepdim=True).values)
old_scale = torch.exp(running_max[:, :, i:i+block_size, :] - new_max)
p = torch.exp(S_block - new_max) # UNNORMALIZED probabilities
running_sum[:, :, i:i+block_size, :] = running_sum[:, :, i:i+block_size, :] * old_scale + p.sum(dim=-1, keepdim=True)
running_max[:, :, i:i+block_size, :] = new_max
# Update output (in SRAM!) - accumulate UNNORMALIZED weights;
# the single division by the final running_sum happens below
O[:, :, i:i+block_size, :] = old_scale * O[:, :, i:i+block_size, :] + torch.matmul(p, V_block)
return O / running_sum
Flash Attention 2¶
Improvements over Flash Attention 1¶
Flash Attention 1:
- Better algorithm, but not fully optimized
- Used shared memory inefficiently
Flash Attention 2:
- Better work partitioning
- Reduced non-matmul FLOPs
- Optimized for specific GPU architectures
- 2x faster than FA1 on A100
Algorithm Differences¶
import torch
Q_blocks = torch.randn(4, 32, 64) # query tiles: [tiles, block, d]
K_blocks = torch.randn(4, 32, 64) # key tiles
V_blocks = torch.randn(4, 32, 64) # value tiles
def compute_attention(q, k, v):
return torch.softmax(q @ k.T, dim=-1) @ v
# FA1: Loop order (Q, K, V) blocks
for Q_block in Q_blocks:
for K_block in K_blocks:
for V_block in V_blocks:
compute_attention(Q_block, K_block, V_block)
# FA2: Loop order optimized for GPU
for K_block in K_blocks:
for Q_block in Q_blocks:
for V_block in V_blocks:
# Better memory access pattern
# Maximizes L2 cache reuse
compute_attention(Q_block, K_block, V_block)
Using Flash Attention¶
Via xFormers (Meta's library)¶
uv pip install xformers
import torch
from xformers.ops import memory_efficient_attention
# Drop-in replacement for standard attention
Q = torch.randn(1, 8, 1024, 64, device='cuda')
K = torch.randn(1, 8, 1024, 64, device='cuda')
V = torch.randn(1, 8, 1024, 64, device='cuda')
# Flash attention
O = memory_efficient_attention(Q, K, V)
# With causal mask
mask = torch.tril(torch.ones(1024, 1024, device='cuda'))
O = memory_efficient_attention(Q, K, V, attn_bias=mask)
Via Flash Attention Library¶
uv pip install flash-attn
from flash_attn import flash_attn_func
# Flash attention with causal mask
Q = torch.randn(1, 128, 1024, 64, device='cuda') # (batch, heads, seq, dim)
K = torch.randn(1, 128, 1024, 64, device='cuda')
V = torch.randn(1, 128, 1024, 64, device='cuda')
# causal=True for autoregressive
O = flash_attn_func(Q, K, V, causal=True)
# No softmax output (not materialized)
# Much faster and less memory!
In Transformers (Hugging Face)¶
from transformers import AutoModelForCausalLM
# Models using Flash Attention
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen3-8B",
attn_implementation="flash_attention_2",
dtype=torch.float16,
device_map="auto"
)
# Uses Flash Attention 2 automatically!
Performance Comparison¶
Benchmarks (A100 GPU, sequence length 2048)¶
Attention Type Time (ms) Memory (GB)
────────────────────────────────────────
Standard 45 16.0
Memory-Efficient 28 8.0
Flash Attn 1 18 4.5
Flash Attn 2 12 3.2
Speedup: 3.75x faster than standard
Memory: 5x less memory usage
Sequence Length Scaling¶
Standard Attention:
Time: O(L²) - doubles when L × √2
Memory: O(L²) - doubles when L × √2
Flash Attention:
Time: O(L²) - but 3-4x faster constant
Memory: O(L) - linear!
For L = 8192:
Standard: 16GB (VRAM limit for an 11GB-class GPU)
Flash: 4GB (can handle much longer!)
Implementation Details¶
Block Size Selection¶
# Optimal block size depends on GPU
# For an 11GB VRAM GPU (Turing):
# - Shared memory: 48KB per SM
# - L2 cache: 5.5MB
import torch
def get_optimal_block_size():
"""
Calculate optimal block size for Flash Attention
"""
# Get GPU properties
device = torch.cuda.current_device()
props = torch.cuda.get_device_properties(device)
# Shared memory per SM
shared_mem_per_sm = 48 * 1024 # 48KB for Turing
# Each block needs: Q (B×H×B_r×D) + K (B×H×B_c×D) + ...
# Estimate: ~3 × B_r × B_c × D bytes
# For D = 64, B_r = B_c = 64:
# Memory: 3 × 64 × 64 × 64 × 2 bytes (fp16) ≈ 1.5MB
# Optimal: 128 for most cases
return 128
BLOCK_SIZE = get_optimal_block_size()
Half Precision (FP16/BF16)¶
# Flash Attention requires half precision
Q = Q.to(torch.float16)
K = K.to(torch.float16)
V = V.to(torch.float16)
# Or bfloat16 (better for training)
Q = Q.to(torch.bfloat16)
# FP16 benefits:
# - 2x less memory
# - Faster compute (Tensor Cores)
# - Sufficient for inference
Limitations and Considerations¶
When NOT to use Flash Attention¶
1. Very short sequences (< 512):
- Overhead of tiling outweighs benefits
- Standard attention is fine
2. Need attention weights:
- Flash doesn't materialize attention matrix
- Use standard attention or compute separately
3. CPU inference:
- Flash is GPU-only
- Standard attention on CPU
4. Perplexity calculation:
- Need exact softmax values
- Can compute separately if needed
Computing Attention Weights¶
def get_attention_weights(Q, K, V):
"""
Compute attention weights separately if needed
Uses more memory but gives exact values
"""
# Compute output with Flash
O = flash_attn_func(Q, K, V)
# Compute attention separately if needed
with torch.no_grad():
scores = torch.matmul(Q, K.transpose(-2, -1)) / (Q.size(-1) ** 0.5)
attn_weights = torch.softmax(scores, dim=-1)
return O, attn_weights
Flash Attention 3¶
Hardware-Aware Optimization¶
Flash Attention 3 (2024):
- Optimized for Hopper (H100) architecture
- Hardware-specific tiling
- Tensor Core optimizations
- Up to 2x faster than FA2 on H100
Key insight:
- Different optimal block sizes for different GPUs
- FA3: H100 optimized
- FA2: A100, V100 optimized
- FA1: General purpose
Summary¶
Flash Attention reorganizes the attention computation rather than approximating it: tiling plus online softmax keep the working set in fast SRAM, cutting memory IO from quadratic to linear. The result is exact attention that is faster and uses less memory than the standard materialized S = Q@K^T path. This lesson showed why standard attention's memory access pattern is the real bottleneck, then the Flash algorithm and its implementation. The rule it leaves: memory bandwidth, not FLOPs, is usually the attention ceiling - and IO-aware algorithm design is how the ceiling moves.
References¶
Related Minder Academy Documents¶
Next Steps¶
- Continue with: 3103: SDPA and torch.compile
- Assessment: 3100: Attention - Quiz
Related Documents:
- 3101: Self-Attention
- 4201: Context Window
-
Experiment Template: EXP_3102: Flash Attention