TExcelTAD
Home › Math for Deep Learning & LLMs › Positional Encodings

Positional Encodings

Attention treats its input as a set: permuting the tokens just permutes the outputs (Scaled Dot-Product Attention). Yet "dog bites man" and "man bites dog" mean different things. Transformers inject order with positional encodings. The three main designs are learned absolute positions, fixed sinusoids, and rotary embeddings (RoPE), which encode relative position directly into the attention scores and are standard in today's LLMs.

Learned absolute positions

Keep a second embedding table P∈Rnmax⁡×dP \in \mathbb{R}^{n_{\max} \times d} and add row tt to the token embedding at position tt: xt=etoken+pt\mathbf{x}_t = \mathbf{e}_{\text{token}} + \mathbf{p}_t (GPT-2, BERT). Simple and effective, but positions beyond nmax⁡n_{\max} have no embedding at all.

Sinusoidal encodings

The original transformer used fixed vectors with geometrically spaced frequencies ωi=10000−2i/d\omega_i = 10000^{-2i/d}:

pt,2i=sin⁡(ωit),pt,2i+1=cos⁡(ωit)p_{t, 2i} = \sin(\omega_it), \qquad p_{t, 2i+1} = \cos(\omega_it)

Each pair of coordinates is a point rotating on a circle at its own speed: fast pairs distinguish neighbors, slow pairs distinguish distant positions, like the hands of a clock. A shift by kk positions is a fixed rotation of each pair, so pt+k\mathbf{p}_{t+k} is a linear function of pt\mathbf{p}_t.

python · try it yourself
import numpy as np

def sinusoidal(n, d):
    t = np.arange(n)[:, None]; i = np.arange(d // 2)[None, :]
    w = 10000.0 ** (-2 * i / d)
    P = np.zeros((n, d)); P[:, 0::2] = np.sin(w * t); P[:, 1::2] = np.cos(w * t)
    return P
P = sinusoidal(64, 16)
print("p_0 :", np.round(P[0], 2))
print("p_5 :", np.round(P[5], 2))
dots = P @ P[20]
print("p_20 . p_t for t = 18..22:", np.round(dots[18:23], 2), " (largest at t = 20)")
print("depends only on the offset:", np.isclose(P[10] @ P[13], P[40] @ P[43]))
p_0 : [0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1.]
p_5 : [-0.96  0.28  1.   -0.01  0.48  0.88  0.16  0.99  0.05  1.    0.02  1.
  0.    1.    0.    1.  ]
p_20 . p_t for t = 18..22: [6.37 7.49 8.   7.49 6.37]  (largest at t = 20)
depends only on the offset: True

Rotary position embeddings (RoPE)

RoPE (Su et al., 2021) does not add anything to the token embedding. Instead it rotates the query and key vectors: each pair of coordinates (2i,2i+1)(2i, 2i+1) at position tt is rotated by angle ωit\omega_it, with RtR_t the block-diagonal matrix of these 2×22 \times 2 rotations (Rotations). Because rotations compose and are orthogonal,

(Rmq)T(Rnk)=qTRmTRnk=qTRn−mk(R_m\mathbf{q})^T(R_n\mathbf{k}) = \mathbf{q}^TR_m^TR_n\mathbf{k} = \mathbf{q}^TR_{n-m}\mathbf{k}

The attention score depends on the positions only through the offset n−mn - m: relative position comes for free, and vector norms are preserved.

python · try it yourself
import numpy as np

def rope(x, t, base=10000.0):
    d = len(x); w = base ** (-np.arange(0, d, 2) / d)
    c, s = np.cos(w * t), np.sin(w * t)
    out = np.empty_like(x)
    out[0::2] = x[0::2] * c - x[1::2] * s
    out[1::2] = x[0::2] * s + x[1::2] * c
    return out
rng = np.random.default_rng(0)
q, k = rng.normal(size=8), rng.normal(size=8)
for m, n in [(3, 7), (100, 104), (0, 4)]:
    print(f"positions ({m:3d}, {n:3d}), offset {n - m}: score {rope(q, m) @ rope(k, n):+.6f}")
print("norm preserved:", np.isclose(np.linalg.norm(rope(q, 57)), np.linalg.norm(q)))
positions (  3,   7), offset 4: score -1.833596
positions (100, 104), offset 4: score -1.833596
positions (  0,   4), offset 4: score -1.833596
norm preserved: True

Extending the context

A model trained on 4k tokens sees unfamiliar rotation angles at position 32k. Position interpolation rescales positions (t→t⋅4096/32768t \to t \cdot 4096/32768) so angles stay in the trained range; NTK-aware scaling and YaRN instead raise the base frequency, stretching the slow dimensions more than the fast ones. With a short fine-tune, such tricks extend RoPE models to much longer contexts. ALiBi takes another route and adds a bias −m∣i−j∣-m\lvert i - j \rvert to the scores, penalizing distance linearly.

In software

  • Llama, Mistral, Qwen and most open LLMs use RoPE on queries and keys inside every attention layer; rope_theta (the base, e.g. 10410^4 to 10610^6) and rope_scaling appear in their configs.
  • GPT-2 uses a learned table of 1024 positions; BERT one of 512.
  • Implementations precompute cos⁡(ωit)\cos(\omega_it) and sin⁡(ωit)\sin(\omega_it) tables once.

Go further: Positional Encoding: Sinusoidal, Learned, RoPE and ALiBi compares the schemes used in real models and how they extend the context.

Exercises

Exercise 1: Frequencies

For d=8d = 8 and base 10000, list the four frequencies ωi\omega_i.

Answer

11, 0.10.1, 0.010.01, 0.0010.001.

Solution

ωi=10000−2i/8=10−i\omega_i = 10000^{-2i/8} = 10^{-i} for i=0,1,2,3i = 0, 1, 2, 3.

Exercise 2: Wavelength

What is the wavelength (in positions) of the slowest pair for d=8d = 8?

Answer

2π⋅1000≈62832\pi \cdot 1000 \approx 6283 positions.

Solution

The wavelength is 2π/ω2\pi/\omega, with ω=0.001\omega = 0.001.

Exercise 3: 2-D RoPE by hand (code)

With d=2d = 2, ω=1\omega = 1, q=k=(1,0)\mathbf{q} = \mathbf{k} = (1, 0), compute the RoPE score for positions (0,π/2)(0, \pi/2) treated as real numbers and compare with cos⁡(π/2)\cos(\pi/2).

Answer

Both are 0 (up to rounding).

Solution

Rotating k\mathbf{k} by 90∘90^\circ makes it orthogonal to q\mathbf{q}.

python · try it yourself
import numpy as np
rot = lambda v, a: np.array([v[0] * np.cos(a) - v[1] * np.sin(a), v[0] * np.sin(a) + v[1] * np.cos(a)])
q = k = np.array([1.0, 0.0])
print(round(rot(q, 0) @ rot(k, np.pi / 2), 12), round(np.cos(np.pi / 2), 12))
0.0 0.0

Test yourself

Why do transformers need positional information?

  1. Attention is permutation-equivariant and ignores order
  2. To reduce memory
  3. To normalize activations
  4. Because of the softmax

With RoPE, the attention score between positions mm and nn depends on…

  1. mm only
  2. nn only
  3. the offset n−mn - m
  4. m+nm + n

What is a limitation of learned absolute position embeddings?

  1. They cannot be trained
  2. There is no embedding for positions beyond the trained maximum
  3. They are rotations
  4. They change the vocabulary