All courses

Queries, keys and values

Explain the roles of Q = XW_Q (what I'm looking for), K = XW_K (what I contain) and V = XW_V (what I pass on if attended to). Compute them and their dot-product match scores for a toy sequence.

Builds on: Why positions must exchange information

▶ Watch this lesson Start the whole course

What the animation says

One score, three jobs

Last time, each position took a weighted average over the others, with weights set by content. But where do those weights come from? The obvious score is the dot product of two embeddings. Take the pronoun it. It is looking for a noun, but it is not a noun itself. So, with plain embeddings: how does the score of it on cat compare with cat on it?

Query, key, value

Always equal. A plain dot product can't tell seeking apart from offering. So each position makes three vectors from its own embedding, each with its own learned matrix. The query says what I'm looking for. For it: a singular noun earlier. The key advertises what I contain. For cat: I'm a singular noun. The value is what I hand over if someone attends to me. For cat: its meaning. It's like a search where every document gets a relevance score. Tap the vector of cat that the query of it is compared with.

All positions at once

Stack the embeddings into a matrix X, one row per position. Multiply X by three learned matrices to get Q, K and V. The same three matrices serve every position. Their width, called d head, is a design choice, often smaller than the embedding size. Row t of Q is the query of position t. Same for keys and values. The score of position t on position j is query t dotted with key j. All pairs at once: Q times K transposed, a T by T grid of scores.

Toy: scores by hand

A toy: three positions, two dimensions. X has rows one zero, zero one, and one one. The key matrix is the identity, so the keys are just X. The query matrix moves the first coordinate into the second slot. Queries: zero one, zero zero, zero one. Row one: query one against each key gives zero, one, one. Query two is all zeros, so row two is zero, zero, zero. Row three repeats row one. Position one scores position two at one. What score does position two give position one?

Values wait their turn

Zero. Position one seeks the second coordinate, and position two's key has it. Position two seeks nothing. Plain embeddings would give a symmetric grid. Separate query and key matrices break that symmetry. In numpy, these lines build Q, K and V, and this line computes the scores. The scores use only queries and keys. Values wait until the weighted average. Tap the matrix that can't change any score.

How does a token decide whom to listen to?

Last time: each position should take a weighted average over other positions, with weights set by content. But where do the weights come from? The obvious score, the dot product of two embedding rows, is symmetric and mixes up three jobs. The pronoun *it* is *looking for* a noun, but it *is not* a noun. What a token seeks, what it offers and what it hands over should be separate.

Three learned roles per position

Each position turns its own embedding into three vectors, each with its own learned matrix: - **Query**: what I'm looking for (*it*: "a singular noun earlier"). - **Key**: what I contain, advertised for matching (*cat*: "I'm a singular noun"). - **Value**: what I pass on if attended to (*cat*: its meaning). Match score = query · key. It works like a search where every document gets a relevance score, not just the top hit.

The formulas

$$Q = XW_Q,\quad K = XW_K,\quad V = XW_V$$ $X\in\mathbb R^{T\times d}$ has one embedding row per position. $W_Q,W_K,W_V\in\mathbb R^{d\times d_{head}}$ are learned and shared by all positions. $d_{head}$ is the length of each query, key and value vector, a design choice that is often smaller than $d$. Row $t$ of $Q$ is $q_t$ (likewise $k_t$, $v_t$). Match score of position $t$ on position $j$: $s_{tj}=q_t\cdot k_j$. All pairs at once: $S=QK^\top\in\mathbb R^{T\times T}$, where $K^\top$ is the transpose of $K$. Scores become averaging weights (the recipe comes next), and the average is taken over the $v_j$.

Toy: T = 3, d = $d_{\text{head}}$ = 2

$X=\begin{bmatrix}1&0\\0&1\\1&1\end{bmatrix}$, $W_Q=\begin{bmatrix}0&1\\0&0\end{bmatrix}$, $W_K=I$ (the identity matrix, which leaves rows unchanged). $Q=XW_Q$ has rows $[0,1],[0,0],[0,1]$. $K=X$. $S=QK^\top$: - Row 1: $q_1=[0,1]$ against $k_1,k_2,k_3$ gives $0,1,1$. - Row 2: $q_2=[0,0]$ gives $0,0,0$. - Row 3: $0,1,1$. Note $s_{12}=1$ but $s_{21}=0$. Position 1 seeks the second coordinate, which position 2's key has. Position 2 seeks nothing. $XX^\top$ would be symmetric.

Same toy in numpy

This adds a value matrix to the same toy. The scores use only $Q$ and $K$. $V$ is not used until the weighted average.
import numpy as np
X = np.array([[1,0],[0,1],[1,1]], float)   # [T, d]
W_Q = np.array([[0,1],[0,0]], float)
W_K = np.eye(2)                            # identity matrix
W_V = np.array([[1,0],[0,2]], float)
Q, K, V = X @ W_Q, X @ W_K, X @ W_V        # each [T, d_head]
S = Q @ K.T                                # [T, T]: S[t, j] = q_t . k_j
print(S)   # rows: [0,1,1], [0,0,0], [0,1,1]
print(V)   # what each position would pass on

Remember

Each position projects its embedding three ways with learned matrices: query (what I seek), key (what I advertise) and value (what I hand over). Match scores are $S=QK^\top$. Separate $W_Q$ and $W_K$ make matching asymmetric, and $W_V$ separates *being found* from *what you deliver*.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.