Positional encoding is a mechanism that injects information about the absolute or relative position of tokens into a sequence model, enabling architectures like the Transformer to process data in parallel without losing the inherent order of the input. Since self-attention is permutation-invariant, positional encodings are mathematically summed with input embeddings to provide a unique representation for each time step.
Glossary
Positional Encoding

What is Positional Encoding?
A technique for injecting information about the absolute or relative position of tokens into a sequence model to preserve the order of the input data.
Common implementations use sinusoidal functions of varying frequencies, allowing the model to extrapolate to sequence lengths unseen during training. Alternatively, learned positional embeddings can be optimized during training. This technique is foundational for behavior sequence transformers and next-event prediction, where the chronological order of user actions is the primary signal for modeling intent.
Key Features of Positional Encoding
Positional encoding is the mechanism that injects information about the absolute or relative position of tokens into a sequence model, enabling parallel architectures like Transformers to understand word order without recurrence.
Absolute Positional Encoding
Assigns a unique vector to each position in the sequence using deterministic mathematical functions. The original Transformer uses sinusoidal functions of varying frequencies:
- Formula:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model)) - Formula:
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
This allows the model to extrapolate to sequence lengths not seen during training, as the functions are continuous and bounded.
Learned Positional Embeddings
Treats each position index as a discrete token and learns a dedicated embedding vector during training, identical to how word embeddings are learned.
- BERT and GPT models use this approach
- Vectors are stored in a lookup table of size
[max_seq_len, d_model] - Cannot extrapolate beyond the maximum training length
- Often outperforms sinusoidal encoding on fixed-length tasks due to task-specific optimization
Relative Positional Encoding
Encodes the pairwise distance between tokens rather than their absolute positions. This captures the intuition that the relationship between words depends more on their relative offset than their absolute location.
- Transformer-XL uses sinusoidal relative encodings
- T5 employs learned relative position biases per attention head
- Enables better generalization to sequences longer than those seen during training
- Critical for tasks where local context patterns dominate
Rotary Position Embedding (RoPE)
Encodes position by rotating the query and key vectors in the attention mechanism by an angle proportional to their position index. The dot product between rotated vectors naturally depends only on their relative distance.
- Used in LLaMA, Mistral, and PaLM architectures
- Provides theoretical elegance: relative position emerges from absolute rotations
- Decays attention scores with increasing relative distance
- Supports efficient long-context extrapolation with minimal modification
ALiBi (Attention with Linear Biases)
Removes positional embeddings entirely and instead subtracts a static, non-learned bias from the attention scores proportional to the distance between tokens. Each attention head uses a different slope.
- Simpler than RoPE or sinusoidal methods
- Used in BLOOM and early efficient Transformer variants
- Demonstrates strong length extrapolation: a model trained on 1024 tokens can perform well on 2048+
- The bias is computed as:
bias = -m * |i - j|wheremis a head-specific slope
2D and 3D Positional Encoding
Extends positional encoding beyond 1D sequences to handle multi-dimensional data like images, video, and point clouds. Position is encoded along multiple axes simultaneously.
- Vision Transformers (ViT) use learned 2D patch position embeddings
- Video models encode
(time, height, width)as separate or combined embeddings - Spatial coordinates in point cloud processing use sinusoidal encodings across X, Y, Z dimensions
- Enables Transformers to process non-sequential structured data
Absolute vs. Relative Positional Encoding
A technical comparison of the two primary methodologies for injecting token position information into the Transformer architecture to preserve sequential order.
| Feature | Absolute Positional Encoding | Relative Positional Encoding |
|---|---|---|
Core Mechanism | Adds a unique, pre-computed vector to each input embedding based on its absolute index in the sequence. | Modifies the self-attention computation itself by adding a learned or fixed bias to the attention score based on the relative distance between token pairs. |
Information Captured | The exact, fixed position of a token (e.g., token at index 5). | The pairwise distance and directional relationship between tokens (e.g., token 'A' is two positions before token 'B'). |
Input Length Generalization | ||
Translation Invariance | ||
Primary Implementation | Sinusoidal functions (Transformer paper) or learned embedding lookup tables. | Directly integrated into the attention score calculation (e.g., Shaw et al., Transformer-XL, T5 bias). |
Max Sequence Length Constraint | Hard limit defined at training time; cannot extrapolate to longer sequences. | No theoretical limit; can generalize to sequences of arbitrary length. |
Computational Overhead | Negligible; a simple element-wise addition to input embeddings. | Moderate; requires computing an O(n^2) relative position matrix during attention. |
Typical Use Case | Tasks with fixed-length inputs like sentence classification or BERT-style pre-training. | Tasks requiring long-range dependencies and length generalization like language modeling and music generation. |
Frequently Asked Questions
Clear, technically precise answers to the most common questions about how sequence models preserve order through positional information injection.
Positional encoding is a technique that injects information about the absolute or relative position of tokens into a sequence model to preserve the order of the input data. It is necessary because the core self-attention mechanism in the Transformer architecture is permutation-invariant—it processes all tokens in parallel and has no inherent sense of sequence order. Without positional encoding, the sentence 'The cat sat on the mat' would be indistinguishable from 'mat the on sat cat The.' The encoding provides a unique signal for each position, allowing the model to differentiate between identical tokens appearing at different locations and to learn temporal or sequential dependencies critical for language understanding, time-series forecasting, and sequential user behavior modeling.
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
Understanding positional encoding requires familiarity with the sequence modeling architectures and attention mechanisms it enables. These core concepts form the technical foundation for injecting order information into parallel processing pipelines.
Transformer Architecture
A neural network design that processes entire sequences in parallel rather than sequentially. Unlike recurrent models, Transformers have no inherent sense of token order, making positional encoding a critical component. The architecture stacks multiple self-attention and feed-forward layers, enabling it to capture long-range dependencies without the vanishing gradient problems that plague RNNs. Introduced in the 2017 paper Attention Is All You Need, it now underpins virtually all modern large language models.
Self-Attention
A mechanism that computes a contextual representation for each token by weighing its relevance against every other token in the sequence. For each position, the model calculates query, key, and value vectors, then produces an output as a weighted sum of values. Critically, self-attention is permutation-invariant—without positional encoding, shuffling the input sequence produces identical outputs, destroying syntactic and semantic order.
Sinusoidal Positional Encoding
The original method proposed in the Transformer paper, using fixed sine and cosine functions of varying frequencies to encode position. Each dimension of the encoding vector corresponds to a sinusoid with a different wavelength:
- Formula: PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
- Formula: PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model)) This design allows the model to easily learn relative positions, as the linear relationship between any two positions can be expressed through the sinusoid properties.
Learned Positional Embeddings
An alternative approach where position representations are treated as trainable parameters initialized randomly and updated via backpropagation. Each position index gets its own embedding vector, identical in dimension to token embeddings. Common in models like BERT and GPT, learned embeddings offer flexibility but are limited to a maximum sequence length defined at training time. They cannot naturally extrapolate to positions beyond this fixed window without interpolation or special techniques like ALiBi.
Rotary Position Embedding (RoPE)
A widely adopted method that encodes position by rotating the query and key vectors in self-attention by an angle proportional to their position. Key properties:
- Relative position is captured through the dot product of rotated vectors
- Absolute position decays naturally with token distance
- Enables length extrapolation beyond training context windows Used in LLaMA, Mistral, and Gemma model families, RoPE has become the dominant encoding scheme in modern open-source LLMs due to its mathematical elegance and empirical performance.
Relative Positional Encoding
A family of methods that model pairwise distances between tokens rather than absolute positions. Instead of assigning a position ID to each token, these encodings inject a bias into the attention computation based on the offset between token pairs:
- T5 uses learned scalar biases for each relative distance bucket
- Transformer-XL uses sinusoidal relative encodings for recurrence
- DeBERTa disentangles content and position in attention Relative encodings naturally handle sequences longer than those seen during training.

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