intermediate attention-transformers 40 min read

Positional Encodings: Sinusoids, Rotations, and RoPE

A positional encoding is a kernel over offsets: sinusoids are a fixed stationary kernel that rules distance logarithmically, RoPE rotates queries and keys so every learned score sees only the offset, and ALiBi multiplies in an exponential kernel that extrapolates in length because it cannot look far

Overview & Motivation

The attention topic read attention as a kernel smoother: a weighted average over a set of keys. A set has no order, and that topic’s Proposition 3 drew the consequence. At the last word, one layer of attention reads the dog bit the man today exactly as it reads the man bit the dog today. A positional encoding supplies the order. The question this topic asks is what kind of object it supplies.

The answer we develop is that every positional encoding is a kernel over offsets: a rule for how much the distance between two positions should change their score. Then length generalization, the ability to read sequences longer than any seen in training, becomes a question about what that kernel does past the training window. Here is the experiment the topic builds toward. We train single attention heads, with each of five ways of adding position, to answer which marked token came last? in sequences of 3232 tokens, and read them on sequences of 256256:

schemeaccuracy at 32at 256
no position at all0.5420.5420.2370.237
sinusoidal code, added0.9960.9960.1420.142
RoPE (rotations)1.0001.0000.4660.466
RoPE, positions interpolated1.0001.0000.9170.917
ALiBi (a linear penalty on distance)0.9990.9990.9780.978

Each row is taken up below.

  1. Sinusoids are a stationary kernel. The sinusoidal code turns the hands of d/2d/2 clocks. Shifting every position is one rotation, and the inner product of two positions depends only on their offset. As dd grows it becomes a ruler that is logarithmic in distance.
  2. Adding a stationary code does not make attention relative. Only a dd-dimensional family of score matrices sees offsets alone, and trained heads sit as far from it as random matrices. The added code collapses at twice its training length, because absolute positions it never saw enter the score, through this term and through the content–position terms.
  3. ALiBi is a product kernel. Its weights are the attention topic’s smoother with a content kernel times an exponential kernel in time. One inequality says both why it extrapolates and why it cannot look far.
  4. RoPE is relative by construction, and up to the learned projections it is the only linear encoding that is. Its score is a trigonometric polynomial in the offset, and past the training window the polynomial does what training never constrained it to do.

Then we take the heads to text. Synthetic company filings name a parent and its subsidiaries and then refer back to “the company”. Asked at every position which company was named most recently, heads trained on 3232-token windows read whole filings. Past the training window, RoPE with interpolated positions reads 0.9860.986 of the answers, and ALiBi, which held at 0.9780.978 through the length tournament, reads 0.5800.580.


Order, and how a mask leaks it

The attention topic’s Proposition 3 says bidirectional attention is permutation-equivariant, and that one causal layer, which reads only earlier positions, depends on its prefix only through the prefix’s multiset. A multiset has no order, but it has a size.

Proposition 1 (A causal layer counts but does not order).

(i) Suppose a causal attention layer’s scores are all equal, the value at position 00 is a vector ee (a beginning-of-sequence token’s), and every other value is 00. Then its output at position tt is ot=e/(t+1)o_t = e/(t+1), so t=1/⟨ot,e⟩−1t = 1/\langle o_t, e\rangle - 1 is recovered exactly from oto_t when ∥e∥=1\lVert e \rVert = 1.

(ii) In general, given the token at tt, one causal layer’s output at tt is a function of the multiset of its prefix. The multiset’s size is the position, and its order is invisible.

Proof.

For (i), equal scores make the weights uniform over the t+1t + 1 positions 0,…,t0, \dots, t, and only the value at position 00 is nonzero. For (ii), the attention topic’s Proposition 3 (ii) gives the dependence on the multiset, given the token at tt, and the number of its elements is a function of it.

∎

So the causal mask itself leaks position, as Haviv and colleagues (2022) observed: a causal stack without any positional encoding can write absolute position into its first layer’s output and use it in the second (Kazemnejad et al. 2023 give a construction). A single causal head cannot. On the task of the overview, where the target is the symbol on the most recent marked token, a head without positions sees a bag of tokens. Every ordering of a bag is equally likely, so the best it can do is guess the most frequent marked symbol. That reader’s accuracy, computed exactly by counting, is 0.5470.547 at length 3232 and 0.2340.234 at 256256; the trained heads without positions reach 0.5420.542 and 0.2370.237, matching it within sampling error at every length.


Position as a set of clocks

Let dd be even and split Rd\mathbb{R}^d into d/2d/2 coordinate planes j=0,…,d/2−1j = 0, \dots, d/2 - 1. Give plane jj the frequency ωj=b−2j/d\omega_j = b^{-2j/d}, for a base bb that is 10410^4 unless stated, so the frequencies fall geometrically from ω0=1\omega_0 = 1 to nearly 1/b1/b. Write R(φ)=(cos⁡φ−sin⁡φsin⁡φcos⁡φ)R(\varphi) = \bigl(\begin{smallmatrix} \cos\varphi & -\sin\varphi \\ \sin\varphi & \cos\varphi \end{smallmatrix}\bigr) for the rotation of a plane by the angle φ\varphi, J=R(π/2)J = R(\pi/2), and Rω(k)=⨁jR(kωj)R_\omega(k) = \bigoplus_j R(k\omega_j) for the block-diagonal rotation that turns plane jj by kωjk\omega_j.

Definition 1 (Absolute additive encoding).

An absolute additive encoding adds a vector p(m)∈Rdp(m) \in \mathbb{R}^d to the embedding of the token at position mm: the layer reads hm=xmE+p(m)h_m = x_m E + p(m). The code pp is either a learned table, one trained vector per position up to the training length and undefined beyond it, or a fixed function of mm.

Definition 2 (Sinusoidal code).

The sinusoidal code is

p(m)=(cos⁡mω0, sin⁡mω0, cos⁡mω1, sin⁡mω1, …, cos⁡mωd/2−1, sin⁡mωd/2−1).p(m) = \bigl(\cos m\omega_0,\ \sin m\omega_0,\ \cos m\omega_1,\ \sin m\omega_1,\ \dots,\ \cos m\omega_{d/2-1},\ \sin m\omega_{d/2-1}\bigr).

This is Vaswani and colleagues’ (2017) code. They put the sine first in each plane, which is a fixed reflection of every plane and changes no inner product. The attention topic’s circle features (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta) are its one-plane case. Picture plane jj as a clock whose hand points at angle mωjm\omega_j: the first hand turns one radian per position, the last almost not at all.

Proposition 2 (Shift is a rotation).

(i) For all integers mm and kk, p(m+k)=Rω(k) p(m)p(m + k) = R_\omega(k)\, p(m).

(ii) The map k↦Rω(k)k \mapsto R_\omega(k) is a homomorphism from Z\mathbb{Z} into the rotation group SO(d)SO(d): Rω(k)Rω(ℓ)=Rω(k+ℓ)R_\omega(k) R_\omega(\ell) = R_\omega(k + \ell) and Rω(k)⊤=Rω(−k)R_\omega(k)^\top = R_\omega(-k).

(iii) Every position lies on the same sphere, ∥p(m)∥2=d/2\lVert p(m) \rVert^2 = d/2.

(iv) The code is injective: p(m)=p(n)p(m) = p(n) only if m=nm = n.

Proof.

For (i), the angle-addition formulas give (cos⁡(m+k)ω,sin⁡(m+k)ω)=R(kω)(cos⁡mω,sin⁡mω)(\cos(m + k)\omega, \sin(m + k)\omega) = R(k\omega)(\cos m\omega, \sin m\omega) in each plane. For (ii), rotations of one plane compose by adding angles, and R(φ)⊤=R(−φ)R(\varphi)^\top = R(-\varphi); each block has determinant cos⁡2+sin⁡2=1\cos^2 + \sin^2 = 1. For (iii), each plane contributes cos⁡2+sin⁡2=1\cos^2 + \sin^2 = 1. For (iv), plane 00 alone has ω0=1\omega_0 = 1, so p(m)=p(n)p(m) = p(n) forces m−nm - n to be a multiple of 2π2\pi, which for integers means m=nm = n, since π\pi is irrational.

∎

Vaswani and colleagues chose the code because, they wrote, a shifted position is a linear function of the original; (i) is that claim, and the linear function is a rotation that does not depend on mm. In the language of Linear Systems (its Example 5), Rω(k)=exp⁡(kA)R_\omega(k) = \exp(kA) with the block-skew generator A=⨁jωjJA = \bigoplus_j \omega_j J. Since every Rω(k)R_\omega(k) is orthogonal, the inner product of two positions cannot depend on where they are.

Theorem 1 (The stationary kernel, and the logarithmic ruler).

(i) For all mm and nn, ⟨p(m),p(n)⟩=κd(n−m)\langle p(m), p(n) \rangle = \kappa_d(n - m), where

κd(Δ)=∑j=0d/2−1cos⁡(Δωj).\kappa_d(\Delta) = \sum_{j=0}^{d/2-1} \cos(\Delta\omega_j).

Every Gram matrix [κd(mi−mk)][\kappa_d(m_i - m_k)] is positive semidefinite, and Toeplitz over consecutive or evenly spaced positions, and (2/d)κd(Δ)=Ecos⁡(ΔΩd)(2/d)\kappa_d(\Delta) = E\cos(\Delta\Omega_d) is the characteristic function of a random frequency Ωd\Omega_d uniform on the dd points ±ωj\pm\omega_j.

(ii) Fix bb and Δ≠0\Delta \ne 0. As d→∞d \to \infty,

2d κd(Δ)  →  Ib(Δ)=Ci⁡(∣Δ∣)−Ci⁡(∣Δ∣/b)ln⁡b,\frac{2}{d}\,\kappa_d(\Delta) \;\to\; I_b(\Delta) = \frac{\operatorname{Ci}(\lvert\Delta\rvert) - \operatorname{Ci}(\lvert\Delta\rvert/b)}{\ln b},

where Ci⁡(x)=−∫x∞cos⁡t dt/t\operatorname{Ci}(x) = -\int_x^\infty \cos t\, dt/t is the cosine integral, and

∣Ib(Δ)−(1−γ+ln⁡∣Δ∣ln⁡b)∣≤1ln⁡b(2∣Δ∣+Δ24b2),\Bigl\lvert I_b(\Delta) - \Bigl(1 - \frac{\gamma + \ln\lvert\Delta\rvert}{\ln b}\Bigr) \Bigr\rvert \le \frac{1}{\ln b}\Bigl(\frac{2}{\lvert\Delta\rvert} + \frac{\Delta^2}{4b^2}\Bigr),

with γ\gamma Euler’s constant.

Proof.

For (i), angle subtraction gives cos⁡mωcos⁡nω+sin⁡mωsin⁡nω=cos⁡((n−m)ω)\cos m\omega \cos n\omega + \sin m\omega \sin n\omega = \cos((n - m)\omega) in each plane. A Gram matrix of vectors is positive semidefinite, since ∑i,kcickκd(mk−mi)=∥∑ici p(mi)∥2≥0\sum_{i,k} c_i c_k \kappa_d(m_k - m_i) = \lVert \sum_i c_i\, p(m_i) \rVert^2 \ge 0, and over consecutive or evenly spaced positions mi−mkm_i - m_k depends only on i−ki - k, which is the Toeplitz form. The characteristic-function form is the average of cos⁡(±Δωj)\cos(\pm\Delta\omega_j) over the dd points.

For (ii), write Ωd=±b−Ud\Omega_d = \pm b^{-U_d} with a fair sign and UdU_d uniform on the grid {0,2/d,…,1−2/d}\{0, 2/d, \dots, 1 - 2/d\}. The grid’s uniform law converges to the uniform law on [0,1][0, 1], so by continuous mapping Ωd\Omega_d converges in distribution to Ω=±b−U\Omega = \pm b^{-U}, UU uniform on [0,1][0, 1]. Since ω↦cos⁡(Δω)\omega \mapsto \cos(\Delta\omega) is bounded and continuous, Ecos⁡(ΔΩd)→Ecos⁡(ΔΩ)E\cos(\Delta\Omega_d) \to E\cos(\Delta\Omega). Substituting ω=b−u\omega = b^{-u}, so du=−dω/(ωln⁡b)du = -d\omega/(\omega \ln b), and then t=∣Δ∣ωt = \lvert\Delta\rvert\omega,

Ecos⁡(ΔΩ)=∫01cos⁡(Δb−u) du=1ln⁡b∫1/b1cos⁡(∣Δ∣ω)ω dω=1ln⁡b∫∣Δ∣/b∣Δ∣cos⁡tt dt=Ib(Δ).E\cos(\Delta\Omega) = \int_0^1 \cos(\Delta b^{-u})\, du = \frac{1}{\ln b}\int_{1/b}^1 \frac{\cos(\lvert\Delta\rvert\omega)}{\omega}\, d\omega = \frac{1}{\ln b}\int_{\lvert\Delta\rvert/b}^{\lvert\Delta\rvert} \frac{\cos t}{t}\, dt = I_b(\Delta).

