AI State of the Art
Fundamentals/The Transformer: The Architecture That Changed Everything/26 min
Section 31

Multi-Head Attention: Why and How

Listen as a podcast →

The problem: one pair of glasses isn't enough

Imagine you're wearing a single pair of glasses to analyze a text. These glasses show you only one aspect of meaning: maybe grammar, maybe semantics, maybe just the relative positions of words. You see one thing, but you're blind to the rest.

That's exactly the problem with a single attention head. Take the sentence "I'm going to the bank":

  • Grammatical relationship: "going" is the verb, "bank" is the prepositional complement
  • Semantic relationship: "bank" = financial institution (not the riverbank)
  • Positional relationship: "bank" is at the end of the sentence, after the preposition "to"

A single attention head is forced to compress all this information into a single set of attention scores. In practice, it ends up capturing only one type of relationship and ignoring the others. But language is inherently multidimensional. To properly understand a text, you need to simultaneously analyze grammar, meaning, position, coreferences, and many other aspects.

The solution: multi-head attention. Instead of a single pair of glasses, imagine 8 specialized pairs working in parallel:

  • Pair 1: sees subject-verb-object relationships
  • Pair 2: sees coreferences (when "he" refers to "cat")
  • Pair 3: sees adjective-noun relationships
  • Pairs 4-8: other linguistic patterns

You look through all 8 pairs simultaneously, then merge the 8 perspectives into one rich and complete understanding.

Why the glasses metaphor works well

Each pair of glasses (attention head) transforms words into its own "vision space" via its own projection matrices. The same word appears differently to each head, exactly like different glasses show you different aspects of the same object. The final fusion combines all these perspectives.

How it works: divide and conquer

The idea is simple: instead of one huge attention head working in the full space, you create several small heads, each working in a reduced subspace.

Take the original Transformer: the representation size is dmodel=512d_{model} = 512.

With 8 attention heads:

  • Each head works in a space of only 512 / 8 = 64 dimensions
  • But the 8 heads operate in parallel

For each head ii (from 1 to 8), independent projections are applied:

Qi=word×WQi(64 dimensions)Q_i = \text{word} \times W_{Q_i} \quad (64 \text{ dimensions}) Ki=word×WKi(64 dimensions)K_i = \text{word} \times W_{K_i} \quad (64 \text{ dimensions}) Vi=word×WVi(64 dimensions)V_i = \text{word} \times W_{V_i} \quad (64 \text{ dimensions}) resulti=Attention(Qi,Ki,Vi)\text{result}_i = \text{Attention}(Q_i, K_i, V_i)

Those four lines say something simple: the word's vector is multiplied by three tables of coefficients belonging to head ii (WQiW_{Q_i}, WKiW_{K_i}, WViW_{V_i}) which pull out three shrunken versions of the word (QiQ_i its question, KiK_i its label, ViV_i its content). The attention formula from the previous lesson is then applied to that trio to give head ii's result.

Each head has its own matrices WQW_Q, WKW_K, WVW_V. This is essential: it's these different matrices that allow each head to specialize on a different type of relationship. Head 1 learns to project words in a way that highlights grammatical links, head 2 projects differently to highlight coreferences, etc.

Then, the results from all 8 heads are concatenated and projected by an output matrix:

Resultfinal=Concat(result1,result2,…,result8)×Woutput\text{Result}_{final} = \text{Concat}(\text{result}_1, \text{result}_2, \ldots, \text{result}_8) \times W_{output}

In words: the 8 small 64-dimension vectors produced by the heads are laid end to end (that is what Concat\text{Concat} does), which gives back a vector of 8 × 64 = 512 dimensions, and that vector is multiplied by one last learned table of coefficients, WoutputW_{output}. This matrix learns to intelligently combine the 8 perspectives into a coherent final representation.

The secret: identical cost

Here's what makes multi-head attention particularly elegant: the computational cost is identical to a single head.

8 heads x 64 dimensions = exactly the same volume of computation as 1 head x 512 dimensions.

You're simply dividing the work among 8 "specialized workers" instead of entrusting it to a single "generalist". Zero overhead. But in exchange, you get 8 different perspectives instead of one. It's a reorganization of computation, not an addition.

A remarkably efficient design

This is an example of genius in network architecture design. You get a much richer representational capacity without paying the slightest additional cost in computation or memory. Just an intelligent division of labor.

What each head actually learns

This isn't just theoretical intuition. Researchers have visualized the attention matrices of each head in trained models, and the results confirm the specialization.

"Subject-verb" head: when it processes a verb, it gives the most attention to the sentence's subject.

  • "The cat eats the mouse": "eats" looks at "cat", "mouse" also looks at "eats"

"Coreference" head: it follows the links between pronouns and their antecedents.

  • "The cat sleeps. It purrs.": "it" gives almost all its attention to "cat"

"Local" head: attention concentrated on the 2-3 immediate neighboring words.

  • Each word mostly looks at its direct neighbors, capturing the local structure of the sentence

"Copy" head: particularly useful in translation, it identifies when a token should be copied as-is.

  • "Paris" in the source sentence looks at "Paris" in the target (proper nouns don't get translated)

Remaining heads: mixed patterns, harder to interpret, but capturing regularities that humans don't easily formalize.

Redundancy: a quality assurance

Fascinating observation: you can remove certain heads from a trained model without catastrophic loss of performance. There's redundancy between heads. But this redundancy isn't waste: it's insurance. If a head learns poorly or captures an unhelpful pattern, the others compensate. It's like having redundant systems in an airplane: most of the time, it's "useless", but the day a system fails, the others take over.

Modern optimizations: the KV cache problem

Multi-head attention has an important practical problem during inference (generating text token by token). At each newly generated token, the model must recompute attention over all previous tokens. To avoid recomputing everything each time, we keep the already-computed Keys and Values in memory: this is the KV cache (K for key, V for value).

Why K and V are cached, and Q never is

This is the question everyone asks and almost nobody answers. Why is it called a KV cache and not a QKV cache?

The answer comes entirely from causal attention. At step t of generation, the model processes one token, the one it has just appended. So it needs:

  • its single query, the one belonging to the current token, the question that particular token is asking;
  • the keys and values of every previous token, because the whole history of the sentence is what has to be consulted in order to answer that question.

Compare the two lifespans. Token 5's query was used once, at step 5, when the model was processing that token. It will never be used again: at step 12 it is token 12 that asks its own question, with its own query. Token 5's key and value, by contrast, are re-read at every subsequent step: token 6 consults them, so does token 7, so does token 1000.

Hence the rule, which holds far beyond Transformers: you cache what gets re-read, not what gets written once.

During training there is no cache at all

The KV cache belongs strictly to token-by-token generation. In training, the whole sequence is presented at once and processed in a single parallel pass: the Q, K and V of every token are computed together, used once, and discarded. There is nothing to cache, because nothing is ever revisited. The cache appears only when the model generates, that is, when it runs one pass per appended token.

This also explains the rest of this page. Since K and V are the only things that grow with the conversation, every optimization that followed targets K and V alone: MQA (Multi-Query Attention), GQA (Grouped-Query Attention), MLA (Multi-head Latent Attention, which compresses K and V into a smaller space before storing them). None of them touches Q, there would be nothing to gain.

The cost, in numbers

Here is the shape of the cache. Per layer, we store one key and one value per head and per token already seen:

elements per layer=2×H×L×dk\text{elements per layer} = 2 \times H \times L \times d_k

Every symbol, in plain words: HH is the number of attention heads, LL the number of tokens already in the context, dkd_k the size of one key (or value) vector for one head. The factor of 2 is not mysterious: it counts the two things being stored, the key and the value. There is no factor of 3, precisely because the query is not stored.

The problem: for a long sequence (128,000 tokens) with 32 heads, each having its own K and V, the cache eats an enormous amount of GPU memory. It's often the bottleneck during inference, not the computation itself.

Recent models have found elegant solutions:

GQA: Grouped-Query Attention

GQA (Grouped-Query Attention): instead of each head having its own K and V, heads are grouped and share K and V within each group.

Concrete example: 8 Query heads, but only 2 sets of K/V:

  • Heads 1-4 share the same set of K, V
  • Heads 5-8 share another set of K, V

Each head keeps its own Query (and therefore its own "perspective"), but shares Keys and Values with its group. The saving is easy to compute: 8 sets of K/V become 2, so the KV cache is 4 times smaller (8 ÷ 2 = 4), for a nearly imperceptible loss of performance.

Models using GQA: LLaMA 2/3, Mistral, Gemma, Qwen, essentially all modern LLMs (Large Language Models).

MQA: Multi-Query Attention

The extreme case, MQA (Multi-Query Attention): all heads share a single set of K and V. Each head keeps its own Query but uses the same Keys and Values.

"Sharing", but sharing what, exactly?

This is where the vocabulary trips everyone up. You will read sometimes that "the heads share a single K/V pair", sometimes that "there is now only one WKW_K matrix and one WVW_V matrix". Those two sentences say exactly the same thing, and seeing why means never being confused about it again.

Recall the fundamental distinction:

NatureWhere it lives
WKW_K, WVW_VLearned parameters: tables of coefficients frozen once and for all at the end of trainingIn the model file, on disk
KK, VVComputed activations: the result of X⋅WKX \cdot W_K and X⋅WVX \cdot W_V on the text currently being readIn memory, for the duration of one request

One matrix applied to one input can only produce one result. So if all the heads now have a single WKW_K instead of HH different ones, they necessarily obtain a single key KK per token instead of HH. Sharing the parameter and sharing the activation are the same decision seen from two sides: the parameter is the cause, the activation is the effect.

The picture that makes it obvious. Go back to the library from the self-attention lesson. Under MHA (Multi-Head Attention, the classic form), each of the HH readers has their own question, their own card index and their own copy of the library. Under MQA, the HH readers still each arrive with their own question (the Qs stay distinct per head, and that is exactly what keeps the heads looking at different things) but they now consult one index and one library instead of each owning a personal copy. We removed the copies, not the readers.

The saving is on the cache, not on the parameters

Going from HH WKW_K matrices down to one does save parameters, but that part is incidental: the attention matrices are only a fraction of the model, and above all their size never changes over the course of a conversation. What grows with every generated token is the cache. Shrinking the cache by a factor of HH is what lets you serve a long context, or more simultaneous users, on the same graphics card. MQA and GQA are inference-memory optimizations, not model-compression techniques.

Result: with 8 heads the KV cache is divided by 8; with 32 heads, by 32. Inference gets considerably faster, because at every token the GPU has far fewer bytes to re-read from its memory. The cost is a slight, measurable quality drop on some benchmarks.

Models using MQA: PaLM, Falcon

Comparison

VariantNumber of K/V setsKV cache memoryPerformance
MHA (original)1 set per head, i.e. HHMaximum (baseline)Excellent
GQA1 set per group of headsDivided by the number of heads per groupExcellent (nearly identical)
MQA1 set for the whole modelDivided by HH, the number of headsGood (slight drop)

In all three cases the number of Queries is unchanged: there is always one per head. Only the K/V column moves.

GQA is today the best compromise and has established itself as the de facto standard: almost no quality loss, but considerable memory savings that allow serving models on less expensive GPUs or processing longer sequences.

Simplified code (pseudo-Python)

class MultiHeadAttention:
    def __init__(self, d_model, num_heads):
        self.num_heads = num_heads
        self.d_k = d_model // num_heads

        self.W_Q = Linear(d_model, d_model)
        self.W_K = Linear(d_model, d_model)
        self.W_V = Linear(d_model, d_model)
        self.W_O = Linear(d_model, d_model)

    def forward(self, x):
        # Projections and reshape
        Q = self.W_Q(x).reshape(batch, seq, self.num_heads, self.d_k)
        K = self.W_K(x).reshape(batch, seq, self.num_heads, self.d_k)
        V = self.W_V(x).reshape(batch, seq, self.num_heads, self.d_k)

        # Per-head attention
        scores = (Q @ K.transpose(-1, -2)) / sqrt(self.d_k)
        weights = softmax(scores, dim=-1)
        output = weights @ V

        # Concatenate and project
        output = output.reshape(batch, seq, d_model)
        return self.W_O(output)

Why this matters

Multi-head attention is the central component that gives the Transformer its ability to understand language in depth. Without it, the model would be limited to capturing a single type of relationship between words. With it, each word simultaneously receives 8, 32, or even 128 different analyses that are then fused into a rich representation.

It's also a model of elegant AI design: rather than adding complexity and cost, we reorganize existing computation to obtain much more representational diversity. This principle of "dividing work without increasing cost" appears in many modern architectural innovations.

Key takeaways

  1. Multiple heads = multiple perspectives in parallel on the same data
  2. Each head has its own matrices W_Q, W_K, W_V (specialization)
  3. Outputs are concatenated and reprojected via W_O
  4. Identical cost to a single head (reorganization, not addition)
  5. Heads spontaneously learn distinct roles: grammar, semantics, position, coreference
  6. K and V are cached, Q never is: a token's query is used once, its key and value are re-read at every later step
  7. No cache during training: the whole sequence is processed at once, the cache exists only at generation time
  8. GQA is the modern standard optimization that massively reduces the KV cache; sharing the matrix WKW_K and sharing the activation KK are two ways of saying the same thing
Check your understanding0 / 4

1. During generation, the attention cache stores the keys and values of every past token, but never their queries. Why?

2. In the cache size, 2 × H × L × d_k, where does the factor 2 come from?

3. In Multi-Query Attention, what exactly do the heads share?

4. The main gain of MQA and GQA is in…