Positional Encoding

Volume II, Chapter 8 — Part II (Chapter 12). Sinusoidal positional encodings from relative-shift desiderata, learned embeddings, RoPE, ALiBi, and length extrapolation theory for Transformers.

Intermediate

Table of Contents

  1. Learning Objectives
  2. Prerequisites
  3. Notation
  4. Core Intuition
  5. Permutation Equivariance of Attention
  6. Desiderata for Positional Encodings
  7. Sinusoidal Encoding: Derivation
  8. Properties and Proofs
  9. Absolute Position Injection
  10. Learned Position Embeddings
  11. Rotary Position Embeddings (RoPE)
  12. ALiBi: Attention with Linear Biases
  13. Comparison and Extrapolation
  14. Worked Examples
  15. Connection to the Broader Curriculum
  16. Common Pitfalls and Misconceptions
  17. Research Perspective
  18. Summary of Takeaways
  19. Exercises

Learning Objectives

After reading this chapter, you should be able to:

  1. Prove that Self-Attention is permutation-equivariant and explain why position information must be injected.
  2. State desiderata for positional encodings (uniqueness, bounded norm, relative expressibility, extrapolation).
  3. Derive sinusoidal encodings from the relative-shift property using rotation matrices.
  4. Prove that PE(t)TPE(t)\text{PE}(t)^T \text{PE}(t') depends only on ttt - t'.
  5. Contrast absolute (sinusoidal, learned) vs. relative (RoPE, ALiBi) position methods.
  6. Explain why RoPE dominates modern LLMs and how it connects to RoPE in LLMs.

Prerequisites


Notation

  • nn — Sequence length
  • dd — Model (embedding) dimension
  • PE(pos,2i)\text{PE}(\text{pos}, 2i) — Sinusoidal encoding at position pos\text{pos}
  • ERn×d\mathbf{E} \in \mathbb{R}^{n \times d} — Positional encoding matrix
  • X+E\mathbf{X} + \mathbf{E} — Position-augmented embeddings

Core Intuition

Self-Attention computes outputs as similarity-weighted sums of values. Dot products qiTkj\mathbf{q}_i^T \mathbf{k}_j are invariant to permutations of token order — the model treats input as an unordered set. Language, code, and time series require order: "dog bites man" \neq "man bites dog".

Positional encodings break permutation symmetry by making each token's representation depend on its index tt. Methods range from adding position vectors to embeddings (sinusoidal, learned) to encoding position in attention itself (RoPE, ALiBi).

Modern LLMs overwhelmingly use RoPE (RoPE), which embeds relative position directly in query–key products — compatible with KV Cache and length extrapolation.

Series context. Chapter 8, Part II (Chapter 12 in full curriculum) in Volume II.

Positional Encoding

PositionEncoding dimPosition 5 fingerprint:
Position
5
sin (even dims)cos (odd dims)Selected pos
Explore: Each dimension oscillates at a different frequency. Every position gets a unique sin/cos fingerprint added to token embeddings.

Permutation Equivariance of Attention

Theorem 1 (Permutation Equivariance). Let Pπ\mathbf{P}_\pi be the permutation matrix for permutation π\pi. Then:

Attention(PπQ,PπK,PπV)=PπAttention(Q,K,V).(1)\text{Attention}(\mathbf{P}_\pi \mathbf{Q}, \mathbf{P}_\pi \mathbf{K}, \mathbf{P}_\pi \mathbf{V}) = \mathbf{P}_\pi \cdot \text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}). \tag{1}

Proof. (PπQ)(PπK)T=PπQKTPπT(\mathbf{P}_\pi \mathbf{Q})(\mathbf{P}_\pi \mathbf{K})^T = \mathbf{P}_\pi \mathbf{Q}\mathbf{K}^T \mathbf{P}_\pi^T. Softmax is row-wise; permuting rows and columns consistently preserves structure. A(PπV)=Pπ(AV)\mathbf{A}(\mathbf{P}_\pi \mathbf{V}) = \mathbf{P}_\pi(\mathbf{A}\mathbf{V}). \blacksquare

Corollary 1. Without position information, shuffling input tokens shuffles outputs identically — the model cannot use order.


Desiderata for Positional Encodings

