KcacheK_{\text{cache}}

The KV cache

Read "K cache" and "V cache". They store the keys and values of earlier tokens during generation, so each is computed once instead of again at every step.

During generation, the keys and values of earlier tokens never change; each step only adds one new row. Storing them cuts the attention work at step tt from O(t2)\mathcal{O}(t^2) to O(t)\mathcal{O}(t), so generating TT tokens costs O(T2)\mathcal{O}(T^2) instead of O(T3)\mathcal{O}(T^3).

The cost is memory. The cache grows in proportion to context length and batch size, and for long contexts or large batches it can take more memory than the model's weights. Reducing it is the main motivation for grouped-query attention (GQA), multi-query attention (MQA) and paged attention.

Where the course uses it

Related terms