Search

Search papers and lessons

Multi-Query Attention

Level 3 · 10 min read

Multi-query attention shares one key head and one value head across all query heads, which shrinks the KV cache by the number of heads at a small cost in quality.

On this page

  • Colour = topic mix
  • Linear algebra
  • Architectures
  • Neural network basics
  • Discrete math
  • Efficiency
  • Probability
  • Sign in to see your progress

TL;DR

Multi-query attention keeps many query heads but gives them all one shared key head and one shared value head. Each query head still has its own query projection, so it can ask a different question of the same context. The saving is in memory: the keys and values that must be stored during generation shrink by the number of heads.

It was proposed to make text generation faster. Decoding reads the whole cache for every new token, so a smaller cache means less memory traffic per step.

Where you'll see it: in the attention layers of large language models that are served at scale, where the KV Cache is the main limit on how many requests a GPU can hold.

Intuition

Picture a meeting where eight analysts each want to question the same set of documents. In Multi-Head Attention, every analyst gets their own copy of the documents, indexed the way they like. Eight copies of the index sit on the desk. In multi-query attention, the documents are indexed once and everyone uses that one index, but each analyst still brings their own question.

The questions are where the diversity lives. Each head's query decides what it looks for, so the heads can still focus on different things. What they lose is the freedom to index the context differently. Every head sees the same keys and the same values.

Why does this matter? During generation the model produces one token at a time. For each new token, every attention layer must read the stored keys and values of all earlier tokens. That cache sits in GPU memory, and reading it is often the slowest part of the step, not the arithmetic. If the cache is eight times smaller, there is eight times less to read per token and eight times more room to hold other requests.

flowchart LR
  subgraph MHA[Multi-head attention]
    Q1[Query 1] --- K1[Key 1]
    Q2[Query 2] --- K2[Key 2]
    Q3[Query 3] --- K3[Key 3]
  end
  subgraph MQA[Multi-query attention]
    QA[Query 1] --- KS[Shared key]
    QB[Query 2] --- KS
    QC[Query 3] --- KS
  end

The left side stores one key per head. The right side stores one key for all heads. The values are shared the same way, and the picture is the same for them.

The math

Use the notation from Multi-Head Attention. The input is X∈Rn×dX \in \mathbb{R}^{n \times d}, where nn is the sequence length and dd is the model width. There are hh query heads, and each head works in width dk=d/hd_k = d / h. The symbol hh is the number of query heads, and dkd_k is the width of each query and key.

Definition: Multi-query attention

Each query head ii has its own projection WiQ∈Rd×dkW_i^Q \in \mathbb{R}^{d \times d_k}. All heads share one key projection WK∈Rd×dkW^K \in \mathbb{R}^{d \times d_k} and one value projection WV∈Rd×dkW^V \in \mathbb{R}^{d \times d_k}:

headi=softmax ⁣((XWiQ)(XWK)⊤dk)XWV,i=1,…,h.\mathrm{head}_i = \mathrm{softmax}\!\left(\frac{(X W_i^Q)(X W^K)^\top}{\sqrt{d_k}}\right) X W^V, \qquad i = 1, \dots, h.

The heads are concatenated and mixed by WOW^O, exactly as in multi-head attention:

MQA(X)=Concat(head1,…,headh) WO.\mathrm{MQA}(X) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\, W^O.

The only change from multi-head attention is that WKW^K and WVW^V lose their head index ii. The score and softmax steps are the same. Each head still computes its own n×nn \times n score matrix, because each head has its own query.

Parameters

In multi-head attention, the key and value projections together have 2hddk=2d22 h d d_k = 2 d^2 weights, since hdk=dh d_k = d. In multi-query attention they have 2ddk=2d2/h2 d d_k = 2 d^2 / h weights. The query projections and the output matrix are unchanged. The saving is therefore a factor of hh on the key and value projections, which are a minor part of the layer's size.

The cache

The part that matters is the KV Cache. For one layer and one token, the cache stores one key and one value for each key-value head:

