RoPE: geometry, derivation, and limitations
How query and key rotations encode relative positions
This page is an advanced deep dive. It assumes that the reader understands the role of positional information and the general attention computation. It studies the geometry of RoPE (Rotary Position Embedding), which applies position-dependent rotations to queries and keys before attention scores are computed.
Three points where positional information enters
The most useful distinction is not only “absolute versus relative”: these mechanisms enter at different points in the computation.
- Input addition: positional information changes the representation before the first block.
- RoPE: positional information acts inside attention, on queries and keys before the dot product.
- Relative bias: positional information modifies attention scores before softmax.
These are mechanism families, not three operations that are necessarily mutually exclusive in every architecture.
Geometric principle
The diagram shows a single coordinate pair. In practice, RoPE acts on multiple pairs with different frequencies. The figure illustrates the geometric operation, not the numerical values of a real model.
For a coordinate pair \((x_1,x_2)\), a rotation by angle \(\theta\) is:
\[ R(\theta)= \begin{pmatrix} \cos\theta & -\sin\theta\\ \sin\theta & \cos\theta \end{pmatrix}, \qquad x'=R(\theta)x. \]
Why does the score depend on the relative offset?
Consider one coordinate pair at a fixed frequency. Let \(q\) and \(k\) be the query and key components before rotation; at positions \(m\) and \(n\), they become \(q_m=R(m\theta)q\) and \(k_n=R(n\theta)k\).
Since rotations satisfy \(R(\alpha)^\top=R(-\alpha)\) and \(R(\alpha)R(\beta)=R(\alpha+\beta)\), we obtain:
\[ q_m^\top k_n = q^\top R(m\theta)^\top R(n\theta)k = q^\top R((n-m)\theta)k. \]
Thus, for this pair and frequency, the score depends on the offset \(n-m\), rather than on the absolute positions separately. RoPE applies this reasoning pair by pair, with a different frequency for each pair.
In an attention head, rotations are applied to \(Q\) and \(K\) after their projections and before computing \(QK^\top\). In standard RoPE, the values \(V\) are not directly rotated. See queries, keys, and values and scaled dot-product attention.
Explore one RoPE pair
Change the positions and frequency. The original q and k vectors stay fixed: this shows one feature-pair contribution, not a full attention-head score.
<label>Query position m <output data-out="m">2</output><input data-control="m" type="range" min="0" max="20" step="1" value="2"></label>
<label>Key position n <output data-out="n">7</output><input data-control="n" type="range" min="0" max="20" step="1" value="7"></label>
<label>Frequency θ (rad / position) <output data-out="theta">0.35</output><input data-control="theta" type="range" min="0" max="1.2" step="0.01" value="0.35"></label>
<label>Shared shift c <output data-out="shift">0</output><input data-control="shift" type="range" min="-10" max="10" step="1" value="0"></label>
<svg class="rope-pair-plot" viewBox="0 0 520 300" role="img" aria-label="Original and rotated q and k vectors in a two-dimensional plane">
<defs><marker id="rope-arrow-q-en" markerWidth="7" markerHeight="7" refX="5" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 z" fill="#2563eb"/></marker><marker id="rope-arrow-k-en" markerWidth="7" markerHeight="7" refX="5" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 z" fill="#d97706"/></marker></defs>
<line x1="30" y1="150" x2="490" y2="150" stroke="currentColor" opacity=".35"/><line x1="260" y1="20" x2="260" y2="280" stroke="currentColor" opacity=".35"/>
<g data-drawing></g>
</svg>
<ul class="rope-legend"><li><span class="rope-swatch rope-q"></span>original q and rotated qₘ</li><li><span class="rope-swatch rope-k"></span>original k and rotated kₙ</li></ul>
<p><strong>Angles:</strong> <output data-out="angles"></output></p>
<p><strong>Contribution qₘ · kₙ:</strong> <output data-out="dot"></output></p>
<p><strong>Relative offset n − m:</strong> <output data-out="relative"></output></p>
<p><strong>After shared shift:</strong> <output data-out="shifted"></output></p>
For fixed q and k, adding the same c to m and n leaves their relative offset and dot product unchanged. Adding a real prefix to a model can change its hidden states, and therefore q and k: that is a different experiment.
From vectors to output: one attention head, step by step
A deterministic toy example with three tokens and one 2D head. Q, K and V projections are given; we isolate the effects of RoPE, causal masking and softmax.
<label>Query position <output data-pipe-out="query">2</output><input data-pipe-control="query" type="range" min="0" max="2" step="1" value="2"></label>
<label class="rope-pipeline-check"><input data-pipe-control="rope" type="checkbox" checked> Apply RoPE to Q and K</label>
<label class="rope-pipeline-check"><input data-pipe-control="causal" type="checkbox" checked> Apply causal mask</label>
<div class="rope-pipeline-stage"><h4>1 · Projections</h4><p>Q, K and V come from the same hidden-state stream through three distinct projections.</p><div data-pipe-out="projections" class="rope-pipeline-data"></div></div>
<div class="rope-pipeline-stage"><h4>2 · Position</h4><p>RoPE rotates Qᵢ and each Kⱼ according to position; V remains unchanged.</p><div data-pipe-out="rotations" class="rope-pipeline-data"></div></div>
<div class="rope-pipeline-stage"><h4>3 · Scores QKᵀ / √d</h4><p>The dot product is computed for each candidate key.</p><div data-pipe-out="scores" class="rope-pipeline-data"></div></div>
<div class="rope-pipeline-stage"><h4>4 · Causal mask</h4><p>Future positions are excluded before softmax.</p><div data-pipe-out="mask" class="rope-pipeline-data"></div></div>
<div class="rope-pipeline-stage"><h4>5 · Softmax</h4><p>Allowed scores become weights that sum to 1.</p><div data-pipe-out="weights" class="rope-pipeline-data"></div></div>
<div class="rope-pipeline-stage"><h4>6 · Aggregate V</h4><p>The output is the weighted sum of accessible value vectors.</p><div data-pipe-out="output" class="rope-pipeline-data"></div></div>
These numbers are a pedagogical toy example, not activations measured from a trained model. Turning off the causal mask intentionally demonstrates non-causal attention.
Why pairing conventions matter
The two layouts below describe the same two rotations when coordinate order and frequency assignment stay consistent.
<label>Pair 0 angle <output data-layout-out="a0">0.40</output><input data-layout-control="a0" type="range" min="-1.5" max="1.5" step="0.05" value="0.4"></label>
<label>Pair 1 angle <output data-layout-out="a1">0.90</output><input data-layout-control="a1" type="range" min="-1.5" max="1.5" step="0.05" value="0.9"></label>
<label class="rope-pipeline-check"><input data-layout-control="mismatch" type="checkbox"> Deliberately mix conventions</label>
<div><h4>Interleaved: [x₀, y₀, x₁, y₁]</h4><p>Pairs: (0, 1) at θ₀; (2, 3) at θ₁</p><output data-layout-out="interleaved"></output></div>
<div><h4>Split-half: [x₀, x₁, y₀, y₁]</h4><p>Pairs: (0, 2) at θ₀; (1, 3) at θ₁</p><output data-layout-out="split"></output></div>
The starting vector is [1, 2, 3, 4] in interleaved layout. The permutation to split-half is [1, 3, 2, 4]. The split-half result is converted back to interleaved order before comparison.
Explore the RoPE frequency scale
A head spreads its coordinate pairs across a geometric range of frequencies. Before moving the controls, predict: which pair rotates fastest, and which keeps a phase near zero for the longest?
<label>Head dimension d <output data-out="dim">128</output>
<select data-control="dim"><option value="64">64</option><option value="128" selected>128</option><option value="256">256</option></select>
</label>
<label>Base θ <output data-out="base">10,000</output>
<input data-control="base" type="range" min="1000" max="1000000" step="1000" value="10000">
</label>
<label>Position p <output data-out="position">128</output>
<input data-control="position" type="range" min="0" max="4096" step="1" value="128">
</label>
<p><strong>Fastest pair (i = 0):</strong> <output data-out="fast"></output></p>
<p><strong>Slowest pair (i = d/2 − 1):</strong> <output data-out="slow"></output></p>
<p><strong>Extreme frequency ratio:</strong> <output data-out="ratio"></output></p>
<table class="rope-frequency-table">
<caption>Sample of pairs across the head dimension</caption>
<thead><tr><th scope="col">Pair i</th><th scope="col">ωᵢ (rad/position)</th><th scope="col">Wavelength 2π/ωᵢ</th><th scope="col">Angle p·ωᵢ (rad)</th></tr></thead>
<tbody data-frequency-rows><tr><td colspan="4">Enable JavaScript to calculate frequencies.</td></tr></tbody>
</table>
Convention: ωᵢ = θ−2i/d, for i = 0,…,d/2−1. The base θ is a model configuration parameter, not a universal constant. Angles are periodic modulo 2π; wavelength tells how many positions it takes a pair to return to the same phase.
Separate RoPE-table memory from KV-cache memory
Set the parameters for one layer. Reducing the rotary fraction shrinks the cosine/sine tables, but does not automatically shrink the K and V tensors stored in the KV cache.
<label>Sequence length <output data-out="seq">8192</output><input data-control="seq" type="range" min="512" max="32768" step="512" value="8192"></label>
<label>Rotary fraction <output data-out="fraction">100%</output><input data-control="fraction" type="range" min="10" max="100" step="10" value="100"></label>
<label>Batch <output data-out="batch">1</output><input data-control="batch" type="range" min="1" max="16" step="1" value="1"></label>
<label>KV heads <output data-out="heads">8</output><input data-control="heads" type="range" min="1" max="32" step="1" value="8"></label>
<label>Head dimension <output data-out="dim">128</output><select data-control="dim"><option>64</option><option selected>128</option><option>256</option></select></label>
<label>Precision <output data-out="bytes">2 bytes</output><select data-control="bytes"><option value="2" selected>BF16 / FP16</option><option value="4">FP32</option><option value="1">8-bit (assumption)</option></select></label>
<div><strong>RoPE cos/sin tables</strong><output data-out="rope"></output></div>
<div><strong>KV cache (K + V)</strong><output data-out="kv"></output></div>
<div><strong>KV cache / tables ratio</strong><output data-out="ratio"></output></div>
<div><strong>Rotary dimensions</strong><output data-out="rotary"></output></div>
One-layer estimate: cos/sin tables = 2 × sequence × (rotary dimensions / 2) elements; KV cache = 2 × batch × sequence × KV heads × full head dimension. This assumes K and V remain full-width in the cache. It excludes allocator overhead, alignment, replication and other buffers. Cache quantization is represented only as an assumed bytes-per-element size, not as a specific format.
Experiment: what can a causal prefix reveal without RoPE?
In this NoPE layer, no rotation or explicit positional coordinate is added. The causal mask still restricts each query to its preceding prefix. Explore what this nested visibility can—and cannot—reveal.
<label>Query position <output data-out="position">4</output><input data-control="position" type="range" min="0" max="7" step="1" value="4"></label>
<label>Content pattern <select data-control="pattern"><option value="ramp" selected>Distinct progression</option><option value="alternating">Alternating −1 / +1</option><option value="constant">Identical content</option></select></label>
<label>Attention distribution <select data-control="attention"><option value="uniform" selected>Uniform over prefix</option><option value="content">Content-dependent (softmax)</option></select></label>
<label>Softmax temperature <output data-out="temperature">1.0</output><input data-control="temperature" type="range" min="0.2" max="3" step="0.1" value="1"></label>
<div><strong>Visible keys</strong><output data-out="visible">5 / 8</output></div>
<div><strong>Weighted value sum</strong><output data-out="aggregate"></output></div>
<div><strong>Weight entropy</strong><output data-out="entropy"></output></div>
Accessible prefix and attention weights
Important limitation: the number of visible keys depends on position, but the aggregated output does not always reveal that position. With identical content, the mean stays identical regardless of prefix length. A real Transformer can use multiple layers, heads, rich representations and nonlinear interactions; this toy is neither a general proof nor a measurement of length generalization.
Hybrid RoPE/NoPE layers: local operations, inherited states
A layer that omits RoPE does not receive a blank or reset representation: it receives the previous layer’s contextualized hidden states. Earlier layers may have made positional and contextual distinctions available to later layers, although no architecture diagram can guarantee that those distinctions survive or are used.
Experiment: mix RoPE and NoPE across layers
Choose which layers rotate Q and K. Every layer still receives the previous layer’s hidden states and keeps causal masking in this autoregressive example.
<button type="button" data-preset="all-rope">All RoPE</button>
<button type="button" data-preset="all-nope">All NoPE</button>
<button type="button" data-preset="alternating">Alternating</button>
<button type="button" data-preset="early-rope">Early RoPE, later NoPE</button>
<p data-summary></p>
<p data-inheritance></p>
Interpretation limit: this is a layer-routing diagram, not a numerical Transformer simulation. A layer receives contextualized representations from the previous layer; those representations may carry positional or contextual distinctions forward. The diagram cannot measure whether a trained model preserves, uses, or loses that information.
Relative bias: add a position term before softmax
An attention score can be decomposed into a content term and a relative-position term, for example (s_{ij}=q_i^k_j/+b(h_i,j-i)). The exact function is architecture-specific. In T5, the bias is a learned scalar indexed by a distance bucket; in ALiBi, a fixed head-specific slope creates a linear penalty. A query-conditioned bias such as the Inkling mechanism described by Raschka is a further parameterization. These biases act on scores before softmax; they are not RoPE rotations.
Experiment: decompose an attention score with relative bias
Start with a content score, then add a position-dependent term before softmax. Compare a query-conditioned bias with a T5-style bucket lookup.
<label>Content score <output data-out="content">1.2</output><input data-control="content" type="range" min="-4" max="4" step="0.1" value="1.2"></label>
<label>Relative offset (key − query) <output data-out="distance">−3</output><input data-control="distance" type="range" min="-16" max="16" step="1" value="-3"></label>
<label>Query-state feature <output data-out="state">0.8</output><input data-control="state" type="range" min="-2" max="2" step="0.1" value="0.8"></label>
<label>Bias strength <output data-out="strength">1.0</output><input data-control="strength" type="range" min="0" max="2" step="0.1" value="1"></label>
<label>Bias family<select data-control="mode"><option value="conditioned" selected>Query-conditioned relative bias (illustrative)</option><option value="bucketed">T5-style bucketed bias (illustrative)</option><option value="none">No relative bias</option></select></label>
<p><strong>Score decomposition</strong></p>
<div><span>Content term</span><output data-out="content-term">1.200</output></div>
<div><span>Relative-position term</span><output data-out="bias">−0.145</output></div>
<div class="relative-bias-total"><span>Pre-softmax score</span><output data-out="total">1.055</output></div>
Important: this is a transparent toy parameterization, not Inkling’s recovered learned function or trained T5 weights. T5 uses learned per-head values indexed by relative-position buckets; the query-conditioned example makes the bias depend on a query-state feature and distance. The score shown is before softmax and before any causal mask is applied.
What RoPE provides — and what it does not guarantee
RoPE provides a structured way to introduce position into attention. Its presence alone does not guarantee reliable extrapolation to sequences much longer than those seen during training.
Long-context behaviour also depends on the frequency base, training sequence length, any scaling methods, the attention mechanism, and the data. The exact variant must be identified before comparing models.
Common misconceptions
- “RoPE simply adds a position vector to the embeddings.” No: in its common form, RoPE rotates pairs of query and key coordinates.
- “RoPE guarantees long context windows.” No: performance beyond the training length depends on several design choices and must be evaluated.
- “RoPE also rotates the values \(V\).” In the standard version, the operation acts on \(Q\) and \(K\); attention then aggregates values using the computed weights.
Implementation checks
Check tensor dimensions, the pairing convention for coordinates, the positions used, numerical precision, and behaviour at several sequence lengths. An indexing error can produce correctly shaped tensors while encoding the wrong positions. Tests should compare outputs against a known reference and inspect attention scores.
Architectural variants and neighboring mechanisms
Full RoPE rotates every coordinate pair in Q and K. Recent architectures can change how many dimensions are rotated or which layers apply RoPE. Other relative mechanisms, introduced in the previous section, modify scores directly; they are not RoPE variants.
- Partial RoPE rotates only a subset of each head’s dimensions. This narrows the sine/cosine tables, but does not reduce the dimensions of cached keys and values in the KV cache. The MiniMax-M3 example discussed by Raschka uses 64 rotary dimensions out of 128. An experimental study by Khan et al. (2026), on 1B and 8B configurations, reports convergence close to full RoPE from around 10% rotary dimensions and up to 10× lower memory for precomputed RoPE tables; these savings do not apply to the KV cache and remain specific to the study’s protocol.
- NoPE omits explicit positional transformations in a layer while retaining the causal mask. Nested visible prefixes can provide an implicit order signal, but not an explicit absolute coordinate or relative distance. Length-generalization results depend on the task and training regime.
- RoPE/NoPE hybrid layers apply RoPE in some layers and omit it in others. SmolLM3 is an example discussed in the article; check the exact pattern against the configuration of the version being studied.
These mechanisms are not interchangeable. The examples are dated snapshots, not an exhaustive taxonomy.
Frequencies and implementation conventions
For an even head dimension d, the standard inverse frequency for pair i is omega_i = b^(-2i/d), and the angle at position m is m * omega_i. Here the cosine/sine tables have shape (sequence_length, d/2): one column per feature pair. They are commonly precomputed and broadcast across batch and heads. Note that the base is model-specific: the classic example often uses 10,000, while the Qwen3 configuration in Raschka’s notebook uses theta = 1,000,000.
def rope_params(head_dim, positions, base=10_000):
assert head_dim % 2 == 0
indices = torch.arange(0, head_dim, 2, device=positions.device)
inv_freq = base ** (-indices.float() / head_dim)
angles = positions.float()[:, None] * inv_freq[None, :]
return angles.cos(), angles.sin()Interleaved pairs adjacent coordinates; split-half pairs the two halves. They are equivalent after a consistent feature permutation, but must not be mixed. Standard RoPE applies to Q and K after projection, not V.
Useful tests
- Check cosine/sine table shapes and broadcasting.
- Check that only rotary dimensions change in Partial RoPE.
- Compare conventions after an explicit feature permutation.
- Shift all positions by the same constant and verify QK-score invariance for fixed Q/K.
- Test prefill and incremental decoding positions with a KV cache.
For a complete PyTorch implementation of Qwen3, see Raschka’s tutorial and repository; external code is not copied here.
References
- Su et al. (2021), RoFormer: Enhanced Transformer with Rotary Position Embedding — the original RoPE formulation.
- Shaw et al. (2018), Self-Attention with Relative Position Representations — relative representations in keys and values.
- Raffel et al. (2020), Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer — T5’s learned bucketed relative bias.
- Press et al. (2022), Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation — ALiBi’s linear bias.
- Hugging Face Transformers documentation — implementation conventions vary by architecture.
Canonical lesson: Positional encoding. This page deepens one particular mechanism; it does not replace the general introduction to positional information.