Positional encoding

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:

Learned vs designed positional encoding:

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:

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 .

More succinctly,In typical implementations, all operations are done over the real numbers, not the complex numbers, but since complex multiplication can be implemented as real 2-by-2 matrix multiplication, this is a mere notational difference.

Radix interpretation

The positional encoding has been interpreted as implementing a base- positional number system for representing real numbers:

Position FrequencyFactorTokens per cycle ("wavelength")Tokens per cycle at
Lowest 16.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 network language 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

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.

YaRN has been used across many models, including DeepSeek, Qwen, Kimi, and GPT-OSS.

References

  1. 1 2 3 Gehring, 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. ISSN 2640-3498.
  2. 1 2 Shaw, Peter; Uszkoreit, Jakob; Vaswani, Ashish (2018). "Self-Attention with Relative Position Representations". arXiv:1803.02155 [cs.CL].
  3. ↑ Google Research. "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding". GitHub. modeling.py, line 496. Commit eedf5716ce1268e56f0a50264a88cafad334ac61. {{cite web}}: |author= has generic name (help)
  4. ↑ 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].
  5. 1 2 Wang, 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.
  6. 1 2 Vaswani, Ashish; Shazeer, Noam; Parmar, Niki; Uszkoreit, Jakob; Jones, Llion; Gomez, Aidan N; Kaiser, Łukasz; Polosukhin, Illia (2017). "Attention is All You Need" (PDF). 31st Conference on Neural Information Processing Systems (NIPS 2017), 4-9 December 2017, Long Beach, CA, USA. Vol. 30. Curran Associates, Inc. arXiv:1706.03762. ISBN 978-1-5108-6096-4. Archived from the original (PDF) on 2024-02-21. Retrieved 2023-10-31.
  7. ↑ 苏, 剑林 (2023-07-06). "Transformer升级之路:10、RoPE是一种β进制编码" [The Road to Transformer Upgrades: 10. RoPE Is a Base-β Encoding]. 科学空间 (in Chinese).
  8. ↑ Press, Ofir; Smith, Noah A.; Lewis, Mike (2021-08-01). "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation". arXiv:2108.12409 [cs.CL].
  9. ↑ Ke, Guolin; He, Di; Liu, Tie-Yan (2021-03-15). "Rethinking Positional Encoding in Language Pre-training". arXiv:2006.15595 [cs.CL].
  10. ↑ Raffel, Colin; Shazeer, Noam; Roberts, Adam; Lee, Katherine; Narang, Sharan; Matena, Michael; Zhou, Yanqi; Li, Wei; Liu, Peter J. (2020). "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer". Journal of Machine Learning Research. 21 (140): 1–67. arXiv:1910.10683. ISSN 1533-7928.
  11. 1 2 Su, Jianlin; Ahmed, Murtadha; Lu, Yu; Pan, Shengfeng; Bo, Wen; Liu, Yunfeng (2024-02-01). "RoFormer: Enhanced transformer with Rotary Position Embedding". Neurocomputing. 568: 127063. doi:10.1016/j.neucom.2023.127063. ISSN 0925-2312. Archived from the original on 2026-01-15.{{cite journal}}: CS1 maint: article number as page number (link)
  12. ↑ Touvron, Hugo; Lavril, Thibaut; Izacard, Gautier; Martinet, Xavier; Lachaux, Marie-Anne; Lacroix, Timothée; Rozière, Baptiste; Goyal, Naman; Hambro, Eric; Azhar, Faisal; Rodriguez, Aurelien; Joulin, Armand; Grave, Edouard; Lample, Guillaume (2023). "LLaMA: Open and Efficient Foundation Language Models". arXiv:2302.13971 [cs.CL].
  13. ↑ Jin, Hongye; Han, Xiaotian; Yang, Jingfeng; Jiang, Zhimeng; Liu, Zirui; Chang, Chia-Yuan; Chen, Huiyuan; Hu, Xia (2024-07-11). "LLM Maybe LongLM: Self-Extend LLM Context Window Without Tuning". arXiv:2401.01325 [cs.CL].
  14. ↑ Sun, Yutao; Dong, Li; Patra, Barun; Ma, Shuming; Huang, Shaohan; Benhaim, Alon; Chaudhary, Vishrav; Song, Xia; Wei, Furu (2022-12-20). "A Length-Extrapolatable Transformer". arXiv:2212.10554 [cs.CL].
  15. ↑ 苏, 剑林 (2025-04-18). "Transformer升级之路:19、第二类旋转位置编码" [The Road to Transformer Upgrades: 19. The Second Type of Rotary Position Encoding]. 科学空间 (in Chinese).
  16. ↑ "Rotary Positional Embeddings with Relative distances (RoPER)". labml.ai research blog. 2022. Retrieved 2026-10-26.
  17. ↑ Haviv, Adi; Ram, Ori; Press, Ofir; Izsak, Peter; Levy, Omer (December 2022). Goldberg, Yoav; Kozareva, Zornitsa; Zhang, Yue (eds.). "Transformer Language Models without Positional Encodings Still Learn Positional Information". Findings of the Association for Computational Linguistics: EMNLP 2022. Abu Dhabi, United Arab Emirates: Association for Computational Linguistics: 1382–1390. doi:10.18653/v1/2022.findings-emnlp.99.
  18. ↑ Kazemnejad, Amirhossein; Padhi, Inkit; Natesan Ramamurthy, Karthikeyan; Das, Payel; Reddy, Siva (2023). "The Impact of Positional Encoding on Length Generalization in Transformers". Advances in Neural Information Processing Systems. 36. Curran Associates, Inc.: 24892–24928. doi:10.52202/075280-1082.
  19. ↑ Wang, Jie; Ji, Tao; Wu, Yuanbin; Yan, Hang; Gui, Tao; Zhang, Qi; Huang, Xuanjing; Wang, Xiaoling (August 2024). Ku, Lun-Wei; Martins, Andre; Srikumar, Vivek (eds.). "Length Generalization of Causal Transformers without Position Encoding". Findings of the Association for Computational Linguistics: ACL 2024. Bangkok, Thailand: Association for Computational Linguistics: 14024–14040. doi:10.18653/v1/2024.findings-acl.834.
  20. ↑ "The Llama 4 herd: The beginning of a new era of natively multimodal AI innovation". ai.meta.com. Archived from the original on 2026-10-21. Retrieved 2026-10-26.
  21. ↑ 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].
  22. ↑ 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. ISBN 979-8-89176-251-0.{{cite journal}}: CS1 maint: periodical has ISBN (link)
  23. ↑ Child, Rewon; Gray, Scott; Radford, Alec; Sutskever, Ilya (2019-04-23). "Generating Long Sequences with Sparse Transformers". arXiv:1904.10509 [cs.LG].
  24. ↑ 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].
  25. 1 2 Xiong, 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.
  26. 1 2 3 Peng, Bowen; Quesnelle, Jeffrey; Fan, Honglu; Shippole, Enrico (2024-05-31). "YaRN: Efficient Context Window Extension of Large Language Models". International Conference on Learning Representations. 2024: 31932–31951.