Positional encoding is a technique that adds a unique signal to each token's embedding vector based on its position in the sequence. Since the self-attention mechanism processes all tokens in parallel without any inherent notion of order, the model would otherwise be unable to distinguish between the sequences "Dog bites man" and "Man bites dog." The encoding is added to the input embeddings at the bottom of the encoder or decoder stack.
Glossary
Positional Encoding

What is Positional Encoding?
Positional encoding is the mechanism used in Transformer architectures to inject information about the absolute or relative position of tokens into the input embeddings, compensating for the inherent permutation-invariance of the self-attention mechanism.
The original Transformer paper proposed a sinusoidal positional encoding using sine and cosine functions of different frequencies. This allows the model to extrapolate to sequence lengths unseen during training. Modern architectures often use learned positional embeddings or Rotary Position Embedding (RoPE), which encodes relative position information directly into the attention computation by rotating the Query and Key vectors, providing better length generalization.
Key Characteristics of Positional Encoding
Since the self-attention mechanism is inherently permutation-invariant, positional encoding is the critical technique that injects information about the absolute or relative position of tokens into the input embeddings, allowing the model to understand sequence order.
Permutation Invariance Problem
Self-attention calculates relationships between tokens without any inherent notion of their order. Without positional encoding, the sentence 'The dog bit the man' would be processed identically to 'The man bit the dog.' Positional encoding solves this by adding a unique signal to each token's embedding based on its position, making the input representation order-aware before it enters the attention layers.
Sinusoidal Absolute Encoding
The original Transformer paper introduced fixed sinusoidal functions to encode absolute position. Each dimension of the positional vector corresponds to a sinusoid with a different frequency:
- Formula:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model)) - Formula:
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model)) - Key Property: The linear relationship between positions allows the model to easily learn to attend by relative position, as
PE(pos+k)can be represented as a linear function ofPE(pos).
Learned Positional Embeddings
An alternative to fixed sinusoids is to treat position as a learnable parameter. A standard embedding lookup table is created for positions 0 up to the maximum context length. These embeddings are trained via backpropagation alongside all other model weights.
- Advantage: The model can learn an optimal encoding for the specific data distribution.
- Disadvantage: Cannot extrapolate to sequence lengths longer than those seen during training, unlike sinusoidal encodings which generalize to arbitrary lengths.
Relative Positional Encoding
Instead of encoding absolute position, relative methods modify the attention mechanism itself to consider the pairwise distance between tokens. This directly models the intuition that the relationship between two words depends more on their distance than their absolute location.
- Approach: A learned bias is added to the attention score based on the offset between token
iand tokenj. - Benefit: Naturally generalizes to sequences longer than any seen during training, as only the relative distance matters.
Rotary Position Embedding (RoPE)
RoPE encodes position by rotating the Query and Key vectors in multi-head attention by an angle proportional to their position. This elegantly combines absolute and relative position encoding.
- Mechanism: The dot product between Query and Key naturally decays with relative distance, encoding relative position implicitly.
- Adoption: Used in Meta Llama, Mistral, and many state-of-the-art open-source models due to its stability and ability to extend context length via interpolation techniques like NTK-aware scaling.
ALiBi (Attention with Linear Biases)
ALiBi removes positional embeddings entirely and instead adds a static, non-learned bias to the attention scores. This bias is a constant penalty proportional to the distance between tokens.
- Simplicity: No trainable positional parameters are required.
- Extrapolation: Demonstrates strong length extrapolation, performing well on sequences up to 2,000 tokens when trained on only 1,024.
- Implementation: For each attention head, a unique slope
mis pre-defined, and the bias is computed as-m * |i - j|.
Sinusoidal vs. Learned Positional Encoding
A comparison of the two primary methods for injecting sequence order information into the permutation-invariant Transformer architecture.
| Feature | Sinusoidal (Fixed) | Learned (Trainable) | Rotary (RoPE) |
|---|---|---|---|
Parameter Count | 0 (no added parameters) | N_context * d_model | 0 (no added parameters) |
Extrapolation Length | Theoretically infinite | Strictly bounded by max training length | Limited but with decay |
Relative Position Capture | Implicit via dot product | ||
Inductive Bias | Smooth, sinusoidal periodicity | Arbitrary, data-driven | Rotational invariance |
Training Speed | Fastest (no gradient updates) | Slower (additional parameters) | Fast (no gradient updates) |
Adoption | Original Transformer, BERT Encoder | GPT-1, GPT-2, Vision Transformers | LLaMA, PaLM, GPT-NeoX |
Distance Decay | Stable long-range decay | No guaranteed decay pattern | Stable long-range decay |
Frequently Asked Questions
Clear, technical answers to the most common questions about how Transformers understand token order.
Positional encoding is a technique for injecting information about the absolute or relative position of tokens into the input embeddings of a Transformer model. It is strictly necessary because the self-attention mechanism is inherently permutation-invariant—it processes tokens as a set, not a sequence. Without positional information, the sentence 'The dog bit the man' and 'The man bit the dog' would produce identical representations. Positional encodings break this symmetry by adding a unique signal to each token's embedding vector based on its location in the sequence, allowing the model to distinguish word order and learn sequential dependencies.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Explore the core mechanisms that enable Transformers to understand sequence order, from absolute sinusoidal functions to modern relative position techniques.
Absolute vs. Relative Positional Encoding
Two fundamental paradigms for injecting sequence order:
- Absolute Encoding: Assigns a unique vector to each position (e.g., sinusoidal or learned). Added directly to input embeddings before attention.
- Relative Encoding: Models the distance between token pairs during attention calculation. Transformer-XL and T5 use relative biases, while RoPE achieves this through vector rotation. Relative methods typically generalize better to sequences longer than those seen during training.
Sinusoidal Positional Encoding
The original method from Vaswani et al. (2017) that uses sine and cosine functions of varying frequencies to generate deterministic position vectors. Each dimension of the encoding corresponds to a sinusoid with a different wavelength, forming a continuous geometric pattern. The key property is that the encoding for position pos + k can be represented as a linear function of the encoding for position pos, theoretically allowing the model to learn relative positions.
Learned Positional Embeddings
A simpler alternative where position representations are treated as trainable parameters in an embedding lookup table, identical to token embeddings. Used in early models like BERT and GPT-2, this approach lets the model discover optimal position representations during training. The primary limitation is the fixed maximum sequence length—positions beyond the pre-defined table size cannot be represented, requiring truncation or interpolation.
Permutation Invariance Problem
The fundamental limitation that makes positional encoding necessary. The self-attention mechanism computes weighted sums of Value vectors based solely on content similarity, with no inherent notion of token order. Without position information, the sentences 'The dog bit the man' and 'The man bit the dog' produce identical representations. Positional encoding breaks this symmetry by injecting sequence-order information into the otherwise order-agnostic attention calculation.
ALiBi (Attention with Linear Biases)
A relative encoding method that adds a static, non-learned bias to the attention scores before softmax. The bias is a linear penalty proportional to the distance between tokens, with different slopes per attention head. This simple approach eliminates the need for explicit position embeddings entirely and has demonstrated remarkable length extrapolation—models trained on short sequences can perform well on much longer ones without fine-tuning.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us