Queries keys and values
Quick answer
Attention retrieves information by comparing a query with keys and mixing the associated values. Queries and keys determine weights; values determine the information returned. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Query-key compatibility
q=[[2,1],[0,3]]k=[[1,0],[0,3],[1,1]]print([[sum(a*b for a,b in zip(u,v)) for v in k] for u in q])Expected output (locally tested): [[2, 3, 3], [0, 9, 3]]. Two queries and three keys produce a 2 by 3 matrix.
How it works
For a sequence of T tokens with embedding width d_model, learned linear projections create Q, K and V. In a single head, Q has shape (L,d_k), K has shape (S,d_k), and V has shape (S,d_v). L is the number of query positions and S the number of source positions. Matrix multiplication Q @ K.T produces an (L,S) compatibility matrix: entry i,j is the dot product of query i and key j. Self-attention projects the same input sequence into all three roles, but the projections can differ. Cross-attention uses queries from one stream and keys and values from another. The weights are normalized across source positions for each query; the output has shape (L,d_v). Attention is a learned mixing operation, not a database lookup guaranteed to return a single matching item. For batched examples a leading batch axis is added; heads add another axis. A large dot product can arise from vector magnitude as well as alignment. Attention weights alone do not establish causal feature importance.
Cross-attention shapes
import torchq=torch.tensor([[1.,0.]])k=torch.tensor([[1.,0.],[0.,1.]])v=torch.tensor([[2.,4.,6.],[8.,10.,12.]])a=(q@k.T).softmax(-1)print(list(a.shape),list((a@v).shape),round(float(a.sum()),6))Expected output (locally tested): [1, 2] [1, 3] 1.0. This unscaled introductory example mixes two value vectors of width three.
Common mistakes
Do not multiply Q by K without transposing its last two dimensions, use values to calculate the dot scores, or assume query and source lengths must be equal.
Practice and next steps
Predict the scores for a query [2,1] against keys [1,0] and [0,3]. Then swap the associated values without changing the scores; explain why the retrieved output changes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Queries keys and values — knowledge check
Apply queries keys and values to small examples and debugging scenarios.
Which tensors determine raw dot scores?
What is the shape of scores for L queries and S keys?
What happens when values change but Q and K remain fixed?
What distinguishes cross-attention?
Do attention weights alone prove causal importance?