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 and two learned vectors and . 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 within each segment are added to the input, as with sinusoidal positional encoding, the -th word of the previous segment and the -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.

