Highlights

Contents

Part I
01

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.

YOU ARE HEREMODERN DECODER BLOCKATTENTION HALFRMSNormq, k, v projRoPE (q, k)GQA: 8 q, 2 kvSDPAFlash kernelo proj+MLP HALFRMSNormgate, up projSiLU(g) ⊙ udown proj+residual stream: x + Attn(Norm(x)), then h + MLP(Norm(h))what changed since GPT-2: positions, norm, MLP, K/V sharing, the attention kernel, and no biases

#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.

ONE FINCH-24 ATTENTION LAYER WITH EVERY SHAPE (B = BATCH, T = TOKENS)x(B, T, 512)q_proj(B, T, 512)k_proj(B, T, 128)v_proj(B, T, 128)view + transpose(B, 8, T, 64)view + transpose(B, 2, T, 64)view + transpose(B, 2, T, 64)apply RoPE to q and k (cos, sin: T × 64)KV cache: append rotated k and plain vSDPA (Part V): softmax(q kᵀ / 8) v → (B, 8, T, 64) → reshape (B, T, 512) → o_projonly q and kare rotated
Figure 2.1RoPE inside one Finch-24 attention layer, with the shape of every tensor. Rotation happens after the projections and head reshape, on queries and keys only, before the cache and before attention.

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:

θi=base−2i/dhead,λi=2πθi\theta_i = \text{base}^{-2i/d_{\text{head}}}, \qquad \lambda_i = \frac{2\pi}{\theta_i}

θi\theta_i is the rotation speed of pair ii in radians per position, and λi\lambda_i 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:

python
inv_freq = 1.0 / (base ** (torch.arange(0, 64, 2).float() / 64))   # (32,) speeds

Fast pairs wrap around within the context; slow pairs sweep only part of a circle. Together they provide position information at several scales.

WAVELENGTH OF EACH OF THE 32 PAIRS IN A 64-WIDE HEAD (LOG SCALE), CONTEXT 4,096101,0001e51e7context 4,096pair 0pair 31grey: base 10,000 (9 pairs never complete a turn) orange: base 500,000 (16 pairs)
Figure 2.2Wavelengths of the 32 pairs of a 64-wide head for two bases, on a log scale, against a 4,096-token context. Raising the base from 10,000 to 500,000 pushes more pairs into the slow group that never wraps around.

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, m θim\,\theta_i, never on the text. So code computes cos⁡(mθi)\cos(m\theta_i) and sin⁡(mθi)\sin(m\theta_i) for every position once, at start-up, and stores them as two tables of shape (Tmax⁡,dhead)(T_{\max}, d_{\text{head}}). 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.

PRECOMPUTED TABLES: cos(m θ_i) AND sin(m θ_i), POSITIONS 0 TO 47, 32 PAIRSinv_freq = 1 / base ** ( arange(0, 64, 2) / 64)m = arange(T_max)ang = outer(m, inv_freq)ang = cat([ang, ang], -1)cos, sin = ang.cos(), ang.sin()# both (T_max, 64), fp32cossinm = 20computed once at start-up, looked up by position forever
Figure 2.3The few lines that build the cos and sin tables, and the tables themselves for positions 0 to 47. Fast pairs on the left change from row to row; slow pairs on the right barely change. The outlined row is what a token at position 20 uses.

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 ii with dimension i+32i + 32: the first half of the head with the second half. That is what the Hugging Face transformers library does.

WHICH DIMENSIONS ROTATE TOGETHER? TWO CONVENTIONS, 8-WIDE TOY HEADinterleavedoriginal paper, Meta Llama code01234567half-split (rotate_half)Hugging Face transformers01234567same model quality, incompatible weights
Figure 2.4Two ways to choose the pairs in an eight-wide toy head. Interleaved pairs neighbours; half-split pairs each dimension with the one half a head away. Both train equally well, but their weights are not interchangeable.

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 WQW_Q and WKW_K 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, x1x_1 (the first 32 numbers) and x2x_2 (the last 32). Define

rotate_half([x1,x2])=[−x2, x1],q′=q⊙cos⁡+rotate_half(q)⊙sin⁡\text{rotate\_half}([x_1, x_2]) = [-x_2,\ x_1], \qquad q' = q \odot \cos + \text{rotate\_half}(q) \odot \sin

Here ⊙\odot means entry-by-entry multiplication. rotate_half and the sine/cosine tables must use the same coordinate pairing, illustrated below.

