AI Logic

Attention Mechanisms

Grouped-Query Attention (GQA)

Updated:

Structure of grouped-query attention. The left shows the computation flow (the query projection and scaled dot-product attention run h times, once per head, while the key and value projections come in G sets shared by the heads of the same group). The right compares how key/value heads are shared (with h = 8, multi-head has 8 K/V heads, GQA (G = 4) has 4, each shared by 2 query heads, and MQA has 1)

What is grouped-query attention

Grouped-query attention (GQA) is a mechanism that splits the hh query heads into GG groups, with the heads in the same group sharing one key head and one value head. Ainslie et al. proposed it in 2023 in the paper "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints" (EMNLP 2023).

The motivation lies in the weaknesses of multi-query attention (MQA). MQA uses a single set of keys and values for all heads, which reduces the amount of data loaded when generating text one word at a time and makes generation much faster. On the other hand, it can degrade quality or make training unstable. GQA does not reduce the key and value heads all the way to one; it stops at an intermediate number GG.

Depending on the value of GG, GQA bridges the following two (Section 2.2 of the paper).

GGNumber of query heads sharing one key/value headEquivalent to
G=hG = h1Multi-head attention
1<G<h1 < G < hh/Gh / GGQA
G=1G = 1hhMQA

For head ii in group gg of the GG groups, the computation is:

headi=Attention(QWiQ, KWgK, VWgV)\mathrm{head}_i = \mathrm{Attention}\left(Q W_i^Q,\ K W_g^K,\ V W_g^V\right)

WgK,WgVW_g^K, W_g^V are per-group weights, and heads in the same group use the same ones. Attention\mathrm{Attention} is scaled dot-product attention. The paper calls a model with GG groups GQA-GG (for example, GQA-8).

If eight researchers all pass around a single reference binder (MQA), waiting time is minimal, but the perspectives they can investigate are limited. If they work in pairs with one binder per pair (GQA), the effort of carrying binders hardly changes, yet each pair can investigate from a different perspective.

The left side of the figure at the top of the article shows the computation flow, and the right side compares the number of key and value heads.

Converting an existing model to GQA

Another contribution of the paper is a method for converting a model trained with multi-head attention into GQA (or MQA) with a small amount of additional training (uptraining). This avoids retraining a GQA model from scratch. The steps are as follows (Sections 2.1 and 2.2).

  1. Split the heads into groups: divide the hh heads into GG groups of h/Gh / G heads each.
  2. Convert by averaging the weights: for each group, average the key projection weights of the heads it contains to form the group's key weight WgKW_g^K. The same goes for values. The query and output weights are used as they are.
  3. Train a little more: retrain the converted model with the same settings and data as the original pretraining for a fraction α\alpha of the original number of training steps. The paper uses α=0.05\alpha = 0.05 (5% of the original pretraining).

On the conversion method, the paper confirms the following (Section 3.3).

  • Averaging works best: in an experiment converting T5-Large to MQA, the results were best for averaging (Mean), then selecting the first head (First), then random initialization (Random). The paper attributes this order to how much of the pretrained model's information is preserved.
  • GQA is somewhat usable right after conversion: MQA was not usable without additional training, but GQA performed reasonably even immediately after conversion. Both improved with 5% additional training, and going to 10% brought only small gains.

The GQA paper applies MQA and GQA only to the decoder's self-attention and cross-attention, not to the encoder's self-attention. The encoder can compute all positions at once, so the amount read from memory is less of a problem to begin with.

Why the middle ground works well

The paper explains why GQA achieves "speed close to MQA and quality close to multi-head" as follows (Section 2.2).

  • Speed is determined by the amount of keys and values: when generating text, the past keys and values (the KV cache) are reloaded from memory for every word, so their size governs speed. Per word and per layer, the KV cache holds 2hdk2 h d_k values for multi-head attention, 2Gdk2 G d_k for GQA, and 2dk2 d_k for MQA.
  • The larger the model, the more drastic MQA's reduction becomes: larger models also have more heads hh, so MQA cuts keys and values to 1/h1/h and greatly reduces expressive power. With GQA, keeping GG fixed as the model grows keeps the reduction ratio constant.
  • In large models, attention loading is relatively small to begin with: the KV cache grows linearly with model width, while computation and parameter count grow with the square of the width. Increasing GG slightly from 1 has only a small effect on overall speed.
  • Less waste when splitting across devices: when a large model is split across multiple devices, MQA's single key/value head is replicated on every device. GQA has multiple key/value heads, so this waste is reduced.

