What is the sinusoidal positional encoding, and why is PEpos+k a linear function of PEpos? How do rotary position embeddings (RoPE) make attention scores depend only on relative position?

Sequence models and transformers, Positional encoding
Level L4 Advanced. Length Medium. Nature Th+Mat Both.

What's being asked

Whether you can use the angle-addition formulas to show the encoding has a relative-position structure, and know how RoPE turns that into a property of the dot product.

Key idea

Each frequency pair (sin⁡pω,cos⁡pω) at position p is a point on a circle, so a shift by k is a rotation: (sin⁡((p+k)ω)cos⁡((p+k)ω))=(cos⁡kωsin⁡kω−sin⁡kωcos⁡kω)(sin⁡pωcos⁡pω). RoPE rotates q and k by angles set by their positions, and for 2-D rotation matrices R(⋅), R(mθ)⊤R(nθ)=R((n−m)θ).

Steps

  1. Definition: PE(p, 2i)=sin⁡(p ωi) and PE(p, 2i+1)=cos⁡(p ωi), with ωi=10000−2i/d, where d is the model dimension. The frequencies fall geometrically from 1 to about 1/10000.
  2. Shift: by sin⁡(a+b)=sin⁡acos⁡b+cos⁡asin⁡b and cos⁡(a+b)=cos⁡acos⁡b−sin⁡asin⁡b, each pair at p+k equals the rotation matrix above (which depends only on k) times the pair at p. Stacking the pairs gives a block-diagonal matrix Mk with PEp+k=Mk PEp.
  3. Limitation: sinusoids are added to the embeddings xm, so the score (xm+PEm)⊤WQ⊤WK(xn+PEn) mixes content with absolute position. Relative position is available, but not enforced.
  4. RoPE: split q and k into 2-D pairs, and rotate pair i by angle mθi at position m: q~m=R(mθ) q and k~n=R(nθ) k.
  5. Then q~m⊤k~n=q⊤R(mθ)⊤R(nθ) k=q⊤R((n−m)θ) k, which depends on the positions only through n−m. RoPE is applied to queries and keys in every layer, not to values, and it is not added to the embeddings.

Common mistakes

How long your answer should be

About 4 minutes; the rotation identity and the RoPE line.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: In speculative decoding, a draft model proposes k tokens and each is accepted independently with probability α. How do you derive the expected number of tokens produced per target-model forward pass, what is its value for α=0.8 and k=4, and what is the expected speedup if one draft forward pass costs c=0.05 of a target forward pass?
Next in Sequence models and transformers: How can softmax attention be written as a kernel smoother? Why does replacing exp⁡(q⊤k) by a feature-map kernel ϕ(q)⊤ϕ(k) reduce the cost from O(n2d) to O(nd2)? How can causal linear attention be computed as an RNN, and what is lost?