Simple Algorithm
Deep Learning · Representation · 24 min

Self-Attention & Multi-Head Attention

Queries, keys and values, scaled dot products and many heads in parallel.

Self-attention fits on one line, softmax⁡(QK⊤/dk)V\softmax(QK^\top/\sqrt{d_k})V, and most of a transformer's design decisions hide inside it: why the scores are scaled, how the future is hidden from each token, why many heads cost no more than one, and where the bill for long contexts comes from. Here you derive each one and implement the layer.

What you’ll learn

  • Compute scaled dot-product attention in matrix form with causal and padding masks, and derive the 1/dk1/\sqrt{d_k} scaling from the variance of a dot product.
  • Prove that self-attention without positional information is permutation-equivariant, and say what breaks the symmetry.
  • Assemble multi-head attention and show that it has 4d24d^2 weights (plus 4d4d biases) whatever the number of heads.
  • Count the FLOPs of an attention layer, 8Td2+4T2d8Td^2+4T^2d, and find the length at which the quadratic term dominates.
  • Distinguish self-attention from cross-attention, and describe the kinds of heads found in trained models.

Attention in matrix form

Stack the TT token vectors of a sequence as the rows of X∈RT×dX\in\R^{T\times d}. Each token is mapped to a query, a key and a value by three learned matrices: Q=XWQQ=XW_Q and K=XWKK=XW_K in RT×dk\R^{T\times d_k}, and V=XWV∈RT×dvV=XW_V\in\R^{T\times d_v}. Every query is compared with every key in one matrix product, and each row of scores becomes a probability distribution over positions. This is scaled dot-product attention:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk+M)⏟A ∈ RT×T V,Atj=exp⁡ ⁣(qt⋅kj/dk+Mtj)∑l=1Texp⁡ ⁣(qt⋅kl/dk+Mtl)\operatorname{Attention}(Q,K,V)=\underbrace{\softmax\!\Big(\frac{QK^\top}{\sqrt{d_k}}+M\Big)}_{A\ \in\ \R^{T\times T}}\,V,\qquad A_{tj}=\frac{\exp\!\big(\mathbf q_t\cdot\mathbf k_j/\sqrt{d_k}+M_{tj}\big)}{\sum_{l=1}^{T}\exp\!\big(\mathbf q_t\cdot\mathbf k_l/\sqrt{d_k}+M_{tl}\big)}
The softmax acts on each row, so every row of AA is nonnegative and sums to 11, and output row tt is the convex combination ∑jAtjvj\sum_jA_{tj}\mathbf v_j of the values. MM is an additive mask: 00 where attention is allowed and −∞-\infty where it is not.
DerivationWhere the √d_k comes from
  1. E[q⋅k]=∑i=1dkE[qi] E[ki]=0\E[\mathbf q\cdot\mathbf k]=\sum_{i=1}^{d_k}\E[q_i]\,\E[k_i]=0

    Assume the coordinates of q\mathbf q and k\mathbf k are independent with mean 00 and variance 11, roughly the situation at initialization when inputs are normalized and weights are scaled to preserve variance. The score is a sum of dkd_k products, with mean

  2. Var⁡(qiki)=1\Var(q_ik_i)=1

    Each product has variance E[qi2ki2]−(E[qiki])2=E[qi2] E[ki2]−0=1\E[q_i^2k_i^2]-\big(\E[q_ik_i]\big)^2=\E[q_i^2]\,\E[k_i^2]-0=1:

  3. Var⁡(q⋅k)=∑i=1dkVar⁡(qiki)=dk\Var(\mathbf q\cdot\mathbf k)=\sum_{i=1}^{d_k}\Var(q_ik_i)=d_k

    The dkd_k products involve disjoint pairs of independent coordinates, so they are independent and their variances add:

  4. Var⁡ ⁣(q⋅kdk)=1instead ofsd⁡(q⋅k)=64=8\Var\!\Big(\frac{\mathbf q\cdot\mathbf k}{\sqrt{d_k}}\Big)=1\qquad\text{instead of}\qquad\operatorname{sd}(\mathbf q\cdot\mathbf k)=\sqrt{64}=8

    Dividing by the standard deviation dk\sqrt{d_k} gives scores of variance 11 for every head size. Without it, a head with dk=64d_k=64 starts with scores of standard deviation 88:

