What is Relative Positional Embedding & how it differs from Absolute?

2D relative positional embedding Diagram with a 4x4 table
Title: 2D relative positional embedding
Source: Stand-Alone Self-Attention in Vision Models

Introduction

In sequence modeling tasks such as natural language processing (NLP) or vision, understanding the relationships between tokens (words, characters, or visual elements) is crucial. Relative Positional Embeddings (RPE) (Shaw et al., 2018 and Huang et al., 2018) proposed a method to encode the relative positions between tokens, making the model sensitive to their relationships, rather than their absolute locations within a sequence. Well-known models that adopted RPE include Transformer-XL (Dai et al., 2019) and T5 (Raffel et al., 2019).

What Are Relative Positional Embeddings?

Relative Positional Embeddings encode the distance between tokens in a sequence, allowing the model to understand not where tokens are located globally, but how they relate to one another. For example, they capture relationships like “token $i$ is 2 positions to the right of token $j$.” This is particularly useful for tasks where relationships between elements matter more than their absolute positions. Examples include syntax parsing, coreference resolution, and spatial tasks in computer vision.

How Do Relative Positional Embeddings Work?

Relative Positional Embeddings modify the self-attention mechanism in transformer models. In self-attention, each token attends to every other token in the sequence by computing an attention score. 

Formula of relative position embeddings:

$$ Attention(Q, K, V) = Softmax\left(\frac{QK^T}{\sqrt{d_K}} + R\right)V $$

Where:

  • $R=R(i,j)=$ bias that depends on the relative position distance between token $i$ in Query and $j$ in Key

With RPE:

1. The attention scores are adjusted to incorporate the relative distance between tokens.

2. These distances can either be:

  • Fixed: Predefined for specific relative positions, such as $[-2, -1, 0, +1, +2]$, or
  • Learned: Trained as embeddings for a range of relative distances.
Illustration of One Possible RPE shown in a 2D array
Title: Illustration of One Possible RPE
Source: AIML.com Research

The figure above presents one possible RPE. Imagine we have a sequence with a length of 5. Each vector represents the relationships for the current token with the others. This allows the model to generalize across sequences of varying lengths, as the relative distance remains invariant regardless of the sequence’s absolute size.

Advantages of Relative Positional Embeddings

  1. Contextual Relationships: RPE focuses on the contextual relationship between tokens, such as the dependency of a word on its preceding or succeeding word.
  2. Generalization: Unlike absolute embeddings, RPE generalizes well to sequences of unseen lengths, since relationships between tokens remain constant.
  3. Efficient Attention: By encoding relative positions directly into the attention mechanism, RPE integrates positional information without requiring separate embedding layers.

Difference from Absolute Positional Embeddings

Self-attention is inherently order-agnostic, as it operates on sets without considering sequence order, so it’s common practice to include an explicit positional signal in the Transformer architecture. The original Transformer uses a sinusoidal position signal or learned position embeddings, a strategy of absolute positional embeddings, in which position representations of each dimension are absolute. 
Formula of absolute position embeddings (PE) in the original Transformer:

$$ PE(pos, 2i) = \sin\left(pos / 10000^{2i/d_{model}}\right) $$ $$ PE(pos, 2i + 1) = \cos\left(pos / 10000^{2i/d_{model}}\right) $$ $$ TransformerInput = Embedding(x) + PE $$

Where:

  • x = input sequence
  • pos = position of the sequence
  • i = ith dimension of an embedding vector
  • dmodel = embedding length

However, absolute position embeddings encode fixed positions and do not capture the relative relationships between tokens. This can be limiting for tasks where relative position (e.g., token distance) is more important than the absolute position in the sequence. In addition, absolute position embeddings are tied to specific positions within a predefined maximum sequence length. If the model encounters sequences longer than it was trained on, it struggles because no positional embeddings exist for those new positions. 

However, absolute position embeddings encode fixed positions and do not capture the relative relationships between tokens. This can be limiting for tasks where relative position (e.g., token distance) is more important than the absolute position in the sequence. In addition, absolute position embeddings are tied to specific positions within a predefined maximum sequence length. If the model encounters sequences longer than it was trained on, it struggles because no positional embeddings exist for those new positions. 

In contrast, relative position embeddings are designed to capture the relative distances between tokens, allowing the model to focus on the relationships between elements regardless of their absolute positions. This makes relative positional embeddings more flexible and better suited for tasks where the contextual relationships between tokens (e.g., proximity or dependency) are critical. 
Formula of relative position embeddings:

$$ Attention(Q, K, V) = Softmax\left(\frac{QK^T}{\sqrt{d_K}} + R\right)V $$

Where:

  • $R=R(i,j)=$ bias that depends on the relative position distance between token $i$ in Query and $j$ in Key

The key differences between the two strategies are summarized in the following table.

Absolute Position Embeddings v.s. Relative Position Embeddings

AspectRelative Position EmbeddingsAbsolute Position Embeddings
Position RepresentationEncodes the relative distance between tokensEncodes the absolute position of each token in the sequence
Generalization AbilityInvariant to sequence length; works well on unseen sequence sizesMay struggle with unseen or longer sequences
ImplementationIntegrated into the attention mechanism by modifying attention scoresAdded to input token embeddings as fixed or learned vectors
Use CasesTasks emphasizing relationships, such as syntax or spatial patternsTasks where absolute positions matter, such as ordered sequences or temporal tasks
Example ModelsTransformer-XL, T5Transformer, BERT

Source:

  1. “Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context” by Dai et al., 2019
  2. “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” by Devlin et al., 2018
  3. “Attention Is All You Need” by Vaswani et al., 2017
  4. “Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer” by Raffel et al., 2019
  5. “Self-Attention with Relative Position Representations” by Shaw et al., 2018
  6. “Music Transformer: Generating Music With Long-Term Structure” by Huang et al., 2018

Summary

Relative Positional Embeddings provide a robust alternative to Absolute Positional Embeddings in tasks where relationships between tokens are more critical than their absolute order. While absolute embeddings remain effective for tasks with fixed positional requirements, RPE excels in generalization, contextual understanding, and handling variable sequence lengths, making it essential in advanced transformer architectures like Transformer-XL and T5.

Video Explanation

  • This video is taken from the Stanford University graduate course CS224U. Overall, it breaks down Contextual Word Representations and Positional Encoding. The video also explains the role of positional encoding, and shares descriptions and limitations of Absolute and Relative Positional Encoding. (Runtime: ~13 mins)

Video Link: NLU I Contextual Word Representations, Part 3: Positional Encoding by Stanford Online

  1. What are Embeddings?
  2. Compare the different Transformer-based model architectures


Author

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute