Skip to content

11.4 Positional encodings: sinusoidal, learned

Multi-head attention gives the same output for “321+654” and “123+456” shuffled into any order of keys: permuting the keys changes nothing. For addition that is fatal, because which digit is the ones digit is entirely a matter of position. The RNNs of the earlier chapters knew order for free, by reading one token at a time. The transformer reads all tokens at once and has to be told.

Concepts from other sections (7)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

This section builds the two ways this book tells it. The first is the fixed sinusoidal table of the 2017 transformer, used by the encoder-decoder Transformer at the end of this chapter, whose shift property is the seed of RoPE in the modern block. The second is the learned table of GPT-2 and BERT. You will see why the frequencies form a geometric ladder, prove that moving kk positions is a fixed rotation, and learn why the angles must be computed in float64.

The section draws on Mathematics: rotate_pairs from Trigonometry, rotations, complex numbers, and Euler’s formula, geometric from Sequences, geometric series, and frequency ladders, normal_init from Variance propagation and initialization, and PCG32 from Modular arithmetic, hashing, and PCG32. From this book it uses the Tensor, the embedding op from The op library and gradcheck_all, and Module from Module system and basic layers. The full solution is python/tinyllm/xfmr/pos.py (sinusoidal_freqs, sinusoidal_pe, shift_pe, SinusoidalPE, LearnedPE), and its contract is course/contracts/py/tinyllm/xfmr/pos.pyi.

Learning objectives

  • Build the sinusoidal table with interleaved sin and cos columns and the frequency ladder ωi=b−2i/d\omega_i = b^{-2i/d}.
  • Prove that PE(p+k)\text{PE}(p + k) is a fixed block rotation of PE(p)\text{PE}(p) and implement shift_pe with one call.
  • Explain why angles are computed in float64 and rounded to float32 once.
  • Build a learned position table as an embedding whose rows get gradient only when used, and honour offset in both modules.
SymbolMeaningType / shape
ppposition, counted from 0int
ddmodel width, evenint
iipair index, 0≤i<d/20 \le i < d/2int
bbbase, 10000 in the paperfloat
ωi=b−2i/d\omega_i = b^{-2i/d}angular frequency of pair ii (radians per position)float64[d/2]
PE(p)\text{PE}(p)the encoding of position ppfloat32[d]
R(θ)R(\theta)the 2D rotation by θ\thetafloat64[2, 2]

Attention is permutation equivariant, so order must enter through the input. The cheapest place is to add a vector that depends only on the position: xp=e(tokenp)+PE(p)x_p = e(\text{token}_p) + \text{PE}(p). Adding (not concatenating) keeps the width dd that every later layer already expects.

The vector should stay bounded however long the sequence is, so raw pp is out. Points on a unit circle, (sin⁡pω,cos⁡pω)(\sin p\omega, \cos p\omega), are bounded and distinct for nearby pp as long as ω\omega is small enough not to wrap. But one circle cannot separate both neighbours and distant positions: a fast ω\omega wraps, a slow one barely moves. The answer is d/2d/2 circles at a geometric ladder of speeds.

PE(p)2i=sin⁡(p ωi),PE(p)2i+1=cos⁡(p ωi),ωi=b−2i/d.\text{PE}(p)_{2i} = \sin(p\,\omega_i), \qquad \text{PE}(p)_{2i+1} = \cos(p\,\omega_i), \qquad \omega_i = b^{-2i/d}.

The frequencies form a geometric sequence with first term 1 and ratio b−2/db^{-2/d} (the geometric helper). Pair 0 turns one radian per position and repeats every 2π2\pi positions; the last pair turns about b−1b^{-1} radians per position and repeats every 2πb2\pi b, about 63 000 positions for b=104b = 10^4. Like a clock with hands of geometric speeds, the fast pairs tell neighbours apart and the slow ones tell far positions apart; geometric spacing gives every scale of distance the same number of pairs.

Each pair lies on the unit circle, so ∥PE(p)∥=d/2\lVert\text{PE}(p)\rVert = \sqrt{d/2} for every pp: unlike adding pp itself, the signal never grows with the sequence. The columns are interleaved, sin at even columns and cos at odd ones. That is the layout of the paper and of rotate_pairs, which makes the shift law below a single call.

There is a precision trap. The angle p ωip\,\omega_i for p=104p = 10^4 is about 10410^4 radians. float32 keeps about 7 significant digits, so the angle is off by roughly 104×6×10−8≈6×10−410^4 \times 6 \times 10^{-8} \approx 6 \times 10^{-4} rad before the sine is even taken. The table is therefore computed in float64 and rounded to float32 at the end.

The table’s most important property comes from the angle-addition formulas:

(sin⁡((p+k)ω)cos⁡((p+k)ω))=(cos⁡kωsin⁡kω−sin⁡kωcos⁡kω)(sin⁡pωcos⁡pω)=R(−kω)(sin⁡pωcos⁡pω).\begin{pmatrix}\sin((p+k)\omega)\\ \cos((p+k)\omega)\end{pmatrix} = \begin{pmatrix}\cos k\omega & \sin k\omega\\ -\sin k\omega & \cos k\omega\end{pmatrix}\begin{pmatrix}\sin p\omega\\ \cos p\omega\end{pmatrix} = R(-k\omega)\begin{pmatrix}\sin p\omega\\ \cos p\omega\end{pmatrix}.

So PE(p+k)\text{PE}(p + k) is PE(p)\text{PE}(p) with pair ii turned by −kωi-k\omega_i: one block-diagonal rotation that depends on kk and not on pp. shift_pe(pe, k, d) is rotate_pairs(pe, -k * omega).

Two consequences follow. A linear layer can learn to “look kk back” the same way at every position. And PE(p)⋅PE(p+k)=∑icos⁡(k ωi)\text{PE}(p) \cdot \text{PE}(p+k) = \sum_i \cos(k\,\omega_i) depends only on the distance. RoPE applies exactly this rotation to the queries and keys instead of adding it to the input.

GPT-2 and BERT take the other route and learn a table P∈RL×dP \in \mathbb{R}^{L \times d} (max_len rows), adding row pp at position pp. It is an embedding indexed by position, initialized N(0,0.022)\mathcal{N}(0, 0.02^2), and only the rows actually used get gradient. It can learn any pattern, but it knows nothing about positions past LL: a model trained on 1024 tokens has no row 1024.

Both modules add positions offset .. offset + T - 1 to an input of length TT. During training offset is 0. When decoding one token at a time with a KV cache, the new token sits at position offset, the number of tokens before it, and must get that row, not row 0.

With d=4d = 4 and b=10000b = 10000, the ladder is ω=(100000,10000−1/2)=(1,0.01)\omega = (10000^0, 10000^{-1/2}) = (1, 0.01), and the first three rows are:

ppsin⁡p\sin pcos⁡p\cos psin⁡0.01p\sin 0.01pcos⁡0.01p\cos 0.01p
00101
10.8414710.5403020.0100000.999950
20.909297-0.4161470.0199990.999800

Now check the shift on pair 0 with k=1k = 1. Applying R(−1)R(-1) to (sin⁡1,cos⁡1)=(0.841471,0.540302)(\sin 1, \cos 1) = (0.841471, 0.540302) gives (0.841471cos⁡1+0.540302sin⁡1,  −0.841471sin⁡1+0.540302cos⁡1)=(0.454649+0.454649,  −0.708073+0.291927)=(0.909297,−0.416147)(0.841471 \cos 1 + 0.540302 \sin 1,\; -0.841471 \sin 1 + 0.540302 \cos 1) = (0.454649 + 0.454649,\; -0.708073 + 0.291927) = (0.909297, -0.416147), which is the p=2p = 2 row.

def sinusoidal_freqs(d: int, base: float = 10000.0) -> NDArray # float64 [d/2]
def sinusoidal_pe(T: int, d: int, base: float = 10000.0, offset: int = 0) -> NDArray # float32 [T, d]
def shift_pe(pe, k: float, d: int, base: float = 10000.0) -> NDArray
class SinusoidalPE(Module): # no parameters; forward(x, offset=0) = x + table[offset : offset + T]
class LearnedPE(Module): # weight [max_len, d]; positions(T, offset); forward(x, offset=0)

