← All courses ← Course Lesson 7 / 18
Part II · The transformer

7. Position: how the model knows word order

Attention is order-blind by construction. Something has to tell the model that 'dog bites man' differs from 'man bites dog'.

By the end of this lesson you can

  • Explain why self-attention is permutation-equivariant
  • Compare absolute, learned, and rotary position encodings
  • Describe how RoPE encodes relative distance through rotation
  • Explain why context-length extension is hard and how it is done

The set problem

Look again at the attention equation. Scores are dot products between queries and keys; the output is a weighted sum. Shuffle the input positions and every score simply moves with them — the computed values are identical. Self-attention treats its input as an unordered set.

That is a genuine problem, since word order carries a great deal of meaning. It is also a genuine feature: it is exactly what allows all positions to be processed in parallel, which is why transformers train so much faster than recurrent networks. The transformer's answer is not to restore sequential processing but to put position information into the vectors themselves.

Approach 1: add a position vector

The original 2017 transformer added a fixed sinusoidal vector to each token embedding. Dimension pairs oscillate at geometrically spaced frequencies:

PE(pos, 2i) = sin(pos / 10000^(2i/d))    PE(pos, 2i+1) = cos(pos / 10000^(2i/d))

Fast dimensions distinguish neighbouring positions; slow ones distinguish far-apart regions. Together they give every position a unique fingerprint, a bit like the digits of a binary counter running at different rates.

GPT-2 and BERT instead used learned absolute embeddings: one trainable vector per position. Simple and effective, with one fatal limitation — position 4000 has no vector at all if you only trained up to 2048. The model cannot extrapolate one step beyond its training length.

Sinusoidal position encoding

Each row is a position, each column a dimension. Notice the frequency gradient left to right.

Approach 2: rotate the vectors (RoPE)

Rotary position embedding is what essentially every current model uses, and the idea is neat.

Take the query and key vectors, split them into 2-dimensional pairs, and rotate each pair by an angle proportional to the position. Different pairs rotate at different rates, again geometrically spaced — pair i turns by pos / 10000^(2i/d) radians, the same base as the sinusoidal formula above. The first pairs complete a full turn every few tokens; the last ones barely move across the whole context. That spread is what the interpolation methods below act on: stretching the slow pairs buys range, and leaving the fast ones alone keeps neighbouring positions distinguishable.

The payoff is in what happens to the dot product. Rotating two vectors by angles and makes their dot product depend only on the difference (m − n). So the attention score between two positions automatically encodes how far apart they are, not where they sit absolutely. The same phrase gets the same internal relationships whether it appears at position 10 or position 10,000.

Other properties that matter in practice:

  • It is applied to Q and K inside every attention layer, not added once at the bottom.
  • It touches no parameters — it is a fixed geometric transform.
  • Attention naturally decays with distance, which is a sensible prior for language.
  • Because the encoding is relative and continuous, you can stretch it after training to extend context.

RoPE as rotation

Watch a query/key pair rotate with position and see how the dot product tracks their separation.

Stretching the context window

A model trained on 8k tokens does not simply work at 128k. The rotation angles at position 100,000 are outside anything it saw, and quality collapses. The common techniques:

  • Position interpolation — scale positions down so that 32k tokens occupy the angle range the model was trained on. Positions become fractional. Cheap, and works with a short fine-tune, but it compresses local resolution.
  • NTK-aware scaling / YaRN — scale the frequency bands unevenly: leave high-frequency (local) dimensions alone and stretch the low-frequency (global) ones. Preserves local precision much better.
  • Long-context fine-tuning — after any of the above, train on genuinely long documents so the model learns to use the range.

Advertised context ≠ usable context. A model can accept 200k tokens and still retrieve poorly from the middle of them. The well-documented "lost in the middle" effect shows retrieval accuracy dipping for material in the middle of a long context relative to the beginning and end. Always measure on your own task rather than trusting the headline number.

Lesson in one breath

Attention treats its input as a set. Position must be injected explicitly — historically by adding sinusoidal or learned vectors, now almost always by rotating query and key vectors by an angle proportional to position (RoPE), which makes attention scores depend on relative distance.

Practice

Answers are checked in your browser and saved to this device. Get one wrong and you can retry as many times as you like.

Exercise 1one answer

Why does a transformer need explicit position information at all?

Exercise 2one answer

What is the key property of RoPE that absolute learned embeddings lack?

Exercise 3select all that apply

Which are true about extending a model's context window? Select all.

Exercise 4type the term

What is the abbreviation for the position encoding scheme that rotates query and key vectors by an angle proportional to position?

Exercise 5one answer

A model was trained with learned absolute position embeddings up to 2048 tokens. You feed it 3000 tokens. What happens?

Done with this lesson?

A lesson counts as complete once it is marked read and every exercise is solved.

Tip: press and to move between lessons.