Relative Position Encoding › Worked Example: Step-by-Step Score Computation
Language AI HandbookAll chapters Relative Position Encoding › Worked Example: Step-by-Step Score ComputationOne section · Sections in this chapter6 / 16 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's walk through a concrete, minimal example to make the math tangible. Consider a four-token sequence with one-dimensional embeddings, maximum clipping distance , and very simple relative position embeddings. The goal is to show exactly where the relative bias comes from and how it modifies the attention scores.
Suppose we have queries , , , and keys , , , . The key-side relative position embeddings (after clipping to ) are:
- (two positions back)
- (one position back)
- (same position)
- (one position forward)
- (two positions forward)
Now let's compute the score from query position 1 to all key positions. With so :
For position pair : offset is , content term is , position term is . Combined score: .
For position pair : offset is , content term is , position term is . Combined score: .
For position pair : offset is , content term is , position term is . Combined score: .
For position pair : offset is , which clips to , content term is , position term is . Combined score: .
The key insight is visible immediately: position 4, despite having the highest content similarity (), is penalized by the relative position embedding because it is far away. Position 1 (same position) receives a slight boost. In a trained model, these biases would reflect linguistic preferences learned from data rather than arbitrary initialization values, but the mechanics are identical.
After applying softmax to the four scores , we get attention weights that favor the nearby positions more than pure content similarity would suggest. This is exactly the behavior we want: locality is naturally preferred, but strong content signals can still override the distance penalty when a truly relevant token appears far away.