AI Wiki中文/EN

Rotary embeddings: relative position through rotation

旋转位置编码

Verify the rotation identity, coordinate layout and cached offsets; test a decay counterexample.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Turn two arrows, then compare their directions

Imagine attaching an arrow to each token. Rotate each arrow by an angle determined by its position. If both positions move by the same amount, both arrows turn together, preserving their inner product. Their relative rotation still changes when only one position moves.

Rotary position embedding, or RoPE, applies this idea to projected query and key vectors. RoFormer develops the rotation construction; the authors’ repository shows adjacent-coordinate pseudo-code. The content vectors still matter: RoPE does not replace attention scores with a distance-only lookup. Begin with positional encoding and orthogonal matrices.

Unit vectors can turn back toward one another; the complete sampled cosine shows why distance alone does not force decay.
Unit vectors can turn back toward one another; the complete sampled cosine shows why distance alone does not force decay.

The relative position appears inside the dot product

For a column vector with two coordinates, use the ordinary counterclockwise rotation:

R(ϕ)=[cos⁡ϕ−sin⁡ϕsin⁡ϕcos⁡ϕ].R(\phi)=\begin{bmatrix}\cos\phi&-\sin\phi\\\sin\phi&\cos\phi\end{bmatrix}.

For an even-dimensional head, split the coordinates into adjacent pairs. Give each pair its own frequency and assemble the rotations into a block-diagonal matrix. With zero-based frequency index j:

ωj=10000−2j/d,Rm=diag⁡(R(mω0),…,R(mωd/2−1)),q~m=RmWQxm,k~n=RnWKxn.\omega_j=10000^{-2j/d},\quad R_m=\operatorname{diag}\big(R(m\omega_0),\ldots,R(m\omega_{d/2-1})\big),\quad \widetilde q_m=R_mW_Qx_m,\quad \widetilde k_n=R_nW_Kx_n.

The rotation follows the content projection. In this construction, queries and keys are rotated; values are not. R_m denotes the whole block matrix, not one shared angle for every coordinate pair.

The useful identity follows from multiplying orthogonal rotations. Define unrotated q_m and k_n as the projected content vectors. Their encoded dot product is:

q~m⊤k~n=qm⊤Rm⊤Rnkn=qm⊤Rn−mkn,qm=WQxm,kn=WKxn.\widetilde q_m^\top\widetilde k_n=q_m^\top R_m^\top R_nk_n=q_m^\top R_{n-m}k_n,\qquad q_m=W_Qx_m,\quad k_n=W_Kx_n.

Only the relative offset enters this explicit positional factor. Holding the unrotated vectors fixed, adding a common offset to m and n does not change the result. In a multilayer network those vectors may themselves depend on position-sensitive earlier computations, so this algebra is not a claim that complete model outputs ignore absolute position or surrounding content.

The same construction preserves norms and has a simple composition law:

∥Rmq∥2=∥q∥2,Rm⊤Rn=Rn−m,RmRn=Rm+n.\|R_mq\|_2=\|q\|_2,\qquad R_m^\top R_n=R_{n-m},\qquad R_mR_n=R_{m+n}.

Norm preservation prevents this rotation alone from magnifying a vector. It does not bound learned projection norms, eliminate floating-point error or guarantee stable optimization.

A frequently overextended claim concerns distance decay. Activate only one pair, and use the same unit content vector for both query and key. Its scaled attention score becomes:

q=k=[10],smn=q⊤R((n−m)ω)k2=cos⁡((n−m)ω)2.q=k=\begin{bmatrix}1\\0\end{bmatrix},\qquad s_{mn}=\frac{q^\top R((n-m)\omega)k}{\sqrt2}=\frac{\cos((n-m)\omega)}{\sqrt2}.

