Self-attention in one page
Sunil Tiwari · Oct 12, 2026 · 6 min read
Queries, keys and values, scaled dot-product attention, and why the √d scaling matters — with NumPy code.
Self-attention lets every token in a sequence look at every other token and decide how much each one matters for its own new representation. It is the operation at the heart of every Transformer, from BERT to the largest language models. The whole idea fits in one equation, and this page walks through it piece by piece.
The problem it solves
Take the sentence "the animal didn't cross the street because it was too tired". To understand it, a model has to connect it back to animal, six words earlier. Recurrent networks pass information along one step at a time, so long-range links fade. Self-attention connects every pair of positions directly, in a single step, and lets the model learn which connections are useful.
Queries, keys and values
Each token arrives as an embedding xi, a vector of dmodel numbers. Self-attention projects it three ways with learned matrices:
Each projection plays a different role:
- Query qi: what this token is looking for.
- Key ki: what this token offers to others who are looking.
- Value vi: the information this token hands over if it is chosen.
The split matters. A token can advertise one thing (its key) while passing on something richer (its value). Search engines work the same way: your query is matched against page titles, but what you read is the page.
The whole computation
Stack the token vectors into matrices Q, K and V (one row per token) and the entire layer is:

Read it from the inside out:
- Scores. QK⊤ is an n×n matrix. Entry (i,j) is the dot product qi⋅kj: how well token j's key matches token i's query.
- Scale. Divide every score by dk, where dk is the length of the key vectors. The next section explains why.
- Mask (decoders only). Set scores for future positions to −∞.
- Softmax. Apply softmax to each row, so row i becomes a probability distribution Pi,⋅ over all tokens.
- Mix. Multiply by V. Token i's output is a weighted average of every value vector: zi=∑jPijvj.
One query, worked through
Follow a single token. In "the cat sat", suppose the query for sat produces scaled scores of 0.3, 2.5 and 2.6 against the keys of the, cat and sat. Softmax turns them into weights:

The new representation of sat is 0.05vthe+0.45vcat+0.50vsat. It is mostly about itself and its subject, with almost nothing from the article. Nothing in the code says "verbs should look at their subjects". The model learns WQ and WK so that such patterns produce high scores.
Why divide by √dₖ?
Suppose the components of q and k are independent, with mean 0 and variance 1. Each product qjkj then has variance 1, and the dot product sums dk of them:
With dk=64, raw scores have a standard deviation of 8. Softmax over numbers that far apart is nearly one-hot: one weight close to 1, the rest close to 0. In that regime the gradients of softmax are tiny and learning stalls. Dividing by dk brings the variance back to 1 and keeps the softmax in its responsive range.
Multi-head attention
One attention pattern per layer is limiting. A token may need to track its syntactic head, the entity it refers to and its neighbours, all at once. Multi-head attention runs h attentions in parallel, each with its own projections into a smaller space of size dk=dmodel/h:

Because each head works in dmodel/h dimensions, eight heads cost about the same as one full-width head. The output projection WO mixes what the heads found back into a single vector per token.
Causal masking
A language model that predicts the next token must not peek at it. Decoders add a mask M before the softmax, with Mij=0 when j≤i and Mij=−∞ when j>i:
Since e−∞=0, masked positions get exactly zero weight. Each token attends only to itself and the tokens before it.

Encoders such as BERT skip the mask and let every token see the whole sequence.
Where it sits in a Transformer
Self-attention is one of two sublayers in each Transformer block. Attention moves information between tokens. A feed-forward network then processes each token on its own. Both are wrapped in a residual connection and layer normalisation, so a block can refine its input without having to rebuild it.

The figure shows the pre-norm arrangement used by most modern models. The original 2017 Transformer applied LayerNorm after each residual addition instead.
In NumPy
The whole layer, including the optional causal mask, is a dozen lines:
import numpy as np
def softmax(x, axis=-1):
x = x - x.max(axis=axis, keepdims=True) # numerical stability
e = np.exp(x)
return e / e.sum(axis=axis, keepdims=True)
def self_attention(X, Wq, Wk, Wv, causal=False):
Q, K, V = X @ Wq, X @ Wk, X @ Wv
scores = Q @ K.T / np.sqrt(K.shape[-1]) # (n, n)
if causal:
n = scores.shape[0]
future = np.triu(np.ones((n, n), dtype=bool), k=1)
scores = np.where(future, -np.inf, scores)
weights = softmax(scores) # each row sums to 1
return weights @ V, weightsThe cost
Every token compares itself with every other token, so the score matrix has n2 entries. Time is O(n2d) and memory for the weights is O(n2) per head. Doubling the context length quadruples the work, which is why long contexts are expensive and why techniques such as FlashAttention (exact attention computed in tiles, never storing the full matrix) and sparse or sliding-window attention exist.
Key takeaways
| Idea | In one line |
| Queries, keys, values | Three learned views of each token: what it seeks, offers and gives. |
| Scores | QK⊤ compares every query with every key. |
| Scaling | Dividing by dk keeps softmax out of its flat, low-gradient regions. |
| Softmax | Turns each row of scores into weights that sum to 1. |
| Output | Each token becomes a weighted average of all value vectors. |
| Multi-head | Several smaller attentions in parallel, each free to learn its own pattern. |
| Causal mask | −∞ on future positions so decoders cannot look ahead. |