For the bound, integration by parts gives Ci⁡(x)=sin⁡x/x−∫x∞sin⁡t dt/t2\operatorname{Ci}(x) = \sin x/x - \int_x^\infty \sin t\, dt/t^2, so ∣Ci⁡(x)∣≤2/x\lvert \operatorname{Ci}(x) \rvert \le 2/x. The integral form Ci⁡(x)=γ+ln⁡x−∫0x(1−cos⁡t) dt/t\operatorname{Ci}(x) = \gamma + \ln x - \int_0^x (1 - \cos t)\, dt/t (DLMF 6.2.12–13), with 0≤1−cos⁡t≤t2/20 \le 1 - \cos t \le t^2/2, gives Ci⁡(x)=γ+ln⁡x−ϵ\operatorname{Ci}(x) = \gamma + \ln x - \epsilon with 0≤ϵ≤x2/40 \le \epsilon \le x^2/4. Put x=∣Δ∣/bx = \lvert\Delta\rvert/b in the second and x=∣Δ∣x = \lvert\Delta\rvert in the first, and divide by ln⁡b\ln b.

∎

Two readings. First, by Herglotz’s theorem (Brockwell and Davis 1991, §4.3), every positive-definite function of an integer offset is the characteristic function of some measure on the circle, so a stationary position code is a choice of spectral measure. The sinusoidal code chooses dd atoms at geometric frequencies, and Rahimi and Recht’s (2007) random features, which the attention topic set aside for positive ones, would sample them instead. Positive definiteness, stationarity, and the spectral picture are the ones formalML builds for Gaussian processes (Gaussian Processes: positive definiteness is its Definition 2, and the other two come later in that article).

Second, (ii) says the similarity of two positions is a logarithmic ruler: past a few positions it is a straight line in ln⁡∣Δ∣\ln\lvert\Delta\rvert, and each doubling of the distance costs the same ln⁡2/ln⁡b≈0.075\ln 2/\ln b \approx 0.075 of similarity, because geometric frequencies give every octave of distance its own few planes. The notebook computes:

Δ\Delta11441616646425625610241024
d=64d = 640.9660.9660.7480.7480.6050.6050.4350.4350.3540.3540.2630.263
d=512d = 5120.9730.9730.7680.7680.6310.6310.4850.4850.3130.3130.1860.186
d=8192d = 81920.9740.9740.7710.7710.6350.6350.4870.4870.3350.3350.1850.185
limit Ib(Δ)I_b(\Delta)0.9740.9740.7720.7720.6350.6350.4870.4870.3350.3350.1850.185
ruler 1−(γ+ln⁡Δ)/ln⁡b1 - (\gamma + \ln\Delta)/\ln b0.9370.9370.7870.7870.6360.6360.4860.4860.3350.3350.1850.185

The convergence in dd is not uniform in Δ\Delta: at Δ=256\Delta = 256, d=512d = 512 is farther from the limit than d=64d = 64 is. Large offsets need many planes. Note also what the table says against a common claim. Stack the code’s vectors as the rows of a matrix PP. The Gram matrix of the positions is PP⊤=[κd(m−n)]PP^\top = [\kappa_d(m - n)], not a multiple of the identity, which is what the table shows. The columns are a separate matter, and P⊤PP^\top P is not diagonal either: at d=16d = 16 the largest cosine between two columns exceeds 0.9990.999 over 6464 positions and is still 0.7390.739 over 40964096. The orthogonality of sines and cosines (Fourier Series, its Theorem 1) holds for integer harmonics over a full period; these frequencies are geometric, and a window is not a period.

The kernel is stationary, but attention does not compare positions directly. A head with query map WQW_Q and key map WKW_K scores position tt against position jj by htMhj⊤/τh_t M h_j^\top/\tau, with M=WQWK⊤M = W_Q W_K^\top and τ=dk\tau = \sqrt{d_k}. With h=xE+ph = xE + p, the score is the sum of four terms, content against content, content against position, position against content, and p(t)Mp(j)⊤p(t) M p(j)^\top. Is that last term at least a function of the offset?

Theorem 2 (Which score matrices see only offsets).

Let ω0,…,ωd/2−1\omega_0, \dots, \omega_{d/2-1} be distinct numbers in (0,π)(0, \pi). For M∈Rd×dM \in \mathbb{R}^{d \times d}, the following are equivalent.

(a) p(m)⊤Mp(n)p(m)^\top M p(n) depends only on n−mn - m, for all integers mm and nn.

(a′) The same holds for all mm and nn in one window of d+1d + 1 consecutive integers.

(b) MM commutes with Rω(1)R_\omega(1).

(c) M=⨁j(ajI+cjJ)M = \bigoplus_j (a_j I + c_j J): block-diagonal, with one rotation-scaling block per plane.

The matrices in (c) form a dd-dimensional subspace of the d2d^2-dimensional space of score matrices. On it, p(m)⊤Mp(n)=∑j(ajcos⁡(Δωj)−cjsin⁡(Δωj))p(m)^\top M p(n) = \sum_j \bigl(a_j \cos(\Delta\omega_j) - c_j \sin(\Delta\omega_j)\bigr) with Δ=n−m\Delta = n - m, a trigonometric polynomial in the offset.

Proof.

Write g(m,n)=p(m)⊤Mp(n)g(m, n) = p(m)^\top M p(n) and R=Rω(1)R = R_\omega(1). By Proposition 2, g(m+1,n+1)=p(m)⊤R⊤MR p(n)g(m + 1, n + 1) = p(m)^\top R^\top M R\, p(n). So gg depends only on n−mn - m, which is to say g(m+1,n+1)=g(m,n)g(m + 1, n + 1) = g(m, n) for all mm and nn, exactly when p(m)⊤(R⊤MR−M)p(n)=0p(m)^\top (R^\top M R - M) p(n) = 0 for all mm and nn.

The vectors p(m)p(m), for any dd consecutive mm, span Rd\mathbb{R}^d. In complex coordinates their entries are e±imωje^{\pm i m\omega_j}, and the matrix [eimλ][e^{i m \lambda}] over dd consecutive mm and the dd distinct points eiλ=e±iωje^{i\lambda} = e^{\pm i\omega_j} is a Vandermonde matrix, hence invertible. So the condition holds on a window of d+1d + 1 positions, or on all of Z\mathbb{Z}, exactly when R⊤MR=MR^\top M R = M, that is, MR=RMMR = RM. This proves (a) ⇔ (a′) ⇔ (b).

For (b) ⇔ (c), RR has the dd distinct eigenvalues e±iωje^{\pm i\omega_j}, so a matrix commuting with it preserves each of its two-dimensional real eigenplanes, which are the coordinate planes. MM is then block-diagonal, and its block BjB_j commutes with the rotation R(ωj)R(\omega_j). Writing out BjR(ωj)=R(ωj)BjB_j R(\omega_j) = R(\omega_j) B_j with sin⁡ωj≠0\sin\omega_j \ne 0 forces Bj=(a−cca)=aI+cJB_j = \bigl(\begin{smallmatrix} a & -c \\ c & a \end{smallmatrix}\bigr) = aI + cJ. Conversely, aI+cJaI + cJ commutes with every rotation of its plane. The formula for the score follows by angle subtraction, since (cos⁡α,sin⁡α) J (cos⁡β,sin⁡β)⊤=sin⁡(α−β)(\cos\alpha, \sin\alpha)\, J\, (\cos\beta, \sin\beta)^\top = \sin(\alpha - \beta).

∎

The theorem says that adding a stationary code to the content does not make attention relative. The position-against-position term is relative only if the learned MM lands in a dd-dimensional subspace of a d2d^2-dimensional space, and the content-against-position terms are not relative at all (Ke, He, and Liu 2021). The relativity defect δ(M)=∥M−ΠM∥F/∥M∥F\delta(M) = \lVert M - \Pi M \rVert_F / \lVert M \rVert_F, with Π\Pi the orthogonal projection onto the subspace (keep each diagonal block’s (tr⁡B/2)I+((B21−B12)/2)J(\operatorname{tr} B/2) I + ((B_{21} - B_{12})/2) J, zero the rest), measures the miss. For a random Gaussian MM, ∥ΠM∥2/∥M∥2\lVert \Pi M \rVert^2 / \lVert M \rVert^2 has a Beta distribution with mean 1/d1/d, so E δ2=1−1/dE\,\delta^2 = 1 - 1/d, and at d=16d = 16 a random matrix has δ≈0.968\delta \approx 0.968. The three sinusoidal heads of the tournament, after training, have δ=0.971\delta = 0.971, 0.9550.955, and 0.9730.973. Training barely moved them: at initialization they were 0.9700.970, 0.9560.956, and 0.9790.979. Within the training window, nothing rewards relativity.

The attention topic’s trained circle denoiser is the opposite case. Its task was rotation-invariant, and it learned M=cIM = cI, which lies in the commutant of a single plane. Exactness is also fragile in another way: over a window short against the slow planes’ wavelengths, the window’s vectors are nearly dependent. The 1616-dimensional code over 6464 positions has numerical rank 1414. Its exact condition number falls from 3.69×10293.69 \times 10^{29} over 1616 positions, through 7.14×10187.14 \times 10^{18} over 6464, to 1.24×10111.24 \times 10^{11} over 256256 and 17.717.7 over 40964096. The first two are past what double precision resolves, so the notebook computes them in 200200-digit arithmetic. A window constrains a slow plane only once the window has watched it turn.


Relative position: biases and the ALiBi kernel

Since the score should depend on the offset, several schemes put the offset into the score directly.

Definition 3 (Relative-position schemes).

For a causal head scoring position tt against j≤tj \le t, with offset r=t−jr = t - j:

  • Shaw, Uszkoreit, and Vaswani (2018) add a learned vector to the key, stj=qt(kj+amin⁡(r,K))⊤/τs_{tj} = q_t (k_j + a_{\min(r, K)})^\top/\tau, one vector per offset up to a clip KK.
  • T5 (Raffel et al. 2020) adds a learned scalar βbucket(r)\beta_{\text{bucket}(r)}, with buckets that are exact for small offsets and logarithmically spaced up to 128128.
  • ALiBi (Press, Smith, and Lewis 2022) subtracts a fixed linear penalty, stj=qtkj⊤/τ−s rs_{tj} = q_t k_j^\top/\tau - s\,r, with slope s=2−8h/Hs = 2^{-8h/H} for head hh of HH.

T5’s buckets show the pattern of the section in miniature. With 3232 buckets, offsets below 1616 get their own bucket and the rest share log-spaced ones, the last of which holds every offset from 113113 on (the logarithmic map reaches it at 16⋅815/16≈112.416 \cdot 8^{15/16} \approx 112.4, not at 128128). Offsets that far back are indistinguishable. Transformer-XL (Dai et al. 2019) puts relative terms into the score in yet another way. ALiBi is the cleanest, because its penalty multiplies the attention topic’s kernel by a second kernel. Our single head uses s=1/2s = 1/2, ALiBi’s first slope at H=8H = 8.

Theorem 3 (ALiBi is a product kernel).

Let one causal ALiBi head with slope s>0s \gt 0 have content scores ctj=qtkj⊤/τc_{tj} = q_t k_j^\top/\tau lying in an interval of width WW. Write αr\alpha_r for the weight on offset rr from a fixed query tt.

(i) αtj∝ectj⋅e−s(t−j)\alpha_{tj} \propto e^{c_{tj}} \cdot e^{-s(t - j)}: a Nadaraya–Watson smoother whose kernel is the product of a content kernel and an exponential kernel in time. In bidirectional form, e−s∣t−j∣e^{-s\lvert t - j \rvert} is a positive-definite kernel, and so is its product with any positive-definite content kernel.

(ii) At every length, the weight on offsets r≥Dr \ge D is at most eWe−sD/(1−e−s)e^{W} e^{-sD}/(1 - e^{-s}).

(iii) For every offset rr, αr≤eW−sr α0\alpha_r \le e^{W - sr}\, \alpha_0. A key farther back than W/sW/s gets less weight than the query’s own position, whatever its content.

Proof.

Part (i) is the softmax of ctj−s(t−j)c_{tj} - s(t - j). The bidirectional kernel e−s∣u∣e^{-s\lvert u \rvert} is the Matérn kernel with smoothness 1/21/2, positive definite (Gaussian Processes, its Definition 3), and a product of positive-definite kernels is positive definite (that topic’s Proposition 2). The content kernel has to be one for this to apply. With WQ=WKW_Q = W_K the scores are a Gram matrix and ectje^{c_{tj}} is positive definite, but with WQ≠WKW_Q \ne W_K the matrix [ctj][c_{tj}] is not even symmetric, and only the time factor is a kernel in this sense. For (iii), αr/α0=ecr−c0−sr≤eW−sr\alpha_r/\alpha_0 = e^{c_r - c_0 - sr} \le e^{W - sr}, since the two content scores differ by at most WW. For (ii), sum (iii) over r≥Dr \ge D and use α0≤1\alpha_0 \le 1: the sum is at most eW∑r≥De−sr=eWe−sD/(1−e−s)e^{W} \sum_{r \ge D} e^{-sr} = e^{W} e^{-sD}/(1 - e^{-s}).

∎

Parts (ii) and (iii) are one inequality read two ways. Read as (ii), it is a guarantee: no matter how long the sequence, the head’s weight stays within a band of offsets fixed by WW and ss, so its behavior at length 10510^5 is its behavior at length 100100. That is why ALiBi extrapolates, and Chi and colleagues (2023) trace its length extrapolation to exactly such a bounded receptive field. Read as (iii), it is a limit: a key past the horizon W/sW/s is outweighed by the query’s own position, so the head cannot retrieve it on weight alone. The bound in (ii) is vacuous inside the horizon. With W=20W = 20 and s=1/2s = 1/2 it is 2.542.54 at D=40D = 40, then 1.15×10−41.15 \times 10^{-4} at 6060 and 5.24×10−95.24 \times 10^{-9} at 8080. Inside the horizon the content decides; past it the position does. In formalML’s terms, this is Nadaraya–Watson in time with bandwidth 1/s1/s (Kernel Regression, its Definition 2).


Rotations: RoPE

Theorem 2 says an added code makes the score relative only if MM is special. Rotary position embedding removes the condition by moving the code from the inputs to the queries and keys, and from addition to rotation.

Definition 4 (Rotary position embedding (RoPE)).

With frequencies θj=b−2j/d\theta_j = b^{-2j/d}, rotate the query at position mm and the key at position nn by their positions:

q~m=Rθ(m) qm,k~n=Rθ(n) kn,\tilde q_m = R_\theta(m)\, q_m, \qquad \tilde k_n = R_\theta(n)\, k_n,

and score ⟨q~m,k~n⟩/τ\langle \tilde q_m, \tilde k_n \rangle / \tau. In complex form, each plane’s coordinates zjz_j are multiplied by eimθje^{i m \theta_j}.

This is Su and colleagues’ (2024) RoPE. Its frequencies are Definition 2’s, so it is the sinusoidal code, applied by multiplication instead of addition.

Proposition 3 (RoPE is relative by construction, and isometric).

(i) ⟨Rθ(m)q,Rθ(n)k⟩=⟨q,Rθ(n−m)k⟩\langle R_\theta(m) q, R_\theta(n) k \rangle = \langle q, R_\theta(n - m) k \rangle.

(ii) ∥Rθ(m)q∥=∥q∥\lVert R_\theta(m) q \rVert = \lVert q \rVert.

(iii) For fixed qq and kk, the offset score s(Δ)=⟨q,Rθ(Δ)k⟩s(\Delta) = \langle q, R_\theta(\Delta) k \rangle is the trigonometric polynomial

s(Δ)=∑jρjcos⁡(Δθj+φj),s(\Delta) = \sum_j \rho_j \cos(\Delta\theta_j + \varphi_j),

with amplitudes ρj=∥qj∥ ∥kj∥\rho_j = \lVert q_j \rVert\, \lVert k_j \rVert and phases φj\varphi_j the angle from the component of qq in plane jj to that of kk.

Proof.

For (i), Rθ(m)⊤Rθ(n)=Rθ(−m)Rθ(n)=Rθ(n−m)R_\theta(m)^\top R_\theta(n) = R_\theta(-m) R_\theta(n) = R_\theta(n - m) by Proposition 2 (ii). Part (ii) holds because rotations are orthogonal. For (iii), in plane jj write qj=∥qj∥(cos⁡α,sin⁡α)q_j = \lVert q_j \rVert (\cos\alpha, \sin\alpha) and kj=∥kj∥(cos⁡β,sin⁡β)k_j = \lVert k_j \rVert (\cos\beta, \sin\beta). Then R(Δθj)kjR(\Delta\theta_j) k_j points at angle β+Δθj\beta + \Delta\theta_j, and its inner product with qjq_j is ∥qj∥∥kj∥cos⁡(Δθj+β−α)\lVert q_j \rVert \lVert k_j \rVert \cos(\Delta\theta_j + \beta - \alpha).

∎

Part (ii) matters for the kernel reading. The attention topic factored the kernel e⟨q,k⟩/τe^{\langle q, k \rangle/\tau} into a Gaussian in ∥q−k∥\lVert q - k \rVert times design weights e∥k∥2/2τe^{\lVert k \rVert^2/2\tau} (its Proposition 1). RoPE leaves every norm alone, so the design weights carry no position: RoPE moves only angles. A rotation applied to both vectors would preserve their inner product, as formalRAG uses for quantization (Optimized Product Quantization, its Theorem 1). RoPE applies different rotations to the two, and what survives is exactly the rotation by the offset.

Is RoPE one clever choice among many? The next theorem says it is the only linear one.

Theorem 4 (RoPE is the general linear relative encoding).

Let Lm∈Rd×dL_m \in \mathbb{R}^{d \times d}, for m∈Zm \in \mathbb{Z}, with L0=IL_0 = I. The following are equivalent.

(a) ⟨Lmq,Lnk⟩\langle L_m q, L_n k \rangle depends only on qq, kk, and n−mn - m, for all qq, kk, mm, and nn.

(b) Lm=UmL_m = U^m for some orthogonal matrix UU.

(c) There are an orthogonal QQ, angles θ1,…,θℓ∈(0,π)\theta_1, \dots, \theta_\ell \in (0, \pi), and integers p,p′≥0p, p' \ge 0 with

Lm=Q(⨁i=1ℓR(mθi)⊕Ip⊕(−1)mIp′)Q⊤.L_m = Q \Bigl( \bigoplus_{i=1}^{\ell} R(m\theta_i) \oplus I_p \oplus (-1)^m I_{p'} \Bigr) Q^\top.
Proof.

(a) ⇒ (b): The bilinear form ⟨Lmq,Lnk⟩=q⊤Lm⊤Lnk\langle L_m q, L_n k \rangle = q^\top L_m^\top L_n k determines the matrix Lm⊤LnL_m^\top L_n, so (a) says Lm⊤Ln=G(n−m)L_m^\top L_n = G(n - m) for some function GG. Taking m=nm = n gives Lm⊤Lm=G(0)=L0⊤L0=IL_m^\top L_m = G(0) = L_0^\top L_0 = I, so every LmL_m is orthogonal. Taking m=0m = 0 gives G(k)=LkG(k) = L_k. Then Lm⊤Lm+k=LkL_m^\top L_{m+k} = L_k, so Lm+k=LmLkL_{m+k} = L_m L_k, and by induction Lm=L1mL_m = L_1^m for all mm, with U=L1U = L_1.

(b) ⇒ (c): An orthogonal matrix is normal, and its real normal form (Horn and Johnson 2013, §2.5) is U=Q(⨁iR(θi)⊕Ip⊕(−Ip′))Q⊤U = Q (\bigoplus_i R(\theta_i) \oplus I_p \oplus (-I_{p'})) Q^\top with QQ orthogonal and θi∈(0,π)\theta_i \in (0, \pi). Raise it to the mm-th power.

(c) ⇒ (a): Lm⊤Ln=Q (⨁iR((n−m)θi)⊕Ip⊕(−1)n−mIp′) Q⊤L_m^\top L_n = Q\,(\bigoplus_i R((n - m)\theta_i) \oplus I_p \oplus (-1)^{n-m} I_{p'})\, Q^\top, a function of n−mn - m.

∎

The orthogonal QQ is absorbed by the learned maps WQW_Q and WKW_K, so up to the projections every linear encoding that makes scores relative is RoPE with some frequencies. It may also leave planes unrotated, as partial rotary embeddings do, or flip a coordinate’s sign at every step, since Ip′I_{p'} can have odd size. RoPE’s only free choice is the spectrum, and it takes Definition 2’s. Su and colleagues derive the two-dimensional case under further assumptions on the encoding; (b) needs none.

Su and colleagues also argue that RoPE gives a “long-term decay” of scores with distance. The argument is a bound, and it is worth seeing exactly what it bounds.

Proposition 4 (What long-term decay means).

In complex form, let hj=qˉjkjh_j = \bar q_j k_j for planes j=0,…,d/2−1j = 0, \dots, d/2 - 1, let hd/2=0h_{d/2} = 0, and let Sj=∑l<jeiΔθlS_j = \sum_{l \lt j} e^{i\Delta\theta_l}. The offset score is s(Δ)=Re⁡∑jhjeiΔθjs(\Delta) = \operatorname{Re} \sum_j h_j e^{i\Delta\theta_j}.

(i) ∣∑jhjeiΔθj∣≤(max⁡j∣hj+1−hj∣)∑j=1d/2∣Sj∣\bigl\lvert \sum_j h_j e^{i\Delta\theta_j} \bigr\rvert \le \bigl(\max_j \lvert h_{j+1} - h_j \rvert\bigr) \sum_{j=1}^{d/2} \lvert S_j \rvert.

(ii) If q=kq = k and each plane has E∥qj∥2=σ2E\lVert q_j \rVert^2 = \sigma^2, then E⟨q,Rθ(Δ)q⟩=σ2κd(Δ)E\langle q, R_\theta(\Delta) q \rangle = \sigma^2 \kappa_d(\Delta).

(iii) If qq and kk are independent, and the planes of kk are independent and each rotation-invariant in distribution, then the distribution of ⟨q,Rθ(Δ)k⟩\langle q, R_\theta(\Delta) k \rangle does not depend on Δ\Delta.

Proof.

For (i), sum by parts: ∑jhj(Sj+1−Sj)=−∑jSj+1(hj+1−hj)\sum_{j} h_j (S_{j+1} - S_j) = -\sum_{j} S_{j+1}(h_{j+1} - h_j), since S0=0S_0 = 0 and hd/2=0h_{d/2} = 0, and bound each term. For (ii), u⊤R(φ)u=∥u∥2cos⁡φu^\top R(\varphi) u = \lVert u \rVert^2 \cos\varphi in each plane, so the expectation is ∑jσ2cos⁡(Δθj)\sum_j \sigma^2 \cos(\Delta\theta_j). For (iii), independence lets each plane turn on its own, so Rθ(Δ)kR_\theta(\Delta) k has the same distribution as kk, and it is independent of qq.

∎

The bound in (i) depends on Δ\Delta through the envelope ∑j∣Sj∣\sum_j \lvert S_j \rvert, which falls with distance on average. At d=128d = 128 its mean over each octave of Δ\Delta falls from 20182018 at Δ=1\Delta = 1 to 312312 over offsets 20482048 to 40954095, or from 31.531.5 to 4.94.9 per plane, though not monotonically within an octave. That is a measurement, not a theorem. The independence in (iii) is needed: take d=4d = 4, k0=k1=(cos⁡β,sin⁡β)k_0 = k_1 = (\cos\beta, \sin\beta) with β\beta uniform, and q=(1,0,1,0)q = (1, 0, 1, 0). Each plane of kk is rotation-invariant, but the score has variance 1+cos⁡(Δ(θ0−θ1))1 + \cos(\Delta(\theta_0 - \theta_1)). Parts (ii) and (iii) say what the envelope is about. A key that matches its query decays as Theorem 1’s logarithmic ruler, and a key unrelated to its query does not decay at all. “Long-term decay” is a property of envelopes and matched pairs, and a trained head decays only where it has learned to.


Past the training window

Now train. The task needs both content and order. Each sequence holds n−1n - 1 tokens, each carrying one of 88 symbols and, with probability 0.10.1, a mark; a query token ends the sequence, and the target is the symbol on the most recent marked token. One causal head of width d=16d = 16 reads it at the query, with each of five schemes: no position, the added sinusoidal code, an added learned table, RoPE, and ALiBi. Each is trained from scratch in NumPy with hand-written gradients for 1,5001{,}500 Adam steps at length 3232, three seeds per scheme, and tested on 2,0002{,}000 fresh sequences at each length. Accuracy, as the mean of three seeds:

scheme3264128256
no position0.5420.5420.3670.3670.2860.2860.2370.237
sinusoidal, added0.9960.9960.2010.2010.1340.1340.1420.142
learned table, added0.9890.989———
RoPE1.0001.0000.9470.9470.8720.8720.4660.466
ALiBi0.9990.9990.9790.9790.9780.9780.9780.978

Every scheme but the first reads the task within the window. Past it, the learned table has nothing to say, and the added sinusoidal code collapses at twice the length: its trained score depends on absolute position, and the absolute positions are new. Theorem 2 accounts for one part of that dependence, not all of it. Replace only the position-against-position term with its projection onto the commutant, and the head still reads 0.2020.202, 0.1360.136, and 0.1430.143 at 6464, 128128, and 256256, because the position-against-content term separates keys as strongly: at length 3232 their spreads across keys are within 6%6\% of each other in every seed. Training always put the query at position 3131. Shift a long sequence so that the query sits there again, keeping every offset, and the head reads 0.7690.769 at 6464, but only 0.3130.313 at 256256, where older keys land on positions training never saw. ALiBi holds, as Theorem 3 (ii) predicts. RoPE degrades steadily, from 0.9470.947 to 0.4660.466, and at 256256 its three seeds range from about 0.310.31 to 0.680.68.

Why does a relative encoding fail to generalize in length? Because “relative” constrains the score to be a function of the offset, not to be a sensible one. Training sees offsets 00 to 3131 only. By Proposition 3 (iii), the head’s score for a marked token at offset rr is a trigonometric polynomial, and training pins it down on [0,31][0, 31] alone. In seed 00 the score falls from 114.10114.10 at r=1r = 1 to a first trough of 5.915.91 at r=34r = 34, as the task rewards. Past the window it dives to −55.86-55.86 at r=90r = 90, and only then climbs, to 84.1484.14 at r=181r = 181, higher than the score of any recent marked token sixteen or more back. All three seeds behave alike: first troughs at 3232 to 3434, deepest points of −55.86-55.86, −38.96-38.96, and −19.39-19.39 at 8989 to 9090, peaks at 181181 to 182182, and the largest amplitude in plane 33. The census in Theorem 5 explains the shape. Only planes 00 and 11 turn a whole circle in 3232 positions, so the head carries its sense of recency in planes 22 and 33, whose wavelengths, 62.862.8 and 198.7198.7, are long enough that half a turn spans the window. A causal head reads the score at Δ=−r\Delta = -r, so where a plane bottoms depends on its trained phase, not on its half wavelength of 31.431.4 alone. Plane 22 bottoms near r=27r = 27 in seed 00, and plane 33, still falling, carries the sum to the first trough. One turn later plane 22 bottoms again, near r=90r = 90, which is the dive. After three turns of plane 22 (188.5188.5 positions) and one of plane 33 (198.7198.7), the two come back toward phase, and both crest near r=180r = 180.

The fixes that practitioners use to extend RoPE’s context change the angles the head sees.

Definition 5 (Context-extension maps).

To read a head trained at length LL on length L′=κLL' = \kappa L:

  • Position interpolation (PI; Chen et al. 2023) maps positions m↦m/κm \mapsto m/\kappa.
  • NTK-aware scaling (bloc97 2023) changes the base, b↦b κd/(d−2)b \mapsto b\,\kappa^{d/(d-2)}.
  • YaRN (Peng et al. 2024) gives plane jj the frequency (1−γj)θj/κ+γjθj(1 - \gamma_j)\theta_j/\kappa + \gamma_j\theta_j, where γj\gamma_j rises linearly from 00 to 11 as L/λjL/\lambda_j, the number of turns the plane made in training, goes from 11 to 3232. It also multiplies the scores by (0.1ln⁡κ+1)2(0.1 \ln\kappa + 1)^2.

Theorem 5 (Wavelength census and rescalings).

Let λj=2π/θj\lambda_j = 2\pi/\theta_j be the wavelength of plane jj.

(i) Over the training offsets 0,…,L−10, \dots, L - 1, plane jj turns through a whole circle exactly when (L−1)θj≥2π(L - 1)\theta_j \ge 2\pi. Any other plane sees only the arc [0,(L−1)θj][0, (L - 1)\theta_j], and past LL it produces angles the head never saw.

(ii) PI maps test offsets 0,…,κL−10, \dots, \kappa L - 1 into [0,L−1/κ][0, L - 1/\kappa], within one position of the trained range, and shrinks the angle between neighbors κ\kappa-fold in every plane.

(iii) NTK-aware scaling gives plane jj the frequency θjκ−2j/(d−2)\theta_j \kappa^{-2j/(d-2)}: plane 00 is unchanged, and the slowest plane is divided by exactly κ\kappa.

(iv) For a(Δ)=Re⁡∑jhjeiΔθja(\Delta) = \operatorname{Re} \sum_j h_j e^{i\Delta\theta_j}, which with Proposition 4’s hjh_j is the offset score, and integers Δ1<Δ2\Delta_1 \lt \Delta_2, the linear interpolation ℓ\ell of aa between them satisfies

∣a(Δ)−ℓ(Δ)∣≤12(Δ−Δ1)(Δ2−Δ)∑j∣hj∣θj2for Δ1≤Δ≤Δ2,\lvert a(\Delta) - \ell(\Delta) \rvert \le \tfrac{1}{2} (\Delta - \Delta_1)(\Delta_2 - \Delta) \sum_j \lvert h_j \rvert \theta_j^2 \quad\text{for } \Delta_1 \le \Delta \le \Delta_2,

and ∑jθj2=(1−b−2)/(1−b−4/d)\sum_j \theta_j^2 = (1 - b^{-2})/(1 - b^{-4/d}).

Proof.

Part (i): the angles rθjr\theta_j for r=0,…,L−1r = 0, \dots, L - 1 sweep the arc [0,(L−1)θj][0, (L - 1)\theta_j], which is a whole circle exactly when its length reaches 2π2\pi. Part (ii): the largest test offset maps to (κL−1)/κ=L−1/κ(\kappa L - 1)/\kappa = L - 1/\kappa, and neighbors differ by θj/κ\theta_j/\kappa in plane jj. Part (iii): (bκd/(d−2))−2j/d=b−2j/dκ−2j/(d−2)(b\kappa^{d/(d-2)})^{-2j/d} = b^{-2j/d} \kappa^{-2j/(d-2)}, which is 11 times θ0\theta_0 at j=0j = 0 and θd/2−1/κ\theta_{d/2-1}/\kappa at j=d/2−1j = d/2 - 1. Part (iv): the interpolation remainder is a(Δ)−ℓ(Δ)=12a′′(ξ)(Δ−Δ1)(Δ−Δ2)a(\Delta) - \ell(\Delta) = \tfrac{1}{2} a''(\xi)(\Delta - \Delta_1)(\Delta - \Delta_2) for some ξ\xi between Δ1\Delta_1 and Δ2\Delta_2, and ∣a′′∣=∣Re⁡∑jhj(iθj)2eiξθj∣≤∑j∣hj∣θj2\lvert a'' \rvert = \lvert \operatorname{Re} \sum_j h_j (i\theta_j)^2 e^{i\xi\theta_j} \rvert \le \sum_j \lvert h_j \rvert \theta_j^2. The sum ∑jb−4j/d\sum_j b^{-4j/d} is geometric.

∎

At d=16d = 16 and L=32L = 32 the wavelengths are 6.36.3, 19.919.9, 62.862.8, 198.7198.7, 628.3628.3, 19871987, 62836283, and 1986919869, so two planes of eight complete a turn. PI keeps every angle in range at a cost in resolution. NTK-aware scaling keeps the fast planes’ resolution and interpolates the slow ones. At κ=4\kappa = 4 its per-plane factors run 11, 0.8200.820, 0.6730.673, 0.5520.552, 0.4530.453, 0.3710.371, 0.3050.305, and 0.2500.250. YaRN, at this small dd, is nearly PI: its factors are 0.3490.349, 0.2650.265, then 0.250.25 in every other plane.

Part (iv) is the reason interpolation is safer than extrapolation. Between trained positions the score is pinned by its curvature, and past them nothing pins it, so ∣a∣\lvert a \rvert can reach ∑j∣hj∣\sum_j \lvert h_j \rvert. Chen and colleagues (2023, their Theorem 2.1) state this bound with the constant d/(4ln⁡b)d/(4\ln b) in place of ∑jθj2\sum_j \theta_j^2. Their proof bounds 1/(1−b−4/d)1/(1 - b^{-4/d}) by d/(4ln⁡b)d/(4\ln b) using cx≤1+xln⁡cc^x \le 1 + x\ln c for x<0x \lt 0, which is the reverse of what convexity gives, so the stated constant is too small. It is 2.562.56 times too small at d=16d = 16 and 1.151.15 times at d=128d = 128. The stated bound then fails: for hj=1h_j = 1 on [0,1][0, 1] at Δ=1/2\Delta = 1/2, the interpolation error at d=128d = 128 is 0.4590.459, while the stated bound is 0.4340.434 and the corrected one is 0.5000.500. With the corrected constant, their conclusion, that interpolated scores are far more stable than extrapolated ones, stands.

Re-reading the trained RoPE heads with each map, with no further training:

RoPE head read with64128256
nothing0.9470.9470.8720.8720.4660.466
PI0.9980.9980.9800.9800.9170.917
NTK-aware0.9700.9700.9660.9660.9770.977
YaRN0.9980.9980.9790.9790.9140.914

Each map rescues the head, and on this task NTK-aware scaling rescues it best at 256256, where its 0.9770.977 ties ALiBi’s 0.9780.978 within sampling error on the same test sequences: it stretches the slow planes just enough to push the rebound past the longest sequence while keeping the fast planes sharp. The next section’s task ranks them differently.


Kernels over offsets, side by side

The laboratory has two figures. Figure A is the geometry. Drag two positions and watch the clocks of the sinusoidal code turn, then lock the offset and see the kernel stay put. The ruler view compares the kernel at three dimensions with its limit, and the last view shows a trained sinusoidal head’s score drifting with absolute position where a relative one would be flat. Figure B is the training. It shows the tournament with every scheme’s learned score against offset, the wavelength census with each rescaling’s factor per plane, and one held-out filing from the case study below, with every reader’s answer at every position.

A · Clocks and kernels — the sinusoidal code, the kernel it induces, and what a learned score does with it
m = 3
n = 10
plane 0plane 1plane 2plane 3plane 4plane 5plane 6plane 7
hand at mhand at n
offset n − m
7
⟨p(m), p(n)⟩ / (d/2)
0.737

Plane j turns at rate b^(−2j/d): the first hand at one radian per step, the last almost not at all. Lock the offset and move either slider: every hand turns, each by its own rate, and the readout does not move. The inner product of two positions depends only on how far apart they are (Proposition 2 and Theorem 1).


B · Past the training window — heads trained at 32 tokens, read longer
00.250.50.7513264128256accuracy on the cue task (mean of 3 seeds)test length (log scale) · trained at 32
NoPEsinusoidal (absolute)learned table (absolute)RoPEALiBiRoPE + PIRoPE + NTK-awareRoPE + YaRN
seen in training-5005010003264128192255RoPE: score for a cue at offset r (seed 0)offset r back from the query
RoPE at 32
1.000
RoPE at 64
0.947
RoPE at 128
0.872
RoPE at 256
0.466
score at r = 1
114.10
score at r = 31, the window's edge
7.70
it rises again: highest score past the window
84.14 at r = 181

Training only sees offsets 0 to 31. The RoPE head's score is a trigonometric polynomial in r (Proposition 3): it falls across the window, as the task rewards, dives past it, and then the planes that never completed a turn bring it back up, until a cue 181 positions back outscores a recent one. ALiBi's score is a straight line down. The absolute codes' curves are drawn for a query at the end of a 256-token sequence; the learned table has nothing past 31.


Finance case study: which company was named last?


Where this goes next

  • The transformer block. Proposition 1’s counter is one way a causal stack writes position into its residual stream, and a block runs many heads, which can carry many slopes and many frequencies at once. The transformer-block topic assembles them.
  • Contextual embeddings. BERT adds a learned table (Definition 1), which is undefined past its length. The contextual-embeddings topic trains with it.
  • Long contexts. formalRAG’s long-context topic models a passage buried in a long context as softly erased (its Proposition 3). Theorem 3’s horizon is one mechanism for such burial, a recency kernel under which far tokens weigh less than near ones, though not the only one, and this page does not model that topic’s U-curve.
  • Graphs and grids. On a cycle the sinusoids are the eigenvectors of the shift, and a stationary kernel is diagonalized by the discrete Fourier basis, as for the abelian Cayley graphs of formalML’s expander-graphs topic (its Proposition 2).

Honest caveats


Implementation

The companion notebook (notebookPath) imports positional_encodings_geometry.py, which owns every number on this page. That module imports the attention topic’s module for its attention function and its harness conventions, the neural-language-models topic’s gradient checker and Adam constants, and the shared finance corpus. It trains 2727 single-head models from scratch in NumPy, 1515 for the tournament and 1212 for the filings, and runs a harness of 2424 assertion-based tests in about half a minute on a laptop CPU. The tests cover:

  • Proposition 1 exactly, and the heads without positions against the best multiset reader, computed exactly.
  • Proposition 2 and Theorem 1 on random instances, the cosine-integral limit at d=8192d = 8192, and the logarithmic ruler.
  • Theorem 2: the window’s null space at random frequencies, a random matrix’s defect, the trained heads’ defects before and after training, and the condition numbers in 200200-digit arithmetic; what projecting one term and moving the query do to the added code.
  • T5’s buckets, and Theorem 3 on random instances up to length 81928192.
  • Proposition 3 against the attention topic’s attention function; Theorem 4 through scipy’s real Schur form; Proposition 4 by Monte Carlo, including the counterexample that makes (iii) need independent planes.
  • Theorem 5’s census and rescalings, the interpolation bound on random instances, and the counterexample to the stated constant.
  • Every hand-written gradient against central differences; the tournament, the RoPE rebound through its dive, and the filings, including the one-pass filing reader against the plain forward pass at every position and the case study’s one filing.

The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.

References & Further Reading