Attention is the mechanism that lets each word in a sentence look at the other words and decide which ones matter. It is the core of the Transformer, the architecture behind today's language models.
The intuition
Take the sentence "The cat sat on the mat because it was warm." To understand it, the model needs to look back at mat. Attention gives every token a way to ask a question (query), every token a way to advertise what it contains (key), and a payload to pass along if it is chosen (value).
Queries, keys and values
Each token embedding x is multiplied by three learned matrices:
q = x · Wq— what am I looking for?k = x · Wk— what do I offer?v = x · Wv— what do I pass on?
The score between token i and token j is the dot product q_i · k_j. High score, strong attention.
Self-attention in NumPy
import numpy as np
rng = np.random.default_rng(0)
T, d = 5, 8 # 5 tokens, 8-dimensional embeddings
X = rng.normal(size=(T, d))
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
Q, K, V = X @ Wq, X @ Wk, X @ Wv
scores = Q @ K.T / np.sqrt(d) # (T, T): how much each token attends to each other
# causal mask: a token may not look at future tokens
mask = np.triu(np.ones((T, T)), k=1).astype(bool)
scores[mask] = -np.inf
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)
out = weights @ V # (T, d): each token is now a mix of the values it attended to
print(weights.round(2))Three details matter:
- Scaling by √d keeps scores from growing with the dimension, so softmax doesn't saturate.
- The causal mask sets future positions to minus infinity, so their weight becomes zero. That is what makes a model generate left to right.
- Each row of
weightssums to 1: every output is a weighted average of value vectors.
Multi-head attention
Real models run several attention "heads" in parallel, each with its own Wq, Wk, Wv. One head might track grammar, another long-range references. Their outputs are concatenated and projected back to the model dimension.
Why it scales
All the work is matrix multiplication, which GPUs do extremely well, and every token is processed at once during training. The catch: the score matrix is T × T, so cost grows with the square of the context length — which is why long-context models need tricks such as efficient attention kernels and caching.
Takeaways
- Attention = scores from queries and keys, softmax, weighted sum of values.
- Masking makes generation causal.
- Multiple heads let the model attend to different relationships at once.