Skip to content
StackDecode
LLM Library
Inside the TransformerAnimated

Self-Attention

Each token gathers information from the other tokens.

The idea

Each token makes a query, a key and a value. Comparing its query with every key gives weights, and the token's new vector is a weighted mix of the values.

Watch it work

Press play, pause, or step through. Some animations have settings you can change.

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. 1Make Q, K and V from each token
  2. 2Score every query against every key
  3. 3Softmax the scores into weights
  4. 4Mix the values using those weights

Where it is used

The core of the transformer.

Watch out for

Cost grows with the square of the sequence length.