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 and add row to the token embedding at position : (GPT-2, BERT). Simple and effective, but positions beyond have no embedding at all.
Sinusoidal encodings
The original transformer used fixed vectors with geometrically spaced frequencies :
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 positions is a fixed rotation of each pair, so is a linear function of .
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 at position is rotated by angle , with the block-diagonal matrix of these rotations (Rotations). Because rotations compose and are orthogonal,
The attention score depends on the positions only through the offset : relative position comes for free, and vector norms are preserved.
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 () 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 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. to ) andrope_scalingappear in their configs. - GPT-2 uses a learned table of 1024 positions; BERT one of 512.
- Implementations precompute and 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 and base 10000, list the four frequencies .
Answer
, , , .
Solution
for .
Exercise 2: Wavelength
What is the wavelength (in positions) of the slowest pair for ?
Answer
positions.
Solution
The wavelength is , with .
Exercise 3: 2-D RoPE by hand (code)
With , , , compute the RoPE score for positions treated as real numbers and compare with .
Answer
Both are 0 (up to rounding).
Solution
Rotating by makes it orthogonal to .
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?
- Attention is permutation-equivariant and ignores order
- To reduce memory
- To normalize activations
- Because of the softmax
With RoPE, the attention score between positions and depends on…
- only
- only
- the offset
What is a limitation of learned absolute position embeddings?
- They cannot be trained
- There is no embedding for positions beyond the trained maximum
- They are rotations
- They change the vocabulary