RoPE, Visualized


English中文

Attention on its own doesn't care about order: shuffle "I love cats" into "cats love I" and every pair of words gets exactly the same score as before. So every LLM needs a position encoding to tell it where each word sits.

The earliest approach adds a fixed vector for each position to the word there, as if tagging every word with "I am at position t". But then adding "Oh" at the start shifts every word back by one, and the score between "cats" and "love" changes, even though they are still right next to each other. RoPE (Rotary Position Embedding) takes a different route: instead of tagging positions, it rotates q and k by an angle set by each word's position, so the score between two words depends only on how far apart they are.

Proposed by Jianlin Su et al. in 2021, it is now used by mainstream open models such as LLaMA, Qwen and Mistral. It also brought a benefit nobody planned for: because positions became angles, a model's context can be stretched after training. The first LLaMA could only read 2K tokens; scale its RoPE angles down proportionally, and with under 1,000 steps of fine-tuning it reads 32K.

This post starts from the attention score and walks you through reinventing RoPE yourself, step by step. Most figures can be dragged, so try them yourself as you read. For a refresher on Transformers, see my Transformer notes, written for Stanford CS224N.

1. Recap: the attention score

This post is built around one example sentence: "I love cats".

Three words, at positions 0, 1 and 2:

Position 0 1 2
Sentence I love cats

In a Transformer's attention, every word produces three vectors: q (query, "what am I looking for"), k (key, "what do I have"), and v (value, "my content").

Take "cats" and "love": the score of "cats" looking at "love" is qcats · klove (the q of "cats" dotted with the k of "love"), a single number measuring how much "cats" attends to "love". "cats" takes its own q and dot-products it with the k of every word in the sentence ("I", "love", and itself), giving 3 scores. Applying a softmax to these 3 scores gives 3 non-negative weights that add up to 1. Using these weights, the weighted sum of the 3 words' v vectors is the output of "cats" for this layer.

Throughout this post, "score" always means this q·k.

In practice the scores are also divided by √dhead (dhead = the per-head dimension) before the softmax. This keeps the dot products from getting too large when dhead is large; otherwise the softmax would put almost all the weight on a single word, and its gradients during training would become tiny. We leave this step out here.

2. Why we need position encoding

