Grouped-query attention: choose how much KV to share
分组查询注意力
Map query heads to KV groups and measure what mean-pooling changes before uptraining.
grouped-query-attentionTwo shared groups instead of four private sets
Suppose four query heads originally have four different key–value sets. Sharing everything saves the most KV storage, but it also ties together projections that could represent different features. Grouped-query attention offers an intermediate choice: heads zero and one can share one set, while heads two and three share another.
GQA generalizes MQA by assigning each group of query heads a shared key head and value head. It also describes how to convert existing multi-head checkpoints and continue pretraining. Choosing the tensor structure and adapting a trained model to it are separate steps.
The example starts with four random KV projection pairs. Mean-pooling to two groups halves logical KV contents from 80 to 40 scalars, but changes the attention output. Pooling to one group reduces contents to 20 and changes it again. The program measures those changes before any uptraining, so it cannot claim that task quality has been recovered.
Define the grouping before doing the matrix products
Let be the query-head count and the KV-group count. This implementation uses equal contiguous groups, so must be a positive divisor of . The group of zero-based head is:
For , the mapping is 0, 0, 1, 1. Other valid assignments are possible, but switching the assignment without also moving the corresponding weights changes the model. A group index is a semantic connection, not merely a convenient reshape.
Each query head uses its own query projection and its assigned group’s key/value projections:
Its attention output, with causal mask , is:
Here the mask is zero on the current and earlier positions and negative infinity on future positions. It is applied before row softmax. The output retains heads; grouping reduces KV heads, not query heads. As in the MQA chapter, the minimal code stops before concatenation and the output projection.
Ainslie and colleagues initialize grouped KV projections by averaging old heads within each group. For a group of size :
There is a useful mathematical interpretation of the mean, but it must not be overstated. In projection-parameter space, it minimizes squared distances:
To derive this, differentiate every scalar entry of the objective: its derivative is twice the group size times that entry of , minus twice the sum of the old entries. Setting it to zero gives the mean; the positive quadratic coefficient establishes the minimum. This is an unweighted parameter-space objective. It is not language-model loss, nor does it minimize downstream attention-output error in general. The nonlinear softmax and each head’s distinct queries prevent that inference.
Logical KV size for one layer and one sequence is:
keeps independent KV for each query head and recovers MHA. shares one KV pair and recovers MQA. Intermediate values trade sharing against representational freedom. The formula does not guarantee monotonic task quality or a proportional speedup.
Measure conversion before claiming adaptation
The complete NumPy program creates four query heads, five positions and width-two keys and values. pool averages projection matrices, not already normalized attention weights. converted then recomputes the actual attention output with the new projections.
"""Mean-pool KV projections, exposing conversion error before any uptraining."""
import json
import numpy as np
def pool(weights, groups):
heads = weights.shape[0]
if type(groups) is not int or groups < 1 or heads % groups:
raise ValueError('Groups must divide the positive number of query heads')
return weights.reshape(groups,heads//groups,*weights.shape[1:]).mean(axis=1)
def attention(q,k,v):
h,t,d=q.shape;g,s,kd=k.shape
if g < 1 or h%g or kd!=d or v.shape[:2]!=(g,s) or t!=s or t<1:
raise ValueError('Incompatible equal-length grouped causal attention shapes')
out=[];weights=[]
for head in range(h):
group=head//(h//g)
scores=q[head]@k[group].T/np.sqrt(d)
scores[np.triu_indices(t,1)]=-np.inf
p=np.exp(scores-scores.max(axis=-1,keepdims=True));p/=p.sum(axis=-1,keepdims=True)
out.append(p@v[group]);weights.append(p)
return np.array(out),np.array(weights)
def example(seed=31):
rng=np.random.default_rng(seed);x=rng.normal(size=(5,4))
wq,wk,wv=rng.normal(scale=.5,size=(3,4,4,2))
return x,wq,wk,wv
def converted(x,wq,wk,wv,groups):
q=np.einsum('td,hdk->htk',x,wq)
k=np.einsum('td,gdk->gtk',x,pool(wk,groups))
v=np.einsum('td,gdk->gtk',x,pool(wv,groups))
return attention(q,k,v)
def main():
args=example();reference=converted(*args,4)[0]
results=[]
for g in [1,2,4]:
out,p=converted(*args,g)
results.append(dict(groups=g,head_to_group=[h//(4//g) for h in range(4)],
cache_elements=2*g*5*2,
rmse_to_unconverted=float(np.sqrt(np.mean((out-reference)**2))),
outputs_last=out[:,-1].tolist()))
print(json.dumps(dict(results=results,uptraining_steps=0,
claim='Averaging projections does not preserve arbitrary attention outputs')))
if __name__ == '__main__':
main()
With seed 31, root mean squared error across all per-head output coordinates is about 0.505631 for one group, 0.400148 for two and zero for four, measured against the original four-head computation. The corresponding KV contents are 20, 40 and 80 scalars. These are conversion errors on random fixed inputs, not perplexities, accuracies or a general ordering of the methods.
The independent checks verify both endpoints, the 0–0–1–1 mapping and the projection-space mean’s stationary condition. They also construct an exact special case: when old KV projections are already identical within each intended group, pooling leaves the attention output unchanged. An arbitrary set of old heads does not have that property.
Mean pooling takes work proportional to the original KV projection parameters. The attention operation still computes a score row for each query head; dense arithmetic remains on the order of , apart from projections. This small implementation materializes scores and weights and uses a Python loop over heads. It demonstrates grouping, not the performance of a fused grouped-attention kernel.
A conversion recipe includes the training that follows
The GQA paper’s method first converts KV projections, then continues pretraining using the original recipe. Its experiments use T5.1.1-based models; the authors describe a setting using an additional 5% of original pretraining steps. That is a reported experimental configuration, not a guarantee that any checkpoint adapts with the same budget. Our uptraining_steps is explicitly zero.
Parameter averaging can put a model in an unfamiliar state. Query heads were trained with their old keys and values, and later layers were trained with their old outputs. Even though the mean is a least-squares solution in parameter space, useful functions need not be preserved. Evaluate both task quality and serving behavior after adaptation.
Tensor-parallel replication, KV layout, dtype and sequence length can affect realized memory traffic. A single KV group may be replicated across partitions, so the logical ratio need not equal the device-memory ratio. Grouping also does not itself increase the allowed context length or solve position-dependent retrieval failures.
A good mean can still change the answer
- For eight query heads and two equal contiguous groups, which heads use group zero? Answer: Heads 0, 1, 2 and 3. Each group contains four heads; heads 4–7 use group one.
- What is the squared-distance-optimal shared scalar for old values 1 and 5? Answer: Three. The derivative of is , so the unique minimum is at three. This says nothing by itself about an attention output.
- When does the two-group conversion preserve the four-head example exactly? Answer: A sufficient condition is that the old key projections and old value projections are each identical within their assigned groups. Queries and masks stay unchanged, so every head sees the same keys and values as before.
- Does lower random-input RMSE establish higher language-model quality? Answer: No. RMSE measures this local numeric change. Compare trained models on relevant held-out tasks under matched evaluation conditions, and report the adaptation cost.
Keep the architecture, conversion and benchmark separate
MQA supplies the single-KV endpoint and the decoding-bandwidth motivation. GQA adds intermediate KV groups and a checkpoint conversion with subsequent training. Its favorable measured trade-offs belong to the paper’s training and evaluation conditions, not to mean pooling alone.
The code makes this separation visible: a group count controls shapes, the mean changes parameters, and output error reports a consequence. There is no hidden training stage. Use KV-cache accounting for full logical storage and FlashAttention for a complementary change to how exact attention is executed.
Make a prediction, then check
With H query heads, which GQA setting equals MHA?
Learning objectives
- Identify MHA and MQA as the endpoints of grouping.
- Derive mean pooling as a projection-space least-squares solution.
- Measure conversion error without claiming quality preservation.
Prerequisites & connections
Explore related knowledge →References
- 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 - Fast Transformer Decoding: One Write-Head is All You Need — v1
Noam Shazeer · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read GQA sections2–3.1/PDF1–2 and Shazeer MQA. Six paired equations and four explained exercises. Exact head mapping, GQA endpoints, mean-pooling stationary condition and special tied-projection equivalence checked; random conversion errors measured with zero uptraining. Authors extra5% condition is not a general adaptation guarantee.
- Single AI author read GQA sections2–3.1/PDF1–2 and Shazeer MQA. Six paired equations and four explained exercises. Exact head mapping, GQA endpoints, mean-pooling stationary condition and special tied-projection equivalence checked; random conversion errors measured with zero uptraining. Authors extra5% condition is not a general adaptation guarantee.
- 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:
- 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.
- 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.
Related topics