Now multiply and add: q⊙cos⁡=[0.5403,2.0000,1.6209,3.9998]q \odot \cos = [0.5403, 2.0000, 1.6209, 3.9998], rotate_half(q)⊙sin⁡=[−2.5244,−0.0400,0.8415,0.0200]\text{rotate\_half}(q) \odot \sin = [-2.5244, -0.0400, 0.8415, 0.0200], and the sum is q′=[−1.9841,1.9599,2.4624,4.0198]q' = [-1.9841, 1.9599, 2.4624, 4.0198]. Check pair (0, 2) the long way, rotating (1,3)(1, 3) by 1 radian: (1⋅cos⁡1−3sin⁡1, 1⋅sin⁡1+3cos⁡1)=(−1.9841,2.4624)(1 \cdot \cos 1 - 3 \sin 1,\ 1 \cdot \sin 1 + 3 \cos 1) = (-1.9841, 2.4624). It matches.

q′ = q · cos + rotate_half(q) · sin FOR A 4-WIDE HEAD AT POSITION m = 1 (θ = 1, 0.01)q1234cos row0.54031.00000.54031.0000sin row0.84150.01000.84150.0100rotate_half(q) = [−x₂, x₁]-3-412q · cos0.54031.99991.62093.9998rotate_half(q) · sin-2.5244-0.04000.84150.0200q′ = sum-1.98411.95992.46244.0198pair (0, 2) rotated by 1 rad directly: (1·cos 1 − 3·sin 1, 1·sin 1 + 3·cos 1) = (−1.9841, 2.4624) ✓
Figure 2.5rotate_half on a four-wide head at position 1. Multiplying q by the cos row, rotate_half(q) by the sin row, and adding gives exactly the pairwise rotation.
python
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) * sin

That 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 64×6464 \times 64 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.

position_ids=cache_len+arange(new_tokens)\text{position\_ids} = \text{cache\_len} + \text{arange}(\text{new\_tokens})

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.

AT DECODE, A NEW TOKEN’S POSITION IS THE CACHE LENGTH, NOT ZEROprompt (prefill)m=0m=1m=2m=3m=4new tokens, correctm=5m=6m=7new tokens, bugm=0m=0m=0position_ids =cache_len + arange(n)every new wordlooks like the first
Figure 2.6Prompt keys are rotated for positions 0 to 4 and cached. New tokens must continue at 5, 6, 7. If they are rotated as position 0, every relative distance is wrong.

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 (m,n)(m, n). With RoPE, every diagonal of the grid, every set of cells with the same n−mn - m, 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.

SCORE OF q AT POSITION m AGAINST k AT POSITION n, SAME CONTENT EVERYWHERE (12 × 12)RoPE: constant along diagonalslearned absolute: no patternevery cell with the same n − m has the same scorethe score also depends on where the pair sits
Figure 2.7Scores for identical content at every position. Under RoPE each diagonal (fixed n − m) is a single value. With learned absolute positions the pattern is irregular.

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 ss before rotating, which is the same as dividing every pair's speed by ss. 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: base′=base⋅sdhead/(dhead−2)\text{base}' = \text{base} \cdot s^{d_{\text{head}} / (d_{\text{head}} - 2)}. For Finch-24 stretching by s=4s = 4, 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 ii, pair 0 is not slowed at all, the slowest pair is slowed by exactly ss, 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 ss. Pairs in between are blended linearly. YaRN also scales the attention logits slightly, by a factor that grows with ln⁡s\ln s, to counter the way longer contexts flatten softmax. For Finch-24 at s=4s = 4, 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.

HOW MUCH EACH PAIR IS SLOWED TO STRETCH 4,096 → 16,384 (s = 4), HEAD SIZE 64pair i (fast → slow)new speed ÷ old speedlinear (PI)NTK-awareYaRN08162431unchanged÷ 4keep the fast pairs sharp, stretch the slow ones
Figure 2.8How much each pair's speed is reduced to stretch 4,096 tokens to 16,384. Linear interpolation slows every pair equally; NTK-aware scaling slows smoothly from none to four times; YaRN leaves fast pairs alone, fully stretches slow ones, and blends in between.
Method Fast pairs Slow pairs Extra training Notes
Position interpolation slowed by ss slowed by ss short fine-tune simple, blurs local detail
NTK-aware unchanged slowed by ss works even without, better with one new base number
YaRN unchanged slowed by ss 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.

PARTIAL ROTARY: ROTATE ONLY THE CONFIGURED SLICEbefore10012345after01-1023454 rotated dimensions4 untouched dimensions90°copyhead width alone does not tell you how much to rotate
Figure 2.9An illustrative eight-wide head with a rotary fraction of 0.5 rotates four dimensions and copies four unchanged. Two interleaved pairs each turn by 90 degrees for this arithmetic demonstration; actual RoPE pairs use their own frequencies.

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.