Multi-head attention: separate readings, one output
多头注意力
Implement all projections and gradients; test head symmetry, masking and a restricted averaging baseline.
multihead-attentionRead two places before mixing what you found
Suppose a query needs one attribute from the first object and another from the second. A single average can blur the distinction. Multi-head attention gives several learned projections their own attention distributions, keeps their outputs separate through concatenation, and then mixes them with an output projection.
This is the mechanism described in the selected Transformer paper and illustrated by The Annotated Transformer. A head is not automatically a linguistic role or a human-readable rule. Start with self-attention, matrix multiplication and backpropagation.
Each head has its own projection and denominator
For one input sequence X with n rows and model width d, head h projects queries, keys and values. A row-wise Softmax produces its attention matrix:
M is zero on allowed connections and negative infinity on blocked ones. Every query must have at least one allowed key. The denominator is separate for each head and query. The output is:
With H heads and dₖ=dᵥ=d/H, concatenation has width d. The original v5 description explicitly includes Wᴼ; the earlier v1 displayed formula inspected for this article omitted that factor. We use v5 and the selected implementation, not a mixture of version-specific formulas.
Let G be the derivative of a scalar loss with respect to Y. The output-projection derivative and the derivative returned to the concatenated heads are:
Split GC into head blocks Gh. Backpropagate through each weighted sum:
For each row, the Softmax Jacobian gives the score derivative without forming a full Jacobian matrix:
The row sum is broadcast across columns. Blocked probabilities and their score derivatives are zero. The dot-product step and input projections then give:
The implementation sums these products over the batch. Its loss is half the mean squared output error over all batch, token and channel entries, so G is the error divided by that entry count. It omits biases and dropout explicitly.
For batch size B at fixed total width d, dense projection work and attention work have different scaling:
The leading attention arithmetic need not multiply by H when head width shrinks accordingly. Materializing every attention matrix still costs memory proportional to H. Implementations that avoid materializing it need a separate memory analysis.
Train all four projections on an explicit teacher
Save as multihead_attention.py; use Python 3.12 and NumPy 1.26.4. Two tokens each carry two position-indicator channels and two numeric attributes. All sixteen combinations of four ±1 attributes form the training set. A fixed two-head teacher attends mainly to opposite tokens. The student trains all 64 entries of WQ, WK, WV and Wᴼ using explicit gradients, 1,600 updates and step size .5.
"""Original two-head self-attention with full explicit parameter gradients."""
import itertools
import json
import numpy as np
def data():
values = np.array(list(itertools.product([-1., 1.], repeat=4)))
x = np.zeros((16, 2, 4)); x[:, 0, 0] = 1; x[:, 1, 1] = 1
x[:, :, 2:] = values.reshape(16, 2, 2)
return x
def heads(x):
b, n, _ = x.shape
return x.reshape(b, n, 2, 2).transpose(0, 2, 1, 3)
def merge(x):
b, _, n, _ = x.shape
return x.transpose(0, 2, 1, 3).reshape(b, n, 4)
def forward(theta, x, mask=None):
theta, x = np.asarray(theta, dtype=float), np.asarray(x, dtype=float)
if theta.shape != (64,) or not np.isfinite(theta).all() or x.ndim != 3 or x.shape[-1] != 4 or not 1 <= x.shape[0] <= 128 or not 1 <= x.shape[1] <= 32 or not np.isfinite(x).all():
raise ValueError('Expected 64 parameters and finite BxNx4 inputs')
n = x.shape[1]
if mask is None: mask = np.ones((n, n), dtype=bool)
mask = np.asarray(mask)
if mask.dtype != np.bool_ or mask.shape != (n, n) or not mask.any(axis=1).all():
raise ValueError('Boolean NxN mask needs at least one valid key in every row')
wq, wk, wv, wo = theta.reshape(4, 4, 4)
q, k, v = [heads(x @ w) for w in [wq, wk, wv]]
logits = q @ k.swapaxes(-2, -1)/np.sqrt(2)
logits = np.where(mask, logits, -np.inf); logits -= logits.max(axis=-1, keepdims=True)
p = np.exp(logits); p /= p.sum(axis=-1, keepdims=True)
c = merge(p @ v)
return c @ wo, (x, q, k, v, p, c, wo)
def objective(theta, x, target, mask=None):
y, cache = forward(theta, x, mask); target = np.asarray(target, dtype=float)
if target.shape != y.shape or not np.isfinite(target).all(): raise ValueError('Invalid targets')
x, q, k, v, p, c, wo = cache; error = y-target; g = error/error.size
grad_o = np.einsum('bni,bnj->ij', c, g)
dz = heads(g @ wo.T); dv = p.swapaxes(-2, -1) @ dz
dp = dz @ v.swapaxes(-2, -1); ds = p*(dp-(p*dp).sum(axis=-1, keepdims=True))
dq = ds @ k/np.sqrt(2); dk = ds.swapaxes(-2, -1) @ q/np.sqrt(2)
grads = [np.einsum('bni,bnj->ij', x, merge(d)) for d in [dq, dk, dv]]
return float(.5*np.mean(error**2)), np.stack(grads+[grad_o]).ravel()
def teacher():
w = np.zeros((4, 4, 4))
w[0, :2, 0] = 1; w[0, :2, 2] = 1
w[1, :2, 0] = [4, -4]; w[1, :2, 2] = [-4, 4]
w[2, 2, [0, 2]] = 1; w[2, 3, [1, 3]] = 1
w[3] = np.eye(4)
return w.ravel()
def permute_heads(theta):
w = np.asarray(theta, dtype=float).reshape(4, 4, 4).copy(); order = [2, 3, 0, 1]
w[:3] = w[:3][:, :, order]
w[3] = w[3, order, :]
return w.ravel()
def train(updates=1600):
if type(updates) is not int or not 0 <= updates <= 3000: raise ValueError('Invalid updates')
x = data(); target = forward(teacher(), x)[0]
theta = np.random.default_rng(9).normal(0, .4, 64); history = []
for step in range(updates+1):
loss, grad = objective(theta, x, target)
if step % 200 == 0 or step == updates: history.append(loss)
if step < updates: theta -= .5*grad
return theta, history
def demo():
x = data(); target, cache = forward(teacher(), x); theta, history = train()
average = x[:, :, 2:].mean(axis=1); design = np.c_[np.ones(16), average]
baseline = design @ np.linalg.lstsq(design, target[:, 0], rcond=None)[0]
rng = np.random.default_rng(101); held = x.copy(); held[:, :, 2:] = rng.uniform(-1, 1, (16, 2, 2))
y = forward(theta, held)[0]; truth = forward(teacher(), held)[0]
return dict(parameter_count=64, training_half_mse=history,
heldout_mse=float(np.mean((y-truth)**2)), teacher_weights=cache[4][0].tolist(),
mean_pool_readout_mse=float(np.mean((baseline-target[:, 0])**2)),
head_permutation_error=float(abs(forward(theta, x)[0]-forward(permute_heads(theta), x)[0]).max()),
causal_weights=forward(theta, x, np.tril(np.ones((2, 2), dtype=bool)))[1][4][0].tolist(),
scope='Two heads, width4,64 trained weights on synthetic teacher outputs; no full Transformer or universal single-head impossibility result.')
if __name__ == '__main__': print(json.dumps(demo(), indent=2))
The teacher’s preferred-token weight is about .996519 in each head. Student half-MSE falls from .433894 to about .000010169; a separate seed with continuous attributes in [−1,1] gives MSE about .000006479. These are synthetic teacher-reproduction results, not language understanding or recovery of unique internal weights.
A restricted baseline averages the two attribute vectors and fits the best linear readout to the teacher’s first-token output. Its MSE is about .493062. Averaging has discarded a difference that the two teacher heads preserve. This particular baseline does not prove that every conceivable single-head architecture fails.
Swapping the two heads, including query/key/value column blocks and the corresponding Wᴼ row blocks, preserves output to floating-point error. The function does not assign permanent meanings to “head one” and “head two.” The independent tests also check all 64 parameter derivatives, causal isolation and token-permutation equivariance when no separate positional operation is added.
Do not confuse a mask with an explanation
The annotated implementation shows the reshape/transpose/concatenate sequence and a finite negative mask constant. Our version uses negative infinity and rejects an all-masked query row instead of returning a meaningless distribution. The Boolean convention is explicit: true means allowed. A loss mask and an attention mask have different purposes.
Large attention weight does not by itself quantify causal importance: value projections and Wᴼ also affect the output. Heads may be redundant, and optimization does not require interpretable specialization. Real Transformer layers add residual paths, normalization and feed-forward blocks; the small program implements only the attention sublayer.
Follow a head all the way to the output
- Dimensions. At d=512 and H=8 with equal head widths, what are dₖ, dᵥ and Wᴼ’s shape? Answer: Both head widths are 64. Concatenation has width 512 and Wᴼ has shape 512×512.
- Differentiate. Why must the score gradient subtract a probability-weighted row sum? Answer: Softmax probabilities share a denominator. Increasing one score changes all probabilities in that row; the subtraction accounts for this coupling.
- Implement. What must change when heads are permuted? Answer: Permute each query/key/value projection’s head column blocks and the matching output-projection row blocks. Changing only the concatenation order generally changes Y.
- Audit. Does the average-readout baseline establish universal superiority over one head? Answer: No. It isolates information lost by a fixed averaging bottleneck on this teacher task. It is not a theorem about all one-head networks, training procedures or tasks.
Compare the mathematical operation and the implementation
The v5 paper defines projected parallel attention and the output map. The Annotated Transformer makes the tensor layout inspectable. Our original NumPy implementation adds independent gradient and symmetry checks; it does not reproduce translation training. The separate causal-masking topic will examine information flow rather than head multiplicity.
Make a prediction, then check
What preserves output when two attention heads are swapped?
Learning objectives
- Derive the four projection gradients.
- Check causal isolation and head permutations.
- Compare compute and attention storage at fixed width.
Prerequisites & connections
Explore related knowledge →References
- Attention Is All You Need (v5)
Ashish Vaswani; Noam Shazeer; Niki Parmar; Jakob Uszkoreit; Llion Jones; Aidan N. Gomez; Łukasz Kaiser; Illia Polosukhin · 2017 - harvardnlp/annotated-transformer: the_annotated_transformer.py @debc9fd
harvardnlp/annotated-transformer contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked Attention v5 sections3.2.1-3.2.3, compared v1 formula and read fixed Annotated Transformer attention/head layout. Seven paired equations and four explained exercises; original64-weight two-head training, all parameter finite differences, causal masking, head/token symmetry, teacher probabilities and restricted mean-readout baseline. Synthetic teacher targets, not translation training or universal single-head inferiority.
- Single AI author checked Attention v5 sections3.2.1-3.2.3, compared v1 formula and read fixed Annotated Transformer attention/head layout. Seven paired equations and four explained exercises; original64-weight two-head training, all parameter finite differences, causal masking, head/token symmetry, teacher probabilities and restricted mean-readout baseline. Synthetic teacher targets, not translation training or universal single-head inferiority.
- Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial label polish and English mobile-title clipping correction preserved. Full article acceptance recorded separately.
Source locations checked:
- Attention Is All You Need (v5) · Read sections3.2.1-3.2.3; PDF4/5 viewed. v5 explicitly includes output projection unlike the inspected v1 formula. No translation benchmark reproduction.
- harvardnlp/annotated-transformer: the_annotated_transformer.py @debc9fd · Read519-530,589-630: projected heads, mask, concatenation and output projection. MIT license fully read; original local implementation, no upstream execution.
Related topics