The vanilla Transformer architecture is fundamentally permutation-invariant. Without an explicit mechanism to track order, a model treats a coherent sentence as an unordered bag of tokens. To solve this, early models utilized Absolute Positional Encodings (APEs), adding a unique coordinate vector to each token's embedding based on its fixed index in the sequence.
While APEs work well when training and testing on the same sequence length, they fail catastrophically at length extrapolation—the ability to process sequences longer than those seen during training. If a model is trained on sequences up to length $L$, it only learns absolute positional embeddings for indices $1$ to $L$. When presented with a sequence of length $2L$ at inference time, the model encounters completely unseen absolute indices. As detailed in a comprehensive survey by Liang Zhao et al. in Length Extrapolation of Transformers: A Survey from the Perspective of Positional Encoding, this out-of-distribution shift causes the self-attention mechanism to break down, leading to severe performance degradation.
To solve this bottleneck, researchers shifted the frame of reference from absolute coordinates to relative distances.
Shift Invariance: Thinking Relatively
Instead of asking "Where am I in the sequence?", a relative positional encoding (RPE) mechanism forces the attention layer to ask "How far apart are we?".
In their foundational work, Peter Shaw et al. introduced this concept in Self-Attention with Relative Position Representations by modifying the self-attention operation to incorporate learnable vectors representing the relative distance ($i - j$) between a query token $i$ and a key token $j$.
The core intuition behind why this works is shift invariance. A distance of 5 tokens carries the same structural meaning whether it occurs at the beginning of a short sentence or 10,000 tokens deep into a massive document. As demonstrated by Jan Rosendahl et al. in Analysis of Positional Encodings for Neural Machine Translation, clipping these relative distances at a maximum threshold forces the model to prioritize local context. Because the model never encounters an "unseen" relative distance beyond the clipped threshold, the attention patterns remain stable and consistent regardless of the total sequence length.
Absolute Encoding (Rigid):
Token: [ The ] [ cat ] [ sat ] ... [ mat ]
Position: 1 2 3 500 --> (Fails if position is 1000)
Relative Encoding (Shift-Invariant):
Query: [ sat ]
Keys: [ The ] [ cat ] [ sat ]
Distance: -2 -1 0 --> (Stays the same anywhere in the text)
Mathematical Formulations of Distance
The machine learning community has developed several distinct mathematical strategies to inject relative distance into the attention calculation:
- Rotary Position Embeddings (RoPE): Instead of adding distance vectors to the token representations, RoPE applies a rotation matrix to the queries and keys in a complex vector space. As utilized by Shengqiang Li et al. in Conformer-based End-to-end Speech Recognition With Rotary Position Embedding, the inner product of the rotated query and key vectors naturally encapsulates their relative angular difference. This elegant formulation ensures that the attention scores decay gracefully as the distance between speech frames or text tokens increases.
- Linear Biases and Penalties: Rather than learning embeddings, some architectures inject a static, non-learnable penalty directly into the attention matrix based on token distance. Xueyi Li et al. demonstrate in Enhancing Length Generalization for Attention Based Knowledge Tracing Models with Linear Biases that these linear distance penalties provide a highly stable performance curve, preventing the attention distribution from "smearing" when processing long interaction histories.
- Continuous and Functional Encodings: To avoid the constraints of discrete lookup tables entirely, some approaches model position as a continuous space. Hsiang-Fu Yu et al. developed FLOATER in Learning to Encode Position for Transformer with Continuous Dynamical Model, which uses Neural Ordinary Differential Equations (ODEs) to define position dynamically. Similarly, Di-Nan Lin shows in How Do Position Encodings Affect Length Generalization? Case Studies On In-Context Function Learning that functional relative encodings allow models to interpret distances continuously, significantly extending the effective input window.
Structural and Task-Aware Coupling
While linear relative distance works well for natural language prose, it falls short on highly structured algorithmic tasks like arithmetic. If a model is asked to add two 100-digit numbers, simply knowing the linear distance between digits is insufficient; the model must align the "ones" column with the "ones" column, the "tens" with the "tens", and so on, regardless of how many digits the numbers contain.
To address this, researchers have designed structural relative encodings that couple positions based on semantic roles rather than sequence indices:
- Abacus Embeddings: Sean McLeish et al. proposed this approach in Transformers Can Do Arithmetic with the Right Embeddings, tracking a digit's position relative to the start of its respective number rather than its absolute position in the prompt. This allows a model trained on 20-digit addition to generalize to 100-digit problems with near-perfect accuracy.
- Position Coupling: In Position Coupling: Improving Length Generalization of Arithmetic Transformers Using Task Structure, Hanseul Cho et al. took this further by assigning identical positional identifiers to tokens that share the same place value across different operands. By embedding the task's inherent structural symmetry directly into the positional representation, the architecture bypasses standard locality biases and learns the underlying mathematical algorithm rather than memorizing sequence slots.
The Radical Alternative: No Positional Encoding (NoPE)
Given the complexities of engineering the perfect relative encoding, a compelling question arises: can we remove explicit positional signals altogether?
Inkit Padhi investigated this in The Impact of Positional Encoding on Length Generalization in Transformers and discovered that decoder-only Transformers without any positional encodings (NoPE) frequently outperform models with complex positional schemes on reasoning tasks.
This works because the causal attention mask inherently breaks permutation invariance. Because a token in a decoder-only model can only attend to the tokens behind it, the model can implicitly deduce relative order and distance purely from the structure of the mask.
This empirical finding is supported by the theoretical work of Daichi Hayakawa et al. in Theoretical Analysis of Hierarchical Language Recognition and Generation by Transformers without Positional Encoding. The authors proved mathematically that omitting explicit positional signals introduces a clean inductive bias that favors relative token relationships over absolute indices. By relying entirely on causal masking and token-to-token interactions, the model avoids overfitting to rigid training lengths and naturally scales to longer sequences.