6.7 — Rotary Position Embedding (RoPE)
Goal: Derive RoPE from the requirement that the q·k dot product depend only on the relative position n − m. Build the operation in the 2D case, lift to general d via block-diagonal rotations, and identify the choice of frequencies θᵢ = 10000^{−2i/d}.
1. Why this session exists
6.6 ended with the claim: rotate and in 2D planes by angles proportional to position, and the dot product becomes a function of alone. This session makes that claim precise.
The construction has three layers:
- 2D core. A single 2D rotation has the property , which is the entire mechanism RoPE uses.
- High-dimensional lift. Split (with even) into pairs, each rotated independently at its own frequency.
- Frequency schedule. Pick the per-pair frequencies so that the network has access to a wide spectrum of "positional wavelengths" — short ones for local order, long ones for global position.
RoPE is the dominant positional encoding in modern LLMs (LLaMA, Mistral, Qwen, Gemini, and most production LLMs from 2023 onward). The derivation is short and the result has a clean geometric interpretation. Both are below.
2. The 2D rotation identity
The 2D rotation matrix by angle is
It is orthogonal: . And it has the composition rule — rotations form a one-parameter group. Combining these:
This is the entire identity RoPE uses. The rest is bookkeeping.
2.1 Applying to attention
Let be a single query and key (we'll lift to higher dimension in §3). Define the position-rotated vectors at positions and :
with a fixed "base frequency" (we will pick it in §4). Compute the dot product:
The dependence on and has collapsed into dependence on alone. The dot product of the rotated query and key depends only on their relative position. This is the property 6.6 §4.3 asked for.
There are no learnable parameters in this construction. The rotations are deterministic functions of and .
3. Lifting to general
A single 2D plane is too narrow for a useful attention head; the standard head dimension is or (6.4). Lift to general (even) by splitting the head dimension into pairs of coordinates and rotating each pair independently with its own frequency.
Let , and group coordinates as
with the -th pair living in the plane spanned by coordinates for . Pick frequencies .
Define the block-diagonal rotation at position :
Each block rotates its pair of coordinates by . The full matrix is orthogonal and has determinant 1.
The rotated query and key at positions and are
The dot product expands as a sum over pairs:
where denotes the 2D restriction of to coordinates . Each pair contributes a term that depends only on , scaled by the pair's own frequency .
The full dot product is therefore a sum of "relative-position responses" at different frequencies. This is the key structural property of RoPE: it doesn't encode position as one number per token; it encodes it as a spectrum of independent rotations, each contributing to a different range of relative offsets.
4. The frequency schedule
The construction so far works for any choice of . The choice in the RoPE paper (Su et al., 2021)[1] mimics the sinusoidal positional encoding of AIAYN:
The base is conventional (and adjustable — long-context fine-tuning often changes it; see 7.13). The resulting frequencies span a wide geometric range:
- : . Highest frequency. Period — captures very short-range positional differences ( of order 1).
- : . Lowest frequency. Period — captures very long-range positional differences.
The spectrum lets the model attend to relative position at multiple "scales." Short-range patterns (n-gram-style) use high-frequency pairs; long-range patterns (document structure) use low-frequency pairs. Different attention heads, and different pairs within a head, end up using different parts of the spectrum.
4.1 The connection to sinusoidal encoding
The sinusoidal positional encoding of AIAYN (see Appendix 6.A) sets the coordinates of to with the same frequencies. The relation is structural: applying to a 2D vector rotates it through the same angle that would sweep. RoPE inherits the frequency schedule but applies it as a rotation of rather than as an additive shift of embeddings.
5. The full RoPE forward pass
Putting the pieces together, RoPE-modified self-attention is:
Note carefully: values are NOT rotated. RoPE applies only to and . The rotation's purpose is to make the dot product positional-dependent; the values are then mixed by an attention weight that already carries the position information.
5.1 Efficient implementation
The block-diagonal rotation has a clean coordinate form. Pair at position acts as:
In implementations, this is computed as two element-wise multiplications using pre-computed and tables: with and holding the cosines and sines at position , the rotation is
where swaps adjacent coordinates with a sign flip (the "negate-then-swap" trick). The cost is two element-wise multiplies plus a swap, all . Trivial compared to the attention dot product.
6. Geometric reading
A clean way to picture what RoPE does:
"At every position, twist the query and key vectors. The angle of the twist grows linearly with position, and different coordinate pairs are twisted at different rates."
Two queries at the same position have the same twist applied — so RoPE preserves the relative orientation of queries at the same position. Two queries at different positions are twisted by different angles, so their inner products with a fixed key become position-dependent.
The dot product depends only on the relative twist angle in each pair, summed across pairs. The model sees "position" through this spectrum of relative-twist responses, and learns to use the spectrum to express positional patterns of various kinds.
7. Properties: why this design wins
Five properties make RoPE the modern default:
(a) Relative-only. The attention score depends only on . This is what we want from a positional encoding for language.
(b) No learnable parameters. The rotations are fixed; the schedule is fixed. No "positional embedding matrix" to size up with context length.
(c) Decays with distance, controllably. For each frequency , the rotation oscillates. Empirically, larger tends to produce a smaller mean attention score at random initialisation — a "soft locality prior" that helps training but does not forbid long-range attention.
(d) Decoupled from values. Position only affects the attention weights, not the values being mixed. The residual stream of 6.10 (Part 2) stays clean.
(e) Tractable extrapolation. The rotation angles are continuous in position, so the model has some signal at positions beyond the training context. Position interpolation, NTK-aware scaling, and YaRN (Peng et al., 2023) all build on this — see 7.13. Compare with learned absolute positional embeddings, which have no defined behaviour at out-of-distribution positions.
8. The base and modern long-context training
The base controls the spread of frequencies. was the choice in AIAYN and the original RoPE paper. Two adjustments are common in modern training:
-
Increase for longer contexts. LLaMA-2 used at 4k context; LLaMA-3 uses at 8k context; Qwen-2-72B-1M uses at 1M context. Larger pushes more frequencies into the low-frequency regime, providing finer positional discrimination at longer distances. This is the simplest way to extend context length and is now standard in pretraining.
-
NTK-aware scaling / YaRN. When extending a model's context window without retraining from scratch (e.g. extending a 4k LLaMA to 128k), one can rescale the frequencies post hoc by a position-interpolation-like rule. The math is in 7.13.
Both adjustments are downstream of the RoPE construction itself — they are choices of , not of the structural form .
9. What we keep going forward
RoPE in one line: rotate and in separate 2D planes by angles proportional to position , with frequencies . The dot product becomes a function of alone.
We have now specified every part of the attention sub-layer: similarity (6.2), wiring (6.3), heads (6.4), mask (6.5), and position (6.6, 6.7). 6.8 introduces the FFN sub-layer that completes one Transformer block.
(a) Prove the identity directly from the matrix form of using / addition formulas.
(b) For and a single frequency , write the block-diagonal rotation matrix for . Verify that .
(c) Show that (the block-diagonal rotations form a one-parameter group). Why does this imply that "RoPE is consistent with absolute position shifts"?
(d) A query is at position with frequencies . Compute explicitly. Then a key is at position . Compute and the dot product . Verify that the answer is what you would get from .
(e) Sketch why applying RoPE to the values (not just ) would break the relative-position property. (Hint: the values appear in without a second rotation; the position rotations would propagate into the output and contaminate the residual stream.)
References
- [1]
Su, J., Lu, Y., Pan, S., et al. (2021). "RoFormer: Enhanced transformer with rotary position embedding". arXiv:2104.09864 — Rotary positional embedding (RoPE) (6.7).
↩