Skip to content
E
Educatum

Explain the purpose and benefits of using multi-head attention in transformer models.

Curated by Educatum AI teamLast updated:
Transformer Models
Direct Answer

Multi-head attention splits queries, keys, and values into h parallel lower-dimensional heads (d_k = d_model / h) with distinct learned projections, allowing each head to attend to different syntactic, positional, or semantic subspaces simultaneously. Because each head operates in a reduced d_k dimension, multi-head attention captures richer relational patterns at roughly the same compute cost as full-dimension single-head attention. Modern LLMs also use Multi-Query (MQA) and Grouped-Query Attention (GQA) to shrink KV-cache memory.

Study Card: Multi-Head Attention in Transformers

Direct Answer

Multi-Head Attention (MHA) (Vaswani et al., 2017) replaces a single full-dimensional attention operation with hh parallel attention heads operating in distinct learned representation subspaces of dimension dk=dv=dmodel/hd_k = d_v = d_{\text{model}} / h:

MultiHead(Q,K,V)=Concat(head1,…,headh) WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\,W^O

headi=Attention ⁣(QWiQ,  KWiK,  VWiV)=softmax ⁣((QWiQ)(KWiK)Tdk+M)(VWiV)\text{head}_i = \text{Attention}\!\left(Q W_i^Q,\; K W_i^K,\; V W_i^V\right) = \text{softmax}\!\left(\frac{(Q W_i^Q)(K W_i^K)^T}{\sqrt{d_k}} + M\right)(V W_i^V)

where WiQ,WiK∈Rdmodel×dkW_i^Q, W_i^K \in \mathbb{R}^{d_{\text{model}} \times d_k}, WiV∈Rdmodel×dvW_i^V \in \mathbb{R}^{d_{\text{model}} \times d_v}, and WO∈Rhdv×dmodelW^O \in \mathbb{R}^{h d_v \times d_{\text{model}}}.

Why MHA is so effective:

  1. Prevents Softmax Averaging Bottlenecks: A single attention head outputs a single convex combination of token values per position; multi-head attention lets different heads simultaneously track syntactic subject-verb links, pronoun coreference, positional neighbors, and semantic modifiers without blurring them together.
  2. Roughly Constant Compute Cost: Because each head shrinks projection size to dk=dmodel/hd_k = d_{\text{model}} / h, total projection parameters (4 dmodel24\,d_{\text{model}}^2) and attention FLOPs stay essentially identical to single-head attention at full dmodeld_{\text{model}}, while gaining hh independent attention matrices.
  3. Ensemble & Gradient Richness: Parallel subspace projections yield smoother optimization and specialization across heads (with modern LLMs extending MHA via MQA and GQA to reduce KV-cache memory during decoding).

Key Terms

  • Attention Head (headi\text{head}_i): Independent scaled dot-product attention module operating on a dkd_k-dimensional subspace.
  • Subspace Projections (WiQ,WiK,WiVW_i^Q, W_i^K, W_i^V): Learned matrices mapping inputs into specialized relational spaces before concatenation and mixing via WOW^O.
  • Constant-Compute Partitioning (dk=dmodel/hd_k = d_{\text{model}} / h): Keeps total FLOPs comparable to single-head attention while multiplying relational expressivity.
  • Multi-Query (MQA) & Grouped-Query Attention (GQA): Variants that keep hh distinct query heads while sharing 11 (MQA) or g<hg < h (GQA) key/value heads to drastically shrink autoregressive KV-cache memory bandwidth.

Example

Consider "The trophy wouldn't fit into the brown suitcase because it was too big":

  • Head 1 (Syntactic): Attends from "fit" back to "trophy" and "suitcase" (verb arguments).
  • Head 2 (Local Modifier): Links "brown" directly to "suitcase".
  • Head 3 (Coreference / Semantic): Resolves "it" strongly toward "trophy" using "big" context.

Concatenating all heads and mixing via WOW^O preserves every distinct relationship simultaneously.

Code Implementation

import torch
import torch.nn as nn


class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, num_heads):
        super().__init__()
        assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
        self.num_heads = num_heads
        self.d_k = d_model // num_heads

        # Joint projections across all heads (equivalent to concatenating h per-head projections)
        self.W_q = nn.Linear(d_model, d_model)
        self.W_k = nn.Linear(d_model, d_model)
        self.W_v = nn.Linear(d_model, d_model)
        self.W_o = nn.Linear(d_model, d_model)

    def scaled_dot_product_attention(self, q, k, v, mask=None):
        # q: (B, H, seq_len_q, d_k), k/v: (B, H, seq_len_k, d_k)
        attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (self.d_k ** 0.5)
        if mask is not None:
            attn_scores = attn_scores.masked_fill(mask == 0, float("-inf"))
        attn_weights = torch.softmax(attn_scores, dim=-1)
        output = torch.matmul(attn_weights, v)
        return output, attn_weights

    def forward(self, q, k, v, mask=None):
        batch_size = q.size(0)

        # Reshape & transpose into (batch_size, num_heads, seq_len, d_k)
        q = self.W_q(q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        k = self.W_k(k).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        v = self.W_v(v).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)

        attn_output, attn_weights = self.scaled_dot_product_attention(q, k, v, mask)

        # Concatenate heads back to (batch_size, seq_len_q, d_model) and mix via W_o
        attn_output = (
            attn_output.transpose(1, 2)
            .contiguous()
            .view(batch_size, -1, self.num_heads * self.d_k)
        )
        return self.W_o(attn_output), attn_weights


torch.manual_seed(0)
batch_size, seq_len, d_model, num_heads = 4, 10, 512, 8
x = torch.randn(batch_size, seq_len, d_model)
mha = MultiHeadAttention(d_model, num_heads)
output, attn_weights = mha(x, x, x)

print("Output shape:", output.shape)            # (4, 10, 512)
print("Attention weights shape:", attn_weights.shape)  # (4, 8, 10, 10)
  • Grouped-Query Attention (GQA) & Multi-Head Latent Attention (MLA): Standard in LLaMA-3, Mistral, and DeepSeek to break memory-bandwidth limits from large MHA KV caches during generation.
  • Head Pruning & Induction Heads: Mechanistic interpretability shows specific heads act as induction heads supporting in-context copying and pattern completion, while some redundant heads can be pruned.
  • Rotary Position Embeddings (RoPE): Applied per head on qiq_i and kik_i vectors prior to dot-product scoring.
  • Cross-Attention: Uses the exact same multi-head mechanism with qq coming from one sequence/modality and k,vk, v from another.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.