Positional Encoding
Compare positional signals at different frequencies, then connect absolute encodings and RoPE to attention.
Jump to a section
Why this matters
Unmasked self-attention without positional signals is permutation-equivariant: rearranging input tokens rearranges the outputs in the same way. It does not supply an independent notion of token position. A causal mask also constrains ordering, so the statement assumes no fixed causal mask.
Positional methods make position available to the model. Sinusoidal and learned absolute encodings modify input representations, while rotary encoding changes query and key vectors so their dot products reflect relative position.
Build the mental model
Sinusoidal encoding gives each position a unique "fingerprint": a vector of sine and cosine values at many different frequencies. Low-frequency dimensions change slowly across positions (coarse location); high-frequency dimensions change fast (fine location). Because the fingerprint is built from sinusoids, the model can also represent relative offsets: the encoding of position pos + k is a fixed linear function of the encoding at pos.
Position becomes a rotation.
Turn three coordinate pairs at different frequencies and inspect how position changes their phase.
The visual loads as you reach this section.
You simply add the positional vector to the token embedding before the first attention layer, so every token carries both "what I am" and "where I am."
Work through the math
The original sinusoidal encoding, for position and dimension index in a model of width :
Each pair of dimensions is a sinusoid with wavelength , geometrically increasing from to just below . Two useful properties: it is defined for any position (although this does not guarantee good predictions beyond the training length), and is a linear transform of , letting attention learn to attend by relative distance.
RoPE takes a different route: instead of adding to embeddings, it rotates the query and key vectors by an angle proportional to their position. The resulting score depends on the query/key content and on the relative offset through the rotation. Its positional dependence is relative; the score is not a function of distance alone. Longer-context performance still requires evaluation and may need position scaling or further training.
Key takeaway: Unmasked attention is permutation-equivariant, so order has to come from somewhere else: added to the embeddings (sinusoidal, learned) or rotated into the Q/K dot product (RoPE). Being able to compute an encoding beyond the training length does not guarantee reliable extrapolation.
| Scheme | Type | Beyond training length | Examples |
|---|---|---|---|
| Sinusoidal | Absolute, fixed, parameter-free | Defined, but quality is not guaranteed | Original Transformer |
| Learned absolute | Absolute, trained table | Requires extending the table beyond its allocated length | BERT, GPT-2 |
| ALiBi | Relative, linear attention bias | Defined for longer distances; evaluate generalization | BLOOM, MPT |
| RoPE | Relative positional effect in Q/K rotations | Defined; extensions often change scaling or training | Llama, Mistral |
Read the implementation
1import torch
2from torch import Tensor
3
4
5def sinusoidal_encoding(seq_len: int, d_model: int) -> Tensor:
6 if d_model <= 0 or d_model % 2:
7 raise ValueError("This paired sine/cosine implementation needs positive even d_model")
8 pos = torch.arange(seq_len).unsqueeze(1) # (seq, 1)
9 i = torch.arange(0, d_model, 2) # even indices
10 div = torch.exp(i * (-torch.log(torch.tensor(10000.0)) / d_model))
11 pe = torch.zeros(seq_len, d_model)
12 pe[:, 0::2] = torch.sin(pos * div) # even dims -> sin
13 pe[:, 1::2] = torch.cos(pos * div) # odd dims -> cos
14 return pe
15
16
17pe = sinusoidal_encoding(seq_len=50, d_model=128)
18tokens = torch.randn(50, 128)
19position_aware = tokens + pe # add, don't concat
20assert pe.shape == (50, 128)Questions and trade-offs
- Conceptual: Why does a Transformer need positional encoding at all? (Unmasked self-attention is permutation-equivariant, without position information it can't distinguish token order.)
- Implementation: Do you add or concatenate positional encodings, and why add? (Add: it keeps dimensionality fixed and lets each dimension carry both content and position; concatenation is another design choice but changes the input width and projections.)
- Applied: Why is sinusoidal encoding able to handle sequences longer than those seen in training? (It's a fixed function defined for any position, so encodings are defined beyond the training length; model accuracy there is not guaranteed.)
- Systems-level: What problem does RoPE solve over absolute learned positions? (It makes the positional part of the attention score depend on relative offset without a finite learned position table. Long-context quality is a separate empirical question.)
- Failure modes: What's the limitation of learned absolute positional embeddings? (The table has a fixed allocated length; extending it requires additional handling. Even allocated positions that were not trained need evaluation.)
Check your understanding
From memory: write the sinusoidal PE formula, explain why you add rather than concatenate, and state one advantage of sinusoidal/RoPE over learned absolute positions. Check against Stage 3.
Sources and further reading
- Vaswani et al., Attention Is All You Need, §3.5: sinusoidal positions.
- Su et al., RoFormer: relative positional dependence through rotations.
Oliver Perrin
Machine Learning Engineer · Founder, LiminalML
LiminalML brings together concept explanations, mathematical examples, and working visuals. Find more writing by Oliver on the LiminalML Substack.
Keep exploring the idea.
Ask a follow-up in a guided session, work through the self-check, or open the visual in Studio to build on it.
Related concepts
Deep Learning
Transformer Architecture
Follow attention, feed-forward layers, normalization, and residual connections through a Transformer block.
Deep Learning
Attention Mechanisms
Turn compatibility scores into attention weights, then combine values. Explore the geometry, normalization, and limits of the mechanism.
LLMs
Embeddings
Compare vectors by direction and magnitude, and connect embedding geometry to retrieval and representation learning.