Mathematical language and representation

Position from rotation: complex phases, Fourier structure and RoPE

Rajesh Ranjan Mahapatra

Rotary position embedding works because position is applied as a reversible rotation to content: absolute phases enter each query and key, but their interaction cancels the origin and exposes relative displacement.

© 2026 Rajesh Ranjan Mahapatra. 32 min read

Position from rotation: complex phases, Fourier structure and RoPEAll Human–Machine Convergence

Mathematical language and representation

Position from rotation: complex phases, Fourier structure and RoPE

Rotary position embedding works because position is applied as a reversible rotation to content: absolute phases enter each query and key, but their interaction cancels the origin and exposes relative displacement.

TLDR

  1. Bare self-attention compares content, not sequence order, unless another mechanism breaks the permutation symmetry.
  2. A two-dimensional feature pair can carry position by rotating through a fixed angle at each token step.
  3. Rotating both queries and keys makes their dot product depend on the difference between positions, not the chosen origin.
  4. A bank of frequencies gives both fine and coarse positional resolution, but periodicity also creates aliasing and extrapolation risk.
  5. Judge a position system separately on algebraic relativity, geometric identifiability and statistical familiarity.
Opening case

Imagine a railway carriage whose seat numbers are repainted every time another carriage is attached at the front. A passenger who was in seat 12 is now in seat 112. Yet nothing about the passenger's neighbours changed. The person two seats to the left is still two seats to the left.

A literal database solution assigns a fresh symbol to every possible seat. A geometric solution gives each passenger a set of clock hands. Advancing one seat turns every hand by its own fixed amount. When two passengers compare clocks, the common repainting disappears. What remains is the angle between their hands.

The central move is to treat position as an operation, not a label. Rotary position embedding, usually shortened to RoPE, applies that move inside attention. It does not store a separate meaning for position 12, position 112 and position 1,000,112. It rotates content vectors according to their indices so that query-key compatibility contains a built-in relative-position law.

A token position represented by three coupled phase dials The same position index turns a fast, medium and slow circular dial by different angles. Their combined hand directions form the position signature. position 0 position m position m + 1 three phases at m fast dial medium dial slow dial one integer index becomes a tuple of phases
Position as coupled clocks. Each frequency receives the same integer index but advances at a different angular rate. The combined state is reusable at every location because it is generated by repeated rotation, not by a location-specific lookup. Illustrative.

Order without numbered seats

Before asking how RoPE works, ask what would be missing without it. A standard attention score starts with a query vector at one token and a key vector at another. Their dot product says how compatible their contents are. It does not, by itself, say which token came first.

The symmetry that hides sequence order

Suppose the input contains three token vectors. Apply the same query, key and value projections to each. If the tokens are permuted, the matrix of pairwise scores is permuted in the same way, and the outputs follow that permutation. The layer is not confused. It is simply respecting a symmetry: the operation has no privileged first, second or third slot.

Bare self-attention is a set operation with a permutation-equivariant output. A causal mask changes that statement because each position can attend to a different number of predecessors. Recurrence, convolution, padding boundaries and data regularities can also leak order. But the content-only dot product contains no ordinal coordinate. The original Transformer therefore added positional encodings to token embeddings because its architecture had neither recurrence nor convolution.[1]

Permutation intervention on a content-only attention layer The same three token vectors are rearranged. Without positional asymmetry, the score matrix and outputs are rearranged but otherwise unchanged. Adding position breaks that symmetry. content only red opens door pairwise score matrix S permute tokens door opens red P S Pᵀ intervention x y add a causal mask, position operator or boundary order can now affect scores
The permutation intervention. Reordering content simply reorders content-only attention. A mask, boundary or positional operator must break that symmetry before the layer can distinguish sequence roles. Illustrative derivation from the attention operation; see Vaswani et al. and Shaw et al.[1][2]

Why an absolute label is not always the right object

The simplest remedy is a table: position 0 receives one learned vector, position 1 another, and so on. A table can memorise useful regularities, but it treats each location as a separate name. Positions outside the table are undefined, and a global shift changes every label even when the relational structure of the sequence is unchanged.

The original sinusoidal encoding replaced the table with sine and cosine functions whose wavelengths form a geometric progression. For a fixed offset, the encoding at the shifted position is a linear transformation of the original encoding.[1] That fact already hints at rotation: sine and cosine at one phase become sine and cosine at another phase through a two-dimensional rotation matrix.

Mechanism

The desired invariant is not “position never matters”. It is “a common shift should not alter a relation that depends only on displacement”. RoPE builds exactly that invariant into query-key scoring while still allowing direction and distance to matter.

