AI Logic

Architectures

XLNet

Updated:

XLNet architecture. Left: the overall pretraining flow (the input in its original order, content-stream and query-stream embeddings, repeated layers that use the previous segment's memory, and token prediction from the query stream), and, for an example prediction order 3β†’2β†’4β†’1, the ranges that the content stream and the query stream can see. Right: inside a layer (relative-position self-attention and feed-forward)

Background and overview

XLNet is a pretrained language model that can use both left and right context by training an autoregressive language model over randomly permuted orders of predicting the words in a sentence. It was proposed in 2019 by Yang et al. of Carnegie Mellon University and Google. Its architecture is Transformer-XL, which can handle long contexts.

XLNet aims to combine the strengths of the two earlier kinds of pretraining:

  • Autoregressive language models (GPT and others): predict the next word from the preceding words, one by one. They correctly learn dependencies between words in the form of a product of probabilities, but each word sees only one side (the left) of the context.
  • Denoising autoencoders (BERT and others): replace some words with [MASK] and restore them. They can use both left and right context, but they predict the masked words as if they were independent of each other, and they use [MASK], which never appears in real input, during pretraining, so the input looks different between pretraining and fine-tuning.

XLNet trains a permutation language model that makes autoregressive predictions in a permuted order of the words. It uses no [MASK] and can still learn dependencies among the predicted words. On top of that, it incorporates two-stream attention, which tells the model which position to predict, and Transformer-XL's segment memory and relative positional encoding.

In the paper, even when trained on the same data with the same settings as BERT, XLNet outperformed BERT on all 11 tasks from SQuAD, RACE, and GLUE. With more data, it outperformed BERT on 20 tasks, including 85.4% accuracy on the RACE reading comprehension task (RoBERTa: 83.2%).

Architecture

The body of XLNet is a stack of MM Transformer-XL layers. In the figure at the top of the article, the left shows the overall pretraining flow and, for an example prediction order, which positions can be seen; the right shows the inside of one layer.

The largest model, XLNet-Large, matches BERT-Large in number of layers, vector size, and so on, and is nearly the same size.

ItemXLNet-Large
Number of layers MM24
Hidden size1024
Number of heads16 (head size 64)
Feed-forward inner size4096
Input length512 tokens
TokenizationSentencePiece

As in the original Transformer, each layer consists of two sublayers, multi-head attention and feed-forward, each followed by a residual addition and layer normalization. It differs from the Transformer in three ways:

  1. Two streams: Each position holds two kinds of vectors.
    • Content stream hh: represents the word at that position itself together with its context. It plays the same role as the hidden state of an ordinary Transformer. The input to the first layer is the word embedding e(x)e(x).
    • Query stream gg: holds only "where" the position is and the context, and does not see the word at that position. The input to the first layer is a learned vector ww shared across all positions.
  2. Relative positional encoding: Positions are expressed by their positions in the original sentence, and "how far apart two positions are" is added to the attention weights.
  3. Segment memory: When a long text is split and processed in order, the content stream of each layer computed for the previous chunk (segment) is saved and added to the K and V of attention for the next segment.

The two streams share the same weights. In both streams, the attention K and V are built from the content stream hh (and the memory). The only difference is how far each can see:

  • Content stream: sees positions up to and including itself in the prediction order
  • Query stream: sees only positions before itself in the prediction order

During fine-tuning, the query stream is dropped and only the content stream is used, as an ordinary Transformer-XL.

The input sentence itself is not permuted. The word order and positional encodings stay as in the original sentence, and only the attention mask creates the condition that "only words earlier in the prediction order can be seen." This construction is necessary because fine-tuning only ever sees sentences in their natural order.

Training: the permutation language model

XLNet pretraining proceeds as follows:

  1. For a sentence x=(x1,…,xT)\mathbf{x} = (x_1, \dots, x_T) of length TT, randomly pick one order z\mathbf{z} that permutes positions 1,…,T1, \dots, T (out of T!T! possibilities).
  2. Following the order z\mathbf{z}, predict the word at the tt-th position ztz_t from the words at the preceding positions z<t\mathbf{z}_{<t}.
  3. The prediction probability is computed from the query stream gg of the last layer. Because gg knows the position ztz_t being predicted, it can make different predictions for different positions given the same context.
  4. To reduce computation, only about the last 1/K1/K of positions in the order are prediction targets (K=6K = 6 for XLNet-Large). Later positions see more context and are easier to predict.

The objective is the expected log-likelihood over all permutations. ZT\mathcal{Z}_T is the set of all permutations of the positions.

maxβ‘ΞΈβ€…β€ŠEz∼ZT[βˆ‘t=1Tlog⁑pΞΈ(xzt∣xz<t)]\max_\theta \; \mathbb{E}_{\mathbf{z} \sim \mathcal{Z}_T} \left[ \sum_{t=1}^{T} \log p_\theta(x_{z_t} \mid \mathbf{x}_{\mathbf{z}_{<t}}) \right]

Each prediction probability is the softmax of the inner product between the query stream gΞΈ(xz<t,zt)g_\theta(\mathbf{x}_{\mathbf{z}_{<t}}, z_t) and the word embedding e(x)e(x).

pΞΈ(Xzt=x∣xz<t)=exp⁑(e(x)⊀gΞΈ(xz<t,zt))βˆ‘xβ€²exp⁑(e(xβ€²)⊀gΞΈ(xz<t,zt))p_\theta(X_{z_t} = x \mid \mathbf{x}_{\mathbf{z}_{<t}}) = \frac{\exp\left(e(x)^\top g_\theta(\mathbf{x}_{\mathbf{z}_{<t}}, z_t)\right)}{\sum_{x'} \exp\left(e(x')^\top g_\theta(\mathbf{x}_{\mathbf{z}_{<t}}, z_t)\right)}

In each layer mm, the two streams are updated as follows (residual connections, layer normalization, and feed-forward are omitted for readability).

gzt(m)←Attention(Q=gzt(mβˆ’1),β€…β€ŠKV=hz<t(mβˆ’1))hzt(m)←Attention(Q=hzt(mβˆ’1),β€…β€ŠKV=hz≀t(mβˆ’1))\begin{aligned} g_{z_t}^{(m)} &\leftarrow \mathrm{Attention}\left(Q = g_{z_t}^{(m-1)},\; KV = \mathbf{h}_{\mathbf{z}_{<t}}^{(m-1)}\right) \\ h_{z_t}^{(m)} &\leftarrow \mathrm{Attention}\left(Q = h_{z_t}^{(m-1)},\; KV = \mathbf{h}_{\mathbf{z}_{\le t}}^{(m-1)}\right) \end{aligned}

The pretraining setup in the paper is as follows:

ItemValue
DataBooksCorpus and English Wikipedia (13GB total), Giga5 (16GB), ClueWeb 2012-B (19GB), Common Crawl (110GB). 32.89 billion tokens in total
Batch8192 sequences Γ— 512 tokens
Steps500K (about 5.5 days on 512 TPU v3)
OptimizerAdam (learning rate 4Γ—10βˆ’44 \times 10^{-4}, Ο΅=10βˆ’6\epsilon = 10^{-6}), weight decay 0.01
Learning rateWarmup over the first 40K steps, then linear decay
Dropout0.1 for both hidden layers and attention

It also includes the following techniques:

  • Span prediction: Instead of choosing prediction targets one at a time, it selects a contiguous span of length L∈{1,…,5}L \in \{1, \dots, 5\}.
  • Bidirectional data input pipeline: Because memory is used, half of each batch feeds the text forward and the other half backward.
  • Relative segment encoding: Instead of adding a "sentence A or sentence B" embedding as BERT does, only whether two positions are in the same segment is added to the attention weights. This also allows fine-tuning on tasks with three or more input segments.
  • No next sentence prediction: The input format is the same as BERT's [CLS, A, SEP, B, SEP], but next sentence prediction is not used in XLNet-Large because it showed no consistent benefit in experiments.

Why bidirectional context can be learned autoregressively

If the prediction order changes every time, the words that come "before" a given word change every time. Because the same weights are used for all orders, over the course of training each word learns to gather information from words on both its left and its right. Each individual prediction is one-directional, but in expectation the model learns bidirectional context.

Consider predicting the 3rd word of a 4-word sentence. With the order 1 β†’ 2 β†’ 3 β†’ 4, it is predicted from the 2 words on the left; with 4 β†’ 3 β†’ 1 β†’ 2, from the 1 word on the right; and with 2 β†’ 4 β†’ 1 β†’ 3, from all 3 words on both sides. Practicing with many orders teaches the model to use words on either side as clues.

Because training keeps the autoregressive form, it also avoids BERT's two problems. Take the paper's example of predicting [New, York] in "New York is a city." When XLNet's order is [is, a, city, New, York], the two objectives are:

JBERT=log⁑p(New∣is a city)+log⁑p(York∣is a city)JXLNet=log⁑p(New∣is a city)+log⁑p(York∣New,is a city)\begin{aligned} J_{\mathrm{BERT}} &= \log p(\mathrm{New} \mid \text{is a city}) + \log p(\mathrm{York} \mid \text{is a city}) \\ J_{\mathrm{XLNet}} &= \log p(\mathrm{New} \mid \text{is a city}) + \log p(\mathrm{York} \mid \mathrm{New}, \text{is a city}) \end{aligned}

BERT predicts New and York separately, so it cannot learn the dependency between the two words, namely that "York is likely to follow New." XLNet predicts them in order, following the product rule of probability, so it can learn this dependency as well. And because it uses no [MASK], the input does not look different between pretraining and fine-tuning.

This also explains why two streams are needed. The output of an ordinary Transformer, hΞΈ(xz<t)h_\theta(\mathbf{x}_{\mathbf{z}_{<t}}), does not know which position is to be predicted next. For two orders that share the same prefix and differ only in the next position to predict, it would output exactly the same predictive distribution. So XLNet uses the query stream gg, which takes the target position ztz_t as input. However, if gg could see the word at position ztz_t itself, the answer would be given away, so gg does not see its own word. On the other hand, predicting other positions requires information about the word at position ztz_t, so a separate content stream hh, which does see its own word, is maintained.

The permutation language model is harder to optimize than an ordinary language model, and it converged slowly in the paper's preliminary experiments. This is why predictions are restricted to about the last 1/K1/K of the order. Increasing KK lightens the computation but reduces the training signal obtained from each sentence.

Experimental results

Fair comparison with BERT (XLNet-Large trained on the same data and settings as BERT; for BERT, the best of the original BERT, whole word masking, and no next sentence prediction. SQuAD is EM / F1; the others are accuracy)

ModelSQuAD 1.1SQuAD 2.0RACEMNLIQNLIRTESST-2CoLA
BERT-Large86.7 / 92.882.8 / 85.575.187.393.074.094.063.7
XLNet-Large (same data)88.2 / 94.085.1 / 87.877.488.493.981.294.465.2

Even with the same data and compute, XLNet outperformed BERT on every task in the table.

Comparison of the versions with more data (all 24 layers, nearly the same size as BERT-Large)

ModelRACE (test accuracy)SQuAD 2.0 (dev, EM / F1)GLUE MNLI (dev)
BERT72.078.98 / 81.7786.6
RoBERTa83.286.5 / 89.490.2
XLNet85.487.9 / 90.690.8

The paper notes that the gap is especially large on tasks that read long contexts, such as SQuAD and RACE. Its interpretation is that the ability of Transformer-XL's memory to handle long contexts may be contributing. In text classification as well, the IMDB error rate dropped from BERT's 4.51% to 3.20%, and Yelp-5 from 29.32% to 27.05%.

Which techniques helped (same size as the 12-layer BERT-Base, trained only on Wikipedia and BooksCorpus; median of 5 runs)

