FlashAttention Explained: GPU SRAM vs. HBM & Online Softmax Tiling
Why standard PyTorch attention bottlenecks on slow GPU HBM reads/writes of the N×N matrix, how FlashAttention fuses tiled matmul + Online Softmax inside blazing-fast on-chip SRAM for O(N) memory, plus Sliding Window & Ring Attention.
FlashAttention computes exact Self-Attention in small blocks inside ultra-fast GPU on-chip SRAM using Online Softmax, never materializing the huge N×N attention matrix in slow HBM memory.
Standard attention runs out of GPU memory (O(N²)) and stalls waiting on slow HBM reads; FlashAttention makes long-context training 2×–4× faster with O(N) memory.
FlashAttention is the algorithmic breakthrough that took Transformers from 2K context windows (2020) to 128K–1M+ context windows (2024–2026) — with ZERO approximation!
PyTorch's F.scaled_dot_product_attention automatically dispatches FlashAttention-2/3; knowing its tiling constraints (head dim ≤ 256, FP16/BF16, causal masks) prevents accidental 10× slowdowns and OOMs.
Understanding that FlashAttention is 100% mathematically exact (not an approximation like Linformer or Performer!) yet 2–4× faster and 10× more memory-efficient changes how you think about GPU systems.
Top-tier ML systems question: 'How can FlashAttention compute softmax across the entire row of length N without ever storing the N×N attention matrix in HBM?'
Does FlashAttention compute an approximation of standard Scaled Dot-Product Attention, or the exact same mathematical output?
- Contrast GPU HBM (large, 80 GB, ~3.35 TB/s) with on-chip SRAM (tiny, ~50 MB, ~30+ TB/s) and explain IO-aware algorithm design
- Prove why naive attention uses O(N²) HBM memory and HBM traffic, while FlashAttention computes EXACT attention in O(N) memory
- Derive the Online Softmax rescaling update (running max m_new and running denominator l_new) across K/V tiles
- Explain how FlashAttention avoids saving the N×N matrix for backward pass via fast recomputation, plus Sliding Window & Ring Attention
Imagine a chef (GPU Tensor Cores) who can chop vegetables at lightning speed, standing next to a tiny cutting board (SRAM) while the refrigerator (HBM) is down a long hallway. Naive PyTorch attention chops one ingredient, walks down the hallway to put a giant tray into the fridge, walks back to apply softmax, puts it back in the fridge, and walks back again! FlashAttention brings small bowls (tiles) to the cutting board, does matmul + softmax + V-multiply all in one fused pass on the cutting board, and only walks back once with the final dish!
1. The GPU Memory Hierarchy Bottleneck: HBM vs. On-Chip SRAM
Standard attention makes 3 separate HBM round-trips for the massive matrix: write , read + write , read + write .
Why Naive Attention OOMs on Long Sequences
For a single sequence of length with heads in FP16:
- The attention matrix alone takes — instantly crashing an 80 GB H100!
- Even for moderate , the Tensor Cores spend most of their time waiting on HBM reads/writes of and rather than doing math.
- FlashAttention's Core Principle (IO-Awareness): Never materialize or in HBM! Load small blocks of into fast on-chip SRAM, fuse inside a single CUDA kernel, and write only the final (shape , just memory!) back to HBM.
2. Online Softmax: The Exact Rescaling Trick That Makes Tiling Work
Step through Tile 1 → Tile 2 in the interactive mini-lab below to watch Online Softmax adjust the running max and rescale Tile 1's partial output to match exact full-row softmax!
Online Softmax Update Equations (Block by Block)
Suppose we already processed Tile 1 with running max , running denominator , and unnormalized partial output . Now Tile 2 arrives with local block max , local sum , and local output :
- New global max:
- Rescale old & new denominators:
- Rescale and accumulate output:
- After the final tile, divide once by : . Notice the rescaling factor is always numerically stable (no overflow!) and gives the exact same result as computing full-row softmax!
O_new = exp(m_old - m_new)·O_old + exp(m_tile - m_new)·O_tile
Tracks the largest attention logit seen across all tiles so far to prevent exp() overflow.
Online Softmax 2-Tile Exact Rescaling Verifier
3. Scaling to 1M+ Tokens: Sliding Window & Ring Attention
FlashAttention solves memory, but attention FLOPs are still . How do frontier models handle 128K–1M+ token contexts?
Beyond Single-GPU FlashAttention
- Sliding Window Attention (Mistral / Gemma 2): Each token attends only to the previous tokens (e.g., ). Across stacked layers, the effective receptive field still grows to (e.g., ), while capping KV-Cache at a fixed ring buffer of size !
- Ring Attention (Context Parallelism): Splits a 1M-token sequence across GPUs arranged in a ring. Each GPU runs FlashAttention on its local Q chunk while asynchronously passing K/V chunks around the ring — overlapping NVLink communication with Tensor Core compute!
Worked Example: Checking Online Softmax Exactness on 2 Tiles
Suppose a row of 4 logits is split into Tile 1 = [1.0, 2.0] and Tile 2 = [4.0, 0.0].
, .
What is the HBM memory complexity of FlashAttention with respect to sequence length N?
Wait — during backpropagation, FlashAttention recomputes the tiles from scratch instead of reading saved attention weights from HBM. Why is recomputing actually FASTER than saving them?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
No! FlashAttention still performs FLOPs (it computes exact full attention). Its massive 2–4× speedup comes from eliminating HBM memory reads/writes, and its 10×+ memory savings come from HBM storage!
FlashAttention On-Chip SRAM Block-Tiling Animator
Watch FlashAttention sweep 4×4 Q/KV tiles inside blazing-fast on-chip SRAM — fusing matmul + online softmax + V accumulation with ZERO O(N²) HBM writes!
PyTorch 2.x F.scaled_dot_product_attention
Default fused attention backend in Hugging Face Transformers, vLLM, and LitGPT — automatically runs FlashAttention-2/3 on supported GPUs.
Long-Context Pre-Training (128K–1M Tokens)
Combines FlashAttention (single-GPU SRAM tiling) with Ring Attention (multi-GPU sequence sharding) to train on entire codebases and books.
import torch
# Online Safe Softmax (core tiling trick behind FlashAttention without materializing N×N)
def online_softmax_tiled(scores: torch.Tensor, block_size: int = 4) -> torch.Tensor:
m = torch.tensor(float("-inf"))
l = torch.tensor(0.0)
# Pass 1: stream blocks to compute exact global max (m) and normalizer (l)
for start in range(0, scores.numel(), block_size):
blk = scores[start:start + block_size]
m_new = torch.maximum(m, blk.max())
l = l * torch.exp(m - m_new) + torch.exp(blk - m_new).sum()
m = m_new
return torch.exp(scores - m) / l
x = torch.randn(16)
tiled = online_softmax_tiled(x, block_size=4)
exact = torch.softmax(x, dim=0)
print(f"Max abs diff vs standard softmax: {(tiled - exact).abs().max().item():.2e}")
exp(m_old - m_new)) is 100% mathematically exact.