The argument in one pass
Chart · flow
flowchart LR
  A["Order without numbered seats"] --> B["The identity hidden in a rotation"]
  B --> C["The frequency bank sets the ruler"]
  C --> D["Test the geometry before<br/>extending it"]
  D -. "re-test" .-> A
  classDef first fill:#0a1424,stroke:#087A98,stroke-width:2px,color:#e6f3ff
  classDef step fill:#0a1424,stroke:#3f7da0,stroke-width:1px,color:#e6f3ff
  class A first
  class B,C,D step
A structural route through Position from rotation: complex phases, Fourier structure and RoPE: from Order without numbered seats to Test whether rotation preserves the…. Reading use: follow the relation, then return to the surrounding argument for evidence and limits.

The identity hidden in a rotation

A rotation seems like an odd place to store a token index. The reason becomes clear in two dimensions, where a vector can be read as a complex number and a position step can be read as multiplication by a unit phase.

One feature pair as a clock hand

Take two coordinates, x and y, from a projected query. Treat them as the complex number z = x + iy. Multiplying by eiθ rotates the pair through angle θ without changing its length. At position m, multiply by eimθ. Moving from position m to m + 1 then applies the same rotation once more.

This is more than a compact code. Repeated position steps compose correctly: rotating by a steps and then b steps is the same as rotating once by a + b steps. Negative steps use the inverse rotation. The integers have been represented as actions on a plane.

Worked example 1: a quarter-turn clock

Let θ be π/2 radians, a quarter-turn per token. Start with the feature pair (1, 0). At positions 0, 1, 2 and 3 it becomes (1, 0), (0, 1), (-1, 0) and (0, -1). The fourth step returns to the start. No lookup table was needed, but the price is visible: a single clock is periodic and therefore cannot uniquely name every integer.

Rotate both sides, then compare

Now let a query content vector q sit at position m, and a key content vector k sit at position n. Rotate each by its own position. Their dot product is

This is the load-bearing identity: RmTRn = Rn−m. Shift both tokens by the same constant c, and the score is unchanged because (n + c) − (m + c) = n − m. RoPE encodes an absolute phase on each vector, yet exposes relative position in their interaction. That is the apparent paradox resolved.

Two rotated vectors whose comparison depends on angular difference A query and key begin with content angles, are rotated by their absolute positions, and are compared. The common origin cancels, leaving the relative angle n minus m. Rₘq Rₙk relative angle Numerical example q = (1, 0) k = (0.8, 0.6) θ = π/4, m = 2, n = 5 n − m = 3 R₃ rotates k by 3π/4 qᵀR₃k ≈ −0.990 Shift both by +100: positions 102 and 105 score remains −0.990
Absolute rotations, relative comparison. The query and key are each rotated by an absolute index, but the dot product contains only their angular difference. Shifting both positions together leaves the score unchanged. Illustrative numerical example based on the RoFormer derivation.[4]
Worked example 2: calculate the same score two ways

Use q = (1, 0), k = (0.8, 0.6), θ = π/4, m = 2 and n = 5. Directly rotate q by π/2 and k by 5π/4, then take the dot product: about -0.990. Or leave q alone, rotate k by the displacement 3π/4, and take the dot product: the same -0.990. The equality is algebraic, not statistical.

Direction survives because sine changes sign

The compact matrix identity also reveals what a single rotary pair can distinguish. Write the displacement as δ = n − m. Expanding the two-dimensional score gives a content-alignment term multiplied by cos(δθ), plus an oriented term multiplied by sin(δθ). The first term is unchanged when the order is reversed. The second changes sign.

Mechanism: content and direction are coupled

The cosine channel asks how well the two content vectors align. The sine channel asks how one must turn to face the other. This decomposition assumes an ordinary Euclidean dot product and a proper two-dimensional rotation.

Swap the query and key positions while holding their content fixed. The displacement changes from δ to −δ. Cosine stays the same, but sine reverses, so the score can distinguish “before” from “after” whenever the oriented content term is non-zero. If the two content vectors are parallel, that term vanishes and this one pair cannot express direction for that comparison. Other pairs and learned projections may still do so.

Rotation also preserves the length of each query and key pair. Position therefore changes their orientation without injecting a larger norm merely because an index is larger. This does not freeze the distribution of complete attention logits. Learned projections can place different content in different frequency pairs, and the sum across pairs can still change substantially with distance. RoPE preserves local vector norm while making compatibility position-sensitive.

From one clock to many frequencies

A real attention head has many coordinates. RoPE pairs them, assigning a different θi to each two-dimensional plane. The full operator is block diagonal: many small rotations running in parallel. Common implementations use a geometric schedule such as θi = B−2i/d, where d is the head dimension, i indexes a coordinate pair, and B is a frequency base.

The fast pairs change sharply between adjacent tokens. Slow pairs preserve a gradual phase over thousands of tokens. Together they map one integer position to a point on a product of circles, sometimes called a torus. Multiple frequencies do not abolish periodicity; they make exact recurrence harder and provide several positional scales at once.

