Repository navigation
Module 15
⬅️ Module 14 · 🗺️ Curriculum · 🏠 Home · Module 16 ➡️
Level: Advanced · Prerequisites: Module 14, Module 01 (rotations) · Time: about 7–8 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Self-attention is blind to order (Module 14), so Transformers need explicit positional information. How positions are represented determines how well a model handles long contexts, generalises to unseen lengths and encodes relative distance. This module derives the main schemes — absolute (learned, sinusoidal), relative (Shaw, Transformer-XL, T5, DeBERTa) and rotary/linear-bias (RoPE, ALiBi) — and the methods used to extend context windows.
After this module you should be able to:
- explain why content-only attention loses order and why one-hot/constant positions fail;
- derive the sinusoidal encoding and its relative-shift property;
- derive RoPE and show its attention score depends only on relative position;
- describe ALiBi, T5 bias and DeBERTa's disentangled attention;
- explain position extrapolation/interpolation and context-length extension.
"Dog bites man" and "man bites dog" contain the same words; only order distinguishes them. We must tell the model each token's position. Two broad ideas: absolute — add a position vector to the token embedding; relative — make the attention score depend on distance

Figure 15.1 — Left: sinusoidal encodings (rows = positions, columns = dimensions; low dimensions oscillate fast, high dimensions slowly). Right: the dot product between positions depends only on their offset. Original figure (figures/make_figs_2.py).
flowchart TD
P["Positional information"] --> ABS["Absolute: add a vector to each token"]
P --> REL["Relative: score depends on i - j"]
ABS --> LRN["Learned table (BERT, GPT-2)"]
ABS --> SIN["Sinusoidal (original Transformer)"]
REL --> EMB["Relative embeddings (Shaw, Transformer-XL, DeBERTa)"]
REL --> BIAS["Logit bias (T5 buckets, ALiBi)"]
REL --> ROT["Rotation of Q and K (RoPE)"]
ROT --> EXT["Context extension: interpolation, NTK-aware, YaRN"]
Figure 15.2 — Families of positional schemes covered in this module. Original diagram.
Module 14 showed
A constant vector added to every token carries no information. One-hot positions ($\mathbf{e}{pos}\in\mathbb{R}^{T{max}}$) are unambiguous but have dimension tied to the maximum length, cannot generalise to unseen positions and treat all positions as unrelated (no notion of "near").
A trainable table
Each pair
so
Shaw et al. (2018) add learned relative embeddings $\mathbf{a}{ij}^K$ (clipped to a maximum distance) into the score: $e{ij}=\mathbf{q}_i^\top(\mathbf{k}j+\mathbf{a}^K{ij})/\sqrt{d}$. Transformer-XL (Dai et al. 2019) decomposes the score into content–content, content–position, global content bias and global position bias terms with sinusoidal relative encodings and learned vectors
T5 adds a learned scalar
DeBERTa (He et al. 2021) represents each token with separate content and position vectors, and computes the score as the sum of content-to-content, content-to-position and position-to-content terms (relative positions), plus an absolute-position decoder before the output layer.
Su et al. (2021): rotate query and key by an angle proportional to position. For a 2-D pair, $R_m=\begin{pmatrix}\cos m\theta&-\sin m\theta\\sin m\theta&\cos m\theta\end{pmatrix}$ and
— the score depends only on the relative offset
Press et al. (2022) add a fixed linear penalty to the logits:
Models fail on lengths far beyond training because unseen rotation angles/embeddings are out of distribution. Remedies for RoPE: Position Interpolation rescales positions
Sinusoidal (
RoPE,
import numpy as np
def sinusoidal(T, d):
pos = np.arange(T)[:, None]; i = np.arange(d // 2)[None]
ang = pos / 10000 ** (2 * i / d)
PE = np.zeros((T, d)); PE[:, 0::2] = np.sin(ang); PE[:, 1::2] = np.cos(ang); return PE
def rope(x, pos, base=10000.0): # x: (T, d), d even
T, d = x.shape; theta = base ** (-2 * np.arange(d // 2) / d)
ang = pos[:, None] * theta[None]; c, s = np.cos(ang), np.sin(ang)
x1, x2 = x[:, 0::2], x[:, 1::2]
out = np.empty_like(x); out[:, 0::2] = x1 * c - x2 * s; out[:, 1::2] = x1 * s + x2 * c; return out
rng = np.random.default_rng(0); q, k = rng.normal(size=(1, 8)), rng.normal(size=(1, 8))
s = lambda m, n: (rope(q, np.array([m])) @ rope(k, np.array([n])).T).item()
assert np.isclose(s(3, 1), s(10, 8)) # same offset -> same score# ALiBi bias for H heads, length T (before softmax): scores += bias
import torch
def alibi_bias(H, T):
slopes = torch.tensor([2 ** (-8 * (h + 1) / H) for h in range(H)])
dist = (torch.arange(T)[:, None] - torch.arange(T)[None]).clamp(min=0) # i - j for j<=i
return -slopes[:, None, None] * dist # (H, T, T)- NoPE / implicit positions: causal decoders can infer position from the mask; some work shows length generalisation without explicit encodings (Kazemnejad et al. 2023).
- 2-D/3-D RoPE for images and video; learned relative bias in Swin/ViT.
- Frequency analysis: high-frequency dimensions encode local order, low-frequency ones coarse position; interpolation compresses high frequencies harmfully, motivating NTK/YaRN band-wise rules.
- Length extrapolation vs. long-context utilisation: perplexity at long lengths does not guarantee that retrieval or reasoning over those lengths works.
- Sliding-window and attention-sink designs (StreamingLLM) maintain stability over unbounded streams.
- Applying RoPE to values or to the wrong head dimension (it is applied to
$Q$ and$K$ only). - Mismatched RoPE base/scale between training and inference checkpoints.
- Adding absolute sinusoids and RoPE together.
- Assuming a model trained at length
$L$ works at$4L$ without extension or evaluation. - Evaluating extrapolation only by perplexity.
Q1. Why add positional information at all?
Self-attention is permutation-equivariant; without positions the model cannot distinguish orderings of the same tokens.
Q2. What is the main advantage of sinusoidal over learned embeddings?
It is defined for any position (potentially extrapolating) and has a built-in relative-shift structure, with no parameters. Learned embeddings are limited to
Q3. Show that the RoPE score depends only on relative position.
$\tilde{\mathbf{q}}m^\top\tilde{\mathbf{k}}n=\mathbf{q}^\top R_m^\top R_n\mathbf{k}=\mathbf{q}^\top R{n-m}\mathbf{k}$ because rotations compose: $R_m^\top R_n=R{n-m}$.
Q4. How does ALiBi allow inference on longer sequences than training?
The linear distance penalty is defined for any distance and is not learned, so no unseen embeddings arise; it also biases toward nearby tokens.
Q5. Why do high-frequency RoPE dimensions complicate position interpolation?
Uniformly compressing positions reduces the resolution of high-frequency components that distinguish adjacent tokens; NTK-aware/YaRN rules scale frequencies selectively.
Q6. How does T5's relative bias differ from RoPE?
T5 adds a learned scalar per (head, distance bucket) to logits; RoPE rotates
Q7. Why are absolute one-hot positions a poor choice?
Dimension grows with maximum length, nearby positions are no more similar than distant ones, and unseen positions have no representation.
Q8. Does a longer context window mean the model uses all of it well?
No; models often under-use information in the middle of long inputs, so evaluate long-context retrieval and reasoning explicitly.
- Vaswani, A., et al. (2017). Attention is all you need. arXiv:1706.03762.
- Shaw, P., Uszkoreit, J., & Vaswani, A. (2018). Self-attention with relative position representations. NAACL. arXiv:1803.02155.
- Dai, Z., et al. (2019). Transformer-XL: attentive language models beyond a fixed-length context. ACL. arXiv:1901.02860.
- Raffel, C., et al. (2020). T5. JMLR, 21.
- He, P., Liu, X., Gao, J., & Chen, W. (2021). DeBERTa: decoding-enhanced BERT with disentangled attention. ICLR. arXiv:2006.03654.
- Su, J., et al. (2021). RoFormer: enhanced Transformer with rotary position embedding. arXiv:2104.09864.
- Press, O., Smith, N. A., & Lewis, M. (2022). Train short, test long: attention with linear biases enables input length extrapolation. ICLR. arXiv:2108.12409.
- Chen, S., et al. (2023). Extending context window of large language models via positional interpolation. arXiv:2306.15595.
- Peng, B., et al. (2023). YaRN: efficient context window extension of large language models. arXiv:2309.00071.
- Kazemnejad, A., et al. (2023). The impact of positional encoding on length generalization in Transformers. NeurIPS. arXiv:2305.19466.
- Liu, N. F., et al. (2024). Lost in the middle: how language models use long contexts. TACL.
⬅️ Module 14 · 🗺️ Curriculum · 🏠 Home · Module 16 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24