Skip to main content
← PROBLEMS / ML-SYSTEMS
An end-to-end domain learning journey

FlashAttention: IO-Aware
Exact Attention.

FlashAttention eliminates the 68.7 GB O(N^2) HBM attention matrix by tiling Q, K, V into ~192 KB GPU SRAM blocks and computing exact attention in O(N) HBM memory via streaming online softmax rescaling.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, tile Q, K, V into on-chip SRAM and maintain running max (m_i) and denominator (l_i) for exact online softmax—cutting HBM memory from O(N^2) to O(N) and bypassing HBM bandwidth bottlenecks.

TL;DR30-second simplified summary
▾

Core Mechanics: Standard attention computes S=QKT/dS = QK^T / \sqrt{d}, P=softmax(S)P = \text{softmax}(S), and O=PVO = PV.

Visual & Structural Flow: Depicts HBM (80GB, 3 TB/s) <-> On-Chip SRAM (228KB, 19 TB/s) Tiled Fusion (HBM Q, K, V -> SM SRAM Tile -> Online Softmax -> HBM Output O); Streaming K_j, V_j Tiles Through SRAM Without Materializing N x N (GPU HBM -> SM SRAM -> Tensor Cores).

Trade-Offs & Production: Two naive workarounds compromise either accuracy or memory: Sparse / Linear Attention: Approximates softmax, degrading long-context retrieval accuracy. FlashAttention achieves exact attention in O(N) HBM memory: Outer/Inner Tiling: Partition QQ into blocks of size BrB_r and K,VK, V into blocks of size BcB_c sized to fit in 192 KB SRAM (d = 128).

Failure Modes & Application: FlashAttention is the core kernel behind modern long-context LLM training and inference: Long-Context LLM Training (32k–1M tokens): Enables training without hitting 80 GB HBM OOMs.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why standard O(N^2) attention hits the GPU HBM memory wall.

Why this matters: The mechanism: understand how Why standard O(N^2) attention hits the GPU HBM memory wall works from first principles.

Standard attention computes S=QKT/dS = QK^T / \sqrt{d}, P=softmax(S)P = \text{softmax}(S), and O=PVO = PV.

At sequence length N=32,768N = 32,768 with $32$ heads in FP16, materializing SS and PP in off-chip GPU HBM consumes $32 \times 32,768^2 \times 2\text{ bytes} = 68.7\text{ GB}$ per layer—exceeding an 80 GB H100/A100 and wasting ~10× slower HBM bandwidth (1.5–3.35 TB/s vs.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens when S and P are materialized in HBM.

Why this matters: The problem: see what breaks without What happens when S and P are materialized in HBM under real concurrency or scale.

Unfused attention kernels suffer two fatal bottlenecks at long context (32k–64k):

  1. O(N^2) HBM OOM: Storing SS and PP for activations causes immediate CUDA Out-of-Memory during training/prefill.
  2. Memory-Bandwidth Bound: Launching separate matmul, mask, softmax, and dropout kernels reads/writes N2N^2 matrices to HBM repeatedly while Tensor Cores sit idle.
GPU Memory Hierarchy

HBM (80GB, 3 TB/s) <-> On-Chip SRAM (228KB, 19 TB/s) Tiled Fusion

HBM Q, K, VO(N*d) inputs onlySM SRAM TileBr x Bc S_ij, P_ijOnline SoftmaxRescale m_i, l_i, O_iHBM Output OO(N*d) + (m, l)

1.Zero N x N in HBM: S_ij and P_ij tiles live strictly in 192–228 KB SM SRAM and are discarded.

2.Online Softmax: Rescales running max m_i and sum l_i across K/V blocks with exact equivalence.

3.O(N) Backward: Saves only O(N) log-sum-exp stats (m, l) to recompute P_ij in SRAM on backward.

4.3x-7x Speedup: Fusing matmul + softmax + PV in SRAM converts bandwidth-bound ops to compute-bound.

Keeping S_ij and P_ij tiles inside fast SM SRAM reduces HBM memory from O(N^2) to O(N) with zero mathematical approximation.

Engineering Decision Framework
Problem
How to implement FlashAttention: IO-Aware Exact Attention without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, tile Q, K, V into on-chip SRAM and maintain running max (m_i) and denominator (l_i) for exact online softmax—cutting HBM memory from O(N^2) to O(N) and bypassing HBM bandwidth bottlenecks.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When FlashAttention: IO-Aware Exact Attention experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why sparse/linear approximations or standard fusion fail).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

