Positional encoding: how attention represents order and distance
Positional encoding supplies coordinates to a model that otherwise attends primarily by content. Three common mechanisms are adding a vector to the token embedding, rotating queries and keys, or adding a distance-dependent bias to attention scores. They act at different places in the computation and are not interchangeable checkpoint settings.
Why order needs an explicit explanation
For unmasked self-attention with shared projections and no position-dependent terms, permuting token rows permutes the output rows in the same way. This is permutation equivariance, not identical output at every position. A permutation-invariant pooling operation would then lose sequence order. A fixed causal mask breaks arbitrary permutation symmetry and already provides some ordering information, so “attention without positional embeddings can never represent order” is too strong.
Write the attention computation for one head as:
Here $p$ is a query position, $q$ is a key position, and $d_h$ is the head dimension. The symbols $q_p$ and $k_q$ denote vectors; the subscript specifies their position. The mask is zero for allowed pairs and negative infinity for forbidden pairs in the mathematical definition. Padding and packed-sequence boundaries require masking in addition to position IDs. At least one key must be permitted for each evaluated softmax row, or the implementation must define a special all-masked-row policy.
1. Sinusoidal and learned absolute positions
For even embedding dimension $d$, the original fixed sinusoidal scheme uses paired frequencies:
The index runs from zero through $d/2-1$. Position is added to a token representation of the same width. In the original Transformer, token embeddings were scaled by $\sqrt d$ before adding the positional vector. Other architectures need not use that scaling.
A learned absolute scheme instead stores a trainable table with one row per supported position. A table of length $L$ and width $d$ contains $Ld$ positional parameters. An unseen index needs a deliberate extension strategy; increasing a configuration limit does not create trained table rows. Fixed sinusoids can be evaluated at new positions, but this mathematical availability does not guarantee quality beyond trained lengths.
2. RoPE: relative displacement through rotations
RoPE applies rotations to pairs of query and key coordinates. For one pair, define:
For frequency $\omega$, query position $p$ and key position $q$:
Orthogonality and composition of rotations give the central identity:
The positional factor depends on relative displacement. Content vectors still matter: this does not mean the whole attention score is a function of distance alone. With fixed content vectors and fixed frequencies, shifting both positions by the same offset preserves their rotated dot product.
svg
The illustration uses a single frequency of 0.4 radians per position and identical unit content vectors. Moving from positions 2 and 5 to positions 7 and 10 rotates both vectors by the same additional angle. Their separation stays 1.2 radians and their dot product stays approximately 0.362358. These are teaching values, not a recommended production frequency schedule.
For an even rotary width $d_r$, a common schedule is $\omega_i=\theta^{-2i/d_r}$. The base $\theta$, rotary width, coordinate pairing and scaling scheme are part of the checkpoint contract. Some implementations pair adjacent coordinates; others pair two halves of the vector. Both layouts can implement rotations, but changing layouts without the corresponding weight/layout conversion changes the model.
Partial RoPE rotates only the selected even-width subspace. Preserve the remaining coordinates. Standard RoPE rotates queries and keys rather than values. Each pair preserves its Euclidean norm in exact arithmetic. This property and common-shift invariance are useful implementation checks, but neither proves that a language model extrapolates reliably.
3. Relative biases and ALiBi
Relative-position methods are a family. Learned scalar buckets add a bias according to a distance bucket; vector-based relative attention can also depend on query content. A bucket limit merges distances rather than preserving every exact displacement.
For causal ALiBi, head $h$ uses a positive slope $s_h$ and penalizes allowed keys by their distance behind the query:
Future keys are still masked. In this convention the bias is added after scaling the content dot product. Different heads have different fixed slopes. At query position 5, slope 0.25 and key positions 2, 4 and 5 give biases -0.75, -0.25 and 0. With equal content scores, nearer allowed keys receive larger probabilities. ALiBi supplies a distance prior; it does not guarantee correct reasoning at arbitrary lengths.
KV-cache positions are logical coordinates
During incremental decoding, the new query and key must use the same logical position they would have used in a full causal forward pass. A cache slot is a storage address, not necessarily a position ID. A sliding or ring buffer can reuse a slot while logical positions continue increasing.
If the cache stores already-rotated keys, rotate each new key once and reuse old keys unchanged under the same positional scheme. Double rotation or a different frequency schedule at decoding changes the scores. Cached keys produced under one scaling policy cannot simply be reused under another; rebuild them or apply a validated conversion. Moving the common origin requires a consistent transformation of all relevant rotated keys and queries.
Left padding must follow the model's position-ID convention, with padding masked out. Packed samples need segment-aware masks; resetting position IDs alone does not prevent cross-sample attention. For images, row and column coordinates can be allocated separate channels or rotary subspaces; flattening order and resolution changes must be specified. Multimodal coordinates likewise require an explicit mapping, not just a longer one-dimensional counter.
Length extension is a model change to validate
A simple position-interpolation example replaces position $p$ by $p/s$ for a scale $s>1$, compressing the range of angles. Other methods alter frequencies or mix scaling rules. These choices change the geometry seen by the model and may require adaptation or fine-tuning. Specify the exact scheme and compare quality at short, trained and extended lengths. Do not infer usable context length from successful memory allocation.
Numerical lab — Python standard library
import math
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def rotate(x, angle):
c, s = math.cos(angle), math.sin(angle)
return [c*x[0]-s*x[1], s*x[0]+c*x[1]]
def close(a, b):
assert abs(a-b) < 1e-12, (a, b)
def softmax(x):
z = max(x)
e = [math.exp(a-z) for a in x]
return [a/sum(e) for a in e]
q, k, w = [0.7, -0.2], [-0.3, 1.1], 0.4
for p, j in [(0, 0), (2, 5), (5, 2), (17, 3)]:
rq, rk = rotate(q, p*w), rotate(k, j*w)
close(dot(rq, rq), dot(q, q))
close(dot(rk, rk), dot(k, k))
close(dot(rq, rk), dot(q, rotate(k, (j-p)*w)))
close(dot(rq, rk), dot(rotate(q, (p+7)*w), rotate(k, (j+7)*w)))
u = [1.0, 0.0]
for p, j in [(2, 5), (7, 10)]:
close(dot(rotate(u, p*w), rotate(u, j*w)), math.cos(1.2))
assert abs(math.cos(1.2)-0.3623577544766736) < 1e-14
assert [-0.25*(5-j) for j in [2, 4, 5]] == [-0.75, -0.25, 0.0]
prob = softmax([-0.75, -0.25, 0])
assert prob[0] < prob[1] < prob[2]
for i in range(4):
omega = 10000**(-2*i/8)
close(math.sin(0*omega), 0)
close(math.cos(0*omega), 1)
# Single head, two coordinates, scalar values; causal attention.
qs = [[0.2+i/5, -0.4+i/7] for i in range(6)]
ks = [[0.8-i/9, 0.1+i/6] for i in range(6)]
vs = [0.5, -1.0, 2.0, 0.2, 1.1, -0.7]
full = []
for p in range(len(qs)):
scores = [dot(rotate(qs[p], p*w), rotate(ks[j], j*w))/math.sqrt(2) for j in range(p+1)]
full.append(dot(softmax(scores), vs[:p+1]))
cache, cached = [], []
for p in range(len(qs)):
cache.append(rotate(ks[p], p*w))
rq = rotate(qs[p], p*w)
scores = [dot(rq, key)/math.sqrt(2) for key in cache]
cached.append(dot(softmax(scores), vs[:p+1]))
for a, b in zip(full, cached):
close(a, b)
wrong = [dot(rotate(qs[-1], 5*w), rotate(key, j*w))/math.sqrt(2) for j, key in enumerate(cache)]
assert abs(dot(softmax(wrong), vs)-full[-1]) > 1e-3
print('Illustrated dot product:', round(math.cos(1.2), 6))
print('ALiBi probabilities:', [round(a, 6) for a in prob])
print('Full/cache maximum error:', max(abs(a-b) for a, b in zip(full, cached)))
print('All positional encoding checks passed.')The lab verifies sinusoidal values at zero, RoPE norm preservation, the signed relative-rotation identity, common-offset invariance, the illustrated dot product, ALiBi penalties, and full-versus-cached causal attention for fixed projected queries, keys and values. It deliberately checks that rotating a cached key twice changes the result. This is a single-head reference; full-model logit parity, padding, packed segments and production-kernel precision still require separate integration tests.
Implementation and performance checks
Start with explicit shapes and a full-precision reference. Check pair layout, even rotary width, untouched dimensions, large position indices, masks, offsets and frequency generation precision. Compare full-prefill logits with token-by-token cached logits using the same checkpoint and a declared tolerance. Exercise left and right padding, segment boundaries, cache eviction and maximum trained length.
Rotations and bias generation can be fused into attention kernels, but performance depends on precision, tensor shapes and memory traffic. Avoid materializing a full quadratic bias matrix when the chosen kernel can generate it internally. Benchmark quality and latency at the target length distribution; retrieval at one distance is not a complete long-context evaluation. Preserve the checkpoint's positional method when reproducing it, and treat alternative methods as controlled architectural experiments.
Sources and implementation references
Vaswani et al., Attention Is All You Need (2017): https://arxiv.org/abs/1706.03762
Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding (2021): https://arxiv.org/abs/2104.09864
Press et al., Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation (2021): https://arxiv.org/abs/2108.12409
Shaw et al., Self-Attention with Relative Position Representations (2018): https://arxiv.org/abs/1803.02155
Chen et al., Extending Context Window of Large Language Models via Positional Interpolation (2023): https://arxiv.org/abs/2306.15595