XLNet: Generalized Autoregressive Pretraining for Language Understanding

Zhilin Yang, Zihang Dai, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le

Introduction

Unsupervised representation learning has been highly successful in the domain of natural language processing . Typically, these methods first pretrain neural networks on large-scale unlabeled text corpora, and then finetune the models or representations on downstream tasks. Under this shared high-level idea, different unsupervised pretraining objectives have been explored in literature. Among them, autoregressive (AR) language modeling and autoencoding (AE) have been the two most successful pretraining objectives.

AR language modeling seeks to estimate the probability distribution of a text corpus with an autoregressive model . Specifically, given a text sequence x=(x1,,xT)\mathbf{x}=(x_{1},\cdots,x_{T}), AR language modeling factorizes the likelihood into a forward product p(x)=t=1Tp(xtx<t)p(\mathbf{x})=\prod_{t=1}^{T}p(x_{t}\mid\mathbf{x}_{<t}) or a backward one p(x)=t=T1p(xtx>t)p(\mathbf{x})=\prod_{t=T}^{1}p(x_{t}\mid\mathbf{x}_{>t}). A parametric model (e.g. a neural network) is trained to model each conditional distribution. Since an AR language model is only trained to encode a uni-directional context (either forward or backward), it is not effective at modeling deep bidirectional contexts. On the contrary, downstream language understanding tasks often require bidirectional context information. This results in a gap between AR language modeling and effective pretraining.

In comparison, AE based pretraining does not perform explicit density estimation but instead aims to reconstruct the original data from corrupted input. A notable example is BERT , which has been the state-of-the-art pretraining approach. Given the input token sequence, a certain portion of tokens are replaced by a special symbol [MASK], and the model is trained to recover the original tokens from the corrupted version. Since density estimation is not part of the objective, BERT is allowed to utilize bidirectional contexts for reconstruction. As an immediate benefit, this closes the aforementioned bidirectional information gap in AR language modeling, leading to improved performance. However, the artificial symbols like [MASK] used by BERT during pretraining are absent from real data at finetuning time, resulting in a pretrain-finetune discrepancy. Moreover, since the predicted tokens are masked in the input, BERT is not able to model the joint probability using the product rule as in AR language modeling. In other words, BERT assumes the predicted tokens are independent of each other given the unmasked tokens, which is oversimplified as high-order, long-range dependency is prevalent in natural language .

Faced with the pros and cons of existing language pretraining objectives, in this work, we propose XLNet, a generalized autoregressive method that leverages the best of both AR language modeling and AE while avoiding their limitations.

Firstly, instead of using a fixed forward or backward factorization order as in conventional AR models, XLNet maximizes the expected log likelihood of a sequence w.r.t. all possible permutations of the factorization order. Thanks to the permutation operation, the context for each position can consist of tokens from both left and right. In expectation, each position learns to utilize contextual information from all positions, i.e., capturing bidirectional context.

Secondly, as a generalized AR language model, XLNet does not rely on data corruption. Hence, XLNet does not suffer from the pretrain-finetune discrepancy that BERT is subject to. Meanwhile, the autoregressive objective also provides a natural way to use the product rule for factorizing the joint probability of the predicted tokens, eliminating the independence assumption made in BERT.

In addition to a novel pretraining objective, XLNet improves architectural designs for pretraining.

Inspired by the latest advancements in AR language modeling, XLNet integrates the segment recurrence mechanism and relative encoding scheme of Transformer-XL into pretraining, which empirically improves the performance especially for tasks involving a longer text sequence.

Naively applying a Transformer(-XL) architecture to permutation-based language modeling does not work because the factorization order is arbitrary and the target is ambiguous. As a solution, we propose to reparameterize the Transformer(-XL) network to remove the ambiguity.

Empirically, under comparable experiment setting, XLNet consistently outperforms BERT on a wide spectrum of problems including GLUE language understanding tasks, reading comprehension tasks like SQuAD and RACE, text classification tasks such as Yelp and IMDB, and the ClueWeb09-B document ranking task.

Related Work The idea of permutation-based AR modeling has been explored in , but there are several key differences. Firstly, previous models aim to improve density estimation by baking an “orderless” inductive bias into the model while XLNet is motivated by enabling AR language models to learn bidirectional contexts. Technically, to construct a valid target-aware prediction distribution, XLNet incorporates the target position into the hidden state via two-stream attention while previous permutation-based AR models relied on implicit position awareness inherent to their MLP architectures. Finally, for both orderless NADE and XLNet, we would like to emphasize that “orderless” does not mean that the input sequence can be randomly permuted but that the model allows for different factorization orders of the distribution.

Another related idea is to perform autoregressive denoising in the context of text generation , which only considers a fixed order though.

