Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 10. Inside the transformer
  4. 10.2

Lesson 10.2 · 2 of 7 · 6 min read · Reviewed 24 Nov 2026

Multi-head attention

By the end, you can

  • Describe how multi-head attention splits, runs and recombines attention.
  • Explain how grouped-query attention changes what each head stores.

One attentionAttention: The mechanism that lets each token weigh every other token in the context when building its representation. operation produces one set of weights per tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id.. But a word relates to its neighbours in several ways at once. In “The engineer who wrote the parser fixed it”, the token fixed needs its subject (engineer), its object (it), and perhaps the tense of nearby verbs. One softmax has to share its weight among all of those. Multi-head attention gives the layer several independent attention operations instead.

How it works

With a model width of 512 and 8 heads, as in the original transformerTransformer: The neural network architecture behind modern LLMs, built from stacked attention and feed-forward layers. paper:

  1. Project each token into 8 separate queries, keys and values, each of length 512 / 8 = 64. Each head has its own W_Q, W_K and W_V.
  2. Attend in every head independently, using the recipe from lesson 10.1. Each head produces its own weights and its own 64-number output per token.
  3. Concatenate the 8 outputs end to end: 8 x 64 = 512 numbers again.
  4. Mix with one more learned matrix, W_O, so information from different heads can be combined.

Because each head works on a slice, the total cost is about the same as one big head of 512. You get several kinds of attention for the price of one.

What heads end up doing

Nobody assigns heads their jobs. Training finds them, and when researchers inspect trained models they often see recognisable patterns:

Pattern What the head does Example
Previous token Each token looks mostly at the one before it Helps copy and continue phrases
Subject finder Verbs look at their subject fixed attends to engineer
Coreference Pronouns look at what they refer to it attends to parser
Broad Weight spread evenly over many tokens A rough summary of the context

Plenty of heads show no clear pattern at all, and some can be removed with little effect. Treat these labels as useful pictures, not as a complete map of how the model works (lesson 10.6).

Sharing keys and values: MQA and GQA

During generation, every head’s keys and values for every past token are kept in memory: the KV cacheKV cache: Stored attention keys and values for tokens already processed, so they are not recomputed for each new token. (lesson 10.5). With 32 heads, that is 32 sets per token per layer.

  • Multi-query attention (MQA): all query heads share one key head and one value head.
  • Grouped-query attention (GQA): query heads are split into groups, and each group shares a key and value head. For example, 32 query heads in 8 groups need only 8 key and value heads.

GQA keeps most of the quality of full multi-head attention while cutting the cache by the group size, here 4x. Many current open-weight modelsOpen-weight model: A model whose trained weights are published so you can download, run and fine-tune it yourself., such as the Llama and Mistral families, use it.

A worked size example

Setting Query heads KV heads Head size Cache per token per layer
Multi-head 32 32 128 2 x 32 x 128 = 8,192 numbers
GQA, 8 groups 32 8 128 2 x 8 x 128 = 2,048 numbers
MQA 32 1 128 2 x 1 x 128 = 256 numbers

The 2 is for keys plus values. The query side is unchanged in all three, so the model still asks 32 different questions.

Common mistakes

  • ThinkingExtended thinking: A mode in which the model reasons step by step in thinking blocks before giving its final answer. more heads means more compute. At a fixed width, more heads means smaller heads.
  • Believing each head has a known, single role. Some do, many don’t.
  • Confusing GQA with fewer heads. GQA keeps every query head and shares only keys and values.

Key points

  • Multi-head attention runs several smaller attention operations side by side, each with its own query, key and value matrices.
  • Each head works on a slice of the model width, so eight heads of 64 cost about the same as one head of 512.
  • Head outputs are joined end to end and mixed by an output matrix, so the layer can combine what different heads found.
  • Multi-query and grouped-query attention let heads share keys and values, which shrinks the KV cache.
Hands-on labRuns in the Playground

Split attention into two heads

Run two attention heads on slices of the same vectors and see them pick different keys.

You will have: A multi_head function that prints each head's top key for the token it and the width after concatenation.

Steps

  1. Fill in head_slice so each head sees only its own 2 of the 4 numbers.
  2. Fill in the concatenation of head outputs.
  3. Run it: head 1 should link it to parser, head 2 should stay on it.
  4. Change one key vector so head 2 prefers another token, and rerun.
  5. Check the joined output is the same width the layer started with.

