Robustness Verification for Transformers
Zhouxing Shi, Huan Zhang, Kai-Wei Chang, Minlie Huang, Cho-Jui Hsieh
Introduction
Deep neural networks have been successfully applied to many domains. However, these black-box models are generally difficult to analyze and their behavior is not guaranteed. Moreover, it has been shown that the predictions of deep networks become unreliable and unstable when tested in unseen situations, e.g., in the presence of small adversarial perturbations to the input (Szegedy et al., 2013; Goodfellow et al., 2014; Lin et al., 2019). Therefore, neural network verification has become an important tool for analyzing and understanding the behavior of neural networks, with applications in safety-critical applications (Katz et al., 2017; Julian et al., 2019; Lin et al., 2019), model explanation (Shih et al., 2018) and robustness analysis (Tjeng et al., 2019; Wang et al., 2018c; Gehr et al., 2018; Wong & Kolter, 2018; Singh et al., 2018; Weng et al., 2018; Zhang et al., 2018).
We resolve several particular challenges in verifying Transformers. First, Transformers with self-attention layers have a complicated architecture. Unlike simpler networks, they cannot be written as multiple layers of affine transformations or element-wise activation functions. Therefore, we need to propagate linear bounds differently for self-attention layers. Second, dot products, softmax, and weighted summation in self-attention layers involve multiplication or division of two variables both under perturbation, namely cross-nonlinearity, which is not present in feed-forward networks. Ko et al. (2019) proposed a gradient descent based approach to find linear bounds, however it is inefficient and poses a computational challenge for Transformer verification since self-attention is the core of Transformers. In contrast, we derive closed-form linear bounds that can be computed in complexity. Third, in the computation of self-attention, output neurons in each position depend on all input neurons from different positions (namely cross-position dependency), unlike the case in recurrent neural networks where outputs depend on only the hidden features from the previous position and the current input. Previous works (Zhang et al., 2018; Weng et al., 2018; Ko et al., 2019) have to track all such dependency and thus is costly in time and memory. To tackle this, we introduce an efficient bound propagating process in a forward manner specially for self-attention layers, enabling the tighter backward bounding process for other layers to utilize bounds computed by the forward process. In this way, we avoid cross-position dependency in the backward process which is relatively slower but produces tighter bounds. Combined with the forward process, the complexity of the backward process is reduced by for input length , while the computed bounds remain comparably tight. Our contributions are summarized below:
We propose an effective and efficient algorithm for verifying the robustness of Transformers with self-attention layers. To our best knowledge, this is the first method for verifying Transformers.
We resolve key challenges in verifying Transformers, including cross-nonlinearity and cross-position dependency. Our bounds are significantly tighter than those by adapting Interval Bound Propagation (IBP) (Mirman et al., 2018; Gowal et al., 2018).
We quantitatively and qualitatively show that the certified bounds computed by our algorithm consistently reflect the importance of input words in sentiment analysis, which justifies that these bounds are meaningful in practice and they shed light on interpreting Transformers.
Related Work
Several works focus on solving Eq. (1) exactly and optimally, using mixed integer linear programming (MILP) (Tjeng et al., 2019; Dutta et al., 2018), branch and bound (BaB) (Bunel et al., 2018), and satisfiability modulo theory (SMT) (Ehlers, 2017; Katz et al., 2017). Unfortunately, due to the nonconvexity of model , solving Eq. (1) is NP-hard even for a simple ReLU network (Katz et al., 2017). Therefore, we can only expect to compute a lower bound of Eq. (1) efficiently by using relaxations. Many algorithms can be seen as using convex relaxations for non-linear activation functions (Salman et al., 2019), including using duality (Wong & Kolter, 2018; Dvijotham et al., 2018), abstract domains (Gehr et al., 2018; Singh et al., 2018; Mirman et al., 2018; Singh et al., 2019), layer-by-layer reachability analysis (Wang et al., 2018b; Weng et al., 2018; Zhang et al., 2018; Gowal et al., 2018) and semi-definite relaxations (Raghunathan et al., 2018; Dvijotham et al., 2019). Additionally, robustness verification can rely on analysis on local Lipschitz constants (Hein & Andriushchenko, 2017; Zhang et al., 2019). However, existing methods are mostly limited to verifying networks with relatively simple architectures, such as feed-forward networks and RNNs (Wang et al., 2018a; Akintunde et al., 2019; Ko et al., 2019), while none of them are able to handle Transformers.
Transformers and Self-Attentive Models.
Transformers (Vaswani et al., 2017) based on self-attention mechanism, further with pre-training on large-scale corpora, such as BERT (Devlin et al., 2019), XLNet (Yang et al., 2019), RoBERTa (Liu et al., 2019), achieved state-of-the-art performance on many NLP tasks. Self-attentive models are also useful beyond NLP, including VisualBERT on vision and language applications (Li et al., 2019b; Su et al., 2019), image transformer for image generation (Parmar et al., 2018), acoustic models for speech recognition (Zhou et al., 2018), sequential recommendation (Kang & McAuley, 2018) and graph embedding (Li et al., 2019a).
The robustness of NLP models has been studied, especially many methods have been proposed to generate adversarial examples (Papernot et al., 2016; Jia & Liang, 2017; Zhao et al., 2017; Alzantot et al., 2018; Cheng et al., 2018; Ebrahimi et al., 2018; Shi et al., 2019). In particular, Hsieh et al. (2019) showed that Transformers are more robust than LSTMs. However, there is not much work on robustness verification for NLP models. Ko et al. (2019) verified RNN/LSTM. Jia et al. (2019); Huang et al. (2019) used Interval Bound Propagation (IBP) for certified robustness training of CNN and LSTM. In this paper, we propose the first verification method for Transformers.
Methodology
We aim to verify the robustness of a Transformer whose input is a sequence of frames . We take binary text classification as a running example, where is a word embedding and the model outputs a score for each class (). Nevertheless, our method for verifying Transformers is general and can also be applied in other applications.
We compute bounds from the first sub-layer to the last sub-layer. For neurons in the -th layer, we aim to represent their bounds as linear functions of neurons in a previous layer, the -th layer:
where with . These steps resemble to CROWN (Zhang et al., 2018) which is proposed to verify feed-forward networks. We further support verifying self-attentive Transformers which are more complex than feed-forward networks. Moreover, unlike CROWN that conducts a fully backward process, we combine the backward process with a forward process (see Sec. 3.3) to reduce the computational complexity of verifying Transformers.
2 Linear Transformations and Unary Nonlinear Functions
Linear transformations and unary nonlinear functions are basic operations in neural networks. We show how bounds Eq. (2) at the -th sub-layer are propagated to the -th layer.
If the -th sub-layer is connected with the -th sub-layer with a linear transformation where are parameters of the linear transformation, we propagate the bounds to the -th layer by substituting :
where “” means that the equations hold for both lower bounds and upper bounds respectively.
Unary Nonlinear Functions
If the -th layer is obtained from the -th layer with an unary nonlinear function , to propagate linear bounds over the nonlinear function, we first bound with two linear functions of :
where are parameters such that the inequation holds true for all within its bounds computed previously. Such linear relaxations can be done for different functions, respectively. We provide detailed bounds for functions involved in Transformers in Appendix B.
where and mean to retain positive and negative elements in vector respectively and set other elements to 0.
3 Self-Attention Mechanism
Self-attention layers are the most challenging parts for verifying Transformers. We assume that is the input to a self-attention layer. We describe our method for computing bounds for one attention head, and bounds for different heads of the multi-head attention in Transformers can be easily concatenated. is first linearly projected to queries , keys , and values with different linear projections, and their bounds can be obtained as described in Sec. 3.2. We also keep their linear bounds that are linear functions of the perturbed embeddings. For convenience, let , where indicates vector concatenation, and thereby we represent the linear bounds as linear functions of :
where and mean that the inequation holds true for queries, keys and values respectively. We then bound the output of the self-attention layer starting from , , .
We bound multiplications and divisions in the self-attention mechanism with linear functions. We aim to bound bivariate function or with two linear functions and , where are bounds of obtained previously. For , we derive optimal parameters: , , , , . We provide a proof in Appendix C. However, directly bounding is tricky; fortunately, we can bound it indirectly by first bounding a unary function and then bounding the multiplication .
A Forward Process
For the self-attention mechanism, instead of using the backward process like CROWN (Zhang et al., 2018), we compute bounds with a forward process which we will show later that it can reduce the computational complexity. Attention scores are computed from and : where is the dimension of and . For each multiplication , it is bounded by:
We then obtain the bounds of :
Recall that is a concatenation of . We can split into vectors with equal dimensions, , such that Eq. (5) becomes
Backward Process to Self-Attention Layers
When computing bounds for a later sub-layer, the -th sub-layer, using the backward process, we directly propagate the bounds at the the closest previous self-attention layer assumed to be the -th layer, to the input layer, and we skip other previous sub-layers. The bounds propagated to the -th layer are as Eq. (2). We substitute with linear bounds in Eq. (6):
We take global bounds as Eq. (3) and Eq. (4) to obtain the bounds of the -th layer.
Advantageous of Combining the Backward Process with a Forward Process
Introducing a forward process can significantly reduce the complexity of verifying Transformers. With the backward process only, we need to compute and , where the major cost is on and there are such matrices to compute. The factor is from the dependency between all pairs of positions in the input and output respectively, which makes the algorithm inefficient especially when the input sequence is long. In contrast, the forward process represents the bounds as linear functions of the perturbed positions only instead of all positions by computing and . Imperceptible adversarial examples may not have many perturbed positions (Gao et al., 2018; Ko et al., 2019), and thus we may assume that the number of perturbed positions, , is small. The major cost is on while there are only such matrices and the sizes of and are relatively comparable for a small . We combine the backward process and the forward process. The number of matrices in the forward process is , and for the backward process, since we do not propagate bounds over self-attention layers and there is no cross-position dependency in other sub-layers, we only compute such that , and thus the number of matrices is reduced to . Therefore, the total number of matrices and we compute is and is times smaller than when only the backward process is used. Moreover, the backward process makes bounds tighter compared to solely the forward one, as we explain in Appendix D.
Experiments
To demonstrate the effectiveness of our algorithm, we compute certified bounds for several sentiment classification models and perform an ablation study to show the advantage of combining the backward and forward processes. We also demonstrate the meaningfulness of our certified bounds with an application on identifying important words.
We use two datasets: Yelp (Zhang et al., 2015) and SST (Socher et al., 2013). Yelp consists of 560,000/38,000 examples in the training/test set and SST consists of 67,349/872/1,821 examples in the training/development/test set. Each example is a sentence or a sentence segment (for the training data of SST only) labeled with a binary sentiment polarity.
We verify the robustness of Transformers trained from scratch. For the main experiments, we consider -layer models (), with 4 attention heads, hidden sizes of 256 and 512 for self-attention and feed-forward layers respectively, and we use ReLU activations for feed-forward layers. We remove the variance related terms in layer normalization, making Transformers verification bounds tighter while the clean accuracies remain comparable (see Appendix E for discussions). Although our method can be in principal applied to Transformers with any number of layers, we do not use large-scale pre-trained models such as BERT because they are too challenging to be tightly verified with the current technologies.
2 Certified Bounds
3 Effectiveness of Combining the Backward Process with a Forward Process
In the following, we show the effectiveness of combining the backward process with a forward process. We compare our proposed method (Backward & Forward) with two variations: 1) Fully-Forward propagates bounds in a forward manner for all sub-layers besides self-attention layers; 2) Fully-Backward computes bounds for all sub-layers including self-attention layers using the backward bound propagation and without the forward process. We compare the tightness of bounds and computation time of the three methods. We use smaller models with the hidden sizes reduced by 75%, and we use 1-position perturbation only, to accommodate Fully-Backward with large computational cost. Experiments are conducted on an NVIDIA TITAN X GPU. Table 3 presents the results. Bounds by Fully-Forward are significantly looser while those by Fully-Backward and Backward & Forward are comparable. Meanwhile, the computation time of Backward & Forward is significantly shorter than that of Fully-Backward. This demonstrates that our method of combining the backward and forward processes can compute comparably tight bounds much more efficiently.
4 Identifying Words Important to Prediction
SST contains sentiment labels for all phrases on parse trees, where the labels range from very negative (0) to very positive (4), and 2 for neutral. For each word, assuming its label is , we take , i.e., the distance to the neutral label, as the importance score, since less neutral words tend to be more important for the sentiment polarity of the sentence. We evaluate on 100 random test input sentences and compute the average importance scores of the most or least important words identified from the examples. In Table 4, compared to the baselines (“Upper” and “Grad”), the average importance score of the most important words identified by our lower bounds are the largest, while the least important words identified by our method have the smallest average score. This demonstrates that our method identifies the most and least important words more accurately compared to baseline methods.
Qualitative Analysis on Yelp
We further analyze the results on a larger dataset, Yelp. Since Yelp does not provide per-word sentiment labels, importance scores cannot be computed as on SST. Thus, we demonstrate a qualitative analysis. We use 10 random test examples and collect the words identified as the most and least important word in each example. In Table 4, most words identified as the most important by certified lower bounds are exactly the words reflecting sentiment polarities (boldfaced words), while those identified as the least important words are mostly stopwords. Baseline methods mistakenly identify more words containing no sentiment polarity as the most important. This again demonstrates that our certified lower bounds identify word importance better than baselines and our bounds provide meaningful interpretations in practice. While gradients evaluate the sensitivity of each input word, this evaluation only holds true within a very small neighborhood (where the classifier can be approximated by a first-order Taylor expansion) around the input sentence. Our certified method gives valid lower bounds that hold true within a large neighborhood specified by a perturbation set , and thus it provides more accurate results.
Conclusion
We propose the first robustness verification method for Transformers, and tackle key challenges in verifying Transformers, including cross-nonlinearity and cross-position dependency. Our method computes certified lower bounds that are significantly tighter than those by IBP. Quantitative and qualitative analyses further show that our bounds are meaningful and can reflect the importance of different words in sentiment analysis.
Acknowledgement
This work is jointly supported by Tsinghua Scholarship for Undergraduate Overseas Studies, NSF IIS1719097 and IIS1927554, and NSFC key project with No. 61936010 and regular project with No. 61876096.
References
Appendix A Illustration of Different Bounding Processes
Figure 1 illustrates a comparison of the Fully-Forward, Fully-Backward and Backward & Forward processes, for a 2-layer Transformer as an example. For Fully-Forward, there are only forward processes connecting adjacent layers and blocks. For Fully-Backward, there are only backward processes, and each layer needs a backward bound propagation to all the previous layers. For our Backward & Forward algorithm, we use backward processes for the feed-forward parts and forward processes for self-attention layers, and for layers after self-attention layers, they no longer need backward bound propagation to layers prior to self-attention layers. In this way, we resolve the cross-position dependency in verifying Transformers while still keeping bounds comparably tight as those by using fully backward processes. Empirical comparison of the three frameworks are presented in Sec. 4.3.
Appendix B Linear Bounds of Unary Nonlinear Functions
We show in Sec. 3.2 that linear bounds can be propagated over unary nonlinear functions as long as the unary nonlinear functions can be bounded with linear functions. Such bounds are determined for each neuron respectively, according to the bounds of the input for the function. Specifically, for a unary nonlinear function , with the bounds of obtained previously as , we aim to derive a linear lower bound and a linear upper bound , such that
where parameters are dependent on and designed for different functions respectively. We introduce how the parameters are determined for different unary nonlinear functions involved in Transformers such that the linear bounds are valid and as tight as possible. Bounds of ReLU and tanh has been discussed by Zhang et al. (2018), and we further derive bounds of , , , . and are only used when the layer normalization is not modified for experiments to study the impact of our modification. For the following description, we define the endpoints of the function to be bounded within range as and . We describe how the lines corresponding to the linear bounds of different functions can be determined, and thereby parameters can be determined accordingly.
For ReLU activation, . ReLU is inherently linear on segments and respectively, so we make the linear bounds exactly for or ; and for , we take the line passing the two endpoints as the upper bound; and we take when and when as the lower bound, to minimize the gap between the lower bound and the original function.
Tanh
For activation, . is concave for , and thus we take the line passing the two endpoints as the lower bound and take a tangent line passing as the upper bound. For , is convex, and thus we take the line passing the two endpoints as the upper bound and take a tangent line passing as the lower bound. For , we take a tangent line passing the right endpoint and as the lower bound, and take a tangent line passing the left endpoint and as the upper bound. and can be found with a binary search.
Exp
is convex, and thus we take the line passing the two endpoints as the upper bound and take a tangent line passing as the lower bound. Preferably, we take . However, is always positive and used in the softmax for computing normalized attention probabilities in self-attention layers, i.e., and . appears in the denominator of the softmax, and to make reciprocal function finitely bounded, the range of should not pass 0. Therefore, we impose a constraint to force the lower bound function to be always positive, i.e., , since is monotonously increasing. is the tangent line passing . So the constraint yields . Hence we take where is a small real value to ensure that such as .
Reciprocal
For the reciprocal function, . It is used in the softmax and layer normalization and its input is limited to have by the lower bounds of , and . With , is convex. Therefore, we take the line passing the two endpoints as the upper bound. And we take the tangent line passing as the lower bound.
Square
For the square function, . It is convex and we take the line passing the two endpoints as the upper bound. And we take a tangent line passing as the lower bound. We still prefer to take appears in the variance term of layer normalization and is later passed to a square root function to compute a standard derivation. To make the input to the square root function valid, i.e., non-negative, we impose a constraint . is the tangent line passing . For , is monotonously decreasing, the constraint we impose is equivalent to , and with , we have . So we take . For , is monotonously increasing, and thus the constraint we impose is equivalent to , and with , we have . So we take . And for , since is negative for while yields a valid lower bound, we take .
Square root
For the square root function, . It is used the to compute a standard derivation in layer normalization and its input is limited to be non-negative by the lower bounds of , and thus . is concave, and thus we take the line passing the two endpoints as the lower bound and take the tangent line passing as the upper bound.
Appendix C Linear Bounds of Multiplications and Divisions
We provide a mathematical proof of optimal parameters for linear bounds of multiplications used in Sec. 3.3. We also show that linear bounds of division can be indirectly obtained from bounds of multiplications and the reciprocal function.
For each multiplication, we aim to bound with two linear bounding planes and , where and are both variables and are concrete bounds of obtained from previous layers, such that:
Our goal is to determine optimal parameters of bounding planes, i.e., , , such that the bounds are as tight as possible.
We define a difference function which is the difference between the original function and the lower bound :
To make the bound as tight as possible, we aim to minimize the integral of the difference function on our concerned area , which is equivalent to maximizing
while . For an optimal bounding plane, there must exist a point such that (otherwise we can validly increase to make larger). To ensure that within the concerned area, we need to ensure that the minimum value of is non-negative. We show that we only need to check cases when is any of , i.e., points at the corner of the considered area. The partial derivatives of are:
If there is such that , should hold true. Thereby , and thus and cannot be the point with the minimum value of . On the other hand, if there is , i.e., on one border of the concerned area but not on any corner, should hold true. Thereby, , and . This property holds true for the other three borders of the concerned area. Therefore, other points within the concerned area cannot have smaller function value , so we only need to check the corners, and the constraints on become
We substitute in Eq. (7) with Eq. (8), yielding
where .
We have shown that the minimum function value within the concerned area cannot appear in , i.e., it can only appear at the border. When is a point with a minimum function value , can also only be chosen from the border of the concerned area. At least one of and holds true.
To maximize , since now only is unknown in and the coefficient of is , we take , and then
For the other case if we take :
We take similarly as in the case when , and then
We notice that , so we can simply adopt the first one. We also notice that are independent of , so we may take any within such as . Thereby, we obtain the a group of optimal parameters of the lower bounding plane:
C.2 Upper Bound of Multiplications
We derive the upper bound similarly. We aim to minimize
where .
To minimize , we take , and then
For the other case if we take :
To minimize , we take , and then
Since , we simply adopt the first case. And are independent of , so we may take any within such as . Thereby, we obtain a group of optimal parameters of the upper bounding plane:
C.3 Linear Bounds of Divisions
We have shown that closed-form linear bounds of multiplications can be derived. However, we find that directly bounding is relatively more difficult. If we try to derive a lower bound for as shown in Appendix C.1, the difference function is
It is possible that a minimum function value of for within the concerned area appears at a point other than the corners. For example, for , , the minimum function value of for appears at which is not a corner of . This makes it more difficult to derive closed-form parameters such that the constraints on are satisfied. Fortunately, we can bound indirectly by utilizing the bounds of multiplications and reciprocal functions. We bound by first bounding a unary function and then bounding the multiplication .
Appendix D Tightness of Bounds by the Backward Process and Forward Process
We have discussed that combining the backward process with a forward process can reduce computational complexity, compared to the method with the backward process only. But we only use the forward process for self-attention layers and do not fully use the forward process for all sub-layers, because bounds by the forward process can be looser than those by the backward process. We compare the tightness of bounds by the forward process and the backward process respectively. To illustrate the difference, for simplicity, we consider a -layer feed-forward network , where is the input vector, and are the weight matrix and the bias vector for the -th layer respectively, is the pre-activation vector of the -th layer, is the vector of neurons in the -th layer, and is an activation function. Before taking global bounds, both the backward process and the forward process bound with linear functions of . When taking global bounds as Eq. (3) and Eq. (4), only the norm of weight matrix is directly related to the in binary search for certified lower bounds. Therefore, we try to measure the tightness of the computed bounds using the difference between weight matrices for lower bounds and upper bounds respectively. We show how it is computed for the forward process and the backward process respectively.
For the forward process, we bound each neuron with linear functions:
To measure the tightness of the bounds, we are interested in , , and also . Initially,
We can forward propagate the bounds of to :
With the global bounds of that can be obtained with Eq. (3) and Eq. (4), we bound the activation function:
And then bounds can be propagated from to :
illustrates how the tightness of the bounds is changed from earlier layers to later layers.
D.2 The Backward Process and Discussions
For the backward process, we bound the neurons in the -th layer with linear functions of neurons in a previous layer, the -th layer:
We have shown in Sec. 3.1 how such bounds can be propagated to , for the case when the input is sequential. For the nonsequential case we consider here, it can be regarded as a special case when the input length is 1. So we can adopt the method in Sec. 3.1 to propagate bounds for the feed-forward network we consider here. We are interested in , and also . Weight matrices of linear bounds before taking global bounds are and which are obtained by propagating the bounds starting from . According to bound propagation described in Sec. 3.2,
illustrates how the tightness bounds can be measured during the backward bound propagation until .
There is a in Eq. (10) instead of in Eq. (9). The norm of in Eq. (9) can quickly grow large as increases during the forward propagation when is greater than 1, while this generally holds true for neural networks to have greater than 1 in feed-forward layers. While in Eq. (10), can have both positive and negative elements and tends to allow cancellations for different , and thus the norm of tends to be smaller. Therefore, the bounds computed by the backward process tend to be tighter than those by the forward framework, which is consistent with our experiment results in Table 3.