The Cost of Attention

Dive into Deep Learning · §10.5

Attention at Scale: Memory Bandwidth, Online Softmax, and FlashAttention
quadratic FLOP & memory scaling · arithmetic intensity · blockwise online softmax · SRAM tiling · FlashAttention

Why Long-Context Attention Hits a Memory Wall

Motivation

  • Quadratic Scratch Footprint (8n^2 Bytes/Head in FP32): Materializing the n \times n score and softmax weight matrices consumes 8\text{ MiB} at n = 1{,}024, 512\text{ MiB} at n = 8{,}192, and 128\text{ GiB} per head at n = 131{,}072.
  • Training Multiplier: Saving weights across all 144 heads of GPT-2 small at n = 8{,}192 requires 36\text{ GiB} per sequence.
  • The Breakthrough: Online softmax (Milakov & Gimelshein, 2018; Rabe & Staats, 2021) and FlashAttention (Dao et al., 2022) compute exact attention in O(n) memory.

Counting FLOPs: When Scores Overtake Projections

Arithmetic Scaling

  • Per-Layer FLOP Decomposition: \textrm{FLOPs} = 8 n d^2 + 4 n^2 d + O(H n^2)
  • The Crossover Ratio: Dividing quadratic score-and-mix work (4n^2d) by linear projection work (8nd^2) gives n / (2d).
  • Short vs. Long Contexts: At d = 768, n = 1{,}024, projections dominate (n/2d = 0.67); at d = 4{,}096, n = 131{,}072, attention scoring and mixing cost 16\times more FLOPs than all projections combined.

Counting Memory: The 8n²-Byte Scratch Footprint

Memory Allocation

Why does naive attention allocate 8n^2 bytes of temporary memory per head in float32?

  • Two n \times n Materializations: scores = Q @ K.T / sqrt(d_h) allocates 4n^2 bytes, and softmax(scores) allocates a second 4n^2-byte buffer for the weights before multiplying by V.
  • Inputs Are Tiny by Comparison: At n = 8{,}192, d_h = 64, the input tensors \mathbf{Q}, \mathbf{K}, \mathbf{V} occupy only 3 \times 8{,}192 \times 64 \times 4\text{ B} = 6\text{ MiB}, while the two n \times n buffers consume 512\text{ MiB} (85\times larger).
def attention(Q, K, V):
    """softmax(Q K^T / sqrt(d_h)) V through the full score matrix."""
    scores = Q @ K.transpose(-2, -1) / math.sqrt(Q.shape[-1])
    return torch.softmax(scores, dim=-1) @ V

Measuring Quadratic Memory and Runtime on a GPU

Empirical Benchmarks

Measuring peak scratch memory (d2l.peak_memory) and wall-clock execution time (d2l.Benchmark) on a single float32 head (d_h = 64) confirms the exact 8n^2 byte footprint and 4\times time jump per doubling of n:

n =  2048: measured    40.6 MiB, predicted 8n^2 B =    32.0 MiB
n =  4096: measured   129.0 MiB, predicted 8n^2 B =   128.0 MiB
n =  8192: measured   514.0 MiB, predicted 8n^2 B =   512.0 MiB
n = 16384: measured  2052.0 MiB, predicted 8n^2 B =  2048.0 MiB
n =  2048: 0.07 ms/call
n =  4096: 0.46 ms/call
n =  8192: 1.84 ms/call
n = 16384: 7.37 ms/call

Why Naive Softmax Seems to Require Two Passes

The Two-Pass Bottleneck

  • Two Global Statistics Needed: Standard stable softmax requires the global row maximum m = \max_j a_j and denominator s = \sum_j \exp(a_j - m) before weighting any value \mathbf{v}_j.
  • Why Must We Keep m? Without subtracting m, \exp(a_j) overflows float16 above a_j \approx 11.09 and float32 above a_j \approx 88.7.
  • The Online Insight: Process keys in blocks and rescale running sums whenever a new block contains a larger maximum m' > m.

Deriving Blockwise Online Softmax

