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 be query heads and be key/value heads.
- multi-head attention (MHA): usually ;
- grouped-query attention (GQA): ;
- multi-query attention (MQA): .
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 , layers , cached length , and head width , keys and values contain
scalars. With , , , , and eight query heads:
| Design | Cache scalars | float32 bytes | |
|---|---|---|---|
| MHA | 8 | 8192 | 32768 |
| GQA | 2 | 2048 | 8192 |
| MQA | 1 | 1024 | 4096 |
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 , , , , and , how many K/V cache scalars are stored?
Compute it first, then check your number.
Hint
Solution
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.