Chapter 9 of 40 · ~26 min read & lab+90 XP
Chapter 9 · Generative AI

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.

What Is It?

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.

Why Is It Required?

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.

Everyday Analogy: Chopping and cooking one bowl of vegetables at a time on a small cutting board instead of carrying every ingredient back and forth to a warehouse across the street.
Why ML Engineers & Data Scientists Actually Need This

FlashAttention is the algorithmic breakthrough that took Transformers from 2K context windows (2020) to 128K–1M+ context windows (2024–2026) — with ZERO approximation!

ML / AI Engineer

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.

Data Scientist

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.

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

Does FlashAttention compute an approximation of standard Scaled Dot-Product Attention, or the exact same mathematical output?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
HBM vs. SRAMSay aloud:“High-Bandwidth Memory vs. Static RAM”
Plain-English Meaning
80 GB main GPU memory (~3.35 TB/s) vs. ~50 MB on-chip compute cache (~30+ TB/s, ~10× faster!)
Everyday Example
HBM is the warehouse; SRAM is the workbench
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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 N×NN \times N 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

Everyday Story First (Zero Math Yet!)

Standard attention makes 3 separate HBM round-trips for the massive N×NN \times N matrix: write S=QK⊤S = QK^\top, read SS + write P=softmax(S)P = \text{softmax}(S), read PP + write O=PVO = PV.

Why FlashAttention Exists: GPU On-Chip SRAM (~30 TB/s) vs. HBM (~3.3 TB/s)On-Chip SRAM (Tiny & Instant)Size: ~20–50 MBSpeed: ~30+ TB/s (10× faster!)FlashAttention fuses QKᵀ + Softmax + V here!Tile BlocksGPU HBM (Huge & Slower)Size: 80 GB (H100)Speed: 3.35 TB/sNever writes O(N²) attention matrix here ✓
An NVIDIA H100 has 80 GB of slower HBM (3.35 TB/s) and ~50 MB of blazing-fast on-chip SRAM (~30+ TB/s) — standard attention wastes time writing the huge N×N matrix back and forth to HBM!

Why Naive Attention OOMs on Long Sequences

For a single sequence of length N=65,536N = 65,536 with H=32H = 32 heads in FP16:

  • The N×NN \times N attention matrix SS alone takes 32×65,5362×2 bytes=275 GB32 \times 65,536^2 \times 2\text{ bytes} = \mathbf{275\text{ GB}} — instantly crashing an 80 GB H100!
  • Even for moderate N=4,096N = 4,096, the Tensor Cores spend most of their time waiting on HBM reads/writes of SS and PP rather than doing math.
  • FlashAttention's Core Principle (IO-Awareness): Never materialize SS or PP in HBM! Load small blocks of Q,K,VQ, K, V into fast on-chip SRAM, fuse QK⊤→mask→softmax→PVQK^\top \to \text{mask} \to \text{softmax} \to PV inside a single CUDA kernel, and write only the final OO (shape N×dkN \times d_k, just O(N)O(N) memory!) back to HBM.

2. Online Softmax: The Exact Rescaling Trick That Makes Tiling Work

Everyday Story First (Zero Math Yet!)

Step through Tile 1 → Tile 2 in the interactive mini-lab below to watch Online Softmax adjust the running max mm and rescale Tile 1's partial output to match exact full-row softmax!

Online Softmax: Exact Attention Across Tiles Without Storing N×N Scores!Tile 1 (K₁, V₁)m₁ = max(S₁), l₁ = Σ exp(S₁−m₁)Tile 2 (K₂, V₂)m_new = max(m₁, max(S₂))Exact Rescale ✓O ← O·e^(m₁−m_new) + P₂V₂Memory drops from O(N²) → O(N) with ZERO approximation error (exact bit-level math)!
FlashAttention tiles Q, K, V into fast on-chip SRAM and uses Online Softmax (running max m and rescaled denominator l) to compute exact attention WITHOUT ever materializing the N×N matrix in HBM!

Online Softmax Update Equations (Block by Block)

Suppose we already processed Tile 1 with running max m1m_1, running denominator l1l_1, and unnormalized partial output O~1\tilde{O}_1. Now Tile 2 arrives with local block max m2m_2, local sum l2l_2, and local output O~2\tilde{O}_2:

  1. New global max: mnew=max⁡(m1,m2)m_{\text{new}} = \max(m_1, m_2)
  2. Rescale old & new denominators: lnew=em1−mnew⋅l1+em2−mnew⋅l2l_{\text{new}} = e^{m_1 - m_{\text{new}}} \cdot l_1 + e^{m_2 - m_{\text{new}}} \cdot l_2
  3. Rescale and accumulate output: O~new=em1−mnew⋅O~1+em2−mnew⋅O~2\tilde{O}_{\text{new}} = e^{m_1 - m_{\text{new}}} \cdot \tilde{O}_1 + e^{m_2 - m_{\text{new}}} \cdot \tilde{O}_2
  4. After the final tile, divide once by lfinall_{\text{final}}: O=O~final/lfinalO = \tilde{O}_{\text{final}} / l_{\text{final}}. Notice the rescaling factor em1−mnew≤1e^{m_1 - m_{\text{new}}} \le 1 is always numerically stable (no overflow!) and gives the exact same result as computing full-row softmax!
Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of FlashAttention's Online Softmax Rescaling