Two naive workarounds compromise either accuracy or memory:

  • Sparse / Linear Attention: Approximates softmax, degrading long-context retrieval accuracy.
  • Row-wise Softmax Without Tiling: Still requires holding full NN-length rows in SRAM, which overflows the 192–228 KB SM SRAM budget at N=65,536N = 65,536.
Component Topology

Naive solution (and why sparse/linear approximations or standard fusion fail)

Caller / AgentingressLLM GatewaycomputeRadix / VectorstorageGPU Poolcontrolpromptprefix / RAGbatched decode
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Tiled Online Softmax + SRAM Kernel Fusion + Recomputation.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

FlashAttention achieves exact attention in O(N) HBM memory:

  • Outer/Inner Tiling: Partition QQ into blocks of size BrB_r and K,VK, V into blocks of size BcB_c sized to fit in 192 KB SRAM (d = 128).
  • Online Softmax Rescaling: For each Kj,VjK_j, V_j tile, compute Sij=QiKjT/dS_{ij} = Q_i K_j^T / \sqrt{d} in SRAM, update minew=max⁡(mi,rowmax(Sij))m_i^{\text{new}} = \max(m_i, \text{rowmax}(S_{ij})), rescale prior accumulator OiO_i and lil_i by emi−minewe^{m_i - m_i^{\text{new}}}, and accumulate P~ijVj\tilde{P}_{ij} V_j in FP32.
  • Backward Recomputation: Store only (mi,li)(m_i, l_i) (O(N)) in HBM; during backward pass, recompute Sij,PijS_{ij}, P_{ij} on-the-fly in SRAM.
Tiled Online Softmax Loop

Streaming K_j, V_j Tiles Through SRAM Without Materializing N x N

GPU HBMSM SRAMTensor Cores1. Load Q_i tile (Br x d)2. Stream K_j, V_j tile (Bc x d)3. Compute S_ij, rescale (m_i,l_i), update O_i4. Write final O_i + (m_i, l_i)only (O(N))

Each Q_i block accumulates exact softmax-weighted V across all K_j, V_j tiles using only O(Br * Bc) SRAM.

import numpy as np

def flash_attention_exact(Q: np.ndarray, K: np.ndarray, V: np.ndarray, Br: int = 64, Bc: int = 64) -> np.ndarray:
    """Exact IO-aware tiled attention with online softmax rescaling (single head)."""
    N, d = Q.shape
    scale = 1.0 / np.sqrt(d)
    O = np.zeros((N, d), dtype=np.float32)
    l = np.zeros((N, 1), dtype=np.float32)
    m = np.full((N, 1), -np.inf, dtype=np.float32)

    for i in range(0, N, Br):
        Qi = Q[i:i+Br].astype(np.float32)
        Oi = np.zeros((Qi.shape[0], d), dtype=np.float32)
        li = np.zeros((Qi.shape[0], 1), dtype=np.float32)
        mi = np.full((Qi.shape[0], 1), -np.inf, dtype=np.float32)

        for j in range(0, N, Bc):
            Kj = K[j:j+Bc].astype(np.float32)
            Vj = V[j:j+Bc].astype(np.float32)
            Sij = (Qi @ Kj.T) * scale
            m_tile = np.max(Sij, axis=1, keepdims=True)
            m_new = np.maximum(mi, m_tile)
            P_tilde = np.exp(Sij - m_new)
            alpha = np.exp(mi - m_new)
            li = alpha * li + np.sum(P_tilde, axis=1, keepdims=True)
            Oi = alpha * Oi + P_tilde @ Vj
            mi = m_new

        O[i:i+Br] = Oi / li
        l[i:i+Br], m[i:i+Br] = li, mi
    return O
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where IO-Aware Tiled Attention applies in ML Systems.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

FlashAttention is the core kernel behind modern long-context LLM training and inference:

  • Long-Context LLM Training (32k–1M tokens): Enables training without hitting 80 GB HBM OOMs.
  • High-Throughput LLM Serving (vLLM / TensorRT-LLM): Paired with PagedAttention for fast prefill and decode.
  • Multimodal & Video Transformers: Scaling exact attention to high-resolution image/video token sequences.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

How does FlashAttention reduce HBM memory from O(N^2) to O(N) while still computing mathematically exact softmax attention?

Recommended Learning Flow