A token trajectory through two phase channels Positions zero to twelve move along two sinusoidal traces, one fast and one slow. At each position, the pair of phases defines a point in a two-frequency state space. position trajectory 024681012 fast phase: local discrimination, repeated wraps slow phase: coarse location, little movement over short spans each vertical pair is one position signature
A trajectory through a frequency bank. Position is not one angle but a tuple of angles. Fast channels distinguish nearby offsets; slow channels provide long-scale variation. The representation follows a deterministic trajectory through their joint phase space. Illustrative.

Why rotation is more than an added sinusoid

Sinusoidal absolute encoding and RoPE use the same elementary geometry but place it at different points in the computation. Add a positional vector to a token before the query and key projections, then expand the dot product. Four families of terms appear: content with content, content with position, position with content, and position with position. The model can learn useful relative relations from those terms, and a fixed shift of the sinusoidal code is indeed a linear transformation.[1] The relative law is nevertheless not isolated in the score by default.

RoPE first forms content-dependent queries and keys, then applies the position operator. The equality RmTRn = Rn−m is therefore built into the bilinear comparison itself. Conventional implementations leave values unrotated, so position modifies which message is selected rather than rewriting the payload carried by the value vector. The distinction is not fixed versus learned position. It is where the desired invariance enters the causal path.

This boundary matters when diagnosing a model. A wrong rotary offset can corrupt routing even if token representations look sensible. A value-path defect can corrupt the retrieved message even when every rotary identity test passes. The two failures may produce the same wrong answer, but they require different interventions.

Where the Fourier comparison is exact, and where it stops

For each frequency θ, the function χθ(m) = eimθ converts addition of integer positions into multiplication of phases: χθ(m + n) = χθ(m)χθ(n). In harmonic analysis, such functions are characters of the translation group. This is the precise Fourier structure inside RoPE.

But RoPE is not, in ordinary use, the discrete Fourier transform of the token sequence. It does not sum every token against an orthogonal frequency grid and return spectral coefficients. It modulates coordinate pairs in queries and keys with a finite, usually non-uniform bank of phases. Recent work has analysed RoPE attention through non-uniform Fourier transforms, but that is a model of its frequency behaviour, not permission to call every rotary layer a full Fourier transform.[13]

Boundary condition

“Fourier-structured” is accurate; “RoPE is the Fourier transform” is too strong. The preserved relation is translation becoming phase multiplication. Orthogonality, completeness and inversion require additional conditions that the standard frequency bank and attention computation do not automatically satisfy.

Optional depth: why rotation represents translation

Integer positions form a group under addition. A rotary pair assigns each integer m a matrix R(m) with the composition rule R(m + n) = R(m)R(n). The zero position maps to the identity matrix, and the negative position maps to the inverse rotation. This makes the position map a representation of integer translation on a two-dimensional vector space.

Because rotations are orthogonal, R(m)T = R(−m). The query-key product therefore reduces as qTR(m)TR(n)k = qTR(n − m)k. The reduction requires the query and key to use the same frequency, coordinate pairing, scale and origin convention. Break any one of those agreements and the clean relative law can fail.

In complex notation, the same representation is the character m ↦ eimθ. A bank of characters samples translation through several angular rates. A full Fourier analysis would additionally specify a function being decomposed, a frequency measure or grid, coefficient extraction, and conditions for reconstruction. RoPE needs none of those to obtain its relative score identity, which is why the narrower description is both sufficient and safer.

The frequency bank sets the ruler

The relative-position identity is exact for every chosen frequency. The usefulness of the resulting geometry is not. A finite bank decides which offsets look distinct, which look similar, and which phase combinations the model ever sees during training.

A positional kernel you can inspect

Strip away learned content for a moment. Put equal weight on every frequency pair and compare position 0 with offset Δ. A simple normalised similarity is

This is not the trained attention score. Learned queries and keys weight phases differently and mix content with position. K is a diagnostic lens: it reveals the geometry supplied to learning before the model decides how to use it.

Illustrative positional similarity over offsets for a 128-dimensional RoPE head A line begins at similarity one for offset zero and oscillates while generally decreasing over offsets to 4096. The curve is not monotonic. 1.00.50−0.5−1 01024204830724096 relative offset Δ K(Δ) d = 128, base = 10,000 64 equal-weight frequency pairs oscillation means no universal monotonic decay
The bare rotary similarity kernel. The average cosine similarity falls overall but oscillates and can rise again. RoPE therefore supplies distance-sensitive phase structure, not a guaranteed monotonic recency penalty for arbitrary learned vectors. Illustrative synthetic calculation: 64 frequencies, base 10,000, equal weights.

Identifiability is a margin, not a yes-or-no property

For a task, the useful question is not whether every integer has a mathematically unique phase signature. It is whether the offsets the task must separate remain far enough apart after projection, scaling and numerical rounding. A parser may need to distinguish distances 1, 2 and 3 with high confidence. A document retriever may care more about separating 8,000 from 24,000 than about one-token precision at either location.