Without a position encoding, q and k are computed from the word vectors alone (in deeper layers they also mix in other words' content), and nothing in them depends on where a word sits. As a result, if you shuffle "I love cats" into "cats love I", every pair of words gets exactly the same score as before ("cats" looking at "love", "love" looking at "I", and so on), just in a different arrangement. The model cannot tell these two sentences apart.

So we have to tell the model "which position each word is at". Any method that does this is called a position encoding.

Strictly speaking, the causal mask used in GPT-style models (each word can only see the words before it) does bring in a little order information on its own, so "the scores stay exactly the same" only holds without the mask. This doesn't affect anything in this post.

3. The problem with absolute position encoding

3a · How it works: add a vector per position

When the Transformer first came out, it used absolute position encoding (absolute PE), and so did GPT-2 later on. Here is how it works.

Prepare a fixed vector pt for each position t, the same length as a word embedding. Before the first layer, add it to the embedding of the word at that position:

input = embedding(word) + p_t

For I love cats:
  I    → embedding(I)    + p0
  love → embedding(love) + p1
  cats → embedding(cats) + p2

Every later layer only sees this "already added" vector. pt comes in two flavors: the original Transformer computes it from sines and cosines of many frequencies (not trained); GPT-2 just treats it as a table with one row per position and learns it. Either way, pt is added only once, at the input, before the first layer.

3b · The problem: scores track "which position", not "how far apart"

Put one more word at the start: "Oh I love cats".

Position 0 1 2 3
Position encoding p0 p1 p2 p3
Sentence 1 I love cats
Sentence 2 Oh I love cats

In both sentences "love" sits right before "cats", but in the second one both words have moved back by one, so the vectors added to "love" and "cats" change from p1, p2 ("love" at position 1, "cats" at position 2) to p2, p3 ("love" at position 2, "cats" at position 3). As a result the score of "cats" looking at "love" differs between the two sentences (Section 6 works it out with real numbers), even though their relationship hasn't changed at all.

The same thing in formulas. Say "cats" is at position m and "love" at position n, with word vectors xm and xn; Wq and Wk are the weight matrices that turn the input into q and k. With absolute PE, q = Wq(xm + pm) and k = Wk(xn + pn). Expanding the dot product:

q·k = (x_m + p_m)ᵀ W_qᵀ W_k (x_n + p_n)
    = x_mᵀ W_qᵀ W_k x_n + x_mᵀ W_qᵀ W_k p_n
      + p_mᵀ W_qᵀ W_k x_n + p_mᵀ W_qᵀ W_k p_n

Add "Oh" at the start and m goes from 2 to 3, n from 1 to 2: pm and pn in the last three terms become different vectors, and only the first term stays the same. Each of the two middle terms contains only one word's position, so it cannot depend only on how far apart the two words are. That is why, with absolute PE, the score depends on where each word itself sits.

Key pointWhat we actually care about is the relationship between "love" and "cats": "love" comes right before "cats" (one position apart). Which exact position "love" happens to sit at in the sentence shouldn't change how much "cats" attends to "love". With absolute PE, the model has no built-in notion of "one position apart". It has to learn it from training data separately for each pair of positions (0 and 1, 1 and 2, 57 and 58, …), so at positions beyond the training length it never learned these patterns. The sin/cos version can still compute a vector for any position, but quality usually drops sharply there; GPT-2's learned table simply has no row past its maximum length.

4. RoPE is a relative position encoding

What we really want is a relative position encoding: the score between two words should depend only on how far apart they are, not on where they sit in the sentence.

RoPE is one such relative position encoding. It does the same job as absolute PE (telling the model where each word is), just differently.

4a · The recipe: multiply q and k by a position-dependent matrix

In every attention layer, after computing each word's q and k, multiply them by a matrix chosen by that word's position:

word at position m:  q  →  R(m) · q
word at position n:  k  →  R(n) · k
v is left alone.

R(m) is a dhead × dhead matrix (dhead = per-head dimension), determined only by the position m. It is fixed, not trained.

In "I love cats": "cats" is at position 2, so its q becomes R(2)·qcats; "love" is at position 1, so its k becomes R(1)·klove. Then the score is computed as usual.

4b · Why the score depends only on relative distance

R is chosen to satisfy one property: R(m)ᵀ R(n) = R(n − m). So after multiplying, the score is:

score = (R(m) q) · (R(n) k)
      = qᵀ R(m)ᵀ R(n) k
      = qᵀ R(n − m) k

m and n only appear as "n − m", i.e. the score depends only on how far apart the two words are:

  • "I love cats": "cats" at position m = 2, "love" at position n = 1, n − m = −1
  • "Oh I love cats": "cats" at position m = 3, "love" at position n = 2, n − m = −1

Same difference, same R(−1), so "cats" looks at "love" with the same score.

RoPE makes the score depend only on relative distance, but that does not mean it works out of the box on texts longer than those seen in training. Beyond the training length the model meets relative distances (and angle combinations) it never saw, and quality drops sharply there too. Real long-context models add methods such as position interpolation or NTK / YaRN scaling on top of RoPE.

4c · Compared with absolute PE

Absolute PE RoPE
How it enters Add a position vector to the input: xt + pt, once In every attention layer, multiply qt, kt by a matrix R(t)
What it affects q, k, v and the MLP all see it (position is mixed into the residual stream) Only q and k, i.e. only the scores
Score depends on Each word's own position How far apart the two words are

So the question becomes: what matrix R(m) has this property? The next section builds it in 2D.

5. Designing the matrix: start in 2D

We need a matrix R(m) with R(m)ᵀR(n) = R(n − m). Start with the smallest case, dhead = 2. The idea is to rotate q by an angle proportional to its position. Two rotations combine by simply adding or subtracting their angles, which is exactly the property we want.

5a · Rotation: turning an arrow by an angle

With dhead = 2, q is just two numbers (a, b), i.e. an arrow in the plane (from the origin to (a, b)). If this word is at position m, RoPE rotates it counterclockwise by m·θ. θ is a fixed angle: each step to the next position adds another θ.

▶ Playing with the figureWhat this figure shows: the larger the position m, the more q turns, but its length stays the same.
Dashed gray is the original q, orange is the rotated q, and the thin arc is the angle turned, m·θ. At position 0, m·θ = 0 and the arrow doesn't move. However it rotates, the arrow's length never changes (it is drawn with length 1 only for clarity; a real q can have any length).
The purple and pink short arrows are the x axis (1,0) and the y axis (0,1) after rotation; they're used in 5b.
Try it: drag "Position m" and watch the orange arrow turn further while its length stays the same.
Rotation angle = m · θ = 30°
…

5b · Writing the rotation as a matrix

Written as a matrix, "rotate by mθ" is:

R(m) = [ cos mθ   −sin mθ ]
       [ sin mθ    cos mθ ]
▶ Reading the figureHow to remember the matrix: its two columns are where the two axes land after rotating by φ (φ = mθ).
Dashed = the original axes, solid = after rotating by φ. Same color and same letter (x and x′, y and y′) = the same axis before and after. The purple and pink short arrows in 5a are exactly these two rotated axes.
x: (1, 0) x′: (cos φ, sin φ) sin φ cos φ φ y: (0, 1) y′: (−sin φ, cos φ) −sin φ cos φ φ
       x axis→  y axis→
R(m) = [ cos φ   −sin φ ]
       [ sin φ    cos φ ]
  • x axis rotated by φ = x′ → (cos φ, sin φ): right by cos φ, up by sin φ
  • y axis rotated by φ = y′ → (−sin φ, cos φ): left by sin φ (hence the minus), up by cos φ

So R·(a, b) = a·column 1 + b·column 2 = (a cos φ − b sin φ, a sin φ + b cos φ).

Keep the coordinates (a, b), but lay them out on the two rotated axes: the point you reach is the vector rotated by φ.

Geometrically, multiplying a 2D vector by R(m) rotates it by mθ around the origin without changing its length — hence "rotary". R(m)ᵀR(n) = R(n − m) now makes sense: rotating back by m and then forward by n is a net rotation of n − m.

Where does the formula (a cos − b sin, a sin + b cos) come from? It can also be derived with polar coordinates:

The arrow has length r and direction α, so a = r cos α, b = r sin α. After rotating by φ the direction becomes α + φ, with the same length:

new a = r cos(α+φ) = r cosα cosφ − r sinα sinφ
      = a·cosφ − b·sinφ
new b = r sin(α+φ) = r sinα cosφ + r cosα sinφ
      = a·sinφ + b·cosφ

5c · Turn together, and the angle only sees m − n

  • Dot product = |q|·|k|·cos(angle between them), so it is set by two things: the lengths and the angle.
  • Lengths: rotation doesn't change length, so |q| and |k| depend only on content, not on position.
  • Angle: it depends only on where the two arrows point relative to each other, not on where each one points. For q at 0° with k at 30°, or q at 100° with k at 130°, the angle is 30° either way, and the dot product is identical.
  • So how far q rotated (m·θ) or k rotated (n·θ) doesn't matter on its own; only their difference (m − n)·θ changes the angle, and with it the dot product.
▶ Playing with the figureWhat this figure shows: when both arrows rotate together, the angle between them stays the same, so the dot product stays the same.
Dashed arrows are q and k before rotation. They are set by content alone and never move when you drag the sliders; the angle between the two dashed arrows is the α − β in the formula below. Solid arrows are q rotated from its dashed arrow by m·θ and k rotated from its dashed arrow by n·θ. The gray arc is the angle between the two solid arrows, which equals (α − β) + (m − n)·θ.
Try it: drag m and n to any values, then click "shift both later". Wherever you start, both solid arrows turn together, the arc keeps its size, and the dot product stays the same. Each click is like adding one more word at the start of the sentence; click several times and you have added several words. Conversely, drag just one slider and m − n changes; only then do the angle and the dot product change too.
Relative distance m − n = 3
Dot product q·k = 0
…

Why "only m − n" lands on this expression: let q's original direction be α and k's be β (both length 1).

after rotation: q's direction = α + m·θ
                k's direction = β + n·θ
dot product = cos(difference of directions)
            = cos( (α + mθ) − (β + nθ) )
            = cos( (α − β)  +  (m − n)·θ )
where α − β depends only on content,
  and (m − n)·θ only on the relative distance

A side note: rotation is not the only option. For example, you could first stretch q and k with the same fixed matrix and then rotate them, and the score would still depend only on n − m. But that extra step is redundant: q = Wqx and k = Wkx are already trainable matrix multiplications, so Wq and Wk can learn such a stretch on their own. So RoPE uses rotation alone, which has another benefit: it does not change the lengths of q and k, so position only affects their direction.

6. Worked example: "I love cats", with words added in front

If we add one or more words in front of "I love cats", how does the score of "cats" looking at "love" change?

Sentence I love cats Oh I love cats Oh well I love cats Oh well so I love cats
Positions of "love", "cats" 1, 2 2, 3 3, 4 4, 5
Absolute PE 0.97 0.46 0.03 0.07
RoPE 0.84 0.84 0.84 0.84

The two words stay right next to each other throughout. With absolute PE the score keeps changing; with RoPE it stays the same.

Setup: dhead = 2, Wq = Wk = identity (q and k equal the input), the word vector of "cats" is (1, 0) and that of "love" is (0, 1). Absolute PE uses the original Transformer's sin/cos formula, which in 2D is pt = (sin t, cos t); RoPE's speed θi = 10000−i/(dhead/2) has only i = 0 in 2D, which means turning 1 radian (about 57°) per position.

7. Going to higher dimensions

Section 5 only covered dhead = 2. How do we rotate when there are more dimensions? Start with 3D.

7a · 3D: rotate one plane, leave the other dimensions alone

Take an arrow (x, y, z) in 3D space and rotate it around the z axis.

▶ Playing with the figureWhat this figure shows: when the arrow rotates around the z axis, only x and y change; z stays the same.
Try it: drag "Rotation angle" or click "Auto-rotate": the arrow's tip moves along a horizontal circle at a constant height, and its shadow on the xy plane (dashed) is just an ordinary 2D rotation. Drag the canvas to change the view.
Key pointIn other words, this 3D rotation only turns the xy plane, and z takes no part.
More dimensions work the same way: every rotation turns some 2D planes and leaves the remaining directions fixed (7d makes this precise). So for a q with dhead dimensions, we just split it into 2D planes and rotate each plane on its own.

7b · Cutting into planes: pairing and speeds

Here is how the split works and how much each plane turns. Take one token's q in some head (length dhead); the token is at position m:

① Pair up: group the dhead dimensions into dhead/2 pairs (so dhead must be even), and treat each pair as a point in its own plane.

  • The simplest choice pairs neighbours: (0, 1), (2, 3), (4, 5), … This is what the RoFormer paper does. Many implementations instead pair "first half with second half"; 8b explains why. Whichever pairing you use, q and k must use the same one.
  • The two numbers of pair i are written (ai, bi) = (q[2i], q[2i+1]). For example, if q = (0.3, −1.2, 0.5, 0.8, …), pair 0 is (a0, b0) = (0.3, −1.2) and pair 1 is (a1, b1) = (0.5, 0.8).

Below is dhead = 8: cells of the same color joined by a line form a pair.

② Each pair has a fixed speed: θi = base−i/(dhead/2), where base is a constant. Pair 0 is the fastest; later pairs get slower. θ is fixed and not trained; only the position m and q itself vary.

③ Rotate pair i by m·θi: with φ = m·θi,

new_a = a·cos φ − b·sin φ
new_b = a·sin φ + b·cos φ

④ Same for k, using k's own position n. v is not rotated.

About base: the original paper uses 10000; recent long-context models often raise it (LLaMA 3 uses 500000). A larger base slows down the later pairs (pair 0 always stays at 1), so the slowest pairs don't complete a full turn even over very long distances, and positions far apart don't come back around to similar angles.

7c · 4 planes, 4 clocks at different speeds

dhead = 8, pairing neighbours into 4 pairs: (0,1), (2,3), (4,5), (6,7). Pair i's speed θᵢ = 10000−i/4: 1, 0.1, 0.01, 0.001 radians per position. Each clock draws only this pair's two numbers of q and k: in plane 0 the q arrow is (q[0], q[1]) and the k arrow is (k[0], k[1]); plane 1 uses (q[2], q[3]) and (k[2], k[3]), and so on.

▶ Playing with the figureWhat this figure shows, two things. Try it:
  • Click "shift both": m and n change together, m − n stays the same, the angle between q and k stays the same in all 4 clocks, every bar stays the same, and so does the total.
  • Drag only m: q turns at a different speed in each clock; plane 0 turns fastest and plane 3 barely moves.
m − n = 3

The total dot product is the sum of the 4 planes' dot products:

Why different speeds per pair:

  • If every pair used the same speed θ, a full turn would bring everything back to where it started. For example, with θ = 60°, six steps make exactly 360° and every plane is back at its starting point: q at position 6 ends up exactly the same as q at position 0, so the score cannot tell whether two words are 0 apart or 6 apart.
  • A smaller θ delays the repeat, but then nearby positions blur together: with a tiny θ, one apart and two apart give almost the same angle.
  • So RoPE gives each pair its own speed, from fast to slow: fast pairs tell nearby distances apart (plane 0 above, 1 radian per position), and slow pairs, which need many positions to complete a turn, tell far distances apart (plane 3, 0.001 radians per position, thousands of positions per turn). Together, the angles of all the pairs do not all return to the start at the same time over a very long range.

7d · Is it still a rotation in high dimensions? Yes

The strict definition of a rotation: a linear map R that satisfies two conditions:

  1. It preserves every vector's length (and therefore every angle as well). This is equivalent to RᵀR = I (I is the identity matrix), and such a matrix is called orthogonal. The determinant (det) of an orthogonal matrix can only be 1 or −1: 1 is a rotation, −1 is a mirror reflection.
  2. It does no reflection, i.e. det R = 1.

The definition is the same in every dimension; "turn by an angle" is just what it looks like in 2D.

RoPE's R(m) is a block-diagonal matrix: one 2×2 rotation block per plane, zeros between blocks. Here is R(m) for dhead = 8, writing ci = cos(m·θi) and si = sin(m·θi); blank cells are 0:

0 1 2 3 4 5 6 7
0 c0 −s0
1 s0 c0
2 c1 −s1
3 s1 c1
4 c2 −s2
5 s2 c2
6 c3 −s3
7 s3 c3

Each pair takes up one 2×2 block [[ci, −si], [si, ci]] on the diagonal, and everything outside the blocks is 0. So when multiplying q, each pair only uses its own two numbers: rows 0 and 1, for example, give (c0·q[0] − s0·q[1], s0·q[0] + c0·q[1]), which is the result of rotating the pair (q[0], q[1]) by m·θ0.

Of the matrix's dhead² cells, only 2·dhead are nonzero (about 1.6% when dhead = 128). So code never builds it; it does elementwise multiply-adds with cos and sin tables instead (Section 8).

With actual numbers, below is the 8×8 matrix for the current m from 7c:

…

Why it meets the definition: each 2×2 block is orthogonal on its own and blocks don't mix, so the whole thing is orthogonal, and det = product of the blocks' dets = 1×1×1×1 = 1.

A stronger fact (a linear algebra theorem): any n-dimensional rotation, in a suitable orthonormal basis, looks like "some 2D rotation blocks + some fixed 1s". A 3D rotation always has a fixed axis (the z axis in 7a) — that is this theorem in 3D. So "split space into 2D planes and rotate each" is not an approximation or a trick in RoPE: this is the only shape a high-dimensional rotation can take. RoPE just fixes the axes (which two dimensions pair up) and chooses each plane's speed θᵢ.

Why not use a "general" high-dimensional rotation: to satisfy R(m)ᵀR(n) = R(n − m), R(m) has to be one rotation A applied m times: R(m) = Am. A can be any high-dimensional rotation, but by the theorem above, in a suitable set of axes A is just a set of 2D rotation blocks, so Am rotates each plane by m times its angle, which is exactly RoPE. The change of axes is a fixed matrix that can be folded straight into Wq and Wk. So a general high-dimensional rotation adds nothing new; RoPE simply picks the axes in advance.

7e · Position m sets how far to turn, dimension p sets which pair

The notation qm[p] has two indices:

  • The word position m: which word in the sequence this is, counting from 0 (0–4095 when sequences are at most 4096 tokens long). It decides how many steps to rotate.
  • The dimension index p: which number in the vector this is (0–7 when dhead = 8). It decides which pair the number belongs to, and therefore its speed θi. With adjacent pairing, dimension p belongs to pair ⌊p/2⌋.

Put together, the pair that qm[p] belongs to is rotated by m·θi. Take "I love cats" with dhead = 4 (two pairs), and look at how far each dimension of qcats (m = 2) and klove (n = 1) is rotated:

Dimension p 0 1 2 3
Pair 0 0 1 1
Speed θ0 θ0 θ1 θ1
qcats rotated by (m = 2) 2θ0 2θ0 2θ1 2θ1
klove rotated by (n = 1) 1θ0 1θ0 1θ1 1θ1
Difference 1·θ0 1·θ0 1·θ1 1·θ1

Within each column, q and k belong to the same pair and use the same speed; they only rotate a different number of steps, and the difference is (m − n)·θi.

A dot product multiplies the two numbers in each column and adds them up. Grouping neighbouring columns by pair gives the sum of each pair's dot product:

q·k = (q[0]·k[0] + q[1]·k[1])  +  (q[2]·k[2] + q[3]·k[3])
    =    dot product of pair 0    +    dot product of pair 1

Each pair's dot product is the dot product of two arrows in the same plane, which depends only on the difference of their angles, (m − n)·θi. So every pair depends only on m − n, and so does the score they add up to.

This is also why q and k must use the same pairing: only then do q and k in the same column of the table belong to the same pair and use the same speed, so that their difference is (m − n)·θi.

8. Where it goes, and how to implement it

8a · In every layer: after splitting heads, before the scores

▶ Reading the figureData flows top to bottom; follow the arrows. This is the pre-norm structure used by models like GPT-2 and LLaMA: each sublayer is preceded by a norm (LLaMA uses RMSNorm). The original Transformer is post-norm.
Notation:
  • B: batch size, how many sequences are processed at once
  • T: sequence length, how many tokens each sequence has
  • d: hidden size, the dimension of each token's vector
  • nhead: number of heads (d = nhead × dhead)
  • N: number of layers
  • pos: position, the position of each token, 0, 1, …, T−1
  • Wo: output projection, the matrix that merges the heads back into d dimensions
token ids (B, T)
Embedding lookup → x (B, T, d)
no position vector addedabsolute PE adds pt here
× N layers, all identical (each layer's output → next layer's input, N times)
h = LayerNorm(x)
q = h Wq, k = h Wk, v = h Wv
split heads → q, k, v are all (B, nhead, T, dhead)
q ← rope(q, pos), k ← rope(k, pos)
RoPE is herev untouched
(inference) store the rotated k and v in the KV cache
scores = q @ kᵀ / √dhead + causal mask → softmax
out = weights @ v → merge heads → Wo → x ← x + out
x ← x + MLP(LayerNorm(x))
no position in the MLP
final LayerNorm → LM head → logits
none at the output either

Where RoPE appears: q and k of every head in every layer. Nowhere else: nothing is added to the input embedding, v is not rotated, and the MLP and output layer are untouched.

Why every layer? Absolute PE is like sticking a label with the position on each word: stick it on once, and every later layer can see it. RoPE sticks no label; it only rotates q and k at the moment a layer compares two words (computes q·k). Once the comparison is done, the rotated q and k are thrown away. The next layer compares again, so it has to rotate again.

Cost: the cos/sin tables (computed from the (T, dhead/2) angle table in 8c) are computed once and shared by all layers (in code usually called freqs_cis or cos_cached / sin_cached). Each layer only does a few elementwise multiply-adds, with no learnable parameters.

Order: q = h Wq (split by head) → RoPE → q @ kᵀ. Where RoPE sits has to satisfy three things:

  • After multiplying by Wq: if you rotate h first and then multiply by Wq, Wq scrambles the rotated planes and the m − n property is lost.
  • After splitting into heads: RoPE acts on each head's own q. Each head's q has dhead dimensions, and RoPE pairs up those dhead dimensions and rotates each pair on its own.
  • Before q @ kᵀ: the whole point is to rotate the q and k used for scoring.

8b · Why code usually splits in half instead of pairing neighbours

So far we paired neighbours: (0, 1), (2, 3), … Many popular implementations (for example Hugging Face's LLaMA code and GPT-NeoX) instead pair dimension i with dimension i + dhead/2, i.e. "first half with second half":

The reason is convenience. With this pairing, all the a's sit in the first half of the vector and all the b's in the second half, so the code just slices x into two contiguous halves (x1, x2) instead of picking every other element. Mathematically nothing changes: the two conventions differ only by a reordering of dimensions, and a model trained from scratch simply learns Wq and Wk around it. What does matter: when loading pretrained weights, use the pairing the model was trained with. That is why converting Meta's original LLaMA checkpoints (adjacent pairing) to the Hugging Face format (first half with second half) permutes the q and k weights.

8c · In code: precompute the angle table

Steps ①–④ in 7b say what to do. In practice, the angle m·θi from step ③ for every word and every pair can be computed up front into an angle table: rows = word position m (0, 1, 2…), columns = pair i, each cell = m × θi, i.e. "how many radians pair i of the word at position m rotates".

Example: in "I love cats", "cats" is at position 2. Look at row 2: pair 0 rotates 2, pair 1 rotates 0.2, pair 2 rotates 0.02, pair 3 rotates 0.002. Within a row, values shrink left to right (later pairs are slower); within a column, values grow top to bottom (later words rotate more).

The table depends only on positions, not content, so it is computed once and shared by q and k, all layers and all heads. In code it is just angles = pos[:, None] * theta[None, :], shape (T, dhead/2).

The code never builds R(m) itself: row m of the angle table determines all of R(m), and step ④ below simply applies a 2D rotation to each pair (a, b).

A way to remember the code: it is like making a sandwich.

  • ① Ingredients: prepare the speeds θ, one per pair, and multiply by the positions to get the angle table (pos × θ).
  • ② Cook two ways: take cos and sin.
  • ③ Cut the bread in half: split x into x1 and x2.
  • ④ Add the filling: x1·cos − x2·sin and x1·sin + x2·cos.
  • ⑤ Close it: concatenate the two halves, and the sandwich is done.
# x: q or k of one head, shape (..., T, d_head); pos: 0 … T−1
i      = torch.arange(d_head//2)
theta  = base ** (-i / (d_head//2))    # ① ingredients: speed of each pair
angles = pos[:, None] * theta[None, :] #    angle table, (T, d_head/2)
cos, sin = angles.cos(), angles.sin()  # ② cook two ways
x1 = x[..., :d_head//2]                # ③ cut in half: each pair's a
x2 = x[..., d_head//2:]                #    and each pair's b
out = cat([x1*cos - x2*sin,            # ④ filling: new a
           x1*sin + x2*cos], dim=-1)   #    new b; ⑤ close

Hugging Face code for LLaMA and similar models writes this step as x*cos + rotate_half(x)*sin, where rotate_half(x) = [−x2, x1] and cos and sin are each repeated twice (length dhead). It just moves the minus sign from ④ into rotate_half; the result is the same as above.

9. Code details

9a · Why not rotate v

  1. Scoring: score = q·k → softmax → weights. This is where RoPE acts: the scores now carry relative distance.
  2. Moving content: output = Σ weight × v. v is the content being taken.

If v were rotated too, each v would be rotated by its own absolute position angle. After the weighted sum, the same content retrieved at position 3 versus position 300 would be a different vector. That isn't relative position, and it scrambles the content.

Compare GPT-2's learned absolute position embedding: it is added straight to the input x, so q, k and v are all affected. RoPE acts only on the scoring step.

9b · KV cache: new tokens continue the positions

The cache stores the rotated k. When the cache already holds P tokens, the new tokens' pos is P, P+1, … — it must not restart at 0. Rotate only the new q and new k; the old k in the cache must not be rotated again.