Why is incorporating relative positional information crucial in transformer models? Discuss scenarios where relative position encoding is particularly beneficial.
While any positional encoding breaks self-attention's permutation equivariance to distinguish word order, incorporating relative positional information is specifically crucial for translation invariance, length generalization beyond training limits, and segment-level recurrence. Modern Transformers implement relative offsets via learned relative key/logit biases (Shaw RPE, T5, ALiBi) or Rotary Position Embeddings (RoPE), ensuring attention depends on signed distance (i - j) rather than arbitrary absolute indices.
Study Card: Importance of Relative Positional Information in Transformers
Direct Answer
Self-attention without positional encoding is permutation-equivariant: shuffling input tokens simply shuffles output vectors. While absolute positional encodings already distinguish basic word-order swaps like "dog bites man" vs. "man bites dog", incorporating relative positional information () solves fundamental limitations of absolute encodings:
- Translation / Shift Invariance: Language dependencies (such as verb–object attachment or code bracket matching) depend on the signed relative distance and direction between tokens, not whether a phrase begins at token 5 or token 5,005.
- Length Generalization & Extrapolation: Learned absolute position tables fail completely beyond , and sinusoidal absolute encodings degrade outside their training distribution. Relative schemes generalize far better to unseen lengths:
- Shaw et al. RPE: Injects learned, clipped relative vectors into attention scores:
- T5 Relative Bias & ALiBi: Add scalar distance-dependent biases directly to pre-softmax attention logits ( in ALiBi).
- Rotary Position Embeddings (RoPE): Rotate at position and at position by and so their inner product depends strictly on relative offset .
- Segment-Level Recurrence: In models like Transformer-XL that cache hidden states from prior chunks, reusing states with absolute position indices would assign duplicate coordinates across chunks; relative encodings keep every cross-chunk attention offset consistent.
Key Terms
- Absolute Positional Encoding: Assigns a position-specific vector to each index added at the input layer.
- Signed Relative Offset (): Encodes both distance and direction (past vs. future) so left-context and right-context relationships remain distinguishable.
- Translation / Shift Invariance: Preserving identical attention behavior when a phrase shifts arbitrarily along the sequence axis.
- RoPE (Rotary Position Embedding): Encodes absolute angles in and whose dot product reduces strictly to relative displacement ; standard across Llama, Mistral, Qwen, and Gemma.
- ALiBi (Attention with Linear Biases): Replaces position vectors with head-specific linear logit penalties proportional to token distance.
Example
In a 10,000-token codebase or legal document, a function call referencing a variable declared 12 tokens earlier should trigger the same local attention pattern whether that pattern appears near line 10 (absolute indices 10–22) or line 4,000 (indices 4,000–4,012). Relative positional encoding makes that interaction invariant to absolute shift, preserves directionality (-1 one token left vs. +1 one token right—note that taking abs(i - j) without a causal mask would erase direction!), and scales smoothly beyond training window sizes when combined with RoPE scaling or ALiBi.
Code Implementation
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
class RelativeSelfAttention(nn.Module):
"""Shaw et al.-style signed relative position attention (preserves distance AND direction)."""
def __init__(self, embed_dim: int, max_rel_dist: int = 10):
super().__init__()
self.embed_dim = embed_dim
self.max_rel_dist = max_rel_dist
self.q_proj = nn.Linear(embed_dim, embed_dim)
self.k_proj = nn.Linear(embed_dim, embed_dim)
self.v_proj = nn.Linear(embed_dim, embed_dim)
# Signed relative offsets in [-max_rel_dist, +max_rel_dist] -> 2 * max_rel_dist + 1 entries
self.rel_k_emb = nn.Embedding(2 * max_rel_dist + 1, embed_dim)
def forward(self, x: torch.Tensor):
# x: (B, L, D)
B, L, D = x.shape
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
pos = torch.arange(L, device=x.device)
# Signed relative matrix: rel_pos[i, j] = j - i (negative = left, positive = right)
rel_pos = pos.unsqueeze(0) - pos.unsqueeze(1)
rel_clipped = torch.clamp(rel_pos, -self.max_rel_dist, self.max_rel_dist) + self.max_rel_dist
a_k = self.rel_k_emb(rel_clipped) # (L, L, D)
content_scores = torch.bmm(q, k.transpose(1, 2)) # (B, L, L)
rel_scores = torch.einsum("bld,lrd->blr", q, a_k) # (B, L, L)
attn_scores = (content_scores + rel_scores) / (D ** 0.5)
attn_weights = F.softmax(attn_scores, dim=-1)
out = torch.bmm(attn_weights, v)
return out, attn_weights
x = torch.randn(4, 8, 64)
rel_attn = RelativeSelfAttention(embed_dim=64, max_rel_dist=10)
output, weights = rel_attn(x)
print("Output shape:", output.shape, "| Attention weights shape:", weights.shape)
Related Concepts
- RoPE & YaRN / NTK Scaling: Extending rotary relative frequencies to support 128K–1M context lengths.
- Transformer-XL: Introduced segment-level recurrence relying on relative positional encodings.
- Causal Masking + RoPE: Combined in modern decoder-only LLMs for autoregressive generation.
- T5 Relative Positional Bias: Bucketing relative offsets logarithmically into learned scalar biases added before softmax.