ModelRACESQuAD 2.0 (F1)MNLI (matched)SST-2
BERT-Base64.376.3084.3492.78
BERT objective + Transformer-XL65.0379.5684.8892.60
XLNet-Base (K=6K = 6)66.6680.9885.6393.35
γ€€without memory65.5580.1585.3292.78
γ€€without span prediction65.9580.6185.4993.12
γ€€without bidirectional data66.3480.6585.3192.66
γ€€with next sentence prediction66.7679.8385.3292.89

Simply switching to Transformer-XL already improves over BERT-Base, and switching the objective to the permutation language model improves it further. Removing memory hurts especially on RACE, which has the longest contexts. Next sentence prediction did not give consistent improvements when added, so XLNet does not use it.

Practical considerations

Keep the following points in mind when using XLNet:

  • Pretraining is computationally heavy: Because each position holds two streams, attention costs more than in BERT. The paper reports that XLNet-Large took about 5.5 days on 512 TPU v3, and that it was still underfitting the data at the end of training.
  • Fine-tuning uses only the content stream: The query stream exists for pretraining. For tasks such as classification, the model is used as an ordinary Transformer-XL.
  • Use a small learning rate for fine-tuning: The paper's settings use learning rates of 1Γ—10βˆ’51 \times 10^{-5} to 3Γ—10βˆ’53 \times 10^{-5}. For SQuAD it also uses layer-wise learning rate decay, with larger rates for upper layers and smaller rates for lower layers (Γ—0.75 per layer).
  • Use the tokenizer that matches the model: XLNet tokenizes with SentencePiece. It is not compatible with BERT's WordPiece tokenizer.

XLNet is trained in an autoregressive form, but it is not an ordinary left-to-right language model. Since pretraining predicts in many different orders, it is not suited as is for continuing text the way GPT does. The paper also evaluates it only on understanding tasks such as question answering, classification, and document ranking.

Because it uses relative positional encoding, unlike BERT, whose input length is fixed by the size of its position embeddings, it can in principle handle inputs longer than 512 tokens. However, pretraining was done with 512 tokens, so whether performance holds for longer inputs must be checked for each task.

Comparison with other models

Comparing pretrained language models from the same perspective gives the following:

ModelArchitectureContext directionPretraining taskUses [MASK]Dependencies among predicted words
GPTTransformer decoder onlyLeft to rightNext word predictionNoLearned
BERTTransformer encoder onlyBoth directionsMasked language model + next sentence predictionYesNot learned (predicted independently)
XLNetTransformer-XL (two streams)Both directions (as an expectation over permuted orders)Permutation language modelNoLearned
RoBERTaTransformer encoder onlyBoth directionsMasked language model (more data and training)YesNot learned

Rough guidelines for choosing:

  • Question answering and reading comprehension over long texts: This is where XLNet's advantages are largest. In the paper, the gaps were large on RACE and SQuAD, which have long contexts.
  • Sentence classification and similar tasks with limited compute: BERT and its improved variants are often easier to work with, since XLNet's pretraining is heavier by the extra stream.
  • Text generation: Use a decoder-only model such as GPT, or an encoder-decoder model such as BART.

PyTorch example

Show code
python
import torch
from transformers import AutoTokenizer, XLNetLMHeadModel, XLNetForSequenceClassification

"""
Example of loading and using a pretrained XLNet with Hugging Face transformers
1. Permutation language model: use perm_mask (which positions cannot be seen) and target_mapping (which positions to predict)
   to make predictions in the same form as pretraining
2. Sentence classification: use only the content stream, add a classification layer, and fine-tune
"""

name = "xlnet-base-cased"
tokenizer = AutoTokenizer.from_pretrained(name)   # SentencePiece