Definition 1 (Positional Encoding). A function PE:Z0Rd\text{PE}: \mathbb{Z}_{\geq 0} \to \mathbb{R}^d maps position tt to a dd-dimensional vector.

Desiderata:

  • D1 (Uniqueness): tt    PE(t)PE(t)t \neq t' \implies \text{PE}(t) \neq \text{PE}(t')
  • D2 (Bounded norm): PE(t)\|\text{PE}(t)\| bounded as tt \to \infty
  • D3 (Relative shift): \exists linear map Mk\mathbf{M}_k with MkPE(t)=PE(t+k)\mathbf{M}_k \text{PE}(t) = \text{PE}(t+k) for all tt
  • D4 (Smoothness): PE(t)\text{PE}(t) varies smoothly in tt
  • D5 (Extrapolation): Defined for t>Tmaxt > T_{\max} (training max length)

Sinusoidal Encoding: Derivation

Seek PE(t)2i=sin(ωit)\text{PE}(t)_{2i} = \sin(\omega_i t), PE(t)2i+1=cos(ωit)\text{PE}(t)_{2i+1} = \cos(\omega_i t) satisfying D3.

Lemma 1 (Angle Addition).

[sin(ω(t+k))cos(ω(t+k))]=[cos(ωk)sin(ωk)sin(ωk)cos(ωk)][sin(ωt)cos(ωt)].(2)\begin{bmatrix} \sin(\omega(t+k)) \\ \cos(\omega(t+k)) \end{bmatrix} = \begin{bmatrix} \cos(\omega k) & \sin(\omega k) \\ -\sin(\omega k) & \cos(\omega k) \end{bmatrix} \begin{bmatrix} \sin(\omega t) \\ \cos(\omega t) \end{bmatrix}. \tag{2}

The matrix is a rotation R(ωk)\mathbf{R}(\omega k) depending only on offset kk.

Definition 2 (Sinusoidal PE, Vaswani et al.).

PE(t,2i)=sin(t100002i/d),PE(t,2i+1)=cos(t100002i/d).(3)\text{PE}(t, 2i) = \sin\left(\frac{t}{10000^{2i/d}}\right), \quad \text{PE}(t, 2i+1) = \cos\left(\frac{t}{10000^{2i/d}}\right). \tag{3}

Frequencies ωi=100002i/d\omega_i = 10000^{-2i/d}: low ii → high frequency (fine position); high ii → low frequency (coarse position).


Properties and Proofs

Proposition 1 (Constant Norm). PE(t)22=d/2\|\text{PE}(t)\|_2^2 = d/2 for all tt.

Proof. i(sin2+cos2)=d/2\sum_i (\sin^2 + \cos^2) = d/2. \blacksquare

Theorem 2 (Relative Position in Dot Product).

PE(t)TPE(t)=i=0d/21cos(tt100002i/d).(4)\text{PE}(t)^T \text{PE}(t') = \sum_{i=0}^{d/2-1} \cos\left(\frac{t - t'}{10000^{2i/d}}\right). \tag{4}

