KV caching
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.
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

$$ |\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.
- ↑ Pope, R., Douglas, S., Chowdhery, A., Devlin, J., Bradbury, J., Levskaya, A., Heek, J., Xiao, K., Agrawal, S., & Dean, J. (2023). Efficiently Scaling Transformer Inference. https://doi.org/10.48550/arXiv.2211.05102
- ↑ Gu, A., & Dao, T. (2024). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. https://doi.org/10.48550/arXiv.2312.00752