DL0044 Multi-Query Attention

What is Multi-Query Attention in transformer models?

Answer

Multi-Query Attention (MQA) is a variant of multi-head attention where all query heads share a single key and value projection instead of each head owning its own K/V. The KV cache therefore stores one K/V pair per token rather than one per head, shrinking cache memory and bandwidth by a factor of h, which directly speeds up autoregressive decoding, usually with only a minor quality cost.

(1) Structure: Queries are still projected into h distinct heads, but all of them attend against one shared K and one shared V.
(2) Cache Savings: The per-token KV cache drops from O(n \cdot h \cdot d_k) to O(n \cdot d_k), hx smaller.
(3) Trade-off: Slightly less expressive than full MHA (one key/value “view” of the sequence), which GQA later interpolates by sharing K/V across small groups of heads.

Mathematical Formulation:
\mathrm{head}_i = \mathrm{softmax}\!\left(\frac{Q_i K_{\text{shared}}^{\top}}{\sqrt{d_k}}\right) V_{\text{shared}}
\mathrm{Cache}_{\text{MQA}} = \frac{1}{h}\,\mathrm{Cache}_{\text{MHA}}

Where:

  • Q_i is the query of head i \in \{1, \ldots, h\}; K_{\text{shared}}, V_{\text{shared}} are the single key/value projections used by all heads.
  • d_k is the head dimension and h the number of query heads.
Side-by-side diagram of multi-head attention with separate query, key, and value boxes per head versus multi-query attention with many query heads converging on one shared key and value box.

Figure 1: MHA gives every head its own K and V; MQA keeps multiple query heads but shares one K and one V across all of them.

Why Decoding Gets Faster: Autoregressive inference is memory-bandwidth bound: every generated token must read the entire KV cache. An hx smaller cache means hx less data movement per step, which is why MQA (and its successor GQA, used in LLaMA-2/3) is standard in serving-oriented LLMs.


Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *