---
site: "zyx.tw"
title: "KV cache 保存注意力中間值，只能重用從開頭連續相同的前段"
description: "前文決定每個位置的計算結果，也決定快取能重用到哪裡。"
url: "https://www.zyx.tw/map/harness/kv-cache"
---

# KV cache 保存注意力中間值，只能重用從開頭連續相同的前段

紀錄 061，深讀 L3，480 字，1 分鐘，v1.0.0，更新 2026-11-16

KV cache 保存每個 token（模型讀寫文字的單位）的注意力中間值，讓模型生成後續內容時能直接取用。

KV cache 只能重用從開頭連續相同的前段。

## 模型先算出什麼，再存下什麼

注意力機制讓後面的 token 決定要參考哪些前文。模型替每個 token 算出 key 與 value，兩者就是 K 與 V，也是 KV cache 保存的中間值。

這裡的計算方向是由前往後：每個 token 的結果取決於排在前面的所有 token。後面新增內容，不會反過來改變前面已算出的結果。

## 生成往後走時，模型如何接著計算

A、B、C 代表依序排列的 token。模型先計算這段內容，並保存各自的 K 與 V；這是後續重用的起點。

序列接上 D 時，模型沿用 A、B、C 的快取，只計算新加入的 D。接著加入 E 時，可用的快取已包含 D，因此模型能沿用 A 到 D 的結果。

下圖示範新增時只計算新 token，以及修改前段後，重算範圍從哪裡開始。

```text
 step 1    [A] [B] [C]             compute A B C, store K and V
 step 2    [A] [B] [C] [D]         reuse A B C, compute D
 step 3    [A] [B] [C] [D] [E]     reuse A B C D, compute E

 change B  [A] [X] [C] [D] [E]     reuse A only, recompute rest
```

Figure: Three generation steps reuse the stored results of earlier tokens and compute only the new token. When an earlier token changes, only the tokens before it can be reused and the rest is recomputed.

1. Store: 第 1 次計算時，保存每個 token 的 key 與 value。
2. Reuse: 之後每一步只計算新的 token，前面的結果直接取用。
3. Break: 改動中間的 token，後面的結果全部失效，要重新計算。

## 為什麼後面的文字相同，仍然要重算

圖中把 B 換成 X 後，A 仍可重用，從 X 開始則要重新計算。

C 雖然沒有換字，前面卻已從 A、B 變成 A、X。原本保存的 C 是依照舊前文算出的結果，不能因為當前位置仍寫著 C，就直接沿用。

## 生成一結束，KV cache 就釋放

這裡討論的 KV cache 原本只用於單次生成，生成結束後，保存的結果就會釋放。

## 來源

- [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching), Claude API docs
- [Cache strategies](https://huggingface.co/docs/transformers/en/kv_cache), Hugging Face Transformers docs
- [Attention Is All You Need](https://arxiv.org/abs/1706.03762), Vaswani et al.
- [Context Engineering for AI Agents: Lessons from Building Manus](https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus), Yichao Ji
- [Unrolling the Codex agent loop](https://openai.com/index/unrolling-the-codex-agent-loop/), Michael Bolin, OpenAI
- [Prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), OpenAI API docs
- [Context caching](https://ai.google.dev/gemini-api/docs/caching), Gemini API docs
- [Automatic Prefix Caching](https://docs.vllm.ai/en/latest/features/automatic_prefix_caching.html), vLLM docs

## 地圖

- 先讀：[Prompt cache 只重用完全相同的前段，變動內容要放後面](https://www.zyx.tw/map/harness/prompt-cache.md)
- 回到：[Harness](https://www.zyx.tw/map.md)
