AI Logic

Positional Encodings

Transformer-XL Relative Positional Encoding

Updated:

How Transformer-XL relative positional encoding works. The left shows the flow of an attention layer: nothing is added to the input, keys and values are built by also concatenating the memory from the previous segment, and in each layer relative position terms using the distance sinusoids R and u, v are added to the score qΒ·k. The top right shows two segments of length 4: with absolute positions the indices of the previous and current segments overlap, but distances 7–0 from query x8 can be distinguished. The bottom right is a table comparing the four score terms (a)–(d) in the original Transformer and Transformer-XL.

What is Transformer-XL relative positional encoding?

Transformer-XL relative positional encoding splits the attention score into four terms and replaces the parts involving absolute position with sinusoids of the query–key distance iβˆ’ji - j and two learned vectors uu and vv. It was proposed by Dai et al. in 2019 in the paper on Transformer-XL, a language model for long text (Section 3.3). No position is added to the input embeddings.

The method was designed to be used together with Transformer-XL's segment-level recurrence. Transformer-XL splits text into segments of fixed length and processes them in order, keeping the hidden states computed for the previous segment as a "memory" that the attention of the next segment can also refer to. This lets the model use context farther back than the length of one segment.

However, if the positions 1,…,L1, \dots, L within each segment are added to the input, as with sinusoidal positional encoding, the jj-th word of the previous segment and the jj-th word of the current segment get the same position information, and the model cannot tell them apart. So instead of absolute positions, only the relative distance, how many words back from the query, is put into the score. With distances, words in the memory and words in the current segment can be distinguished without collisions.

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 relative position representations, T5 relative position bias, RoPE, and ALiBi, so the injection points can be compared directly. The top right shows that when segments are reused, absolute position indices collide, whereas distances can be distinguished. The bottom right lays out the four terms of the score for the original Transformer and for Transformer-XL.

Theory (rewriting the four score terms with relative position)

The explanation follows the equations in Section 3.3 of the paper. Let ExiE_{x_i} be the embedding of word xix_i, UiU_i the positional encoding of absolute position ii, and Wq,WkW_q, W_k the weights that produce the queries and keys.

The original Transformer uses Exi+UiE_{x_i} + U_i as input, so expanding the score between query ii and key jj gives the following four terms.

Ai,jabs=Exi⊀Wq⊀WkExj⏟(a)+Exi⊀Wq⊀WkUj⏟(b)+Ui⊀Wq⊀WkExj⏟(c)+Ui⊀Wq⊀WkUj⏟(d)A^{\mathrm{abs}}_{i,j} = \underbrace{E_{x_i}^\top W_q^\top W_k E_{x_j}}_{(a)} + \underbrace{E_{x_i}^\top W_q^\top W_k U_j}_{(b)} + \underbrace{U_i^\top W_q^\top W_k E_{x_j}}_{(c)} + \underbrace{U_i^\top W_q^\top W_k U_j}_{(d)}

Transformer-XL rewrites these four terms as follows.

  1. Replace the absolute key position UjU_j in (b) and (d) with the relative positional encoding Riβˆ’jR_{i-j}. RR is the same sinusoid matrix as in the original Transformer and is not learned.
  2. Replace the absolute query position Ui⊀Wq⊀U_i^\top W_q^\top in (c) and (d) with learned vectors uu and vv. The same vectors are used for every query position, so the absolute query position disappears from the equation.
  3. Split the key weight into two: Wk,EW_{k,E} for word content and Wk,RW_{k,R} for distance.

The rewritten result is the following equation.

Ai,jrel=Exi⊀Wq⊀Wk,EExj⏟(a)+Exi⊀Wq⊀Wk,RRiβˆ’j⏟(b)+u⊀Wk,EExj⏟(c)+v⊀Wk,RRiβˆ’j⏟(d)A^{\mathrm{rel}}_{i,j} = \underbrace{E_{x_i}^\top W_q^\top W_{k,E} E_{x_j}}_{(a)} + \underbrace{E_{x_i}^\top W_q^\top W_{k,R} R_{i-j}}_{(b)} + \underbrace{u^\top W_{k,E} E_{x_j}}_{(c)} + \underbrace{v^\top W_{k,R} R_{i-j}}_{(d)}

The paper gives each of the four terms the following meaning.

TermMeaningDetermined by
(a)Content-based addressingContent of the query and key words
(b)Content-dependent positional biasQuery content and distance iβˆ’ji - j
(c)Global content biasKey content only (same for every query)
(d)Global positional biasDistance iβˆ’ji - j only

In practice, this is combined with segment-level recurrence. In layer nn, keys and values are produced from the sequence that concatenates the memory mnβˆ’1m^{n-1} (the hidden states of the previous segment, with gradients stopped) and the hidden states hnβˆ’1h^{n-1} of the current segment, while queries are produced from the current segment only.

h~nβˆ’1=[SG(mnβˆ’1)∘hnβˆ’1],q=hnβˆ’1Wq⊀,k=h~nβˆ’1Wk,E⊀,v=h~nβˆ’1Wv⊀\tilde{h}^{n-1} = \bigl[\mathrm{SG}(m^{n-1}) \circ h^{n-1}\bigr], \quad q = h^{n-1} W_q^\top, \quad k = \tilde{h}^{n-1} W_{k,E}^\top, \quad v = \tilde{h}^{n-1} W_v^\top Ai,j=qi⊀kj+qi⊀Wk,RRiβˆ’j+u⊀kj+v⊀Wk,RRiβˆ’jA_{i,j} = q_i^\top k_j + q_i^\top W_{k,R} R_{i-j} + u^\top k_j + v^\top W_{k,R} R_{i-j}

A causal mask is applied to these scores, softmax is taken, and the values are summed with the resulting weights. No position is added to the values.

Computing (b) naively for every pair (i,j)(i, j) requires a number of vectors Wk,RRiβˆ’jW_{k,R} R_{i-j} proportional to the square of the sequence length. Appendix B of the paper uses the fact that the distance iβˆ’ji - j only ranges from 00 to M+Lβˆ’1M + L - 1 (MM is the memory length and LL the segment length): it computes each distance once and then rearranges the results by shifting each row. This way, computing the distance vectors costs only an amount proportional to the sequence length.

Why relative position enables segment reuse

Position information gives the model cues about "where to look." The paper argues that it is more natural to inject these cues directly into the score of every layer rather than adding them once to the input embeddings, and that representing them as relative distances rather than absolute positions generalizes better. When a query looks at earlier words, it can judge order by knowing how many words back each key is, without knowing the key's position in the sentence. Moreover, given distances, absolute positions can be recovered recursively by following them, so no position information is lost.

Think of book pages: if page numbers (absolute positions) restart at 1 in every chapter, page 3 of the previous chapter gets confused with page 3 of the current chapter. Counting "how many pages back from the page being read" avoids confusion even across chapters.

There are two differences from relative position representations (the method of Shaw et al.).

  • It has terms (c) and (d): The method of Shaw et al. only has terms corresponding to (a) and (b), without the two bias terms (c) and (d).
  • It represents distance with sinusoids: The method of Shaw et al. merges WkRW_k R into a single learned matrix, whereas Transformer-XL keeps the sinusoidal RR and multiplies it by the weight Wk,RW_{k,R}. The paper states that thanks to this sinusoidal inductive bias, a model trained with memory of a certain length can handle memory several times longer at evaluation time.

In the analysis in the paper's appendix, the overall tendency to attend to nearby words arises mainly from term (b); term (d) also favors nearby words but is flatter than (b) and tends to look farther.

Experimental results

Comparison of position representations and segment reuse (excerpt from Table 6 in the paper): Perplexity of 128M-parameter models on WikiText-103 (lower is better). The attention length during training is 128. "Same length as training" uses the same length at evaluation; "best" is the best value obtained by changing the attention length at evaluation, along with that length. For the loss, "full" computes it at all positions in the segment and "half" only at the latter half of positions.

ReusePosition representationLossSame length as trainingBestLength at best
YesTransformer-XL methodFull27.0226.77500
YesShaw et al. relative position representationsFull27.9427.94256
YesTransformer-XL methodHalf28.6928.33460
NoTransformer-XL methodFull29.5929.02260
NoShaw et al. relative position representationsFull29.7529.75120
NoSinusoidal (absolute position)Half30.9730.97120

