Attention playground
Build scaled dot-product attention by hand on a short sentence. Drag the word vectors, edit the query, key and value matrices, and watch the scores, the softmax weights and the outputs change at every step.
Attention is the operation at the centre of every transformer. Each token asks a question (its query), compares it with what every token offers (its key), and returns a weighted average of what the tokens carry (their values). On this page you build it yourself, one step at a time, with numbers small enough to check by hand.
You will see three figures:
- The attention lab. One head on a sentence of up to 8 words. Every vector has 2 numbers, so every vector is a point in a plane.
- Two heads side by side. Two heads read the same sentence in different ways, and their outputs are combined.
- Sinusoidal positional encodings. How a transformer gets the order of the tokens.
1. The attention lab #
Pick a sentence, then click a token to make it the query. Follow the five steps in the box under the planes: the query is compared with every key; the scores (orange for positive, aqua for negative) go through a softmax; the output is the weighted average of the grey values. Drag a word in the embedding plane (the first plane): every number on the page updates. Notice that the blue output never leaves the grey region around the values (their convex hull).
The lab computes, for every token at the same time:
| Step | What happens | Formula |
|---|---|---|
| 1. Embed | look up the vector of each word, and add a position code | |
| 2. Project | three matrices give a query, a key and a value | |
| 3. Score | compare the query of token with the key of token | |
| 4. Softmax | turn each row of scores into weights that sum to 1 | |
| 5. Mix | average the values with these weights |
Try this #
- Does the same word always get the same output? Choose "the cat sat on the mat". Click the
first "the" (position 0), then the second "the" (position 4), and compare the two rows of the
weight matrix. Then turn on the causal mask. Then turn it off again and move the slider of
the position code to 1.
What you should see
Without positions and without a mask, the two rows are equal and the two outputs are equal: for both. The two tokens have the same embedding, so they have the same query, and they see the same set of keys. Attention alone treats the input as a set of tokens. The causal mask breaks the tie (the first "the" sees only itself, the second sees five tokens), and so does the position code: with the two tokens get different vectors . - What does the temperature do? Choose "it → cat" and click "it". Move down to 0.1,
then up to 3. Then set and compare with and the preset .
What you should see
With the row of "it" is almost one-hot: weight 1.00 on "cat", and the output jumps onto the value of "cat". With the weights are flat (largest 0.28) and the output moves towards the mean of all values. Doubling doubles every score, which gives exactly the same weights as halving . This is why the scores are divided by : the scale of the scores controls how sharp the softmax is. - What if the query carries no information? Choose the preset . Look at the weight
matrix. Then turn on the causal mask.
What you should see
All queries are zero, so all scores are 0 and every row of is uniform: . Every token gets the same output, the mean of all values. With the causal mask, row is uniform over the first tokens, so is the running mean (for example on each of the first three tokens in row 2). - Can context change the meaning of a word? Choose "river bank" and click "bank". Note its
output . Then choose "money bank" and click "bank" again.
What you should see
"bank" has the same embedding in both sentences. In the first sentence its largest weight (0.47) is on "river" and . In the second its largest weight (0.39) is on "money" and . The output of attention is a contextual vector: it depends on the other words in the sentence.
In the lab, you set and keep . A friend keeps and sets . Everything else is the same. How do the two weight matrices compare?
, so every score doubles: . Dividing by also doubles every score. The softmax sees the same numbers in both cases. The softmax does not change when you add a constant to all scores of a row, but it does change when you multiply them: larger scores give sharper weights. The mask sets the same entries to in both cases, so it does not matter.
The lab uses and the causal mask. The values of the first three tokens are , and . What is the output ?
All scores are 0, so the softmax gives equal weights to the visible keys. With the causal mask, row 2 sees keys 0, 1 and 2, each with weight . So . A zero query gives uniform weights, not a zero output.
2. Two heads side by side #
Click a token and compare the two weight matrices. Head 1 compares tokens only along the first axis, head 2 only along the second axis (see their matrices and ). The plane below shows the two head outputs and their combination, the multi-head output. Try other presets, or type your own numbers in the matrices.
Multi-head attention runs heads in parallel. Each head has its own matrices , so it computes its own weights and its own outputs . The outputs are put side by side (concatenated) and multiplied by an output matrix . Write as a stack of blocks , one block for each head. Then the result is a sum over heads:
In the figure, and , so the result is the midpoint of the two head outputs.
Try this #
- Why use more than one head? In "it → cat", click "hungry". Which token does each head
attend to most? Then give head 2 the same preset as head 1.
What you should see
Head 1 (axis 1) puts 0.65 on "cat"; head 2 (axis 2) puts 0.49 on "ate". One head can find the subject while the other finds the verb, and the combined output mixes both. When both heads have the same matrices, they compute the same weights and the same outputs, and the second head adds nothing. Different heads are useful only because they learn different projections.
Both heads use the same , and , and as in the figure. How does the multi-head output compare with the output of one head with these matrices?
Equal matrices give equal weights, so , and . The second head adds parameters but no new information. Heads help only when their projections differ. (With the result would be : the scale comes from , which the model learns.)
3. Sinusoidal positional encodings #
Move the position , or press Play. Each pair of dimensions is a clock hand that turns by the angle per position. The first pairs turn fast, the last ones hardly move. The chart shows how similar is to the encoding of every other position . Notice that the curve moves with but keeps its shape. Change the base and the dimension .
Attention alone does not know the order of the tokens (experiment 1). The original transformer adds a fixed vector to the embedding of the token at position . For :
with base . Each pair is a point on the unit circle at the angle . A step of positions turns every pair by the angle . This turn does not depend on , so with a fixed block rotation , and
a function of the offset only. The lab above uses one such pair, , multiplied by the slider value .
Try this #
- What does the base change? Keep . Read the similarity at offset under the
chart, first with , then with . Press Play with each base.
What you should see
With the similarity at is 0.66; with it is 0.40. A smaller base makes the slow clocks turn faster, so nearby positions become less similar and the encoding separates positions better inside a short window. A larger base keeps slow pairs that are still different after thousands of positions, which matters for long sequences.
4. The math in one place #
For a sequence of tokens with vectors stacked as the rows of :
The softmax acts on each row of the score matrix separately, and row of is the output of token .
- The mask has where query may not see key , and 0 elsewhere. The causal mask hides the later tokens: for . Since , masked keys get weight exactly 0, and the other weights still sum to 1.
- Why . If the entries of and are independent with mean 0 and variance 1, then has variance . Dividing by keeps the scores of order 1, so the softmax is not too sharp at the start of training.
- The output is a weighted average. The weights in a row are positive and sum to 1, so lies in the convex hull of the values (the grey region in the lab).
- Temperature. The lab divides the scores by before the softmax. A standard transformer has . We add only to show the effect of the scale of the scores.
- Cost. The score matrix has entries, so attention costs time and memory for each head.
5. Learn more in the tracks #
- Deep Learning, lesson 9: Attention: queries, keys, values and masks: the full derivation, the softmax Jacobian, padding masks, multi-head shapes and cross-attention.
- Deep Learning, lesson 10: Positional encodings: sinusoidal and learned encodings, RoPE and ALiBi.
- Deep Learning, lesson 11: The transformer: how attention, the MLP, normalization and residual connections form a block.
- Linear Algebra, lesson 15: an attention head as two low-rank matrices and around a softmax.
- Linear Algebra, lesson 4: rotations and orthogonal matrices, used by the positional encodings.
- Calculus, lesson 6: backpropagation through the softmax.
- Large Language Models: how attention is used to build and train language models.