Online Softmax Recurrence

  • Three Running Statistics per Query: Running maximum m, unnormalized sum s = \sum_j e^{a_j - m}, and unnormalized output \mathbf{o} = \sum_j e^{a_j - m}\mathbf{v}_j.
  • Block Update Rule: m' = \max\!\big(m, \max_j a_j\big), \quad s' = s\,e^{m - m'} + \sum_j e^{a_j - m'} \mathbf{o}' = \mathbf{o}\,e^{m - m'} + \sum_j e^{a_j - m'}\mathbf{v}_j
  • Exact Output: After all blocks, \mathbf{o} / s = \mathrm{softmax}(\mathbf{a})\mathbf{V}.

Worked Example: Online Softmax Across Two Blocks

Step-by-Step Numerical Trace

  • Block 1 (scores 1, 3): Sets m_1 = 3 and s_1 = e^{-2} + e^0 \approx 1.1353.
  • Block 2 (scores 5, 2): Updates maximum to m_2 = \max(3, 5) = 5, rescales s_1 by e^{3-5} = e^{-2}, and adds e^0 + e^{-3} to reach s_2 \approx 1.2034.
  • Associative & Commutative: Processing Block 2 before Block 1 keeps m = 5 (e^{m-m'} = 1) and yields the exact same sum 1.2034.

Visualizing Striped Online Softmax Memory

Linear Working Memory

  • One Stripe at a Time: Instead of materializing the n \times n score matrix, we hold only one n \times c score stripe for the current block of c keys.
  • Running Query State: Alongside the stripe, we store \mathbf{m} \in \mathbb{R}^{n \times 1}, \mathbf{s} \in \mathbb{R}^{n \times 1}, and \mathbf{O} \in \mathbb{R}^{n \times d_v} (O(n d_v) floats total).
  • Memory Reduction: Peak score memory drops from O(n^2) to O(nc), which is linear in n for fixed block size c.

Online softmax sweeps an n × c stripe across key blocks while updating m, s, and O.

Implementing Chunked Causal Attention

Code Implementation

The reference causal_attention materializes the full n \times n score matrix; it is the baseline every faster kernel must match:

def causal_attention(Q, K, V):
    """Reference: causal attention with the full score matrix."""
    scores = Q @ K.transpose(-2, -1) / math.sqrt(Q.shape[-1])
    mask = d2l.causal_mask(Q.shape[-2], device=Q.device)
    scores.masked_fill_(~mask, torch.finfo(Q.dtype).min)
    return torch.softmax(scores, dim=-1) @ V

Implementing Chunked Causal Attention (cont.)

Code Implementation

Masking with finfo(dtype).min, not -\infty, keeps fully masked blocks free of -\infty - (-\infty) = \mathrm{NaN}:

def chunked_attention(Q, K, V, chunk_size=512):
    """Exact causal attention, one n-by-chunk_size block at a time."""
    n, d_h = Q.shape
    m = torch.full((n, 1), torch.finfo(Q.dtype).min, device=Q.device)
    s = torch.zeros(n, 1, device=Q.device)
    O = torch.zeros(n, V.shape[-1], device=Q.device)
    pos_q = torch.arange(n, device=Q.device)[:, None]
    for start in range(0, n, chunk_size):
        Kc, Vc = K[start:start + chunk_size], V[start:start + chunk_size]
        pos_k = torch.arange(start, start + Kc.shape[0], device=Q.device)
        scores = Q @ Kc.T / math.sqrt(d_h)
        scores.masked_fill_(pos_k[None, :] > pos_q, torch.finfo(Q.dtype).min)
        m_new = torch.maximum(m, scores.max(dim=-1, keepdim=True).values)
        scale = torch.exp(m - m_new)                  # Rescale the past
        P = torch.exp(scores - m_new)
        s = s * scale + P.sum(dim=-1, keepdim=True)
        O = O * scale + P @ Vc
        m = m_new
    return O / s

Verifying Exactness and Linear Memory Growth

Chunked vs. Full-Matrix Benchmark

  • Exact to Machine Precision: At n = 2{,}048, d_h = 64, chunked_attention matches causal_attention within \sim 10^{-7} (float32 rounding):
maximum deviation: 2.38e-07
  • Quadratic \to Linear Memory: At n = 16{,}384, full-matrix attention consumes 2{,}048\text{--}2{,}308\text{ MiB} (>2\text{ GiB}), whereas chunked_attention (c = 512) uses \approx 36\text{--}132\text{ MiB} (>17\times less).

n = 16,384: full matrix 2308.0 MiB, chunked  132.4 MiB

The Hardware Bottleneck: GPU HBM vs. On-Chip SRAM

GPU Memory Hierarchy

  • Tensor Cores vs. HBM: A GPU executes \sim 165–1{,}000\text{ TFLOP/s} in 16-bit matrix arithmetic, while off-chip device memory transfers only \sim 1.0\text{ TB/s} (GDDR6X, RTX 4090) to 3.35\text{ TB/s} (HBM, H100): \sim 164 FLOPs per byte transferred on the RTX 4090. We write HBM for either kind.
  • On-Chip SRAM (tens of \text{TB/s}): Registers and L1/shared memory are an order of magnitude faster than device memory but hold only \sim 0.1\text{ GB} in total.
  • Why Python Chunking Is Still Slow: Launching separate kernels reads and writes every n \times c stripe to slow HBM.

Arithmetic Intensity of Naive Attention

Roofline Analysis

  • Four HBM Passes Over n^2 Floats: Naive attention writes \mathbf{S} to HBM, reads \mathbf{S} for softmax, writes \mathbf{A} to HBM, and reads \mathbf{A} to multiply by \mathbf{V}.
  • Low Arithmetic Intensity: \textrm{Intensity} \;\xrightarrow{n \to \infty}\; \frac{d_h + d_v}{4}\;\textrm{FLOPs/byte (fp16)}
  • Memory-Bound Regime: For d_h = d_v = 64 in FP16, intensity is only 32\text{ FLOPs/byte}—far below the \sim 164\text{ FLOPs/byte} ridge point of the RTX 4090.

FlashAttention: Tiling Queries and Keys in SRAM

IO-Aware Kernel Fusion

  • Zero HBM Score Traffic: FlashAttention loads a query tile \mathbf{Q}_i and (m_i, s_i, \mathbf{O}_i) into on-chip SRAM, streams (\mathbf{K}_j, \mathbf{V}_j) tiles from HBM, and writes \mathbf{O}_i / s_i to HBM only once.
  • HBM Traffic Bound: Choosing max tile size b \propto M / d_h cuts quadratic HBM traffic from 4n^2 to \Theta(n^2 d_h^2 / M) floats.
  • O(n) Backward Recomputation: Saves only \ell_i = m_i + \log s_i (1 float/query) and recomputes \alpha_{ij} = \exp(a_{ij} - \ell_i) on chip during backprop.

Benchmarking Fused FlashAttention vs. Naive Attention

Code & Wall-Clock Speedup

We benchmark causal_attention against the framework’s fused FlashAttention kernel on B = 2 sequences, H = 8 heads, d_h = 64, and n = 8{,}192 in float16:

def fused_attention(Q, K, V, is_causal=True):
    """Attention in PyTorch's fused FlashAttention kernel."""
    with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
        return F.scaled_dot_product_attention(Q, K, V, is_causal=is_causal)

B, H, n = 2, 8, 8192
X = torch.randn(B, H, n, d_h, device=d2l.try_gpu(), dtype=torch.float16)
# The unmasked kernel computes every tile: it shows what skipping saves
for name, f in [('naive', causal_attention), ('fused', fused_attention),
                ('fused, no mask',
                 lambda Q, K, V: fused_attention(Q, K, V, is_causal=False))]:
    t = d2l.Benchmark(lambda: f(X, X, X)).time
    mem = d2l.peak_memory(f, X, X, X)
    print(f'{name:>14}: {t*1e3:6.2f} ms, peak memory {mem/2**20:7.1f} MiB')
         naive:  19.95 ms, peak memory  4176.0 MiB
         fused:   1.08 ms, peak memory    16.5 MiB
fused, no mask:   1.72 ms, peak memory    16.5 MiB

Analyzing the Fused Kernel Speedup and Causal Skipping

Dissecting the Benchmark

Comparing naive, fused (causal), and fused, no mask separates two distinct sources of speedup:

  • 1. Eliminating HBM Score Traffic (naive \to fused, no mask): Cuts peak temporary memory from \sim 4{,}096\text{ MiB} (16 \times 4n^2 bytes) down to a small multiple of the 16\text{ MiB} output tensor (> 80\times memory reduction) and speeds up execution several-fold by running near peak Tensor Core throughput (2.7 \times 10^{11}\text{ FLOPs}).
  • 2. Causal Tile Skipping (fused, no mask \to fused): Because a causal mask zeroes all entries above the diagonal (j > i), a tiled kernel skips the entire upper triangle of empty tiles without computing them.
  • Why Causal Skipping Gives \sim 1.5\times Instead of 2\times: Diagonal tiles straddle j = i and must apply elementwise masking, and thread-block scheduling across variable-length causal rows incurs small load-balancing overhead.

What Fused Kernels Solve—and What Remains O(n²)

Architectural Perspective

  • What FlashAttention solves: Eliminates the \Theta(n^2) HBM score and weight matrices, reducing peak scratch memory to \Theta(n d_h) and HBM traffic to \Theta(n^2 d_h^2 / M).
  • What remains \Theta(n^2): Total arithmetic FLOPs still scale as \Theta(n^2 d), and the autoregressive KV cache still grows as O(n d)—motivating sliding windows and linear attention (§10.6).

Concept Check: Online Softmax and Memory Traffic

Check Your Understanding

Work through these three systems and algorithmic questions:

  1. Log-Sum-Exp Backward Reconstruction: After the final block of online softmax produces (m, s, \mathbf{o}), how can the backward pass recover the exact softmax weight \alpha_j of key j from its score a_j and the single stored scalar \ell = m + \log s?
  2. Float16 Overflow Without Running Max: In float16 (max finite value 65{,}504 \approx e^{11.09}), what happens if you accumulate raw \sum_j e^{a_j} without subtracting the running maximum m when a scaled score reaches a_j = 12?
  3. Tile Size vs. Head Width: Using FlashAttention’s HBM traffic bound \Theta(n^2 d_h^2 / M) for on-chip SRAM size M, how does doubling the head width from d_h = 64 to d_h = 128 (at fixed total width d) affect the maximum tile size b and HBM traffic?

Concept Check: Online Softmax and Memory Traffic (answers)

Check Your Understanding

Answers:

  1. \alpha_j = \exp(a_j - \ell), because \exp(a_j - m - \log s) = \exp(a_j - m) / s = \alpha_j, requiring only 1 float per query instead of (m, s) or all n weights.
  2. Immediate overflow to inf, followed by inf / inf = NaN in the output normalizer. Carrying m guarantees a_j - m' \le 0 so every exponential lies in (0, 1].
  3. Tile size b \le M / (4d_h) halves, so twice as many passes over \mathbf{K}, \mathbf{V} are needed and quadratic HBM traffic increases (by 2\times per head, or 4\times at fixed head count).

Summary: The Computational Cost of Attention

Key Takeaways

  • The O(n^2) HBM Wall: Naive attention allocates 8n^2 bytes per head (128\text{ GiB} at n = 128\text{K}) and is severely HBM-bandwidth bound.
  • Online Softmax Recurrence: Updates running (m, s, \mathbf{o}) in one streaming pass via e^{m - m'} rescaling.
  • FlashAttention Tiling: Fuses \mathbf{Q}\mathbf{K}^\top, softmax, and \mathbf{P}\mathbf{V} inside on-chip SRAM in \Theta(n) HBM memory while skipping empty upper-triangular causal tiles.