numbers per token per layer={2hdk=2dmulti-head attention2dk=2d/hmulti-query attention\text{numbers per token per layer} = \begin{cases} 2 h d_k = 2d & \text{multi-head attention} \\ 2 d_k = 2d / h & \text{multi-query attention} \end{cases}

The ratio between the two cases is exactly hh. If a model has LL layers and each number takes bb bytes, the total cache for a sequence of TT tokens is L⋅T⋅bL \cdot T \cdot b times the numbers per token per layer. Multi-query attention divides this total by hh.

Cost of the score matrices

Multi-query attention does not change the number of score entries. Each query head still computes an n×nn \times n matrix during training or prompt processing, so the arithmetic for the scores is the same. The gain is in what has to be stored and read between tokens during generation.

Worked examples

Example
Two query heads sharing one key and one value

Take the two-token setup from Multi-Head Attention: d=2d = 2, h=2h = 2, dk=dv=1d_k = d_v = 1. The tokens are xa=(1,0)x_a = (1, 0) and xb=(0,1)x_b = (0, 1). The output projection is the identity. Head 1 uses W1Q=(1,0)⊤W_1^Q = (1, 0)^\top, and head 2 uses W2Q=(0,1)⊤W_2^Q = (0, 1)^\top. In multi-query attention, both heads share WK=(1,0)⊤W^K = (1, 0)^\top and WV=(2,4)⊤W^V = (2, 4)^\top.

  1. Shared keys: ka=xa⋅(1,0)=1k_a = x_a \cdot (1, 0) = 1 and kb=xb⋅(1,0)=0k_b = x_b \cdot (1, 0) = 0.
  2. Shared values: va=xa⋅(2,4)=2v_a = x_a \cdot (2, 4) = 2 and vb=xb⋅(2,4)=4v_b = x_b \cdot (2, 4) = 4.
  3. Head 1 query for token aa: q1=xa⋅(1,0)=1q_1 = x_a \cdot (1, 0) = 1. Scores: (1⋅1,1⋅0)=(1,0)(1 \cdot 1, 1 \cdot 0) = (1, 0).
  4. Softmax of (1,0)(1, 0) is (ee+1,1e+1)≈(0.7311,0.2689)\left(\frac{e}{e+1}, \frac{1}{e+1}\right) \approx (0.7311, 0.2689).
  5. Head 1 output: 0.7311×2+0.2689×4≈2.53790.7311 \times 2 + 0.2689 \times 4 \approx 2.5379.
  6. Head 2 query for token aa: q2=xa⋅(0,1)=0q_2 = x_a \cdot (0, 1) = 0. Scores: (0⋅1,0⋅0)=(0,0)(0 \cdot 1, 0 \cdot 0) = (0, 0).
  7. Softmax of (0,0)(0, 0) is (0.5,0.5)(0.5, 0.5).
  8. Head 2 output: 0.5×2+0.5×4=30.5 \times 2 + 0.5 \times 4 = 3.
  9. Concatenated output for token aa: (2.5379,3.0)(2.5379, 3.0).

Compare with multi-head attention on the same input, where head 2 had its own keys and values and returned 0.26890.2689. With one shared key, head 2 can no longer favour xbx_b by itself. Its query is zero, so it spreads its focus evenly over both tokens. The two heads still differ, but only through their queries.

The cache tells the same story. Multi-head attention stores four numbers per token here: a key and value for each head. Multi-query attention stores two: one key and one value. The ratio is h=2h = 2.

Interpretation: sharing keys and values forces all heads to look at the same index. The heads can still choose different focus patterns, but the choice is limited to what the shared keys allow.

Example
Cache size for a realistic model

Take a hypothetical model with L=32L = 32 layers, width d=4096d = 4096, and h=32h = 32 heads, so dk=128d_k = 128. Store values in 16-bit floats, so b=2b = 2 bytes. Serve a single sequence of T=8192T = 8192 tokens.

  1. Multi-head attention stores 2hdk=2⋅32⋅128=81922 h d_k = 2 \cdot 32 \cdot 128 = 8192 numbers per token per layer.
  2. Bytes per token across all layers: 32⋅8192⋅2=524,28832 \cdot 8192 \cdot 2 = 524{,}288 bytes, which is 512 KiB.
  3. For 81928192 tokens: 524,288×8192=4,294,967,296524{,}288 \times 8192 = 4{,}294{,}967{,}296 bytes, which is 4 GiB.
  4. Multi-query attention stores 2dk=2562 d_k = 256 numbers per token per layer.
  5. Bytes per token across all layers: 32⋅256⋅2=16,38432 \cdot 256 \cdot 2 = 16{,}384 bytes, which is 16 KiB.
  6. For 81928192 tokens: 16,384×8192=134,217,72816{,}384 \times 8192 = 134{,}217{,}728 bytes, which is 128 MiB.
  7. The ratio is 44 GiB /128/ 128 MiB =32=h= 32 = h.

Interpretation: the one sequence drops from 4 GiB of cache to 128 MiB. The weights of the model are the same size either way, so the cache is the part that multi-query attention shrinks. A server that keeps many sequences in memory can hold roughly hh times as many. These figures are arithmetic for the hypothetical model above, not measurements from a real system.

Tradeoffs and failure modes

Multi-query attention trades a little model quality for a much smaller cache. Sharing one key and value head removes the model's ability to index the context in several ways at once. The quality loss is usually small, but it is a loss, and it grows with how aggressively the heads are shared.

The main practical question is whether to train with multi-query attention from the start, or to convert an existing multi-head model. Ainslie and colleagues showed in 2023 that an existing multi-head checkpoint can be converted ("uptrained") using about 5% of the original pre-training compute. The conversion keeps most of the quality at a much lower cost than training from scratch.

SituationProblemBetter choice
Long contexts or many concurrent requestsThe KV Cache fills GPU memoryMulti-query attention, or Grouped-Query Attention to keep more key-value heads
Quality is the top priority and memory is not tightSharing keys and values costs some accuracyPlain Multi-Head Attention
Existing multi-head checkpointRetraining from scratch is expensiveConvert the checkpoint and train briefly
Very long sequences in trainingScore matrices grow with the square of the lengthMemory-efficient exact kernels such as [[flashattention-paper

Failure modes to watch for. A model trained with multi-head attention and then switched to multi-query attention without further training can lose more quality than expected. The shared key and value projections are new, and the model has to learn to use them. Also, multi-query attention saves memory and bandwidth during generation, but it does not reduce the score computation, which is unchanged. Judging the saving by training memory alone will give a misleading picture.

History

Noam Shazeer published Fast Transformer Decoding: One Write-Head is All You Need in 2019. The paper addressed decoding speed. The paper argued that incremental decoding is limited by the memory bandwidth needed to reload the keys and values at every step. Shazeer showed that sharing one key and value head across all query heads shrinks those tensors, and reported much faster decoding with only a slight quality loss on translation and language-modelling benchmarks.

In 2023 Ainslie and colleagues proposed grouped-query attention as a middle path. It keeps a small number of key-value groups instead of one shared head, and they showed how to uptrain multi-head checkpoints into this form, and that the grouped version reaches quality close to multi-head attention at speed close to multi-query. Multi-query attention is the extreme case of that idea, with one group.

Check yourself

QuestionIn multi-query attention, which part of the layer is shared across heads, and which part stays separate?Show answer

The key projection WKW^K and the value projection WVW^V are shared, so every query head reads the same keys and values. Each head keeps its own query projection WiQW_i^Q, and the output matrix WOW^O still mixes the concatenated heads. The shared keys and values are what reduce the cache.

QuestionA model has h=16h = 16 query heads and width d=2048d = 2048, so dk=128d_k = 128. How many key and value numbers per token per layer does multi-head attention store, and how many does multi-query attention store?Show answer

Multi-head attention stores 2hdk=2⋅16⋅128=40962 h d_k = 2 \cdot 16 \cdot 128 = 4096 numbers per token per layer, which equals 2d2d. Multi-query attention stores 2dk=2562 d_k = 256 numbers. The ratio is 4096/256=16=h4096 / 256 = 16 = h.

QuestionWhy does multi-query attention leave the number of score entries unchanged, even though it shrinks the cache?Show answer

Each query head still has its own query, so each head still computes a score for every pair of positions, which is an n×nn \times n matrix per head. The shared key only changes which keys those scores are computed against. The saving is in storage and reads of keys and values between generation steps, not in the number of scores.

QuestionApplied: you are serving a model with 64 query heads, and the GPU runs out of memory when many long requests run at once. Which change would you consider first, and what would you check before deploying it?Show answer

The likely cause is the key-value cache, which grows with the number of heads and the length of each request. Switching to multi-query attention would cut the cache by up to 64 times. Before deploying, check that the model was trained with this design, or that a converted checkpoint has been tested on your task. Switching an existing multi-head model without retraining can lose quality. Grouped-query attention is a milder option if the loss is too large.

Sources