Multi-Query Attention › Multi-Query Attention: Extreme Sharing

Michael BrenndoerferUpdated August 4, 202511 min read
Language AI HandbookAll chapters
Part 29 of 67Modern Decoder Models
Chapter 210Multi-Query Attention › Multi-Query Attention: Extreme Sharing
Reading section 3 of 11 · Multi-Query Attention: Extreme Sharing · 11 minSection 3 of 11 · 11 min

Book contents

Section 3 of 11 · 11 min read

Multi-Query Attention › Multi-Query Attention: Extreme SharingOne section · Sections in this chapter3 / 11 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Multi-Query Attention, introduced by Noam Shazeer in 2019, addresses the KV cache problem through aggressive parameter sharing. The core insight is simple: instead of having hh separate key and value projections (one per head), use just one shared key and one shared value projection across all heads.

Multi-Query Attention (MQA)

Multi-Query Attention maintains multiple query heads but shares a single key head and a single value head across all of them. Each query head computes attention using the same keys and values, reducing the KV cache size by a factor of hh (the number of heads).

The MQA Formulation

To truly understand Multi-Query Attention, we need to first build intuition about what multi-head attention does and why each component exists. Think of attention as a retrieval system: queries ask questions, keys advertise what information is available, and values contain the actual content to retrieve. Multi-head attention runs multiple such retrieval systems in parallel, each learning to find different kinds of relationships.

Step 1: The Standard Multi-Head Attention Baseline

In standard multi-head attention, each head ii transforms the input through its own learned projection matrices. Given an input sequence X\mathbf{X}, we compute the three head-specific projection outputs:

Qi=XWiQ,Ki=XWiK,Vi=XWiV\mathbf{Q}_i = \mathbf{X} \mathbf{W}^Q_i, \quad \mathbf{K}_i = \mathbf{X} \mathbf{W}^K_i, \quad \mathbf{V}_i = \mathbf{X} \mathbf{W}^V_i

where:

  • X∈Rn×dmodel\mathbf{X} \in \mathbb{R}^{n \times d_{\text{model}}}: the input sequence with nn tokens, each represented as a dmodeld_{\text{model}}-dimensional vector
  • WiQ∈Rdmodel×dk\mathbf{W}^Q_i \in \mathbb{R}^{d_{\text{model}} \times d_k}: the query projection matrix for head ii
  • WiK∈Rdmodel×dk\mathbf{W}^K_i \in \mathbb{R}^{d_{\text{model}} \times d_k}: the key projection matrix for head ii
  • WiV∈Rdmodel×dv\mathbf{W}^V_i \in \mathbb{R}^{d_{\text{model}} \times d_v}: the value projection matrix for head ii
  • dkd_k: the dimension of queries and keys per head (typically dmodel/hd_{\text{model}} / h)
  • dvd_v: the dimension of values per head (often equal to dkd_k)

The subscript ii on each projection matrix is the key detail here. It tells us that every head learns its own transformation. Head 1 might learn to project tokens in a way that emphasizes syntactic features, while head 2 might emphasize semantic similarity. This specialization is what makes multi-head attention so powerful: the model can simultaneously attend to different types of relationships.

But this flexibility comes at a cost. During inference, we must cache the keys and values for each head separately. With 32 heads, we store 32 different Ki\mathbf{K}_i matrices and 32 different Vi\mathbf{V}_i matrices. This is where the memory bottleneck arises.

Step 2: The MQA Insight: Sharing Keys and Values

MQA asks a provocative question: do we really need different keys and values for each head? The hypothesis is that while different heads benefit from asking different questions (different queries), they might be able to share a common "index" (keys) and "content store" (values).

Mathematically, MQA removes the subscript from the key and value projections:

Qi=XWiQ,K=XWK,V=XWV\mathbf{Q}_i = \mathbf{X} \mathbf{W}^Q_i, \quad \mathbf{K} = \mathbf{X} \mathbf{W}^K, \quad \mathbf{V} = \mathbf{X} \mathbf{W}^V

Notice the key change:

  • WiQ\mathbf{W}^Q_i: still has subscript ii, meaning each head retains its own query projection
  • WK\mathbf{W}^K and WV\mathbf{W}^V: no subscript, meaning a single projection shared across all heads

