Rotary Position Embeddings (RoPE)

A positional encoding that rotates queries and keys so attention depends on relative position via phase differences.

published · difficulty 3/5 · 14 min read

Reading map and next steps

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

Self-attention by itself does not know token order: it only sees a set of vectors and compares them.

RoPE injects position by rotating each token's query and key vectors by an angle that depends on its position. The magic is that when you take a dot product between a rotated query at position pp and a rotated key at position qq, the result depends on the relative offset (q−p)(q-p).

A good mental model is "clock hands at multiple speeds":

  • high-frequency rotations capture local order (nearby tokens),
  • low-frequency rotations capture long-range order (far-apart tokens).
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

In a 2D subspace, define a rotation matrix:

R(θ)=(cos⁡θ−sin⁡θsin⁡θcos⁡θ).R(\theta) = \begin{pmatrix} \cos\theta & -\sin\theta \\\\ \sin\theta & \cos\theta \end{pmatrix}.

RoPE rotates queries/keys by position-dependent angles, and their dot product reduces to a relative angle:

q~p⊤k~q=qp⊤R(θq−θp)kq,q~p=R(θp)qp,k~q=R(θq)kq,R(θp)⊤R(θq)=R(θq−θp).\tilde q_p^\top \tilde k_q = q_p^\top R(\theta_q - \theta_p) k_q, \qquad \tilde q_p = R(\theta_p) q_p, \qquad \tilde k_q = R(\theta_q) k_q, \qquad R(\theta_p)^\top R(\theta_q)=R(\theta_q-\theta_p).

So attention can depend on relative position through (θq−θp)(\theta_q-\theta_p).

In practice, RoPE applies this to many 2D pairs with different frequencies. A common choice is:

θp,i=p ωi,ωi=base−2i/d,\theta_{p,i} = p\,\omega_i, \qquad \omega_i = \mathrm{base}^{-2i/d},

where dd is head dimension and ii indexes the 2D pairs.

RoPE applies this rotation independently to each 2D coordinate pair (2i,2i+1)(2i,2i+1) of a head, so dd is typically even and i∈{0,…,d2−1}i \in \{0,\dots,\frac d2-1\}.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
import numpy as np

def R(theta):
    c, s = np.cos(theta), np.sin(theta)
    return np.array([[c, -s], [s, c]])

def rope_dot(q, k, p, qpos, w):
    return float((R(p * w) @ q) @ (R(qpos * w) @ k))

q = np.array([1.0, 0.2])
k = np.array([0.3, 1.0])
w = 0.7  # one frequency, for illustration

for delta in [0, 1, 2, 4, 8]:
    a = rope_dot(q, k, p=0, qpos=delta, w=w)
    b = rope_dot(q, k, p=5, qpos=5 + delta, w=w)  # same relative offset
    print("delta =", delta, "dot =", round(a, 3), "dot (shifted) =", round(b, 3))
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

Live Concept Demo

Explore Rotary Position Embeddings (RoPE)

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Efficient Attention at Scale: KV Cache, GQA & FlashAttention

Choose what to inspect in Rotary Position Embeddings (RoPE). This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Use the demo to rotate queries/keys and see how relative position becomes a phase difference that attention can learn to exploit.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Rotary Position Embeddings (RoPE)

What is the smallest example that makes Rotary Position Embeddings (RoPE) click without losing the math?

BeforeScaled Dot-Product Attention & Transformer LayersNow4/4 sections readyTryManipulate one control and predict the visible change.NextEfficient Attention at Scale: KV Cache, GQA & FlashAttention
Object contextAttention & Transformers
ConceptLearner lens

Rotary Position Embeddings (RoPE)

What is the smallest example that makes Rotary Position Embeddings (RoPE) click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inScaled Dot-Product Attention & Transformer Layers

Bring the mental model from Scaled Dot-Product Attention & Transformer Layers; this page will reuse it instead of restarting from zero.

Work hereRotary Position Embeddings (RoPE)

A positional encoding that rotates queries and keys so attention depends on relative position via phase differences.

Carry outEfficient Attention at Scale: KV Cache, GQA & FlashAttention

The next edge should feel earned: use the demo prediction here before following Efficient Attention at Scale: KV Cache, GQA & FlashAttention.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptRotary Position Embeddings (RoPE)Attention & Transformers

Mechanism Storyboard

See the idea move before the page explains it

A positional encoding that rotates queries and keys so attention depends on relative position via phase differences.

Demo notes open01 / Intuition
Editorial transformer illustration of rotary position vectors, relative phase arcs, and query-key geometry.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Rotary Position Embeddings (RoPE) should make visible.

Visual Inquiry

Make the image answer a mathematical question

A positional encoding that rotates queries and keys so attention depends on relative position via phase differences.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Rotary Position Embeddings (RoPE) easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

Object - ConceptRotary Position Embeddings (RoPE)Question

What is the smallest example that makes Rotary Position Embeddings (RoPE) click without losing the math?

concept:attention-transformers/rope
Boundary

sources: su-2021-roformer

Check

Open the closest source note before trusting the local explanation.

Evidence

1 selected-object source shown first; 1 reference total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · paper · 2021RoFormer: Enhanced Transformer with Rotary Position EmbeddingSu et al.
Located CF editorial boundary

Primary RoPE source. Sections 3.1-3.2 derive position-dependent rotations for q/k and show the query-key inner product uses the relative rotary product R_{Theta,n-m}.

Used here as

Su et al. state that RoPE encodes absolute position with a rotation matrix and incorporates explicit relative-position dependency in self-attention; Sec. 3.1 frames the q-k inner product...

Caveat

