Inferensys

Glossary

Positional Encoding

A technique for injecting information about the absolute or relative position of tokens into input embeddings, compensating for the permutation-invariant nature of the self-attention mechanism.
Engineer reviewing vector database search results on laptop, embeddings visualization on screen, home office coding session.
SEQUENCE ORDER INJECTION

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.

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.

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.

INJECTING SEQUENCE ORDER

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.

01

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.

02

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 of PE(pos).
03

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.
04

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 i and token j.
  • Benefit: Naturally generalizes to sequences longer than any seen during training, as only the relative distance matters.
05

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.
06

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 m is pre-defined, and the bias is computed as -m * |i - j|.
POSITIONAL ENCODING STRATEGIES

Sinusoidal vs. Learned Positional Encoding

A comparison of the two primary methods for injecting sequence order information into the permutation-invariant Transformer architecture.

FeatureSinusoidal (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

POSITIONAL ENCODING EXPLAINED

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.

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.