Highlights

Contents

Part V
05

RoPE: Rotate, Don’t Add

Position can change a comparison instead of an embedding. RoPE rotates queries and keys. Their relative rotation depends on the gap, while longer contexts still require adaptation and testing.

YOU ARE HERE"raw text"tokenizerembeddings+ positionslearnedwavesRoPEDECODER BLOCK× NnormattentionQKVsoftmaxmaskheadsn × n+normMLP+residual streamKV cachefinal normLM headsoftmaxP(next)training: the loss sends a correction back to every weight

#Section 27Rotate, Don’t Add

Rotary position embedding, or RoPE, was introduced by Jianlin Su and colleagues in RoFormer in 2021. A query qq describes what a token seeks; a key kk describes how another token can be found. Their dot product determines a matching score.

Treat each pair of query or key features as a point on a plane. Rotate it by an angle determined by its position, rather than adding a position vector to the input.

The formula is the school formula for rotating a point by an angle ϕ\phi:

[q0′q1′]=[cos⁡ϕ−sin⁡ϕsin⁡ϕcos⁡ϕ][q0q1],ϕ=m θ\begin{bmatrix} q'_0 \\ q'_1 \end{bmatrix} = \begin{bmatrix} \cos\phi & -\sin\phi \\ \sin\phi & \cos\phi \end{bmatrix} \begin{bmatrix} q_0 \\ q_1 \end{bmatrix}, \qquad \phi = m\,\theta

Read it out loud: the new first number is the old first number times cos⁡ϕ\cos\phi minus the old second number times sin⁡ϕ\sin\phi, and the new second number is the old first times sin⁡ϕ\sin\phi plus the old second times cos⁡ϕ\cos\phi. The angle ϕ\phi is the token's position mm times a fixed rotation speed θ\theta (the Greek letter theta) for this pair.

The figure rotates an illustrative query pair. Its direction changes while its length remains fixed.

ONE PAIR OF A QUERY, ROTATED BY ITS POSITION (TOY θ = 0.5 RAD PER POSITION)m=1m=3m=4q at m = 0q′ at m = 21.0 radq = (1.00, 0.50), m = 2, angle mθ = 1.0q′₀ = 1.00 · cos 1 − 0.50 · sin 1 = 0.12q′₁ = 1.00 · sin 1 + 0.50 · cos 1 = 1.11length before: √(1.00² + 0.50²) = 1.118length after: √(0.12² + 1.11²) = 1.118only the direction changes:position is stored as an angle
Figure 1.36One query pair rotated by its position. The dashed arrow is the pair before rotation; the orange arrow is the same pair at position 2. Dots mark where it would point at positions 1, 3 and 4. The length never changes, only the direction.

Rotation preserves length, so the position operation changes orientation without changing the vector's size.

#Section 28Every Pair Has Its Own Speed

A real query has many pairs, not one. Finch's attention heads are 64 numbers wide, so each query has 32 pairs. RoPE gives each pair its own dial and its own speed, exactly like the clock hands of Part IV:

θi=base−2i/dhead,i=0,1,…,dhead2−1\theta_i = \text{base}^{-2i/d_{\text{head}}}, \qquad i = 0, 1, \dots, \tfrac{d_{\text{head}}}{2} - 1

With base 10,000 and a 64-wide head, pair 0 turns at θ0=1\theta_0 = 1 radian per position, pair 8 at 0.1, pair 16 at 0.01, pair 24 at 0.001 and the last pair, 31, at 0.000133. Notice that dd here is the head size (64), not the model width (512), because RoPE acts inside each head separately.

A TOKEN AT POSITION m = 5, FOUR OF ITS 32 PAIRS (HEAD SIZE 64, BASE 10,000)pair 0: θ = 1.00turned 5.00 radpair 8: θ = 0.10turned 0.50 radpair 16: θ = 0.01turned 0.050 radpair 24: θ = 0.001turned 0.005 radfast pairs notice small gaps, slow pairs notice big ones
Figure 1.37Four of the 32 pairs for a token at position 5. Pair 0 has turned 5 radians, most of a full turn. Pair 24 has turned only 0.005 radians, which is barely visible.