def perm_mask_from_order(order, seq_len):
    """Build perm_mask from the prediction order `order` (a sequence of 0-based positions).
    When perm_mask[0, i, j] = 1, position i cannot see position j.
    Rule for the query stream (the side used for prediction): it can see only positions before itself in the order."""
    rank = torch.empty(seq_len, dtype=torch.long)
    rank[torch.tensor(order)] = torch.arange(seq_len)
    # positions j with rank[j] >= rank[i] (itself or later in the order) cannot be seen
    mask = (rank.unsqueeze(0) >= rank.unsqueeze(1)).float()
    return mask.unsqueeze(0)                        # [1, seq_len, seq_len]


# --- 1. Predict the last word with the permutation language model ---
lm = XLNetLMHeadModel.from_pretrained(name)
lm.eval()                                           # disable dropout
ids = tokenizer("The capital of France is Paris", add_special_tokens=False,
                return_tensors="pt").input_ids     # [1, n]
n = ids.shape[1]
target = n - 1                                      # predict the last position
order = list(range(n - 1))[::-1] + [target]         # example: earlier words right to left, then target last
perm_mask = perm_mask_from_order(order, n)
target_mapping = torch.zeros(1, 1, n)               # [batch, num_predict, seq_len]
target_mapping[0, 0, target] = 1.0
with torch.no_grad():
    logits = lm(ids, perm_mask=perm_mask, target_mapping=target_mapping).logits  # [1, 1, vocab_size]
top5 = logits[0, 0].topk(5).indices
print(tokenizer.convert_ids_to_tokens(top5.tolist()))   # candidates (most probable first)

# --- 2. Classify the relation between two sentences (one fine-tuning step) ---
clf = XLNetForSequenceClassification.from_pretrained(name, num_labels=2)  # the classification layer is newly initialized
optimizer = torch.optim.AdamW(clf.parameters(), lr=2e-5, eps=1e-6, weight_decay=0.01)

batch = tokenizer(
    ["A man is playing a guitar.", "A dog runs in the park."],    # sentence A
    ["A person plays an instrument.", "The cat is sleeping."],    # sentence B
    padding=True, truncation=True, max_length=128, return_tensors="pt")
labels = torch.tensor([1, 0])                                     # 1: related, 0: unrelated

clf.train()                                         # enable dropout
out = clf(**batch, labels=labels)                   # no perm_mask, so ordinary use that sees all positions
out.loss.backward()
optimizer.step()
optimizer.zero_grad()

clf.eval()
with torch.no_grad():
    probs = clf(**batch).logits.softmax(dim=-1)     # [2, 2]
print(probs)

FAQ

Q. What is the difference between XLNet and BERT?
A.

Both use left and right context, but they learn it differently. BERT replaces some words with [MASK] and predicts the masked words independently of each other. XLNet uses no [MASK] and learns through autoregressive prediction over permuted prediction orders. As a result, it can also learn dependencies among the masked words (e.g., York following New), and the input does not look different between pretraining and fine-tuning.

Q. Does the permutation language model shuffle the words of the input sentence?
A.

No. Only "the order in which words are predicted" is permuted; the word order and positions of the input stay as in the original sentence. An attention mask makes only positions earlier in the prediction order visible. This method is necessary because fine-tuning only ever sees sentences in their natural order.

Q. Why are two streams (content and query) needed?
A.

Prediction requires a representation that knows the target position ztz_t but not the word at that position. An ordinary hidden state does not know which position is being predicted, so it would make the same prediction for different positions. XLNet therefore predicts with the query stream gg, which knows only the position, while the content stream hh carries the word information needed to predict other positions.

References

  1. Yang, Z., Dai, Z., Yang, Y., Carbonell, J., Salakhutdinov, R., & Le, Q. V. (2019). XLNet: Generalized Autoregressive Pretraining for Language Understanding. NeurIPS 2019. arXiv:1906.08237.
  2. Dai, Z., Yang, Z., Yang, Y., Carbonell, J., Le, Q. V., & Salakhutdinov, R. (2019). Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. ACL 2019. arXiv:1901.02860.
  3. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. arXiv:1810.04805.
  4. Hugging Face. Transformers documentation: XLNet.