10.5 The Cost of Attention

Long-context language models process tens or hundreds of thousands of tokens in a single pass. Because dense self-attention evaluates a score for every pair of positions, both its arithmetic and its naive memory footprint grow quadratically with sequence length nn. At n=8,192n = 8{,}192, a single head evaluates 6.7×1076.7 \times 10^7 query--key pairs (256 MiB in float32).

For several years, O(n2)O(n^2) memory was widely assumed to be an unavoidable cost of exact attention. Then Rabe and Staats (2021) demonstrated—building on the online softmax algorithm of Milakov and Gimelshein (2018)—that exact attention never requires materializing the n×nn \times n score matrix, and FlashAttention (Dao et al., 2022) turned tiled online softmax into an IO-aware GPU kernel that is both faster than naive attention and linear in memory.

This section counts the FLOPs and memory of dense attention, benchmarks them on a GPU, derives blockwise online softmax, and compares a chunked implementation and fused FlashAttention kernels against naive matrix materialization.

from torch.nn.attention import SDPBackend, sdpa_kernel

10.5.1 Quadratic Time and Memory#

10.5.1.1 Counting FLOPs#

For a multi-head self-attention layer of width dd with HH heads of width dh=d/Hd_h = d/H over nn tokens, the multi-head complexity count (Section 10.3) together with the row-wise softmax gives

8nd2⏟projections  +  4n2d⏟scores and mixing  +  O(Hn2)FLOPs.(10.5.1)\underbrace{8 n d^2}_{\textrm{projections}} \;+\; \underbrace{4 n^2 d}_{\textrm{scores and mixing}} \;+\; O(Hn^2) \quad \textrm{FLOPs}. \tag{10.5.1}

The quadratic 4n2d4n^2 d term (2n2dh2n^2 d_h for QK⊤\mathbf{Q}\mathbf{K}^\top and 2n2dh2n^2 d_h for AV\mathbf{A}\mathbf{V} across HH heads) overtakes the linear 8nd28nd^2 projection term once n>2dn > 2d. For GPT-2 small (d=768d = 768, n=1,024n = 1{,}024), projections still dominate; for a model with d=4,096d = 4{,}096 at n=131,072n = 131{,}072, n/(2d)=16n / (2d) = 16, so scoring and mixing require 16×16\times as many FLOPs as the attention projections (and roughly 5×5\times as many as the entire transformer block once the feed-forward network of Chapter 11 is included, which moves the block crossover to n≈6dn \approx 6d).

10.5.1.2 Counting Memory#

At long contexts, memory often becomes the bottleneck before arithmetic. A naive implementation materializes both the n×nn \times n score matrix and its n×nn \times n softmax weight matrix, consuming 8n28n^2 bytes per head and sequence in float32 (versus O(nd)O(nd) for projections). For one head of width dh=64d_h = 64 at n=8,192n = 8{,}192, Q,K,V\mathbf{Q}, \mathbf{K}, \mathbf{V} occupy just 6 MiB together while the two n×nn \times n buffers consume 512 MiB; at n=131,072n = 131{,}072, a single float32 attention matrix would require 64 GiB. During training, saving attention weights across all 12 layers and 12 heads of GPT-2 small at n=8,192n = 8{,}192 would require 144×256 MiB=36 GiB144 \times 256\textrm{ MiB} = 36\textrm{ GiB} per sequence.

We verify the 8n28n^2-byte scratch footprint on one float32 head (dh=64d_h = 64) using d2l.peak_memory (Section 5.7):

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

Evaluating d2l.peak_memory(attention, Q, Q, Q) across sequence lengths n∈{2048,4096,8192,16384}n \in \{2048, 4096, 8192, 16384\} confirms that each doubling of nn quadruples the temporary memory allocation right in line with 8n28n^2 bytes:

d_h = 64
for n in [2048, 4096, 8192, 16384]:
    Q = torch.randn(n, d_h, device=d2l.try_gpu())
    mem = d2l.peak_memory(attention, Q, Q, Q)  # Allocator high-water mark
    print(f'n = {n:5d}: measured {mem/2**20:7.1f}'
          f' MiB, predicted 8n^2 B = {8*n*n/2**20:7.1f} MiB')
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

10.5.1.3 Measuring Time#

Timing the same forward pass with d2l.Benchmark (Section 5.7) confirms the quadratic runtime growth once nn is large enough to amortize kernel launch latency (n≥8,192n \ge 8{,}192):

for n in [2048, 4096, 8192, 16384]:
    Q = torch.randn(n, d_h, device=d2l.try_gpu())
    print(d2l.Benchmark(lambda: attention(Q, Q, Q), desc=f'n = {n:5d}'))
n =  2048: 0.07 ms/call
n =  4096: 0.46 ms/call
n =  8192: 1.84 ms/call
n = 16384: 7.37 ms/call

10.5.2 Exact Attention Without the Matrix#

10.5.2.1 Blockwise Online Softmax#

At first glance, the softmax denominator ∑j′exp⁡(aj′)\sum_{j'} \exp(a_{j'}) and the numerical-stability row maximum max⁡j′aj′\max_{j'} a_{j'} (Section 3.3.5.2) appear to require all nn scores before any value can be weighted. Online softmax (Milakov and Gimelshein, 2018) avoids this two-pass requirement by processing keys in blocks of size cc and maintaining three running statistics per query: the running maximum score mm, the running denominator sum s=∑jeaj−ms = \sum_j e^{a_j - m}, and the unnormalized output accumulator o=∑jeaj−mvj\mathbf{o} = \sum_j e^{a_j - m} \mathbf{v}_j.

When a new block of scores {aj}\{a_j\} and values {vj}\{\mathbf{v}_j\} arrives, updating the running maximum to m′=max⁡(m,max⁡jaj)m' = \max(m, \max_j a_j) requires rescaling the previously accumulated sum ss and output o\mathbf{o} by em−m′e^{m - m'}:

m′=max⁡(m,max⁡jaj),s′=s em−m′+∑jeaj−m′,o′=o em−m′+∑jeaj−m′ vj.(10.5.2)\begin{aligned} m' &= \max\big(m, \max_j a_j\big), \\ s' &= s\, e^{m - m'} + \sum\nolimits_j e^{a_j - m'}, \\ \mathbf{o}' &= \mathbf{o}\, e^{m - m'} + \sum\nolimits_j e^{a_j - m'}\, \mathbf{v}_j. \end{aligned} \tag{10.5.2}

For example, if block 1 has scores (1,3)(1, 3), then m=3m = 3 and s=e−2+e0≈1.135s = e^{-2} + e^0 \approx 1.135. If block 2 has scores (5,2)(5, 2), the new maximum is m′=5m' = 5, so the block-1 sum is rescaled by e3−5=e−2e^{3 - 5} = e^{-2} and incremented by e5−5+e2−5e^{5 - 5} + e^{2 - 5}, yielding s′=e−4+e−2+e0+e−3≈1.203s' = e^{-4} + e^{-2} + e^0 + e^{-3} \approx 1.203—identical to the standard softmax denominator computed with the global maximum 55 known in advance. After the final block, o/s\mathbf{o} / s equals softmax(a)V\mathrm{softmax}(\mathbf{a})\mathbf{V} up to floating-point round-off, while holding only one n×cn \times c score stripe in memory at a time (Figure 10.5.1, (Rabe and Staats, 2021)).

Figure 10.5.1:

Online softmax processes the score matrix one key block at a time. Of the scores, only the current n×cn \times c stripe is in memory, next to the running maxima, sums and outputs m,s,O\mathbf{m}, \mathbf{s}, \mathbf{O} of all queries; the full n×nn \times n matrix is never stored.

10.5.2.2 A Chunked Implementation#

We compare full-matrix causal_attention against chunked_attention, which steps through key--value blocks of width chunk_size=512 using (10.5.2) (initializing mm and masking future positions with finfo(dtype).min to avoid −∞−(−∞)=NaN-\infty - (-\infty) = \mathrm{NaN} when an entire block is causally masked; see Exercise 2d).

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

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

chunked_attention matches causal_attention to float32 precision (∼10−6\sim 10^{-6}) while reducing peak memory from O(n2)O(n^2) to O(nc)O(nc):

n, d_h = 2048, 64
Q, K, V = (torch.randn(n, d_h, device=d2l.try_gpu()) for _ in range(3))
err = (chunked_attention(Q, K, V) - causal_attention(Q, K, V)).abs().max()
print(f'maximum deviation: {float(err):.2e}')
maximum deviation: 2.38e-07

Comparing d2l.peak_memory across n∈{2048,4096,8192,16384}n \in \{2048, 4096, 8192, 16384\} verifies that chunked_attention replaces the quadratic O(n2)O(n^2) memory curve of causal_attention with linear O(nc)O(nc) scaling:

lengths, mems = [2048, 4096, 8192, 16384], [[], []]
for n in lengths:
    Q = torch.randn(n, d_h, device=d2l.try_gpu())
    mems[0].append(d2l.peak_memory(causal_attention, Q, Q, Q) / 2**20)
    mems[1].append(d2l.peak_memory(chunked_attention, Q, Q, Q) / 2**20)
print(f'n = {n:,}: full matrix {mems[0][-1]:6.1f} MiB, '
      f'chunked {mems[1][-1]:6.1f} MiB')
d2l.plot(lengths, mems, 'sequence length n', 'peak memory (MiB)',
         legend=['full matrix', 'chunked'], xscale='log', yscale='log')
n = 16,384: full matrix 2308.0 MiB, chunked  132.4 MiB

10.5.2.3 Memory Traffic and Fused Kernels#

A GPU's compute units execute matrix arithmetic orders of magnitude faster than its off-chip device memory can transfer data (e.g., on an RTX 4090, ∼165\sim 165 TFLOP/s in float16 versus ∼1\sim 1 TB/s of memory bandwidth; see Chapter 13). Data-center cards build this memory from high-bandwidth memory (HBM) and the RTX 4090 from GDDR6X. We follow the FlashAttention paper and write HBM for the device memory of either kind. Naive attention is memory-bandwidth bound: it writes the n×nn \times n score matrix to HBM, reads it back for softmax, writes the n×nn \times n weights to HBM, and reads them again to multiply by V\mathbf{V}—moving 4n24n^2 floats across HBM with low arithmetic intensity (Exercises 4 and 5). Because a Python loop like chunked_attention still launches separate GPU kernels that read and write every n×cn \times c stripe to HBM, it reduces peak memory allocation without reducing total HBM traffic.

FlashAttention (Dao et al., 2022) tiles both queries and keys so that each score block and its running statistics (m,s,o)(m, s, \mathbf{o}) reside entirely in fast on-chip SRAM throughout the loop, never touching HBM. For the backward pass, instead of saving n×nn \times n attention weights, the forward pass stores only the scalar log-normalizer ℓ=m+log⁡s\ell = m + \log s per query (O(n)O(n) memory) and recomputes the score tiles on chip during backpropagation.

We benchmark the framework-provided fused FlashAttention kernel against causal_attention on B=2B = 2 sequences, H=8H = 8 heads, dh=64d_h = 64, and n=8,192n = 8{,}192 in float16. Including an unmasked fused run separates the O(n2)O(n^2) HBM-traffic speedup from the ∼1.5×\sim 1.5\times speedup of skipping upper-triangular causal tiles:

The fused kernel is F.scaled_dot_product_attention.

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

The fused kernel reduces temporary memory from ∼4\sim 4 GiB (16⋅4n216 \cdot 4n^2 bytes) to a small multiple of the 16 MiB output and runs several times faster close to the GPU's peak matrix throughput. Even with fused kernels, however, exact attention still performs Θ(n2d)\Theta(n^2 d) arithmetic operations; achieving linear time complexity requires changing the attention mechanism itself (Section 10.6).

10.5.3 Summary#

Dense self-attention requires 8nd2+4n2d8nd^2 + 4n^2d FLOPs per layer, so its quadratic score-and-mix work overtakes the linear projections once n>2dn > 2d. Worse still, materializing the n×nn \times n score and weight matrices allocates 8n28n^2 bytes per head in float32 and renders naive attention memory-bandwidth bound on modern GPUs. Online softmax eliminates both n×nn \times n buffers without approximation by processing keys in blocks and maintaining a running maximum mm, normalizer ss, and value accumulator o\mathbf{o} whose partial sums rescale by em−m′e^{m - m'} whenever mm increases. FlashAttention fuses this tiled recurrence inside fast on-chip SRAM, reducing off-chip memory to O(n)O(n) and achieving multi-fold wall-clock speedups while preserving exact attention and its Θ(n2d)\Theta(n^2 d) arithmetic count.

10.5.4 Exercises#

  1. Online softmax by hand. One query meets four keys in two blocks of two. Its scores are (0,2)(0, 2) in the first block and (1,3)(1, 3) in the second, and the values are the numbers 1,21, 2 in the first block and 3,43, 4 in the second.

    1. Apply (10.5.2) block by block, starting from m=−∞m = -\infty, s=0s = 0 and o=0o = 0. Record mm, ss and oo after each block, and divide to obtain the output.
    2. Compute the four softmax weights directly, and check that they give the same output.
    3. After the last block, form ℓ=m+log⁡s\ell = m + \log s and recompute each of the four weights as eaj−ℓe^{a_j - \ell} from its score alone. Check that they agree with the weights of the previous part and sum to one, and explain why a fused kernel's backward pass can keep ℓ\ell instead of mm and ss.
  2. [code] The running maximum. Remove the running maximum from chunked_attention, so that the state accumulates plain sums of eaje^{a_j}. Run the result with Q\mathbf{Q}, K\mathbf{K}, V\mathbf{V} and the state ss, O\mathbf{O} in float16, on queries scaled up by a factor of 1010.

    1. Before running, compute the largest exponent xx for which exe^x is finite in float16, and estimate the fraction of scaled scores that exceed it when queries and keys of width 6464 have independent standard normal entries.
    2. Run the modified function, and report at which operation the first infinite or undefined value appears.
    3. Explain why carrying mm bounds every exponent by zero. A term eaj−m′e^{a_j - m'} that is smaller than the smallest positive float16 number rounds to zero. Bound the total contribution of such terms to ss, relative to the term of the largest score, for a row of nn keys.
    4. chunked_attention initializes mm with the most negative finite value of the dtype and masks scores with the same value. Take n=2cn = 2c for blocks of cc keys, and let the loop visit the two key blocks in reverse order, so that every score of the first visited block is masked for a query in the first block. Trace mm, ss, and O\mathbf{O} for that query through both iterations, and show that the final output is still exact.
  3. Merging partial states. Fix one query with scores aja_j and values vj\mathbf{v}_j. For a set BB of keys, call the triple (mB,sB,oB)(m_B, s_B, \mathbf{o}_B) that (10.5.2) produces from the keys in BB alone the partial state of BB, so that oB/sB\mathbf{o}_B / s_B is the attention output restricted to BB.

    1. Derive the partial state of B∪B′B \cup B' for disjoint sets BB and B′B' from the two partial states, and show that (10.5.2) is the special case in which B′B' is a single block.
    2. Show that this merge is associative and commutative. Conclude that the key blocks can be processed in any order, or in parallel and merged in a tree of depth ⌈log⁡2(n/c)⌉\lceil \log_2 (n/c) \rceil for blocks of cc keys, and explain why this matters when a single query attends to a long cache during generation.
    3. Replace the pair (mB,sB)(m_B, s_B) by the single number ℓB=mB+log⁡sB\ell_B = m_B + \log s_B and the triple by (ℓB,oˉB)(\ell_B, \bar{\mathbf{o}}_B) with oˉB=oB/sB\bar{\mathbf{o}}_B = \mathbf{o}_B / s_B. Express the merged ℓ\ell and oˉ\bar{\mathbf{o}} in these terms, and show that oˉ\bar{\mathbf{o}} is a convex combination of oˉB\bar{\mathbf{o}}_B and oˉB′\bar{\mathbf{o}}_{B'} whose weights depend only on ℓB\ell_B and ℓB′\ell_{B'}.
  4. Arithmetic intensity of attention. Consider one head with nn queries and keys of width dhd_h and values of width dvd_v. Its two matrix products, QK⊤\mathbf{Q}\mathbf{K}^\top and the product of the weights with V\mathbf{V}, cost 2n2dh2n^2 d_h and 2n2dv2n^2 d_v floating-point operations, and the softmax costs a few operations per score.

    1. Suppose that the score matrix is written to memory once and read once by the softmax, whose output is written once and read once by the value product, all in single precision. Count the bytes moved by these four passes, and by reading Q\mathbf{Q}, K\mathbf{K}, V\mathbf{V} and writing the output.
    2. Neglecting the softmax arithmetic, form the ratio of operations to bytes and let n→∞n \to \infty at fixed dhd_h and dvd_v. Show that the limit is (dh+dv)/8(d_h + d_v)/8, and state how the softmax arithmetic changes it.
    3. Redo the limit for inputs and scores in a 16-bit format. Take the 16-bit throughput and the memory bandwidth of an H100 or a B200 from Table 13.2.1, compute the ratio of operations per byte, and decide whether attention with dh=dv=64d_h = d_v = 64 is limited by arithmetic or by memory traffic on it.
  5. Traffic of a tiled schedule. ● By Exercise 4a, the naive layer moves 4n24n^2 floats to and from main memory beyond the terms linear in nn, since the score matrix and the weight matrix are each written once and read once. Ignore all traffic that is linear in nn.

    1. Suppose that chunked_attention runs one operation at a time, each reading its inputs from main memory and writing its output back. Count, as functions of nn, cc, and dhd_h, the floats moved for the score stripes, the floats moved for Q\mathbf{Q} and the accumulator O\mathbf{O}, and the number of operations launched. Which of these quantities does chunking reduce relative to the naive layer?
    2. A fused kernel instead holds a tile of bb queries, their output accumulator, and one tile each of bb keys and bb values in a fast memory of MM floats, so that 4bdh≤M4bd_h \leq M; the scores of a tile and the running mm and ss stay in fast memory as well. It loads each query tile once, streams all key and value tiles past it, and writes each output tile once. Show that its traffic beyond the linear terms is 2n2dh/b2n^2 d_h / b floats and that the largest admissible tile gives Θ(n2dh2/M)\Theta(n^2 d_h^2 / M), the bound that Dao et al. (2022) prove for FlashAttention.
    3. Compute the ratio of the fused traffic to the naive traffic for dh∈{64,128,256}d_h \in \{64, 128, 256\} with M=216M = 2^{16}, and state how the head width limits the benefit of tiling.

Discussions