Sinusoidal positional encoding represents a word's position in the sentence as a set of sin and cos values with different periods and adds it to the word embedding. It was proposed by Vaswani et al. in 2017 in the Transformer paper. It has no learned parameters and is fully determined by a formula.
Position information is needed because scaled dot-product attention, the core of the Transformer, does not distinguish word order. Attention only computes a weight for each pair of words, so on its own it treats "the dog chases the cat" and "the cat chases the dog" as the same set of words. To give each word order information, a different vector is added to its embedding for each position.
The 2i-th and (2i+1)-th values of the vector added to the word at position pos are given by the following formulas (Section 3.5 of the paper).
Here pos is the position (0, 1, 2, β¦), i is the index of a dimension pair (0β€i<dmodelβ/2), and dmodelβ is the embedding size (512 in the paper). Even dimensions use sin and odd dimensions use cos.
Meaning of the formula and example values
The denominator 100002i/dmodelβ grows for later dimensions. As a result, earlier dimensions are fast-changing waves and later dimensions change slowly. The wavelength (length of one period) of dimension 2i is 2Οβ 100002i/dmodelβ, growing geometrically from 2Οβ6.3 for the first dimension to almost 10000β 2Ο for the last.
The figure at the top of the article is computed from the formula with dmodelβ=128 for illustration. The left shows the value for each position (vertical) and dimension (horizontal), and the right plots the values of several dimensions along the position axis. Dimensions further left oscillate rapidly, while dimensions further right barely change.
Think of the second, minute, and hour hands of a clock. The second hand alone returns to the same place every minute, but combined with the minute and hour hands it uniquely identifies any time of day. Sinusoidal positional encoding likewise distinguishes positions in a long sentence by combining waves of different speeds.
As a small example, compute the values for dmodelβ=4. The pair i=0 is sin(pos),cos(pos), and the pair i=1 is sin(pos/100),cos(pos/100).
Position pos
Dim 0 (sin, fast)
Dim 1 (cos, fast)
Dim 2 (sin, slow)
Dim 3 (cos, slow)
0
0.000
1.000
0.000
1.000
1
0.841
0.540
0.010
1.000
2
0.909
β0.416
0.020
1.000
3
0.141
β0.990
0.030
1.000
All values lie within β1 to 1, so adding them to the embeddings does not change their magnitude drastically.
The positional encoding is added to the embedding, not concatenated. To allow the addition, its size is set to the same dmodelβ as the embedding. The Transformer also multiplies the embedding by dmodelββ before adding the positional encoding, so word information is less likely to be drowned out by position information.
Why sin and cos?
The paper chose pairs of sin and cos because the vector PEpos+kβ at an offset of k positions can be expressed as a linear transformation (a matrix multiplication) of PEposβ. This is thought to make it easier for the model to learn relative positions such as "how many words back."
With the frequency of one pair written as Οiβ=1/100002i/dmodelβ, the trigonometric addition formulas give the following.
The matrix on the right depends only on the offset k, not on the position pos. In other words, "k positions later" is represented by the same rotation from any position.
The paper gives one more reason: the encoding may allow the model to handle sentences longer than those seen in training (to extrapolate), since the formula can compute values for any position.
Comparison with other position representations
The paper also compared this with learning a vector for each position (learned positional embeddings) and reported nearly identical results (BLEU 25.7 versus 25.8 on the EnglishβGerman development set). It nevertheless chose sinusoids because values can be computed for sequences longer than those seen in training.
Many position representations have been proposed since.
Subtracts a penalty proportional to distance from the attention scores
None
When sequences longer than training are needed
Learned positional embeddings cannot represent positions beyond the maximum length fixed during training. Sinusoidal encoding has no such limit because it is computed by formula, but note the following.
Sinusoidal positional encoding can compute values for any position, but there is no guarantee that the model works well on sequences longer than in training. Later work (Press et al., 2022) reported that models using sinusoidal positional encoding degrade sharply when given sequences longer than in training. To handle long sequences, consider ALiBi, or RoPE combined with methods such as position interpolation.
PyTorch example
βΆShow code
python
import math
import torch
import torch.nn as nn
class SinusoidalPositionalEncoding(nn.Module):
"""Build the positional encoding with the formula in Section 3.5 of the paper and add it to the embeddings"""
def __init__(self, d_model: int, max_len: int = 5000, dropout: float = 0.1):
super().__init__()
pos = torch.arange(max_len).unsqueeze(1) # [max_len, 1]
# Compute 1 / 10000^(2i/d_model) via exp and log
div = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
pe = torch.zeros(max_len, d_model)
pe[:, 0::2] = torch.sin(pos * div) # even dimensions: sin
pe[:, 1::2] = torch.cos(pos * div) # odd dimensions: cos
self.register_buffer("pe", pe) # store as a non-learned buffer
self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: [batch, seq_len, d_model]
return self.dropout(x + self.pe[: x.size(1)])
# Example from the table in the text (d_model = 4)
pe = SinusoidalPositionalEncoding(d_model=4, max_len=4, dropout=0.0).pe
print(pe) # each row is position 0-3; matches the table in the text
# Transformer input: multiply the embedding by βd_model, then add the positional encoding
d_model, vocab_size = 512, 37000
embed = nn.Embedding(vocab_size, d_model)
pos_enc = SinusoidalPositionalEncoding(d_model)
tokens = torch.randint(0, vocab_size, (2, 20)) # batch 2, length 20
x = pos_enc(embed(tokens) * math.sqrt(d_model))
print(x.shape) # torch.Size([2, 20, 512])
FAQ
Q. Why the number 10000?
A.
To make the wavelength of the slowest wave long enough that positions do not overlap even in long sentences. The paper does not explain the choice of 10000 in detail, but since the wavelengths range from 2Ο to 10000Β·2Ο, positions can be distinguished even in sentences of thousands of words.
Q. Doesn't adding the positional encoding destroy the word meaning information?
A.
The values stay within β1 to 1, and the embedding is multiplied by βd_model before the addition, so word information is not badly disrupted. During training, the model adjusts its weights so it can use both word and position information.
Q. Is it still used in today's large language models?
A.
Most current large language models use other methods such as RoPE. However, the way sinusoidal frequencies are chosen (a geometric sequence with base 10000) carries over to RoPE, so it is a foundation for understanding position representations.