The best value was obtained when both segment reuse and the Transformer-XL position representation were used. Also, only the Transformer-XL position representation improved accuracy when the attention length was extended at evaluation. Although training used only length 128, evaluation improved with lengths extended to 500. The paper notes that the absolute position method could only be trained well with the "half" loss.

Data that does not need long dependencies (Table 7 in the paper): Models of about 300M parameters compared on One Billion Word, which does not require long dependencies.

SettingPerplexity
Transformer-XL (with reuse, this method)25.2
Position replaced with Shaw et al. relative position representations25.7
Without reuse27.1

Even on short sentences, this method outperformed the method of Shaw et al.

Effective context length (Table 8 in the paper): The paper also compares the longest context over which extending it still yields gains (relative effective context length, RECL). For models of the same size, Transformer-XL reached 700 (at r=0.1r = 0.1, where rr is the fraction of hardest examples considered), but this dropped to 400 when the position representation was replaced with that of Shaw et al., and to 300 without reuse.

Practical considerations

This method adds terms (b) and (d), which take a dot product with the query for each distance iβˆ’ji - j, so it cannot be computed with ordinary attention matrix multiplications alone. The shift-and-rearrange computation in Appendix B must be implemented, and fast implementations such as FlashAttention may not be usable as is.

Also keep the following in mind.

  • Stop gradients through the memory: The hidden states of the previous segment are used as fixed values that do not propagate gradients. If gradients flowed through them, computation and memory would grow without bound.
  • The memory holds the hidden states of "the layer below": The keys and values of layer nn use the output of layer nβˆ’1n-1 for the previous segment. As a result, the reachable distance grows with each layer and is proportional to the number of layers times the segment length.
  • Range of distances: Distances range from 00 to "memory length + segment length βˆ’ 1." Extending the memory at evaluation uses sinusoids for large distances never seen in training. In the paper's experiments this improved accuracy, but how far it can be extended should be verified for each dataset and model.

In the paper's equations, uu and vv are single vectors independent of the query position. The PyTorch implementation below gives each head its own copy of each and computes (a) + (c) together as (qi+u)⊀kj(q_i + u)^\top k_j, and (b) + (d) together as (qi+v)⊀Wk,RRiβˆ’j(q_i + v)^\top W_{k,R} R_{i-j}.

Comparison with other position representations

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 representationsPer-distance vectors added to scores and values in every layerYes (vectors for 2k+12k+1 distances)Computable because the distance is clippedTranslation, etc.
Transformer-XL relative positional encoding (this article)Terms (b)(c)(d) using distance sinusoids added to scores in every layerYes (Wk,RW_{k,R} and uu, vv)Improved when memory was extended (128 β†’ 500 in the paper)Transformer-XL
T5 relative position biasA learned number per distance bucket added to scores in every layerYes (32 buckets Γ— number of heads)Improves up to about 2Γ— the lengthT5
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 process long text segment by segment while reusing the hidden states of the previous segment, the Transformer-XL method is a good fit. Absolute positions cannot distinguish positions across segments, so relative position is essential for this use.
  • To keep computation light, candidates include the T5 relative position bias and ALiBi, which just add one number per distance, and RoPE, which does not change the form of the score. The Transformer-XL method costs more because it takes a dot product with the query for each distance.
  • To also represent the relation between word content and distance (such as "this kind of word looks nearby"), this method, which has term (b), or relative position representations are a good fit. The T5 method and ALiBi add numbers that depend only on distance, so they do not represent this relation.

PyTorch example

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


def sinusoid(klen: int, d: int) -> torch.Tensor:
    """Sinusoids R for distances klen-1, ..., 1, 0 (not learned). [klen, d]"""
    dist = torch.arange(klen - 1, -1, -1.0)
    inv_freq = 1.0 / (10000 ** (torch.arange(0, d, 2).float() / d))
    ang = dist[:, None] * inv_freq[None, :]
    return torch.cat([ang.sin(), ang.cos()], dim=-1)


class RelMultiHeadAttention(nn.Module):
    """One attention layer of Transformer-XL (A_rel in Section 3.3 of the paper)"""

    def __init__(self, d_model: int, n_head: int):
        super().__init__()
        self.h, self.dh = n_head, d_model // n_head
        self.w_q = nn.Linear(d_model, d_model, bias=False)
        self.w_kv = nn.Linear(d_model, 2 * d_model, bias=False)   # W_{k,E} and W_v
        self.w_r = nn.Linear(d_model, d_model, bias=False)        # W_{k,R} (key weight for distance)
        self.u = nn.Parameter(torch.zeros(n_head, self.dh))       # (c) global content bias
        self.v = nn.Parameter(torch.zeros(n_head, self.dh))       # (d) global positional bias
        self.out = nn.Linear(d_model, d_model, bias=False)

    def forward(self, h: torch.Tensor, mem: torch.Tensor) -> torch.Tensor:
        B, L, D = h.shape
        M = mem.shape[1]
        cat = torch.cat([mem.detach(), h], dim=1)                  # [SG(m) ∘ h]: stop gradients through the memory
        klen = M + L
        q = self.w_q(h).view(B, L, self.h, self.dh)                # queries from the current segment only
        k, v = self.w_kv(cat).view(B, klen, 2, self.h, self.dh).unbind(2)
        r = self.w_r(sinusoid(klen, D)).view(klen, self.h, self.dh)  # W_{k,R} R (once per distance)

        ac = torch.einsum("bihd,bjhd->bhij", q + self.u, k)        # (a) + (c)
        bd_raw = torch.einsum("bihd,chd->bhic", q + self.v, r)     # (b) + (d). Column c is distance klen-1-c
        # Rearrange columns to match the distance M+i-j between query i (position M+i overall) and key j (the shift in Appendix B)
        dist = (M + torch.arange(L))[:, None] - torch.arange(klen)[None, :]
        idx = (klen - 1 - dist).clamp(0, klen - 1)
        bd = bd_raw.gather(-1, idx.expand(B, self.h, L, klen))

        score = (ac + bd) / math.sqrt(self.dh)                     # dividing by √d follows common implementations
        score = score.masked_fill(dist < 0, float("-inf"))         # do not look at future words
        attn = score.softmax(dim=-1)
        out = torch.einsum("bhij,bjhd->bihd", attn, v).reshape(B, L, D)
        return self.out(out)


# Process segments in order, using this layer's input as memory for the next segment
B, L, M, D = 2, 4, 4, 64
layer = RelMultiHeadAttention(D, n_head=8)
mem = torch.zeros(B, 0, D)                     # no memory at first
for seg in torch.randn(3, B, L, D):            # three segments of length 4
    out = layer(seg, mem)
    mem = seg[:, -M:].detach()                 # memory for layer n is the layer n-1 hidden state of the previous segment
    print(out.shape)                           # torch.Size([2, 4, 64])

FAQ

Q. How does it differ from relative position representations (the method of Shaw et al.)?
A.

The method of Shaw et al. has only the terms corresponding to (a) and (b) of the score and learns the per-distance vectors entirely. The Transformer-XL method adds the two bias terms (c) and (d) and represents distance by multiplying the non-learned sinusoids Riβˆ’jR_{i-j} by the weight Wk,RW_{k,R}. In the paper's comparisons (WikiText-103, One Billion Word), the Transformer-XL method achieved lower perplexity and gained more when attention was extended at evaluation.

Q. Can it be used in models that do not reuse segments?
A.

Yes. Setting the memory length to 0 gives attention that uses relative position within an ordinary single sequence. In Table 6 of the paper, the model using the Transformer-XL method without reuse (perplexity 29.59) also did better than sinusoidal encoding without reuse (30.97) and the method of Shaw et al. (29.75). The effect is largest, however, when combined with segment reuse.

Q. What do $u$ and $v$ learn?
A.

uu represents "words that tend to be attended to from any query" (the global content bias), and vv represents "distances that tend to be attended to from any query" (the global positional bias). In the original Transformer, these places held the absolute query position UiU_i; to use only relative position, they are replaced with learned vectors that do not depend on position.

References

  1. Z. Dai, Z. Yang, Y. Yang, J. Carbonell, Q. V. Le, and R. Salakhutdinov, "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context," ACL, 2019.
  2. P. Shaw, J. Uszkoreit, and A. Vaswani, "Self-Attention with Relative Position Representations," NAACL, 2018.
  3. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.