Positional information: sinusoidal, learned, RoPE, ALiBi
Attention cannot see order — here is every way we give it one
Self-attention is permutation-equivariant: without extra information, "dog bites man" and "man bites dog" are the same input. How positions are injected decides whether a model can handle sequences longer than it saw in training — the question behind every "1M-token context" announcement. Rotary embeddings (RoPE) are used by essentially every open model you will fine-tune (8.2 Fine-tuning and PEFT) or serve (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization), and context extension methods build directly on the math here (7.12 Beyond vanilla attention: state space models, long context and hybrids).
You'll be able to
- Show that attention is permutation-equivariant and explain why positions must be injected
- Write the sinusoidal encoding and prove its relative-shift (rotation) property
- Derive how RoPE makes query–key scores depend only on relative position and implement it
- Compare learned, sinusoidal, relative-bias, RoPE and ALiBi schemes on extrapolation and explain context-extension tricks
Key ideas
- Self-attention is permutation-equivariant; order must be injected either into the inputs or into the attention scores.
- Sinusoidal encodings are a bank of rotating 2-D clocks; a fixed offset k is a fixed rotation R_k, so relative position is linearly recoverable.
- Learned absolute position tables cannot represent positions beyond the training length.
Show 4 more key ideas
- RoPE rotates each query/key pair by an angle proportional to its position; the dot product then depends only on the relative offset n − m.
- ALiBi adds a per-head linear distance penalty to the scores and extrapolates to longer sequences without any position embeddings.
- Context extension (position interpolation, NTK scaling, YaRN, larger RoPE base) rescales positions or frequencies so unseen lengths map into the trained range.
- RoPE touches only q and k, never v — values carry content, positions only shape who attends to whom.
Suggested path through this lesson
Attention is blind to order
Permute the rows of and self-attention permutes its output rows the same way — nothing else changes, because every score is computed independently of where and sit. Formally, for any permutation matrix , : the layer is permutation-equivariant. A transformer without positional information treats "dog bites man" and "man bites dog" identically. So order has to be injected, and the design space is: where (added to the input, or inside the attention scores) and how (absolute positions, or relative offsets).
Sinusoidal encodings (the original)
The 2017 paper adds to each token embedding a fixed vector with
Pair up dimensions : each pair is a point on the unit circle rotating with angular frequency . Low spins fast (wavelength ), high spins slowly (wavelength ) — a binary-counter-like clock in continuous form, visible as stripes in the positional-encoding demo below.
The relative-shift property. Why sinusoids rather than, say, a single counter? Because a fixed offset acts as a rotation that does not depend on :
which is just the angle-addition formulas and . So for a block-diagonal rotation determined by alone: a linear layer can learn "attend three tokens back" without knowing the absolute position. The dot product depends only on and decays with distance.
Learned absolute positions
BERT and GPT-2 instead learn a table (GPT-2: ) and add row to each token. Simple and as good as sinusoids in-distribution, but position 1025 has no row at all — the model cannot run past its training length. Both schemes also entangle "what" and "where" in the same vector, which attention then has to disentangle.
Relative positions inside attention
Shaw et al. (2018), Transformer-XL and T5 moved position out of the embeddings and into the attention scores: T5 adds a learned scalar bias to , with offsets bucketed logarithmically so that far-apart pairs share parameters. This encodes relative order directly, which is what language mostly cares about.
Rotary position embeddings (RoPE)
RoPE (Su et al., 2021) is the scheme used by Llama, Qwen, Gemma and most open models. The goal: make the attention score depend on the relative offset while keeping the ordinary dot product. Split and into 2-D pairs and rotate pair at position by the angle :
Rotations compose by adding angles, so and
The score is a function of content and of only — relative position, achieved by multiplying rather than adding, and applied to and only (values are untouched). Because high-frequency pairs rotate quickly, attention between distant tokens is naturally damped. In code the rotation is two element-wise products with precomputed and tables:
import torch
def rope(x, base=10000.0): # x: (..., n, d) with d even
n, d = x.shape[-2], x.shape[-1]
theta = base ** (-torch.arange(0, d, 2) / d) # (d/2,) frequencies
ang = torch.arange(n)[:, None] * theta[None, :] # (n, d/2) = position * theta
cos, sin = ang.cos(), ang.sin()
x1, x2 = x[..., 0::2], x[..., 1::2]
return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1).flatten(-2)
Apply rope to queries and keys before the dot product and the attention function from 7.2 Scaled dot-product and multi-head attention, fully derived needs no other change.
Math check. With , one pair, : a query at position 3 and a key at position 1 give ; a query at position 10 and a key at position 8 give the same . Same offset, same score — that is the whole point.
ALiBi: no embeddings at all
ALiBi (Press et al., 2021) adds a penalty proportional to distance directly to the scores, for , with a fixed slope per head (a geometric sequence, e.g. for 8 heads). Nearby tokens are favoured, each head at a different range, and nothing is tied to a maximum length — ALiBi models extrapolate to sequences several times longer than they were trained on, at some cost in long-range precision.
Extending context after training
Positions are also what breaks when you ask for a longer context. RoPE trained on 4k tokens produces unseen rotation angles at position 8k. Two fixes: position interpolation rescales positions by so they stay inside the trained range, followed by a short fine-tune; NTK-aware scaling and YaRN rescale the base frequency instead (raising the base, which Llama 3 pushes to ) so that low frequencies stretch while high frequencies keep their resolution. Long-context models then continue pretraining on long sequences. Vision Transformers face the same problem in 2-D and use learned patch positions or 2-D RoPE variants (5.7 Vision Transformers).
| scheme | where | absolute or relative | extrapolates? | used by |
|---|---|---|---|---|
| sinusoidal | added to input | absolute (relative recoverable) | poorly | original transformer |
| learned table | added to input | absolute | no (hard limit) | BERT, GPT-2/3 |
| T5 relative bias | added to scores | relative | moderately | T5 |
| RoPE | rotates q and k | relative (in the dot product) | with interpolation/YaRN | Llama, Qwen, Gemma, Mistral |
| ALiBi | linear bias on scores | relative | yes, by design | BLOOM, MPT |
Where this shows up later
- Llama-style decoders combine RoPE with RMSNorm, SwiGLU and GQA — 7.6 Decoder-only: GPT and autoregressive generation, 7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization.
- Context extension and the quadratic cost of long sequences — 7.12 Beyond vanilla attention: state space models, long context and hybrids; the limits of long context versus retrieval — 9.1 Why RAG, and the canonical pipeline.
- The same "inject position, then attend" recipe is used for image patches in ViT (5.7 Vision Transformers) and for audio frames in Whisper (8.10 Multimodal models).
Common pitfalls (4)
- Applying RoPE to the values as well as queries and keys — the relative-position property only needs q and k.
- Expecting a model with learned absolute positions to work on inputs longer than its position table.
- Confusing 'relative position' schemes with 'no position information' — ALiBi has no embeddings but encodes distance very explicitly.
- Assuming a larger RoPE base alone gives long-context ability; models still need (continued) training on long sequences.
Recap: all 7 key points
- Self-attention is permutation-equivariant; order must be injected either into the inputs or into the attention scores.
- Sinusoidal encodings are a bank of rotating 2-D clocks; a fixed offset k is a fixed rotation R_k, so relative position is linearly recoverable.
- Learned absolute position tables cannot represent positions beyond the training length.
- RoPE rotates each query/key pair by an angle proportional to its position; the dot product then depends only on the relative offset n − m.
- ALiBi adds a per-head linear distance penalty to the scores and extrapolates to longer sequences without any position embeddings.
- Context extension (position interpolation, NTK scaling, YaRN, larger RoPE base) rescales positions or frequencies so unseen lengths map into the trained range.
- RoPE touches only q and k, never v — values carry content, positions only shape who attends to whom.
Watch
The positional-encoding segment shows the sine/cosine clocks with concrete numbers.
Read
Try it live
Interactive demo
runs in your browserExercises
- Prove the shift property numerically
Implement the sinusoidal encoding for and . For , fit a single linear map from to by least squares over all positions. Expected: the fit is essentially exact (residual below ) and the learned matrix is block-diagonal with 2×2 rotations.
- RoPE invariance test
Using the
ropefunction, sample random and with . Compute the rotated dot product for positions , and . Expected: all three scores are identical to floating-point precision; differs. - Extrapolation experiment
Train the tiny GPT from 7.8 Build GPT from scratch (nanoGPT walkthrough) with block size 64 using (a) a learned position table and (b) RoPE, then evaluate loss on sequences of length 128. Expected: (a) cannot run at all without hacks; (b) runs but its loss degrades — then apply position interpolation (scale positions by 0.5) and observe partial recovery.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →