AI Logic

Attention Mechanisms

Multi-Query Attention (MQA)

Updated๏ผš

Structure of multi-query attention. Left: the computation flow (the query linear layer and scaled dot-product attention are repeated h times, once per head, while a single key linear layer and value linear layer are shared by all heads; the results are concatenated and passed through a linear layer). Right: a comparison of how key/value heads are shared (with h = 8, multi-head has 8 K/V heads, GQA has 4, and MQA has 1)

What is multi-query attention

Multi-query attention (MQA) is a variant of multi-head attention in which queries are produced separately for each head, while keys and values are produced only once and shared by all heads. It was proposed by Shazeer in 2019 in the paper "Fast Transformer Decoding: One Write-Head is All You Need". The goal is to speed up Transformer generation, where text is produced one token at a time.

The only difference from multi-head attention is the number of linear layers for keys and values. Head ii is computed as follows.

headi=Attention(QWiQ,ย KWK,ย VWV)\mathrm{head}_i = \mathrm{Attention}\left(Q W_i^Q,\ K W^K,\ V W^V\right)
  • WiQW_i^Q: the query linear-layer weights, separate for each head (same as multi-head attention).
  • WK,WVW^K, W^V: the key and value linear-layer weights, shared by all heads. In multi-head attention these were WiK,WiVW_i^K, W_i^V, separate for each head.
  • Attention\mathrm{Attention}: scaled dot-product attention.

The paper explains that MQA is obtained from multi-head attention code simply by removing the "heads" dimension from the keys, values, and their linear layers. The output linear layer WOW^O and the queries are unchanged.

Picture eight researchers (heads): instead of each fetching a different reference book from the shelf, they all share one book and only their questions (queries) differ. The effort of carrying books from the shelf drops to one-eighth.

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

Why generation is slow

MQA works because the slowness of token-by-token generation comes not from the amount of computation but from the amount of data read from memory. Section 2.4 of the paper analyzes it as follows.

During training, the target text is known, so queries for all positions can be computed at once. During generation, however, each output token becomes the next input, so tokens can only be computed one at a time. The keys and values for all past positions are stored (the KV cache) and reread for every new token.

Let nn be the sequence length, dd the vector size, bb the batch size, and hh the number of heads, and consider generating nn tokens.

ComputeMemory readsReads รท compute
Multi-head attentionฮ˜(bnd2)\Theta(bnd^2)ฮ˜(bn2d+nd2)\Theta(bn^2d + nd^2)ฮ˜(nd+1b)\Theta\left(\frac{n}{d} + \frac{1}{b}\right)
MQAฮ˜(bnd2)\Theta(bnd^2)ฮ˜(bnd+bn2k+nd2)\Theta(bnd + bn^2 k + nd^2)ฮ˜(1d+ndh+1b)\Theta\left(\frac{1}{d} + \frac{n}{dh} + \frac{1}{b}\right)

k=d/hk = d / h is the vector size of each head. On GPUs and TPUs, compute throughput is about two orders of magnitude higher than memory bandwidth, so when "reads รท compute" approaches 1, the compute units sit idle waiting for data.

  • The 1b\frac{1}{b} term: comes from reading the weights. It shrinks with larger batches.
  • The nd\frac{n}{d} term: comes from reading the keys and values. It grows with longer sequences and does not shrink with larger batches.

Because MQA has a single key/value head, this nd\frac{n}{d} term becomes hh times smaller (ndh\frac{n}{dh}). Compute stays the same; only the reads decrease.

The KV cache per layer per token holds 2hdk2 h d_k values in multi-head attention and 2dk2 d_k values in MQA. With the paper's experimental setting (h=8h = 8, dk=128d_k = 128), that is 2048 values versus 256. The sequence length and batch size that fit in memory can grow accordingly.

Computation steps

One MQA layer is computed in the following order (the code in Section 3 of the paper).

  1. Create queries per head: multiply the input by head ii's weights WiQW_i^Q to produce hh queries (each Nร—dkN \times d_k).
  2. Create only one set of keys and values: multiply by WK,WVW^K, W^V to produce a single set of keys and values (each Nร—dkN \times d_k).
  3. Per-head attention: each of the hh queries computes scaled dot-product attention using the same keys and values.
  4. Concatenate and apply a linear layer: concatenate the hh outputs and multiply by WOW^O to return to the original size.

During generation, the keys and values for the one new token from step 2 are appended to the end of the KV cache, and attention is computed between the query and the entire cache so far.

Even with fewer keys and values, the attention weight matrix is still Nร—NN \times N per head. What MQA reduces is the amount of keys and values (the KV cache and the reads from it); the compute quadratic in sequence length NN is unchanged. When N2N^2 is the bottleneck for long sequences, combine it with other methods such as FlashAttention or sparse attention.

Experimental results

The paper compares encoder-decoder Transformers (6 layers, dmodel=1024d_{\text{model}} = 1024, h=8h = 8, dk=dv=128d_k = d_v = 128) on English-to-German translation (WMT 2014). Since MQA has fewer linear-layer parameters, its feed-forward width is increased from 4096 to 5440 to match the total parameter count (211M). As alternative ways to shrink keys and values, models with fewer heads or shorter vectors are also compared.

Quality is as follows (Table 1). ln(PPL) is the log of the development-set perplexity (lower is better), and higher BLEU is better. Test BLEU is given as greedy decoding / beam search (beam 4).

Attentionhhdk,dvd_k, d_vln(PPL)BLEU (dev)BLEU (test)
Multi-head81281.42426.727.7 / 28.4
MQA81281.43926.527.5 / 28.5
Multi-head (fewer heads)11281.51825.8
Multi-head (fewer heads)2641.48026.226.8 / 27.9
Multi-head (fewer heads)4321.48826.1
Multi-head (shorter vectors)8161.51325.8

Speed is as follows (Table 2; microseconds per output token on TPUv2; sequence length 128).

AttentionTrainingGeneration (encoder + decoder)Beam search, width 4 (encoder + decoder)
Multi-head13.21.7 + 462.0 + 203
MQA13.01.5 + 3.81.6 + 32

The results show the following.

  • Generation becomes much faster: decoder time per token drops from 46 to 3.8 microseconds, about 12 times faster. Training speed is almost unchanged.
  • The quality loss is small: development BLEU drops by 0.2, but test BLEU with beam search is 28.5, above multi-head attention (28.4).
  • Better than reducing heads or vector size: all models that reduced hh or dkd_k to shrink keys and values did worse than MQA.

In language modeling experiments (Billion-Word benchmark, development perplexity), MQA scored 30.2 versus 29.9 for multi-head attention, better than the models with fewer heads or shorter vectors (30.9โ€“31.2) (Table 3).

Practical considerations

MQA trades a little of the model's expressiveness for speed.

With only one set of keys and values, the ability of each head to look at the input from a different perspective weakens, and quality can drop slightly. The later GQA paper reports that training T5-Large from scratch with MQA led to frequent loss spikes during pretraining and quick divergence when fine-tuning on long-input tasks. If training is unstable, consider an approach that keeps a few key/value heads, such as grouped-query attention (GQA).

Also keep the following in mind.

  • It is faster only during generation: in training, where all positions are computed at once, and in encoder processing, memory reads are rarely the bottleneck, so speed barely changes (training time in Table 2 is 13.2 versus 13.0).
  • The parameter count decreases: the key and value linear layers shrink by a factor of hh. The paper widens the feed-forward layer to match parameter counts in its comparison. When comparing with a multi-head attention model, decide in advance whether to match them.
  • A pretrained model cannot be turned into MQA as is: the weight shapes differ. The GQA paper shows a method that converts a multi-head attention model to MQA by averaging its key and value weights over heads, followed by additional training of about 5% of the original pretraining.

Comparison with other methods

Comparing, from the same angle, the multi-head attention variants that change "how heads hold keys and values" gives the following (hh is the number of query heads).

MethodKey/value headsKV cache per token (one layer)QualityGeneration speed
Multi-head attention (Vaswani et al., 2017)hh2hdk2 h d_kBaselineSlow
MQA (Shazeer, 2019)12dk2 d_kSlightly lowerFastest
GQA (Ainslie et al., 2023)GG (1<G<h1 < G < h)2Gdk2 G d_kClose to multi-headClose to MQA

There are other ways to reduce the amount of keys and values.

  • Limit the positions attended: the paper also combines MQA with a "local" version that restricts decoder self-attention to the previous 32 positions, showing that the two effects are independent (in Table 2, local MQA takes 3.3 microseconds per generated token).
  • Lower the precision of values: quantization stores values, including keys and values, with fewer bits (related work in the GQA paper).
  • Reduce reads with a different mechanism: speculative sampling proposes multiple tokens with a small model and verifies them together with the large model (also related work in the GQA paper).

Rough guidelines for choosing:

  • Generation speed and memory are the top priority: use MQA.
  • Preserve quality as much as possible, or training stability is a concern: use GQA.
  • No generation (classification or encoder-only models): multi-head attention is sufficient.

PyTorch example

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


class MultiQueryAttention(nn.Module):
    """Multi-query attention: queries per head, one set of keys and values for all heads"""

    def __init__(self, d_model=1024, num_heads=8, dropout=0.0):
        super().__init__()
        assert d_model % num_heads == 0
        self.h = num_heads
        self.d_k = d_model // num_heads
        self.w_q = nn.Linear(d_model, d_model)    # W_1^Q, ..., W_h^Q combined
        self.w_k = nn.Linear(d_model, self.d_k)   # W^K (one head only)
        self.w_v = nn.Linear(d_model, self.d_k)   # W^V (one head only)
        self.w_o = nn.Linear(d_model, d_model)    # W^O
        self.dropout = dropout

    def forward(self, x, cache=None, is_causal=False):
        """x: [B, N, d_model]. cache is (K, V) up to the previous step (both [B, 1, M, d_k])"""
        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).unsqueeze(1)                                   # [B, 1, N, d_k]
        v = self.w_v(x).unsqueeze(1)
        if cache is not None:  # during generation: append only one head's K and V to the cache
            k = torch.cat([cache[0], k], dim=2)
            v = torch.cat([cache[1], v], dim=2)
        # With enable_gqa=True, the single K/V head is shared by the h query heads.
        # 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,
        )
        out = out.transpose(1, 2).reshape(B, N, self.h * self.d_k)  # concatenate
        return self.w_o(out), (k, v)


mqa = MultiQueryAttention()
mqa.eval()

# Computing all positions at once, as in training
x = torch.randn(2, 10, 1024)
y, (k, v) = mqa(x, is_causal=True)
print(y.shape, k.shape)  # torch.Size([2, 10, 1024]) torch.Size([2, 1, 10, 128])

# Generation: one token at a time. The cache holds one head ([2, 8, M, 128] for multi-head)
cache = (k, v)
x_new = torch.randn(2, 1, 1024)
y_new, cache = mqa(x_new, cache=cache)
print(cache[0].shape)  # torch.Size([2, 1, 11, 128])

# In older versions without enable_gqa, replicate K and V for each head before passing them (same result)
q = torch.randn(2, 8, 10, 128)
same = F.scaled_dot_product_attention(q, k.expand(-1, 8, -1, -1), v.expand(-1, 8, -1, -1), is_causal=True)

FAQ

Q. Does MQA also speed up training?
A.

Hardly. In the paper's experiments, training time per token was 13.2 microseconds for multi-head attention and 13.0 for MQA. In training, all positions can be computed at once, so memory reads are rarely the bottleneck. The speedup comes during inference, when tokens are generated one at a time.

Q. How is MQA different from reducing the number of heads?
A.

Both reduce the amount of keys and values, but reducing the number of heads also reduces the number of query perspectives. MQA keeps hh query heads and shares only the keys and values. In the paper's translation experiments, models reduced to 1, 2, or 4 heads had development BLEU of 25.8โ€“26.2, lower than MQA's 26.5.

Q. How do I use MQA in PyTorch?
A.

Pass queries shaped [B,h,N,dk][B, h, N, d_k] and keys and values shaped [B,1,N,dk][B, 1, N, d_k] to F.scaled_dot_product_attention, and specify enable_gqa=True. As long as the number of query heads is divisible by the number of key/value heads, keys and values are shared in the computation without being replicated.

References

  1. N. Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need," arXiv:1911.02150, 2019.
  2. 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.
  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."