This oscillates. With frequency one, the score increases from distance three to distance six. The selected RoFormer version discusses an Abel-summation bound and illustrates a long-range trend; that discussion does not prove that every possible query-key score decreases monotonically. The program deliberately includes the simple counterexample. Its displayed single-pair curve is the raw inner product, before division by the square root of two.

Caching needs the same position convention as the original computation. If P tokens are already cached, the new query row r uses position P+r, not r:

mr=P+r,q~mr⊤k~j=qmr⊤Rj−(P+r)kj.m_r=P+r,\qquad \widetilde q_{m_r}^{\top}\widetilde k_j=q_{m_r}^{\top}R_{j-(P+r)}k_j.

Resetting the query’s position while retaining already rotated cached keys changes the relative offsets. Multiplying every position by a new scale is also a different operation from a common translation: it changes the relative phases.

Verify identities before trying longer contexts

Save as rotary_embeddings.py and run with Python 3 and NumPy. No network is trained or downloaded.

"""Original RoPE algebra and counterexamples; adjacent coordinate pairs."""
import json
import numpy as np


def rotate(x, positions, base=10000.):
    x = np.asarray(x, dtype=float);p = np.asarray(positions, dtype=float)
    if x.ndim != 2 or not x.size or max(x.shape)>128 or x.shape[1]%2 or p.shape != (len(x),):
        raise ValueError('bounded matrix with even width and matching positions required')
    if not np.isfinite(x).all() or not np.isfinite(p).all() or not np.isfinite(base) or base<=1:
        raise ValueError('finite inputs and base>1 required')
    f = base ** (-np.arange(0, x.shape[1], 2)/x.shape[1]);angle = p[:, None]*f
    c,s = np.cos(angle),np.sin(angle);y = np.empty_like(x)
    y[:,0::2] = x[:,0::2]*c - x[:,1::2]*s
    y[:,1::2] = x[:,0::2]*s + x[:,1::2]*c
    return y


def scores(q, k, qp, kp):return rotate(q,qp) @ rotate(k,kp).T / np.sqrt(np.shape(q)[1])


def demo():
    rng = np.random.default_rng(12);q=rng.normal(size=(5,8));k=rng.normal(size=(5,8));p=np.arange(5)
    direct=scores(q,k,p,p)
    relative=np.array([[q[i] @ rotate(k[j:j+1],[j-i])[0]/np.sqrt(8) for j in range(5)] for i in range(5)])
    delta=np.arange(17);unit=np.array([[1.,0.]])
    oscillation=(rotate(np.repeat(unit,len(delta),axis=0),delta) @ unit.T)[:,0]
    # A single common offset preserves logits; changing the position scale does not.
    return dict(norm_error=float(np.max(np.abs(np.linalg.norm(rotate(q,p),axis=1)-np.linalg.norm(q,axis=1)))),
                relative_identity_error=float(np.max(np.abs(direct-relative))),
                common_offset_error=float(np.max(np.abs(direct-scores(q,k,p+40,p+40)))),
                doubled_positions_gap=float(np.max(np.abs(direct-scores(q,k,2*p,2*p)))),
                cached_offset_error=float(np.max(np.abs(scores(q[3:],k,p[3:],p)-direct[3:]))),
                wrongly_reset_query_gap=float(np.max(np.abs(scores(q[3:],k,[0,1],p)-direct[3:]))),
                distances=delta.tolist(),single_pair_scores=oscillation.tolist(),
                adjacent_vs_split_half_note='This implementation rotates adjacent pairs; a different layout needs a consistent weight permutation.')


if __name__ == '__main__':print(json.dumps(demo(),indent=2))

The eight-dimensional test preserves vector norms and the relative-position identity to within about 5e-16. Shifting all positions by 40 has the same precision-level agreement. Doubling positions changes scores by about 1.01000. Correct cached query offsets match the full result; resetting the two new queries to positions zero and one creates a maximum difference about 1.23793.

The first coordinate pair also traces a cosine over integer distances 0–16. A plot that shows only its downward segment would hide the counterexample. Keep both downward and upward segments when checking a proposed decay explanation.