The equal-weight kernel K is a first warning system, not a collision certificate. Two offsets can have the same average cosine while distributing phase error across frequency pairs differently. Learned queries and keys can amplify one pair, suppress another, or use the sine channel that K omits. Conversely, two signatures that look distinct in exact arithmetic may become operationally close after low-precision trigonometry and a narrow rotary subspace.

A better Gate B test defines the required offset set, computes pairwise phase distances under the deployed scaling and precision, then records the smallest separation margin. Inject the most confusable pair into a task whose content is otherwise identical. If behaviour changes only when the positional margin changes, the geometry is causally implicated. Task-relative separation, not abstract uniqueness, is the operative standard.

Fast resolution, slow context

A frequency θ has wavelength λ = 2π/θ tokens. The fastest conventional pair has a wavelength near 6.28 tokens. Slower pairs have progressively larger wavelengths. In a 128-dimensional head with base 10,000, the slowest pair has a wavelength of about 54,410 tokens. At a 4,096-token training length, the fastest pair has turned roughly 652 times, while the slowest has completed only about 0.075 of a cycle.

That spread is useful. It is also uneven training exposure. Some channels repeatedly display their periodic behaviour. Others reveal only a small arc. The model may learn local phase relations confidently while seeing too little evidence to infer how the slowest channels behave across a full turn.

Logarithmic wavelength ladder for 64 RoPE frequency pairs Sixty-four dots span wavelengths from about six to fifty-four thousand tokens on a logarithmic axis. A marker at 4096 tokens separates channels that complete a full cycle during training from slower channels that do not. 64 rotary wavelengths, logarithmic token scale 6 60 600 6k 60k training length 4,096 at least one full cycle observed less than one full cycle observed 18 of 64 pairs complete under one cycle by 4k
A realistic frequency ladder. A geometric schedule spans several orders of magnitude. In this common synthetic configuration, 18 of 64 pairs have not completed one full cycle by 4,096 tokens, which makes their long-range behaviour statistically less exposed even though the algebra is defined. Illustrative calculation for d = 128 and base = 10,000.
Worked example 3: the 128-dimensional head

Configure 64 rotary pairs with base 10,000. Adjacent positions have bare kernel similarity K(1) ≈ 0.970, so neighbouring phase signatures are close rather than orthogonal. At Δ = 128, K is about 0.333. At Δ = 4,096, it is about -0.053. These numbers do not say where attention will go. They say what positional correlations the projections can exploit.

The near-collision that preserves the law

With only four frequency pairs, the geometry is much easier to fool. Use an eight-dimensional head with base 10,000. The wavelengths are approximately 6.28, 62.8, 628 and 6,283 tokens. At offset 6,283, several dials return close to their starting directions at once. The equal-weight phase similarity is about 0.996.

The relative identity has not failed. RmTRn is still exactly Rn−m. The problem is that R6283 happens to resemble the identity on this small frequency bank. Exact relational algebra and useful positional identifiability are different properties.

Three meanings of “it knows position”

The phrase hides three separate claims:

Algebraic relativity asks whether global shifts cancel and displacements compose correctly. RoPE answers yes by construction. Geometric identifiability asks whether task-relevant offsets produce distinguishable operators at the available dimension and precision. That depends on the frequency bank. Statistical familiarity asks whether training has taught the model to use the relevant phase combinations, distances and score distributions. That depends on data, optimisation and context curriculum.

This distinction resolves an apparent contradiction in the literature. RoPE has an exact relative-position formula, yet empirical studies find that it does not automatically generalise to longer downstream sequences.[8] Both statements can be true because the first concerns algebra and the second concerns learned behaviour outside the training regime.

Evidence status

The rotation identity is established mathematics. Reported long-context gains and failures are empirical and model-specific. Claims that a particular spectral defect explains all length failures remain contested because attention dilution, data scarcity, optimisation, tokenisation and task format can produce similar observations.

RoPE is one answer, not the definition of position

Learned relative representations can add vectors indexed by displacement.[2] T5 adds learned relative-position biases to attention logits.[3] ALiBi adds a head-specific linear penalty proportional to distance, creating an explicit recency prior without sinusoidal phases.[5] Causal language models without explicit positional encodings can still acquire implicit position signals, plausibly from the causal mask and learned computation.[7] A broader review shows how these choices distribute position across inputs, scores and architectural constraints.[6]

Table 1. What different position mechanisms build into attention
MechanismWhere position entersBuilt-in relationMain structural trade-off
Learned absolute embeddingAdded to token representationEach trained index has its own vectorFlexible in range, undefined or untrained beyond it
Sinusoidal absolute encodingAdded to token representationFixed shifts are linear within sine-cosine pairsContent and position mix through several attention terms
Learned relative relationKey, value or attention scorePairwise displacement is explicitMay require buckets, clipping or extra pairwise structure
ALiBiAdditive attention-logit biasLinear distance penalty with head-specific slopesStrong recency prior, less expressive periodic geometry
RoPEMultiplicative rotations of queries and keysRmTRn = Rn−mPeriodic frequency bank, phase-regime sensitivity
No explicit encodingMask and learned network computationNo explicit positional lawPosition may emerge, but its mechanism and transfer are less controlled
Where RoPE enters a conventional attention head Token content is projected into query, key and value streams. Position rotations are applied to queries and keys only. Their score controls a weighted sum of unrotated values. attention-head cross-section token content x WQ WK WV q k v rotateby m rotateby n dot product depends on n−m softmax weight value content is conventionally not rotated weighted message RoPE changes the address calculation, not the semantic payload carried by v.
RoPE's implementation boundary. Conventional RoPE rotates projected queries and keys before their compatibility score. Values remain on the message path. This distinction matters when attributing what position can change. Mechanism based on RoFormer and common Transformer implementations.[4][15]
How the claim changes under pressure
Chart · state
stateDiagram-v2
  [*] --> Claim
  state "The symmetry that hides<br/>sequence order" as Claim
  state "Why an absolute label is not<br/>always the right object" as Test
  state "One feature pair as a clock hand" as Revision
  Claim --> Test: expose mechanism
  Test --> Decision: evidence survives
  Test --> Revision: rival survives
  Revision --> Claim: narrow or rebuild
  Decision --> [*]
The revision loop begins with The symmetry that hides sequence order and keeps counterexamples inside the reasoning path. Reading use: follow the relation, then return to the surrounding argument for evidence and limits.

Test the geometry before extending it

A configuration file can permit 32,000 tokens while the model still fails to use evidence at token 28,000. Extending the index range changes phase geometry, training distribution and attention competition at the same time.

Stretching the context changes two things at once

Suppose a model was trained to length 4,096 and must now serve 32,768 tokens. Raw extrapolation keeps the angular step per token unchanged. Every frequency travels eight times farther than during training, exposing the model to new phase combinations and potentially different attention-logit behaviour.

Position interpolation instead maps target index m to m/8. The longest target sequence stays inside the old phase range, which reduces phase novelty. But adjacent target tokens now differ by only one eighth of the former angle. Interpolation trades extrapolation risk for compressed local positional resolution. Fine-tuning can teach the model to work with that altered ruler.

Raw RoPE extrapolation compared with position interpolation A training phase range to 4096 tokens is compared with a target length eight times larger. Raw extrapolation traverses new phase territory; interpolation compresses eight target steps into the old phase range. same target length, different phase geometry training 04,096 phase range observed raw extrapolation 032,768 new phase territory and new wrap combinations position interpolation old phase range retained, local angular step divided by eight
Two ways to lengthen the ruler. Raw extrapolation preserves local angular spacing but visits phase regimes outside training. Position interpolation remains closer to the trained phase range while compressing local separation. Illustrative geometry based on Position Interpolation.[9]

Position Interpolation reported extensions of RoPE-based models with relatively short fine-tuning by linearly down-scaling indices.[9] YaRN introduced frequency-aware interpolation and attention scaling, with later revisions continuing to refine the method.[10] LongRoPE searched non-uniform scaling factors and used progressive extension.[11] LongRoPE2 combined rescaling with mixed-length training and argued that insufficient exposure of higher RoPE dimensions contributes to persistent out-of-distribution behaviour.[12]

These are important results, not universal guarantees. Effective context depends on the model, training data, attention architecture, task and evaluation. Official libraries now expose several RoPE variants, including linear, dynamic, YaRN, LongRoPE and model-specific scaling.[15] A recognised configuration name confirms that code can run. It does not prove that evidence at the declared limit can influence the answer correctly.

Worked example 4: a configured 32k system

Consider a hypothetical decoder with 128-dimensional heads, base 10,000 and 4,096-token training sequences. The deployment target is 32,768. Raw RoPE multiplies every phase excursion by eight. Linear interpolation keeps the maximum phase excursion near training but reduces every adjacent angular difference to one eighth. The correct choice cannot be made from context length alone. A retrieval task may tolerate compression, while character-level alignment may depend on precise local offsets.

The same formula can be wired into different systems

Before blaming a frequency schedule, verify that the implementation realises the schedule you think it does. Libraries differ in how they pair coordinates. Some rotate adjacent coordinates; others split the head into two halves and pair corresponding entries. These conventions are equivalent only when the weights, rotation helper and checkpoint agree. Mixing them preserves vector norms while silently changing every oriented interaction.

Position identifiers create a second boundary. Padding tokens, packed sequences and a key-value cache can make the physical array index differ from the logical token position. In autoregressive decoding, a new query must use the position that follows the cached keys. Resetting its identifier to zero does not test a new origin. It moves only one side of the comparison and changes every displacement. A legitimate origin shift must be applied consistently to both query and key positions.

