RoPE Rotates Query and Key Pairs
RoPE splits projected queries and keys into coordinate pairs and rotates each pair using its position and frequency. Calculate the geometry, verify norm preservation, and record pairing, sign, origin, scaling, and precision conventions.
Rotary Position Embedding, or RoPE, inserts position information after the query and key projections. It divides query and key features into 2D pairs and rotates each pair by an angle determined by the token position and that pair's frequency.
The standard formulation taught here rotates queries and keys, not values. A codebase may arrange paired coordinates differently, so we will state the layout before calculating anything.
Start with One 2D Rotation
For column vectors, define
At position , one query pair becomes
where is the frequency assigned to that pair.
Let , , and . The angle is , so
The rotation changes direction while preserving length.
Extend the Operation Across the Head Width
For an even query-key head width , this chapter pairs adjacent coordinates:
Each pair has its own frequency. A common RoPE schedule follows the same broad fast-to-slow pattern as sinusoidal encodings. The complete query at position receives block-diagonal rotations: one 2D block for every coordinate pair.
For a four-coordinate query,
the first pair may turn quickly while the second turns slowly. The operation does not mix the two pairs with each other.
Verify the Geometry
Rotate adjacent query-key pairs
The code applies one stated adjacent-pair convention and checks that every pair preserves its Euclidean length.
Ready to run.
The first pair becomes approximately . The second pair rotates through the smaller angle .
Conventions That Must Agree
Two implementations can both be called RoPE and still disagree because of:
- adjacent-coordinate versus split-half pairing;
- the sign used by the 90-degree partner operation;
- whether positions begin at 0 or another offset;
- the frequency base and any context-length scaling;
- which fraction of the query-key width is rotated;
- the dtype used to calculate angles at large indices.
Shape checks will not detect these differences. A reliable port compares selected rotated values and attention logits under the same convention.
Q1. Rotate one query pair
Using the rotation matrix on this page, rotate by angle . What is the second coordinate?
Compute it first, then check your number.
Hint
Solution
Reference
- Jianlin Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding, 2021.