Why does the spread matter? Draw 512 random scores and apply the softmax. With standard deviation 11 the largest weight is typically under 3%, so every key contributes and gradients reach all of them. With standard deviation 88 the largest weight is about three-quarters on average: the row is nearly one-hot from the first step. The softmax's Jacobian, diag⁡(a)−aa⊤\diag(\mathbf a)-\mathbf a\mathbf a^\top, vanishes as a\mathbf a approaches a one-hot vector, so almost no gradient would reach WQW_Q and WKW_K. The scaling keeps the initial attention soft regardless of head size.

Masks, and the symmetry they break

Two masks appear in practice, and both act before the softmax, by adding −∞-\infty to forbidden scores. Their weights become exactly 00, and each row still sums to 11 over the allowed positions.

  • The causal mask sets Mtj=−∞M_{tj}=-\infty for j>tj>t, so position tt sees only positions 1,…,t1,\dots,t. One forward pass then yields a prediction at every position, each conditioned only on its own prefix.
  • The padding mask handles batches of sequences of different lengths. Shorter sequences are padded to a common length TT, and every key column that belongs to padding is set to −∞-\infty, so no real token attends to filler. Outputs at padded query positions are simply ignored by the loss.
python
import torch
import torch.nn.functional as F

B, H, T, dk = 2, 4, 5, 16
q, k, v = (torch.randn(B, H, T, dk) for _ in range(3))
lengths = torch.tensor([5, 3])                          # the second sequence ends in 2 padding tokens
real_key = torch.arange(T)[None, :] < lengths[:, None]  # (B, T): True for real tokens
causal = torch.ones(T, T, dtype=torch.bool).tril()      # (T, T): True where j <= t
allowed = causal[None, None] & real_key[:, None, None, :]   # (B, 1, T, T), broadcast over heads
z = F.scaled_dot_product_attention(q, k, v, attn_mask=allowed)  # (B, H, T, dk)
# with no padding, attn_mask=causal or is_causal=True gives the same result

PyTorch's boolean attn_mask marks the pairs that may attend (True) and is broadcast over batch and heads; a float mask is added to the scores instead. The default scale is 1/dk1/\sqrt{d_k}, from the last dimension of the query.

DerivationProof
  1. (PX)WQ((PX)WK)⊤=P QK⊤P⊤(PX)W_Q\big((PX)W_K\big)^\top=P\,QK^\top P^\top

    Permuting the rows of XX permutes the rows of QQ, KK and VV alike, so the score matrix is permuted in its rows and its columns:

  2. softmax⁡ ⁣(P S P⊤)=P softmax⁡(S) P⊤\softmax\!\big(P\,S\,P^\top\big)=P\,\softmax(S)\,P^\top

    A row-wise softmax commutes with both operations: permuting the rows permutes the outputs' rows, and permuting the entries within a row permutes that row's outputs.

  3. P A P⊤ (PV)=P (AV)P\,A\,P^\top\,(PV)=P\,(AV)

    Multiply by the permuted values and use P⊤P=IP^\top P=I:

Check your understanding

Which change makes a self-attention layer's output for a given token depend on where the other tokens stand in the sequence?

  1. Using more heads
  2. Dividing the scores by dk\sqrt{d_k}
  3. Using a larger value dimension dvd_v
  4. A causal mask, or position vectors added to the inputs
Show the answer

D. A causal mask, or position vectors added to the inputs

The proof needs the mask to be invariant under S↦PSP⊤S\mapsto PSP^\top, and M=0M=0 is. A causal mask is not: what token tt sees depends on which tokens precede it. Adding a positional encoding makes the input rows themselves differ by position. Heads, scaling and widths all leave the symmetry intact.

Multi-head attention

One head produces one distribution per query. Multi-head attention runs HH heads in parallel, each in its own subspace of size dk=dv=d/Hd_k=d_v=d/H with its own projections WQ(h),WK(h),WV(h)∈Rd×d/HW_Q^{(h)},W_K^{(h)},W_V^{(h)}\in\R^{d\times d/H}, then concatenates the HH outputs and mixes them with WO∈Rd×dW_O\in\R^{d\times d}:

