LearnQuestion bank

What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually memory-bandwidth-bound, and describe how grouped-query or multi-query attention changes this.

ResearchTechnicalHard

Theme reported publicly: OpenAI

Answer it yourself first, out loud or on paper, then compare.

Answer

Model answer, written in a candidate's voice

In short

  • Per layer, store K and V for all past tokens; each decode step computes only the new token’s Q (and its K/V to append).
  • Memory ≈ 2 × layers × kv_heads × head_dim × seq_len × batch × bytes.
  • Decode reads all weights plus the whole cache for one token, so arithmetic intensity is low and it is usually memory-bandwidth-bound.
  • GQA/MQA reduce kv_heads (MQA to 1, GQA in between), shrinking the cache by roughly heads/kv_heads versus multi-head attention.
  • Paged allocation, eviction/sliding-window or token-dropping, and quantised K/V caches reduce footprint; prefill is parallel/compute-heavy while decode is sequential/bandwidth-heavy.

In full

During autoregressive generation, the key-value cache stores, for every layer, the K and V tensors for all previously generated tokens, so each new step only needs to compute the new token’s query (and its K/V to append) and attend against the cached K/V. Its footprint is approximately 2 × layers × kv_heads × head_dim × seq_len × batch × bytes, where the factor 2 is for K and V and bytes is the element size. Decoding is usually memory-bandwidth-bound because each token requires reading essentially all model weights plus the full cache while doing very little arithmetic, giving low arithmetic intensity. Grouped-query and multi-query attention reduce kv_heads—MQA down to one and GQA to a small number between one and the number of query heads—so the cache shrinks by about heads/kv_heads compared with standard multi-head attention. In practice, systems also use paged/block allocation to avoid fragmentation and enable sharing, eviction or sliding-window/token-dropping to bound the cache, and quantised K/V storage to cut bytes; this matters because prefill processes the prompt in parallel and is compute-heavy, while decode is sequential one-token-at-a-time and bandwidth-heavy.

Corrected by an independent AI reviewer.

What a strong answer covers

  • Per layer, cache K and V for past tokens, and compute only the new token’s query.
  • Memory ≈ 2 × layers × kv_heads × head_dim × seq_len × batch × bytes.
  • Each decode step reads all the weights plus the cache for little compute (low arithmetic intensity).
  • GQA/MQA shrink the cache by heads/kv_heads.
  • Paged memory, eviction and quantised caches; prefill vs decode.

Common mistakes

  • Dropping the factor of 2 or the layer count.
  • Thinking the cache changes model outputs.