Chapter 4 KV Cache Optimization
In the previous chapter, we divided autoregressive generation into prefill and decode, and saw how a model generates text one token at a time. This chapter explains one of the most fundamental and important optimizations in an inference system: KV Cache. By preserving the Keys and Values of historical tokens in every attention layer, KV Cache avoids recomputing results during decode and makes long-sequence generation practical.
This chapter starts with the repeated computation that occurs without KV Cache, then explains what is cached, how the cache is read and written, and the resulting complexity benefits.
1 Learning Objectives
After completing this chapter, you will be able to:
- Explain why computation is repeated without KV Cache: starting from the autoregressive generation loop, explain why every step must send the entire history through the model again, and why historical tokens' K/V representations are repeatedly projected and reused in attention computation.
- Describe KV Cache's core idea and cached objects: explain that KV Cache stores the tensors produced when historical tokens pass through K/V linear projections in every self-attention layer, rather than Query, the attention matrix, logits, or complete hidden states.
- Derive the complexity benefits of KV Cache: derive
and without a cache from the K/V-projection and attention-matrix perspectives, and show how KV Cache reduces K/V projection to and per-step attention from to . - Distinguish prefill from decode: explain how prefill computes and writes K/V for all prompt tokens at once, while decode computes K/V only for each new token and appends it to the cache.
2 Repeated Computation Without KV Cache
In autoregressive language-model generation, the model predicts one next token, appends that token to the end of the input sequence, and predicts another token. Without KV Cache, the model does not retain what it computed in the prior step. Every prediction must send the complete history so far through the network and recompute it from scratch.
This means the model processes the full prompt to generate token 1, then the prompt plus token 1 to generate token 2, then the prompt plus tokens 1 and 2 to generate token 3. The input grows at every step, and the model repeatedly projects every historical token and recomputes attention. This repeated work is the source of inefficiency without KV Cache.
2.1 Generation Loop Without KV Cache

Figure 1. Generation loop without KV Cache
Suppose the prompt is
Step 1: send the whole prompt to the model and obtain the first new token,
Step 2: append
Step 3: append
The model returns logits for every position, but we care only about the final position because it predicts the next token. We take its logits, sample from them or choose the argmax, append the new token to the sequence, and start the next iteration.
The input is the entire history, not just the newly generated token. The model performs a forward pass for every token even though we need output only from the final position. Historical tokens are recomputed repeatedly: their Keys and Values have not changed, but because they were not saved, they must be calculated again at every step.
2.2 Where Computation Is Wasted: Repeated Historical K/V Projections

Figure 2. Repeated projections of historical K/V
To see where the wasted computation occurs, consider the calculations within a single step. Suppose the input sequence at step
In the attention layer, the model first applies linear projections to all
The model then computes attention scores by multiplying Query by the transpose of Key and dividing by
Throughout this process,
2.3 A Small Example: From [x₁, x₂] to [x₁, x₂, y₁, y₂]

Figure 3. Example generation without KV Cache
Suppose the prompt contains only two tokens,
Step 1: the input is
Step 2: the input becomes
Step 3: the input becomes
The K/V for
2.4 How Much Is Repeated: O(n²) or O(n³)?

