KV cache

last edited

A KV cache stores the attention keys and values of every token already processed, so an autoregressive transformer computes them once, not at every step. Each new token adds one row to the cache and attends over the stored rows. The price is memory that grows with context length and batch size.

keysvaluestoken t: compute one new k, vread rows 1 to t-1 from cacheno recompute of past tokenscache, one row per tokennew token (query)

Origins and the memory formula

08k: 1 gb32k: 4 gb131k: 16 gb2 x 32 layers x 8 kv heads x 128 x 2 bytes= 131,072 bytes per token

Caching keys and values is standard in incremental decoding. Shazeer's 2019 paper named the bottleneck: repeatedly loading the large key and value tensors costs memory bandwidth.

Per token the cache holds 2 x layers x KV heads x head dim x bytes. Take the 8B model in the Llama 3.1 config. It lists 32 layers and 8 KV heads. Head dim is 128 and the dtype is bfloat16. That gives 131,072 bytes per token. A full 131,072-token context then needs 16 gigabytes.

Methods that shrink and manage it

mha512 kibgqa128 kibmqa16 kibdots are query heads, blocks are cached kv heads

Multi-query attention shares one KV head across all query heads. GQA in 2023 keeps a middle number of KV heads. Llama 3.1 gives each group of four query heads one KV head.

PagedAttention in vLLM stores the cache in fixed blocks like virtual memory pages. It reports 2-4x throughput. Prefix caching reuses blocks when requests share a prompt start. RadixAttention does this with a tree.

KIVI quantizes keys per channel and values per token to 2 bits, for 2.6x less peak memory. DeepSeek-V2 packs keys and values into one latent vector and cuts the cache by 93.3 percent.

In image and video models

attends to cached k, vkv of finished chunksnew chunk9.4 fps streaming on one gpu (CausVid)

Most image generators refine patches in parallel via diffusion transformers, so they keep no such store. Step reuse is a separate idea. KV caches appear where output comes token by token or frame by frame.

LlamaGen applies next-token prediction to image tokens. VAR predicts whole scales, each attending to cached coarser ones. Among video models, CausVid makes a diffusion transformer causal and streams at 9.4 FPS using KV caching.

Sources