Skip to content
StackDecode
AI & ML Atlas
Deep LearningtechniqueInteractive simulation

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.

thecatsatonthemat
  • positive
  • negative
  • attention weight

Take the sentence. We will compute what the word "cat" (highlighted) should pay attention to.

1/4

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

  1. 1Project each token embedding into Q, K and V.
  2. 2Compute scores QKᵀ and divide by √dₖ.
  3. 3Apply softmax to each row to get attention weights.
  4. 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.

Related