Efficient Transformers
The quadratic cost of attention, inference memory and the ways around them.
A transformer spends its time in three different ways. Training and reading a prompt are large matrix products that keep the arithmetic units busy. Generating text, one token at a time, mostly waits for memory: every new token re-reads every weight and every cached key and value. Each regime has its own bottleneck, so efficient transformers come in families: compute fewer scores, approximate the softmax, move fewer bytes, store less, or produce several tokens per pass.
What you’ll learn
- Count the FLOPs and the bytes moved by a decoder in training, prefill and decoding, and explain why prefill is compute-bound while decoding is bound by memory bandwidth.
- Compute the size of a KV cache, numbers per sequence, and what multi-query and grouped-query attention save.
- Describe sliding-window, dilated, strided, global and block-sparse attention, and how far information travels through a stack of windows.
- Derive low-rank and kernelized (linear) attention, implement causal linear attention as a recurrence, and state what these approximations give up.
- Match IO-aware exact attention, cache compression, batching and speculative decoding to the costs they reduce.
Three regimes, three bottlenecks
Self-Attention & Multi-Head Attention priced one attention sublayer at FLOPs for tokens of width , and noted that a naive implementation stores a matrix of weights per head. Those counts describe one pass over whole sequences, which is what training does. A deployed decoder works in two further regimes:
- Prefill. The prompt's tokens go through the model in one pass, as in training. Every weight matrix multiplies a block of many token vectors, so arithmetic dominates.
- Decoding. Each new token goes through the model alone and attends to the stored keys and values of everything before it, the KV cache. Every weight matrix now multiplies a single vector.
For a decoder with layers and key–value heads of size , storing numbers of bytes, the cache of one sequence of length holds a key and a value per head, per layer and per token:
A LLaMA-2-7B-like decoder has layers and 32 key–value heads of size 128, and caches 16-bit numbers. How many GiB does the KV cache of one 4,096-token sequence occupy?
Show the answer
2 GiB
bytes GiB: keys and values, 32 layers, 4,096 tokens, 32 heads of 128 numbers, 2 bytes each. A batch of 16 such conversations needs 32 GiB, more than twice the 13.5 GB of the model's weights. With 8 key–value heads instead of 32 it would be 0.5 GiB per sequence.
Generating one token at context length costs FLOPs in the weight matrices of an -parameter model, plus for the scores and for the weighted sum in each layer. The step must read every weight once and the sequence's whole cache, in 16-bit numbers:
With multi-head attention , so the two counts coincide: one FLOP per byte. For the 7B model () at both are . On the illustrative accelerator of The Roofline Model & Compute Efficiency ( FLOP/s, B/s) the arithmetic would need 0.016 ms and the memory traffic needs 5.2 ms:
Prefill of a 4,096-token prompt runs the same weights on all its tokens at once: FLOPs plus causal attention, , for about the same number of bytes. Its arithmetic intensity is in the thousands, far to the right of the ridge at 333:
The same weights are compute-bound in prefill and memory-bound by a factor of hundreds in decoding. A faster decoder must move fewer bytes per generated token (smaller caches, fewer bits, more tokens per pass); doing less arithmetic would not help.
Attend to fewer pairs
The most direct saving computes only some of the scores. A sparsity pattern fixes which pairs may interact, and every other score is masked to before the softmax:
- Sliding window (local attention): position attends to itself and the positions before it. Scores cost instead of , and the cache keeps only the last entries per layer.
- Dilated window: the same number of keys spaced apart, spanning positions; different heads can use different dilations.
- Strided patterns: a local band plus every -th position. With every token reaches every other in two hops, at cost (Child et al., 2019).
- Global tokens: a few positions, such as a classification token or the question in question answering, attend to everything and are attended by everything (Longformer: Beltagy, Peters & Cohan, 2020). BigBird adds a few random links per token (Zaheer et al., 2020).
A window does not cut a token off from the distant past. The output of layer at position depends on layer at positions back to , each of which depended on positions before it, so stacked windows can carry information positions back ( with dilation), the way stacked convolutions grow a receptive field.
Think first Mistral 7B uses sliding-window attention with in each of its 32 layers. In principle, how many positions back can information reach the top layer, and how much smaller than a full cache can its cache be at 32,768 tokens?
Each layer moves information at most positions, so 32 layers reach , the "approximately 131K tokens" of Jiang et al. (2023). That bounds the path, not what survives it: distant information has to be relayed through intermediate tokens in every layer. The cache needs only the last entries per layer, so a rolling buffer that stores position in slot is times smaller than a full cache.
Sparsity saves time only when whole blocks of the score matrix can be skipped: masking scattered entries inside a dense product costs as much as computing them. The causal mask is the simplest block pattern, and skipping the blocks above the diagonal made FlashAttention-2 1.7–1.8 times faster than unmasked attention (Dao, 2024). Among open models of the mid-2020s, the sparse pattern seen most often is the plain sliding window, in every layer or interleaved with full-attention layers: Mistral 7B combines windows in all its layers with grouped-query attention (Jiang et al., 2023), and Gemma 2 alternates sliding-window and global layers (Gemma Team, 2024).
Approximate the softmax
A second family keeps every pair but approximates the weights, so that the matrix is never formed.
Low rank. If the weights are close to a low-rank matrix, the sequence axis of the keys and values can be compressed. Linformer (Wang et al., 2020) learns with and computes
Kernels. Write the softmax weight as a similarity, , and replace it by a product of feature maps, with . The sum over keys then factors, because matrix products are associative: , and the right-hand side costs . Under a causal mask the sums run over and become running totals, so causal linear attention is a recurrent network whose state is a matrix (Katharopoulos, Vyas, Pappas & Fleuret, 2020):
import torch
import torch.nn.functional as F
def phi(x): # a positive feature map (Katharopoulos et al., 2020)
return F.elu(x) + 1
def linear_attn_parallel(q, k, v): # causal; q, k: (T, r), v: (T, dv)
q, k = phi(q), phi(k)
S = torch.cumsum(k[:, :, None] * v[:, None, :], dim=0) # S_t for every t at once
u = torch.cumsum(k, dim=0) # u_t for every t
return torch.einsum('tr,trd->td', q, S) / (q * u).sum(-1, keepdim=True)
def linear_attn_recurrent(q, k, v): # the same layer as an RNN with an r x dv state
q, k = phi(q), phi(k)
S, u, out = torch.zeros(k.shape[1], v.shape[1]), torch.zeros(k.shape[1]), []
for t in range(q.shape[0]):
S, u = S + torch.outer(k[t], v[t]), u + k[t] # constant memory per new token
out.append(q[t] @ S / (q[t] @ u))
return torch.stack(out)
q, k, v = torch.randn(8, 4), torch.randn(8, 4), torch.randn(8, 3)
assert torch.allclose(linear_attn_parallel(q, k, v), linear_attn_recurrent(q, k, v), atol=1e-5)The parallel form trains on whole sequences; the recurrent form generates. This parallel version materializes every , numbers, for clarity; practical kernels process the sequence in chunks.
Random features. The Performer (Choromanski et al., 2021) keeps the softmax kernel itself. With random Gaussian vectors and , the estimate is positive and unbiased for ; the Artificial Intelligence course's lesson Efficient Attention & Long Context derives its variance.
Why can't Linformer's compression of the keys along the sequence, with , be used in a decoder that generates text?
- Each compressed key mixes all positions, future ones included, and is tied to one sequence length
- It needs more memory than standard attention
- It removes the softmax, so the weights no longer sum to one
- It works only with a single head
Show the answer
A. Each compressed key mixes all positions, future ones included, and is tied to one sequence length
A causal model must let position depend only on positions , and generation must work at every length. A row of mixes keys from the whole sequence and has a fixed width. Kernelized attention has neither problem: its sums over are running totals.
Exact attention, fewer bytes
The approximations above cut FLOPs. At the lengths most models are trained on, though, standard attention is slow for another reason: memory traffic. A GPU keeps its tensors in HBM, tens of gigabytes read at a few terabytes per second, and computes out of on-chip SRAM, a few tens of megabytes in total with roughly ten times the bandwidth. A naive implementation runs three kernels: it writes the scores to HBM, reads them back to compute , writes , and reads it again to form . That is HBM accesses per head, nearly all of them for intermediate results, and stays in memory for the backward pass.
FlashAttention (Dao, Fu, Ermon, Rudra & Ré, 2022) computes the same output tile by tile. A block of queries and a block of keys and values are loaded into SRAM, their scores are formed and used there, and the result is folded into a running output with the online softmax: each query row keeps its running maximum and its running sum of , and rescales what it has accumulated by whenever a new block raises the maximum. Nothing of size ever reaches HBM.
| Sequence length | Storing for one head (16-bit) | FlashAttention's per-row statistic (32-bit) |
|---|---|---|
| 2,048 | 8 MiB | 8 KiB |
| 8,192 | 128 MiB | 32 KiB |
| 131,072 | 32 GiB | 512 KiB |
The forward pass does the same arithmetic and the backward pass does more, since it recomputes the scores, yet the kernel is faster because it moves far fewer bytes: its HBM traffic is for an SRAM holding numbers, many times below when . It trained GPT-2 up to 3 times faster end to end than the HuggingFace implementation and 1.7 times faster than Megatron-LM's (Dao et al., 2022), and FlashAttention-2 roughly doubled the kernel's speed again (Dao, 2024). Because it changes no number in the model, it can replace standard attention in any network; as of the mid-2020s, kernels of this kind sit behind the fused attention calls of the major frameworks, such as PyTorch's F.scaled_dot_product_attention on supported GPUs. FlashAttention in Depth proves the online softmax correct and derives the IO bound and its optimality.
Storing less: the KV cache
In decoding, every byte of the cache is read once per generated token, so the cache's size sets both the memory per sequence and the time per step. Four levers shrink it:
- Fewer key–value heads. Multi-query attention shares one key head and one value head among all query heads (Shazeer, 2019); grouped-query attention shares each of key–value heads within a group of query heads (Ainslie et al., 2023). The cache shrinks by : Anatomy of a Modern LLM found 128 KiB per token for Llama 3 8B instead of 512 KiB. Multi-head latent attention caches one low-dimensional latent vector per token and layer (plus a small key that carries positions), from which every head's keys and values are reconstructed (DeepSeek-AI, 2024).
- Fewer bits. Storing keys and values in 8 or 4 bits halves or quarters the cache. With scales per channel for the keys, which have a few large fixed channels, 2 bits have worked for several open models (Liu et al., 2024).
- Fewer tokens. Eviction keeps only some positions: the most recent ones plus those that have received the most attention so far (H2O: Zhang et al., 2023), or the first few tokens plus a recent window, because the first tokens act as attention sinks (Attention Sinks & Massive Activations). Unlike a rolling buffer for a model trained with windows, eviction changes the computation, and an evicted token cannot be recovered if a later query needs it.
- Less waste. Allocating each sequence's cache in fixed-size blocks, like pages of virtual memory, avoids reserving space for the longest possible output (Kwon et al., 2023).
Which change reduces the bytes a decoding step reads from the cache but leaves the attention FLOPs per generated token unchanged?
- A sliding window of tokens
- FlashAttention
- Grouped-query attention
- Causal linear attention
Show the answer
C. Grouped-query attention
All query heads still score every cached token, so the FLOPs stay at per cached token and layer, while only heads of keys and values are stored and read. A window cuts both bytes and FLOPs; linear attention replaces the cache with a fixed state and computes a different function.
More tokens per pass
Two ideas make each pass over the weights produce more tokens.
Batching. Decoding sequences together reads each weight once for all of them, so the weight matrices' intensity rises to about (The Roofline Model & Compute Efficiency). Each sequence still reads its own cache, so cache reads do not amortize: at long contexts they dominate, and throughput approaches the bandwidth divided by the cache bytes per sequence. Continuous batching keeps the batch full by letting finished sequences leave and new requests join after any step (Yu et al., 2022), and PagedAttention makes more sequences fit (Kwon et al., 2023).
Speculation. When a step is memory-bound, scoring several tokens costs about as much as scoring one, because the weights are read once either way. In speculative decoding a cheap draft model with next-token distribution proposes tokens; the large model, with distribution , scores all of them in one pass and accepts each drafted with probability , stopping at the first rejection and resampling that token from renormalized. The output is distributed exactly as if the large model had generated it alone, and if each drafted token is accepted independently with probability , one pass yields tokens on average (Leviathan, Kalman & Matias, 2023; Chen et al., 2023).
| Family | Examples | What it reduces | Same outputs? |
|---|---|---|---|
| Sparse patterns | sliding, dilated and strided windows; global and random links (Longformer, BigBird) | scores computed; with windows, cache size | no: a different model, trained with the pattern |
| Low-rank and kernel attention | Linformer, linear attention, Performer | the factor | no |
| IO-aware kernels | FlashAttention and its successors | HBM traffic and activation memory | yes |
| Fewer or smaller keys and values | MQA, GQA, latent attention; quantized caches | cache size and bytes per step | architectures are trained in; quantization is lossy |
| Eviction | recent tokens plus heavy hitters; sinks plus a window | cache size | no |
| Scheduling and memory management | continuous batching, paging | idle hardware, fragmentation | yes |
| Speculative decoding | draft models, extra prediction heads | large-model passes per token | yes, in distribution |
Key takeaways
- Training and prefill are compute-bound matrix products. Decoding reads every weight and the whole KV cache for each token at about one FLOP per byte, so it is memory-bound by the ridge factor, hundreds on current accelerators.
- A KV cache holds numbers per sequence (2 GiB at 4,096 tokens for a 7B multi-head model); sharing key–value heads divides it by , and latent attention, quantization and eviction shrink it further.
- Sparse patterns compute fewer scores: windows of width relay information positions, and global and random links restore universality at a cost in depth. Low-rank and kernel methods approximate the softmax; a fixed-size state limits exact recall.
- FlashAttention computes exact attention with far less memory traffic and extra memory, changing no number in the model.
- Batching amortizes weight reads but not cache reads; speculative decoding verifies several drafted tokens per pass, with a rejection rule that leaves the output distribution unchanged.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
On the illustrative accelerator ( FLOP/s, B/s), one decoding step of the 7B model at batch 1 and context 4,096 takes at least 5.2 ms. Which change lowers that bound the most?
- Doubling the peak FLOP/s
- Storing the weights and the cache in 8 bits instead of 16
- Restricting attention to a sliding window of 2,048 tokens
- Switching to FlashAttention
Show the answer
B. Storing the weights and the cache in 8 bits instead of 16
The step is memory-bound, so its time is bytes over bandwidth: s. Halving every byte halves it, to about 2.6 ms. A 2,048-token window halves only the cache, 2.1 of the 15.6 GB, for about 4.9 ms, and more FLOP/s changes nothing.
A decoder with layers and 40 query heads of size 128 caches 16-bit keys and values. It is retrained with grouped-query attention and 8 key–value heads. How large is the cache per token now?
- 800 KiB, unchanged
- 80 KiB
- 160 KiB
- 20 KiB
Show the answer
C. 160 KiB
bytes KiB, a factor below the 800 KiB of full multi-head attention. A 4,096-token conversation then needs 640 MiB instead of about 3.1 GiB.
A 24-layer decoder uses sliding-window attention with in every layer. Which statement is correct?
- Information can travel up to positions back, but only by being relayed through intermediate positions, layer by layer
- Tokens more than 1,024 positions back can never influence the output
- The KV cache still grows with the full length of the text
- The attention FLOPs per generated token still grow with the full length of the text
Show the answer
A. Information can travel up to positions back, but only by being relayed through intermediate positions, layer by layer
Each layer moves information at most positions, so layers reach ; nothing farther is visible directly, and what arrives has been mixed into intermediate tokens on the way. The cache needs only the last entries per layer, and each token's attention costs about FLOPs per layer.
In speculative decoding, a draft model with next-token distribution proposes a token , and the target model's distribution at that position is . Which rule makes the emitted token follow exactly?
- Accept if it is the target's most likely token; otherwise emit the target's most likely token
- Accept with probability ; on rejection, sample again from
- Always accept , since the draft was trained to imitate the target
- Accept with probability ; on rejection, sample from renormalized
Show the answer
D. Accept with probability ; on rejection, sample from renormalized
Acceptance gives each token probability , and the residual supplies the missing . Speculative Decoding proves it and counts the tokens each pass yields.
Go deeper
- FlashAttention in Depth · Tiling, the online softmax and partitioning work across a GPU.
- Serving Language Models · KV caches, paging, continuous batching and latent attention.
- Speculative Decoding · Drafting tokens cheaply and verifying them exactly.
Further reading
- Y. Tay, M. Dehghani, D. Bahri & D. Metzler, "Efficient transformers: A survey," ACM Computing Surveys (2022).
- T. Dao, D. Y. Fu, S. Ermon, A. Rudra & C. Ré, "FlashAttention: Fast and memory-efficient exact attention with IO-awareness," NeurIPS (2022).
- I. Beltagy, M. E. Peters & A. Cohan, "Longformer: The long-document transformer," arXiv:2004.05150 (2020).
- A. Katharopoulos, A. Vyas, N. Pappas & F. Fleuret, "Transformers are RNNs: Fast autoregressive transformers with linear attention," ICML (2020).
- R. Pope et al., "Efficiently scaling transformer inference," MLSys (2023).