Simple Algorithm
Artificial Intelligence · Deep Layer · 26 min

Positional Encodings

Sinusoids, rotary embeddings and length generalization.

Shuffle the words of a sentence and plain self-attention cannot tell. Every transformer therefore injects position somewhere: added to the input, rotated into queries and keys, or subtracted from the scores. The choice decides, among other things, whether a model trained on 4,000 tokens can read 32,000.

What you’ll learn

  • Explain why self-attention needs positional information, and classify encodings as absolute or relative, fixed or learned.
  • Derive the rotation structure of sinusoidal encodings and the relative-position property of rotary embeddings (RoPE).
  • Prove that ALiBi's linear biases confine each head to a soft window of width about 1/m1/m, and relate this to length extrapolation.
  • Explain why RoPE fails to extrapolate, and why position interpolation and frequency-aware rescaling extend context windows.

Why position must be added

Self-attention is permutation-equivariant (Attention & Transformers): permute the input rows and the outputs permute the same way. A causal mask breaks the symmetry in part, since position ii sees exactly ii tokens, and decoders trained with no positional encoding at all ("NoPE") still learn positional information (Haviv et al., 2022). Every major architecture nevertheless adds position explicitly, in one of these ways:

SchemeWhere position entersTypeExamples
Sinusoidaladded to the input embeddingsabsolute, fixedthe original transformer (2017)
Learned absoluteadded to the input, one vector per position up to nmax⁡n_{\max}absolute, learned; undefined beyond nmax⁡n_{\max}BERT, GPT-2
Relative embeddings and biasesa learned term per clipped or bucketed offset i−ji-j, in the keys or the scoresrelative, learnedShaw et al. (2018); Transformer-XL (2019); T5 (2020)
Rotary (RoPE)queries and keys rotated by position-dependent anglesrelative in the score, fixedRoFormer (Su et al., 2021); widely used in open LLMs by the mid-2020s
ALiBia fixed penalty −mh (i−j)-m_h\,(i-j) on the scoresrelative, fixedPress, Smith & Lewis (2022)
Length generalization asks how a model trained on sequences of length at most LL behaves on longer ones. Learned absolute embeddings have no vector for position L+1L+1; the other schemes are defined everywhere but extrapolate very differently.
Think first How can a causal decoder with no positional encoding tell positions apart?

Through the mask. A head with constant scores gives position ii the average of the first ii values. If the sequence starts with a fixed beginning-of-sequence token, that token's share of the average is 1/i1/i, a position signal later layers can read; Kazemnejad et al. (2023) prove a construction of this kind. In the attention widget, the uniform head under the causal mask gives "it", the 8th word, exactly 1/81/8 on each visible word.

Sinusoids are rotations

Vaswani et al. encode position pp in dd dimensions with sinusoids of geometrically spaced frequencies:

PE(p)2i=sin⁡(ωip),PE(p)2i+1=cos⁡(ωip),ωi=10000−2i/d,i=0,…,d2−1\mathrm{PE}(p)_{2i}=\sin(\omega_ip),\qquad\mathrm{PE}(p)_{2i+1}=\cos(\omega_ip),\qquad\omega_i=10000^{-2i/d},\quad i=0,\dots,\tfrac d2-1
Wavelengths 2π/ωi2\pi/\omega_i run from 2π2\pi tokens to about 2π⋅1042\pi\cdot10^4 tokens. Each pair of coordinates is a point on a circle turning at its own speed: a clock with d/2d/2 hands.
DerivationOffsets are linear maps
  1. ui(p+k)=(cos⁡ωiksin⁡ωik−sin⁡ωikcos⁡ωik)ui(p)⟹PE(p+k)=Rk PE(p)\mathbf u_i(p+k)=\begin{pmatrix}\cos\omega_ik&\sin\omega_ik\\-\sin\omega_ik&\cos\omega_ik\end{pmatrix}\mathbf u_i(p)\quad\Longrightarrow\quad\mathrm{PE}(p+k)=R_k\,\mathrm{PE}(p)

    Group the coordinates into pairs ui(p)=(sin⁡ωip,cos⁡ωip)\mathbf u_i(p)=(\sin\omega_ip,\cos\omega_ip). The angle-addition formulas shift a pair by kk positions with a rotation that does not depend on pp:

  2. PE(p)⋅PE(q)=∑i=0d/2−1cos⁡(ωi(p−q))\mathrm{PE}(p)\cdot\mathrm{PE}(q)=\sum_{i=0}^{d/2-1}\cos\big(\omega_i(p-q)\big)

    RkR_k is block-diagonal and orthogonal, so "the token kk places back" is a fixed linear function of the current position's code, which a query projection can learn, as Vaswani et al. intended. Inner products of codes depend only on the offset:

  3. cos⁡(ωΔ)=cos⁡(ω(Δ+2π/ω))\cos(\omega\Delta)=\cos\big(\omega(\Delta+2\pi/\omega)\big)

    Several frequencies are needed because each one alone is periodic: a single hand cannot tell offset Δ\Delta from Δ+2π/ωi\Delta+2\pi/\omega_i. Slow hands break the ties of fast ones, making the code nearly unique over the range of the slowest.

Rotary position embedding

DerivationProof
  1. ⟨Rmq,Rnk⟩=q⊤Rm⊤Rn k=q⊤Rn−m k\langle R_m\mathbf q,R_n\mathbf k\rangle=\mathbf q^\top R_m^\top R_n\,\mathbf k=\mathbf q^\top R_{n-m}\,\mathbf k

    Each RmR_m is orthogonal, and rotations of the same pair commute and add their angles, so Rm⊤Rn=R−mRn=Rn−mR_m^\top R_n=R_{-m}R_n=R_{n-m}:

  2. ∑iRe⁡(q~ieimθi k~ieinθi‾)=Re⁡∑iq~ik~i‾ ei(m−n)θi\sum_i\operatorname{Re}\Big(\tilde q_ie^{\mathrm im\theta_i}\,\overline{\tilde k_ie^{\mathrm in\theta_i}}\Big)=\operatorname{Re}\sum_i\tilde q_i\overline{\tilde k_i}\,e^{\mathrm i(m-n)\theta_i}

    In complex form a rotation multiplies by eimθie^{\mathrm im\theta_i}, and the real inner product of two pairs is Re⁡(q~ k~‾)\operatorname{Re}(\tilde q\,\overline{\tilde k}):

  3. ∣∑ihieiΔθi∣≤(max⁡i∣hi+1−hi∣)∑j=1d/2∣∑i<jeiΔθi∣\Big|\sum_ih_ie^{\mathrm i\Delta\theta_i}\Big|\le\Big(\max_i\abs{h_{i+1}-h_i}\Big)\sum_{j=1}^{d/2}\Big|\sum_{i<j}e^{\mathrm i\Delta\theta_i}\Big|

    Position enters the score multiplicatively, with no content–position cross terms, and norms are preserved. Su et al. derived the form as the solution of ⟨f(q,m),f(k,n)⟩=g(q,k,m−n)\langle f(\mathbf q,m),f(\mathbf k,n)\rangle=g(\mathbf q,\mathbf k,m-n) in two dimensions. Writing hi=q~ik~i‾h_i=\tilde q_i\overline{\tilde k_i} with hd/2=0h_{d/2}=0, Abel summation bounds the score by partial sums whose average size shrinks as ∣m−n∣\abs{m-n} grows: a mild bias toward nearby tokens.

Why RoPE fails to extrapolate, and how windows are extended. Pair ii completes a turn every 2π/θi2\pi/\theta_i tokens. Fast pairs cycle many times within the training length LL, so every angle they will ever produce has been seen. Slow pairs never complete a turn, so beyond LL they produce angles the model has never seen. Position interpolation (Chen et al., 2023) rescales positions, m↦mL/L′m\mapsto mL/L', mapping a window of L′L' tokens back into the trained range of angles; a short fine-tuning, about a thousand steps, then adapts the model. Interpolation is safe because the score is a smooth function of the offset:

s(Δ)=Re⁡∑ihieiΔθi,∣s′(Δ)∣≤∑i∣hi∣ θis(\Delta)=\operatorname{Re}\sum_ih_ie^{\mathrm i\Delta\theta_i},\qquad\abs{s'(\Delta)}\le\sum_i\abs{h_i}\,\theta_i
Between trained integer offsets ss cannot move far; beyond LL nothing constrains it. Uniform interpolation also squeezes the fast pairs, crowding neighboring tokens together, so "NTK-aware" rescaling (proposed informally in 2023) and YaRN (Peng et al., 2024) interpolate mainly the slow pairs, leave the fast ones alone and adjust the softmax temperature. Raising the base bb is the simplest version of the idea.
Predict before you look

With base b=104b=10^4 and head dimension d=128d=128, the slowest RoPE pair (i=63i=63) has wavelength 2π⋅104⋅126/128≈54,4002\pi\cdot10^{4\cdot126/128}\approx54{,}400 tokens. What fraction of a full turn does it complete across a 4,096-token training context, in percent?

Show the answer

7.5 %

4096/54,400≈0.0754096/54{,}400\approx0.075: the slowest pairs sweep only about 27∘27^\circ during training. At 32,000 tokens they would reach about 210∘210^\circ, angles never seen in training, which is why naive extrapolation fails, while interpolation keeps every angle inside the trained range.

ALiBi, locality and length generalization

ALiBi (Press, Smith & Lewis, 2022) adds no embedding at all. Each head hh subtracts a penalty proportional to distance from its causal scores:

sij=qi⋅kjdk−mh (i−j)(j≤i),mh=2−8h/H,h=1,…,Hs_{ij}=\frac{\mathbf q_i\cdot\mathbf k_j}{\sqrt{d_k}}-m_h\,(i-j)\quad(j\le i),\qquad m_h=2^{-8h/H},\quad h=1,\dots,H
With H=8H=8 heads the slopes are 12,14,…,1256\tfrac12,\tfrac14,\dots,\tfrac1{256}, so some heads are sharply local and others nearly global. A 1.3-billion-parameter model trained on 1,024 tokens matched, at 2,048 tokens, the perplexity of a sinusoidal model trained on 2,048, while training 11% faster.
DerivationProof
  1. ∑Δ>WaΔ=∑Δ>WecΔ−mΔ∑Δ≥0ecΔ−mΔ≤eB∑Δ>We−mΔe−B\sum_{\Delta>W}a_\Delta=\frac{\sum_{\Delta>W}e^{c_\Delta-m\Delta}}{\sum_{\Delta\ge0}e^{c_\Delta-m\Delta}}\le\frac{e^{B}\sum_{\Delta>W}e^{-m\Delta}}{e^{-B}}

    Write Δ=i−j≥0\Delta=i-j\ge0 and cΔ∈[−B,B]c_\Delta\in[-B,B] for the content score, so the weight at distance Δ\Delta is proportional to ecΔ−mΔe^{c_\Delta-m\Delta}. Bound the numerator above, and the denominator below by its Δ=0\Delta=0 term:

  2. ∑Δ>We−mΔ=e−m(W+1)1−e−m⟹∑Δ>WaΔ≤e2B e−m(W+1)1−e−m\sum_{\Delta>W}e^{-m\Delta}=\frac{e^{-m(W+1)}}{1-e^{-m}}\quad\Longrightarrow\quad\sum_{\Delta>W}a_\Delta\le\frac{e^{2B}\,e^{-m(W+1)}}{1-e^{-m}}

    Sum the geometric tail:

  3. W+1≥1m(2B+log⁡1ε+log⁡11−e−m)W+1\ge\frac{1}{m}\Big(2B+\log\frac1\varepsilon+\log\frac1{1-e^{-m}}\Big)

    Set the bound to ε\varepsilon and solve; 1−e−m≈m1-e^{-m}\approx m for small slopes. Far tokens carry negligible weight however long the input, so at test time no head meets unfamiliar amounts of attention at unfamiliar distances, hence stable perplexity. The same fact is the limitation: no head reads directly beyond its window, so distant information must hop through layers.

Stable perplexity is not the same as using a long context: a model can extrapolate in perplexity by ignoring distant tokens. Tasks that need far-away information tell a different story. In multi-document question answering, accuracy drops when the relevant passage sits in the middle of a long context (Liu et al., 2024). On synthetic reasoning tasks, NoPE decoders generalized to longer inputs better than most explicit encodings (Kazemnejad et al., 2023), and training with positions sampled at random from a larger range helps algorithmic tasks extrapolate (Ruoss et al., 2023).

Key takeaways

  • Self-attention needs position injected: added to the input (sinusoidal, learned), rotated into queries and keys (RoPE), or added to the scores (relative biases, ALiBi).
  • Sinusoidal codes satisfy PE(p+k)=RkPE(p)\mathrm{PE}(p+k)=R_k\mathrm{PE}(p) with block rotations, so offsets are linear maps and code inner products depend only on p−qp-q.
  • RoPE gives ⟨Rmq,Rnk⟩=⟨q,Rn−mk⟩\langle R_m\mathbf q,R_n\mathbf k\rangle=\langle\mathbf q,R_{n-m}\mathbf k\rangle: relative position entering multiplicatively. Slow pairs meet unseen angles beyond the training length, which interpolation and frequency-aware rescaling avoid.
  • ALiBi's penalty −mh(i−j)-m_h(i-j) confines each head to a soft window of width about 1/mh1/m_h: stable perplexity on long inputs but no direct long-range reads. Extrapolating in perplexity is not the same as using a long context.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

With RoPE, how does the score between a query at position mm and a key at position nn depend on the positions?

  1. Through m+nm+n
  2. Only through m−nm-n, because Rm⊤Rn=Rn−mR_m^\top R_n=R_{n-m}
  3. Through mm and nn separately, as with learned absolute embeddings
  4. Not at all, because rotations preserve norms
Show the answer

B. Only through m−nm-n, because Rm⊤Rn=Rn−mR_m^\top R_n=R_{n-m}

Rotations of the same pair compose by adding angles, and Rm⊤=R−mR_m^\top=R_{-m}, so ⟨Rmq,Rnk⟩=⟨q,Rn−mk⟩\langle R_m\mathbf q,R_n\mathbf k\rangle=\langle\mathbf q,R_{n-m}\mathbf k\rangle.

Question 2

Why can a linear query projection implement "attend to the token kk positions back" on top of sinusoidal encodings?

  1. Because PE(p−k)=R−k PE(p)\mathrm{PE}(p-k)=R_{-k}\,\mathrm{PE}(p) for a fixed rotation R−kR_{-k} that does not depend on pp
  2. Because sinusoids of different frequencies are orthogonal functions
  3. Because the encodings are learned during training
  4. Because the dot product of two different position codes is always zero
Show the answer

A. Because PE(p−k)=R−k PE(p)\mathrm{PE}(p-k)=R_{-k}\,\mathrm{PE}(p) for a fixed rotation R−kR_{-k} that does not depend on pp

A query WQPE(p)W_Q\mathrm{PE}(p) with WQW_Q containing R−kR_{-k} points at PE(p−k)\mathrm{PE}(p-k), and its dot product with key PE(j)\mathrm{PE}(j) is ∑icos⁡ωi(j−p+k)\sum_i\cos\omega_i(j-p+k), maximal at j=p−kj=p-k. The widget's previous-token head is exactly this construction with k=1k=1.

Question 3

A RoPE model trained on 4,096 tokens must read 16,384. Why does position interpolation work better than running it unchanged?

  1. It removes the slowest frequencies
  2. It makes the model attend only within 4,096-token windows
  3. It keeps every rotation angle within the range seen in training, where the score is a smooth, well-trained function of the offset
  4. It adds attention heads for the new positions
Show the answer

C. It keeps every rotation angle within the range seen in training, where the score is a smooth, well-trained function of the offset

Positions are scaled by L/L′=1/4L/L'=1/4. Fast pairs already cycled during training; slow pairs would otherwise produce unseen angles. Within the trained range, ∣s′(Δ)∣≤∑i∣hi∣θi\abs{s'(\Delta)}\le\sum_i\abs{h_i}\theta_i limits how far fractional offsets can stray.

Question 4

What does an ALiBi head with slope m=116m=\tfrac1{16} and bounded content scores effectively do?

  1. Attend only to the first token
  2. Attend uniformly over the whole context
  3. Ignore content and attend by distance alone
  4. Attend within a soft window of order 1/m1/m tokens, up to logarithmic factors, with geometrically decaying weight beyond it
Show the answer

D. Attend within a soft window of order 1/m1/m tokens, up to logarithmic factors, with geometrically decaying weight beyond it

The penalty −mΔ-m\Delta multiplies far weights by e−mΔe^{-m\Delta}, so mass beyond distance WW is at most e2Be−m(W+1)/(1−e−m)e^{2B}e^{-m(W+1)}/(1-e^{-m}). Content still decides which keys win inside the window.

Further reading

  • J. Su et al., "RoFormer: Enhanced transformer with rotary position embedding," arXiv:2104.09864 (2021); Neurocomputing (2024).
  • O. Press, N. A. Smith & M. Lewis, "Train short, test long: Attention with linear biases enables input length extrapolation," ICLR (2022).
  • S. Chen, S. Wong, L. Chen & Y. Tian, "Extending context window of large language models via positional interpolation," arXiv:2306.15595 (2023).
  • A. Kazemnejad, I. Padhi, K. Natesan Ramamurthy, P. Das & S. Reddy, "The impact of positional encoding on length generalization in transformers," NeurIPS (2023).
  • P. Dufter, M. Schmitt & H. Schütze, "Position information in transformers: An overview," Computational Linguistics 48 (2022).