Understanding Transformers from Scratch — No Magic Allowed
Attention mechanisms, positional encodings, and multi-head attention explained with working NumPy code. No black boxes. Written after the ACM ML Workshop Series Session 4.
Every transformer explanation eventually shows you this formula:
Attention(Q, K, V) = softmax(QKᵀ / √d_k) V
and moves on as though it explained something. This post builds up to that line in NumPy, one piece at a time, until it is obvious rather than memorised.
The problem attention solves
Recurrent networks process a sequence one token at a time, carrying a hidden state forward. Two consequences follow: information from token 1 has to survive a long chain of updates to influence token 500, and nothing can be computed in parallel because each step needs the previous one.
Attention discards the chain. Every token looks at every other token directly, in one operation.
Queries, keys, and values
The naming is borrowed from retrieval, and the analogy holds up:
- A query is what a token is looking for
- A key is what each token advertises about itself
- A value is what a token actually contributes if selected
Each is a learned linear projection of the same input:
import numpy as np
def projections(X, W_q, W_k, W_v):
Q = X @ W_q # (seq_len, d_k)
K = X @ W_k # (seq_len, d_k)
V = X @ W_v # (seq_len, d_v)
return Q, K, V
The model learns three different views of the same tokens. Nothing mystical — just three weight matrices.
Scoring
Similarity between a query and a key is a dot product. Doing it for every pair at once is one matrix multiply:
scores = Q @ K.T # (seq_len, seq_len)
Entry [i][j] is how much token i cares about token j.
Why divide by √d_k
This is the step most explanations skip. Dot products of vectors with d_k
independent components have variance proportional to d_k. As dimension grows,
scores spread further apart, and softmax of widely-spread values saturates —
one entry goes to ~1, the rest to ~0. Gradients through a saturated softmax are
nearly zero, so learning stalls.
Dividing by √d_k normalises the variance back to roughly 1:
scores = (Q @ K.T) / np.sqrt(Q.shape[-1])
It is a numerical stability fix, not a modelling choice.
Softmax and the weighted sum
def softmax(x, axis=-1):
# Subtract the max for numerical stability — exp of a large
# number overflows long before the maths says it should
x = x - np.max(x, axis=axis, keepdims=True)
e = np.exp(x)
return e / np.sum(e, axis=axis, keepdims=True)
def attention(Q, K, V, mask=None):
scores = (Q @ K.T) / np.sqrt(Q.shape[-1])
if mask is not None:
scores = np.where(mask, scores, -np.inf)
weights = softmax(scores)
return weights @ V, weights
That is the whole formula, and every term in it now has a reason.
Masking
For a decoder, token i must not see tokens after it — otherwise the model
learns to cheat by reading the answer. A lower-triangular mask enforces it:
seq_len = 5
causal_mask = np.tril(np.ones((seq_len, seq_len))).astype(bool)
Setting masked scores to -inf before softmax sends their weight to exactly
zero, rather than merely small.
Multi-head attention
One attention operation produces one weighting of the sequence. But a token can relate to others in several ways at once — syntactically, semantically, positionally. Multi-head attention runs several in parallel over slices of the representation, then concatenates:
def multi_head_attention(X, W_q, W_k, W_v, W_o, n_heads):
seq_len, d_model = X.shape
d_head = d_model // n_heads
heads = []
for h in range(n_heads):
s = slice(h * d_head, (h + 1) * d_head)
Q, K, V = X @ W_q[:, s], X @ W_k[:, s], X @ W_v[:, s]
out, _ = attention(Q, K, V)
heads.append(out)
return np.concatenate(heads, axis=-1) @ W_o
Note that total compute is roughly unchanged — the heads split the dimension rather than duplicating it.
Positional encoding
Attention is permutation-invariant. Shuffle the input and the output shuffles identically, because nothing in the formula refers to order. Position has to be added to the representation itself:
def positional_encoding(seq_len, d_model):
pos = np.arange(seq_len)[:, None]
i = np.arange(d_model)[None, :]
angle = pos / np.power(10000, (2 * (i // 2)) / d_model)
pe = np.zeros((seq_len, d_model))
pe[:, 0::2] = np.sin(angle[:, 0::2])
pe[:, 1::2] = np.cos(angle[:, 1::2])
return pe
The sinusoidal choice means relative positions are expressible as a linear function of the encodings, so the model can learn "three tokens back" as a consistent operation regardless of absolute position.
Putting it together
A transformer block is attention, a feed-forward network, and residual connections with layer normalisation around both. The residuals are what make depth trainable — without them, gradients through dozens of layers vanish.
Stack the block, and that is the architecture. There is no additional trick hiding underneath.