Jump to content

KV caching

From Wikibase

Languages: English · français · Esperanto

KV caching is a technique to reduce computational cost during sequential next token prediction in Transformers by caching the attention keys and values computed for earlier tokens for use in calculation of later tokens.

[1]

Compute without KV caching

To generate an output token sequence of length $T$ via sequential next token prediction:

At step $t$ the model evaluates attention (e.g., self-attention) over the first $t$ tokens processed so far, at cost $O(t^2d)$, where $d$ is the hidden dimension of the attention mechanism.

Overall compute:

$$ \sum_{t=1}^{T}O(t^2d)=O(T^3 d) $$

where $O$ is the big-O notation.

Compute with KV caching

With the cache in place, each step scores only the 1 new token against the $t$ stored keys and values, at cost $O(td)$, and the total becomes

$$ \sum_{t=1}^{T}O(td)=O(T^2 d), $$

Memory tradeoff

As the context window of LLMs grow larger, approaching or exceeding $10^6$ tokens in 2026, the memory cost of KV caching can itself become a bottleneck. · Open in a new tab

$$ |\mathbf{K}|+|\mathbf{V}|=2Td $$

scalars per layer.

Which means, memory size required for full caching grows linearly with the length of the generated sequence.

[2]