跳到內容

技術

KV 快取 (KV cache)

KV cache

Transformer 推理時把過去 token 的 Key/Value tensor 快取下來、避免每步都重算的機制,也是長 context 吃記憶體的主因。

登入以收藏
Transformer 生成第 N+1 個 token 時,attention 需要前面 1 到 N 個 token 的 Key 和 Value。每步都重新計算是 O(N²) 的工作量。KV cache 把第一次算出來的 K/V tensor 存起來,後面每個新 token 只要計算一份新的 K/V 加上查 cache。這讓生成從每 token 平方變成線性。 它重要的原因是:KV cache 讓生成變得可行,但它也是吃記憶體的元兇。70B 模型每個 context token 大概要 1MB 以上 cache。100k context = 100+ GB KV cache,這就是為什麼長 context 推理那麼吃 GPU 記憶體、provider 對長輸入收更貴的錢。 舉個例子:你把 5 萬 token 的文件貼進 Claude 或 GPT 連續問問題時,API 把那份文件的 KV cache 起來——後續提問都重用同一份 prefill。Anthropic 的 prompt caching 功能基本上就是把 KV cache 重用暴露給 API 使用者,cached prefix token 收更低費用。 值得知道的優化:PagedAttention(vLLM)把 KV cache 當成虛擬記憶體管理、GQA(grouped-query attention)讓每個 head 的 cache 變小、MLA(DeepSeek)進一步壓縮 cache。延伸閱讀:attention、context window、prefill、prompt caching。

最後更新: 2026-04-29

We use cookies

Anonymous analytics help us improve the site. You can opt out anytime. Learn more