Done when

  • Head 1's top key for it is parser.
  • Head 2's top key for it is it.
  • The concat width prints as 4.

Open in the Playground No API key needed.

Starter code (Python)
import math

# Width 4, split into 2 heads of 2 numbers each. The vectors are hand-made so the two heads learn different habits.
TOKENS = ["the", "parser", "crashed", "because", "it"]
# Each token's query, key and value, already projected (4 numbers each).
Q = {"the": [0, 0, 1, 0], "parser": [0, 0, 1, 0], "crashed": [1, 0, 1, 0], "because": [0, 0, 1, 0], "it": [2, 0, 0, 2]}
K = {"the": [0, 0, 0, 0], "parser": [2, 0, 0, 0], "crashed": [0, 0, 0, 0], "because": [0, 0, 2, 0], "it": [0, 0, 0, 2]}
V = {t: [i, i, -i, -i] for i, t in enumerate(TOKENS)}
HEADS, WIDTH = 2, 4
SIZE = WIDTH // HEADS

def softmax(xs):
    m = max(xs)
    e = [math.exp(x - m) for x in xs]
    return [x / sum(e) for x in e]

def head_slice(vec, h):
    # TODO: return the numbers that belong to head h: positions h * SIZE up to (h + 1) * SIZE.
    return vec

def attend_head(token, h):
    i = TOKENS.index(token)
    q = head_slice(Q[token], h)
    scores = []
    for j, other in enumerate(TOKENS):
        s = sum(a * b for a, b in zip(q, head_slice(K[other], h))) / math.sqrt(SIZE)
        scores.append(s if j <= i else float("-inf"))   # causal mask
    w = softmax(scores)
    out = [sum(w[j] * head_slice(V[t], h)[d] for j, t in enumerate(TOKENS)) for d in range(SIZE)]
    return w, out

def multi_head(token):
    outs, tops = [], []
    for h in range(HEADS):
        w, out = attend_head(token, h)
        tops.append(TOKENS[w.index(max(w))])
        # TODO: concatenate this head's output onto outs (outs.extend(out)).
    return tops, outs

tops, joined = multi_head("it")
for h, top in enumerate(tops):
    print(f"head {h + 1} top key for 'it': {top}")
print("concat width:", len(joined))
Show a solution
import math

# Width 4, split into 2 heads of 2 numbers each. The vectors are hand-made so the two heads learn different habits.
TOKENS = ["the", "parser", "crashed", "because", "it"]
# Each token's query, key and value, already projected (4 numbers each).
Q = {"the": [0, 0, 1, 0], "parser": [0, 0, 1, 0], "crashed": [1, 0, 1, 0], "because": [0, 0, 1, 0], "it": [2, 0, 0, 2]}
K = {"the": [0, 0, 0, 0], "parser": [2, 0, 0, 0], "crashed": [0, 0, 0, 0], "because": [0, 0, 2, 0], "it": [0, 0, 0, 2]}
V = {t: [i, i, -i, -i] for i, t in enumerate(TOKENS)}
HEADS, WIDTH = 2, 4
SIZE = WIDTH // HEADS

def softmax(xs):
    m = max(xs)
    e = [math.exp(x - m) for x in xs]
    return [x / sum(e) for x in e]

def head_slice(vec, h):
    return vec[h * SIZE:(h + 1) * SIZE]

def attend_head(token, h):
    i = TOKENS.index(token)
    q = head_slice(Q[token], h)
    scores = []
    for j, other in enumerate(TOKENS):
        s = sum(a * b for a, b in zip(q, head_slice(K[other], h))) / math.sqrt(SIZE)
        scores.append(s if j <= i else float("-inf"))   # causal mask
    w = softmax(scores)
    out = [sum(w[j] * head_slice(V[t], h)[d] for j, t in enumerate(TOKENS)) for d in range(SIZE)]
    return w, out

def multi_head(token):
    outs, tops = [], []
    for h in range(HEADS):
        w, out = attend_head(token, h)
        tops.append(TOKENS[w.index(max(w))])
        outs.extend(out)                                 # concatenate head outputs
    return tops, outs

tops, joined = multi_head("it")
for h, top in enumerate(tops):
    print(f"head {h + 1} top key for 'it': {top}")
print("concat width:", len(joined))
Quick checkA model has a width of 1,024 and 16 attention heads. How long is each head's query vector?
How sure are you?
Pick an answer and how sure you are