The paper also examines the relationship between the number of groups and speed (Figure 6, T5-XXL, input 2048 and output 512). Increasing the groups from 1 (MQA) to 8 slows things only slightly, and it gets slower as it approaches multi-head attention. Based on this, the paper chooses G=8G = 8.

Experimental results

The paper compares T5.1.1 Large and XXL (multi-head attention) with XXL models converted to MQA and GQA-8 and trained for an additional 5%. Evaluation covers summarization (ROUGE-1 on CNN/Daily Mail, arXiv, PubMed, MediaSum, and MultiNews), translation (BLEU on WMT), and question answering (F1 on TriviaQA). TinferT_{\text{infer}} is the inference time per sample (seconds, TPUv4) (Table 1).

ModelTinferT_{\text{infer}}AverageCNNarXivPubMedMediaSumMultiNewsWMTTriviaQA
MHA-Large0.3746.042.944.646.235.546.627.778.2
MHA-XXL1.5147.243.845.647.536.446.928.481.9
MQA-XXL0.2446.643.045.046.936.146.528.581.3
GQA-8-XXL0.2847.143.545.447.736.347.228.481.6

The results show the following.

  • GQA performs close to multi-head: its average is 47.1, almost the same as MHA-XXL's 47.2, and 0.5 higher than MQA-XXL (46.6).
  • GQA is nearly as fast as MQA: inference takes 0.28 seconds, close to MQA-XXL's 0.24 seconds and about one fifth of MHA-XXL's 1.51 seconds.
  • Converting a large model pays off more than using a small one: even MQA-XXL is faster (0.24 vs. 0.37) and better (46.6 vs. 46.0) than MHA-Large.

The conversion and additional training with α=0.05\alpha = 0.05 took about 600 TPUv3 chip-days of compute.

Practical considerations

GQA places constraints on how the numbers of heads and groups are chosen.

The number of query heads hh must be divisible by the number of groups GG. PyTorch's F.scaled_dot_product_attention(..., enable_gqa=True) likewise requires the number of query heads to be divisible by the number of key/value heads. PyTorch also groups query heads by consecutive indices (query heads 0∼h/G−10 \sim h/G - 1 use key/value head 0). When loading pretrained weights, check that the group assignment matches this.

Also keep the following in mind.

  • It is faster only during generation: what decreases is the amount of keys and values. The attention weight matrix is still N×NN \times N per head, so the computation quadratic in sequence length does not change. For long sequences, combine it with FlashAttention or similar.
  • The paper evaluates only encoder-decoder models: the paper's limitations section expects GQA's advantage over MQA to be even larger in decoder-only models, which do not separate self-attention and cross-attention, but this was not verified.
  • No comparison with training from scratch: due to compute constraints, the paper does not compare uptrained GQA with GQA trained from scratch.
  • Summarization evaluation has limits: the paper notes that measuring the quality of long-form generation with ROUGE is imperfect, which makes it hard to be confident in the trade-off conclusions.

Comparison with other methods

Comparing "how keys and values are held across heads" on the same criteria (hh is the number of query heads):

MethodNumber of key/value headsKV cache per word (one layer)QualityGeneration speedTraining stability
Multi-head attention (Vaswani et al., 2017)hh2hdk2 h d_kBaselineSlowStable
MQA (Shazeer, 2019)12dk2 d_kCan degradeFastestCan be unstable
GQA (Ainslie et al., 2023)GG2Gdk2 G d_kClose to multi-headClose to MQAStable in the paper's experiments

Training stability is based on Appendix A of the paper. Training MQA T5-Large from scratch led to frequent loss spikes, and fine-tuning on long-input tasks diverged quickly. Uptrained MQA was more stable than that but showed high variance in results, while GQA was stable.

The paper's related work lists other ways of speeding up generation. All of them can be combined with GQA.

  • FlashAttention: computes without keeping the N2N^2 score matrix in memory, speeding up training.
  • Quantization: stores weights and values, including keys and values, with fewer bits.
  • Knowledge distillation: trains a small model on the outputs of a large model, making the model itself smaller.
  • Speculative sampling: a small model proposes several tokens, and a large model verifies them together.

Guidelines for choosing:

  • To speed up a text-generation model without losing quality: use GQA. In the paper's experiments, G=8G = 8 was the sweet spot between speed and quality.
  • To put generation speed and memory first: use MQA.
  • If you already have a model trained with multi-head attention: following the paper, average the key/value weights per group and then train for about 5% of the original pretraining.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


class GroupedQueryAttention(nn.Module):
    """Grouped-query attention: split the h query heads into G groups,
    and share one key head and one value head per group (G = h gives MHA, G = 1 gives MQA)"""

    def __init__(self, d_model=1024, num_heads=8, num_groups=4, dropout=0.0):
        super().__init__()
        assert d_model % num_heads == 0
        assert num_heads % num_groups == 0, "the number of query heads must be divisible by the number of groups"
        self.h, self.g = num_heads, num_groups
        self.d_k = d_model // num_heads
        self.w_q = nn.Linear(d_model, num_heads * self.d_k)   # W_i^Q (h of them)
        self.w_k = nn.Linear(d_model, num_groups * self.d_k)  # W_g^K (G of them)
        self.w_v = nn.Linear(d_model, num_groups * self.d_k)  # W_g^V (G of them)
        self.w_o = nn.Linear(num_heads * self.d_k, d_model)
        self.dropout = dropout

    def forward(self, x, is_causal=False):
        B, N, _ = x.shape
        q = self.w_q(x).view(B, N, self.h, self.d_k).transpose(1, 2)  # [B, h, N, d_k]
        k = self.w_k(x).view(B, N, self.g, self.d_k).transpose(1, 2)  # [B, G, N, d_k]
        v = self.w_v(x).view(B, N, self.g, self.d_k).transpose(1, 2)
        # enable_gqa=True: shared in order, i.e. query heads 0 to h/G-1 use key/value head 0.
        # dropout_p ignores model.eval(), so set it to 0 yourself
        out = F.scaled_dot_product_attention(
            q, k, v, dropout_p=self.dropout if self.training else 0.0,
            is_causal=is_causal, enable_gqa=True,
        )
        return self.w_o(out.transpose(1, 2).reshape(B, N, self.h * self.d_k))


@torch.no_grad()
def mha_to_gqa(w_kv_mha, num_heads, num_groups):
    """Conversion from the paper: average the key (or value) weights of the heads within each group.
    w_kv_mha: nn.Linear(d_model, h*d_k) weight [h*d_k, d_model] -> [G*d_k, d_model]"""
    d_k = w_kv_mha.shape[0] // num_heads
    w = w_kv_mha.view(num_groups, num_heads // num_groups, d_k, -1)  # consecutive heads form one group
    return w.mean(dim=1).reshape(num_groups * d_k, -1)


gqa = GroupedQueryAttention(num_heads=8, num_groups=4)
gqa.eval()
x = torch.randn(2, 10, 1024)
print(gqa(x, is_causal=True).shape)  # torch.Size([2, 10, 1024])

# convert multi-head attention K weights (8 heads) into 4 groups
w_k_mha = torch.randn(8 * 128, 1024)
gqa.w_k.weight.copy_(mha_to_gqa(w_k_mha, num_heads=8, num_groups=4))
print(gqa.w_k.weight.shape)  # torch.Size([512, 1024])(4 groups × 128)

FAQ

Q. How many groups $G$ should I use?
A.

The paper chooses G=8G = 8 for T5-XXL, because increasing the groups from 1 (MQA) to 8 slows inference only slightly, while increasing further toward multi-head attention makes it slower. Choose GG from values that divide the number of query heads, and decide by comparing speed and quality on validation data.

Q. Does a GQA model have to be trained from scratch?
A.

No. With the paper's method, a model trained with multi-head attention is converted to GQA by averaging its key and value weights per group, then trained for about 5% of the original pretraining. For the paper's T5-XXL, this reached almost the same average quality as MHA-XXL (47.1 vs. 47.2).

Q. Which is faster, MQA or GQA?
A.

MQA, which has the fewest keys and values, is slightly faster. For the paper's T5-XXL, inference time per sample was 0.24 seconds for MQA and 0.28 seconds for GQA-8. GQA had higher quality (average 47.1 vs. 46.6) and trained more stably, so GQA is the better fit when quality matters.

References

  1. J. Ainslie, J. Lee-Thorp, M. de Jong, Y. Zemlyanskiy, F. Lebrón, and S. Sanghai, "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints," EMNLP, 2023.
  2. N. Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need," arXiv:1911.02150, 2019.
  3. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  4. PyTorch Documentation, "torch.nn.functional.scaled_dot_product_attention."