Proof. sin(ωt)sin(ωt)+cos(ωt)cos(ωt)=cos(ω(tt))\sin(\omega t)\sin(\omega t') + \cos(\omega t)\cos(\omega t') = \cos(\omega(t-t')). \blacksquare

Attention dot products xtTxt+PE(t)TPE(t)\mathbf{x}_t^T \mathbf{x}_{t'} + \text{PE}(t)^T \text{PE}(t') encode relative distance (tt)(t - t').


Absolute Position Injection

Definition 3 (Absolute PE). Input to the Transformer:

x~t=xt+PE(t).(5)\tilde{\mathbf{x}}_t = \mathbf{x}_t + \text{PE}(t). \tag{5}

Position is added before the first attention layer. Subsequent layers propagate position implicitly through representations.


Learned Position Embeddings

Definition 4 (Learned PE). Learn matrix EposRTmax×d\mathbf{E}_{\text{pos}} \in \mathbb{R}^{T_{\max} \times d}; row tt is position tt.

  • Parameters — 0 — TmaxdT_{\max} \cdot d
  • Extrapolation — Partial — Fails beyond TmaxT_{\max}
  • Relative structure — Via dot product — Not guaranteed

Used in BERT, GPT-2. Works well within training length; fails catastrophically beyond.


Rotary Position Embeddings (RoPE)

Definition 5 (RoPE). Apply position-dependent rotation to Q and K:

q~t=Rtqt,k~t=Rtkt,(6)\tilde{\mathbf{q}}_t = \mathbf{R}_t \mathbf{q}_t, \quad \tilde{\mathbf{k}}_{t'} = \mathbf{R}_{t'} \mathbf{k}_{t'}, \tag{6}

where Rt\mathbf{R}_t is block-diagonal with 2×22 \times 2 rotations at frequencies ωi\omega_i.

Theorem 3 (Relative Position in RoPE).

q~tTk~t=qtTRttkt.(7)\tilde{\mathbf{q}}_t^T \tilde{\mathbf{k}}_{t'} = \mathbf{q}_t^T \mathbf{R}_{t'-t} \mathbf{k}_{t'}. \tag{7}

Proof. RtTRt=Rtt\mathbf{R}_t^T \mathbf{R}_{t'} = \mathbf{R}_{t'-t} (rotation composition). \blacksquare

Full treatment in RoPE. Used in LLaMA, Mistral, Gemma.


ALiBi: Attention with Linear Biases

Definition 6 (ALiBi). Add linear penalty to attention scores:

score(t,t)=qtTktmhtt,(8)\text{score}(t, t') = \mathbf{q}_t^T \mathbf{k}_{t'} - m_h \cdot |t - t'|, \tag{8}

with head-specific slopes mh=28h/Hm_h = 2^{-8h/H}.

Properties: Zero extra parameters; explicit locality bias; extrapolates to longer sequences. Used in BLOOM, MPT.


Comparison and Extrapolation

  • Sinusoidal — Via dot product — Partial — 0 — Original Transformer
  • Learned — No — No — TmaxdT_{\max} d — BERT, GPT-2
  • RoPE — Native — Yes (with scaling) — 0 — LLaMA, modern LLMs
  • ALiBi — Bias — Yes — HH slopes — BLOOM

NTK-aware scaling extends RoPE to longer contexts by rescaling frequencies at inference — see RoPE.


Worked Examples

Example 1: PE Norm

For d=512d = 512, PE(t)2=256\|\text{PE}(t)\|^2 = 256 for all tt — positions contribute fixed energy.

Example 2: Relative Dot Product

PE(5)TPE(8)=PE(0)TPE(3)\text{PE}(5)^T \text{PE}(8) = \text{PE}(0)^T \text{PE}(3) — depends only on distance 3.

Example 3: RoPE Attention

Positions 10 and 13 differ by 3; same attention score as positions 100 and 103.


Connection to the Broader Curriculum


Common Pitfalls and Misconceptions

Pitfall 1: Assuming attention encodes order without PE.

Pitfall 2: Using learned PE beyond TmaxT_{\max}.

Pitfall 3: Confusing absolute PE addition with RoPE rotation.

Pitfall 4: Ignoring position in cross-attention (encoder–decoder).


Research Perspective

Sinusoidal PE (Vaswani et al., 2017). RoPE (Su et al., 2021) now standard. ALiBi (Press et al., 2022). Long-context research: YaRN, NTK scaling, position interpolation.


Summary of Takeaways

  • Problem — Attention is permutation-equivariant
  • Sinusoidal — Rotation-based relative shift
  • Dot product — Depends on ttt - t'
  • RoPEqtTRttkt\mathbf{q}_t^T \mathbf{R}_{t'-t} \mathbf{k}_{t'}
  • Modern choice — RoPE for autoregressive LLMs

Next: Variational Autoencoders


Exercises

Exercise 1. Prove Theorem 1 (permutation equivariance).

Exercise 2. Derive (2) from angle addition formulas.

Exercise 3. Prove Theorem 2 (relative dot product).

Exercise 4. Prove Theorem 3 (RoPE relative attention).

Exercise 5. Compare parameter counts: learned PE vs. RoPE for Tmax=8192T_{\max} = 8192, d=4096d = 4096.

Exercise 6. Why does ALiBi use different slopes per head?

Exercise 7. Explain failure mode of learned PE at 2× training length.

Exercise 8. Connect RoPE rotations to Eigenvalues of rotation matrices.