Rotating n vectors of width d costs order nd and needs no learned parameters for a fixed frequency schedule. Storing sine/cosine tables for n positions also costs order nd, though values can instead be generated as needed. Dense attention remains quadratic in sequence length. Avoid forming a dense d-by-d rotation matrix when pairwise arithmetic suffices.

Layout and extrapolation are separate questions

The implementation pairs coordinates (0,1), (2,3) and so on. Other implementations pair coordinates from two halves. A consistent coordinate permutation can relate these layouts, but switching the rotation formula without transforming the associated weights or cached vectors changes the model. Shape compatibility does not establish mathematical equivalence.

The formula accepts positions beyond a training window, but useful long-context behavior is empirical. Larger phases, numerical precision, frequency changes and the learned use of position all matter. Padding and cache offsets must follow the position-ID policy used by the actual model. This small algebra test provides no natural-language benchmark or guarantee about an extended context window.

Track the sign and the position origin

  1. Rotate the column vector [1,0] through π/2. What happens to its norm?

Answer: It becomes [0,1], with norm one. The inverse rotation returns it to the starting vector. The coordinate order is important: a shift matrix for a [sin,cos] pair uses a different sign arrangement.

  1. Let the query be [1,0] at position zero and the key be [0,1] at position π/2, with frequency one. What is the scaled score?

Answer: The key rotates to [-1,0], so the raw dot product is minus one and the scaled score is minus one divided by the square root of two. This checks the key position minus query position sign in the relative rotation.

  1. Three tokens are cached and two new queries arrive. Which positions should those queries use, and why is a reset wrong?

Answer: They use three and four. Resetting to zero and one while cached keys retain their original positions changes the query-key phase differences. The program checks this error without requiring any language-model training.

  1. Does preservation of vector norms imply that attention scores decrease with distance?

Answer: No. Fixed-length arrows can rotate back toward one another. The single active pair gives a cosine: its value near distance six is higher than at distance three. A constant magnitude bound and a monotonic-decay claim are different statements.

Separate the construction from its broader claims

The selected RoFormer v5 is the November 2023 revision of work first submitted in 2021. We use its rotation construction and inspect its decay argument rather than treating an informal summary as a universal theorem. The fixed 2022 repository README is a separate historical artifact with a useful pseudo-code illustration; it is not executed here. Compare the multiplicative construction with relative position representations, where learned vectors or scalar biases directly modify pairwise attention.

Make a prediction, then check

Must every RoPE query-key score decrease as distance grows?

Choose one answer

Learning objectives

  • Derive relative logits and norm preservation.
  • Track paired coordinates and cache offsets.
  • Construct a nonmonotonic distance counterexample.

Prerequisites & connections

Explore related knowledge →

References

  1. RoFormer: Enhanced Transformer with Rotary Position Embedding (v5)
    Jianlin Su; Yu Lu; Shengfeng Pan; Ahmed Murtadha; Bo Wen; Yunfeng Liu · 2023
  2. ZhuiyiTechnology/roformer: README.md @dfc678a
    ZhuiyiTechnology/roformer contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read RoFormer v5 sections3.1-3.2.2/3.4.3 and fixed author README pseudo-code; PDF5/8 viewed. Six paired equations and four exercises; norm and relative rotation identities, adjacent coordinate layout, absolute cache offsets and a nonmonotonic cosine counterexample. No universal score-decay theorem or extended-context benchmark.

  • Single AI author read RoFormer v5 sections3.1-3.2.2/3.4.3 and fixed author README pseudo-code; PDF5/8 viewed. Six paired equations and four exercises; norm and relative rotation identities, adjacent coordinate layout, absolute cache offsets and a nonmonotonic cosine counterexample. No universal score-decay theorem or extended-context benchmark.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial text-coordinate precision assertion and visual-label refinements preserved. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.