The Lipschitz Constant of Self-Attention
Hyunjik Kim, George Papamakarios, Andriy Mnih
Introduction
In deep learning, we often use Lipschitz continuity as a constraint for neural networks, to control how much a network’s output can change relative to its input. Such Lipschitz constraints are useful in several contexts. For example, Lipschitz constraints can endow models with provable robustness against adversarial pertubations (Cisse et al., 2017; Tsuzuku et al., 2018; Anil et al., 2019), and guaranteed generalisation bounds (Sokolić et al., 2017). Moreover, the dual form of the Wasserstein distance is defined as a supremum over Lipschitz functions with a given Lipschitz constant, hence Lipschitz-constrained networks are used for estimating Wasserstein distances (Peyré & Cuturi, 2019). Further, Lipschitz-constrained networks can stabilise training for GANs, an example being spectral normalisation (Miyato et al., 2018). Finally, Lipschitz-constrained networks are also used to construct invertible models and normalising flows. For example, Lipschitz-constrained networks can be used as a building block for invertible residual networks and hence flow-based generative models (Behrmann et al., 2019; Chen et al., 2019). Additionally, Neural ODEs (Chen et al., 2018; Grathwohl et al., 2019) are typically defined using vector fields parameterized via Lipschitz networks, so that the flow generated by the vector field is guaranteed to exist for all times.
Nonetheless, designing Lipschitz-continuous neural networks and computing (or even upper-bounding) their Lipschitz constant is a hard problem. Previous work mostly focused on fully-connected and convolutional networks, not only because they are common in deep learning, but also because they are relatively simple to analyze, as compositions of linear maps and pointwise non-linearities. Even in this case however, exact evaluation of the Lipschitz constant of fully-connected and convolutional networks is NP-hard (Virmaux & Scaman, 2018) and obtaining a tight upper bound remains a challenging task (Virmaux & Scaman, 2018; Fazlyab et al., 2019; Latorre et al., 2020).
Fully-connected and convolutional networks are not the only neural networks worthy of interest. Recently, self-attention (Vaswani et al., 2017) has become a popular alternative to recurrent neural networks. Self-attention is a key component of the Transformer (Vaswani et al., 2017), that has found success as a building block in models of various data modalities, starting with natural-language processing (Vaswani et al., 2017; Devlin et al., 2019; Brown et al., 2020) and extending to computer vision (Zhang et al., 2019; Parmar et al., 2019), audio generation (Huang et al., 2019), and reinforcement learning (Parisotto et al., 2020). However, so far no previous work has analysed the Lipschitz properties of self-attention, and thus it has been unclear whether self-attention is a viable option in applications that require Lipschitz constraints. In this work, we address this gap in the theory of self-attention by providing a thorough analysis of its Lipschitz properties. In particular, we make the following contributions:
We prove that the widely used dot-product self-attention is not Lipschitz, and therefore not suitable to use in applications requiring Lipschitz constraints.
We formulate L2 self-attention as an alternative, and show that it is Lipschitz.
We derive a theoretical upper bound on the Lipschitz constant of L2 self-attention, and provide empirical evidence of the asymptotic tightness of the bound.
As a practical demonstration of the theory, we use this bound to formulate invertible self-attention, and explore its use in a Transformer architecture for character-level language modelling. We compare its test log-likelihood and stability to dot-product self-attention.
Lipschitz Constant of Fully-Connected/Convolutional Layers
We first define the notion of Lipschitz continuity, and proceed to define the Lipschitz constant.
Given two metric spaces and , a function is called Lipschitz continuous (or -Lipschitz) if there exists a constant such that
The smallest such is the Lipschitz constant of , denoted .
Next, we outline some basic results that are useful for estimating Lipschitz constants, also covered in related works (Virmaux & Scaman, 2018; Behrmann et al., 2019). We describe how these results are used to provide bounds on the Lipschitz constant of fully-connected networks (FCN) and convolutional neural networks (CNN), using the fact that both are compositions of linear maps and pointwise non-linearities. To begin with, the following theorem suggests a way to bound for a differentiable Lipschitz function :
Hence if is a linear map represented by a matrix then
where is the operator norm on matrices induced by the vector -norm, and is the largest singular value of . Under this choice of norm, many common non-linearities (including relu, sigmoid, tanh, elu) are -Lipschitz. is usually estimated via power iteration; we provide details on how this is done in Appendix B.
Since we now know the Lipschitz constants of the components of both FCN and CNN, we can bound their Lipschitz constants by applying the following lemma:
Let be two composable Lipschitz functions. Then is also Lipschitz with .
For a fully-connected network (FCN) or a convolutional neural network (CNN) , we have under a choice of -norm with -Lipschitz non-linearities .
The above bound is not necessarily tight; there are various works that compute tighter bounds for FCN and CNN (e.g. Virmaux & Scaman, 2018; Fazlyab et al., 2019; Latorre et al., 2020).
Lipschitz Constant of Self-Attention
In what follows, we will prove that as defined above is not Lipschitz, assuming that the map is non-trivial, i.e. . It is sufficient to show that a single head is not Lipschitz, since is a linear combination of the outputs of each head. Also note that is a stochastic matrix, i.e. its entries are non-negative and its rows sum to . Since the rows of are the ’s, a linear transformation of each by some matrix is equivalent to right multiplication of by . So right multiplication of by is a linear map and thus Lipschitz. Therefore, we are interested in the mapping ; this is not a linear mapping because itself is a non-linear function of . In fact, we show that is not Lipschitz, thus proving the first main result of the paper:
DP-MHA is not Lipschitz for any vector -norm with .
Summary of Proof. We use Theorem 2.1, noting that if the supremum of the norm of the Jacobian is infinite, then the mapping is not Lipschitz. In particular, we show that when for some , some elements of the Jacobian of grow proportionally to the sample variance of , which is unbounded.
is the Kronecker delta
See Appendix A for useful identities in deriving the above Jacobian.
Let us investigate the scalar . We observe that it is in fact a variance of a discrete distribution. Specifically:
We use this observation to show that is unbounded, and so is unbounded, hence DP-MHA is not Lipschitz. Consider the case . Then
High-level intuition for proof. At , , the mean of the inputs. The rate of change of is governed by how fast the softmax saturates when is perturbed, which is determined by how spread out the are. The more spread out they are (the higher the sample variance), the greater the rate of saturation of the softmax, and the faster the rate of change of . Since the sample variance of can be arbitrarily large, the rate of change of can also be arbitrarily large, i.e. the entries of the Jacobian (and hence its -norm) can become arbitrarily large. In Appendix D, we show that adding bias terms to and does not resolve the issue.
The implications of this result are the following. (1) There can be undesirable behaviour (e.g. training instabilities) for the Transformer when some inputs are close to zero and others have large magnitude. (2) Dot-product self-attention (and hence the standard Transformer) is not a suitable choice when we require a Lipschitz neural network, such as for formulating invertible residual networks (Behrmann et al., 2019). Therefore, to use self-attention and Transformers in such applications, a Lipschitz formulation of self-attention is required, together with an explicit (ideally tight) upper bound to its Lipschitz constant, to quantify how much the output can change with respect to changes in the input.
2 L2 self-attention: a Lipschitz formulation of self-attention
The pathology in dot-product self-attention arises because the softmax probabilities are constant with respect to when . This behaviour can be undesirable as we want to vary according to , regardless of whether is zero or not. Hence we propose an alternative form of self-attention based on L2 distance:
with the normalisation constant ensuring that . We will refer to it as L2 self-attention. It is reminiscent of the standard squared-exponential kernel, but with softmax normalisation that ensures that each row of the kernel matrix sums to . Normalisation is usually necessary to deal with inputs of varying length (Wang et al., 2018), hence we keep the softmax for L2 self-attention. Similarly to dot-product self-attention, L2 self-attention can be computed efficiently with matrix operations; see Appendix E for details, with a comparison of wall-clock runtimes between different choices of attention.
We require for each head to be Lipschitz. In Lemma F.1 of Appendix F we show that L2-MHA is not Lipschitz for arbitrary , , and that tying is sufficient for L2-MHA to be Lipschitz, with intuition for why tying is sufficient.
In each head of the self-attention , right multiplication by has been included for the theorem below to hold (details are in the proof). In practice, there is little harm done by this extra linear transformation, since when the heads are combined together in , each is additionally transformed by , a free parameter.
The second main result of the paper is the following:
L2-MHA is Lipschitz, with the following bound on :
and the following bound on :
where is an invertible univariate function on , and is the input sequence length.
Specifically, where is the Lambert -function, which grows sub-logarithmically as (Corless et al., 1996). Hence the above bounds can be simplified to for and for .
See Appendix F, which uses the key observation that is a covariance matrix (c.f. Equation (7)) to bound , the norm of the Jacobian of . Appendix G shows how the argument can be modified to prove the analogous result for the case with masking in the self-attention. ∎
These bounds are complemented by the concurrent work of Vuckovic et al. (2020), which provides a bound on using measure-theoretic tools.
Application: Invertible Self-Attention
Consider the residual function . Behrmann et al. (2019) give the following sufficient condition for its invertibility: if is a contraction with respect to some metric, i.e. if , and the metric space on which is defined is complete, then is invertible. (A Euclidean space with a metric induced by a -norm for is always complete.) Specifically, the inverse is the unique fixed point of the recursion , since by the definition of the inverse we have . Because is a contraction, Banach’s Fixed Point Theorem guarantees that this fixed point exists and is unique for all , and that the recursion converges for all initial values (often set to in practice) exponentially fast. Hence the inverse can be computed to arbitrary accuracy (up to numerical precision in practice) by the above fixed-point iteration.
Note that a composition of such invertible residual blocks is also invertible. Behrmann et al. (2019) use this observation to design invertible ResNets: they take to be a CNN normalised by an upper bound on given by Corollary 2.1, making the resulting function contractive. For the -norm , a hyperparameter is chosen and each linear map (convolution) in the CNN is multiplied by if where is estimated by power iteration (c.f. Appendix B). This multiplicative factor determines the scale of the Lipschitz constant of the normalised function.
2 Invertible self-attention
The standard use case of self-attention is with a skip connection inside the Transformer. A Transformer block is composed of residual blocks of multihead self-attention (MHA) and fully-connected (FCN) layers (Figure 1). Hence similarly to invertible ResNets, we can normalise L2-MHA by the upper bounds given in Theorem 3.2 to obtain Contractive-L2-MHA , with which we can obtain invertible self-attention . Since Dropout is also part of the residual branch along with Contractive-L2-MHA, we should check that it is also contractive. At test time, Dropout multiplies inputs by the dropout keep probability , so it is a contraction with Lipschitz constant at evaluation time. At training time, Dropout amounts to setting some inputs to zero, while keeping other inputs constant. This can be expressed as right multiplication by a diagonal binary matrix , and for such matrices we can verify . Notice that LayerNorm is not part of the residual branch, hence its Lipschitz continuity is not relevant for invertibility; rather, we can replace it with an invertible normalisation such as ActNorm (Kingma & Dhariwal, 2018). However, architectures that place LayerNorm inside the residual branch (termed pre-LN as opposed to the traditional post-LN in Figure 1) have become more prevalent in the literature (Wang et al., 2019; Xiong et al., 2020), and in this case it makes sense to investigate its Lipschitz continuity. We show that LayerNorm is Lipschitz in Appendix N, with a bound on its Lipschitz constant.
In the next section, we investigate the properties of invertible self-attention and how it compares with the standard dot-product self-attention; we replace DP-MHA in the Transformer with Contractive-L2-MHA, hence replacing the residual self-attention module with invertible self-attention. We are not interested in the modified Transformer per se, but rather in comparing the properties of invertible self-attention to standard self-attention — we only use the Transformer as a testbed for this purpose, since self-attention is commonly used in a Transformer. Given the theoretical focus of the paper, we believe that a more challenging application of invertible self-attention, such as normalising flow-based modelling, would be more suitable as a separate paper focused on that particular application.
Experimental Results
We use this observation to provide empirical evidence for the asymptotic tightness of the upper bound on in Theorem 3.2. In Figure 2, we show the upper bound as well as the lower bound on obtained by optimising with respect to for L2-MHA with 50 different random initialisations of , with and varying between and . See Appendix H for further details. Note that we use a log-scale for the x-axis, and recall that the upper bound is , dominated by the term for large . Hence the plot for the upper bound shows a linear trend. We also observe that the slope of the lower bound is very similar, providing empirical evidence that the upper bound is asymptotically tight.
There are at least two possible explanations for the gap between the upper and lower bounds. (1) The lower bound is only a local optimum — the true Lipschitz constant is a global optimum across inputs, which can be difficult to attain especially for high values of . (2) The multiplicative constant of the upper bound may be loose. Assuming asymptotic tightness, it remains an open question whether the multiplicative constant can be tightened. We show the analogous plot for and discuss the results in Appendix J. Additionally in Appendix K, we show that optimising w.r.t. for DP-MHA causes the norm to diverge, providing empirical verification of Theorem 3.1, that DP-MHA is indeed not Lipschitz.
2 Numerical invertibility of MHA residual map
Recall from Section 4.1 that is invertible if is contractive. Hence if is Contractive-L2-MHA, is necessarily invertible. However, technically we do not disprove the invertibility of DP-MHA, since the converse does not hold in general i.e. if is DP-MHA, which we have shown is not Lipschitz hence not contractive, it may still be the case that is invertible. To verify that DP-MHA (with the skip connection) is not invertible in practice, we compare the numerical invertibility of the residual map between the cases where is L2-MHA and DP-MHA in Figure 3. For each, we take MHA with heads and randomly initialised weights, and quantify the maximum reconstruction error across a batch of inputs whose outputs are inverted via the fixed-point iteration described in Section 4.1. We use , , and (see Appendix I for analogous results for a wider range of and and for DP-MHA with trained weights). To highlight the difference between the two types of self-attention, recall in the proof of Theorem 3.1 (showing that DP-MHA is not Lipschitz) that when one of the inputs is , some terms of the Jacobian grow with the sample variance of . Hence we check numerical invertibility at a set of inputs where and are chosen uniformly at random.
In Figure 3, we see that DP-MHA is not invertible whereas L2-MHA is invertible for sufficiently small . This shows how not having the theoretical guarantee of being contractive can cost us invertibility in practice. We note that the figure shows local invertibility at the sampled inputs, as opposed to global invertibility across the whole input space, yet this clearly highlights the difference between the two choices of self-attention. Experiments with the globally invertible self-attention obtained by normalising with the Lipschitz upper bound are provided in the next section.
3 Expressiveness of L2-MHA and invertible self-attention
A natural question to ask is: how does the expressiveness of L2-MHA and Contractive-L2-MHA (that leads to invertible self-attention with the skip connection) compare with the original DP-MHA? We expect that the Lipschitz constraint will limit the expressiveness of the Transformer, and would like to find out by how much. We investigate this by comparing the performance of the original Transformer and the Transformer with invertible self-attention (c.f. Figure 1) at character-level language modelling on the Penn Treebank dataset (Marcus et al., 1993). We compare the test negative log-likelihood (NLL) of a baseline LSTM, the original Transformer (DP-MHA), and a series of models between the original Transformer and the Transformer with invertible self-attention (Contractive-L2-MHA), making one change at a time and tuning the hyperparameters on a validation set. For Contractive-L2-MHA, we normalise L2-MHA by the bound on as it is tighter than the bound on . During training we backpropagate through these contractive blocks (including the denominator) to update the model parameters. We found that only backpropagating through the numerator (i.e. applying stop-gradient to denominator) gave slightly worse performance. See Appendix H for experimental details.
The results are shown in Figure 4. The first plot shows the best performing LSTM reaching a test NLL of around , and the second plot shows the best performing Transformer reaching a slightly improved performance for – layers of Transformer blocks. We observe instabilities in training for a higher number of layers, requiring careful tuning of the learning rate schedule for stability at the cost of performance, a commonly observed phenomenon in the literature of deep Transformer architectures (Bapna et al., 2018; Parisotto et al., 2020). The third plot shows results for the Transformer with DP-MHA replaced with L2-MHA but without tying and , and we observe a very similar test performance. The fourth plot shows the change when we further tie the query and key weights (making ); we see that there is a small degradation in performance. Here the number of trainable parameters has been reduced, but in Appendix L we show that matching parameter count does not help performance, suggesting that the reduction in performance when tying queries and keys is not solely due to having fewer parameters. We note that performance saturates at around layers for each Transformer model so far. On the rightmost plot we show results when further dividing self-attention in each block by the upper bound on , to obtain invertible self-attention. This does give reduced performance for the same number of layers, but we can attain similar performance with more layers, no longer saturating at layers.
Thus we conclude the following. (1) Replacing the dot-product with the L2 distance incurs hardly any loss in expressiveness. (2) Tying the query and key weights to obtain Lipschitz self-attention incurs a small loss in expressiveness. (3) Dividing by the upper bound on to obtain invertible self-attention incurs a noticeable loss in expressiveness, but also has a stabilising effect on the optimisation of the Transformer, thus allowing one to compensate for the apparent loss in expressiveness by increasing the number of layers.
4 Training Stability of DP-MHA vs L2-MHA
In Figure 5, we compare the output variance of trained L2-MHA against trained DP-MHA, with weights from the one-layer Transformer (L2), model and (DP) model used for Figure 4 respectively. We take the same distribution of inputs as used for the numerical invertibility experiment in Section 5.2, and show the histogram of inputs and outputs after flattening the input/output tensors. We see that the range of outputs remains similar to the range of inputs for Lipschitz L2-MHA, whereas for DP-MHA the outputs have a much wider range, because the Jacobian norm is large for DP-MHA at these inputs.
In practice, this leads to instabilities in training for DP-MHA, hence requiring careful tuning of the learning rate schedule for training deeper Transformer models: linear warmup and square root decay, as detailed in Appendix H. We investigate the behaviour of the different Transformer models on the above PTB task when using a fixed learning rate. We observe that DP-MHA fails to train at all beyond 10 layers, whereas both L2-MHA () (i.e. Lipschitz L2-MHA but not contractive) and Contractive-L2-MHA shows stable training for up to 18 layers (see Appendix M for the training curves). This was the deepest model we could fit on a single GPU, and we expect to be able to train even deeper models with these two. In Table 1 we show the best Test NLL across training for each of the Transformer models. Note that for DP-MHA training becomes unstable beyond 10 layers, so we are only able to provide results up to 10 layers. The generalisation performance of the best model for each setting of self-attention is similar.
Conclusion and Discussion
We have shown that the widely used dot-product self-attention is not Lipschitz, and that the proposed L2 self-attention is Lipschitz, by deriving an Lipschitz bound for and an bound for , where is the input sequence length. We also provided empirical evidence of the asymptotic tightness of the bound for . We demonstrated that Lipschitz-constrained self-attention can be used to formulate invertible self-attention, which we experimentally evaluated on a character-level language modelling task. And finally, we also showed that L2-MHA is more stable during training, allowing the use of fixed learning rate for stable training of deep architectures.
Our approach to Lipschitz self-attention has been to replace the dot-product kernel with an L2 kernel. An alternative would be to constrain the inputs of self-attention to be bounded; if the input space is compact, e.g. , any continuously differentiable function is Lipschitz, including dot-product self-attention. However, while being simple to implement, this solution has its own difficulties. First, it makes the Lipschitz constant depend on the range of the input, and thus obtaining a tight bound would require non-trivial mathematical work. We stress that a guarantee that the function is Lipschitz does not tell us anything about its Lipschitz constant; without a tight Lipschitz bound, the true Lipschitz constant can be very large, at which point it is unhelpful that the function is Lipschitz. Second, since self-attention is typically applied at multiple layers within a model (e.g. Transformer), the input to each self-attention will live in a different compact set that depends on the parameters of the previous layers, complicating the analysis for subsequent layers. A solution is to constrain the inputs of each layer to be in the same compact set, e.g. by passing them through a sigmoid non-linearity. This however can have undesirable side effects such as vanishing gradients when the sigmoids are saturated. Despite these difficulties, this could be a worthwhile alternative route for obtaining Lipschitz self-attention to explore in the future.
Having a provably Lipschitz self-attention module at our disposal makes it possible to use Transformer-based architectures in applications requiring Lipschitz constraints, while enjoying theoretical guarantees. A natural application of Lipschitz self-attention is for residual flows (Behrmann et al., 2019), and for parameterising Neural ODEs (Chen et al., 2018) where a Lipschitz vector field guarantees the existence of a unique solution to the ODE for all times. These models can be used for density estimation and generative modelling of sets. Another interesting direction for future work would be to analyse different variants of self-attention based on kernels other than dot-product and L2, as (Tsai et al., 2019) do from an experimental perspective, for which we believe the mathematical tools developed in this paper may aid the analysis.
Acknowledgements
We would like to thank Adam Kosiorek, Arnaud Doucet, Yee Whye Teh, Michalis Titsias, Emilien Dupont and Theophane Weber for helpful discussion and feedback.
References
Appendix A Useful Identities for deriving Jacobian expressions
In this section, we list some useful identities for deriving the Jacobians of the expressions in the paper.
Note is a row vector, so is a matrix.
Appendix B Power Iteration
The iteration will converge if has an eigenvalue that is strictly greater in magnitude than its other eigenvalues, and the starting vector has a nonzero component in the direction of an eigenvector associated with the dominant eigenvalue. This happens with probability if is chosen at random, and the convergence is geometric with ratio where is the eigenvalue with second largest magnitude (Mises & Pollaczek-Geiringer, 1929).
Appendix C Proof of Theorem 3.1 for General D𝐷D
DP-MHA is not Lipschitz for any vector -norm with .
For the last equality, note has all rows equal to zero except for the th row given by . We can then verify that simplifies to .
For vector -norms, is bounded if and only if its entries are bounded, by definition of the operator norm. The entries of are bounded for arbitrary only if the entries of are bounded. So let us investigate the entries of this matrix. Writing out each term of the matrix, we observe that it is in fact a covariance matrix of a discrete distribution. Specifically:
Note that we have shown that single head dot-product self-atttention () is not Lipschitz, but it is clear that this implies multihead self-attention DP-MHA is also not Lipschitz, since the output of multihead attention is a linear combination of the outputs of each head. ∎
Appendix D Bias term in DP Self-Attention
Appendix E Efficient Computation of L2 Self-Attention
Dot-product self-attention only requires a few matrix multiplications to compute the logits (i.e. the inputs to the softmax) between all pairs of inputs, without having to loop over pairs, hence it can be computed efficiently. Similarly, we can show that L2 self-attention can also be computed in an efficient manner. Using the identity we can compute the logits of L2 attention between all pairs via matrix multiplications and computation of row-wise L2 norms, with negligible overhead compared to dot-product self-attention. Specifically, for L2 self-attention we can show that
In Table 2 we show the wall-clock training times for the Transformer models with different attention functions and a varying number of layers. It is evident that the differences between the models are rather small.
Appendix F Proof of Theorem 3.2
Also note is symmetric, and each row/colum sums to , i.e. . Hence we may simplify the Jacobian terms as follows:
Let . Then we have:
The intuition for this result is as follows: a reason for DP-MHA not being Lipschitz is that for ,, the attention weights become uniform regardless of the values of for . A similar issue arises for L2-MHA with and full-rank , as shown above: given any , we can choose such that the become uniform.
Hence we impose the restriction that . With this assumption we have
Noting , we would like to upper bound .
Consider the choice , where is the maximum absolute row sum of . A key observation is that if we can bound the -norm of the Jacobian of , a single output of , (i.e. a single block row of ) then this is also a bound on due to permutation equivariance of self-attention; all block rows have the same maximal when each is optimised over the input . Using this, we can prove that admits an upper bound that is . Below we state and prove lemmas that lead to the proof of this upper bound.
First we analyse the term , that appears in the first term of . Note that for , so that the rows of are , we have
The central inequality used throughout the proof of the main theorem is the following:
where (hence ). Define:
First note that as , exponentially fast, causing the product . Hence we expect the above quantity to be bounded and attain its maximum.
Let for notational conciseness, and note . By taking partial derivatives with the chain rule, we have that for
Hence the derivative is if and only if or , the latter being equivalent to . Hence at the maximum, the non-zero values among must be equal to one another. It is clear now that the maximum value is attained when for (and recall ). So for . Substituting this into , and rearranging, we obtain . Note is increasing for hence . ∎
Note for . Since is increasing, we have for . In fact, it is known that (Corless et al., 1996).
Using the inequalities , and , we have:
For the first equality, note that . For the second equality, note that the summand for is because the term . Each of the terms in the brackets are bounded by the following lemmas:
( defined as in Lemma F.2).
.
Note for real vectors . Hence
where , .
Note since for vector . Hence .
Putting the above lemmas altogether, with the observation by permutation invariance of (since is permutation equivariant and is the maximum absolute row sum), we have
where the last inequality holds for .
The full multihead attention map that combines the heads is:
Note the Jacobian is a block matrix whose rows are , hence , and similarly . Hence we have
Combining this with Inequality (33), we have:
Let A be a block matrix with block rows . Then , and equality holds if and only if the first right singular vectors of the align.
Note that equality holds if and only if the first right singular vectors of the align. ∎
Hence a bound on the spectral norm of each block row of can give us an bound on , which may be loose, and it remains an open question as to whether this bound can be tightened.
To bound the norm of each row of , we use the following lemmas:
Directly use Cauchy–Schwartz on and in the proof of Lemma F.4. ∎
Again using the inequalities , and , with the additional equality , we have the bound:
To obtain the final result for the full multihead self-attention , we need a final lemma:
Let A be a block matrix with block columns . Then .
where we are using the substitution , and the last inequality holds by e.g. Cauchy–Schwartz inequality on and . ∎
Since , by Lemma F.8 we have that
Combining this with Inequality (34), we have:
Appendix G The Case with Masking
Since self-attention is often used with masking, a natural question is how masking affects the derived bounds. In self-attention (for any choice of attention function), masking is implemented as follows: given a set of mask indices , the logits (i.e. the inputs to the softmax) are set to at the mask indices. That is,
Masking implies is not a function of for , hence for . Thus is equal to the th output for self-attention with inputs restricted to , the unmasked inputs with respect to the th output. Hence will no longer contribute to the bound on , and hence the bound for the unmasked case will continue to hold as long as i.e. attends to itself (this is necessary for the proof of Lemma F.2 to hold). The bound can in fact be tightened by replacing with , the number of unmasked inputs with respect to the th output.
Appendix H Experimental Details
For the experiment in Section 5.1, showing the asymptotic tightness of the upper bound on where is L2-MHA, we fix all free parameters of (namely ) to be the identity, and only optimise the input . We use random initialisations of for each , where for (we observed that having itself be random improves optimisation). We display the top results for each value of after optimising each random initialisation till convergence using Adam (Kingma & Ba, 2015) with a learning rate of .
For the experiments in Section 5.3, we comparing the performance of the original Transformer and the Transformer with Lipschitz/invertible self-attention at character-level language modelling on the Penn Treebank dataset (Marcus et al., 1993).We use the standard training-validation-test split, and the dataset can be found at e.g. https://github.com/harvardnlp/TextFlow/tree/master/data/ptb. Each training example is a sentence represented as a variable-length sequence of characters, and examples are batched according to length such that padding is minimised, with the maximum sequence length set to . All models are autoregressive, outputting the logits for the categorical likelihood predicting the next character, and are trained using maximum likelihood (cross-entropy loss) with a batch size of . The LSTM models have the dimensionality of the hidden state equal to the dimensionality of the cell state (the usual default implementation). The Transformer models are trained with a varying number of blocks (number of layers) with heads and , tuning hyperparameters for dropout rate in and base learning rate with number of warmup iterations for the standard custom learning rate schedule in Vaswani et al. (2017):
where is the learning rate at training iteration . Hence the learning rate linearly increases from to over iterations, then decays proportionally to . We use Glorot Uniform initialisation (Glorot & Bengio, 2010) for all weights (), except for weights in L2-MHA that are initialised from , and is a hyperparameter. For , we used . All experiments were done in Tensorflow 1.14 (Abadi et al., 2016) on single Nvidia Tesla V100 GPUs.
Appendix I Numerical Invertibility of MHA Residual Map
Following Section 5.2, Figure 6 confirms that numerical invertibility does not hold for trained weights for dot-product multihead self-attention (DP-MHA) (obtained from one-layer Transformer (DP) model used for Figure 4), similar to the randomly initialised weight case. Figure 7 shows additional results for different values of and .
In Figure 8, we show the lower bound on obtained by optimising using the same optimisation procedure as for Figure 2 of Section 5.1. Here the optimisation is more difficult, evident in the variance of the top values, and the trend is less clear, but it appears that grows at a rate of . The message is less clear here, and there are at least two possibilities:
The optimisation is difficult even for small values of , hence Figure 8 shows a loose lower bound.
If the lower bound is tight, this suggests that the bound in Theorem 3.2 is not asymptotically tight, and could be improved to (or as for ).
Appendix K Optimising the norm of the Jacobian of DP-MHA
In Figure 9, we show how the norm of the Jacobian for DP-MHA keeps increasing when being optimised with respect to . This is a useful sanity check validating our theoretical result of Theorem 3.1, that DP-MHA is not Lipshchitz. The oscillations are likely due to momentum term of Adam optimizer that was used to optimise the norm.
Appendix L Experiment tying keys and queries of L2-MHA but preserving parameter count
In Figure 4 of Section 5.3, we have shown that there is a clear reduction in performance when tying the keys and queries. To test whether this can be attributed to the reduction in parameter count, we tried doubling the number of columns of when the keys and queries are shared (i.e. from to ) so that the shared model has the same number of parameters as the unshared model. In Figure 10, the third column shows results for shared L2-MHA, but with the same number of parameters as the unshared L2-MHA i.e. without tying the keys and queries. The performance is similar to the second column (tying with a reduced number of parameters), suggesting that there is an inherent limitation in expressiveness to tying the keys and queries, and that the reduction in number of parameters is an insufficient explanation this phenomenon.
Appendix M Training curves for fixed learning rate DP-MHA vs L2-MHA
Appendix N The Lipschitz constant of LayerNorm
In this section, we show that LayerNorm is Lipschitz, with a loose bound on its Lipschitz constant w.r.t. to the -norm. LayerNorm is defined as follows:
In the trivial case where are all equal or when , hence , so its Lipschitz constant is 0. Thus let us assume and not all are equal.
First let us compute the derivative of and w.r.t :
Now the derivative of , the th element of , w.r.t. is
recalling that is the maximum absolute row sum.
Let . Hence , and
Noting that this expression is scale-invariant in , we may assume WLOG , since we are assuming not all are equal and hence at least one is non-zero.
Since all terms are bounded, this continuous expression reaches a global maximum for some value of with .
It is easy to see that at the global maximum, : suppose this were to be true, WLOG . Then let us see how the quantity (37) changes when is increased by and is decreased by , keeping the sum constant. It is easy to see that the numerator stays constant, but the denominator changes by . Since for small , the numerator of (37) stays constant but the denominator decreases, the quantity (37) increases, contradicting that the global max is obtained for . Hence we may assume that .
Hence the quantity (37) (in particular, ) is differentiable at the global maximum, at which the partial derivatives of the following Lagrangian are zero:
From now on let us write for below to reduce clutter. Setting and noting , we obtain
Hence at the global maximum, takes one of two values and . Further we have that
If both and are among the , we have that . Solving for and plugging it in back to Equation (38), we get:
Since , and , is minimised when only one of the is and the rest are . Hence a crude lower bound on is , giving a bound:
However we conjecture that the true global maximum is attained when (i.e. all the for are equal to ), for which it is easy to show that .