In deep learning, the positional encoding is a component of sequence models, especially Transformers. Input data such as text, images, or audio is converted to a sequence of numerical representations called tokens, and the position of each token is encoded as a vector. This combination of token embedding vectors and positional encoding vectors is a context window.
Positional encoding is used because the standard attention mechanism used in Transformers by default treats all tokens symmetrically over all positions (i.e. permutation-symmetric), thus effectively treating the input as a bag of tokens, rather than a sequence of tokens.
Typology
Absolute vs relative positional encoding:
In an absolute positional encoding scheme, the position of a token within a context is encoded. That is, it matters whether a token is at position 1 or position 100. This was proposed in 2017, just before Transformer was published.
In a relative positional encoding scheme, the relative position of two tokens within a context is encoded. That is, it matters not whether a token is at position 1 or position 100, and it only matters whether one token is in front of another token by 1 or 100. This property is also called translational invariance. This was propsed in 2018, just after Transformer was published.
Learned vs designed positional encoding:
In a learned positional encoding scheme, the parameters of positional encoding are learned like any other parameter in a model, usually by backpropagation.
In a designed positional encoding scheme, the parameters are not learned, and picked by the researchers. That is, they are hyperparameters.
For example, BERT used two levels of positional embeddings, one for the per-token position, and one for per-segment position. Both are absolute and learned. It was reported that learned absolute positional encoding generally perform better than relative positional encoding when there are special tokens that always occur in a specific location, such as the [CLS] token of BERT-like architectures. However, with learned absolute positional encoding, a model cannot process contexts longer than what it is trained for.
Other possibly desirable properties of a positional encoding scheme include:
Symmetry: In a symmetric positional encoding scheme, the positional encoding of a token tokens before is the same as that of a token tokens after. This property only makes sense for non-causal Transformers, since in a causal Transformer, a token cannot pay any attention to its subsequent tokens.
Monotonicity: In a monotonic positional encoding scheme, the positional encoding increases attention weighing on nearby tokens compared to far-away tokens.
Sinusoidal
A standard transformer architecture, showing on the left an encoder, and on the right a decoder.
The original transformer paper (Attention Is All You Need) uses a sinusoidal absolute positional encoding. Each token is converted to an token embedding vector , plus a positional encoding vector .
depends only on the identity of the token, not on . That is, the token "the" would have the same , no matter if it appears in the first or the last position. depends only on the position of the token, not on the identity of the token. That is, the -th token always has the same , no matter if it is "the" or "a".
Both the encoder and the decoder takes as input. This is shown in the picture.
Both and has the same number of dimensions, since they must be added. Both of them have even dimensions, since that is what the positional encoding vector requires.
Let the dimension be , then the position encoding vector is defined as
Illustration of (absolute) positional encoding with parameters .
where .
Here, is a free parameter that should be significantly larger than the biggest that would be input into the positional encoding function. The original paper uses .
The positional encoding has been interpreted as implementing a base-positional number system for representing real numbers:
Position
Frequency
Factor
Tokens per cycle ("wavelength")
Tokens per cycle at
Lowest
1
6.3
Next lowest
7.5
Highest
52261
The effect of base- positional number system means the attention mechanism is to apportion its attention by coordinate. For low frequency (long wavelength) coordinates, RoPE implicitly states that these coordinates encode information that varies slowly over a sequence, and vice versa for high frequency (low wavelength) coordinates. Concretely, the first 2 coordinates are treated as encoding features that vary quickly every token, while the last 2 coordinates are treated as encoding features that vary slowyl over 10000s of tokens.
Symmetry
This positional encoding method was designed based on previous work on convolutional neural networklanguage model. In the author's words, "we hypothesized it would allow the model to easily learn to attend by relative position."
A relative position shift is just a linear transformation away:where is the distance one wishes to shift. More generally, any convolution of relative positions is also just a linear transformation away:for any constants . This allows the transformer to take any encoded position and find a linear sum of the encoded locations of its neighbors.
ALiBi
In the original Transformer, positions are encoded by a vector that is added to the token embedding vector , and the Transformer only sees their sum . ALiBi (Attention with Linear Biases) is a relative positional encoding scheme that partially decouples the position encoding from the token embedding, by injecting positional encoding directly into each attention mechanism block.
The attention mechanism block in the original Transformer iswhere stand for the matrices for the query, key, and value vectors, stands for the dimension of the key, and stands for the mask matrix. Explicitly,
The ALiBi attention mechanism modifies it toHere, is a learnable scalar, and is the linear bias matrix defined byin other words, . The idea being that the linear bias matrix is a softened mask. Just as represent full attention paid, and represents no attention paid, the linear bias matrix linearly decreases the attention logit. Note that in the causally masked Transformer, any attention paid to the future is blanked out by the causal mask matrixso the upper triangular part of does not matter.
ALiBi allows pretraining on short context windows, then fine-tuning on longer context windows. Since it is directly plugged into the attention mechanism, it can be combined with any positional encoder that is plugged into the "bottom" of the entire network (which is where the sinusoidal encoder on the original transformer, as well as RoPE and many others, are located).
More generally, is a more general version:where is a Toeplitz matrix.For example, Google T5 used a learned Relative Position Representation, where the diagonals in the positional bias matrix are grouped into bands to decrease the number of learnable parameters of .
Relatedly, Relative Position Representations was an early attempt by some of the original authors of the Transformer to make a decoupled relative positional encoding scheme. It has not been used much in practice since 2018. In this scheme, learned positional encoding vectors are added to the key and value vectors in an attention mechanism block.
RoPE
RoPE (Rotary Positional Encoding) is another scheme for relative positional encoding. It works by rotating the key and value vectors input into a attention mechanism block.
Consider a feature vector with even dimensions: . Like in the original sinuisoidal positional encoding scheme, it can be written as a complex vector . Then, to encode it as positioned at , the -th feature vector is represented by rotating its entries:where the frequencies are usually designed by hand. A standard design is where , the same base as the original Transformer, and common since the original RoPE paper and Llama.
In an attention mechanism, RoPE is implemented aswhereand similarly for the RoPE key matrix .
Like the original positional encoding, it is translation-invariant and behaves as a base- positional number system. Specifically, translation symmetry means thatfor any and any .
ReRoPE
ReRoPE and Leaky ReRoPE:
Variants
Extrapolatable Position Embedding (xPos) adds decay terms to the rotation of RoPE, designed to damp out the high-frequency oscillations at long distances.though the decay terms are inverted for the key vectors:It is also limited to causal attention masking, since otherwise the attention scores will diverge.
RoPE-2D applies RoPE to tokens that are arranged on a plane. They are used in vision transformers. Similarly, Transformers that process videos may use RoPE-3D. In equations,
RoPE with Relative distances (RoPER), or value-output RoPE (VO-RoPE), applies RoPE to value vectors. The idea is to rotate the value vectors using RoPE.The idea is as follows: the output matrix is an attention-weighted sum of the value vectors:so relative positional encoding can be implemented by rotating each value vector absolutely, then undoing it in the output vectors, thus resulting in another relative positional encoding.note that .
NoPE
In NoPE (No Positional Encoding), there is no positional encoding. The idea is that a decoder's causal masking lets each token to see only tokens , which is an implicit kind of positional encoding.
NoPE is rarely used for all attention modules of a Transformer, since it degrades performance too much is used to save compute. However, NoPE may be used for some attention modules to trade off performance for computing cost. For example, Llama 4 alternates layers of NoPE and RoPE, with RoPE in 3 layers and NoPE in the 4th. They call it iRoPE ("interleaved RoPE").
Context extension
Since the per-token cost of inference scales with context length, training cost is decreased by using shorter contexts during training. However, this would make the resulting model bad at using longer contexts. Consequently, a common way to train a model is to "train short, test long", i.e. training a model on short contexts, and use it on long contexts.
Context extension was a concern since the original Transformer paper. In it, the authors reported trying both learned positional encoding and desigend positional encoding. They found both to result in similar performance, and decided to use the designed positional encoding, since it "may allow the model to extrapolate to sequence lengths longer than the ones encountered during training".
A slightly more sophisticated method is train according to a curriculum: Begin by training on a short context length, then train on a longer context length. This can be repeated. For example, the model can be pretrained on context lengths up to 8K tokens, then up to 64K, then up to 512K.
Context lengths can even be mixed during training. It was found that given a fixed training budget, training on a mixture of long contexts and short contexts resulted in higher performance than purely training on long contexts.
In general, context extension using RoPE consists of training a model on one context length with one set of RoPE angles , then its RoPE angles are modified to , and it is trained further on context length for some .
Some architectures natively support context extension. For example, convolutional seq2seq, and sliding window attention, are both insensitive to context length.
Dynamic scaling
YaRN
In Positional Interpolation (PI), frequencies are stretched equally: . This was found to degrade performance beyond , as the model loses the high-frequency resolution that tells adjacent tokens apart.
In Adjusted Base Frequency (ABF) (other names include "NTK-aware", "NTK-RoPE", "RoPE-ABF"), the base is increased: , where is designed so thatEquivalently, . The effect is that the highest frequency is not stretched, the lowest frequency is stretched by , and those in-between are interpolated.
In "NTK-by-parts", high frequencies are not stretched, low frequencies are stretched by , and those in-between are interpolated:where
if the feature rotates by more than times over the length of a context: . Equivalently, the wavelength is short enough: .
if the feature rotates by less than times over the length of a context: . Equivalently, the wavelength is long enough: .
is linearly interpolated otherwise: .
YaRN (Yet another RoPE extensioN) uses NTK-by-parts with frequencies scales with , meaning that wavelengths shorter than are not stretched, wavelengths longer than are fully stretched by , and those in-between are stretched by an in-between value.
YaRN alse scales up the logits in the attention mechanism. The idea is that stretching frequencies blurs the corresponding features, and scaling up the logits unblurs them. The authors experimented with context-extending models from the Llama and Llama 2 series, and found empirically thatworked well.
123Gehring, Jonas; Auli, Michael; Grangier, David; Yarats, Denis; Dauphin, Yann N. (2017-07-17). "Convolutional Sequence to Sequence Learning". Proceedings of the 34th International Conference on Machine Learning. PMLR: 1243–1252. ISSN2640-3498.
12Shaw, Peter; Uszkoreit, Jakob; Vaswani, Ashish (2018). "Self-Attention with Relative Position Representations". arXiv:1803.02155 [cs.CL].
↑Devlin, Jacob; Chang, Ming-Wei; Lee, Kenton; Toutanova, Kristina (11 October 2018). "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding". arXiv:1810.04805v2 [cs.CL].
12Wang, Benyou; Shang, Lifeng; Lioma, Christina; Jiang, Xin; Yang, Hao; Liu, Qun; Simonsen, Jakob Grue (2021). "On Position Embeddings in BERT". International Conference on Learning Representations.
↑苏, 剑林 (2025-04-18). "Transformer升级之路:19、第二类旋转位置编码"[The Road to Transformer Upgrades: 19. The Second Type of Rotary Position Encoding]. 科学空间 (in Chinese).
↑Press, Ofir; Smith, Noah A.; Lewis, Mike (2022-04-22). "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation". arXiv:2108.12409 [cs.CL].
↑Gao, Tianyu; Wettig, Alexander; Yen, Howard; Chen, Danqi (July 2025). Che, Wanxiang; Nabende, Joyce; Shutova, Ekaterina; Pilehvar, Mohammad Taher (eds.). "How to Train Long-Context Language Models (Effectively)". Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). Vienna, Austria: Association for Computational Linguistics: 7376–7399. doi:10.18653/v1/2025.acl-long.366. ISBN979-8-89176-251-0.{{cite journal}}: CS1 maint: periodical has ISBN (link)
↑Child, Rewon; Gray, Scott; Radford, Alec; Sutskever, Ilya (2019-04-23). "Generating Long Sequences with Sparse Transformers". arXiv:1904.10509 [cs.LG].
↑Chen, Shouyuan; Wong, Sherman; Chen, Liangjian; Tian, Yuandong (2023-06-28). "Extending Context Window of Large Language Models via Positional Interpolation". arXiv:2306.15595 [cs.CL].
12Xiong, Wenhan; Liu, Jingyu; Molybog, Igor; Zhang, Hejia; Bhargava, Prajjwal; Hou, Rui; Martin, Louis; Rungta, Rashi; Sankararaman, Karthik Abinav; Oguz, Barlas; Khabsa, Madian; Fang, Han; Mehdad, Yashar; Narang, Sharan; Malik, Kshitiz (June 2024). Duh, Kevin; Gomez, Helena; Bethard, Steven (eds.). "Effective Long-Context Scaling of Foundation Models". Proceedings of the 2024 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (Volume 1: Long Papers). Mexico City, Mexico: Association for Computational Linguistics: 4643–4663. doi:10.18653/v1/2024.naacl-long.260.