The resulting matrices have dimensions:

  • Qi∈Rn×dk\mathbf{Q}_i \in \mathbb{R}^{n \times d_k}: unique query matrix for head ii
  • K∈Rn×dk\mathbf{K} \in \mathbb{R}^{n \times d_k}: one shared key matrix for all heads
  • V∈Rn×dv\mathbf{V} \in \mathbb{R}^{n \times d_v}: one shared value matrix for all heads

This is a simple but effective change. Different heads can still "ask different questions" because each projects the input into its own query space. But they all look up answers from the same key-value store. It's like having 32 researchers who each have their own research questions but share access to a single library catalog and book collection.

Step 3: Computing Attention with Shared KV

Each head now computes attention using its unique queries against the shared keys and values:

headi=softmax(QiKTdk)V\text{head}_i = \text{softmax}\left(\frac{\mathbf{Q}_i \mathbf{K}^T}{\sqrt{d_k}}\right) \mathbf{V}

Let's trace through what happens in this formula:

  1. Compute attention scores: QiKT\mathbf{Q}_i \mathbf{K}^T produces an n×nn \times n matrix where entry (p,q)(p, q) measures how much token at position pp should attend to position qq. Because Qi\mathbf{Q}_i is unique to head ii, each head produces different attention patterns.

  2. Scale the scores: Dividing by dk\sqrt{d_k} prevents the dot products from growing too large as dimension increases. Without scaling, the softmax would produce very peaked distributions, making gradients vanish during training.

  3. Normalize to weights: The softmax converts each row of scores into a probability distribution that sums to 1. These are the attention weights.

  4. Aggregate values: Multiplying by V\mathbf{V} computes a weighted sum of value vectors. All heads aggregate from the same V\mathbf{V}, but with different weights.

The key insight is that expressiveness comes from two sources: the diversity of attention patterns (which heads preserve through unique queries) and the diversity of retrieved content (which MQA sacrifices through shared values). Empirically, the diversity of attention patterns matters more than the diversity of values for most tasks.

To illustrate this, let's visualize how different query heads can produce distinct attention patterns even when sharing the same keys and values.

Out[7]:
Visualization
Heatmap of attention weights for Head 1, showing high attention concentrated on recent tokens along the diagonal.
Head 1: Local focus pattern, attending primarily to recent tokens.
Heatmap of attention weights for Head 2, showing strong attention to the first token position for all query positions.
Head 2: Start token pattern, strongly attending to the first position.
Heatmap of attention weights for Head 3, showing uniform attention distributed equally across all previous tokens.
Head 3: Uniform pattern, equal attention across all previous tokens.
Heatmap of attention weights for Head 4, showing higher attention on even-indexed key positions in an alternating pattern.
Head 4: Alternating pattern, preferring even-indexed positions.

Each head learns a different way to "ask questions" of the shared key-value store. Head 1 might focus on recent context for local coherence, Head 2 might anchor to the beginning of the sequence, Head 3 might aggregate broadly, and Head 4 might pick up periodic patterns. The shared keys and values don't limit this diversity; they simply mean all heads retrieve from the same "library."

Step 4: Combining Head Outputs

Finally, we concatenate all head outputs and project back to the model dimension:

MQA(X)=Concat(head1,…,headh)WO\text{MQA}(\mathbf{X}) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h) \mathbf{W}^O

where:

  • headi∈Rn×dv\text{head}_i \in \mathbb{R}^{n \times d_v}: the output from attention head ii, containing each head's weighted aggregation
  • Concat(⋅)∈Rn×(h⋅dv)\text{Concat}(\cdot) \in \mathbb{R}^{n \times (h \cdot d_v)}: concatenation along the feature dimension
  • WO∈R(h⋅dv)×dmodel\mathbf{W}^O \in \mathbb{R}^{(h \cdot d_v) \times d_{\text{model}}}: the output projection that mixes information across heads
  • hh: the total number of attention heads

This final projection is unchanged from standard MHA. Each head contributes its perspective, and the output projection learns to combine them into a coherent representation. The key benefit of MQA is that we achieve this with much less memory overhead during inference.

Visualizing the Difference

The architectural difference between MHA and MQA becomes clear when we visualize the projection structure.

Out[8]:
Visualization
Diagram of Multi-Head Attention showing multiple separate Q, K, V projection blocks for each of the h attention heads.
Multi-Head Attention (MHA): Each head maintains its own Q, K, V projections, requiring h copies in the KV cache.
Diagram of Multi-Query Attention showing multiple Q projection blocks but only a single shared K and V projection block used by all heads.
Multi-Query Attention (MQA): All heads share a single K and V projection, reducing cache size by a factor of h.