DL0043 KV Cache

What is KV Cache in transformers, and why is it useful during inference?

Answer

The KV cache stores the key and value vectors of all previously generated tokens so that autoregressive decoding never recomputes them. At each step the model computes Q, K, V only for the new token, appends K and V to the cache, and attends over the cached history, turning each decoding step from an O(n^2 d) full recompute into an O(n d) lookup, at the price of O(n) growing memory.

(1) What Is Cached: Per layer, the projected keys and values K_{1:t}, V_{1:t} of every past token; they never change once computed, so recomputing them is pure waste.
(2) Why It Helps: With causal masking, token t attends to exactly K_{1:t}, V_{1:t}; caching reduces each step to one new query against a read-only cache.
(3) The Cost: Memory grows linearly (2 \cdot n \cdot d values per layer for K and V, O(L \cdot n \cdot d) across L layers) and becomes the inference bottleneck for long contexts and large batches.

Mathematical Formulation:
\mathrm{Attention}(q_t, K_{1:t}, V_{1:t}) = \mathrm{softmax}\!\left(\frac{q_t K_{1:t}^{\top}}{\sqrt{d_k}}\right) V_{1:t}
\mathrm{Memory}_{\text{cache}} = 2 \cdot L \cdot n \cdot d_{\text{model}} \;\; \text{values}

Where:

  • q_t is the query of the current token t; K_{1:t}, V_{1:t} are the cached keys and values for tokens 1 \ldots t.
  • d_k is the per-head key dimension, d_{\text{model}} the model width, and L the number of layers; the factor 2 counts K and V buffers separately.
Two-panel diagram of attention without cache, recomputing a full query matrix each step, versus with cache, computing only the new token's query and reusing cached keys and values.

Figure 1: Without cache every step recomputes the full Q, K, V; with cache only the new token’s query is computed while cached K/V (purple) supply the history.

Practical Note: During training the full sequence is processed in parallel so the cache does not apply; it is an inference-only optimization, and its size is why long-context serving is memory-bound rather than FLOP-bound.


Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *