Positional Encoding — telling attention where things live.
Raw self-attention has no built-in notion of order. Without positional information, it cannot distinguish the dog bit the man from the man bit the dog. This lecture compares several ways to give transformers a sense of position, including the case for learning without an explicit encoding.
§0The deck at a glance
The deck first explains why order matters, then compares absolute, sinusoidal, relative, and RoPE encodings in terms of their strengths and limitations. It ends with NoPE, the finding that a causal decoder can sometimes infer position from its attention mask.
§1Why position matters
Before we pick an encoding, we have to be clear about what is broken. Self-attention takes a set of vectors and returns a set of vectors — every query looks at every key by dot-product similarity, and the similarity does not know or care where in the sequence either token came from. Language, unlike a bag of marbles, has order. Three slides set that up.
§2Absolute PE — the naive first try
The most straightforward answer: give every position a vector, look it up like you look up a word, add it to the token embedding. This is how BERT and GPT-2 do it, and it works — with two nagging problems the deck will make you feel.
What these two slides show
Slide 5 is the recipe: an absolute PE is a vector of the same dimension as the word
embedding — call it d_model — and each position pos = 0, 1, 2, …, L−1 gets one
such vector. During training these vectors are stored in a lookup table and learned by gradient descent,
exactly like the word embedding table. The position vector is added to the word vector before the first
attention layer.
Slide 6 is the honest post-mortem: three concrete failure modes.
Why the drawbacks hurt
- "Model just remembers the position vectors." Every position is an independent parameter. Position 42 and position 43 have no reason to be similar to each other — the model has to learn from data that adjacent positions should behave similarly, and it usually does, but nothing in the parameterisation forces it.
- No relative-position information. The attention score between token at position 5 and token at position 12 has no built-in notion of "they are 7 apart". The model has to reconstruct that distance from the difference of two absolute lookups, which is hard.
- Cannot extrapolate. If you trained with a maximum sequence length of 512, position 513 has no vector — the lookup table simply doesn't have that row. At test time you either have to truncate or reinitialise, and both hurt.
BERT was trained with max length 512 exactly because of this. That's not an accident of engineering — it is a direct consequence of using absolute embeddings.
§3Sinusoidal PE — the Vaswani recipe
The original transformer paper picked a different design: instead of learning the position table, compute it from a fixed formula built out of sines and cosines at exponentially spaced frequencies. Five slides justify why that fixed formula was chosen and where it still falls short.
What these two slides show
The honest scoreboard for sinusoidal. On the gains side: it gives you a word position at all (so, unlike a bag of words, the model is no longer permutation-blind), it performs about as well as learned absolute embeddings on standard benchmarks, and — the property Vaswani et al. were most excited about — it can in principle extrapolate. Position 513 has a defined vector even if you only trained up to 512.
Why "in principle" is doing a lot of work
The drawback slide corrects the optimism. In practice sinusoidal encodings do compute a well-defined vector for position 513 — but the attention layers above them were only ever trained on positions 0–511, so the downstream behaviour on unseen positions degrades quickly. This turns out to be a general theme, not a sinusoidal-specific bug — most positional schemes generalise poorly to sequence lengths much longer than they were trained on, and a lot of the work in §5 and §6 is about trying to close that gap.
The second drawback is more of a design comment: sinusoidal PE has no learnable parameters. Whether that is good or bad depends on your taste. It saves parameters and removes a source of overfitting, but it also means the model cannot adapt the encoding to the corpus.
§4Relative PE — encode the gap, not the position
Both absolute and sinusoidal encode where a token is. But attention scores really only care about how far apart two tokens are. Shaw et al. (2018) and later T5 (Raffel et al. 2020) pushed this idea to its natural conclusion: instead of adding a position vector to each token, inject a bias directly into the pairwise attention logit — and make that bias a function of the distance between the two tokens.
What these two slides show
T5's specific way of doing relative PE, in two parts. Slide 14 gives the shape: a single learned scalar per relative offset per attention head, added to the attention logit. The scalar table is shared across all transformer layers but separate per head.
Slide 15 gives the sizing trick. T5 does not learn one scalar per offset up to sequence length — it uses 32 buckets, and the buckets grow logarithmically. Offsets 1, 2, 3, 4 might each get their own bucket. Offsets 5–8 share a bucket. Offsets 9–16 share the next. And so on up to offset 128; everything past 128 shares one big "far away" bucket.
Why bucketise?
Two reasons. First, parameter efficiency: a 32-scalar table per head is cheap regardless of context length. Second — and this is the important one — fine-grained distance only matters when tokens are close. The model needs to distinguish "adjacent" from "2 apart" from "3 apart", because those are typical distances between a word and its head. But the difference between "500 apart" and "501 apart" is almost never linguistically meaningful; both are just "far".
The last bullet on slide 15 is subtle but important. Even though a single layer is blind to distances past 128, the next layer sees combinations of the previous layer's outputs — and by chaining local reads, a stack of layers can effectively build up a sensitivity to arbitrarily long-range structure. This is the same principle that lets a CNN with 3×3 kernels see the whole image after enough layers.
What these two slides show
The scoreboard for relative PE. On the plus side: varied sequence length is handled naturally — the encoding is a function of the offset, and offsets don't depend on absolute sequence length. Train on 512, test on 1024, and the model still knows what "3 apart" means.
On the minus side, three practical costs.
- Implementation complexity. A per-pair bias means an
O(L²)tensor of biases per layer. Efficient implementations need care — you don't want to materialise the fullL × Lmatrix if you don't have to. - Training/inference latency. The extra add is cheap but non-zero, and it lands on the critical path of every attention op.
- KV-cache invalidation. This is the biggest one and the reason relative PE fell out of
fashion for large autoregressive LMs. In a decoder-only LM you cache the keys and values of previous
tokens so you don't recompute them at each step. But with relative PE, when a new token arrives, the bias
b(i − j)for existing keys shifts — becauseijust changed. So you cannot simply reuse the cached keys and values as they are; you have to recompute the attention logits. This is a serious performance tax on generation.
RoPE (§5) was designed specifically to fix the caching problem while keeping the relative-position feel of T5. It succeeds so well that essentially every modern LLM — LLaMA, Qwen, Mistral, DeepSeek — uses it.
§5RoPE — rotate the query and key
Rotary Position Embedding (Su et al., 2021) is the answer that took over. The trick is elegant. Instead of adding a positional vector to the input, or a scalar bias to the logit, RoPE rotates the query and key vectors in the complex plane by an angle proportional to their position. When you then take the dot product q·k, the rotation angles combine into a difference — so the dot product ends up depending only on the relative position, while each vector still knows its own absolute position. Seven slides to work through the picture, the algebra, and the payoff.
What these two slides show
Slide 21 is the derivation in complex form and the 2D real form. Represent each 2D slice of the vector as a
complex number. Then rotating by angle m·θ is just multiplying by eimθ.
So the position-encoded query for token at position m is
and similarly for the key at position n. When you form the inner product, — the answer only depends on m − n. That is the whole point.
Slide 22 promotes the 2D picture to d dimensions. The rotation acts as a big block-diagonal
matrix , where each 2×2 block on the diagonal is a standard rotation by angle m·θᵢ. The
frequencies θᵢ are pre-defined the same way as in sinusoidal PE:
The rotation matrix looks huge but you never actually build it. In code, RoPE is applied by taking pairs
of adjacent dimensions (x2i, x2i+1) and computing
(x2icos φ − x2i+1sin φ, x2isin φ + x2i+1cos φ)
with φ = m·θᵢ. That's it — one pair of trig multiplies per pair of dimensions, no matrix ever
materialised.
What these two slides show
RoPE's scoreboard. Four gains, one drawback.
- Flexibility of sequence length. Nothing in the design assumes a maximum sequence length — you can encode position 100,000 as easily as position 5. The attention behaviour at position 100,000 is only as good as the training data, but the encoding itself never runs out of vectors.
- Decaying inter-token dependency. Because different dimension-pairs rotate at different
rates, the inner product of two rotated vectors naturally decays as the offset
|m − n|grows — high-frequency pairs oscillate quickly and average out, low-frequency pairs stay coherent. So RoPE gives you a built-in "closer tokens matter more" inductive bias, without you having to hand-code it. - Works with linear-attention variants. Because RoPE is applied to the queries and keys directly (not injected into the softmax bias), it composes cleanly with linear-attention and other efficient-attention recipes that don't touch the softmax at all.
- Interpretability. Rotations have a picture — you can literally see position as angle. This makes RoPE the easiest positional scheme to reason about qualitatively.
The single drawback is honest: implementation complexity. It is not free code. You need to interleave sin/cos multiplies at the right place in the attention forward pass, and getting the dimension pairing right (adjacent pairs, or the split-half convention some frameworks use) is a common source of bugs.
Practically every LLM you have heard of from 2023 onwards — LLaMA, Qwen, Mistral, DeepSeek, Gemma, Phi — uses RoPE. Later work (YaRN, NTK-aware scaling, position interpolation) extends RoPE to context lengths far beyond what it was trained on, but the core recipe is unchanged.
§6NoPE — maybe you didn't need any of this
The last section is a plot twist. Kazemnejad et al. (2023) asked a stubborn question: what happens if you remove the positional encoding entirely? The result — for decoder-only, causally masked models — is surprising. The model still learns to use word order, apparently because the causal mask itself carries enough asymmetry that gradient descent can reconstruct positional information without any explicit encoding. Five slides on this finding and its consequences for current frontier models.
What these two slides show
The NoPE claim and its justification, over two slides.
Slide 26 puts it as sharply as possible. There is no positional signal in the input at all
— not absolute, not sinusoidal, not relative, not RoPE. Yet the model still learns to use word order. The
reason: the causal mask in a decoder-only transformer is itself an asymmetric
operator. A token at position t can attend only to tokens at positions ≤ t, never
in the other direction. The set of tokens visible to token 0 is a strict subset of the set visible to token
1, which is a strict subset of the set visible to token 2, and so on. Any position-sensitive computation the
model wants to do — counting how many tokens are on the left, or measuring recency — can be assembled out of
that asymmetry.
Slide 27 spells out the mechanism. Since gradient descent will exploit any structural asymmetry that helps the loss, and since the causal mask is such an asymmetry, the model organically learns to route positional information through the attention pattern. The paper's striking empirical finding is that the resulting attention patterns end up looking a lot like T5's relative-position patterns — meaning the model has essentially reinvented relative PE from the mask alone.
Note the "causal mask" qualifier. NoPE does not work for encoder-only models (BERT-style) with bidirectional attention — there the attention operation is fully symmetric, and without a positional signal the model really is order-blind. NoPE is a phenomenon of decoder-only LMs. Which, conveniently, is what almost all modern frontier LLMs are.