Search

Search papers and lessons

Grouped-Query Attention

Level 3 · 11 min read

Grouped-query attention lets groups of query heads share one key head and one value head, shrinking the KV cache without sharing keys and values across every head.

On this page

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

TL;DR

Grouped-query attention, or GQA, splits the query heads of a multi-head layer into groups. Every head in a group shares one key head and one value head, while each head keeps its own query. The model stores fewer keys and values per token, so the KV Cache shrinks by the sharing factor, and the quality loss is much smaller than when all heads share one key and value.

Where you'll see it: in the attention layers of large language models that need a small KV cache, where it cuts the memory needed for long contexts and large batches during generation.

Intuition

Teams sharing a filing cabinet

Picture a support centre with 32 agents. Each agent has a different question to ask about a customer's history, which is the query. The history itself is stored in a filing cabinet, the keys and values.

Full multi-head attention gives every agent a private cabinet. Each cabinet is an exact copy of the customer's history, and the storage grows with every message in the conversation. Multi-query attention gives all 32 agents one shared cabinet. That is cheap to store, but agents who need different parts of the history now compete for the same organisation of files. Grouped-query attention puts the agents into teams, say eight teams of four, and gives each team one cabinet. Each team's cabinet is organised for the questions its members tend to ask, and the storage is a quarter of the private-cabinet version (8 cabinets instead of 32).

In the model, the agents are query heads, the cabinets are key and value heads, and the teams are groups.

Why the cache is the thing to shrink

During generation the model produces one token at a time. Each new token reads every stored key and value from GPU memory. The GQA paper describes this directly: autoregressive decoder inference is a severe bottleneck because of the memory bandwidth needed to load the attention keys and values at every decoding step (Ainslie et al., 2023, section 1). The cache also takes up space, so it limits how many requests a GPU can hold at once and how long a context can get.

Reducing the number of key and value heads attacks both problems. The arithmetic work for the query heads is unchanged, but there is far less data to move and store.

flowchart LR
  Q1["Query head 1"] --> A["Key and value, group 1"]
  Q2["Query head 2"] --> A
  Q3["Query head 3"] --> B["Key and value, group 2"]
  Q4["Query head 4"] --> B

The math

Let hh be the number of query heads, gg the number of groups, and dhd_h the width of one head. The sharing factor is h/gh / g, the number of query heads per group. Grouped-query attention requires gg to divide hh. Let LL be the number of layers, and bb the number of bytes per stored number, so b=2b = 2 for 16-bit floats.

Definition: Grouped-query attention

Let grp(i)\mathrm{grp}(i) be the group that query head ii belongs to. For an input XX with one row per position, each query head has its own projection WiQW_i^Q, while the keys and values come from the projections of its group:

headi=softmax ⁣((XWiQ) (XWgrp(i)K)⊤dh)XWgrp(i)V\mathrm{head}_i = \mathrm{softmax}\!\left(\frac{(X W_i^Q)\,(X W_{\mathrm{grp}(i)}^K)^\top}{\sqrt{d_h}}\right) X W_{\mathrm{grp}(i)}^V

The heads are concatenated and mixed by an output matrix, exactly as in Multi-Head Attention.

Only the key and value projections are shared. Each query head still computes its own attention scores over the positions, so the layer keeps hh separate score matrices.

Special cases

Two settings recover the older designs.

  • If g=hg = h, every group has one head, so each query head has its own key and value. This is Multi-Head Attention.
  • If g=1g = 1, all query heads share one key and one value head. This is multi-query attention, introduced by Shazeer in 2019, see Multi-Query Attention.

Grouped-query attention is the family in between. The paper writes GQA-gg for the version with gg groups.

The cache size

For each token, each layer stores gg keys and gg values, each of width dhd_h. That is 2gdh2 g d_h numbers per layer, so the cache per token is

bytes per token=2⋅L⋅g⋅dh⋅b.\text{bytes per token} = 2 \cdot L \cdot g \cdot d_h \cdot b.

Compared with multi-head attention, which uses g=hg = h, the cache is smaller by the factor g/hg / h. For a sequence of nn tokens, multiply by nn. This is the same formula as in KV Cache with the number of key and value heads substituted for the model width.

What does not change

