AcademyAcademy
DocsLearnGitHub

Course

AI & LLM Foundations

Loading progress...

  1. 1

    The Idea Behind AI Models

    5 min read

  2. 2

    Agents, Tools and MCP

    2 min read

  3. 3

    Benchmark Methodology

    1 min read

  4. 4

    Technical Correction Register

    3 min read

  5. 5

    AI Network Infrastructure

    4 min read

  6. 6

    Mechanistic Interpretability

    3 min read

  7. 7

    Hardware Economics and Inference

    6 min read

  8. 8

    KV Cache, SSM State, and Context Engineering

    5 min read

  9. 9

    Quantization, Optimization, and Model Metadata

    4 min read

  10. 10

    Self-Attention, Multi-Head Attention, and Cross-Attention

    5 min read

  11. 11

    Source Audit

    2 min read

Publications
  • All publications
  • Publication 01Why a Bigger GPU Doesn't Always Mean Faster AI Inference
  • Publication 02Why Your AI Takes Time to Think Before It Starts Speaking
  • Publication 03The KV Cache: The Memory Behind Every Token
  • Publication 04Multi-Head Attention, Grouped-Query Attention and Multi-Query Attention
← Source publicationsRelated curated lesson →

Source publication. Illustration placeholders and evidence labels are preserved as supplied.

Multi-Head Attention, Grouped-Query Attention and Multi-Query Attention

Understanding how attention heads work, why models share KV heads, and what it means for inference

AI, LLMs & Neural Network Engineering, Publication 04


How to read the evidence labels

Technical claims in this article carry a label where the source matters.

LabelMeaning
VERIFIEDDirectly supported by a primary source or authoritative document that I opened while writing
CALCULATEDDerived arithmetically from stated assumptions; you can reproduce it
REPORTEDStated by a paper, vendor or secondary source; not independently reproduced
HYPOTHESISPlausible reasoning, not demonstrated here
UNRESOLVEDEvidence is insufficient or conflicting

The filing cabinet problem

Imagine a panel of 32 analysts reading a very long document, one word at a time. Every analyst asks their own question about each new word: "Who is doing the action?", "What does this pronoun refer to?", "Which earlier word does this one depend on?"

To answer, each analyst needs notes on every word read so far. In the simplest arrangement, every analyst keeps a private filing cabinet with their own copy of those notes. That is generous, and it is also expensive: 32 cabinets, all updated with every new word, all consulted again for the next one.

There are two obvious ways to economize. You can keep the 32 analysts and their 32 different questions, but make groups of them share a cabinet. Or you can make all 32 share a single cabinet.

That is the whole story of this publication. The analysts are query heads. The cabinets are key/value heads. The three arrangements are Multi-Head Attention (MHA), Grouped-Query Attention (GQA) and Multi-Query Attention (MQA).

The question we will follow is:

Why do Transformers use multiple attention heads, and why have architectures evolved from MHA towards GQA and MQA?

Publication 03 explained what the cabinets cost in memory. This one explains why there are so many of them, why it turned out we can often do with fewer, and what that does and does not buy us.


1. The problem we inherit from Publication 03

During generation, the model caches the keys and values of every earlier token so it never has to recompute them. Per layer, per token, the cache needs:

bytes per token per layer = 2 × H_kv × d_head × B

where H_kv is the number of KV heads, d_head is the width of each head, B is bytes per element (2 for FP16), and the leading 2 is for storing both K and V.

Two things follow, and they are why this article exists.

First, H_kv sits directly in that formula. Anything that changes the number of KV heads changes the cache size, linearly. CALCULATED

Second, the cache is not only stored, it is read again for every generated token. The original MQA paper (Shazeer, 2019) identified exactly this as the bottleneck: incremental decoding is slow because of the memory-bandwidth cost of repeatedly loading the large keys and values tensors. VERIFIED (arXiv:1911.02150, abstract)

So there are two reasons to care about KV heads: capacity (does it fit?) and bandwidth (how long does it take to read?).


2. Why attention has heads at all

AI-assisted diagram: separate learned projections produce Q, K and V.

We only need the essentials here. A token's hidden vector is projected three ways:

  • Query (Q): what this position is looking for.
  • Key (K): an indexed description of what each position offers.
  • Value (V): the information that actually gets passed along.

Attention compares queries with keys to get scores, normalizes them with softmax, and uses them to take a weighted sum of values. These are learned projections, not literal questions or database rows.

A single attention computation produces one attention map, which means one perspective on the sentence. Take "The detective followed the spy with binoculars." Who has the binoculars? A single head tends to commit to one reading and largely ignore the other. Multi-head attention fixes this by running several attention computations in parallel, each with its own learned projections, so different heads can pick up different relationships (who is acting, what is nearby, how the grammar fits together).

AI-assisted diagram: multiple heads operate on projected representations.

Each head works in a smaller space of width d_head. In the memoir's teaching example, a 512-wide representation is split into four heads of 128. Because each head is narrower, running several of them costs roughly what one wide head would, under the convention that the head widths add up to the model width. That example is illustrative. Real models choose their own head counts and widths, and nothing in the mechanism requires the head widths to add up to the hidden size (see the memoir flags at the end).

Important: from here on, keep two counts separate. Query heads decide how many different questions are asked. KV heads decide how many different sets of notes are kept. MHA, GQA and MQA differ only in the relationship between these two numbers.


3. Multi-Head Attention: one cabinet per analyst

In MHA, every query head has its own key head and its own value head. With 32 query heads you have 32 key heads and 32 value heads.

AI-assisted diagram: representative one-to-one pairs out of 32; each KV head contains a key head and a value head.

This is the most expressive arrangement. Every head can look at the sequence through its own keys and carry its own values. It is also the most expensive one to cache.


4. Two ways to share: MQA, then GQA

Multi-Query Attention

Shazeer proposed keeping all the query heads but sharing a single key head and a single value head across them. VERIFIED (arXiv:1911.02150)

AI-assisted diagram: all 32 query heads share one key head and one value head.

The paper reports that the resulting models can be much faster to decode, with only minor quality degradation relative to the baseline. VERIFIED (abstract). Note that this is the author's own result, on the models and tasks of that paper.

Grouped-Query Attention

GQA, introduced by Ainslie et al. (2023), is the middle ground. The query heads are divided into G groups, and each group shares one key head and one value head. VERIFIED (arXiv:2305.13245)

AI-assisted diagram: representative groups from eight groups of four query heads.

The paper's own notation makes the family explicit: GQA with one group is MQA, and GQA with as many groups as query heads is MHA. VERIFIED So these are not three unrelated mechanisms. They are three settings of one dial, the number of KV heads.

Query headsKV headsQuery heads per KV head
MHAHH1
GQAHG (1 < G < H)H / G
MQAH1H

AI-assisted diagram: summarized head-sharing relationships for the stated example.

Important: the number of query heads does not change. GQA and MQA do not remove questions; they remove duplicated notes.

Why the GQA paper exists

Two motivations are stated in the paper itself. VERIFIED

  • MQA can degrade quality and cause training instability, and training a separate model only for fast inference may not be desirable.
  • Large models tend to scale their head counts, so cutting to a single KV head becomes a more aggressive reduction for them, and standard sharding replicates that single head across model partitions. GQA avoids that waste.

5. The worked example

This is the memoir's example: 32 query heads, head dimension 128, FP16 (2 bytes per element).

AI-assisted diagram: 32 query heads, head dimension 128 and FP16; excludes runtime overhead.

M = 2 × H_kv × d_head × B      (per token, per layer)

MHA: 2 × 32 × 128 × 2 = 16,384 bytes
GQA: 2 ×  8 × 128 × 2 =  4,096 bytes   (4 query heads per KV head)
MQA: 2 ×  1 × 128 × 2 =    512 bytes

CALCULATED. GQA with 8 KV heads stores one quarter of MHA, and MQA one thirty-second.

Per-token, per-layer numbers are small, so let us scale them up. The cache is multiplied by the number of layers and the number of cached tokens.

Two real configurations

ModelLayersQuery headsKV headsHead dimKV per token (FP16)Per 8,192-token sequenceSame model if it used MHA
Mistral 7B32328128128 KiB1.0 GiB4.0 GiB
Llama 3 70B80648128320 KiB2.5 GiB20.0 GiB

CALCULATED from configuration values that are REPORTED below. Assumptions: FP16 cache, every layer caches all tokens, no padding or allocator overhead (the same simplifications as Publication 03).

What was read, and what was derived:

  • Mistral 7B: the configuration lists 32 hidden layers, 32 attention heads, 8 key/value heads and hidden size 4096. The head dimension of 128 is derived as 4096 / 32 (the file does not print it). Several copies of this configuration were checked on Hugging Face; the v0.1 configuration also sets a sliding window of 4,096, which would cap the cache, so the 8,192-token figure is the full-attention case. A v0.3 configuration shows the same head counts with the sliding window disabled.
  • Llama 3 70B: hidden size 8192, 64 attention heads, 80 layers, 8 KV heads. The head dimension of 128 is derived as 8192 / 64 and is consistent with an independent paper's remark that Llama 3 70B stores 2 × 8 × 128 = 2,048 cache elements per token per layer. REPORTED
  • These configurations were read from copies hosted in community repositories, not from Meta's or Mistral's own gated or official pages. Treat them as REPORTED.

The Mistral 7B row happens to reproduce the memoir's 32-query-head, 8-KV-head, 128-dimension example exactly.

A small helper, if you want to run your own numbers:

def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_elem=2):
    return 2 * layers * kv_heads * head_dim * bytes_per_elem

# Llama 3 70B as configured above
per_tok = kv_bytes_per_token(80, 8, 128)       # 327,680 bytes = 320 KiB
per_seq = per_tok * 8192 / 2**30               # 2.5 GiB

6. What does not change

This is where people overreach, so let us be precise.

Query heads stay. In a GQA model with 32 query heads and 8 KV heads, there are still 32 distinct attention maps per layer. The 4 query heads that share a KV head ask different questions of the same notes. VERIFIED by definition (Ainslie et al.)

Score computation is not reduced. Each query head still computes its scores against the keys. The cost of that step depends on the number of query heads, the head width and the number of cached tokens, and not on the number of KV heads. For one new token against n cached tokens, a simplified count of the query-key dot products is 2 × H_q × d_head × n floating-point operations (one multiply and one add per element), which for 32 query heads, width 128 and n = 8,192 is 67,108,864 whether the model has 32, 8 or 1 KV heads. CALCULATED, ignoring softmax and the value-weighted sum (which scale the same way).

What does shrink is the cache, the cache traffic, and the K and V projection matrices. For a hidden size of 4096 and head width 128, the K and V projections per layer hold 33.5M, 8.4M and 1.05M parameters under MHA, GQA-8 and MQA respectively. CALCULATED

That last point matters for fair comparison. Cutting KV heads removes parameters, so an honest comparison must say whether total parameter count was held constant. The Llama 2 paper did exactly this: to keep overall parameter count similar across MHA, GQA and MQA variants, it enlarged the feed-forward layers to compensate for the smaller attention layers. VERIFIED (arXiv:2307.09288, appendix)

Warning: "fewer KV heads" does not mean "less attention computation". It means a smaller cache and less data to read for the same number of questions.


7. Why the industry moved this way

The motivation is an engineering one, and it has three parts.

Capacity

A smaller cache per token means more tokens or more concurrent sequences fit in the same GPU memory. In the Llama 3 70B example above, an MHA-style cache would be 8 times larger for the same sequence. CALCULATED

Bandwidth

Decode generates one token at a time, and each step must read the weights and the cached keys and values. Weight reads are shared by every sequence in a batch, while cache reads are per sequence. So the larger the batch and the longer the context, the larger the share of traffic that is KV cache, and the more a smaller cache helps. HYPOTHESIS as a reasoning step from the roofline picture in earlier publications; it is the same argument the MQA paper makes about bandwidth. The converse is also expected: with a single sequence and short context, the weights dominate and fewer KV heads should change decode speed little.

