Sources. This article primarily draws on Jianlin Su’s “Transformer Upgrade Path 2: Rotary Position Embedding That Combines the Best of Both Worlds”, together with the RoFormer, Linear Transformer, and Performer papers.
Thirty-second summary. In the previous article, “Rereading the Transformer Upgrade Path (1): Tracing Sinusoidal Positional Encoding to Its Source”, every sin/cos pair acts like a “position clock” that represents a position as coordinates on the unit circle. RoPE uses the same position angles but no longer adds a position vector to the token. Instead, it places the sin/cos values inside a rotation operator and directly rotates the content-derived Query and Key. Position rotates by , and position by ; when the rotated vectors are compared by an inner product, the shared absolute rotation cancels, leaving only . RoPE therefore does not multiply an already constructed attention-logit matrix by distance weights. It changes how Queries and Keys are compared before those logits exist.
First establish the global picture: RoPE performs only four steps inside one attention computation.
- Produce position-free vectors and from the token representations;
- For the -th feature pair, is the rotation increment in radians for each one-token step, so the accumulated angle at position is ; for positions , obtain the corresponding and ;
- Rotate the Query and Key within the feature dimensions of each attention head: ;
- Only then compute and assemble all into the logit matrix.
is a block rotation acting on the feature dimensions of one token. It is not the attention matrix. At no point does RoPE take an elementwise product between a logit matrix and a rotation matrix.
We will repeatedly use the following notation:
| Symbol | Meaning |
|---|---|
| Absolute positions of the Query and Key | |
| Displacement of the Query relative to the Key | |
| Token representation at position | |
| Query, Key, and Value before positional information is introduced | |
| Query/Key dimensionality of one attention head, assumed even in this article | |
| Matrix that rotates a vector counterclockwise by in the two-dimensional plane | |
| Block matrix that rotates every dimension pair in a complete attention head by | |
| Radians rotated by the -th dimension pair for each token step |
The core RoPE path ends with the quick reference in Section 8. Section 9 discusses ways to combine RoPE with linear attention; it is not required for understanding RoPE itself and can be skipped entirely.
1. What Gap in Sinusoidal PE Is RoPE Trying to Fill?
First, put positional encoding aside. Standard self-attention produces three groups of vectors from token representations:
A Query can be understood as “what position is looking for,” a Key as “which features position can be found by,” and a Value as the information actually retrieved after that position has been selected. Their inner product
determines how well the Query and Key match.
The problem is that if neither nor carries position, then this match compares only content and does not know how many steps separate the two tokens.
The previous article introduced Sinusoidal positional encoding, which first constructs a position vector and then adds it to the token representation. To describe additive PE and RoPE in the same language, write “adding a position vector” as a position-dependent transformation:
The second argument tells the function which to use. Projecting the transformed tokens into Queries and Keys gives
Now expand their inner product without skipping any terms:
The four terms are content—content, content—position, position—content, and position—position. The previous article showed that the Sinusoidal vectors themselves have a clean relative-phase structure—for example, depends only on . But the complete score above also passes through and mixes in the other three terms, so it is not forced into a form in which position appears only through .
This naturally suggests the next step. If position ultimately exists to affect the Query—Key comparison, can we define a more suitable position transformation directly on the Query and Key? Denote these two transformations by
RoPE’s core motivation
We want to find a pair of position transformations, and . They first write the absolute positions into the Query and Key; after the transformed vectors are compared by an inner product, the position variables should appear only through the relative displacement :
The left-hand side contains the transformations we still need to design; the right-hand side states the form we want their inner product to take. In other words, we work backward from the relative-position target instead of choosing first and merely hoping that the desired structure emerges.
This does not require the score to depend on distance alone: the right-hand side still retains the Query and Key content . Only the position variables are restricted, and they may appear only through . RoPE’s concrete choice is to let both and use rotations determined by position.
This objective has an intuitive test. If both tokens are shifted backward by positions, their relative distance does not change:
We therefore also want the content match to remain unchanged after this shared shift. All that remains is to construct a simple transformation with this property.
2. Properties of Two-Dimensional Rotation Matrices
2.1 What Exactly Does a Rotation Matrix Do?
In the two-dimensional plane, a vector
becomes
after a counterclockwise rotation by .
For example, take , which initially points along the positive horizontal axis. After a rotation by ,
so it now points along the positive vertical axis. Rotation changes the direction of a vector, not its length.
2.2 Why Does the Transpose Equal the Reverse Rotation?
Transposing the rotation matrix swaps its rows and columns:
On the other hand,
so
The two matrices are identical entry by entry. Therefore,
The geometry is just as simple: after rotating a hand by , restoring it to its original direction requires a rotation by .
2.3 Why Can Two Consecutive Rotations Add Their Angles?
First rotating by and then by corresponds to the matrix product
To expose every term, temporarily abbreviate as , and as :
Now apply the angle-sum identities for sine and cosine:
The product above becomes
Hence,
If there is only one sentence to remember, it is this: rotations multiply; their angles add.
3. How Does RoPE Make the Inner Product Depend Only on Relative Position?
Now take one two-dimensional Query and Key:
Choose a fixed per-step rotation angle . This is not a new signal that appears from nowhere. It is the same per-step phase increment used by Sinusoidal PE. For the -th dimension pair, define
Sinusoidal PE treats these two numbers as a pair of coordinates in a position vector. RoPE places the same two numbers inside a rotation operator:
The precise relationship is therefore not “first construct a Sinusoidal position vector and then convert it into RoPE.” Instead, both methods generate sin/cos values from the same position angles; Sinusoidal PE uses them as coordinates to add, whereas RoPE uses them as rotation coefficients to multiply. Implementations normally cache these sin/cos values directly, without explicitly constructing or the full matrix .
Continue with one two-dimensional pair. At position , RoPE rotates the Query by ; at position , it rotates the Key by :
Take the inner product of the rotated vectors:
The three steps use, respectively:
- ;
- ;
- .
Only remains as a position variable in the final expression:
Although the Query and Key are each rotated according to their absolute positions , when they meet in the inner product they see only their relative position.
If both positions are shifted by , then similarly
The shared disappears. This is the matrix form of “a global shift does not change a relative relationship.”
4. RoPE Does Not Reweight an Existing Attention-Logit Matrix
The previous section proved that position appears only through , but we must first rule out a natural misconception. RoPE does not compute the original logit matrix and then multiply every by a distance-dependent weight.
4.1 The Two Operations Use a Different Order
Elementwise distance weighting would have the form
where . Each original logit can only be enlarged, reduced, or sign-flipped by the scalar .
RoPE uses a different order. It first rotates the Query and Key inside the -dimensional feature space of each token and only then constructs the logit matrix:
mix each pair of feature coordinates. They are not the same object as the matrix , and no elementwise product is taken between them. The simplest distinction is that scalar reweighting can never turn an original zero logit into a nonzero value, whereas relative rotation can change the coordinate alignment and do exactly that.
4.2 How Does Relative Rotation Change Content Matching?
We can now answer the more intuitive question: for the same Query and Key, why does changing the relative position change their matching score?
Let
Because , the two-dimensional RoPE score can be written as
To keep every step visible, first write out the two factors on the right:
and
The second equality uses the fact that cosine is even and sine is odd: and .
First multiply the matrix and the vector:
Now write the transposed Query explicitly as a row vector:
The inner product can then be evaluated one line at a time:
The RoPE score therefore contains two parts:
The easiest misconception here is to imagine RoPE as “multiplying the original dot product by a distance cosine.” Only the first term has that form. The second term also cross-compares the first coordinate of the Query with the second coordinate of the Key, and the second coordinate of the Query with the first coordinate of the Key.
What does this expression actually say? Two controlled experiments make it concrete. To keep the rotations easy to calculate mentally, temporarily take , so a one-position difference means a rotation. This is a toy setting chosen to magnify the mechanism, not the only frequency used by a real model.
| Experiment | Query | Original Key | Rotated Key | RoPE score | |
|---|---|---|---|---|---|
| A1 | |||||
| A2 | |||||
| B1 | |||||
| B2 |
Start with experiment A. The content vectors are identical in both rows; only the relative position changes:
Thus even when the content is unchanged, relative position rotates the Key first and then changes how well it matches the Query.
Now consider experiment B. The Query and Key are initially orthogonal, so their score at the same position is . When , turns the Key from into , exactly aligning it with the Query, and the score becomes .
These examples make only one point: RoPE lets relative position determine the coordinate directions in which two pieces of content are compared. It does not add a fixed reward or penalty for distance, nor does it guarantee that the score decreases with distance.
A real attention head uses many different values at once, while are content vectors learned by the model. The position difference determines how each coordinate pair rotates; the content determines whether those rotated coordinates match. The results from all dimensions are then added together.
5. From One Dimension Pair to a Complete Attention Head
In a real model, one attention head usually has tens or hundreds of dimensions. RoPE groups these dimensions into pairs:
The -th pair has its own per-step rotation angle . The complete rotation can be written as a block-diagonal matrix:
A common frequency schedule is inherited from Sinusoidal PE:
with the classic base . Larger values rotate quickly and are more sensitive to local position differences; smaller values rotate slowly and vary more gradually over longer distances.
The complete score is the sum of the scores from all two-dimensional blocks:
where are determined by the content in the -th Query/Key pair.
Rotation also preserves vector length. Because
we have
Position changes direction, not the magnitude of the Query or Key.
The multi-frequency score is still a content-dependent finite trigonometric sum. It may oscillate with distance; it is not guaranteed to decrease strictly, nor are distant tokens guaranteed to receive less attention. A more precise statement is that geometric frequencies supply multiscale phase structure and, when many frequencies are mixed, tend to produce oscillatory decorrelation. This is not a hard-coded distance penalty.
6. Where Does RoPE Enter Standard Attention?
For one attention head, the computation can be written in five steps.
Step 1: Produce Q, K, and V from the Input
Step 2: Rotate Only Q and K
Here is not a new, undefined matrix. It is the complete-head rotation from the previous section. To save the reader from searching backward, write it once more:
rotates every Query dimension pair according to position , and rotates every Key dimension pair according to position . Therefore,
Step 3: Compute Every Query—Key Score
Step 4: Add the Mask, Then Apply Softmax
Here we use an additive mask. Define by
It is added to the score before the exponential:
The plus sign is therefore intentional. When reading is allowed, ; when it is forbidden, . Implementations usually replace with a very large negative number representable by the chosen data type.
If an implementation uses a Boolean mask, that is a different representation. It is usually converted into the additive mask used here, or applied through an equivalent multiplication after exponentiation. In this article, is defined from the start in the pre-softmax logit space.
Step 5: Use the Weights to Aggregate the Unrotated Values
Values usually do not need to be rotated. RoPE’s purpose is to make the pairing score—“how much information should position take from position ?”—depend on relative position. Once contains that information, it can directly select and combine the Values.
In code-like form:
q, k, v = project(x)
q_rope = q * cos(position) + rotate_half(q) * sin(position)
k_rope = k * cos(position) + rotate_half(k) * sin(position)
score = q_rope @ k_rope.T / sqrt(head_dim)
weight = softmax(score + mask)
output = weight @ v
For every two-dimensional block ,
which is exactly the part of the rotation matrix multiplied by .
One boundary still needs to be explicit: standard attention must compute every combination and form an score matrix. RoPE adds positional structure; it does not automatically turn the complexity of standard attention into linear complexity.
7. Core Conclusions and Boundaries
At this point, the core path needed to understand RoPE itself is complete. The preceding derivations establish or directly demonstrate that:
- RoPE and Sinusoidal PE use the same kind of position angles and sin/cos signals, but assign them different roles: RoPE places them inside a rotation operator, whereas Sinusoidal PE places them inside a position vector;
- Two-dimensional RoPE is a length-preserving rotation;
- , so the position variables enter the Query—Key score only through relative displacement;
- Shifting the Query and Key together does not change their relative rotation;
- RoPE rotates Q/K before the logit matrix is formed; it does not apply elementwise distance weights to existing logits;
- The RoPE score is not merely the original dot product multiplied by a distance cosine, because it also contains cross-coordinate content matching.
These derivations do not prove that:
- RoPE is the unique solution to the relative-position objective;
- the RoPE score decreases strictly and monotonically with distance;
- a model using RoPE must prefer nearby tokens;
- being able to compute rotation angles beyond the training length guarantees reliable length extrapolation;
- RoPE reduces the complexity of standard attention.
8. Quick Reference
| Question | Shortest answer |
|---|---|
| Where do RoPE’s sin/cos values come from? | It generates sin/cos from the same kind of position angles and frequencies as Sinusoidal PE, but uses them directly as rotation coefficients. |
| What does RoPE rotate? | The projected Query and Key in each attention head. |
| Where does the rotation matrix act? | In the -dimensional feature space of one token, not on the attention matrix. |
| Why pair every two dimensions? | Two dimensions are exactly enough to represent a length-preserving planar rotation. |
| Why does relative position appear? | . |
| Does RoPE add a position vector to content? | No. It directly rotates the content-derived Q/K vectors. |
| Does RoPE multiply the logit matrix elementwise? | No. It rotates Q/K first and constructs the logits from the rotated vectors. |
| Does RoPE merely multiply the dot product by a cosine? | No. It also introduces cross-coordinate matching controlled by the sine term. |
| Why is the Value usually not rotated? | Relative position already enters the attention weights that select the Values, so the Values can be aggregated directly. |
| Does standard attention become linear as a result? | No. It must still compute Query—Key scores. |
The single most important sentence from the core RoPE path is:
RoPE uses sin/cos signals from the same source as Sinusoidal PE to express position as rotations acting on Queries and Keys; when the two are compared, their absolute rotations cancel and only relative displacement remains.
9. Optional Reading: RoPE and Linear Attention
The remainder addresses a separate question: once RoPE is understood, can it be combined with the multiplication reordering used by linear attention? This is not part of RoPE’s definition and does not affect the preceding conclusions about standard attention. Readers interested only in RoPE itself can skip directly to the references.
This section introduces two additional symbols: denote the feature maps applied to Queries and Keys in linear attention.
9.1 Why Is Linear Attention Called “Linear”?
Here “linear” means that the amount of computation grows linearly with sequence length , not that the entire module contains no nonlinear functions.
To make the contrast with standard attention explicit, temporarily omit RoPE and the mask. Standard attention is
Every coefficient is jointly produced by one specific Query—Key pair. A length- sequence has such pairs, so all Keys and Values cannot first be compressed into a finite Query-independent summary.
Linear attention changes this crucial pairwise coefficient. It chooses or approximates a similarity that separates into two feature vectors:
Let
Its normalized output is then
Place the two forms side by side and the difference is concentrated in the middle column:
| Standard attention | Linear attention | |
|---|---|---|
| Query—Key coefficient | ||
| Form every pair first? | Yes, pairs in total | Not necessary; Keys and Values can be aggregated first |
| Normalization | Softmax for each Query | Divide by |
| Computation in sequence length | when the feature dimension is fixed |
The key to linear attention is therefore not merely that “softmax is absent from the formula.” It is that and can be computed separately, after which the associativity of matrix multiplication changes the order of summation.
Because does not depend on the summation index , it can be moved outside the sum:
We can therefore compute two summary quantities for the entire sequence first:
and then let every Query read them:
No explicit attention matrix is constructed. When the feature dimension is fixed, the computation is linear in sequence length .
In the causal setting, replace the full-sequence sums with prefix states:
Position can read only the state accumulated up to that position, so it cannot see future tokens.
9.2 How Does RoPE Enter Linear Attention?
9.2.1 Why Does RoPE Preserve the Multiplication Reordering?
Assume that the feature dimensions can also be paired. Rotate the Query and Key features separately:
Their similarity still depends only on the relative rotation:
At the same time, the numerator can still be reordered:
We may therefore aggregate
before allowing the rotated Query to read it. RoPE’s position transformation acts on each Query and Key separately; it does not require a complete score matrix to exist first. The multiplication reordering that matters most to linear attention therefore remains valid.
9.2.2 Why Does the Denominator Become a Problem?
Many linear-attention methods choose with nonnegative outputs. Then
so the denominator is a sum of nonnegative similarities and the output can be interpreted as a weighted average of Values.
Rotation does not preserve the property that “every coordinate is nonnegative.” For example,
Thus, even if originally contain only nonnegative coordinates, the rotated similarity
may be negative. If these values are summed directly in the denominator, positive and negative terms can cancel, and the denominator may even approach .
9.2.3 What Treatment Does the RoFormer Paper Use?
The linear-attention form presented in RoFormer uses the rotated features only in the numerator, while the denominator retains the original nonnegative features:
This preserves two properties:
- Both numerator and denominator can still be computed in linear complexity through pre-aggregation.
- The denominator continues to use unrotated nonnegative features, reducing the risk of division by zero caused by positive—negative cancellation.
The cost must also be stated clearly. The effective coefficient of Value is
may be negative, and in general it does not satisfy
The output is therefore still a content aggregation with a normalized scale, but it is no longer a strict probability-weighted average.
9.2.4 Rotate Before or After the Feature Map?
When reading different implementations, we also encounter two orders that look similar but are genuinely different:
| Order | Form | Main property |
|---|---|---|
| Map, then rotate | The relative-rotation identity holds exactly, but nonnegative features become signed | |
| Rotate, then map | With positive random features, it can approximate the rotated softmax kernel while preserving nonnegativity, but this is a kernel approximation rather than the exact identity in the row above |
For example, Performer’s FAVOR+ uses positive random features to approximate the softmax kernel. Applying RoPE to the original Queries and Keys before mapping the rotated vectors through these features can approximate standard RoPE attention while retaining linear computation. This is a different combination from the RoFormer linear formula in the previous subsection; both should not be collapsed into the single phrase “add RoPE.”
9.3 What Does “Suitable for Linear Attention” Actually Require?
What linear attention truly requires is not one particular positional-encoding name, but a position-aware similarity that can be factored as
As long as the Query-side and Key-side can be computed separately, the Keys and Values still have a chance to be aggregated first.
RoPE satisfies this condition naturally:
Many relative-position biases that are added directly to a complete attention matrix, by contrast, cannot be used until every pairwise score already exists, so the same reordering does not apply directly.
This is not a uniqueness theorem for RoPE. Any other position function that can be separated may also work with linear attention. For example, cosFormer uses separable cosine position reweighting to retain nonnegativity while enabling linear computation. A more accurate conclusion is therefore:
RoPE’s advantage is that it uses absolute-position rotations applied separately to the Query and Key to construct an explicit relative-position interaction. This separable structure is naturally suited to linear attention, but it is not the only possible structure.
The optional material can be compressed into three points:
- linear attention depends on a similarity that can be computed separately on the Query and Key sides;
- RoPE rotates Queries and Keys separately, so it can preserve this multiplication reordering;
- “the computation remains linear” does not imply that the rotated weights remain nonnegative or sum to one—the exact behavior depends on the feature map, rotation order, and normalization scheme.
The single most important sentence from the optional section: RoPE’s relationship to linear attention comes from its separable structure—its transformations can act independently on Queries and Keys. This is a compatibility result, not a prerequisite for defining or understanding RoPE.
References and Image Sources
- Jianlin Su (2021). “Transformer Upgrade Path 2: Rotary Position Embedding That Combines the Best of Both Worlds”. This article begins from the questions and RoPE construction in that post, then reorganizes the teaching sequence around two-dimensional rotation, standard attention, and linear attention.
- Su, J. et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. Standard RoPE formulation, properties, and its linear-attention scheme.
- Katharopoulos, A. et al. (2020). Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention. Linear attention through kernel features and associativity.
- Choromanski, K. et al. (2021). Rethinking Attention with Performers. Softmax-attention approximation with positive orthogonal random features.
- Qin, Z. et al. (2022). cosFormer: Rethinking Softmax in Attention. Its separable cosine position reweighting shows that RoPE is not the only possible positional structure for linear attention.
- Figure 1 is an author-created mechanism diagram.