3.5 Attention Compute and KV Cache Memory
Double the prompt length from 4,096 to 8,192 tokens. A decoder that writes out every attention score now needs four times the space for those scores. Its ordinary KV cache only doubles. The two objects have different shapes. Count the bytes in one layer, then compare how the work changes between prompt prefill and generating one more token.
Count the operation being compared
Let be sequence length, the hidden width, and a convolution’s kernel width. Ignore constant factors and batch size initially. The original Transformer comparison describes an attention core operating on already-projected queries, keys and values. [1]
| Operation | Leading arithmetic | Sequential dependency across known tokens |
|---|---|---|
| Attention core and | All queries can be processed in parallel | |
| Q/K/V/output projections | Parallel over tokens | |
| Dense recurrent layer | recurrent steps | |
| Width- dense convolution | Parallel within a layer |
An attention layer therefore costs ; an FFN adds another width-dependent term. The slogan “attention is cheaper when ” compares only the core to a dense recurrent layer. Constants, kernels and memory traffic decide actual latency.
Derive the attention terms
For a head of width , the query, key and value matrices each have shape . Forming computes dot products of width . Multiplying the probabilities by takes the same order of work. With query heads and , the two matrix products together scale as . Softmax also visits the scores in each head. By comparison, a single input projection from through a matrix costs .
One attention layer directly connects visible query–key positions; causal masking limits visibility to the past. An ordinary RNN passes a signal through recurrent steps. A convolution needs enough depth to cover the desired distance: logarithmic depth assumes a suitable dilation schedule, not arbitrary fixed-width convolutions.
Parallel prefill is different from autoregressive decode
During teacher-forced training or prefill, all input tokens are known. Their queries can be evaluated together. This is the meaning of the comparison table’s constant number of sequence-level sequential stages; it does not mean constant elapsed time on finite hardware.
During autoregressive decoding, the next token depends on the sampled previous token. With a KV cache, one new query attends to stored keys, costing for the attention core plus projections and FFN work. Generating many tokens still requires sequential decoding steps. Vanilla nonlinear RNNs have a recurrent dependency during both modes; specialized state-space scans are a separate case discussed in Chapter 20.
Why do attention scores quadruple while the KV cache only doubles?
Take one request and one grouped-query attention layer with 32 query heads, 8 KV heads, and 128 values per head. In grouped-query attention, several query heads share a key and value head [4]. Suppose scores, keys and values each use two bytes per element.
| Prompt length | One dense prefill score tensor | Keys and values kept for decoding |
|---|---|---|
| 4,096 tokens | 1,024 MiB | 16 MiB |
| 8,192 tokens | 4,096 MiB | 32 MiB |
The score tensor has a row and a column per prompt token in each query head. Doubling the prompt doubles both dimensions. The cache adds one key vector and one value vector per new token in each KV head. Doubling the prompt only doubles the number of stored positions. The table counts a full score tensor, including any masked slots, if an implementation materializes it. FlashAttention tiles the computation so it can avoid writing that tensor to device memory [2]. The KV cache budget counts cached keys and values across layers and requests.
The following Python counts elements from their shapes. It allocates no tensors and excludes weights, workspaces, padding and allocator overhead.
from math import prod
def attention_bytes(tokens):
# One sequence, one layer. All three tensors store 2-byte elements.
score_shape = (1, 32, tokens, tokens)
key_shape = value_shape = (1, 8, tokens, 128)
return 2 * prod(score_shape), 2 * (prod(key_shape) + prod(value_shape))
for tokens in (4096, 8192):
scores, kv = attention_bytes(tokens)
print(tokens, scores // 2**20, kv // 2**20)
# tokens, score MiB, KV MiB
# 4096 1024 16
# 8192 4096 32
Explore the cost model
The following values divide out a common factor from the growth terms. They are not measured FLOPs or speed and exclude projections. Set the sequence length to the hidden width of 512. Both displayed terms are then 262,144. Double the length and compare which term grows faster.
Compare growth at a hidden width of 512
- Attention core · n²
- 262,144
- Recurrent layer · n × 512
- 262,144
The next design questions
Linear attention targets sequence-linear arithmetic at fixed feature dimension. Reformer’s LSH attention instead targets ; these methods should not all be called linear. Approximation quality, memory and hardware efficiency must be evaluated together. Chapter 20 develops these trade-offs. [3]
Quizzes
Quiz 1: Why does not prove a full Transformer layer is faster than an RNN?
The comparison omits projections and FFN work, and arithmetic scaling omits hardware, kernels and memory traffic.
Quiz 2: Does FlashAttention make dense attention arithmetic linear in sequence length?
No. It avoids materializing the full score matrix through tiling and recomputation, while dense pairwise attention still has quadratic arithmetic.
Quiz 3: Why can training process known tokens in parallel while decoding cannot generate all tokens at once?
Teacher forcing supplies the full sequence; decoding must obtain a token before conditioning on it in the next generation step.
Quiz 4: What would double when doubling sequence length, and what would quadruple?
At fixed width and batch, the RNN arithmetic term doubles, while naive attention-score storage and dense attention-core arithmetic quadruple. This does not predict whole-system latency.
References
- Vaswani, A., et al. (2017). Attention is all you need. Advances in neural information processing systems, 30. arXiv:1706.03762.
- Dao et al. (2022). FlashAttention.
- Kitaev et al. (2020). Reformer: The Efficient Transformer.
- Ainslie et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints.