Key-Value Head Sharing Changes Inference Memory

Distinguish query heads from K/V heads and calculate exact cache reductions for multi-head, grouped-query, and multi-query attention.

Multi-query attention and grouped-query attention change how query heads share key and value projections. The query-head count may stay fixed while the number of K/V heads falls, reducing the decode cache.

Keep the Head Counts Distinct

Let hqh_q be query heads and hkvh_{kv} be key/value heads.

  • multi-head attention (MHA): usually hkv=hqh_{kv}=h_q;
  • grouped-query attention (GQA): 1<hkv<hq1<h_{kv}<h_q;
  • multi-query attention (MQA): hkv=1h_{kv}=1.

Several query heads share each K/V head in GQA or MQA. Scaled dot-product attention remains, but the projection and cache contract changes.

Calculate the Cache

For batch BB, layers LL, cached length TT, and head width dhd_h, keys and values contain

NKV=2LBhkvTdhN_{KV}=2LBh_{kv}Td_h

scalars. With B=1B=1, L=4L=4, T=16T=16, dh=8d_h=8, and eight query heads:

Designhkvh_{kv}Cache scalarsfloat32 bytes
MHA8819232768
GQA220488192
MQA110244096

MQA uses one eighth of this MHA cache. This is a shape result, not a latency benchmark. Kernel design, memory movement, batching, and hardware determine measured speed.

Q1. Calculate a grouped-query cache

For B=2B=2, L=3L=3, hkv=2h_{kv}=2, T=10T=10, and dh=4d_h=4, how many K/V cache scalars are stored?

Compute it first, then check your number.

Hint
Evaluate 2LBhkvTdh2LBh_{kv}Td_h.
Solution
2×3×2×2×10×4=9602\times3\times2\times2\times10\times4=960 scalars.
Not attempted
Review

Not marked done.

Preserve the Evidence Boundary

Shazeer (2019) reports multi-query decoding experiments for specified models and hardware. The cache formula generalizes under its declared tensor contract; the measured quality and speed results do not automatically generalize to every implementation.

Pause and reflect

In your own words, note what you understood, what remains unclear, or what you want to revisit. The note stays with this lesson.

0 of 1 exercises marked done

Review

Not marked done.

LLM PrimerKey-Value Head Sharing Changes Inference Memoryhttps://llmprimer.com/transformers/variants-scaling-and-boundaries/key-value-head-sharing-changes-inference-memory© 2026 LLM Primer