Queries, keys, values and attention weights
What it is
Attention is a learned retrieval operation. A query vector is compared with key vectors to produce relevance scores; softmax turns those scores into non-negative weights that sum to one; the output is the weighted combination of value vectors. A query asks what is relevant now, keys say what each candidate offers, and values contain the information to retrieve. The query, key, and value projections are learned, so the model can discover several useful notions of relevance rather than relying on a fixed distance rule.
Why it matters
Unlike a fixed recurrent state, attention can directly connect distant items, and its weights change with the current query. This creates short information paths between related positions, but it also means the cost and behaviour of the model depend on sequence length, masking, and the learned representations rather than on word distance alone.
In the real world: How a translation model decides which source words matter for each word it writes.
Visual example
Interactive attention routingSelect a query token to inspect its weights, strongest connection, and the paths used to retrieve context.
Why this matters
Attention is a content-dependent routing operation. Changing the query changes the whole distribution over the same candidate values.
- 1Choose a queryEach row of the matrix is one token asking what to retrieve.
- 2Read its rowEvery row sums to 100%; darker cells carry more value into the output.
- 3Follow pathsThe paths show that same row as weighted retrieval, not as a fixed connection.
import torch
import torch.nn.functional as F
q = torch.randn(1, 64) # one query
k = torch.randn(6, 64) # six candidates
v = torch.randn(6, 64)
scores = q @ k.T / 64 ** 0.5 # (1, 6) compatibilities
weights = F.softmax(scores, dim=-1)
out = weights @ v # (1, 64) — a weighted average of values
weights.sum() # tensor(1.)Reading attention weights as a complete explanation. They describe one routing operation, not necessarily which input caused the final model decision.
Practise it: Scaled Dot-Product Attention