Attention from Scratch
A recurrent encoder reads a sentence token by token and hands the decoder one vector: its last hidden state. Whatever the sentence length, 5 tokens or 500, everything the decoder will ever know about the input has to fit into those few hundred numbers. In Training Sequence Models you saw the practical symptoms: long inputs are remembered worse than short ones, and the gradient from the last output to the first input passes through every step in between.
Attention removes the bottleneck. Instead of one summary vector, the model keeps a vector for every input position and, at each output step, computes a fresh weighted average of all of them. The weights are computed from the data: a position that is relevant right now gets a large weight, the rest get small ones. Every position is one step away from every other, so there is no long chain for information or gradients to cross. The derivation and the geometry of the dot product are in Dot-Product Attention; this lesson implements it in NumPy, adds the masks that real batches need, splits it into heads, and checks every piece against PyTorch.
Queries, keys and values
Each token's vector is projected three ways. The query says what token is looking for, the key says what token offers, and the value is what token hands over when it is chosen. The match between a query and a key is their dot product; a softmax over all keys turns the matches into weights that sum to 1; the output is the weighted sum of the values.
The lab: one sentence, six queries
The lab below uses the sentence "the cat sat on the mat" with fixed 4-dimensional embeddings and fixed , (no positional information, so both "the" rows are identical). Row of the heatmap is query ; each cell is a weight; the column on the right shows that every row sums to 1.000. It starts on row 3, "sat": its largest weight, 0.621, is on itself, followed by "cat" at 0.198. Drag the temperature : below 1 the row sharpens towards a single key, above 1 it spreads out (the readout gives the row's entropy in bits; 1.57 bits at against a maximum of 2.58 for six keys). Switch the mask to "causal" and the cells above the diagonal become masked: "sat" may now only look at "the", "cat" and itself.
The formula
For a sequence stacked into matrices , and :
The softmax runs along each row (over keys). Dividing by keeps the scores at unit scale when the entries of and are: a dot product of independent unit-variance terms has variance , and without the division the softmax saturates and its gradient vanishes (why). The mask is added before the softmax, so a forbidden key gets and the remaining weights still sum to 1. Two masks cover almost every case:
- Padding mask: sequences in a batch have different lengths and are padded to the same . Pad positions must never be attended, so the mask removes those keys for every query.
- Causal mask: a decoder that predicts token must not see tokens after . The mask removes keys , the upper triangle (Causal Masking).
The example reproduces the lab's numbers exactly from the same matrices.
import numpy as np
tokens = ["the", "cat", "sat", "on", "the", "mat"]
X = np.array([[2, 0, 0, 0.4], [0, 2, 0.6, 0], [0.4, 0.8, 2, 0],
[1.2, 0, 0.4, 1.2], [2, 0, 0, 0.4], [0, 1.8, 0.2, 1]])
W_q = np.array([[1, 0, 0, 0.5], [0, 1.2, 0.4, 0], [0, 0.8, 1, 0], [0.5, 0, 0, 1]])
W_k = np.array([[0.8, 0, 0.2, 0], [0, 1, 0, 0.6], [0.2, 0.6, 0.9, 0], [0, 0, 0.4, 1]])
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
Q, K = X @ W_q, X @ W_k
d = Q.shape[-1]
S = Q @ K.T / np.sqrt(d)
A = softmax(S)
print("scores of 'sat':", np.round(S[2], 2).tolist())
print("weights of 'sat':", np.round(A[2], 3).tolist())
print("row sums:", np.round(A.sum(axis=1), 3).tolist())
print("most attended key per query:", [tokens[j] for j in A.argmax(axis=1)])
print("rows of the two 'the' tokens equal:", np.allclose(A[0], A[4]))
causal = np.triu(np.ones((6, 6), dtype=bool), k=1) # True above the diagonal = future
A_c = softmax(np.where(causal, -np.inf, S))
print("causal weights of 'sat':", np.round(A_c[2], 3).tolist())
print("row 1 under the causal mask:", np.round(A_c[0], 3).tolist())
for T in (0.5, 1.0, 2.0):
a = softmax(S[2] / T)
H = -(a * np.log2(a)).sum()
print(f"T = {T}: max weight {a.max():.3f}, entropy {H:.2f} bits")scores of 'sat': [1.01, 3.79, 4.93, 1.89, 1.01, 3.35]
weights of 'sat': [0.012, 0.198, 0.621, 0.03, 0.012, 0.127]
row sums: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
most attended key per query: ['the', 'sat', 'sat', 'mat', 'the', 'cat']
rows of the two 'the' tokens equal: True
causal weights of 'sat': [0.015, 0.238, 0.747, 0.0, 0.0, 0.0]
row 1 under the causal mask: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
T = 0.5: max weight 0.872, entropy 0.68 bits
T = 1.0: max weight 0.621, entropy 1.57 bits
T = 2.0: max weight 0.397, entropy 2.23 bits
Three things to notice. The softmax is the stable version (subtract the row maximum), which also handles correctly as long as one key in the row survives. Under the causal mask, the weight that "sat" gave to "on" and "mat" (0.03 and 0.127) is redistributed over the three allowed keys, so its own weight rises from 0.621 to 0.747, and the first token can only attend to itself (weight 1.0). And the two "the" rows are identical: attention by itself does not know where a token is. That is why transformers add positional encodings.
Batches with padding and a causal mask
A real implementation works on a batch (B, T, d) and accepts a boolean mask that broadcasts against the (B, T, T) scores. Below, the second sequence has only 3 real tokens and 2 padding positions. The padding mask has shape (B, 1, T) (one row, shared by every query), the causal mask (T, T); combined with & they broadcast to (B, T, T). The test at the end is the one that matters: overwrite the padding with garbage, and the outputs at the real positions must not change.
import numpy as np
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def attention(Q, K, V, mask=None):
"""Q: (..., Tq, d), K and V: (..., Tk, d). mask: True where a key may be attended."""
S = Q @ np.swapaxes(K, -1, -2) / np.sqrt(Q.shape[-1])
if mask is not None:
S = np.where(mask, S, -np.inf)
A = softmax(S)
return A @ V, A
rng = np.random.default_rng(0)
B, T, d = 2, 5, 8
x = rng.normal(size=(B, T, d))
lengths = np.array([5, 3]) # the second sequence has 2 padding positions
key_ok = np.arange(T)[None, :] < lengths[:, None] # (B, T)
pad_mask = key_ok[:, None, :] # (B, 1, T): same for every query
causal = np.tril(np.ones((T, T), dtype=bool)) # (T, T): key j <= query i
out, A = attention(x, x, x, pad_mask & causal)
print("mask shape:", (pad_mask & causal).shape)
print("weights, sequence 2, query 3:", np.round(A[1, 2], 3).tolist())
print("weight on padding keys (seq 2):", float(A[1, :, 3:].sum()))
print("output shape:", out.shape)
# Change the padded positions: the real positions' outputs do not move.
x2 = x.copy()
x2[1, 3:] = 99.0
out2, _ = attention(x2, x2, x2, pad_mask & causal)
print("real outputs unchanged:", np.allclose(out[1, :3], out2[1, :3]))mask shape: (2, 5, 5)
weights, sequence 2, query 3: [0.071, 0.044, 0.885, 0.0, 0.0]
weight on padding keys (seq 2): 0.0
output shape: (2, 5, 8)
real outputs unchanged: True
Here to keep the code short; in a layer they come from three projections. The padded query rows (positions 4 and 5 of sequence 2) still produce outputs, which are meaningless; the loss must ignore them (the ignore_index / loss-mask trick from sequence training).
Multi-head attention is a reshape
One attention pattern per layer is limiting: a token may need to look at its subject and at the previous token at the same time. Multi-head attention runs attentions in parallel, each on its own slice of the projected vectors, and concatenates the results before a final output projection :
In code there are no separate matrices. You project once with full matrices, then reshape (B, T, E) to (B, T, h, d_h) and move the head axis forward to (B, h, T, d_h). The attention function, which only looks at the last two axes, then treats the heads as one more batch axis. The math of why the cost stays the same as one big head is in Multi-Head Attention; the check here is that the reshape gives exactly the same result as an explicit loop over column slices.
import numpy as np
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def attention(Q, K, V, mask=None):
S = Q @ np.swapaxes(K, -1, -2) / np.sqrt(Q.shape[-1])
if mask is not None:
S = np.where(mask, S, -np.inf)
A = softmax(S)
return A @ V, A
def split_heads(x, h): # (B, T, E) -> (B, h, T, E/h)
B, T, E = x.shape
return x.reshape(B, T, h, E // h).transpose(0, 2, 1, 3)
def merge_heads(x): # (B, h, T, dh) -> (B, T, h*dh)
B, h, T, dh = x.shape
return x.transpose(0, 2, 1, 3).reshape(B, T, h * dh)
def mha(x, Wq, Wk, Wv, Wo, h, mask=None):
Q, K, V = (split_heads(x @ W, h) for W in (Wq, Wk, Wv))
out, A = attention(Q, K, V, mask) # every head at once, shapes (B, h, T, T)
return merge_heads(out) @ Wo, A
rng = np.random.default_rng(0)
B, T, E, h = 2, 4, 8, 2
x = rng.normal(size=(B, T, E))
Wq, Wk, Wv, Wo = (rng.normal(0, E ** -0.5, (E, E)) for _ in range(4))
y, A = mha(x, Wq, Wk, Wv, Wo, h)
print("output", y.shape, "weights", A.shape)
# The same thing with an explicit loop over heads: each head owns a slice of columns.
dh = E // h
heads = []
for i in range(h):
cols = slice(i * dh, (i + 1) * dh)
o, _ = attention(x @ Wq[:, cols], x @ Wk[:, cols], x @ Wv[:, cols])
heads.append(o)
y_loop = np.concatenate(heads, axis=-1) @ Wo
print("reshape version == loop version:", np.allclose(y, y_loop))
print("y[0, 0]:", np.round(y[0, 0], 3).tolist())
print("parameters:", 4 * E * E)output (2, 4, 8) weights (2, 2, 4, 4)
reshape version == loop version: True
y[0, 0]: [0.099, 0.197, 0.12, 0.521, 0.403, 0.15, 0.412, -1.028]
parameters: 256
The weights come back with shape (B, h, T, T): one attention map per head. The layer has weights for , independent of and of the sequence length; the cost that grows with length is the score matrix.
The same in PyTorch
PyTorch offers the kernel as torch.nn.functional.scaled_dot_product_attention (which picks a fused, memory-efficient implementation when it can) and the full layer as nn.MultiheadAttention. The recorded example (run on a CPU, float64 so the comparison is tight) feeds both the same inputs as the NumPy code. To compare the layer, our four weight matrices are copied into it, which requires knowing its parameter layout:
in_proj_weighthas shape(3E, E): the query, key and value projections stacked by rows, in that order.nn.Linear-style layers computex @ W.T, so ourx @ Wqmatrix goes in transposed.out_projis an ordinarynn.Linear(E, E), again transposed. Both projections have biases by default; we zero them.
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def attention(Q, K, V, mask=None):
S = Q @ np.swapaxes(K, -1, -2) / np.sqrt(Q.shape[-1])
if mask is not None:
S = np.where(mask, S, -np.inf)
A = softmax(S)
return A @ V, A
rng = np.random.default_rng(0)
B, T, E, h = 2, 5, 8, 2
x = rng.normal(size=(B, T, E))
key_ok = np.arange(T)[None, :] < np.array([5, 3])[:, None] # (B, T), True = real token
causal = np.tril(np.ones((T, T), dtype=bool))
# 1. The functional kernel. A boolean attn_mask means True = may attend (same as ours).
xt = torch.tensor(x, dtype=torch.float64)
ours, _ = attention(x, x, x, key_ok[:, None, :] & causal)
theirs = F.scaled_dot_product_attention(xt, xt, xt, attn_mask=torch.tensor(key_ok[:, None, :] & causal))
print("SDPA with mask matches:", np.allclose(ours, theirs.numpy(), atol=1e-12))
ours_c, _ = attention(x, x, x, causal)
theirs_c = F.scaled_dot_product_attention(xt, xt, xt, is_causal=True)
print("SDPA is_causal matches:", np.allclose(ours_c, theirs_c.numpy(), atol=1e-12))
# 2. nn.MultiheadAttention with our weights copied in.
Wq, Wk, Wv, Wo = (rng.normal(0, E ** -0.5, (E, E)) for _ in range(4))
mha = nn.MultiheadAttention(E, h, batch_first=True, dtype=torch.float64)
print("in_proj_weight:", tuple(mha.in_proj_weight.shape), "out_proj.weight:", tuple(mha.out_proj.weight.shape))
with torch.no_grad():
mha.in_proj_weight.copy_(torch.tensor(np.concatenate([Wq.T, Wk.T, Wv.T]))) # rows: q, k, v
mha.in_proj_bias.zero_()
mha.out_proj.weight.copy_(torch.tensor(Wo.T)) # Linear computes x @ W.T
mha.out_proj.bias.zero_()
def split(z):
return z.reshape(B, T, h, E // h).transpose(0, 2, 1, 3)
o, A_heads = attention(split(x @ Wq), split(x @ Wk), split(x @ Wv), key_ok[:, None, None, :])
y_np = o.transpose(0, 2, 1, 3).reshape(B, T, E) @ Wo
# key_padding_mask uses the OPPOSITE convention: True = ignore this key.
y_t, A_avg = mha(xt, xt, xt, key_padding_mask=torch.tensor(~key_ok))
print("MHA output matches:", np.allclose(y_np, y_t.detach().numpy(), atol=1e-12))
print("returned weights:", tuple(A_avg.shape), "= mean over heads:", np.allclose(A_heads.mean(axis=1), A_avg.detach().numpy()))
_, A_all = mha(xt, xt, xt, key_padding_mask=torch.tensor(~key_ok), average_attn_weights=False)
print("average_attn_weights=False:", tuple(A_all.shape))
print("parameters:", sum(p.numel() for p in mha.parameters()))SDPA with mask matches: True
SDPA is_causal matches: True
in_proj_weight: (24, 8) out_proj.weight: (8, 8)
MHA output matches: True
returned weights: (2, 5, 5) = mean over heads: True
average_attn_weights=False: (2, 2, 5, 5)
parameters: 288
Everything matches to . The details worth remembering:
- Two mask conventions. In
scaled_dot_product_attentiona booleanattn_maskis True where attention is allowed. Innn.MultiheadAttention,key_padding_mask(and a booleanattn_mask) is True where it is forbidden. Passing the wrong one does not raise an error; it silently attends only to the padding. A float mask is added to the scores in both, so0and-infmean the same everywhere. - The returned weights are averaged over heads by default: shape
(B, T, T), not(B, h, T, T). Passaverage_attn_weights=Falsefor one map per head, orneed_weights=Falsewhen you don't need them at all (that also lets PyTorch use the fused kernel). - Parameters: 288 = , the 256 weights plus four bias vectors of 8.
batch_first=Truemakes the layer take(B, T, E); the default is(T, B, E), a frequent source of wrong-but-running code.
Pitfalls
- A row with every key masked. The softmax of a row of is = NaN, which then spreads through every later layer. It happens with left padding plus a causal mask, or with an empty sequence. Make sure each query can see at least one key (its own position usually), or replace NaN rows with zeros after the softmax.
- Masking after the softmax. Multiplying the weights by a 0/1 mask leaves rows that no longer sum to 1. Mask the scores, before the softmax.
- Forgetting the . Training still runs, but with large head dimensions the softmax saturates early and learning is slow.
- Mixing up the axes when splitting heads.
x.reshape(B, h, T, dh)without the transpose is the classic bug: it runs, the shapes look right, and each "head" mixes positions. The loop-vs-reshape check above catches it. - Memory. The score matrix is per head and per batch item. At , and float32 that is 1 GiB per sequence for one layer's scores, which is why fused kernels (FlashAttention-style, used by
scaled_dot_product_attention) never store it.
Practice
- In the lab, set the causal mask and query 6, "mat". Which keys can it attend to, and what is the maximum possible entropy of its row?
Answer
All six (it is the last token, so nothing is in its future): the causal mask changes nothing for the last row. The maximum entropy for six keys is bits.
- Without running it: if every score in a row increases by the same constant , how do the weights change? What if the mask's is replaced by ?
Answer
Not at all: softmax is invariant to adding a constant to the whole row. With the forbidden weights are in floating point, so the result is the same, and a fully masked row no longer gives NaN (it gives a uniform average over all keys, including the forbidden ones, which is still wrong but finite). Be careful in float16, where overflows to ; libraries use the dtype's most negative finite number.
- Change
split_headsin the multi-head example tox.reshape(B, h, T, E // h)(no transpose) and rerun. What does the loop-vs-reshape check print, and why?
Answer
False. Reshaping (B, T, E) straight to (B, h, T, d_h) reinterprets memory: the first "head" takes the first numbers, which are the first two tokens' full vectors, so each head mixes several positions' features instead of taking one slice of every position.
- In the PyTorch example, pass
key_padding_mask=torch.tensor(key_ok)(the un-negated mask). What happens to sequence 2?
Answer
Its 3 real keys are now forbidden and the 2 padding keys allowed, so every query of sequence 2 attends only to padding. Sequence 1 has no padding, so every key is forbidden and its rows are NaN. No error is raised: always check a mask convention with a test like "changing the padding must not change the outputs".
Test yourself
What problem of a recurrent encoder-decoder does attention remove?
- The need for a loss function
- Squeezing the whole input into one fixed-size vector, with long paths between distant positions
- The need for embeddings
- The softmax at the output
Where is the causal mask applied?
- To the weights after the softmax, by multiplying with a 0/1 matrix
- To the scores before the softmax, setting keys to
- To the values
- To the output projection
In the lab's sentence, why are the rows of the two 'the' tokens identical?
- Because of the causal mask
- Because the temperature is 1
- Because they have the same embedding and attention has no notion of position
- Because the softmax is rounded
nn.MultiheadAttention(8, 2) returns attention weights of shape (B, T, T). What are they?
- The weights of head 1
- The mean of the heads' weights
- The scores before the softmax
- The weights of the last head
For nn.MultiheadAttention, key_padding_mask is a boolean tensor in which True means…
- this key may be attended
- this key must be ignored
- this query is padding
- this head is disabled