Proposed Method

In this section, we first review and compare the conventional AR language modeling and BERT for language pretraining. Given a text sequence x=[x1,,xT]{\mathbf{x}}=\left[{x_{1},\cdots,x_{T}}\right], AR language modeling performs pretraining by maximizing the likelihood under the forward autoregressive factorization:

where hθ(x1:t1)h_{\theta}({\mathbf{x}}_{1:t-1}) is a context representation produced by neural models, such as RNNs or Transformers, and e(x)e(x) denotes the embedding of xx. In comparison, BERT is based on denoising auto-encoding. Specifically, for a text sequence x{\mathbf{x}}, BERT first constructs a corrupted version x^\hat{{\mathbf{x}}} by randomly setting a portion (e.g. 15%) of tokens in x{\mathbf{x}} to a special symbol [MASK]. Let the masked tokens be xˉ\bar{{\mathbf{x}}}. The training objective is to reconstruct xˉ\bar{{\mathbf{x}}} from x^\hat{{\mathbf{x}}}:

where mt=1m_{t}=1 indicates xtx_{t} is masked, and HθH_{\theta} is a Transformer that maps a length-TT text sequence x{\mathbf{x}} into a sequence of hidden vectors Hθ(x)=[Hθ(x)1,Hθ(x)2,,Hθ(x)T]H_{\theta}({\mathbf{x}})=\left[{H_{\theta}({\mathbf{x}})_{1},H_{\theta}({\mathbf{x}})_{2},\cdots,H_{\theta}({\mathbf{x}})_{T}}\right]. The pros and cons of the two pretraining objectives are compared in the following aspects:

Independence Assumption: As emphasized by the \approx sign in Eq. (2), BERT factorizes the joint conditional probability p(xˉx^)p(\bar{{\mathbf{x}}}\mid\hat{{\mathbf{x}}}) based on an independence assumption that all masked tokens xˉ\bar{{\mathbf{x}}} are separately reconstructed. In comparison, the AR language modeling objective (1) factorizes pθ(x)p_{\theta}({\mathbf{x}}) using the product rule that holds universally without such an independence assumption.

Input noise: The input to BERT contains artificial symbols like [MASK] that never occur in downstream tasks, which creates a pretrain-finetune discrepancy. Replacing [MASK] with original tokens as in does not solve the problem because original tokens can be only used with a small probability — otherwise Eq. (2) will be trivial to optimize. In comparison, AR language modeling does not rely on any input corruption and does not suffer from this issue.

Context dependency: The AR representation hθ(x1:t1)h_{\theta}({\mathbf{x}}_{1:t-1}) is only conditioned on the tokens up to position tt (i.e. tokens to the left), while the BERT representation Hθ(x)tH_{\theta}({\mathbf{x}})_{t} has access to the contextual information on both sides. As a result, the BERT objective allows the model to be pretrained to better capture bidirectional context.

2 Objective: Permutation Language Modeling

According to the comparison above, AR language modeling and BERT possess their unique advantages over the other. A natural question to ask is whether there exists a pretraining objective that brings the advantages of both while avoiding their weaknesses.

Borrowing ideas from orderless NADE , we propose the permutation language modeling objective that not only retains the benefits of AR models but also allows models to capture bidirectional contexts. Specifically, for a sequence x{\mathbf{x}} of length TT, there are T!T! different orders to perform a valid autoregressive factorization. Intuitively, if model parameters are shared across all factorization orders, in expectation, the model will learn to gather information from all positions on both sides.

To formalize the idea, let ZT\mathcal{Z}_{T} be the set of all possible permutations of the length-TT index sequence [1,2,,T]\left[{1,2,\dots,T}\right]. We use ztz_{t} and z<t{\mathbf{z}}_{<t} to denote the tt-th element and the first t1t-1 elements of a permutation zZT{\mathbf{z}}\in\mathcal{Z}_{T}. Then, our proposed permutation language modeling objective can be expressed as follows:

Essentially, for a text sequence x{\mathbf{x}}, we sample a factorization order z{\mathbf{z}} at a time and decompose the likelihood pθ(x)p_{\theta}({\mathbf{x}}) according to factorization order. Since the same model parameter θ\theta is shared across all factorization orders during training, in expectation, xtx_{t} has seen every possible element xixtx_{i}\neq x_{t} in the sequence, hence being able to capture the bidirectional context. Moreover, as this objective fits into the AR framework, it naturally avoids the independence assumption and the pretrain-finetune discrepancy discussed in Section 2.1.

