Study the paper
Attention Is All You Need
Lessons, visuals, quizzes, flashcards, and resources—organized in teaching order.
Injecting Sequence Order: Positional Encodings
Sinusoidal Positional Encoding (Even Dimensions)
Sinusoidal Positional Encoding (Even Dimensions)
Source equation
In non-recurrent architectures like the Transformer, sequence order is not implicitly captured by the network structure. To inject positional information, sinusoidal positional encodings are added to the input embeddings. This equation defines the encoding value for even dimensions of the positional vector.
Sources
equation
PE(pos,2i)=sin(pos/100002i/dmodel)\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})
\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})Sources
equation
PE(pos,2i)=sin(pos/100002i/dmodel)\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})
\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})The positional encoding uses a combination of sine and cosine functions of different frequencies. For any given position and even dimension index , the value is computed using a sine function whose wavelength forms a geometric progression from to . This allows the model to easily learn to attend by relative positions, since for any fixed offset , can be represented as a linear function of .
Sources
equation
PE(pos,2i)=sin(pos/100002i/dmodel)\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})
\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})Implementation detail
Illustrative Calculation
Let's calculate the positional encoding value for:
- Position
- Dimension index (meaning )
- Model dimension
Step 1: Calculate the denominator
Step 2: Calculate the argument of the sine function
Step 3: Compute the sine value
Sources
equation
PE(pos,2i)=sin(pos/100002i/dmodel)\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})
\displaystyle PE_{(pos,2i)}=sin(pos/10000^{2i/d_{\text{model}}})- The position of the token in the sequence · scalar
- The index of the dimension (where $2i$ represents even dimensions) · scalar
- The total dimensionality of the model's hidden states · scalar
- The positional encoding value at position $pos$ for the even dimension $2i$ · scalar