All courses

Attention in plain words

Each token is held as a vector, and attention is the only place where those vectors exchange information. Each position forms a query (what it is looking for) and compares it with the keys (what each earlier position offers). It then takes a weighted average of those positions' values, with weights set by how well query and key match. In a language model a position may only look backwards, never at future tokens. Several attention 'heads' run side by side, each free to look for something different.

▶ Watch this lesson Start the whole course

What the animation says

Where tokens share information

Inside a language model, every token is held as its own vector, a list of numbers. Most of the model's work transforms each of those vectors separately, side by side. But take this sentence: the trophy didn't fit in the case because it was too big. To make sense of 'it', its vector needs facts from 'trophy' and 'case'. Attention is the only mechanism that moves information between positions. So when the model processes 'it', which words can attention pull from?

Ask, advertise, deliver

Itself and earlier words only. Text is predicted left to right, so later words are off limits. To choose where to look, each position computes three vectors from its own vector. A query: what am I looking for? A key: what do I offer to anyone searching? And a value: what I hand over if I am picked. It compares its query with each visible key: one match score per position. The scores become weights that sum to one, and it receives the weighted average of the values.

Position 3 looks back

Tiny example: two-number vectors, and we skip one scaling step for now. Position three's query, matched against three keys, gives scores two, zero, zero. Exponentiate: about seven point four, one, and one, totalling nine point four. Divide by the total: weights point seven nine, point one one, point one one. Mix the values with those weights: seven point nine, one point one. Mostly position one. Now raise position one's score from two to four. What happens to the output's first number?

All positions at once

About nine point six, never past ten. Weights sum to one, so it's an average, not a sum. Real models do every position at once. Each row of this grid is one position's scores. Cells above the diagonal are the future: set to minus infinity, their weight becomes zero. In code, one matrix product makes all the scores; another mixes all the values. Subtracting each row's maximum first leaves the weights unchanged and prevents overflow. Tap the line that stops positions from seeing the future.

Many heads, one scale

One more detail: scores are divided by the square root of the head's width. Longer vectors give bigger dot products. Without the division, weights would pile onto one position. Attention also runs as several heads side by side, each with its own learned matrices. One head might learn to track what 'it' refers to; another, the word just before. Their outputs are joined and mapped back to the model's width by one more learned matrix. So: attention is where positions share information. Match queries to keys, then average the values.

Where do tokens share information?

An LLM holds each token as its own vector, and most of its computation transforms each vector separately. But to read *“The trophy didn't fit in the case because it was too big”*, the vector for *it* needs facts from *trophy* and *case*. Attention is the only mechanism by which one position's vector can pull in information from other positions. How does it decide where to look, and what does it take?

Ask, advertise, deliver

Each position computes three vectors from its own vector: - **query**: what am I looking for? - **key**: what do I offer to anyone searching? - **value**: what I hand over if I am picked. A position compares its query with the keys of itself and every earlier position. It turns the match scores into weights that sum to 1, then takes the weighted average of those positions' values. It never sees later positions, because text is predicted left to right.

One head, then many

Let $X_t$ be row $t$ of $X\in\mathbb{R}^{T\times d}$, the vector at position $t$. Each head has three learned matrices $W_Q,W_K,W_V\in\mathbb{R}^{d\times d_{head}}$, whose numbers are set during training. Per head: $q_t=X_tW_Q$, $k_j=X_jW_K$, $v_j=X_jW_V$, each in $\mathbb{R}^{d_{head}}$. $$s_{tj}=\tfrac{q_t\cdot k_j}{\sqrt{d_{head}}},\quad a_{tj}=\tfrac{e^{s_{tj}}}{\sum_{i\le t}e^{s_{ti}}},\quad o_t=\sum_{j\le t}a_{tj}v_j$$ For $j>t$, $a_{tj}=0$. Dot products of longer vectors tend to be larger. Dividing by $\sqrt{d_{head}}$ keeps scores in a similar range whatever $d_{head}$ is, so the weights don't all pile onto one position. $h$ heads run side by side, each with its own matrices. Their outputs are concatenated, and another learned matrix $W_O$ maps the result back to width $d$.

Position 3 looks back

Take $d_{head}=2$ and skip the $\sqrt{d_{head}}$ for clarity. Query: $q_3=(1,0)$. Keys: $k_1=(2,0)$, $k_2=(0,1)$, $k_3=(0,0)$ → scores $2, 0, 0$. Exponentiate: $7.39, 1, 1$. Sum $=9.39$ → weights $0.79, 0.11, 0.11$. Values: $v_1=(10,0)$, $v_2=(0,10)$, $v_3=(0,0)$. Output: $0.79(10,0)+0.11(0,10)+0.11(0,0)=(7.9,\,1.1)$. This is mostly position 1's content, because its key matched best.

All positions at once

Stacking all queries and keys gives a $T\times T$ score matrix, where row $t$ holds position $t$'s scores. Entries above the diagonal are set to $-\infty$. Their weights become $e^{-\infty}=0$, so no position sees the future. One matrix product with $V$ then computes every position's weighted average. In the code, `@` is matrix multiplication and `.T` is the transpose. Subtracting each row's maximum before exponentiating leaves the weights unchanged, since only score differences matter. It also stops huge numbers from overflowing.
import numpy as np
rng = np.random.default_rng(0)
T, d, d_head = 4, 8, 2
X = rng.normal(size=(T, d))                      # one row per token
W_Q, W_K, W_V = (rng.normal(size=(d, d_head)) for _ in range(3))
Q, K, V = X @ W_Q, X @ W_K, X @ W_V              # each [T, d_head]
S = Q @ K.T / np.sqrt(d_head)                    # [T, T] match scores
S[np.triu_indices(T, k=1)] = -np.inf             # no looking ahead
A = np.exp(S - S.max(axis=1, keepdims=True))     # subtract row max: same weights, no overflow
A /= A.sum(axis=1, keepdims=True)                # each row sums to 1
out = A @ V                                      # [T, d_head] weighted averages
print(A.round(2))                                # lower-triangular

Remember this

Attention is the only place where positions exchange information. Each position matches its query against the keys of itself and earlier positions, then receives the match-weighted average of their values. Several heads do this side by side, each with its own idea of what to look for.

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.