MHA⁡(X)=[Z(1) ⋯ Z(H)] WO=∑h=1HZ(h) WO(h),Z(h)=softmax⁡ ⁣(XWQ(h)(XWK(h))⊤d/H+M)XWV(h)\operatorname{MHA}(X)=\big[Z^{(1)}\ \cdots\ Z^{(H)}\big]\,W_O=\sum_{h=1}^{H}Z^{(h)}\,W_O^{(h)},\qquad Z^{(h)}=\softmax\!\Big(\frac{XW_Q^{(h)}\big(XW_K^{(h)}\big)^\top}{\sqrt{d/H}}+M\Big)XW_V^{(h)}
WO(h)W_O^{(h)} is the block of d/Hd/H rows of WOW_O that multiplies head hh's output. Read this way, every head computes its own pattern, reads values through its own projection and writes an update of full width dd; the layer's output is the sum of the heads' writes.
DerivationCounting the weights
  1. H⋅d⋅dH=d2for each of WQ, WK, WVH\cdot d\cdot\frac dH=d^2\quad\text{for each of }W_Q,\ W_K,\ W_V

    The HH query projections, each d×d/Hd\times d/H, sit side by side in one d×dd\times d matrix. The same holds for keys and values:

  2. 3d2⏟Q,K,V+d2⏟WO+4d⏟biases=4d2+4d\underbrace{3d^2}_{Q,K,V}+\underbrace{d^2}_{W_O}+\underbrace{4d}_{\text{biases}}=4d^2+4d

    Add the output projection WOW_O and one bias vector of length dd per matrix:

  3. dk=dH=5128=64d_k=\frac dH=\frac{512}{8}=64

    HH does not appear: more heads means more, narrower attention patterns at the same cost in weights. Vaswani et al. (2017) split d=512d=512 into H=8H=8 heads of 6464 dimensions each; heads of 64 to 128 dimensions remain common.

python
import torch.nn as nn
import torch.nn.functional as F

class MultiHeadAttention(nn.Module):
    def __init__(self, d, n_heads):
        super().__init__()
        assert d % n_heads == 0
        self.h, self.dk = n_heads, d // n_heads
        self.qkv = nn.Linear(d, 3 * d)    # W_Q, W_K, W_V side by side: 3d^2 + 3d
        self.out = nn.Linear(d, d)        # W_O: d^2 + d

    def forward(self, x, causal=True):    # x: (B, T, d)
        B, T, d = x.shape
        q, k, v = self.qkv(x).split(d, dim=-1)
        q, k, v = (t.view(B, T, self.h, self.dk).transpose(1, 2) for t in (q, k, v))
        z = F.scaled_dot_product_attention(q, k, v, is_causal=causal)   # (B, h, T, dk)
        z = z.transpose(1, 2).reshape(B, T, d)                          # concatenate the heads
        return self.out(z)

Splitting one d×3dd\times3d projection into heads is exactly the block structure of the derivation: the heads are just a reshaping of the same matrices. Fused kernels behind scaled_dot_product_attention compute all heads at once.

Predict before you look

GPT-2's smallest model has width d=768d=768 and 12 heads. How many parameters, in millions, does one of its attention sublayers have, biases included?

Show the answer

2.36 M

4d2+4d=4×589,824+3,072=2,362,368≈2.364d^2+4d=4\times589{,}824+3{,}072=2{,}362{,}368\approx2.36 million, independent of the 12 heads. Twelve layers of attention hold about 28 million of the model's roughly 124 million parameters; the feed-forward layers hold twice as many.

What a layer costs