Fast pairs distinguish nearby positions but wrap around often. Slow pairs vary over longer distances. Their combined angles describe gaps at different scales; the base controls the frequency range.

#Section 29The Trick: Only the Gap Survives

Rotate the query by its position mm and the key by its position nn, then take their dot product. Using R(ϕ)R(\phi) for "rotate by angle ϕ\phi", the result can be rewritten as:

(R(mθ) q)⋅(R(nθ) k)=q⋅(R((n−m)θ) k)\big(R(m\theta)\,q\big) \cdot \big(R(n\theta)\,k\big) = q \cdot \big(R((n - m)\theta)\,k\big)

Rotating both vectors by the same extra angle preserves their relative angle. The positional part of their dot product therefore depends on the gap, while the content still affects the score.

Shift both positions together in the figure: the score stays unchanged. Change their gap and the score changes. This isolates relative-position behavior.

SHIFT BOTH TOKENS BY 10: THE ANGLE BETWEEN THEM, AND THE SCORE, STAY PUTq at 2k at 5score = 1.0329q at 12k at 15score = 1.0329no rotation:score = 0.5000gap 3 both times
Figure 1.38Shifting both tokens by ten positions. Both arrows turn by the same extra angle, so the angle between them, and therefore the score, is unchanged at 1.0329.

This is the relative position property, delivered exactly and for free. "Two words apart" scores the same on page 1 and on page 300. The model learns "a pronoun often looks a few tokens back" once, and it applies everywhere.

#Section 30Where RoPE Sits in Attention

Where exactly does the rotation happen? Part VI builds attention properly, but the outline is short. Each token's vector xx is multiplied by three learned matrices to produce its query qq, its key kk and its value vv, the content it will hand over if another token attends to it. RoPE rotates qq by the query token's position mm and kk by the key token's position nn. Then the rotated queries and keys are compared, the scores pass through softmax (Part VII) to become weights, and the weights blend the values.

WHERE ROPE ACTS: ON q AND k, AFTER PROJECTION, BEFORE THE DOT PRODUCTxWQqrotate by mWKkrotate by nWVvno rotationq′ · k′ / √dsoftmax× vv keepsits content
Figure 1.39RoPE inside attention. The query and key are rotated after their projections and right before the dot product. The value is never rotated, so the content passed between tokens does not depend on position.

Values are not rotated. RoPE shapes the matching scores, while the values supply the content to blend. Applying it inside every attention layer makes position available at each comparison.

The rotation as one matrix

If you want to write the whole rotation as one matrix for a 64-wide head, it is a 64×6464 \times 64 grid that is almost entirely zeros, with small 2×22 \times 2 rotation blocks down the diagonal. Each block rotates one pair and leaves every other pair alone. For a 64-wide head that is 32 blocks, and 3,968 of the 4,096 entries are zero.

THE ROTATION FOR POSITION m AS ONE 8 × 8 MATRIX: 2 × 2 BLOCKS ON THE DIAGONALc0−s0000000s0c000000000c1−s1000000s1c100000000c2−s2000000s2c200000000c3−s3000000s3c3ci = cos(m θi), si = sin(m θi)For a 64-wide head the matrix is 64 × 64,with 32 blocks and 3,968 zeros out of 4,096.Code never builds it. It computesq′ = q · cos + rotate_half(q) · sindirectly, using precomputed cos and sin tables.each block turns one pairand ignores the rest
Figure 1.40The rotation for position m written as a matrix, for a toy 8-wide head. Each orange block rotates one pair by its own angle; everything off the blocks is zero.

