Positional encoding: give order a coordinate
位置编码
Derive sinusoidal shifts and separate computable positions from reliable extrapolation.
positional-encodingThe same words can describe different events
“Dog bites person” and “Person bites dog” contain the same words. A model that treats the input only as a bag cannot distinguish their roles. Content-only self-attention moves its outputs along with a permutation of its inputs. It does not create an independent sense of which slot came first.
The Transformer paper adds a position vector to every token embedding. Positions can come from a learned table or a fixed formula. This chapter studies absolute positions and their sinusoidal form; Shaw and colleagues instead represent relationships between pairs of positions. Read self-attention and inner products first.
A coordinate is useful only through what the model learns from it
Let X contain one token vector per row and Π be a permutation matrix. For content-only attention F, permuting the queries, keys and values together permutes the output in the same way:
The reason is that the score matrix is permuted on both axes; row-wise softmax and weighted aggregation respect those permutations. This statement assumes no fixed causal mask or other position-dependent operation. A causal mask already distinguishes which positions can read which others, so it breaks the unrestricted permutation symmetry even without added position vectors.
An absolute position vector p_i is attached to slot i. With row-vector embeddings e_i and projection matrices W_Q and W_K, the attention score expands into four terms:
The terms express content-content, content-position, position-content and position-position interactions. Adding a position vector therefore does not force attention to be a pure function of relative distance. Even if the position-position term has a clean shift identity, the two cross terms need not.
For even width d, sinusoidal encoding assigns a sine/cosine pair to each frequency:
Here PE(p) is written as a column vector; its transpose supplies an input row. The implementation uses d=8 and base 10000. Different frequencies provide coordinates that change at different rates. No position parameter is trained. A learned table instead stores an independent vector for each supported index; the BERT implementation checks that the sequence fits within its configured table before slicing the required rows.
For one frequency, the sine and cosine angle-addition identities yield a linear shift operator. Applied to a column pair, the signs are:
Stack these two-by-two blocks to shift a full encoding. The signs depend on the order [sin, cos]; the familiar rotation matrix for [x, y] uses a different convention. For pure sinusoidal vectors, their dot product and norm follow directly:
This identity concerns the raw position vectors. Arbitrary learned projections and interactions with token content do not inherit it automatically. Likewise, a formula being defined at position 1000 does not show that a model trained only through position 100 will make useful predictions there.
To isolate that distinction, fit a scalar position readout on four positions using the minimum-norm least-squares solution:
P_T contains the training encodings as rows, and t contains their position numbers. There are eight coefficients but only four training examples. The pseudoinverse chooses a particular interpolating solution; the training data do not guarantee how it behaves beyond those positions.
Shift, permute and extrapolate
Save as positional_encoding.py; Python 3 and NumPy are sufficient.
"""Original sinusoidal/additive-position experiment; no length generalization claim."""
import json
import numpy as np
def sinusoidal(positions, width=8, base=10000.):
p = np.asarray(positions, dtype=float)
if p.ndim != 1 or not 1 <= p.size <= 128 or not np.isfinite(p).all():
raise ValueError('bounded finite position vector required')
if not isinstance(width, int) or width < 2 or width > 128 or width % 2 or not np.isfinite(base) or base <= 1:
raise ValueError('even width 2..128 and finite base>1 required')
f = base ** (-np.arange(0, width, 2) / width)
out = np.empty((len(p), width));out[:, 0::2] = np.sin(p[:, None] * f);out[:, 1::2] = np.cos(p[:, None] * f)
return out
def attention(x):
x = np.asarray(x, dtype=float)
if x.ndim != 2 or not x.size or max(x.shape) > 128 or not np.isfinite(x).all():
raise ValueError('finite bounded matrix required')
scores = x @ x.T / np.sqrt(x.shape[1]);p = np.exp(scores - scores.max(axis=1, keepdims=True));p /= p.sum(axis=1, keepdims=True)
return p @ x
def shift_matrix(offset, width=8, base=10000.):
# For column [sin(tw), cos(tw)], the shift has clockwise block convention.
sinusoidal([offset], width, base)
f = base ** (-np.arange(0, width, 2) / width)
c, s = np.cos(offset * f), np.sin(offset * f);m = np.zeros((width, width))
for i in range(width // 2):m[2*i:2*i+2, 2*i:2*i+2] = [[c[i], s[i]], [-s[i], c[i]]]
return m
def demo():
rng = np.random.default_rng(8);x = rng.normal(size=(5, 8));order = np.array([2, 0, 4, 1, 3]);p = sinusoidal(np.arange(5))
shifted = sinusoidal(np.arange(5) + 7);pure0 = p @ p.T;pure7 = shifted @ shifted.T
added0 = (x+p) @ (x+p).T;added7 = (x+shifted) @ (x+shifted).T
# An exact fit on four positions need not extrapolate even with defined features.
train = sinusoidal(np.arange(4));target = np.arange(4, dtype=float)
coef = np.linalg.lstsq(train, target, rcond=None)[0]
future = np.arange(4, 12);pred = sinusoidal(future) @ coef
return dict(no_position_permutation_error=float(np.max(np.abs(attention(x[order])-attention(x)[order]))),
fixed_position_permutation_gap=float(np.max(np.abs(attention(x[order]+p)-attention(x+p)[order]))),
sinusoid_shift_error=float(np.max(np.abs(p @ shift_matrix(7).T-shifted))),
pure_position_dot_shift_error=float(np.max(np.abs(pure0-pure7))),
additive_content_dot_shift_gap=float(np.max(np.abs(added0-added7))),
position_norms=np.linalg.norm(p,axis=1).tolist(),train_mse=float(np.mean((train @ coef-target)**2)),
future_mse=float(np.mean((pred-future)**2)),future_positions=future.tolist(),future_predictions=pred.tolist(),
first_frequency_pairs=p[:, :2].tolist())
if __name__ == '__main__':print(json.dumps(demo(),indent=2))
The content-only permutation error is below 1e-15. Permuting tokens while keeping position vectors attached to their original slots changes the result, with a maximum difference about 1.51206. The sinusoidal shift and pure-position dot-product identities agree to floating-point precision, while shifting positions in the content-plus-position scores changes them by about 3.55049.
The small readout fits positions 0–3 with MSE about 6e-30. On positions 4–11 its MSE is about 0.516251. Those numbers show a concrete failure of guaranteed extrapolation, not a general verdict on sinusoidal encodings. Different targets, training positions, model classes and regularization can behave differently.
Generating n encodings costs order nd and stores nd numbers. The formula has no learned parameters. A learned table with L rows has Ld parameters. Either choice still feeds an attention computation whose dense score matrix is quadratic in sequence length.
Distinct coordinates are not a trained skill
Finite precision matters for very large angles. A single frequency repeats periodically; multiple frequencies provide a richer signature, but neither visual distinctness nor a constant norm proves reliable long-context reasoning. Extending a learned table also requires a policy for the new rows and usually further evaluation or training.
The original paper describes sinusoidal extrapolation as a motivation and reports similar results for its learned and sinusoidal variants in the stated experiments. That is narrower than a theorem about every trained model. Our least-squares task deliberately measures a simple numerical target rather than language understanding.
Which part of the computation remembers order?
- For width two, what are the encodings at positions zero and π/2?
Answer: The single frequency is one, giving [0,1] and [1,0]. The program accepts real positions for algebraic experiments, although token positions are normally integers.
- Why is the raw sinusoidal dot product unchanged when the same offset is added to both positions?
Answer: Each sine/cosine pair contributes the cosine of their difference. Adding the same offset cancels in that difference. This does not cancel arbitrary content-position cross terms in an actual attention score.
- If you permute both token embeddings and their already attached position vectors together, should the content-only attention function recover permutation equivariance?
Answer: Yes. It now receives a permutation of the complete row vectors X+P. The distinction is between moving an existing token-position pair and moving tokens into different fixed slots. A fixed causal mask would require its own consistent permutation for the same argument.
- A readout has zero error on four training positions. Does that identify its eight coefficients or prove extrapolation?
Answer: Neither follows. Four constraints leave possible null-space directions; the pseudoinverse selects the minimum-norm solution. The supplied experiment evaluates that solution at eight new positions and records a nonzero error. Inspect the evaluation instead of inferring it from the training fit.
Compare where position enters
The original additive scheme, relative pair representations and learned BERT table place different constraints on position information. Their comparison is more useful than treating all “position embeddings” as interchangeable. Continue with rotary embeddings, which apply position-dependent rotations to projected queries and keys, and relative position representations, which modify pair scores or values directly.
Make a prediction, then check
Does a sinusoidal formula guarantee accurate predictions at unseen lengths?
Learning objectives
- Derive sinusoidal position-shift matrices.
- Identify permutation symmetry without positions.
- Test extrapolation beyond fitted positions.
Prerequisites & connections
Explore related knowledge →References
- Attention Is All You Need (v5)
Ashish Vaswani; Noam Shazeer; Niki Parmar; Jakob Uszkoreit; Llion Jones; Aidan N. Gomez; Łukasz Kaiser; Illia Polosukhin · 2017 - Self-Attention with Relative Position Representations
Peter Shaw; Jakob Uszkoreit; Ashish Vaswani · 2018 - google-research/bert: modeling.py @eedf571
google-research/bert contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author additionally read Attention v5 section3.5/PDF6, Shaw selected method sections and fixed BERT position-table code. Six paired equations and four explained exercises; sinusoidal shifts, row/column conventions, content cross terms, conditional permutation symmetry and minimum-norm readout extrapolation failure. Defined coordinates do not guarantee language generalization.
- Single AI author additionally read Attention v5 section3.5/PDF6, Shaw selected method sections and fixed BERT position-table code. Six paired equations and four explained exercises; sinusoidal shifts, row/column conventions, content cross terms, conditional permutation symmetry and minimum-norm readout extrapolation failure. Defined coordinates do not guarantee language generalization.
- Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial text-coordinate precision assertion and visual-label refinements preserved. Full article acceptance recorded separately.
Source locations checked:
- Attention Is All You Need (v5) · Reused identical Source object; additionally read v5 section3.5, including sine/cosine formula and extrapolation motivation; PDF6 actually viewed. Original source note and access date preserved.
- Self-Attention with Relative Position Representations · Read sections2.1-3.3; PDF2/3 viewed: clipped key-minus-query offsets, relative keys/values and shared storage. No translation benchmark reproduction.
- google-research/bert: modeling.py @eedf571 · Read489-520,524-558,697-723: learned position bounds, key-padding mask and finite negative logit sentinel. Apache2 opening only; no upstream execution or copying.
Related topics