Skip to content

Module 15

Anurag Prasad edited this page Nov 9, 2026 · 8 revisions

Module 15 — Positional Encoding and Modern Attention Variants

⬅️ 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


Overview and learning goals

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.

Beginner: the big picture

"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 $i-j$ between query and key. Relative schemes usually generalise better to different sequence lengths.

Sinusoidal positional encoding and its offset-dependent similarity

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"]
Loading

Figure 15.2 — Families of positional schemes covered in this module. Original diagram.

Core concepts and derivations

Why content-only attention lacks order

Module 14 showed $\mathrm{Attn}(PX)=P\mathrm{Attn}(X)$. Without position information the output set is the same for any ordering of the inputs.

Constant and one-hot positional representations

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").

Learned positional embeddings

A trainable table $P\in\mathbb{R}^{T_{max}\times d}$, input $\mathbf{x}_i+\mathbf{p}i$ (BERT, GPT-2). Simple and flexible, but undefined beyond $T{max}$ and each row is trained only on sequences that reach that position.

Sinusoidal encoding and frequency interpretation

$$ PE_{(pos,2i)}=\sin!\Bigl(\frac{pos}{10000^{2i/d}}\Bigr),\qquad PE_{(pos,2i+1)}=\cos!\Bigl(\frac{pos}{10000^{2i/d}}\Bigr). $$

Each pair $(2i,2i+1)$ is a point on a circle rotating with angular frequency $\omega_i=10000^{-2i/d}$ — a geometric progression of wavelengths from $2\pi$ to $2\pi\cdot10^4$, like digits of a clock. Relative shift property: with $\mathbf{u}_{pos}=(\sin\omega p,\cos\omega p)$,

$$ \begin{pmatrix}\sin\omega(p+k)\\cos\omega(p+k)\end{pmatrix}=\begin{pmatrix}\cos\omega k&\sin\omega k\-\sin\omega k&\cos\omega k\end{pmatrix}\begin{pmatrix}\sin\omega p\\cos\omega p\end{pmatrix}, $$

so $PE_{pos+k}$ is a fixed linear (rotation) function of $PE_{pos}$ — letting attention learn to attend by offset. Moreover $PE_p\cdot PE_q=\sum_i\cos\bigl(\omega_i(p-q)\bigr)$ depends only on $p-q$ (Figure 15.1, right).

Relative positions: Shaw et al. and Transformer-XL

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 $\mathbf{u},\mathbf{v}$, and caches previous segments for longer context.

T5 relative position bias

T5 adds a learned scalar $b_{h,,\mathrm{bucket}(i-j)}$ per head to the logits; distances are bucketed (exact for small, logarithmic for large), sharing parameters across positions and extrapolating coarsely to long distances.

DeBERTa disentangled attention

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.

Rotary position embedding (RoPE)

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 $\tilde{\mathbf{q}}_m=R_m\mathbf{q}$, $\tilde{\mathbf{k}}n=R_n\mathbf{k}$. Since $R_m^\top R_n=R{n-m}$:

$$ \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} $$

— the score depends only on the relative offset $n-m$ while the embeddings stay absolute-looking. In $d$ dimensions, split into $d/2$ pairs with frequencies $\theta_i=10000^{-2i/d}$ (block-diagonal rotation); the cost is element-wise, with no extra parameters. Distant tokens' scores decay with distance on average. RoPE is used in LLaMA-family and many other LLMs.

ALiBi

Press et al. (2022) add a fixed linear penalty to the logits: $e_{ij}=\mathbf{q}_i^\top\mathbf{k}_j/\sqrt d-m_h,(i-j)$ for $j\le i$, with head-specific slopes forming a geometric sequence (e.g. $2^{-8h/H}$). No positional embeddings are used; the bias encourages recency and enables training on short sequences with inference on longer ones.

Context length and position extrapolation

Models fail on lengths far beyond training because unseen rotation angles/embeddings are out of distribution. Remedies for RoPE: Position Interpolation rescales positions $m\to m,L/L'$ so extended positions fall inside the trained range, followed by brief fine-tuning (Chen et al. 2023); NTK-aware scaling enlarges the frequency base; YaRN interpolates by frequency band and adjusts attention temperature (Peng et al. 2023). Long-context ability also requires data, not just positional tricks ("lost in the middle", Liu et al. 2024).

Worked example

Sinusoidal ($d=4$, $pos=1$): $\omega_0=1$, $\omega_1=10000^{-0.5}=0.01$. $PE_1=(\sin1,\cos1,\sin0.01,\cos0.01)=(0.841,0.540,0.010,1.000)$.

RoPE, $d=2$, $\theta=\pi/2$, $\mathbf{q}=\mathbf{k}=(1,0)$. Position $m=1$: $R_1\mathbf{q}=(0,1)$; position $n=3$: $R_3\mathbf{k}=(\cos\frac{3\pi}2,\sin\frac{3\pi}2)=(0,-1)$; score $=-1$. Shifting both by 2 (positions 3 and 5): $R_3\mathbf{q}=(0,-1)$, $R_5\mathbf{k}=(\cos\frac{5\pi}2,\sin\frac{5\pi}2)=(0,1)$; score $=-1$ — identical, since the offset is still 2.

Implementation

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)

Advanced topics

  • 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.

Pitfalls and best practices

  • 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.

Conceptual questions and answers

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 $T_{max}$ but can fit the data better within it.

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 $Q$/$K$ with fixed frequencies and adds no parameters.

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.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally