AI State of the Art
SOTA/Advanced Attention Mechanisms/25 min
Section 72

Multi-Query Attention (MQA)

Listen as a podcast →

The bottleneck nobody sees

You're waiting for a response from ChatGPT. The model generates word by word, each token takes about 50 to 100 ms. Why so slow? You might think it's a compute power problem, that the GPU is grinding away at full capacity to produce each word.

In reality, it's the opposite. During token-by-token generation, the GPU is often half idle. It's waiting. The real bottleneck is memory: for each new token generated, the model must re-read from GPU RAM the key (K) and value (V) vectors of all previous tokens, that's the famous KV cache. And reading this memory is slow compared to the GPU's compute speed.

Imagine a brilliant student (the GPU) who can solve equations very fast, but who at each step has to go fetch a book from a huge library. It's not the computation that slows them down, it's the trip to the book.

For a 70-billion parameter model with 80 layers, 64 heads, and a context of 8,000 tokens, the KV cache exceeds 20 gigabytes (the detailed arithmetic is just below). Re-reading over 20 GB of memory for each generated token, that's the real bottleneck.

Multi-Query Attention (MQA), proposed by Noam Shazeer in 2019, is an elegant and radical solution to this problem.

Fast Transformer Decoding: One Write-Head is All You Need

Refresher: standard Multi-Head Attention

In standard MHA (Multi-Head Attention), each attention head i has its own projections for queries, keys, and values:

Qi=X⋅WiQ,Ki=X⋅WiK,Vi=X⋅WiVQ_i = X \cdot W_i^Q, \quad K_i = X \cdot W_i^K, \quad V_i = X \cdot W_i^V

In plain terms: XX is the text being processed (one vector per token), and WiQW_i^Q, WiKW_i^K, WiVW_i^V are the three weight matrices of head ii, parameters learned during training, frozen afterwards. Applying them to the text, each head computes its own queries QiQ_i, keys KiK_i and values ViV_i, results, recomputed for every new text.

For H heads with per-head dimension dk=d/Hd_k = d / H, the KV cache stores 2×H×L×dk2 \times H \times L \times d_k elements per layer: HH is the number of heads, LL the number of tokens in the context, dkd_k the size of one key (or value) vector, and the factor of 2 counts the two things being stored, the key and the value. No factor of 3: the current token's query is used once and never again, so it is never stored, the full explanation is in the multi-head attention lesson. With H = 64 heads, L = 8,000 tokens, dkd_k = 128: that gives 2 x 64 x 8,000 x 128 = 131 million elements per layer. Multiply by 80 layers = 10.5 billion elements, or about 21 GB in float16 (2 bytes per element).

The KV cache: why it exists

During autoregressive generation, each new token must "look at" all previous tokens via the attention mechanism. Without a cache, you'd have to recompute the K and V projections of the entire context at each new token, a colossal waste. The KV cache stores these projections once and for all: you cache what gets re-read at every step (the keys and values of the whole past), not what is used once (the current token's query). It's essential for speed, but it keeps growing with context length. For a 70B model with 128K tokens of context, the same arithmetic gives hundreds of GB.

The MQA mechanism: a single K/V pair for all heads

Shazeer's idea is disarmingly simple: instead of giving each head its own K and V projections, share a single K/V pair across all heads.

Qi=X⋅WiQ(DISTINCT per head, H projections)Q_i = X \cdot W_i^Q \quad \text{(DISTINCT per head, H projections)} K=X⋅WK(SHARED across all heads, 1 single projection)K = X \cdot W^K \quad \text{(SHARED across all heads, 1 single projection)} V=X⋅WV(SHARED across all heads, 1 single projection)V = X \cdot W^V \quad \text{(SHARED across all heads, 1 single projection)}

Reading these three lines: each head keeps its own query matrix WiQW_i^Q, but there is now only one key matrix WKW^K and one value matrix WVW^V for everyone, hence a single KK and a single VV.

Sharing the matrix or sharing the result: same thing

MQA can be described two ways: "the heads share the weight matrices WKW^K and WVW^V" (the learned parameter) or "the heads share the keys and values KK and VV" (the result computed on the text). The two formulations are equivalent: the same matrix applied to the same input XX necessarily produces the same result. The savings, however, are on the result side: what grows with the conversation and saturates memory is the cache of computed KK and VV, not the weight matrices, whose size never changes.

Each head still computes its own attention, with its own query:

headi=softmax ⁣(Qi⋅K⊤dk)⋅V\text{head}_i = \text{softmax}\!\left(\frac{Q_i \cdot K^\top}{\sqrt{d_k}}\right) \cdot V

In words: head ii compares its queries QiQ_i to the shared keys KK, divides by dk\sqrt{d_k} to keep the scores in a reasonable range, turns those scores into weights that sum to 1 (the softmax), and uses them to take a weighted average of the shared values VV.

So all heads query the same keys and values. The diversity between heads comes solely from the queries, they determine "what each head is looking for" in the context.

Diagram titled Multi-Query Attention. At the top, an Input X box with arrows to four boxes Q1, Q2, Q3, Q4 and to two stacked boxes K (shared) and V (shared). Dashed orange arrows connect the single K/V pair to four Attn boxes, each of which also receives the arrow from its own query. The four Attn boxes converge into a Concat + Project box. On the side, a label reads KV Cache: 1 x (K + V).
The mechanism in one picture. Every head keeps its own query (Q1 to Q4, blue arrows), but there is only one K and one V, fanned out to all heads by the dashed orange arrows. The label on the right sums up the payoff: whatever the head count, the cache holds a single key/value pair.Source : Marcel Brenndoerfer, Multi-Query Attention

KV cache reduction: a factor of H

The KV cache goes from 2×H×L×dk2 \times H \times L \times d_k to 2×1×L×dk2 \times 1 \times L \times d_k. That's a reduction by a factor of H (the number of heads).

ConfigurationKV cache per layerReduction
MHA (H = 64 heads)2 x 64 x L x dkd_kReference
MQA (1 K/V pair)2 x 1 x L x dkd_k64 times less

For our 70B parameter example with 8K tokens: the KV cache goes from ~21 GB to ~330 MB (21 GB ÷ 64). That's a radical change, we go from a major memory problem to something negligible.

Bar chart titled KV Cache Memory: MHA vs MQA (32K Context). Three groups of two bars, for the 7B, 13B and 70B scales. In red, Multi-Head Attention: 16 GB, 25 GB and 80 GB. In green, Multi-Query Attention: 0.50 GB, 0.62 GB and 1.25 GB. A dashed grey horizontal line sits just above 24 GB.
The same arithmetic as above, for a 32,000-token context. Red is the cache of an MHA model, green the same model in MQA. At the 70B scale it drops from 80 GB to 1.25 GB, the factor of 64 the table promises. The dashed line marks the memory of a 24 GB GPU: under MHA the cache alone blows past it from the 13B scale on, while the three green bars stay almost invisible.Source : Marcel Brenndoerfer, Multi-Query Attention
Why this directly speeds up inference