Remark on Permutation The proposed objective only permutes the factorization order, not the sequence order. In other words, we keep the original sequence order, use the positional encodings corresponding to the original sequence, and rely on a proper attention mask in Transformers to achieve permutation of the factorization order. Note that this choice is necessary, since the model will only encounter text sequences with the natural order during finetuning.

To provide an overall picture, we show an example of predicting the token x3x_{3} given the same input sequence x{\mathbf{x}} but under different factorization orders in the Appendix A.7 with Figure 4.

3 Architecture: Two-Stream Self-Attention for Target-Aware Representations

While the permutation language modeling objective has desired properties, naive implementation with standard Transformer parameterization may not work. To see the problem, assume we parameterize the next-token distribution pθ(Xztxz<t)p_{\theta}(X_{z_{t}}\mid{\mathbf{x}}_{{\mathbf{z}}_{<t}}) using the standard Softmax formulation, i.e., pθ(Xzt=xxz<t)=exp(e(x)hθ(xz<t))xexp(e(x)hθ(xz<t)),p_{\theta}(X_{z_{t}}=x\mid{\mathbf{x}}_{{\mathbf{z}}_{<t}})=\frac{\exp\left({e(x)^{\top}h_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{<t}})}\right)}{\sum_{x^{\prime}}\exp\left({e(x^{\prime})^{\top}h_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{<t}})}\right)}, where hθ(xz<t)h_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{<t}}) denotes the hidden representation of xz<t{\mathbf{x}}_{{\mathbf{z}}_{<t}} produced by the shared Transformer network after proper masking. Now notice that the representation hθ(xz<t)h_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{<t}}) does not depend on which position it will predict, i.e., the value of ztz_{t}. Consequently, the same distribution is predicted regardless of the target position, which is not able to learn useful representations (see Appendix A.1 for a concrete example). To avoid this problem, we propose to re-parameterize the next-token distribution to be target position aware:

where gθ(xz<t,zt)g_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{<t}},z_{t}) denotes a new type of representations which additionally take the target position ztz_{t} as input.

Two-Stream Self-Attention While the idea of target-aware representations removes the ambiguity in target prediction, how to formulate gθ(xz<t,zt)g_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{<t}},z_{t}) remains a non-trivial problem. Among other possibilities, we propose to “stand” at the target position ztz_{t} and rely on the position ztz_{t} to gather information from the context xz<t{\mathbf{x}}_{{\mathbf{z}}_{<t}} through attention. For this parameterization to work, there are two requirements that are contradictory in a standard Transformer architecture: (1) to predict the token xztx_{z_{t}}, gθ(xz<t,zt)g_{\theta}(\mathbf{x}_{\mathbf{z}_{<t}},z_{t}) should only use the position ztz_{t} and not the content xztx_{z_{t}}, otherwise the objective becomes trivial; (2) to predict the other tokens xzjx_{z_{j}} with j>tj>t, gθ(xz<t,zt)g_{\theta}(\mathbf{x}_{\mathbf{z}_{<t}},z_{t}) should also encode the content xztx_{z_{t}} to provide full contextual information. To resolve such a contradiction, we propose to use two sets of hidden representations instead of one:

The content representation hθ(xzt)h_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{\leq t}}), or abbreviated as hzth_{z_{t}}, which serves a similar role to the standard hidden states in Transformer. This representation encodes both the context and xztx_{z_{t}} itself.

The query representation gθ(xz<t,zt)g_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{<t}},z_{t}), or abbreviated as gztg_{z_{t}}, which only has access to the contextual information xz<t{\mathbf{x}}_{{{\mathbf{z}}}_{<t}} and the position ztz_{t}, but not the content xztx_{z_{t}}, as discussed above.

Computationally, the first layer query stream is initialized with a trainable vector, i.e. gi(0)=wg_{i}^{(0)}=w, while the content stream is set to the corresponding word embedding, i.e. hi(0)=e(xi)h_{i}^{(0)}=e(x_{i}). For each self-attention layer m=1,,Mm=1,\dots,M, the two streams of representations are schematically222To avoid clutter, we omit the implementation details including multi-head attention, residual connection, layer normalization and position-wise feed-forward as used in Transformer(-XL). The details are included in Appendix A.2 for reference. updated with a shared set of parameters as follows (illustrated in Figures 1 (a) and (b)):

where Q, K, V denote the query, key, and value in an attention operation . The update rule of the content representations is exactly the same as the standard self-attention, so during finetuning, we can simply drop the query stream and use the content stream as a normal Transformer(-XL). Finally, we can use the last-layer query representation gzt(M)g_{z_{t}}^{(M)} to compute Eq. (4).

Partial Prediction While the permutation language modeling objective (3) has several benefits, it is a much more challenging optimization problem due to the permutation and causes slow convergence in preliminary experiments. To reduce the optimization difficulty, we choose to only predict the last tokens in a factorization order. Formally, we split z{\mathbf{z}} into a non-target subsequence zc{\mathbf{z}}_{\leq c} and a target subsequence z>c{\mathbf{z}}_{>c}, where cc is the cutting point. The objective is to maximize the log-likelihood of the target subsequence conditioned on the non-target subsequence, i.e.,

𝑐1𝐳subscript𝑝𝜃conditionalsubscript𝑥subscript𝑧𝑡subscript𝐱subscript𝐳absent𝑡\max_{\theta}\quad\mathbb{E}_{{\mathbf{z}}\sim\mathcal{Z}_{T}}\Big{[}\log p_{\theta}({\mathbf{x}}_{{\mathbf{z}}_{>c}}\mid{\mathbf{x}}_{{\mathbf{z}}_{\leq c}})\Big{]}=\mathbb{E}_{{\mathbf{z}}\sim\mathcal{Z}_{T}}\left[\sum_{t=c+1}^{\left|{{\mathbf{z}}}\right|}\log p_{\theta}(x_{z_{t}}\mid{\mathbf{x}}_{{\mathbf{z}}_{z>c{\mathbf{z}}_{>c} is chosen as the target because it possesses the longest context in the sequence given the current factorization order z{\mathbf{z}}. A hyperparameter KK is used such that about 1/K1/K tokens are selected for predictions; i.e., z/(zc)K\left|{{\mathbf{z}}}\right|/(\left|{{\mathbf{z}}}\right|-c)\approx K. For unselected tokens, their query representations need not be computed, which saves speed and memory.

4 Incorporating Ideas from Transformer-XL

Since our objective function fits in the AR framework, we incorporate the state-of-the-art AR language model, Transformer-XL , into our pretraining framework, and name our method after it. We integrate two important techniques in Transformer-XL, namely the relative positional encoding scheme and the segment recurrence mechanism. We apply relative positional encodings based on the original sequence as discussed earlier, which is straightforward. Now we discuss how to integrate the recurrence mechanism into the proposed permutation setting and enable the model to reuse hidden states from previous segments. Without loss of generality, suppose we have two segments taken from a long sequence s{\mathbf{s}}; i.e., x~=s1:T\tilde{{\mathbf{x}}}={\mathbf{s}}_{1:T} and x=sT+1:2T{\mathbf{x}}=\mathbf{s}_{T+1:2T}. Let z~\tilde{{\mathbf{z}}} and z{\mathbf{z}} be permutations of [1T][1\cdots T] and [T+12T][T+1\cdots 2T] respectively. Then, based on the permutation z~\tilde{{\mathbf{z}}}, we process the first segment, and then cache the obtained content representations h~(m)\tilde{{\mathbf{h}}}^{(m)} for each layer mm. Then, for the next segment x\mathbf{x}, the attention update with memory can be written as

where [.,.][.,.] denotes concatenation along the sequence dimension. Notice that positional encodings only depend on the actual positions in the original sequence. Thus, the above attention update is independent of z~\tilde{{\mathbf{z}}} once the representations h~(m)\tilde{{\mathbf{h}}}^{(m)} are obtained. This allows caching and reusing the memory without knowing the factorization order of the previous segment. In expectation, the model learns to utilize the memory over all factorization orders of the last segment. The query stream can be computed in the same way. Finally, Figure 1 (c) presents an overview of the proposed permutation language modeling with two-stream attention (see Appendix A.7 for more detailed illustration).

5 Modeling Multiple Segments

Many downstream tasks have multiple input segments, e.g., a question and a context paragraph in question answering. We now discuss how we pretrain XLNet to model multiple segments in the autoregressive framework. During the pretraining phase, following BERT, we randomly sample two segments (either from the same context or not) and treat the concatenation of two segments as one sequence to perform permutation language modeling. We only reuse the memory that belongs to the same context. Specifically, the input to our model is the same as BERT: [CLS, A, SEP, B, SEP], where “SEP” and “CLS” are two special symbols and “A” and “B” are the two segments. Although we follow the two-segment data format, XLNet-Large does not use the objective of next sentence prediction as it does not show consistent improvement in our ablation study (see Section 3.4).

Relative Segment Encodings Architecturally, different from BERT that adds an absolute segment embedding to the word embedding at each position, we extend the idea of relative encodings from Transformer-XL to also encode the segments. Given a pair of positions ii and jj in the sequence, if ii and jj are from the same segment, we use a segment encoding sij=s+\mathbf{s}_{ij}=\mathbf{s}_{+} or otherwise sij=s\bm{\mathbf{s}}_{ij}=\bm{\mathbf{s}}_{-}, where s+\mathbf{s}_{+} and s\mathbf{s}_{-} are learnable model parameters for each attention head. In other words, we only consider whether the two positions are within the same segment, as opposed to considering which specific segments they are from. This is consistent with the core idea of relative encodings; i.e., only modeling the relationships between positions. When ii attends to jj, the segment encoding sij\mathbf{s}_{ij} is used to compute an attention weight aij=(qi+b)sija_{ij}=(\bm{\mathbf{q}}_{i}+\bm{\mathbf{b}})^{\top}\bm{\mathbf{s}}_{ij}, where qi\bm{\mathbf{q}}_{i} is the query vector as in a standard attention operation and b\bm{\mathbf{b}} is a learnable head-specific bias vector. Finally, the value aija_{ij} is added to the normal attention weight. There are two benefits of using relative segment encodings. First, the inductive bias of relative encodings improves generalization . Second, it opens the possibility of finetuning on tasks that have more than two input segments, which is not possible using absolute segment encodings.

6 Discussion

Comparing Eq. (2) and (5), we observe that both BERT and XLNet perform partial prediction, i.e., only predicting a subset of tokens in the sequence. This is a necessary choice for BERT because if all tokens are masked, it is impossible to make any meaningful predictions. In addition, for both BERT and XLNet, partial prediction plays a role of reducing optimization difficulty by only predicting tokens with sufficient context. However, the independence assumption discussed in Section 2.1 disables BERT to model dependency between targets.

To better understand the difference, let’s consider a concrete example [New, York, is, a, city]. Suppose both BERT and XLNet select the two tokens [New, York] as the prediction targets and maximize logp(New Yorkis a city)\log p(\text{New York}\mid\text{is a city}). Also suppose that XLNet samples the factorization order [is, a, city, New, York]. In this case, BERT and XLNet respectively reduce to the following objectives:

𝑝conditionalNewis a city𝑝conditionalYorkis a city\mathcal{J}_{\text{BERT}}=\log p(\text{New}\mid\text{is a city})+\log p(\text{York}\mid\text{is a city}), \mathcal{J}_{\text{XLNet}}=\log p(\text{New}\mid\text{is a city})+\log p(\text{York}\mid{\color[rgb]{1,0,1}\definecolor[named]{pgfstrokecolor}{rgb}{1,0,1}\pgfsys@color@cmyk@stroke{0}{1}{0}{0}\pgfsys@color@cmyk@fill{0}{1}{0}{0}\text{New}},\text{is a city}). Notice that XLNet is able to capture the dependency between the pair (New, York), which is omitted by BERT. Although in this example, BERT learns some dependency pairs such as (New, city) and (York, city), it is obvious that XLNet always learns more dependency pairs given the same target and contains “denser” effective training signals.

For more formal analysis and further discussion, please refer to Appendix A.5.

Experiments

Following BERT , we use the BooksCorpus and English Wikipedia as part of our pretraining data, which have 13GB plain text combined. In addition, we include Giga5 (16GB text) , ClueWeb 2012-B (extended from ), and Common Crawl for pretraining. We use heuristics to aggressively filter out short or low-quality articles for ClueWeb 2012-B and Common Crawl, which results in 19GB and 110GB text respectively. After tokenization with SentencePiece , we obtain 2.78B, 1.09B, 4.75B, 4.30B, and 19.97B subword pieces for Wikipedia, BooksCorpus, Giga5, ClueWeb, and Common Crawl respectively, which are 32.89B in total.

Our largest model XLNet-Large has the same architecture hyperparameters as BERT-Large, which results in a similar model size. During pretraining, we always use a full sequence length of 512. Firstly, to provide a fair comparison with BERT (section 3.2), we also trained XLNet-Large-wikibooks on BooksCorpus and Wikipedia only, where we reuse all pretraining hyper-parameters as in the original BERT. Then, we scale up the training of XLNet-Large by using all the datasets described above. Specifically, we train on 512 TPU v3 chips for 500K steps with an Adam weight decay optimizer, linear learning rate decay, and a batch size of 8192, which takes about 5.5 days. It was observed that the model still underfits the data at the end of training. Finally, we perform ablation study (section 3.4) based on the XLNet-Base-wikibooks.

Since the recurrence mechanism is introduced, we use a bidirectional data input pipeline where each of the forward and backward directions takes half of the batch size. For training XLNet-Large, we set the partial prediction constant KK as 6 (see Section 1). Our finetuning procedure follows BERT except otherwise specified333Hyperparameters for pretraining and finetuning are in Appendix A.4.. We employ an idea of span-based prediction, where we first sample a length L[1,,5]L\in[1,\cdots,5], and then randomly select a consecutive span of LL tokens as prediction targets within a context of (KL)(KL) tokens.

We use a variety of natural language understanding datasets to evaluate the performance of our method. Detailed descriptions of the settings for all the datasets can be found in Appendix A.3.

2 Fair Comparison with BERT

Here, we first compare the performance of BERT and XLNet in a fair setting to decouple the effects of using more data and the improvement from BERT to XLNet. In Table 1, we compare (1) best performance of three different variants of BERT and (2) XLNet trained with the same data and hyperparameters. As we can see, trained on the same data with an almost identical training recipe, XLNet outperforms BERT by a sizable margin on all the considered datasets.

3 Comparison with RoBERTa: Scaling Up

After the initial publication of our manuscript, a few other pretrained models were released such as RoBERTa and ALBERT . Since ALBERT involves increasing the model hidden size from 1024 to 2048/4096 and thus substantially increases the amount of computation in terms of FLOPs, we exclude ALBERT from the following results as it is hard to lead to scientific conclusions. To obtain relatively fair comparison with RoBERTa, the experiment in this section is based on full data and reuses the hyper-parameters of RoBERTa, as described in section 3.1.

The results are presented in Tables 2 (reading comprehension & document ranking), 3 (question answering), 4 (text classification) and 5 (natural language understanding), where XLNet generally outperforms BERT and RoBERTa. In addition, we make two more interesting observations:

For explicit reasoning tasks like SQuAD and RACE that involve longer context, the performance gain of XLNet is usually larger. This superiority at dealing with longer context could come from the Transformer-XL backbone in XLNet.

For classification tasks that already have abundant supervised examples such as MNLI (>390K), Yelp (>560K) and Amazon (>3M), XLNet still lead to substantial gains.

4 Ablation Study

We perform an ablation study to understand the importance of each design choice based on four datasets with diverse characteristics. Specifically, there are three main aspects we hope to study:

The effectiveness of the permutation language modeling objective alone, especially compared to the denoising auto-encoding objective used by BERT.

The importance of using Transformer-XL as the backbone neural architecture.

The necessity of some implementation details including span-based prediction, the bidirectional input pipeline, and next-sentence prediction.

With these purposes in mind, in Table 6, we compare 6 XLNet-Base variants with different implementation details (rows 3 - 8), the original BERT-Base model (row 1), and an additional Transformer-XL baseline trained with the denoising auto-encoding (DAE) objective used in BERT but with the bidirectional input pipeline (row 2). For fair comparison, all models are based on a 12-layer architecture with the same model hyper-parameters as BERT-Base and are trained on only Wikipedia and the BooksCorpus. All results reported are the median of 5 runs.

Examining rows 1 - 4 of Table 6, we can see both Transformer-XL and the permutation LM clearly contribute the superior performance of XLNet over BERT. Moreover, if we remove the memory caching mechanism (row 5), the performance clearly drops, especially for RACE which involves the longest context among the 4 tasks. In addition, rows 6 - 7 show that both span-based prediction and the bidirectional input pipeline play important roles in XLNet. Finally, we unexpectedly find the the next-sentence prediction objective proposed in the original BERT does not necessarily lead to an improvement in our setting. Hence, we exclude the next-sentence prediction objective from XLNet.

Finally, we also perform a qualitative study of the attention patterns, which is included in Appendix A.6 due to page limit.

Conclusions

XLNet is a generalized AR pretraining method that uses a permutation language modeling objective to combine the advantages of AR and AE methods. The neural architecture of XLNet is developed to work seamlessly with the AR objective, including integrating Transformer-XL and the careful design of the two-stream attention mechanism. XLNet achieves substantial improvement over previous pretraining objectives on various tasks.

The authors would like to thank Qizhe Xie and Adams Wei Yu for providing useful feedback on the project, Jamie Callan for providing the ClueWeb dataset, Youlong Cheng, Yanping Huang and Shibo Wang for providing ideas to improve our TPU implementation, Chenyan Xiong and Zhuyun Dai for clarifying the setting of the document ranking task. ZY and RS were supported by the Office of Naval Research grant N000141812861, the National Science Foundation (NSF) grant IIS1763562, the Nvidia fellowship, and the Siebel scholarship. ZD and YY were supported in part by NSF under the grant IIS-1546329 and by the DOE-Office of Science under the grant ASCR #KJ040201.

References

Appendix A Target-Aware Representation via Two-Stream Self-Attention

In this section, we provide a concrete example to show how the standard language model parameterization fails under the permutation objective, as discussed in Section 1. Specifically, let’s consider two different permutations z(1){\mathbf{z}}^{(1)} and z(2){\mathbf{z}}^{(2)} satisfying the following relationship

Then, substituting the two permutations respectively into the naive parameterization, we have

Effectively, two different target positions ii and jj share exactly the same model prediction. However, the ground-truth distribution of two positions should certainly be different.

A.2 Two-Stream Attention

Here, we provide the implementation details of the two-stream attention with a Transformer-XL backbone.

A.3 Datasets

The RACE dataset contains near 100K questions taken from the English exams for middle and high school Chinese students in the age range between 12 to 18, with the answers generated by human experts. This is one of the most difficult reading comprehension datasets that involve challenging reasoning questions. Moreover, the average length of the passages in RACE are longer than 300, which is significantly longer than other popular reading comprehension datasets such as SQuAD . As a result, this dataset serves as a challenging benchmark for long text understanding. We use a sequence length of 512 during finetuning.

A.3.2 SQuAD

SQuAD is a large-scale reading comprehension dataset with two tasks. SQuAD1.1 contains questions that always have a corresponding answer in the given passages, while SQuAD2.0 introduces unanswerable questions. To finetune an XLNet on SQuAD2.0, we jointly apply a logistic regression loss for answerability prediction similar to classification tasks and a standard span extraction loss for question answering .

A.3.3 Text classification Datasets

Following previous work on text classification , we evaluate XLNet on the following benchmarks: IMDB, Yelp-2, Yelp-5, DBpedia, AG, Amazon-2, and Amazon-5.

A.3.4 GLUE Dataset

The GLUE dataset is a collection of 9 natural language understanding tasks. The test set labels are removed from the publicly released version, and all the practitioners must submit their predictions on the evaluation server to obtain test set results. In Table 5, we present results of multiple settings, including single-task and multi-task, as well as single models and ensembles. In the multi-task setting, we jointly train an XLNet on the four largest datasets—MNLI, SST-2, QNLI, and QQP—and finetune the network on the other datasets. Only single-task training is employed for the four large datasets. For QNLI, we employed a pairwise relevance ranking scheme as in for our test set submission. However, for fair comparison with BERT, our result on the QNLI dev set is based on a standard classification paradigm. For WNLI, we use the loss described in .

A.3.5 ClueWeb09-B Dataset

Following the setting in previous work , we use the ClueWeb09-B dataset to evaluate the performance on document ranking. The queries were created by the TREC 2009-2012 Web Tracks based on 50M documents and the task is to rerank the top 100 documents retrieved using a standard retrieval method. Since document ranking, or ad-hoc retrieval, mainly concerns the low-level representations instead of high-level semantics, this dataset serves as a testbed for evaluating the quality of word embeddings. We use a pretrained XLNet to extract word embeddings for the documents and queries without finetuning, and employ a kernel pooling network to rank the documents.

A.4 Hyperparameters

The hyperparameters used for pretraining XLNet are shown in Table 7.

A.4.2 Hyperparameters for Finetuning

The hyperparameters used for finetuning XLNet on various tasks are shown in Table 8. “Layer-wise decay” means exponentially decaying the learning rates of individual layers in a top-down manner. For example, suppose the 2424-th layer uses a learning rate ll, and the Layer-wise decay rate is α\alpha, then the learning rate of layer mm is lα24ml\alpha^{24-m}.

A.5 Discussion and Analysis

To prove a general point beyond one example, we now turn to more formal expressions. Inspired by previous work , given a sequence x=[x1,,xT]\mathbf{x}=[x_{1},\cdots,x_{T}], we define a set of target-context pairs of interest, I={(x,U)}\mathcal{I}=\{(x,\mathcal{U})\}, where U\mathcal{U} is a set of tokens in x\mathbf{x} that form a context of xx. Intuitively, we want the model to learn the dependency of xx on U\mathcal{U} through a pretraining loss term logp(xU)\log p(x\mid\mathcal{U}). For example, given the above sentence, the pairs of interest I\mathcal{I} could be instantiated as:

Note that I\mathcal{I} is merely a virtual notion without unique ground truth, and our analysis will hold regardless of how I\mathcal{I} is instantiated.

Given a set of target tokens T\mathcal{T} and a set of non-target tokens N=x\T\mathcal{N}={\mathbf{x}}\backslash\mathcal{T}, BERT and XLNet both maximize logp(TN)\log p(\mathcal{T}\mid\mathcal{N}) but with different formulations:

where T<x\mathcal{T}_{<x} denote tokens in T\mathcal{T} that have a factorization order prior to xx. Both objectives consist of multiple loss terms in the form of logp(xVx)\log p(x\mid\mathcal{V}_{x}). Intuitively, if there exists a target-context pair (x,U)I(x,\mathcal{U})\in\mathcal{I} such that UVx\mathcal{U}\subseteq\mathcal{V}_{x}, then the loss term logp(xVx)\log p(x\mid\mathcal{V}_{x}) provides a training signal to the dependency between xx and U\mathcal{U}. For convenience, we say a target-context pair (x,U)I(x,\mathcal{U})\in\mathcal{I} is covered by a model (objective) if UVx\mathcal{U}\subseteq\mathcal{V}_{x}.

Given the definition, let’s consider two cases:

If UN\mathcal{U}\subseteq\mathcal{N}, the dependency (x,U)(x,\mathcal{U}) is covered by both BERT and XLNet.

If UNT<x\mathcal{U}\subseteq\mathcal{N}\cup\mathcal{T}_{<x} and UT<x\mathcal{U}\cap\mathcal{T}_{<x}\not=\emptyset, the dependency can only be covered by XLNet but not BERT. As a result, XLNet is able to cover more dependencies than BERT. In other words, the XLNet objective contains more effective training signals, which empirically leads to better performance in Section 3.

A.5.2 Comparison with Language Modeling

Borrowing examples and notations from Section A.5.1, a standard AR language model like GPT is only able to cover the dependency (x=York,U={New})(x=\text{York},\mathcal{U}=\{\text{New}\}) but not (x=New,U={York})(x=\text{New},\mathcal{U}=\{\text{York}\}). XLNet, on the other hand, is able to cover both in expectation over all factorization orders. Such a limitation of AR language modeling can be critical in real-world applications. For example, consider a span extraction question answering task with the context “Thom Yorke is the singer of Radiohead” and the question “Who is the singer of Radiohead”. The representations of “Thom Yorke” are not dependent on “Radiohead” with AR language modeling and thus they will not be chosen as the answer by the standard approach that employs softmax over all token representations. More formally, consider a context-target pair (x,U)(x,\mathcal{U}):

If U⊈T<x\mathcal{U}\not\subseteq\mathcal{T}_{<x}, where T<x\mathcal{T}_{<x} denotes the tokens prior to xx in the original sequence, AR language modeling is not able to cover the dependency.

In comparison, XLNet is able to cover all dependencies in expectation.

Approaches like ELMo concatenate forward and backward language models in a shallow manner, which is not sufficient for modeling deep interactions between the two directions.

A.5.3 Bridging the Gap Between Language Modeling and Pretraining

With a deep root in density estimation444The problem of language modeling is essentially density estimation for text data. , language modeling has been a rapidly-developing research area . However, there has been a gap between language modeling and pretraining due to the lack of the capability of bidirectional context modeling, as analyzed in Section A.5.2. It has even been challenged by some machine learning practitioners whether language modeling is a meaningful pursuit if it does not directly improve downstream tasks 555https://openreview.net/forum?id=HJePno0cYm. XLNet generalizes language modeling and bridges such a gap. As a result, it further “justifies” language modeling research. Moreover, it becomes possible to leverage the rapid progress of language modeling research for pretraining. As an example, we integrate Transformer-XL into XLNet to demonstrate the usefulness of the latest language modeling progress.

A.6 Qualitative Analysis of Attention Patterns

We compare the attention pattern of BERT and XLNet without finetuning. Firstly, we found 4 typical patterns shared by both, as shown in Fig. 2.

More interestingly, in Fig. 3, we present 3 patterns that only appear in XLNet but not BERT: (a) The self-exclusion pattern attends to all other tokens but itself, probably offering a fast way to gather global information; (b) The relative-stride pattern attends to positions every a few stride apart relative to the query position; (c) The one-side masked pattern is very similar to the lower-left part of Fig. 1-(d), with the upper-right triangle masked out. It seems that the model learns not to attend the relative right half. Note that all these three unique patterns involve the relative positions rather than absolute ones, and hence are likely enabled by the “relative attention” mechanism in XLNet. We conjecture these unique patterns contribute to the performance advantage of XLNet. On the other hand, the proposed permutation LM objective mostly contributes to a better data efficiency, whose effects may not be obvious from qualitative visualization.

A.7 Visualizing Memory and Permutation

In this section, we provide a detailed visualization of the proposed permutation language modeling objective, including the mechanism of reusing memory (aka the recurrence mechanism), how we use attention masks to permute the factorization order, and the difference of the two attention streams.

As shown in Figure 5 and 6, given the current position ztz_{t}, the attention mask is decided by the permutation (or factorization order) z\mathbf{z} such that only tokens the occur before ztz_{t} in the permutation can be attended; i.e., positions ziz_{i} with i<ti<t. Moreover, comparing Figure 5 and 6, we can see how the query stream and the content stream work differently with a specific permutation through attention masks. The main difference is that the query stream cannot do self-attention and does not have access to the token at the position, while the content stream performs normal self-attention.