Meta's Llama 2 appendix is consistent with this. It reports that multi-query variants allow higher throughput at larger batch sizes and show similar latency at smaller batches. VERIFIED (Figure 24 caption, arXiv:2307.09288). I am paraphrasing the finding, which was measured on Meta's setup and models.

Quality

Sharing has a cost in expressiveness, and the evidence on its size is mixed in an interesting way:

  • The GQA paper reports that uptrained GQA reaches quality close to MHA while being almost as fast as MQA, on the T5 models and tasks it tested. VERIFIED (abstract). It also states that MQA can degrade quality and cause training instability.
  • Llama 2 chose GQA over MQA for the 34B and 70B models, citing its ablation results and ease of scaling inference. VERIFIED
  • DeepSeek-V2 states that MQA and GQA need less cache but do not match MHA performance, and provides its own ablation (Appendix C.1 of their paper). REPORTED by authors who are advocating an alternative (see section 9), so weigh it accordingly.
  • Llama 3 adopted GQA for both the 8B and 70B models, which Meta describes as an inference-efficiency choice. VERIFIED (model card)

What this supports: a quality-versus-memory trade-off exists, and GQA with a moderate number of KV heads has been a popular compromise in widely used open models. What it does not support: that one arrangement is universally best. How much quality a given reduction costs depends on the model, the training recipe and the task. UNRESOLVED as a general statement.


8. What it means for hardware and deployment

AI-assisted diagram: each query produces its own attention weights over the shared keys and values.

When a model is split across GPUs with tensor parallelism, attention is sharded by head. With 8 KV heads this is clean up to 8 GPUs: each GPU can own one KV head and its share of the cache. Beyond that there are not enough KV heads to go around.

Inference engines handle this by replicating KV heads across GPUs. vLLM's documentation of decode context parallelism describes it directly: once the tensor-parallel size exceeds the number of KV heads, the cache starts duplicating, with tp // num_kv_heads identical copies. VERIFIED (vLLM blog). An independent glossary and an independent paper describe the same behaviour. REPORTED

For Llama 3 70B with 8 KV heads:

Tensor-parallel sizeKV heads per GPUCache behaviour
42Sharded cleanly
81Sharded cleanly
161 (each head on 2 GPUs)2 identical copies; extra GPUs add no extra cache capacity for it

CALCULATED from the rule above.

The practical lesson is that the KV-head count is a deployment parameter, not just an architecture detail. It sets how far you can scale a model across GPUs before the cache stops dividing, and it affects how much memory is left for batching and context.

One caution: "all modern open models use 8 KV heads" is a tempting generalization and it is wrong. Reported configurations include models with fewer, for example 2 KV heads for a 32-query-head Qwen model and 4 for Qwen-30B-A3B. REPORTED. Always read the model's own configuration. In llama.cpp-style metadata the fields are head_count (query heads) and head_count_kv (KV heads), as the memoir notes.

Important: fewer KV heads do not automatically make everything faster. Kernel implementation, hardware, batch size, context length and parallelism strategy all decide what you actually see. If you are choosing hardware, compute the cache from the real configuration (section 5) and then benchmark.


9. Beyond sharing: a pointer to MLA

GQA and MQA reduce the cache by sharing. DeepSeek-V2 took a different route called Multi-head Latent Attention (MLA), which compresses keys and values jointly into a low-rank latent vector and caches that. VERIFIED (arXiv:2405.04434). The paper reports a 93.3% KV-cache reduction versus DeepSeek 67B. REPORTED, and note that this compares two different models (a dense one and a mixture-of-experts one), so it is not a clean measurement of attention design alone. MLA is a topic of its own and we leave it there.


10. Converting an existing model

You do not always have to train a GQA model from scratch. The GQA paper describes converting an MHA checkpoint by mean-pooling the original heads within each group into one key head and one value head, then continuing training for a small fraction of the original compute. For the T5 experiments in the paper that fraction was 5%. VERIFIED (arXiv:2305.13245). That result is for those models; I have not verified how well it transfers to other architectures.


Takeaways

  1. Multi-head attention exists to give a model several perspectives on the same text.
  2. Query heads ask; KV heads remember. MHA, GQA and MQA are three settings of one dial: how many KV heads serve the query heads.
  3. Fewer KV heads shrink the cache, the cache traffic and the K/V projections. They do not reduce the number of attention maps or the score computation.
  4. The benefit is largest at long context and high concurrency, where the cache dominates memory and traffic.
  5. There is a quality trade-off whose size depends on the model and recipe. There is no universal winner.
  6. The KV-head count shapes deployment, because it limits how far the cache can be divided across GPUs.

Publication 03 asked how much memory the cache takes. This one asked why the cache is that size and how designers shrink it. There is a different problem inside attention that sharing does not touch: the attention scores themselves. The next publication, on FlashAttention, picks that up.


Issues found in the source memoir

These were flagged rather than silently corrected. Line references are to AI memoir refine.md.

  1. GQA sharing wording (L1212). The OCR reads as though GQA lets "1 Query" share. The same page's arithmetic (2 × 8 × 128 × 2 = 4,096) implies 8 KV heads, so 4 query heads per KV head. This article uses 4.
  2. Truncated sharing sentences (L1208–1210, L628–631). Both describe GQA reducing the number of key heads by letting query heads share, but one ends without its object and the other is partly illegible. The article states it as: GQA reduces the number of KV heads. The memoir's phrasing says "key heads" only.
  3. Hidden size versus heads × head width (L641–645; Appendix A). The memoir's 512 = 4 × 128 example is a good teaching case, and its other example (24 query heads × 256 = 6,144 query width, 4 × 256 = 1,024 KV width) treats hidden size as a separate quantity. Nothing in the mechanism forces the head widths to add up to the hidden size. This article does not assume it.
  4. "Same computational cost as one large head" (Appendix A text). True approximately for the projections under the equal-width convention, but not a general law. The article hedges it.
  5. "Couldn't use d_q because … Grouped Query or Multi Query Attention" (L1335). The query and key vectors must have the same width for the dot product, so d_q = d_k per head even in GQA and MQA. What GQA and MQA change is the number of KV heads, not the per-head width. The stated reason looks off, so this article does not repeat it.
  6. Query heads versus KV heads (general). Some memoir lines say "number of key heads" where "KV heads" is meant. The article uses KV heads throughout.

Sources

  • Shazeer, N. (2019). Fast Transformer Decoding: One Write-Head is All You Need. arXiv:1911.02150. https://arxiv.org/abs/1911.02150
  • Ainslie, J. et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. arXiv:2305.13245 (EMNLP 2023). https://arxiv.org/abs/2305.13245
  • Touvron, H. et al. (2023). Llama 2: Open Foundation and Fine-Tuned Chat Models. arXiv:2307.09288, Appendix A.2.1. https://arxiv.org/abs/2307.09288
  • Meta. Llama 3 model card. https://github.com/meta-llama/llama3/blob/main/MODEL_CARD.md
  • DeepSeek-AI (2024). DeepSeek-V2. arXiv:2405.04434. https://arxiv.org/abs/2405.04434
  • vLLM blog, Efficient Decode Context Parallelism with vLLM for Long Context Workloads. https://vllm.ai/blog/2026-08-07-decode-context-parallelism
  • SemiAnalysis InferenceX glossary, KV head replication. https://inferencex.semianalysis.com/glossary/kv-head-replication
  • Model configurations (Mistral 7B, Llama 3 70B): config.json files as hosted in community Hugging Face repositories; the official repositories were not opened.
  • Qwen KV-head counts: the same glossary entry, and Shift Parallelism, arXiv:2509.16495.
  • Llama 3 70B cache width of 2 × 8 × 128: TPLA, arXiv:2508.15881.