Autoregressive LLM inference is typically memory-bandwidth bound: the GPU waits for data to arrive from HBM (High Bandwidth Memory, the graphics card's main memory), not for it to finish computations. The KV cache must be read in its entirety for each generated token. Reducing its size by a factor of 64 means 64 times fewer memory reads per token, which translates directly into much higher generation throughput.

Impact on quality: surprisingly small

The natural question: by sharing K and V across all heads, you inevitably lose expressiveness. What's the quality cost?

Research shows a modest degradation. In the original paper, translation quality stays nearly identical to the baseline; later work (notably the GQA paper) does measure a clearer drop on some demanding tasks. Why so little, given such radical sharing?

The intuition: the diversity of attention patterns comes mainly from the queries, not from keys and values. Think of attention heads as investigators querying a database. Each investigator (head) asks different questions (distinct queries), but they all consult the same files (shared K/V). Each investigator's specialization lies in what they're looking for, not in the files themselves.

Keys and values capture the same semantic information from the context regardless of the head. Sharing this context representation therefore doesn't lose much expressiveness.

Who uses MQA in production?

MQA has been adopted by several major models:

  • PaLM (Google): one of the first large models to adopt it at scale
  • Falcon 7B (TII): pure MQA; Falcon 40B already uses the grouped variant
  • StarCoder: code generation model with MQA

Converting MHA to MQA after training

You have an already-trained MHA model and want MQA's benefits without starting from scratch? It's possible:

  1. Take the H K and V projection matrices from the H heads
  2. Average them into a single shared projection
  3. Briefly retrain the model, at about 5% of the original training budget
Three-panel figure. Left panel, Traditional Multi-head attention (MHA): eight blue queries, each linked by a vertical arrow to its own red key topped by its own yellow value. Middle panel, Multi-query attention (MQA): eight blue queries whose arrows all converge on a single red key topped by a single yellow value. Right panel, Adapting MHA to MQA: the key projections K1, K2 up to KH, all of height d_h and width d_model, feed into a Mean Pool block that outputs one shared projection K_MQ of the same shape.
The right-hand panel is exactly the recipe described above: the H key projection matrices, one per head, are averaged entry by entry by the Mean Pool block to give the single shared matrix of the MQA model. Same operation for the values. The two left panels are a reminder of what the conversion changes: from one key and one value per query (left) to a single key and value for all of them (middle).Source : Towards Data Science, Demystifying GQA
The uptrained conversion

Google demonstrated (in the GQA paper, which also tests conversion to MQA) that this weight averaging, followed by a short additional training run at 5% of the original pre-training compute, recovers nearly all of the original MHA model's performance. You get MQA's inference gains without paying the full training cost again, an excellent investment/benefit ratio.

Advantages and limitations

What MQA brings:

  • KV cache reduction by a factor of H, the number of heads (32 to 128 depending on the model)
  • Significant acceleration of token-by-token generation
  • Minimal architectural modification, easy to implement
  • Compatible with Flash Attention and other inference optimizations

What MQA sacrifices:

  • Heads can no longer specialize their K/V representations independently
  • Slight measurable quality degradation, especially on tasks requiring very fine attention
  • Doesn't reduce training cost (queries remain distinct, computation is the same)
When MQA goes too far

For frontier models where every tenth of a benchmark point matters, MQA's quality loss can be unacceptable. The middle-ground solution: Grouped Query Attention (GQA), which shares K/V among groups of heads (for example 8 groups of 8 heads) rather than across all heads. GQA offers a tunable trade-off between MHA's maximum quality and MQA's maximum efficiency. It has become the de facto standard in recent models (LLaMA 2/3, Mistral, etc.).

Final comparison: MHA vs MQA

AspectMHAMQA
K, V projectionsH distinct (H = 32 to 128)1 single shared
KV cache per layer2 × H × L × dkd_k2 × L × dkd_k
QualityReferenceSlightly lower, mostly on fine-grained tasks
Memory reads per tokenReferenceDivided by H
Latency per tokenReferenceSignificantly reduced

MQA is an elegant architectural optimization that directly tackles the real bottleneck of LLM inference: memory bandwidth. Its idea (sharing K/V across all heads) paved the way for GQA, which refines this quality/efficiency trade-off to make it acceptable even for the most demanding models.

Check your understanding0 / 5

1. During token-by-token generation, the GPU is often half idle. Why?

2. MQA is sometimes described as the heads sharing the matrices W_K and W_V, sometimes as the heads sharing the keys and values K and V. What should you make of this?

3. Despite such radical sharing, quality drops surprisingly little. What intuition does the page give?

4. You have an already-trained MHA model and want MQA's benefits. What do you do?

5. For a frontier model where every tenth of a benchmark point matters, MQA's quality loss can be unacceptable. What is the middle-ground solution?