Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

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 nn be sequence length, dd the hidden width, and kk 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]

OperationLeading arithmeticSequential dependency across known tokens
Attention core QKTQK^T and AVAVO(n2d)O(n^2d)All queries can be processed in parallel
Q/K/V/output projectionsO(nd2)O(nd^2)Parallel over tokens
Dense recurrent layerO(nd2)O(nd^2)nn recurrent steps
Width-kk dense convolutionO(knd2)O(knd^2)Parallel within a layer

An attention layer therefore costs O(n2d+nd2)O(n^2d+nd^2); an FFN adds another width-dependent O(nd2)O(nd^2) term. The slogan “attention is cheaper when n<dn<d” 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 dhd_h, the query, key and value matrices each have shape [n,dh][n,d_h]. Forming QKTQK^T computes n2n^2 dot products of width dhd_h. Multiplying the [n,n][n,n] probabilities by VV takes the same order of work. With HH query heads and d=Hdhd=Hd_h, the two matrix products together scale as O(n2d)O(n^2d). Softmax also visits the n2n^2 scores in each head. By comparison, a single input projection from [n,d][n,d] through a [d,d][d,d] matrix costs O(nd2)O(nd^2).

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 nn stored keys, costing O(nd)O(nd) 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 lengthOne dense prefill score tensorKeys and values kept for decoding
4,096 tokens1,024 MiB16 MiB
8,192 tokens4,096 MiB32 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 dd 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 O(nlog⁡n)O(n\log n); 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 n<dn<d 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

  1. Vaswani, A., et al. (2017). Attention is all you need. Advances in neural information processing systems, 30. arXiv:1706.03762.
  2. Dao et al. (2022). FlashAttention.
  3. Kitaev et al. (2020). Reformer: The Efficient Transformer.
  4. Ainslie et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints.