# Why Do LLMs Cache K and V but Usually Not Q?

> During autoregressive generation, LLMs use KV cache to avoid recomputing the attention keys and values for all previous tokens. The Query (Q) is generated dynamically for each new token and is therefore not cached. This article explains how this works under causal attention, the benefits of prefix caching, and the memory trade-offs involved.

- Source: https://www.waytoagi.com/en/kb/learning-path/llm-kv-cache-q
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/L9DSw8RPdibYPDkIThrcO8C6nzg
- Updated: 2026-10-23

---

> 🔗 Original link: [https://x.com/dongxi_nlp/status/20989455...](https://x.com/dongxi_nlp/status/2098945504289669481)

> Dongxi NLP · X · @dongxi_nlp · 2026-09-13 09:22

> 📌 This article is reposted. Copyright belongs to the original author. The full text is subject to the original link.

![](https://www.waytoagi.com/api/kb-media/BEnLbiwr6ocXk9xlvprcZjmlnVf)

You hand a very long project document to an AI and ask it to summarize it for you.

The response begins, with one token generated after another. When generating the next segment, the model still needs to use the preceding document and the answer it has already produced.

Does that mean that for every additional token, the model has to recompute the entire ever-growing text from scratch?

**KV cache allows the model to retain a portion of the computation it has already completed.** But why does it keep the K and V? Q also participates in attention—why is it usually discarded after use?

This article explores that question and helps you truly understand **KV cache**.


## Does every new token require recomputing everything from the beginning?

Let’s shorten the input to “The sky is”. Assume the model continues by generating “ blue” and then “.”.

The model first processes the entire prompt and builds the KV cache for each layer. This step is called **prefill**. The output at the last prompt position passes through the vocabulary head to produce the logits used to select the first output token.

After “blue” is selected, the model treats it as new input and continues to predict “.”.

Look at the animation below: **Before and after “blue” appears, which blocks stay in place and which are newly added?**

The existing K/V values remain in place, and the K/V for the new position are appended. The new token still needs to go through the model’s computation, but the repeated calculations on the valid historical states are avoided.

Pay attention to the sequence: **When “blue” is selected, its K/V have not yet been computed. Only when it is fed back into the model to predict the next token are its K/V calculated.**


## Why keep K and V, but usually not Q?

In an attention layer, each position has an input vector, also called a hidden state. Three learnable projections transform it into query (Q), key (K), and value (V).

When processing the “blue” position, its new Q computes matching scores with the K values from “The sky is” and from “blue” itself.

The scores are scaled and passed through softmax to become attention weights. These weights are then used to perform a weighted sum of the corresponding V values, producing the output of this attention head.

**The next position will generate its own Q, but it may still need to read the K/V from previous positions.** The historical Q has already completed the computation for its own position; during normal decoding, there is no need to reuse it.

Writing this process as a formula gives us the following line:

![](https://www.waytoagi.com/api/kb-media/AjSZb2cQ9oa4OHxb8FjcgtMhnSc)

This explains the name **KV cache**: K and V continue to be read by subsequent positions; Q is regenerated with each new position.


## As context grows longer, why do previous calculations remain valid?

Let’s return to the project document. Suppose it begins with “The budget is 1 million yuan,” followed by progress, personnel, and delivery plans.

Now compare two operations:

- At the end of the document, append: “Please summarize the risks.”
- Change the opening “1 million yuan” to “500,000 yuan.”

**Which operation will invalidate the old cache? Think about it first, then watch the animation.** The letters in the figure represent token positions.

The difference comes from the **information flow in causal attention**: a position can only attend to itself and preceding inputs; it cannot read future content.

Therefore, appending a question at the end does not retroactively change the computations already performed at the document positions. However, modifying the budget at the beginning may affect the representations of all subsequent positions, so the entire previous cache cannot be reused directly.

In other words, changing “1 million yuan” at the beginning to “500,000 yuan” alters the context for every subsequent token generation, which invalidates the old cache.


## When a new token arrives, what exactly is being computed?

Now let’s zoom in on the step where “blue” is fed back into the model. Looking at just one attention head: **the historical K/V remain unchanged; the new position generates its own Q, K, and V; the new Q then reads from all available K/V.**

The new K/V are first added to the cache and then participate in attention, so the current Q can also attend to its own position. After this head’s output is used by subsequent computations, the K/V are still retained for the next position to read.

The Head output in the diagram must still go through the remaining intra-layer computations and the rest of the model before producing the next-token logits. When the input and execution conditions are compatible, the results from the cached and uncached versions should be consistent within an acceptable numerical error range.

## Why Does It Save Repeated Computation but Increase VRAM Usage?

The longer a document is, the more positions the model may need to retain. **When using a full KV cache that grows with sequence length, newly added positions continue to consume additional memory.**

We can calculate it dimension by dimension: number of sequences, number of layers, number of positions retained per layer, number of KV heads, width of each head, and bytes per element.

Assuming K and V are stored separately, have the same width, and all layers share the same structure, the total is obtained by multiplying these values together:

![](https://www.waytoagi.com/api/kb-media/Vti3bO6qkoNPK5xkc2dc4cyZnUc)

Let’s assign the following hypothetical configuration to this document: 24 layers, 1 sequence, 8 KV heads, head width of 64, and 2 bytes per element.

- Retaining **4,096** positions: the KV tensor totals **192 MiB**.
- Retaining **8,192** positions: it increases to **384 MiB**.

Observe the two changes shown in the animation: first the number of positions increases, then it returns to the original length. Compare this with another configuration that uses fewer KV heads.

## Can the Same Document Be Reused for a Different Question?

You just asked the AI to summarize the risks, and now you want to know the deadlines. Suppose the two requests are structured as follows:

**Request A:** [Same project document] + “Summarize the risks.”

**Request B:** [Same project document] + “List the deadlines.”

If the actual token prefix for the document portion is completely identical, the model and execution settings are compatible, and the system still retains that portion of the cache, it can be reused. The two questions and their continuations can then be computed separately. This technique is called **prefix caching**.

The three terms—**prefill, KV cache, and prefix caching**—can be distinguished as follows: **prefill is the computation phase that processes the prompt; KV cache is the saved K/V state; prefix caching is the strategy of reusing existing prefix states.** Even if prefix caching is not enabled, regular generation can still use the KV cache.

A typical example from the vLLM official documentation is repeatedly asking questions about the same annual report or software manual. The project document above follows the same pattern: the first request builds the cache through prefill; subsequent requests that hit the shared prefix can directly reuse the corresponding K/V, eliminating the repeated computation for that part.

The new question still needs to perform prefill and read the document’s K/V; the new answer still requires token-by-token decoding. **Prefix caching primarily saves the repeated prefill work and does not eliminate the computation required to generate the new response.**

If Request B inserts a different instruction before the document, the shared prefix may become shorter. Even if the subsequent document text is identical, the model cannot directly assume that its causal states are the same.

## What If We Redesign the Source and Sharing Mechanism of KV?

The previous discussion started from “each layer saves its own K/V.” Once you understand these computational dependencies, the changes in DeepSeek-V4.1-Flash become clear.

**First, the source: Causal Encoder–Decoder.**  
The decoder’s global KV is derived from the final output of the causal encoder. Each decoder layer still generates its own Q, along with its local sliding-window KV.

**Next, cross-layer sharing: Cross-layer sharing.**  
In the configuration discussed, layer 21 uses the encoder output to generate a single decoder global KV bank, which is then shared by layers 21–40.

You can focus on layers 21 and 22: they read from the shared global entries, but each maintains its own Q and local states. The shared entries do not force identical attention weights; sparse selection determines which global entries are actually read.

**Finally, the representation of K/V: Shared KV representation.**  
In the reference core-attention kernel, the same selected vector is used both for computing the matching score with Q and for the weighted summation in the output.

Watch the animation: How does one global KV connect to multiple layers? After zooming in on a vector, which two computations does it participate in?

The model still maintains its local caches, indexer state, and other data. There is a clear distinction between *Shared KV representation* and simply placing two independent K/V arrays adjacent to each other in memory.

Returning to the project documentation: suppose the input this time contains **100,000 tokens**. The serving scheme described in the report can handle it as follows:

1. The encoder processes the entire prompt and produces the representation used to build the decoder’s global KV.
2. The decoder then processes only the final **128 prompt tokens** to reconstruct its local state. Earlier history remains accessible through the global KV.

This shows that the source of the global KV directly affects which computations can be adjusted during the prefill phase. When generating subsequent tokens, new inputs still pass through both the causal encoder and the decoder.

## Back to the Original Document

Now we can connect everything along the same scenario with the KV cache:

- **Continue writing the answer:** The new position generates its own Q and reads the still-valid historical K/V.
- **Modify the document’s beginning:** Re-examine the reuse scope starting from the point where the actual token prefix changes.
- **Change the question:** Check for common prefixes, execution conditions, and whether the cache is still retained.
- **Read a longer document:** Pay attention to the storage growth caused by retained positions and how the architecture organizes these states.
