Self-Attention
Every token in a sequence looks at every other token to update its meaning.
The idea
Each token is turned into a query, a key and a value. A token's query is compared with all keys; the resulting weights mix the values. "Bank" next to "river" therefore ends up with a different vector than "bank" next to "loan". The scores are divided by √dₖ so they stay in a good range for the softmax.
softmax(QKᵀ / √dₖ)·V
Watch it run
This is a real computation, not a drawing. Pause, step, change the settings, or try new random data.
- positive
- negative
- attention weight
Take the sentence. We will compute what the word "cat" (highlighted) should pay attention to.
The vectors here are random, so the pattern of attention is arbitrary. In a trained model these weights are learned. Pick another query word with the slider.
Step by step
- 1Project each token embedding into Q, K and V.
- 2Compute scores QKᵀ and divide by √dₖ.
- 3Apply softmax to each row to get attention weights.
- 4Multiply the weights by V to get the new token vectors.
Where it is used
Inside every transformer layer.
Watch out for
Quadratic cost in sequence length.