"Attention is all you need" is probably the most quoted paper title in machine learning. But when you open a transformer codebase, the attention layer can look scary: reshapes, transposes, masks, and an odd square root in the middle.
Under all that, the core is a short function: two matrix multiplications and a softmax. In this post we'll write scaled dot-product attention in plain NumPy, check that every piece behaves as expected, and then extend it to causal masking and multiple heads. No frameworks, no magic.
The intuition first
Think about reading the sentence *"The animal didn't cross the street because it was too tired."* To understand "it", you look back at the other words and decide which ones are relevant. Here that's "animal", not "street".
Attention gives every token a way to do that:
- Each token produces a query (Q): "what am I looking for?"
- Each token produces a key (K): "what do I contain?"
- Each token produces a value (V): "what will I pass on if you pick me?"
A token compares its query with every key. Higher similarity means more attention. Its new representation is a weighted average of the values, using those attention weights.
The formula
Attention(Q, K, V) = softmax(Q·Kᵀ / √dₖ) · V
Read it left to right:
Q·Kᵀgives a score for every (query, key) pair./ √dₖscales the scores (more on why in a moment).softmaxturns each row of scores into weights that add up to 1.· Vmixes the values using those weights.
Writing it in NumPy
We need a numerically stable softmax first. (If "stable" isn't familiar, our log-sum-exp post explains it.)
import numpy as np
def softmax(z, axis=-1):
shifted = z - z.max(axis=axis, keepdims=True)
e = np.exp(shifted)
return e / e.sum(axis=axis, keepdims=True)
def scaled_dot_product_attention(Q, K, V, mask=None):
d_k = Q.shape[-1]
scores = Q @ K.swapaxes(-2, -1) / np.sqrt(d_k)
if mask is not None:
scores = np.where(mask, scores, -1e9)
weights = softmax(scores, axis=-1)
return weights @ V, weightsThat's the whole mechanism. Using swapaxes(-2, -1) instead of .T means the same function works for a single sequence (seq, d) and for batched or multi-head tensors (heads, seq, d). We'll need that shortly.
Now let's create some token embeddings and project them into Q, K and V with weight matrices, the way a real layer does:
rng = np.random.default_rng(42)
seq_len, d_model = 4, 8
X = rng.normal(size=(seq_len, d_model)) # 4 tokens, 8 features each
W_q, W_k, W_v = (rng.normal(size=(d_model, d_model)) / np.sqrt(d_model) for _ in range(3))
Q, K, V = X @ W_q, X @ W_k, X @ W_v
out, weights = scaled_dot_product_attention(Q, K, V)
print(out.shape, weights.shape) # (4, 8) (4, 4)
print(np.allclose(weights.sum(axis=-1), 1.0)) # TrueThe output has the same shape as the input, one new vector per token. The weight matrix is (4, 4): row i says how much token i attends to each token j, and every row adds up to 1.
Why divide by √dₖ?
This is a favourite interview question, so let's measure it instead of memorising it.
If the entries of q and k are independent with variance 1, their dot product is a sum of dₖ terms, so its variance grows to about dₖ:
q = rng.normal(size=(1000, 512))
k = rng.normal(size=(1000, 512))
raw = (q * k).sum(axis=-1)
print(round(raw.var(), 1)) # ~501
print(round((raw / np.sqrt(512)).var(), 2)) # ~0.98With dₖ = 512, raw scores have a standard deviation of about 22. Softmax on numbers that spread out becomes almost one-hot: one weight near 1, the rest near 0. In that region softmax's gradients are tiny, so the model struggles to learn. Dividing by √dₖ brings the variance back to about 1 and keeps softmax in a range where gradients flow.
Causal masking: no peeking at the future
A language model generating text must not attend to tokens that come after the current position, or it would be cheating during training. We enforce that with a lower-triangular mask:
causal = np.tril(np.ones((seq_len, seq_len), dtype=bool))
out, weights = scaled_dot_product_attention(Q, K, V, mask=causal)
print(np.round(weights, 2))[[1. 0. 0. 0. ]
[0.62 0.38 0. 0. ]
[0.24 0.39 0.38 0. ]
[0.34 0.18 0.31 0.17]]Exactly what we want. The first token can only see itself, so its weight is 1. The second splits its attention between tokens 1 and 2. Everything above the diagonal is zero.
Why -1e9 instead of -np.inf? Both give zero weight after softmax. But if a row were entirely masked, -inf would produce nan (from -inf - (-inf)), while a large finite number fails more gently. Production code handles fully masked rows explicitly. For learning, a large negative constant is the safe choice.
Multi-head attention
One attention pattern can only capture one kind of relationship at a time. Multi-head attention runs several smaller attentions in parallel, so one head can track syntax, another coreference, another position, and so on. Then it combines the results.
The trick is all in reshaping. We split d_model into num_heads chunks of size d_head:
def multi_head_attention(X, W_q, W_k, W_v, W_o, num_heads, mask=None):
seq_len, d_model = X.shape
d_head = d_model // num_heads
def split(t):
# (seq, d_model) -> (heads, seq, d_head)
return t.reshape(seq_len, num_heads, d_head).transpose(1, 0, 2)
Q, K, V = split(X @ W_q), split(X @ W_k), split(X @ W_v)
out, _ = scaled_dot_product_attention(Q, K, V, mask) # runs per head
# (heads, seq, d_head) -> (seq, d_model)
out = out.transpose(1, 0, 2).reshape(seq_len, d_model)
return out @ W_o
W_o = rng.normal(size=(d_model, d_model)) / np.sqrt(d_model)
print(multi_head_attention(X, W_q, W_k, W_v, W_o, num_heads=2, mask=causal).shape)
# (4, 8)Because our attention function uses swapaxes(-2, -1) and axis=-1, it works on the extra heads dimension without any changes. The (seq, seq) causal mask broadcasts across all heads automatically.
Watch the transpose. A very common bug is reshaping
(seq, d_model)straight to(heads, seq, d_head). The shapes line up, so nothing crashes, but you've mixed features from different tokens into the same head. Always reshape to(seq, heads, d_head)first, then transpose.
What this costs
The score matrix is seq_len × seq_len. Double the context length and you quadruple the attention memory and compute. That one fact explains a lot of modern LLM engineering: FlashAttention (compute attention in tiles without storing the full matrix), KV caching (reuse past keys and values during generation), and the steady push for longer, cheaper context windows.
Key takeaways
- Attention is
softmax(QKᵀ / √dₖ) · V: score, scale, normalise, mix. - The
√dₖkeeps score variance near 1, so softmax doesn't saturate and gradients survive. - Causal masking is a lower-triangular boolean mask applied before softmax.
- Multi-head attention is the same function on reshaped tensors. Reshape, then transpose.
- Cost grows with the square of sequence length, which drives most attention optimisations.
Ready to test yourself? Try the Causal Attention Mask and Stable Masked Softmax problems in our problem set. They cover the two pieces people most often get subtly wrong.
Frequently asked questions
What are queries, keys and values in attention?
Each token is projected into three vectors. The query describes what the token is looking for, the key describes what it contains, and the value is the information it passes on. Attention weights come from query-key similarity and are used to average the values.
Why is attention scaled by the square root of d_k?
The dot product of two random vectors has a variance that grows with their dimension. Dividing by the square root of d_k keeps the variance near one, so softmax does not saturate and gradients stay useful.
What is the difference between self-attention and multi-head attention?
Self-attention computes one set of attention weights over a sequence. Multi-head attention runs several smaller attention operations in parallel on different learned projections and concatenates the results, letting the model capture several kinds of relationships at once.