Positional encodings (sinusoidal)
Transformers process all tokens in parallel, losing the sequential order information that RNNs naturally preserve. Positional encoding injects position information into token embeddings so the model knows "which word came first."

Even dimensions use sine, odd dimensions use cosine. These are added (not concatenated) to the token embeddings.
Derivation: Why This Formula?
Step 1: Need something that changes with position We want to be unique for each position. A simple counter would work but scales unboundedly—position 1000 would dominate the embedding values.
Step 2: Bounded functions—sine and cosine Trig functions oscillate in , keeping values bounded. For a single frequency :
Why this step? Sine gives us periodicity. Different positions get different values, but the function repeats. One frequency isn't enough because it repeats (period ), making distant positions look similar.
Step 3: Multiple frequencies for different dimensions Use a different frequency for each embedding dimension. Dimension gets frequency:
Why decreasing frequencies?
- Low dimensions ( small): high frequency changes rapidly with position captures fine-grained local order
- High dimensions ( large): low frequency changes slowly captures coarse global position
The factor sets the wavelength range. The longest wavelength is positions.
Step 4: Alternating sine and cosine Even dimensions use sine, odd use cosine of the same frequency:
Why both? The pair forms a 2D representation of position on a circle of frequency . This allows the model to learn linear transformations to compute relative positions using trig identities:
A linear layer can learn weights and to shift any position by steps.
Relative Position: For any fixed offset , is a linear function of :
where is a linear transformation. This makes relative distances learnable.
Bounded Values: All components stay in .
Extrapolation: Works for positions longer than training sequences (unlike learned positional embeddings capped at max length).
Worked Example 1: Computing PE for a 4-Dimensional Model
Let , compute .
Dimensions: (since and cover indices 0,1,2,3).
Dimension 0 (i=0, even → sine):
Dimension 1 (i=0, odd → cosine):
Dimension 2 (i=1, even → sine):
Dimension 3 (i=1, odd → cosine):
Why these steps? Lower dimensions (0,1) oscillate rapidly (high ), capturing exact position. Higher dimensions (2,3) oscillate slowly (low ), capturing coarse position within sequence.
Final:
Worked Example 2: Demonstrating Relative Position Linearity
Show that relates linearly to for dimension pair .
For dimension , let . We have:
For position :
Using angle addition:
Why this step? The trig identity converts the new position into a weighted sum of the old position's encoding. The weights and depend only on the offset (1 step), not the absolute position.
Similarly for the cosine dimension:
In matrix form:
This is a rotation matrix! A +1 offset rotates the 2D representation by angle . The model can learn this transformation to attend to relative positions.
Worked Example 3: Why 10000 as the Base?
The wavelength of dimension is:
For :
- Dimension 0 (): (high frequency)
- Dimension 255 (): (low frequency)
(Note: is slightly less than , so the maximal wavelength is just under .)
Why this range?
- Short wavelengths () distinguish adjacent positions (every position looks different)
- Long wavelengths () encode global position in long documents (sequences up to ~10k tokens)
The geometric progression ensures smooth coverage across scales—each dimension handles a specific "zoom level" of position.
Why this step? Too small a base (e.g., 100) → longest wavelength only ~628 positions → fails on long sequences. Too large → spectrum stretches too much, wasting resolution. The value balances fine local resolution with long-range coverage.
Step 1: Embed tokens into vectors (from embedding table):
- "The" →
- "cat" →
- "sat" →
Step 2: Compute positional encodings for positions 0,1,2 (using ):
For :
For :
For :
Step 3: Add positional encodings to embeddings:
- "The" + =
- "cat" + =
- "sat" + =
These position-aware embeddings feed into the first transformer layer.
Why this step? Addition (not concatenation) preserves dimensionality and lets the model blend semantic content (embeddings) with positional information (encodings).
Why it feels right: Since we compute PE per position, it seems like it's encoding the token itself.
The fix: Positional encoding ONLY encodes where the token is, not what it is. The token embedding encodes meaning ("cat" vs "dog"). They're added together:
Without the embedding, the model has no idea what words mean. Without PE, it has no idea what order they're in.
Why it feels right: Concatenation keeps information distinct: has both components intact.
The fix: Concatenation doubles dimensionality ( → ), increasing compute cost. Addition works because:
- Embeddings and PE live in the same space
- Self-attention learns to disentangle them via learned projections
- PE values are small (bounded in [-1,1]) compared to embeddings (initialized with larger variance), so they "nudge" rather than overwhelm
Empirically, addition works as well as concatenation with half the parameters.
Why it feels right: The index runs from 0 to , same as positions 0 to .
The fix: Each dimension encodes a frequency component present at ALL positions. Dimension 0 oscillates quickly at every position (high frequency). Dimension 511 oscillates slowly at every position (low frequency). Think of it like a Fourier transform: low frequencies capture the big picture, high frequencies capture details. Every position uses all dimensions.
Recall Explain to a 12-Year-Old
Imagine you're reading a comic book, but someone cut out all the panels and shuffled them. You'd see Batman punching a villain, then the villain planning the crime, then Batman arriving—totally out of order! You need the panel numbers (1, 2, 3..) to put the story back together.
A Transformer is like a super-smart reader that looks at all panels once. But if we just give it the panels without numbers, it can't tell the story correctly. So we write a secret code on each panel that says "this is panel 3" without actually writing "3".
The code is a pattern of waves—like a fingerprint made of wiggly lines. Panel 1 gets one fingerprint, panel 2 gets another, and so on. Some parts of the fingerprint wiggle fast (to tell nearby panels apart), and some wiggle slow (to tell if you're near the start or end of the comic). We add this fingerprint to each panel, so the Transformer knows the order while still seeing all the pictures at once.
- Fixed (not learned)
- Addition to embeddings
- Sine on even, cosine on odd
- Ten-thousand base (10000)
Visual: Imagine a spiral notebook where each coil (dimension) has a different tightness—tight coils for fine position, loose coils for coarse position.
Connections
- Token Embeddings: PE is added to these to create position-aware inputs
- Self-Attention Mechanism: PE enables attention to distinguish "attend to previous word" from "attend to next word"
- Multi-Head Attention: Different heads can learn to focus on different relative position offsets
- Learned Positional Embeddings: Alternative to sinusoidal; learned lookup table (limited to training sequence length)
- Relative Positional Encodings: Modern alternative (T5, Transformer-XL) that directly encodes relative distances in attention
- Fourier Transform: Sinusoidal PE decomposes position into frequency components, analogous to frequency analysis
- Rotary Position Embeddings (RoPE): Modern variant that applies rotation in attention space rather than adding to embeddings
#flashcards/ai-ml
Why can't Transformers use sequence order without positional encoding?
What is the formula for sinusoidal positional encoding at position , dimension ?
Why do we use multiple frequencies across embedding dimensions?
How does sinusoidal PE enable the model to learn relative positions?
Why pair sine and cosine at the same frequency?
Why 10000 as the base constant?
Why add PE to embeddings instead of concatenating?
What's the longest sequence sinusoidal PE can handle?
Sinusoidal PE vs learned positional embeddings—key difference?
If you remove positional encoding, what behavior emerges?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, transformer ka ek interesting problem hai — ye saare tokens ko ek saath, parallel mein process karta hai. RNN jaisa nahi jo ek-ek karke words padhta hai aur order automatically yaad rakhta hai. Toh transformer ke liye "The cat sat" aur "sat cat the" ek jaise dikhte hain, kyunki self-attention permutation invariant hai — matlab tokens ko shuffle kar do, attention scores same rahenge. Lekin real life mein word order matter karta hai na? "Dog bites man" aur "man bites dog" bilkul alag baat hai! Isiliye humein position ki information alag se model mein daalni padti hai, aur yahi kaam karta hai positional encoding.
Ab sawaal ye hai ki position kaise encode karein? Simple counter [1,2,3,...] use kar sakte the, par problem ye hai ki bade positions ki values bahut badi ho jayengi aur embedding ko dominate kar dengi. Isliye smart trick use hoti hai — sine aur cosine functions, jo hamesha -1 se +1 ke beech rehte hain, bounded. Aur ek hi frequency kaafi nahi, kyunki wo repeat ho jaati hai. Isliye har embedding dimension ke liye alag frequency rakhte hain — chhoti dimensions high frequency (fine-grained local order capture karti hain), badi dimensions low frequency (coarse global position). Even dimensions mein sine, odd mein cosine — is sin-cos jodi se position ek circle par 2D point ban jaata hai.
Ye kyun important hai? Sabse badi baat — ye setup model ko relative position samajhne deta hai. Trig identity ki wajah se, PE(pos+k) hamesha PE(pos) ka ek linear transformation hota hai. Matlab model asaani se seekh leta hai ki "position 3 se 5" aur "position 103 se 105" ka distance same feel hota hai. Aur ek aur bonus — kyunki ye formula-based hai, learned nahi, ye training se lambi sequences par bhi kaam karta hai (extrapolation). Toh yaad rakho, positional encoding hi wo cheez hai jo transformer ko word order ka sense deti hai — iske bina model bas ek "bag of words" jaisa behave karega, sentence ka matlab kho dega.