TL;DR
XLNet is a pretraining method for Transformers that keeps the autoregressive rule (predict each word from the words before it in some order) but trains over random orders of the words. Across those orders every word is predicted from context on both sides, and the input never contains a special mask token, which the paper identifies as a source of mismatch between BERT's pretraining and fine-tuning. The paper reports that XLNet beats BERT across many tasks under comparable settings, with large gains on reading comprehension and question answering.
Builds on: Permutation Language Modeling, Masked Language Modeling · Leads to: the line of pretrained encoders from 2019 and 2020 that were judged against BERT and RoBERTa on these benchmarks
Why it mattered
XLNet was one of the strongest pretrained models on the standard language understanding benchmarks in mid-2019, and it became a reference point for the next year of encoder research. Its reported scores on SQuAD and RACE, two reading comprehension benchmarks, moved the state of the art by several points,.
The paper also showed that the two main pretraining families, autoregressive and masked, could be compared on equal terms. The authors trained XLNet and BERT with the same data and the same hyperparameters, so the gap came from the objective and architecture, not from more data. That comparison is part of why the field started to treat objectives as a design choice to be measured rather than a fixed recipe.
The problem
By 2019 there were two successful pretraining objectives, and each had a clear flaw. Autoregressive language modeling factorises the probability of a sentence into one-step predictions, which gives a clean training signal. But each prediction sees only one side of the word, so it misses the context on the other side that many understanding tasks need. Masked language modeling, used by BERT, hides some words and predicts them from both sides. But the mask token never appears in real text, so pretraining and fine-tuning see different inputs. And because the masked words are predicted separately from one another, the model cannot use the product rule to model the dependency between them.
The paper's question was whether one objective could keep the good parts of both: the exact factorisation of the autoregressive family and the two-sided context of the masked family.
How it works
XLNet's pipeline has five stages. The walkthrough below uses the paper's own example sentence, "New York is a city", with positions 1 to 5 holding "New", "York", "is", "a" and "city".
- Take a pretraining sequence and keep it in its normal order. The paper's Remark on Permutation is explicit that only the factorisation order changes; the input and its positional information stay as they are. Check: position 2 still holds "York" and still knows it is the second word.
- Sample a factorisation order, a random permutation of the five positions. Say the draw is . Check: each position appears exactly once.
- Choose which predictions to train on. Only the last part of the order is predicted, so the earliest positions, which have little context, are skipped. With the paper's setting for XLNet-Large, about one token in six is predicted. Check: in this order the model predicts the last token, "York", and the context for it is every other word.
- Run the two streams of attention. The content stream builds representations that include each word. The query stream builds, for each target position, a representation that knows the position but not the word there, so the model can predict the word without copying it. Check: the query for position 2 sees the content of positions 3, 5, 1 and 4, but not the content at position 2.
- Score the predictions. The loss is the sum of the log-probabilities of the predicted words, given the words revealed before each one in the sampled order. Training averages this over orders and sequences, and the same weights are used for all orders.
flowchart TB A[Sequence kept in normal order] --> B[Sample a factorisation order] B --> C[Choose the last tokens of the order as targets] C --> D[Content stream: word plus position] C --> E[Query stream: position only] D --> F[Query reads content of earlier positions] E --> F F --> G[Log-probability of each target word] G --> H[Average over orders and update weights]
The model also uses two architecture pieces from Transformer-XL, the autoregressive Transformer of the same authors. The first is relative positional encoding, which describes how far apart two tokens are rather than giving each token an absolute index, so Positional Encoding is applied to distances. The second is segment recurrence, which lets a segment of text reuse cached hidden states from the segment before it. Both are applied on top of the permutation objective.
Worked examples
Take a three-word sentence with positions 1, 2, 3. There are orders. For each order, look at what the word at position 2 sees when it is predicted.
- Order : position 2 is first, so it sees nothing.
- Order : position 2 is first again, so it sees nothing.
- Order : position 2 is second, and it sees position 1 only.
- Order : position 2 is second, and it sees position 3 only.
- Order : position 2 is last, and it sees positions 1 and 3, both sides.
- Order : position 2 is last again, and it sees both sides.
- Count the orders: 2 with no context, 2 with one side, and 2 with both sides. So the word at position 2 sees both sides in of orders. The average over orders is what the objective rewards, and it is why the model learns two-sided use of context even though each single prediction is one-directional.
Take a sequence of words, with . The relation gives , so and the model predicts the last two words of the order.
- The sampled order ends with positions and . The objective sums over and .
- Suppose the model gives the word at a probability of . Its log is .
- Suppose it gives the word at a probability of . Its log is .
- Add the two logs: . This is the contribution of this order to the objective.
- Ten words are not predicted in this order, but their hidden states still serve as context for the two targets.
- Interpretation: the cut point turns a 12-word training signal into one that focuses on two hard predictions, each with about ten words of context.
The RACE reading comprehension benchmark is scored by accuracy on the test set. The paper's Table 2 reports 83.2% for RoBERTa and 85.4% for XLNet, both as single models in the comparison the table makes.
- RoBERTa's error rate is percent.
- XLNet's error rate is percent.
- The absolute gain is percentage points.
- The share of RoBERTa's errors that XLNet removes is , or about 13%.
- Interpretation: an improvement of about 2 points looks modest in absolute terms, but it removes about one error in eight that RoBERTa made on this benchmark.
Try it: on SQuAD 2.0 dev, the paper reports F1 of 81.77 for BERT and 90.6 for XLNet. What share of the gap between BERT and a perfect 100 does XLNet close? Answer: the remaining gap for BERT is , and XLNet closes of it, which is , about 48%.
The math
Step 1 in symbols: the objective
For a sequence , let be the set of all permutations of . For one permutation , the words revealed before step are . The permutation language modeling objective is
Here are the parameters, shared by all orders, and is the average over sampled orders. The expression is the autoregressive product rule, applied in each order, averaged over orders. Its meaning is laid out in Permutation Language Modeling.
Step 2 in symbols: why the same weights can serve every order
The model reads only the words before a target in its order, so the context for a target is a function of the set of revealed positions. Because the parameters are shared across orders, the model learns to use context from positions on either side. The paper states that in expectation, each word has seen every other word in the sequence.
Step 3 in symbols: the target-aware prediction
If the next-word distribution depended only on the context , it would be the same for every target position, because the context does not change with the target. The paper therefore makes the distribution depend on the target position too:
Here is the embedding of word , is the query representation, and the denominator is the Softmax over the vocabulary.
Step 4 in symbols: the two streams
The content representation encodes the context and the word at . The query representation encodes the context and the position , but not the word. For layer of the Transformer, the paper updates the two streams with shared parameters :
The query stream attends only to positions revealed before , and does not include the word at in its keys and values. The content stream also attends to itself. The first layer's query starts from a trained vector and the content stream from the word embedding. After pretraining, the query stream is dropped, and the content stream runs as an ordinary Transformer.
Step 5 in symbols: partial prediction
Let be a cut point and split the order into a non-target part and a target part . The objective becomes
The paper chooses with a hyperparameter so that , which predicts about of the tokens. The authors give two reasons: the last tokens of an order have the most context, and predicting every token made optimisation slow in their preliminary runs.
Results
The paper reports four kinds of evidence.
The first is a fair comparison with BERT. Table 1 trains XLNet-Large on the same data and hyperparameters as BERT-Large. XLNet beats the best of three BERT variants on every dataset in the table. For example, on RTE the scores are 74.0 for BERT and 81.2 for XLNet, and on SQuAD 2.0 the F1 scores are 85.5 for BERT and 87.8 for XLNet.
The second is scale. Table 2 compares XLNet with RoBERTa on RACE. XLNet scores 85.4% against 83.2% for RoBERTa and 72.0% for BERT, and the paper reports that its ClueWeb09-B document ranking score also beats BERT.
The third is reading comprehension on SQuAD. On the dev sets, XLNet reaches an F1 of 95.1 on SQuAD 1.1 and 90.6 on SQuAD 2.0, against 90.9 and 81.77 for the BERT runs the authors reproduced or reported.
The fourth is breadth: on the benchmarks the paper reports, XLNet is ahead of BERT on every dataset in Table 1, and the gains span question answering, natural language inference, sentiment analysis and document ranking.
The limits are equally clear. The largest results combine a much larger pretraining corpus with a larger model, so the objective is not the only factor. The ablations in Table 6 show that both the permutation objective and the Transformer-XL backbone contribute to the gain over BERT. And the claimed advantage rests on the authors' own benchmarks and reruns; later readers should check which numbers are single models and which are ensembles, since some table entries are.
Common mistakes and tradeoffs
It is tempting to think XLNet shuffles the input sentence. In fact the sequence keeps its order, and only the factorisation order changes. The paper says this choice is needed because fine-tuning sees text in its natural order.
It is tempting to think XLNet is a bidirectional encoder in the BERT sense. In fact each conditional is one-directional in its own order, and the two-sided context appears only in expectation across orders. Within one sentence, a given prediction still sees a subset of the words.
It is tempting to read the 20-task result as a clean win. The comparison is fair on data and hyperparameters, as the paper's Table 1 shows, but the pretraining mix goes well beyond BERT's data: it adds Giga5, ClueWeb 2012-B and Common Crawl to the 13 GB of BooksCorpus and Wikipedia that BERT uses. The fair Table 1 comparison controls for this, but the headline Table 2 numbers do not.
The method has costs of its own. It needs two streams, sampled orders and extra masks, so each step costs more than plain masked pretraining. Partial prediction means only a fraction of tokens give a training signal per sequence, which the paper addresses with the cut point but does not remove.
Use it when you are pretraining an encoder for understanding tasks and can afford the compute. Do not use it for text generation, where a plain autoregressive model with a KV Cache is simpler. A masked model such as BERT is a cheaper alternative when compute is tight.
Reading guide
The paper is long, so read it in this order.
- Abstract and Section 1: the two flaws of BERT and the idea of permutation language modeling. Needs Autoregressive Model and Masked Language Modeling.
- Section 2.1, Background: the three comparisons between the autoregressive and masked objectives. Needs Language Model and Cross-Entropy Loss.
- Section 2.2, Objective: the permutation objective and the remark that only the order of factorisation changes. Needs Permutation Language Modeling and Conditional Probability.
- Section 2.3, Architecture: the two-stream attention. Needs Attention Mechanism, Multi-Head Attention and Softmax. The paper also depends on Attention Is All You Need for the base architecture.
- Section 2.4, Transformer-XL ideas: relative positional encoding and segment recurrence. Needs Positional Encoding.
- Section 2.5, Multiple segments: how two segments are packed into one input. Needs Word Embedding.
- Section 3, Experiments: the fair comparison with BERT and the benchmark results. Needs Fine-Tuning for how models are adapted to each task.
- Appendices: formal analysis of the objective and additional ablations. Read them after the main text.
Check yourself
QuestionWhat does the permutation in XLNet change, and what does it leave alone?Show answer
It changes the order in which words are predicted, which determines the context each prediction can use. It leaves the order of the input sequence alone, along with the positional information attached to each word, because fine-tuning sees text in its natural order.
QuestionFor three words, the word at position 2 is predicted last in 2 of the 6 orders. In what fraction of orders does it see both of its neighbours?Show answer
It sees both sides only when it is predicted last in the order, and that happens in 2 of 6 orders, so the fraction is .
QuestionA sequence has words and . Using , how many words are predicted per order?Show answer
The relation gives , so four words are predicted per order, which is about one in five of the 20.
QuestionWhy does the query stream exist alongside the content stream? Explain in terms of what the prediction would do without it.Show answer
Without the query stream, the representation of the context would be the same for every target, so the model could not tell which word to predict. Including the target word in its own representation would make the prediction a copy of the input and the objective trivial. The query stream carries the target position but not the target word, which resolves both problems.
QuestionA team is building a classifier for customer messages and cares only about its accuracy on that task. They have a fixed compute budget and cannot afford XLNet-Large. What should they weigh before choosing an objective?Show answer
They should weigh how much training compute XLNet's extra streams, sampled orders and partial prediction cost against what they gain in task accuracy. A masked model such as BERT is cheaper and well understood, and the paper's gains depend on large pretraining corpora and large models. A smaller pretrained encoder that fits the budget may beat XLNet on this task, so they should test on their own data rather than rely on the paper's benchmarks.