The fixed table is data, not a parameter: storing it as a plain array keeps it out of the gradient and the state_dict. The learned table is the opposite, a parameter read through embedding, so that only the rows used get gradient. Both modules take offset so the same module serves training (offset 0) and cached decoding.

The ladder is the geometric sequence, with the validation that keeps the table meaningful:

def _check_d(d: int) -> None:
# Pairs need an even width; an odd last column would have no partner.
if not isinstance(d, (int, np.integer)) or d < 2 or d % 2:
raise ValueError(f"d must be a positive even integer, got {d}")
def sinusoidal_freqs(d: int, base: float = 10000.0) -> NDArray:
_check_d(d)
# base <= 1 would make the ladder flat or increasing: no slow pairs.
if not (np.isfinite(base) and base > 1.0):
raise ValueError(f"base must be finite and > 1, got {base}")
# omega_i = base^(-2i/d): first term 1, ratio base^(-2/d) (M00.3).
return geometric(1.0, float(base) ** (-2.0 / d), d // 2)

The ratio is b−2/db^{-2/d}, not b−1/db^{-1/d}: with d/2d/2 terms the last one is b−2(d/2−1)/d≈b−1b^{-2(d/2-1)/d} \approx b^{-1}, so the slowest pair repeats every 2πb2\pi b positions.

The table is an outer product of positions and frequencies, then sin and cos written into interleaved columns:

def sinusoidal_pe(T: int, d: int, base: float = 10000.0, offset: int = 0) -> NDArray:
if T < 0 or offset < 0:
raise ValueError(f"T and offset must be non-negative, got {T}, {offset}")
w = sinusoidal_freqs(d, base)
# Angles in float64: at p = 10^4 a float32 angle is off by about 5e-4 rad.
# Positions start at `offset` (0 in training), counted from 0, not 1.
ang = np.arange(offset, offset + T, dtype=np.float64)[:, None] * w[None, :]
pe = np.empty((T, d), dtype=np.float64)
pe[:, 0::2] = np.sin(ang) # PE(p, 2i)
pe[:, 1::2] = np.cos(ang) # PE(p, 2i + 1)
return pe.astype(np.float32) # round once, after the trig

The shift is one call, because the layout matches rotate_pairs:

def shift_pe(pe: ArrayLike, k: float, d: int, base: float = 10000.0) -> NDArray:
x = np.asarray(pe)
if x.shape[-1] != d:
raise ValueError(f"pe has width {x.shape[-1]}, expected d = {d}")
# The pair (sin a, cos a) turned by -k*omega is (sin(a + k omega),
# cos(a + k omega)): a rotation (M00.2) that depends on k, not on p.
return rotate_pairs(x, -float(k) * sinusoidal_freqs(d, base))

rotate_pairs(x, θ) maps a pair (e,o)(e, o) to (ecos⁡θ−osin⁡θ,  esin⁡θ+ocos⁡θ)(e\cos\theta - o\sin\theta,\; e\sin\theta + o\cos\theta). With e=sin⁡ae = \sin a, o=cos⁡ao = \cos a and θ=−kω\theta = -k\omega the first entry is sin⁡acos⁡kω+cos⁡asin⁡kω=sin⁡(a+kω)\sin a\cos k\omega + \cos a \sin k\omega = \sin(a + k\omega): the minus sign is what moves forward in position. Each pair gets its own angle kωik\omega_i; one shared angle would scramble the slow pairs.

The fixed module precomputes max_len rows once and slices:

class SinusoidalPE(Module):
def __init__(self, max_len: int, d: int, base: float = 10000.0) -> None:
super().__init__()
# ...
# A constant, not a parameter: no gradient, not in the state_dict.
self.table = sinusoidal_pe(max_len, d, base)
def forward(self, x: Tensor, offset: int = 0) -> Tensor:
T = x.shape[-2]
# ... width check ...
if offset < 0 or offset + T > self.max_len:
# Refuse instead of wrapping: a wrapped slice would silently reuse rows.
raise ValueError(...)
# Tensor + ndarray: the gradient flows to x and nowhere else.
return x + self.table[offset : offset + T].astype(x.dtype)

The learned module is an embedding table indexed by position:

class LearnedPE(Module):
def __init__(self, max_len: int, d: int, std: float = 0.02, rng: Any = None) -> None:
super().__init__()
# ...
r = rng if rng is not None else PCG32(0).substream("init")
self.max_len, self.d = max_len, d
# N(0, std^2) from the seeded stream (M07.3): the same init in every language.
self.weight = Tensor(normal_init((max_len, d), std, r), requires_grad=True)
def positions(self, T: int, offset: int = 0) -> Tensor:
# ... range check against max_len ...
# Rows offset .. offset+T-1 of the table, with their gradient.
return F.embedding(self.weight, np.arange(offset, offset + T))
def forward(self, x: Tensor, offset: int = 0) -> Tensor:
# ... width check ...
return x + self.positions(x.shape[-2], offset)

F.embedding is a gather whose backward scatters into exactly the rows read, so rows past the sequence length stay at their initial values. positions is public because GPT-2 and BERT want the position rows on their own. The full solution is pos.py.

Building the table is O(max_len⋅d)O(\text{max\_len} \cdot d) once; each forward is a slice and an add, O(Td)O(Td). The learned table costs L⋅dL \cdot d parameters and its gradient touches only TT rows.

fairseq and some HF code use a half layout: all sines first, then all cosines. That is equally valid but needs a different rotation helper. Interleaving matches the paper and the rotation helper, so the shift law reuses existing code.

Computing rows per call would allow unbounded positions, but costs trig on every step; a fixed max_len matches the learned table’s contract and makes “past the table” a clear error. Computing in float32 would be faster but wrong at long positions; the cost of float64 is paid once.

There is one tradeoff accepted here: neither encoding extrapolates past max_len. The rotation property is the seed of RoPE, which removes that limit for relative distances.

A correct solution must reproduce the worked table (frequencies (1, 0.01) and the three rows) so everyone agrees on layout and ladder, and the worked shift (turning PE(1) by −ω-\omega gives PE(2)) to pin down the rotation’s sign. At long positions, the table at positions up to 65535, for two settings, must match a 50-digit mpmath reference, so long contexts keep exact positions. The properties argued above must hold: one fixed R(k)R(k) for every pp, negative kk included (the relative-position property RoPE builds on); PE(p)⋅PE(p+k)=∑icos⁡kωi\text{PE}(p)\cdot\text{PE}(p+k) = \sum_i \cos k\omega_i; every pair has norm 1; and offset gives the tail of a longer table, which the module honours.

For the modules, the sinusoidal module has an empty state_dict and passes gradient through to xx; the learned module adds rows offset.. and only those rows get gradient; and its init is a seeded N(0,std2)\mathcal{N}(0, \text{std}^2) with default std 0.02, the same in every language. Odd dd, a base ≤1\le 1, and positions past the table must raise, so nothing wraps around silently. The model suite test_pos.py uses the formula itself as the oracle (Python’s math in float64, including positions p≥104p \ge 10^4).

The common mistakes and how the code avoids each:

PitfallSymptomHow the solution avoids it
sin and cos concatenated (or swapped) instead of interleavedthe shift law fails; checkpoints from other code disagreewrites pe[:, 0::2] = sin, pe[:, 1::2] = cos
exponent i/di/d instead of 2i/d2i/dthe ladder ends at b−1/2b^{-1/2}: far positions aliasratio base ** (-2.0 / d) over d // 2 terms
angles in float32rows past a few thousand off in the 4th decimalangles built from a float64 arange, cast to float32 only at the end
the shift turned the wrong way, or by the same angle for every pairshift_pe goes back in position, or scrambles pairspasses the per-pair vector -k * omega to rotate_pairs
positions counted from 1every row one late; HF and torch disagreenp.arange(offset, offset + T) starts at 0 when offset = 0
offset ignoredincremental decoding gives every new token position 0both modules slice rows offset .. offset + T - 1
the fixed table registered as a parameterit trains and lands in the checkpointself.table is a plain ndarray
learned rows read as constantswpe never learnsrows gathered with F.embedding(self.weight, ...)
std ignored by the learned tableevery table starts at 0.02normal_init((max_len, d), std, r) uses the argument
an odd width acceptedthe last feature has no partner_check_d rejects odd or tiny d

The encoder-decoder Transformer applies SinusoidalPE to both the source and the target embeddings; this is how the chapter’s addition model reads digit positions. LearnedPE is GPT-2’s wpe and BERT’s position embedding. RoPE rotates queries and keys by the same ladder instead of adding a vector, and Whisper decoding calls this code through its declared contract.

The production equivalents:

Solution pieceProduction equivalentWhat it addsWhere to look
sinusoidal_pefairseq SinusoidalPositionalEmbeddingthe half layout (all sin, then all cos) and a padding offsetfairseq/modules/sinusoidal_positional_embedding.py
shift_peRoPEthe rotation applied inside attention, so scores depend on p−qp - q onlyRoPE; Su et al. 2021
LearnedPEHF GPT2Model.wpe, BertEmbeddings.position_embeddingsabsolute positions capped at n_positionstransformers/models/gpt2/modeling_gpt2.py
no position at allALiBi, NoPEa distance penalty on scores, or causality alone, for length extrapolationPress et al. 2022; Kazemnejad et al. 2023
  • Vaswani et al., “Attention Is All You Need” (2017), section 3.5.
  • Kazemnejad, “Transformer Architecture: The Positional Encoding” (2019).
  • Su et al., “RoFormer” (2021), for where the rotation goes next.
  • positional encoding: a vector depending only on position, added to the token embedding so attention can see order.
  • frequency ladder: the geometric sequence ωi=b−2i/d\omega_i = b^{-2i/d} of angular speeds, from 1 down to about b−1b^{-1}.
  • interleaved layout: sin at column 2i2i and cos at column 2i+12i+1, the pair layout of the paper.
  • shift law: PE(p+k)\text{PE}(p+k) equals PE(p)\text{PE}(p) with each pair rotated by −kωi-k\omega_i, independent of pp.
  • learned position table: an embedding of max_len rows indexed by position, trained like any parameter.
  • offset: the absolute position of the first input token, nonzero during cached decoding.
  • Attention sees its keys as a set, so position must be added to the input: xp=e(tokenp)+PE(p)x_p = e(\text{token}_p) + \text{PE}(p).
  • Pair ii of PE(p)\text{PE}(p) is the point (sin⁡p ωi,cos⁡p ωi)(\sin p\,\omega_i, \cos p\,\omega_i) with ωi=10000−2i/d\omega_i = 10000^{-2i/d}, a geometric ladder from 1 radian per position down to about 10−410^{-4}.
  • Moving kk positions is a fixed rotation of every pair, the same for every pp, so PE(p)⋅PE(p+k)\text{PE}(p) \cdot \text{PE}(p + k) depends only on kk.
  • Angles must be computed in float64: at p=104p = 10^4 a float32 angle is already off in the fourth decimal.
  • A learned table is just an embedding indexed by position: it adds rows offset .. and only those rows get gradient.
  1. Why must the ratio of the ladder be b−2/db^{-2/d} and not b−1/db^{-1/d}?
    AnswerThere are $d/2$ frequencies. With ratio $b^{-2/d}$ the last is about $b^{-1}$, so the slowest pair has period $2\pi b$. With $b^{-1/d}$ the ladder stops at about $b^{-1/2}$, the slowest period is only $2\pi\sqrt b \approx 630$ positions, and far positions alias.
  2. Why is the shift a rotation by −kωi-k\omega_i rather than +kωi+k\omega_i?
    AnswerThe pair is stored as (sin, cos), not (cos, sin). `rotate_pairs` with angle $\theta$ sends $(\sin a, \cos a)$ to $(\sin(a - \theta), \cos(a - \theta))$, so moving forward by $k\omega$ needs $\theta = -k\omega$.
  3. Why is SinusoidalPE.table a plain array and not a Tensor with requires_grad?
    AnswerIt is a fixed function of position. As a parameter it would be updated by the optimizer (no longer sinusoidal, so the shift law breaks) and saved in every checkpoint for no reason.
  4. What goes wrong in cached decoding if offset is ignored?
    AnswerEach new token is fed alone, so $T = 1$, and without `offset` it always gets row 0. Every generated token then looks like the first token of the sequence.
  5. Why does LearnedPE read its rows through F.embedding instead of slicing weight.data?
    AnswerSlicing the raw array would give a constant with no path back to `weight`, so the table would never learn. `embedding` records the gather and scatters the gradient into the rows used.