ExploreMy JigsMission
MakeMake a Jig

© JigSpace Inc. 2026

jig.comContact@JigSpace on X

KV Cache in Transformer Inference

publicRemix · Free
DBy DUSK

How a transformer stores Keys and Values in GPU memory and reuses them to generate text faster

Transcript

8 steps · 4 min read
  1. 1

    Step 1: The KV cache · KV 缓存

    A language model writes one token, a small piece of a word, at a time. Each glass shelf is one layer of the model, and its cells hold memory saved for later. 语言模型一次只写一个词元(词的一小块)。每层玻璃架代表模型的一层,格子里存着留待复用的记忆。

    Token 词元 · Layer 层 · GPU memory 显存

  2. 2

    Step 2: Tokens climb the layers · 词元逐层上升

    The prompt "The cat sat" enters together. Each token rises through every layer, and at each layer it leaves a Key (cyan) and a Value (purple) in GPU memory. 提示词一起进入。每个词元逐层上升,在每一层留下一个键(青色)和一个值(紫色)。

This first pass is called prefill. 这一步叫“预填充”。
  • 3

    Step 3: Query, Key, Value · 查询、键、值

    To choose the next word, the newest token asks a question, the Query (white). It compares the Query with every Key, then mixes the matching Values. 为了选出下一个词,最新的词元提出查询(白色),与每个键比较,再按匹配程度混合各个值。

    The Query is used once and thrown away. Only K and V are cached. 查询用完即弃,只缓存 K 和 V。

  • 4

    Step 4: Generate step by step · 逐步生成

    Press the button to make one new token. Only the new token climbs the layers; the old Keys and Values are simply read from the cache. 按下按钮生成一个新词元。只有新词元需要逐层计算,旧的键和值直接从缓存读取。

    Bars in front show the work for each step. 前方的柱子表示每一步的计算量。

  • 5

    Step 5: Without the cache · 没有缓存时

    Switch the cache off and watch. Every step must rebuild the Keys and Values of all earlier tokens (amber flashes). The amber bars grow taller each step, while the cyan bars stay small. 关闭缓存看看:每一步都要重新计算之前所有词元的键和值(琥珀色闪光),琥珀色柱子越来越高,青色柱子保持很矮。

    Same answer either way. The cache only saves repeated work. 两种方式结果完全相同,缓存只省去重复计算。

  • 6

    Step 6: Inspect a cached tensor · 查看缓存张量

    Tap any glowing cell. A label shows which layer and token it belongs to and how big it is. In Llama 2 7B one Key per layer and token holds 32 heads × 128 numbers. 点一点发光的格子,标签会显示它属于哪一层、哪个词元,以及有多大。

    32 × 128 numbers × 2 bytes = 8 KiB per cell. 每格 8 KiB。

  • 7

    Step 7: Memory grows with length · 显存随长度增长

    Slide to make the text longer. For Llama 2 7B the cache needs about 0.5 MiB per token, so 4,096 tokens take 2 GiB. At 131,072 tokens it no longer fits beside the model on one 80 GB GPU. 拖动滑块加长文本:每个词元约 0.5 MiB,4096 个词元需要 2 GiB;到 131072 个词元时,一块 80 GB 显卡装不下了。

    Weights stay the same size; only the cache grows. 权重大小不变,只有缓存在增长。

  • 8

    Step 8: Memory for speed · 用显存换速度

    The KV cache trades GPU memory for speed: the longer the text, the more repeated work it saves. Newer models shrink it by letting several Queries share one Key and Value. 键值缓存用显存换取速度:文本越长,省下的重复计算越多。新模型让多个查询共用一组键和值来缩小它。

    Llama 2 70B shares 8 KV heads among 64 query heads. 70B 模型 64 个查询头共用 8 个键值头。