Home Knowledge Base Positional Encoding for Transformers

Positional Encoding for Transformers

Why Positional Encoding? Transformers have no inherent notion of sequence order. Positional encoding injects position information so the model knows where each token is in the sequence.

Encoding Methods

Sinusoidal Positional Encoding (Original Transformer) $$ PE_{(pos, 2i)} = \sin(pos / 10000^{2i/d}) $$ $$ PE_{(pos, 2i+1)} = \cos(pos / 10000^{2i/d}) $$

Learned Positional Embeddings

RoPE (Rotary Position Embedding) Used by: Llama, Mistral, Qwen, and most modern models

Key ideas:

# Simplified RoPE application
def apply_rope(x, freqs):
    # Split into pairs, rotate by position-dependent angle
    x_rotated = rotate_half(x) * freqs
    return x * torch.cos(freqs) + x_rotated * torch.sin(freqs)

ALiBi (Attention with Linear Biases) Used by: MPT, BLOOM

Comparison

MethodExtrapolationLearningModern Use
SinusoidalLimitedFixedLess common
LearnedNoneTrainableLegacy
RoPEGood (with scaling)FixedMost popular
ALiBiExcellentFixedSome models

Length Extrapolation RoPE can be extended with:

positional encodingropealibi

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.