Positional Encoding
Inject word order and sequence position into embeddings using harmonic sinusoidal functions and modern rotary embeddings (RoPE).
Transformers process all words in a sentence at once in parallel (unlike humans or older models that read one word after another). Without position signals, 'dog bites man' and 'man bites dog' would look completely identical to the model! Positional encoding gives each word a unique seat number so word order is preserved.
The original 2017 Transformer paper introduced these sinusoidal waves because they require zero training. Modern frontier LLMs (such as LLaMA 3 and Mistral) use RoPE (Rotary Position Embeddings), which encode relative distances by rotating vector spaces directly in attention.
Sinusoidal Positional Encoding Formula
Notice the smooth transition from rapid oscillations at low dimensions to slow, continuous harmonic curves at high dimensions.
Input Vector Sum (Embedding + Position)
- Parallel processing: Transformers ingest all tokens simultaneously and require explicit position markers.
- Geometric fingerprint: Sine and cosine waves across diverse frequencies generate a unique signature for each index.
- Distance awareness: Neighboring positions have high cosine similarity, allowing attention to gauge distance.
- Element-wise sum: The input to the first layer is simply word_embedding + position_encoding.
Drag the position slider and observe how the bar pattern shifts smoothly across dimensions.