TL;DR
A Transformer language model can only see a fixed window of text, because each window is processed on its own and the text before it is thrown away. Transformer-XL keeps the hidden states of the previous window and lets the next window attend to them, so information can flow across windows. It also replaces the usual absolute position codes with relative ones, which is what makes reusing those states coherent. The paper reports dependencies 80% longer than RNNs can use, and evaluation more than 1,800 times faster than a vanilla Transformer at long attention lengths.
Builds on: Transformer, Positional Encoding, Language Model · Leads to: long-context language models that carry state across segments.
Why it mattered
Language models trained on long documents need to remember things from many sentences back: a character introduced early in a story, a variable defined at the top of a program. Its numbers were state of the art when it appeared. It set new results on WikiText-103 (perplexity 18.3), enwik8 (0.99 bits per character with the largest model), text8 (1.08), One Billion Word (21.8) and Penn Treebank (54.52, without finetuning).
The method also changed how evaluation is done. The vanilla model recomputes the representations of earlier text from scratch, which is slow. Transformer-XL reuses cached states, and the paper reports evaluation up to 1,874 times faster than the vanilla model at attention length 3,800.
The problem
Before this paper, a Transformer language model handled long text by cutting it into fixed-length segments and training each segment alone. The paper calls the baseline the vanilla model. It has two costs.
The first is a hard limit on dependency length. No information crosses a segment boundary, so the longest dependency the model can learn is the segment length, which the paper says is "a few hundred" characters in character-level models. Self-attention does not suffer from vanishing gradients the way recurrent networks do, but this cap means the model cannot use that advantage.
The second is context fragmentation. Cutting text at fixed positions ignores sentence and other semantic boundaries. The first few symbols of each segment then have almost no context, so they are hard to predict, which slows learning and hurts results.
LSTMs had a different problem. They are hard to optimize because of vanishing and exploding gradients, and the paper cites a finding that LSTM language models use about 200 context words on average. The gap is in both directions: the Transformer can attend across long ranges in principle, but the vanilla training setup does not let it.
How it works
Here is the idea on a tiny case. The segment length is 2, and the text is the four tokens "a b c d". The vanilla model splits it into [a, b] and [c, d] and trains each segment alone. Transformer-XL does the same split, but it keeps the hidden states computed for [a, b] and lets the segment [c, d] attend to them as extra context.
flowchart LR
subgraph S1[Segment 1: a b]
H1[hidden states h1 at each layer]
end
subgraph S2[Segment 2: c d]
H2[new hidden states h2]
end
H1 -- cached, stop-gradient memory --> H2
S2 --> P[predict next tokens]
-
Split the text into segments. Segment 1 is [a, b] and segment 2 is [c, d]. Each has length . In the paper's own runs the length is in the hundreds.
-
Process segment 1 as usual. Each layer produces a hidden state for every position in the segment. Toy check: a hidden state for "a" can see only "a", and "b" sees "a" and "b".
-
Cache the states. Before moving on, the hidden states of segment 1 at each layer are stored. The paper applies a stop-gradient to them, so gradients do not flow back into the cached segment.
-
Give segment 2 the cache as extra context. When segment 2 is processed, each layer's keys and values are computed over the cached states followed by the current segment's states. In the toy case, "c" can now attend to "a", "b" and itself, and "d" can attend to "a", "b", "c" and itself. The queries still come only from the current segment.
-
Use relative positions. The cached states came from positions 1 and 2 in an earlier segment, and the current segment also starts at position 1. Reusing absolute position codes would give "a" and "c" the same code, since both are first in their segment. The fix is to encode the distance between query and key, , inside the attention score instead of adding a position code to the input. Toy check: "d" is at distance 1 from "c" and distance 3 from "a", whichever segment each came from.
-
Stack the recurrence across layers. Each layer's cache is one layer lower than its own output, so the reach of the dependency grows with depth as well as with segment length. The paper gives the maximum dependency length as for layers and segment length . Toy check: with 2 layers and , the reach is about 4 positions, twice the single-segment window.
-
Evaluate with the cache. At test time the cached states are reused rather than recomputed. This is where the speed-up comes from. The paper also raises the cache length at evaluation, which lets the model see more context than it saw in training.
The math
Step 1 in symbols. Language modeling factorizes the probability of a corpus as , so the task is to model each next-token distribution. Segments are , and is the layer- hidden state of segment , where is the hidden size.
Step 3 and 4 in symbols. The hidden states of the previous segment are concatenated with the current ones, with a stop-gradient on the cached part:
Here means concatenation along the length dimension. The queries come from the current segment only, and the keys and values come from the extended sequence:
Step 5 in symbols. In the vanilla Transformer, the attention score between query position and key position splits into four terms: content-to-content, content-to-absolute-position, absolute-position-to-content, and absolute-to-absolute. Transformer-XL rewrites them using only the relative distance , with a fixed sinusoidal matrix and two learned vectors and :
Term (a) is content-based addressing. Term (b) is a position bias that depends on the content of the query. Terms (c) and (d) are biases that do not depend on the query's position, which is why the query vector is replaced by the learned and . The paper uses separate key matrices for content and for position.
Toy check of the distance term: if is the code for distance 1 and for distance 3, then position attending to and to get different position terms regardless of which segment each came from. That is what lets reused states keep their order.
Results
Language modeling benchmarks. The paper reports perplexity for word-level models (lower is better) and bits per character for character-level models (lower is better). Table values are as printed in the paper.
| Benchmark | Previous best | Transformer-XL |
|---|---|---|
| WikiText-103, perplexity, large model | 20.5 | 18.3 |
| enwik8, bpc, 24-layer model (277M) | 1.06 (64-layer vanilla, 235M) | 0.99 |
| text8, bpc, 24-layer model (277M) | 1.13 (64-layer vanilla, 235M) | 1.08 |
| One Billion Word, perplexity, large model | 23.7 | 21.8 |
| Penn Treebank, perplexity, no finetuning | 55.3 | 54.52 |
On enwik8, the 12-layer Transformer-XL (41M parameters) matches the 64-layer vanilla Transformer (235M parameters) at 1.06, using about 17% of the parameter budget. On WikiText-103, the standard 151M model scores 24.0 perplexity and the large 257M model scores 18.3.
Dependency length. The paper's relative effective context length (RECL) measures how far back a model's predictions still improve. Transformer-XL (151M) reaches about 900 words at the top-10% hard examples, and the paper reports it is 80% longer than the best recurrent model and 450% longer than the vanilla Transformer.
Ablations. On WikiText-103, the paper removes each of its two ideas. Using the standard 128M model, the full method with recurrence reaches 27.02 perplexity; with the Shaw et al. relative encoding it reaches 27.94; without recurrence it reaches 29.59 (initial-length evaluation; 29.02 with the best evaluation length). On One Billion Word, a dataset with no long-range dependencies, recurrence alone helps: 25.2 with it, 27.1 without. This separates the two effects. Recurrence helps even when long context is not needed, because it removes fragmentation.
Speed. Evaluation is up to 1,874 times faster than the vanilla model at attention length 3,800, and 363 times faster at length 800.
Limits. The method costs extra memory for the cache, which the authors address by comparing under the same GPU memory budget and still finding Transformer-XL better. The experiments are on language modeling and the paper's generated samples are trained on WikiText-103 only, so the claim about coherent text is qualitative. The paper does not test on tasks outside language modeling. The stop-gradient means no gradient flows into the cached segment, so training does not shape those cached states through the recurrence.
Reading guide
- Section 1, Introduction: needs Transformer and Language Model. The two contributions in its last paragraphs are the recurrence and the position encoding; read them together.
- Section 2, Related Work: needs Recurrent Neural Network to see what LSTM-based models were trying to do.
- Section 3.1, Vanilla model: needs Autoregressive Model for the factorization and Positional Encoding for the absolute position codes it replaces.
- Section 3.2, Recurrence: the core idea. The stop-gradient and the reach are the two things to hold on to. The comparison to truncated Backpropagation Through Time is worth the time.
- Section 3.3, Relative positional encodings: the four-term decomposition. Work through terms (a) to (d) on paper before reading the rewrite.
- Section 4, Experiments: the tables are the main results. Table 6 is the ablation and Table 8 the RECL measure. Perplexity is defined in Perplexity.
- Appendices: the RECL definition and the memory-constrained comparison.
Check yourself
QuestionWhy does the vanilla model's dependency length have a hard cap, and what does Transformer-XL change to remove it?Show answer
In the vanilla model each segment is trained alone, so no information crosses a segment boundary and the longest dependency is limited to the segment length. Transformer-XL caches the previous segment's hidden states and lets the current segment attend to them, so information can pass from one segment to the next and the reach grows with depth and segment length.
QuestionIn the paper's toy setup, a 2-layer model with segment length 2 processes a long text. Using the bound of length times layers, roughly how far back can a position see?Show answer
The paper gives the maximum dependency length as . With and the product is 4, so a position can see roughly four positions back, twice what a single segment of length 2 allows. This is an order-of-magnitude bound, so "about 4" is the right level of precision.
QuestionWhy does reusing cached hidden states require relative rather than absolute position encodings?Show answer
A cached segment and the current segment both start at position 1 in their own coordinates. With absolute encodings added to the input, the model cannot tell that a key from the cache is one segment earlier than a key from the current segment, so the positions become ambiguous. Encoding the distance inside the attention score removes that ambiguity, because the distance between a query and a key is the same whichever segment each came from.
QuestionOn enwik8 the 12-layer Transformer-XL reports 1.06 bpc with 41M parameters, and the 64-layer vanilla Transformer reports 1.06 with 235M. What fraction of the parameters does the Transformer-XL use?Show answer
41 / 235 is about 0.174, so about 17% of the parameter budget. The paper states this as "17%".
QuestionA colleague says Transformer-XL is 1,874 times more accurate than the vanilla Transformer. What is wrong with that claim?Show answer
The 1,874 figure is a speed-up, measured as how much slower the vanilla model runs at evaluation (Table 9, attention length 3,800). It is not an accuracy measure. Accuracy is reported as perplexity or bits per character, and the paper's accuracy gains are much smaller numbers, such as 20.5 to 18.3 perplexity on WikiText-103.
Sources
- Dai et al., Transformer-XL: Attentive Language Models beyond a Fixed-Length Context — arXiv:1901.02860
- Vaswani et al., Attention Is All You Need — arXiv:1706.03762