Skip to content
StackDecode
LLM Library
FoundationsAnimated

Positional Encoding and RoPE

Telling the model the order of the tokens.

The idea

Attention itself ignores order, so position is injected. Modern models use rotary position embeddings (RoPE), which rotate the query and key vectors by an angle that depends on position, so attention scores depend on relative distance.

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. 1Give each token a position number
  2. 2Rotate query and key vectors by an angle based on it
  3. 3Attention scores now reflect distance
  4. 4Scaling tricks stretch RoPE to longer contexts

Where it is used

Llama, Qwen, Mistral, DeepSeek and most open models.

Watch out for

Models degrade beyond the lengths they were trained for unless position scaling is applied.