AI Logic

Positional Encodings

Relative Position Representations

Updated๏ผš

How relative position representations are used. The left shows the flow of an attention layer: nothing is added to the input, and in each layer a relative position term qยทaK is added to the scores and aV to the values. The right is a table for a length-6 sequence with k = 2 giving, for each pair of query position i and key position j, the index clip(j โˆ’ i, 2) of the vector used; cells on the same diagonal use the same vector, and pairs 3 or more apart are merged into the edge indices โˆ’2 or 2.

What are relative position representations?

Relative position representations learn vectors that encode "how far apart two words are" rather than "which position a word is at", and add them directly into the attention computation. They were proposed by Shaw, Uszkoreit, and Vaswani in 2018.

The scaled dot-product attention in the Transformer does not distinguish word order on its own. The original Transformer added absolute positions to the input embeddings using sinusoidal positional encoding or learned positional embeddings. However, grammatical relations such as "a particle comes right after the subject" are often determined by the distance between words rather than by where they sit in the sentence.

Relative position representations therefore add nothing to the input. Instead, when attention compares a query word ii with a key word jj, a vector that depends on the distance jโˆ’ij - i is added. Because the distance is clipped at a fixed value kk, only 2k+12k+1 vectors are learned.

The left of the figure at the top of the article shows where position information is injected. It has the same layout as the figures in the articles on learned positional embeddings, RoPE, and ALiBi, so the injection points can be compared directly. The right is a table of which distance vector is used for each pair of words.

Theory (adding per-distance vectors to attention)

The explanation follows the equations in Section 3 of the paper. Let the input sequence be x1,โ€ฆ,xnx_1, \dots, x_n (xiโˆˆRdxx_i \in \mathbb{R}^{d_x}), the size of one attention head be dzd_z, and the clipping distance be kk. WQ,WK,WVW^Q, W^K, W^V are the weights of the linear layers that produce the queries, keys, and values.

  1. Clip the distance jโˆ’ij - i from word ii to word jj to the range โˆ’k-k to kk.
  2. For each clipped distance, learn a key vector wKw^K and a value vector wVw^V. There are 2k+12k+1 distances โˆ’k,โ€ฆ,k-k, \dots, k, so there are 2k+12k+1 vectors of each kind.
  3. When computing the score between words ii and jj, add the distance vector aijKa^K_{ij} to the key before taking the dot product with the query.
  4. Turn the scores into weights ฮฑij\alpha_{ij} with softmax (as in ordinary attention).
  5. When producing the output, also add the distance vector aijVa^V_{ij} to the value before taking the weighted sum.

Steps 1 and 2 are expressed as follows.

aijK=wclip(jโˆ’i,โ€‰k)K,aijV=wclip(jโˆ’i,โ€‰k)V,clip(x,k)=maxโก(โˆ’k,minโก(k,x))a^K_{ij} = w^K_{\mathrm{clip}(j-i,\,k)}, \qquad a^V_{ij} = w^V_{\mathrm{clip}(j-i,\,k)}, \qquad \mathrm{clip}(x, k) = \max\bigl(-k, \min(k, x)\bigr)

Steps 3โ€“5 are the following equations (Eqs. (4) and (3) in the paper).

eij=xiWQ(xjWK+aijK)โŠคdz,ฮฑij=expโกeijโˆ‘l=1nexpโกeil,zi=โˆ‘j=1nฮฑij(xjWV+aijV)e_{ij} = \frac{x_i W^Q \bigl(x_j W^K + a^K_{ij}\bigr)^\top}{\sqrt{d_z}}, \qquad \alpha_{ij} = \frac{\exp e_{ij}}{\sum_{l=1}^{n} \exp e_{il}}, \qquad z_i = \sum_{j=1}^{n} \alpha_{ij} \bigl(x_j W^V + a^V_{ij}\bigr)

Without aijKa^K_{ij} and aijVa^V_{ij}, these are exactly the equations of ordinary attention. The right of the figure at the top of the article shows, for length n=6n = 6 and k=2k = 2, which vector index is used for each word pair (i,j)(i, j). Along each diagonal from top-left to bottom-right the distance is the same, so the same vector is used.

The paper presents this method as a special case of a mechanism that "views the input as a graph whose nodes are words and whose edges are word pairs, and adds a per-edge vector to attention." If the edge vectors encode relations other than distance (such as syntactic relations), the same equations can inject other information as well.

Why distance alone can represent position, and how to compute it efficiently

With relative position representations, the only information added to the score between words ii and jj is the distance jโˆ’ij - i. As a result, a pair of words in the same arrangement is treated the same wherever it appears in the sentence. Once the model learns a rule that looks at "the word 3 positions back," it can apply it at the start or the end of a sentence. It also does not depend on the total length of the sequence.

The distance is clipped at kk because the paper hypothesizes that "beyond a certain distance, precise relative position information is not useful." Thanks to clipping, even for long sequences never seen in training, every pair uses one of the 2k+12k+1 vectors, so the same computation applies. The paper also notes that because many layers are stacked, even if one layer can only distinguish distances up to kk, information about more distant positions may still propagate to upper layers.

Computationally, each word pair gets a different vector, so the scores can no longer be computed with a single matrix multiplication as is. The paper splits the score into two terms (Eq. (5)).

eij=xiWQ(xjWK)โŠค+xiWQ(aijK)โŠคdze_{ij} = \frac{x_i W^Q (x_j W^K)^\top + x_i W^Q (a^K_{ij})^\top}{\sqrt{d_z}}

The first term is the same matrix multiplication as in ordinary attention. The second term is computed by reshaping the tensors and performing a matrix multiplication per position. Furthermore, sharing the distance vectors across heads and across sequences keeps the additional memory at O(n2da)O(n^2 d_a) (dad_a is the length of a distance vector; the paper uses da=dzd_a = d_z). In the translation experiments, steps per second dropped by only 7%.

Experimental results

Translation accuracy (Table 1 in the paper): The paper compares BLEU on the test set (newstest2014) for WMT 2014 Englishโ†’German (EN-DE) and Englishโ†’French (EN-FR) translation. "Absolute position" is the sinusoidal positional encoding of the original Transformer.

ModelPosition representationEN-DEEN-FR
Transformer (base)Absolute position26.538.2
Transformer (base)Relative position representations26.838.7
Transformer (big)Absolute position27.941.2
Transformer (big)Relative position representations29.241.5

Relative position representations scored higher in every setting, with improvements of 0.3โ€“1.3. The base model uses k=16k = 16 and the big model uses k=8k = 8. Adding sinusoidal positional encoding on top of relative position representations brought no further improvement.

Effect of the clipping distance kk (Table 2 in the paper): BLEU of the base model without absolute positions on the EN-DE development set (newstest2013).

kk01241664256
BLEU12.525.525.825.925.825.925.8

k=0k = 0 is equivalent to having no position information, and BLEU drops to 12.5. For kโ‰ฅ2k \ge 2 there was almost no difference.

Which helps more, the key vectors or the value vectors (Table 3 in the paper): Under the same conditions, aijKa^K_{ij} and aijVa^V_{ij} are removed and compared.

aijVa^V_{ij} (added to values)aijKa^K_{ij} (added to scores)BLEU
YesYes25.8
NoYes25.8
YesNo25.3
NoNo12.5

For translation, aijKa^K_{ij} added to the scores alone was sufficient. The paper, however, leaves open whether the same holds for other tasks.

Practical considerations

Because relative position representations add a different vector for each word pair, attention can no longer be computed with plain matrix multiplications alone. For a sequence of length nn, vectors for nร—nn \times n pairs (O(n2da)O(n^2 d_a) memory) must be handled, and without a careful implementation the computation becomes slow or runs out of memory. When using a fast attention implementation (such as FlashAttention), check whether it supports the additional terms.

Also keep the following in mind.

  • kk can be small: In the translation experiments there was almost no difference for kโ‰ฅ2k \ge 2. A larger kk does not improve accuracy; it only increases the number of learned vectors.
  • Decide how widely the distance vectors are shared: The paper notes that they can be shared across heads to reduce memory. In the translation experiments, however, the base model uses separate vectors per layer and head, and the big model uses separate vectors per layer.
  • A word's pair with itself also uses the distance-0 vector: w0w_0 is added for pairs with i=ji = j. Since the clipping range โˆ’kโˆผk-k \sim k includes 0, there are 2k+12k+1 vectors, not 2k2k.

Comparison with other position representations

Relative position representations were the starting point for approaches that inject position information inside attention rather than into the input. Later methods have made the computation lighter or handled long sequences better.

