Key takeaways
- Attention scores only look at content. They don't know where a word sits, so position has to be supplied separately.
- RoPE (rotary position embedding) turns position m into a rotation angle mθ. It rotates only q and k, never v, and has no learnable parameters.
- Because "the transpose is a reverse rotation" and "two turns add their angles", the dot product after rotation depends only on the relative position n−m.
- The dimensions turn in pairs, and pair i turns at speed θi=Θ−2i/H: fast pairs handle what is near, slow pairs handle what is far. Θ is the only hyperparameter, usually 10,000.
- In code you can treat each pair as a complex number, or cache cos and sin in advance and use element-wise multiplication instead of a big matrix.
Can attention tell word order?
Here are two sentences: "Dog bites man" and "man bites dog". Same three words, completely opposite meanings.
Last episode we met attention: each word takes its query vector q and computes a dot product with every word's key vector k, and the bigger the dot product, the more attention it pays. The catch is that q and k are computed from the word itself and nothing else. Whether "dog" comes first or third, its q and k are exactly the same.
So the two score tables are just the same rows and columns in a different order; not a single number has changed. The score from "dog" to "bites" is 2.1 in both sentences. So who bit whom? From the attention scores alone, there's no way to tell.
We need some way to tell the model where each word sits. The star of this episode, RoPE, is the most popular way to do that in today's large models.
Telling the model about position
Absolute position encoding. The most direct approach is to give each position a vector of its own (one for position 0, one for position 1, and so on) and add it onto the word's embedding. The original Transformer generated these position vectors from sine waves; GPT-2 simply treats them as parameters and learns them.
But in language, what usually matters most is relative position. Take "the word right before me": at the start of a sentence or around word one thousand, it's the same relationship. With absolute positions, the model has to learn that relationship separately at every position. And a learned table has a fixed length: GPT-2 has just 1024 positions, and beyond that there is no vector at all.
Making a wish. Take a query at position m and a key at position n. We'd like their score to depend on just two things: what each one contains, and the distance between them:
⟨f(q,m),f(k,n)⟩=g(q,k,m−n)
Here f is some operation that "puts" position information into a vector, and ⟨⋅,⋅⟩ is the dot product. We want an f that makes the absolute positions on the left cancel out by themselves, leaving only the relative distance.
In 2021, Jianlin Su and colleagues found a beautiful answer in the RoFormer paper: rotate the vectors. That's RoPE, and today it's used by Llama, Qwen and many other models.
First, rotate one vector
Step away from language models for a moment and go back to a flat coordinate plane. A vector is just an arrow from the origin, like (2,1). To rotate it, we swing the arrow around the origin by an angle θ; counterclockwise counts as positive, and the length stays the same. What are the new coordinates?
Start with the simplest arrow: (1,0), lying along the x axis with length 1. Turn it by θ and its tip lands on the circle of radius 1, at horizontal coordinate cosθ and vertical coordinate sinθ. That's exactly how cosine and sine are defined. At 30° that's (0.87,0.5).
Now the arrow along the y axis, (0,1). It turns by the same angle and stays at a right angle to the first, so it lands at (−sinθ,cosθ).
The key step: any vector can be built from these two basic arrows. (2,1) is two copies of the first arrow plus one copy of the second. Rotate the whole picture at once and that recipe doesn't change: the rotated arrow is still two of the rotated first arrow plus one of the rotated second. So for any vector (x1,x2):
Rθx=x1[cosθsinθ]+x2[−sinθcosθ]=[cosθsinθ−sinθcosθ][x1x2]
That 2×2 matrix is the rotation matrix Rθ. Its two columns are exactly where the two basic arrows land after the turn.
Let's check: at θ=90∘, cosθ=0 and sinθ=1, so (2,1) becomes (−1,2), exactly a quarter turn counterclockwise.
Three properties of rotation
Everything that follows rests on these three:
Property one: two turns in a row equal one turn by the sum of the angles. Turn by α, then by β, and it's the same as turning by α+β:
RβRα=Rα+β
Multiply those two matrices out and you get the angle addition formulas from high school trig.
Property two: the transpose turns you back. To transpose a matrix, flip it across its main diagonal: the first row becomes the first column, the second row the second column. After the flip, the minus sign has moved to the bottom left, and that's exactly the matrix for turning by −θ, because cos(−θ)=cosθ and sin(−θ)=−sinθ:
Rθ⊤=[cosθ−sinθsinθcosθ]=R−θ
Turn by θ, then multiply by the transpose, and the arrow is right back where it started.
Property three (the most important): turning both vectors together leaves the dot product alone. Besides "multiply matching entries and add them up", the dot product has a geometric meaning: multiply the two lengths, then multiply by the cosine of the angle between them:
q⋅k=∥q∥∥k∥cosφ
So if we turn q and k together by the same angle, the lengths don't change, the angle between them doesn't change, and the dot product doesn't budge. With q=(2,1) and k=(1,2), turning both by 80° keeps the dot product at 4. But as soon as the two turn by different amounts, the angle between them changes, and so does the dot product.
Turning position into an angle
Now the idea behind RoPE practically suggests itself: take the vector at position m and turn it by mθ, where θ is a fixed "how much to turn per step":
f(x,m)=Rmθx
Position 0 doesn't turn at all, position 1 turns by one θ, position 2 by two, and the further along you go, the more it turns.
A concrete example with θ=30∘, q=(2,1) and k=(1,2). With no rotation, the dot product is 2×1+1×2=4.
| q at m |
k at n |
dot product |
| 3 (turns 90°) |
1 (turns 30°) |
4.60 |
| 5 |
3 |
4.60 |
Shift both two places later and each arrow turns an extra 60°, yet the dot product is still 4.60. That's property three at work: the extra turn is the same for both, so the angle between them stays put. The only thing that sets that angle is the gap between the positions: 3−1 and 5−3 are both 2.
So as long as the distance stays fixed, it doesn't matter where the two words are in the sentence; the score never changes. But once the distance changes (say q stays put while k slides back toward the start, from position 9 to 5), the angle changes and the score changes with it, sliding from 4.60 all the way to −4.00.
Intuition: Turning q by mθ is like first turning it alone by (m−n)θ, then turning it along with k by nθ. The shared part leaves the dot product alone, so the dot product depends only on m−n.
The proof: only relative position survives
Now let's prove it properly with matrices. We want the dot product of q turned by mθ with k turned by nθ:
⟨Rmθq,Rnθk⟩=(Rmθq)⊤Rnθk=q⊤Rmθ⊤Rnθk=q⊤R−mθRnθk=q⊤R(n−m)θk(1)(2)(3)(4)
The reason for each step:
- A dot product can be written with a transpose: the vector on the left lies down to become a row, then multiplies the column standing on the right.
- The transpose of a product is the product of the transposes in reverse order, so (Rmθq)⊤=q⊤Rmθ⊤.
- Property two: the transpose of a rotation is the same rotation run backwards, Rα⊤=R−α.
- Property one: two turns in a row add their angles, RαRβ=Rα+β, and −mθ+nθ=(n−m)θ.
Look at the last line: m and n on their own have disappeared, and all that's left is their difference, n−m. Wherever two words sit, if they're the same distance apart, they get the same score.
So RoPE is exactly the f we were looking for, and our wish has come true:
f(x,m)=Rmθx,g=q⊤R(n−m)θk
(The wish was written with m−n and the proof ends with n−m. They differ only by a sign; either way, the score depends only on the gap between the two positions.)
High dimensions: rotate in pairs
In real models q and k aren't two-dimensional; each attention head usually has a dimension H of 64 or 128. RoPE's trick is to split the vector into pairs: dimensions 0 and 1 form one pair, 2 and 3 the next, and so on, for H/2 pairs. Each pair is treated as an arrow on its own little plane and rotates independently.
Pair i (indices 2i and 2i+1) turns by mθi. Notice that every pair has its own θi, so as position m moves forward, the pairs' "clock hands" turn at different speeds. Written as one big matrix, this is a block diagonal matrix: small 2×2 rotation blocks down the diagonal and zeros everywhere else:
Rm=⋱Rm(i)⋱∈RH×H,Rm(i)=[cos(mθi)sin(mθi)−sin(mθi)cos(mθi)]
The full dot product is just the sum of the pairs' dot products. Each pair depends only on m−n, so of course the sum does too.
Where RoPE sits in the model: it runs in every layer and every attention head. First the weight matrices produce q and k, then each is rotated according to its position (qm←Rmqm, km←Rmkm), and only then do we take the dot product. RoPE itself has no learnable parameters at all.
Watch out: The value vector v is never rotated. Position only needs to affect who attends to whom, which is the score. The content that gets passed along doesn't need to be changed by position.
Why different speeds?
First, what goes wrong with just one speed? Say every step forward turns the arrow 30°. By position 12 it has turned a full 360° and is right back where it started, so as far as it can tell, position 0 and position 12 are identical.
- Turn fast, and neighboring positions are easy to tell apart, but the pattern repeats after just a few steps.
- Turn slowly, and you can cover a long distance, but neighbors become almost impossible to tell apart.
Intuition: Clocks solved this long ago. The second hand races around, the minute hand is slower, and the hour hand slower still. The second hand alone can't tell one o'clock from two; put all three together and you can read the exact time.
RoPE works the same way: H/2 pairs of dimensions means H/2 hands, with speeds running from fast to slow, spaced out exponentially. The speed of pair i is:
θi=Θ−2i/H
A small example: H=8 and Θ=10,000. The four pairs turn at 1, 0.1, 0.01 and 0.001 radians per position, each ten times slower than the last. Run position m from 0 to 60: the first hand goes around nearly ten times, the second about once, the third only a little way, and the fourth barely moves.
- High-frequency pairs (small i, large θi) rotate quickly, so adjacent positions differ a lot. They tell who is right next to whom (local discrimination).
- Low-frequency pairs (large i, small θi) rotate slowly, changing very little between neighbors and going a long way without coming back around. They sense roughly how far apart two words are (long-range information).
This exponential spread comes straight from the sine wave position encoding of the original Transformer: the frequencies are spread evenly on a log scale, which covers every scale efficiently. In real models H is often 128, giving 64 hands, with speeds falling from 1 all the way down to nearly one ten-thousandth.
Θ: RoPE's only hyperparameter
The capital Θ in that formula is RoPE's only hyperparameter, usually set to 10,000. In code and config files it often goes by rope theta or rotary base (rotary_base in Hugging Face).
- The fastest pair (i=0) has speed 1: it turns 1 radian per position, about 57°, so it makes a full turn in just over 6 positions.
- The slowest pair turns at nearly 1/Θ. A full turn (mθi=2π) takes about 2πΘ positions. With Θ=10,000, that's roughly 63,000 positions.
So Θ roughly sets the longest distance the model can natively tell apart. To handle longer contexts, you turn it up so the slowest hand turns even more slowly. Llama 3, for example, uses 500,000 (2πΘ is about 3.14 million positions).
Long-range decay. RoPE has one more nice property. Suppose q and k have exactly the same content, and we slowly pull them further apart. At distance 0 the score is at its highest. As the distance grows, the hands of the different pairs drift further and further out of step, their contributions cancel out, and the score heads downward (wobbling as it falls toward 0). That matches intuition: words that are far apart are usually less related.
Watch out: Long-range decay is only a tendency. The model can still learn to pay attention to things that are very far away.
Another view: complex multiplication
There's an even neater way to write RoPE, using complex numbers. Don't worry if you've never studied them; you only need one fact: i is a special number whose square is −1. (In this section i is the imaginary unit; don't confuse it with the pair index i above.)
A number of the form a+bi is a complex number, and we can draw it as the point (a,b): a is the horizontal coordinate (real part) and b the vertical one (imaginary part). For example, 2+i is the point (2,1).
Here's the magic: multiplying by i is a 90° turn:
(2+i)⋅i=2i+i2=−1+2i
That's the very point (−1,2) we got from the rotation matrix. More generally, Euler's formula says:
eiθ=cosθ+isinθ
That's the point on the unit circle at angle θ, so multiplying by eiθ rotates by θ. Let's expand it to check, using i2=−1:
(a+bi)(cosθ+isinθ)=(acosθ−bsinθ)+i(asinθ+bcosθ)
The real part is acosθ−bsinθ and the imaginary part is asinθ+bcosθ: exactly what the rotation matrix gives.
So in RoPE each pair of dimensions [x2i,x2i+1] can be treated as one complex number z=x2i+ix2i+1, and encoding position m just means multiplying by eimθ. "Two turns add their angles" simply becomes "exponents add up".
In the complex view the proof takes a single line. First, flip the sign of k's imaginary part; that's the conjugate, written kˉ. Multiply q by kˉ, take the real part, and you get exactly the dot product. For q=2+i and k=1+2i:
(2+i)(1−2i)=4−3i,Re=4=(2,1)⋅(1,2)
After rotating, we have q times eimθ, multiplied by the conjugate of k times einθ. The conjugate turns n into −n, the exponents combine, and only m−n is left:
Re[(qeimθ)⋅(keinθ)]=Re[qkˉei(m−n)θ]
Once again, the absolute positions are gone.
Efficient code: no big matrix needed
The clumsy way: build an H×H block diagonal matrix for every position and do a full matrix multiplication. But that matrix is almost all zeros. With H=128, one matrix multiplication takes over 16,000 multiplications, and only 256 of them actually do anything.
What we do in practice: write the rotation as element-wise multiplication (⊙):
[x1x2]⊙[cos(mθ)cos(mθ)]+[−x2x1]⊙[sin(mθ)sin(mθ)]
Expand it: the first row is x1cos−x2sin and the second is x1sin+x2cos, a perfect match for the rotation matrix.
Step 1: cache the angles ahead of time. Position m times each pair's θi gives an angle table; take cos and sin of it and cache them when the model is initialized. In the code, self.theta is Θ, d_k is the head dimension H, and arange(0, d_k, 2) produces exactly the 2i values:
positions = torch.arange(max_seq_len, device=device) # (max_seq_len)
thetas = self.theta ** (-torch.arange(0, d_k, 2, device=device) / d_k) # (d_k // 2)
angles = positions.unsqueeze(-1) * thetas.unsqueeze(0)
Step 2: pull out the even and odd entries. In the forward pass, group the last dimension into pairs by reshaping it to H/2 rows and 2 columns. The left column holds the even entries, the right column the odd ones.
x_pairs = x.reshape(*x.shape[:-1], -1, 2)
x_even = x_pairs[..., 0]
x_odd = x_pairs[..., 1]
Step 3: apply the formula, computing all the new even and odd entries in one go:
x_out_even = x_even * cos - x_odd * sin
x_out_odd = x_even * sin + x_odd * cos
Step 4: interleave them back. torch.stack adds a new dimension, placing the new even and odd entries side by side, and flatten squashes it, weaving them back into the original shape in the order x0′,x1′,…:
torch.stack([x_out_even, x_out_odd], dim=-1).flatten(start_dim=-2)
Watch out: Some codebases don't pair up neighboring dimensions. Instead they pair the first half with the second half (dimension i with dimension i+H/2). Only the pairing differs; the idea is exactly the same. One catch, though: weights trained with one layout can't be plugged straight into the other.
Recap
- Attention scores only look at content and can't see position; absolute position encodings must learn each relationship position by position and stop at a fixed length. What we want is a score that depends only on content and relative distance.
- RoPE turns position m into a rotation angle mθ, f(x,m)=Rmθx. It rotates only q and k, never v, and has no learnable parameters.
- Because Rα⊤=R−α and RαRβ=Rα+β, the rotated dot product q⊤R(n−m)θk depends only on the relative position n−m.
- Dimensions turn in pairs at speeds θi=Θ−2i/H: fast pairs handle what is near, slow pairs what is far. Θ, usually 10,000, roughly sets the longest natively distinguishable distance (about 2πΘ positions), and scores tend to decay with distance.
- In code, treat each pair as a complex number (multiply by eimθ), or cache cos and sin and use element-wise multiplication instead of a big matrix.
With attention and position encoding done, every Transformer layer still has two building blocks left: normalization and the feed-forward network. Next time: RMSNorm and SwiGLU.