Figure 4. Complexity of repeated computation
The amount of repeated work can be quantified. If we consider only historical token K/V projections, step 1 computes K/V for one token, step 2 for two tokens, step 3 for three tokens, and step
This is one source of the statement that generation without KV Cache is
If we instead count the total number of elements in the full
This is why you may encounter either
Regardless of the accounting method, the fundamental problem is the same: historical K/V can be reused but is recomputed at every step because it is not saved. A model forward pass is stateless; it recalculates whatever input it receives and does not remember the previous step.
3 What Does KV Cache Store?
For a detailed introduction to KV Cache, see Chapter 4 of Part I.
KV Cache stores the K and V tensors produced when every historical token passes through Key and Value linear projections in every self-attention layer during autoregressive generation. It does not store Query, raw tokens, or logits. It lets the current token compute only its own Query and directly look up the Keys and Values that historical tokens have already produced.
3.1 Common Misconceptions
KV Cache does not cache the hidden state of the entire sequence. It stores the Key and Value projection results inside attention for every layer.
KV Cache is not one cache shared by every layer. Each layer has its own K/V cache.
KV Cache does not cache the attention matrix. Attention weights are temporary values calculated at each step and are not saved.
KV Cache does not cache logits. Logits are produced only by the final layer and are used only to sample at the current step.
KV Cache is not limited to the final layer. On the contrary, every self-attention layer needs its own K/V cache.
With RoPE, Key is usually cached after rotary positional encoding is applied. Query is rotated at the current step before use. Value generally does not use positional rotation.
KV Cache fundamentally preserves the Keys and Values of historical tokens at each layer, preventing the model from recomputing the full history at every step. The model's forward pass remains stateless, but the inference system uses an external cache to reuse historical computation.
Without KV Cache, step
4 KV Cache: From O(n²) to O(n)
This section focuses only on complexity changes caused by sequence length. To simplify the analysis, we ignore constants such as the number of layers
Let the prompt length be
To highlight the dominant behavior, assume
4.1 Without KV Cache: Historical K/V Is Recomputed Every Step
Without KV Cache, step
Considering only K/V projection, computation at step
The total K/V projection work for generating
This is one source of the statement that generation without KV Cache is
If we instead count the attention-score matrix, its size at step
elements. Across
Thus, from the perspective of full attention matrices, the total complexity without KV Cache is
4.2 With KV Cache: Historical K/V Is Computed Only Once
With KV Cache, generation has two stages.
During prefill, the prompt is passed through the model once, and the K/V for every prompt token is computed and written into the cache. Decode then processes one new token at a time.
At decode step
The total K/V projection work for generating
K/V projection therefore decreases from
Now consider attention. The current token uses its Query to query historical Keys, whose length is
Across
Per-step attention decreases from
to
4.3 Complexity Comparison
| Perspective | Without KV Cache | With KV Cache |
|---|---|---|
| Per-step K/V projection | ||
| Cumulative K/V projection over | ||
| Per-step attention | ||
| Cumulative attention over | ||
| Cache memory |
If we include hidden dimension
4.4 From O(n²) to O(n)
The phrase "from
This is the most direct benefit of KV Cache.
However, attention still has to interact with history. The current token must query every historical Key, so per-step attention is
Therefore, the reduction to
4.5 Total Complexity Including Prefill
When the prompt is included, a complete generation with KV Cache is approximately:
- Prefill:
attention, K/V projection and cache construction. - Decode:
attention, K/V projection.
Total attention is approximately
and total K/V projection is approximately
Without KV Cache, total attention is approximately
and total K/V projection is approximately
The core complexity benefits of KV Cache can therefore be summarized as
and
The cumulative attention cost of decode, which queries history token by token, still remains
5 Summary and Exercises
5.1 Summary
This chapter established the key ideas behind how KV Cache eliminates repeated work in autoregressive generation:
- The problem without a cache: every generated token causes the model to reprocess the complete history. Historical K/V projection accumulates to
, while full attention matrices accumulate to . - What is cached: KV Cache stores the results of Key and Value projections for historical tokens in every layer. Query serves only the current step, so historical Queries do not need to be cached.
- Prefill and decode: prefill computes K/V for the complete prompt and writes it to cache; decode computes K/V only for each new token, appends it, and uses the current Query to read historical K/V.
- Benefits and cost: cumulative K/V projection decreases from
to and per-step attention decreases from to ; in exchange, KV Cache memory grows linearly with the number of layers, batch size, and sequence length.
5.2 Exercises
- Why are historical tokens' Keys and Values recomputed at every decode step without KV Cache?
- Why does KV Cache store only Key and Value rather than Query, the attention matrix, or logits?
- Compare how prefill and decode read and write KV Cache, and describe the computational characteristics of each stage.
- What specific computation does the claim "KV Cache reduces complexity from
to " refer to? Why does cumulative attention complexity across the full decode process remain ?