Multi-query attention: four questions, one set of keys
多查询注意力
Implement shared-KV attention and test why different query heads still produce different weights.
multiquery-attentionSharing the reference material does not merge the questions
Four query heads can ask different questions of the same keys and values. One may concentrate on an early position, another on the most recent one. Sharing keys does not force their dot products to be equal, because the queries remain different.
That is the change introduced by multi-query attention, or MQA. Conventional multi-head attention gives every head its own query, key and value projections. MQA keeps the multiple query heads but uses one shared key projection and one shared value projection. It reduces the KV state that must be stored and read during decoding.
Our five-position example has four query heads and width two. Shared keys and values contain 20 scalars together; physically repeating them for four heads would contain 80. The attention still produces four head outputs. The example verifies equivalence to that repeated representation, not equivalence to an arbitrary independently parameterized multi-head model.
Remove the KV head axis, keep the query head axis
For one sequence of shape , query heads and key/value width , MQA projections are:
Each query head has a projection. The key and value projections have that shape too, but each is shared across all heads. With causal masking, head at position computes:
Future positions receive zero weight. The weighted output is:
The output still has a head dimension. A full layer concatenates those head outputs and projects them back to model width:
The runnable example stops at the per-head outputs so sharing is easy to inspect; it does not include , residuals or a language-model head. That boundary is explicit rather than hiding omitted operations inside a function named “Transformer.”
Compare logical KV contents for a sequence of length , assuming equal key and value width:
For , these are 80 and 20 scalars. Multiply by layers, batch size and scalar bytes for a full logical cache. Actual allocations can include replication, padding and buffers. In particular, physically expanding shared KV into a separate array for every query head defeats the intended storage reduction.
A dense attention implementation still forms one score per query-head/query/key combination:
Here it is 100 allocated score entries, although the causal mask permits only 60. MQA does not remove the query-head factor from query–key arithmetic. Its principal decoding benefit concerns KV memory traffic; a fourfold logical cache reduction is not automatically a fourfold end-to-end speedup. Shazeer’s analysis states simplifying assumptions, and hardware, batching and kernel implementation affect the outcome.
Prove sharing without duplicating the stored state
The NumPy implementation uses query shape H,T,d, key shape T,d and value shape T,d. Its contractions read the same keys and values for every head. It uses stable row softmax and a causal mask; no external model or dataset is downloaded.
"""Original shared-KV attention; broadcasting is mathematical, not physical cache duplication."""
import json
import numpy as np
def attention(q, k, v):
if q.ndim != 3 or k.ndim != 2 or v.ndim != 2 or q.shape[-1] != k.shape[-1] or len(k) != len(v):
raise ValueError('Expected Q[H,T,d], K[S,d], V[S,v]')
if q.shape[1] != len(k) or len(k) == 0:
raise ValueError('This example uses equal nonempty causal lengths')
scores = np.einsum('htd,sd->hts', q, k)/np.sqrt(k.shape[-1])
scores = np.where(np.tril(np.ones((len(k),len(k)),dtype=bool)), scores, -np.inf)
p = np.exp(scores-scores.max(axis=-1,keepdims=True))
p /= p.sum(axis=-1,keepdims=True)
return np.einsum('hts,sv->htv',p,v), p
def example():
rng = np.random.default_rng(23)
x = rng.normal(size=(5,4))
wq = rng.normal(scale=.5,size=(4,4,2))
wk, wv = rng.normal(scale=.5,size=(2,4,2))
return np.einsum('td,hdk->htk',x,wq), x@wk, x@wv
def main():
q,k,v=example();out,p=attention(q,k,v)
print(json.dumps(dict(heads=4,kv_heads=1,weights_last=p[:,-1].tolist(),
outputs_last=out[:,-1].tolist(),
cache_elements_shared=k.size+v.size,
cache_elements_expanded=4*(k.size+v.size),
head_weight_difference=float(np.max(abs(p[0]-p[1]))),
pair_scores=q.shape[0]*len(k)*len(k))))
if __name__ == '__main__':
main()
For seed 23, the last-position weight vectors differ across heads. Across all positions, the maximum difference between heads zero and one is about 0.419813. Their stored KV arrays are nevertheless identical because there is only one copy. At the first position, every head has just one permitted key, so all weights equal one and all outputs equal the first value vector.
The independent tests compute the result again with scalar loops over head, position, key and coordinate. They also compare against a reference with shared KV explicitly repeated into four identical heads. Those checks establish the tensor-axis interpretation. They do not show that replacing a trained model’s independent KV projections preserves its outputs.
Attention arithmetic costs on the order of in this dense teaching implementation, excluding projections. It stores quadratic scores and weights plus linear shared KV. A memory-efficient attention kernel can address the quadratic intermediate separately; that is the subject of FlashAttention.
Less cache is a constraint on the model, too
Independent heads can learn different key and value subspaces. MQA ties those subspaces together. Different queries still permit different attention distributions, but they do not restore arbitrary independent KV projections. The sharing pattern changes the parameterization and can change task quality.
The GQA paper discusses converting multi-head checkpoints and then continuing pretraining to adapt them. It explicitly treats conversion and subsequent training as separate steps. Taking a mean of old KV projections is not an identity transformation, and successful conversion cannot be inferred from tensor shapes alone.
The example is a forward computation with randomly sampled fixed projections. It has no training, decoder throughput measurement or language benchmark. It does not test cross-attention, unequal query/key lengths, tensor-parallel replication or attention dropout. The supplied function deliberately rejects unequal causal lengths to keep its mask convention unambiguous.
Follow the axes
- With eight query heads, 100 positions and width 16, how many shared KV scalars are stored per layer and sequence? Answer: 3,200. Independently stored MHA keys and values would contain 25,600 at those dimensions. Queries and output projections are not included in either count.
- Why can two heads sharing assign different weights? Answer: Their query vectors can differ, giving different dot products against each shared key. The softmax then normalizes different score rows.
- If all query heads are identical as well, what happens? Answer: With identical masks and the same shared KV, their scores, weights and per-head outputs match. A later output projection can mix these copies, but the attention heads themselves add no distinct information.
- Does the expanded-reference equality justify swapping any MHA checkpoint to MQA without training? Answer: No. The reference repeats one KV set; a general checkpoint has different sets. Equality under tied parameters is not equality after changing untied parameters.
MQA is one endpoint of a sharing choice
Shazeer’s 2019 paper proposes keeping query heads while sharing KV, motivated by incremental decoding’s memory bandwidth. Its first-version pseudocode is not used as executable code here; the example is an original implementation of the stated computation. The later GQA paper supplies an intermediate sharing pattern and a conversion-plus-uptraining recipe under its own experimental conditions.
Continue with GQA to choose several KV groups rather than one. Keep three comparisons separate: mathematical output under fixed parameters, language-model quality after training, and serving speed under a specified workload.
Make a prediction, then check
In MQA, must all query heads have the same attention weights?
Learning objectives
- Track head axes through query, key, value and output tensors.
- Verify shared KV against an explicitly expanded reference.
- Separate cache reduction from query arithmetic and measured speed.
Prerequisites & connections
Explore related knowledge →References
- Fast Transformer Decoding: One Write-Head is All You Need — v1
Noam Shazeer · 2019 - GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
Joshua Ainslie; James Lee-Thorp; Michiel de Jong; Yury Zemlyanskiy; Federico Lebrón; Sumit Sanghai · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read Shazeer v1 sections2.4/3–3.1/PDF4–6 and GQA PDF1–2. Six paired equations and four explained exercises. Original shared-KV computation verified by scalar loops and expanded tied-parameter reference, distinct query weights, first-token equality and cache dimensions. Not arbitrary MHA checkpoint equivalence or trained-model benchmark.
- Single AI author read Shazeer v1 sections2.4/3–3.1/PDF4–6 and GQA PDF1–2. Six paired equations and four explained exercises. Original shared-KV computation verified by scalar loops and expanded tied-parameter reference, distinct query weights, first-token equality and cache dimensions. Not arbitrary MHA checkpoint equivalence or trained-model benchmark.
- Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. Twelve final Chinese-mobile/English-desktop screenshots all directly inspected after revisions. Full article acceptance recorded separately.
Source locations checked:
- Fast Transformer Decoding: One Write-Head is All You Need — v1 · Read sections2.1,2.3.1,2.4,3–3.1; visually checked PDF4–6. Shared keys/values, distinct queries and incremental bandwidth argument under simplifying assumptions. Paper pseudocode was not copied or executed.
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints · Read PDF1–2 visually, sections2–3.1: mean pooling plus further pretraining, GQA endpoints and T5.1.1 conditions. No uptraining, speed or quality benchmark reproduced.
Related topics