Positional Encoding
Self-attention ignores the order of its inputs. Permuting the tokens permutes the outputs in the same way. “The woman ate the raccoon” and “the raccoon ate the woman” would give the same set of vectors. A positional encoding tells the model where each token sits. The lecture lists four schemes:
- Sinusoidal: add a fixed vector to the embedding of the token at position . The original transformer used sines and cosines of many frequencies. The lecture notes that this scheme is no longer used.
- NoPE: use no positional encoding at all.
- Learned relative bias: add a learned number to the score of query and key . The number depends only on the offset .
- RoPE (rotary position embedding): rotate each query and each key by an angle proportional to its position. The score then depends on the two positions only through their offset.
The sinusoidal encoding of Vaswani et al. (2017) has, for even and ,
The learned relative bias changes the attention weights to
RoPE in two dimensions uses the rotation matrix by the angle . The score of query and key becomes
Intuition
The Fall 2022 lecture 19 notes describe the sinusoidal encoding with the hands of a clock. Each pair is a hand that turns at speed . The pair with turns fast, and the last pairs turn very slowly. Position sets the angle of every hand. Moving positions turns every hand by a fixed angle, and turning is a linear map. A query can therefore ask for “the token places back” with a learned linear map. The network has no sine units, but it does not need any. The learned projections and can learn the needed rotations.
The obvious way to add position is to concatenate to the embedding . That costs extra dimensions. In practice is added to , which seems to mix content and position. It works because the vectors are long, with hundreds or thousands of entries. Write a query as a content part plus a position part, , and the same for a key. Then
Unrelated vectors in high dimensions are nearly orthogonal, so the two cross terms are small. A query can then match on content, on position or on both.
The last two schemes act inside attention instead of on the inputs. Position only matters when a query compares itself with keys. The relative bias and RoPE change exactly that comparison.
Properties
(Shifts Are Rotations) Shifting a sinusoidal encoding by positions is a rotation that does not depend on the position .
Take one pair with angle and shift by . The angle addition formulas give
The matrix is a rotation that depends on but not on . Stacking one such block per pair gives for a block-diagonal . The inner product of two encodings also depends only on the offset:
The encoding is absolute, since each position gets its own vector, but relative positions are easy to read from it.
(The Relative Bias Changes the Attention Matrix) The learned bias adds a matrix with constant diagonals to the scores, the same for every input.
Entry of the bias matrix is , so every diagonal holds one number. Such a matrix is called a Toeplitz matrix. The bias does not depend on the tokens, only on how far apart they are. A head can learn large and falling with the distance, which makes it prefer recent tokens. For a context of tokens, each head learns numbers, or numbers if attention is causal. Shifting a whole sentence to later positions leaves every offset, and so every bias, unchanged. Prince notes that relative position often matters more than absolute position, since a passage of text can start anywhere.
(RoPE Gives Relative Scores) Rotating queries and keys by their positions makes every score depend on the positions only through .
Rotations satisfy and . The score is therefore . Rotations also keep lengths, so the norms of queries and keys do not change. For , RoPE splits the query and the key into pairs. It rotates pair by , with frequencies like the sinusoidal ones. Each layer rotates its queries and keys but never its values. Nothing is added to the embeddings.
Not Taught in Lecture
The general form follows Su et al. (2021). The lecture shows the two-dimensional case.
With for , RoPE maps the pair of a vector at position to
The usual base is . Many code bases pair coordinate with coordinate instead of . This “rotate half” version precomputes the cosines and sines and needs no matrix. The two pairings differ only by a fixed reordering of the coordinates, which the learned projections can absorb.
(Why NoPE Can Work) A decoder with causal attention can find positions without any encoding, because the mask itself depends on position.
Not Taught in Lecture
The lecture names NoPE without explaining it. The explanation follows Haviv et al. (2022) and Kazemnejad et al. (2023).
Unmasked self-attention cannot tell positions apart. The causal mask breaks this symmetry, since token sees exactly tokens. A head that spreads its weight evenly gives the first token the weight . If the first token is <start>, the output at position then carries the number . Later layers can turn this into a sense of position. Decoder-only language models trained this way perform about as well as models with encodings. An encoder without a mask cannot do this.
(Learned Absolute Encodings) Many models learn one vector per position instead of using sinusoids, which fixes their maximum input length.
Not Taught in Lecture
This follows Prince §12.3.1 and its chapter notes.
BERT and GPT-3 learn a table of position vectors, like the token table. The table has one row per position up to the training length, such as for BERT. A longer input has positions with no vector. Prince reports that learned and sinusoidal encodings perform about the same. Relative encodings did better in the comparison he cites. Sinusoidal encodings, relative biases and RoPE can be computed for any position. Press et al. (2022) show that sinusoidal and rotary models still degrade on inputs longer than in training.
Examples
(Easy) Sinusoidal Encodings
Use , so the two frequencies are and .
Compute , and . Check that . The encodings are The first pair turns by radian per position. The second pair turns by radians and barely moves. The inner products are and . Both pairs of positions have offset , so their inner products match. For offset , .
(Medium) A Relative Bias
A causal head has the biases , and . All content scores equal , so only the biases matter.
Find the weights of the query at on the keys . Repeat for the query at on the keys . The query at has the offsets , and . Its scores plus biases are , and . The softmax gives The head prefers the current token and gives less weight further back. The query at has the same offsets to keys , and . It gives them the same weights. The pattern moves with the query, and the head learns it once for all positions. The constant content score cancels in the softmax.
(Hard) RoPE by Hand
Use and . A query sits at position , and a key sits at position .
Compute the rotated score in two ways. Then move both tokens places later and compare. Rotating the query by gives . Rotating the key by gives Their inner product is .
The second way uses with . Rotating by gives . The inner product with is , the same.
At positions and , the offset is still , so the score is again . Without RoPE the score would be at every pair of positions. With the key places back instead of , the score becomes . The score now carries the offset, while the lengths of and stay the same.
See Also
- 7.1. Attention, which ignores order without an encoding.
- 7.2. Transformer Architecture, where the encoding enters the model.
- 7.3. Token Embeddings, the vectors to which absolute encodings are added.
- 7.5. Encoder and Decoder Models, for the causal mask behind NoPE.
- 1. Representing Rotations, for rotation matrices.