DerivationFLOPs of one attention sublayer
  1. 4⋅2Td2=8Td2(Q, K, V and the output WO)4\cdot2Td^2=8Td^2\quad(Q,\ K,\ V\text{ and the output }W_O)

    Count a multiply–add as 2 FLOPs, so multiplying an m×nm\times n matrix by an n×pn\times p one costs 2mnp2mnp. The four projections each multiply T×dT\times d by d×dd\times d:

  2. H⋅(2T2dk+2T2dk)=4T2dH\cdot\big(2T^2d_k+2T^2d_k\big)=4T^2d

    Each head forms Q(h)K(h)⊤Q^{(h)}K^{(h)\top}, a T×dkT\times d_k times dk×Td_k\times T product, and then multiplies the T×TT\times T weights by V(h)V^{(h)}, of size T×dkT\times d_k. Over HH heads, with Hdk=dHd_k=d:

  3. Cattn≈8Td2+4T2d,4T2d=8Td2  ⟺  T=2dC_{\text{attn}}\approx8Td^2+4T^2d,\qquad4T^2d=8Td^2\iff T=2d

    The softmax and scaling add only O(HT2)\order{HT^2} operations. In total, and the length at which the two terms are equal:

  4. Clayer≈24Td2+4T2dC_{\text{layer}}\approx24Td^2+4T^2d

    With the feed-forward network (16Td216Td^2, next lesson) the whole layer costs 24Td2+4T2d24Td^2+4T^2d, and the quadratic term takes over only at T=6dT=6d. A causal mask makes half the scores useless; kernels that skip the masked blocks save nearly half of the 4T2d4T^2d.

Width ddLength TTProjections 8Td28Td^2Scores and mixing 4T2d4T^2d
7681,0244.8×1094.8\times10^93.2×1093.2\times10^9
4,0964,0965.5×10115.5\times10^{11}2.7×10112.7\times10^{11}
4,09632,7684.4×10124.4\times10^{12}1.8×10131.8\times10^{13}
FLOPs for one attention sublayer and one sequence, forward pass only. The ratio of the two columns is T/2dT/2d.
Predict before you look

A layer of width d=1024d=1024 processes T=8192T=8192 tokens. How many times larger is the attention core (4T2d4T^2d) than the projections (8Td28Td^2)?

Show the answer

4 ×

The ratio is 4T2d/8Td2=T/2d=8192/2048=44T^2d/8Td^2=T/2d=8192/2048=4. Long contexts shift the cost from the weights, which do not depend on TT, to the token-to-token interactions.

Memory. A naive implementation stores the T×TT\times T weights of every head for the backward pass. At T=8192T=8192 in 16-bit numbers that is 81922×28192^2\times2 bytes =128=128 MiB per head per layer, which quickly exceeds a GPU's memory at long contexts. Exact kernels such as FlashAttention never store the full matrix: they compute it in tiles in fast on-chip memory and recompute it during the backward pass (Efficient Transformers, and FlashAttention in Depth for the algorithm).

Cross-attention, and the heads models learn

In an encoder–decoder model the decoder also needs to read the input. Cross-attention takes its queries from the decoder states Y∈RTout×dY\in\R^{T_{\text{out}}\times d} and its keys and values from the encoder's output E∈RTin×dE\in\R^{T_{\text{in}}\times d}:

CrossAttn⁡(Y,E)=softmax⁡ ⁣((YWQ)(EWK)⊤dk+Mpad) EWV ∈ RTout×dv\operatorname{CrossAttn}(Y,E)=\softmax\!\Big(\frac{(YW_Q)(EW_K)^\top}{\sqrt{d_k}}+M_{\text{pad}}\Big)\,EW_V\ \in\ \R^{T_{\text{out}}\times d_v}
The score matrix is Tout×TinT_{\text{out}}\times T_{\text{in}} and needs no causal mask, since the whole input is known; only padding in the input is masked. During generation EWKEW_K and EWVEW_V are computed once and reused for every output token. It plays the role of the attention of Bahdanau, Cho and Bengio (2015), with scaled dot products in place of their additive scores.

What trained heads do. Studies of trained models find recurring head types. In BERT-base, Clark et al. (2019) found heads that put most of their weight on the previous or the next token, heads whose attention tracks syntactic relations such as verbs to their direct objects with over 75% accuracy, and a large share of attention parked on the separator token [SEP], which they read as a "no-op" (Attention Sinks & Massive Activations takes that up). In translation models, Voita et al. (2019) identified positional, syntactic and rare-word heads, and pruned 38 of 48 encoder heads at a cost of only 0.15 BLEU. In decoders, an induction head finds an earlier occurrence of the current token and copies the token that followed it, so "… A B … A" predicts "B" (Elhage et al., 2021; Olsson et al., 2022): a mechanism behind in-context learning.

