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 . At , a single head evaluates query--key pairs (256 MiB in float32).
For several years, 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 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_kernel10.5.1 Quadratic Time and Memory#
10.5.1.1 Counting FLOPs#
For a multi-head self-attention layer of width with heads of width over tokens, the multi-head complexity count (Section 10.3) together with the row-wise softmax gives
The quadratic term ( for and for across heads) overtakes the linear projection term once . For GPT-2 small (, ), projections still dominate; for a model with at , , so scoring and mixing require as many FLOPs as the attention projections (and roughly as many as the entire transformer block once the feed-forward network of Chapter 11 is included, which moves the block crossover to ).
10.5.1.2 Counting Memory#
At long contexts, memory often becomes the bottleneck before arithmetic. A naive implementation materializes both the score matrix and its softmax weight matrix, consuming bytes per head and sequence in float32 (versus for projections). For one head of width at , occupy just 6 MiB together while the two buffers consume 512 MiB; at , 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 would require per sequence.
We verify the -byte scratch footprint on one float32 head ()
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) @ VEvaluating d2l.peak_memory(attention, Q, Q, Q) across sequence lengths confirms that each doubling of quadruples the temporary memory allocation right in line with 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 is large enough to amortize
kernel launch latency ():
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 and the numerical-stability row maximum (Section 3.3.5.2) appear to require all 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 and maintaining three running statistics per query: the running maximum score , the running denominator sum , and the unnormalized output accumulator .
When a new block of scores and values arrives, updating the running maximum to requires rescaling the previously accumulated sum and output by :
For example, if block 1 has scores , then and . If block 2 has scores , the new maximum is , so the block-1 sum is rescaled by and incremented by , yielding —identical to the standard softmax denominator computed with the global maximum known in advance. After the final block, equals up to floating-point round-off, while holding only one score stripe in memory at a time (Figure 10.5.1, (Rabe and Staats, 2021)).
Online softmax processes the score matrix one key block at a time. Of the scores, only the current stripe is in memory, next to the running maxima, sums and outputs of all queries; the full 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 and masking future positions with
finfo(dtype).min to avoid 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 / schunked_attention matches causal_attention to float32 precision () while reducing peak memory from to :
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 verifies that chunked_attention replaces the quadratic memory curve of causal_attention with linear 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,
TFLOP/s in float16 versus 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 score matrix to HBM, reads it back for softmax,
writes the weights to HBM, and reads them again to multiply by
—moving 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 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 reside entirely in fast on-chip SRAM throughout the loop, never touching HBM. For the backward pass, instead of saving attention weights, the forward pass stores only the scalar log-normalizer per query ( memory) and recomputes the score tiles on chip during backpropagation.
We benchmark the framework-provided fused FlashAttention kernel
against causal_attention on
sequences, heads, , and in float16. Including
an unmasked fused run separates the HBM-traffic speedup from the
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 GiB ( 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 arithmetic operations; achieving linear time complexity requires changing the attention mechanism itself (Section 10.6).
10.5.3 Summary#
Dense self-attention requires FLOPs per layer, so its quadratic score-and-mix work overtakes the linear projections once . Worse still, materializing the score and weight matrices allocates bytes per head in float32 and renders naive attention memory-bandwidth bound on modern GPUs. Online softmax eliminates both buffers without approximation by processing keys in blocks and maintaining a running maximum , normalizer , and value accumulator whose partial sums rescale by whenever increases. FlashAttention fuses this tiled recurrence inside fast on-chip SRAM, reducing off-chip memory to and achieving multi-fold wall-clock speedups while preserving exact attention and its arithmetic count.
10.5.4 Exercises#
-
Online softmax by hand. One query meets four keys in two blocks of two. Its scores are in the first block and in the second, and the values are the numbers in the first block and in the second.
- Apply (10.5.2) block by block, starting from , and . Record , and after each block, and divide to obtain the output.
- Compute the four softmax weights directly, and check that they give the same output.
- After the last block, form and recompute each of the four weights as 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 instead of and .
-
[code] The running maximum. Remove the running maximum from
chunked_attention, so that the state accumulates plain sums of . Run the result with , , and the state , in float16, on queries scaled up by a factor of .- Before running, compute the largest exponent for which is finite in float16, and estimate the fraction of scaled scores that exceed it when queries and keys of width have independent standard normal entries.
- Run the modified function, and report at which operation the first infinite or undefined value appears.
- Explain why carrying bounds every exponent by zero. A term that is smaller than the smallest positive float16 number rounds to zero. Bound the total contribution of such terms to , relative to the term of the largest score, for a row of keys.
chunked_attentioninitializes with the most negative finite value of the dtype and masks scores with the same value. Take for blocks of 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 , , and for that query through both iterations, and show that the final output is still exact.
-
Merging partial states. Fix one query with scores and values . For a set of keys, call the triple that (10.5.2) produces from the keys in alone the partial state of , so that is the attention output restricted to .
- Derive the partial state of for disjoint sets and from the two partial states, and show that (10.5.2) is the special case in which is a single block.
- 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 for blocks of keys, and explain why this matters when a single query attends to a long cache during generation.
- Replace the pair by the single number and the triple by with . Express the merged and in these terms, and show that is a convex combination of and whose weights depend only on and .
-
Arithmetic intensity of attention. Consider one head with queries and keys of width and values of width . Its two matrix products, and the product of the weights with , cost and floating-point operations, and the softmax costs a few operations per score.
- 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 , , and writing the output.
- Neglecting the softmax arithmetic, form the ratio of operations to bytes and let at fixed and . Show that the limit is , and state how the softmax arithmetic changes it.
- 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 is limited by arithmetic or by memory traffic on it.
-
Traffic of a tiled schedule. ● By Exercise 4a, the naive layer moves floats to and from main memory beyond the terms linear in , since the score matrix and the weight matrix are each written once and read once. Ignore all traffic that is linear in .
- Suppose that
chunked_attentionruns one operation at a time, each reading its inputs from main memory and writing its output back. Count, as functions of , , and , the floats moved for the score stripes, the floats moved for and the accumulator , and the number of operations launched. Which of these quantities does chunking reduce relative to the naive layer? - A fused kernel instead holds a tile of queries, their output accumulator, and one tile each of keys and values in a fast memory of floats, so that ; the scores of a tile and the running and 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 floats and that the largest admissible tile gives , the bound that Dao et al. (2022) prove for FlashAttention.
- Compute the ratio of the fused traffic to the naive traffic for with , and state how the head width limits the benefit of tiling.
- Suppose that