Attention
A self-attention layer lets every token in a sentence look at the others and take a blend of what it finds. As a formula it fits on one line, O = softmax(QKᵀ/√d)·V, but the line reads inside out. Here it is in the order it runs, for the four tokens the cat sat down. Each token is two numbers, so every matrix stays small enough to read.
Step
Mask
In the plane
The same layer, drawn as points. Pick whose output to follow: the query of
Things to try
- Follow V. Its arrow leaves at step 2 and isn't used until step 7. The whole middle of the layer only decides how much of each value to take, never what the values are.
- Turn on the causal mask, then step to Mask. The top-right triangle of the scores becomes −∞, and after the softmax those weights are exactly 0. the, with nothing before it, gives all its weight to itself.
- Set WQ to zero and step to Softmax. Every query is zero, so every score is zero and every weight is ¼. Each output is the plain average of the values.
- Scale WQ up. Doubling the queries doubles every score, and the softmax sharpens: each row puts nearly all its weight on its best key.
Things to notice
- The tokens don't meet until step 3. Up to there, each row is computed from its own token alone. QKᵀ is the only place where one token's numbers touch another's.
- The output never leaves the green shape. Its weights are positive and add up to 1, so it's a blend of the values, and it stays between them.
- The layer doesn't know the word order. Without the mask, swapping two tokens' embeddings only swaps their rows in every matrix. Real models add the position to each embedding for this reason.
- Why √2? With d numbers per vector, a dot product adds up d products, so the scores grow with d. Dividing by √d keeps the softmax from becoming too sharp in big models, where d is in the hundreds.
How it's built
- The variables. Each embedding coordinate and each matrix entry is a
<t-var>. They're page-wide, with no<t-scope>, so the diagram and the planes further down share them. The step is a<t-num>, and the mask and the query are<t-choice>s. - The math knows nothing about the page.
attention()takes plain arrays and returns every intermediate matrix. The diagram itself is data: a list of nodes, each with the step it runs in, and a list of edges.drawFlow()marks each node as done, active or pending for the current step. - One effect draws it all. The effect reads every variable, runs the layer and redraws the diagram, the panel and both planes. See Updating a chart.
- The buttons set the step. Back, Next, Play and a click on a node all call
scope.set("step", …), like dragging the step number does. Dragging a token in a plane callsscope.setValues.
Open the source panels above for the full markup, script and styles.