The score computation still uses hh score matrices. Training compute therefore changes little, and the saving shows up mainly in memory traffic and cache size during decoding. The paper makes the same point when it notes that larger models suffer relatively less from the attention memory overhead, because the cache scales with the model dimension while the parameters scale with its square.

Converting an existing checkpoint

A GQA model does not have to be trained from scratch. The paper converts a multi-head checkpoint by mean-pooling the original key and value projections within each group. Each group key head is the average of the heads it replaces. The converted model then needs a short extra pre-training run, called uptraining. In the paper's experiments this is a fraction α\alpha of the original pre-training steps, and the main results use α=0.05\alpha = 0.05. For the T5-XXL model in the paper, that took about 600 TPUv3 chip-days.

Worked examples

Example
Four query heads, two groups, one token

Use head width dh=1d_h = 1 so the scale dh\sqrt{d_h} is 1. Four query heads form two groups: heads 1 and 2 share group A, and heads 3 and 4 share group B.

  1. Count the cached numbers for one token in one layer. Multi-head attention stores 4 keys and 4 values, so 8 numbers. GQA with 2 groups stores 2 keys and 2 values, so 4 numbers. Multi-query attention stores 1 key and 1 value, so 2 numbers.
  2. Ratios against multi-head attention: 8→48 \to 4 is a factor of 12\tfrac{1}{2}, and 8→28 \to 2 is a factor of 14\tfrac{1}{4}. These match g/hg / h.
  3. Now compute two heads that share group A. The cache holds two positions for group A: keys [1,0][1, 0] and values [10,4][10, 4].
  4. Head 1 has query 11. Scores are [1⋅1,1⋅0]=[1,0][1 \cdot 1, 1 \cdot 0] = [1, 0]. The softmax weights are e/(e+1)≈0.7311e / (e + 1) \approx 0.7311 and 1/(e+1)≈0.26891 / (e + 1) \approx 0.2689.
  5. Head 1 output =0.7311⋅10+0.2689⋅4≈8.386= 0.7311 \cdot 10 + 0.2689 \cdot 4 \approx 8.386.
  6. Head 2 has query 00. Scores are [0,0][0, 0], so both weights are 0.50.5. Head 2 output =0.5⋅10+0.5⋅4=7= 0.5 \cdot 10 + 0.5 \cdot 4 = 7.

Interpretation: both heads read the same two cached entries. They still produce different outputs because their queries differ, and the cache holds half the entries that multi-head attention would hold for these two heads.

Example
Cache size for a realistic configuration

Take an illustrative model with L=32L = 32 layers, h=32h = 32 query heads of width dh=128d_h = 128, 16-bit storage (b=2b = 2), and a sequence of n=4096n = 4096 tokens. These are not the paper's numbers; they show the scale of the effect.

  1. Multi-head attention, g=32g = 32: bytes per token =2⋅32⋅32⋅128⋅2=524,288= 2 \cdot 32 \cdot 32 \cdot 128 \cdot 2 = 524{,}288, which is 512 KiB. For 4096 tokens, that is 2 GiB.
  2. GQA with g=8g = 8: bytes per token =2⋅32⋅8⋅128⋅2=131,072= 2 \cdot 32 \cdot 8 \cdot 128 \cdot 2 = 131{,}072, which is 128 KiB. For 4096 tokens, that is 512 MiB.
  3. Multi-query attention, g=1g = 1: bytes per token =16= 16 KiB. For 4096 tokens, that is 64 MiB.
  4. At a batch of 16 sequences, the GQA cache is 16⋅51216 \cdot 512 MiB =8= 8 GiB, down from 32 GiB with multi-head attention.

Interpretation: the choice of gg sets the cache directly. Going from 32 groups to 8 frees three quarters of the cache memory, which is space the server can use for more concurrent requests or longer contexts.

Example
The paper's measured trade-off on T5-XXL

The GQA paper reports these values in its Table 1, for per-sample inference time on TPUv4 and average dev-set score across its summarisation, translation and question-answering tasks.

ModelInference time (s)Average score
MHA-XXL1.5147.2
MQA-XXL, 5% uptrained0.2446.6
GQA-8-XXL, 5% uptrained0.2847.1
  1. Speed-up of GQA-8 over multi-head attention: 1.51/0.28≈5.41.51 / 0.28 \approx 5.4.
  2. Speed-up of multi-query attention over multi-head attention: 1.51/0.24≈6.31.51 / 0.24 \approx 6.3.
  3. Score gap of GQA-8 to multi-head attention: 47.2−47.1=0.147.2 - 47.1 = 0.1 points.
  4. Score gap of multi-query attention: 47.2−46.6=0.647.2 - 46.6 = 0.6 points.

Interpretation: GQA-8 gives most of the speed of multi-query attention, about 5.4 times faster than multi-head attention, while keeping almost all of its quality. These numbers come from one T5 setup in the paper and should not be read as a universal speed-up for other models or hardware.

Tradeoffs and failure modes

Grouped-query attention is a memory decision. It helps most when the cache is the bottleneck.

SituationProblemBetter choice
Long contexts or large batches on a fixed GPUThe key-value cache fills memoryGQA with fewer groups, which cuts the cache by g/hg / h
Short contexts, small batchesThe cache is small, so there is little to saveMulti-head attention keeps the most capacity
Fastest possible decoding, quality can drop a littleOne shared key and value (multi-query) saves the most memoryMulti-query attention, ideally after uptraining
Existing multi-head checkpoint, limited training budgetTraining from scratch is expensiveConvert by mean-pooling and uptrain a small fraction of the steps
Encoder self-attentionEncoder states are computed in parallel, so memory bandwidth is rarely the limitKeep full multi-head attention there; the paper applies GQA only to decoder self-attention and cross-attention

Failure modes to watch for:

  • Too few groups. Quality falls as gg shrinks. The paper found that multi-query attention, with one group, needs uptraining before it is useful, while GQA already performs reasonably right after conversion. It chose 8 groups for its T5-XXL experiments as a middle ground.
  • Converting without uptraining. A converted checkpoint is a damaged model until it has been trained a little further. Skipping that step costs quality.
  • Expecting a training speed-up. Every query head still computes its own scores, so training compute barely changes. Plan around memory and decoding speed.
  • Confusing gg with the number of query heads. Serving code has to know both numbers. Mismatched shapes produce wrong outputs or crashes, not just slowdowns.

History

Multi-query attention came first. In 2019 Shazeer proposed multi-query attention, which uses one key head and one value head for all query heads, to speed up decoding in transformer models. The GQA paper cites this work for the observation that decoder inference is limited by the memory bandwidth needed for keys and values.

GQA came in 2023. Joshua Ainslie and colleagues proposed grouping the query heads so that each group shares a key and value head. They also gave a recipe for converting existing multi-head checkpoints and uptraining them for a small share of the original compute. Their argument, in the paper's words, is that uptrained GQA reaches quality close to multi-head attention with speed comparable to multi-query attention.

Check yourself

QuestionWhat does the number gg count in grouped-query attention?Show answer

It counts the groups of query heads, and so the number of key and value heads stored per layer. Each group has one key head and one value head, shared by the h/gh / g query heads in it.

QuestionA model has h=32h = 32 query heads, width dh=128d_h = 128, L=32L = 32 layers, 16-bit storage, and uses GQA with g=4g = 4. How big is the cache for one 2048-token sequence?Show answer

Bytes per token =2⋅32⋅4⋅128⋅2=65,536= 2 \cdot 32 \cdot 4 \cdot 128 \cdot 2 = 65{,}536, which is 64 KiB. For 2048 tokens, 2048⋅642048 \cdot 64 KiB =128= 128 MiB.

QuestionWhy does grouped-query attention save memory even though every query head still computes its own attention scores?Show answer

The memory saving comes from the keys and values, not from the scores. The cache stores gg key and value heads per token rather than hh. The score matrices exist only during the computation for the current step and are not stored across steps, so reducing the cached keys and values is what cuts the cache. The arithmetic for the scores is unchanged, which is why training speed barely moves.

QuestionYou are serving a model with multi-head attention. At batch size 16 and long contexts, the GPU runs out of memory for the cache. Why can you not just change the attention layer's group count at serving time, and what would you do?Show answer

The weights were trained with hh separate key and value projections. Changing the group count changes the shape of those projections, so the existing checkpoint would give wrong results. You would need to convert the checkpoint by mean-pooling the key and value heads within each group, and then uptrain it for a small fraction of the original steps to recover quality. This is a training task, not a configuration change.

Sources