Bring the mental model from Scaled Dot-Product Attention & Transformer Layers; this page will reuse it instead of restarting from zero.
Attention & Transformers
Grouped-Query Attention: Sharing KV Heads
How multi-head, grouped-query, and multi-query attention differ by the number of key/value heads, and why reducing H_kv shrinks the decoding KV cache by H_kv / H_q.
Concept Structure
Grouped-Query Attention: Sharing KV Heads
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Grouped-Query Attention: Sharing KV HeadsConceptual Bridge
What should feel connected as you move through this page.
How multi-head, grouped-query, and multi-query attention differ by the number of key/value heads, and why reducing H_kv shrinks the decoding KV cache by H_kv / H_q.
The next edge should feel earned: use the demo prediction here before following LLM Serving at Scale: Prefill, Decode & Continuous Batching.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
Canonical sources: Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need", Ainslie et al., "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints", Touvron et al., "Llama 2: Open Foundation and Fine-Tuned Chat Models", and Meta, "The Llama 3 Herd of Models".
In standard multi-head attention, every query head has its own key head and value head. That is expressive, but during autoregressive decoding it means every layer stores a key vector and a value vector for every head at every previous token.
Grouped-query attention changes one invariant: keep many query heads, but use fewer key/value heads. Several query heads share the same cached keys and values. Multi-query attention is the extreme case where all query heads share one KV head.
This is not the same as making attention sparse or approximate. Each query head still attends over the full context. The saving comes from storing and reading fewer cached KV channels during decoding.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let a transformer layer have
query heads and
key/value heads. Assume is divisible by and define the group size
For query head , the shared KV head index is
The attention output for head is
For one decoded token, is a query vector with shape . The cached and tensors have shape for the selected shared KV head. GQA changes which cached KV channel a query head reads; it does not remove context positions from the softmax.
The three common cases are:
- Multi-head attention: , so .
- Grouped-query attention: , so a group of query heads shares each KV head.
- Multi-query attention: , so every query head shares the same KV head.
During decoding, the KV cache for a batch of sequences, layers, context length , head dimension , and element width bytes is approximately
The factor of 2 stores both keys and values. Compared with multi-head attention, the KV-cache ratio is therefore
and the reduction factor is
That ratio is the core invariant. If a model keeps query heads but uses KV heads, the decoding KV cache is one quarter of full multi-head attention for the same batch, layers, context length, head dimension, and dtype.
This is a logical fixed-shape cache estimate. Real serving stacks may add paging metadata, fragmentation, cross-device duplication, or temporary expanded KV views, so measured allocator memory can differ from the clean structural ratio.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
This witness checks the head-sharing map and the KV-cache memory ratio. It deliberately ignores model-quality questions and focuses only on the structural invariant.
def architecture(h_q, h_kv):
if h_kv == h_q:
return "MHA"
if h_kv == 1:
return "MQA"
return "GQA"
def kv_head_for_query(q_head, h_q, h_kv):
assert h_q % h_kv == 0
group_size = h_q // h_kv
return q_head // group_size
def kv_cache_gb(tokens, layers, h_kv, d_head, batch=1, bytes_per_elem=2):
elements = batch * layers * tokens * h_kv * d_head * 2
return elements * bytes_per_elem / 1e9
h_q = 32
h_kv = 8
tokens = 128_000
layers = 32
d_head = 128
selected_q = 9
group_size = h_q // h_kv
selected_kv = kv_head_for_query(selected_q, h_q, h_kv)
gqa_cache = kv_cache_gb(tokens, layers, h_kv, d_head)
mha_cache = kv_cache_gb(tokens, layers, h_q, d_head)
ratio = gqa_cache / mha_cache
assert architecture(h_q, h_kv) == "GQA"
assert group_size == 4
assert selected_kv == 2
assert ratio == h_kv / h_q
print({
"architecture": architecture(h_q, h_kv),
"group_size": group_size,
"selected_mapping": f"Q{selected_q} -> KV{selected_kv}",
"kv_cache_gb": round(gqa_cache, 2),
"ratio_vs_mha": ratio,
"reduction_factor": h_q / h_kv,
})
The same arithmetic classifies MHA and MQA. Set and the group size becomes 1; set and the group size becomes all query heads.
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
Use the demo to vary , , context length, and head dimension. Before reveal, the exact sharing group, selected Q-to-KV mapping, cache size, and ratio are hidden.
Commit two predictions: the number of query heads per KV head, and the KV-cache fraction relative to MHA. Reveal checks both predictions and then shows the architecture class, selected mapping, cache GB, ratio, and memory reduction factor.
Live Concept Demo
Explore Grouped-Query Attention: Sharing KV Heads
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Commit to what Grouped-Query Attention: Sharing KV Heads should make visible before reading the result.
After The First Pass
Turn the concept into an inspected object.
Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.
Mechanism Storyboard
See the idea move before the page explains it
How multi-head, grouped-query, and multi-query attention differ by the number of key/value heads, and why reducing H_kv shrinks the decoding KV cache by H_kv / H_q.
Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change Grouped-Query Attention: Sharing KV Heads should make visible.
Visual Inquiry
Make the image answer a mathematical question
How multi-head, grouped-query, and multi-query attention differ by the number of key/value heads, and why reducing H_kv shrinks the decoding KV cache by H_kv / H_q.
Which visible object should carry the first intuition?
Pick the cue that should make Grouped-Query Attention: Sharing KV Heads easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Primary MQA source. Grounds the incremental-decoding memory-bandwidth bottleneck and the idea of sharing keys and values across query heads.
Open sourcePrimary GQA source. Introduces grouped-query attention as an intermediate between multi-head attention and multi-query attention.
Open sourceModel report that uses grouped-query attention in larger Llama 2 variants; useful as adoption/context evidence, not the core mechanism proof.
Open sourceModel report that documents GQA use in the Llama 3 family; useful as adoption/context evidence, not the core mechanism proof.
Open sourceClaim Review
How multi-head, grouped-query, and multi-query attention differ by the number of key/value heads, and why reducing H_kv shrinks the decoding KV cache by H_kv / H_q.
Claims without a substantive review badge still need exact source-support review.
shazeer-2019-mqa, ainslie-2023-gqa, touvron-2023-llama2, meta-2024-llama3
Use equation, code, and demo objects to check whether the source support is operational.
Shazeer supports MQA by removing the K/V heads dimension and reducing incremental-decoding memory access by h. Ainslie supports GQA as query-head groups sharing K/V heads between MQA and MHA. Llama 2/3 support adoption/context.
Sources: Fast Transformer Decoding: One Write-Head is All You Need, GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints, Llama 2: Open Foundation and Fine-Tuned Chat Models, The Llama 3 Herd of ModelsLogical fixed-shape decoding KV-cache size only; excludes expanded KV views, paging/fragmentation, sharding duplication, quantization, prefill memory, quality, and latency claims.A bounded review summary is present; still check caveats and exact source scope.Checked Shazeer 2019, Ainslie et al. 2023, Llama 2, and Llama 3. Shazeer and Ainslie ground the mechanism and cache/head-count ratio: Shazeer covers the MQA endpoint and incremental-decoding bandwidth term, while Ainslie defines GQA as query-head groups sharing one K/V head. Llama 2 and Llama 3 support adoption and deployment motivation, not the formula proof.
Reviewer: codex+gpt-pro-batch2; reviewed 2026-06-27Source support candidates
paper 2019Fast Transformer Decoding: One Write-Head is All You NeedPrimary MQA source. Grounds the incremental-decoding memory-bandwidth bottleneck and the idea of sharing keys and values across query heads.
paper 2023GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsPrimary GQA source. Introduces grouped-query attention as an intermediate between multi-head attention and multi-query attention.
paper 2023Llama 2: Open Foundation and Fine-Tuned Chat ModelsModel report that uses grouped-query attention in larger Llama 2 variants; useful as adoption/context evidence, not the core mechanism proof.
paper 2024The Llama 3 Herd of ModelsModel report that documents GQA use in the Llama 3 family; useful as adoption/context evidence, not the core mechanism proof.
Practice Loop
Try the idea before it explains itself
How multi-head, grouped-query, and multi-query attention differ by the number of key/value heads, and why reducing H_kv shrinks the decoding KV cache by H_kv / H_q.
Before touching the demo, predict one visible change that should happen in Grouped-Query Attention: Sharing KV Heads.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
Research Room
Attach the question to an exact object
Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.Open the draft below to save one note and next action in this browser.
Grouped-Query Attention: Sharing KV Heads
What is the smallest example that makes Grouped-Query Attention: Sharing KV Heads click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays locally in this browser for concept:attention-transformers/grouped-query-attention.
- Source ids to inspect: shazeer-2019-mqa, ainslie-2023-gqa, touvron-2023-llama2, meta-2024-llama3
- Definition, prerequisite, and contrast concept links
- The equation or code witness that makes the concept operational
- One demo state that shows the invariant instead of a slogan
- The learner can state the mechanism in their own words
- The learner can name the prerequisite that would repair confusion
- The learner can predict how the mechanism changes under one perturbation
I am working in Continuous Function's research reading room. Object: concept - Grouped-Query Attention: Sharing KV Heads Object key: concept:attention-transformers/grouped-query-attention Context: Attention & Transformers Anchor id: concept/concept-notebook/attention-transformers/grouped-query-attention Open question: What is the smallest example that makes Grouped-Query Attention: Sharing KV Heads click without losing the math? Evidence to inspect: - Source ids to inspect: shazeer-2019-mqa, ainslie-2023-gqa, touvron-2023-llama2, meta-2024-llama3 - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.
concept/concept-notebook/attention-transformers/grouped-query-attention
concept:attention-transformers/grouped-query-attention