Key takeaways

  • Attention computes softmax⁡(QK⊤/dk+M)V\softmax(QK^\top/\sqrt{d_k}+M)V: each output is a convex combination of values, with weights from query–key dot products; masks add −∞-\infty before the softmax.
  • A dot product of two dkd_k-dimensional vectors with independent unit-variance coordinates has variance dkd_k; dividing by dk\sqrt{d_k} keeps the initial softmax away from saturation for every head size.
  • Without masks or positions, self-attention is permutation-equivariant, SA⁡(PX)=PSA⁡(X)\operatorname{SA}(PX)=P\operatorname{SA}(X); causal masks and positional encodings break the symmetry.
  • Multi-head attention splits width dd into HH heads of size d/Hd/H for 4d2+4d4d^2+4d parameters whatever HH, and a layer costs about 8Td2+4T2d8Td^2+4T^2d FLOPs, so the quadratic part dominates beyond T=2dT=2d.
  • Cross-attention takes queries from the decoder and keys and values from the encoder. Trained models show recurring head types: positional, syntactic, delimiter and induction heads.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Suppose every coordinate of a query and a key is an independent draw with mean 00 and variance 11, and dk=128d_k=128, roughly the situation at initialization. How spread out is the raw dot product q⋅k\mathbf q\cdot\mathbf k, and which factor does scaled dot-product attention apply to it?

  1. About 11.311.3; it multiplies by 1/1281/\sqrt{128}
  2. 128128; it multiplies by 1/1281/128
  3. 11; no scaling is needed
  4. About 11.311.3; it multiplies by 1/1281/128
Show the answer

A. About 11.311.3; it multiplies by 1/1281/\sqrt{128}

The variance is the sum of 128128 unit variances, so the standard deviation is 128≈11.3\sqrt{128}\approx11.3. Multiplying by 1/dk1/\sqrt{d_k} restores unit variance, keeping the softmax away from one-hot rows at the start of training.

Question 2

A batch holds a 10-token sentence padded to T=16T=16. In an encoder (no causal mask), which scores receive −∞-\infty?

  1. The rows of the 6 padding positions, so padding tokens attend to nothing
  2. The columns of the 6 padding keys, so no query attends to padding
  3. The diagonal, so no token attends to itself
  4. Every score above the diagonal
Show the answer

B. The columns of the 6 padding keys, so no query attends to padding

Masking the key columns of the padding removes the filler from every real token's weighted average. The outputs at padding positions are meaningless but harmless: the loss ignores them. A fully masked row would even be dangerous, since a softmax of all −∞-\infty is undefined.

Question 3

For a single attention sublayer of width dd, at what sequence length do the score and mixing FLOPs equal the projection FLOPs?

  1. T=d/2T=d/2
  2. T=dT=\sqrt d
  3. T=2dT=2d
  4. T=6dT=6d
Show the answer

C. T=2dT=2d

4T2d=8Td24T^2d=8Td^2 gives T=2dT=2d. Including the feed-forward network's 16Td216Td^2 moves the crossover for the whole layer to T=6dT=6d.

Question 4

In the cross-attention of an encoder–decoder translator, where do the queries, keys and values come from?

  1. All three from the encoder output
  2. All three from the decoder states, with a causal mask
  3. Queries from the encoder output; keys and values from the decoder states
  4. Queries from the decoder states; keys and values from the encoder output
Show the answer

D. Queries from the decoder states; keys and values from the encoder output

Each output position asks a question (query) of the source sentence (keys) and reads what it finds (values). The score matrix is Tout×TinT_{\text{out}}\times T_{\text{in}}, and the encoder's keys and values are computed once per input.

Go deeper

Further reading

  • A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser & I. Polosukhin, "Attention is all you need," NeurIPS (2017).
  • K. Clark, U. Khandelwal, O. Levy & C. D. Manning, "What does BERT look at? An analysis of BERT's attention," BlackboxNLP (2019).
  • E. Voita, D. Talbot, F. Moiseev, R. Sennrich & I. Titov, "Analyzing multi-head self-attention: Specialized heads do the heavy lifting, the rest can be pruned," ACL (2019).
  • C. Olsson et al., "In-context learning and induction heads," Transformer Circuits Thread (2022).
  • S. J. D. Prince, Understanding Deep Learning, ch. 12 "Transformers" (MIT Press, 2023).