MethodWhere position is injectedLearned parametersSequences longer than trainingMain uses
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmaxโกร—dL_{\max} \times d)Cannot be representedBERT, GPT
Sinusoidal positional encodingAdded to the input embeddings (once)NoneValues can be computed, but accuracy drops sharplyOriginal Transformer
Relative position representations (this article)Per-distance vectors added to scores and values in every layerYes (vectors for 2k+12k+1 distances)Computable because the distance is clippedTranslation, etc.
T5 relative position biasPer-distance numbers (scalars) added to scores in every layerYes (one number per distance bucket)ComputableT5
RoPEQueries and keys rotated by an angle proportional to position in every layerNoneOnly slightly longerLLaMA, etc.
ALiBiA penalty proportional to distance subtracted from scores in every layerNoneAccuracy is easier to maintainWhen sequences longer than training are needed
  • To let training shape the distance information flexibly, relative position representations or the T5 relative position bias are a good fit. Relative position representations add a vector of head size per distance, while T5 adds a single number per distance, so T5 learns fewer parameters.
  • To avoid adding learned parameters and to use fast attention implementations as is, RoPE is a candidate.
  • To run inference on sequences longer than those seen in training, ALiBi is a strong choice. In the comparison in the ALiBi paper, the T5 relative position bias can also extrapolate, but training was more than twice as slow as with sinusoidal encoding.

Transformer-XL relative positional encoding is another method that injects relative distance into attention.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn


class RelativeMultiHeadAttention(nn.Module):
    """Self-attention with the relative position representations of Shaw et al. (2018) (Eqs. (3)-(5))"""

    def __init__(self, d_model: int, n_heads: int, k: int = 16):
        super().__init__()
        self.h, self.d = n_heads, d_model // n_heads
        self.k = k
        self.q = nn.Linear(d_model, d_model)
        self.kv = nn.Linear(d_model, 2 * d_model)
        self.out = nn.Linear(d_model, d_model)
        # 2k+1 vectors for distances -k..k, shared across heads (Section 3.3 of the paper)
        self.w_k = nn.Embedding(2 * k + 1, self.d)
        self.w_v = nn.Embedding(2 * k + 1, self.d)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, n, _ = x.shape
        q = self.q(x).view(B, n, self.h, self.d).transpose(1, 2)          # [B, h, n, d]
        k, v = self.kv(x).view(B, n, 2, self.h, self.d).unbind(dim=2)
        k, v = k.transpose(1, 2), v.transpose(1, 2)                        # [B, h, n, d]

        # Use clip(j - i, k) + k as the table index (0..2k)
        pos = torch.arange(n, device=x.device)
        idx = (pos[None, :] - pos[:, None]).clamp(-self.k, self.k) + self.k  # [n, n]
        a_k, a_v = self.w_k(idx), self.w_v(idx)                              # [n, n, d]

        # Eq. (5): ordinary dot-product term + dot product of the query with a^K_ij
        scores = q @ k.transpose(-2, -1)                                     # [B, h, n, n]
        scores = scores + torch.einsum("bhid,ijd->bhij", q, a_k)
        attn = torch.softmax(scores / math.sqrt(self.d), dim=-1)

        # Eq. (3): add a^V_ij to the values too, then take the weighted sum
        z = attn @ v + torch.einsum("bhij,ijd->bhid", attn, a_v)             # [B, h, n, d]
        return self.out(z.transpose(1, 2).reshape(B, n, self.h * self.d))


# Nothing is added to the input. Position information is used only inside attention
layer = RelativeMultiHeadAttention(d_model=512, n_heads=8, k=16)
x = torch.randn(2, 40, 512)        # batch 2, length 40
print(layer(x).shape)              # torch.Size([2, 40, 512])
x_long = torch.randn(2, 300, 512)  # even longer than training, each pair uses one of the 33 vectors
print(layer(x_long).shape)         # torch.Size([2, 300, 512])

FAQ

Q. How should the clipping distance $k$ be chosen?
A.

In the paper's translation experiments, BLEU barely changed for kโ‰ฅ2k \ge 2 (25.8โ€“25.9). The paper itself uses k=16k = 16 for the base model and k=8k = 8 for the big model. Start with about 8โ€“16, then reduce it as far as accuracy stays the same to cut the number of learned vectors.

Q. Should it be combined with absolute position representations (such as sinusoidal encoding)?
A.

In the paper's translation experiments, adding sinusoidal positional encoding to relative position representations brought no improvement. Relative position representations alone appear to provide enough word-order information.

Q. Is $a^V_{ij}$, added to the values, necessary?
A.

For translation, removing it left BLEU unchanged (25.8 in both cases). Removing aijKa^K_{ij}, added to the scores, lowered it to 25.3. To lighten the computation, one option is to use only aijKa^K_{ij}, but the paper has not verified whether the same holds for other tasks.

References

  1. P. Shaw, J. Uszkoreit, and A. Vaswani, "Self-Attention with Relative Position Representations," NAACL, 2018.
  2. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, ล. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  3. O. Press, N. A. Smith, and M. Lewis, "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation," ICLR, 2022.