Checks only RoPE's rotary q/k attention-score mechanism; not RoPE scaling, arbitrary long-context extrapolation, YaRN/LongRoPE, KV-cache behavior, or production model performance.

Open source

Claim Review

A positional encoding that rotates queries and keys so attention depends on relative position via phase differences.

Object - ConceptRotary Position Embeddings (RoPE)Question

What is the smallest example that makes Rotary Position Embeddings (RoPE) click without losing the math?

concept:attention-transformers/rope
Boundary

sources: su-2021-roformer

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 1 reference and 3 local witnesses are available for inspection.

RoPE encodes absolute token positions by rotating query and key vectors, so their dot product can depend on relative position through the phase difference between positions.
Used here as

Su et al. state that RoPE encodes absolute position with a rotation matrix and incorporates explicit relative-position dependency in self-attention; Sec. 3.1 frames the q-k inner product as a function of emb...

Local witness
Equation 1
R(θ)=(cos⁡θ−sin⁡θsin⁡θcos⁡θ).R(\theta) = \begin{pmatrix} \cos\theta & -\sin\theta \\\\ \sin\theta & \cos\theta \end{pmatrix}.
Equation 2
q~p⊤k~q=qp⊤R(θq−θp)kq,q~p=R(θp)qp,k~q=R(θq)kq,R(θp)⊤R(θq)=R(θq−θp).\tilde q_p^\top \tilde k_q = q_p^\top R(\theta_q - \theta_p) k_q, \qquad \tilde q_p = R(\theta_p) q_p, \qquad \tilde k_q = R(\theta_q) k_q, \qquad R(\theta_p)^\top R(\theta_q)=R(\theta_q-\theta_p).
Caveat

Checks only RoPE's rotary q/k attention-score mechanism; not RoPE scaling, arbitrary long-context extrapolation, YaRN/LongRoPE, KV-cache behavior, or production model performance.

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. Check caveats and exact source scope.

Checked RoFormer abstract/introduction and Sec. 3.1-3.2: RoPE uses position-dependent rotations for q/k, the 2D complex form has phase gap m-n, and the general self-attention score contains R_{Theta,n-m}. Local math/code/demo witness the toy relative-angle mechanism.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice · Rotary Position Embeddings (RoPE)

Try the idea in your own words

A positional encoding that rotates queries and keys so attention depends on relative position via phase differences.

Concept · Current object

Rotary Position Embeddings (RoPE)

Source boundary: sources: su-2021-roformer

Object context and links

Attention & Transformers

concept:attention-transformers/rope
Choose a task

Explain the mechanism

For Rotary Position Embeddings (RoPE): What is the smallest example that makes Rotary Position Embeddings (RoPE) click without losing the math? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Local to this page session. Not saved after leaving or reloading.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer does not erase help history. Outside help cannot be verified here.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    This draft and any AI response do not establish mastery. Try a different case later without help; this page has not measured that learning.

    Grounded object roomClose
    Selected object routeAsk from this object; carry one invariant back.sources: su-2021-roformer
    1. ObjectConceptRotary Position Embeddings (RoPE)
    2. PredictBefore revealRotary Position Embeddings (RoPE) prediction
    3. WitnessCompare codeRotary Position Embeddings (RoPE) code witness 1
    4. RoomAsk groundedChecking local snapshot
    ConceptRotary Position Embeddings (RoPE)Attention & Transformers

    Research Room

    Attach the question to an exact object

    Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptAttention & Transformers

    Rotary Position Embeddings (RoPE)

    Anchored question

    What is the smallest example that makes Rotary Position Embeddings (RoPE) click without losing the math?

    Source boundaryInspect source ids: su-2021-roformerStable content-object key attached
    Role lenses for this object

    These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

    Learner evidence requestAsk what would make "Rotary Position Embeddings (RoPE)" feel predictable rather than familiar.
    Assumption

    Source ids su-2021-roformer must support the exact object, not just the surrounding topic.

    Source-checking summary

    Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

    Proposed experiment

    Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

    Next action

    The learner can state the mechanism in their own words

    Evidence4 checks
    PredictionChecking carried observation
    ActionReady for one action
    AILearner handoff ready
    Open source object
    01PredictionChecking browser-local route memory
    02EvidenceChecking for a carried observation
    03BoundaryInspect source ids: su-2021-roformer
    04Next moveSave one next action
    Local action draftNo local draft saved yetExpand only when ready to capture one local next action
    Local action draft

    This draft stays locally in this browser for concept:attention-transformers/rope.

    No local draft saved.
    Evidence to inspect
    • Source ids to inspect: su-2021-roformer
    • Definition, prerequisite, and contrast concept links
    • The equation or code witness that makes the concept operational
    • One demo state that shows the invariant instead of a slogan
    What would resolve this
    • The learner can state the mechanism in their own words
    • The learner can name the prerequisite that would repair confusion
    • The learner can predict how the mechanism changes under one perturbation
    Object-attached AI handoff

    I am working in Continuous Function's research reading room. Object: concept - Rotary Position Embeddings (RoPE) Object key: concept:attention-transformers/rope Context: Attention & Transformers Anchor id: concept/concept-notebook/attention-transformers/rope Open question: What is the smallest example that makes Rotary Position Embeddings (RoPE) click without losing the math? Evidence to inspect: - Source ids to inspect: su-2021-roformer - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids su-2021-roformer must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Rotary Position Embeddings (RoPE)" feel predictable rather than familiar." | assumption: Source ids su-2021-roformer must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: su-2021-roformer" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Rotary Position Embeddings (RoPE)" feel predictable rather than familiar. - Assumption to keep visible: Source ids su-2021-roformer must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

    concept/concept-notebook/attention-transformers/rope concept:attention-transformers/rope