Three further choices matter: how many head dimensions are rotary, where scaling is applied, and in which precision phases are generated. Rotating only part of a head leaves a content-only subspace beside the positional one. Scaling queries but not cached keys breaks the relative identity. Computing large angles in limited precision can introduce avoidable phase error even when the symbolic formula is correct. Precomputation and cache reuse should therefore be tested as part of the mechanism, not treated as neutral plumbing.

Failure-injection protocol

Run four paired tests before a context-extension claim: shift every logical position by the same constant; rotate forward and then apply the inverse; compare a full-sequence pass with token-by-token cached decoding; and deliberately mismatch the scaling or pairing convention on one side. The first three should agree within the declared numerical tolerance. The last should fail clearly. If the negative control does not separate, the test is too weak to certify the implementation.

Record the frequency base, rotary dimension, pairing convention, position-id policy, scaling rule, cache offset and phase precision with the result. That manifest turns “we use RoPE” into a reproducible mechanism claim. Without it, two systems can share a configuration label while implementing materially different positional operators.

A three-layer positional competence audit

The practical contribution of this paper is an audit that refuses to collapse three questions into one score.

Gate A, algebraic relativity: verify the operator identity numerically across random vectors, shifts and data types. A failure here indicates an implementation or indexing defect. Gate B, geometric identifiability: inspect adjacent resolution, distant phase similarities, wavelength coverage and numerical precision inside the target range. A failure here indicates an unsuitable ruler, not necessarily a failed model. Gate C, statistical familiarity: run controlled behavioural tests across positions, lengths and phase interventions. A failure here may arise from training, attention competition or the rest of the architecture even when the first two gates pass.

Three concentric tests for positional competence An inner ring tests the exact relative-position law, a middle ring tests offset distinguishability, and an outer ring tests whether training and behaviour remain reliable at deployment lengths. A relative law RₘᵀRₙ = Rₙ₋ₘ B offset identifiability C trained use at target length Pass conditions shift and inverse tests match to tolerance task offsets stay distinguishable behaviour survives target-length shifts Break conditions indexing or rotation mismatch collision inside required offset range retrieval or reasoning fails under shift Passing an inner ring never certifies an outer ring.
The three-layer positional competence audit. The exact group law is necessary for RoPE's intended invariance, but it does not certify offset resolution or learned long-context use. Each outer layer requires its own evidence. Practitioner synthesis introduced in this paper.

Run the geometry audit

The interactive lab below computes the bare frequency geometry. It tests the exact relative law with deterministic pseudo-random vectors, plots K(Δ), finds a high-similarity distant offset, counts slow channels that complete less than one cycle during training, and displays the trade-off introduced by interpolation.

Executable lab
Must be even; each pair receives one frequency.
Larger bases produce slower lowest frequencies.
Used for wavelength exposure and the distant-offset search boundary.
The chart samples up to the target length; collision search is capped for responsiveness.
Interpolation divides target indices by target length / training length.
Ignore trivial local similarity when finding a near-return.
0relative-law maximum error
0K(1), adjacent phase similarity
0highest sampled distant similarity
0offset of that distant similarity
0pairs below one training cycle
0effective angular-step ratio
Interactive rotary positional similarity chart The chart plots average cosine similarity between a zero position and relative offsets under the selected RoPE configuration.
Positional geometry audit. Change the dimension, base, training length, target length and scaling mode. A positive inner-law result permits reliance on the intended shift identity. It does not certify model quality. Synthetic, runs locally in the browser; no data leaves the page.

How to interpret the result

Table 2. What each audit outcome permits
ObservationPermitted conclusionNot permittedNext test
Relative-law error is near floating-point toleranceThe implementation preserves the intended rotary shift identity for tested casesThe model uses position correctly or generalises in lengthRun offset and global-shift behavioural interventions
High distant K(Δ)The bare phase bank contains a near-return at that offsetThe trained model must confuse those positionsConstruct matched retrieval examples at the two offsets
Many slow channels see under one cycle in trainingThose channels have limited phase-range exposureThey are useless or necessarily undertrainedAblate or rescale selected frequency bands
Interpolation reduces the step ratioLocal angular separation has been compressedLocal task accuracy will fall by the same factorMeasure exact-offset and character-level tasks
Behaviour fails only at long lengthThe deployed system lacks demonstrated effective contextRoPE alone caused the failureControl for attention dilution, data and task format
Python · positional_geometry_audit.py
from __future__ import annotations

import argparse
import math
from dataclasses import dataclass

import numpy as np


@dataclass(frozen=True)
class AuditResult:
    relative_law_error: float
    adjacent_similarity: float
    distant_similarity: float
    distant_offset: int
    slow_pairs: int
    pair_count: int
    angular_step_ratio: float