Real code never builds that matrix, because multiplying by thousands of zeros is wasted work. It multiplies by precomputed tables of cos⁡(mθi)\cos(m\theta_i) and sin⁡(mθi)\sin(m\theta_i) directly, using a little helper called rotate_half, which Unit II walks through line by line. The answer is identical.

#Section 31Far-Apart Tokens Get a Weaker Pull

RoPE has a pleasant side effect. Imagine a query and a key with exactly the same content, so that without rotation their score would be as high as possible. As the distance between them grows, the fast pairs end up pointing in all sorts of directions relative to each other, and their contributions to the dot product partly cancel out. The slow pairs still agree, but there are fewer of them.

The illustrated average over equally weighted pairs tends to decrease with distance, with oscillations. Learned queries and keys need not follow a monotonic decay.

AVERAGE ROPE SCORE OF TWO IDENTICAL VECTORS VS DISTANCE (HEAD SIZE 64, BASE 10,000)distance n − mscore ÷ maximum1: 0.9716: 0.61128: 0.280128256384512wobbles, but trends down:far tokens pull a bit less
Figure 1.41The average score of two identical vectors under RoPE as their distance grows. It starts at the maximum, wobbles, and drifts down.

That is a sensible default for language, where nearby words usually matter more, and the model can still overcome it: a query and key with strongly matching content in the slow pairs can attend across thousands of tokens. The RoFormer paper called this long-term decay.

#Section 32Beyond the Training Length

Beyond training length, slow pairs can enter angles the model has never learned to interpret. Being able to compute those angles does not establish reliable long-context behavior.

Position interpolation compresses the position range before rotation. Chen and colleagues proposed it in 2023. It keeps long-context angles closer to familiar ones but changes nearby gaps too, so the model needs adaptation and evaluation.

ANGLES SEEN BY THE SLOWEST PAIR (θ = 0.000133), TRAINED ON 1,024 TOKENStrained, 1,024 tokens0.136 radrun on 4,096 tokens0.546 radinterpolated: m ÷ 40.137 radedge of what training sawnever seen: quality breaks
Figure 1.42The angles the slowest pair sees. Training covered 0 to 0.136 radians. Running on four times the length pushes it to 0.546, unseen territory; dividing positions by four squeezes it back inside.

Interpolation slows every pair down equally, including the fast ones that did not need it, which blurs their fine view of nearby words. Better methods, NTK-aware scaling and YaRN, slow the pairs unevenly, leaving fast pairs nearly alone and stretching the slow ones the most. Unit II compares them in detail.

Learned (Part III) Sinusoidal (Part IV) RoPE (Part V)
Acts on the input, once the input, once qq and kk, in every layer
Parameters Tmax⁡×dmodelT_{\max} \times d_{\text{model}} none none
Relative position learned indirectly implicit, blurred by adding exact, by construction
Mixes into content? yes yes no (vv and xx untouched)
Longer than training impossible without new rows computable, untrained stretch with interpolation plus short training

That last row, plus the exact relative behaviour and zero parameters, is why RoPE won.

Sharp edges of RoPE

Never rotate v. Only queries and keys get rotated. If the values are rotated too, the content passed between tokens depends on absolute position, and output quality drops in confusing ways. If outputs drift with absolute position, check this first.

Which numbers form a pair? Some code pairs neighbours (entry 0 with entry 1, 2 with 3). Other code pairs the first half of the head with the second half (entry 0 with entry 32 in a 64-wide head). Both train equally well, but weights trained one way give garbage in code written the other way. Unit II shows the conversion.

Rotated keys in the cache. During generation (Part XI), old keys are stored already rotated. The new token must be rotated by its true position, which is the number of tokens already stored, not 0.

Partial rotary. Some models, such as GPT-NeoX and Phi, rotate only part of each head and leave the rest alone. Rotating the whole head breaks them. Read the config's rotary fraction before porting.

Precision of the angles. Angles get large at long positions. Computing cos⁡\cos and sin⁡\sin in 16-bit precision loses accuracy exactly where you need it. Precompute the tables in 32-bit.