RoPE, Properly
Rotary positions must match the saved model. Small convention changes can load successfully and still change its answers. Follow pairing, tables, cached positions, and context scaling through the implementation.
#Section 1Where RoPE Lives
RoPE rotates query and key pairs so their positional comparison depends on the gap. Finch-24 replaces the learned position table with these rotations inside attention.
Project the input into queries, keys, and values, then reshape into heads. Apply RoPE to query and key pairs. Cache the rotated keys and unrotated values before attention combines them.
Three details cause most RoPE bugs. RoPE comes after the reshape into heads, because each head’s 64 numbers are rotated as 32 pairs of their own. The cache stores keys already rotated, so they never need rotating again. And values are never rotated at all. Also, the token embeddings are no longer touched by any position information, and there is no position table, so Finch-24’s context of 4,096 is a training choice, not a table size.
#Section 2The Frequency Table and the Base
Every pair in a head turns at its own speed, and all 32 speeds come from one number in the config, the base, called rope_theta in Hugging Face configs:
is the rotation speed of pair in radians per position, and is its wavelength, the number of positions it takes to make one full turn. In code the speeds are usually called inv_freq and computed in one line:
inv_freq = 1.0 / (base ** (torch.arange(0, 64, 2).float() / 64)) # (32,) speedsFast pairs wrap around within the context; slow pairs sweep only part of a circle. Together they provide position information at several scales.
Raising the base slows more pairs, changing the available long-distance signal. Match the checkpoint's base rather than treating it as an interchangeable default.
#Section 3Build cos and sin Once, Look Them Up Forever
The rotation angle for a pair depends only on the position and the pair's speed, , never on the text. So code computes and for every position once, at start-up, and stores them as two tables of shape . During the forward pass it looks up the rows for the positions it needs. Each table has 64 columns rather than 32 because each pair's value is stored twice, once for each of its two members, in the order the rotation code expects.
Compute angles in higher precision before converting the final sine and cosine values. Large positions amplify low-precision angle errors. Ensure tables cover the positions inference will use.
#Section 4Pairing Conventions and rotate_half
RoPE rotates numbers in pairs. But which two numbers in a 64-wide head form a pair? There are two conventions, and mixing them up is one of the most common bugs when porting a model.
Interleaved pairing puts neighbours together: dimension 0 with 1, 2 with 3, and so on. That is how the RoFormer paper wrote it and how Meta's original Llama code implements it, by viewing each head as 32 complex numbers. Half-split pairing puts dimension with dimension : the first half of the head with the second half. That is what the Hugging Face transformers library does.
Both conventions produce equally good models, because the projection matrices learn to put matching information into whichever dimensions get rotated together. The trouble is that a checkpoint trained with one convention gives nonsense in code written for the other. Conversion scripts fix this by permuting the rows of the and weights so that dimensions that were neighbours end up half a head apart.
rotate_half, step by step
The half-split convention leads to a neat trick that avoids building any rotation matrix. Write the head as two halves, (the first 32 numbers) and (the last 32). Define
Here means entry-by-entry multiplication. rotate_half and the sine/cosine tables must use the same coordinate pairing, illustrated below.
Now multiply and add: , , and the sum is . Check pair (0, 2) the long way, rotating by 1 radian: . It matches.
def rotate_half(x):
x1, x2 = x.chunk(2, dim=-1) # first and second half of the head
return torch.cat([-x2, x1], dim=-1)
def apply_rope(q, k, cos, sin): # q: (B, H, T, 64), cos/sin: (T, 64)
return q * cos + rotate_half(q) * sin, k * cos + rotate_half(k) * sinThat is the actual code found in most model implementations, and it does exactly what Chapter 1's block-diagonal rotation matrix does, with two multiplications and an addition instead of a matrix that is 97% zeros.
#Section 5Positions at Decode Time
During generation (Chapter 1, Part XI), tokens arrive one at a time and old keys sit in the cache, already rotated. Each new token must be rotated by its true position in the whole text. If the prompt had five tokens at positions 0 to 4, the first generated token is at position 5, then 6, then 7.
It sounds too obvious to get wrong, and it is one of the most common bugs in hand-written inference loops. If the code forgets the offset and rotates every new token as if it were at position 0, the relative distance between the new query and the cached keys is wrong for every pair. The model behaves as though each new word were the first word of the text, and output falls apart within a few tokens.
Left padding causes the same bug in disguise. When prompts of different lengths are batched with padding on the left, the first real token of a short prompt sits at index 3 or 4. If positions are taken from the raw index, every real token is rotated by the wrong amount. Derive position_ids from the attention mask, counting only real tokens.
#Section 6Stretching to Longer Contexts
Proof by picture: only distance matters
Before stretching anything, it is worth seeing the relative-position property directly. Put the same query content at every position and the same key content at every position, and compute the score for every pair of positions . With RoPE, every diagonal of the grid, every set of cells with the same , is one solid colour: pairs the same distance apart get exactly the same score, wherever they sit. With learned absolute positions added to the content instead, the colours change along each diagonal, because the score also depends on absolute position.
Three ways to stretch
A model trained on 4,096 tokens has never seen the angles its slow pairs reach at 16,384. Chapter 1 introduced position interpolation: divide every position by the stretch factor before rotating, which is the same as dividing every pair's speed by . It works, but it slows the fast pairs too, and the fast pairs did not need it: they wrapped around thousands of times during training and have seen every angle. Slowing them blurs the model's fine view of nearby words.
NTK-aware scaling, proposed in 2023 by a Reddit user writing as bloc97, changes the base instead of the positions: . For Finch-24 stretching by , the base goes from 10,000 to about 41,800. Because each pair's speed depends on the base raised to a power that grows with , pair 0 is not slowed at all, the slowest pair is slowed by exactly , and pairs in between are slowed smoothly in between.
YaRN, published by Bowen Peng and colleagues in 2023, makes the split explicit by wavelength. Pairs whose wavelength is much shorter than the original context (more than 32 full turns within it) are left alone. Pairs whose wavelength is longer than the original context are fully interpolated, slowed by . Pairs in between are blended linearly. YaRN also scales the attention logits slightly, by a factor that grows with , to counter the way longer contexts flatten softmax. For Finch-24 at , pairs 0 to 10 keep their speed, pairs 23 to 31 are slowed by 4, and pair 16 is slowed by a factor of about 2.6.
| Method | Fast pairs | Slow pairs | Extra training | Notes |
|---|---|---|---|---|
| Position interpolation | slowed by | slowed by | short fine-tune | simple, blurs local detail |
| NTK-aware | unchanged | slowed by | works even without, better with | one new base number |
| YaRN | unchanged | slowed by | short fine-tune | plus a small logit scale |
| Llama 3.1 scaling | unchanged (wavelength < 2,048) | slowed by 8 (wavelength > 8,192) | long-context training | blend in between |
Meta’s Llama 3.1 used its own variant of the same idea to go from 8,192 to 128,000 tokens: wavelengths shorter than 2,048 are untouched, wavelengths longer than 8,192 are divided by a factor of 8, and those in between are blended, followed by a substantial long-context training phase. All of these methods change which angles long texts produce; none of them removes the need for at least some training on long text.
Sharp edges of RoPE in practice
Rotating v. Rotating values as well as queries and keys makes the content passed between tokens depend on position. The model runs, and quality quietly drops.
Converted checkpoints. Moving weights between Meta’s interleaved format and Hugging Face’s half-split format requires permuting the Q and K projection rows. Skip it and the model talks nonsense. Use the conversion script that ships with the model.
Partial rotary. GPT-NeoX, Phi and some others rotate only part of each head, a fraction set in the config (rotary_pct or partial_rotary_factor). Rotating the whole head breaks them.
Scaling config fields. Long-context checkpoints carry a rope_scaling entry in their config (type, factor, and for Llama 3.1 the low and high frequency factors). Code that ignores it computes the original, unstretched speeds and degrades past the original context.