Practice / Transformer pieces

Rotary position embeddings

Ten problems on rotary position embeddings (RoPE): the 2-D rotation matrix and its algebra, why the score of a rotated query and key depends only on their relative position, the score as a sinusoid in the offset, the block-diagonal form and shift invariance, the complex-number form, the frequencies and wavelengths at d = 128, the backward pass through the rotation, the derivative with respect to the offset and the frequencies, RoPE inside attention backward, and position interpolation, with worked solutions and the mistakes that lose the position or flip its sign.

Before you start

Rotary position embeddings put position into attention without adding anything to the token: each query and key is rotated, two coordinates at a time, by an angle proportional to its position, and the dot product of two rotated vectors then depends only on how far apart they are. That one fact is the whole design, and it follows from three lines of trigonometry. These ten problems derive it for one pair of coordinates, extend it to the full block-diagonal rotation, rewrite it with complex numbers, work out the frequencies and wavelengths used in practice, and then do what a framework does: backpropagate through the rotation, inside attention. The five mistakes are the ones that leave the model running: both vectors rotated by the same angle, a transposed rotation with the sign of the offset flipped, values rotated too, a backward pass that rotates forwards, and a pairing of coordinates that differs between queries and keys.

  • The conventions are those of the attention page: vectors are columns, a gradient has the shape of its variable, and a token at position mm has query q∈Rdq \in \mathbb{R}^d and key k∈Rdk \in \mathbb{R}^d with dd even.
  • The 2-D rotation by angle α\alpha is R(α)=(cos⁡α−sin⁡αsin⁡αcos⁡α)R(\alpha) = \begin{pmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha & \cos\alpha\end{pmatrix}; it turns a vector anticlockwise by α\alpha. The trig-identities page's addition formulas are used freely.
  • The coordinates of qq are grouped into d/2d/2 pairs: pair pp is q(p)=(q2p−1,q2p)⊤∈R2q^{(p)} = (q_{2p-1}, q_{2p})^\top \in \mathbb{R}^2 for p=1,…,d/2p = 1, \dots, d/2. Each pair has its own frequency θp=10000−2(p−1)/d\theta_p = 10000^{-2(p-1)/d}, so θ1=1\theta_1 = 1 and the frequencies decrease geometrically. The ratio θp+1/θp\theta_{p+1}/\theta_p is 10000−2/d10000^{-2/d}.
  • RoPE at position mm rotates pair pp by the angle mθpm\theta_p: Rm=blockdiag⁡(R(mθ1),…,R(mθd/2))R_m = \operatorname{blockdiag}\big(R(m\theta_1), \dots, R(m\theta_{d/2})\big), a d×dd\times d matrix, and the rotated query is q~=Rmq\tilde q = R_mq. A key at position nn becomes k~=Rnk\tilde k = R_nk. The score is s=q~⊤k~s = \tilde q^\top\tilde k (the attention page's SmnS_{mn} before the division by d\sqrt d). Values are not rotated.
  • Implementations that pair coordinate jj with j+d/2j + d/2 instead ("rotate half") are the same construction after one fixed permutation of the coordinates, applied to every qq and kk alike.
  • Complex form: a pair (x,y)⊤(x, y)^\top is the complex number x+iyx + \mathrm{i}y with i2=−1\mathrm{i}^2 = -1; zˉ\bar z is the conjugate and Re⁡\operatorname{Re} the real part. Euler's formula is eiα=cos⁡α+isin⁡αe^{\mathrm{i}\alpha} = \cos\alpha + \mathrm{i}\sin\alpha.
  • LL is a scalar loss and g=∂L/∂sg = \partial L/\partial s the upstream gradient of a score; inside attention, GG, G~\tilde G and ∇SL\nabla_S L are the attention page's matrices.

Builds on: Attention backward, Trig identities

Problems

  1. ·

    Show that R(α)⊤R(α)=IR(\alpha)^\top R(\alpha) = I, det⁡R(α)=1\det R(\alpha) = 1, R(α)R(β)=R(α+β)R(\alpha)R(\beta) = R(\alpha + \beta) and R(α)⊤=R(−α)R(\alpha)^\top = R(-\alpha).

  2. ·

    One pair with frequency θ\theta: the query q∈R2q \in \mathbb{R}^2 at position mm and the key k∈R2k \in \mathbb{R}^2 at position nn. Show that (R(mθ)q)⊤(R(nθ)k)=q⊤R((n−m)θ)k(R(m\theta)q)^\top(R(n\theta)k) = q^\top R\big((n - m)\theta\big)k.

  3. ··

    For one pair, write s(φ)=q⊤R(φ)ks(\varphi) = q^\top R(\varphi)k in the form acos⁡φ+bsin⁡φa\cos\varphi + b\sin\varphi, giving aa and bb in terms of the entries of qq and kk. Show that a2+b2=∥q∥2∥k∥2a^2 + b^2 = \|q\|^2\|k\|^2, and hence that s(φ)=∥q∥∥k∥cos⁡(φ−ψ)s(\varphi) = \|q\|\|k\|\cos(\varphi - \psi) for some angle ψ\psi. What is ψ\psi?

  4. ··

    Full dimension dd. Show that Rm⊤Rn=Rn−mR_m^\top R_n = R_{n-m}, that the score (Rmq)⊤(Rnk)(R_mq)^\top(R_nk) is a sum over pairs that depends on mm and nn only through n−mn - m (so it is unchanged if both positions shift by the same ss), and that ∥Rmq∥=∥q∥\|R_mq\| = \|q\|.

  5. ··

    Complex form. Write pair pp of qq as zp=q2p−1+iq2pz_p = q_{2p-1} + \mathrm{i}q_{2p} and of kk as wp=k2p−1+ik2pw_p = k_{2p-1} + \mathrm{i}k_{2p}. Show that rotating a pair by α\alpha is multiplying its complex number by eiαe^{\mathrm{i}\alpha}, that q(p)⊤k(p)=Re⁡(zpwˉp)q^{(p)\top}k^{(p)} = \operatorname{Re}(z_p\bar w_p), and that the RoPE score is Re⁡∑pzpwˉp ei(m−n)θp\operatorname{Re}\sum_p z_p\bar w_p\,e^{\mathrm{i}(m - n)\theta_p}.

  6. ·

    With d=128d = 128 and base 1000010000: give θ1\theta_1 and θ64\theta_{64}, the wavelength 2π/θp2\pi/\theta_p of the first and last pairs in positions, and the number of pairs whose wavelength is at most a context length of 40964096 (the pairs that complete at least one full turn inside the context).

  7. ···

    Backward through the rotation. For s=(Rmq)⊤(Rnk)s = (R_mq)^\top(R_nk) with upstream gradient g=∂L/∂sg = \partial L/\partial s, compute ∇qL\nabla_qL and ∇kL\nabla_kL. Then, for a general vector u=∇q~Lu = \nabla_{\tilde q}L of upstream gradient at the rotated query q~=Rmq\tilde q = R_mq, give ∇qL\nabla_qL.

  8. ···

    Show that ddφR(φ)=R(φ+π/2)\tfrac{d}{d\varphi}R(\varphi) = R(\varphi + \pi/2). Treating the offset Δ=n−m\Delta = n - m as a continuous variable, compute ∂s/∂Δ\partial s/\partial\Delta for the full score s(Δ)=∑pq(p)⊤R(Δθp)k(p)s(\Delta) = \sum_p q^{(p)\top}R(\Delta\theta_p)k^{(p)}, and compute ∂s/∂θp\partial s/\partial\theta_p for learned or rescaled frequencies.

  9. ···

    Attention with RoPE: Q~\tilde Q and K~\tilde K have rows (Rmqm)⊤(R_mq_m)^\top and (Rnkn)⊤(R_nk_n)^\top for tokens at positions m,n=1,…,Nm, n = 1, \dots, N, S=Q~K~⊤/dS = \tilde Q\tilde K^\top/\sqrt d, A=softmax⁡(S)A = \operatorname{softmax}(S) row-wise, O=AVO = AV. Using the attention page's results for ∇Q~L\nabla_{\tilde Q}L and ∇K~L\nabla_{\tilde K}L, write ∇qmL\nabla_{q_m}L and ∇knL\nabla_{k_n}L. Then show that shifting every position by the same ss leaves AA and OO unchanged.

  10. ··

    Position interpolation extends a model trained at context L0L_0 to context sL0sL_0 by using positions m/sm/s in place of mm. Show that this equals keeping the positions and dividing every frequency by ss, that every wavelength is multiplied by ss, and compute, for d=128d = 128 and s=4s = 4, how many pairs now complete a turn within 40964096 positions.

Worked solutions

Problem 1

Show that R(α)⊤R(α)=IR(\alpha)^\top R(\alpha) = I, det⁡R(α)=1\det R(\alpha) = 1, R(α)R(β)=R(α+β)R(\alpha)R(\beta) = R(\alpha + \beta) and R(α)⊤=R(−α)R(\alpha)^\top = R(-\alpha).

  1. R(α)⊤R(α)=(cos⁡αsin⁡α−sin⁡αcos⁡α)(cos⁡α−sin⁡αsin⁡αcos⁡α)=(cos⁡2α+sin⁡2α00sin⁡2α+cos⁡2α)=IR(\alpha)^\top R(\alpha) = \begin{pmatrix}\cos\alpha & \sin\alpha\\ -\sin\alpha & \cos\alpha\end{pmatrix}\begin{pmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha & \cos\alpha\end{pmatrix} = \begin{pmatrix}\cos^2\alpha + \sin^2\alpha & 0\\ 0 & \sin^2\alpha + \cos^2\alpha\end{pmatrix} = I.Multiply out; the off-diagonal entries are −cos⁡αsin⁡α+sin⁡αcos⁡α=0-\cos\alpha\sin\alpha + \sin\alpha\cos\alpha = 0, and cos⁡2+sin⁡2=1\cos^2 + \sin^2 = 1.
  2. det⁡R(α)=cos⁡2α+sin⁡2α=1\det R(\alpha) = \cos^2\alpha + \sin^2\alpha = 1.ad−bcad - bc with b=−sin⁡αb = -\sin\alpha.
  3. R(α)R(β)=(cos⁡αcos⁡β−sin⁡αsin⁡β−cos⁡αsin⁡β−sin⁡αcos⁡βsin⁡αcos⁡β+cos⁡αsin⁡β−sin⁡αsin⁡β+cos⁡αcos⁡β)=R(α+β)R(\alpha)R(\beta) = \begin{pmatrix}\cos\alpha\cos\beta - \sin\alpha\sin\beta & -\cos\alpha\sin\beta - \sin\alpha\cos\beta\\ \sin\alpha\cos\beta + \cos\alpha\sin\beta & -\sin\alpha\sin\beta + \cos\alpha\cos\beta\end{pmatrix} = R(\alpha + \beta).The entries are the addition formulas: cos⁡(α+β)=cos⁡αcos⁡β−sin⁡αsin⁡β\cos(\alpha + \beta) = \cos\alpha\cos\beta - \sin\alpha\sin\beta and sin⁡(α+β)=sin⁡αcos⁡β+cos⁡αsin⁡β\sin(\alpha + \beta) = \sin\alpha\cos\beta + \cos\alpha\sin\beta.
  4. R(α)⊤=(cos⁡αsin⁡α−sin⁡αcos⁡α)=(cos⁡(−α)−sin⁡(−α)sin⁡(−α)cos⁡(−α))=R(−α)R(\alpha)^\top = \begin{pmatrix}\cos\alpha & \sin\alpha\\ -\sin\alpha & \cos\alpha\end{pmatrix} = \begin{pmatrix}\cos(-\alpha) & -\sin(-\alpha)\\ \sin(-\alpha) & \cos(-\alpha)\end{pmatrix} = R(-\alpha).cos⁡\cos is even and sin⁡\sin is odd.
  5. R(α)⊤R(α)=IR(\alpha)^\top R(\alpha) = I, det⁡R(α)=1\det R(\alpha) = 1, R(α)R(β)=R(α+β)R(\alpha)R(\beta) = R(\alpha + \beta), R(α)⊤=R(−α)R(\alpha)^\top = R(-\alpha)A rotation preserves lengths and angles (orthogonal, determinant +1+1 so no reflection), rotations compose by adding angles, and the inverse of a rotation is its transpose, which is the rotation back. Step 3 also shows rotations in the plane commute: R(α)R(β)=R(β)R(α)R(\alpha)R(\beta) = R(\beta)R(\alpha).

Problem 2

One pair with frequency θ\theta: the query q∈R2q \in \mathbb{R}^2 at position mm and the key k∈R2k \in \mathbb{R}^2 at position nn. Show that (R(mθ)q)⊤(R(nθ)k)=q⊤R((n−m)θ)k(R(m\theta)q)^\top(R(n\theta)k) = q^\top R\big((n - m)\theta\big)k.

  1. (R(mθ)q)⊤(R(nθ)k)=q⊤R(mθ)⊤R(nθ)k(R(m\theta)q)^\top(R(n\theta)k) = q^\top R(m\theta)^\top R(n\theta)k.(Ab)⊤=b⊤A⊤(Ab)^\top = b^\top A^\top.
  2. R(mθ)⊤=R(−mθ)R(m\theta)^\top = R(-m\theta).Problem 1, step 4.
  3. R(−mθ)R(nθ)=R(nθ−mθ)=R((n−m)θ)R(-m\theta)R(n\theta) = R(n\theta - m\theta) = R\big((n - m)\theta\big).Problem 1, step 3: angles add.
  4. (R(mθ)q)⊤(R(nθ)k)=q⊤R((n−m)θ)k(R(m\theta)q)^\top(R(n\theta)k) = q^\top R\big((n - m)\theta\big)kThe absolute positions mm and nn have cancelled: the score is the unrotated qq against kk rotated by the relative offset n−mn - m times the frequency. Nothing was assumed about qq or kk, so this holds for whatever the projections produce.

Problem 3

For one pair, write s(φ)=q⊤R(φ)ks(\varphi) = q^\top R(\varphi)k in the form acos⁡φ+bsin⁡φa\cos\varphi + b\sin\varphi, giving aa and bb in terms of the entries of qq and kk. Show that a2+b2=∥q∥2∥k∥2a^2 + b^2 = \|q\|^2\|k\|^2, and hence that s(φ)=∥q∥∥k∥cos⁡(φ−ψ)s(\varphi) = \|q\|\|k\|\cos(\varphi - \psi) for some angle ψ\psi. What is ψ\psi?

  1. R(φ)k=(k1cos⁡φ−k2sin⁡φ, k1sin⁡φ+k2cos⁡φ)⊤R(\varphi)k = (k_1\cos\varphi - k_2\sin\varphi,\ k_1\sin\varphi + k_2\cos\varphi)^\top.Matrix times vector.
  2. s(φ)=q1k1cos⁡φ−q1k2sin⁡φ+q2k1sin⁡φ+q2k2cos⁡φ=(q1k1+q2k2)cos⁡φ+(q2k1−q1k2)sin⁡φs(\varphi) = q_1k_1\cos\varphi - q_1k_2\sin\varphi + q_2k_1\sin\varphi + q_2k_2\cos\varphi = (q_1k_1 + q_2k_2)\cos\varphi + (q_2k_1 - q_1k_2)\sin\varphi.Dot with qq and collect the cos⁡\cos and sin⁡\sin terms.
  3. a=q1k1+q2k2=q⊤ka = q_1k_1 + q_2k_2 = q^\top k and b=q2k1−q1k2b = q_2k_1 - q_1k_2.Read off step 2. aa is the dot product; bb is the 2-D cross product of kk and qq (the signed area of their parallelogram).
  4. a2+b2=q12k12+2q1k1q2k2+q22k22+q22k12−2q2k1q1k2+q12k22=(q12+q22)(k12+k22)a^2 + b^2 = q_1^2k_1^2 + 2q_1k_1q_2k_2 + q_2^2k_2^2 + q_2^2k_1^2 - 2q_2k_1q_1k_2 + q_1^2k_2^2 = (q_1^2 + q_2^2)(k_1^2 + k_2^2).Expand both squares; the cross terms cancel and the remaining four terms factor.
  5. Let r=∥q∥∥k∥r = \|q\|\|k\| and choose ψ\psi with rcos⁡ψ=ar\cos\psi = a and rsin⁡ψ=br\sin\psi = b. Then s(φ)=r(cos⁡ψcos⁡φ+sin⁡ψsin⁡φ)=rcos⁡(φ−ψ)s(\varphi) = r(\cos\psi\cos\varphi + \sin\psi\sin\varphi) = r\cos(\varphi - \psi).Step 4 says (a,b)(a, b) lies on the circle of radius rr, so such a ψ\psi exists (when r>0r > 0); then the difference formula for cosine (the trig-identities page).
  6. ψ\psi is the angle from kk to qq.With kk along the first axis, k=(∥k∥,0)⊤k = (\|k\|, 0)^\top and q=∥q∥(cos⁡ψ′,sin⁡ψ′)⊤q = \|q\|(\cos\psi', \sin\psi')^\top at angle ψ′\psi': then a=∥q∥∥k∥cos⁡ψ′a = \|q\|\|k\|\cos\psi' and b=q2k1=∥q∥∥k∥sin⁡ψ′b = q_2k_1 = \|q\|\|k\|\sin\psi', so ψ=ψ′\psi = \psi'. The dot product is unchanged by rotating both vectors, so this holds in general.
  7. s(φ)=(q⊤k)cos⁡φ+(q2k1−q1k2)sin⁡φ=∥q∥∥k∥cos⁡(φ−ψ)s(\varphi) = (q^\top k)\cos\varphi + (q_2k_1 - q_1k_2)\sin\varphi = \|q\|\|k\|\cos(\varphi - \psi), ψ\psi the angle from kk to qqAs the offset n−mn - m grows, the score of one pair oscillates between ±∥q∥∥k∥\pm\|q\|\|k\| with period 2π/θ2\pi/\theta, and is largest when the rotation by φ=(n−m)θ\varphi = (n - m)\theta brings kk into line with qq. The full score (Problem 4) is a sum of d/2d/2 such sinusoids with different periods, which is what lets it single out particular offsets.

Problem 4

Full dimension dd. Show that Rm⊤Rn=Rn−mR_m^\top R_n = R_{n-m}, that the score (Rmq)⊤(Rnk)(R_mq)^\top(R_nk) is a sum over pairs that depends on mm and nn only through n−mn - m (so it is unchanged if both positions shift by the same ss), and that ∥Rmq∥=∥q∥\|R_mq\| = \|q\|.

  1. Rm⊤Rn=blockdiag⁡(R(mθp)⊤R(nθp))p=blockdiag⁡(R((n−m)θp))p=Rn−mR_m^\top R_n = \operatorname{blockdiag}\big(R(m\theta_p)^\top R(n\theta_p)\big)_p = \operatorname{blockdiag}\big(R((n - m)\theta_p)\big)_p = R_{n-m}.Block-diagonal matrices multiply block by block, and the transpose of a block-diagonal matrix is block-diagonal with transposed blocks; each block is Problem 2 with θ=θp\theta = \theta_p.
  2. (Rmq)⊤(Rnk)=q⊤Rm⊤Rnk=q⊤Rn−mk(R_mq)^\top(R_nk) = q^\top R_m^\top R_nk = q^\top R_{n-m}k.(Ab)⊤=b⊤A⊤(Ab)^\top = b^\top A^\top and step 1.
  3. q⊤Rn−mk=∑p=1d/2q(p)⊤R((n−m)θp)k(p)q^\top R_{n-m}k = \sum_{p=1}^{d/2}q^{(p)\top}R\big((n - m)\theta_p\big)k^{(p)}.A block-diagonal matrix acts on each pair separately, and the dot product adds up the pairs.
  4. Replacing (m,n)(m, n) by (m+s,n+s)(m + s, n + s) leaves n−mn - m unchanged, so the score is unchanged.Step 3 contains mm and nn only in the combination n−mn - m.
  5. ∥Rmq∥2=q⊤Rm⊤Rmq=q⊤R0q=q⊤q\|R_mq\|^2 = q^\top R_m^\top R_mq = q^\top R_0q = q^\top q.Step 1 with n=mn = m, and R0=IR_0 = I since R(0)=IR(0) = I.
  6. Rm⊤Rn=Rn−mR_m^\top R_n = R_{n-m}; (Rmq)⊤(Rnk)=∑pq(p)⊤R((n−m)θp)k(p)(R_mq)^\top(R_nk) = \sum_p q^{(p)\top}R((n - m)\theta_p)k^{(p)}, a function of n−mn - m alone; ∥Rmq∥=∥q∥\|R_mq\| = \|q\|The score depends on relative position, and so do the attention weights built from it (Problem 9): a sequence shifted by ss positions attends the same way. Each pair contributes ∥q(p)∥∥k(p)∥cos⁡((n−m)θp−ψp)\|q^{(p)}\|\|k^{(p)}\|\cos((n - m)\theta_p - \psi_p) by Problem 3, and the rotation never changes the size of a query or key, so the 1/d1/\sqrt d scaling argument of the attention page is untouched.

Problem 5

Complex form. Write pair pp of qq as zp=q2p−1+iq2pz_p = q_{2p-1} + \mathrm{i}q_{2p} and of kk as wp=k2p−1+ik2pw_p = k_{2p-1} + \mathrm{i}k_{2p}. Show that rotating a pair by α\alpha is multiplying its complex number by eiαe^{\mathrm{i}\alpha}, that q(p)⊤k(p)=Re⁡(zpwˉp)q^{(p)\top}k^{(p)} = \operatorname{Re}(z_p\bar w_p), and that the RoPE score is Re⁡∑pzpwˉp ei(m−n)θp\operatorname{Re}\sum_p z_p\bar w_p\,e^{\mathrm{i}(m - n)\theta_p}.

  1. eiα(x+iy)=(cos⁡α+isin⁡α)(x+iy)=(xcos⁡α−ysin⁡α)+i(xsin⁡α+ycos⁡α)e^{\mathrm{i}\alpha}(x + \mathrm{i}y) = (\cos\alpha + \mathrm{i}\sin\alpha)(x + \mathrm{i}y) = (x\cos\alpha - y\sin\alpha) + \mathrm{i}(x\sin\alpha + y\cos\alpha).Euler's formula, then multiply out using i2=−1\mathrm{i}^2 = -1.
  2. The real and imaginary parts are the two entries of R(α)(x,y)⊤R(\alpha)(x, y)^\top.Compare with R(α)R(\alpha) applied to (x,y)⊤(x, y)^\top: first entry xcos⁡α−ysin⁡αx\cos\alpha - y\sin\alpha, second xsin⁡α+ycos⁡αx\sin\alpha + y\cos\alpha.
  3. zwˉ=(x1+iy1)(x2−iy2)=(x1x2+y1y2)+i(y1x2−x1y2)z\bar w = (x_1 + \mathrm{i}y_1)(x_2 - \mathrm{i}y_2) = (x_1x_2 + y_1y_2) + \mathrm{i}(y_1x_2 - x_1y_2), so Re⁡(zwˉ)=x1x2+y1y2\operatorname{Re}(z\bar w) = x_1x_2 + y_1y_2.Multiply out; the real part is the dot product of the two pairs, and the imaginary part is Problem 3's bb.
  4. z~p=eimθpzp\tilde z_p = e^{\mathrm{i}m\theta_p}z_p and w~p=einθpwp\tilde w_p = e^{\mathrm{i}n\theta_p}w_p are the rotated pairs.Step 2 with α=mθp\alpha = m\theta_p and nθpn\theta_p.
  5. z~pw~p‾=eimθpzp e−inθpwˉp=zpwˉp ei(m−n)θp\tilde z_p\overline{\tilde w_p} = e^{\mathrm{i}m\theta_p}z_p\,e^{-\mathrm{i}n\theta_p}\bar w_p = z_p\bar w_p\,e^{\mathrm{i}(m - n)\theta_p}.eiβw‾=e−iβwˉ\overline{e^{\mathrm{i}\beta}w} = e^{-\mathrm{i}\beta}\bar w, and exponents add.
  6. Rotation by α\alpha is multiplication by eiαe^{\mathrm{i}\alpha}; q(p)⊤k(p)=Re⁡(zpwˉp)q^{(p)\top}k^{(p)} = \operatorname{Re}(z_p\bar w_p); score =Re⁡∑pzpwˉp ei(m−n)θp= \operatorname{Re}\sum_p z_p\bar w_p\,e^{\mathrm{i}(m - n)\theta_p}Step 3 applied to the rotated pairs and summed over pp. This is how RoPE is usually implemented: view the last axis as complex, multiply by a precomputed table of eimθpe^{\mathrm{i}m\theta_p}, view as real again. The relative-position property is the exponent rule eimθe−inθ=ei(m−n)θe^{\mathrm{i}m\theta}e^{-\mathrm{i}n\theta} = e^{\mathrm{i}(m - n)\theta}, which is Problem 1's R(α)R(β)=R(α+β)R(\alpha)R(\beta) = R(\alpha + \beta) in different clothes.

Problem 6

With d=128d = 128 and base 1000010000: give θ1\theta_1 and θ64\theta_{64}, the wavelength 2π/θp2\pi/\theta_p of the first and last pairs in positions, and the number of pairs whose wavelength is at most a context length of 40964096 (the pairs that complete at least one full turn inside the context).

  1. θ1=100000=1\theta_1 = 10000^{0} = 1 and θ64=10000−126/128\theta_{64} = 10000^{-126/128}.p=1p = 1 gives exponent 00; p=64p = 64 gives −2⋅63/128=−126/128-2\cdot 63/128 = -126/128.
  2. 10000126/128=e(126/128)ln⁡10000=e0.984375⋅9.2103≈e9.0664≈866010000^{126/128} = e^{(126/128)\ln 10000} = e^{0.984375\cdot 9.2103} \approx e^{9.0664} \approx 8660, so θ64≈1.15×10−4\theta_{64} \approx 1.15\times10^{-4}.ln⁡10000=4ln⁡10≈9.2103\ln 10000 = 4\ln 10 \approx 9.2103.
  3. Wavelength of pair 11: 2π/1≈6.282\pi/1 \approx 6.28 positions; of pair 6464: 2π⋅8660≈54,4002\pi\cdot 8660 \approx 54{,}400 positions.A pair rotates by θp\theta_p per position, so it completes a turn every 2π/θp2\pi/\theta_p positions.
  4. Pair pp completes a turn within 40964096 positions iff 2π/θp≤40962\pi/\theta_p \le 4096 iff 100002(p−1)/128≤4096/(2π)10000^{2(p-1)/128} \le 4096/(2\pi).Substitute θp\theta_p and invert; the inequality direction is preserved because θp>0\theta_p > 0.
  5. 2(p−1)128ln⁡10000≤ln⁡40962π≈ln⁡651.9≈6.480\dfrac{2(p - 1)}{128}\ln 10000 \le \ln\dfrac{4096}{2\pi} \approx \ln 651.9 \approx 6.480, so p−1≤128⋅6.4802⋅9.2103≈45.03p - 1 \le \dfrac{128\cdot 6.480}{2\cdot 9.2103} \approx 45.03.Take logs; 4096/(2π)≈651.94096/(2\pi) \approx 651.9.
  6. θ1=1\theta_1 = 1, θ64≈1.15×10−4\theta_{64} \approx 1.15\times10^{-4}; wavelengths ≈6.3\approx 6.3 and ≈54,400\approx 54{,}400 positions; 4646 of the 6464 pairs complete a turn within 40964096 positionsp≤46.03p \le 46.03, so p=1,…,46p = 1, \dots, 46. The remaining 1818 pairs turn through less than a full circle over the whole context and act like a slowly varying, almost monotone position signal; the fast pairs resolve nearby offsets. Trained at a shorter context, those slow pairs have never seen the angles a longer context produces, which is the problem position interpolation addresses (Problem 10).

Problem 7

Backward through the rotation. For s=(Rmq)⊤(Rnk)s = (R_mq)^\top(R_nk) with upstream gradient g=∂L/∂sg = \partial L/\partial s, compute ∇qL\nabla_qL and ∇kL\nabla_kL. Then, for a general vector u=∇q~Lu = \nabla_{\tilde q}L of upstream gradient at the rotated query q~=Rmq\tilde q = R_mq, give ∇qL\nabla_qL.

  1. s=q⊤Rn−mks = q^\top R_{n-m}k.Problem 4, step 2.
  2. ∇qs=Rn−mk\nabla_qs = R_{n-m}k.s=q⊤cs = q^\top c with c=Rn−mkc = R_{n-m}k not depending on qq, and ∇q(q⊤c)=c\nabla_q(q^\top c) = c (the matrix-calculus page).
  3. s=k⊤Rn−m⊤q=k⊤Rm−nqs = k^\top R_{n-m}^\top q = k^\top R_{m-n}q, so ∇ks=Rm−nq\nabla_ks = R_{m-n}q.A scalar equals its transpose; Rn−m⊤=Rm−nR_{n-m}^\top = R_{m-n} by Problem 1, step 4, block by block.
  4. ∇qL=g Rn−mk\nabla_qL = g\,R_{n-m}k and ∇kL=g Rm−nq\nabla_kL = g\,R_{m-n}q.LL depends on qq and kk only through ss, so the chain rule multiplies by gg.
  5. q~=Rmq\tilde q = R_mq gives ∂q~/∂q=Rm\partial\tilde q/\partial q = R_m, so ∇qL=Rm⊤∇q~L=Rm⊤u=R−mu\nabla_qL = R_m^\top\nabla_{\tilde q}L = R_m^\top u = R_{-m}u.A linear map's Jacobian is its matrix, and for a scalar LL, ∇qL=(∂q~/∂q)⊤∇q~L\nabla_qL = (\partial\tilde q/\partial q)^\top\nabla_{\tilde q}L (the Jacobians page); then Rm⊤=R−mR_m^\top = R_{-m}.
  6. ∇qL=g Rn−mk\nabla_qL = g\,R_{n-m}k, ∇kL=g Rm−nq\nabla_kL = g\,R_{m-n}q; in general ∇qL=R−m∇q~L\nabla_qL = R_{-m}\nabla_{\tilde q}L: rotate the upstream gradient back by the token's own angleStep 4 is step 5 applied to ∇q~L=gk~=gRnk\nabla_{\tilde q}L = g\tilde k = gR_nk: R−mRnk=Rn−mkR_{-m}R_nk = R_{n-m}k. The backward pass of RoPE is RoPE with the sign of the position flipped, which in the complex form is multiplication by e−imθpe^{-\mathrm{i}m\theta_p}, the conjugate table. It costs the same as the forward pass and needs no stored activations beyond the positions.

Problem 8

Show that ddφR(φ)=R(φ+π/2)\tfrac{d}{d\varphi}R(\varphi) = R(\varphi + \pi/2). Treating the offset Δ=n−m\Delta = n - m as a continuous variable, compute ∂s/∂Δ\partial s/\partial\Delta for the full score s(Δ)=∑pq(p)⊤R(Δθp)k(p)s(\Delta) = \sum_p q^{(p)\top}R(\Delta\theta_p)k^{(p)}, and compute ∂s/∂θp\partial s/\partial\theta_p for learned or rescaled frequencies.

  1. ddφR(φ)=(−sin⁡φ−cos⁡φcos⁡φ−sin⁡φ)\tfrac{d}{d\varphi}R(\varphi) = \begin{pmatrix}-\sin\varphi & -\cos\varphi\\ \cos\varphi & -\sin\varphi\end{pmatrix}.Differentiate each entry.
  2. R(φ+π/2)=(cos⁡(φ+π/2)−sin⁡(φ+π/2)sin⁡(φ+π/2)cos⁡(φ+π/2))=(−sin⁡φ−cos⁡φcos⁡φ−sin⁡φ)R(\varphi + \pi/2) = \begin{pmatrix}\cos(\varphi + \pi/2) & -\sin(\varphi + \pi/2)\\ \sin(\varphi + \pi/2) & \cos(\varphi + \pi/2)\end{pmatrix} = \begin{pmatrix}-\sin\varphi & -\cos\varphi\\ \cos\varphi & -\sin\varphi\end{pmatrix}.cos⁡(φ+π/2)=−sin⁡φ\cos(\varphi + \pi/2) = -\sin\varphi and sin⁡(φ+π/2)=cos⁡φ\sin(\varphi + \pi/2) = \cos\varphi (the trig-identities page). The two matrices agree.
  3. ∂∂Δq(p)⊤R(Δθp)k(p)=θp q(p)⊤R(Δθp+π/2)k(p)\dfrac{\partial}{\partial\Delta}q^{(p)\top}R(\Delta\theta_p)k^{(p)} = \theta_p\,q^{(p)\top}R(\Delta\theta_p + \pi/2)k^{(p)}.Chain rule: the angle Δθp\Delta\theta_p has derivative θp\theta_p with respect to Δ\Delta, and step 2 gives the derivative of RR with respect to its angle. q(p)q^{(p)} and k(p)k^{(p)} are constants here.
  4. ∂s/∂Δ=∑pθp q(p)⊤R(Δθp+π/2)k(p)\partial s/\partial\Delta = \sum_p\theta_p\,q^{(p)\top}R(\Delta\theta_p + \pi/2)k^{(p)}.Sum step 3 over the pairs.
  5. θp\theta_p appears only in pair pp's term, and the angle Δθp\Delta\theta_p has derivative Δ\Delta with respect to θp\theta_p.Each frequency belongs to one block.
  6. ∂s/∂θp=Δ q(p)⊤R(Δθp+π/2)k(p)\partial s/\partial\theta_p = \Delta\,q^{(p)\top}R(\Delta\theta_p + \pi/2)k^{(p)}.Chain rule as in step 3 with the roles of Δ\Delta and θp\theta_p swapped.
  7. ddφR(φ)=R(φ+π/2)\tfrac{d}{d\varphi}R(\varphi) = R(\varphi + \pi/2); ∂s/∂Δ=∑pθp q(p)⊤R(Δθp+π/2)k(p)\partial s/\partial\Delta = \sum_p\theta_p\,q^{(p)\top}R(\Delta\theta_p + \pi/2)k^{(p)}; ∂s/∂θp=Δ q(p)⊤R(Δθp+π/2)k(p)\partial s/\partial\theta_p = \Delta\,q^{(p)\top}R(\Delta\theta_p + \pi/2)k^{(p)}For one pair, by Problem 3 with φ→φ+π/2\varphi \to \varphi + \pi/2, the derivative is −asin⁡φ+bcos⁡φ-a\sin\varphi + b\cos\varphi, the derivative of acos⁡φ+bsin⁡φa\cos\varphi + b\sin\varphi. The frequency gradient carries a factor Δ\Delta: distant pairs of tokens push the frequencies hardest, which is why learned or fine-tuned frequencies are sensitive to the longest offsets in the training data.

Problem 9

Attention with RoPE: Q~\tilde Q and K~\tilde K have rows (Rmqm)⊤(R_mq_m)^\top and (Rnkn)⊤(R_nk_n)^\top for tokens at positions m,n=1,…,Nm, n = 1, \dots, N, S=Q~K~⊤/dS = \tilde Q\tilde K^\top/\sqrt d, A=softmax⁡(S)A = \operatorname{softmax}(S) row-wise, O=AVO = AV. Using the attention page's results for ∇Q~L\nabla_{\tilde Q}L and ∇K~L\nabla_{\tilde K}L, write ∇qmL\nabla_{q_m}L and ∇knL\nabla_{k_n}L. Then show that shifting every position by the same ss leaves AA and OO unchanged.

  1. ∇Q~L=1d(∇SL)K~\nabla_{\tilde Q}L = \tfrac1{\sqrt d}(\nabla_SL)\tilde K and ∇K~L=1d(∇SL)⊤Q~\nabla_{\tilde K}L = \tfrac1{\sqrt d}(\nabla_SL)^\top\tilde Q.The attention page's Problems 5 and 6, with Q~\tilde Q, K~\tilde K in place of QQ, KK: the attention computation is unchanged, it only receives rotated inputs.
  2. Row mm of Q~\tilde Q depends on qmq_m alone, through q~m=Rmqm\tilde q_m = R_mq_m.Each token is rotated by its own position; no other token's query enters its row.
  3. ∇qmL=Rm⊤ (row m of ∇Q~L)⊤=R−m (∇Q~L)m,:⊤\nabla_{q_m}L = R_m^\top\,(\text{row } m \text{ of } \nabla_{\tilde Q}L)^\top = R_{-m}\,(\nabla_{\tilde Q}L)_{m,:}^\top.Problem 7, step 5, applied to row mm: the upstream gradient at q~m\tilde q_m is row mm of ∇Q~L\nabla_{\tilde Q}L, written as a column.
  4. ∇knL=R−n (∇K~L)n,:⊤\nabla_{k_n}L = R_{-n}\,(\nabla_{\tilde K}L)_{n,:}^\top.The same argument for keys, with k~n=Rnkn\tilde k_n = R_nk_n.
  5. Smn=(Rmqm)⊤(Rnkn)/dS_{mn} = (R_mq_m)^\top(R_nk_n)/\sqrt d depends on mm and nn only through n−mn - m.Problem 4, step 4, for every entry.
  6. Shifting all positions by ss leaves every SmnS_{mn} unchanged, hence AA and O=AVO = AV.(n+s)−(m+s)=n−m(n + s) - (m + s) = n - m; AA is a function of SS and VV is not rotated.
  7. ∇qmL=R−m(1d(∇SL)K~)m,:⊤\nabla_{q_m}L = R_{-m}\big(\tfrac1{\sqrt d}(\nabla_SL)\tilde K\big)_{m,:}^\top, ∇knL=R−n(1d(∇SL)⊤Q~)n,:⊤\nabla_{k_n}L = R_{-n}\big(\tfrac1{\sqrt d}(\nabla_SL)^\top\tilde Q\big)_{n,:}^\top: each row of the attention page's gradient rotated back by its own position; AA and OO are invariant to a common shift of all positionsSo RoPE is a layer wrapped around attention: forward, rotate QQ and KK row by row; backward, rotate the gradients back row by row and hand the rest to the attention page. The shift invariance means a RoPE model sees no absolute position at all; the only asymmetry it has is the causal mask, which tells a token how many keys lie before it.

Problem 10

Position interpolation extends a model trained at context L0L_0 to context sL0sL_0 by using positions m/sm/s in place of mm. Show that this equals keeping the positions and dividing every frequency by ss, that every wavelength is multiplied by ss, and compute, for d=128d = 128 and s=4s = 4, how many pairs now complete a turn within 40964096 positions.

  1. Pair pp at position m/sm/s is rotated by (m/s)θp=m(θp/s)(m/s)\theta_p = m(\theta_p/s).The angle is a product, and the factor 1/s1/s can be attached to either side.
  2. So the score with positions m/sm/s, n/sn/s and frequencies θp\theta_p equals the score with positions mm, nn and frequencies θp/s\theta_p/s.Step 1 applies to every pair of every query and key; the rotated vectors are identical.
  3. The wavelength becomes 2π/(θp/s)=s⋅2π/θp2\pi/(\theta_p/s) = s\cdot 2\pi/\theta_p.Problem 6's definition with the new frequency.
  4. Pair pp completes a turn within 40964096 iff s⋅2π/θp≤4096s\cdot 2\pi/\theta_p \le 4096 iff 100002(p−1)/128≤4096/(2πs)=4096/(8π)≈163.010000^{2(p-1)/128} \le 4096/(2\pi s) = 4096/(8\pi) \approx 163.0.Problem 6, step 4, with 2πs2\pi s in place of 2π2\pi.
  5. p−1≤128ln⁡163.02ln⁡10000≈128⋅5.09418.42≈35.4p - 1 \le \dfrac{128\ln 163.0}{2\ln 10000} \approx \dfrac{128\cdot 5.094}{18.42} \approx 35.4, so p≤36.4p \le 36.4.Take logs as in Problem 6, step 5.
  6. Positions m/sm/s with frequencies θp\theta_p equal positions mm with frequencies θp/s\theta_p/s; wavelengths scale by ss; at d=128d = 128, s=4s = 4, 3636 pairs complete a turn within 40964096 positions, down from 4646The first pair's wavelength goes from 2π2\pi to 8π8\pi positions. Every angle the model sees at the long context is one it saw during training (its range is the same as at L0L_0), which is why interpolation needs little fine-tuning; the cost is that adjacent positions now differ by a quarter of the angle they used to, so the fast pairs resolve neighbours less sharply. Schemes such as NTK-aware scaling and YaRN divide the slow pairs' frequencies by more than the fast pairs', trading between the two effects, and Problems 6 and 10 are the arithmetic they rest on.

Where this goes wrong

1. Rotating the query and the key by the same angle

RoPE is applied to queries and keys with one function, and the position passed in has to be the right one for each.

  1. q~=Rmq\tilde q = R_mq for the query at position mmRight so far.
  2. “Apply the same rotation to the key.”The slip that causes the mistake: the key belongs to position nn, and its rotation must use nn, not the query's mm.
  3. s=(Rmq)⊤(Rmk)=q⊤Rm⊤Rmk=q⊤ks = (R_mq)^\top(R_mk) = q^\top R_m^\top R_mk = q^\top kProblem 4, step 1 with n=mn = m: Rm⊤Rm=IR_m^\top R_m = I. Every score is the plain dot product, the positions have cancelled completely, and the model is a bag of tokens with no position information at all; the loss still goes down, so nothing fails loudly.

2. Transposing the wrong rotation

The relative-position step has a transpose in it, and which rotation carries it decides the sign of the offset.

  1. (Rmq)⊤(Rnk)=q⊤Rm⊤Rnk(R_mq)^\top(R_nk) = q^\top R_m^\top R_nkRight so far: Problem 2, step 1.
  2. “Rm⊤RnR_m^\top R_n is the rotation by m−nm - n.”The shortcut that causes the mistake: the transposed factor is the one whose angle is negated, so Rm⊤Rn=R−mRn=Rn−mR_m^\top R_n = R_{-m}R_n = R_{n-m}.
  3. s=q⊤Rm−nks = q^\top R_{m-n}kThe offset's sign is flipped. For one pair the score is acos⁡φ+bsin⁡φa\cos\varphi + b\sin\varphi (Problem 3), and φ→−φ\varphi \to -\varphi flips the sign of the bb term, so the two agree only when b=q2k1−q1k2=0b = q_2k_1 - q_1k_2 = 0, that is, when qq and kk are parallel. In Problem 7 the same slip gives ∇qL=gRm−nk\nabla_qL = gR_{m-n}k in place of gRn−mkgR_{n-m}k, which fails a gradient check for every pair of positions except m=nm = n.

3. Rotating the values as well

The rotation is applied to two of the three projections, and the third looks like an omission.

  1. q~m=Rmqm\tilde q_m = R_mq_m and k~n=Rnkn\tilde k_n = R_nk_n give SmnS_{mn} depending on n−mn - m onlyRight so far: Problem 4.
  2. “For consistency, rotate VV by position too.”The analogy that causes the mistake: QQ, KK and VV are produced alike, so they should be treated alike; but position enters attention through the scores, and VV never touches a score.
  3. Om=∑nAmnRnvnO_m = \sum_n A_{mn}R_nv_nShifting all positions by ss leaves AA unchanged (Problem 9) but replaces RnR_n by Rn+sR_{n+s}, so the output of every token changes with the absolute position of the sequence, and the relative-position property is lost at the output. With the rotation on QQ and KK only, Om=∑nAmnvnO_m = \sum_nA_{mn}v_n is invariant to the shift.

4. Backward pass that rotates forwards

The backward pass of a layer reuses the forward code, and for RoPE the forward code rotates by +mθp+m\theta_p.

  1. q~=Rmq\tilde q = R_mq and the upstream gradient u=∇q~Lu = \nabla_{\tilde q}LRight so far.
  2. “The gradient flows back through the same rotation.”The shortcut that causes the mistake: the backward of a linear map is its transpose, and Rm⊤=R−mR_m^\top = R_{-m} is the rotation the other way.
  3. ∇qL=Rmu\nabla_qL = R_muProblem 7 gives R−muR_{-m}u. For the score s=q~⊤k~s = \tilde q^\top\tilde k this makes ∇qL=gRmRnk=gRm+nk\nabla_qL = gR_mR_nk = gR_{m+n}k instead of gRn−mkgR_{n-m}k: a gradient with the right norm and the wrong direction, by the angle 2mθp2m\theta_p in pair pp. In the complex implementation the fix is one conjugate: multiply by e−imθpe^{-\mathrm{i}m\theta_p} on the way back.

5. Pairing the coordinates differently for queries and keys

The paper pairs coordinate 2p−12p - 1 with 2p2p; many implementations pair jj with j+d/2j + d/2. Both are RoPE, until they are mixed.

  1. Pair (q2p−1,q2p)(q_{2p-1}, q_{2p}) rotated by mθpm\theta_p, and the same pairing for kk, gives a score depending on n−mn - mRight so far: Problem 4, whichever fixed pairing is used, provided it is the same for qq and kk.
  2. “The pairing is a convention, so the query code can use one and the key code (or the pretrained weights) another.”The assumption that causes the mistake: Problem 2 cancels Rm⊤RnR_m^\top R_n block by block, which needs the blocks of RmR_m and RnR_n to sit on the same pairs of coordinates.
  3. Rotate (q2p−1,q2p)(q_{2p-1}, q_{2p}) by mθpm\theta_p but (kj,kj+d/2)(k_j, k_{j+d/2}) by nθjn\theta_jRm⊤RnR_m^\top R_n is no longer block-diagonal on matching pairs, so the score is not a function of n−mn - m: it changes when the sequence is shifted, and the model trained with one convention is garbage under the other. This is the bug behind permuting the query and key projection weights when converting checkpoints between the two layouts; the test is Problem 4, step 4: compute the score at (m,n)(m, n) and at (m+s,n+s)(m + s, n + s) and check they agree.

Print this set: rotary-position-embeddings.pdf (problems, answers, and worked solutions on separate pages).