O_new = exp(m_old - m_new)·O_old + exp(m_tile - m_new)·O_tile

Running Safe Maximum

Tracks the largest attention logit seen across all tiles so far to prevent exp() overflow.

In our example: Tile 1 max=2.0, Tile 2 max=4.0 → m_new=4.0
Put it together with real numbers: FlashAttention-2 also parallelizes across the sequence length dimension and swaps the loop order (outer loop over Q tiles, inner loop over K/V tiles) to minimize non-matmul FLOPs and hit ~70%+ H100 Tensor Core utilization!
Animated Mini-Lab • 2.3

Online Softmax 2-Tile Exact Rescaling Verifier

Error vs Global Softmax: 0.000000 ✓
Tile 1 cached: m₁ = 2.0, l₁ = 1.368
Tile 2 arrives: m_new = 4.0 → rescale factor e^(m₁−m_new) = 0.1353
Updated exact P(s₄) = 0.8228 (zero N×N HBM write!)

3. Scaling to 1M+ Tokens: Sliding Window & Ring Attention

Everyday Story First (Zero Math Yet!)

FlashAttention solves O(N2)O(N^2) memory, but attention FLOPs are still O(N2)O(N^2). How do frontier models handle 128K–1M+ token contexts?

Scaling to 1M Tokens: Sliding Window Attention & Multi-GPU Ring AttentionSliding Window (Mistral / Gemma 2)Attend only to last W = 4,096 tokensStacked L layers → Receptive field = L × W!Constant O(W) KV-Cache size forever!Ring Attention (Multi-GPU 1M Context)Shard sequence across G GPUs in a ringPass K/V blocks around ring while computingOverlaps NVLink comms with FlashAttention!
Beyond FlashAttention, Sliding Window Attention (Mistral) caps local memory at W tokens, while Ring Attention shards 1M-token sequences across multi-GPU rings.

Beyond Single-GPU FlashAttention

  • Sliding Window Attention (Mistral / Gemma 2): Each token attends only to the previous WW tokens (e.g., W=4096W = 4096). Across LL stacked layers, the effective receptive field still grows to L×WL \times W (e.g., 32×4096=131K32 \times 4096 = 131\text{K}), while capping KV-Cache at a fixed ring buffer of size WW!
  • Ring Attention (Context Parallelism): Splits a 1M-token sequence across PP 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!
Walk Through With Me · Interactive Worked Example

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].

11. Process Tile 1 = [1.0, 2.0]Step 1 / 3

m1=2.0m_1 = 2.0, l1=e1−2+e2−2=e−1+1≈1.3679l_1 = e^{1-2} + e^{2-2} = e^{-1} + 1 \approx 1.3679.

Teacher's Note: Computed entirely inside SRAM!
Pause & Check · Quick Intuition Pulse

What is the HBM memory complexity of FlashAttention with respect to sequence length N?

Try It YourselfChallenge

Wait — during backpropagation, FlashAttention recomputes the QK⊤QK^\top tiles from scratch instead of reading saved attention weights from HBM. Why is recomputing actually FASTER than saving them?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

No! FlashAttention still performs O(N2)O(N^2) FLOPs (it computes exact full attention). Its massive 2–4× speedup comes from eliminating O(N2)O(N^2) HBM memory reads/writes, and its 10×+ memory savings come from O(N)O(N) HBM storage!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS FlashAttention Tile Sweeper move K/V tiles into on-chip SRAM and update Online Softmax stats (m, l) past 40% progress.
Interactive Animation • 2.3 Deep Lab

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!

T(0,0)
skip
skip
skip
T(1,0)
T(1,1)
skip
skip
T(2,0)
T(2,1)
T(2,2)
skip
T(3,0)
T(3,1)
T(3,2)
T(3,3)
FlashAttention-2 Advantages
• HBM Memory: O(N) instead of O(N²)
• Causal Block Skipping: skips 50% of tiles!
• Speedup: 2–4× faster wall-clock training & prefill
0%
SRAM Fusing Q_block[0] × KV_block[0]
Intuition Takeaway: FlashAttention tiles Q,K,VQ, K, V into blazing-fast on-chip GPU SRAM and uses exact Online Softmax rescaling to compute full attention in O(N)O(N) HBM memory without ever materializing the N×NN \times N matrix.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Saying FlashAttention reduces attention FLOPs from O(N²) to O(N).
Best Practice: Be precise: FlashAttention reduces HBM memory from O(N2)O(N^2) to O(N)O(N) and drastically cuts HBM IO, while FLOPs remain O(N2)O(N^2) (exact attention)!
Trap #2: Saying FlashAttention approximates softmax.
Best Practice: Emphasize that Online Softmax rescaling (exp(m_old - m_new)) is 100% mathematically exact.
Chapter Mastery Check (+90 XP)
Score: 0 / 2
1Why is FlashAttention dramatically faster than naive PyTorch attention even though both perform O(N²) FLOPs?
2What statistics does FlashAttention maintain per query row to make tiled Online Softmax exact?

Apply What You Learned — Solve Matching Coding Problems