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) @ VDive 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
Motivation
Arithmetic Scaling
Memory Allocation
Why does naive attention allocate 8n^2 bytes of temporary memory per head in float32?
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.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
The Two-Pass Bottleneck
float16 above a_j \approx 11.09 and float32 above a_j \approx 88.7.Online Softmax Recurrence
Step-by-Step Numerical Trace
Linear Working Memory
Code Implementation
The reference causal_attention materializes the full n \times n score matrix; it is the baseline every faster kernel must match:
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 / sChunked vs. Full-Matrix Benchmark
chunked_attention matches causal_attention within \sim 10^{-7} (float32 rounding):maximum deviation: 2.38e-07
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
GPU Memory Hierarchy
Roofline Analysis
IO-Aware Kernel Fusion
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
Dissecting the Benchmark
Comparing naive, fused (causal), and fused, no mask separates two distinct sources of speedup:
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}).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.Architectural Perspective
Check Your Understanding
Work through these three systems and algorithmic questions:
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?Check Your Understanding
Answers:
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].Key Takeaways