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 generates a hand for each position. RoPE goes one step further: instead of adding a position vector to a token, it uses the angle associated with that position to rotate the content-derived Query and Key directly. Position rotates by , and position by ; when their inner product is taken, the shared absolute rotation cancels, leaving only . In standard attention, this relative rotation enters the score before softmax. In linear attention, the computational reordering that aggregates Keys and Values first can be preserved as long as the rotations still act separately on the Query and Key. However, “the computation remains linear” does not mean “the weights remain nonnegative and sum to one.” These are two separate questions.
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 | |
| Feature maps applied to Queries and Keys in linear attention |
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
We want them to satisfy
The right-hand side still depends on the content of the Query and Key. The only restriction is on the position variables: 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. First, Understand Two-Dimensional Rotation Step by Step
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. Why Does the Core of RoPE Fit in One Line?
Now take one two-dimensional Query and Key:
Choose a fixed per-step rotation angle . 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. What Does “Rotating Content” Actually Change?
The previous section proved that position appears only through , but it has not yet answered a 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. 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.
8. How Does RoPE Enter Linear Attention?
8.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.
8.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 .
8.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.
8.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. 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.
10. What Do These Derivations Prove—and What Do They Not?
They establish or directly demonstrate that:
- Two-dimensional RoPE is a length-preserving rotation.
- , so position appears in the Query—Key score only through relative displacement.
- Shifting the Query and Key together does not change their relative rotation.
- A RoPE score is not merely the original dot product multiplied by a distance cosine; it also includes cross-coordinate matches between content dimensions.
- RoPE can be applied separately to the Query and Key, so it does not automatically break the multiplication reordering used by linear attention.
They do not establish that:
- RoPE is the unique solution to the relative-position objective.
- A 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.
- Every linear-attention method retains nonnegative probability weights that sum to after RoPE is added.
- RoPE reduces the complexity of standard attention.
11. Quick Reference
| Question | Shortest answer |
|---|---|
| What does RoPE rotate? | The projected Queries and Keys in each attention head. |
| 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 merely multiply a dot product by a cosine? | No. It also introduces sine-controlled cross-coordinate matches. |
| Why are Values usually not rotated? | Relative position already enters the attention weights that select the Values, so the Values themselves can be aggregated directly. |
| Does standard attention become linear in complexity? | No. It still computes Query—Key scores. |
| Why is RoPE suited to linear attention? | It acts separately on the Query and Key, preserving separable computation. |
| Are the weights in linear attention still probabilities? | Not necessarily. Rotated features can produce negative similarities, depending on the feature map and normalization scheme. |
| Is RoPE the only relative-position method compatible with linear attention? | No. The key condition is whether the position-aware similarity can be factored. |
The single most important sentence to remember is:
RoPE does not attach a position label to a token. It rotates the Query and Key in their respective positional coordinate systems; when they are compared, the absolute coordinates cancel and only relative displacement remains.
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.