Inferensys

Glossary

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.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
SEQUENCE ORDER PRESERVATION

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.

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.

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.

Sequence Order Preservation

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.

01

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.

02

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
03

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
04

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
05

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| where m is a head-specific slope
06

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
SEQUENCE ORDERING STRATEGIES

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.

FeatureAbsolute Positional EncodingRelative 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.

POSITIONAL ENCODING EXPLAINED

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.

Prasad Kumkar

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.