Positional Encodings
Sinusoids, rotary embeddings and length generalization.
Shuffle the words of a sentence and plain self-attention cannot tell. Every transformer therefore injects position somewhere: added to the input, rotated into queries and keys, or subtracted from the scores. The choice decides, among other things, whether a model trained on 4,000 tokens can read 32,000.
What you’ll learn
- Explain why self-attention needs positional information, and classify encodings as absolute or relative, fixed or learned.
- Derive the rotation structure of sinusoidal encodings and the relative-position property of rotary embeddings (RoPE).
- Prove that ALiBi's linear biases confine each head to a soft window of width about , and relate this to length extrapolation.
- Explain why RoPE fails to extrapolate, and why position interpolation and frequency-aware rescaling extend context windows.
Why position must be added
Self-attention is permutation-equivariant (Attention & Transformers): permute the input rows and the outputs permute the same way. A causal mask breaks the symmetry in part, since position sees exactly tokens, and decoders trained with no positional encoding at all ("NoPE") still learn positional information (Haviv et al., 2022). Every major architecture nevertheless adds position explicitly, in one of these ways:
| Scheme | Where position enters | Type | Examples |
|---|---|---|---|
| Sinusoidal | added to the input embeddings | absolute, fixed | the original transformer (2017) |
| Learned absolute | added to the input, one vector per position up to | absolute, learned; undefined beyond | BERT, GPT-2 |
| Relative embeddings and biases | a learned term per clipped or bucketed offset , in the keys or the scores | relative, learned | Shaw et al. (2018); Transformer-XL (2019); T5 (2020) |
| Rotary (RoPE) | queries and keys rotated by position-dependent angles | relative in the score, fixed | RoFormer (Su et al., 2021); widely used in open LLMs by the mid-2020s |
| ALiBi | a fixed penalty on the scores | relative, fixed | Press, Smith & Lewis (2022) |
Think first How can a causal decoder with no positional encoding tell positions apart?
Through the mask. A head with constant scores gives position the average of the first values. If the sequence starts with a fixed beginning-of-sequence token, that token's share of the average is , a position signal later layers can read; Kazemnejad et al. (2023) prove a construction of this kind. In the attention widget, the uniform head under the causal mask gives "it", the 8th word, exactly on each visible word.
Sinusoids are rotations
Vaswani et al. encode position in dimensions with sinusoids of geometrically spaced frequencies:
Group the coordinates into pairs . The angle-addition formulas shift a pair by positions with a rotation that does not depend on :
is block-diagonal and orthogonal, so "the token places back" is a fixed linear function of the current position's code, which a query projection can learn, as Vaswani et al. intended. Inner products of codes depend only on the offset:
Several frequencies are needed because each one alone is periodic: a single hand cannot tell offset from . Slow hands break the ties of fast ones, making the code nearly unique over the range of the slowest.
Rotary position embedding
Each is orthogonal, and rotations of the same pair commute and add their angles, so :
In complex form a rotation multiplies by , and the real inner product of two pairs is :
Position enters the score multiplicatively, with no content–position cross terms, and norms are preserved. Su et al. derived the form as the solution of in two dimensions. Writing with , Abel summation bounds the score by partial sums whose average size shrinks as grows: a mild bias toward nearby tokens.
Why RoPE fails to extrapolate, and how windows are extended. Pair completes a turn every tokens. Fast pairs cycle many times within the training length , so every angle they will ever produce has been seen. Slow pairs never complete a turn, so beyond they produce angles the model has never seen. Position interpolation (Chen et al., 2023) rescales positions, , mapping a window of tokens back into the trained range of angles; a short fine-tuning, about a thousand steps, then adapts the model. Interpolation is safe because the score is a smooth function of the offset:
With base and head dimension , the slowest RoPE pair () has wavelength tokens. What fraction of a full turn does it complete across a 4,096-token training context, in percent?
Show the answer
7.5 %
: the slowest pairs sweep only about during training. At 32,000 tokens they would reach about , angles never seen in training, which is why naive extrapolation fails, while interpolation keeps every angle inside the trained range.
ALiBi, locality and length generalization
ALiBi (Press, Smith & Lewis, 2022) adds no embedding at all. Each head subtracts a penalty proportional to distance from its causal scores:
Write and for the content score, so the weight at distance is proportional to . Bound the numerator above, and the denominator below by its term:
Sum the geometric tail:
Set the bound to and solve; for small slopes. Far tokens carry negligible weight however long the input, so at test time no head meets unfamiliar amounts of attention at unfamiliar distances, hence stable perplexity. The same fact is the limitation: no head reads directly beyond its window, so distant information must hop through layers.
Stable perplexity is not the same as using a long context: a model can extrapolate in perplexity by ignoring distant tokens. Tasks that need far-away information tell a different story. In multi-document question answering, accuracy drops when the relevant passage sits in the middle of a long context (Liu et al., 2024). On synthetic reasoning tasks, NoPE decoders generalized to longer inputs better than most explicit encodings (Kazemnejad et al., 2023), and training with positions sampled at random from a larger range helps algorithmic tasks extrapolate (Ruoss et al., 2023).
Key takeaways
- Self-attention needs position injected: added to the input (sinusoidal, learned), rotated into queries and keys (RoPE), or added to the scores (relative biases, ALiBi).
- Sinusoidal codes satisfy with block rotations, so offsets are linear maps and code inner products depend only on .
- RoPE gives : relative position entering multiplicatively. Slow pairs meet unseen angles beyond the training length, which interpolation and frequency-aware rescaling avoid.
- ALiBi's penalty confines each head to a soft window of width about : stable perplexity on long inputs but no direct long-range reads. Extrapolating in perplexity is not the same as using a long context.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With RoPE, how does the score between a query at position and a key at position depend on the positions?
- Through
- Only through , because
- Through and separately, as with learned absolute embeddings
- Not at all, because rotations preserve norms
Show the answer
B. Only through , because
Rotations of the same pair compose by adding angles, and , so .
Why can a linear query projection implement "attend to the token positions back" on top of sinusoidal encodings?
- Because for a fixed rotation that does not depend on
- Because sinusoids of different frequencies are orthogonal functions
- Because the encodings are learned during training
- Because the dot product of two different position codes is always zero
Show the answer
A. Because for a fixed rotation that does not depend on
A query with containing points at , and its dot product with key is , maximal at . The widget's previous-token head is exactly this construction with .
A RoPE model trained on 4,096 tokens must read 16,384. Why does position interpolation work better than running it unchanged?
- It removes the slowest frequencies
- It makes the model attend only within 4,096-token windows
- It keeps every rotation angle within the range seen in training, where the score is a smooth, well-trained function of the offset
- It adds attention heads for the new positions
Show the answer
C. It keeps every rotation angle within the range seen in training, where the score is a smooth, well-trained function of the offset
Positions are scaled by . Fast pairs already cycled during training; slow pairs would otherwise produce unseen angles. Within the trained range, limits how far fractional offsets can stray.
What does an ALiBi head with slope and bounded content scores effectively do?
- Attend only to the first token
- Attend uniformly over the whole context
- Ignore content and attend by distance alone
- Attend within a soft window of order tokens, up to logarithmic factors, with geometrically decaying weight beyond it
Show the answer
D. Attend within a soft window of order tokens, up to logarithmic factors, with geometrically decaying weight beyond it
The penalty multiplies far weights by , so mass beyond distance is at most . Content still decides which keys win inside the window.
Further reading
- J. Su et al., "RoFormer: Enhanced transformer with rotary position embedding," arXiv:2104.09864 (2021); Neurocomputing (2024).
- O. Press, N. A. Smith & M. Lewis, "Train short, test long: Attention with linear biases enables input length extrapolation," ICLR (2022).
- S. Chen, S. Wong, L. Chen & Y. Tian, "Extending context window of large language models via positional interpolation," arXiv:2306.15595 (2023).
- A. Kazemnejad, I. Padhi, K. Natesan Ramamurthy, P. Das & S. Reddy, "The impact of positional encoding on length generalization in transformers," NeurIPS (2023).
- P. Dufter, M. Schmitt & H. Schütze, "Position information in transformers: An overview," Computational Linguistics 48 (2022).