Positional representations and rotary embeddings
Derive how coordinate rotations make an attention score depend on relative token position.
On this page
The question for today
What you’ll understand
- Explain why token mixing needs positional information.
- Derive the relative-angle identity for rotary attention scores.
- Identify the limits of extrapolating beyond trained sequence lengths.
Attention computes relationships between token representations. Without a positional mechanism, content alone does not tell an unrestricted attention layer whether a word occurred first or last. Positional representations supply structure to those relationships. Rotary position embeddings encode position by rotating paired query and key coordinates. Their geometry is simple enough to derive directly, making it possible to distinguish a true relative-position identity from unsupported claims about unlimited context.
Specify where position enters
For a sequence of length L and model width d, additive position embeddings provide an L by d table or function that is combined with token embeddings. Relative biases instead modify attention scores according to displacement or another positional relation. Rotary embeddings transform query and key features before their dot product. These choices are not interchangeable: they inject position at different points and create different extrapolation and parameter-sharing behavior.
A causal mask already distinguishes allowed past positions from future positions, so a masked attention architecture is not fully permutation equivariant in the same way as unrestricted attention. Nevertheless, a mask is not a general substitute for encoding distances and order. A position convention must also remain consistent between training and cached generation. Reusing cached keys with incorrect position indices can produce valid tensor shapes while computing the wrong attention scores.
Relative position emerges inside the dot product
A two-dimensional rotation preserves vector length. Rotating a query at position m and a key at position n yields a dot product containing the product of the transpose of one rotation with the other. That product is a rotation through their angle difference. Consequently the positional part depends on n minus m, while the score still depends on both content vectors. Different coordinate pairs provide different angular scales, allowing several distance-sensitive patterns to coexist.
Apply the same pairing layout and frequency convention to queries and keys. Some implementations pair neighboring coordinates and others pair corresponding coordinates from two halves; the weight layout must match the convention. Scaling by the square root of head dimension remains a separate part of scaled dot-product attention. Rotary embeddings do not change the L by L score matrix's basic dense attention complexity, and they do not directly rotate values in the usual formulation.
Extrapolation remains an empirical question
A formula can be evaluated at positions larger than those seen in training, but that does not prove useful behavior there. Large displacements create unfamiliar phase combinations, and finite-dimensional periodic features can make different distances difficult to distinguish. Frequency rescaling or interpolation changes those phases and therefore changes the model's behavior. Evaluate such extensions against a held-out long-context task, not simply whether inference avoids an indexing exception.
Measure retrieval accuracy as a function of both context length and target position. Include multiple distractors and tests whose answers cannot be inferred from a short prefix. Keep context extension methods, fine-tuning data, attention implementation, and memory budget explicit. A longer context also increases key-value cache storage and prefill compute even if positional features themselves are cheap. Numerical precision in forming angles and trigonometric values can matter at large indices, so verify implementations against a higher-precision reference.
Work it through
Compute a rotary score by hand
Use one coordinate pair, query q=(1,0), key k=(1,0), frequency ω=π/2, query position m=0, and key position n=1. Ignore attention's dimension scaling.
At position zero the query is unchanged: R(0)q=(1,0).
The key rotates by π/2, becoming R(π/2)k=(0,1). Their dot product is zero.
Shift both positions by two. The query becomes (−1,0) and key becomes (0,−1), whose dot product is again zero. The relative displacement remains one.
A common positional shift preserves this pair's score, although changing the content vectors or relative displacement generally changes it.
The living notebook
Explore the model
Interactive lab · waves
Inspect relative phase
The lab adds sin(2x−t) to a second wave with phase difference and amplitude ratio controls. It makes constructive and destructive phase relationships visible. It is not a rotary embedding or attention computation; the worked example supplies the actual vector rotations and dot product.
- Sum at x = 0
- 0.866
- Resultant amplitude
- 1.732
- Phase difference
- 60°
Two waves share the same frequency and wave number. Playback advances t in sin(2x − t) + a sin(2x − t + phase). Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forA relative phase can change a combined response while a common phase shift moves both components together.
Pause & reason
Check your understanding
Your turn
Try it yourself
With q=k=(1,0) and frequency π/3, compare the unscaled rotary scores for position differences zero, one, and three.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
For these content vectors, the score is the cosine of the relative angle.
Compare with the solution
The scores are cos(0)=1, cos(π/3)=0.5, and cos(π)=−1. They can be negative even though a later softmax produces nonnegative attention probabilities. This pair is periodic: a difference of six returns score one, illustrating why one frequency cannot identify every distance uniquely.
Keep the idea
Take it with you
- Position can enter embeddings, scores, or query-key geometry.
- Rotary score geometry depends on relative angles and content together.
- An evaluable position formula does not establish reliable long-context generalization.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.