def frequencies(head_dim: int, base: float) -> np.ndarray:
    if head_dim < 2 or head_dim % 2:
        raise ValueError("head_dim must be a positive even integer")
    if base <= 1:
        raise ValueError("base must be greater than 1")
    pair_index = np.arange(head_dim // 2, dtype=np.float64)
    return base ** (-2.0 * pair_index / head_dim)


def rotate(x: np.ndarray, position: float, theta: np.ndarray) -> np.ndarray:
    pairs = x.reshape(-1, 2)
    angle = position * theta
    c, s = np.cos(angle), np.sin(angle)
    out = np.empty_like(pairs)
    out[:, 0] = pairs[:, 0] * c - pairs[:, 1] * s
    out[:, 1] = pairs[:, 0] * s + pairs[:, 1] * c
    return out.reshape(-1)


def kernel(offsets: np.ndarray, theta: np.ndarray, scale: float) -> np.ndarray:
    return np.cos(offsets[:, None] * scale * theta[None, :]).mean(axis=1)


def audit(
    head_dim: int = 128,
    base: float = 10_000.0,
    train_length: int = 4096,
    target_length: int = 32768,
    interpolate: bool = False,
    search_start: int | None = None,
) -> AuditResult:
    if train_length < 2 or target_length < 2:
        raise ValueError("train_length and target_length must both be at least 2")
    if search_start is not None and search_start < 2:
        raise ValueError("search_start must be at least 2")

    theta = frequencies(head_dim, base)
    scale = min(1.0, train_length / target_length) if interpolate else 1.0

    rng = np.random.default_rng(7)
    q, k = rng.normal(size=head_dim), rng.normal(size=head_dim)
    tests = [(3, 11), (17, 29), (101, 503), (train_length // 3, train_length - 1)]
    errors = []
    for m, n in tests:
        direct = np.dot(rotate(q, m * scale, theta), rotate(k, n * scale, theta))
        relative = np.dot(q, rotate(k, (n - m) * scale, theta))
        errors.append(abs(direct - relative))

    stop = min(target_length, 100_000)
    start = min(max(2, search_start if search_start is not None else train_length), stop)
    offsets = np.arange(start, stop + 1, dtype=np.float64)
    similarities = kernel(offsets, theta, scale)
    winner = int(np.argmax(similarities))

    training_cycles = train_length * theta / (2.0 * math.pi)
    return AuditResult(
        relative_law_error=float(max(errors)),
        adjacent_similarity=float(kernel(np.array([1.0]), theta, scale)[0]),
        distant_similarity=float(similarities[winner]),
        distant_offset=int(offsets[winner]),
        slow_pairs=int(np.sum(training_cycles < 1.0)),
        pair_count=len(theta),
        angular_step_ratio=scale,
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--head-dim", type=int, default=128)
    parser.add_argument("--base", type=float, default=10_000.0)
    parser.add_argument("--train-length", type=int, default=4096)
    parser.add_argument("--target-length", type=int, default=32768)
    parser.add_argument("--interpolate", action="store_true")
    args = parser.parse_args()
    print(audit(**vars(args)))

Save the code as positional_geometry_audit.py, install NumPy, and run python positional_geometry_audit.py. Add --interpolate to compare linear interpolation. A positive result on the relative-law test means the rotary implementation obeys its intended algebra within numerical tolerance. A negative result points to an indexing, pairing, scaling or precision defect.

The code cannot establish that a model understands order, retrieves distant evidence or reasons across long documents. It deliberately excludes learned weights, tokenisation, attention masks, values, training data and downstream tasks. Its purpose is to expose the positional mechanism that prose often hides, then tell you which behavioural experiment is still required.

Optional depth: a minimal behavioural protocol

Train a small causal Transformer on a synthetic offset-retrieval task at lengths 64 to 256. Place a key-value pair at a controlled displacement from the query. Evaluate four interventions separately: shift the entire sequence without changing displacement; hold length fixed while changing displacement; hold displacement fixed while increasing distractors; and rescale or replace the positional operator while freezing model weights. Record accuracy by absolute position, relative offset and sequence length. This design separates origin sensitivity, geometric resolution, attention dilution and adaptation debt.

Open research hypothesis

The three-layer audit should predict long-context failures better than training-length perplexity alone when models share data and architecture but differ in positional geometry. The hypothesis would be strengthened if near-collisions and phase-regime novelty forecast offset-specific errors that disappear after targeted rescaling or curriculum. It would be weakened if models remain reliable despite severe audit warnings, or fail independently of them. Attention dilution and insufficient long-range examples are the strongest rival explanations.

Strongest alternative explanation

A model can fail at 32,000 tokens even with a flawless positional operator because the relevant key competes with thousands of distractors, the task was absent from training, or the model's computation does not preserve evidence across layers. Conversely, a model can recover useful position without explicit RoPE through its causal mask. Recent systems have even interleaved RoPE layers with layers that omit positional embeddings.[14] Position geometry is one causal layer, not the whole context mechanism.

The evidence conversation
Chart · sequence
sequenceDiagram
  participant Q as Question
  participant M as Mechanism
  participant E as Evidence
  participant D as Decision
  Q->>M: Order without numbered seats
  M->>E: The symmetry that hides sequence order
  E-->>M: compare rival explanations
  E->>D: Test whether rotation preserves the relation
  D-->>Q: revise scope or act
Question, mechanism, evidence and decision exchange the burdens developed in Position from rotation: complex phases, Fourier structure and RoPE. Reading use: follow the relation, then return to the surrounding argument for evidence and limits.

Test whether rotation preserves the relation

Do not choose or scale a positional encoding because it supports a large number in a configuration field. Choose it because its invariance, resolution and training regime match the task.

For a task whose meaning should survive a global shift, demand and test a relative law. For tasks that depend on exact local offsets, inspect what interpolation does to adjacent angular separation. For long-range retrieval, search for positional near-returns, but also control attention dilution. For extrapolation, measure performance by both absolute location and relative displacement so that origin failures do not hide inside aggregate accuracy.

The engineering decision is to separate “the formula is defined” from “the geometry is discriminative” and from “the model has learned to use it”. RoPE gives an elegant answer to the first question. The frequency bank and numerical implementation shape the second. Only controlled training and intervention answer the third.

This also changes how alternatives are compared. A learned relative bias, ALiBi, RoPE and NoPE may achieve similar short-context scores while preserving different relations. Compare them by the intervention that matters: global shift, local displacement, length stretch, sparse retrieval, multidimensional structure or streaming state. Output matching on the original benchmark is not enough.

Decision rule: specify the positional invariance your task requires, verify the operator law, audit the target-range geometry, then earn the claimed context length with offset-controlled behavioural evidence. Never treat a rotary scaling setting as proof of effective context.

Periodic geometry succeeds because it reuses a small set of transformations across an unbounded index domain. Its limit is the same fact viewed from the other side: periodic signals revisit old directions. The right question is therefore not whether rotation “contains position” in the abstract. It is whether the chosen rotations preserve the relation your system must act upon, at the scales where it must act.

Glossary

Absolute position
A coordinate measured from a chosen sequence origin, such as token index 417.
Relative position
A displacement between two coordinates, such as “the key is 12 tokens before the query”.
Complex phase
A unit complex number eiφ whose angle φ represents rotation while its magnitude remains one.
Frequency
The angular change per token. Higher frequency means faster rotation and shorter wavelength.
Wavelength
The token distance required for a frequency to complete one full 2π rotation.
Group action
A rule that turns composition in one domain, here addition of positions, into composable transformations of another domain.
Kernel K(Δ)
The equal-weight average cosine similarity of the bare rotary phase bank at relative offset Δ. It is a diagnostic, not a trained attention score.
Length extrapolation
Using a model at sequence lengths beyond those represented in its training regime.
Position interpolation
Compressing target indices into a phase range closer to that seen in training.

References

  1. Vaswani, A. et al. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems 30.
  2. Shaw, P., Uszkoreit, J. and Vaswani, A. (2018). Self-Attention with Relative Position Representations. NAACL-HLT.
  3. Raffel, C. et al. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. Journal of Machine Learning Research, 21(140).
  4. Su, J. et al. (2021; journal version 2024). RoFormer: Enhanced Transformer with Rotary Position Embedding. Neurocomputing, 568.
  5. Press, O., Smith, N. A. and Lewis, M. (2022). Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation. ICLR.
  6. Dufter, P., Schmitt, M. and Schütze, H. (2022). Position Information in Transformers: An Overview. Computational Linguistics, 48(3), 733-763.
  7. Haviv, A. et al. (2022). Transformer Language Models without Positional Encodings Still Learn Positional Information. Findings of EMNLP.
  8. Kazemnejad, A. et al. (2023). The Impact of Positional Encoding on Length Generalization in Transformers.
  9. Chen, S. et al. (2023). Extending Context Window of Large Language Models via Positional Interpolation.
  10. Peng, B. et al. (2023, revised 2026). YaRN: Efficient Context Window Extension of Large Language Models.
  11. Ding, Y. et al. (2024). LongRoPE: Extending LLM Context Window Beyond 2 Million Tokens. ICML.
  12. Shang, N. et al. (2025). LongRoPE2: Near-Lossless LLM Context Window Scaling.
  13. Hua, E. et al. (2024). Fourier Position Embedding: Enhancing Attention's Periodic Extension for Length Generalization.
  14. Meta AI (2025). The Llama 4 herd: the beginning of a new era of natively multimodal AI innovation. Official architecture notes.
  15. Hugging Face Transformers. Utilities for Rotary Embedding. Official implementation documentation.