Datasets:
Tasks:
Question Answering
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
100K - 1M
ArXiv:
License:
Add files using upload-large-folder tool
Browse filesFiles changed (50)
- md/dev/89ia77nZ8u/89ia77nZ8u.mdAdded
- md/dev/Loek7hfb46P/Loek7hfb46P.mdAdded
- md/dev/T8wHz4rnuGL/T8wHz4rnuGL.mdAdded
- md/dev/Uuf2q9TfXGA/Uuf2q9TfXGA.mdAdded+355
- md/dev/VYYf6S67pQc/VYYf6S67pQc.mdAdded+335
- md/dev/VpYBxaPLaj-/VpYBxaPLaj-.mdAdded+537
- md/dev/jQgsZDspz5h/jQgsZDspz5h.mdAdded+378
- md/train/-xEk43f_EO6/-xEk43f_EO6.mdAdded+277
- md/train/2-0wS9-cSL/2-0wS9-cSL.mdAdded+424
- md/train/3Aoft6NWFej/3Aoft6NWFej.mdAdded+274
- md/train/B1M8JF9xx/B1M8JF9xx.mdAdded+324
- md/train/BJfOXnActQ/BJfOXnActQ.mdAdded+284
- md/train/CO87OIEOGU8/CO87OIEOGU8.mdAdded+229
- md/train/ErivP29kYnx/ErivP29kYnx.mdAdded+258
- md/train/H1eSS3CcKX/H1eSS3CcKX.mdAdded+704
- md/train/H1ecDoR5Y7/H1ecDoR5Y7.mdAdded+515
- md/train/HJWLfGWRb/HJWLfGWRb.mdAdded+264
- md/train/HkSZyinVG/HkSZyinVG.mdAdded+250
- md/train/HkeuD34KPH/HkeuD34KPH.mdAdded+303
- md/train/HkxjYoCqKX/HkxjYoCqKX.mdAdded+306
- md/train/HyAddcLge/HyAddcLge.mdAdded
- md/train/HylsTT4FvB/HylsTT4FvB.mdAdded
- md/train/HyxfGCVYDr/HyxfGCVYDr.mdAdded
- md/train/Hyxu6oAqYX/Hyxu6oAqYX.mdAdded
- md/train/LKUfuWxajHc/LKUfuWxajHc.mdAdded
- md/train/LKoMTwTuQnC/LKoMTwTuQnC.mdAdded
- md/train/MBH29cOeohr/MBH29cOeohr.mdAdded
- md/train/S1Bb3D5gg/S1Bb3D5gg.mdAdded
- md/train/S1sRrN-CW/S1sRrN-CW.mdAdded
- md/train/SJxSOJStPr/SJxSOJStPr.mdAdded
- md/train/SklD9yrFPS/SklD9yrFPS.mdAdded
- md/train/SyProzZAW/SyProzZAW.mdAdded
- md/train/SyevYxHtDB/SyevYxHtDB.mdAdded
- md/train/T6AxtOaWydQ/T6AxtOaWydQ.mdAdded
- md/train/Xb8xvrtB8Ce/Xb8xvrtB8Ce.mdAdded
- md/train/dx11_7vm5_r/dx11_7vm5_r.mdAdded
- md/train/fSTD6NFIW_b/fSTD6NFIW_b.mdAdded
- md/train/hl3v8io3ZYt/hl3v8io3ZYt.mdAdded
- md/train/hw2VfWAr6t6/hw2VfWAr6t6.mdAdded
- md/train/ioyq7NsR1KJ/ioyq7NsR1KJ.mdAdded
- md/train/jnRqf0CzBK/jnRqf0CzBK.mdAdded
- md/train/lE1AB4stmX/lE1AB4stmX.mdAdded
- md/train/luGQiBeRMxd/luGQiBeRMxd.mdAdded
- md/train/r1CE9GWR-/r1CE9GWR-.mdAdded
- md/train/r1fYuytex/r1fYuytex.mdAdded
- md/train/rkRwGg-0Z/rkRwGg-0Z.mdAdded
- md/train/rkeMHjR9Ym/rkeMHjR9Ym.mdAdded
- md/train/rkmtTJZCb/rkmtTJZCb.mdAdded
- md/train/rylnK6VtDH/rylnK6VtDH.mdAdded
- md/train/tHgJoMfy6nI/tHgJoMfy6nI.mdAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355# TOWARDS UNDERSTANDING ENSEMBLE, KNOWLEDGE DISTILLATION AND SELF-DISTILLATION IN DEEP LEARNING
Zeyuan Allen-Zhu Meta FAIR Labs zeyuanallenzhu@meta.com
Yuanzhi Li Mohamed bin Zayed University of AI Yuanzhi.Li@mbzuai.ac.ae
# ABSTRACT
We formally study how ensemble of deep learning models can improve test accuracy, and how the superior performance of ensemble can be distilled into a single model using knowledge distillation. We consider the challenging case where the ensemble is simply an average of the outputs of a few independently trained neural networks with the same architecture, trained using the same algorithm on the same data set, and they only differ by the random seeds used in the initialization.
We show that ensemble/knowledge distillation in deep learning works very differently from traditional learning theory (such as boosting or NTKs). We develop a theory showing that when data has a structure we refer to as “multi-view”, then ensemble of independently trained neural networks can provably improve test accuracy, and such superior test accuracy can also be provably distilled into a single model. Our result sheds light on how ensemble works in deep learning in a way that is completely different from traditional theorems, and how the “dark knowledge” is hidden in the outputs of the ensemble and can be used in distillation.1
# 1 INTRODUCTION
Ensemble (Dietterich, 2000; Hansen & Salamon, 1990; Polikar, 2006) is one of the most powerful techniques in practice to improve the performance of deep learning. By simply averaging the outputs of merely a few (like 3 or 10) independently-trained neural networks of the same architecture, using the same training method over the same training data, it can significantly boost the prediction accuracy over the test set comparing to individual models. The only difference is the randomness used to initialize these networks and/or the randomness during training. Moreover, it is discovered by Hinton et al. (2015) that such superior performance of the ensemble can be transferred into a single model (of the same size as the individual models) using a technique called knowledge distillation: that is, simply train a single model to match the output of the ensemble (such as ${ \mathfrak { s o o } } \%$ cat $^ +$ $10 \%$ car”, also known as soft labels) as opposite to the true data labels, over the same training data.
On the theory side, there are lots of works studying the superior performance of ensemble from principled perspectives (see full version for citations). However, most of these works only apply to: (1). Boosting: where the coefficients associated with the combinations of the single models are actually trained, instead of simply taking average; (2). Bootstrapping/Bagging: the training data are different for each single model; (3). Ensemble of models of different types and architectures; or (4). Ensemble of random features or decision trees. To the best of our knowledge, none of these cited works apply to the particular type of ensemble that is widely used in deep learning: simply take a uniform average of the output of the learners, which are neural networks with the same architecture and are trained by stochastic gradient descent (SGD) over the same training set. In fact, very critically, for deep learning models:
• TRAINING AVERAGE DOES NOT WORK: if one directly trains to learn an average of individual neural networks initialized by different seeds, the performance is much worse than ensemble. • KNOWLEDGE DISTILLATION WORKS: the superior performance of ensemble in deep learning can be distilled into a single model (Hinton et al., 2015).
 Figure 1: Ensemble in deep learning is very different from ensemble in random feature mappings. Details in Figure 6.
• SELF-DISTILLATION WORKS: even distilling a single model into another of the same size, there is performance boost. (Furlanello et al., 2018; Mobahi et al., 2020; Zhang et al., 2019)
We are unaware of any satisfactory theoretical explanation for the phenomena above. For instance, as we shall argue, some traditional view for why ensemble works, such as ‘ensemble can enlarge the feature space in random feature mappings’, even give contradictory explanations to the above phenomena, thus cannot explain knowledge distillation or ensemble in deep learning. Motivated by this gap between theory and practice we study the following question for multi-class classification:
# Our theoretical questions:
How does ensemble improve the test-time performance in deep learning when we simply (unweightedly) average over a few independently trained neural networks? – Especially when all the neural networks have the same architecture, are trained over the same data set using the same standard training algorithm and only differ by the random seeds, and even when all single models already have $1 0 0 \%$ training accuracy? How can such superior test-time performance of ensemble be later “distilled” into a single neural network of the same architecture, simply by training the single model to match the output of the ensemble over the same training data set?
Our results. We prove for certain multi-class classification tasks with a special structure we refer to as multi-view, with a training set $\mathcal { Z }$ consisting of $N$ i.i.d. samples from some unknown distribution $\mathcal { D }$ , for certain two-layer convolutional network $f$ with (smoothed-)ReLU activation as learner:
• (Single model has bad test accuracy): there is a value $\mu > 0$ such that when a single model $f$ is trained over $\mathcal { Z }$ using the cross-entropy loss, via gradient descent (GD) starting from random Gaussian initialization, the model can reach zero training error efficiently. However, w.h.p. the prediction (classification) error of $f$ over $\mathcal { D }$ is between $0 . 4 9 \mu$ and $0 . 5 1 \mu$ .
• (Ensemble provably improves test accuracy): let $f _ { 1 } , f _ { 2 } , \cdots , f _ { L }$ be $L = \widetilde { \Omega } ( 1 )$ independently trained single models as above, then w.h.p. $\begin{array} { r } { \overline { { G } } = \frac { 1 } { L } \sum _ { \ell } f _ { \ell } } \end{array}$ has prediction error $\le 0 . 0 1 \mu$ over $\mathcal { D }$ .
• (Ensemble can be distilled into a single model): if we further train (using GD from random initialization) another single model $f _ { 0 }$ (same architecture as each $f _ { \ell } )$ to match the output of $\begin{array} { r } { G = \frac { 1 } { L } \sum _ { \ell } \bar { f } _ { \ell } } \end{array}$ merely over the same training data set $\mathcal { Z }$ , then $f _ { 0 }$ can be trained efficiently and w.h.p. $f _ { 0 }$ will have prediction error $\le 0 . 0 1 \mu$ over $\mathcal { D }$ as well.
• (Self-distillation also improves test accuracy): if we further train (using GD from random initialization) another single model $f ^ { \prime }$ (same architecture as $f _ { 1 } )$ ) to match the output of the single model $f _ { 1 }$ merely over the same training data set $\mathcal { Z }$ , then $f ^ { \prime }$ can be trained efficiently and w.h.p. has prediction error at most $\leq 0 . 2 6 \mu$ over $\mathcal { D }$ . The main idea is that self-distillation is performing “implicit ensemble $^ +$ knowledge distillation”, as we shall argue in Section 4.2.
We defer discussions of our empirical results to Section 5. However, we highlight some of the empirical findings, as they shall confirm and justify our theoretical approach studying ensemble and knowledge distillation in deep learning. Specifically, we give empirical evidences showing that:
• Knowledge distillation does not work for random feature mappings; and ensemble in deep learning is very different from ensemble in random feature mappings (see Figure 1). • Special structures in data (such as the “multi-view” structure we shall introduce) is needed for ensemble of neural networks to work. • The variance due to label noise or the non-convex landscape of training, in the independentlytrained models, may not be connected to the superior performance of ensemble in deep learning.
# 2 OUR METHODOLOGY AND INTUITION
# 2.1 A FAILURE ATTEMPT USING RANDOM FEATURE MAPPINGS
The recent advance in deep learning theory shows that under certain circumstances, neural networks can be treated as a linear function over random feature mappings — see (Allen-Zhu et al., 2019b; Arora et al., 2019b; Daniely et al., 2016; Du et al., $2 0 1 8 \mathrm { b }$ ; Jacot et al., 2018; Zou et al., 2018) and the references therein. In particular, the theory shows when $f : \mathbb { R } ^ { D + d } \mathbb { R }$ is a neural network with inputs $x \in \mathbb { R } ^ { d }$ and weights $W \in \mathbb { R } ^ { D }$ , in some cases, $f ( W , x )$ can be approximated by:
$$f ( W , x ) \approx f ( W _ { 0 } , x ) + \left. W - W _ { 0 } , \nabla _ { W } f ( W _ { 0 } , x ) \right.$$
where $W _ { 0 }$ is the random initialization of the neural network, and $\Phi _ { W _ { 0 } } ( x ) : = \nabla _ { W } f ( W _ { 0 } , x )$ is the neural tangent kernel (NTK) feature mapping. This is known as the NTK approach. If this approximation holds, then training a neural network can be approximated by learning a linear function over random features $\Phi _ { W _ { 0 } } ( x )$ , which is very theory-friendly.
Ensemble works for random features / NTK. Traditional theorems (Alhamdoosh & Wang, 2014; Brown et al., 2005a; Bryll et al., 2003; Tsymbal et al., 2005) suggest that the ensemble of independently trained random feature models can indeed significantly improve test-time performance, as it enlarges the feature space from $\Phi _ { W _ { 0 } } ( x )$ to $\{ \Phi _ { W _ { 0 } ^ { ( i ) } } ( x ) \} _ { i \in [ L ] }$ for $L$ many independently sampled W (i)0 . This can be viewed as a feature selection process (Alvarez et al., 2012; Cai et al., 2018; Oliveira et al., 2003; Opitz, 1999; Rokach, 2010), and we have confirmed it for NTK in practice, see Figure 1. However, can we understand ensemble and knowledge distillation in $D L$ as feature selections using NTK? Unfortunately, our empirical results provide many counter examples towards those arguments, see discussions below and Figure 1.
Contradiction 1: training average works even better. Although ensemble of linear functions over NTK features with different random seeds: $f _ { i } ( x ) = \langle W ^ { ( i ) } , \Phi _ { W _ { 0 } ^ { ( i ) } } ( x ) \rangle$ does improve test accuracy, however, such improvement is mainly due to the use of a larger set of random features, whose combinations contain functions that generalize better. To see this, we observe that an even superior performance (than the ensemble) can simply be obtained by directly training $F ( x ) = { \textstyle { \frac { 1 } { L } } } \left( f _ { 1 } + \dot { f } _ { 2 } + \cdot \cdot \cdot + f _ { L } \right)$ from random initialization. In contrast, recall if $f _ { i } ( x )$ ’s are multi-layer neural networks with different random seeds, then training their average barely gives any better performance comparing to individual networks $f _ { i }$ , as now all the $f _ { i }$ ’s are capable of learning the same set of features.
Contradiction 2: knowledge distillation does not work. For NTK feature mappings, we observe that the result obtained by ensemble cannot be distilled at all into individual models, indicating the features selected by ensemble is not contained in the feature $\Phi _ { W _ { 0 } ^ { ( i ) } } ( x )$ of any individual model. In contrast, in actual deep learning, ensemble does not enlarge feature space: so an individual neural network is capable of learning the features of the ensemble model.
In sum, ensemble in deep learning may be very different from ensemble in random features. It may be more accurate to study ensemble / knowledge distillation in deep learning as a feature learning process, instead of a feature selection process. But still, we point out a fundamental difficulty:
# Key challenge:
If a single deep learning model is capable of — through knowledge distillation — learning the features of the ensemble model and achieving better test accuracy comparing to training the single model directly (and the same training accuracy, typically at global optimal of $1 0 0 \%$ ), then why the single model cannot learn these features directly when we train the model to match the true data labels? What is the dark knowledge hidden in the output of ensemble (a.k.a. soft label)2 comparing to the original hard label?
# 2.2 ENSEMBLE IN DEEP LEARNING: A FEATURE LEARNING PROCESS
Before addressing the key challenge, we point out that prior works are very limited with respect to studying neural network training as a feature learning process. Most of the existing works proving that neural networks can learn features only focus on the case when the input is Gaussian or
 Figure 2: Illustration of images with multiple views (features) in the ImageNet dataset.
Gaussian-like — see for instance (Kawaguchi, 2016; Soudry & Carmon, 2016; Xie et al., 2016) and many others. However, as we demonstrate in Figure 7 in the full version,
# Ensemble in DL might not improve test accuracy when inputs are Gaussian-like:
Empirically, ensemble does not improve test accuracy in deep learning, in certain scenarios when the distribution of the input data is Gaussian or even mixture of Gaussians. This is true over various learner network structures (fully-connected, residual, convolution neural networks) and various labeling functions (when the labels are generated by linear functions, fully-connected, residual, convolutional networks, with/without label noise, with/without classification margin).
Bias variance view of ensemble: Some prior works also try to attribute the benefit of ensemble as reducing the variance of individual solutions due to label noise or non-convex landscape of the training objective. However, reducing such variance can reduce a convex test loss (typically crossentropy), but not necessarily the test classification error. Concretely, the synthetic experiments in Figure 7 show that, after applying ensemble over Gaussian-like inputs, the variance of the model outputs is reduced but the test accuracy is not improved. We give many more empirical evidences to show that the variance (either from label noise or from the non-convex landscape) is usually not the cause for why ensemble works in deep learning, see Section 5.
Hence, to understand the true benefit of ensemble in deep learning in theory, we would like to study a setting that can approximate practical deep learning, where:
• The input distribution is more structured than standard Gaussian and there is no label noise. (From above discussions, ensemble cannot work for deep learning distribution-freely). • The individual neural networks all are well-trained, in the sense that the training accuracy in the end is $1 0 0 \%$ , and there is nearly no variance in the test accuracy for individual models. (So training never fails.)
In this work, we propose to study a setting of data that we refer to as multi-view, where the above two conditions both hold when we train a two-layer neural networks with (smoothed-)ReLU activations. We also argue that the multi-view structure we consider is fairly common in the data sets used in practice, in particular for vision tasks. We give more details below.
# 2.3 OUR APPROACH: LEARNING MULTI-VIEW DATA
Let us first give a thought experiment to illustrate our approach, and we present the precise mathematical definition of the “multi-view” structure in Section 3. Consider a binary classification problem and four “features” $v _ { 1 } , v _ { 2 } , v _ { 3 } , v _ { 4 }$ . The first two features correspond to the first class label, and the next two features correspond to the second class label. In the data distribution:
• When the label is class 1, then:3
both $v _ { 1 } , v _ { 2 }$ appears with weight 1, one of $v _ { 3 } , v _ { 4 }$ appears with weight 0.1 w.p. $8 0 \%$ only $v _ { 1 }$ appears with weight 1, one of $v _ { 3 } , v _ { 4 }$ appears with weight 0.1 w.p. $1 0 \%$ only $v _ { 2 }$ appears with weight 1, one of $v _ { 3 } , v _ { 4 }$ appears with weight 0.1 w.p. $1 0 \%$
• When the label is class 2, then
both $v _ { 3 } , v _ { 4 }$ appears with weight 1, one of $v _ { 1 } , v _ { 2 }$ appears with weight 0.1 w.p. $8 0 \%$ only $v _ { 3 }$ appears with weight 1, one of $v _ { 1 } , v _ { 2 }$ appears with weight 0.1 w.p. $1 0 \%$ only $v _ { 4 }$ appears with weight 1, one of $v _ { 1 } , v _ { 2 }$ appears with weight 0.1 w.p. $1 0 \%$
 Figure 3: Visualization of the channels in layer-23 of a ResNet-34 trained on CIFAR-10.
We call the $8 0 \%$ of the data multi-view data: these are the data where multiple features exist and can be used to classify them correctly. We call the rest $2 0 \%$ of the data single-view data: some features for the correct labels are missing. 4
How individual neural networks learn. Under the multi-view data defined above, if we train a neural network using the cross-entropy loss via gradient descent (GD) from random initialization, during the training process of the individual networks, we show that:
• The network will quickly pick up one of the feature $v \in \{ v _ { 1 } , v _ { 2 } \}$ for the first label, and one of the features $v ^ { \prime } \in \bar { \{ v _ { 3 } , v _ { 4 } \} }$ for the second label. So, $9 0 \%$ of the training examples, consisting of all the multi-view data and half of the single-view data (those with feature $v$ or $v ^ { \prime }$ ), are classified correctly. Once classified correctly (with a large margin), these data begin to contribute negligible to gradient by the nature of the cross-entropy loss. • Next, the network will memorize (using e.g. the noise in the data) the remaining $1 0 \%$ of the training examples without learning any new features, due to insufficient amount of left-over samples after the first phase, thus achieving training accuracy $1 0 0 \%$ but test accuracy $9 0 \%$ .
How ensemble improves test accuracy. It is simple why ensemble works. Depending on the randomness of initialization, each individual network will pick up $v _ { 1 }$ or $v _ { 2 }$ each w.p. $5 0 \%$ . Hence, as long as we ensemble ${ \widetilde { O } } ( 1 )$ many independently trained models, w.h.p. their ensemble will pick up both features $\{ v _ { 1 } , v _ { 2 } \}$ and both features $\{ v _ { 3 } , v _ { 4 } \}$ . Thus, all the data will be classified correctly.
How knowledge distillation works. Perhaps less obvious is how knowledge distillation works. Since ensemble learns all the features $v _ { 1 } , v _ { 2 } , v _ { 3 } , v _ { 4 }$ , given a multi-view data with label 1, the ensemble will actually output $\propto ( 2 , 0 . 1 )$ , where the 2 comes from features $v _ { 1 } , v _ { 2 }$ and 0.1 comes from one of $v _ { 3 } , v _ { 4 }$ . On the other hand, an individual model learning only one of $v _ { 3 } , v _ { 4 }$ will actually output $\propto ( 2 , 0 )$ when the feature $v _ { 3 }$ or $v _ { 4 }$ in the data does not match the one learned by the model. Hence, by training the individual model to match the output of the ensemble, the individual model is forced to learn both features $v _ { 3 } , v _ { 4 }$ , even though it has already perfectly classified the training data. This is the “dark knowledge” hidden in the output of the ensemble model. (This theoretical finding is consistent with practice: Figure 8 in the full paper suggests that models trained from knowledge distillation should have learned most of the features, and further computing their ensemble does not give much performance boost.)
Significance of our technique. Our work belongs to the generic framework of feature learning in DL where one proves that certain aspects of the algorithm (e.g. the randomness) affects the order where features are learned. This is fundamentally different from convex optimization, such as kernel method, where (with $\ell _ { 2 }$ regularization) there is an unique global minimum so the choice of the random seed does not matter (thus, ensemble does not help). There are other works that consider other aspects, such as the choice of learning rate, that can affect the order where the features are learned (Li et al., 2019). Our work is fundamentally different: they only focus on the NTK setting where the features are not learned; we study a feature learning process. Recall, the NTK setting cannot be used to explain ensemble and distillation in DL. Our work extends the reach of traditional machine learning theory, where typically the “generalization” is separated from “optimization.” Such “separate” treatment might not be enough to understand how deep learning works.
 Figure 4: Illustration of a multi-view and a single-view data point; the feature vectors can also be combined with feature noise and random noise, see Def. 3.1.
# 3 PROBLEM SETUP
The “multi-view” data distribution is a straight-forward generalization of the intuitive setting in Section 2.3. For simplicity, in the main body, we use example choices of the parameters mainly a function of $k$ (such as $P = k ^ { 2 }$ , $\begin{array} { r } { \gamma = \frac { 1 } { k ^ { 1 . 5 } } } \end{array}$ , $\textstyle \mu = { \frac { k ^ { 1 . 2 } } { N } }$ , $\rho = k ^ { - 0 . 0 1 }$ , $\sigma _ { 0 } = 1 / \sqrt { k }$ as we shall see), and we consider the case when $k$ is sufficiently large. In our full version, we shall give a much larger range of parameters for the theorems to hold.
# 3.1 DATA DISTRIBUTION AND NOTATIONS
We consider learning a $k$ -class classification problem over $P$ -patch inputs, where each patch has dimension $d$ . In symbols, each labelled data is represented by $( X , y )$ where $X = ( x _ { 1 } , x _ { 2 } , \cdot \cdot \cdot , x _ { P } ) \in$ $( \mathbb { R } ^ { d } ) ^ { P }$ is the data vector and $y \in [ k ]$ is the data label. For simplicity, we focus on the case when ${ \dot { P } } = k ^ { 2 }$ , and $d = { \mathsf { p o l y } } ( k )$ for a large polynomial.
We consider the setting when $k$ is sufficiently large.5 We use “w.h.p.” to denote with probability at least $1 - e ^ { - \Omega ( \log ^ { 2 } k ) }$ , and use $\widetilde { O } , \widetilde { \Theta } , \widetilde { \Omega }$ notions to hide polylogarithmic factors in $k$ .
We first assume that each label class $j \in [ k ]$ has multiple associated features, say two features for the simplicity of math, represented by unit feature vectors $v _ { j , 1 } , v _ { j , 2 } \in \mathbb { R } ^ { d }$ . For notation simplicity, we assume that all the features are orthogonal, namely,
$$\begin{array} { r } { \forall j , j ^ { \prime } \in [ k ] , \forall \ell , \ell ^ { \prime } \in [ 2 ] , \| v _ { j , \ell } \| _ { 2 } = 1 \quad \mathrm { a n d } v _ { j , \ell } \bot v _ { j ^ { \prime } , \ell ^ { \prime } } \mathrm { w h e n } ( j , \ell ) \ne ( j ^ { \prime } , \ell ^ { \prime } ) } \end{array}$$
although our work also extends to the “incoherent” case trivially. We denote by
$$\mathcal { V } : = \{ v _ { j , 1 } , v _ { j , 2 } \} _ { j \in [ k ] }$$
We consider the following data and label distribution. Let $C _ { p }$ be a global constant, $s \in [ 1 , k ^ { 0 . 2 } ]$ be a sparsity parameter. To be concise, we define the multi-view distribution $\mathcal { D } _ { m }$ and single-view distribution $\mathcal { D } _ { s }$ together. Due to space limitation, here we hide the specification of the random “noise” and defer it to the full version.6
Definition 3.1 (data distributions $\mathcal { D } _ { m }$ and $\mathcal { D } _ { s }$ ). Given $\mathcal { D } \in \{ \mathcal { D } _ { m } , \mathcal { D } _ { s } \}$ , we define $( X , y ) \sim \mathcal { D }$ as follows. First choose the label $y \in [ k ]$ uniformly at random. Then, the data vector $X$ is generated
as follows (also illustrated in Figure 4).
1. Denote $\mathcal { V } ( X ) = \{ v _ { y , 1 } , v _ { y , 2 } \} \cup \mathcal { V } ^ { \prime }$ as the set of feature vectors used in this data vector $X$ , where $\mathcal { V } ^ { \prime }$ is a set of features uniformly sampled from $\left\{ v _ { j ^ { \prime } , 1 } , v _ { j ^ { \prime } , 2 } \right\} _ { j ^ { \prime } \in [ k ] \backslash \{ y \} }$ , each with probability $\frac { s } { k }$ .
2. For each $v \in \mathcal { V } ( X )$ , pick $C _ { p }$ many disjoint patches in $[ P ]$ and denote it as $\mathcal { P } _ { v } ( X ) \subset [ P ]$ (the distribution of these patches can be arbitrary). We denote $\mathcal { P } ( X ) = \cup _ { v \in \mathcal { V } ( X ) } \mathcal { P } _ { v } ( X )$ .
3. If $\mathcal { D } = \mathcal { D } _ { s }$ is the single-view distribution, pick a value ${ \widehat { \ell } } = { \widehat { \ell } } ( X ) \in$ [2] uniformly at random.
4. For each $v \in \mathcal { V } ( X )$ and $p \in { \mathcal { P } } _ { v } ( X )$ , we set $x _ { p } = z _ { p } v + \mathbf { \zeta } ^ { \cdot } n o i s e ^ { , \cdot } \in \mathbb { R } ^ { d }$ , where, the random coefficients $z _ { p } \geq 0$ satisfy that:
In the case of multi-view distribution $\mathcal { D } = \mathcal { D } _ { m }$ ,
$$\begin{array} { r l } & { \sum _ { p \in \mathcal { P } _ { v } ( X ) } z _ { p } \in [ 1 , O ( 1 ) ] ~ w h e n ~ v \in \{ v _ { y , 1 } , v _ { y , 2 } \} , \quad ^ { 7 } } \\ & { \sum _ { p \in \mathcal { P } _ { v } ( X ) } z _ { p } \in [ \Omega ( 1 ) , 0 . 4 ] ~ w h e n ~ v \in \mathcal { V } ( X ) \setminus \{ v _ { y , 1 } , v _ { y , 2 } \} , } \end{array}$$
In the case of single-view distribution $\mathcal { D } = \mathcal { D } _ { s }$ ,
$$\begin{array} { r l } & { \sum _ { p \in \mathcal { P } _ { v } ( X ) } z _ { p } \in [ 1 , O ( 1 ) ] ~ w h e n ~ v = v _ { y , \widehat { \ell } } , } \\ & { \sum _ { p \in \mathcal { P } _ { v } ( X ) } z _ { p } \in [ \rho , O ( \rho ) ] ~ w h e n ~ v = v _ { y , 3 - \widehat { \ell } } , } \\ & { \sum _ { p \in \mathcal { P } _ { v } ( X ) } z _ { p } \in [ \Omega ( \Gamma ) , \Gamma ] ~ w h e n ~ v \in \mathcal { V } ( X ) \setminus \{ v _ { y , 1 } , v _ { y , 2 } \} . } \end{array}$$
5. For each $p \in [ P ] \setminus { \mathcal { P } } ( X )$ , we set $x _ { p }$ to consist only of “noise”.
Remark 3.2. The distribution of how to pick ${ \mathcal { P } } ( X )$ and assign $\sum _ { p \in \mathcal { P } _ { v } ( X ) } z _ { p }$ to each patch in $p \in$ ${ \mathcal { P } } _ { v } ( X )$ can be arbitrary (and can depend on other randomness in the data as well). In particular, we have allowed different features $v _ { j , 1 } , v _ { j , 2 }$ to show up with different weights in the data (for example, for multi-view data, some view $v _ { y , 1 }$ can consistently have larger $z _ { p }$ comparing to $v _ { y , 2 }$ ). Yet, we shall prove that the order to learn these features by the learner network can still be flipped depending on the randomness of network initialization.
Interpretation of our data distribution. As we argue more in the full paper, our setting can be tied to a down-sized version of convolutional networks applied to image classification data. With a small kernel size, good features in an image typically appear only at a few patches, and most other patches are random noise or low-magnitude feature noises. More importantly, our noise parameters shall ensure that, the concept class is not learnable by linear classifiers or constant degree polynomials. We believe a (convolutional) neural network with ReLU-like activation is somewhat necessary.
Our final data distribution $\mathcal { D }$ , and the training data set $\mathcal { Z }$ are formally given as follows.
Definition 3.3 ( $\mathcal { D }$ and $\mathcal { Z }$ ). The distribution $\mathcal { D }$ consists of data from $\mathcal { D } _ { m }$ w.p. $1 - \mu$ and from $\mathcal { D } _ { s }$ w.p. $\mu$ . We are given $N$ training samples from $\mathcal { D }$ , and denote the training data set as $\mathcal { Z } = \mathcal { Z } _ { m } \cup \mathcal { Z } _ { s }$ where ${ \mathcal { Z } } _ { m }$ and $\mathcal { Z } _ { s }$ respectively represent multi-view and single-view training data. We write $( X , y ) \sim { \mathcal { Z } }$ as $( X , y )$ sampled uniformly at random from the empirical data set, and denote $N _ { s } = | \mathcal { Z } _ { s } |$ . $W e$ again for simplicity focus on the setting when $\begin{array} { r } { \mu = \frac { \bar { 1 } } { \mathsf { p o l y } ( k ) } } \end{array}$ and we are given samples $N = { \dot { k } } ^ { 1 . 2 } / \mu .$ so each label i appears at least $\widetilde \Omega ( 1 )$ in $\mathcal { Z } _ { s }$ . Our result trivially applies to many other choices of $N$ .
# 3.2 LEARNER NETWORK
We consider a learner network using the following smoothed ReLU activation function $\widetilde { \sf R e L U }$ :
Definition 3.4. For integer $q \geq 2$ and threshold $\varrho = \frac { 1 } { \mathsf { p o l y l o g } ( k ) }$ , the smoothed function $\widetilde { \mathsf { R e L U } } ( z ) : = 0$ for $z \le 0$ ; $\begin{array} { r } { \widetilde { \mathsf { R e L U } } ( z ) : = \frac { z ^ { q } } { q \varrho ^ { q - 1 } } } \end{array}$ for $z \in [ 0 , \varrho ]$ ; and $\begin{array} { r } { \widetilde { \mathsf { R e L U } } ( z ) : = z - ( 1 - \frac { 1 } { q } ) \varrho } \end{array}$ for $z \geq \varrho$ .
Since $\widetilde { \sf R e L U }$ is smooth we denote its gradient as $\widetilde { \mathsf { R e L U } } ^ { \prime } ( z )$ . We focus on $q = 4$ while our result applies to other constants $q \geq 3$ (see full version) or most other forms of smoothing.
The learner network $F ( X ) _ { \cdot } = ( F _ { 1 } ( X ) , \dots , F _ { k } ( X ) ) \in \mathbb { R } ^ { k }$ is a two-layer convolutional network parameterized by $w _ { i , r } \in \mathbb { R } ^ { d }$ for $i \in [ k ] , r \in [ m ]$ , satisfying
$$\begin{array} { r l } { \forall i \in [ k ] \colon } & { { } F _ { i } ( X ) = \sum _ { r \in [ m ] } \sum _ { p \in [ P ] } \widetilde { \mathsf { R e L U } } ( \langle w _ { i , r } , x _ { p } \rangle ) } \end{array}$$
Although there exists network with $m = 2$ that can classify the data correctly (e.g. $w _ { i , r } = v _ { i , r }$ for $r \in [ 2 ] )$ ), in this paper, for efficient optimization purpose it is convenient to work on a moderate level of over-parameterization: $m \in [ { \mathsf { p o l y l o g } } ( k ) , k ]$ . Our lower bounds hold for any $m$ in this range and upper bounds hold even for small over-parameterization $m = { \mathsf { p o l y l o g } } ( k )$ .
Training a single model. We learn the concept class (namely, the labeled data distribution) using gradient descent with learning rate $\eta > 0$ , over the cross-entropy loss function $L$ using $N$ training data points $\mathcal { Z } = \{ ( X _ { i } , y _ { i } ) \} _ { i \in [ N ] }$ . We denote the empirical loss as:
$$\begin{array} { r } { L ( F ) = \frac { 1 } { N } \sum _ { i \in [ N ] } L ( F ; X _ { i } , y _ { i } ) = \mathbb { E } _ { ( X , y ) \sim \mathcal { Z } } [ L ( F ; X , y ) ] } \end{array}$$
where $\begin{array} { r } { L ( F ; X , y ) = - \log { \frac { e ^ { F _ { y } ( X ) } } { \sum _ { j \in [ k ] } e ^ { F _ { j } ( X ) } } } } \end{array}$ g eFy(X)Pj∈[k] eFj (X) . We randomly initialize the network F by letting each $w _ { i , r } ^ { ( 0 ) } \sim \mathcal { N } ( 0 , \sigma _ { 0 } ^ { 2 } I )$ for $\sigma _ { 0 } ^ { 2 } = 1 / k$ , which is the most standard initialization people use in practice.
To train a single model, at each iteration $t$ we update using gradient descent (GD):9
$$w _ { i , r } ^ { ( t + 1 ) } \gets w _ { i , r } ^ { ( t ) } - \eta \mathbb { E } _ { ( X , y ) \sim \mathcal { Z } } \nabla _ { w _ { i , r } } L ( F ^ { ( t ) } ; X , y )$$
We run the algorithm for $T = { \mathsf { p o l y } } ( k ) / \eta$ iterations. We use $F ^ { ( t ) }$ to denote the model $F$ with hidden weights $\{ w _ { i , r } ^ { ( t ) } \}$ at iteration $t$ .
Notations. We denote by $\begin{array} { r } { \mathbf { l o g i t } _ { i } ( F , X ) : = \frac { e ^ { F _ { i } ( X ) } } { \sum _ { j \in [ k ] } e ^ { F _ { j } ( X ) } } , } \end{array}$ = eFi(X)Pj∈[k] eFj (X) . Using this, we can write down
$$\forall i \in [ k ] , r \in [ m ] \colon \quad - \nabla _ { w _ { i , r } } L ( F ; X , y ) = ( \mathbb { 1 } _ { i \neq y } - \log \operatorname { i } \mathbf { t } _ { i } ( F , X ) ) \nabla _ { w _ { i , r } } F _ { i } ( X ) ~ .$$
# 4 MAIN THEOREMS AND EXPLANATIONS
We now state the main theorems (and the one for self-distillation is in the full paper).10
Theorem 1 (single model). For every sufficiently large $k > 0$ , every $m \in [ { \mathsf { p o l y l o g } } ( k ) , k ] ,$ , every $\eta \leq$ 1poly(k) , suppose we train a single model using the gradient descent update (3.1) starting from the random initialization defined in Section 3.2, then after T = poly(k) many iterations, with probability $\geq 1 - e ^ { - \Omega ( \log ^ { 2 } k ) }$ , the model $F ^ { ( T ) }$ satisfies:
• (training is perfect): meaning for all $( X , y ) \in { \mathcal { Z } }$ , all $i \in [ k ] \setminus \{ y \}$ : ${ \cal F } _ { y } ^ { ( T ) } ( X ) > { \cal F } _ { i } ^ { ( T ) } ( X ) .$
• (test accuracy is consistently bad): meaning that:
$${ \bf P r } _ { ( X , y ) \sim \mathcal { D } } [ \exists i \in [ k ] \setminus \{ y \} : F _ { y } ^ { ( T ) } ( X ) < F _ { i } ^ { ( T ) } ( X ) ] \in [ 0 . 4 9 \mu , 0 . 5 1 \mu ] \ .$$
We shall give technical intuitions about why Theorem 1 holds in the full version. But, at a high-level, we shall construct a “lottery winning” set $\mathcal { M } \subseteq [ k ] \times [ 2 ]$ of cardinality $| \mathcal { M } | \in [ k ( 1 - o ( 1 ) ) , k ]$ . It only depends on the random initialization of $F$ . Then, with some effort we can prove that, for every $( i , \ell ) \in \mathcal { M }$ , at the end of the training $F ^ { ( T ) }$ will learn feature $v _ { i , \ell }$ but not learn feature $v _ { i , 3 - \ell }$ . This means for those single-view data $( X , y )$ with $y = i$ and ${ \widehat { \ell } } ( X ) = 3 - \ell$ , the final network $F ^ { ( T ) }$ will predict its label wrong. This is why the final test accuracy is around $0 . 5 \mu$ .
Note the property that test accuracy consistently belongs to the range $[ 0 . 4 9 \mu , 0 . 5 1 \mu ]$ should be reminiscent of message $\textcircled{5}$ in Figure 6, where multiple single models, although starting from different random initialization, in practice does have a relatively small variance in test accuracies.
Ensemble. Suppose $\{ F ^ { [ \ell ] } \} _ { \ell \in [ K ] }$ are $K = \widetilde \Omega ( 1 )$ independently trained models of $F$ with $m =$ polylog $( k )$ for $\begin{array} { r } { T = O \big ( \frac { \mathsf { p o l y } ( k ) } { \eta } \big ) } \end{array}$ iterations (i.e., the same setting as Theorem 1 except we only need a small over-parameterization $m = { \mathsf { p o l y l o g } } ( k ) .$ ). Let us define their ensemble
$$\begin{array} { r } { G ( X ) = \frac { \widetilde { \Theta } ( 1 ) } { K } \sum _ { \ell } F ^ { [ \ell ] } ( X ) } \end{array}$$
Theorem 2 (ensemble). In the same setting as Theorem $I$ except now we only need a small $m =$ polylog $( k )$ , we have for the ensemble model $G$ in (4.1), with probability at least $1 - e ^ { - \Omega ( \log ^ { 2 } k ) }$ :
• (training is perfect): meaning for all $( X , y ) \in { \mathcal { Z } }$ , for all $i \in [ k ] \setminus \{ y \}$ : $G _ { y } ( X ) > G _ { i } ( X )$ .
• (test accuracy is almost perfect): meaning that:
$${ \bf P r } _ { ( X , y ) \sim { \mathcal D } } [ \exists i \in [ k ] \setminus \{ y \} : G _ { y } ( X ) < G _ { i } ( X ) ] \le 0 . 0 0 1 \mu ~ .$$
As we discussed in Section 2.3, the reason Theorem 2 holds attributes to the fact that those lottery winning sets $\mathcal { M }$ depend on the random initialization of the networks; and therefore, when multiple models are put together, their “union” of $\mathcal { M }$ shall cover all possible features $\{ v _ { i , \ell } \} _ { ( i , \ell ) \in [ k ] \times [ 2 ] }$ . Moreover, our theorem only requires individual $K = \widetilde \Omega ( 1 )$ models for ensemble, which is indeed “averaging the output of a few independently trained models”.
# 4.1 KNOWLEDGE DISTILLATION FOR ENSEMBLE
We consider a knowledge distillation algorithm given the existing ensemble model $G$ (see (4.1)) as follows. For every label $i \in [ k ]$ , let us define the truncated scaled logit as (for $\begin{array} { r } { \tau = \frac { 1 } { \log ^ { 2 } k } ) } \end{array}$
$$\begin{array} { r } { \mathbf { l o g i t } _ { i } ^ { \tau } ( F , X ) = \frac { e ^ { \operatorname* { m i n } \{ \tau ^ { 2 } F _ { i } ( X ) , 1 \} / \tau } } { \sum _ { j \in [ k ] } e ^ { \operatorname* { m i n } \{ \tau ^ { 2 } F _ { j } ( X ) , 1 \} / \tau } } } \end{array}$$
(This should be reminiscent of the logit function with temperature used by the original knowledge distillation work (Hinton et al., 2015); we use truncation instead which is easier to analyze.)
Now, we train a new network $F$ from random initialization (where the randomness is independent of all of those used in $F ^ { [ \ell ] }$ ). At every iteration $t$ , we update each weight $w _ { i , r }$ by:
$$\begin{array} { r } { v _ { i , r } ^ { ( t + 1 ) } = w _ { i , r } ^ { ( t ) } - \eta \nabla _ { w _ { i , r } } L ( F ^ { ( t ) } ) - \eta ^ { \prime } \mathbb { E } _ { ( X , y ) \sim \mathcal { Z } } \left[ \left( \mathbf { l o g } \mathbf { i t } _ { i } ^ { \tau } ( F ^ { ( t ) } , X ) - \mathbf { l o g } \mathbf { i t } _ { i } ^ { \tau } ( G , X ) \right) ^ { - } \nabla _ { w _ { i , r } } F _ { i } ^ { ( t ) } ( X - Y ) \right] , } \end{array}$$
Notation. Throughout the paper we denote by $[ a ] ^ { + } = \operatorname* { m a x } \{ 0 , a \}$ and $[ a ] ^ { - } = \operatorname* { m i n } \{ 0 , a \}$ .
This knowledge distillation method (4.3) is almost identical to the one used in the original work (Hinton et al., 2015), except we use a truncation during the training to make it more (theoretically) stable. Moreover, we update the distillation objective using a larger learning rate $\eta ^ { \prime }$ comparing to $\eta$ of the cross-entropy objective. This is also consistent with the training schedule used in (Hinton et al., 2015).
Let $F ^ { ( t ) }$ be the resulting network obtained by (4.3) at iteration $t$ . We have the following theorem:
Theorem 3 (ensemble distillation). Consider the distillation algorithm (4.3) in which $G$ is the ensemble model defined in (4.1). For every k > 0, for m = polylog(k), for every η ≤ 1poly(k) , setting η′ = ηpoly(k), after T = poly(k) many iterations with probability at least $1 - e ^ { - \Omega ( \log ^ { 2 } k ) }$ , for at least $90 \%$ of the iterations $t \leq \dot { T }$ :
• (test accuracy is almost perfect): meaning that:
$$\operatorname { \bf P r } _ { ( X , y ) \sim \mathcal { D } } [ \exists i \in [ k ] \setminus \{ y \} : F _ { y } ^ { ( t ) } ( X ) < F _ { i } ^ { ( t ) } ( X ) ] \le 0 . 0 0 1 \mu .$$
Remark. Theorem 3 necessarily means that the distilled model $F$ has learned all the features $\underline { { \{ v _ { i , \ell } \} } } _ { ( i , \ell ) \in \lbrack k \rbrack \times \lbrack 2 \rbrack }$ from the ensemble model $G$ . This is consistent with our empirical findings in Figure 8: if one trains multiple individual models using knowledge distillation with different random seeds, then their ensemble gives no further performance boost.
REFERENCES Monther Alhamdoosh and Dianhui Wang. Fast decorrelated neural network ensembles with random weights. Information Sciences, 264:104–117, 2014. Zeyuan Allen-Zhu and Yuanzhi Li. What Can ResNet Learn Efficiently, Going Beyond Kernels? In NeurIPS, 2019a. Full version available at http://arxiv.org/abs/1905.10337. Zeyuan Allen-Zhu and Yuanzhi Li. Can SGD Learn Recurrent Neural Networks with Provable Generalization? In NeurIPS, 2019b. Full version available at http://arxiv.org/abs/ 1902.01028. Zeyuan Allen-Zhu and Yuanzhi Li. Backward feature correction: How deep learning performs deep learning. arXiv preprint arXiv:2001.04413, 2020. Zeyuan Allen-Zhu, Yuanzhi Li, and Zhao Song. On the convergence rate of training recurrent neural networks. In NeurIPS, 2019a. Full version available at http://arxiv.org/abs/1810. 12065. Zeyuan Allen-Zhu, Yuanzhi Li, and Zhao Song. A convergence theory for deep learning via overparameterization. In ICML, 2019b. Full version available at http://arxiv.org/abs/ 1811.03962. Jose M Alvarez, Yann LeCun, Theo Gevers, and Antonio M Lopez. Semantic road segmentation via multi-scale ensembles of learned features. In European Conference on Computer Vision, pp. 586–595. Springer, 2012. Sanjeev Arora, Simon S Du, Wei Hu, Zhiyuan Li, Ruslan Salakhutdinov, and Ruosong Wang. On exact computation with an infinitely wide neural net. arXiv preprint arXiv:1904.11955, 2019a. Sanjeev Arora, Simon S. Du, Wei Hu, Zhiyuan Li, and Ruosong Wang. Fine-grained analysis of optimization and generalization for overparameterized two-layer neural networks. CoRR, abs/1901.08584, 2019b. URL http://arxiv.org/abs/1901.08584. Veronica Bol ´ on-Canedo and Amparo Alonso-Betanzos. Ensembles for feature selection: A review ´ and future trends. Information Fusion, 52:1–12, 2019. Leo Breiman. Bagging predictors. Machine learning, 24(2):123–140, 1996. Gavin Brown, Jeremy Wyatt, Rachel Harris, and Xin Yao. Diversity creation methods: a survey and categorisation. Information Fusion, 6(1):5–20, 2005a. Gavin Brown, Jeremy L Wyatt, and Peter Tino. Managing diversity in regression ensembles. ˇ Journal of machine learning research, 6(Sep):1621–1650, 2005b. Robert Bryll, Ricardo Gutierrez-Osuna, and Francis Quek. Attribute bagging: improving accuracy of classifier ensembles by using random feature subsets. Pattern recognition, 36(6):1291–1302, 2003. Jie Cai, Jiawei Luo, Shulin Wang, and Sheng Yang. Feature selection in machine learning: A new perspective. Neurocomputing, 300:70–79, 2018. Yuan Cao and Quanquan Gu. Generalization bounds of stochastic gradient descent for wide and deep neural networks. In Advances in Neural Information Processing Systems, pp. 10835–10845, 2019. Victor Chernozhukov, Denis Chetverikov, and Kengo Kato. Comparison and anti-concentration bounds for maxima of gaussian random vectors. Probability Theory and Related Fields, 162(1): 47–70, 2015. Amit Daniely. Sgd learns the conjugate kernel class of the network. In Advances in Neural Information Processing Systems, pp. 2422–2430, 2017. Amit Daniely, Roy Frostig, and Yoram Singer. Toward deeper understanding of neural networks: The power of initialization and a dual view on expressivity. In Advances in Neural Information Processing Systems (NIPS), pp. 2253–2261, 2016. Thomas G Dietterich. Ensemble methods in machine learning. In International workshop on multiple classifier systems, pp. 1–15. Springer, 2000. Simon S Du, Jason D Lee, Haochuan Li, Liwei Wang, and Xiyu Zhai. Gradient descent finds global minima of deep neural networks. arXiv preprint arXiv:1811.03804, November 2018a. Simon S Du, Xiyu Zhai, Barnabas Poczos, and Aarti Singh. Gradient descent provably optimizes over-parameterized neural networks. arXiv preprint arXiv:1810.02054, 2018b. David A Freedman et al. Bootstrapping regression models. The Annals of Statistics, 9(6):1218– 1228, 1981. Yoav Freund and Robert E Schapire. A decision-theoretic generalization of on-line learning and an application to boosting. Journal of computer and system sciences, 55(1):119–139, 1997. Yoav Freund, Robert Schapire, and Naoki Abe. A short introduction to boosting. Journal-Japanese Society For Artificial Intelligence, 14(771-780):1612, 1999. Jerome Friedman, Trevor Hastie, Robert Tibshirani, et al. Additive logistic regression: a statistical view of boosting (with discussion and a rejoinder by the authors). The annals of statistics, 28(2): 337–407, 2000. Jerome H Friedman. Greedy function approximation: a gradient boosting machine. Annals of statistics, pp. 1189–1232, 2001. Tommaso Furlanello, Zachary C Lipton, Michael Tschannen, Laurent Itti, and Anima Anandkumar. Born again neural networks. arXiv preprint arXiv:1805.04770, 2018. Mikel Galar, Alberto Fernandez, Edurne Barrenechea, Humberto Bustince, and Francisco Herrera. A review on ensembles for the class imbalance problem: bagging-, boosting-, and hybrid-based approaches. IEEE Transactions on Systems, Man, and Cybernetics, Part C (Applications and Reviews), 42(4):463–484, 2011. Behrooz Ghorbani, Song Mei, Theodor Misiakiewicz, and Andrea Montanari. Linearized two-layers neural networks in high dimension. arXiv preprint arXiv:1904.12191, 2019. Boris Hanin and Mihai Nica. Finite depth and width corrections to the neural tangent kernel. arXiv preprint arXiv:1909.05989, 2019. Lars Kai Hansen and Peter Salamon. Neural network ensembles. IEEE transactions on pattern analysis and machine intelligence, 12(10):993–1001, 1990. Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv preprint arXiv:1503.02531, 2015. Tin Kam Ho. The random subspace method for constructing decision forests. IEEE transactions on pattern analysis and machine intelligence, 20(8):832–844, 1998. Arthur Jacot, Franck Gabriel, and Clement Hongler. Neural tangent kernel: Convergence and gen- ´ eralization in neural networks. In Advances in neural information processing systems, pp. 8571– 8580, 2018. Kenji Kawaguchi. Deep learning without poor local minima. In Advances in Neural Information Processing Systems, pp. 586–594, 2016. Josef Kittler, Mohamad Hatef, Robert PW Duin, and Jiri Matas. On combining classifiers. IEEE transactions on pattern analysis and machine intelligence, 20(3):226–239, 1998. Ron Kohavi, George H John, et al. Wrappers for feature subset selection. Artificial intelligence, 97 (1-2):273–324, 1997. J Zico Kolter and Marcus A Maloof. Dynamic weighted majority: An ensemble method for drifting concepts. Journal of Machine Learning Research, 8(Dec):2755–2790, 2007. Alex Krizhevsky. Learning multiple layers of features from tiny images. 2009. Ludmila I Kuncheva. Combining pattern classifiers: methods and algorithms. John Wiley & Sons, 2014. Yuanzhi Li and Yingyu Liang. Learning overparameterized neural networks via stochastic gradient descent on structured data. In Advances in Neural Information Processing Systems, 2018. Yuanzhi Li, Colin Wei, and Tengyu Ma. Towards explaining the regularization effect of initial large learning rate in training neural networks. arXiv preprint arXiv:1907.04595, 2019. Pankaj Mehta, Marin Bukov, Ching-Hao Wang, Alexandre GR Day, Clint Richardson, Charles K Fisher, and David J Schwab. A high-bias, low-variance introduction to machine learning for physicists. Physics reports, 810:1–124, 2019. Hossein Mobahi, Mehrdad Farajtabar, and Peter L Bartlett. Self-distillation amplifies regularization in hilbert space. arXiv preprint arXiv:2002.05715, 2020. M Arthur Munson and Rich Caruana. On feature selection, bias-variance, and bagging. In Joint European Conference on Machine Learning and Knowledge Discovery in Databases, pp. 144– 159. Springer, 2009. Chris Olah, Alexander Mordvintsev, and Ludwig Schubert. Feature visualization. Distill, 2(11):e7, 2017. doi: 10.23915/distill.00007. https://distill.pub/2017/feature-visualization. Luiz S Oliveira, Robert Sabourin, Flavio Bortolozzi, and Ching Y Suen. Feature selection for ´ ensembles: A hierarchical multi-objective genetic algorithm approach. In Seventh International Conference on Document Analysis and Recognition, 2003. Proceedings., pp. 676–680. Citeseer, 2003. David W Opitz. Feature selection for ensembles. In AAAI, pp. 379–384, 1999. Robi Polikar. Ensemble based systems in decision making. IEEE Circuits and systems magazine, 6 (3):21–45, 2006. Juan Jose Rodriguez, Ludmila I Kuncheva, and Carlos J Alonso. Rotation forest: A new classifier ´ ensemble method. IEEE transactions on pattern analysis and machine intelligence, 28(10):1619– 1630, 2006. Lior Rokach. Pattern classification using ensemble methods, volume 75. World Scientific, 2010. Lior Rokach and Oded Z Maimon. Data mining with decision trees: theory and applications, volume 69. World scientific, 2008. Robert E Schapire, Yoav Freund, Peter Bartlett, Wee Sun Lee, et al. Boosting the margin: A new explanation for the effectiveness of voting methods. The annals of statistics, 26(5):1651–1686, 1998. Vaishaal Shankar, Alex Fang, Wenshuo Guo, Sara Fridovich-Keil, Ludwig Schmidt, Jonathan Ragan-Kelley, and Benjamin Recht. Neural kernels without tangents. arXiv preprint arXiv:2003.02237, 2020. Daniel Soudry and Yair Carmon. No bad local minima: Data independent training error guarantees for multilayer neural networks. arXiv preprint arXiv:1605.08361, 2016. Alexey Tsymbal, Mykola Pechenizkiy, and Padraig Cunningham. Diversity in search strategies for ´ ensemble feature selection. Information fusion, 6(1):83–98, 2005. Giorgio Valentini. An experimental bias-variance analysis of svm ensembles based on resampling techniques. IEEE Transactions on Systems, Man, and Cybernetics, Part B (Cybernetics), 35(6): 1252–1271, 2005. Giorgio Valentini and Thomas G Dietterich. Bias-variance analysis of support vector machines for the development of svm-based ensemble methods. Journal of Machine Learning Research, 5(Jul): 725–775, 2004. Bo Xie, Yingyu Liang, and Le Song. Diversity leads to generalization in neural networks. arXiv preprint Arxiv:1611.03131, 2016. Greg Yang. Scaling limits of wide neural networks with weight sharing: Gaussian process behavior, gradient independence, and neural tangent kernel derivation. arXiv preprint arXiv:1902.04760, 2019. Sergey Zagoruyko and Nikos Komodakis. Wide residual networks. arXiv preprint arXiv:1605.07146, 2016. Linfeng Zhang, Jiebo Song, Anni Gao, Jingwei Chen, Chenglong Bao, and Kaisheng Ma. Be your own teacher: Improve the performance of convolutional neural networks via self distillation. In ICCV, pp. 3713–3722, 2019. Difan Zou, Yuan Cao, Dongruo Zhou, and Quanquan Gu. Stochastic gradient descent optimizes over-parameterized deep relu networks. arXiv preprint arXiv:1811.08888, 2018.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335# Mildly Conservative $Q$ -Learning for Offline Reinforcement Learning
Jiafei Lyu1∗, Xiaoteng $\mathbf { M } \mathbf { a } ^ { 2 * }$ , Xiu Li1†, Zongqing $\mathbf { L u ^ { 3 \dag } }$ 1Tsinghua Shenzhen International Graduate School, Tsinghua University 2Department of Automation, Tsinghua Unversity 3School of Computer Science, Peking University {lvjf20,ma-xt17}@mails.tsinghua.edu.cn, li.xiu@sz.tsinghua.edu.cn, zongqing.lu@pku.edu.cn
# Abstract
Offline reinforcement learning (RL) defines the task of learning from a static logged dataset without continually interacting with the environment. The distribution shift between the learned policy and the behavior policy makes it necessary for the value function to stay conservative such that out-of-distribution (OOD) actions will not be severely overestimated. However, existing approaches, penalizing the unseen actions or regularizing with the behavior policy, are too pessimistic, which suppresses the generalization of the value function and hinders the performance improvement. This paper explores mild but enough conservatism for offline learning while not harming generalization. We propose Mildly Conservative $Q$ -learning (MCQ), where OOD actions are actively trained by assigning them proper pseudo $Q$ values. We theoretically show that MCQ induces a policy that behaves at least as well as the behavior policy and no erroneous overestimation will occur for OOD actions. Experimental results on the D4RL benchmarks demonstrate that MCQ achieves remarkable performance compared with prior work. Furthermore, MCQ shows superior generalization ability when transferring from offline to online, and significantly outperforms baselines. Our code is publicly available at https://github.com/dmksjfl/MCQ.
# 1 Introduction
Continually interacting with the environment of online reinforcement learning (RL) is often infeasible and unrealistic, since the data collection process of the agent may be expensive, difficult, or even dangerous, especially in real-world applications. Offline RL, instead, aims at learning from a static dataset that was previously collected by some unknown process [36], hence eliminating the need for environmental interactions during training.
The main challenge of offline RL is the distribution shift of state-action visitation frequency between the learned policy and the behavior policy. The evaluation of out-of-distribution (OOD) actions causes extrapolation error [14], which can be exacerbated through bootstrapping [34] and result in severe overestimation errors. Thus, keeping conservatism in value estimation is necessary in offline RL [24, 50, 60]. Previous methods achieve the conservatism by compelling the learned policy to be close to the behavior policy [14, 58, 34, 13, 57], by penalizing the learned value functions from being over-optimistic upon out-of-distribution (OOD) actions [35, 33, 59], or by learning without querying OOD samples [56, 8, 62, 32, 40].
 Figure 1: Comparison of prior methods against mild conservatism. The red spots represent the dataset samples. The left figure shows that penalizing OOD actions makes the value function drop sharply at the boundary of the dataset’s support, which barriers policy learning. The central figure depicts that policy regularization keeps the policy near behavior policy, leading to undesired performance if the behavior policy is unsatisfying. On the right side, we illustrate the basic idea of mild conservatism. The estimated values for OOD actions are allowed to be high as long as it does not affect the learning for the optimal policy supported by the dataset, i.e., $Q ( s , \bar { a } ^ { \mathrm { o o d } } ) < \bar { \operatorname * { m a x } } _ { a \in \mathrm { S u p p o r t } ( \mu ) } Q ( s , a ) .$
In practice, we rely on neural networks to extract knowledge from the dataset and generalize it to the nearby unseen states and actions when facing continuous state and action spaces. In other words, we need the networks to “stitch” the suboptimal trajectories to generate the best possible trajectory supported by the dataset. Unfortunately, there is no free lunch. Conservatism, which offline RL celebrates, often limits the generalization and impedes the performance of the agent. Existing approaches are still inadequate in balancing conservatism and generalization. As illustrated in Figure 1, policy regularization is unreliable for offline RL when the data-collecting policy is poor, and value penalization methods often induce unnecessary pessimism in both the in-dataset region and OOD region. We argue that the proper conservatism should be as mild as possible. As depicted in Figure 1, we aim at well estimating the value function in the support of the dataset, and allowing value estimates upon OOD actions to be high (even higher than their optimal values) as long as $Q ( s , a ^ { \mathrm { o o d } } ) < \operatorname* { m a x } _ { a \in \mathrm { S u p p o r t } ( \mu ) } Q ( s , a )$ is satisfied. The mild conservatism benefits generalization since value estimates upon OOD actions are slightly optimistic instead of being overly conservative.
To fulfill that, we propose a novel Mildly Conservative Bellman (MCB) operator for offline RL, where we actively train OOD actions and query their $Q$ values. We theoretically analyze the convergence property of the MCB operator under the tabular MDP setting. We show that the policy induced by the MCB operator is guaranteed to behave better than the behavior policy, and can consistently improve the policy with a tighter lower bound compared with policy constraint methods or value penalization methods like CQL [35]. For practical usage, we propose the practical MCB operator and illustrate its advantages by theoretically showing that erroneous overestimation error will not occur with it. We then estimate the behavior policy with a conditional variational autoencoder (CVAE) [29, 51], and integrate the practical MCB operator with the Soft Actor-Critic (SAC) [20] algorithm. To this end, we propose our novel offline RL algorithm, Mildly Conservative $Q$ -learning (MCQ).
Experimental results on the D4RL MuJoCo locomotion tasks demonstrate that MCQ surpasses recent strong baseline methods on most of the tasks, especially on non-expert datasets. Meanwhile, MCQ shows superior generalization capability when transferring from offline to online, validating our claims that mild pessimism is of importance to offline learning.
# 2 Preliminaries
We consider a Markov Decision Process (MDP) specified by a tuple $\langle S , \mathcal { A } , r , \rho _ { 0 } , p , \gamma \rangle$ , where $s$ is the state space, $\mathcal { A }$ is the action space, $r ( s , a ) : S \times \mathcal { A } \mapsto \mathbb { R }$ is the reward function, $\rho _ { 0 } ( s )$ is the initial state distribution, $p ( s ^ { \prime } | s , a ) : \bar { \mathcal { S } } \check { \times } \bar { \mathcal { A } } \times \bar { \mathcal { S } } \mapsto [ 0 , 1 ]$ is the transition probability, $\gamma \in [ 0 , 1 )$ is the discount factor. Reinforcement learning (RL) aims at finding a policy $\pi ( \cdot | s )$ such that the expected cumulative long-term rewards $J ( \pi ) = \mathbb { E } _ { s _ { 0 } \sim \rho _ { 0 } ( \cdot ) , a _ { t } \sim \pi ( \cdot \vert s _ { t } ) , s _ { t + 1 } \sim p ( \cdot \vert s _ { t } , a _ { t } ) } [ \sum _ { t = 0 } ^ { \infty } \gamma ^ { t } r ( s _ { t } , a _ { t } ) ]$ are maximized. The state-action function $Q ( s , a )$ measures the discounted return starting from state $s$ and action $a$ , and following the policy $\pi$ . We assume that the reward function $r ( s , a )$ is bounded, i.e., $| r ( s , a ) | \leq r _ { \operatorname* { m a x } }$ . Given a policy $\pi ( \cdot | s )$ , the Bellman backup for obtaining the corresponding $Q$ function gives:
$$\begin{array} { r } { \mathcal T ^ { \pi } Q ( s , a ) : = r ( s , a ) + \gamma \mathbb E _ { s ^ { \prime } } \mathbb E _ { a ^ { \prime } \sim \pi ( \cdot \vert s ^ { \prime } ) } [ Q ( s ^ { \prime } , a ^ { \prime } ) ] . } \end{array}$$
The $Q$ function of the optimal policy satisfies the following Bellman optimal operator:
$$\mathcal { T } Q ( s , a ) : = r ( s , a ) + \gamma \mathbb { E } _ { s ^ { \prime } } \left[ \operatorname* { m a x } _ { a ^ { \prime } \in \mathcal { A } } Q ( s ^ { \prime } , a ^ { \prime } ) \right] .$$
In offline RL setting, the online interaction is infeasible, and we can only have access to previously collected datasets $\bar { \mathcal { D } } = \{ ( s _ { i } , a _ { i } , r _ { i } , s _ { i + 1 } ^ { \prime } , d _ { i } ) \} _ { i = 1 } ^ { N }$ , where $d$ is the done flag. We denote the behavior policy as $\mu ( \cdot | s )$ . The Bellman backup relies on actions sampled from the learned policy, $a ^ { \prime } \sim \pi ( \cdot | s ^ { \prime } )$ . However, $a ^ { \prime }$ can lie outside of the support of $\mu$ due to the distribution shift between $\pi$ and $\mu$ . The value estimates upon $a ^ { \prime }$ can then be arbitrarily wrong, resulting in bad policy training. Unlike prior work, we actively train OOD actions by constructing them pseudo target values. In this way, we retain pessimism while enjoying better generalization.
# 3 Mildly Conservative $Q$ -Learning
In this section, we first formally define the MCB operator and characterize its dynamic programming properties in the tabular MDP setting. We further give a practical version of the MCB operator. We show that no erroneous overestimation will occur with the MCB operator. Finally, we incorporate the MCB operator with SAC [20] and present our novel offline RL algorithm.
# 3.1 Mildly Conservative Bellman (MCB) Operator
Definition 1. The Mildly Conservative Bellman (MCB) operator is defined as
$$\begin{array} { r } { \mathcal { T } _ { \mathrm { M C B } } Q ( s , a ) = ( \mathcal { T } _ { 1 } \mathcal { T } _ { 2 } ) Q ( s , a ) , } \end{array}$$
where
$$\begin{array} { r l } & { { \mathcal T } _ { 1 } Q ( s , a ) = \left\{ \begin{array} { l l } { Q ( s , a ) , } & { \mu ( a | s ) > 0 . } \\ { \operatorname* { m a x } _ { a ^ { \prime } \sim \mathrm { S u p p o r t } ( \mu ( \cdot | s ) ) } Q ( s , a ^ { \prime } ) - \delta , } & { e l s e . } \end{array} \right. } \\ & { { \mathcal T } _ { 2 } Q ( s , a ) = \left\{ \begin{array} { l l } { r ( s , a ) + \gamma \mathbb { E } _ { s ^ { \prime } } \left[ \operatorname* { m a x } _ { a ^ { \prime } \in A } Q ( s ^ { \prime } , a ^ { \prime } ) \right] , } & { \mu ( a | s ) > 0 , } \\ { Q ( s , a ) , } & { e l s e . } \end{array} \right. } \end{array}$$
The basic idea behind this novel operator is that if the learned policy outputs actions that lie in the support region of $\mu$ , then we go for backup; while if OOD actions are generated, we deliberately replace their value estimates with $\begin{array} { r } { \operatorname* { m a x } _ { a ^ { \prime } \sim \operatorname { S u p p o r t } ( \mu ( \cdot | s ) ) } Q ( s , a ^ { \prime } ) - \delta } \end{array}$ , where $\delta > 0$ can be arbitrarily small. That is, different from standard Bellman backup, we set up a checking procedure (i.e., $\mathcal { T } _ { 1 , }$ ) of whether the previous backup (i.e., $\mathcal { T } _ { 2 }$ ) involves OOD actions for the update. Intrinsically, we construct pseudo target values for OOD actions. We subtract a small positive $\delta$ such that OOD actions will not be chosen when executing policy via arg $\operatorname* { m a x } _ { a \in \mathcal { A } } Q ( s , a )$ .
For a better understanding of the MCB operator, we theoretically analyze its dynamic programming properties in the tabular MDP setting. All proofs are deferred to Appendix A.
Proposition 1. In the support region of the behavior policy, i.e., Support $( \mu )$ , the MCB operator is a $\gamma$ -contraction operator in the $\mathcal { L } _ { \infty }$ norm, and any initial $Q$ function can converge to a unique fixed point by repeatedly applying $\mathcal { T } _ { \mathrm { M C B } }$ .
Proposition 2 (Behave at least as well as behavior policy). Denote $Q _ { \mathrm { M C B } }$ as the unique fixed point acquired by the MCB operator, then in $\operatorname { S u p p o r t } ( \mu )$ we have: $Q _ { \mu } \leq Q _ { \mathrm { M C B } } \leq Q _ { \mu ^ { * } }$ , where $Q _ { \mu }$ is the $Q$ function of the behavior policy and $Q _ { \mu ^ { * } }$ is the $Q$ function of the optimal policy in the batch.
Proposition 2 indicates that the policy induced by the MCB operator can behave at least as well as the behavior policy, and can approximate the optimal batch-constraint policy. Apart from this advantage, we further show that the MCB operator results in milder conservatism. We start by observing that value penalization method, like CQL [35], guarantees that the learned value function $\hat { Q } ^ { \pi } ( s , a )$ is a lower bound of its true value $Q ^ { \pi } ( s , a )$ . It is also ensured that following such conservative update leads to a safe policy improvement, i.e., $\begin{array} { r } { J ( \pi _ { \mathrm { C Q L } } ) \ge J ( \mu ) - \mathcal { O } ( \frac { 1 } { ( 1 - \gamma ) ^ { 2 } } ) } \end{array}$ (Theorem 3.6 in [35]). For explicit policy constraint methods, e.g., $\mathrm { T D } 3 { + } \mathrm { B C }$ [13], the learned policy $\pi _ { p }$ mimics the behavior policy $\mu$ , and can hardly behave significantly better than $\mu$ . We show in Proposition 3 that explicit policy constraint methods also exhibit a safe policy improvement, $\begin{array} { r } { J ( \pi _ { p } ) \geq J ( \dot { \mu } ) - \mathcal { O } ( \frac { 1 } { ( 1 - \gamma ) ^ { 2 } } ) } \end{array}$ ( 1(1−γ)2 ), while the MCB operator can consistently improve the policy with a tighter lower bound.
Proposition 3 (Milder Pessimism). Suppose there exists an explicit policy constraint offline reinforcement learning algorithm such that the $K L$ -divergence of the learned policy $\pi _ { p } ( \cdot | s )$ and the behavior policy $\mu ( \cdot | s )$ is optimized to guarantee max $( \mathrm { K L } ( \mu , \pi _ { p } ) , \mathrm { K L } ( \pi _ { p } , \mu ) ) \leq \dot { \epsilon }$ , ∀s. Denote $\begin{array} { r } { \epsilon _ { \mu } ^ { \pi _ { p } } = \operatorname* { m a x } _ { s } | \mathbb { E } _ { a \sim \pi _ { p } } A ^ { \mu } ( s , a ) | . } \end{array}$ , where $A ^ { \mu } ( s , a )$ is the advantage function. Then
$$J ( \pi _ { p } ) \geq J ( \mu ) - \frac { \sqrt { 2 } \gamma \epsilon _ { \mu } ^ { \pi _ { p } } } { ( 1 - \gamma ) ^ { 2 } } \sqrt { \epsilon } ,$$
while for the policy $\pi _ { \mathrm { M C B } }$ learned by applying the MCB operator, we have
$$J ( \pi _ { \mathrm { M C B } } ) \geq J ( \mu ) .$$
In summary, the MCB operator benefits the offline learning in two aspects: (1) the operator is a contraction, and any initial $Q$ functions are guaranteed to converge to a unique fixed point; (2) the learned policy of the MCB operator is ensured to be better than the behavior policy, and reserve milder pessimism compared with policy constraint methods or CQL.
# 3.2 Practical MCB Operator
In practice, it is intractable to acquire $\begin{array} { r } { \operatorname* { m a x } _ { a ^ { \prime } \sim \operatorname { S u p p o r t } ( \mu ( \cdot | s ) ) } Q ( s , a ^ { \prime } ) } \end{array}$ in $\mathcal { T } _ { 1 }$ of Eq. (4) in continuous control domains, and the behavior policy is often unknown. Thus, we fit an empirical behavior policy $\hat { \mu }$ with supervised learning based on the static dataset. The pseudo target values for the OOD actions are then computed by sampling $N$ actions from $\hat { \mu }$ , and taking maximum over their value evaluation. Formally, we define the practical MCB operator below, accompanied by the theoretical analysis.
Definition 2. The practical Mildly Conservative Bellman (MCB) operator is defined as
$$\hat { \mathcal { T } } _ { \mathrm { M C B } } Q ( s , a ) = ( \hat { \mathcal { T } } _ { 1 } \mathcal { T } _ { 2 } ) Q ( s , a ) ,$$
where
$$\begin{array} { r } { \hat { \mathcal { T } } _ { 1 } Q ( s , a ) = \left\{ \begin{array} { l l } { Q ( s , a ) , \qquad ~ } & { \mu ( a | s ) > 0 . } \\ { \mathbb { E } _ { \{ a _ { i } ^ { \prime } \} ^ { N } \sim \hat { \mu } ( \cdot | s ) } \left[ \operatorname* { m a x } _ { a ^ { \prime } \sim \{ a _ { i } ^ { \prime } \} ^ { N } } Q ( s , a ^ { \prime } ) \right] , } & { e l s e . } \end{array} \right. } \end{array}$$
Compared with Eq. (4), we make a small modification of $\mathcal { T } _ { 1 }$ , and keep $\mathcal { T } _ { 2 }$ unchanged. There is no need to subtract $\delta$ here as generally $\begin{array} { r } { { \mathbb E } _ { \{ a _ { i } ^ { \prime } \} ^ { N } \sim \hat { \mu } ( \cdot | s ) } \left[ \operatorname* { m a x } _ { a ^ { \prime } \sim \{ a _ { i } ^ { \prime } \} ^ { N } } Q ( s , a ^ { \prime } ) \right] \leq \operatorname* { m a x } _ { a ^ { \prime } \sim \mathrm { S u p p o r t } ( \mu ) } Q ( s , a ^ { \prime } ) . } \end{array}$ . The practical MCB operator is much easier to implement in practice. We show that the practical MCB operator is still a $\gamma$ -contraction in the support region of the behavior policy $\mu$ .
Proposition 4. Proposition 1 still holds for the practical MCB operator.
Since we fit the empirical distribution $\hat { \mu }$ of the behavior policy $\mu$ , there may exist a shift between $\hat { \mu }$ and $\mu$ , especially when we represent the policy via neural networks. That suggests that OOD actions $a ^ { \prime }$ can still be sampled from $\hat { \mu }$ such that $a ^ { \prime } \overset { \cdot } { \notin } \operatorname { S u p p o r t } ( \mu ( \cdot | s ) )$ . Our last main result reveals that erroneous overestimation issue will not occur with the aid of the practical MCB operator.
Proposition 5 (No erroneous overestimation will occur). Assuming that $\operatorname* { s u p } _ { s } D _ { \mathrm { T V } } ( \hat { \mu } ( \cdot | s ) \quad | |$ $\begin{array} { r } { \mu ( \cdot | \bar { s } ) ) \leq \epsilon < \frac { 1 } { 2 } } \end{array}$ , we have
$$\mathbb { E } _ { \{ a _ { i } ^ { \prime } \} ^ { N } \sim \hat { \mu } ( \cdot | s ) } \left[ \operatorname* { m a x } _ { a ^ { \prime } \in \{ a _ { i } ^ { \prime } \} ^ { N } } Q ( s , a ^ { \prime } ) \right] \leq \operatorname* { m a x } _ { a ^ { \prime } \in \mathrm { S u p p o r t } ( \mu ( \cdot | s ) ) } Q ( s , a ^ { \prime } ) + ( 1 - ( 1 - 2 \epsilon ) ^ { N } ) \frac { r _ { \operatorname* { m a x } } } { 1 - \gamma } .$$
Remark: This proposition generally requires a comparatively well-fitted empirical behavior policy $\hat { \mu }$ . In practice, we model $\hat { \mu }$ with a CVAE. In most cases, CVAE can already fit the dataset well and guarantee a good performance. Whereas there may exist some situations, e.g., the dataset is highly multi-modal, then one can replace the CVAE as the conditional GAN (CGAN) to better capture the different modes in the dataset as depicted in [61]. We believe generative models like CGAN will be a good choice by then.
Intuitively, the above conclusion says that if the empirical behavior policy $\hat { \mu }$ well fits $\mu$ , i.e., $\epsilon$ is small enough, then regardless of how $\{ a _ { i } ^ { \prime } \} ^ { N }$ are sampled, the pseudo target value will approximate the maximum $Q$ -value within the dataset’s support with high probability. The extrapolation error is under the scale of $\begin{array} { r } { ( 1 - ( 1 - 2 \epsilon ) ^ { N } ) \frac { r _ { \operatorname* { m a x } } } { 1 - \gamma } } \end{array}$ . We expect a good empirical behavior policy such that most of the actions sampled from it will be in-distribution. However, if $\epsilon$ is large, $N$ can act as a trade-off parameter. The smaller $N$ we use, the more conservative we are. Fortunately, we find empirically that our method performs well in a large interval of $N$ over different tasks (see Section 4.2). Hence, it is safe to fix a $N$ in practice.
# 3.3 Algorithm
As aforementioned, we often cannot get prior information about the behavior policy $\mu$ . Thus, we need to empirically fit a behavior policy $\hat { \mu }$ with supervised learning for applying the practical MCB operator. Our algorithm, Mildly Conservative $Q$ -learning (MCQ), trains an additional generative model, which is also adopted by many prior work [14, 17, 33, 67]. We build our novel offline algorithm upon an off-the-shelf off-policy online RL algorithm, Soft Actor-Critic (SAC) [20].
Modelling the behavior policy with the CVAE. We utilize a conditional variational autoencoder (CVAE) [29, 51, 14] to model the behavior policy $\mu$ . Given a fixed logged dataset, the goal of the CVAE is to reconstruct actions conditioned on the states such that the reconstructed actions come from the same distribution as the actions in the dataset, i.e., $\mu ( \cdot | s )$ . That generally satisfies the assumption we make in Proposition 5. As concerned by [32], training a generative model like CVAE still may produce out-of-dataset actions, which leads to extrapolation error since undefined $Q$ values can be possibly queried. Prior methods, like BCQ [14], do not well address such issue. While for our algorithm, such concern is mitigated because overestimation error is actually under control as is guaranteed by Proposition 5.
The CVAE $G _ { \omega } ( s )$ parameterized by $\omega$ is made up of an encoder $E _ { \xi } ( s , a )$ and a decoder $D _ { \psi } ( s , z )$ parameterized by $\xi$ , $\psi$ respectively, $\omega = \{ \xi , \psi \}$ . The CVAE is optimized by maximizing its variational lower bound, which is equivalent to minimizing the following objective function.
$$\mathcal { L } _ { \mathrm { C V A E } } = \mathbb { E } _ { ( s , a ) \sim \mathcal { D } , z \sim E _ { \xi } ( s , a ) } \left[ ( a - D _ { \psi } ( s , z ) ) ^ { 2 } + \mathrm { K L } \left( E _ { \xi } ( s , a ) , \mathcal { N } ( 0 , { \bf I } ) \right) \right] ,$$
where $\operatorname { K L } ( p , q )$ denotes the KL-divergence between probability distribution $p ( \cdot )$ and $q ( \cdot )$ , and $\mathbf { I }$ is the identity matrix. When sampling actions from the CVAE, we first sample a latent variable $z$ from the prior distribution, which is set to be multivariate normal distribution $\mathcal { N } ( 0 , \bf { I } )$ , and then pass it in conjunction with the state $s$ into the decoder $D _ { \psi } ( s , z )$ to get the desired decoded action.
It is also worth noting that we do not choose GAN [19] as the generative model because it is known to suffer from training instability and mode collapse [52, 6, 5]. Also, GAN consumes much more time and memories to train compared with the CVAE.
Loss functions. In deep RL, the $Q$ function is represented with a neural network parameterized by $\theta$ and is updated via minimizing the temporal difference (TD) loss $\mathbb { E } _ { s , a , r , s ^ { \prime } } [ ( Q _ { \theta } ( s , a ) - \mathcal { T } Q ( s , a ) ) ^ { 2 } ]$ . We actually are performing the regression task $( s , a ) \mapsto \mathcal { T } Q ( s , a )$ to train the $Q$ function. The target value ${ \mathcal { T } } Q ( s , a )$ is usually computed by utilizing a lagging target network parameterized by $\theta ^ { \prime }$ without gradient backpropagation. As a typical actor-critic [30, 31, 53] algorithm, SAC uses its critic networks to perform value estimation and uses a separate actor network for policy improvement. In order to incorporate the MCB operator with the off-the-shelf SAC algorithm, we need to check whether the sampled action $a ^ { \prime } \sim \bar { \pi } ( \cdot | s )$ lies outside of the behavior policy’s support, i.e., whether $\mu ( a ^ { \prime } | s ) > 0$ . However, such a criterion is not reliable, because the true behavior policy $\mu$ is unknown and it is difficult to examine whether $\mu ( a ^ { \prime } | s ) > 0$ in practice. It is also problematic if we rely on the empirical behavior policy $\hat { \mu }$ to check whether $a ^ { \prime }$ is OOD as $\hat { \mu }$ itself can produce OOD actions.
We then resort to constructing an auxiliary loss for OOD actions and integrating it with the standard Bellman error. Specifically, we sample $a ^ { \mathrm { o o d } }$ from the learned policy $\pi ( \cdot | _ { s } \mathrm { i n } )$ based on the sampled state $s ^ { \mathrm { i n } } \sim \mathcal { D }$ from the dataset and assign them pseudo target values based on the practical MCB operator. Note that the superscript ood is used to distinguish from the in-dataset real actions, and $a ^ { \mathrm { { \bar { o } o d } } }$ is not necessarily an OOD action. We remark that if $a ^ { \mathrm { o o d } } \in \operatorname { S u p p o r t } ( \mu ( \cdot | s ) )$ , the pseudo $Q$
# Algorithm 1 Mildly Conservative $Q$ -learning (MCQ)
1: Initialize CVAE $G _ { \omega }$ , critic networks $Q _ { \theta _ { 1 } } , Q _ { \theta _ { 2 } }$ and actor network $\pi _ { \phi }$ with random parameters 2: Initialize target networks $\theta _ { 1 } ^ { \prime } \theta _ { 1 } , \theta _ { 2 } ^ { \prime } \theta _ { 2 }$ and offline replay buffer $\mathcal { D }$ . 3: for $t = 1$ to $T$ do 4: Sample a mini-batch $B = \{ ( s , a , r , s ^ { \prime } , d ) \}$ from $\mathcal { D }$ , where $d$ is the done flag 5: Train CVAE via minimizing Eq. (10) 6: Get target value: $\begin{array} { r } { y = r ( s , \bar { a } ) + \gamma \left[ \operatorname* { m i n } _ { i = 1 , 2 } Q _ { \theta _ { i } ^ { \prime } } ( s ^ { \prime } , a ^ { \prime } ) - \alpha \log \pi _ { \phi } ( a ^ { \prime } | s ^ { \prime } ) \right] , a ^ { \prime } \sim \pi _ { \phi } ( \cdot | s ^ { \prime } ) } \end{array}$ 7: Sample $N$ actions from $\pi$ based on each $s$ and $s ^ { \prime }$ , set $s ^ { \mathrm { i n } } = \{ s , s ^ { \prime } \}$ 8: Compute the target value for the OOD actions via Eq. (13) 9: Update critic $\theta _ { i }$ with gradient descent via minimizing Eq. (11) 10: Update actor $\phi$ with gradient ascent via Eq. (14) 11: Update target networks: $\theta _ { i } ^ { \prime } \tau \theta _ { i } + ( 1 - \tau ) \theta _ { i } ^ { \prime } , i = 1 , 2$ 12: end for
value will not negatively affect the evaluation upon it, because in-distribution actions are still trained to approximate the optimal batch-constraint $Q$ value. In this way, we actively train both possible OOD actions and in-distribution actions simultaneously via $o o D$ sampling. The resulting objective function for the critic networks is presented in Eq. (11).
$$\mathcal { L } _ { \mathrm { c r i t i c } } = \lambda \mathbb { E } _ { ( s , a , r , s ^ { \prime } ) \sim \mathcal { D } } \left[ ( Q _ { \theta _ { i } } ( s , a ) - y ) ^ { 2 } \right] + ( 1 - \lambda ) \mathbb { E } _ { s ^ { \mathrm { i n } } \sim \mathcal { D } , a ^ { \mathrm { o o d } } \sim \pi } \left[ ( Q _ { \theta _ { i } } ( s ^ { \mathrm { i n } } , a ^ { \mathrm { o o d } } ) - y ^ { \prime } ) ^ { 2 } \right] ,$$
where the target value for the in-distribution actions gives
$$y = r ( s , a ) + \gamma \left[ \operatorname* { m i n } _ { i = 1 , 2 } Q _ { \theta _ { i } ^ { \prime } } ( s ^ { \prime } , a ^ { \prime } ) - \alpha \log \pi _ { \phi } ( a ^ { \prime } | s ^ { \prime } ) \right] , \alpha \in \mathbb { R } _ { + } ,$$
which follows the standard target value of vanilla SAC. The hyperparameter $\lambda$ balances the indistribution data training and OOD action training. Following the formulas of the practical MCB operator in Eq. (9), the pseudo target value for the OOD action is computed by:
$$y ^ { \prime } = \operatorname* { m i n } _ { j = 1 , 2 } \mathbb { E } _ { \{ a _ { i } ^ { \prime } \} ^ { N } \sim \hat { \mu } } \left[ \operatorname* { m a x } _ { a ^ { \prime } \sim \{ a _ { i } ^ { \prime } \} ^ { N } } Q _ { \theta _ { j } } ( s ^ { \mathrm { i n } } , a ^ { \prime } ) \right] .$$
Note that we experimentally find that replacing the min operator with a mean operator does not raise much difference in performance. We hence take advantage of the min operator to fulfill the pseudo clipped double $Q$ -learning for OOD actions.
The policy is then optimized by solving the following optimization problem:
$$\pi _ { \phi } : = \operatorname* { m a x } _ { \phi } \mathbb { E } _ { s \sim \mathcal { D } , a \sim \pi _ { \phi } ( \cdot | s ) } \left[ \operatorname* { m i n } _ { i = 1 , 2 } Q _ { \theta _ { i } } ( s , a ) - \alpha \log \pi _ { \phi } ( \cdot | s ) \right] .$$
We detail the learning procedure of our MCQ in Algorithm 1. Different from [13], our method does not require normalization over states or value functions. The only change we make to the vanilla SAC algorithm is an extra auxiliary loss term (blue term in Eq. (11)) such that OOD actions are actively and properly trained. The additional critic loss term can also be plugged into other off-policy online RL algorithms directly. As an evidence, we combine the MCB operator with TD3 [15], yielding a deterministic version of MCQ. Please refer to Appendix B for more details.
# 4 Experiments
In this section, we first empirically demonstrate the effectiveness and advantages of our proposed MCQ algorithm on D4RL benchmarks [12]. We then conduct a detailed parameter study to show the hyperparameter sensitivity of MCQ. We also experimentally illustrate that the value estimation of MCQ will not incur severe overestimation and pessimistic value estimates are witnessed in practice. Finally, we show the superior offline-to-online fine-tuning benefits of MCQ on some MuJoCo datasets.
# 4.1 Results on MuJoCo Datasets
We experimentally compare our MCQ against behavior cloning (BC), SAC, and several recent strong baseline methods, CQL [35], UWAC [59], TD3+BC [13], and IQL [32], on D4RL [12] benchmarks.
We choose these methods as they typically represent different categories of model-free offline RL, i.e., CQL is a value penalization method, $\mathrm { T D } 3 { + } \mathrm { B C }$ involves explicit policy constraint (BC loss), UWAC relies on uncertainty estimation for training, and IQL learns without querying OOD samples.
We conduct experiments on MuJoCo locomotion tasks, which are made up of five types of datasets (random, medium, medium-replay, medium-expert, and expert), yielding a total of 15 datasets. We use the most recently released "-v2" datasets for performance evaluation. The results of BC and SAC are acquired by using our implemented code. The results of CQL and UWAC are obtained by running their official codes, because the reported scores in their papers are not obtained on MuJoCo "-v2" datasets. We take the results of $\mathrm { T D } 3 { + } \mathrm { B C }$ from its original paper (Table 7 in [13]). Since the IQL paper does not report its performance on MuJoCo random and expert datasets, we run IQL using the official codebase on them and take the results on medium, medium-replay, medium-expert datasets from its original paper directly. All methods are run for 1M gradient steps.
Table 1: Normalized average score comparison of MCQ against baseline methods on D4RL benchmarks over the final 10 evaluations. 0 corresponds to a random policy and 100 corresponds to an expert policy. The experiments are run on MuJoCo "-v2" datasets over 4 random seeds. $\mathbf { r } =$ random, $\mathbf { m } =$ medium, $\mathrm { m - r = }$ medium-replay, $\mathbf { m } { - } \mathbf { e } =$ medium-expert, ${ \bf e } =$ expert. We bold the highest mean.
<table><tr><td>Task Name</td><td>BC</td><td>SAC</td><td>CQL</td><td>UWAC</td><td>TD3+BC</td><td>IQL</td><td>MCQ (ours)</td></tr><tr><td>halfcheetah-r</td><td>2.2±0.0</td><td>29.7±1.4</td><td>17.5±1.5</td><td>2.3±0.0</td><td>11.0±1.1</td><td>13.1±1.3</td><td>28.5±0.6</td></tr><tr><td>hopper-r</td><td>3.7±0.6</td><td>9.9±1.5</td><td>7.9±0.4</td><td>2.7±0.3</td><td>8.5±0.6</td><td>7.9±0.2</td><td>31.8±0.5</td></tr><tr><td>walker2d-r</td><td>1.3±0.1</td><td>0.9±0.8</td><td>5.1±1.3</td><td>2.0±0.4</td><td>1.6±1.7</td><td>5.4±1.2</td><td>17.0±3.0</td></tr><tr><td>halfcheetah-m</td><td>43.2±0.6</td><td>55.2±27.8</td><td>47.0±0.5</td><td>42.2±0.4</td><td>48.3±0.3</td><td>47.4±0.2</td><td>64.3±0.2</td></tr><tr><td>hopper-m</td><td>54.1±3.8</td><td>0.8±0.0</td><td>53.0±28.5</td><td>50.9±4.4</td><td>59.3±4.2</td><td>66.2±5.7</td><td>78.4±4.3</td></tr><tr><td>walker2d-m</td><td>70.9±11.0</td><td>-0.3±0.2</td><td>73.3±17.7</td><td>75.4±3.0</td><td>83.7±2.1</td><td>78.3±8.7</td><td>91.0±0.4</td></tr><tr><td>halfcheetah-m-r</td><td>37.6±2.1</td><td>0.8±1.0</td><td>45.5±0.7</td><td>35.9±3.7</td><td>44.6±0.5</td><td>44.2±1.2</td><td>56.8±0.6</td></tr><tr><td>hopper-m-r</td><td>16.6±4.8</td><td>7.4±0.5</td><td>88.7±12.9</td><td>25.3±1.7</td><td>60.9±18.8</td><td>94.7±8.6</td><td>101.6±0.8</td></tr><tr><td>walker2d-m-r halfcheetah-m-e</td><td>20.3±9.8</td><td>-0.4±0.3</td><td>81.8±2.7</td><td>23.6±6.9</td><td>81.8±5.5</td><td>73.8±7.1</td><td>91.3±5.7</td></tr><tr><td></td><td>44.0±1.6</td><td>28.4±19.4</td><td>75.6±25.7</td><td>42.7±0.3</td><td>90.7±4.3</td><td>86.7±5.3</td><td>87.5±1.3</td></tr><tr><td>hopper-m-e</td><td>53.9±4.7</td><td>0.7±0.0</td><td>105.6±12.9</td><td>44.9±8.1</td><td>98.0±9.4</td><td>91.5±14.3</td><td>111.2±0.1</td></tr><tr><td>walker2d-m-e</td><td>90.1±13.2</td><td>1.9±3.9</td><td>107.9±1.6</td><td>96.5±9.1</td><td>110.1±0.5</td><td>109.6±1.0</td><td>114.2±0.7</td></tr><tr><td>Average Above</td><td>36.5</td><td>11.3</td><td>59.1</td><td>37.0</td><td>58.2</td><td>59.9</td><td>72.8</td></tr><tr><td>halfcheetah-e</td><td>91.8±1.5</td><td>-0.8±1.8</td><td>96.3±1.3</td><td>92.9±0.6</td><td>96.7±1.1</td><td>95.0±0.5</td><td>96.2±0.4</td></tr><tr><td>hopper-e walker2d-e</td><td>107.7±0.7</td><td>0.7±0.0</td><td>96.5±28.0</td><td>110.5±0.5</td><td>107.8±7</td><td>109.4±0.5</td><td>111.4±0.4</td></tr><tr><td></td><td>106.7±0.2</td><td>0.7±0.3</td><td>108.5±0.5</td><td>108.4±0.4</td><td>110.2±0.3</td><td>109.9±1.2</td><td>107.2±1.1</td></tr><tr><td>Total Average</td><td>49.6</td><td>9.0</td><td>67.3</td><td>50.4</td><td>67.6</td><td>68.9</td><td>79.2</td></tr></table>
In our experiments, we set the number of sampled actions $N = 1 0$ by default and tune the weighting coefficient $\lambda$ . We report the $\lambda$ used for all tasks in Appendix C, along with details on the experiments and implementation. We summarize the normalized average score comparison of MCQ against recent baselines in Table 1. Unsurprisingly, we observe that MCQ behaves better than BC on all of the tasks, which is consistent with our theoretical analysis in Proposition 2 and 3. MCQ also significantly outperforms the base SAC algorithm. Prior offline RL methods struggle for good performance on non-expert datasets like random and medium-replay, while MCQ surpasses them with a remarkable margin on many non-expert datasets. We attribute the less satisfying performance of prior offline RL methods to their strict conservatism, which restricts their generalization beyond the support of the dataset and leads to limited performance. The results, therefore, validate our claim that milder pessimism is more we need for offline learning. Furthermore, MCQ is also competitive to baselines on expert datasets. MCQ achieves the best performance on 11 out of 15 datasets, yielding a total average score of 72.8 on non-expert datasets, and an average score of 79.2 on all 15 datasets. Whereas the second best method, IQL, has an average score of 59.9 on non-expert datasets and a total average score of 68.9 across all tasks.
# 4.2 Parameter Study
In this subsection, we conduct a detailed parameter study on MCQ. MCQ generally contains two hyperparameters, weighting coefficient $\lambda$ and number of sampled actions $N$ . To demonstrate the parameter sensitivity of MCQ, we choose two datasets from MuJoCo locomotion tasks and conduct experiments on them, halfcheetah-medium-v2, and hopper-medium-replay-v2. The experiments are run for 1M gradient steps over 4 different random seeds.
 Figure 2: Parameter study and $Q$ function estimation on halfcheetah-medium-v2 and hopper-mediumreplay-v2. The shaded region captures the standard deviation.
Weighting coefficient $\lambda$ . The weighting coefficient $\lambda$ is a critical hyperparameter for MCQ, which directly controls the balance between in-distribution actions training and OOD actions training. If we set $\lambda = 1$ , then MCQ degenerates into the base SAC algorithm. If $\lambda$ leans towards 0, the critics will be overwhelmed by OOD actions. Intuitively, one ought not to use small $\lambda$ , because more weights are desired for standard Bellman error such that in-distribution state-action pairs can be well-trained. We observe significant performance drop with smaller $\lambda$ in Figure 2(a) and 2(b). Also, we find that choosing $0 . 7 \leq \lambda < 1$ generally induces good performance.
Number of sampled actions $N$ . $N$ works as a regularizer to control the potential extrapolation error. In case the behavior policy $\mu$ is known, we require $N$ to be as large as possible to better estimate the maximum $Q$ value. While in practice, we leverage the CVAE to approximate $\mu$ , from which OOD actions can be sampled. $N$ then plays a role to balance pessimism and generalization. To see the influence of $N$ , we fix $\lambda = 0 . 9 5$ for the two datasets. Experimental results in Figure 2(d) and 2(e) indicate that MCQ is insensitive to $N$ for a wide range of $N$ . We therefore set $N = 1 0$ by default.
Value estimation. We present the $Q$ value estimates with respect to (w.r.t.) $\lambda$ and $N$ in Figure 2(c) and 2(f). The $Q$ estimation is calculated via $\mathbb { E } _ { i = 1 , 2 } \mathbb { E } _ { ( s , a ) \sim \mathcal { D } } \big [ Q _ { \theta _ { i } } ( s , a ) \big ]$ . The results illustrate that (1) smaller $\lambda$ will incur severe underestimation issue (as depicted by Figure 2(c), $Q$ values collapse with $\lambda = 0 . 5$ or $\lambda = 0 . 3$ ); (2) no overestimation is observed, even with a large $\lambda = 0 . 9 5$ , which validates the theoretical result in Proposition 5; (3) the $Q$ estimates resemble each other under different $N$ . We conclude that MCQ ensures a stable and good value estimation with a proper $\lambda$ .
# 4.3 Offline-to-online Fine-tuning
We examine the offline-to-online fine-tuning capability of MCQ against some prior strong offline RL baselines, CQL [35], $\mathrm { T D } 3 { + } \mathrm { B C }$ [13], IQL [32]. We additionally compare against AWAC [45], which is designed intrinsically for offline-to-online adaptation. We conduct experiments on MuJoCo random and medium-replay datasets. It is challenging to train on these datasets for both offline and offline-to-online fine-tuning as they are non-expert, or even contain many bad transitions. We first train baselines and MCQ for 1M gradient steps offline and then perform online fine-tuning for another 100K gradient steps. Note that IQL paper [32] adopts 1M steps for online fine-tuning. However, we argue that 1M steps of online interactions are even enough to train off-policy online RL algorithms from scratch to perform very well. We thus believe 100K steps is more reasonable for the online interaction. All methods are run over 4 random seeds. The results are shown in Figure 3, where the shaded region denotes the standard deviation. As expected, we observe that MCQ consistently outperforms prior offline RL methods as well as AWAC on all of the datasets, often surpassing all of them with a large margin. The mild pessimism of MCQ makes it adapt faster, or keep the offline good performance during online interactions. Other prior offline RL methods, unfortunately, fail in achieving satisfying performance during online interaction due to strict conservatism and lack of generalization ability.
 Figure 3: Offline-to-online fine-tuning results on 6 D4RL MuJoCo locomotion tasks.
# 5 Related Work
Model-free offline RL. Prior model-free offline RL methods are typically designed to restrict the learned policy from producing OOD actions. They usually achieve this by leveraging importance sampling [47, 54, 39, 44, 16], incorporating explicit policy constraints [34, 58, 17, 13, 11], learning latent actions [67, 3], penalizing learned value functions such that low values are assigned to unseen actions [35, 33, 41], using adaptive methods [18], and uncertainty quantification [59, 65, 4]. Another line of the methods, instead, resorts to learning without querying OOD actions [56, 8, 32]. By doing so, they constrain the learning process within the support of the dataset. Nevertheless, existing methods may induce unnecessarily over-pessimistic value functions, and their performance is largely confined by how well the behavior policy is [45, 38, 4]. That partly explains why these methods are not satisfiable when trained on non-expert datasets (e.g., random datasets). MCQ keeps milder conservatism and better generalization ability as OOD actions are actively trained with proper targets.
Model-based offline RL. Model-based offline RL methods, in contrast, learn the dynamics model in a supervised manner, and leverage the learned dynamics for policy optimization. Advances in this field include uncertainty quantification [46, 64, 27, 10], learning conservative value functions [63], representation learning [37, 48], constraining the learned policy with a behavior cloning loss [42], and sequential modelling [7, 23, 43]. However, there is no guarantee that the trained dynamics models are reliable, e.g., poor transitions can be generated, especially in complex high-dimensional environments [22]. Meanwhile, training dynamics models raises extra computation costs.
Offline-to-online RL. There are some efforts on accelerating online interactions with the aid of offline logged data, which is also referred to as learning from demonstration [21, 26, 49]. Offline-to-online RL, instead, aims at enhancing the well-trained offline policy via online interactions. To ensure a fast adaptation and stable policy improvement, many techniques are adopted, such as model ensemble [38], explicit policy constraints [45, 66]. Offline-to-online fine-tuning will be difficult if the trained value function or policy is overly pessimistic, which may lead to a suboptimal policy.
# 6 Conclusion
In this paper, we propose Mildly Conservative $Q$ -learning (MCQ) to alleviate the over pessimism in existing offline RL methods. MCQ actively train OOD actions by constructing them proper pseudo target values following the guidance of the practical Mildly Conservative Bellman (MCB) operator. We theoretically illustrate that the policy induced by the MCB operator behaves at least as well as the behavior policy, and no erroneous overestimation will occur for the practical MCB operator. Furthermore, we extensively compare MCQ against recent strong baselines on MuJoCo locomotion tasks. Experimental results show that MCQ surpasses these baselines with a large margin on many non-expert datasets, and is also competitive with baselines on expert datasets. Moreover, we demonstrate the superior generalization capability of MCQ when transferring from offline to online. These altogether reveal that mild conservatism is critical for offline learning. We hope this work can promote the offline RL towards mild pessimism, and bring new insights into the community.
One drawback of our current algorithm lies in the need of tuning the weighting coefficient $\lambda$ . However, we empirically find that $0 . 7 \leq \lambda < 1$ can usually induce satisfying performance. We leave the automatic tuning of $\lambda$ as future work.
# Acknowledgments and Disclosure of Funding
This work was supported in part by the Science and Technology Innovation 2030-Key Project under Grant 2021ZD0201404, in part by the NSF China under Grant 61872009. The authors would like to thank the anonymous reviewers for their valuable comments and advice.
# References
[1] J. Achiam, D. Held, A. Tamar, and P. Abbeel. Constrained Policy Optimization. In International Conference on Machine Learning, 2017. [2] R. Agarwal, M. Schwarzer, P. S. Castro, A. C. Courville, and M. G. Bellemare. Deep Reinforcement Learning at the Edge of the Statistical Precipice. In Advances in Neural Information Processing Systems, 2021. [3] A. Ajay, A. Kumar, P. Agrawal, S. Levine, and O. Nachum. OPAL: Offline Primitive Discovery for Accelerating Offline Reinforcement Learning. In International Conference on Learning Representations, 2021. [4] C. Bai, L. Wang, Z. Yang, Z.-H. Deng, A. Garg, P. Liu, and Z. Wang. Pessimistic Bootstrapping for Uncertainty-Driven Offline Reinforcement Learning. In International Conference on Learning Representations, 2022. [5] D. Bang and H. Shim. MGGAN: Solving Mode Collapse Using Manifold-Guided Training. IEEE/CVF International Conference on Computer Vision Workshops, pages 2347–2356, 2021. [6] D. Bau, J.-Y. Zhu, J. Wulff, W. S. Peebles, H. Strobelt, B. Zhou, and A. Torralba. Seeing What a GAN Cannot Generate. In IEEE/CVF International Conference on Computer Vision, pages 4501–4510, 2019. [7] L. Chen, K. Lu, A. Rajeswaran, K. Lee, A. Grover, M. Laskin, P. Abbeel, A. Srinivas, and I. Mordatch. Decision Transformer: Reinforcement Learning via Sequence Modeling. ArXiv, abs/2106.01345, 2021. [8] X. Chen, Z. Zhou, Z. Wang, C. Wang, Y. Wu, Q. Deng, and K. W. Ross. BAIL: Best-Action Imitation Learning for Batch Deep Reinforcement Learning. In Advances in Neural Information Processing Systems, 2020. [9] I. Csiszár and J. Körner. Information Theory - Coding Theorems for Discrete Memoryless Systems, Second Edition. Cambridge University Press, 2011. [10] C. P. Diehl, T. Sievernich, M. Krüger, F. Hoffmann, and T. Bertram. UMBRELLA: Uncertainty-Aware Model-Based Offline Reinforcement Learning Leveraging Planning. ArXiv, abs/2111.11097, 2021. [11] R. Fakoor, J. Mueller, P. Chaudhari, and A. Smola. Continuous Doubly Constrained Batch Reinforcement Learning. In Advances in Neural Information Processing Systems, 2021. [12] J. Fu, A. Kumar, O. Nachum, G. Tucker, and S. Levine. D4RL: Datasets for Deep Data-Driven Reinforcement Learning. ArXiv, abs/2004.07219, 2020. [13] S. Fujimoto and S. S. Gu. A Minimalist Approach to Offline Reinforcement Learning. In Advances in Neural Information Processing Systems, 2021. [14] S. Fujimoto, D. Meger, and D. Precup. Off-Policy Deep Reinforcement Learning without Exploration. In International Conference on Machine Learning, 2019. [15] S. Fujimoto, H. van Hoof, and D. Meger. Addressing Function Approximation Error in Actor-Critic Methods. In International Conference on Machine Learning, 2018. [16] C. Gelada and M. G. Bellemare. Off-Policy Deep Reinforcement Learning by Bootstrapping the Covariate Shift. In AAAI Conference on Artificial Intelligence, volume 33, 2019. [17] S. K. S. Ghasemipour, D. Schuurmans, and S. S. Gu. EMaQ: Expected-Max Q-Learning Operator for Simple Yet Effective Offline and Online RL. In International Conference on Machine Learning, 2021. [18] D. Ghosh, A. Ajay, P. Agrawal, and S. Levine. Offline RL Policies Should be Trained to be Adaptive. ArXiv, abs/2207.02200, 2022. [19] I. J. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. C. Courville, and Y. Bengio. Generative Adversarial Nets. In Advances in Neural Information Processing Systems, 2014. [20] T. Haarnoja, A. Zhou, P. Abbeel, and S. Levine. Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor. In International Conference on Machine Learning, 2018. [21] T. Hester, M. Vecerík, O. Pietquin, M. Lanctot, T. Schaul, B. Piot, D. Horgan, J. Quan, A. Sendonaris, I. Osband, G. Dulac-Arnold, J. P. Agapiou, J. Z. Leibo, and A. Gruslys. Deep Q-learning From Demonstrations. In AAAI Conference on Artificial Intelligence, 2018. [22] M. Janner, J. Fu, M. Zhang, and S. Levine. When to Trust Your Model: Model-Based Policy Optimization. In Advances in Neural Information Processing Systems, 2019. [23] M. Janner, Q. Li, and S. Levine. Offline Reinforcement Learning as One Big Sequence Modeling Problem. In Advances in Neural Information Processing Systems, 2021. [24] Y. Jin, Z. Yang, and Z. Wang. Is Pessimism Provably Efficient for Offline RL? In International Conference on Machine Learning, pages 5084–5096. PMLR, 2021. [25] S. M. Kakade and J. Langford. Approximately Optimal Approximate Reinforcement Learning. In International Conference on Machine Learning, 2002. [26] B. Kang, Z. Jie, and J. Feng. Policy Optimization with Demonstrations. In International Conference on Machine Learning, 2018. [27] R. Kidambi, A. Rajeswaran, P. Netrapalli, and T. Joachims. MOReL: Model-Based Offline Reinforcement Learning. In Advances in Neural Information Processing Systems, 2020. [28] D. P. Kingma and J. Ba. Adam: A Method for Stochastic Optimization. In International Conference on Learning Representation, 2015. [29] D. P. Kingma and M. Welling. Auto-Encoding Variational Bayes. ArXiv, abs/1312.6114, 2013. [30] V. R. Konda and V. S. Borkar. Actor-Critic - Type Learning Algorithms for Markov Decision Processes. SIAM J. Control. Optim., 38:94–123, 1999. [31] V. R. Konda and J. N. Tsitsiklis. Actor-Critic Algorithms. In Advances in Neural Information Processing Systems, 1999. [32] I. Kostrikov, A. Nair, and S. Levine. Offline Reinforcement Learning with Implicit Q-Learning. In International Conference on Learning Representations, 2022. [33] I. Kostrikov, J. Tompson, R. Fergus, and O. Nachum. Offline Reinforcement Learning with Fisher Divergence Critic Regularization. In International Conference on Machine Learning, 2021. [34] A. Kumar, J. Fu, G. Tucker, and S. Levine. Stabilizing Off-Policy Q-Learning via Bootstrapping Error Reduction. In Advances in Neural Information Processing Systems, 2019. [35] A. Kumar, A. Zhou, G. Tucker, and S. Levine. Conservative Q-Learning for Offline Reinforcement Learning. In Advances in Neural Information Processing Systems, 2020. [36] S. Lange, T. Gabel, and M. A. Riedmiller. Batch Reinforcement Learning. In Reinforcement Learning, 2012. [37] B.-J. Lee, J. Lee, and K.-E. Kim. Representation Balancing Offline Model-based Reinforcement Learning. In International Conference on Learning Representations, 2021. [38] S. Lee, Y. Seo, K. Lee, P. Abbeel, and J. Shin. Offline-to-Online Reinforcement Learning via Balanced Replay and Pessimistic Q-Ensemble. In Conference on Robot Learning, 2021. [39] Y. Liu, A. Swaminathan, A. Agarwal, and E. Brunskill. Off-Policy Policy Gradient with State Distribution Correction. ArXiv, abs/1904.08473, 2019. [40] X. Ma, Y. Yang, H. Hu, J. Yang, C. Zhang, Q. Zhao, B. Liang, and Q. Liu. Offline Reinforcement Learning with Value-based Episodic Memory. In International Conference on Learning Representations, 2022. [41] Y. J. Ma, D. Jayaraman, and O. Bastani. Conservative Offline Distributional Reinforcement Learning. In Advances in Neural Information Processing Systems, volume 34, 2021. [42] T. Matsushima, H. Furuta, Y. Matsuo, O. Nachum, and S. Gu. Deployment-Efficient Reinforcement Learning via Model-Based Offline Optimization. In International Conference on Learning Representations, 2021. [43] L. Meng, M. Wen, Y. Yang, C. Le, X. Li, W. Zhang, Y. Wen, H. Zhang, J. Wang, and B. Xu. Offline Pre-trained Multi-Agent Decision Transformer: One Big Sequence Model Tackles All SMAC Tasks. ArXiv, abs/2112.02845, 2021. [44] O. Nachum, Y. Chow, B. Dai, and L. Li. DualDICE: Behavior-Agnostic Estimation of Discounted Stationary Distribution Corrections. In Advances in Neural Information Processing Systems, 2019. [45] A. Nair, M. Dalal, A. Gupta, and S. Levine. Accelerating Online Reinforcement Learning with Offline Datasets. ArXiv, abs/2006.09359, 2020. [46] Y. Ovadia, E. Fertig, J. Ren, Z. Nado, D. Sculley, S. Nowozin, J. V. Dillon, B. Lakshminarayanan, and J. Snoek. Can You Trust Your Model’s Uncertainty? Evaluating Predictive Uncertainty Under Dataset Shift. In Advances in Neural Information Processing Systems, 2019. [47] D. Precup, R. S. Sutton, and S. Dasgupta. Off-Policy Temporal Difference Learning with Function Approximation. In International Conference on Machine Learning, 2001. [48] R. Rafailov, T. Yu, A. Rajeswaran, and C. Finn. Offline Reinforcement Learning from Images with Latent Space Models. In Learning for Dynamics and Control (L4DC), 2021. [49] A. Rajeswaran, V. Kumar, A. Gupta, J. Schulman, E. Todorov, and S. Levine. Learning Complex Dexterous Manipulation with Deep Reinforcement Learning and Demonstrations. ArXiv, abs/1709.10087, 2018. [50] P. Rashidinejad, B. Zhu, C. Ma, J. Jiao, and S. Russell. Bridging Offline reinforcement Learning and Imitation Learning: A Tale of Pessimism. Advances in Neural Information Processing Systems, 34, 2021. [51] K. Sohn, H. Lee, and X. Yan. Learning Structured Output Representation using Deep Conditional Generative Models. In Advances in Neural Information Processing Systems, 2015. [52] A. Srivastava, L. Valkov, C. Russell, M. U. Gutmann, and C. Sutton. VEEGAN: Reducing Mode Collapse in GANs using Implicit Variational Learning. In Advances in Neural Information Processing Systems, 2017. [53] R. S. Sutton and A. G. Barto. Reinforcement learning: An introduction. MIT press, 2018. [54] R. S. Sutton, A. R. Mahmood, and M. White. An Emphatic Approach to the Problem of Off-policy Temporal-Difference Learning. Journal of Machine Learning Research, 17:2603–2631, 2016. [55] J. Wang, W. Li, H. Jiang, G. Zhu, S. Li, and C. Zhang. Offline Reinforcement Learning with Reverse Model-based Imagination. In Advances in Neural Information Processing Systems, 2021. [56] Q. Wang, J. Xiong, L. Han, P. Sun, H. Liu, and T. Zhang. Exponentially Weighted Imitation Learning for Batched Historical Data. In Advances in Neural Information Processing Systems, 2018. [57] Z. Wang, A. Novikov, K. Zolna, J. T. Springenberg, S. E. Reed, B. Shahriari, N. Siegel, J. Merel, C. Gulcehre, N. M. O. Heess, and N. de Freitas. Critic Regularized Regression. In Advances in Neural Information Processing Systems, 2020. [58] Y. Wu, G. Tucker, and O. Nachum. Behavior Regularized Offline Reinforcement Learning. ArXiv, abs/1911.11361, 2019. [59] Y. Wu, S. Zhai, N. Srivastava, J. M. Susskind, J. Zhang, R. Salakhutdinov, and H. Goh. Uncertainty Weighted Actor-Critic for Offline Reinforcement Learning. In International Conference on Machine Learning, 2021. [60] T. Xie, C.-A. Cheng, N. Jiang, P. Mineiro, and A. Agarwal. Bellman-Consistent Pessimism for Offline Reinforcement Learning. Advances in Neural Information Processing Systems, 34, 2021. [61] S. Yang, Z. Wang, H. Zheng, Y. Feng, and M. Zhou. A Regularized Implicit Policy for Offline Reinforcement Learning. ArXiv, abs/2202.09673, 2022. [62] Y. Yang, X. Ma, L. Chenghao, Z. Zheng, Q. Zhang, G. Huang, J. Yang, and Q. Zhao. Believe what you see: Implicit constraint approach for offline multi-agent reinforcement learning. Advances in Neural Information Processing Systems, 34, 2021. [63] T. Yu, A. Kumar, R. Rafailov, A. Rajeswaran, S. Levine, and C. Finn. COMBO: Conservative Offline Model-Based Policy Optimization. In Advances in Neural Information Processing Systems, 2021. [64] T. Yu, G. Thomas, L. Yu, S. Ermon, J. Y. Zou, S. Levine, C. Finn, and T. Ma. MOPO: Model-based Offline Policy Optimization. In Advances in Neural Information Processing Systems, 2020. [65] A. Zanette, M. J. Wainwright, and E. Brunskill. Provable Benefits of Actor-Critic Methods for Offline Reinforcement Learning. In Advances in Neural Information Processing Systems, 2021. [66] Y. Zhao, R. Boney, A. Ilin, J. Kannala, and J. Pajarinen. Adaptive Behavior Cloning Regularization for Stable Offline-to-Online Reinforcement Learning, 2022. [67] W. Zhou, S. Bajracharya, and D. Held. PLAS: Latent Action Space for Offline Reinforcement Learning. In Conference on Robot Learning, 2020.
# Checklist
1. For all authors...
(a) Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope? [Yes] (b) Did you describe the limitations of your work? [Yes] (c) Did you discuss any potential negative societal impacts of your work? [N/A] (d) Have you read the ethics review guidelines and ensured that your paper conforms to them? [Yes]
2. If you are including theoretical results...
(a) Did you state the full set of assumptions of all theoretical results? [Yes] (b) Did you include complete proofs of all theoretical results? [Yes]
3. If you ran experiments...
(a) Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? [Yes] (b) Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? [Yes] (c) Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? [Yes] (d) Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? [Yes]
4. If you are using existing assets (e.g., code, data, models) or curating/releasing new assets...
(a) If your work uses existing assets, did you cite the creators? [Yes] (b) Did you mention the license of the assets? [Yes] (c) Did you include any new assets either in the supplemental material or as a URL? [No] (d) Did you discuss whether and how consent was obtained from people whose data you’re using/curating? [No] (e) Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? [N/A]
5. If you used crowdsourcing or conducted research with human subjects...
(a) Did you include the full text of instructions given to participants and screenshots, if applicable? [N/A] (b) Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? [N/A] (c) Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? [N/A]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537# ROBUST UNIVERSAL ADVERSARIAL PERTURBATIONS
Anonymous authors Paper under double-blind review
# ABSTRACT
Universal Adversarial Perturbations (UAPs) are imperceptible, image-agnostic vectors that cause deep neural networks (DNNs) to misclassify inputs from a data distribution with high probability. In practical attack scenarios, adversarial perturbations may undergo transformations such as changes in pixel intensity, rotation, etc. while being added to DNN inputs. Existing methods do not create UAPs robust to these real-world transformations, thereby limiting their applicability in attack scenarios. In this work, we introduce and formulate robust UAPs. We build an iterative algorithm using probabilistic robustness bounds and transformations generated by composing arbitrary sub-differentiable transformation functions to construct such robust UAPs. We perform an extensive evaluation on the popular CIFAR-10 and ILSVRC 2012 datasets measuring our UAPs’ robustness under a wide range common, real-world transformations such as rotation, contrast changes, etc. Our results show that our method can generate UAPs up to $2 3 \%$ more robust than existing state-of-the-art baselines.
# 1 INTRODUCTION
Deep neural networks (DNNs) have achieved impressive results in many application domains such as natural language processing (Abdel-Hamid et al., 2014; Brown et al., 2020), medicine (Esteva et al., 2017; 2019), and computer vision (Simonyan & Zisserman, 2014; Szegedy et al., 2016). Despite their performance, they can be fragile in the face of adversarial perturbations: small imperceptible changes added to a correctly classified input that make a DNN misclassify. While there is a large amount of work on generating adversarial perturbations (Szegedy et al., 2013; Goodfellow et al., 2014; Moosavi-Dezfooli et al., 2016; Madry et al., 2017; Carlini & Wagner, 2017; Xiao et al., 2018a; Dong et al., 2018; Croce & Hein, 2019; Wang et al., 2019; Zheng et al., 2019; Andriushchenko et al., 2019; Tramèr et al., 2020), the threat model considered by these works cannot be realized in practical scenarios. This is because the threat model depends upon unrealistic assumptions about the power of the attacker: the attacker knows the DNN input in advance, generates input-specific perturbations in real-time and exactly combines the perturbation with the input before being processed by the DNN.
Practically feasible adversarial perturbations. In this work, we consider a more practical adversary to reveal real-world vulnerabilities of state-of-the-art DNNs. We assume that the attacker (i) does not know the DNN inputs in advance, (ii) can only transmit additive adversarial perturbations, and (iii) their transmitted perturbations are susceptible to modification due to real-world effects. Examples of attacks in our threat model include adding stickers to the cameras for fooling image classifiers (Li et al., 2019b) or transmitting perturbations over the air for deceiving audio classifiers (Li et al., 2019a). Note that this threat model is distinct from directly generating adversarial examples (Athalye et al., 2018) which require access to the original input.
The first two requirements in our threat model can be fulfilled by generating Universal Adversarial Perturbations (UAPs) (Moosavi-Dezfooli et al., 2017). Here the attacker can train a single adversarial perturbation that has a high probability of being adversarial on all inputs in the training distribution. However, as our experimental results show, the generated UAPs need to be combined with the DNN inputs precisely, otherwise they fail to remain adversarial. In practice, changes to UAPs are likely due to real-world effects. For example, the stickers applied to a camera can undergo changes in contrast due to weather conditions or the transmitted perturbation in audio can change due to noise in the transmission channel. This non-robustness reduces the efficiency of practical attacks created with existing methods (Moosavi-Dezfooli et al., 2017; Shafahi et al., 2020; Li et al., 2019b;a).
 Figure 1: Robust UAPs (left) cause a classier to misclassify on most of the data distribution even after transformations are applied on them. Standard UAPs (right) are not robust to transformations and have a low probability of remaining UAPs after transformation.
This work: Robust UAPs. To overcome the above limitation, we propose the concept of robust UAPs: perturbations that have a high probability of remaining adversarial on inputs in the training distribution even after applying a set of real-world transformations. The optimization problem in generating robust UAPs (Moosavi-Dezfooli et al., 2017) is the main challenge as we are looking for perturbations that are adversarial for a set of inputs as well as to transformations applied to the perturbations. To address this challenge, we make the following main contributions:
• We introduce Robust UAPs and formulate their generation as an optimization problem. • We design a new method for constructing robust UAPs. Our method is general and works for any transformations generated by composing arbitrary sub-differentiable transformation functions. We provide an algorithm for computing provable probabilistic bounds on the robustness of our UAPs against many practical transformations. • We perform an extensive evaluation of the effectiveness of our method, RobustUAP, on stateof-the-art models for the popular CIFAR-10 (Krizhevsky et al., 2009) and ILSVRC 2012 (Deng et al., 2009) datasets. We compare the robustness of our UAPs under compositions of challenging real-world transformations, such as rotation, contrast change, etc. We show that on both datasets, the UAPs generated by RobustUAP are significantly more robust, achieving up to $2 3 \%$ more robustness, than the UAPs generated from the baselines.
Our work is complementary to the development of real-world attacks (Li et al., $2 0 1 9 \mathrm { a } ; \mathrm { b } )$ ) in various domains, which require modeling how the universal perturbations change during transmission. RobustUAP can improve the efficiency of such attacks by constructing perturbations that are more robust against domain-specific, real-world transformations than possible with existing algorithms (Moosavi-Dezfooli et al., 2017; Shafahi et al., 2020; Li et al., 2019a;b).
# 2 BACKGROUND
In this section, we provide necessary background definitions and notation for our work.
Adversarial Examples and Perturbations. An adversarial example is a misclassified data point that is close (in some norm) to a correctly classified data point (Goodfellow et al., 2014; Madry et al., 2017; Carlini & Wagner, 2017). Let $\mu \doteq \mathbb { R } ^ { d }$ be the input data distribution, $\mathbf { x } \in \mu$ be an input point with the corresponding true label $y \in \mathbb { R }$ , and $f : \mathbb { R } ^ { \bar { d } } \mathbb { R } ^ { d ^ { \prime } }$ be our target classifier. For ease of notation, we define $f _ { k } ( { \bf x } )$ to be the $k ^ { \mathrm { { t h } } }$ element of $f ( \mathbf { x } )$ and allow ${ \hat { f } } ( \mathbf { x } ) = \arg \operatorname* { m a x } _ { k } f _ { k } ( \mathbf { x } )$ to directly refer to the classification label. We use $\mathbf { v }$ to reference image specific perturbations and $\mathbf { u }$ to reference universal adversarial perturbations, $\mathbf { v _ { r } }$ and $\mathbf { u _ { r } }$ refer to the robust variants and will be defined in Sec. 3. We now formally define an adversarial example.
Definition 2.1. Given a correctly classified point $\mathbf { x }$ , a distance function $d ( \cdot , \cdot ) : \mathbb { R } ^ { d } \times \mathbb { R } ^ { d } \to \mathbb { R }$ , and bound $\epsilon \in \mathbb { R }$ , $\mathbf { x } ^ { \prime }$ is an adversarial example iff $d ( { \bf x } ^ { \prime } , { \bf x } ) < \epsilon$ and $\hat { f } ( { \bf x } ^ { \prime } ) \neq y$ .
In this paper, we consider examples $\mathbf { x } ^ { \prime }$ generated as $\mathbf { x } ^ { \prime } = \mathbf { x } + \mathbf { v }$ where $\mathbf { v }$ is an adversarial perturbation.
Universal Adversarial Perturbations. UAPs are single vector, input-agnostic perturbations (Moosavi-Dezfooli et al., 2017). They differ from traditional adversarial attacks, which create perturbations dependent on each input sample. To measure UAP performance, we introduce the notion of universal adversarial success rate, which measures the probability that a perturbation $\mathbf { u }$ when added to $\mathbf { x }$ , sampled from $\mu$ , causes a change in classification under $f$ .
Definition 2.2. Given a data distribution $\mu$ , and perturbation u, universal adversarial success rate $\operatorname { A S R } _ { U }$ for $\mathbf { u }$ , is defined as
$$\operatorname { A S R } _ { U } ( f , \mu , { \mathbf { u } } ) = \underset { { \mathbf { x } } \sim \mu } { P } \left( \hat { f } ( { \mathbf { x } } + { \mathbf { u } } ) \neq \hat { f } ( { \mathbf { x } } ) \right)$$
Using Definition 2.2, we formally define a UAP.
Definition 2.3. A universal adversarial perturbation is a vector $\mathbf { u } \in \mathbb { R } ^ { d }$ which, when added to almost all datapoints in $\mu$ causes the classifier $f$ to misclassify. Formally, given $\gamma$ , a bound on universal ASR, and $l _ { p }$ -norm with corresponding bound $\epsilon$ , $\mathbf { u }$ is a UAP iff $\mathrm { A S R } _ { U } ( f , \mu , { \bf u } ) > \gamma$ and $| | \mathbf { u } | | _ { p } < \epsilon$ .
In general, if the additive perturbations have small $l _ { p }$ -norm , then they look like noise and do not affect the semantic content of the image. For ease of notation in later parts of the paper, we can also pose the construction of UAPs as an expectation minimization problem:
$$\underset { u } { \arg \operatorname* { m i n } } \mathbb { E } _ { \mathbf { x } \sim \mu } [ \delta ( \hat { f } ( \mathbf { x } + \mathbf { u } ) , \hat { f } ( \mathbf { x } ) ) ] \mathrm { s . t . } | | \mathbf { u } | | _ { p } < \epsilon$$
where $\delta$ is the Kronecker Delta function (Agarwal, 2013).
# 3 ROBUST UNIVERSAL ADVERSARIAL PERTURBATIONS
In this section, we will define the optimization problem for generating robust UAPs. We first define transformation sets and neighborhoods.
Definition 3.1. A transformation, $\tau$ , is a composition of bijective sub-differentiable transformation functions. A transformation set, $T$ , is a set of distinct transformations. A point $\mathbf { v } ^ { \prime }$ is in the neighborhood $N _ { T } ( \mathbf { v } )$ , of $\mathbf { v }$ , if there is a transform in $T$ that maps $\mathbf { v }$ to $\mathbf { v } ^ { \prime }$ . Formally,
$$\mathbf { v } ^ { \prime } \in N _ { T } ( \mathbf { v } ) \iff \exists \tau \in T { \mathrm { ~ s . t . ~ } } \tau ( \mathbf { v } ) = \mathbf { v } ^ { \prime }$$
Example 3.2. Let $T$ be the set of all transformations represented by a rotation of $\pm 3 0 ^ { \circ }$ , scaling of up to a factor of 2, and a translation of up to $\pm 2$ pixels, in this case one $\tau \in T$ could be {rotation of $8 ^ { \circ }$ , scaling a factor of 1.2, and translation of -1.3} in that order and $N _ { T } ( \mathbf { v } )$ would include any point that can be obtained by applying one of the transformations from $T$ on $\mathbf { v }$ .
In order to define robust UAPs we introduce robust universal adversarial success rate.
Definition 3.3. Given a data distribution $\mu$ , transformation set $T$ , universal ASR level $\gamma$ , bound $\epsilon$ on $l _ { p }$ -norm, and perturbation $\mathbf { u _ { r } }$ , robust universal adversarial success rate, $\operatorname { A S R } _ { R }$ , is defined as,
$$\mathbf { A S R } _ { R } ( f , \mu , T , \gamma , \mathbf { u _ { r } } ) = \underset { \mathbf { u } _ { r } ^ { \prime } \sim N _ { T } ( \mathbf { u _ { r } } ) } { \cal P } ( \mathbf { A S R } _ { U } ( f , \mu , \mathbf { u } _ { r } ^ { \prime } ) > \gamma \land | | \mathbf { u } _ { \mathbf { r } } ^ { \prime } | | _ { p } < \epsilon )$$
The robust universal adversarial success rate measures the probability that a neighbor of $\mathbf { u _ { r } }$ is also an UAP on $\mu$ , i.e. after transformation it maintains high universal ASR. We note that even though $| | \mathbf { u } _ { \mathbf { r } } | | _ { p } \leq \epsilon$ , it can happen that a ${ \bf u } _ { \bf r } ^ { \prime } \in \ d { \cal N } _ { T } ( { \bf u } _ { \bf r } )$ has $| | \mathbf { u } _ { \mathbf { r } } ^ { \prime } | | _ { p } > \epsilon$ , this is particularly true for the semantic transformations considered in this work. Therefore, we require that the norm of $\mathbf { u } _ { \mathbf { r } } ^ { \prime }$ is small.
Using Definition 3.3 we can now formally define a robust UAP.
Definition 3.4. A robust universal adversarial perturbation, $\mathbf { u _ { r } }$ , is one which most points within a neighborhood of $\mathbf { u _ { r } }$ when added to most points in $\mu$ fool the classifier, $f . \mathbf { u _ { r } }$ satisfies $\bar { | } | \mathbf { u _ { r } } | | _ { p } < \epsilon$ and $\mathrm { A S R } _ { R } ( f , \mu , T , \gamma , \mathbf { u _ { r } } ) > \zeta$ .
In order to construct robust UAPs, we can pose the following expectation minimization problem:
$$\underset { \mathbf { u } _ { \mathbf { r } } } { \arg \operatorname* { m i n } } \ \underset { \mathbf { u } _ { \mathbf { r } } ^ { \prime } \in N _ { T } ( \mathbf { u } _ { \mathbf { r } } ) } { \mathbb { E } } [ I ( | | \mathbf { u } _ { \mathbf { r } } ^ { \prime } | | < \epsilon ) \times \underset { \mathbf { x } \sim \mu } { \mathbb { E } } [ \delta ( \hat { f } ( \mathbf { x } + \mathbf { u } _ { \mathbf { r } } ^ { \prime } ) , \hat { f } ( \mathbf { x } ) ) ] ] \ \mathrm { s . t . } \ | | \mathbf { u } _ { \mathbf { r } } | | _ { p } < \epsilon$$
Here $I : \mathbb { R } ^ { d } \mathbb { R }$ denotes an indicator function. The inner expectation represents the UAP condition for the transformed perturbation $\mathbf { u } _ { \mathbf { r } } ^ { \prime }$ while the outer expectation represents the neighborhood robustness condition. Solving Equation 5 requires computing $\mathbf { u _ { r } }$ which minimizes the expectation over the transformation set and data distribution. This composition makes it computationally harder than minimizing over only the transformation set, as in EOT (Athalye et al., 2018), or than minimizing over only the data distribution, as done for standard UAP (Moosavi-Dezfooli et al., 2017).
# 4 GENERATING ROBUST UNIVERSAL ADVERSARIAL PERTURBATIONS
In this section, we will discuss our approach for optimizing Equation 5 to generate UAPs robust to transformations generated by a composition of arbitrary sub-differentiable transformation functions. At a high level, the objective can be seen as gluing the outer expectation, a EOT objective over the transformations applied on the perturbation, with the inner expectation, a UAP objective over the input data distribution. We first describe intuitive baselines for optimizing Equation 5 and then present our new algorithm, RobustUAP.
# 4.1 STOCHASTIC GRADIENT DESCENT
The first baseline directly solves Equation 5 using gradient descent. Since we are solving a constrained optimization problem, we cannot use gradient descent directly. Instead, we can solve the Lagrangianrelaxed form of the problem as in (Carlini & Wagner, 2017; Athalye et al., 2018).
$$\underset { \mathbf { u } _ { \mathbf { r } } } { \arg \operatorname* { m i n } } \ \underset { \mathbf { u } _ { \mathbf { r } } ^ { \prime } \in N _ { T } ( \mathbf { u } _ { \mathbf { r } } ) } { \mathbb { E } } [ I ( | | \mathbf { u } _ { \mathbf { r } } ^ { \prime } | | < \epsilon ) \times \underset { \mathbf { x } \sim \mu } { \mathbb { E } } [ \delta ( \hat { f } ( \mathbf { x } + \mathbf { u } _ { \mathbf { r } } ^ { \prime } ) , \hat { f } ( \mathbf { x } ) ) ] ] - \lambda | | \mathbf { u } _ { \mathbf { r } } | | _ { p }$$
We use a momentum based Stochastic Gradient Descent (SGD) method for solving Equation 6. Shafahi et al. (2020) suggests that this is an effective method for generating standard UAPs. In order to implement this, we replace the Kronecker Delta function with a loss function, $L$ . We iteratively converge towards the inner expectation by computing it in batches, and towards the outer expectation by sampling a large number of transformations. Given that we would like to estimate on a batch, $\hat { \mathbf { x } } \subset \mu$ , and a random set of transformations sampled from $T$ , $\hat { \tau } \subset T$ , we can approximate Equation 6:
$$\frac { I ( | | \hat { \tau } _ { j } ( \mathbf { u _ { r } } ) | | < \epsilon ) } { | \hat { \mathbf { x } } | \times | \hat { \tau } | } \sum _ { i = 1 } ^ { | \hat { \mathbf { x } } | } \sum _ { j = 1 } ^ { | \hat { \tau } | } L [ f ( \hat { \mathbf { x } } _ { \mathbf { i } } + \hat { \tau } _ { j } ( \mathbf { u _ { r } } ) ) , f ( \hat { \mathbf { x } } _ { \mathbf { i } } ) ] - \lambda | | \mathbf { u _ { r } } | | _ { p }$$
Our final algorithm is in Appendix C.
# 4.2 STANDARD UAP ALGORITHM WITH ROBUST ADVERSARIAL PERTURBATIONS
For our second baseline, we leverage the standard UAP algorithm from Moosavi-Dezfooli et al. (2017) (see Appendix D for the algorithm). The standard UAP algorithm iterates over the entire training dataset and at each input, $\mathbf { x _ { i } }$ , computes the smallest additive change, $\Delta \mathbf { u }$ , to the current perturbation, u, that would make $\mathbf { u } + \Delta \mathbf { u }$ an adversarial perturbation for $\mathbf { x _ { i } }$ . Intuitively, over time the algorithm will approach a perturbation that works on most inputs in the training dataset. This approach works by computing robust adversarial perturbations rather than standard adversarial perturbations. At each point $\mathbf { x _ { i } }$ , we compute the smallest additive change, $\Delta \mathbf { u _ { r } }$ , to the current robust adversarial perturbation, $\mathbf { u _ { r } }$ , that would make $\mathbf { u } _ { \mathbf { r } } + \Delta \mathbf { u } _ { \mathbf { r } }$ a robust adversarial perturbation for $\mathbf { x _ { i } }$ .
We search for robust adversarial perturbations by optimizing the expectation that a point in the neighborhood of $\mathbf { v _ { r } }$ is adversarial while restricting the perturbation to an $l _ { p }$ norm of $\epsilon$ . We formulate this as the following minimization problem:
$$\underset { \mathbf { v _ { r } } } { \arg \operatorname* { m i n } } \quad \underset { \mathbf { v _ { r } ^ { \prime } } \in { \cal { W } } _ { T } ( \mathbf { v _ { r } } ) } { \mathbb { E } } [ I ( | | \mathbf { v _ { r } ^ { \prime } } | | < \epsilon ) \times \delta ( \hat { f } ( \mathbf { x } + \mathbf { v } _ { \mathbf { r } } ^ { \prime } ) , \hat { f } ( \mathbf { x } ) ) ] \mathrm { ~ s . t . ~ } | | \mathbf { v _ { r } } | | _ { p } < \epsilon$$
# 4.3 ROBUST UAP ALGORITHM
The baseline algorithms have two fundamental limitations: (i) they rely on random sampling over the symbolic transformation region, but the sampling strategy does not explicitly try to maximize the robustness of the generated UAP over the entire symbolic region, and (ii) they do not estimate robustness on unsampled transformations. As a result, the baselines yield suboptimal UAPs (as confirmed by our experiments below). To overcome these fundamental limitations, we create a method to compute probabilistic bounds for expected robustness on an entire symbolic region. We leverage this method for approximating expected robustness in a new algorithm to generate robust UAPs with guarantees. We make a simplifying assumption that ${ { N } _ { T } } ( { \bf { u } } _ { \bf { r } } )$ has a well defined, sampleable probability density function (PDF) as we cannot bound robustness for arbitrary transformations. Our experiments show that even though our assumptions do not hold for all the transformation sets considered in this work, they significantly improve the robustness of our generated UAPs. Our approximation of the expected robustness relies on the following theoretical result:
Theorem 4.1. Given a perturbation $\mathbf { u _ { r } }$ , a neural network $f _ { i }$ , a finite set of inputs $\mathbf { X }$ , a set of transformations $T$ , and minimum universal adversarial success rate $\gamma ~ \in ~ \mathbb { R }$ . Let $p ( \gamma ) =$ $P _ { \mathbf { u } _ { \mathbf { r } } ^ { \prime } \sim N _ { T } ( \mathbf { u } _ { \mathbf { r } } ) } ( A S R _ { U } ( f , \mathbf { X } , \mathbf { u } _ { \mathbf { r } } ^ { \prime } ) > \gamma )$ . For $i \in { 1 \dots n }$ , let ${ \bf u } _ { \bf r } ^ { \bf i } \sim N _ { T } ( { \bf u } _ { \bf r } )$ be random variables with a well defined PDF and $I : \mathbb { R } ^ { d } \mathbb { R }$ be the indicator function, let
$$\hat { p } _ { n } ( \gamma ) = \frac { 1 } { n } \sum _ { i = 1 } ^ { n } I ( A S R _ { U } ( f , \mathbf { X } , \mathbf { u } _ { \mathbf { r } } ^ { \mathbf { i } } ) > \gamma )$$
For accura0 and 1. If $\psi \in ( 0 , 1 )$ , and confidence, $\phi \in ( 0 , 1 )$ , where $( 0 , 1 )$ is the open interval between $\begin{array} { r } { \dot { n } \geq \frac { 1 } { 2 \psi ^ { 2 } } \ln \frac { 2 } { \phi } } \end{array}$
$$P ( | \hat { p } _ { n } ( \gamma ) - p ( \gamma ) | < \psi ) \geq 1 - \phi$$
Proof. The bound on $n$ is derived via the Chernoff inequality applied to $\hat { p } _ { n } ( \gamma )$ and $\mathbb { E } [ \hat { p } _ { n } ( \gamma ) ] =$ $p ( \gamma )$ (Chernoff, 1952; Alippi, 2014). Equation 10 holds since computing universal ASR is Lebesgue measurable over the data distribution and since we assume ${ { N } _ { T } } ( { \bf { u } } _ { \bf { r } } )$ has a well defined PDF. $\boxed { \begin{array} { r l } \end{array} }$
Theorem 4.1 states that with enough samples from the neighborhood of a perturbation, $\mathbf { u _ { r } }$ , the adversarial success rate of $\mathbf { u _ { r } }$ on the entire neighborhood is arbitrarily close to the adversarial success rate of $\mathbf { u _ { r } }$ on sampled transformations with probability greater than $1 - \phi$ . One key observation is that the Chernoff bound is independent of the dimensionality of the sample space which allows us to efficiently apply this result to high-dimensional transformation set provided they have a well-defined PDF (e.g., $L _ { \infty }$ -ball) and obtain provable bounds on the expected robustness. For the combinations of semantic transformations, such as rotation, translation, etc. used in the experiment section the neighborhood does not have a well-defined PDF, thus we uniformly sample the parameter space of each transformation to produce a point in the neighborhood. We believe uniformly sampling the parameter space is a realistic approximation of real-world effects.
Leveraging Theorem 4.1, we create EstimateRobustness which given accuracy, $\psi$ , and confidence, $\phi$ , returns the robust adversarial success rate on a finite set of inputs with probabilistic robustness guarantees under the assumptions of Theorem 4.1. The pseudocode for EstimateRobustness is in Algorithm 1
# Algorithm 1 EstimateRobustness
Our algorithm: RobustUAP. We leverage Theorem 4.1 and Algorithm 1 to develop RobustUAP, the pseudocode for which is seen in Algorithm 2. Similar to the SGD baseline, we approximate the expectation in Equation 5 in batches. We start by sampling transformations from the PDF of the neighborhood. We set the number of transformations, $n$ , based on Theorem 4.1 to satisfy the desired confidence level and accuracy. For each gradient step, we compute the mean loss over the current batch and set of sampled transforms (line 8). For each set of batch and sampled transformations, instead of making a single gradient update like SGD, we use Projected Gradient Descent (PGD) to iteratively compute a more robust update to the universal perturbation and end only when the estimated robustness on the batch satisfies a given threshold (line 10). At the end of each epoch, we check the robustness across the entire training set and transformation space using EstimateRobustness and stop when we have reached the desired performance (line 14).
# Algorithm 2 Robust UAP Algorithm
1: Init $\begin{array} { r } { \mathbf { u } _ { \mathbf { r } } 0 , n \lceil \frac { 1 } { 2 \psi ^ { 2 } } \ln \frac { 2 } { \phi } \rceil } \end{array}$ $i = 1 \dots n$ $\tau _ { i } \sim T$ 3: repeat 4: for $\mathbf { B } \subset \mathbf { X }$ do 5: if EstimateRobustnes $\mathbf { \Phi } _ { \mathsf { S } } ( f , \mathbf { B } , T , \gamma , \mathbf { u _ { r } } , \psi , \phi ) < \zeta$ then 6: $\Delta \mathbf { u _ { r } } \gets 0$ 7: repeat 8: Compute $\begin{array} { r } { L _ { \mathbf { B } , \tau } = \frac { 1 } { | \mathbf { B } | \times n } \sum _ { i = 1 } ^ { | \mathbf { B } | } \sum _ { j = 1 } ^ { n } L [ f ( \mathbf { B _ { i } } + \tau _ { j } ( \mathbf { u _ { r } } + \Delta \mathbf { u _ { r } } ) ) , f ( \mathbf { B _ { i } } ) ] } \end{array}$ 9: $\Delta \mathbf { u } _ { \mathbf { r } } = \mathcal { P } _ { p , \epsilon } ( \Delta \mathbf { u } _ { \mathbf { r } } + \alpha \mathrm { s i g n } ( \nabla L _ { \mathbf { B } , \tau } ) )$ 10: until EstimateRobustnes $\mathrm { s } ( f , \mathbf { B } , T , \gamma , \mathbf { u _ { r } } + \Delta \mathbf { u _ { r } } , \psi , \phi ) < \zeta$ 11: Update the perturbation with projection: $\mathbf { u _ { r } } \gets \mathcal { P } _ { p , \epsilon } ( \mathbf { u _ { r } } + \Delta \mathbf { u _ { r } } )$ 12: end if 13: end for 14: until EstimateRobustne $\mathfrak { s s } ( f , \mathbf { X } , T , \gamma , \mathbf { u _ { r } } , \psi , \phi ) < \zeta$
# 5 EVALUATION
Our RobustUAP framework is applicable to all transformation sets in a variety of domains. We empirically evaluate our method RobustUAP and three baseline approaches (SGD, StandardUAP_RP, StandardUAP (Moosavi-Dezfooli et al., 2017)) on popular models from the vision domain. We show that RobustUAP is more robust on both uniform random noise and compositions of real-world transformations such as rotation, scaling, etc.
Experimental evaluation. We consider two popular image recognition datasets: CIFAR10(Krizhevsky et al., 2009) and ILSVRC 2012(Deng et al., 2009). For CIFAR-10, we evaluate on the entire test set (1,000 images) and use a state-of-the-art pretrained VGG16 (Simonyan & Zisserman, 2014) network as the target classification model. For ILSVRC 2012, we evaluate on a random subset of the test set (1,000 images), and use a state-of-the-art Inception-v3 (Szegedy et al., 2016) network. We evaluate the robustness against uniform random noise as well as a composition of transformations from brightness/contrast, rotation, scaling, shearing, and translation. All experiments were performed on a desktop PC with a GeForce RTX(TM) 3090 GPU and a 16-core Intel(R) Core(TM) i9-9900KS CPU $\textcircled { a } 4 . 0 0 \mathrm { G H z }$ .
We report the results for $l _ { 2 }$ -norm with $\epsilon = 1 0 0$ for ILSVRC 2012 and $\epsilon = 1 0$ for CIFAR-10. These values were chosen based on the values presented by the original UAP paper (Moosavi-Dezfooli et al., 2017). We use an image normalization function given by our pretrained models and thus scaled our $\epsilon$ values accordingly. We note that the $\epsilon$ -values are significantly smaller than the image norms. Therefore the generated perturbation is imperceptible and does not affect the semantic content of the image. Due to the hardness of the optimization problem, for the same norm value, the effectiveness of a UAP is less than input-specific perturbations. We note that crafting input-specific perturbations requires making unrealistic assumptions about the power of the attacker as mentioned in the introduction and therefore we do not consider them part of our threat model which aims to generate practically feasible perturbations. We use $\psi = 0 . 0 5$ and $\phi = 0 . 0 5$ resulting in $n = 7 3 8$ for generating samples for our RobustUAP algorithm as well as reporting robust ASR in our evaluation. The UAPs are trained on 2,000 images, other parameters for evaluation are given in Appendix E.
# 5.1 ROBUSTNESS TO RANDOM NOISE
First, we show that our algorithm generates UAPs robust against uniform random noise. Here our neighborhood is defined as an $L _ { \infty }$ ball of radius $\epsilon$ around the perturbation. $U ( \epsilon )$ represents noise drawn uniformly from such a ball. Figure 2 shows the performance of each algorithm. For example, the RobustUAP algorithm achieves a $\operatorname { A S R } _ { U }$ of 0.9 greater than $9 7 \%$ of the time under $U ( 0 . { \bar { 1 } } )$ on CIFAR-10, where all other algorithms achieve 0.9 at most $3 0 \%$ of the time. RobustUAP outperforms all other algorithms for both noise sizes. StandardUAP has a lower mean and higher variance in universal ASR and is much less robust to transformation. A table of Robust ASR results for $\gamma = 0 . 8$ can be seen in Appendix F. Our Robust ASR results are guaranteed to be $\pm 0 . 0 5$ from the actual result with a probability of $9 5 \%$ . For example, we estimate that RobustUAP has $\operatorname { A S R } _ { R }$ of $9 6 . 1 \%$ for U(0.3), we are guaranteed that the true robustness is $> 9 1 . 1 \%$ with a probability of $9 5 \%$ . Note that we get robustness guarantees from EstimateRobustness as our neighborhood has a well-defined PDF.
 Figure 2: For each method, a point $( x , y )$ in the corresponding line represents the percentage of sampled UAPs $( y \% )$ with Universal $\mathbf { A } \mathbf { S } \mathbf { R } > x$ for $U ( 0 . 1 )$ and $U ( 0 . 3 )$ on ILSVRC and CIFAR-10.
# 5.2 ROBUSTNESS TO SEMANTIC TRANSFORMATIONS
Next, we consider transformation sets generated by composing five popular semantic transformations in existing literature (Athalye et al., 2018; Balunovic et al., 2019): brightness/contrast, rotation, ´ scaling, shearing, and translation.
We use a variety of different compositions to show that our algorithm works under different conditions, and base our parameters for the transformations on (Balunovic et al., 2019). For our experiments, ´ $R ( \theta )$ corresponds to rotations with angles between $\pm \theta$ ; $T ( x , y )$ , to translations of $\pm x$ horizontally and $\pm y$ vertically; $S c ( p )$ to scaling the image between $\pm p \%$ ; $S h ( m )$ to shearing by shearing factor between $\pm m \%$ ; and $B ( \alpha , \beta )$ to changes in contrast between $\pm \alpha \%$ and brightness between $\pm \beta$ . Further details about these transformations can be seen in Appendix A. We consider compositions of different subsets and ranges of these transformations shown in Table 1 including composing all transformations together. The hardness of generating robust UAPs depends on the effect that the transformation set has on the UAP (i.e. random noise has a relatively small effect compared to rotation). The hardness also increases with the number of transformations in the composition as well as the range of parameters for each individual transformation. For example, generating robust UAPs is harder for the composition shown in the first and last row for ILSVRC 2012 in Table 1 compared to the second and third row. The same is true for generating a UAP robust to uniform random noise.
 Figure 3: For each method, a point $( x , y )$ in the corresponding line represents the percentage of sampled UAPs $( y \% )$ with Universal $\mathrm { A S R } > x$ for the different semantic transformations on ILSVRC.
Robust ASR $( \mathbf { A S R _ { R } } )$ ). Figure 3 shows performance of UAPs obtained by applying 738 randomly sampled transformations to the original UAPs generated by different methods on ILSVRC, similar graphs for CIFAR-10 can be found in Appendix G. The RobustUAP algorithm outperforms all others in each case, we observe that for these harder transformation sets StandardUAP loses its effectiveness completely. In Table 1 we compare robust universal adversarial success rate $\mathrm { A S R } _ { R }$ with $\gamma = 0 . 6$ , in other words, we are finding the percentage of sampled neighbors of the perturbation that are still UAPs with $6 0 \%$ effectiveness on the testing set. We provide average $\operatorname { A S R } _ { U }$ scores as well as $\mathrm { A S R } _ { R }$ for different $\gamma$ levels in Appendix $_ \mathrm { H }$ .
Our RobustUAP algorithm achieves at least $5 3 . 4 \%$ higher robust ASR when compared to the standard UAP algorithm on both datasets and the challenging transformation sets shown in Table 1. Furthermore, our RobustUAP algorithm significantly outperforms both robust baseline approaches. Except for the $T ( 2 , 2 )$ case which we observe to be the easiest, RobustUAP achieves at least $1 1 . 6 \%$ performance gain over the baselines. SGD is the best performing baseline and achieves high robust ASR on relatively easier transformation sets performing within $\bar { 1 } \%$ of RobustUAP on $T ( 2 , 2 )$ . On harder transformation sets, this gap widens considerably, see Table 1.
<table><tr><td>DATASET</td><td>TRANSFORMATION SET</td><td>STANDARD UAP</td><td>SGD</td><td>STANDARD UAP_RP</td><td>ROBUST UAP</td></tr><tr><td rowspan="4">ILSVRC 2012</td><td>R(20)</td><td>0.0%</td><td>69.9%</td><td>2.9%</td><td>93.2%</td></tr><tr><td>T(2,2)</td><td>35.9%</td><td>96.1%</td><td>38.8%</td><td>97.1%</td></tr><tr><td>Sc(5),R(5),B(5,0.01)</td><td>22.3%</td><td>85.4%</td><td>43.7%</td><td>96.1%</td></tr><tr><td>R(10),T(2,2), Sh(2),Sc(2),B(2,0.001)</td><td>0.0%</td><td>63.1%</td><td>2.9%</td><td>86.4%</td></tr><tr><td rowspan="3">CIFAR-10</td><td>R(30),B(2,0.001)</td><td>0.0%</td><td>64.1%</td><td>2.9%</td><td>75.7%</td></tr><tr><td>R(2),Sh(2)</td><td>42.7%</td><td>88.3%</td><td>52.4%</td><td>96.1%</td></tr><tr><td>R(10),T(2,2),Sh(2),Sc(2),B(2,0.001)</td><td>0.0%</td><td>58.3%</td><td>7.8%</td><td>79.6%</td></tr></table>
Table 1: Robust ASR of RobustUAP compared to the three baselines.
Visualization. We visualize UAPs generated with RobustUAP and StandardUAP transformed with random transformations from $\bar { R ( 1 0 ) } , \bar { T ( 2 , 2 ) } , S h ( 2 ) , S c ( 2 ) , \bar { B ( 2 , 0 . 0 0 1 ) }$ and added to images in ILSVRC 2012 in Figure 4. Our robust UAPs have a similar level of imperceptibility to standard UAPs and do not affect the semantic content of the images. Robust UAPs affect the model classification after transformation with high probability, unlike standard UAPs.
 Figure 4: Examples of perturbed images with labels. The top row is unperturbed ILSVRC 2012 test set images, the second row has a randomly transformed robust UAP added to it, and the bottom row has a randomly transformed standard UAP added to it. Labels calculated using Inception-v3.
We further visualize UAPs generated with our three robust algorithms on the same transformation set against a standard UAP generated on ILSVRC 2012 in Figure 5. We observe that UAPs generated by the StandardUAP algorithm resemble those generated by the StandardUAP_RP algorithm. We believe that this is due to the similarity in the workings of both algorithms. However, the two UAPs are not identical. Under our transformation set the center of the image is least likely to be perturbed so we observe StandardUAP_RP algorithm concentrates its budget towards the center. Both the RobustUAP and the SGD algorithm generate larger patterns distributed over the entire image.
# 5.3 ADDITIONAL EXPERIMENTS
In Appendix I we show how our robust UAPs compare to standard UAPs on the non-robust universal ASR metric. In Appendix J, we evaluate our methods on ResNet18 (He et al., 2015) and MobileNet (Howard et al., 2017) for CIFAR-10 and ILSVRC 2012 respectively. The results follow the same trends as those reported in Table 1. In Appendix H we provide the average $\operatorname { A S R } _ { U }$ achieved by all the algorithms and also provide $\operatorname { A S R } _ { R }$ computed with different values of $\gamma$ for the same transformation sets in Table 1. Finally, we provide runtimes for all algorithms in Appendix L.
 Figure 5: Comparison of UAPs generated with (a) StandardUAP, (b) RobustUAP, (c) StandardUAP_RP, and (d) RobustUAP on ILSVRC 2012.
# 6 RELATED WORK
In this section, we survey works closely related ours.
UAP Algorithms. Most works focusing on UAPs (Moosavi-Dezfooli et al., 2017; Mopuri et al., 2018; Zhang et al., 2020a; Khrulkov & Oseledets, 2018; Li et al., 2020; Akhtar et al., 2018; Hendrik Metzen et al., 2017; Zhang et al., 2020b) generate singular vectors and do not consider perturbation robustness. Bahramali et al. (2021) introduces a perturbation generator model (PGM) for the wireless domain which creates UAPs with random trigger patterns. They show that both adversarial training and noise subtracting defenses used in the wireless domain are highly effective in mitigating the effects of a single vector UAP attack; they further show that their method of generating a set of UAPs is an effective way for an attacker to circumvent these defenses. Although PGM provides a method for efficiently sampling unique UAPs, they do not train to be robust to real-world transformations. In contrast, our method enables efficient sampling of UAPs that are robust to transformations.
Robust Adversarial Examples. The following papers introduce notions of robustness under different viewpoints and environmental conditions for constructing realizable adversarial examples. This is a different threat model compared to the additive perturbations discussed in this paper. Luo et al. (2018) constructs adversarial examples which minimize human detectability, further introducing the idea of robustness for adversarial examples. They show that their attacks are robust against jpeg compression. Sharif et al. (2016) attack facial recognition systems by putting adversarial perturbations on glass frames. Their work demonstrates a successful physical attack under stable conditions and poses. Eykholt et al. (2018) proposes Robust Physical Perturbations $\mathrm { ( R P _ { 2 } ) }$ in order to show that adding graffiti on a stop sign can cause it to be misclassified in both simulations and in the real world. Athalye et al. (2018) introduce Expectation over Transformation (EOT) and use it to print real-world objects which are adversarial given a range of physical and environmental conditions.
Robust Adversarial Perturbations. Li et al. (2019a) generates music which affects a voice assistant based system from picking up its wake word. Li et al. (2019b) presents a method for generating a targeted adversarial sticker which changes an image classifier’s classification from one pre-specified class to another. Both of these methods rely on specific use cases and are tailored towards generating adversaries coming from strict distributions, e.g. (Li et al., 2019a) generates guitar music while (Li et al., 2019b) generates a small grid of dots. These works build on algorithms akin to our baseline approaches and are limited in scope to domain specific transformations. Our work provides a framework for improving robustness against a wide range of transformations in diverse domains and can be leveraged for improving the effectiveness of these attacks.
# 7 CONCLUSION
In this paper, we demonstrate that standard UAPs are highly susceptible to transformations, i.e. they fail to be universally adversarial under transformation. We propose a new method, RobustUAP to generate robust UAPs based upon obtaining probabilistic bounds on UAP robustness across an entire transformation space. Our experiments provide empirical evidence that this principled approach generates UAPs that are practically more robust under a wide range of transformation sets than those from the baseline methods.
# REFERENCES
Ossama Abdel-Hamid, Abdel-rahman Mohamed, Hui Jiang, Li Deng, Gerald Penn, and Dong Yu. Convolutional neural networks for speech recognition. IEEE/ACM Transactions on audio, speech, and language processing, 22(10):1533–1545, 2014.
DC Agarwal. Tensor Calculus and Riemannian Geometry. Krishna Prakashan Media, 2013.
Naveed Akhtar, Jian Liu, and Ajmal Mian. Defense against universal adversarial perturbations. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 3389–3398, 2018.
Cesare Alippi. Intelligence for embedded systems. Springer, 2014.
Maksym Andriushchenko, Francesco Croce, Nicolas Flammarion, and Matthias Hein. Square attack: a query-efficient black-box adversarial attack via random search, 2019.
Anish Athalye, Logan Engstrom, Andrew Ilyas, and Kevin Kwok. Synthesizing robust adversarial examples. In International conference on machine learning, pp. 284–293. PMLR, 2018.
Alireza Bahramali, Milad Nasr, Amir Houmansadr, Dennis Goeckel, and Don Towsley. Robust adversarial attacks against dnn-based wireless communication systems. arXiv preprint arXiv:2102.00918, 2021.
Mislav Balunovic, Maximilian Baader, Gagandeep Singh, Timon Gehr, and Martin Vechev. Certifying ´ geometric robustness of neural networks. Advances in Neural Information Processing Systems 32, 2019.
Philipp Benz, Chaoning Zhang, Tooba Imtiaz, and In So Kweon. Double targeted universal adversarial perturbations. In Proceedings of the Asian Conference on Computer Vision, 2020.
Philipp Benz, Soomin Ham, Chaoning Zhang, Adil Karjauv, and In So Kweon. Adversarial robustness comparison of vision transformer and mlp-mixer to cnns. arXiv preprint arXiv:2110.02797, 2021.
Tom B Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language models are few-shot learners. arXiv preprint arXiv:2005.14165, 2020.
Nicholas Carlini and David Wagner. Towards evaluating the robustness of neural networks. In 2017 ieee symposium on security and privacy (sp), pp. 39–57. IEEE, 2017.
Herman Chernoff. A measure of asymptotic efficiency for tests of a hypothesis based on the sum of observations. The Annals of Mathematical Statistics, pp. 493–507, 1952.
Francesco Croce and Matthias Hein. Minimally distorted adversarial examples with a fast adaptive boundary attack, 2019.
Jia Deng, Wei Dong, Richard Socher, Li-Jia Li, Kai Li, and Li Fei-Fei. Imagenet: A large-scale hierarchical image database. In 2009 IEEE Conference on Computer Vision and Pattern Recognition, pp. 248–255, 2009. doi: 10.1109/CVPR.2009.5206848.
Yinpeng Dong, Fangzhou Liao, Tianyu Pang, Hang Su, Jun Zhu, Xiaolin Hu, and Jianguo Li. Boosting adversarial attacks with momentum. In IEEE Conference on Computer Vision and Pattern Recognition (CVPR), June 2018.
Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, et al. An image is worth 16x16 words: Transformers for image recognition at scale. arXiv preprint arXiv:2010.11929, 2020.
Andre Esteva, Brett Kuprel, Roberto A Novoa, Justin Ko, Susan M Swetter, Helen M Blau, and Sebastian Thrun. Dermatologist-level classification of skin cancer with deep neural networks. nature, 542(7639):115–118, 2017.
Andre Esteva, Alexandre Robicquet, Bharath Ramsundar, Volodymyr Kuleshov, Mark DePristo, Katherine Chou, Claire Cui, Greg Corrado, Sebastian Thrun, and Jeff Dean. A guide to deep learning in healthcare. Nature medicine, 25(1):24–29, 2019.
Kevin Eykholt, Ivan Evtimov, Earlence Fernandes, Bo Li, Amir Rahmati, Chaowei Xiao, Atul Prakash, Tadayoshi Kohno, and Dawn Song. Robust physical-world attacks on deep learning visual classification. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 1625–1634, 2018.
Ian J Goodfellow, Jonathon Shlens, and Christian Szegedy. Explaining and harnessing adversarial examples. arXiv preprint arXiv:1412.6572, 2014.
Kaiming He, X Zhang, S Ren, and J Sun. Deep residual learning for image recognition." computer vision and pattern recognition (2015). Google Scholar There is no corresponding record for this reference, pp. 770–778, 2015.
Jan Hendrik Metzen, Mummadi Chaithanya Kumar, Thomas Brox, and Volker Fischer. Universal adversarial perturbations against semantic image segmentation. In Proceedings of the IEEE international conference on computer vision, pp. 2755–2764, 2017.
Andrew G Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, and Hartwig Adam. Mobilenets: Efficient convolutional neural networks for mobile vision applications. arXiv preprint arXiv:1704.04861, 2017.
Max Jaderberg, Karen Simonyan, Andrew Zisserman, et al. Spatial transformer networks. Advances in neural information processing systems, 28:2017–2025, 2015.
Oguzhan Fatih Kar, Teresa Yeo, Andrei Atanov, and Amir Zamir. 3d common corruptions and data ˘ augmentation. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 18963–18974, 2022.
Valentin Khrulkov and Ivan Oseledets. Art of singular vectors and universal adversarial perturbations. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 8562– 8570, 2018.
Alex Krizhevsky, Geoffrey Hinton, et al. Learning multiple layers of features from tiny images, 2009.
Juncheng Li, Shuhui Qu, Xinjian Li, Joseph Szurley, J. Zico Kolter, and Florian Metze. Adversarial music: Real world audio adversary against wake-word detection system. In Proc. Neural Information Processing Systems (NeurIPS), pp. 11908–11918, 2019a.
Juncheng Li, Frank R. Schmidt, and J. Zico Kolter. Adversarial camera stickers: A physical camerabased attack on deep learning systems. In Proc. International Conference on Machine Learning, ICML, volume 97, pp. 3896–3904, 2019b.
Yingwei Li, Song Bai, Cihang Xie, Zhenyu Liao, Xiaohui Shen, and Alan Yuille. Regional homogeneity: Towards learning transferable universal adversarial perturbations against defenses. In European Conference on Computer Vision, pp. 795–813. Springer, 2020.
Bo Luo, Yannan Liu, Lingxiao Wei, and Qiang Xu. Towards imperceptible and robust adversarial example attacks against neural networks. In Thirty-second aaai conference on artificial intelligence, 2018.
Aleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras, and Adrian Vladu. Towards deep learning models resistant to adversarial attacks. arXiv preprint arXiv:1706.06083, 2017.
Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, and Pascal Frossard. Deepfool: a simple and accurate method to fool deep neural networks. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 2574–2582, 2016.
Seyed-Mohsen Moosavi-Dezfooli, Alhussein Fawzi, Omar Fawzi, and Pascal Frossard. Universal adversarial perturbations. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 1765–1773, 2017.
Konda Reddy Mopuri, Aditya Ganeshan, and R Venkatesh Babu. Generalizable data-free objective for crafting universal adversarial perturbations. IEEE transactions on pattern analysis and machine intelligence, 41(10):2452–2465, 2018.
Ali Shafahi, Mahyar Najibi, Zheng Xu, John Dickerson, Larry S Davis, and Tom Goldstein. Universal adversarial training. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 34, pp. 5636–5643, 2020.
Mahmood Sharif, Sruti Bhagavatula, Lujo Bauer, and Michael K Reiter. Accessorize to a crime: Real and stealthy attacks on state-of-the-art face recognition. In Proceedings of the 2016 acm sigsac conference on computer and communications security, pp. 1528–1540, 2016.
Karen Simonyan and Andrew Zisserman. Very deep convolutional networks for large-scale image recognition. arXiv preprint arXiv:1409.1556, 2014.
Christian Szegedy, Wojciech Zaremba, Ilya Sutskever, Joan Bruna, Dumitru Erhan, Ian Goodfellow, and Rob Fergus. Intriguing properties of neural networks. arXiv preprint arXiv:1312.6199, 2013.
Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jon Shlens, and Zbigniew Wojna. Rethinking the inception architecture for computer vision. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 2818–2826, 2016.
Florian Tramèr, Nicholas Carlini, Wieland Brendel, and Aleksander Madry. On adaptive attacks to adversarial example defenses. CoRR, abs/2002.08347, 2020.
Shiqi Wang, Yizheng Chen, Ahmed Abdou, and Suman Jana. Enhancing gradient-based attacks with symbolic intervals, 2019.
Chaowei Xiao, Bo Li, Jun yan Zhu, Warren He, Mingyan Liu, and Dawn Song. Generating adversarial examples with adversarial networks. In Proc. International Joint Conference on Artificial Intelligence (IJCAI-18), pp. 3905–3911, 2018a.
Chaowei Xiao, Jun-Yan Zhu, Bo Li, Warren He, Mingyan Liu, and Dawn Song. Spatially transformed adversarial examples. arXiv preprint arXiv:1801.02612, 2018b.
Chaoning Zhang, Philipp Benz, Tooba Imtiaz, and In So Kweon. Understanding adversarial examples from the mutual influence of images and perturbations. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 14521–14530, 2020a.
Chaoning Zhang, Philipp Benz, Tooba Imtiaz, and In-So Kweon. Cd-uap: Class discriminative universal adversarial perturbation. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 34, pp. 6754–6761, 2020b.
Tianhang Zheng, Changyou Chen, and Kui Ren. Distributionally adversarial attack. Proc. AAAI Conference on Artificial Intelligence, 33:2253–2260, 07 2019.
# APPENDIX
# A SEMANTIC TRANSFORMATIONS
In this section, we discuss the semantic transformations used in the paper. Brightness and contrast can be represented via bias $( \beta )$ and gain $( \alpha > 0 )$ ) parameters respectively. Formally, if $\mathbf { x }$ is the original image, then the transformed image, $\mathbf { x } ^ { \prime }$ , can be represented as
$$\mathbf { x } ^ { \prime } = \alpha \mathbf { x } + \beta$$
Rotation, scaling, shearing, and translation are all affine transformations acting on the coordinate system, $c$ , of the images instead of the pixel values, $\mathbf { x }$ . In order to recover the pixel values and differentiate over the transformation, we will need sub-differentiable interpolation, see Appendix B. For finite dimensions, affine transformations can be represented as a linear coordinate map where the original coordinates are multiplied by an invertible augmented matrix and then translated with additional bias vector. Below, we give the general form for an affine transformation given augmented matrix A, bias matrix $\mathbf { b }$ , and input coordinates $c$ . We can compute the output coordinates, $c ^ { \prime }$ , as
$${ \left[ \begin{array} { l } { \mathbf { c } ^ { \prime } } \\ { 1 } \end{array} \right] } = { \left[ \begin{array} { l l l l } { [ c c c | c ] } & { \mathbf { A } } & & { \mathbf { b } } \\ { 0 } & { \ldots } & { 0 } & { 1 } \end{array} \right] } { \left[ \begin{array} { l } { \mathbf { c } } \\ { 1 } \end{array} \right] }$$
Below, we give the augmented matrix A and additional bias matrix $\mathbf { b }$ for rotation, scaling, shearing, and translation.
Rotation, $R ( \theta )$ , by $\theta$ degrees:
$$\mathbf { A } = { \binom { \cos { \theta } } { \sin { \theta } } } \quad { \cos { \theta } } ^ { \prime } \mathbf { , b } = { \binom { 0 } { 0 } }$$
Scaling, $S c ( p )$ , by $p \%$ :
$$\mathbf { A } = \left( { \begin{array} { c c } { 1 + { \frac { p } { 1 0 0 } } } & { 0 } \\ { 0 } & { 1 + { \frac { p } { 1 0 0 } } } \end{array} } \right) , \mathbf { b } = \left( { \begin{array} { c } { 0 } \\ { 0 } \end{array} } \right)$$
Shearing, $S h ( m )$ , by shear factor $m \%$ :
$$\mathbf { A } = { \binom { 1 } { 0 } } \quad { \overset { 1 + { \frac { m } { 1 0 0 } } } { 1 } } ) , \mathbf { b } = { \binom { 0 } { 0 } }$$
Translation, $T ( x , y )$ , by $x$ pixels horizontally and $y$ pixels vertically:
$$\mathbf { A } = { \binom { 0 } { 0 } } \ { \begin{array} { l } { 0 } \\ { 0 } \end{array} } ) , \mathbf { b } = { \binom { x } { y } }$$
# B INTERPOLATION
Affine transformations may change a pixel’s integer coordinates into non-integer coordinates. Interpolation is typically used to ensure that the resulting image can be represented on a lattice (integer) pixel grid. For this paper, we will be using bilinear interpolation, a common interpolation method which achieves a good trade-off between accuracy and efficiency in practice and is commonly used in literature (Xiao et al., 2018b; Balunovic et al., 2019). Let ´ $x _ { i , j }$ , $x _ { i , j } ^ { \prime }$ represent the pixel value position -coordina $i , j$ fond the original and transform-coordinate of the pixel at image respectively. Let after transformation. We $c _ { i , j } ^ { \prime x } , c _ { i , j } ^ { \prime y }$ represent ther transformed $x$ $y$ $i , j$ image by summing over all pixels $n , m \in [ 1 \dots H ] \times [ 1 \dots W ]$ where $H$ and $W$ represent the height and width of the image.
$$x _ { i , j } ^ { \prime } = \sum _ { n } ^ { H } \sum _ { m } ^ { W } x _ { n , m } \operatorname* { m a x } ( 0 , 1 - | c _ { i , j } ^ { \prime x } - m | ) \operatorname* { m a x } ( 0 , 1 - | c _ { i , j } ^ { \prime y } - n | )$$
This interpolation can be computed for each channel in the image. While interpolation is typically not differentiable, in order to generate adversarial examples using standard techniques we need a differentiable version of interpolation. (Jaderberg et al., 2015) introduces differentiable image sampling. Their method works for any interpolation method as long as the (sub-)gradients can be defined with respect to $x , c ^ { \prime } { } _ { i , j }$ . For bilinear interpolation this becomes,
$$\frac { \partial x _ { i , j } ^ { \prime } } { \partial x _ { n , m } } = \sum _ { n } ^ { H } \sum _ { m } ^ { W } \operatorname* { m a x } ( 0 , 1 - | c ^ { \prime } _ { i , j } - m | ) \operatorname* { m a x } ( 0 , 1 - | c ^ { \prime } _ { i , j } - n | )$$
$$\frac { \partial x _ { i , j } ^ { \prime } } { \partial c _ { i , j } ^ { \prime \boldsymbol { x } } } = \sum _ { n } ^ { H } \sum _ { m } ^ { W } x _ { n , m } \operatorname* { m a x } ( 0 , 1 - | c _ { i , j } ^ { \prime \boldsymbol { y } } - n | ) \left\{ \begin{array} { l l } { 1 } & { \mathrm { i f ~ } m \ge | c _ { i , j } ^ { \prime \boldsymbol { x } } - m | } \\ { - 1 } & { \mathrm { i f ~ } m < | c _ { i , j } ^ { \prime \boldsymbol { x } } - m | } \\ { 0 } & { \mathrm { o t h e r w i s e } } \end{array} \right.$$
# C SGD ALGORITHM
Our SGD UAP algorithm is based on standard momentum based SGD while optimizing over the objective proposed in 5, the algorithm details can be seen in Algorithm 3.
# Algorithm 3 Stochastic Gradient Descent UAP Algorithm
1: Initialize $\mathbf { u _ { r } } \gets 0 , \Delta \mathbf { u _ { r } } \gets 0$ 2: repeat 3: for $\mathbf { B } \in \mathbf { X }$ do 4: 5: $\begin{array} { r } { \Delta \mathbf { u } _ { \mathbf { r } } \gets \alpha \Delta \mathbf { u } _ { \mathbf { r } } - \frac { \nu } { | \hat { \mathbf { x } } | \times | \hat { t } | } \sum _ { i = 1 } ^ { | \hat { \mathbf { x } } | } \sum _ { j = 1 } ^ { | \hat { t } | } \nabla L \big [ f \big ( \hat { \mathbf { x } } _ { \mathbf { i } } + \hat { t } _ { j } ( \mathbf { u } _ { \mathbf { r } } ) \big ) , f \big ( \hat { \mathbf { x } } _ { \mathbf { i } } \big ) \big ] } \end{array}$ $\hat { t } \subset T$ 6: Update the perturbation with projection: 7: $\mathbf { u } \gets \mathcal { P } _ { p , \epsilon } ( \mathbf { u _ { r } } + \Delta \mathbf { u _ { r } } )$ 8: end for 9: until $A S R _ { R } ( f , \mathbf { X } , T , \gamma , \mathbf { u _ { r } } ) < \zeta$
# D ITERATIVE UAP ALGORITHM
Moosavi-Dezfooli et al. (2017) introduces an iterative UAP algorithm, the algorithm can be seen in Algorithm 4.
1: Initialize $\mathbf u \gets 0$ 2: repeat 3: for $\mathbf { x _ { i } } \in \mathbf { X }$ do 4: if ${ \bar { \hat { f } } } ( \mathbf { x _ { i } } + \mathbf { u } ) = { \hat { f } } ( \mathbf { x _ { i } } )$ then 5: Compute minimal adversarial perturbation: 6: $\Delta \mathbf { u } \arg \operatorname* { m i n } _ { \mathbf { r } } | | \mathbf { r } | | _ { 2 }$ s.t. $\hat { f } ( \mathbf { x _ { i } } + \mathbf { u } + \mathbf { r } ) \neq \hat { f } ( \mathbf { x _ { i } } )$ 7: Update the perturbation with projection: 8: $\mathbf { u } \bar { \mathbf { \Omega } } \ll \mathcal { P } _ { p , \epsilon } ( \bar { \mathbf { u } } + \Delta \mathbf { u } )$ 9: end if 10: end for 11: until $A S R _ { U } ( f , { \bf X } , { \bf u } ) < \gamma$
# E EXPERIMENT PARAMETERS
In our experiments, we have capped all algorithms at 5 epochs or if they have achieved an $\mathrm { A S R } _ { R }$ of 0.95. The UAPs are trained with the same transformation set that they are evaluated on. For algorithms running PGD internally, we have capped the number of iterations to 40.
# F FURTHER EVALUATION OF UNIFORM NOISE
Results in Table 2. Table 2: Robust ASR with uniform random noise, $\gamma = 0 . 8$ .
<table><tr><td>DATASET</td><td>TRANSFORMATION SET</td><td>STANDARD UAP</td><td>SGD</td><td>STANDARD UAP_RP</td><td>ROBUST UAP</td></tr><tr><td>ILSVRC</td><td>U(0.1)</td><td>81.6%</td><td>94.2%</td><td>91.3%</td><td>99.0%</td></tr><tr><td>2012</td><td>U(0.3)</td><td>10.7%</td><td>68.9%</td><td>42.7%</td><td>96.1%</td></tr><tr><td>CIFAR-10</td><td>U(0.1)</td><td>66.0%</td><td>98.1%</td><td>96.1%</td><td>100%</td></tr><tr><td></td><td>U(0.3)</td><td>5.8%</td><td>96.1%</td><td>47.6%</td><td>100%</td></tr></table>
# G UAP PERFORMANCE AGAINST SEMANTIC TRANSFORMATIONS ON CIFAR-10
 Figure 6: For each method, a point $( x , y )$ in the corresponding line represents the percentage of sampled UAPs $( y \% )$ with Universal ASR $> x$ for the different semantic transformations on CIFAR10.
# H AVERAGE $\mathrm { A S R } _ { U }$ AND $\operatorname { A S R } _ { R }$ WITH DIFFERENT $\gamma$ ’ S
We provide additional metrics computed on the same set of transformations, datasets, and models as in Table 1. In Table 3, we present the Average $\operatorname { A S R } _ { U }$ rather than $\mathrm { A S R } _ { R }$ . The average shows us that our RobustUAP algorithm creates UAPs which after transformation on average are better UAPs than all other algorithms. We observe that the average shows us that even standard UAPs aren’t completely ineffective after transformation they just have a very low chance of being highly effective.
<table><tr><td>DATASET</td><td>TRANSFORMATION SET</td><td>STANDARD UAP</td><td>SGD</td><td>STANDARD UAP_RP</td><td>ROBUST UAP</td></tr><tr><td rowspan="4">ILSVRC 2012</td><td>R(20)</td><td>16.3%</td><td>71.5%</td><td>24.7%</td><td>81.3%</td></tr><tr><td>T(2,2)</td><td>52.6%</td><td>82.6%</td><td>55.4%</td><td>85.4%</td></tr><tr><td>Sc(5),R(5),B(5,0.01)</td><td>44.9%</td><td>76.3%</td><td>58.5%</td><td>82.2%</td></tr><tr><td>R(10),T(2,2),Sh(2),Sc(2),B(2,0.001)</td><td>13.6%</td><td>64.8%</td><td>29.0%</td><td>75.3%</td></tr><tr><td rowspan="3">CIFAR-10</td><td>R(30),B(2,0.001)</td><td>9.9%</td><td>66.8%</td><td>22.2%</td><td>73.4%</td></tr><tr><td>R(2),Sh(2)</td><td>57.1%</td><td>78.8%</td><td>61.2%</td><td>82.9%</td></tr><tr><td>R(10),T(2,2),Sh(2),Sc(2),B(2,0.001)</td><td>16.2%</td><td>61.2%</td><td>32.6%</td><td>76.4%</td></tr></table>
Table 3: Average Universal ASR of our Robust UAP algorithms and the standard UAP (MoosaviDezfooli et al., 2017) method.
In Table 4, we present $\operatorname { A S R } _ { R }$ computed at $\gamma = [ 0 . 5 , 0 . 7 ]$ rather than $\gamma = 0 . 6$ . This table shows a similar story to above, and shows that our algorithm produces better results under a variety of success thresholds.
<table><tr><td rowspan="3">DATASET</td><td rowspan="3">TRANSFORMATION SET</td><td colspan="2">STANDARD UAP</td><td colspan="2">SGD</td><td colspan="2">STANDARD</td><td colspan="2"></td><td rowspan="3">ROBUST UAP</td></tr><tr><td colspan="2">0.5</td><td colspan="2">0.5</td><td colspan="2">UAP_RP 0.5</td><td colspan="2"></td></tr><tr><td></td><td>0.7</td><td></td><td></td><td>0.7</td><td></td><td>0.7</td><td>0.5</td></tr><tr><td rowspan="4">ILSVRC 2012</td><td>R(20)</td><td>1.9%</td><td>0.0%</td><td></td><td>88.3%</td><td>58.3%</td><td>10.7%</td><td>1.0%</td><td></td><td>98.1% 76.7%</td></tr><tr><td>T(2,2)</td><td>51.5% 21.4% 100% 84.5% 57.3% 2</td><td></td><td></td><td></td><td></td><td></td><td>23.3%</td><td></td><td>100% 91.3%</td></tr><tr><td>Sc(5),R(5),B(5,0.01)</td><td>38.8%11.7%</td><td></td><td></td><td>96.1% 67.0%64.1%25.2%</td><td></td><td></td><td></td><td></td><td>99.0%87.4%</td></tr><tr><td>R(10),T(2,2), Sh(2), Sc(2),B(2,0.001)</td><td>1.9%</td><td>0.0%</td><td></td><td>82.5% 38.8%12.6%</td><td></td><td></td><td>1.0%</td><td>95.1%</td><td>59.2%</td></tr><tr><td rowspan="3">CIFAR-10 R(2), Sh(2)</td><td>R(30),B(2,0.001)</td><td>1.0%</td><td>0.0%</td><td></td><td>80.6% 43.7% 12.6%</td><td></td><td></td><td>1.0%</td><td>93.2%</td><td>49.5%</td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>62.1% 22.3% 96.1% 68.9% 68.0% 30.1% 99.0% 89.3%</td></tr><tr><td>R(10),T(2,2),Sh(2),Sc(2),B(2,0.001)</td><td>2.9%</td><td></td><td></td><td>0.0% 67.0% 38.8% 19.4%</td><td></td><td></td><td>1.0%</td><td></td><td>93.2% 55.3%</td></tr></table>
Table 4: Robust ASR of our Robust UAP algorithms and the standard UAP (Moosavi-Dezfooli et al., 2017) method with $\gamma = [ 0 . 5 , 0 . 7 ]$ . Table 5: Universal ASR of our Robust UAP algorithms and the standard UAP method.
<table><tr><td>DATASET</td><td>STANDARDUAP</td><td>SGD</td><td>STANDARDUAP_RP</td><td>ROBUS TUAP</td></tr><tr><td>ILSVRC 2012</td><td>95.5%</td><td>85.6%</td><td>82.3%</td><td>91.3%</td></tr><tr><td>CIFAR-10</td><td>96.2%</td><td>89.3%</td><td>84.0%</td><td>93.7%</td></tr></table>
# I COMPARISON ON NON-ROBUST UNIVERSAL ASR METRIC
We compare our robust UAPs to standard UAPs on the non-robust universal ASR metric, see Table 5. All robust UAPs are generated to be robust against $R ( 1 0 ) , T ( 2 , 2 ) , S h ( 2 ) , S c ( 2 ) , B ( 2 , 0 . 0 0 1 )$ . We observe that at the same $l _ { 2 }$ -norm all robust UAPs achieve a lower universal ASR than the standard UAP algorithm. This result is not too surprising as solving the optimization problem for robust UAP is significantly more difficult. We further observe that our RobustUAP algorithm is the most effective in comparison to the other robust baseline approaches.
# J ADDITIONAL MODELS
We also provide additional data on our methods evaluated on the same transformations and datasets but on different models. In this case, we use ResNet-18 (He et al., 2015) for CIFAR-10 and MobileNet (Howard et al., 2017) for ILSVRC 2012. Results can be seen in Table 6. We observe similar performance across models suggesting that the performance of the attacks is more directly tied to transformation set and dataset.
Table 6: Robust ASR on Resnet-18 for CIFAR-10 and MobileNet for ILSVRC 2012.
<table><tr><td>DATASET</td><td>MODEL</td><td>TRANSFORMATION SET</td><td>STANDARD UAP</td><td>SGD</td><td>STANDARD ROBUST UAP_RP</td><td>UAP</td></tr><tr><td rowspan="4">ILSVRC 2012</td><td rowspan="4">MOBILENET</td><td>R(20)</td><td>8.1%</td><td>71.2%</td><td>2.6%</td><td>85.0%</td></tr><tr><td>T(2,2)</td><td>40.9%</td><td>98.7%</td><td>54.3%</td><td>99.6%</td></tr><tr><td>Sc(5), R(5),B(5,0.01)</td><td>16.3%</td><td>94.5%</td><td>44.3%</td><td>96.3%</td></tr><tr><td>R(10),T(2,2), Sh(2),Sc(2),B(2,0.001)</td><td>4.1%</td><td>75.7%</td><td>8.6%</td><td>86.2%</td></tr><tr><td rowspan="3">CIFAR-10 RESNET-18</td><td rowspan="3"></td><td>R(30),B(2,0.001)</td><td>0.9%</td><td>67.8%</td><td>6.4%</td><td>74.9%</td></tr><tr><td>R(2),Sh(2)</td><td>49.9%</td><td>99.5%</td><td>49.1%</td><td>99.8%</td></tr><tr><td>R(10),T(2,2),Sh(2),Sc(2),B(2,0.001)</td><td>8.0%</td><td>70.8%</td><td>12.2%</td><td>83.8%</td></tr></table>
# K COMMON CORRUPTIONS
We also evaluate robust UAP against the 2D fog transformations in (Kar et al., 2022). We set the shift intensity of the fog to be 1 and train our robust UAPs to be robust against random fog perturbations. We observe similar results to the transformations we experiment with above. The graph of the results can be seen in Figure 7.
 Figure 7: For each method, a point $( x , y )$ in the corresponding line represents the percentage of sampled UAPs $( y \% )$ with Universal ASR $> x$ for the different semantic transformations on ILSVRC2012.
# L ALGORITHM RUNTIMES
We compare the average runtimes of the different methods on one of our most challenging $R ( 1 0 ) , \bar { T ( 2 , 2 ) } , S h ( 2 ) , \bar { S c } ( 2 ) , B ( 2 , 0 . 0 0 1 )$ transformation set on ILSVRC-2012 and $n = 7 3 8$ . The results are in Table 7. We observe that RobustUAP is the slowest algorithm and SGD is the fastest. RobustUAP uses EstimateRobustness in each loop and thus with high $n$ it requires much more time to compute. The extra computation enables Robust UAP to obtain better robustness than all baselines. On the same set of transformations and dataset we observe that one iteration of EstimateRobustness on the entire test set takes on average 19 minutes. When running EstimateRobustness in the RobustUAP loop, each call takes 36 seconds for a batch size of 32.
Table 7: Average Runtime for Robust UAP algorithms
<table><tr><td>ALGORITHM</td><td>TIME(MIN)</td></tr><tr><td>STANDARD UAP</td><td>37</td></tr><tr><td>SGD</td><td>32</td></tr><tr><td>STANDARD UAP_RP</td><td>43</td></tr><tr><td>ROBUST UAP</td><td>118</td></tr></table>
# M EFFECT OF COMPUTE TIME ON ROBUSTNESS
Previous sections highlight SGD as the most competitive algorithm to RobustUAP in terms of performance. However, in the previous section we note that SGD takes significantly less time to run. In this section, we investigate how RobustUAP performs with limited compute time as well as how SGD performs with increased runtime. We first add results to the ILSVRC 2012 part of Table 1 by also computing RobustUAP performance when limited to the same amount of time that SGD takes. Table 8 shows that RobustUAP outperforms SGD even when its compute time is limited with up to $9 \%$ more robustness on our most challenging transformation $R ( 1 0 ) , \bar { T } ( 2 , 2 ) , S h ( 2 ) , S c ( 2 ) , B ( \bar { 2 , } 0 . 0 0 1 ) .$ .
<table><tr><td>DATASET</td><td>TRANSFORMATION SET</td><td>SGD</td><td>ROBUST UAP</td><td>RESTRICTED ROBUST UAP</td></tr><tr><td rowspan="4">ILSVRC 2012</td><td>R(20)</td><td>69.9%</td><td>93.2%</td><td>72.9%</td></tr><tr><td>T(2,2)</td><td>96.1%</td><td>97.1%</td><td>96.9%</td></tr><tr><td>Sc(5),R(5),B(5,0.01)</td><td>85.4%</td><td>96.1%</td><td>86.3%</td></tr><tr><td>R(10),T(2,2),Sh(2),Sc(2),B(2,0.001)</td><td>63.1%</td><td>86.4%</td><td>72.0%</td></tr></table>
Table 8: Robust ASR of RobustUAP restricted to the same amount of compute time as SGD.
Next, we vary the number of SGD iterations. We compute the robust ASR on ILSVRC for robustness against $R ( 1 0 ) , T ( 2 , 2 ) , S h ( 2 ) , S c ( 2 ) , B ( 2 , 0 . 0 0 1 )$ . Figure 8, shows the robust ASR achieved by SGD over time, here we observe that SGD’s performance flatlines after a small number of iterations and seems to be unable to surpass about 65. Here SGD is allowed to continue to run past where it would usually stop (at around 250 iterations), in this experiment we allow it to go to 1250 iterations which is about the same amount of time that RobustUAP takes to run. RobustUAP is able to achieve a performance of 72 even when restricted to the amount of compute time of base SGD (It achieves 86.4 when unrestricted). These two results in combination show that RobustUAP is able to find more robust UAPs than SGD whose performance stabilizes.
 Figure 8: The Robust ASR with $\gamma = 0 . 6$ for SGD over time
# N ROBUSTNESS ON HOLD-OUT TRANSFORMATIONS
In this section, we measure the effectiveness of our robust UAPs against hold-out transformations. In this experiment, we learn a UAP which is robust to $R ( 5 )$ and obtain a robust ASR of 96.2 at $\gamma = 0 . 6$ . We then measure its effectiveness against $S c ( 5 )$ and get a robust ASR of 85.4, in contrast, a robust UAP trained directly to be robust to $S c ( 5 )$ obtains robust ASR of 98.1. Next, we measure the robustness of UAP trained against $R ( 5 )$ when subjected to transformations from $B ( 5 , 0 . 0 1 )$ . Here we get a robust ASR of 97.3, whereas a robust UAP trained to be robust to $B ( 5 , 0 . 0 1 )$ obtains a robust ASR of 99.2. Finally, we test the robust UAP on $R ( 5 ) , S c ( 5 ) , B ( 5 , 0 . 0 1 )$ and get a robust ASR of 83.1. Our previous results show that a UAP trained to be robust against these parameters directly can obtain a robust ASR of 96.1. In each case, our UAP maintains robustness on hold-out transformations but has lower performance compared to robust UAPs trained directly to be robust to those transformations.
# O TARGETED ATTACK
So far in this paper we have focused on untargeted attacks, i.e. attacks which aim to degrade the general performance of the model. Targeted attacks are also possible with both standard adversarial attack methods and universal adversarial perturbation methods. Here, we can simply turn our algorithm from untargeted to targeted by replacing the loss function. We would like to have target class, A, be classified as target class, B. Instead of maximizing the expected value of the cross entropy loss we can instead formulate the loss based on maximizing B while minimizing A similar to (Benz et al., 2020). For ILSVRC 2012, we randomly select a couple of target classes and perform this attack, for each of these cases, we train our robust UAP to be robust to $R ( 1 0 ) , T ( 2 , 2 ) , S h ( 2 ) , S c ( 2 ) , B ( 2 , 0 . 0 0 1 )$ . Table 9 shows our results for robust ASR with $\gamma = 0 . 6$ . We are measuring our robust ASR of turning class A into class B and observe similar results with RobustUAP being the most robust followed by SGD. It is also interesting to note that different random combinations lead to more or less success, i.e. it is easier to turn a dog into another dog than perfume into a padlock.
Table 9: Robust ASR of RobustUAP for target to target attack compared to the three baselines with $\gamma = 0 . 6$ .
<table><tr><td>DATASET</td><td>TARGET CLASS</td><td>STANDARD UAP</td><td>SGD</td><td>STANDARD UAP_RP</td><td>ROBUST UAP</td></tr><tr><td>ILSVRC-2012</td><td>TOY POODLE →→MALTESE DOG PERFUME-→PADLOCK</td><td>42.4% 0.0%</td><td>99.1% 63.8%</td><td>85.6% 5.1%</td><td>99.8% 76.4%</td></tr></table>
# P DATA EFFICIENCY
In this section, we will evaluate the data efficiency of RobustUAP. We use RobustUAP to generate UAPs robust to $R ( 1 0 ) , T ( 2 , 2 ) , S h ( 2 ) , S c ( 2 ) , B ( 2 , 0 . 0 0 1 )$ on ILSVRC-2012 with differing amounts of training data. The results can be seen in Figure 9. These results show that the algorithm is able to achieve good performance at 500 data points but continues to improve up to 4000 data points. After that it seems to stagnate.
 Figure 9: Robust ASR with $\gamma = 0 . 6$ for RobustUAP with differing amounts of training data
# Q TRANSFERABILITY
In this section, we will evaluate the transferability of RobustUAP. Previous works on UAPs (Moosavi-Dezfooli et al., 2017) show that UAPs are transferable across different models. Here, we will evaluate whether robust UAPs exhibit the same behavior for robustness. The robust UAPs studied here are generated with RobustUAP on $R ( 1 0 ) , T ( 2 , 2 ) , S h ( 2 ) , S c ( 2 ) , B ( 2 , 0 . 0 0 1 )$ for ILSVRC-2012 with $\gamma = 0 . 6$ . We use a variety of models: Inception-v3 (Szegedy et al., 2016), MobileNet (Howard et al., 2017), Inception-v3 trained to be robust on $R ( 2 0 )$ (InceptionR20), Inceptionv3 trained to be robust on horizontal flips (InceptionHF), and ViT (Dosovitskiy et al., 2020). Table 10 shows us that our robust UAPs are transferable between different architectures. Our results show that robust UAPs transfer their robustness properties between architectures and models. Ignoring ViT, on all of the Inception and MobileNet models, the generated UAPs maintain at least $65 \%$ robust ASR when transferred to each other. This transfer is less but still significant for ViT where it maintains at least $32 \%$ robustness when transferred to or from the other models.
Table 10: Robust ASR when UAP is learned on source model and transfered to target model.
<table><tr><td></td><td colspan="5">TARGET MODEL</td></tr><tr><td>SOURCE MODEL</td><td>INCEPTION</td><td>MOBILENET</td><td>INCEPTIONR20</td><td>INCEPTIONHF</td><td>VIT</td></tr><tr><td>INCEPTION</td><td>86.4%</td><td>65.2%</td><td>75.2%</td><td>78.5%</td><td>35.1%</td></tr><tr><td>MOBILENET</td><td>74.3%</td><td>86.2%</td><td>67.3%</td><td>68.6%</td><td>38.3%</td></tr><tr><td>INCEPTIONR20</td><td>80.1%</td><td>67.3%</td><td>81.3%</td><td>73.1%</td><td>32.0%</td></tr><tr><td>INCEPTIONHF</td><td>77.8%</td><td>70.9%</td><td>75.8%</td><td>83.8%</td><td>34.6%</td></tr><tr><td>VIT</td><td>41.2%</td><td>32.4%</td><td>43.2%</td><td>39.7%</td><td>88.5%</td></tr></table>
# R TRANSFORMER-BASED MODELS
Recently, transformers have become popular as a new architecture for deep learning models for computer vision tasks. In this section, we evaluate the effectiveness of robust UAPs against one such model, ViT (Dosovitskiy et al., 2020). Benz et al. (2021) has shown that standard UAPs are still effective against transformer based architectures. In Table 11 we can see that we get similar results compared to our results on Inception and MobileNet. This shows that our methods work against transformer based models as well.
<table><tr><td>DATASET</td><td>MODEL TRANSFORMATION SET</td><td></td><td>STANDARD UAP</td><td>SGD</td><td>STANDARD ROBUST UAP_RP</td><td>UAP</td></tr><tr><td>ILSVRC-2012 VIT</td><td></td><td>R(10),T(2,2),Sh(2),Sc(2),B(2,0.001)</td><td>2.0%</td><td>72.1%</td><td>12.9%</td><td>88.5%</td></tr></table>
Table 11: Robust ASR of RobustUAPcompared to the three baselines for ViT.
# S ROBUST UAPS AGAINST ROBUSTLY TRAINED NETWORKS
In this section, we are interested in seeing whether training networks to be robust against the same transformations that the UAP is trying to be robust against is helpful. For this, we trained two new Inception-v3 networks. Because of time limitations, we started with our base Inception-v3 network and fine-tuned it using data augmentations. For the first network InceptionR20, we augmented the data by adding random rotations within 20 degrees. For the second network InceptionHF, we augmented the data by adding horizontal flips. We then crafted UAPs robust against rotations and flips on InceptionR20 and InceptionHF respectively. The results can be seen in Table 12. We can compare the $R ( 2 0 )$ results to those from our normal inception network. We postulate that since the network has received some additional robustness training it is harder to attack, and thus we should see slightly lower robustness scores. However, it seems that training the network to be robust to $R ( 2 0 )$ does not significantly effect the ability to create robust UAPs. The horizontal flips seems like it might be too easy of a transformation as even standard UAP performs quite well for robust ASR.
<table><tr><td>DATASET</td><td>MODEL</td><td>TRANSFORMATION SET</td><td>STANDARD UAP</td><td>SGD</td><td>STANDARD UAP_RP</td><td>ROBUST UAP</td></tr><tr><td>ILSVRC-2012</td><td>INCEPTIONR20 INCEPTIONHF</td><td>R(20) HF</td><td>6.3% 81.3%</td><td>72.4% 99.5%</td><td>10.2% 89.7%</td><td>81.3% 99.6%</td></tr></table>
Table 12: Robust ASR of RobustUAP compared to the three baselines for robust networks.
# T ABLATION ON OPTIMIZATION STRATEGY
In this section, we study the effect of using different optimizers in addition to SGD. We use a variety of standard PyTorch optimizers, Adam, Adamax, Adagrad, and RMSProp. We formulate the optimization problem in the same way but instead use these algorithms in order to optimize our perturbation. We compute these results on ILSVRC-2012 with Inception-v3 and use $R ( 1 0 ) , T ( 2 , 2 ) , S h ( 2 ) , S c ( 2 ) , B ( 2 , 0 . 0 0 1 )$ as the transformation set and with $\gamma = 0 . 6$ . The results can be seen in Table 13. We see that the optimization strategy has some affect on the results and that SGD performs the best. We also found that SGD performed marginally faster than the rest of the approaches.
Table 13: Comparison of different optimization strategies.
<table><tr><td>OPTIMIZER|ASRR</td><td></td></tr><tr><td>SGD ADAM</td><td>63.1% 59.7%</td></tr><tr><td>ADAMAX ADAGRAD</td><td>60.1% 62.3%</td></tr><tr><td>RMSPROP</td><td>58.3%</td></tr></table>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378# Contrastive and Non-Contrastive Self-Supervised Learning Recover Global and Local Spectral Embedding Methods
Randall Balestriero Meta AI Research, FAIR NYC, USA rbalestriero@meta.com
Yann LeCun Meta AI Research, FAIR, NYU NYC, USA ylecun@meta.com
# Abstract
Self-Supervised Learning (SSL) surmises that inputs and pairwise positive relationships are enough to learn meaningful representations. Although SSL has recently reached a milestone: outperforming supervised methods in many modalities. . . the theoretical foundations are limited, method-specific, and fail to provide principled design guidelines to practitioners. In this paper, we propose a unifying framework under the helm of spectral manifold learning to address those limitations. Through the course of this study, we will rigorously demonstrate that VICReg, SimCLR, BarlowTwins et al. correspond to eponymous spectral methods such as Laplacian Eigenmaps, Multidimensional Scaling et al. This unification will then allow us to obtain (i) the closed-form optimal representation for each method, (ii) the closedform optimal network parameters in the linear regime for each method, (iii) the impact of the pairwise relations used during training on each of those quantities and on downstream classification task performances, and most importantly, (iv) the first theoretical bridge between contrastive and non-contrastive methods towards global and local spectral embedding methods respectively, hinting at the benefits and limitations of each. For example, (i) if the pairwise relation is aligned with the downstream task, any SSL method can be employed successfully and will recover the supervised method, but in the low data regime, SimCLR or VICReg with high invariance hyper-parameter should be preferred; (ii) if the pairwise relation is misaligned with the downstream task, BarlowTwins or VICReg with small invariance hyper-parameter should be preferred.
# 1 Introduction
Self-Supervised Learning (SSL) is one of the most promising method to learn data representations that generalize across downstream tasks. SSL places itself in-between supervised and unsupervised learning as it does not require labels but does require knowledge of what makes some samples semantically close to others. Hence, where unsupervised learning relies on a collection of inputs $( X )$ , and supervised learning relies on inputs and outputs $( X , Y )$ , SSL relies on inputs and inter-sample relations $( X , G )$ that indicate semantic similarity. The latter matrix $G$ is often constructed by augmenting $\boldsymbol { X }$ through data-augmentations known to preserve input semantics [1–3] e.g. horizontal flip for an image, although recent methods have went away from Data-Augmentation (DA)by using videos from which consecutive frames can be seen as semantically equivalent [4–6].
Although SSL originated decades ago [7], recent advances have pushed SSL performances beyond expectations [8–10]. Due to those rapid empirical advances, an urgent need for a principled theoretical understanding of those methods has emerged [11, 12]. Studies in this direction often take one of the three following approaches: (i) studying the training dynamics and optimization landscapes of existing methods e.g. validating some empirically found tricks as necessary conditions for stable gradient dynamics [13–16], (ii) studying the role of each SSL component e.g. the projector and predictor networks [17–19], or (iii) developing novel SSL criteria that often combine multiple interpretable objectives that a SSL model must fulfill [20–25]. While those branches have led to novel understandings and even stem novel SSL methods, some fundamental questions remain open.
 Figure 1: Summary of our unification of SSL methods to known local and global spectral embedding methods. In doing so, we are able to find the exact settings for which different methods provably become identical. In short, all are concerned in preserving the left-singular vectors of the similarity matrix $\pmb { G }$ (see Fig. 6) in the representation $z$ .
More recently, a few focused studies have started to provide theoretical works e.g. Tian [27] on contrastive losses with deep linear networks, HaoChen et al. [28, 29] on SimCLR [8], [30] on the projector of contrastive models, [14] on BYOL [31] and SimSIAM [8].Those studies paved our way forward as we propose in this paper a much broader analysis that applies to most (if not all) existing SSL methods allowing us for the first time to provide provable design guildelines to practitioners in their choice of architecture and methods. We do so by unifying most SSL methods as different flavors of spectral methods for embedding and clustering as summarized in Fig. 1. The instrumental results we obtain allow us to answer some long-standing questions both when employing a linear model and an infinite capacity one which we summarize as part of our contributions below:
1. Closed-form optimal representation for SSL losses. The Deep Network (DN)representation $z$ of inputs $\boldsymbol { X }$ learned by minimizing any SSL loss given a sample relation matrix $G$ is obtained in closed-form, shedding light to many spectral properties of those representations e.g. SSL only constrains the left singular vectors and singular values of $z$ to align with the ones of $G$ (Sections 3.1, 4.1 and 5.1 for VICReg, SimCLR and BarlowTwins). 2. Closed-form optimal network parameters for SSL losses with linear networks. The linear representation $\pmb { Z } = \pmb { X } \pmb { W } + \pmb { b }$ parameters obtained by minimizing any SSL loss given a sample relation matrix $G$ are obtained in closed-form, providing insights into the type of input statistics that a network parameters focuses on to produce the optimal input mapping (Sections 3.2 and 5.2 for VICReg and BarlowTwins). 3. Exact equivalence between SSL and spectral embedding methods. SSL methods employ diverse criterion that can be tied to eponymous spectral analysis methods both in embedding space and in data space, and with a nonlinear or a linear DN e.g. Laplacian Eigenmaps (VICReg, Section 3.2), ISOMAP (SimCLR/NNCLR, Section 4.3), Canonical Correlation Analysis (BarlowTwins, Section 5.2) and when employing a linear network as Locality Preserving Projection (VICReg), Cannonical Correlation Analysis (BarlowTwins), and Linear Discriminant Analysis for both VICReg and BarlowTwins (summarized in Fig. 1).
We also relegate to Appendix C a study quantifying the relationship between the optimal representation of each SSL method and the downstream classification task performances e.g. when the correct data relation matrix is given (Appendix C.3) as those results, although not crucial to our contributions, follow directly from the above ties between SSL and spectral embedding. We carefully prove each statement of this study in Appendix $F$ .
# 2 Notations and Background on Self-Supervised Learning
We provide in this section a brief reminder of the main Self-Supervised Learning (SSL) methods, their associated losses, and the common notations that we will rely on for the remaining of the study.
Dataset, Embedding and Relation Matrix Notations. Regardless of the loss and method employed, SSL relies on having access to a set of observations i.e. input samples $\pmb { X } \triangleq [ \pmb { x } _ { 1 } , \ldots , \pmb { x } _ { N } ] ^ { T } \in \mathbb { R } ^ { N \times D }$ and a known pairwise positive relation between those samples e.g. in the form of a symmetric matrix $G \in ( \mathbb { R } ^ { + } ) ^ { N \times N }$ where $( G ) _ { i , j } > 0$ iff samples $\mathbf { \Delta } _ { \mathbf { \mathcal { X } } _ { i } }$ and $\boldsymbol { \mathscr { x } } _ { j }$ are known to be semantically related, and with 0 in the diagonal. Commonly, one is only given a dataset $X ^ { \prime }$ and artificially constructs $\boldsymbol { X }$ and $G$ from augmentations of $X ^ { \prime }$ e.g. rotated, noisy versions of the original samples and turning the corresponding entries of $G$ to be positive for the samples that have been augmented form the same original sample. Lastly, $\boldsymbol { Z } \in \mathbb { R } ^ { \boldsymbol { \tilde { N } \times K } }$ denotes the matrix of feature maps obtained from a model $f _ { \theta } : \mathbb { R } ^ { D } \mapsto \mathbb { R } ^ { K }$ —commonly a Deep Network— as $Z \triangleq [ f _ { \boldsymbol \theta } ( \pmb { x } _ { 1 } ) , \ldots , f _ { \boldsymbol \theta } ( \pmb { x } _ { N } ) ] ^ { T }$ .
VICReg. With the above notations out of the way, we can remind the VICReg loss as defined in Bardes et al. [25] as a function of $\boldsymbol { X }$ and $G$ in the following triplet loss
$$\mathcal { L } _ { \mathrm { v i c } } = \alpha \sum _ { k = 1 } ^ { K } \operatorname* { m a x } \Bigg ( 0 , 1 - \sqrt { \mathrm { C o v } ( \boldsymbol { Z } ) _ { k , k } } \Bigg ) + \beta \sum _ { j \neq k } \mathrm { C o v } ( \boldsymbol { Z } ) _ { k , j } ^ { 2 } + \frac { \gamma } { N } \sum _ { i = 1 } ^ { N } \sum _ { j = 1 } ^ { N } ( \boldsymbol { G } ) _ { i , j } \| \boldsymbol { Z } _ { i , \cdot } - \boldsymbol { Z } _ { j , \cdot } \| _ { 2 } ^ { 2 } .$$
We will often refer to each term in Eq. (1) as ${ \mathcal { L } } _ { \mathrm { v a r } }$ , ${ \mathcal { L } } _ { \mathrm { c o v } }$ , and ${ \mathcal { L } } _ { \mathrm { i n v } }$ respectively.
SimCLR. The SimCLR loss [8] is slightly different and first produces an estimated relation matrix ${ \widehat { G } } ( Z )$ generally using the cosine similarity (CoSim) via
$$( \widehat { G } ( Z ) ) _ { i , j } = \frac { e ^ { \operatorname { C o S i m } ( z _ { i } , z _ { j } ) / \tau } } { \sum _ { j = 1 , j \neq i } ^ { N } e ^ { \operatorname { C o S i m } ( z _ { i } , z _ { j } ) / \tau } } ,$$
with $\tau > 0$ a temperature parameter. Then SimCLR encourages the elements of ${ \widehat { G } } ( Z )$ and $G$ to match. The most popular solution to achieve that is to leverage the infoNCE loss given by
$$\mathcal { L } _ { \mathrm { S i m C L R } } = - \sum _ { i = 1 } ^ { N } \sum _ { h = 1 } ^ { N } ( G ) _ { i , j } \log ( \widehat { G } ( Z ) ) _ { i , j } .$$
The only difference between SimCLR and its varients e.g. NNCLR [32] lies in defining $G$ .
BarlowTwins. Lastly, BarlowTwins [24] proposes yet a slightly different approach where $z _ { i }$ must be close to $z _ { j }$ if $G _ { i , j } > 0$ . They do so with different flavors of losses and constraints to facilitate training. Hence, and for those models only, it is common to explicitly group $\boldsymbol { X }$ into two subsets $X _ { \mathrm { l e f t } }$ and $X _ { \mathrm { r i g h t } }$ based on $G$ so that $( ( X _ { \mathrm { l e f t } } ) _ { n } , ( X _ { \mathrm { r i g h t } } ) _ { n } ) , \forall n$ are all the positive pairs from $( X , G )$ . This does not lose any generality. In fact, suppose that we have 5 samples $a , b , c , d , e$ , and that $G$ says that $a , b , c$ are related to each other, and that $d , e$ are related to each other. Then, we can create the two data matrices as
$$\begin{array} { r } { \mathbf { X } _ { \mathrm { l e f t } } = [ a , a , b , b , c , c , d , e ] , \ X _ { \mathrm { r i g h t } } = [ b , c , a , c , a , b , e , d ] . \ } \end{array}$$
Once the two (left/right) views are obtained, the corresponding embeddings $Z _ { \mathrm { l e f t } } , Z _ { \mathrm { r i g h t } }$ can be computed and the BarlowTwins is then defined as
$$\mathcal { L } _ { \mathrm { B T } } = \sum _ { k = 1 } ^ { K } ( \mathrm { C o S i m } ( ( Z _ { \mathrm { l e f t } } ) _ { , k } , ( Z _ { \mathrm { r i g h t } } ) _ { , k } ) - 1 ) ^ { 2 } + \alpha \sum _ { k = 1 , k ^ { \prime } \neq k } ^ { K } \mathrm { C o S i m } ( ( Z _ { \mathrm { l e f t } } ) _ { , k } , ( Z _ { \mathrm { r i g h t } } ) _ { , k ^ { \prime } } ) ^ { 2 } .$$
where one should notice that those terms correspond to the cross-correlation matrix between the two embeddings.
Our goal in the following sections (Section 3 for VICReg, Section 4 for SimCLR/NNCLR, and Section 5 for BarlowTwins) will be to find the optimal representations $z$ of $\boldsymbol { X }$ in various regimes. Three surprising facts will emerge: (i) all existing methods recover exactly some flavors of famous spectral methods, (ii) the spectral properties of $z$ can be provably characterized for each methods, and (iii) from those properties, we will provide necessary and sufficient conditions for a SSL representation to perfectly solve a downstream task. We provide linear algebra notations in Appendix B that might be useful for readers unfamiliar with methods such as the Singular Value Decomposition (SVD) [33].
# 3 VICReg Minimizes the Dirichlet Energy to Produce Smooth Signals on the Graph $G$ While Preventing Dimensional Collapse
Recall from Section 2 and Eq. (1) that VICReg is defined as a triplet loss (variance/invariance/covariance). We first demonstrate in Section 3.1 that the optimal VICReg representation can be obtained in closed form (Theorem 1) and that turning the VICReg optimization as a constrained problem recovers Laplacian Eigenmaps in embedding space and Kernel Locality Preserving Projection in data space (Section 3.2). We also consider the linear network regime where we obtain the analytical form of the optimal network’s parameters (Theorem 3).
# 3.1 Close-Form Optimal Representation for VICReg
First, we build up some insights into VICReg by demonstrating how the invariance term corresponds to the Dirichlet energy of the signal $z$ on the graph $G$ . Then, replacing the variance hinge loss at 1 with the squared loss at 1 as in minimizing the former. With t ${ \textstyle \sum _ { k = 1 } ^ { K } \left( 1 - \operatorname { C o v } ( Z ) _ { k , k } \right) ^ { 2 } }$ , notice that minimizing the latter impthe close-form optimal representation $Z ^ { * }$ minimizing Eq. (1) only as a function of $G$ and the loss’ hyperparameters.
From invariance to trace minimization. The first insight that we propose into VICReg is obtained by rewriting the invariance loss of VICReg as the energy of the signal $z$ on the graph $G$ [34] since we have (derivations in Appendix F.5)
$$\sum _ { i = 1 } ^ { N } \sum _ { j = 1 } ^ { N } ( G ) _ { i , j } \| ( \boldsymbol { Z } ) _ { i , \cdot } - ( \boldsymbol { Z } ) _ { j , \cdot } \| _ { 2 } ^ { 2 } = 2 \operatorname { T r } \left( \boldsymbol { Z } ^ { T } \boldsymbol { L } \boldsymbol { Z } \right) \ ( \triangleq \operatorname { D i r i c h l e t } \operatorname { e n e r g y } \operatorname { o f } \boldsymbol { Z } \operatorname { o n } G ) ,$$
where $\pmb { L }$ is the graph Laplacian matrix $L = D - G$ with $_ { D }$ the diagonal degree matrix of $G$ i.e. $\begin{array} { r } { ( D ) _ { i , j } = \sum _ { j } ( \mathbf { \bar { G } } ) _ { i , j } } \end{array}$ and $( \boldsymbol { D } ) _ { i , j } = \boldsymbol { 0 } , \forall i \neq j$ . From Eq. (6) it is clear that the invariance term depends on the matching between the left singular vectors of $z$ and the eigenvectors of $\pmb { L }$ . Hence, non-contrastive learning aims at producing non-degenerate signals $z$ that are smooth on $G$ .
Optimal representation. To gain further insights into VICReg, we ought to obtain the analytical form of the optimal representation $Z ^ { \ast }$ minimizing Eq. (1) —although this optimum is not unique e.g. adding a constant entry to each column of $z$ does not change the loss value (details in Appendix F.6). We can now obtain the following characterization of $Z ^ { * }$ as a function of the spectral decomposition of the matrix that combines two Laplacian matrices (details in Appendix F.7). The first, (left of Eq. (7)) comes form the variance+covariance term is the Laplacian of a complete graph i.e. where each node/sample is connected all others. The second comes from the SSL graph $G$ to form the following (with its eigen-decomposition)
$$\underbrace { I - \mathbf { 1 } \mathbf { 1 } ^ { T } / N } _ { \mathrm { a \ c o m p l e t e \ g r a p h } } - \underbrace { \frac { \gamma } { \alpha } \left( \pmb { D } - \pmb { G } \right) } _ { \mathrm { L a p l a c i a n \ o f \ t h e \ S S L / s u p . \ g r a p h } } = P _ { \alpha , \gamma } \mathrm { d i a g } ( \pmb { \lambda } _ { \alpha , \gamma } ) P _ { \alpha , \gamma } ^ { T } ,$$
where the eigenvalues/eigenvectors are in descending orders. The eigenvectors of the combined Laplacians will be key to produce the optimal VICReg representation as formalized below.
Theorem 1. A global minimizer of the VICReg loss $\mathbf { \zeta } \alpha = \beta , \forall \gamma )$ denoted by $\mathbf { \delta Z } _ { \alpha , \gamma } ^ { * }$ is obtained from Eq. (7) along with the minimal achievable loss which are given by
$$Z _ { \alpha , \gamma } ^ { * } = ( P _ { \alpha , \gamma } ( \operatorname { d i a g } ( \lambda _ { \alpha , \gamma } ) N ) ^ { 1 / 2 } ) _ { : 1 : K } \quad a n d \quad \operatorname * { m i n } _ { Z \in \mathbb { R } ^ { N \times K } } { \mathscr { L } _ { \mathrm { V I C } } } = \alpha ( K - \| ( \lambda _ { \alpha , \beta } ) _ { 1 : K } \| _ { 2 } ^ { 2 } ) ,$$
and any $K$ -out-of- $N$ columns of $P _ { \alpha , \gamma } ( \mathbf { A } _ { \alpha , \gamma } N ) ^ { 1 / 2 }$ is a local minimum. (Proof in Appendix $F . 7 .$ )
The above result provides a few key insights. First, only the ratio $\gamma / \alpha$ governs the VICReg representation. Second, there exists many local minimum, some of which can be explicitly found by taking various $K$ -out-of- $N$ columns of $P _ { \alpha , \gamma } ( \mathbf { A } _ { \alpha , \gamma } N ) ^ { 1 / 2 }$ which we display in Fig. 2 along with the loss landscape of ${ \mathcal { L } } _ { \mathrm { V I C } }$ around the optimal representation $Z ^ { * }$ . We also depict in Fig. 3 the evolution of the eigenvalues $( \lambda _ { \alpha , \gamma } ) _ { 1 : K }$ for varying $\gamma$ along with the downstream task (induced by $G$ ) training performance. We observe that VICReg benefits from a sweet-spot where it can both preserve a full-rank representation $Z ^ { \ast }$ and incorporate enough information about $G$ to solve the task at hand perfectly.
Before moving to other SSL methods, we first emphasize the ability of VICReg to recover local spectral methods in the following sections.
# 3.2 VICReg Recovers Local Spectral Embedding Methods
The goal of this section is to relate VICReg to known local spectral embedding methods both in feature space $( Z )$ and in data space $( X )$ .
 Figure 2: Left: depiction of the optimal VICReg loss with varying hyper-parameters (blue line) when the representation is formed from the top $[ k : K + k - 1 ]$ eigenvectors of Eq. (7) with convex interpolation in-between. Recall from Theorem 1 that the global optimum is given by the $[ 1 : K - 1 ]$ case. We also depict the downstream task performance (orange line) and we clearly observe that both are closely related as expected (see Theorem 9). Notice that since we are considering classification, even without the correct first eigenvector the linear classifier on top of $Z _ { \alpha , \gamma } ^ { * }$ is able to solve the task at hand thanks to the probability constraint that must sum to 1 i.e. the last component can be recovered from the first $C - 1$ . Right: depiction of the loss landscape of ${ \mathcal { L } } _ { \mathrm { V I C } }$ around the optimal $Z _ { \alpha , \gamma } ^ { * }$ on the left using the directions provides by the top $[ 2 : K ]$ and $[ 3 : K \bar { + } 1 ]$ eigenvectors of Eq. (7), and then with random directions in $z$ -space. All experiments employed $N = 2 5 6$ , $K = 1 6$ , $\operatorname { r a n k } ( G ) { \overset { - } { = } } 4$ .
 Figure 3: Top: minimal VICReg loss (blue) from Theorem 1 and corresponding downstream task performance (orange). Bottom: evolution of $Z _ { \alpha , \gamma } ^ { * }$ ’s singular values. VICReg benefits from a $( \alpha , \gamma )$ -zone for which $\mathbf { \delta Z } _ { \alpha , \gamma } ^ { * }$ remains full rank and incorporates enough information on $\pmb { G }$ to solve the downstream task. Hence, VICReg hyper-parameters $\gamma / \alpha$ should be adapted depending on the confidence one has into $_ G$ All experiments employed $N =$ 256, $\bar { K } = 3 2$ , $\operatorname { r a n k } ( G ) = 8$ .
In feature space. Laplacian Eigenmaps (LE) [35] is a non-parametric method searching for a representation $z$ by minimizing the following Brockett [36] optimization problem
$$\operatorname* { m i n } _ { \theta : Z ^ { T } D Z = I } \mathrm { T r } \left( Z ^ { T } \left( D - G \right) Z \right) ,$$
with $_ { D }$ the diagonal degree matrix of $G$ (recall Eq. (7)).
Theorem 2. Given a dataset $\boldsymbol { X }$ and relation matrix $G$ solving the $L E$ optimization problem Eq. (8) produces a representation that minimizes the VICReg loss with constraint that the variance and covariance loss are 0 as in ${ \mathcal { L } } _ { \mathrm { v i c } } ( Z _ { \mathrm { L E } } ^ { * } ) { = } \mathrm { m i n } _ { Z } { \mathcal { L } } _ { \mathrm { i n v } } ( Z )$ s.t. ${ \mathcal { L } } _ { \mathrm { v a r } } { = } O$ and ${ \mathcal { L } } _ { \mathrm { c o v } } { = } O .$ . (Proof in Appendix F.8.)
One important observation is that 8 recovers yet another SSL method known as W-MSE [37] which can now be seen as the constrained counterpart of VICReg, and in the linear regime, recovers Slow Feature Analysis (SFA) although without the dimension ordering, and is thus also closely related to its extension presented in Pfau et al. [38]. Furthermore, Eq. (8) and variants have been studied in Agrawal et al. [39] in the context of kernel PCA, some of which could provide interesting variations of the constrained VICReg setting. We also ought to highlight however that a crucial part of LE lies in the design of that matrix $G$ , often found from a $k$ -NN graph [40] of the samples $\boldsymbol { X }$ in the input space, while in SSL it is constructed from data-augmentations, or given.
In data space with DNs. The difficulty to produce new representations $_ z$ for new data samples (a shared difficulty among non-parametric methods) led to the development of a two-step modeling process [41] as x (∈ RD) 7→ h = ϕ(x) (∈ RS) 7→ z = W T h (∈ RK ) with S ≫ K, W ∈ RM×K , and where $\phi$ ’s goal is to learn a generic input embedding that can be reused on new samples $_ { \textbf { \em x } }$ . To see this, we collect those mappings for all the training set into the matrix $\Phi \in \mathbb { R } ^ { N \times S }$ . With that, the LE problem in data space —known as the kernel Locality Preserving Projection (kLPP) [42] problem— becomes
$$\operatorname* { m i n } _ { \theta : W ^ { T } \Phi ^ { T } D \Phi W = I } \mathrm { T r } \left( W ^ { T } \Phi ^ { T } \left( D - G \right) \Phi W \right) ,$$
so that the original LE representation $z$ can be obtained simply as ${ Z = \Phi W }$ . And more importantly, given a new sample $_ { \textbf { \em x } }$ , one directly computes $z = W ^ { T } \phi ( \mathbf { \dot { x } } )$ . The crucial result of interest for our study is the following one that simply combines Theorem 2 with a result from He and Niyogi [42] demonstrating the equivalence between LE in feature space and KLLE in data space.
Proposition 1. VICReg with variance/covariance constraint solves $L E$ in embedding space and KLLE in input space (recall Eq. (9)) employing a DN for $\phi$ .
In data space with linear models. We now consider a linear mapping $Z = X W$ (the offset is taken care of by adding a 1 column to $\boldsymbol { X }$ ). In that case, VICReg with constrained $\mathcal { L } _ { \mathrm { v a r } } = 0 , \mathcal { L } _ { \mathrm { c o v } } = 0$ (as in Theorem 3)recovers two known spectral methods: Locality Preserving Projections (LPP) [42] for an arbitrary relation matrix $G$ , and Linear Discriminant Analysis (LDA) [43, 44] when $G$ is the supervised relation matrix. In both cases we obtain the analytical form of the optimal weights $W$ , as long as the within class/cluster variance is positive.
Theorem 3. Linear VICReg recovers LPP for any $G$ and $K \leq N$ , and recovers LDA for supervised $G$ and $K = C$ , in both cases the optimal parameter $W ^ { * }$ is given by the top- $K$ eigenvectors of $( X ^ { T } ( D - G ) X ) ^ { - 1 } X ^ { T } G X$ . (Proofs in Appendices F.13 and F.14.)
Interestingly, the eigenvalues associated to the eigenvectors of $W ^ { * }$ exactly recover the multivariate analysis of variance (MANOVA) sufficient statistics of the data [45, 46]. Hence, although not further explored in this study, we believe that important statistical results could be further obtained e.g. to assess the goodness-of-fit of the model without requiring a downstream task [47–49]. We now turn to another important SSL loss which is SimCLR and its variants.
# 4 SimCLR Solves a Generalized Multidimensional Scaling Problem à la ISOMAP
Recall from Section 2 and Eq. (2) that SimCLR first computes a similarity matrix $\widehat { G }$ of some flavor that depends on the representation $z$ , and then matches it against the known data relation $G$ . Different $z \mapsto { \widehat { \hat { G } } }$ methods lead to different variants of SimCLR [8] such as NNCLR [32] or MeanShift [50]. The goal of this section is two-fold. First, we demonstrate in Section 4.1 that different $Z \mapsto { \widehat { G } }$ mappings are solutions of different optimization problems (Theorem 4) —all trying to estimate the similarity matrix $G$ from the signals $z$ akin to Laplacian estimation in Graph Signal Processing. Second, we demonstrate in Section 4.2 that SimCLR and its variants force $z$ ’s spectrum to align with the one of $G$ as the training task falls back to a generalized (kernel) Multi-Dimensional Scaling method (Proposition 2).
# 4.1 Step 1: SimCLR Pairwise Similarities Solve a Graph Laplacian Estimation Problem
Let’s first define the minimization problem that given a set of signals i.e. rows of $z$ produces a relation estimate $\widehat { G }$ of $G$ . To ease notations, we gather in the $N \times N$ matrix $_ { D }$ all the pairwise distances $( \pmb { { \cal D } } ) _ { i , j } = d ( f _ { \theta } ( \pmb { x } _ { i } ) , f _ { \theta } ( \pmb { x } _ { j } ) )$ with $d$ any preferred metric. The standard problem of estimating $\widehat { G }$ from $z$ can be cast as an optimization problem [51, 52] as
$$\widehat { G } _ { d , \mathcal { R } } = \underset { G \in \mathcal { G } } { \arg \operatorname* { m i n } } \sum _ { i , j } d \big ( f _ { \theta } ( \boldsymbol { x } _ { i } ) , f _ { \theta } ( \boldsymbol { x } _ { j } ) \big ) ( G ) _ { i , j } + \mathcal { R } ( G ) = \underset { G \in \mathcal { G } } { \arg \operatorname* { m i n } } \mathrm { T r } ( D G ) + \mathcal { R } ( G ) ,$$
with $\mathcal { G }$ the set (or subset) of symmetric matrices with nonnegative entries and zero diagonal, and with $\mathcal { R }$ a regularizer preventing $\widehat { G }$ to be the trivial zero matrix e.g.
$$\mathcal { R } _ { \mathrm { l o g } } ( G ) = \sum _ { i \neq j } \tau G _ { i , j } ( \log ( G _ { i , j } ) - 1 ) \quad \mathrm { o r } \quad \mathcal { R } _ { \mathrm { F } } ( G ) = \sum _ { i \neq j } \tau G _ { i , j } ( G _ { i , j } - 1 ) .$$
 Figure 4: Depiction of the representation’s singular values during training (from blue to red with the SimCLR loss with $\mathcal { G } _ { \mathrm { r s t o } }$ , varying $\operatorname { r a n k } ( G ) \in \{ 8 , 1 6 , 3 2 \}$ (rows, green dotted lines), number in top-right corner) with various $( d , \mathcal { R } )$ configurations (columns, recall Theorem 4). The rank of the learned representation matches exactly the one of $_ G$ validating the result from Theorem 5 regardless of the chosen hyper-parameters.
We provide in Fig. 7 a depiction of the impact of ${ \mathcal { R } } ( G )$ which pushes the entries of the weight matrix to be close to 1 with strength depending on the temperature parameter $\tau$ . Hence $\widehat { G }$ from Eq. (10) is the optimal graph —expressed as a weight matrix— for which the signal $Z = f _ { \theta } ( { \boldsymbol { X } } )$ on that graph is smooth. For example one can solve Eq. (10) only on $\mathcal { G } _ { \mathrm { r s t o } }$ , the space of right-stochastic matrices i.e. a subset of $\mathcal { G }$ that only contains matrices whose rows sum to 1 i.e. $\mathcal { G } _ { \mathrm { r s t o } } \overset { - } { = } \{ G \in \mathcal { G } : G { \bf 1 } = { \bf 1 } \}$ .
Theorem 4. Using $\mathcal { R }$ from Eq. (11) leads to the following graph weight estimate
$$\begin{array} { r l } & { ( \widehat { \pmb { G } } _ { d , \mathcal { R } _ { \mathrm { l o g } } } ) _ { i , j } = e ^ { \frac { - 1 } { \tau } d ( f _ { \theta } ( \pmb { x } _ { i } ) , f _ { \theta } ( \pmb { x } _ { j } ) ) } 1 _ { \{ 1 \neq j \} } , \qquad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad ( w i t h \mathscr { G } ) } \\ & { ( \widehat { \pmb { G } } _ { d , \mathcal { R } _ { \mathrm { l o g } } } ) _ { i , j } = \frac { e ^ { \frac { - 1 } { \tau } d ( f _ { \theta } ( \pmb { x } _ { i } ) , f _ { \theta } ( \pmb { x } _ { j } ) ) } } { \sum _ { j \neq i } e ^ { \frac { - 1 } { \tau } d ( f _ { \theta } ( \pmb { x } _ { i } ) , f _ { \theta } ( \pmb { x } _ { j } ) ) } } 1 _ { \{ 1 \neq j \} } , \qquad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad ( w i t h \mathscr { G } _ { \mathrm { r s t o } } ) } \end{array}$$
and thus if d is the cosine distance, Eq. (12) recovers SimCLR’s case. (Proof in Appendix F.9.)
Based on this result, deriving novel, principled and interpretable variations of SimCLR is streamlined as we demonstrate in Appendix E by solving Eq. (10) with different constraints. Now that we understood the first part of the SimCLR method, we move to the second part, matching that graph estimate to the given one.
# 4.2 Step 2: SimCLR Fits the Estimated Graph $\widehat { G }$ to the Known Graph $G$
After SimCLR estimates the graph with $\widehat { G }$ as per the previous section, it employs a loss to enforce $\widehat { G }$ to be as close as possible to $G$ with some desired metric. That metric should reflect the properties that $G$ fulfills e.g. being a doubly-stochastic, right-stochastic or else. We demonstrate in this section that in doing so, SimCLR forces $z$ to have the same nonzero left singular vectors as the nonzero eigenvectors of $G$ , and that as opposed to VICReg, the rank of $\boldsymbol { Z } _ { \tau } ^ { \ast }$ and $G$ always matches.
Let’s first denote the SimCLR contrastive loss to be one of the two following variants (depending on the type of constraints put on $\widehat { G }$ and $G$
$$\mathcal { L } _ { \mathrm { S i m C L R } } = \Vert \pmb { G } - \widehat { \pmb { G } } \Vert _ { F } ^ { 2 } \mathrm { o r } - \frac { 1 } { N } \sum _ { n = 1 } ^ { N } \sum _ { n ^ { \prime } = 1 } ^ { N } ( \pmb { G } ) _ { n , n ^ { \prime } } \log ( ( \widehat { \pmb { G } } ) _ { n , n ^ { \prime } } ) .$$
When minimizing Eq. (13), SimCLR will learn an embedding $z$ so that the graph estimate matches closely the known graph $G$ . This already brings a contrast from VICReg showing that instead, SimCLR learns to produce signals such that the graph estimate is close to the known graph.We now characterize the optimal SimCLR representation $\boldsymbol { Z } _ { \tau } ^ { \ast }$ , recalling that we denote by $U _ { G }$ and $\Sigma _ { G }$ the left singular vectors and singular values of $G$ respectively. Notice that since $G$ is symmetric semi-definite positive, $U$ also corresponds to its eigenvectors and $\Sigma _ { G } ^ { 2 }$ to its eigenvalues.
Theorem 5. A global minimizer of the SimCLR loss denoted by $Z ^ { * }$ along with the minimal achievable loss using Eq. (16) or Eq. (17), $\tau \geq \mathrm { m a x } _ { i , j } ( D ) _ { i , j }$ and with the LHS of Eq. (13) are given by
$$\pmb { Z } _ { \tau } ^ { * } = ( \pmb { U } _ { G } \pmb { \Sigma } _ { G } ^ { 1 / 2 } ) _ { : , 1 : K } \quad a n d \quad \operatorname* { m i n } _ { \pmb { Z } \in \mathbb { R } ^ { N \times K } } \mathcal { L } _ { \mathrm { S i m C L R } } = \sum _ { k = K + 1 } ^ { N } ( \pmb { \Sigma } _ { G } ^ { 2 } ) _ { k , k } ,$$
up to permutations of the singular vectors associated to the same singular value. Also, for any loss of Eq. (13) and graph estimation, the rank of $\boldsymbol { Z } _ { \tau } ^ { * }$ is $\operatorname* { m i n } ( K , \operatorname { r a n k } ( G ) )$ . (Proof in Appendix F.10.)
We illustrate the above theorem for many combinations of distances and regularizers in Fig. 4 where we see that in all cases, SimCLR forces the representations $z$ to have a dimensional collapse, a phenomenon first observed in Hua et al. [17] and that has been one of the unanswered phenomenon in SSL [20, 30].
In our goal to unify SSL methods under the helm of spectral embedding methods, we now propose the following section that ties SimCLR and its variants to global spectral methods.
# 4.3 SimCLR Recovers Global Spectral Embedding Methods
We now propose to tie the SimCLR method along with its variants e.g. NNCLR to known global spectral methods, e.g. ISOMAP [53] which is in contrast to VICReg which was tied to local spectral methods (recall Section 3.2).
In feature space. Let’s first recall that ISOMAP is a variation of Multi-Dimensional Scaling (MDS) [54] also known as Principal Coordinates Analysis. Classical MDS tries to learn embedding vectors that have similar pairwise distance (usually $\ell _ { 2 }$ ) than the pairwise distance of the given input data. Often, MDS does this by using similarities instead of distances and thus by solving the following optimization problem minZ $\| \check { G } - Z Z ^ { T } \| _ { F } ^ { 2 }$ . At the most general level, ISOMAP simply corresponds to solving that same optimization problem but after redefining $G$ to better capture the geometric information of $\boldsymbol { X }$ e.g. using the shortest path distance of the $k$ -NN graph of $\boldsymbol { X }$ [55]. The surprising result that we formalize below is that SimCLR and its variants recover ISOMAP.
Proposition 2. SimCLR, using the settings of Theorem 5, recovers ISOMAP (and MDS for the correct choice of $G$ ). (Proof in Appendix F.11.)
In data space with DNs. From the above, we can extend Proposition 2 but in input space, in a very similar way as was done in Section 3.2. In fact, originating in Webb [56], there was a search to extend MDS, and ISOMAP to an input space formulation to solve the out-of-bag problem. In this setting, and taking MDS as an example, the original similarity matrix ${ \boldsymbol { z } } { \boldsymbol { z } } ^ { T }$ is replaced with $\Phi { \cal W } ^ { T } { \cal W } \Phi ^ { \breve { T } }$ using the same notations as in Eq. (9) and already known relationship between those models, we obtain the following.
Proposition 3 ([57]). Whenever SimCLR recovers ISOMAP or MDS in feature space, it recovers kernel ISOMAP or kernel PCA [58] in input space.
We now ought to turn to BarlowTwins, another non-contrastive method akin to VICReg (both of which fall back to LDA in the linear regime and with supervised $G$ ).
# 5 BarlowTwins Solves a (Kernel) Canonical Correlation Analysis Problem and Can Recover VICReg
Our last step in our journey to unify SSL methods under spectral embedding methods deals with BarlowTwins. Akin to the development for VICReg and SimCLR, BarlowTwins will also fall back to a known spectral method in embedding space (Section 5.1) and in data space (Section 5.2) where in the later case we again obtain the close-form optimal network parameters in the linear regime.
# 5.1 BarlowTwins Recovers Kernel Canonical Correlation Analysis
Recall from Section 2 and Eq. (5) that the BarlowTwins loss is based on a cross-correlation matrix between positive pairs of samples. As we did for VICReg and SimCLR, our goal here is to tie BarlowTwins to a known spectral method known as Kernel Canonical Correlation Analysis.
Although we focus here on BarlowTwins for clarity. We hope that our results on BarlowTwins will stem the unification of those methods too in future works. Going back to BarlowTwins, we now obtain the following result that nicely parallels with the ones we obtained for VICReg and SimCLR. In data space, BarlowTwins can be regarded (put in perspective with Section 5.2) as a nonlinear canonical correlation analysis (NLCA) [59] and in particular Kernel CCA (KCCA) [60, 61] akin to how VICReg recovered Kernel Locality Preserving Projection and SimCLR Kernel ISOMAP. We leverage the same notations as in Section 3.2.
Theorem 6. BarlowTwins recovers Kernel Canonical Correlation Analysis with a DN as the featurizer $\phi$ and produce a representation with rank $\operatorname* { m i n } ( K , D )$ for any value of α (recall Eq. (5)) and with orthogonal columns. (Proof in Appendix F.12.).
We thus obtain from the above that BarlowTwins employing a DN featurized is akin to the Deep CCA [62] that proposed this setting exactly, and further akin to SimSIAM and BYOL [31] since Lee et al. [26] related the latter to Deep CCA. In addition to those links, the above provides further interpretation into the BarlowTwins’ loss e.g. the additional $\epsilon$ constant added in the denominator of the BarlowTwins loss further corresponds to a ridge-type regularization which as been introduced in Gretton et al. [63] as a mean to introduce numerical stability.
The above statement also brings yet another flavor of SSL methods. In fact, where VICReg allows to control the rank of $z$ to be in-between $K$ and $\mathrm { { r a n k } } ( G )$ throug the loss hyper-parameters, and where SimCLR enforces the rank of $z$ to be exactly the rank of $G$ , BarlowTwins enforces to have a full-rank representation. We depict in Fig. 8 the evolution of $\operatorname { r a n k } ( Z )$ depending on the rank of the initialized representation rank $Z _ { \mathrm { i n i t } } )$ using a gradient descent optimizer. We see that if the initialization is full rank but $G$ is lower rank, the BarlowTwins loss does not collapse the extra nonzero singular values of $z$ . Vice-versa, if $\operatorname { r a n k } ( Z _ { \mathrm { i n i t } } ) < \operatorname { r a n k } ( G )$ then BarlowTwins loss will increase the rank of $z$ . lastly, although not further studied here, we should point out to the reader that regularized forms of KCCA can be shown to include kernel ridge regression and regularized kernel Fisher LDA as special cases [64], further tying the special cases for which different SSL methods would fall back to the same model.
In the following section we will demonstrate how BarlowTwins in the linear regime exactly recovers Canonical Correlation Analysis.
# 5.2 With a Linear Network BarlowTwins Recovers Canonical Correlation Analysis and Linear Discriminant Analysis
The goal of this section is to further demonstrate the benefits of connecting SSL methods to spectral methods by exploiting the known techniques of the latter to help answer questions on the former.
As was done $\mathrm { V I C R e g }$ (we use linear settings of Section 3.2), we now obtain the optimal weights for BarlowTwins in the linear regime. We can even provide additional insights in this case since BarlowTwins is often seen as a key method that allows the use of different parameters/architectures to process $X _ { \mathrm { l e f t } }$ and $X _ { \mathrm { r i g h t } }$ . We now show under what conditions on $G$ sharing parameters is sufficient by first demonstrating how BarlowTwins recovers exactly CCA, and even LDA for supervised $G$ . To streamline notations, we assume that our data is already centered, and thus define the covariance and cross-covariance matrices as $C _ { l l } = X _ { \mathrm { l e f t } } ^ { T } X _ { \mathrm { r i g h t } } , C _ { l r } \overset { \cdot } { = } X _ { \mathrm { l e f t } } ^ { T } X _ { \mathrm { r i g h t } }$ and so on.
Theorem 7. In the linear regime BarlowTwins recovers CCA with optimal weights given by
$$W _ { \mathrm { l e f t } } ^ { * } = \ t o p { - } K \ e i g e n \nu e c t o r s \ o f \ C _ { \mathrm { l l } } ^ { - 1 } C _ { \mathrm { l r } } C _ { \mathrm { r r } } ^ { - 1 } C _ { \mathrm { r l } } \ a n d \ W _ { \mathrm { r i g h t } } ^ { * } = C _ { \mathrm { r r } } ^ { - 1 } C _ { \mathrm { r l } } W _ { \mathrm { l e f t } } ^ { * } ,$$
and $( i )$ —with a symmetric $G$ , weight-sharing naturally occurs— as the optimal weights are $W _ { \mathrm { l e f t } } ^ { * } =$ $W _ { \mathrm { r i g h t } } ^ { * } = t o p { - } K$ eigenvectors of $C _ { \mathrm { r r } } ^ { - 1 } C _ { \mathrm { r l } }$ and (ii) if $G$ is supervised and $K = C$ then BarlowTwins recovers $L D A$ and thus constrained VICReg (recall Theorem 3). (Proof in Appendix F.15.)
The above result opens new venues to extend current SSL methods (BarlowTwins in this case). For example, penalized matrix decomposition (PMD) from Witten et al. [65] formulates a novel sparse formulation of CCA. In our context, this could lead to a new variation of BarlowTwins, in both the linear and nonlinear regimes. With the above results, we now connected most SSL methods to spectral methods, and found key properties that their representations/parameters inherit. We provide for completeness a few direct results in Appendix C that directly leverage the above results to characterize downstream performances of each method.
# 6 Conclusions and Limitations
We provided a unifying analysis of the major self-supervised learning methods covering VICReg (Section 3), SimCLR (Section 4) and BarlowTwins (Section 5) along with SimSIAM and BYOL thanks to already existing results tying those to Deep CCA. In doing so, we were able to find the commonalities between all those methods and to provide general guidelines on how to derive alternative SSL methods from first principles. At a more general level, we were able to parallel the many SSL methods to global and local methods in spectral methods respectively. Among the many insights that we obtained, the most crucial one is that VICReg enables a continue control on collapsing the representation’s rank versus encapsulating information about $G$ . This is in contrast to BarlowTwins and SimCLR that either always maintain full-rank, or always collapse the representation none of which would be ideal. One major limitation is that for the nonlinear regime, we study the case of an infinite capacity model i.e. no implicit bias coming from the architecture comes into play. A potentially insightful future work would thus be to perform a similar analysis as the one provided here but including the implicit bias on the nonlinear mapping that different architecture exhibit. This way, we would obtain not only insights into the various SSL methods but also in their combination with various model architectures.
# References
[1] Angjoo Kanazawa, David W Jacobs, and Manmohan Chandraker. Warpnet: Weakly supervised matching for single-view reconstruction. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 3253–3261, 2016. [2] David Novotny, Samuel Albanie, Diane Larlus, and Andrea Vedaldi. Self-supervised learning of geometrically stable features through probabilistic introspection. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 3637–3645, 2018. [3] Spyros Gidaris, Praveer Singh, and Nikos Komodakis. Unsupervised representation learning by predicting image rotations. arXiv preprint arXiv:1803.07728, 2018. [4] Pierre Sermanet, Corey Lynch, Yevgen Chebotar, Jasmine Hsu, Eric Jang, Stefan Schaal, Sergey Levine, and Google Brain. Time-contrastive networks: Self-supervised learning from video. In 2018 IEEE international conference on robotics and automation (ICRA), pages 1134–1141. IEEE, 2018. [5] Dahun Kim, Donghyeon Cho, and In So Kweon. Self-supervised video representation learning with space-time cubic puzzles. In Proceedings of the AAAI conference on artificial intelligence, volume 33, pages 8545–8552, 2019. [6] Dejing Xu, Jun Xiao, Zhou Zhao, Jian Shao, Di Xie, and Yueting Zhuang. Self-supervised spatiotemporal learning via video clip order prediction. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 10334–10343, 2019. [7] Jane Bromley, Isabelle Guyon, Yann LeCun, Eduard Säckinger, and Roopak Shah. Signature verification using a" siamese" time delay neural network. Advances in neural information processing systems, 6, 1993. [8] Ting Chen, Simon Kornblith, Mohammad Norouzi, and Geoffrey Hinton. A simple framework for contrastive learning of visual representations. In International conference on machine learning, pages 1597–1607. PMLR, 2020. [9] Ishan Misra and Laurens van der Maaten. Self-supervised learning of pretext-invariant representations. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 6707–6717, 2020. [10] Mathilde Caron, Hugo Touvron, Ishan Misra, Hervé Jégou, Julien Mairal, Piotr Bojanowski, and Armand Joulin. Emerging properties in self-supervised vision transformers. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 9650–9660, 2021. [11] Priya Goyal, Dhruv Mahajan, Abhinav Gupta, and Ishan Misra. Scaling and benchmarking self-supervised visual representation learning. In Proceedings of the ieee/cvf International Conference on computer vision, pages 6391–6400, 2019. [12] Linus Ericsson, Henry Gouk, and Timothy M Hospedales. How well do self-supervised models transfer? In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 5414–5423, 2021. [13] Xiang Wang, Xinlei Chen, Simon S Du, and Yuandong Tian. Towards demystifying representation learning with non-contrastive self-supervision. arXiv preprint arXiv:2110.04947, 2021. [14] Yuandong Tian, Xinlei Chen, and Surya Ganguli. Understanding self-supervised learning dynamics without contrastive pairs. In International Conference on Machine Learning, pages 10268–10278. PMLR, 2021. [15] Zixin Wen and Yuanzhi Li. Toward understanding the feature learning process of self-supervised contrastive learning. In International Conference on Machine Learning, pages 11112–11122. PMLR, 2021. [16] Ashwini Pokle, Jinjin Tian, Yuchen Li, and Andrej Risteski. Contrasting the landscape of contrastive and non-contrastive learning. arXiv preprint arXiv:2203.15702, 2022. [17] Tianyu Hua, Wenxiao Wang, Zihui Xue, Sucheng Ren, Yue Wang, and Hang Zhao. On feature decorrelation in self-supervised learning. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 9598–9608, 2021. [18] Li Jing, Pascal Vincent, Yann LeCun, and Yuandong Tian. Understanding dimensional collapse in contrastive self-supervised learning. arXiv preprint arXiv:2110.09348, 2021. [19] Florian Bordes, Randall Balestriero, and Pascal Vincent. High fidelity visualization of what your self-supervised representation knows about. arXiv preprint arXiv:2112.09164, 2021. [20] Sanjeev Arora, Hrishikesh Khandeparkar, Mikhail Khodak, Orestis Plevrakis, and Nikunj Saunshi. A theoretical analysis of contrastive unsupervised representation learning. arXiv preprint arXiv:1902.09229, 2019. [21] Azade Nazi, Will Hang, Anna Goldie, Sujith Ravi, and Azalia Mirhoseini. Generalized clustering by learning to optimize expected normalized cuts. arXiv preprint arXiv:1910.07623, 2019. [22] Tongzhou Wang and Phillip Isola. Understanding contrastive representation learning through alignment and uniformity on the hypersphere. In International Conference on Machine Learning, pages 9929–9939. PMLR, 2020. [23] Haizhou Shi, Dongliang Luo, Siliang Tang, Jian Wang, and Yueting Zhuang. Run away from your teacher: Understanding byol by a novel self-supervised approach. arXiv preprint arXiv:2011.10944, 2020. [24] Jure Zbontar, Li Jing, Ishan Misra, Yann LeCun, and Stéphane Deny. Barlow twins: Selfsupervised learning via redundancy reduction. arXiv preprint arXiv:2103.03230, 2021. [25] Adrien Bardes, Jean Ponce, and Yann LeCun. Vicreg: Variance-invariance-covariance regularization for self-supervised learning. arXiv preprint arXiv:2105.04906, 2021. [26] Jason D Lee, Qi Lei, Nikunj Saunshi, and Jiacheng Zhuo. Predicting what you already know helps: Provable self-supervised learning. Advances in Neural Information Processing Systems, 34:309–323, 2021. [27] Yuandong Tian. Deep contrastive learning is provably (almost) principal component analysis. arXiv preprint arXiv:2201.12680, 2022. [28] Jeff Z HaoChen, Colin Wei, Adrien Gaidon, and Tengyu Ma. Provable guarantees for selfsupervised deep learning with spectral contrastive loss. Advances in Neural Information Processing Systems, 34, 2021. [29] Jeff Z HaoChen, Colin Wei, Ananya Kumar, and Tengyu Ma. Beyond separability: Analyzing the linear transferability of contrastive representations to related subpopulations. arXiv preprint arXiv:2204.02683, 2022. [30] Christopher Tosh, Akshay Krishnamurthy, and Daniel Hsu. Contrastive learning, multi-view redundancy, and linear models. In Algorithmic Learning Theory, pages 1179–1206. PMLR, 2021. [31] Jean-Bastien Grill, Florian Strub, Florent Altché, Corentin Tallec, Pierre Richemond, Elena Buchatskaya, Carl Doersch, Bernardo Avila Pires, Zhaohan Guo, Mohammad Gheshlaghi Azar, et al. Bootstrap your own latent-a new approach to self-supervised learning. Advances in Neural Information Processing Systems, 33:21271–21284, 2020. [32] Debidatta Dwibedi, Yusuf Aytar, Jonathan Tompson, Pierre Sermanet, and Andrew Zisserman. With a little help from my friends: Nearest-neighbor contrastive learning of visual representations. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 9588–9597, 2021. [33] Carl Eckart and Gale Young. The approximation of one matrix by another of lower rank. Psychometrika, 1(3):211–218, 1936. [34] Ulrike Von Luxburg. A tutorial on spectral clustering. Statistics and computing, 17(4):395–416, 2007. [35] Mikhail Belkin and Partha Niyogi. Laplacian eigenmaps for dimensionality reduction and data representation. Neural computation, 15(6):1373–1396, 2003. [36] Roger W Brockett. Dynamical systems that sort lists, diagonalize matrices, and solve linear programming problems. Linear Algebra and its applications, 146:79–91, 1991. [37] Aleksandr Ermolov, Aliaksandr Siarohin, Enver Sangineto, and Nicu Sebe. Whitening for self-supervised representation learning. In International Conference on Machine Learning, pages 3015–3024. PMLR, 2021. [38] David Pfau, Stig Petersen, Ashish Agarwal, David G. T. Barrett, and Kimberly L. Stachenfeld. Spectral inference networks: Unifying deep and spectral learning. In International Conference on Learning Representations, 2019. URL https://openreview.net/forum?id $=$ SJzqpj09YQ. [39] Akshay Agrawal, Alnur Ali, Stephen Boyd, et al. Minimum-distortion embedding. Foundations and Trends® in Machine Learning, 14(3):211–378, 2021. [40] Ville Hautamaki, Ismo Karkkainen, and Pasi Franti. Outlier detection using k-nearest neighbour graph. In Proceedings of the 17th International Conference on Pattern Recognition, 2004. ICPR 2004., volume 3, pages 430–433. IEEE, 2004. [41] Yoshua Bengio, Jean-françcois Paiement, Pascal Vincent, Olivier Delalleau, Nicolas Roux, and Marie Ouimet. Out-of-sample extensions for lle, isomap, mds, eigenmaps, and spectral clustering. Advances in neural information processing systems, 16, 2003. [42] Xiaofei He and Partha Niyogi. Locality preserving projections. Advances in neural information processing systems, 16, 2003. [43] Ronald A Fisher. The use of multiple measurements in taxonomic problems. Annals of eugenics, 7(2):179–188, 1936. [44] Patricia Cohen, Stephen G West, and Leona S Aiken. Applied multiple regression/correlation analysis for the behavioral sciences. Psychology press, 2014. [45] Ralph G O’Brien and Mary K Kaiser. Manova method for analyzing repeated measures designs: an extensive primer. Psychological bulletin, 97(2):316, 1985. [46] Carl J Huberty and Stephen Olejnik. Applied MANOVA and discriminant analysis. John Wiley & Sons, 2006. [47] Sebastian Mika, Gunnar Ratsch, Jason Weston, Bernhard Scholkopf, and Klaus-Robert Mullers. Fisher discriminant analysis with kernels. In Neural networks for signal processing IX: Proceedings of the 1999 IEEE signal processing society workshop (cat. no. 98th8468), pages 41–48. Ieee, 1999. [48] Sergey Ioffe. Probabilistic linear discriminant analysis. In European Conference on Computer Vision, pages 531–542. Springer, 2006. [49] Jing-Hao Xue and Peter Hall. Why does rebalancing class-unbalanced data improve auc for linear discriminant analysis? IEEE transactions on pattern analysis and machine intelligence, 37(5):1109–1112, 2014. [50] Soroush Abbasi Koohpayegani, Ajinkya Tejankar, and Hamed Pirsiavash. Mean shift for selfsupervised learning. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 10326–10335, 2021. [51] Xiaowen Dong, Dorina Thanou, Pascal Frossard, and Pierre Vandergheynst. Learning laplacian matrix in smooth graph signal representations. IEEE Transactions on Signal Processing, 64 (23):6160–6173, 2016. [52] Vassilis Kalofolias. How to learn a graph from smooth signals. In Artificial Intelligence and Statistics, pages 920–929. PMLR, 2016. [53] Joshua B Tenenbaum, Vin de Silva, and John C Langford. A global geometric framework for nonlinear dimensionality reduction. science, 290(5500):2319–2323, 2000. [54] Joseph B Kruskal. Multidimensional scaling by optimizing goodness of fit to a nonmetric hypothesis. Psychometrika, 29(1):1–27, 1964. [55] Franco P Preparata and Michael I Shamos. Computational geometry: an introduction. Springer Science & Business Media, 2012. [56] Andrew R Webb. Multidimensional scaling by iterative majorization using radial basis functions. Pattern Recognition, 28(5):753–759, 1995. [57] Christopher Williams. On a connection between kernel pca and metric multidimensional scaling. Advances in neural information processing systems, 13, 2000. [58] Bernhard Schölkopf, Alexander Smola, and Klaus-Robert Müller. Nonlinear component analysis as a kernel eigenvalue problem. Neural computation, 10(5):1299–1319, 1998. [59] Jacques Dauxois and Guy Martial Nkiet. Nonlinear canonical analysis and independence tests. The Annals of Statistics, 26(4):1254–1278, 1998. [60] Pei Ling Lai and Colin Fyfe. Kernel and nonlinear canonical correlation analysis. International Journal of Neural Systems, 10(05):365–377, 2000. [61] Kenji Fukumizu, Francis R Bach, and Arthur Gretton. Statistical consistency of kernel canonical correlation analysis. Journal of Machine Learning Research, 8(2), 2007. [62] Galen Andrew, Raman Arora, Jeff Bilmes, and Karen Livescu. Deep canonical correlation analysis. In International conference on machine learning, pages 1247–1255. PMLR, 2013. [63] Arthur Gretton, Ralf Herbrich, Alexander Smola, Olivier Bousquet, Bernhard Schölkopf, et al. Kernel methods for measuring independence. 2005. [64] Malte Kuss and Thore Graepel. The geometry of kernel canonical correlation analysis. 2003. [65] Daniela M Witten, Robert Tibshirani, and Trevor Hastie. A penalized matrix decomposition, with applications to sparse principal components and canonical correlation analysis. Biostatistics, 10(3):515–534, 2009. [66] Laurenz Wiskott and Terrence J Sejnowski. Slow feature analysis: Unsupervised learning of invariances. Neural computation, 14(4):715–770, 2002. [67] Huan Xu, Constantine Caramanis, and Sujay Sanghavi. Robust pca via outlier pursuit. Advances in neural information processing systems, 23, 2010. [68] Magnus R Hestenes. Inversion of matrices by biorthogonalization and related results. Journal of the Society for Industrial and Applied Mathematics, 6(1):51–90, 1958. [69] Han Bao, Yoshihiro Nagano, and Kento Nozawa. Sharp learning bounds for contrastive unsupervised representation learning. arXiv preprint arXiv:2110.02501, 2021. [70] Gene H Golub and Christian Reinsch. Singular value decomposition and least squares solutions. In Linear algebra, pages 134–151. Springer, 1971. [71] Like Hui and Mikhail Belkin. Evaluation of neural architectures trained with square loss vs crossentropy in classification tasks, 2020. URL https://arxiv.org/abs/2006.07322. [72] Robert Geirhos, Kantharaju Narayanappa, Benjamin Mitzkus, Matthias Bethge, Felix A Wichmann, and Wieland Brendel. On the surprising similarities between supervised and selfsupervised models. arXiv preprint arXiv:2010.08377, 2020. [73] Nicholas J Higham. Computing a nearest symmetric positive semidefinite matrix. Linear algebra and its applications, 103:103–118, 1988. [74] Octavian Ganea, Sylvain Gelly, Gary Bécigneul, and Aliaksei Severyn. Breaking the softmax bottleneck via learnable monotonic pointwise non-linearities. In International Conference on Machine Learning, pages 2073–2082. PMLR, 2019. [75] Zhilin Yang, Zihang Dai, Ruslan Salakhutdinov, and William W Cohen. Breaking the softmax bottleneck: A high-rank rnn language model. arXiv preprint arXiv:1711.03953, 2017. [76] H Knaf. Kernel fisher discriminant functions–a concise and rigorous introduction. 2007. [77] Andrew J Wathen and Shengxin Zhu. On spectral distribution of kernel matrices related to radial basis functions. Numerical Algorithms, 70(4):709–726, 2015. [78] Xin Liang, Ren-Cang Li, and Zhaojun Bai. Trace minimization principles for positive semidefinite pencils. Linear Algebra and its Applications, 438(7):3085–3106, 2013. [79] Effrosini Kokiopoulou, Jie Chen, and Yousef Saad. Trace optimization and eigenproblems in dimension reduction methods. Numerical Linear Algebra with Applications, 18(3):565–602, 2011. [80] Andrew R Webb. Statistical pattern recognition. John Wiley & Sons, 2003. [81] Yue-Fei Guo, Shi-Jin Li, Jing-Yu Yang, Ting-Ting Shu, and Li-De Wu. A generalized foley– sammon transform based on generalized fisher discriminant criterion and its application to face recognition. Pattern Recognition Letters, 24(1-3):147–158, 2003. [82] Huan Wang, Shuicheng Yan, Dong Xu, Xiaoou Tang, and Thomas Huang. Trace ratio vs. ratio trace for dimensionality reduction. In 2007 IEEE Conference on Computer Vision and Pattern Recognition, pages 1–8. IEEE, 2007. [83] Cheng Li and Bingyu Wang. Fisher linear discriminant analysis. CCIS Northeastern University, 2014. [84] Maurice S Bartlett. Further aspects of the theory of multiple regression. In Mathematical Proceedings of the Cambridge Philosophical Society, volume 34, pages 33–40. Cambridge University Press, 1938. [85] Trevor Hastie, Andreas Buja, and Robert Tibshirani. Penalized discriminant analysis. The Annals of Statistics, 23(1):73–102, 1995. [86] MJR Healy. A rotation method for computing canonical correlations. Mathematics of Computation, 11(58):83–86, 1957. [87] L Magnus Ewerbring and Franklin T Luk. Canonical correlations and generalized svd: applications and new algorithms. Journal of computational and applied mathematics, 27(1-2):37–52, 1989. [88] David R Hardoon, Sandor Szedmak, and John Shawe-Taylor. Canonical correlation analysis: An overview with application to learning methods. Neural computation, 16(12):2639–2664, 2004. [89] Olcay Kursun, Ethem Alpaydin, and Oleg V Favorov. Canonical correlation analysis using within-class coupling. Pattern Recognition Letters, 32(2):134–144, 2011.
[90] Viivi Uurtio, João M Monteiro, Jaz Kandola, John Shawe-Taylor, Delmiro Fernandez-Reyes, and Juho Rousu. A tutorial on canonical correlation methods. ACM Computing Surveys (CSUR), 50(6):1–33, 2017.
# Checklist
1. For all authors...
(a) Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope? [Yes] Each section of the study answers a specific aspect of the abstract (b) Did you describe the limitations of your work? [Yes] We discussed the assumptions of each result. (c) Did you discuss any potential negative societal impacts of your work? [N/A] We do not believe that our work has any potential negative societal impacts (d) Have you read the ethics review guidelines and ensured that your paper conforms to them? [Yes]
2. If you are including theoretical results...
(a) Did you state the full set of assumptions of all theoretical results? [Yes] For each method we carefully state our assumptions and provide background and citations for known results/assumptions (b) Did you include complete proofs of all theoretical results? [Yes] All the proofs are carefully expressed in multiple appendices with additional details to ensure full transparency on our results.
3. If you ran experiments...
(a) Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? [Yes] Code to reproduce the figures is provided in the supplementary materials (b) Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? [Yes] For each figure we provided the exact hyper-parameters used in each case within the caption (c) Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? [No] We only provide empirical validation that do not require errors bars (d) Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? [No] We only provide empirical validation on toy settings that do not require GPU or cluster computations
4. If you are using existing assets (e.g., code, data, models) or curating/releasing new assets...
(a) If your work uses existing assets, did you cite the creators? [N/A] we did not use existing assets (b) Did you mention the license of the assets? [Yes] No licence provided (c) Did you include any new assets either in the supplemental material or as a URL? [Yes] We include in the supplementary material the code to reproduce the figures provides in this paper. (d) Did you discuss whether and how consent was obtained from people whose data you’re using/curating? [N/A] (e) Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? [N/A]
5. If you used crowdsourcing or conducted research with human subjects...
(a) Did you include the full text of instructions given to participants and screenshots, if applicable? [N/A] (b) Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? [N/A] (c) Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? [N/A]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277# Multi-Scale Representation Learning on Proteins
Vignesh Ram Somnath∗ Dept. of Computer Science ETH Zurich vsomnath@ethz.ch
Charlotte Bunne∗ Dept. of Computer Science ETH Zurich bunnec@ethz.ch
Andreas Krause Dept. of Computer Science ETH Zurich krausea@ethz.ch
# Abstract
Proteins are fundamental biological entities mediating key roles in cellular function and disease. This paper introduces a multi-scale graph construction of a protein – HOLOPROT – connecting surface to structure and sequence. The surface captures coarser details of the protein, while sequence as primary component and structure – comprising secondary and tertiary components – capture finer details. Our graph encoder then learns a multi-scale representation by allowing each level to integrate the encoding from level(s) below with the graph at that level. We test the learned representation on different tasks, (i.) ligand binding affinity (regression), and (ii.) protein function prediction (classification). On the regression task, contrary to previous methods, our model performs consistently and reliably across different dataset splits, outperforming all baselines on most splits. On the classification task, it achieves a performance close to the top-performing model while using $1 0 \mathrm { x }$ fewer parameters. To improve the memory efficiency of our construction, we segment the multiplex protein surface manifold into molecular superpixels and substitute the surface with these superpixels at little to no performance loss.
# 1 Introduction
Protein design and engineering has become a crucial component of pharmaceutical research and development, finding application in a wide variety of diagnostic and industrial settings. Besides understanding the design principles determining structure and function of proteins, current efforts seek to further enhance or discover proteins with properties useful for technological or therapeutic applications. To efficiently guide the search in the vast design space of functional proteins, we need to be able to robustly predict properties of a candidate protein [Yang et al., 2019]. Moreover, understanding role and function of proteins is crucial to study causes and mechanism of human disease [Fessenden, 2017].
To achieve this, representations incorporating the complex nature of proteins are required. Proteins consist of amino acids, organic molecules linked by peptide bonds forming a linear sequence. Each of the twenty amino acids carries a unique side chain, giving rise to an incomprehensibly large combinatorial space of possible protein sequences. The primary sequence drives the folding of polymers – a spontaneous process guided by hydrophobic interactions, formation of intramolecular hydrogen bonds, and van der Waals forces into a unique three-dimensional structure. The resulting shape and surface manifold with rich physiochemical properties carry essential information for understanding function and potential molecular interactions.
Previous methods typically only consider an individual subset within these scales, focusing on either sequence [Öztürk et al., 2018, Hou et al., 2018], three-dimensional structure [Hermosilla et al., 2021, Derevyanko et al., 2018] or surface [Gainza et al., 2020]. Two proteins with similar sequences can fold into entirely different conformations. While these proteins might catalyze the same type of ooreactions, their behavior to specific inhibiting drugs might be divergent. Interaction between proteins and ligands, on the other hand, is controlled by molecular surface contacts [Gainza et al., 2020]. Molecular surfaces, determined by subjacent amino acids, are fingerprinted with patterns of geometric and chemical properties, and thus their integration in protein representations is crucial.
 Figure 1: Overview of HOLOPROT Our multi-scale protein representation algorithm integrates primary, secondary and tertiary elements of protein structures and connects them to the surface. We extract higher-level protein motifs by introducing molecular superpixels. Both structure and surface are represented as graphs $\mathcal { G } _ { B }$ and $\mathcal { G } _ { S }$ , respectively. The method is evaluated on two representative fintasks, protein-ligand binding affinity and enzyme-catalyzed reaction classification.
In this work, we present a novel multi-scale graph representation which integrates and connects the complex nature of proteins across all levels of information. HOLOPROT consists of a surface and structure layer (both represented as graphs) with explicit edges between the layers. Our construction finiris guided by the intuition that propagating information from surface to structure would allow each residue to learn encodings reflective of not just its immediate residue neighborhood, but also the higher-level geometric and chemical properties that arise from interactions between a residue and ooits neighborhood. The associated multi-scale encoder then learns representations by integrating sathe encoding from the layer below, with the graph at that layer (Section 3). Such multi-scale representations have been previously used in molecular graph generation [Jin et al., 2020] with impressive results.
We further improve the memory efficiency of our construction by segmenting the large and rich protein surface into molecular “superpixels”, summarizing higher-level fingerprint features and motifs of proteins. Substituting the surface layer with these superpixels results in little to no performance degradation across the evaluated tasks. The concept of molecular superpixels might be of interest beyond our model (Section 4).
The multi-objective and multi-task nature of protein engineering poses a challenge for current methods, often designed and evaluated only on specific subtasks of protein design. By incorporating the biology of proteins, strong representations exhibit robust performance across tasks. We demonstrate our model’s versatility and range of applications by deploying it to tasks of rather distinct nature, including a regression task, e.g., inference of protein ligand binding affinity, and classification tasks, i.e., enzyme-catalyzed reaction classification (Section 5).
# 2 Related Work
Protein Representation Learning With increasing availability of sequence and structure data, the field of protein representation learning has advanced rapidly, with methods falling largely in one of the following categories:
Sequence-based methods. One-dimensional amino acid sequences continue to be the simplest, most abundant source of protein data and various methods have been developed that borrow architectures developed in natural language processing (NLP). One-dimensional convolutional neural networks have been used to classify a protein sequence into folds and enzyme function [Hou et al., 2018, Dalkiran et al., 2018], and to predict their binding affinity to ligands [Öztürk et al., 2018]. Furthermore, methods have applied complex NLP models trained unsupervised on millions of unlabeled protein sequences and fine-tuned them on different downstream tasks [Rao et al., 2019, Elnaggar et al., 2020, Bepler and Berger, 2019]. Despite being advantageous when only the sequence is available, these methods ignore the full spatial complexity of proteins.
Structure-based methods. To learn beyond sequences, approaches have been developed, that consider the 3D structure of proteins. 3D convolutional neural networks have been utilized for protein quality assessment [Derevyanko et al., 2018], protein contact prediction [Townshend et al., 2019] and protein-ligand binding affinity tasks [Ragoza et al., 2017, Jiménez et al., 2018, Townshend et al., 2020]. An alternate representation treats proteins as graphs, applying graph neural networks for enzyme classification [Dobson and Doig, 2005], interface prediction [Fout et al., 2017], and protein structure quality prediction [Baldassarre et al., 2021]. Gligorijevic et al. [2021] use a long short term memory cell (LSTM) to encode the sequence, followed by a graph convolutional network (GCN) [Kipf and Welling, 2017] to capture the tertiary structure, and apply this to the function prediction task. Hermosilla et al. [2021] propose a convolutional operator that learns to adapt filters based on the primary, secondary, and tertiary structure of a protein, showing strong performance on reaction and fold class prediction.
Surface-based methods. Taking a different viewpoint, Gainza et al. [2020] hypothesize that the protein surface displays patterns of chemical and geometric features that fingerprint a protein’s interaction with other biomolecules. They utilize geodesic convolutions, which are extensions of convolutions on surfaces, and learn fingerprint vectors, showing improved performance across binding pocket and protein interface prediction tasks.
Protein Motif Detection Protein motifs have largely been synonymous with common and conserved patterns in a protein’s sequence or structure influencing protein function, e.g., the helixturn-helix motif binds DNA. Understanding these fragments is essential for 3D structure prediction, modeling, and drug design. While reliably detecting evolutionary motifs, existing tools [Golovin and Henrick, 2008] do not provide a full segmentation of the protein surface manifold. Our work takes a different viewpoint, by looking at protein motifs from the context of a protein surface. Previous methods developed in this context either only consider geometric information rather than physiological properties [Cantoni et al., 2010], are computationally expensive [Cantoni et al., 2011], or designed for particular downstream tasks [Stepniewska-Dziubinska et al., 2020]. Our molecular superpixel approach provides a task-independent segmentation utilizing both geometric and chemical features, while also being computationally efficient.
# 3 Multi-Scale Protein Representation
In this section, we describe our multi-scale graph construction and the associated encoder. Figure 1 illustrates the main principles of HOLOPROT. We represent a protein $\mathcal { P }$ as a graph $\mathcal { G } _ { \mathcal { P } }$ with two layers capturing different scales:
(i.) Surface layer. This layer captures the coarser representation details of a protein. The protein surface is generated using the triangulation software MSMS [Connolly, 1983, Sanner et al., 1996]. We represent this layer as a graph $\mathcal { G } _ { S }$ , where each surface node $u _ { \cal S }$ has a feature vector $\mathbf { f } _ { u _ { S } }$ denoting its charge, hydrophobicity and local curvature [Gainza et al., 2020]. Two surface nodes $( u _ { S } , v _ { S } )$ have an edge if they are part of a triangulation. Each surface node additionally has a residue identifier $r$ , indicating the amino acid residue it corresponds to. Multiple surface nodes can have the same residue identifier. (ii.) Structure layer. This layer captures the finer representation details of a protein. A protein typically has four structural levels: (i.) primary structure (sequence), (ii.) secondary structure $\alpha$ -helices and $\beta$ -sheets), (iii.) tertiary structure (3D structure) and (iv.) quaternary structure (complexes) [Fout et al., 2017]. We represent this layer as a graph $\mathcal { G } _ { B }$ , where each node $u _ { B }$ corresponds to a residue $r$ . Two nodes $( u _ { B } , v _ { B } )$ have an edge in $\mathcal { G } _ { B }$ if the $\mathbf { C } _ { \alpha }$ atoms of the two nodes occur within a certain distance of each other. Distance based thresholding ensures that different structural levels are implicitly captured in the neighborhood of a node $u _ { B }$ .
We further introduce edges from the surface layer to the structure layer in order to propagate information between them. Specifically, we introduce a directed edge between a surface node $u _ { \mathcal { S } }$ and a backbone node $u _ { B }$ if they both have the same residue identifier $r$ . Typically, we have between 20-40 surface nodes $\{ u _ { \mathcal { S } } \}$ that map to the same structure node $u _ { B }$ . This gives us the multi-scale graph which is then encoded by our multi-scale message passing network. Details on the features used for both the structure and surface layer can be found in Appendix ??.
# 3.1 Multi-Scale Encoder
Our multi-scale message passing network uses one message passing neural network (MPN) for each layer in the multi-scale graph [Lei et al., 2017, Gilmer et al., 2017]. This allows us to learn structured representations of each scale, which can then be tied together through connections between the scales. Before detailing the remainder of the architecture, we introduce some notational preliminaries. For simplicity, we denote the MPN encoding process as $\mathbf { M P N } _ { \theta } ( \cdot )$ with parameters $\theta$ . We denote $\mathbf { M L P } _ { \theta } ( \bar { \mathbf { x } } , \mathbf { y } )$ for a multi-layer perceptron (MLP) with parameters $\theta$ , whose input is the concatenation of $\mathbf { x }$ and $\mathbf { y }$ , and $\operatorname { M L P } _ { \theta } ( \mathbf { x } )$ when the input is only $\mathbf { x }$ . We also denote the residue identifier of a node $u$ with $\operatorname { i d } ( u )$ , and the neighbors of a node $u$ as $\mathcal { N } ( u )$ . The details of the MPN architecture are listed in the Appendix ??.
# 3.1.1 Surface Message Passing Network
We first encode the surface layer $\mathcal { G } _ { S }$ of the multi-scale protein graph $\mathcal { G } _ { \mathcal { P } }$ . The inputs to the MPN are node features $\mathbf { f } _ { u _ { S } }$ and edge features $\mathbf { f } _ { u _ { S } v _ { S } }$ of $\mathcal { G } _ { S }$ . For more details on the input features used for surface nodes and edges, refer to Appendix ??. The MPN (with parameters $\theta _ { S }$ ) propagates messages between the nodes for $K$ iterations, and outputs a representation $h _ { u s }$ for each surface node $u _ { \cal S }$ ,
$$\{ \mathbf h _ { u _ { S } } \} = \mathrm { M P N } _ { \theta _ { S } } ( \mathcal G _ { S } , \{ \mathbf f _ { u _ { S } } \} , \{ \mathbf f _ { u _ { S } v _ { S } } \} _ { v _ { S } \in \mathcal N ( u _ { S } ) } ) .$$
# 3.1.2 Structure Message Passing Network
For each node $u _ { B }$ in the structure layer $\mathcal { G } _ { B }$ , we first prepare the input to the MPN (with parameters $\theta _ { B } ,$ ) by using an MLP (with parameters $\theta$ ) on the concatenated version of its initial features $\mathbf { f } _ { u B }$ and the mean of the surface node vectors with the same residue identifier $S = \{ \mathbf { h } _ { u _ { s } } | \mathrm { i d } ( u _ { S } ) = \mathrm { i d } ( \bar { u } _ { B } ) \}$
$$\begin{array} { r } { { \bf x } _ { u s } = \mathrm { M L P } _ { \theta } \big ( { \bf f } _ { u s } , \Sigma _ { s } { \bf h } _ { u _ { S } } \big / | S | \big ) . } \end{array}$$
Given the edge features $\mathbf { f } _ { u B v s }$ , we then run $K$ iterations of message passing, to compute the representations $\mathbf { h } _ { u _ { B } }$ for each structure node $u _ { B }$ ,
$$\begin{array} { r } { \{ \mathbf { h } _ { u _ { B } } \} = \mathrm { M P N } _ { \theta _ { B } } ( \mathcal G _ { B } , \{ \mathbf { x } _ { u _ { B } } \} , \{ \mathbf { f } _ { u _ { B } v _ { B } } \} _ { v _ { B } \in \mathcal N ( u _ { B } ) } ) . } \end{array}$$
The graph representation $\mathbf { c } _ { \mathcal { G } _ { \mathcal { P } } }$ is an aggregation of structure node representations,
$$\mathbf { c } _ { \mathcal { G } _ { \mathcal { P } } } = \sum _ { u _ { B } \in \mathcal { G } _ { B } } \mathbf { h } _ { u _ { B } } .$$
# 3.2 Task Specific Training
This multi-scale encoding allows us to learn a structured representation of a protein tying different scales together, which can then be utilized for any downstream task. In this work, we evaluate our method on two rather distinct tasks (i.) protein-ligand binding affinity regression, and (ii.) enzyme– catalyzed reaction classification. The architectural details for both downstream tasks are described below. These modules can be adapted and modified in order to utilize HOLOPROT for other use cases.
# 3.2.1 Protein-Ligand Binding Affinity
Protein-ligand binding affinity prediction depends on the interaction of a protein, encoded using the HOLOPROT framework, and a corresponding ligand, in most cases small molecules. To encode the ligand represented as a graph $\mathcal { G } _ { \mathcal { L } }$ , we use another MPN (with parameters $\theta _ { \mathcal { L } }$ ) and aggregate its node representations to obtain a graph representation $c _ { \mathcal { G } _ { \mathcal { L } } }$ . We concatenate the graph representations $\mathbf { c } _ { \mathcal { G } _ { \mathcal { P } } }$ (Equation 1) of the protein and $c _ { \mathcal { G } _ { \mathcal { L } } }$ of the ligand, and use that as input to a MLP (with parameters $\phi$ ) to obtain predictions,
$$s _ { a } = \mathrm { M L P } _ { \phi } ( c _ { \mathcal { G } _ { \mathcal { P } } } , c _ { \mathcal { G } _ { \mathcal { L } } } ) .$$
The model is trained by minimizing the mean squared error.
 Figure 2: Molecular Superpixels and Surface Features of the HIV-1 Protease (PDB ID: 2AVQ). a. Molecular superpixels, indicated by different colors $k = 2 0$ ), and the corresponding surface features, i.e., b. hydropathy, c. shape index, and d. free electrons. As highlighted, molecular superpixels are spatially compact and overlap with surface regions dominated by single features such as hydrophobic patches while capturing coherent areas across all surface features. The protein complex contains 198 residues.
# 3.2.2 Enzyme-Catalyzed Reaction Classification
To predict the enzyme-catalyzed reaction class, we use the graph representation $\mathbf { c } _ { \mathcal { G } _ { \mathcal { P } } }$ of the protein obtained via HOLOPROT as the input to a MLP (with parameters $\phi$ ) to obtain the prediction logits,
$$p _ { k } = \mathrm { M L P } _ { \phi } ( c _ { \mathcal { G } } ) .$$
The model is trained by minimizing the cross-entropy loss.
# 4 Superpixels on Molecular Surfaces
Protein surface manifolds are complex and represented via large meshes. In order to improve the computational and memory efficiency of our construction, we introduce the notion of molecular superpixels. Originally developed in computer vision [Ren and Malik, 2003, Mori et al., 2004, Kohli et al., 2009], superpixels are defined as perceptually uniform regions in the image. In the molecular context, we refer to superpixels as segments on the protein surface capturing higher-level fingerprint features and protein motifs such as hydrophobic binding sites.
In order to apply the segmentation principle to three-dimensional molecular surfaces, we employ graph-based superpixel algorithms on triangulated surface meshes. The superpixel representation of the protein surface needs to satisfy several requirements, as (i.) molecular superpixels should not reduce the overall achievable performance of HOLOPROT, and (ii.) molecular superpixels need to form geometrically compact clusters, and overlap with surface regions that are coherent in physiological surface properties, e.g., capture hydrophobic binding sides or highly charged areas. Popular graph-based segmentation tools such as Felzenszwalb and Huttenlocher [2004, FH], mean shift [Comaniciu and Meer, 2002], and watershed [Vincent and Soille, 1991], however, produce non-compact superpixels of irregular sizes and shapes. By posing the segmentation task as a maximization problem on a graph maximizing over (i.) the entropy rate of the random walk on the surface graph $\bar { \mathcal { G } } s = ( \gamma _ { S } , \mathcal { E } _ { S } )$ favoring the formation of compact and homogeneous clusters, and (ii.) a balancing term encouraging clusters with similar sizes, the entropy rate superpixel (ERS) segmentation algorithm [Liu et al., 2011] outperforms previous methods across different tasks [Stutz et al., 2018] and achieves the desired properties of molecular superpixels.
In order to incorporate geometric and chemical features of the surface $\mathbf { F } _ { S }$ , we extend the surface graph $\mathcal { G } _ { S } = ( \nu _ { S } , \mathcal { E } _ { S } )$ with a non-negative similarity measure $w$ , given as $\begin{array} { r } { w _ { i j } = \sum _ { \mathbf { f } \in \mathbf { F } _ { \mathcal { S } } } | \mathbf { f } _ { v _ { i } } \mathbf { f } _ { v _ { j } } | } \end{array}$ for nodes $v _ { i }$ and $v _ { j }$ if connected by an edge $e _ { i j }$ . We simulate a random walk $\mathbf { X } = \{ X _ { t } | t \in T , X _ { t } \in \mathcal { V } _ { S } \}$ on a protein surface mesh, where the transition probability $p _ { i j }$ between two nodes $v _ { i }$ and $v _ { j }$ is defined as $p _ { i j } = P ( X _ { t + 1 } = v _ { j } | X _ { t } = v _ { i } ) = w _ { i j } / w _ { i }$ , where $\begin{array} { r } { \boldsymbol { w } _ { i } = \sum _ { k : e _ { i k } \in \mathcal { E } _ { S } } \boldsymbol { w } _ { i k } } \end{array}$ .The corresponding stationary distributions of nodes $\gamma _ { s }$ are given by
$$\pmb { \mu } = \left( \mu _ { 1 } , \mu _ { 2 } , . . . , \mu _ { | \mathcal { V } s | } \right) ^ { \top } = \left( \frac { w _ { 1 } } { w _ { T } } , \frac { w _ { 2 } } { w _ { T } } , . . . , \frac { w _ { | \mathcal { V } s | } } { w _ { T } } \right) ^ { \top } .$$
Molecular superpixels are then defined by a subset of edges $\mathcal { M } \subseteq \mathcal { E } _ { S }$ such that the resulting graph, $\mathcal { G } _ { S } = ( \nu _ { S } , \bar { \mathcal { M } } )$ , contains exactly $k$ connected subgraphs. Computing molecular superpixels is achieved via optimizing the objective function with respect to the edge set $\mathcal { M }$
$$\operatorname* { m a x } _ { \mathcal { M } } - \sum _ { i } \mu _ { i } \sum _ { j } p _ { i j } ( \mathcal { M } ) \log \left( p _ { i j } ( \mathcal { M } ) \right) - \sum _ { i } p _ { Z _ { \mathcal { M } } } ( i ) \log \left( p _ { Z _ { \mathcal { M } } } ( i ) \right) - n _ { \mathcal { M } }$$
# s.t. $\mathcal { M } \subseteq \mathcal { E } _ { S }$ and $n _ { \mathcal { M } } \geq k$ ,
where $n _ { \mathcal { M } }$ is the number of connected components in the graph, $p _ { Z _ { \mathcal { M } } }$ denotes the distribution of cluster memberships $Z _ { \mathcal { M } }$ , and $\lambda \geq 0$ is the weight of the balancing term. Both terms satisfy monotonicity and submodularity and can thus be efficiently optimized based on techniques from submodular optimization [Nemhauser et al., 1978]. For further details on the entropy rate superpixel algorithm, see Liu et al. [2011].
A molecular superpixel $m$ comprising $k$ surface vertices is then given as $\mathbf { f } _ { m } = ( \mathbf { f } _ { v _ { 1 } } , \ldots , \mathbf { f } _ { v _ { k } } )$ for all f $\in \mathbf { F } _ { \mathcal { S } }$ . We summarize the feature representation of each molecular superpixel via the graph $\mathcal { G _ { M } } = ( \nu _ { \mathcal { M } } , \mathcal { E _ { M } } )$ , where each node $m \in \mathcal { V } _ { \mathcal { M } }$ is represented via $( \mathrm { m e a n } ( \mathbf { f } _ { m } )$ , std $( \mathbf { f } _ { m } )$ , $\mathtt { m a x } ( \mathbf { f } _ { m } )$ $\mathfrak { m i n } ( \mathbf { f } _ { m } ) )$ for all $\mathbf { f } \in \mathbf { F } _ { \mathcal { S } }$ and an edge $e \in \mathcal { E } _ { \mathcal { M } }$ via the Wasserstein distance between neighboring superpixels.
Figure 2 demonstrates molecular superpixels for the enzyme HIV-1 protease [Brik and Wong, 2003]. Besides being spatially compact, superpixels overlap with surface regions dominated by single features such as hydrophobic patches, while capturing coherent areas across all surface features. Further examples of superpixels are displayed in Appendix ??.
# 5 Evaluation
Successful protein engineering requires optimization of multiple objectives. When searching for a protein with desired functionality, auxiliary but crucial properties such as stability measured in terms of free energy of folding also need to be satisfied. Furthermore, the field is also subject to a plethora of potential tasks and applications. In order to capture the multi-objective and multi-task nature of protein engineering, we evaluate our method on two representative tasks: regression of the binding affinity between proteins and their ligands, and classification of enzyme proteins based on the type of reaction they catalyze.
# 5.1 Protein-Ligand Binding Affinity Prediction
Studying the interaction between proteins and small molecules is crucial for many downstream tasks, e.g., accelerating virtual screening for potential candidates in drug discovery or protein design to improve the output of an enzyme-catalyzed reaction. The architecture of the regression module is described in Equation 2.
Dataset. The PDBBIND database (version 2019) [Liu et al., 2017] is a collection of the experimentally measured binding affinity data for all types of biomolecular complexes deposited in the Protein Data Bank [Berman et al., 2000]. After quality filtering for resolution and surface construction, the refined subset comprises a total of 4, 709 biomolecular complexes. The binding affinity provided in PDBBIND is experimentally determined and expressed in molar units of the inhibition constant $( K _ { i } )$ or dissociation constant $( K _ { d } )$ . Similar to previous methods [Öztürk et al., 2018, Townshend et al., 2020], we do not distinguish both constants and predict negative log-transformed binding affinity $p K _ { d } / p K _ { i }$ . We split the dataset into training, test and validation splits based on the scaffolds of the corresponding ligands (scaffold), or a $30 \%$ and a $60 \%$ sequence identity threshold (identity $30 \%$ , identity $60 \%$ ) to limit homologous ligands or proteins appearing in both train and test sets.
Baselines. For evaluating the overall performance on the regression task, we compare HOLOPROT against several baselines including current state-of-the-art methods on both tasks. This comprises sequence-based methods [Öztürk et al., 2018, Rao et al., 2019, Bepler and Berger, 2019, Elnaggar et al., 2020] as well as methods based on the three-dimensional structure of proteins [Townshend et al., 2020, Hermosilla et al., 2021], and recent methods using geometric deep learning on protein molecular surfaces [Gainza et al., 2020].
Table 1: Protein-Ligand Binding Affinity Prediction Results Comparison predictive performance of ligand binding affinity using the PDBbind dataset [Liu et al., 2017] of HOLOPROT against other methods. Results are reported for 3 experimental runs.
<table><tr><td>Model</td><td>#Params</td><td colspan="3">Sequence Identity (30 %)</td><td colspan="3">Sequence Identity (60 %)</td></tr><tr><td></td><td></td><td>RMSE</td><td>Pearson</td><td>Spearman</td><td>RMSE</td><td>Pearson</td><td>Spearman</td></tr><tr><td>Sequence-based Methods</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Ozturk et al. [2018]</td><td>1.93M</td><td>1.866 ± 0.080</td><td>0.472 ± 0.022</td><td>0.471 ± 0.024</td><td>1.762 ± 0.261</td><td>0.666 ± 0.012</td><td>0.663 ± 0.015</td></tr><tr><td>Bepler and Berger [2019]</td><td>48.8M 93.0M</td><td>1.985 ± 0.006</td><td>0.165 ± 0.006</td><td>0.152 ± 0.024</td><td>1.891 ± 0.004</td><td>0.249 ± 0.006</td><td>0.275 ± 0.008</td></tr><tr><td>Rao et al. [2019]</td><td>2.4M1</td><td>1.890 ± 0.035 1.544 ± 0.015</td><td>0.338 ± 0.044</td><td>0.286 ± 0.124 0.434± 0.058</td><td>1.633 ± 0.016 1.641 ± 0.016</td><td>0.568± 0.033</td><td>0.571 ± 0.021</td></tr><tr><td>Elnaggar et al.[2020] Surface-based Methods</td><td></td><td></td><td>0.438 ± 0.053</td><td></td><td></td><td>0.595 ± 0.014</td><td>0.588 ± 0.009</td></tr><tr><td>Gainza et al. [2020]</td><td>0.62M</td><td>1.484 ± 0.018</td><td>0.467 ± 0.020</td><td>0.455 ± 0.014</td><td>1.426 ± 0.017</td><td>0.709 ±0.008</td><td>0.701 ± 0.011</td></tr><tr><td>Structure-based Methods</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Townshend et al. [2020]2</td><td></td><td>1.429 ± 0.042</td><td>0.541 ± 0.029</td><td>0.532 ± 0.033</td><td>1.450 ± 0.024</td><td>0.716 ± 0.008</td><td>0.714 ± 0.009</td></tr><tr><td>Townshend et al.[2020]3</td><td>5.80M</td><td>1.936 ± 0.120 1.554 ± 0.016</td><td>0.581 ± 0.039 0.414 ± 0.053</td><td>0.647± 0.071</td><td>1.493 ± 0.010 1.473 ± 0.024</td><td>0.669 ± 0.013</td><td>0.691± 0.010</td></tr><tr><td>Hermosilla et al. [2021]</td><td></td><td></td><td></td><td>0.428 ±0.032</td><td></td><td>0.667 ± 0.011</td><td>0.675 ± 0.019</td></tr><tr><td>HOLOPROT (O)</td><td>1.44 M</td><td>1.464 ± 0.006</td><td>0.509 ± 0.002</td><td>0.500 ± 0.005</td><td>1.365 ± 0.038</td><td>0.749 ± 0.014</td><td>0.742 ± 0.011</td></tr><tr><td>HOLOPROT()</td><td>1.76 M</td><td>1.491 ± 0.004</td><td>0.491 ± 0.014</td><td>0.482 ± 0.017</td><td>1.416 ± 0.022</td><td>0.724 ± 0.011</td><td>0.715 ± 0.006</td></tr></table>
<table><tr><td>Model</td><td>#Params</td><td colspan="3">Scaffold</td></tr><tr><td></td><td></td><td>RMSE</td><td>Pearson</td><td>Spearman</td></tr><tr><td>Sequence-based Methods</td><td></td><td></td><td></td><td></td></tr><tr><td>Ozturk et al. [2018]</td><td>1.93 M</td><td>1.908 ± 0.145</td><td>0.384 ± 0.014</td><td>0.387 ± 0.016</td></tr><tr><td>Bepler and Berger [2019]</td><td>48.8M</td><td>1.864 ± 0.009</td><td>0.269 ±0.002</td><td>0.285 ± 0.019</td></tr><tr><td>Rao et al. [2019]</td><td>93.0M</td><td>1.680 ± 0.055</td><td>0.487 ± 0.029</td><td>0.462 ± 0.051</td></tr><tr><td>Elnaggar et al. [2020]</td><td>2.4M1</td><td>1.592 ± 0.009</td><td>0.398 ± 0.027</td><td>0.409 ± 0.029</td></tr><tr><td>Surface-based Methods Gainza et al. [2020]</td><td>0.62 M</td><td>1.583 ± 0.132</td><td>0.416 ± 0.111</td><td>0.412 ± 0.126</td></tr><tr><td>Structure-based Methods</td><td></td><td></td><td></td><td></td></tr><tr><td>Hermosilla et al. [2021]</td><td>5.80M</td><td>1.592 ± 0.012</td><td>0.365 ± 0.024</td><td>0.373 ± 0.019</td></tr><tr><td>HOLOPROT (O)</td><td>1.44 M</td><td>1.523 ± 0.028</td><td>0.489 ± 0.019</td><td>0.491 ± 0.020</td></tr><tr><td>HOLOPROT()</td><td>1.28M</td><td>1.516 ± 0.014</td><td>0.491 ± 0.016</td><td>0.493 ± 0.014</td></tr></table>
full surface molecular superpixels
Evaluation metrics. For evaluating different methods, we use three metrics – root mean squared error (RMSE), Pearson correlation coefficient, and Spearman correlation coefficient. We also include the mean and standard deviation across 3 experimental runs.
Results. Table 1 displays the results on protein-ligand binding affinity. HOLOPROT $( \circ , \bullet )$ performs consistently well across different tasks and dataset splits, outperforming all methods on the splits scaffold and identity $60 \%$ . On identity $30 \%$ , our method outperforms most baselines, while having lower variability across the evaluated metrics. HOLOPROT with molecular superpixels $( \bullet )$ performs similar to HOLOPROT on the entire surface, with no or little performance loss, suggesting that molecular superpixels capture meaningful biological motifs. We include the models from [Townshend et al., 2020] for completeness, but note that these models were trained only using the protein binding pocket. Binding sites on proteins are often structurally highly conserved regions [Panjkovich and Daura, 2010]. Considering only binding pockets, which vary less between the train and test splits, provides an additional simplification making the task less challenging. All other baselines were tested on the full proteins.
# 5.2 Enzyme-Catalyzed Reaction Classification
Predicting the reaction class of enzymes without the use of sequence similarity allows for efficient screening of de novo proteins, i.e., macromolecules without evolutionary homologs, for catalytic properties [des Jardins et al., 1997]. The architecture of the classification module is described in Equation 3).
Table 2: Enzyme-Catalyzed Reaction Classification Results Comparison of classification accuracy of HOLOPROT against other methods.
<table><tr><td>Model</td><td>Parameters</td><td>Reaction Class Accuracy</td></tr><tr><td>Sequence-based Methods</td><td></td><td></td></tr><tr><td>Hou et al. [2018]</td><td>41.7M</td><td>70.9 %</td></tr><tr><td>Bepler and Berger [2019]</td><td>31.7 M</td><td>66.7 %</td></tr><tr><td>Rao et al.[2019] (Transformer)</td><td>38.4M</td><td>69.8 %</td></tr><tr><td>Elnaggar et al. [2020]</td><td>420.0M</td><td>72.2 %</td></tr><tr><td>Structure-basedMethods</td><td></td><td></td></tr><tr><td>Kipf and Welling [2017]</td><td>1.0 M</td><td>67.3 %</td></tr><tr><td>Derevyanko et al. [2018]</td><td>6.0M</td><td>78.8 %</td></tr><tr><td>Hermosilla et al. [2021]</td><td>9.8M</td><td>87.2 %</td></tr><tr><td>HOLOPROT(O)</td><td>0.64M</td><td>77.8 %</td></tr><tr><td>HOLOPROT()</td><td>0.64 M</td><td>78.9 %</td></tr></table>
full surface molecular superpixels
Dataset. Enzyme Commission (EC) numbers constitute an ontological system with the purpose of defining and organizing enzyme functions [Webb, 1992]. The four digits of an EC number are related in a functional hierarchy, where the first level annotates the main enzymatic classes, while the next levels constitute subclasses, e.g. the EC number of the HIV-1 protease is 3.4.23.16. This task aims at predicting the enzyme-catalyzed reaction class of a protein based on according to all four levels of the EC number. We use the same dataset and splits as provided by [Hermosilla et al., 2021], comprising 37, 428 proteins from 384 EC numbers, with 29, 215 instances for training, 2, 562 instances for validation, and 5, 651 for testing. For more details on dataset construction, we refer to Hermosilla et al. [2021, Appendix C].
Baselines. For the classification task, we again compare HOLOPROT against several baselines including sequence-based methods [Hou et al., 2018], methods partially pretrained on millions of sequences [Rao et al., 2019, Bepler and Berger, 2019, Elnaggar et al., 2020] as well as methods utilizing principles of geometric deep learning [Kipf and Welling, 2017, Derevyanko et al., 2018, Hermosilla et al., 2021]. The values for different baselines are taken from [Hermosilla et al., 2021].
Evaluation metric. Model performance is measured via the mean accuracy score.
Results. We report the results of enzyme-catalyzed reaction classification in Table 2. While our method $( \circ , \bullet )$ is unable to outperform the current state-of-the-art method [Hermosilla et al., 2021], we achieve equivalent, if not better results to other methods at a fraction of the parameters used. Molecular superpixels also capture biologically meaningful protein surface motifs, as evidenced by a small increase in the overall classification performance.
# 5.3 Ablation Studies
To further evaluate the contribution of HOLOPROT to learning multi-scale protein representations, we conduct several ablation studies. First, we analyze if the performance of the multi-scale model outperforms its isolated components, i.e. when using only structure or surface representation for subsequent downstream tasks. The second ablation axis analyzes the construction of molecular superpixel representations. Besides computing summary features for each molecular superpixel as described in Section 4, we learn patch representations via a MPN on the superpixel graph. The ablation study were conducted on both tasks, ligand binding affinity (Section 5.1) and enzyme catalytic function classification (Section 5.2).
As displayed in Table 3, HOLOPROT with $( \bullet )$ and without molecular superpixels ( ) improve over the performance of structure and surface representations. Further, the results of the ablation study clearly show that different protein scales are more relevant for particular downstream tasks, e.g., predicting the enzyme-catalyzed reaction class from surface only results in poor performance. We further see no
Table 3: Ablation Studies Results Evaluation of architectural design choices of HOLOPROT by analyzing the performance of its individual components as well as feature summarization of molecular superpixels.
<table><tr><td>Model</td><td colspan="3">Ligand Binding Affinity Sequence Identity (30 %)</td><td>Enzyme Class</td></tr><tr><td></td><td>RMSE</td><td>Pearson</td><td>Spearman</td><td>Accuracy</td></tr><tr><td>Structure</td><td>1.476 ± 0.027</td><td>0.51 ± 0.029</td><td>0.503 ± 0.027</td><td>74.2 %</td></tr><tr><td>Surface</td><td>1.482 ± 0.015</td><td>0.512 ± 0.022</td><td>0.505 ± 0.017</td><td>28.6 %</td></tr><tr><td>HOLOPROT(O)</td><td>1.464 ± 0.006</td><td>0.509 ± 0.002</td><td>0.500 ± 0.005</td><td>77.8 %</td></tr><tr><td>HOLOPROT()</td><td>1.491 ± 0.004</td><td>0.491 ±0.014</td><td>0.482 ± 0.017</td><td>78.9 %</td></tr><tr><td>HOLOPROT()</td><td>1.491 ± 0.027</td><td>0.503 ±0.005</td><td>0.492 ± 0.004</td><td>75.7 %</td></tr></table>
full surface ? molecular superpixels molecular superpixel with MPN
improvement in applying a MPN within a molecular superpixel ( ) over using summary features ( ). Further ablation studies are presented in Appendix ??.
# 5.4 Limitations
Despite the reported success of HOLOPROT, our method faces some limitations. First, HOLOPROT relies on existing protein structures and the corresponding generated surface manifolds. However, protein sequence data still remains the most abundant data source, and in protein design, conformations of mutated macromolecules are unknown. This limitation could however be partly remedied, (i.) by the recent advancements in protein structure prediction [Senior et al., 2020, Jumper et al., 2021, AlphaFold] [Baek et al., 2021, RoseTTAFold] and protein structure determination methods such as cryo-electron microscopy [Callaway, 2020], and (ii.) by utilizing homology modeling algorithms on available wild type structures for mutant analysis [Schymkowitz et al., 2005]. Second, our method requires precomputed surface meshes, resulting in an additional preprocessing step before deploying HOLOPROT to the desired application. This bottleneck can be bypassed by utilizing techniques developed in the concurrent work by Sverrisson et al. [2020], which allow computation and sampling of the molecular surface on-the-fly.
# 6 Conclusion
In this work, we present a novel multi-scale protein graph construction, HOLOPROT, which integrates finer and coarser representation details of a protein by connecting sequence and structure with surface. We further establish molecular superpixels, which capture higher-level fingerprint motifs on the protein surface, improving the memory efficiency of our construction without reducing the overall performance. We validate HOLOPROT’s effectiveness and versatility through representative tasks on protein-ligand binding affinity and enzyme-catalyzed reaction class prediction. While being significantly more parameter-efficient, HOLOPROT performs consistently well across different tasks and dataset splits, partly outperforming current state-of-the-art methods. This will potentially be of great benefit and advantage when working with datasets of reduced size, e.g., comprising experiments on mutational fitness of proteins, thus opening up new possibilities within protein engineering and design, which we leave for future work.
# Acknowledgments
This project received funding from the Swiss National Science Foundation under the National Center of Competence in Research (NCCR) Catalysis under grant agreement 51NF40 180544. Moreover, we thank Mojmír Mutný and Clemens Isert for their valuable feedback.
# References
M. Baek, F. DiMaio, I. Anishchenko, J. Dauparas, S. Ovchinnikov, G. R. Lee, J. Wang, Q. Cong, L. N. Kinch, R. D. Schaeffer, et al. Accurate prediction of protein structures and interactions using a three-track neural network. Science, 373(6557), 2021.
F. Baldassarre, D. Menéndez Hurtado, A. Elofsson, and H. Azizpour. GraphQA: protein model quality assessment using graph convolutional networks. Bioinformatics, 37(3), 2021.
T. Bepler and B. Berger. Learning Protein Sequence Embeddings using Information From Structure. In International Conference on Learning Representations (ICLR), 2019.
H. M. Berman, J. Westbrook, Z. Feng, G. Gilliland, T. N. Bhat, H. Weissig, I. N. Shindyalov, and P. E. Bourne. The Protein Data Bank. Nucleic Acids Research, 28(1), 2000.
A. Brik and C.-H. Wong. HIV-1 protease: mechanism and drug discovery. Organic & Biomolecular Chemistry, 1(1), 2003.
E. Callaway. ’It will change everything’: DeepMind’s AI makes gigantic leap in solving protein structures. Nature, 2020.
V. Cantoni, R. Gatti, and L. Lombardi. Segmentation of SES for Protein Structure Analysis. In Bioinformatics, 2010.
V. Cantoni, R. Gatti, and L. Lombardi. 3D Protein Surface Segmentation through Mathematical Morphology. In International Joint Conference on Biomedical Engineering Systems and Technologies. Springer, 2011.
D. Comaniciu and P. Meer. Mean Shift: A Robust Approach Toward Feature Space Analysis. IEEE Transactions on Pattern Analysis and Machine Intelligence, 24(5), 2002.
M. L. Connolly. Solvent-accessible surfaces of proteins and nucleic acids. Science, 221(4612), 1983.
A. Dalkiran, A. S. Rifaioglu, M. J. Martin, R. Cetin-Atalay, V. Atalay, and T. Dogan. ECPred: a tool ˘ for the prediction of the enzymatic functions of protein sequences based on the EC nomenclature. BMC Bioinformatics, 19(1), 2018.
G. Derevyanko, S. Grudinin, Y. Bengio, and G. Lamoureux. Deep convolutional networks for quality assessment of protein folds. Bioinformatics, 34(23), 2018.
M. des Jardins, P. D. Karp, M. Krummenacker, T. J. Lee, and C. A. Ouzounis. Prediction of enzyme classification from protein sequence without the use of sequence similarity. In Proceedings. International Conference on Intelligent Systems for Molecular Biology, volume 5, 1997.
P. D. Dobson and A. J. Doig. Predicting Enzyme Class From Protein Structure Without Alignments. Journal of Molecular Biology, 345(1), 2005.
A. Elnaggar, M. Heinzinger, C. Dallago, G. Rihawi, Y. Wang, L. Jones, T. Gibbs, T. Feher, C. Angerer, D. Bhowmik, et al. ProtTrans: Towards Cracking the Language of Life’s Code Through SelfSupervised Deep Learning and High Performance Computing. arXiv Preprint, 2020.
P. F. Felzenszwalb and D. P. Huttenlocher. Efficient Graph-Based Image Segmentation. International Journal of Computer Vision, 59(2), 2004.
M. Fessenden. Protein maps chart the causes of disease. Nature, 549(7671), 2017.
A. Fout, J. Byrd, B. Shariat, and A. Ben-Hur. Protein Interface Prediction using Graph Convolutional Networks. In Advances in Neural Information Processing Systems (NeurIPS), volume 30, 2017.
P. Gainza, F. Sverrisson, F. Monti, E. Rodola, D. Boscaini, M. Bronstein, and B. Correia. Deciphering interaction fingerprints from protein molecular surfaces using geometric deep learning. Nature Methods, 17(2), 2020.
J. Gilmer, S. S. Schoenholz, P. F. Riley, O. Vinyals, and G. E. Dahl. Neural Message Passing for Quantum Chemistry. In International Conference on Machine Learning (ICML), 2017.
V. Gligorijevic, P. D. Renfrew, T. Kosciolek, J. K. Leman, K. Cho, T. Vatanen, D. Berenberg, B. Taylor, I. M. Fisk, R. J. Xavier, R. Knight, and R. Bonneau. Structure-Based Function Prediction using Graph Convolutional Networks. Nature Communications, 12(1), 2021.
A. Golovin and K. Henrick. MSDmotif: exploring protein sites and motifs. BMC Bioinformatics, 9 (1), 2008. P. Hermosilla, M. Schäfer, M. Lang, G. Fackelmann, P.-P. Vázquez, B. Kozlikova, M. Krone, T. Ritschel, and T. Ropinski. Intrinsic-Extrinsic Convolution and Pooling for Learning on 3D Protein Structures. In International Conference on Learning Representations (ICLR), 2021. J. Hou, B. Adhikari, and J. Cheng. DeepSF: deep convolutional neural network for mapping protein sequences to folds. Bioinformatics, 34(8), 2018. J. Jiménez, M. Skalic, G. Martinez-Rosell, and G. De Fabritiis. KDEEP: Protein–Ligand Absolute Binding Affinity Prediction via 3D-Convolutional Neural Networks. Journal of Chemical Information and Modeling, 58(2), 2018. W. Jin, R. Barzilay, and T. Jaakkola. Hierarchical generation of molecular graphs using structural motifs. In International Conference on Machine Learning, pages 4839–4848. PMLR, 2020. J. Jumper, R. Evans, A. Pritzel, T. Green, M. Figurnov, O. Ronneberger, K. Tunyasuvunakool, R. Bates, A. Žídek, A. Potapenko, et al. Highly accurate protein structure prediction with AlphaFold. Nature, 596(7873), 2021. T. N. Kipf and M. Welling. Semi-Supervised Classification with Graph Convolutional Networks. In International Conference on Learning Representations (ICLR), 2017. P. Kohli, P. H. Torr, et al. Robust Higher Order Potentials for Enforcing Label Consistency. International Conference on Computer Vision (ICCV), 82(3), 2009. T. Lei, W. Jin, R. Barzilay, and T. Jaakkola. Deriving Neural Architectures from Sequence and Graph Kernels. In International Conference on Machine Learning (ICML), 2017. M.-Y. Liu, O. Tuzel, S. Ramalingam, and R. Chellappa. Entropy Rate Superpixel Segmentation. In IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2011. Z. Liu, M. Su, L. Han, J. Liu, Q. Yang, Y. Li, and R. Wang. Forging the Basis for Developing Protein–Ligand Interaction Scoring Functions. Accounts of Chemical Research, 50(2), 2017. G. Mori, X. Ren, A. A. Efros, and J. Malik. Recovering Human Body Configurations: Combining Segmentation and Recognition. In IEEE Conference on Computer Vision and Pattern Recognition (CVPR), volume 2, 2004. G. L. Nemhauser, L. A. Wolsey, and M. L. Fisher. An analysis of approximations for maximizing submodular set functions. Mathematical programming, 14(1), 1978. H. Öztürk, A. Özgür, and E. Ozkirimli. DeepDTA: deep drug–target binding affinity prediction. Bioinformatics, 34(17), 2018. A. Panjkovich and X. Daura. Assessing the structural conservation of protein pockets to study functional and allosteric sites: implications for drug discovery. BMC structural biology, 10(1): 1–14, 2010. M. Ragoza, J. Hochuli, E. Idrobo, J. Sunseri, and D. R. Koes. Protein–ligand scoring with convolutional neural networks. Journal of chemical information and modeling, 57(4):942–957, 2017. R. Rao, N. Bhattacharya, N. Thomas, Y. Duan, X. Chen, J. Canny, P. Abbeel, and Y. S. Song. Evaluating Protein Transfer Learning with TAPE. In Advances in Neural Information Processing Systems (NeurIPS), 2019. X. Ren and J. Malik. Learning a Classification Model for Segmentation. In IEEE Conference on Computer Vision and Pattern Recognition (CVPR), volume 2, 2003. M. F. Sanner, A. J. Olson, and J.-C. Spehner. Reduced Surface: An Efficient Way to Compute Molecular Surfaces. Biopolymers, 38(3), 1996. J. Schymkowitz, J. Borg, F. Stricher, R. Nys, F. Rousseau, and L. Serrano. The FoldX web server: an online force field. Nucleic Acids Research, 33, 2005. A. W. Senior, R. Evans, J. Jumper, J. Kirkpatrick, L. Sifre, T. Green, C. Qin, A. Žídek, A. W. Nelson, A. Bridgland, et al. Improved protein structure prediction using potentials from deep learning. Nature, 577(7792), 2020. M. M. Stepniewska-Dziubinska, P. Zielenkiewicz, and P. Siedlecki. Improving detection of proteinligand binding sites with 3d segmentation. Scientific Reports, 10(1), 2020. D. Stutz, A. Hermans, and B. Leibe. Superpixels: An evaluation of the state-of-the-art. Computer Vision and Image Understanding, 166, 2018. F. Sverrisson, J. Feydy, B. Correia, and M. Bronstein. Fast end-to-end learning on protein surfaces. bioRxiv, 2020. R. Townshend, R. Bedi, P. Suriana, and R. Dror. End-to-End Learning on 3D Protein Structure for Interface Prediction. Advances in Neural Information Processing Systems (NeurIPS), 32, 2019. R. J. Townshend, M. Vögele, P. Suriana, A. Derry, A. Powers, Y. Laloudakis, S. Balachandar, B. Anderson, S. Eismann, R. Kondor, et al. ATOM3D: Tasks On Molecules in Three Dimensions. NeurIPS Workshop of Learning Meaningful Representations of Life (LMRL), 2020. L. Vincent and P. Soille. Watersheds in Digital Spaces: An Efficient Algorithm Based on Immersion Simulations. IEEE Computer Architecture Letters, 13(06), 1991. E. C. Webb. Enzyme Nomenclature 1992. Recommendations of the Nomenclature Committee of the International Union of Biochemistry and Molecular Biology on the Nomenclature and Classification of Enzymes. Academic Press, 1992. K. K. Yang, Z. Wu, and F. H. Arnold. Machine-learning-guided directed evolution for protein engineering. Nature Methods, 16(8), 2019.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424# Robustifying $\ell _ { \infty }$ Adversarial Training to the Union of Perturbation Models
Anonymous Author(s) Affiliation Address email
# Abstract
1 Classical adversarial training (AT) frameworks are designed to achieve high ad 2 versarial accuracy against a single attack type, typically $\ell _ { \infty }$ norm-bounded per 3 turbations. Recent extensions in AT have focused on defending against the union 4 of multiple perturbation models but this benefit is obtained at the expense of a 5 significant (up to $1 0 \times$ ) increase in training complexity over single-attack $\ell _ { \infty }$ AT. 6 In this work, we expand the capabilities of widely popular single-attack $\ell _ { \infty }$ AT 7 frameworks to provide robustness to the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations while 8 preserving their training efficiency. Our technique, referred to as Shaped Noise 9 Augmented Processing (SNAP), exploits a well-established byproduct of single 10 attack AT frameworks – the reduction in the curvature of the decision boundary of 11 networks. SNAP prepends a given deep net with a shaped noise augmentation layer 12 whose distribution is learned along with network parameters using any standard 13 single-attack AT. As a result, SNAP enhances adversarial accuracy of ResNet-18 14 on CIFAR-10 against the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations by $1 \dot { 4 } \%$ -to- $2 0 \%$ for 15 four state-of-the-art (SOTA) single-attack $\ell _ { \infty }$ AT frameworks, and, for the first 16 time, establishes a benchmark for ResNet-50 and ResNet-101 on ImageNet.
# 17 1 Introduction
18 Today adversarial training (AT) provides state-of-the-art (SOTA) empirical defense against adver 19 sarial perturbations. For this, adversarial perturbations are used during training to optimize a robust 20 loss function [20, 41, 30, 35]. Early AT frameworks [20, 41] were $7 \times$ -to- $1 0 \times$ more computationally 21 demanding than vanilla training. More recent works [30, 35, 40] have significantly reduced the 22 computational demands of AT via single-step attacks and superconvergence. 23 However, today’s AT frameworks predominantly focus on a single-attack, i.e., they seek robustness 24 to a single perturbation, typically $\ell _ { \infty }$ -bounded [30, 35, 37, 41, 43, 40, 39, 26, 9, 34, 42, 10, 11, 14]. 25 This results in low performance against other perturbations such as $\ell _ { 2 } , \ell _ { 1 }$ , or the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ . 26 Indeed, as showemploying only $\ell _ { \infty }$ Fig. 1, four state-of-the-art (SOTA) single-attack AT fra-bounded perturbations achieve low adversarial accuracy ${ \mathcal { A } } _ { \mathrm { a d v } } ^ { ( U ) }$ rksof $\approx 1 5 \%$ mar-to- $2 0 \%$ 28 against the union of perturbations. Recent extensions in AT [21, 32, 18] do seek higher 29 A(U) but only at the expense of $6 \times$ -to- $. 1 0 \times$ increase in the total training time (blue markers in 30 Fig. 1). The large training time of these AT frameworks has inhibited their application to large-scale 31 datasets such as ImageNet, e.g., Maini et al. [21], Tramèr & Boneh [32] show results for MNIST and 32 CIFAR-10 only, while Laidlaw et al. [18] only additionally show $6 4 \times 6 4$ ImageNet-100 results. 33 The high training time for AT frameworks arises from two sources: (i) the need to employ larger 34 networks, e.g., MSD [21] with ResNet-18 achieves higher $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ than PAT [18] with ResNet-50 (see 35 Fig. 1); and (ii) the need to incorporate multiple perturbations during each attack step and a higher 36 overall number of attack steps, e.g., 50 in MSD [21], 20 in AVG [32]. Obviously one can always 37 reduce the number of attack steps in MSD/AVG to proportionally reduce training time. Doing so 38 results in training time and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ to rapidly approach the training complexity and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \bar { U } ) }$ of standard AT 39 frameworks, e.g., a 5-step MSD and 2-step AVG is equivalent in training time and accuracy to PGD 40 and TRADES, respectively. Notwithstanding the expensive nature of 50-step multi-attack training, 41 today MSD [21] achieves a SOTA $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ of $47 \%$ with ResNet-18 on CIFAR-10. 42 This poses a question: can we approach the high 43 robustness of multiple-attack AT such as 50-step 44 MSD against the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations 45 while maintaining the low training time of fast single 46 attack AT frameworks such as FreeAdv [30] and Fas 47 tAdv [35]? 48 In our quest to answer this question we find that noise 49 augmentation using adequately shaped noise within 50 standard single-attack AT frameworks employing $\ell _ { \infty }$ - 51 bounded perturbations significantly improves robust 52 ness against the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations. 53 The improvement appears to be a consequence of a 54 well-established byproduct of AT frameworks – the 55 reduction in the curvature of the decision boundary of 56 networks trained using single-attack AT [6, 23]. We 57 confirm this connection by quantifying the impact 58 of single-attack AT on the geometric orientations of 59 different perturbations. 60 Based on this insight, we propose Shaped Noise 61 Augmented Processing (SNAP) – a method to en 62 hance robustness against the union of perturbation types by augmenting single-attack AT frameworks. 63 SNAP prepends a deep net with a shaped noise (SN) augmentation layer (see Fig. 4) whose dis 64 tribution parameter $\Sigma$ is learned with that of the network $\mathbf { \eta } ^ { ( \theta ) }$ within any standard single-attack AT 65 framework. SNAP improves the robustness of four SOTA $\ell _ { \infty }$ -AT frameworks against the union of 66 $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations by $15 \%$ -to- $20 \%$ on CIFAR-10 (red markers in Fig. 1) with only a modest 67 $( \sim 1 0 \% )$ increase in training time. This expands the capabilities of widely popular single-attack $\ell _ { \infty }$ 68 AT frameworks to providing robustness to the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations without sacrificing 69 training efficiency. We validate SNAP’s benefits via thorough comparisons with nine SOTA adver 70 sarial training and randomized smoothing frameworks across different operating regimes on both 71 CIFAR-10 and ImageNet.
 Figure 1: Adv uracy $( \mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) } )$ $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ wall-clock total training time on CIFAR10 with different AT frameworks on single NVIDIA TESLA P100 GPU. $\epsilon =$ (0.031, 0.5, 12) for $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations, respectively. SNAP enhances robustness with a small increase in training time. All frameworks except PAT employ ResNet-18.
72 Onenetw73 ome of our woeNet that achieve $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) } = 3 2 \% ( 3 5 \% )$ e for the first time R against the union of $( \ell _ { \infty } ( \epsilon = 2 / 2 5 5 ) , \ell _ { 2 } ( \epsilon =$ $\ell _ { 1 } ( \epsilon = 7 2 . 0 )$ ) perturbations. Our code and trained models will be shared publicly on GitHub.
# 2 Related Work
76 We categorize works on adversarial vulnerability of DNNs as follows:
77 Low-complexity adversarial training: The high computational needs of AT frameworks has spurred 78 significant efforts in reducing their complexity [40, 30, 35, 43]. FreeAdv [30] updates weights while 79 accumulating multiple attack iterations. FastAdv [35] employs appropriate use of single-step attacks, 80 while Zheng et al. [43] leverage inter-epoch similarity between adversarial perturbations. However, 81 these fast AT methods seek robustness against a single perturbation type, e.g., $\ell _ { \infty }$ norm-bounded 82 perturbations. In contrast, SNAP expands the capabilities of these AT frameworks by enhancing 83 robustness to the union of three perturbation types $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ , while preserving their efficiency.
Robustness against union of perturbation models: The focus on the robustness against the union of multiple perturbation types is relatively new. Kang et al. [16] studied transferability between different perturbation types, while Jordan et al. [15] considered combination attacks with low perceptual distortion. Stutz et al. [31] proposed a modification in AT to detect images with different models of perturbations via confidence thresholding, but they don’t attempt to classify perturbed images correctly. For accurate classification in the presence of different perturbation models, Tramèr &
90 Boneh [32] studied empirical and theoretical trade-offs involved in including multiple perturbation 91 types simultaneously during training. Maini et al. [21] further built upon this work to propose the 92 multi steepest descent (MSD) AT framework which chooses one among the three perturbation models 93 $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ in each attack iteration during training, achieving SOTA adversarial accuracy on CIFAR 94 10 against the union of the $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbation models, albeit at a high $( 1 0 \times )$ training time. In 95 contrast, SNAP provides high robustness against the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbation models using 96 established single-attack $\ell _ { \infty }$ AT frameworks. This enables to showcase the benefits of our approach 97 on large-scale datasets such as ImageNet. 98 Recently, Laidlaw et al. [18] developed a novel AT framework (PAT) with low perceptual distortion 99 attacks to demonstrate impressive generalization to unseen attacks. In contrast, we focus on extending 100 the capabilities of widely popular $\ell _ { \infty }$ -AT frameworks to providing robustness against the union of 101 $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations, while preserving their training efficiency. 102 Noise augmentation: Multiple recent works have investigated the role of randomization in enhancing 103 adversarial robustness [12, 24, 8, 25] with theoretical guarantees. Another prominent line of work 104 in this category is randomized smoothing [5, 29, 19, 38], where random noise is used as a tool to 105 compute certification bounds. Rusak et al. [28] also explored the role of noise augmentation for 106 improving the robustness against common-corruptions [13]. In contrast, in SNAP, noise augmentation 107 is used as a means to enable widely popular $\ell _ { \infty }$ -AT frameworks to efficiently achieve high robustness 108 against the union of multiple norm-bounded perturbations. As is the characteristic of AT works, our 109 results are primarily empirical in nature. Hence, we follow recent guidelines [33, 21] to evaluate the 110 accuracy against the strongest possible adversaries. We do explicitly compare $\ell _ { \infty } { - } \mathrm { A T } { + } \mathrm { S N A P }$ with 111 randomized smoothing approaches in the Appendix.
# 112 3 Subspace Analysis of Adversarial Perturbations
113 In this section, we employ subspace methods to compre 114 hend the distinction between $\ell _ { \infty }$ , $\ell _ { 2 }$ and $\ell _ { 1 }$ perturbations. 115 For each input $\pmb { x } _ { i } \in \mathbb { R } ^ { D }$ in dataset $X$ , consider adversar 116 ial perturbations $\alpha _ { i }$ , $\beta _ { i }$ , and $\gamma _ { i }$ bounded within $\ell _ { \infty }$ , $\ell _ { 2 }$ , 117 and $\ell _ { 1 }$ norms, respectively. 118 We begin with a hypothesis (see Fig. 2): The perturbations 119 $\alpha , \beta ,$ , and $\gamma$ corresponding to input x have directions that 120 differ significantly if the curvature of the decision bound 121 ary is high in the neighborhood of $_ { \textbf { \em x } }$ . Conversely, if the 122 curvature of the decision boundary is low, the perturba 123 tions $_ \alpha$ , $\beta$ , and $\gamma$ tend to point in similar directions. 124 Since, prior works [6, 23] have found that single-attack 125 AT reduces the curvature of the decision boundary, we test 126 our hypothesis by studying the following two networks
 !: ℓ! norm bounded; $\beta \colon \ell _ { 2 }$ norm bounded; %: $\ell _ { 1 }$ norm bounded Figure 2: Illustration of the role of decision boundary curvature on the distinction between different types of perturbations $_ { \pmb { \alpha } }$ , $\beta$ and $\gamma$ of the given input $_ { \textbf { \em x } }$ .
on CIFAR-10 data: a non-robust ResNet18 $f _ { \theta } ^ { \mathrm { v a n } }$ trained using vanilla training, and a robust ResNet18 $f _ { \theta } ^ { \mathrm { r o b } }$ trained using the TRADES [41] AT framework employing $\ell _ { \infty }$ perturbations.
129 We compute perturbations $\alpha _ { i } , \beta _ { i }$ , and $\gamma _ { i }$ for each $\pmb { x } _ { i } \in X$ for both networks, i.e., $\kappa \in \{ \mathrm { v a n } , \mathrm { r o b } \}$ . We 130 compute the singular vector basis ${ \mathcal { P } } ^ { \kappa }$ for the set of $\ell _ { 2 }$ bounded perturbations $\Delta ^ { \kappa } = \{ \beta _ { 1 } ^ { \kappa } , \ldots , \beta _ { | X | } ^ { \kappa } \}$ 131 The normalized mean squared projections of the three types of perturbation vectors on the singular 132 vector basis ${ \mathcal { P } } ^ { \kappa }$ of vanilla trained ResNet-18 $( \mathcal { P } ^ { \mathrm { v a n } } )$ )(Fig. 3(a)) and TRADES trained ResNet-18 133 $( \mathcal { P } ^ { \mathrm { r o b } } )$ )(Fig. 3(b)) shows a clear contrast. 134 The perturbations of a vanilla trained network roll-off gradually to occupy a larger subspace as 135 indicated in Fig. 3(a). Specifically, the projections of $_ { \pmb { \alpha } }$ and $\gamma$ occupy almost all 3000 directions in 136 the basis $\mathcal { P } ^ { \mathrm { v a n } }$ since their mean squared projections are within $\sim 1 0 \%$ of the maximum value $m _ { \mathrm { m a x } }$ 137 This shows that the dominant singular vectors of $\beta$ are not well-aligned with $_ { \pmb { \alpha } }$ and $\gamma$ in a vanilla 138 trained network. With TRADES AT (Fig. 3(b)), however, all three types of perturbations are squeezed 139 into a much smaller subspace spanning only the top 250 singular vectors in the perturbation basis 140 ${ \mathcal { P } } ^ { \mathrm { r o b } }$ . Outside these 250 dimensions, the mean squared projections fall to $< 1 0 \%$ of their maximum 141 value. 142 In summary, the results in Fig. 3 validate the hypothesis that single-attack AT increases the average 143 alignment of different perturbation types due to the reduction in the decision boundary curvature. In 44 Sec. 4, we exploit this behavior of single-attack $\ell _ { \infty }$ AT to improve its robustness against the union of 45 multiple perturbation models via SNAP.
 Figure 3: Normalized mean squared projections of three perturbation types on the singular vector basis ${ \mathcal { P } } ^ { \kappa }$ of $\ell _ { 2 }$ perturbations of ResNet18 on CIFAR-10 after: (a) vanilla training $\kappa \equiv \operatorname { v a n } )$ , and (b) TRADES training $\kappa \equiv \mathrm { r o b }$ ). The singular vectors $\mathbf { \Delta } _ { \mathbf { \mathcal { p } } _ { i } ^ { \kappa } }$ comprising $\mathcal { P } ^ { \kappa } = \{ p _ { 1 } ^ { \kappa } , \ldots , p _ { D } ^ { \kappa } \}$ are ordered in descending order of their singular values.
# 146 4 Shaped Noise Augmented Processing (SNAP)
We show that single-attack AT can be enhanced to address multiple perturbations by introducing noise to appropriately wiggle the $\ell _ { \infty }$ -bounded perturbations (Fig. 4(a)). However, to do so, the noise distribution needs to be chosen and shaped appropriately to minimize its impact on natural accuracy and robustness to $\ell _ { \infty }$ -bounded perturbations.
153 We experiment with both $\ell _ { \infty }$ and $\ell _ { 2 }$ perturbations in single 154 attack AT frameworks and find $\ell _ { \infty } { \cdot } \mathbf { A } \mathrm { T }$ to be suitable for 155 our proposed shaped noise augmentation (see Sec. 5.2.1 for 156 details). Hence, in this section, we describe SNAP for single 157 attack AT frameworks employing $\ell _ { \infty }$ perturbations.
# 4.1 SNAPnet
A deep net $f _ { \theta } ( \pmb { x } ) _ { \mathbf { \lambda } } \colon \mathbb { R } ^ { D } \{ 0 , 1 \} ^ { C }$ parametrized by $\theta$ maps the input $\pmb { x } \in \mathbb { R } ^ { D }$ to a one-hot vector ${ \pmb y } \in \{ 0 , 1 \} ^ { \tilde { C } }$ over $C$ classes.
162 We construct a SNAP-based deep net (SNAPnet) $f _ { \boldsymbol { \theta } , \Sigma } ^ { \mathrm { S N } } ( \boldsymbol { x } )$ by 163 introducing an additive shaped noise (SN) layer (Fig. 4(b)), 164 where the noise distribution parameter $\Sigma$ is learned during 165 training. Formally,
 Figure 4: SNAP: (a) intuition underlying SNAP (not an exact depiction), and (b) SNAPnet $f _ { \boldsymbol { \theta } , \Sigma } ^ { \mathrm { S N } } ( \boldsymbol { x } )$ constructed from a given deep net $f _ { \boldsymbol { \theta } } ( \pmb { x } )$ by prepending a shaped noise (SN) augmentation layer which perturbs the primary input $_ { \textbf { \em x } }$ with noise $\mathbf { n }$ whose distribution parameter $\Sigma$ is learned during AT along with the base network parameter $\theta$ .
$${ \pmb y } = f _ { \theta , \Sigma } ^ { \mathrm { S N } } ( { \pmb x } ) = f _ { \theta } \big ( { \pmb x } + { \pmb n } \big ) = f _ { \theta } \big ( { \pmb x } + V \Sigma { \pmb n } _ { 0 } \big ) ,$$
166 where $\mathbf { n } _ { 0 } \sim \mathcal { L } ( 0 , \mathbf { I } _ { D \times D } )$ is a zero-mean isotropic Laplace 167 noise vector, $\Sigma = \mathrm { D i a g } [ \sigma _ { 1 } , \dots , \sigma _ { D } ]$ is a distribution param 168 eter denoting its per-dimension standard deviation, ${ \bf { I } } _ { D \times D }$ 169 denotes the $D \times D$ identity matrix, and $V = [ \pmb { v } _ { 1 } , \dots , \pmb { v } _ { D } ]$ denotes a basis in $\mathbb { R } ^ { D }$ . We also studied 170 Gaussian and Uniform distributed ${ \bf n } _ { 0 }$ , but empirically find the Laplace distribution to yield better 171 results (Sec. 5.2.1). We use $V = \mathbf { I } _ { D \times D }$ for all our experiments in the main text and study other 172 options for $V$ in the Appendix.
173 The final classification decision $d$ is computed via
$$d = \arg \operatorname* { m a x } _ { c } { \left[ \mathbb { E } _ { \mathbf { n } } [ \pmb { y } ] \right] } _ { c } ,$$
174 where $[ \pmb { a } ] _ { c }$ denotes the $c$ -th element of vector $^ { a }$ . Note, the shaped noise perturbs the input $_ { \textbf { \em x } }$ with a 175 noise source $\mathbf { n } = V \Sigma \mathbf { n } _ { 0 }$ (Eq. (1)). The distribution parameter $\Sigma$ is learned in the presence of any 176 standard AT method [20, 41, 30] used for learning deep net parameters $\theta$ as described next.
# Algorithm 1 Training SNAPnet
Input: training set $X$ ; basis $V = [ \pmb { v } _ { 1 } , \dots , \pmb { v } _ { D } ]$ ; total noise power $P _ { \mathrm { n o i s e } }$ ; minibatch size $r$ ; baseline training method BASE; noise variance update frequency $U _ { f }$ ; Total number of epochs $T$
Initialize: noise variances $\Sigma _ { 0 } = \mathrm { { D i a g } } [ \sigma _ { 1 , 0 } , . . . , \sigma _ { D , 0 } ]$ . Output: robust network $f _ { \boldsymbol { \theta } , \Sigma } ^ { \mathrm { S N } }$ , noise variances $\Sigma _ { T } = \operatorname { \bar { D i a g } } [ \sigma _ { 1 , T } ^ { 2 } , \dots , \sigma _ { D , T } ^ { 2 } ]$ . 1: for epoch $t = 1 \dots T$ do 2: for mini-batch $B = \{ { \pmb x } _ { 1 } , \ldots , { \pmb x } _ { r } \}$ do θ ← BASE\`∞ f SNθ,Σt {xi}ri=1, θ . BASE() Training 3: end for 4: if $t$ mod $U _ { f } = 0$ then . SNAP Distribution Update once every $U _ { f }$ epochs 5: for mini-batch $B = \{ { \pmb x } _ { 1 } , \ldots , { \pmb x } _ { r } \}$ do 6: $\begin{array} { r l r } & { } & { \{ \pmb { x } _ { i } ^ { \mathrm { a d v } } \} _ { i = 1 } ^ { r } \mathrm { P G D } _ { \ell _ { 2 } } ^ { ( K ) } \bigg ( f _ { \theta , \Sigma _ { t } } ^ { \mathrm { S N } } \big ( \{ \pmb { x } _ { i } \} _ { i = 1 } ^ { r } \big ) \bigg ) ; \quad \eta _ { i } = \pmb { x } _ { i } ^ { \mathrm { a d v } } - \pmb { x } _ { i } \forall i \in \{ 1 , \dots , r \} } \\ & { } & { \gamma _ { j } \gamma _ { j } + \sum _ { i = 1 } ^ { r } \big ( \langle \pmb { v } _ { j } , \eta _ { i } \rangle \big ) ^ { 2 } \quad \forall j \in \{ 1 , \dots , D \} \qquad \mathrm { ~ \mathbb { b } \ c c u m u l a t e \ p r o j e c t i o n s } ; } \\ & { } & { \frac { \mathrm { n d \ d \Pi \ f o r } } { j , t + 1 } = P _ { \mathrm { n o i s e } } \frac { \sqrt { \gamma _ { j } } } { \sum _ { k = 1 } ^ { D } \sqrt { \gamma _ { k } } } \quad \forall j \in \{ 1 , \dots , D \} \quad \mathrm { ~ \mathbb { b } \ c n o r m a l i z e \ a c c u m u l a t e d \ p r o j e c t i o n s } ; } \end{array}$ 7: See Eq. (3) 8: 9: eσ See Eq. (3) 10: else 11: $\Sigma _ { t + 1 } \Sigma _ { t }$ 12: end if 13: end for
# 177 4.2 Training SNAPnet
178 Algorithm 1 summarizes the procedure for training SNAPnet $f _ { \boldsymbol { \theta } , \Sigma } ^ { \mathrm { S N } } ( \boldsymbol { x } )$ . In each epoch, an arbitrary 179 AT method BASE() (line 2) updates network parameters $\theta$ with input perturbed by noise $\mathbf { n }$ . Here 180 BASE() can be any established AT framework [20, 41, 30, 35] employing $\ell _ { \infty }$ perturbation. 181 The SNAP parameter $\Sigma$ is updated once every $U _ { f } = 1 0$ epochs via a SNAP distribution update (lines 182 4-10). In this update, the per-dimension noise variance $\sigma _ { j } ^ { 2 }$ is updated proportional to the root mean 183 squared projection of the adversarial perturbations $\eta$ on the basis $V$ given a total noise constraint 184 $\begin{array} { r } { \bar { \sum _ { j = 1 } ^ { D } } \sigma _ { j } ^ { 2 } = P _ { \mathrm { n o i s e } } } \end{array}$ , where $P _ { \mathrm { n o i s e } }$ denotes the total noise power. Formally,
$$\sigma _ { j } ^ { 2 } \propto \sqrt { \mathbb { E } _ { \pmb { x } \in X } \left( \langle \pmb { \eta } , \pmb { v } _ { j } \rangle ^ { 2 } \right) } \quad \mathrm { s . t . } \quad \sum _ { j = 1 } ^ { D } \sigma _ { j } ^ { 2 } = P _ { \mathrm { n o i s e } } ,$$
185 where $\eta$ is the $\ell _ { 2 }$ norm-bounded PGD adversarial perturbation for the given input $\boldsymbol { x } \in \boldsymbol { X }$ (line 6). 186 Note that these $\ell _ { 2 }$ perturbations are employed only for noise shaping and are distinct from the $\ell _ { \infty }$ 187 perturbations employed by BASE() AT (line 2). Also, $\ell _ { \infty }$ perturbations cannot be used here since 188 their projections are constant $\forall j$ when $V = \mathbf { I } _ { D \times D }$ , whereas employing $\ell _ { 1 }$ perturbations leads to poor 189 shaping due to high sparsity. 190 Thus, in SNAP, the average squared $\ell _ { 2 }$ norm of the noise vector $\mathbf { n }$ is held constant at $P _ { \mathrm { n o i s e } }$ while 191 adapting the noise variances in the individual dimensions so as to align the noise vectors with the 192 adversarial perturbations on average. Intuitively, the decision boundary is pushed aggressively in 193 those directions.
# 194 4.3 Remarks
195 Note that the SNAP distribution update is distinct from BASE() AT. Hence, SNAP doesn’t require any 196 hyperparameter tuning in BASE(). For fairness to baselines we keep all hyperparameters identical 197 when introducing SNAP in all our experiments. However, SNAP introduces a new hyperparameter 198 $P _ { \mathrm { n o i s e } }$ , which permits to trade adversarial robustness $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ for natural accuracy ${ \mathcal { A } } _ { \mathrm { n a t } }$ . This trade-off is 199 explored in Sec. 5.2.2. 200 The computational overhead of SNAP is small $( \sim 1 0 \%$ ) since the SNAP Distribution Update occurs 201 once in 10 epochs using just $20 \%$ of the training data to update the noise standard deviations $\sigma _ { j }$ . We 202 provide more details about the SNAP Distribution Update in the Appendix.
<table><tr><td>Method</td><td>Anat</td><td>A ∈=0.03</td><td>A ∈=0.5</td><td>A ∈= 12</td><td>A</td></tr><tr><td colspan="6">PGD AT withloo perturbations</td></tr><tr><td>PGD +SNAP[G] +SNAP[U]</td><td>84.6 80.7 85.1</td><td>48.8 45.7 42.7</td><td>62.3 66.9 66.7</td><td>15.0 34.6 28.6</td><td>15.0 31.9 26.6</td></tr><tr><td colspan="6">+SNAP[L] 83.0 44.8 68.6 40.1 PGD AT withl2 perturbations</td></tr><tr><td>PGD +SNAP[G] +SNAP[U]</td><td>89.3 83.0</td><td>28.8 35.0</td><td>67.3 65.8</td><td>31.8 39.9</td><td>25.1 30.2</td></tr></table>
Table 1: ResNet-18 CIFAR-10 results showing the impact of SNAP augmentation of PGD [20] AT framework with $\ell _ { \infty }$ (top) and $\ell _ { 2 }$ (bottom) perturbations where [G], [U], and [L], denote shaped Gaussian, Uniform, and Laplace noise.
<table><tr><td>Method</td><td>Anat</td><td>A ∈= 0.03</td><td>A ∈=0.5</td><td>A e=12</td><td>A</td></tr><tr><td colspan="6">High Complexity ATwith loperturbations</td></tr><tr><td>PGD +SNAP</td><td>84.6 83.0</td><td>48.8 44.8</td><td>62.3 68.6</td><td>15.0 40.1</td><td>15.0 35.6</td></tr><tr><td>TRADES +SNAP</td><td>82.1 80.9</td><td>50.2 45.2</td><td>59.6 66.9</td><td>19.8 46.6</td><td>19.7 41.2</td></tr><tr><td colspan="6">Low Complexity AT with looperturbations</td></tr><tr><td>FreeAdv +SNAP</td><td>81.7 83.5</td><td>46.1 39.7</td><td>59 66.2</td><td>15.0 34.3</td><td>15.0 29.6</td></tr><tr><td>FastAdv +SNAP</td><td>85.7 84.2</td><td>46.2 40.4</td><td>60.0 67.9</td><td>13.2 36.6</td><td>13.2 30.8</td></tr></table>
Table 2: ResNet-18 CIFAR-10 results showing the impact of SNAP augmentation of established $\ell _ { \infty }$ -AT frameworks. The computational overhead of SNAP is limited to $\sim 1 0 \%$ .
# 03 5 Experimental Results
# 5.1 Setup
Following experimental settings of prior work [41, 30, 21], we employ a ResNet-18 network for CIFAR-10 experiments and both ResNet-50 and ResNet-101 networks for ImageNet experiments. Accuracy on clreferred to via $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) }$ t , $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 2 } ) }$ s refe, and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ o wit, for $\ell _ { \infty }$ ${ \mathcal { A } } _ { \mathrm { n a t } }$ $\ell _ { 2 }$ and a, and $\ell _ { 1 }$ uracy on adversarially perturbed test data isnorm bounded perturbations, respectively. Accuracy against the union of all three perturbations is denoted by $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ .
For a fair robustness comparison, our evaluation setup closely follows the setup of Maini et al. [21] for CIFAR-10 data: (1) choose norm bounds $\epsilon = ( 0 . 0 3 1 , 0 . 5 , 1 2 . 0 )$ for $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations, respectively; (2) scale norm bounds for images to lie between $[ 0 , 1 ]$ ; (3) choose the PGD attack configuration to be $I O O$ iterations with $I O$ random restarts for all perturbation types1; and (4) estimate $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ as the fraction of test data that is simultaneously resistant to all three perturbation models.
Following the guidelines of Tramer et al. [33], we carefully design adaptive PGD attacks that target the full defense – SN layer – since SNAPnet is end-to-end differentiable. Specifically, we backpropagate to primary input $_ { \textbf { \em x } }$ through the SN layer (see Fig. 4). Thus, the final shaped noise distribution is exposed to the adversary. We also account for the expectation $\mathbb { E } _ { \mathbf { n } } [ \cdot ]$ in Eq. (2) by explicitly averaging deep net logits over $N _ { 0 } ( = 8 )$ noise samples before computing the gradient, which eliminates any gradient obfuscation, and is known to be the strongest attack against noise augmented models [29]. In the Appendix we also show robustness stress tests and evaluate more attacks.
On CIFAR-10 data, we compare with the following seven key SOTA AT frameworks: PGD [20], TRADES [41], FreeAdv [30], FastAdv [35], AVG [32], MSD [21], PAT [18]. We also compare with two randomized smoothing frameworks [5, 29] in the Appendix. Thanks to their GitHub code releases, we first successfully reproduce their results with a ResNet-18 network in our environment. In the case of PAT [18], we evaluate and compare with their pretrained ResNet-50 model on CIFAR-10. We compare all training times on a single NVIDIA P100 GPU. On ImageNet data, we primarily compare to FreeAdv [30]. We train ResNet-50 and its SNAPnet version with FreeAdv on a Google Cloud server with four NVIDIA P100 GPUs to compare their accuracy and training times. We will release our pretrained models and code on GitHub.
# 5.2 Ablation Studies
# 5.2.1 Impact of Noise Distribution and Model of BASE() AT Perturbations
line 2 in Alg. 1) on In this subsection, we first study the impact of employing $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ . For each choice, we further experiment with three $\ell _ { \infty }$ vs. $\ell _ { 2 }$ perturbations in BASE AT() (see ributions for the $\ell _ { 1 }$
237 BASE AT() since Maini et al. [21] showed that employing $\ell _ { 1 }$ single-attack AT achieves very low 238 robustness to all attacks. We choose PGD [20] AT as BASE AT() for this ablation study. For a fair 239 comparison across the noise distributions, we fix $P _ { \mathrm { n o i s e } } = 1 6 0$ , enforcing all noise vectors to have the 240 same average $\ell _ { 2 }$ norm. For each distribution, the noise is shaped per the procedure summarized in 241 Alg. 1.
As observed in Table 1, $\ell _ { \infty }$ -PGD AT achieves much lower $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ than $\ell _ { 2 }$ -PGD AT, an observation also reported by Maini et al. [21]. With SNAP, however, we find that there is an interaction between the perturbation model in PGD AT and the noise distribution in SNAP. For instance, SNAP[U] enhances $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ by $11 \%$ with $\ell _ { \infty }$ -PGD AT while not achieving any improvement with $\ell _ { 2 }$ -PGD AT. In fact, SNAP appears to be particularly suitable for $\ell _ { \infty }$ -AT, since it always improves $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ by $11 \%$ -to- $2 0 . 6 \%$
Finally, of the three noise distributions, we find the Laplace distribution to be distinctly superior, achieving the highest A(U)adv ( $3 5 . 6 \%$ and $3 0 . 8 \%$ ) due to a significant improvement in $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ for both $\ell _ { \infty }$ and $\ell _ { 2 }$ PGD AT, respectively. The superiority of the Laplace distribution in achieving high $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ stems from its heavier tail compared to the Gaussian and Uniform distributions with the same variance. Shaped Laplace noise generates the highest fraction of extreme values in a given noise sample. Hence, it is more effective in improving accuracy against $\ell _ { 1 }$ -bounded attacks, which are the strongest when perturbing few pixels by a large magnitude [21, 32]. We discuss this further in the Appendix. Henceforth, unless otherwise mentioned, we choose Laplace noise for SNAP and $\ell _ { \infty }$ perturbations for BASE() AT as the default setting since it achieves the highest ${ \mathcal { A } } _ { \mathrm { a d v } } ^ { ( U ) }$ .
# 5.2.2 Impact of $P _ { \mathrm { n o i s e } }$
Next, we explore the impact of the SNAP hyperparameter $P _ { \mathrm { n o i s e } }$ , which constrains the average squared $\ell _ { 2 }$ norm of the noise vector n. It enables to trade between adversarial and natural accuracy.
Fig. 5 shows that, as $P _ { \mathrm { n o i s e } }$ increases, $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ improves from $31 \%$ to $47 \%$ , accompanied by a graceful $( 5 \% )$ drop in ${ \mathcal { A } } _ { \mathrm { n a t } }$ and a small drop of $2 \%$ in $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) }$ that stabilizes to $\approx 4 5 \%$ . These results show: (1) SNAP preserves the impact of $\ell _ { \infty }$ perturbations which is not surprising since PGD AT [20] explicitly includes those, and (2) $P _ { \mathrm { n o i s e } }$ provides an explicit knob to control the $\boldsymbol { A } _ { \mathrm { n a t } }$ vs. ${ \mathcal { A } } _ { \mathrm { a d v } }$ trade-off. Henceforth, we choose $P _ { \mathrm { n o i s e } }$ values that incur $< 1 . 5 \%$ drop in ${ \mathcal { A } } _ { \mathrm { n a t } }$ for all $\mathrm { S N A P { + } A T }$ experiments.
 Figure 5: ResNet-18 CIFAR-10 results: ad-(a) versarial racy $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ , $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) }$ , an ural ${ \mathcal { A } } _ { \mathrm { n a t } }$ vs. total noise power $P _ { \mathrm { n o i s e } }$ $\mathrm { P G D + S N A P }$ .
# 5.2.3 SNAP augmented SOTA AT Frameworks
Table 2 shows the effectiveness of SNAP for four SOTA AT frameworks: high complexity frameworks, such as PGD [20], TRADES [41], and low complexity frameworks such as FreeAdv [30], FastAdv [35]. All are trained against $\ell _ { \infty }$ attacks with $\epsilon = 0 . 0 3 1$ . As expected, while they achieve high $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) }$ , their $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 2 } ) }$ and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ are lower.
For high-complexity AT, SNAP enhances $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 2 } ) }$ and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ by $\sim 6 \%$ and $\sim 2 5 \%$ , respectively, while incurring only a drop of $\sim 5 \%$ in $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) }$ adv adv . Thus overall, SNAP improves robustness $( \mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) } )$ by $\sim 2 0 \%$ against the union of the three perturbation models. Note that this robustness improvement comes robustness at only a $\sim 1 \%$ $( \mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) } )$ drop in are also significant ${ \mathcal { A } } _ { \mathrm { n a t } }$ (see Table 2). For low-complexity ATs, SNAP improvements in union $( \sim 1 5 \% )$ ). Again, presence of SNAP improves $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 2 } ) }$ and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ This time the drop in $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) }$ is $\sim 7 \%$ . We believe this is due to the fact that thes frameworks employ weaker single-step attacks during training. Note that in the case of FreeAdv $^ +$ observe a $\sim 2 \%$ increase in ${ \mathcal { A } } _ { \mathrm { n a t } }$ , a trend we also observe in the ImageNet experiments described later.
Table 3: CIFAR-10 results for comparing adversarial accuracy A(U)adv vs. training time (on single NVIDIA P100 GPU) for different AT frameworks and the improvements by introducing proposed SNAP technique. All frameworks except PAT [18] (which employs ResNet-50) employ ResNet-18.
<table><tr><td rowspan=1 colspan=1>Method</td><td rowspan=1 colspan=1>LR schedule</td><td rowspan=1 colspan=1>Epochs</td><td rowspan=1 colspan=1>Anat</td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>Total time(minutes)</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>SetA:Total Time</td><td rowspan=1 colspan=1>SetA:Total Time≥</td><td rowspan=1 colspan=1>12 Hrs</td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=5 colspan=1>AVG 50Step[32]AVG 20 Step [32]AVG 10 Step [32]PAT[18]MSD 50 Step [21]MSD 30 Step [21]</td><td rowspan=1 colspan=1>cyclic</td><td rowspan=1 colspan=1>50</td><td rowspan=1 colspan=1>84.8</td><td rowspan=1 colspan=1>40.4</td><td rowspan=5 colspan=1>4217183495613641693978</td></tr><tr><td rowspan=4 colspan=1>cycliccyclicstepcycliccyclic</td><td rowspan=2 colspan=1>5050</td><td rowspan=2 colspan=1>85.686.7</td><td rowspan=1 colspan=1>40.438.9</td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=3 colspan=1>501005050</td><td></td></tr><tr><td rowspan=2 colspan=1>86.782.481.782.4</td><td></td></tr><tr><td rowspan=1 colspan=1>38.936.647.044.9</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>SetB:8Hrs</td><td rowspan=1 colspan=3>Set B:8 Hrs<Total Time<12 Hrs</td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=1 colspan=1>AVG 5 Step [32]MSD 20 Step [21]TRADES [41]TRADES+SNAP</td><td rowspan=1 colspan=1>cycliccyclicstepstep</td><td rowspan=1 colspan=1>5050100100</td><td rowspan=1 colspan=1>87.883.082.080.9</td><td rowspan=1 colspan=1>33.737.319.741.2</td><td rowspan=1 colspan=1>489690516566</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>SetC:5Hr</td><td rowspan=1 colspan=1><TotalTi</td><td rowspan=1 colspan=1>ne<8Hi</td><td rowspan=1 colspan=1>S</td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=1 colspan=1>MSD 10 Step [21]PGD [20]PGD+SNAP</td><td rowspan=1 colspan=1>cyclicstepstep</td><td rowspan=1 colspan=1>50100100</td><td rowspan=1 colspan=1>83.684.683.0</td><td rowspan=1 colspan=1>33.315.035.6</td><td rowspan=1 colspan=1>342354403</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>SetD:2Hr</td><td rowspan=1 colspan=1><TotalTi</td><td rowspan=1 colspan=1>ne<5Hi</td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=1 colspan=1>AVG 2 Step [32]MSD 5 Step [21]PGD [20]TRADES [41]PGD+SNAPTRADES+SNAP</td><td rowspan=1 colspan=1>cycliccycliccycliccycliccycliccyclic</td><td rowspan=1 colspan=1>505050505050</td><td rowspan=1 colspan=1>88.484.082.880.082.378.8</td><td rowspan=1 colspan=1>22.012.615.721.433.540.8</td><td rowspan=1 colspan=1>232185177258199280</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>SetE:</td><td rowspan=1 colspan=1>TotalTime<</td><td rowspan=1 colspan=1>2Hrs</td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=2 colspan=1>FreeAdv [30]FastAdv [35]FreeAdv+SNAPFastAdv+SNAP</td><td rowspan=2 colspan=1>stepcyclicstepcyclic</td><td rowspan=1 colspan=1>200</td><td rowspan=1 colspan=1>81.7</td><td rowspan=1 colspan=1>15.0</td><td rowspan=2 colspan=1>66478869</td></tr><tr><td rowspan=1 colspan=1>5020050</td><td rowspan=1 colspan=1>85.783.584.2</td><td rowspan=1 colspan=1>13.229.630.8</td></tr></table>
<table><tr><td>Training</td><td>Anat (%)</td><td>A e= 2/255</td><td>A ∈ = 2.0</td><td>A e = 72.0</td><td>A</td><td>Total time (minutes)</td></tr><tr><td colspan="7">ResNet-50</td></tr><tr><td>FreeAdv [30]</td><td>61.7</td><td>47.8</td><td>19.9</td><td>14.8</td><td>12.6</td><td>3590</td></tr><tr><td>FreeAdv+SNAP</td><td>66.8</td><td>46.1</td><td>37.8</td><td>37.4</td><td>32.4</td><td>3756</td></tr><tr><td colspan="7">ResNet-101</td></tr><tr><td>FreeAdv [30]</td><td>65.4</td><td>51.8</td><td>22.8</td><td>18.8</td><td>16.1</td><td>5678</td></tr><tr><td>FreeAdv+SNAP</td><td>69.7</td><td>50.3</td><td>41.1</td><td>40.2</td><td>35.4</td><td>5904</td></tr></table>
Table 4: ImageNet results: Iso-hyperparameter introduction of SNAP yields $\sim 2 0 \%$ improvement in adversarial accuracy $( \mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) } )$ with modest impact on training time for ResNet-50 and ResNet-101.
# 286 5.3 Robustness vs. Training Complexity
Next we quantify adversarial robustness vs. training time trade-offs. Table 3 shows that SNAP augmentation of single-attack AT frame rks achieves the highest $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ , when training time is $\mathbf { E }$
For instance, TRADES $^ +$ SNAP achieves a $4 \%$ higher $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) } ( = 4 1 \% )$ than MSD-20 with 2 hours lower training time (Set B in Table 3). Similarly, PGD $^ +$ SNAP achieves a $2 \%$ higher $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ than MSD-10 while having a similar training time (Set C). Note that both PGD and TRADES here use 100 training epochs with standard step learning rate (LR) schedule, while MSD frameworks employ a cyclic learning rate schedule to achieve superconvergence in 50 epochs.
295 In Set D, following Maini et al. [21], we employ a cyclic learning rate schedule for PGD, TRADES, 296 as well as for $\mathrm { P G D + S N A P }$ and TRADES $^ +$ SNAP to achieve convergence in 50 epochs. Improvements 297 in $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ for PGD $^ +$ SNAP and TRADES $^ +$ SNAP are similar to those in Sets $\mathbf { B }$ and C. Most notably,
298 $\mathrm { P G D + S N A P }$ with cyclic learning rate achieves $\sim 2 0 \%$ and $1 1 . 5 \%$ high $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ than MSD-5 and 299 AVG-2, respectively, while having aTable 2 with training times. FastAdv300 training time and FreeAdv $\sim 3$ hours). Set AP achieve $\mathbf { E }$ auigh a from, while $+ { \mathrm { S N A P } }$ $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) } \sim 3 0 \%$ 301 $1 8 \%$ erving thigher $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ ining efficiency of both Fthan MSD-5, while being $\sim 2 . 7 \times$ nd FreeAdv. Notably, FastAdv+SNAP achievesmore efficient to train.
# 5.4 ImageNet Results
Thanks to SNAP’s low computational overhead combined with FreeAdv’s fast training time, we are for the first time able to report adversarial accuracy of ResNet-50 and ResNet-101 against the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ attacks on ImageNet.
We closely follow the evaluation setup of Shafahi et al. [30]. Specifically, we use 100 step PGD attack, one of the strongest adversaries considered by Shafahi et al. [30], and evaluate on the entire test set. We first reproduce FreeAdv [30] results using the same hyperparameters and then introduce SNAP. All hyperparameter details are specified in the Appendix.
In order to clearly demonstrate the contrast between robustness to different perturbation models, we evaluate with FreeAdv achi $\epsilon \overset { \cdot } { = } ( 2 / 2 5 5 , 2 . 0 , 7 2 . 0 )$ $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ attacks, respectivet-50, but a lower n inand adv , and consequently, a low $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) } = 4 7 . 8 \%$ $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ o f $1 2 . 6 \%$ against the union of the perturbations. In contrast, $A _ { \mathrm { a d v } } ^ { ( \ell _ { 2 } ) } = 2 0 \%$ $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) } =$ FreeAdv+SNAP improves $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 2 } ) }$ and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { 1 } ) }$ by $1 7 \%$ and $2 2 \%$ , respectively, accompanied by a $5 \%$ improvement in ${ \mathcal { A } } _ { \mathrm { n a t } }$ and a small $2 \%$ loss in $\mathcal { A } _ { \mathrm { a d v } } ^ { ( \ell _ { \infty } ) }$ . This results in an overall robustness improvement of $\mathrm { \bar { 2 0 \% } }$ against the union of the perturbation models, setting a first benchmark for ResNet-50 on ImageNet. Upon increasing the network to ResNet-101, both natural and adversarial accuracies improve by $\approx 4 \%$ for FreeAdv, a trend also observed by Shafahi et al. [30]. SNAP further improves FreeAdv’s results for $\boldsymbol { A } _ { \mathrm { n a t } }$ and $\mathcal { A } _ { \mathrm { a d v } } ^ { ( U ) }$ by $4 . 3 \%$ and $1 9 . 3 \%$ .
# 6 Discussion
Given the wide popularity of $\ell _ { \infty } { \cdot } \mathbf { A } \mathbf { T } .$ , in this paper, we propose SNAP as an augmentation that generalizes the effectiveness of $\ell _ { \infty }$ -AT to the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations. SNAP’s strength is its simplicity and efficiency. Consequently, this work sets a first benchmark for ResNet-50 and ResNet101 networks which are resilient to the union of $( \ell _ { \infty } , \ell _ { 2 } , \ell _ { 1 } )$ perturbations on ImageNet. Note that norm-bounded perturbations include a large class of attacks, e.g., gradient-based [20, 27, 32, 21, 4, 22], decision-based [3] and black-box [1] attacks.
More work is needed to extend the proposed SNAP technique to attacks beyond norm-bounded additive perturbations, e.g., functional [17, 36], rotation [7], texture [2], etc. We provide preliminary evaluations in this direction in the Appendix. It is important to note that SNAP is meant to be an efficient technique for improving $\ell _ { \infty }$ -AT, and not a new defense. Indeed defending against a large variety of attacks simultaneously remains an open problem, with encouraging results from recent efforts [21, 18].
Another limitation of our approach is that its benefits are demonstrated empirically. It is an inevitable consequence of a lack of any theoretical guarantees for underlying AT frameworks. An interesting direction of future work is to explore whether any theoretical guarantees can be derived for anisotropic shaped noise distributions in SNAP by building upon the recent developments in randomized smoothing [29, 38]. This could be a potential avenue for bridging the gap between certification bounds and empirical adversarial accuracy.
Finally, we believe that any effort on improving adversarial robustness of deep nets has net positive societal impact. However, recent past in this field has shown that any improvements in defense techniques also lead to more effective threat models. While such a cat-and-mouse game is of great intellectual value in the academic setting, it does have an unintentional negative societal consequence of equipping malicious outside actors with a broad set of tools. This further underscores the wellrecognized need for provable defenses.
# References
[1] Andriushchenko, M., Croce, F., Flammarion, N., and Hein, M. Square attack: a query-efficient black-box adversarial attack via random search. In European Conference on Computer Vision, pp. 484–501. Springer, 2020. [2] Bhattad, A., Chong, M. J., Liang, K., Li, B., and Forsyth, D. A. Unrestricted adversarial examples via semantic manipulation. arXiv preprint arXiv:1904.06347, 2019. [3] Brendel, W., Rauber, J., and Bethge, M. Decision-based adversarial attacks: Reliable attacks against black-box machine learning models. In International Conference on Learning Representations, 2018. [4] Chen, P.-Y., Sharma, Y., Zhang, H., Yi, J., and Hsieh, C.-J. Ead: elastic-net attacks to deep neural networks via adversarial examples. In Thirty-second AAAI conference on artificial intelligence, 2018. [5] Cohen, J., Rosenfeld, E., and Kolter, Z. Certified adversarial robustness via randomized smoothing. In International Conference on Machine Learning (ICML), 2019. [6] Dezfooli, S. M. M., Fawzi, A., Fawzi, O., Frossard, P., and Soatto, S. Robustness of classifiers to universal pertur-bations: A geometric perspective. In International Conference on Learning Representations (ICLR), 2018. [7] Engstrom, L., Tran, B., Tsipras, D., Schmidt, L., and Madry, A. Exploring the landscape of spatial robustness. In International Conference on Machine Learning, pp. 1802–1811. PMLR, 2019. [8] Gilmer, J., Ford, N., Carlini, N., and Cubuk, E. Adversarial examples are a natural consequence of test error in noise. In International Conference on Machine Learning, pp. 2280–2289, 2019. [9] Gowal, S., Qin, C., Uesato, J., Mann, T., and Kohli, P. Uncovering the limits of adversarial training against norm-bounded adversarial examples. arXiv preprint arXiv:2010.03593, 2020. [10] Gui, S., Wang, H., Yu, C., Yang, H., Wang, Z., and Liu, J. Model compression with adversarial robustness: A unified optimization framework. arXiv preprint arXiv:1902.03538, 2019. [11] Guo, M., Yang, Y., Xu, R., Liu, Z., and Lin, D. When nas meets robustness: In search of robust architectures against adversarial attacks. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 631–640, 2020. [12] He, Z., Rakin, A. S., and Fan, D. Parametric noise injection: Trainable randomness to improve deep neural network robustness against adversarial attack. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2019. [13] Hendrycks, D. and Dietterich, T. Benchmarking neural network robustness to common corruptions and perturbations. In International Conference on Learning Representations, 2018. [14] Hu, T.-K., Chen, T., Wang, H., and Wang, Z. Triple wins: Boosting accuracy, robustness and efficiency together by enabling input-adaptive inference. arXiv preprint arXiv:2002.10025, 2020. [15] Jordan, M., Manoj, N., Goel, S., and Dimakis, A. G. Quantifying perceptual distortion of adversarial examples. arXiv preprint arXiv:1902.08265, 2019. [16] Kang, D., Sun, Y., Brown, T., Hendrycks, D., and Steinhardt, J. Transfer of adversarial robustness between perturbation types. arXiv preprint arXiv:1905.01034, 2019. [17] Laidlaw, C. and Feizi, S. Functional adversarial attacks. Advances in Neural Information Processing Systems, 2019. [18] Laidlaw, C., Singla, S., and Feizi, S. Perceptual adversarial robustness: Defense against unseen threat models. International Conference on Learning Representations (ICLR), 2018. [19] Li, B., Chen, C., Wang, W., and Duke, L. C. Certified adversarial robustness with addition gaussian noise. Neural Information Processing Systems (NeurIPS), 2019. [20] Madry, A., Makelov, A., Schmidt, L., Tsipras, D., and Vladu, A. Towards deep learning models resistant to adversarial attacks. International Conference on Learning Representations (ICLR), 2018. [21] Maini, P., Wong, E., and Kolter, J. Z. Adversarial robustness against the union of multiple perturbation models. In International Conference on Machine Learning (ICML), 2020. [22] Moosavi-Dezfooli, S.-M., Fawzi, A., and Frossard, P. Deepfool: a simple and accurate method to fool deep neural networks. In Proceedings of the IEEE conference on computer vision and pattern recognition (CVPR), 2016. [23] Moosavi-Dezfooli, S.-M., Fawzi, A., Uesato, J., and Frossard, P. Robustness via curvature regularization, and vice versa. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2019. [24] Pinot, R., Meunier, L., Araujo, A., Kashima, H., Yger, F., Gouy-Pailler, C., and Atif, J. Theoretical evidence for adversarial robustness through randomization: the case of the exponential family. In Advances in Neural Information Processing Systems, 2019. [25] Pinot, R., Ettedgui, R., Rizk, G., Chevaleyre, Y., and Atif, J. Randomization matters. how to defend against strong adversarial attacks. In International Conference on Machine Learning (ICML), 2020. [26] Rebuffi, S.-A., Gowal, S., Calian, D. A., Stimberg, F., Wiles, O., and Mann, T. Fixing data augmentation to improve adversarial robustness. arXiv preprint arXiv:2103.01946, 2021. [27] Rony, J., Hafemann, L. G., Oliveira, L. S., Ayed, I. B., Sabourin, R., and Granger, E. Decoupling direction and norm for efficient gradient-based l2 adversarial attacks and defenses. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 4322–4330, 2019. [28] Rusak, E., Schott, L., Zimmermann, R. S., Bitterwolf, J., Bringmann, O., Bethge, M., and Brendel, W. A simple way to make neural networks robust against diverse image corruptions. In European Conference on Computer Vision, pp. 53–69. Springer, 2020. [29] Salman, H., Li, J., Razenshteyn, I., Zhang, P., Zhang, H., Bubeck, S., and Yang, G. Provably robust deep learning via adversarially trained smoothed classifiers. In Advances in Neural Information Processing Systems, pp. 11289–11300, 2019. [30] Shafahi, A., Najibi, M., Ghiasi, A., Xu, Z., Dickerson, J., Studer, C., Davis, L. S., Taylor, G., and Goldstein, T. Adversarial training for free! Advances in Neural Information Processing Systems (NeurIPS), 2019. [31] Stutz, D., Hein, M., and Schiele, B. Confidence-calibrated adversarial training: Generalizing to unseen attacks. In International Conference on Machine Learning, pp. 9155–9166. PMLR, 2020. [32] Tramèr, F. and Boneh, D. Adversarial training and robustness for multiple perturbations. In Advances in Neural Information Processing Systems, pp. 5858–5868, 2019. [33] Tramer, F., Carlini, N., Brendel, W., and Madry, A. On adaptive attacks to adversarial example defenses. arXiv preprint arXiv:2002.08347, 2020. [34] Vivek, B. and Babu, R. V. Single-step adversarial training with dropout scheduling. In 2020 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), pp. 947–956. IEEE, 2020. [35] Wong, E., Rice, L., and Kolter, J. Z. Fast is better than free: Revisiting adversarial training. In International Conference on Machine Learning (ICLR), 2020. [36] Xiao, C., Zhu, J.-Y., Li, B., He, W., Liu, M., and Song, D. Spatially transformed adversarial examples. In International Conference on Learning Representations, 2018. [37] Xie, C. and Yuille, A. Intriguing properties of adversarial training at scale. In International Conference on Learning Representations, 2020. [38] Yang, G., Duan, T., Hu, E., Salman, H., Razenshteyn, I., and Li, J. Randomized smoothing of all shapes and sizes. International Conference on Machine Learning (ICML), 2020. [39] Yang, Y.-Y., Rashtchian, C., Zhang, H., Salakhutdinov, R., and Chaudhuri, K. A closer look at accuracy vs. robustness. Advances in Neural Information Processing Systems, 33, 2020. [40] Zhang, D., Zhang, T., Lu, Y., Zhu, Z., and Dong, B. You only propagate once: Accelerating adversarial training via maximal principle. arXiv preprint arXiv:1905.00877, 2019. [41] Zhang, H., Yu, Y., Jiao, J., Xing, E., El Ghaoui, L., and Jordan, M. Theoretically principled trade-off between robustness and accuracy. In International Conference on Machine Learning (ICML), 2019. [42] Zhang, J., Xu, X., Han, B., Niu, G., Cui, L., Sugiyama, M., and Kankanhalli, M. Attacks which do not kill training make adversarial learning stronger. In International Conference on Machine Learning, pp. 11278–11287. PMLR, 2020. [43] Zheng, H., Zhang, Z., Gu, J., Lee, H., and Prakash, A. Efficient adversarial training with transferable adversarial examples. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 1181���1190, 2020.
1. For all authors...
(a) Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope? [Yes] (b) Did you describe the limitations of your work? [Yes] See Section 6. (c) Did you discuss any potential negative societal impacts of your work? [Yes] See Section 6. (d) Have you read the ethics review guidelines and ensured that your paper conforms to them? [Yes]
2. If you are including theoretical results...
(a) Did you state the full set of assumptions of all theoretical results? [N/A] (b) Did you include complete proofs of all theoretical results? [N/A]
3. If you ran experiments...
(a) Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? [Yes] An URL to our code as well as the pretrained models is provided in the Appendix. (b) Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? [Yes] All training hyperparameters are mentioned in the Appendix. Our technique does introduce a new hyperparameter, whose impact is discussed in Sec. 5.2.2. (c) Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? [Yes] We do run a subset of experiments multiple times to obtain error bars (see Appendix). In doing so we confirm that our technique is effective across random initializations. However, some of the training runs in our work are too expensive to run multiple times. (d) Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? [Yes] Yes, we explicitly mention the type of GPUs used and the training times in Section 5.
4. If you are using existing assets (e.g., code, data, models) or curating/releasing new assets...
(a) If your work uses existing assets, did you cite the creators? [Yes] We appropriately cite the relevant papers while using their code to reproduce/extend their results. (b) Did you mention the license of the assets? [Yes] Our own codes & models, as well as, all the other codes that we use are available freely in public domain. We do mention so explicitly in Section 5.1 (c) Did you include any new assets either in the supplemental material or as a URL? [Yes] We do share our own code and pretrained model as a part of the supplemental material (d) Did you discuss whether and how consent was obtained from people whose data you’re using/curating? [N/A] (e) Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? [N/A]
5. If you used crowdsourcing or conducted research with human subjects...
(a) Did you include the full text of instructions given to participants and screenshots, if applicable? [N/A] (b) Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? [N/A] (c) Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? [N/A]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274# PMI-MASKING: PRINCIPLED MASKING OF CORRELATED SPANS
Yoav Levine Barak Lenz Opher Lieber Omri Abend
Kevin Leyton-Brown Moshe Tennenholtz Yoav Shoham
AI21 Labs, Tel Aviv, Israel
{yoavl,barakl,opherl,omria,...}@ai21.com
# ABSTRACT
Masking tokens uniformly at random constitutes a common flaw in the pretraining of Masked Language Models (MLMs) such as BERT. We show that such uniform masking allows an MLM to minimize its training objective by latching onto shallow local signals, leading to pretraining inefficiency and suboptimal downstream performance. To address this flaw, we propose PMI-Masking, a principled masking strategy based on the concept of Pointwise Mutual Information (PMI), which jointly masks a token $n$ -gram if it exhibits high collocation over the corpus. PMIMasking motivates, unifies, and improves upon prior more heuristic approaches that attempt to address the drawback of random uniform token masking, such as whole-word masking, entity/phrase masking, and random-span masking. Specifically, we show experimentally that PMI-Masking reaches the performance of prior masking approaches in half the training time, and consistently improves performance at the end of training.
# 1 INTRODUCTION
In the couple of years since BERT was introduced in a seminal paper by Devlin et al. (2019a), Masked Language Models (MLMs) have rapidly advanced the NLP frontier (Sun et al., 2019; Liu et al., 2019; Joshi et al., 2020; Raffel et al., 2019). At the heart of the MLM approach is the task of predicting a masked subset of the text given the remaining, unmasked text. The text itself is broken up into tokens, each token consisting of a word or part of a word; thus “chair” constitutes a single token, but out-of-vocabulary words like “e-igen-val-ue” are broken up into several sub-word tokens. In BERT, $1 5 \%$ of tokens are chosen to be masked uniformly at random. It is the random choice of single tokens that we address in this paper: we show that this approach is suboptimal and offer a principled alternative.
To see why Random-Token Masking is suboptimal, consider the special case of sub-word tokens. Given the masked sentence “To approximate the matrix, we use the eigenvector corresponding to its largest e-[mask]-val-ue”, an MLM will quickly learn to predict “igen” based only on the context “e[mask]-val-ue”, rendering the rest of the sentence redundant. The question is whether the network will also learn to relate the broader context to the tokens comprising “eigenvalue”. When they are masked together, the network is forced to do so, but such masking occurs with vanishingly small probability. One might hypothesize that the network would nonetheless be able to piece such meaning together from local cues; however, we show that it often struggles to do so.
We establish this via a controlled experiment, in which we reduced the size of the vocabulary, thereby breaking more words into sub-word tokens. We compared the extent to which such vocabulary reduction degraded regular BERT relative to so-called Whole-Word Masking BERT (WWBERT) (Devlin et al., 2019b), a version of BERT that jointly masks all sub-word tokens comprising an out-of-vocabulary word during training. We show that vanilla BERT’s performance degrades much more rapidly than that of WWBERT as the vocabulary size shrinks. The intuitive explanation is that Random-Token Masking is wasteful; it overtrains on easy sub-word tasks (such as predicting “igen”) and undertrains on harder whole-word tasks (predicting “eigenvalue”).
The advantage of Whole-Word Masking over Random-Token Masking is relatively modest for standard vocabularies, because out-of-vocabulary words are rare. However, the tokenization of words is a very special case of a much broader statistical linguistic phenomenon of collocation: the cooccurrence of series of tokens at levels much greater than would be predicted simply by their individual frequencies in the corpus. There are millions of collocated word $n$ -grams — multi-word expressions, phrases, and other common word combinations — whereas there are only tens of thousands of words in frequent use. So it is reasonable to hypothesize that Random-Token Masking generates many wastefully easy problems and too few usefully harder problems because of multiword collocations, and that this affects performance even more than the rarer case of tokenized words; we show that this indeed is the case.
Several prior works have considered the idea of masking across spans longer than a single word. Sun et al. (2019) and Guu et al. (2020) proposed Knowledge Masking and Salient Span Masking, respectively, in which tokens comprising entities or phrases, as identified by external parsers, are jointly masked. While extending the scope of Whole-Word Masking, the restriction to specific types of correlated $n$ -grams, along with the reliance on imperfect tools for their identification, has limited the gains achievable by these approaches. With a similar motivation in mind, SpanBERT of Joshi et al. (2020) introduced Random-Span Masking, which masks word spans of lengths sampled from a geometric distribution at random positions in the text. Random-Span Masking was shown to consistently outperform Knowledge Masking, is simple to implement, and inspired prominent MLMs (Raffel et al., 2019). However, while Random-Span Masking increases the chances of masking collocations, with high probability the selected spans break up correlated n-grams, such that the prediction task can often be performed by relying on local cues.
In this paper we offer a principled approach to masking spans that consistently provide high signal, unifying the intuitions behind the above approaches while also outperforming them. Our approach, dubbed PMI-Masking, uses Pointwise Mutual Information (PMI) to identify collocations, which we then mask jointly. At a high level, PMI-Masking consists of two stages. First, given any pretraining corpus, we identify a set of contiguous $n$ -grams that exhibit high cooccurrence probability relative to the individual occurrence probabilities of their components. We for
 Figure 1: SQuAD2.0 development set F1 scores of BERTBASE models trained with different masking schemes, evaluated every 200K steps during pretraining.
malize this notion by proposing an extended definition of Pointwise Mutual Information from bigrams to longer $n$ -grams. Second, we treat these collocated $n$ -grams as single units; the masking strategy selects at random both from these units and from standard tokens that do not participate in such units. Figure 1, detailed and reinforced by further experiments in section 5, shows that (1) PMI-Masking dramatically accelerates training, matching the end-of-pretraining performance of existing approaches in roughly half of the training time; and (2) PMI-Masking improves upon previous masking approaches at the end of pretraining.
# 2 MOTIVATION: MLMS ARE SENSITIVE TO TOKENIZATION
In this section we describe a simple experiment that motivates our PMI-Masking approach. We examined BERT’s ability to learn effective representations for words consisting of multiple subword tokens, treating this setting as an easily controlled analogue for the multi-word collocation problem that truly interests us. Our experiment sought to assess the performance gain obtained from always masking whole words as opposed to masking each individual token uniformly at random. We compared performance across a range of vocabulary sizes, using the same WordPiece Tokenizer1 that produced the original vocabulary of $\sim 3 0 \mathrm { K }$ tokens. As we decreased a 30K-token vocabulary to 10K and 2K tokens, the average length of a word over the pretraining corpus increased from 1.08 tokens to 1.22 and 2.06 tokens, respectively. Thus, by reducing the vocabulary size, we increased the frequency of multi-token words by a large factor.
Table 1: SQuAD2.0 development set F1 scores of BERTBASE models trained with Random-Token and Whole-Word masking schemes and with different vocabulary sizes (30K; 10K; 2K).
<table><tr><td></td><td>1.08 tokens per word (30K vocabulary)</td><td>1.22 tokens per word (10K vocabulary)</td><td>2.06 tokens per word (2K vocabulary)</td></tr><tr><td>Random-Token Masking</td><td>79.3</td><td>77.8</td><td>72.8</td></tr><tr><td>Whole-Word Masking</td><td>79.7</td><td>79.5</td><td>77.6</td></tr></table>
Table 1 presents the performance of BERT models trained with these vocabularies, measured as score on the SQuAD2.0 development set (the experimental setup is described in section 4). The downstream performance of Random-Token Masking substantially degraded as vocabulary size decreased and the number of spans of sub-word tokens increased. One reason for such degradation might be the model seeing less text as context (512 input tokens cover less text when more words are broken into multiple tokens). This possibly plays a role; however, for models with the same vocabularies trained via Whole-Word Masking, this degradation was significantly attenuated. We therefore conjecture that this degradation occurred primarily because of the random masking strategy, which allows the model to use “shortcuts” for minimizing its loss, thus hindering its ability to learn the distribution of the entire multi-token word.
If our conjecture is correct, such shortcuts are just as problematic in the case of inter-word collocations. In fact, for the regular 30K-token vocabulary, divided words are rare, so inter-word collocations would pose a larger problem than intra-word collocations in the common setting. One possible mitigation might be to expand the vocabulary to include multi-word collocations. However, there are millions of these, and such vocabulary sizes are currently infeasible. Even if we could get around the practical issue of size, this approach may suffer from generalization problems: the frequency of each multi-word collocation can be lower than the sample complexity for learning a meaningful representation. An alternative, more practical approach is to leave the vocabulary as is, but jointly mask co-located words, with the intention of cutting off local statistical “shortcuts” and allowing the model to improve further by learning from broader context. This is the approach we take in this paper. In what follows we detail such a masking approach and show its advantages experimentally.
# 3 MASKING CORRELATED $n$ -GRAMS
# 3.1 EXISTING MASKING APPROACHES
We now more formally present the MLM setup as well as existing masking approaches, which we implement as baselines. Given text tokenized into a sequence of tokens, Masked Language Models are trained to predict a set fraction of “masked” tokens, where this fraction is called the masking budget and is traditionally set to $1 5 \%$ . The modified input is inserted into the Transformer-based architecture (Vaswani et al., 2017) of BERT, and the pretraining task is to predict the original identity of each chosen token. Several alternatives have been proposed for choosing the set of tokens to mask.
Random-Token Masking (Devlin et al., 2019a) The original BERT implementation selects tokens for masking independently at random, where $80 \%$ of the $1 5 \%$ chosen tokens are replaced with [MASK], $10 \%$ are replaced with a random token, and $10 \%$ are kept unchanged.
Whole-Word Masking (Devlin et al., 2019b) The sequence of input tokens is segmented into units corresponding to whole words. Tokens for masking are then chosen by sampling entire units at random until the masking budget is met. Following Devlin et al. (2019a), for $8 0 \% / 1 0 \% / 1 0 \%$ of the units, all tokens are replaced with [MASK]tokens/ random tokens/ the original tokens, respectively.
Random-Span Masking (Joshi et al., 2020) Contiguous random spans are selected iteratively until the $1 5 \%$ masking budget is spent. At each iteration, a span length (in words) is sampled from a geometric distribution $\ell \sim \mathrm { G e o } ( 0 . 2 )$ , and capped at 10 words. Then, the starting point for the span to be masked is randomly selected. Replacement with [MASK], random, or original tokens is done as above, where spans constitute the units.
# 3.2 PMI: FROM BIGRAMS TO $n$ -GRAMS
Our aim is to define a masking strategy that targets correlated sequences of tokens in a principled way. Of course, modeling such correlations in large corpora was widely studied in computational linguistics (Zuidema (2006); Ramisch et al. (2012); inter alia). Particularly relevant to our work is the notion of Pointwise Mutual Information (Fano, 1961), which quantifies how often two events occur, compared with what we would expect if they were independent. Define the probability of any $n$ -gram as the number of its occurrences in the corpus divided by the number of all the $n$ -grams in the corpus. PMI leverages these probabilities to give a natural measure of collocation of bigrams: how surprising the bigram $w _ { 1 } w _ { 2 }$ is, given the unigram probabilities of $w _ { 1 }$ and $w _ { 2 }$ . Formally, given two tokens $w _ { 1 }$ and $w _ { 2 }$ , the PMI of the bigram “ $\cdot _ { w _ { 1 } w _ { 2 } }$ ” is
$$\mathrm { P M I } ( w _ { 1 } w _ { 2 } ) = \log \frac { p ( w _ { 1 } w _ { 2 } ) } { p ( w _ { 1 } ) p ( w _ { 2 } ) } .$$
Importantly, PMI is qualitatively different from pure frequency: a relatively frequent bigram may not have a very high PMI score, and vice versa. For example, the bigram “book is” appears 34772 times in the WIKIPEDIA $+ \mathbf { B }$ OOKCORPUS dataset but is ranked around position 760K in the PMI ranking for bi-grams over this corpus, while the bigram “boolean algebra” appears 849 times in the corpus but is ranked around position 16K in the PMI ranking.
What about contiguous spans of more than two tokens? For a given $n$ -gram, we would again like to measure how strongly its components indicate one another. We thus require a measure that captures correlations among more than two variables. A standard and direct extension of the PMI measure to more than two variables, referred to as ‘specific correlation’ in Van de Cruys (2011), and as ‘Naive$\mathrm { P M I } _ { n } $ in this paper, is based on the ratio between the $n$ -gram’s probability and the probabilities of its component unigrams:
$$\mathrm { N a i v e \mathrm { - } P M I } _ { n } ( w _ { 1 } \ldots w _ { n } ) = \log { \frac { p ( w _ { 1 } \ldots w _ { n } ) } { \prod _ { j = 1 } ^ { n } p ( w _ { j } ) } }$$
As in the bivariate case, this measure compares the actual empirical probability of the $n$ -gram in the corpus with the probability it would have if its components occurred independently. However, the above definition suffers from an inherent flaw: an $n$ -gram’s Naive- $\mathrm { P M I } _ { n }$ will be high if it contains a segment with high PMI, even if that segment is not particularly correlated with the rest of the $n$ -gram. Consider for example the case of trigrams:
$$\begin{array} { r } { \operatorname { i v e - P M I } _ { 3 } ( w _ { 1 } w _ { 2 } w _ { 3 } ) = \log \{ \frac { p ( w _ { 1 } w _ { 2 } w _ { 3 } ) } { p ( w _ { 1 } ) p ( w _ { 2 } ) p ( w _ { 3 } ) } \cdot \frac { p ( w _ { 1 } w _ { 2 } ) } { p ( w _ { 1 } w _ { 2 } ) } \} = \operatorname { P M I } ( w _ { 1 } w _ { 2 } ) + \log \frac { p ( w _ { 1 } w _ { 2 } w _ { 3 } ) } { p ( w _ { 1 } w _ { 2 } ) p ( w _ { 3 } ) } } \end{array}$$
Where $\mathrm { P M I } ( w _ { 1 } w _ { 2 } )$ is defined in eq. 1. When $\mathrm { P M I } ( w _ { 1 } w _ { 2 } )$ is high, the Naive- $\mathrm { P M I _ { 3 } }$ measure of the trigram “w1w2w3” will start at this high baseline. The added term of log p(w1w2w3)p(w1w2)p(w3) quantifies the actual added information of “ $w _ { 3 } \mathrm { ^ { , } }$ to this correlated bigram, i.e., it quantifies how far $p ( w _ { 1 } w _ { 2 } w _ { 3 } )$ is from being separable w.r.t. the segmentation into $" w _ { 1 } w _ { 2 } "$ and $^ { 6 6 } w _ { 3 } \ '$ . For example, since the PMI of the bigram “Kuala Lumpur” is very high, the Naive- $\mathrm { P M I } _ { n }$ of the trigram “Kuala Lumpur is” is misleadingly high, placing it at position 43K out of all trigrams in the WIKIPEDIA $^ +$ BOOKCORPUS dataset. It is in fact placed much higher than obvious collocations such as the trigram “editor in chief ”, which is ranked at position 210K out of all trigrams.
In order to favor $n$ -grams that cannot be easily subdivided into shorter unrelated spans, we propose a measure of distance from separability with respect to all of an $n$ -gram’s possible segmentations rather than with respect only to the segmentation into single tokens:
$$\operatorname { \mathbf { P M I } } _ { n } ( w _ { 1 } \dots w _ { n } ) = \operatorname* { m i n } _ { \substack { \sigma \in \sec ( w _ { 1 } \dots w _ { n } ) } } \log \frac { p ( w _ { 1 } \dots w _ { n } ) } { \prod _ { s \in \sigma } p ( s ) }$$
Here, $\sec ( w _ { 1 } \ldots w _ { n } )$ is the set of all contiguous segmentations of the $n$ -gram $^ { \bullet } w _ { 1 } \ldots w _ { n } ^ { \quad \bullet }$ (excluding the identity segmentation), where any segmentation $\sigma \in \sec ( w _ { 1 } \ldots w _ { n } )$ is composed of sub-spans which together give $^ { } w _ { 1 } \dots w _ { n } ^ { \quad \prime \prime }$ . Intuitively, this measure effectively discards the contribution of high PMI segments; the minimum in Eq. 3 implies that an $n$ -gram’s collocation score is given by its weakest link, i.e., by the segmentation that is closest to separability. When ranked by the above $\mathrm { P M I } _ { n }$ measure, the trigram “Kuala Lumpur is” is demoted to position 1.6M, since the segmentation into “Kuala Lumpur” and “is” yields unrelated segments, while the trigram “editor in chief ” is upgraded to position 33K since its segmentations yield correlated components. As we will see, this definition is not only conceptually cleaner, but also leads to improved performance.
# 3.2.1 PMI-MASKING
We implement our strategy of treating highly collocating $n$ -grams as units for masking by assembling a list of $n$ -grams as a masking vocabulary in parallel to the 30K-token vocabulary. Specifically, we make use of the entire pretraining corpus for compiling a list of collocations. We consider word $n$ -grams of lengths 2–5 having over 10 occurrences in the corpus, and include the highest ranking collocations over the corpus, as measured via our proposed $\mathrm { P M I } _ { n }$ measure (Eq. 3). Noticing that the $\mathrm { P M I } _ { n }$ measure is sensitive to the length of the $n$ -gram, we assemble per-length rankings for each $n \in \{ 2 , 3 , 4 , 5 \}$ , and integrate these rankings to compose the masking vocabulary. After conducting a preliminary evaluation of how an $n$ -gram’s quality as a collocation degrades with its $\mathrm { P M I } _ { n }$ rank (detailed in the appendix), we chose the masking vocabulary size to be 800K, for which approximately half of pretraining corpus tokens were identified as part of some correlated $n$ -gram.
In order to get some sense of the differences between the attained masking vocabulary and prior approaches, we annotated a random sample of 500 bigrams and 500 trigrams from the masking vocabulary with Entity/Not-Entity labels. We found that only around $14 \%$ of the entries in the bigrams/trigrams lists were annotated as entities, while the rest are other types of collocations. Moreover, we found that while named entities are very prevalent at the very top of the list, they are scarce otherwise. By refining the view into highest and lowest ranking PMI bigram groups, we get that $50 \%$ of the top $20 \%$ are entities while only $1 \%$ of the bottom $20 \%$ are entities, and similar trends are attained for trigrams. This breakdown can illuminate a natural intuition regarding high ranking PMI n-grams representing entities (employed also by previous works (Downey et al., 2007; Korkontzelos et al., 2008)) – indeed the top ranking PMI entries are largely entities. But we chose a much larger PMI-based masking vocabulary (see appendix 1 on the process of choosing its size), and the proportion of entities drops to around 1/7, with many of the added entries representing other types of collocations (the annotated lists are given as supplementary material).
After composing the masking vocabulary, we treat its entries as units to be masked together. All input tokens not identified with entries from the masking vocabulary are treated independently as units for masking according to the Whole-Word Masking scheme. If one masking vocabulary entry contains another entry in a given input, we treat the larger one as the unit for masking, e.g., if the masking vocabulary contains the $n$ -grams “the united states”, “air force”, and “the united states air force”, the latter will be one unit for masking when it appears. In the case of overlapping entries, we choose one at random as a unit for masking and treat the remaining tokens as independent units, e.g., if the input text contains “by the way out” and the masking vocabulary contains the $n$ -grams “by the way” and “the way out”, we can choose either “by the way” and “out” or “by” and “the way out” as units for masking.
After we segment the sequence of input tokens into units for masking, we then choose tokens for masking by sampling units uniformly at random until $1 5 \%$ of the tokens (the standard tokens of the 30K-token vocabulary) in the input are selected. As in the prior methods, replacement with [MASK] $( 8 0 \% )$ , random $( 1 0 \% )$ , or original $( 1 0 \% )$ ) tokens is done at the unit level.
# 4 EXPERIMENTAL SETUP
To evaluate the impact of PMI-Masking, we trained Base-sized BERT models (Devlin et al., 2019a) with each of the masking schemes presented in Section 3. Rather than relying on existing implementations for baseline masking schemes, which vary in training specifics, we reimplemented each scheme within the same framework used to train our PMI-Masked models. For control, we trained within the same framework models with Naive-PMI-Masking and Frequency-Masking, following the procedure described above for PMI-Masking, but ranking by the Naive- $\mathrm { P M I } _ { n }$ measure (Eq. 2) and by pure-frequency, respectively. In Section 5, we compare our PMI-Masking to all internallytrained masking schemes (Table 2) as well as with externally released models (Table 3).
# 4.1 PRETRAINING
We trained uncased models with a 30K-sized vocabulary that we constructed over WIKIPEDIA +BOOKCORPUS via the WordPiece Tokenizer used in BERT. We omitted the Next Sentence Prediction task, as it was shown to be superfluous (Joshi et al., 2020), and trained only on the Masked Language Model task during pretraining. We trained with a sequence length of 512 tokens, batch size of 256, and a varying number of steps detailed in Section 5. For pretraining, after a warmup of 10, 000 steps we used a linear learning rate decay, therefore models that ran for a different overall amount of steps are not precisely comparable after a given amount of steps. We set remaining parameters to values similar to those used in the original BERT pretraining, detailed in the appendix.
We performed the baseline pretraining over the original corpus used to train BERT: the 16GB WIKIPEDIA $^ +$ BOOKCORPUS dataset. We show that PMI-Masking achieved even larger performance gains relative to the baselines when training over more data, by adding the 38GB OPENWEBTEXT (Gokaslan & Cohen, 2019) dataset, an open-source recreation of the WebText corpus described in Radford et al. (2019). As described in section 3, we compose our $\mathrm { P M I } _ { n }$ -based masking vocabulary according to the pretraining corpus in use.
# 4.2 EVALUATION
We evaluate our pretrained models on two question answering benchmarks: the Stanford Question Answering Dataset (SQuAD) and the ReAding Comprehension from Examinations (RACE), as well as on the General Language Understanding Evaluation (GLUE) benchmark. Additionally, we report the Single-Token perplexity of our pretrained models.
• SQuAD (Rajpurkar et al., 2016) has served as a major question answering benchmark for pretrained models. It provides a paragraph of context and a question, and the task is to answer the question by extracting the relevant span from the context. We focus on the latest more challenging variant, SQuAD2.0 (Rajpurkar et al., 2018), in which some questions are not answered in the provided context, and the task includes identifying such cases. • RACE (Lai et al., 2017) is a large-scale reading comprehension dataset collected from English examinations in China, designed for middle and high school students. Each passage is associated with multiple questions; for each, the task is to select one correct answer from four options. RACE has significantly longer context than other popular reading comprehension datasets and the proportion of questions that requires reasoning is very large. GLUE (Wang et al., 2018) is a collection of 9 datasets for evaluating natural language understanding systems. Tasks are framed as either single-sentence classification or sentence-pair classification tasks. For full details, please see the appendix. • Single-Token perplexity We evaluate an MLM’s ability to predict single-tokens by measuring perplexity over a held out test set of 110K tokens from OPENWEBTEXT. For each test example, a single token for prediction is masked and the remainder of the input tokens are unmasked.
In Tables 2 and 3, for every downstream task we swept 8 different hyperparameter configurations (batch sizes $\in \{ 1 6 , 3 2 \}$ and learning rates $\in \{ 1 , 2 , 3 , 5 \} \cdot 1 0 ^ { - 5 } )$ . We report the best median development set score over five random initializations per hyper-parameter. When applicable, the model with this score was evaluated on the test set. The development set score of each configuration was attained by fine-tuning the model over 4 epochs (SQuAD2.0 and RACE) or 3 epochs (all GLUE tasks except RTE and $\mathrm { S T S } - 1 0 $ epochs) and performing early stopping based on each task’s evaluation metric on the development set. In the preliminary experiments of Table 1, and in Figures 1 and 2 for which we evaluate many pretraining checkpoints per model, we report the average of the three middle scores out of 5 random initializations for a single set of hyper-parameters (batch size 32 and learning rate $3 \cdot 1 0 ^ { - 5 }$ ).
 2.4M steps on Wikipedia+BookCorpus (16G)
 Figure 2: Scores on $\mathrm { S Q u A D 2 . 0 }$ development set of BERTBASE models trained for $2 . 4 \mathbf { M }$ steps, as done by Joshi et al. (2020) when proposing Random-Span Masking. Left: PMI-Masking efficiently elicits information from limited data. Right: More data, PMI-Masking continues to improve. See numerical scores in the appendix, along with the same trends on the RACE benchmark.
# 5 EXPERIMENTAL RESULTS
We evaluated the different masking strategies in two key ways. First, we measured their effect on downstream performance throughout pretraining to assess how efficiently they used the pretraining phase. Second, we more exhaustively evaluated downstream performance of different approaches at the end of pretraining. We examine how the advantage of PMI-Masking is affected by the size of the pretraining corpus and by amount of examples seen during pretraining (batch size $\times$ training steps).
# 5.1 EVALUATING DOWNSTREAM PERFORMANCE THROUGHOUT PRETRAINING
By examining the model’s downstream performance after each 200K steps of pretraining, we demonstrate that PMI-Masking speeds up MLM training. Figure 1 investigates the standard BERT setting of pretraining on the Wikipedia $^ +$ BookCorpus dataset for 1M training steps with batch size 256. It shows that the PMI-Masking method clearly outperformed a variety of prior approaches, as well as the baseline pure frequency based masking, on the SQuAD2.0 development set for all examined checkpoints (these patterns are consistent on RACE, see detailed scores in the appendix). PMIMasking achieved the score of Random-Span Masking, the best of the existing approaches, after roughly half as many steps of pretraining.
We ran a second experiment that increased the number of steps from 1M to 2.4M, while maintaining the batch size and the pretraining corpus; this was the setting used by Joshi et al. (2020) when proposing Random-Span Masking. We observed that while PMI-masking learned much more quickly, it eventually reached a plateau, and Random-Span Masking caught up after enough training steps. Figure 2 (left) details these results.
Finally, we increased the amount of training data by adding the OPENWEBTEXT corpus $( \sim 3 . 5 \times$ more data). Figure 2 (right) demonstrates that the plateau we previously observed in PMIMasking’s performance was due to limited training data. When training for $2 . 4 \mathbf { M }$ training steps on the Wikipedia+BookCorpus $+$ OpenWebText dataset, PMI-masking reached the same score that Random-Span Masking did at the end of training after roughly half of the pretraining, and continued to improve. Thus, PMI-Masking definitively outperformed Random-Span masking in a scenario where data was not a bottleneck, as is ideally the case in MLM pretraining (Raffel et al., 2019).
# 5.2 EVALUATING DOWNSTREAM PERFORMANCE AFTER PRETRAINING
Table 2 shows that after pretraining was complete, PMI-Masking outperformed prior masking approaches in downstream performance on the SQuAD2.0, RACE, and GLUE benchmarks. In agreement with Figure 2, for longer pretraining (2.4M training steps) the absolute advantage of PMIMasking is boosted across all tasks when pretraining over a larger corpus (adding OPENWEBTEXT). The table also shows that Naive-PMI Masking, based on the straightforward extension in eq. 2 to the standard bivariate PMI, significantly falls behind our more nuanced definition in eq. 3, and is often on par with Random-Span Masking.
Table 2: Dev/Test performance on the SQuAD, RACE, and GLUE benchmarks of BERT Base sized models pretrained and evaluated according to section 4. We report EM (exact match) and F1 scores for SQuAD2 and accuracy for RACE. For GLUE we report the average scores on the development set and the official leaderboard scores on the test set (see the per-task scores in the appendix).
<table><tr><td>BERTBasewith different maskings</td><td colspan="2">SQuAD2.0 EM F1</td><td>RACE Acc.</td><td>GLUE Avg</td></tr><tr><td>1M training steps on WIKIPEDIA+BOOKCORPUS(16G):</td><td colspan="4"></td></tr><tr><td>Random-Token Masking</td><td colspan="4">76.4/- 79.6/-</td></tr><tr><td>Random-Span Masking Naive-PMI-Masking</td><td>77.1/-</td><td>80.3/-</td><td>67.8/66.2 68.6/66.9 69.7/67.8</td><td>83.1/- 83/-</td></tr><tr><td>PMI-Masking</td><td>78.2/- 78.5/-</td><td>81.3/- 81.4/-</td><td>70.1/68.4</td><td>84.1/- 84.1/-</td></tr><tr><td>2.4M training steps on WIKIPEDIA+BOOKCORPUS(16G)</td><td colspan="4"></td></tr><tr><td>Random-Span Masking</td><td>79.7/80.0</td><td>82.7/82.8</td><td>71.9/69.5</td><td>84.8/79.7</td></tr><tr><td>Naive-PMI-Masking</td><td>80.3/80.2</td><td>83.2/83.2</td><td>71.7/69.8</td><td>84.5/80.0</td></tr><tr><td>PMI-Masking</td><td>80.2/80.9</td><td>83.3/ 83.6</td><td>72.3/70.9</td><td>84.7/80.3</td></tr><tr><td>2.4M training steps on WIKIPEDIA+BOOKCORPUS+OPENWEBTEXT(54G):</td><td colspan="4"></td></tr><tr><td></td><td></td><td></td><td></td><td></td></tr><tr><td>Random-Span Masking</td><td>80.1/80.4</td><td>83.2/83.3</td><td>74.0/72.2</td><td>85.1/80.1</td></tr><tr><td>Naive-PMI-Masking</td><td>80.4/80.0</td><td>83.3/83.0</td><td>73.9/71.4</td><td>85.6/80.3</td></tr><tr><td>PMI-Masking</td><td>80.9/82.0</td><td>83.9/84.9</td><td>74.8/73.2</td><td>86.0/80.8</td></tr></table>
Table 3: Comparing the RACE scores of our PMI-Masked models with comparable published Basesized models. The scores of prior MLMs were attained by finetuning released models in the same setup of the PMI-Masked models (Section 4), except for those marked in $^ { \bullet } \dag ^ { \bullet }$ , reported in Zhang & Li (2020). The number of examples reflects the amounts of text examined during training, as all prior models train over the same sequence length as our PMI-Masked models, namely 512. AMBERT was trained over WIKIPEDIA $^ +$ OPENWEBTEXT (47G), SpanBERT over WIKIPEDIA $^ +$ BOOKCORPUS (16G), and RoBERTa over WIKIPEDIA $^ +$ BOOKCORPUS $^ +$ OPENWEBTEXT $^ +$ STORIES $^ +$ CCNEWS (160G – see details in Liu et al. (2019)).
<table><tr><td>PMI vsPrior BASE MLMs</td><td>Corpus size</td><td>Batch × Steps = Examples</td><td>RACE dev/test</td></tr><tr><td> PMI vs n-grams in vocabulary</td><td></td><td></td><td></td></tr><tr><td>AMBERT (Zhang& Li, 2020)</td><td>47G</td><td>1024 × 0.5M= 512G</td><td>68.9†/66.8t</td></tr><tr><td>PMI-Masking</td><td>16G</td><td>256 ×1M =256M</td><td>70.1/68.4</td></tr><tr><td>PMI vs Random-Span Masking</td><td></td><td></td><td></td></tr><tr><td>SpanBERTBASE (Joshi et al., 2020)</td><td>16G</td><td>256 × 2.4M = 614.4M</td><td>70.5/68.7</td></tr><tr><td>PMI-Masking</td><td>16G</td><td>256 × 2.4M = 614.4M</td><td>72.3/70.9</td></tr><tr><td colspan="4">PMI vs Random-Token Masking with 3X more data and 6X more training examples</td></tr><tr><td>RoBERTaBAsE (Liu et al.,2019)</td><td>160G</td><td>8K × 0.5M=4G</td><td>74.9/73</td></tr><tr><td>PMI-Masking</td><td>54G</td><td>256 × 2.4M= 614.4M</td><td>74.8/73.2</td></tr></table>
We also compared our PMI-Masking Base-sized models to published Base-sized models (Table 3), and again saw PMI-Masking increase both pretraining efficiency and end-of-training downstream performance. Zhang & Li (2020) trained their ‘AMBERT’ model over a vocabulary of $n$ -grams in parallel to the regular word/subword level vocabulary, performing the hard task of $n$ -gram prediction in parallel to the easy Random-Token level prediction task during pretraining. This approach yielded a model with $7 5 \%$ more parameters than the common Base size of our PMI-Masking model. By using the PMI-masking scheme on a regular BERT architecture and vocabulary, we attained a significantly higher score on the RACE benchmark, despite training over a corpus $3 \times$ smaller and showing the model $2 \times$ fewer examples during pretraining.
Joshi et al. (2020) and Liu et al. (2019) only reported scores for SpanBERT and RoBERTa (respectively) for Large-sized models in their original papers, but did release weights for Base-sized models. We fine-tuned these models on the RACE development set via the same fine-tuning procedure we employed for our PMI-Masking models (described in Section 4), and evaluated the best performing model on the publicly available RACE test set. A PMI-Masking Base-sized model scored more than 2 points higher than the SpanBERTBASE trained by Random-Span Masking over the same pretraining corpus when shown the same number of examples. Remarkably, a PMI-Masking Base-sized model scored slightly higher than RoBERTaBASE trained by Random-Token Masking, even though RoBERTa was given access to a pretraining corpus $3 \times$ larger and shown $6 \times$ more training examples.
Lastly, we note that the measure of Single-Token perplexity is not indicative of downstream performance, when reported for models trained with different masking schemes. Comparing the adjacent table with the downstream evaluation of the same models in Table 2, it is clear that the ability to predict single tokens from context is not correlated with performance. This reinforces our observation that by minimizing their training objective, standard MLMs, which mask tokens randomly, train to excel on relatively many easy tasks that do not reflect the knowledge required for downstream understanding.
Table 4: The Single-Token perplexity of MLMs trained for 1M steps over WIKI+BOOKCORPUS.
<table><tr><td colspan="2">Single-Token Perplexity</td></tr><tr><td>Random-Token Masking</td><td>2.96</td></tr><tr><td>Random-Span Masking</td><td>4.30</td></tr><tr><td>Naive-PMI-Masking</td><td>7.35</td></tr><tr><td>PMI-Masking</td><td>21.85</td></tr></table>
# 6 CONCLUSION
Bidirectional language models hold the potential to unlock greater signal from the training data than unidirectional models (such as GPT). BERT-based MLMs are historically the first (and still the most prominent) implementation of inherently bidirectional language models, but they come at a price. A hint of this price is the fact that Single-Token perplexity, which captures the ability to predict single tokens and which has a natural probabilistic interpretation in the autoregressive unidirectional case, ceases to correlate with downstream performance across different MLMs (see Table 4). This means that the original MLM task, which is focused on single token prediction, should be reconsidered. This has been the focus of this paper, which points to the inefficiency of random-token masking, and offers PMI-masking as an alternative with several advantages: (i) It is a principled approach, based on a nuanced extension of binary PMI to the n-ary case. (ii) It leads to better downstream performance, for example it surpasses RoBERTa (which uses vanilla random token masking) on the challenging reading comprehension RACE test with $6 \times$ less training over a $3 \times$ smaller corpus, and it dominates the more naive, heuristic approach of random span masking at any point during pretraining, matches its end-of-training performance halfway during its own pretraining, and at the end of training improves on it by 1-2 points across a variety of downstream tasks. Perhaps due to their conceptual simplicity, unidirectional models were the first to break the 100B parameter limit with the recent GPT3 (Brown et al., 2020). Bidirectional models will soon follow, and this paper can accelerate their development by offering a way to significantly lower their training costs while boosting performance.
# REFERENCES
Roy Bar-Haim, Ido Dagan, Bill Dolan, Lisa Ferro, Danilo Giampiccolo, Bernardo Magnini, and Idan Szpektor. The second PASCAL recognising textual entailment challenge. In Proceedings of the second PASCAL challenges workshop on recognising textual entailment, pp. 6–4, 2006. Tom B Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language models are few-shot learners. arXiv preprint arXiv:2005.14165, 2020. Daniel Cer, Mona Diab, Eneko Agirre, Inigo Lopez-Gazpio, and Lucia Specia. Semeval-2017 task ˜ 1: Semantic textual similarity multilingual and crosslingual focused evaluation. In International Workshop on Semantic Evaluation (SemEval), pp. 1–14, Vancouver, Canada, 2017. Ido Dagan, Oren Glickman, and Bernardo Magnini. The PASCAL recognising textual entailment challenge. In Machine Learning Challenges Workshop, pp. 177–190. Springer, 2005.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pre-training of deep bidirectional transformers for language understanding. In North American Association for Computational Linguistics (NAACL), 2019a.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Original bert github repository. https://github.com/google-research/bert, 2019b.
William B Dolan and Chris Brockett. Automatically constructing a corpus of sentential paraphrases. In Proceedings of the International Workshop on Paraphrasing, 2005.
Doug Downey, Matthew Broadhead, and Oren Etzioni. Locating complex named entities in web text. In Proceedings of the 20th International Joint Conference on Artifical Intelligence, IJCAI’07, pp. 2733–2739, San Francisco, CA, USA, 2007. Morgan Kaufmann Publishers Inc.
R.M Fano. Transmission of Information: A Statistical Theory of Communications. Transmission of Information: A Statistical Theory of Communications. M.I.T. Press, 1961. ISBN 9780262060011. URL https://books.google.co.il/books?id $\underline { { \underline { { \mathbf { \Pi } } } } } =$ VSYIAQAAIAAJ.
Danilo Giampiccolo, Bernardo Magnini, Ido Dagan, and Bill Dolan. The third PASCAL recognizing textual entailment challenge. In Proceedings of the ACL-PASCAL workshop on textual entailment and paraphrasing, pp. 1–9, 2007.
Aaron Gokaslan and Vanya Cohen. Openwebtext corpus, 2019.
Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat, and Ming-Wei Chang. Realm: Retrievalaugmented language model pre-training. arXiv preprint arXiv:2002.08909, 2020.
Mandar Joshi, Danqi Chen, Yinhan Liu, Daniel S Weld, Luke Zettlemoyer, and Omer Levy. Spanbert: Improving pre-training by representing and predicting spans. Transactions of the Association for Computational Linguistics, 8:64–77, 2020.
Ioannis Korkontzelos, Ioannis P Klapaftis, and Suresh Manandhar. Reviewing and evaluating automatic term recognition techniques. In International Conference on Natural Language Processing, pp. 248–259. Springer, 2008.
Guokun Lai, Qizhe Xie, Hanxiao Liu, Yiming Yang, and Eduard Hovy. Race: Large-scale reading comprehension dataset from examinations. arXiv preprint arXiv:1704.04683, 2017.
Hector J Levesque, Ernest Davis, and Leora Morgenstern. The Winograd schema challenge. In AAAI Spring Symposium: Logical Formalizations of Commonsense Reasoning, volume 46, pp. 47, 2011.
Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. RoBERTa: A robustly optimized BERT pretraining approach. arxiv preprint arXiv:1907.11692, 2019.
Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. arXiv preprint, 2019.
Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J Liu. Exploring the limits of transfer learning with a unified text-to-text transformer. arXiv preprint arXiv:1910.10683, 2019.
Pranav Rajpurkar, Jian Zhang, Konstantin Lopyrev, and Percy Liang. Squad: $1 0 0 { , } 0 0 0 { + }$ questions for machine comprehension of text. arXiv preprint arXiv:1606.05250, 2016.
Pranav Rajpurkar, Robin Jia, and Percy Liang. Know what you don’t know: Unanswerable questions for squad. arXiv preprint arXiv:1806.03822, 2018.
Carlos Ramisch, Vitor De Araujo, and Aline Villavicencio. A broad evaluation of techniques for automatic acquisition of multiword expressions. In Proceedings of ACL 2012 Student Research Workshop, pp. 1–6, 2012.
Richard Socher, Alex Perelygin, Jean Wu, Jason Chuang, Christopher D Manning, Andrew $\mathrm { N g }$ , and Christopher Potts. Recursive deep models for semantic compositionality over a sentiment treebank. In Empirical Methods in Natural Language Processing (EMNLP), pp. 1631–1642, 2013.
Yu Stephanie Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xinlun Tian, Danxiang Zhu, Hao Tian, and Hua Wu. ERNIE: Enhanced representation through knowledge integration. arXiv preprint arXiv:1904.09223, 2019.
Tim Van de Cruys. Two multivariate generalizations of pointwise mutual information. In Proceedings of the Workshop on Distributional Semantics and Compositionality, pp. 16–20, 2011.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in Neural Information Processing Systems (NIPS), 2017.
Alex Wang, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R Bowman. Glue: A multi-task benchmark and analysis platform for natural language understanding. arXiv preprint arXiv:1804.07461, 2018.
Alex Wang, Amapreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R Bowman. Glue: A multi-task benchmark and analysis platform for natural language understanding. In International Conference on Learning Representations (ICLR), 2019.
Alex Warstadt, Amanpreet Singh, and Samuel R. Bowman. Neural network acceptability judgments. arXiv preprint arXiv:1805.12471, 2018.
Adina Williams, Nikita Nangia, and Samuel Bowman. A broad-coverage challenge corpus for sentence understanding through inference. In North American Association for Computational Linguistics (NAACL), pp. 1112–1122, 2018.
Xinsong Zhang and Hang Li. Ambert: A pre-trained language model with multi-grained tokenization. arXiv preprint arXiv:2008.11869, 2020.
Willem Zuidema. What are the productive units of natural language grammar? a dop approach to the automatic identification of constructions. In Proceedings of the Tenth Conference on Computational Natural Language Learning (CoNLL-X), pp. 29–36, 2006.
 Figure 3: Quality measures of top ranking $\mathrm { P M I } _ { n }$ $n$ -grams lists increased in increments of 50K. The masking vocabulary size was chosen such that it includes as many $n$ -grams labeled as collocation as possible, while not including too many $n$ -grams labeled as not a collocation, in an internally constructed test set detailed below. $r$ is the percent of all positively labeled examples from the test set that appear within the given list (recall), $c$ is the percent of all negatively labeled examples from the test set that do not appear within the given list (complement-recall). We aim for a list size for which both $r$ and $c$ are high enough, and employ $f$ as a measure for this, finally choosing a list size of $8 0 0 \mathrm { K }$ .
# A DETERMINING THE MASKING VOCABULARY SIZE
The $\mathrm { P M I } _ { n }$ measure, defined in eq. 3, provides an $n$ -gram ranking function that is intended to rank an $n$ -gram higher if its components are more indicative of one another. However, this measure alone is not enough for composing a masking vocabulary: we need to decide on its size $M$ (the masking vocabulary will be composed of the top- $M$ ranked $n$ -grams). One could advocate for an ablation study in which $M$ is varied, and models are pretrained per $M$ and evaluated. This can be done in future work, and perhaps an even stronger result can be shown for PMI-Masking with masking vocabulary size chosen by such optimization.
As a proxy, we determined the masking vocabulary size $M$ via a small scale evaluation of an $n$ - gram’s “collocation quality” as a function of its $\mathrm { P M I } _ { n }$ rank. Specifically, we created an ad hoc test set composed of $1 0 0 0 ~ n$ -grams that we labeled either as collocation or not a collocation (available upon request). We did that by choosing at random 10 words with frequency above 10000 in WIKIPEDIA $^ +$ BOOKCORPUS, and for each word sampled 25 $n$ -grams per length $n \in \{ 2 , 3 , 4 , 5 \}$ that contain it. Finally, we manually labeled each collected $n$ -gram, where the textbook definition of collocation was given to the annotators (the annotator agreement was $80 \%$ over 100 shared examples).
Then, we increased a list size $M$ in steps of $5 0 \mathrm { K }$ , adding $n$ -grams from the top ranking $\mathrm { P M I } _ { n }$ downwards. For each $M$ -sized list we computed two different scores on the test set. The first is the recall of the positive examples in the list, denoted $r$ : the percent of all positively labeled examples from the test set that appear within the given list. The second is the recall of the negative examples in the complement of the list, dubbed complement-recall, denoted $c$ : the percent of all negatively labeled examples from the test set that do not appear within the given list. By these definitions, the recall $r$ starts low and increases with list size and the complement-recall $c$ follows an opposite trend, as can be seen in Figure 3. Our desired masking vocabulary size should yield a list with many $n$ -grams labeled as collocation while containing little $n$ -grams labeled not a collocation. we define $\textstyle f { \overset { } { = } } { \frac { 2 r \cdot c } { r + c } }$ as a measure for optimization which balances the two requirements, and Figure 3 shows that this measure is highest at sizes of around 700-800, so we set the masking vocabulary size to be 800K.
Table 5 shows the pretraining hyper-parameters we used, as well as the architecture specifics, both follow the standard implementation of BERT.
Number of Layers 12 Hidden Size 768 Sequence Length 512 FFN Inner Hidden Size 3072 Attention Heads 1 2 Attention Head Size 64 Dropout 0.1 Attention Dropout 0.1 Warmup Steps 10,000 Peak Learning Rate 1e-4 Batch Size 256 Weight Decay 0.01 Initializer Range 0.02 Learning Rate Decay Linear Adam 1e-6 Adam $\beta _ { 1 }$ 0.9 Adam $\beta _ { 2 }$ 0.999
# C EVALUATION OF DIFFERENT CHECKPOINTS DURING PRETRAINING
Tables 6 and 7 respectively present the development set scores on SQuAD2.0 and RACE, attained for models at different checkpoints during pretraining. The SQuAD2.0 scores are depicted in Figures 1 and 2.
<table><tr><td>pretraining checkpoint:</td><td>200</td><td>400</td><td>600</td><td>800</td><td>1000</td><td>1200</td><td>1600</td><td>2000</td><td>2400</td></tr><tr><td colspan="10">1M training steps on WIKIPEDIA+BOOKCORPUS</td></tr><tr><td>Random-Token Masking</td><td>74.4</td><td>76.7</td><td>77.9</td><td>78.9</td><td>79.3</td><td>一</td><td></td><td></td><td></td></tr><tr><td>Whole-Word Masking</td><td>74.8</td><td>77.9</td><td>78.4</td><td>79.1</td><td>79.6</td><td></td><td></td><td></td><td></td></tr><tr><td>Frequency-Masking</td><td>75.5</td><td>78</td><td>79.2</td><td>79.4</td><td>79.7</td><td>1</td><td>1</td><td></td><td></td></tr><tr><td>Random-Span Masking</td><td>74.8</td><td>77.4</td><td>78.9</td><td>79.6</td><td>80.0</td><td></td><td></td><td></td><td></td></tr><tr><td>PMI-Masking</td><td>77.0</td><td>78.8</td><td>80.3</td><td>81.1</td><td>81.3</td><td>1</td><td></td><td></td><td></td></tr><tr><td colspan="10"> 2.4M training steps on WIKIPEDIA+BOOKCORPUS</td></tr><tr><td>Random-Span Masking</td><td>75.8</td><td>78.4</td><td></td><td></td><td>80.9</td><td>81.8</td><td>82.2</td><td></td><td>83.1</td></tr><tr><td>PMI-Masking</td><td>77.2</td><td>79.8</td><td>79.8 81.0</td><td>80.4 81.6</td><td>81.8</td><td>82.4</td><td>83.1</td><td>82.9 83.0</td><td></td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>83.3</td></tr><tr><td colspan="10"> 2.4M training steps on WIKIPEDIA+BOOKCORPUS+OPENWEBTEXT</td></tr><tr><td>Random-Span Masking</td><td>77.1</td><td>78.9</td><td>80.9</td><td>81.0</td><td>81.8</td><td>82.3</td><td>82.7</td><td>83.1</td><td>83.2</td></tr><tr><td>PMI-Masking</td><td>78.4</td><td>80.7</td><td>82.1</td><td>82.4</td><td>82.9</td><td>83.3</td><td>83.8</td><td>84.0</td><td>84.3</td></tr></table>
Table 6: The F1 score on the SQuAD2.0 development set of models taken at various checkpoints along the pretraining of BERT Base sized models trained with different masking schemes. These scores are depicted in Figures 1 and 2. We finetuned on SQuAD2.0 with batch size of 32 and learning rate of $3 \cdot 1 0 ^ { \bar { - } 5 }$ over 4 epochs without early stopping. We did this for 5 random initializations of the task’s head and the reported score is an average of the three middle scores.
<table><tr><td>pretraining checkpoint:</td><td>200</td><td>400</td><td>600</td><td>800</td><td>1000</td><td>1200</td><td>1600</td><td>2000</td><td>2400</td></tr><tr><td colspan="10">1M training steps on WIKIPEDIA+BoOKCORPUS</td></tr><tr><td>Random-Token Masking</td><td>61.2</td><td>64.3</td><td>65.6</td><td>66.4</td><td>67.1</td><td></td><td></td><td></td><td></td></tr><tr><td>Whole-Word Masking</td><td>62.0</td><td>64.9</td><td>66.0</td><td>67.0</td><td>67.8</td><td></td><td></td><td></td><td></td></tr><tr><td>Frequency-Masking</td><td>63.7</td><td>65.7</td><td>67.3</td><td>68.5</td><td>68.8</td><td></td><td></td><td></td><td></td></tr><tr><td>Random-Span Masking</td><td>61.7</td><td>64.7</td><td>66.8</td><td>67.9</td><td>68.0</td><td></td><td></td><td></td><td></td></tr><tr><td>PMI-Masking</td><td>63.5</td><td>66.8</td><td>68.4</td><td>68.9</td><td>69.7</td><td></td><td></td><td></td><td></td></tr><tr><td colspan="10">2.4M training steps on WIKIPEDIA+BOOKCORPUS</td></tr><tr><td>Random-Span Masking</td><td>62.3</td><td>64.3</td><td>65.6</td><td>67.8</td><td>69.0</td><td>68.9</td><td>70.3</td><td>71.0</td><td>71.4</td></tr><tr><td>PMI-Masking</td><td>63.6</td><td>66.7</td><td>67.3</td><td>68.5</td><td>69.2</td><td>70.4</td><td>70.5</td><td>71.2</td><td>72.2</td></tr><tr><td colspan="10">2.4M training steps on WIKIPEDIA+BOOKCORPUS+OPENWEBTEXT</td></tr><tr><td>Random-Span Masking</td><td>64.6</td><td>67.0</td><td>69.2</td><td>69.9</td><td>70.5</td><td>71.3</td><td>72.9</td><td>73.5</td><td>73.4</td></tr><tr><td>PMI-Masking</td><td>66.5</td><td>68.6</td><td>70.7</td><td>71.4</td><td>72.4</td><td>72.5</td><td>73.6</td><td>74.1</td><td>74.5</td></tr></table>
Table 7: The accuracy score on the RACE development set of models taken at various checkpoints along the pretraining of BERT Base sized models trained with different masking schemes. We finetuned on RACE with batch size of 32 and learning rate of $3 \cdot 1 0 ^ { - 5 }$ over 4 epochs without early stopping. We did this for 5 random initializations of the task’s head and the reported score is an average of the three middle scores.
# D GLUE TASKS AND DETAILED SCORES
The General Language Understanding Evaluation (GLUE) benchmark (Wang et al., 2019) consists of 9 sentence-level tasks. Sentence-level classification tasks: CoLA (Warstadt et al., 2018) (evaluating linguistic acceptability) and SST-2 (Socher et al., 2013) (sentiment classification). Sentencepair similarity tasks: MRPC (Dolan & Brockett, 2005) (binary paraphrasing classification task), STS-B (Cer et al., 2017): (graded similarity scoring task), and $\mathrm { \bar { Q } O P ^ { 2 } }$ (binary paraphrasing classification task). Natural language inference tasks: MNLI (Williams et al., 2018), QNLI (Rajpurkar et al., 2016), RTE (Dagan et al., 2005; Bar-Haim et al., 2006; Giampiccolo et al., 2007) and WNLI (Levesque et al., 2011). Table 8 shows the detailed per-task scores of our examined models.
Table 8: Results on the different tasks of the GLUE benchmark. For all tasks the scores reflect accuracy, except for STS-B (spearman score) and CoLA (Mathews Correlation). For results reported on the development set (1M training steps), the average score is simply the average of reported scores. For results reported on the test sets (2.4M training steps), the average score is the official GLUE leaderboard score. The official score includes averaging of F1 scores for QQP and MRPC, as well as the default majority submission score of 65.1 for WNLI.
<table><tr><td>GLUE</td><td>MNLI</td><td>QNLI</td><td>QQP</td><td>RTE</td><td>SST</td><td>MRPC</td><td>CoLA</td><td>STS</td><td>Avg</td></tr><tr><td colspan="10">1Mtraining steps on Wikipedia+BookCorpus; ondev</td></tr><tr><td>Random-Span Masking</td><td>84.0/-</td><td>91.4</td><td>90.8</td><td>69.0</td><td>92.8</td><td>88.5</td><td>58.5</td><td>88.9</td><td>83.0</td></tr><tr><td>Naive-PMI-Masking</td><td>85.1/-</td><td>91.9</td><td>91.0</td><td>74.0</td><td>93.3</td><td>88.2</td><td>60.3</td><td>89.3</td><td>84.1</td></tr><tr><td>PMI-Masking</td><td>85.2/-</td><td>91.8</td><td>91.0</td><td>72.2</td><td>92.7</td><td>89.7</td><td>60.6</td><td>89.3</td><td>84.1</td></tr><tr><td colspan="10">2.4M training steps on WIKIPEDIA+BoOKCORPUS; ( on</td></tr><tr><td>Random-Span Masking</td><td>85.7/84.7</td><td>92.9</td><td>89.4</td><td>test 69.8</td><td>93</td><td>85.4</td><td>56.5</td><td>86.6</td><td>79.7</td></tr><tr><td>Naive-PMI-Masking</td><td>85.5/85.3</td><td>92.2</td><td>89.2</td><td>68.9</td><td>93.6</td><td>85.4</td><td>59.4</td><td>87.3</td><td>80.0</td></tr><tr><td>PMI-Masking</td><td>85.3/85.0</td><td>92.0</td><td>89.2</td><td>69.0</td><td>94.0</td><td>85.6</td><td>61.8</td><td>86.8</td><td>80.3</td></tr><tr><td colspan="10">2.4M training steps on WIKIPEDIA+BOOKCORPUS+OPENWEBTEXT; on test</td></tr><tr><td>Random-Span Masking</td><td>86.3/85.1</td><td>92.2</td><td>89.4</td><td>71.1</td><td>94.6</td><td>85.6</td><td>56.8</td><td>87.2</td><td>80.1</td></tr><tr><td>Naive-PMI-Masking</td><td>86/85.4</td><td>91.7</td><td>89.4</td><td>69.2</td><td>95.1</td><td>87.8</td><td>57.5</td><td>87.9</td><td>80.3</td></tr><tr><td>PMI-Masking</td><td>86.6/85.8</td><td>93.1</td><td>89.5</td><td>72.9</td><td>94.7</td><td>87.7</td><td>57.4</td><td>87.7</td><td>80.8</td></tr></table>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324# ON THE QUANTITATIVE ANALYSIS OF DECODERBASED GENERATIVE MODELS
Yuri Burda OpenAI yburda@openai.com
Yuhuai Wu Department of Computer Science University of Toronto ywu@cs.toronto.edu
Ruslan Salakhutdinov School of Computer Science Carnegie Mellon University rsalakhu@cs.cmu.edu
Roger Grosse Department of Computer Science University of Toronto rgrosse@cs.toronto.edu
# ABSTRACT
The past several years have seen remarkable progress in generative models which produce convincing samples of images and other modalities. A shared component of many powerful generative models is a decoder network, a parametric deep neural net that defines a generative distribution. Examples include variational autoencoders, generative adversarial networks, and generative moment matching networks. Unfortunately, it can be difficult to quantify the performance of these models because of the intractability of log-likelihood estimation, and inspecting samples can be misleading. We propose to use Annealed Importance Sampling for evaluating log-likelihoods for decoder-based models and validate its accuracy using bidirectional Monte Carlo. The evaluation code is provided at https:// github.com/tonywu95/eval_gen. Using this technique, we analyze the performance of decoder-based models, the effectiveness of existing log-likelihood estimators, the degree of overfitting, and the degree to which these models miss important modes of the data distribution.
# 1 INTRODUCTION
In recent years, deep generative models have dramatically pushed forward the state-of-the-art in generative modelling by generating convincing samples of images (Radford et al., 2016), achieving state-of-the-art semi-supervised learning results (Salimans et al., 2016), and enabling automatic image manipulation (Zhu et al., 2016). Many of the most successful approaches are defined in terms of a process which samples latent variables from a simple fixed distribution (such as Gaussian or uniform) and then applies a learned deterministic mapping which we will refer to as a decoder network. Important examples include variational autoencoders (VAEs) (Kingma & Welling, 2014; Rezende et al., 2014), generative adversarial networks (GANs) (Goodfellow et al., 2014), generative moment matching networks (GMMNs) (Li & Swersky, 2015; Dziugaite et al., 2015), and nonlinear independent components estimation (Dinh et al., 2014). We refer to this set of models collectively as decoder-based models, also known as density networks (MacKay & Gibbs, 1998).
While many decoder-based models are able to produce convincing samples (Denton et al., 2015; Radford et al., 2016), rigorous evaluation remains a challenge. Comparing models by inspecting samples is labor-intensive, and potentially misleading (Theis et al., 2016). While alternative quantitative criteria have been proposed (Bounliphone et al., 2016; Im et al., 2016; Salimans et al., 2016), log-likelihood of held-out test data remains one of the most important measures of a generative model’s performance. Unfortunately, unless the decoder is designed to be reversible (Dinh et al., 2014; 2016), log-likelihood estimation in decoder-based models is typically intractable. In the case of VAE-based models, a learned encoder network gives a tractable lower bound, but for GANs and GMMNs it is not obvious how even to compute a good lower bound. Even when lower bounds are available, their accuracy may be hard to determine. Because of the difficulty of log-likelihood evaluation, it is hard to answer basic questions such as whether the networks are simply memorizing training examples, or whether they are missing important modes of the data distribution.
 Figure 1: (a) samples from a GAN with 10 latent dimensions, (b) and (c) samples from a GAN with 50 latent dimensions at different epochs of training. While it is difficult to visually discern differences between these three models, their log-likelihood (LLD) values span almost 300 nats.
The most widely used estimator of log-likelihood for GANs and GMMNs is the Kernel Density Estimator (KDE) (Parzen, 1962). It estimates the likelihood under an approximation to the model’s distribution obtained by simulating from the model and convolving the set of samples with a kernel (typically Gaussian). Unfortunately, KDE is notoriously inaccurate for estimating likelihood in high dimensions, because it is hard to tile a high-dimensional manifold with spherical Gaussians (Theis et al., 2016).
In this paper, we propose to use annealed importance sampling (AIS; (Neal, 2001)) to estimate log-likelihoods of decoder-based generative models and to obtain approximate posterior samples. Importantly, we validate this approach using Bidirectional Monte Carlo (BDMC) (Grosse et al., 2015), which provably bounds the log-likelihood estimation error and the KL divergence from the true posterior distribution for data simulated from a model. For most models we consider, we find that AIS is two orders of magnitude more accurate than KDE, and is accurate enough to perform fine-grained comparisons between generative models. In the case of VAEs, we show that AIS can be further sped up by using the recognition network to determine the initial distribution; this yields an estimator which is fast enough to be run repeatedly during training.
Using the proposed method, we analyze several scientific questions central to understanding decoderbased generative models. First, we measure the accuracy of KDE and of the importance weighting bound which is commonly used to evaluate VAEs. We find that the KDE error is larger than the (quite significant) log-likelihood differences between different models, and that KDE can lead to misleading conclusions. The importance weighted bound, while reasonably accurate, can also yield misleading results in some cases.
Second, we compare the log-likelihoods of VAEs, GANs, and GMMNs, and find that VAEs achieve log-likelihoods several hundred nats higher than the other models (even though KDE considers all three models to have roughly the same log-likelihood). Third, we analyze the degree of overfitting in VAEs, GANs, and GMMNs. Contrary to a commonly proposed hypothesis, we find that GANs and GMMNs are not simply memorizing their training data; in fact, their log-likelihood gaps between training and test data are much smaller relative to comparably-sized VAEs. Finally, by visualizing (approximate) posterior samples obtained from AIS, we observe that GANs miss important modes of the data distribution, even ones which are represented in the training data.
We emphasize that none of the above phenomena can be measured using KDE or the importance weighted bound, or by inspecting samples. (See Fig. 1 for an example where it is tricky to compare models based on samples.) While log-likelihood is by no means a perfect measure, we find that the ability to accurately estimate log-likelihoods of decoder-based models yields crucial insight into their behavior and suggests directions for improving them.
# 2 BACKGROUND
# 2.1 DECODER-BASED GENERATIVE MODELS
In generative modelling, a decoder network is often used to define a generative distribution by transforming samples from some simple distribution (e.g. normal) to the data manifold. In this
paper, we consider three kinds of decoder-based generative models: Variational Autoencoder (VAE) (Kingma & Welling, 2014), Generative Adversarial Network (GAN) (Goodfellow et al., 2014), and Generative Moment Matching Network (GMMN) (Li & Swersky, 2015; Dziugaite et al., 2015).
# 2.1.1 VARIATIONAL AUTOENCODER
A variational autoencoder (VAE) (Kingma & Welling, 2014) is a probabilistic directed graphical model. It is defined by a joint distribution over a set of latent random variables $z$ and the observed variables $x$ $: p ( x , z ) = p ( x | z ) p ( z )$ . The prior over the latent random variables, $p ( z )$ , is usually chosen to be a standard Gaussian distribution. The data likelihood $p ( x | z )$ is usually a Gaussian or Bernoulli distribution whose parameters depend on $z$ through a deep neural network, known as the decoder network. It also uses an approximate inference model called an encoder or recognition network, that serves as a variational approximation $q ( z | x )$ to the posterior $p ( z | x )$ . The decoder network and the encoder networks are jointly trained to maximize the evidence lower bound (ELBO):
$$\log p ( x ) \geq \mathbb { E } _ { q ( z | x ) } [ \log p ( x | z ) ] - K L ( q ( z | x ) | | p ( z ) )$$
In addition, the reparametrization trick is used to reduce the variance of the gradient estimate.
# 2.1.2 GENERATIVE ADVERSARIAL NETWORK (GAN)
A generative adversarial network (GAN) (Goodfellow et al., 2014) is a generative model trained by a game between a decoder network and a discriminator network. It defines the generative model by sampling the latent variable $z$ from some simple prior distribution $p ( z )$ (e.g., Gaussian) followed through the decoder network. The discriminator network $D ( \cdot )$ outputs a probability of a given sample coming from the data distribution. Its task is to distinguish samples from the generator distribution from real data. The decoder network, on the other hand, tries to produce samples as realistic as possible, in order to fool the discriminator into accepting its outputs as being real. The competition between the two networks results in the following minimax problem:
$$\operatorname* { m i n } _ { G } \operatorname* { m a x } _ { D } \mathbb { E } _ { x \sim p _ { d a t a } } [ \log D ( x ) ] + \mathbb { E } _ { z \sim p ( z ) } [ \log ( 1 - D ( G ( z ) ) ]$$
Unlike VAE, the objective is not explicitly related to the log-likelihood of the data. Moreover, the generative distribution is a deterministic mapping, i.e., $\bar { p } ( x | z )$ is a Dirac delta distribution, parametrized by the deterministic decoder. This can make data likelihood ill-defined, as the probability density of any particular point $x$ can be either infinite, or exactly zero.
# 2.1.3 GENERATIVE MOMENT MATCHING NETWORK (GMMN)
Generative moment matching networks (GMMNs) (Li & Swersky, 2015; Dziugaite et al., 2015) adopt maximum mean discrepancy (MMD) as the training objective, a moment matching criterion where kernel mean embedding techniques are used to avoid unnecessary assumptions of the distributions. It has the same issue as GAN in that the log-likelihood is undefined.
# 2.2 ANNEALED IMPORTANCE SAMPLING
We are interested in estimating the probability $\begin{array} { r } { p ( x ) = \int p ( z ) p ( x | z ) \mathrm { d } z } \end{array}$ a model assigns to an observation $x$ . This is equivalent to computing the normalizing constant of the unnormalized distribution $f ( z ) ~ = ~ p ( z , { \bar { x } } )$ . One naïve approach is likelihood weighting, where one samples $\{ z ^ { ( k ) } \} _ { k = 1 } ^ { K } \sim p ( z )$ and averages the conditional likelihoods $p ( x | z ^ { ( k ) } )$ . This is justified by the following identity:
$$p ( x ) = \int \frac { p ( x , z ) } { p ( z ) } p ( z ) \mathrm { d } z = \mathbb { E } _ { z \sim p ( z ) } [ p ( x | z ) ]$$
Likelihood weighting can be viewed as simple importance sampling, where the proposal distribution is the prior $p ( z )$ and the target distribution is the posterior $p ( z | x )$ . Unfortunately, importance sampling works well only when the proposal distribution is a good match for the target distribution. For the models considered in this paper, the (very broad) prior can be drastically different than the (highly concentrated) posterior, leading to inaccurate estimates of the likelihood.
Annealed importance sampling (AIS; Neal, 2001) is a Monte Carlo algorithm commonly used to estimate (ratios of) normalizing constants. Roughly speaking, it computes a sequence of importance sampling based estimates, each of which is stable because it involves two distributions which are very similar. In particular, suppose one is interested in estimating the normalizing constant $\begin{array} { r } { \mathcal { Z } = \int f ( \boldsymbol { z } ) \mathrm { d } \dot { \boldsymbol { z } } } \end{array}$ of an unnormalized distribution $f ( z )$ . (In the likelihood estimation setting, $f ( z ) = p ( z , x )$ and ${ \mathcal { Z } } = p ( x )$ .) One must specify a sequence of distributions $q _ { 1 } , . . . , q _ { T }$ , where $q _ { t } = f _ { t } / Z _ { t }$ , and $f _ { T } = f$ is the target distribution. It is required that one can obtain one or more exact samples from the initial distribution $q _ { 1 }$ . One must also specify a sequence of reversible MCMC transition operators $\mathcal { T } _ { 1 } , . . . , \mathcal { T } _ { T }$ , where $\mathcal { T } _ { t }$ leaves $q _ { t }$ invariant.
AIS produces a (nonnegative) unbiased estimate of the ratio $\mathcal { Z } _ { T } / \mathcal { Z } _ { 1 }$ as follows: first, we sample a random initial state $z _ { 1 } \sim q _ { 1 }$ and set the initial weight $w _ { 1 } = 1$ . For every stage $t \geq 2$ we update the weight $w$ and sample the state $z _ { t }$ according to
$$w _ { t } w _ { t - 1 } \frac { f _ { t } ( z _ { t - 1 } ) } { f _ { t - 1 } ( z _ { t - 1 } ) } \qquad z _ { t } \sim \mathcal { T } _ { t } ( z | z _ { t - 1 } )$$
As demonstrated by Neal (2001), this procedure produces a nonnegative weight $w _ { T }$ such that $\mathbb { E } [ w _ { T } ] = \mathcal { Z } _ { T } / \mathcal { Z } _ { 1 }$ . Typically, btains the un $\mathcal { Z } _ { 1 }$ is known,ed estimate le independent AIS weights. In the likelihood estimation $\{ w _ { T } ^ { ( K ) } \} _ { k = 1 } ^ { K }$ $\begin{array} { r } { \hat { \mathcal { Z } } _ { T } = \mathcal { Z } _ { 1 } \frac { 1 } { K } \sum _ { k = 1 } ^ { K } w _ { T } ^ { ( K ) } } \end{array}$ setting, $\mathcal { Z } _ { 1 } = 1$ and , so we denote this estimator as ${ \hat { p } } ( x )$ .
Typically, the unnormalized intermediate distributions are simply defined to be geometric averages $\dot { f _ { t } ( z ) } = \dot { \sp { \prime } } f _ { 1 } ( z ) \sp { 1 - \beta _ { t } } f _ { T } ( z ) \sp { \beta _ { t } }$ , where the $\beta _ { t }$ are monotonically increasing parameters with $\beta _ { 1 } = 0$ and $\beta _ { T } = 1$ . For $f _ { 1 } ( z ) = p ( z )$ and $f _ { T } ( z ) = p ( z , x )$ , this gives
$$f _ { t } ( z ) = p ( z ) p ( x | z ) ^ { \beta _ { t } } .$$
As shown by Neal (2001), under certain regularity conditions, the variance of $\hat { \mathcal { Z } } _ { T }$ tends to zero as the number of intermediate distributions is increased. AIS is very effective in practice, and has been used to estimate normalizing constants of complex high-dimensional distributions (Salakhutdinov $\&$ Murray, 2008).
# 2.3 BIDIRECTIONAL MONTE CARLO
AIS provides a nonnegative unbiased estimate ${ \hat { p } } ( x )$ of $p ( x )$ . However, it is often more practical to estimate $p ( x )$ in the log space, i.e. $\log p ( x )$ , because of underflow problem of dealing with many products of probability measure. In general, we note that logarithm of a nonnegative unbiased estimate is a stochastic lower bound of the log estimand (Grosse et al., 2015). In particular, $\log { \hat { p } } ( x )$ is a stochastic lower bound on $\log p ( x )$ , satisfying $\mathbb { E } [ \log { \hat { p } ( x ) } ] \leq \log p ( x )$ and $\operatorname* { P r } ( \log { \hat { p } } ( x ) > \log p ( x ) +$ $b ) < e ^ { - b }$ .
Grosse et al. (2015) pointed out that if AIS is run in reverse starting from an exact posterior sample, it yields an unbiased estimate of $1 / p ( x )$ , which (by the above argument) can be seen as a stochastic upper bound on $\log p ( x )$ . The combination of lower and upper bounds from forward and reverse AIS is known as bidirectional Monte Carlo (BDMC). In many cases, the combination of bounds can pinpoint the true value quite precisely. While posterior sampling is just as hard as log-likelihood estimation (Jerrum et al., 1986), in the case of log-likelihood estimation for simulated data, one has available a single exact posterior sample: the parameters and/or latent variables which generated the data. Because this trick is only applicable to simulated data, BDMC is most useful for measuring the accuracy of a log-likelihood estimator on simulated data.
Grosse et al. (2016) observed that BDMC can also be used to validate posterior inference algorithms, as the gap between upper and lower bounds is itself a bound on the KL divergence of approximate samples from the true posterior distribution.
# 3 METHODOLOGY
For a given generative distribution $p ( x , z ) = p ( z ) p ( x | z )$ , our task is to measure the log-likelihood of test examples $\log p ( x _ { t e s t } )$ . We first discuss how we define the generative distribution for decoderbased networks. For VAE, the generative distribution is defined in the standard way, where $p ( z )$ is a standard normal distribution and $p ( x | z )$ is a normal distribution parametrized by mean $\mu _ { \boldsymbol { \theta } } ( z )$ and $\sigma _ { \theta } ( z )$ , predicted by the generator given the latent code. However, the observation distribution for GANs and GMMNs is typically taken to be a delta function, so that the model’s distribution covers only a submanifold of the space of observables. In order for the likelihood to be well-defined, we follow the same assumption made when evaluating using Kernel Density Estimator (Parzen, 1962): we assume a Gaussian observation model with a fixed variance hyperparameter $\sigma ^ { 2 }$ . We will refer to the distribution defined by this Gaussian observation model as $p _ { \sigma }$ .
Observe that the KDE estimate is given by
$$\hat { p } _ { \sigma } ( x ) = \frac { 1 } { K } \sum _ { k = 1 } ^ { K } p _ { \sigma } ( x | z ^ { ( k ) } ) ,$$
wher e {z(k)}K are samples from the prior $p ( z )$ . This is equivalent to likelihood weighting for the distribution $p _ { \sigma }$ , which is an instance of simple importance sampling (SIS). Because SIS is an unbiased estimator of the likelihood, $\log \hat { p } _ { \sigma } ( x )$ is a stochastic lower bound on $\log p _ { \sigma } ( x )$ (Grosse et al., 2015). Unfortunately, SIS can result in very poor estimates when the evidence has low prior probability (i.e. the posterior is very dissimilar to the prior). This suggests that AIS might be able to yield much more accurate log-likelihood estimates under $p _ { \sigma }$ . We note that KDE can be viewed as a special case of AIS where the number of intermediate distributions is set to 0.
We now describe specifically how we carry out evaluation using AIS. In most of our experiments, we choose the initial distribution of AIS to be $p ( z )$ , the same prior distribution used in training decoderbased models. If the model provides an encoder network (e.g., VAE), we can take the approximated distribution predicted by the encoder $q ( z | x )$ as the initial distribution of the AIS chain. For continuous data, we define the unnormalized density of target distribution to be the joint generative distribution with the Gaussian noise model, $p _ { \sigma } ( x , z ) = p _ { \sigma } ( x | z ) p ( z )$ . For the small subset of experiments done on the binary data, we define the observation model to be a Bernoulli model with mean predicted by the decoder. Our intermediate distributions are geometric averages of the prior and posterior, as in Eqn. 5. Since all of our experiments are done using continuous latent space, we use Hamiltonian Monte Carlo (Neal, 2010) as the transition operator for sampling latent samples along annealing. The evaluation code is provided at https://github.com/tonywu95/eval_gen.
# 4 RELATED WORK
AIS is known to be a powerful technique of estimating the partition function of the model. One influential example was the use of AIS to evaluate deep belief networks (Salakhutdinov & Murray, 2008). Although we used the same technique, the problem we consider is completely different. First of all, the model they consider is undirected graphical models, whereas decoder-based models are directed graphical models. Secondly, their model has a well-defined probabilistic density function in terms of energy function, whereas we need to consider different probabilistic model for one in which the the likelihood is ill-defined. In addition, we validate our estimates using BDMC.
Theis et al. (2016) give an in-depth analysis of issues that might come up in evaluating generative models. They also point out that a model that completely fails at modelling the proportion of modes of the distribution might still achieve a high likelihood score. Salimans et al. (2016) propose an image-quality measure which they find to be highly correlated with human visual judgement. They propose to feed the samples $x$ of the model to the “inception” model to obtain a conditional label distribution $p ( y | x )$ , and evaluate the score defined by exp $\mathbb { E } _ { x } \mathrm { K L } ( p ( y | x ) | | p ( y ) )$ , which is motivated by having a low entropy of $p ( y | x )$ but a large entropy of $p ( y )$ . However, the measure is largely based on visual quality of the sample, and we argue that the visual quality can be a misleading way to evaluate a model.
# 5 EXPERIMENTS
# 5.1 DATASETS
All of our experiments were performed on the MNIST dataset of images of handwritten digits (LeCun et al., 1998). For consistency with prior work on evaluating decoder-based models, most of our experiments used the continuous inputs. We dequantized the data following Uria et al. (2013), by adding a uniform noise of $\scriptstyle { \frac { 1 } { 2 5 6 } }$ to the data and rescaling it to be in $[ 0 , 1 ] ^ { D }$ after dequantization. We use the standard split of MNIST into 60,000 training and 10,000 test examples, and used 50,000 images from the training set for training, and remaining 10,000 images for validation. In addition, some of our experiments used the binarized MNIST dataset with a Bernoulli observation model (Salakhutdinov & Murray, 2008).
# 5.2 MODELS
For most of our experiments, we considered two decoder architectures: a small one with 10 latent dimensions, and a larger one with 50 latent dimensions. We use standard Normal distribution as prior for training all of our models. All layers were fully connected, and the number of units in each layer was 10–64–256–256-1024–784 for the smaller architecture and 50–1024–1024–1024–784 for the larger one. We trained both architectures using the VAE, GAN, and GMMN objectives, resulting in six networks which we refer to as VAE-10, VAE-50, etc. In general, the larger architecture performed substantially better on both the training and test sets, but we analyze the smaller architecture as well because it better highlights some of the differences between the training criteria. Additional architectural details are given in Appendix A.1.
In order to enable a direct comparison between training criteria, all models used a spherical Gaussian observation model with fixed variance. This is consistent with previous protocols for evaluating GANs and GMMNs. However, we note that this observation model is a nontrivial constraint on the VAEs, which could instead be trained with a more flexible diagonal Gaussian observation model where the variances depend on the latent state. Such observation models can easily achieve much higher log-likelihood scores, for instance by noticing that boundary pixels are always close to 0. (E.g., we trained a VAE with the more general observation model which achieved a log-likelihood of at least 2200 nats on continuous MNIST.) Therefore, the log-likelihood values we report should not be compared directly against networks which have a more flexible observation model.
# 5.3 VALIDATION OF LOG-LIKELIHOOD ESTIMATES
Before we analyze the performance of the trained networks, we must first determine the accuracy of the log-likelihood estimators. In this section, we validate the accuracy of our AIS-based estimates using BDMC. We then analyze the error in the KDE and IWAE estimates and highlight some cases where these measures miss important phenomena.
# 5.3.1 VALIDATION OF AIS
We used AIS to estimate log-likelihoods for all models under consideration. Except where otherwise specified, all AIS estimates were obtained using 16 independent chains, 10,000 intermediate distributions of the form in Eqn. 5, and a transition operator consisting of one proposed HMC trajectory with 10 leapfrog steps.1 Following Ranzato et al. (2010), the HMC stepsize was tuned to achieve an acceptance rate of 0.65 (as recommended by Neal (2010)).
For all six models, we evaluated the accuracy of this estimation procedure using BDMC on data sampled from the model’s distribution on 1000 simulated examples. The gap between the loglikelihood estimates produced by forward AIS (which gives a lower bound) and reverse AIS (which gives an upper bound) bounds the error of the AIS estimates on simulated data. We refer to this gap as the BDMC gap. For five of the six networks under consideration, we found the BDMC gap to be less than 1 nat. For the remaining model (GAN-50), the gap was about 10 nats. Both gaps are much smaller than our measured log-likelihood differences between models. If these gaps are representative of the true error in the estimates on the real data, then this indicates AIS is accurate enough to make fine-grained comparisons between models and to benchmark other log-likelihood estimators. (The BDMC gap is not guaranteed to hold for the real data, although Grosse et al. (2016) found the behavior of AIS to match closely between real and simulated data.)
# 5.3.2 HOW ACCURATE IS KERNEL DENSITY ESTIMATION?
Kernel density estimation (KDE) (Parzen, 1962) is widely used to evaluate decoder-based models (Goodfellow et al., 2014; Li & Swersky, 2015), and a variant was proposed in the setting of evaluating Boltzmann machines (Bengio et al., 2013). Papers reporting KDE estimates often caution that the

Figure 2: (a) Log-likelihood of GAN-50, under different choices of variance parameter. (b) Log-likelihood of GMMN-10 on 100 simulated examples evaluated by AIS and KDE vs. the corresponding running time. We show the BDMC gap converges to almost zero as we increase the running time. (c) Log-likelihood of IWAE on 10,000 test examples evaluated by AIS and IWAE bound vs. running time. (a), (b) are results on continuous MNIST, and (c) is on binarized MNIST. Note that AIS/AIS $^ +$ encoder dominates the other estimate in both estimation accuracy and running time Table 1: AIS vs. IWAE bound on 10,000 test examples of binarized MNIST. “# dist” denotes the number of intermediate distributions used for evalution. We find AIS estimate is consistently 1 nat higher than IWAE bound; AIS+encoder can achieve about the same estimate as AIS, but with 1 order of magnitude less number of intermediate distributions.
<table><tr><td rowspan=2 colspan=2>(Nats)IWAE</td><td rowspan=1 colspan=1>AIS</td><td rowspan=1 colspan=1>AIS+encoder</td><td rowspan=1 colspan=1>IWAE bound</td><td rowspan=1 colspan=1># dist AIS</td><td rowspan=1 colspan=1># dist AIS+encoder</td><td rowspan=1 colspan=1># samples</td></tr><tr><td rowspan=1 colspan=1>IWAE</td><td rowspan=1 colspan=1>-85.679-85.619</td><td rowspan=1 colspan=1>-85.754-85.621</td><td rowspan=1 colspan=1>-86.902-86.464</td><td rowspan=1 colspan=1>100010000</td><td rowspan=1 colspan=1>1001000</td><td rowspan=1 colspan=1>10000100000</td></tr></table>
KDE is not meant to be applied in high-dimensional spaces and that the results might therefore be inaccurate. Nevertheless, KDE remains the standard protocol for evaluating decoder-based models. We analyzed the accuracy of the KDE estimates by comparing against AIS. Both estimates are stochastic lower bounds on the true log-likelihood (see Section 3), so larger values are guaranteed (with high probability) to be more accurate.
For each estimator, we varied one parameter influencing the computational budget; for AIS, this was the number of intermediate distributions (chosen from $\{ 1 0 0 , 5 \bar { 0 } 0 , 1 0 0 0 , 2 0 0 0 , \bar { 1 } 0 0 0 0 \} )$ , and for KDE, it was the number of samples (chosen from $\{ 1 0 0 0 0 , 1 0 0 0 0 0 , 5 0 0 0 0 0 , 1 0 0 0 0 0 0 , 2 0 0 0 0 0 \} )$ . Using GMMN-10 for illustration, we plot both log-likelihood estimates 100 simulated examples as a function of evaluation time in Fig. 2(b). We also plot the upper bound of likelihood given by running AIS in reverse direction. We see that the BDMC gap approaches to zero, validating the accuracy of AIS. We also see that the AIS estimator achieves much more accurate estimates during similar evaluation time. Furthermore, the KDE estimates appear to level off, suggesting one cannot obtain accurate results even using orders of magnitude more samples.
The KDE estimation error also impacts the estimate of the observation noise $\sigma$ , since a large value of $\sigma$ is needed for the samples to cover the full distribution. We compared the log-likelihoods estimated by AIS and KDE with varying choices of $\sigma$ on 100 training and validation examples of MNIST. We used 1 million simulated samples for KDE evaluation, which takes almost the same time as running AIS estimation. In Fig. 2(a), we show the log-likelihood of GAN-50 estimated by KDE and AIS as a function of $\sigma$ . Because the accuracy of KDE declines sharply for small $\sigma$ values, it creates a strong bias towards large $\sigma$ .
# 5.3.3 HOW ACCURATE IS THE IWAE BOUND?
In principle, one could estimate VAE likelihoods using the VAE objective function (which is a lower bound on the true log-likelihood). However, it is more common to use importance weighting, where the proposal distribution is computed by the recognition network. This is provably more accurate than the VAE bound (Burda et al., 2016). Because the importance weighted estimate corresponds to the objective function used by the Importance Weighted Autoencoder (IWAE) (Burda et al., 2016), we will refer to it as the IWAE bound.
On continuous MNIST, the IWAE bound underestimated the true log-likelihoods by at least 33.2 nats on the training set and 187.4 nats on the test set. While this is considerably more accurate than KDE, the error is still significant. Interestingly, this result also suggests that the recognition network overfits the training data.
<table><tr><td>(Nats)</td><td>AIS Test</td><td>AISTrain</td><td>BDMC gap</td><td>KDE Test</td><td>IWAE Test</td></tr><tr><td>VAE-50</td><td>991.435±6.477</td><td>1298.830±0.863</td><td>1.540</td><td>351.213</td><td>826.325</td></tr><tr><td>GAN-50</td><td>627.297±8.813</td><td>648.283±21.115</td><td>10.045</td><td>300.331</td><td>/</td></tr><tr><td>GMMN-50</td><td>593.472±8.591</td><td>607.272±1.451</td><td>1.146</td><td>277.193</td><td>/</td></tr><tr><td>VAE-10</td><td>705.375±7.411</td><td>791.029±0.810</td><td>0.832</td><td>408.659</td><td>486.466</td></tr><tr><td>GAN-10</td><td>328.772±5.538</td><td>346.640±4.260</td><td>0.934</td><td>259.673</td><td>/</td></tr><tr><td>GMMN-10</td><td>346.679±5.860</td><td>358.943±6.485</td><td>0.605</td><td>262.73</td><td>/</td></tr></table>
Table 2: Model comparisons on 1000 test and training examples of continuous MNIST. Confidence intervals reflect the variability from the choice of training or test examples (which appears to be the dominant source of error for the AIS values). AIS, KDE, and IWAE are all stochastic lower bounds on the log-likelihood.
Since VAE and IWAE results have customarily been reported on binarized MNIST, we additionally trained an IWAE in this setting. The training details are given in Appendix A.2. To show the practicality of our method, we evaluated the IWAE on the full 10000 test using AIS and IWAE bound, with different choices of intermediate distribution and number of simulated samples, shown in Table 1. We also evaluate AIS with the initial distribution defined by encoders of VAEs, denoted as AIS+encoder. We find that the IWAE bound underestimates the true value by at least 1 nat, which is a large difference by the standards of binarized MNIST. (E.g., it represents about half of the gap between a state-of-the-art permutation-invariant model (Tran et al., 2016) and one which exploits structure (van den Oord et al., 2016).) The AIS and IWAE estimates are compared in terms of evaluation time in Fig. 2 (c).
# 5.4 SCIENTIFIC FINDINGS
Having validated the accuracy of AIS, we now use it to analyze the effectiveness of various training criteria. We also highlight phenomena which would not be observable using existing log-likelihood estimators or by inspecting samples. For all experiments in this section, we used 10,000 intermediate distributions for AIS, 1 million simulated samples for KDE, and 200,000 importance samples for the IWAE bound. (These settings resulted in similar computation time for all three estimators.)
# 5.4.1 MODEL LIKELIHOOD COMPARISON
We evaluated the trained models using AIS and KDE on 1000 test examples of MNIST; results are shown in Table 2. We find that for all three training criteria, the larger architectures consistently outperformed the smaller ones. We also find that for both the 10- and 50-dimensional architectures, the VAEs achieved substantially higher log-likelihoods than GANs or GMMNs. It is not surprising that the VAEs achieved higher likelihood, because they were trained using a likelihood-based objective while the GANs and GMMNs were not. However, it is interesting that the difference in log-likelihoods was so large; in the rest of this section, we attempt to analyze what exactly is causing this large difference.
We note that the KDE errors were of the same order of magnitude as the differences between models, indicating that it cannot be used reliably to compare log-likelihoods. Furthermore, KDE did not identify the correct ordering of models; for instance, it estimated a lower log-likelihood for VAE50 than for VAE-10, even though its true log-likelihood was almost 300 nats higher. KDE also underestimated by an order of magnitude the log-likelihood improvements that resulted from using the larger architectures. (E.g., it estimated a 15 nat difference between GMMN-10 and GMMN-50, even though the true difference was 247 nats as estimated by AIS.)
These differences are also hard to observe simply by looking at samples; for instance, we were unable to visually distinguish the quality of samples for GAN-10 and GAN-50 (see Fig. 1), even though their log-likelihoods differed by almost 300 nats on both the training and test sets.
# 5.4.2 MEASURING THE DEGREE OF OVERFITTING
One question that arises in evaluation of decoder-based generative models is whether they memorize parts of the training dataset. One cannot test this by looking only at model samples. The commonly reported nearest-neighbors from the training set can be misleading (Theis et al., 2016), and interpolation in the latent space between different samples can be visually appealing, but does not provide a quantitative measure of the degree of generalization.
 Figure 3: Training curves for (a) GAN-50, (b) VAE-50, and (c) GMMN-10, as measured by AIS, KDE, and (if applicable) the IWAE lower bound. All estimates shown here are lower bounds. In (c), the gap between training and validation log-likelihoods is not fairly small (see Table 2).
To analyze the degree of overfitting, Fig. 3 shows training curves for three networks as measured by AIS, KDE, and the IWAE bound. We observe that GAN-50’s training and test log-likelihoods are nearly identical throughout training, disconfirming the hypothesis that it was memorizing training data. Both GAN-50 and GMMN-50 overfit less than VAE-50.
We also observed two phenomena which could not be measured using existing techniques. First, in the case of VAE-50, the IWAE lower bound starts to decline after 200 epochs, while the AIS estimates hold steady, suggesting it is the recognition network rather than the generative network which is overfitting most. Second, the GMMN-50 training and validation error continue to improve at 10,000 epochs, even though KDE erroneously indicates that performance has leveled off.
# 5.4.3 HOW APPROPRIATE IS THE OBSERVATION MODEL?
Appendix B addresses the questions of whether the spherical Gaussian observation model is a good fit and whether the log-likelihood differences could be an artifact of the observation model. We find that all of the models can be substantially improved by accounting for non-Gaussianity, but that this effect is insufficient to explain the gap between the VAEs and the other models.
# 5.4.4 ARE THE NETWORKS MISSING MODES?
It was previously observed that one of the potential failure modes of Boltzmann machines is to fail to generate one or more modes of a distribution or to drastically misallocate probability mass between modes (Salakhutdinov & Murray, 2008). Here we analyze this for decoder-based models.
First, we ask a coarse-grained version of this question: do the networks allocate probability mass correctly between the 10 digit classes, and if not, can this explain the difference in log-likelihood scores? In Fig. 1, we see that GAN-50’s distribution of digit classes was heavily skewed: out of 100 samples, it generated 37 images of 1’s, but only a single 2. This appears to be a large effect, but it does not explain the magnitude of the log-likelihood difference from VAEs. In particular, if the allocation of digit classes were off by a factor of 10, this effect by itself could cost at most l $\mathrm { 9 g 1 0 \approx 2 . 3 }$ nats of log-likelihood. Since VAE-50 outperformed GAN-50 by 364 nats, this effect cannot explain the difference.
However, MNIST has many factors of variability beyond simply the 10 digit classes. In order to determine whether any of the models missed more fine-grained modes, we visualized posterior samples for each model conditioned on training and test images. In particular, for each image $x$ under consideration, we used AIS to approximately sample $z$ from the posterior distribution $p ( \bar { z } | x )$ , and then ran the decoder on $z$ . While these samples are approximate, Grosse et al. (2016) point out that the BDMC gap also bounds the KL divergence of approximate samples from the true posterior. With the exception of GAN-50, our BDMC gaps were on the order of 1 nat, suggesting our approximate posterior samples are fairly representative. The results are shown in Fig. 4. Further posterior visualizations for digit class 2 (the most difficult for the models we considered) are shown in Appendix C.
Both VAEs’ posterior samples match the observations almost perfectly. (We observed a few poorly reconstructed examples on the test set, but not on the training set.) The GANs and GMMNs fail to reconstruct some of the examples on both the training and validation sets, suggesting that they failed to learn some modes of the distribution.
 Figure 4: (a) and (b) show visualization of posterior samples of 10 training/validation examples. (c) shows visualization of posterior samples of 10 training examples of digit “2". Each column of 10 digits comes from true data and the six models. The order of visualization is: True data, GAN-10, VAE-10, GMMN-10, GAN-50, VAE-50, GMMN-50.
# ACKNOWLEDGMENTS
We like to thank Yujia Li for providing his original GMMN model and codebase, and thank Jimmy Ba for advice on training GANs. Ruslan Salakhutdinov is supported in part by Disney and ONR grant N000141310721. We also thank the developers of Lasagne (Battenberg et al., 2014) and Theano (Al-Rfou et al., 2016).
# REFERENCES
Rami Al-Rfou, Guillaume Alain, Amjad Almahairi, and et al. Theano: A python framework for fast computation of mathematical expressions, 2016.
Eric Battenberg, Sander Dieleman, Daniel Nouri, Eben Olson, Aäron van den Oord, Colin Raffel, Jan Schlüter, and Søren Kaae Sønderby. lasagne. https://github.com/Lasagne/Lasagne, 2014.
Y. Bengio, L. Yao, and K. Cho. Bounding the test log-likelihood of generative models. arXiv:1311.6184, 2013.
Wacha Bounliphone, Eugene Belilovsky, Matthew B. Blaschko, Ioannis Antonoglou, and Arthur Gretton. A test of relative similarity for model selection in generative models. In ICLR. 2016.
Yuri Burda, Roger Grosse, and Ruslan Salakhutdinov. Importance weighted autoencoders. In ICLR, 2016.
E. Denton, S. Chintala, A. Szlam, and R. Fergus. Deep generative image models using a laplacian pyramid of adversarial networks. In NIPS, 2015.
Laurent Dinh, David Krueger, and Yoshua Bengio. Nice: Non-linear independent components estimation. arXiv preprint arXiv:1410.8516, 2014.
Laurent Dinh, Jascha Sohl-Dickstein, and Samy Bengio. Density estimation using real nvp. arXiv:1605.08803, 2016.
Gintare Karolina Dziugaite, Daniel M. Roy, and Zoubin Ghahramani. Training generative neural networks via Maximum Mean Discrepancy optimization. In UAI. 2015.
Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, and Yoshua Bengio. Generative adversarial nets. In Z. Ghahramani, M. Welling, C. Cortes, N. D. Lawrence, and K. Q. Weinberger (eds.), Advances in Neural Information Processing Systems 27, pp. 2672–2680. Curran Associates, Inc., 2014. URL http://papers.nips. cc/paper/5423-generative-adversarial-nets.pdf.
Roger Grosse, Siddharth Ancha, and Daniel M. Roy. Measuring the reliability of MCMC inference with bidirectional Monte Carlo. In NIPS, 2016.
Roger B. Grosse, Zoubin Ghahramani, and Ryan P. Adams. Sandwiching the marginal likelihood using bidirectional monte carlo. arXiv preprint arXiv:1511.02543, 2015.
Daniel Jiwoong Im, Chris Dongjoo Kim, Hui Jiang, and Roland Memisevic. Generating images with recurrent adversarial networks. arXiv preprint arXiv:1602.05110, 2016.
Mark R. Jerrum, Leslie G. Valiant, and Vijay V. Vazirani. Random generation of combinatorial structures from a uniform distribution. Theoretical Computer Science, 43:169–188, 1986.
Diederik P. Kingma and Max Welling. Auto-encoding variational bayes. In ICLR, 2014.
Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11):2278–2324, November 1998.
Yujia Li and Kevin Swersky. Generative moment matching networks. In In ICML 32, 2015.
D. J. C. MacKay and M. N. Gibbs. Density networks. In J. W. Kay and D. M. Titterington (eds.), Statistics and Neural Networks, pp. 129–146. O.U.P., 1998.
Radford M. Neal. Annealed importance sampling. Statistics and Computing, 11(2):125–139, April 2001. ISSN 0960-3174. doi: 10.1023/A:1008923215028. URL http://dx.doi.org/10. 1023/A:1008923215028.
Radford M. Neal. MCMC using Hamiltonian dynamics. Handbook of Markov Chain Monte Carlo, 54:113–162, 2010.
Emanuel Parzen. On estimation of a probability density function and mode. The Annals of Mathematical Statistics, 33(3):pp. 1065–1076, 1962. ISSN 00034851. URL http://www.jstor. org/stable/2237880.
Alec Radford, Luke Metz, and Soumith Chintala. Unsupervised representation learning with deep convolutional generative adversarial networks. In ICLR, 2016.
Marc’Aurelio Ranzato, Alex Krizhevsky, and Geoffrey E Hinton. Factored 3-way restricted Boltzmann machines for modeling natural images. In International Conference on Artificial Intelligence and Statistics (AISTATS), pp. 621–628, 2010.
Danilo J. Rezende, Shakir Mohamed, and Daan Wierstra. Stochastic backpropagation and approximate inference in deep generative models. In Tony Jebara and Eric P. Xing (eds.), Proceedings of the 31st International Conference on Machine Learning (ICML-14), pp. 1278–1286. JMLR Workshop and Conference Proceedings, 2014. URL http://jmlr.org/proceedings/ papers/v32/rezende14.pdf.
Ruslan Salakhutdinov and Iain Murray. On the quantitative analysis of Deep Belief Networks. In Andrew McCallum and Sam Roweis (eds.), Proceedings of the 25th Annual International Conference on Machine Learning (ICML 2008), pp. 872–879. Omnipress, 2008.
Tim Salimans, Ian Goodfellow, Wojciech Zaremba, Vicki Cheung, Alec Radford, and Xi Chen. Improved techniques for training gans. In NIPS, 2016.
Lucas Theis, Aäron van den Oord, and Matthias Bethge. A note on the evaluation of generative models. In ICLR, 2016.
Dustin Tran, Rajesh Ranganath, and David M. Blei. The variational Gaussian process. In ICLR, 2016.
Benigno Uria, Iain Murray, and Hugo Larochelle. RNADE: The real-valued neural autoregressive density-estimator. In Advances in Neural Information Processing Systems 26, pp. 2175–2183. 2013. URL http://www.benignouria.com/en/research/papers/Uria2013.pdf.
Aäron van den Oord, Nal Kalchbrenner, and Koray Kavukcuoglu. Pixel recurrent neural networks. In ICML, 2016.
Martin J. Wainwright and Eero P. Simoncelli. Scale mixtures of Gaussians and the statistics of natural images. In NIPS, 1999.
Jun-Yan Zhu, Philipp Krähenbühl, Eli Shechtman, and Alexei A. Efros. Generative visual manipulation on the natural image manifold. In Proceedings of European Conference on Computer Vision (ECCV), 2016.
# A NETWORK ARCHITECTURES/TRAINING
# A.1 MODELS ON CONTINUOUS MNIST
The decoders have all fully connected layers, and the number of units in each layer was 10–64–256– 256-1024–784 for the smaller architecture and 50–1024–1024–1024–784 for the larger one. Other architecture details are summarized as follows.
• For GAN-10, we used a discriminator with the architecture 784-512-256-1, where each layer used dropout with parameter 0.5. For GAN-50, we used a discriminator with architecture 784-4096-4096-4096-4096-1. All hidden layers used dropout with parameter 0.8. All hidden layers in both networks used the tanh activation function, and the output layers used the logistic function. The larger model uses an encoder of an architecture 784-1024-1024-1024-100. We add dropout layer between each hidden layer, with a dropout rate of 0.2. The smaller model uses an encoder of an architecture 784-256-64-20. Generator’s hidden layers use tanh activation function, and the output layer uses sigmoid unit. Encoder’s hidden layers use tanh activation function, and the output layer uses linear activation. • GMMN: The hidden layers use ReLU activation function, and the output layer uses sigomid unit.
For training GAN/VAE, we use our own implementation. We use Adam for optimization, and perform grid search of learning rate from $\{ 0 . 0 0 1 , 0 . 0 0 0 1 , 0 . 0 0 0 0 1 \}$ . For training GMMN, we take the implementation from https://github.com/yujiali/gmmn.git. Following the implementation, we use SGD with momentum for optimization, and perform grid search of learning rate from $\lbrace 0 . 1 , 0 . 5 , 1 , 2 \rbrace$ , with momentum 0.9.
# A.2 MODELS ON BINARIZED MNIST
Its decoder has the architecture 50-200-200-784 with all tanh hidden layers and sigmoid output layer, and its encoder is symmetric in architecture, with linear output layer. We take the implementation at https://github.com/yburda/iwae.git for training the IWAE model.The IWAE bound was computed with 50 samples during training. We keep all the hyperparameter choices the same as in the implementation.
B HOW PROBLEMATIC IS THE GAUSSIAN OBSERVATION MODEL? Table 3: Optimal variance vs. Fixed variance
<table><tr><td>(Nats)</td><td colspan="3">Train</td><td colspan="3">Valid</td></tr><tr><td></td><td>Optimal</td><td>Fixed</td><td>Improvement</td><td>Optimal</td><td>Fixed</td><td>Improvement</td></tr><tr><td>GAN-50</td><td>711.405</td><td>620.498</td><td>90.907</td><td>702.699</td><td>623.492</td><td>79.207</td></tr><tr><td>GMMN-50</td><td>655.807</td><td>571.803</td><td>84.004</td><td>661.652</td><td>594.612</td><td>67.040</td></tr><tr><td>GAN-10</td><td>376.788</td><td>318.948</td><td>57.840</td><td>368.585</td><td>316.614</td><td>51.971</td></tr><tr><td>GMMN-10</td><td>393.976</td><td>345.177</td><td>48.799</td><td>371.325</td><td>332.360</td><td>38.965</td></tr></table>
In this section, we consider whether the difference in log-likelihood between models could be an artifact of the Gaussian noise model (which we know to be a poor fit). In principle, the Gaussian noise assumption could be unfair to the GANs and GMMNs, because the VAE training uses the correct observation model, while the GAN and GMMN objectives do not have any particular observation model built in.
To determine the size of this effect, we evaluated the models under a different regime where, instead of choosing a fixed value of the observation noise $\sigma$ on a validation set, $\sigma$ was tuned independently for each example.2 This is not a proper generative model, but it can be viewed as an upper bound on the log-likelihood that would be achievable with a heavy-tailed and radially symmetric noise model.3 Results are shown in Table 3. We see that adapting $\sigma$ for each example results in a log-likelihood improvement between 30 and 100 nats for all of the networks. In general, the examples which show the largest performance jump are images of 1’s (which prefer smaller $\sigma$ ) and 2’s (which prefer larger $\sigma _ { . }$ ). This is a significant effect, and suggests that one could significantly improve the log-likelihood scores by picking a better observation model. However, this effect is smaller in magnitude than the differences between VAE and GAN/GMMN log-likelihoods, so it fails to explain the likelihood difference.
# C POSTERIOR VISUALIZATION OF DIGIT “2"
According to the log-likelihood evaluation, we find digit “2" is the hardest digit for modelling. In this section we investigate the quality of modelling $" 2 "$ of each model. We randomly sampled a fixed set of 100 samples of digit “2" from training data and compare whether model capture this mode. We show the plots of “2" for GAN-10, GAN-50, VAE-10 and true data in the following figures for illustration. We see that GAN-10 fails at capturing many instances of digit “2" in the training data! We see instead of generating $" 2 "$ , it tries to generate digit “1", “7" “9", “4", “8" from reconstruction. GAN-50 does much better, its reconstruction are all digit “2" and there is only some style difference from the true data. VAE-10 totally dominates this competition, where it perfectly reconstructs all the samples of digit “2". We emphasize if directly sampling from each model, samples look visually indistinguishable (see Fig. 1), but we can clearly see differences in posterior samples.
 Figure 5: Posterior samples of digit “2" for GAN-10.
 Figure 6: Posterior samples of digit “2" for GAN-50.
 Figure 7: Posterior samples of digit “2" for VAE-10.
 Figure 8: 100 digit “2" from training data.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284# LEARNING TO LEARNWITH CONDITIONAL CLASS DEPENDENCIES
Xiang Jiang?†, Mohammad Havaei?, Farshid Varno?†, Gabriel Chartrand?, Nicolas Chapados?, Stan Matwin† ?Imagia Inc., †Dalhousie University {xiang.jiang,mohammad,farshid.varno,gabriel,nic}@imagia.com, stan@cs.dal.ca
# ABSTRACT
Neural networks can learn to extract statistical properties from data, but they seldom make use of structured information from the label space to help representation learning. For example “cat” and “dog” are closer than “cat” and “truck”. Although some label structure can implicitly be obtained when training on huge amounts of data, in a few-shot learning context where little data is available, making explicit use of the label structure can inform the model to reshape the representation space to reflect a global sense of class dependencies. We propose a meta-learning framework, Conditional class-Aware Meta-Learning (CAML), that conditionally transforms feature representations based on a metric space that is trained to capture inter-class dependencies. This enables a conditional modulation of the feature representations of the base-learner to impose regularities informed by the label space. Experiments show that the conditional transformation in CAML leads to more disentangled representations and achieves competitive results on the miniImageNet benchmark.
# 1 INTRODUCTION
In machine learning, the objective of classification is to train a model to categorize inputs into various classes. We usually assume a categorical distribution over the label space, and thus effectively ignore dependencies among them. However, class structure does exist in real world and is also present in most datasets. Although class structure can be implicitly obtained as a by-product during learning, it is not commonly exploited in an explicit manner to develop better learning systems. The use of label structure might not be of prime importance when having access to huge amounts of data, such the full ImageNet dataset. However, in the case of few-shot learning where little data is available, meta-information such as dependencies in the label space can be crucial.
In recent years, few-shot learning—learning from few examples across many tasks—has received considerable attention (Ravi & Larochelle, 2016; Snell et al., 2017; Finn et al., 2017; Vinyals et al., 2016). In particular, the concept of meta-learning has been shown to provide effective tools for few-shot learning tasks. In contrast to common transfer learning methods that aim to fine-tune a pre-trained model, meta-learning systems are trained by being exposed to a large number of tasks and evaluated in their ability to learn new tasks effectively. In meta-training, learning happens at two levels: a meta-learner that learns across many tasks, and a base-learner that optimizes for each task. Model-Agnostic Meta-Learning (MAML) is a gradient-based meta-learning algorithm that provides a mechanism for rapid adaptation by optimizing only for the initial parameters of the base-learner (Finn et al., 2017).
Our motivation stems from a core challenge in gradient-based meta-learning, wherein the quality of gradient information is key to fast generalization: it is known that gradient-based optimization fails to converge adequately when trained from only a few examples (Ravi & Larochelle, 2016), hampering the effectiveness of gradient-based meta-learning techniques. We hypothesize that under such circumstances, introducing a metric space trained to encode regularities of the label structure can impose global class dependencies on the model. This class structure can then provide a high-level view of the input examples, in turn leading to learning more disentangled representations.
We propose a meta-learning framework taking advantage of this class structure information, which is available in a number of applications. The Conditional class-Aware Meta-Learning (CAML) model is tasked with producing activations in a manner similar to a standard neural network, but with the additional flexibility to shift and scale those activations conditioned on some auxiliary meta-information. While there are no restrictions on the nature of the conditioning factor, in this work we model class dependencies by means of a metric space. We aim to learn a function mapping inputs to a metric space where semantic distances between instances follow an Euclidean geometry—classes that are semantically close lie in close proximity in an $\ell ^ { p }$ sense. The goal of the conditional class-aware transformation is to make explicit use of the label structure to inform the model to reshape the representation landscape in a manner that incorporates a global sense of class structure.
The contributions of this work are threefold: (i) We provide a meta-learning framework that makes use of structured class information in the form of a metric space to modulate representations in few-shot learning tasks; (ii) We introduce class-aware grouping to improve the statistical strength of few-shot learning tasks; (iii) We show experimentally that our proposed algorithm learns more disentangled representation and achieves competitive results on the miniImageNet benchmark.
# 2 BACKGROUND
We start by describing the meta-learning formulation proposed by Vinyals et al. (2016) and Ravi & Larochelle (2016), and review MAML (Finn et al., 2017), of which CAML is an instance.
# 2.1 META-LEARNING PROBLEM FORMULATION
The goal of meta-learning is to learn from a distribution of tasks. The learning happens on two levels: (i) a meta-level model, or meta-learner, that learns across many tasks, and (ii) a base-level model, or base-learner, that operates within each specific task. Meta-learning happens in task space, where each task can be treated as one meta-example. In the meta-learning formulation, we define a collection of regular tasks as meta-sets $\mathcal { D }$ , and each task $\mathcal { D } \in \mathcal { D }$ has its own $\mathcal { D } ^ { \mathrm { t r a i n } }$ and $\mathcal { D } ^ { \mathrm { t e s t } }$ split. $\mathcal { D } ^ { \mathrm { t r a i n } }$ is often denoted as the “support set” and $\mathcal { D } ^ { \mathrm { t e s t } }$ the “query set”. The resulting meta-learner objective is to choose parameters $\theta$ that minimize the expected loss $\mathcal { L } ( \cdot ; \theta )$ across all tasks in $\mathcal { D }$ ,
$$\begin{array} { r } { \theta ^ { * } = \mathrm { a r g m i n } _ { \theta } \mathbb { E } _ { \mathcal { D } \sim \mathcal { D } } [ \mathcal { L } ( \mathcal { D } ; \theta ) ] . } \end{array}$$
At the meta-level, the meta-sets $\mathcal { D }$ can be further split into disjoint meta-training set $\mathcal { D } _ { \mathrm { m e t a - t r a i n } }$ , meta-validation set $\mathcal { D } _ { \mathrm { m e t a - v a l i d } }$ and meta-test set $\mathcal { D } _ { \mathrm { m e t a - t e s t } }$ . The meta-learner is trained on $\mathcal { D } _ { \mathrm { m e t a - t r a i n } }$ , validated on $\mathcal { D } _ { \mathrm { m e t a - v a l i d } }$ and finally evaluated on $\mathcal { D } _ { \mathrm { m e t a - t e s t } }$ .
# 2.2 MODEL-AGNOSTIC META-LEARNING
Model-Agnostic Meta-Learning (Finn et al., 2017) is a meta-learning algorithm that aims to learn representations that encourage fast adaptation across different tasks. The meta-learner and base-learner share the same network structure, and the parameters learned by the meta-learner are used to initialize the base-learner on a new task.
To optimize the meta-learner, we first sample a set of tasks $\{ \mathcal { D } _ { 1 } , \mathcal { D } _ { 2 } , . . . , \mathcal { D } _ { S } \}$ from the meta-training set $\mathcal { D } _ { \mathrm { m e t a - t r a i n } }$ . For a meta-learner parameterized by $\theta$ , we compute its adapted parameters $\theta _ { i }$ for each sampled task $\mathcal { D } _ { i }$ . The adapted parameters $\theta _ { i }$ are task-specific and tell us the effectiveness of $\theta$ as to whether it can achieve generalization through one or a few additional gradient steps. The objective of the meta-learner is to optimize the representation $\theta$ such that it leads to good task-specific adaptations $\theta _ { i }$ with only a few gradient steps. The meta-learner performs slow learning at the meta-level across many tasks to support fast learning on new tasks. At meta-test time, we initialize the base-learner with the meta-learned representation $\theta ^ { * }$ followed by gradient-based fine-tuning.
# 3 METHOD
# 3.1 CONDITIONAL CLASS-AWARE META-LEARNING
As shown in Figure 1, the proposed Conditional class-Aware Meta-Learning (CAML) is composed of four components: an embedding function $f _ { \phi }$ that maps inputs to a metric space, a base-learner $f _ { \theta }$ that learns each individual task, an adaptation function $f _ { c }$ that conditionally modulates the representations of the base-learner, and a meta-learner that learns across different tasks. Figure 1 depicts a toy illustration of the task inference procedure where examples from three classes are mapped onto a metric space using $f _ { \phi }$ , which are further used to modulate the base-learner $f _ { \theta }$ through a conditional transformation function $f _ { c }$ .
 Figure 1: Overview of Conditional class-Aware Meta-Learning. Inputs to the model are mapped onto an embedding space using $f _ { \phi }$ which are then used to modulate the base-learner $f _ { \theta }$ through a conditional transformation $f _ { c }$ . We use MAML (not shown) to meta-learn $f _ { c } , f _ { \theta }$ , and a metric loss to pre-train $f _ { \phi }$
The main contribution of this paper is to incorporate metric-based conditional transformations $( f _ { c } )$ into the meta-learning framework at the instance level. A notable feature of the proposed method is that the model has a global sense of the label space through the embedding function $f _ { \phi }$ by mapping examples onto the semantically meaningful metric space. The embeddings on the metric space inform the base-learner $f _ { \theta }$ about the label structure which in turn helps disentangle representations from different classes. This structured information can also provide a global view of the input examples to improve gradient-based meta-learning.
In a simplistic form, our proposed model makes predictions using
$$\hat { y } = f _ { \theta } \Big ( x ; f _ { c } \big ( f _ { \phi } ( x ) \big ) \Big ) ,$$
where the base-learner $f _ { \theta }$ is conditioned on the embedding space $f _ { \phi } \left( x \right)$ through the conditional transformation $f _ { c }$ . This is in contrast with a regular base-learner where $\hat { y } = f _ { \boldsymbol { \theta } } ( \boldsymbol { x } )$ . In our framework, we use MAML to meta-learn $f _ { c }$ and $f _ { \theta }$ . The metric space is pre-trained using distance-based loss function.
# 3.2 METRIC SPACE AS CONDITIONAL INFORMATION
We encode information of the label structure through $f _ { \phi }$ in the form of an $M$ -dimensional metric space, where each input example is reduced to a point in the metric space. The goal of the metric learning step is to optimize parameter $\phi$ such that distances between examples in the metric space are semantically meaningful. Given the parameters of the metric space $\phi$ , which is represented by a convolutional network, we calculate a centroid $\mathbf { c } _ { t }$ for each class $t$ ,
$$\mathbf { c } _ { t } = \frac { 1 } { K } \sum _ { ( \mathbf { x } _ { i } , y _ { i } ) \in \mathcal { D } ^ { \mathrm { t r a i n } } } \mathbb { 1 } _ { \{ y _ { i } = t \} } f _ { \phi } ( \mathbf { x } _ { i } ) ,$$
where $K$ denotes the number of examples for class $t$ , $\mathbb { 1 } _ { \{ y _ { i } = t \} }$ denotes an indicator function of $y _ { i }$ which takes value 1 when $y _ { i } = t$ and 0 otherwise. The centroid $\mathbf { c } _ { t }$ is the sample mean among all instances from the same class which is treated as a prototype representation of the class $t$ . The mapping function $f _ { \phi }$ is optimized to minimize the negative log-probability defined in Eq. (1) by minimizing the Euclidean distance $d$ between an example and its corresponding class centroid $\mathbf { c } _ { t }$ while maximizing its Euclidean distance to other class centroids $\mathbf { c } _ { t ^ { \prime } }$ :
$$\underset { \phi } { \mathrm { a r g m i n } } \mathbb { E } \Bigg [ d ( f _ { \phi } ( \mathbf { x } _ { i } ) , \mathbf { c } _ { t } ) ) + \log \sum _ { t ^ { \prime } } \mathrm { e x p } ( - d ( f _ { \phi } ( \mathbf { x } _ { i } ) , \mathbf { c } _ { t ^ { \prime } } ) ) \Bigg ] .$$
In relation to prototypical networks (Snell et al., 2017), we use the same loss function for metric learning. However, these frameworks differ in the test mode: we are not interested in example-centroid distances for label assignment, but rather in the projection $f _ { \phi } ( \mathbf { x } _ { i } )$ from the input space to the metric space that encapsulates inferred class regularities given the input example $\mathbf { x } _ { i }$ . In relation to other pre-training methods that use the meta-train classes to train a 64-way classifier, our use of the metric space imposes distance-based constraints to learn embeddings that follow semantically meaningful distance measures.
 Figure 2: Conditionally transformed convolutional block. The convolutional feature maps are conditionally scaled and shifted based on the input image’s representation in the pre-trained metric space.
We empirically find it difficult to optimize both the metric space and base-learner end-to-end. The metric space is pre-trained on the meta-train data and it is not updated during meta-learning. This also ensures the metric space is trained on a large number of classes to capture the global class dependencies.
# 3.3 CONDITIONALLY TRANSFORMED CONVOLUTIONAL BLOCK
We now turn to describing the conditionally transformed convolutional block, shown in Figure 2, which uses the metric space described in Section 3.2 to inform the base-learner about the label structure of a task. The conditional transformation $f _ { c }$ receives embeddings from the metric space and produces transformation operations to modulate convolutional representations of the base-learner $f _ { \theta }$ .
Our conditional transformation has close relation to Batch Normalization (BN) (Ioffe & Szegedy, 2015) that normalizes the input to every layer of a neural network. In order to conditionally modulate feature representations, we use Conditional Batch Normalization (CBN) (Dumoulin et al., 2017) to predict scale and shift operators from conditional input $\mathbf { s } _ { i }$ :
$$\begin{array} { r } { \hat { \gamma } _ { c } = f _ { c , \gamma } ( \mathbf { s } _ { i } ) , \qquad \hat { \beta } _ { c } = f _ { c , \beta } ( \mathbf { s } _ { i } ) , } \end{array}$$
where $f _ { c , \gamma }$ and $f _ { c , \beta }$ can be any differentiable function. This gives our model the flexibility to shift or scale the intermediate representations based on some source information in $\mathbf { s } _ { i }$ . Since examples belonging to the same class are conceptually close, we exploit this inherent relationship in the metric space to modulate the feature maps at the example level in a way that encodes the label structure.
Once we obtained the embedding function $f _ { \phi }$ , we use two auxiliary networks, learned end-to-end together with the meta-learner, to predict the shift and scale factors of the convolutional feature map:
$$\hat { \gamma } _ { i , c } = f _ { c , \gamma } ( f _ { \phi } ( \mathbf { x } _ { i } ) ) , \hat { \beta } _ { i , c } = f _ { c , \beta } ( f _ { \phi } ( \mathbf { x } _ { i } ) ) .$$
Having computed $\hat { \gamma } _ { i , c }$ and $\hat { \beta } _ { i , c }$ , Conditional Batch Normalization (CBN) is applied as follows:
$$\mathrm { C B N } ( \mathbf { R } _ { i , c } | \hat { \gamma } _ { i , c } , \hat { \beta } _ { i , c } ) = \hat { \gamma } _ { i , c } \frac { { \mathbf { R } _ { i , c } - \mathbb { E } [ \mathbf { R } _ { c } ] } } { \sqrt { \mathrm { V a r } [ \mathbf { R } _ { c } ] + \epsilon } } + \hat { \beta } _ { i , c } ,$$
where $\mathbf { R } _ { i , c }$ refers to the $c ^ { t h }$ feature map from the $i ^ { t h }$ example, $\epsilon$ is a small constant, $\beta _ { c }$ and $\gamma _ { c }$ are learnable parameters shared within a task. $\mathbb { E } [ \mathbf { R } _ { c } ]$ and $\mathrm { V a r } [ \mathbf { R } _ { c } ]$ are batch mean and variance of $\mathbf { R } _ { c }$ .
It is worthwhile to note the effect of conditional transformation. The conditional bias transformation with $\hat { \beta } _ { i , c }$ is analogous to concatenation-based conditioning where the conditional information is concatenated to the feature maps (Dumoulin et al., 2018). The conditional scaling factor provides multiplicative interactions between the metric space and the feature maps to aggregate information.
Furthermore, the goal of the conditionally transformed convolutional block is to simultaneously capture the two views of a classification task: a global view that is aware of the relationships among all classes, and a local views of the current N-way K-shot classification task. The metric space, or the global view, is pre-trained in a way that is independent of the current N-way K-shot task; while the base-learner, or the local view, attempts to develop representations for the current classification task. Although the metric space is never trained on the meta-test classes, we expect the learned metric space to generalize from the meta-train tasks to the meta-test tasks.
We further describe parameter sharing for CBN learning in Section 3.3.1, and class-aware grouping in Section 3.3.2 which provides more statistical strength for more effective few-shot learning.
 Figure 3: CBN shared architecture
 Figure 4: Normalization methods. ‘C’ denotes channels, $\mathrm { ^ { 6 } H }$ , W’ spatial dimensions and $\mathbf { \Delta } ^ { \mathsf { } } \mathbf { N } ^ { \mathsf { \prime } }$ examples.
# 3.3.1 MULTITASK LEARNING OF CBN
Although one can predict $\hat { \gamma } _ { c }$ and $\hat { \boldsymbol \beta } _ { c }$ using two separate functions, we find it beneficial to use shared parameters as shown in Figure 3. The shared representations are more efficient at producing conditional transformations which also provide a strong inductive bias to help learning (Caruana, 1997).
# 3.3.2 CLASS-AWARE GROUPING
We propose class-aware grouping, as shown in Figure 4 (b), to further exploit properties of metric space. The motivation stems from a lack of statistical strength when learning from only a few examples. As an example, in $N .$ -way 1-shot learning, the model is required to find the most meaningful way to distinguish different classes. However, gradient-based optimization may lead to the discovery of irrelevant features which coincide with the class labels, such as background colors.
We address this problem by class-aware grouping that is guided by our metric space. This is related to “transduction”, which is a standard technique in MAML-based methods. Transduction as discussed in Nichol et al. (2018), makes use of the channel mean $\mathbb { E } [ \mathbf { R } _ { c } ]$ and variance $\mathrm { V a r } [ \mathbf { R } _ { c } ]$ , defined in Eq. (4), of query examples when evaluating a base-learner. In contrast to standard transduction methods that calculate mean and variance over all examples of the current batch, we introduce class-aware grouping that clusters examples into different groups and use group-based mean and variance to normalize different channels. The grouping is determined by distance measures in the metric space where examples are grouped together based on their nearest centroid $\mathbf { } c _ { t }$ defined in Section 3.2. Class-aware grouping is integrated into CBN as:
$$\mathrm { C B N } ( \mathbf { R } _ { i , c } | \hat { \gamma } _ { i , c } , \hat { \beta } _ { i , c } ) = \hat { \gamma } _ { i , c } \frac { \mathbf { R } _ { i , c } - \mathbb { E } [ \mathbf { R } _ { i , c } \cdot \mathbb { 1 } _ { \{ x _ { i } \in t \} } ] } { \sqrt { \mathrm { V a r } [ \mathbf { R } _ { i , c } \cdot \mathbb { 1 } _ { \{ x _ { i } \in t \} } ] + \epsilon } } + \hat { \beta } _ { i , c } ,$$
where $\mathbb { 1 } _ { \{ x _ { i } \in t \} }$ indicates if an example $x _ { i }$ belongs to cluster $t$ , and $\mathbb { E } [ \mathbf { R } _ { i , c } { \cdot } \mathbb { 1 } _ { \{ x _ { i } \in t \} } ]$ represents the average of channel $\mathbf { R } _ { c }$ among examples clustered at $c _ { t }$ . This is depicted in Figure 4 where the channel mean and variance are calculated for every group.This approach informs the base-learner about what to expect from the query examples at the class level through channel mean and variance, which provides more explicit guidance to the meta-learning procedure.
# 3.4 TRAINING DETAILS
The base-learner $( f _ { \theta } )$ is composed of 4 layers of $3 \times 3$ convolutions with a $4 \times 4$ skip connections from the input to the final convolutional layer. The use of skip connections is to improve the gradient flow as MAML unfolds the inner loop into one computational graph. The use of skip connections is empirically important to the proposed model. Each convolutional layer has 30 channels and is followed by CBN, ReLU and $2 \times 2$ max-pooling operations. The output of the final convolution is flattened and fed to a 1-layer dense classifier. For learning the metric space $( f _ { \phi } )$ , we use the same residual network (ResNet-12) as Oreshkin et al. (2018). The metric space is pre-trained on the same meta-training dataset for 30,000 episodes and not updated while learning the base-learner. The meta-learner is trained for 50,000 episodes. We empirically observe that training the metric space and meta-learner end-to-end is overly complex and prone to over-fitting. For CBN functions $( f _ { c } )$ , we use 3 dense layers with 30 hidden units each. Every layer is followed by a ReLU except for the last layer where no activation is used. For the meta-learner, we use MAML with 1 gradient step for 1-shot learning and 5 gradient steps for 5-shot learning. We use the Adam (Kingma & Ba, 2014) optimizer and clip the L2 norm of gradients with an upper bound of 5. Similar to MAML, we use transduction where the statistics of the current batch is used for $\mathbb { E } ( . )$ and $\mathrm { V a r } ( . )$ in Eq. (4) for both training and testing.
# 4 RELATED WORK
# 4.1 META-LEARNING
Meta-learning or “learning-to-learn” (Schmidhuber, 1987; Bengio et al., 1992; Mitchell & Thrun, 1993; Vilalta & Drissi, 2002) has been studied as a means to acquire meta-knowledge across many tasks. In recent years, meta-learning has become an important approach for few-shot learning. A number of approaches aim to learn universal learning procedure approximators by supplying training examples to the meta-learner that outputs predictions on testing examples (Hochreiter et al., 2001; Vinyals et al., 2016; Santoro et al., 2016; Mishra et al., 2017). Other approaches learn to generate model parameters conditioned on training examples (Gomez & Schmidhuber, 2005; Munkhdalai & Yu, 2017; Ha et al., 2016; Gidaris & Komodakis, 2018), or learning optimization algorithms across different tasks (Ravi & Larochelle, 2016; Andrychowicz et al., 2016; Li & Malik, 2017).
# 4.1.1 GRADIENT-BASED META-LEARNING
Our work is more inline with gradient-based meta-learning that aims to learn representations that encourage fast adaptation on new tasks. These methods are based on model-agnostic meta-learning (MAML) introduced by Finn et al. (2017). While the original MAML requires second-order gradients in meta-optimization, REPTILE (Nichol et al., 2018) only uses first-order gradient information. Furthermore, Latent Embedding Optimization (LEO) (Rusu et al., 2018) is proposed to perform gradient-based optimization on a lowdimensional latent space instead of the original high-dimensional parameter space. We emphasize that all those methods do not make explicit use of structured label information, which is a main novelty in this paper.
# 4.1.2 METRIC-BASED META-LEARNING
Our work also relates closely to metric-based meta-learning that learns a metric space across different tasks. Siamese networks (Koch et al., 2015) learn a similarity measure between inputs using a shared network architecture that outputs high probability when paired examples are from the same class. Matching networks (Vinyals et al., 2016) use full context embeddings to encode examples to the metric space and use attention as a similarity measure for predictions. Prototypical networks (Snell et al., 2017) compute a centroid, or prototype, for every class that are later used for distance-based queries of new examples. Task dependent adaptive metric (TADAM) (Oreshkin et al., 2018) uses metric scaling based on tasks representations to learn a task-dependent metric space.
A notable difference between the metric-based methods and our approach is that, the metric space in our model is not aimed for distance-based classification. Rather, we use the metric space to represent class structure which facilitates the gradient-based meta learning towards better generalization. Another difference between our method and TADAM is that, TADAM scales the metric space at the task level where all examples within a task are scaled in the same manner. In contrast, our method provides instance-based conditioning that makes use of the precise representation of each example. Put another way, TADAM modulates the inference on a metric space from a task perspective, while CAML uses example-level representation to modulate the representation at the content level.
# 4.2 CONDITIONAL TRANSFORMATION
In style transfer, conditional instance normalization is proposed by Dumoulin et al. (2017) that transforms the content image conditioned on the domain of the style image. In visual question answering, De Vries et al. (2017) have shown that it is beneficial to modulate early visual signals of a pre-trained residual network by language in the form of conditional batch normalization. It was further shown that feature-wise linear modulation (Perez et al., 2017; Dumoulin et al., 2018) can efficiently select meaningful representations for visual reasoning.
 Figure 5: t-SNE visualization of the learned metric space colored by category.
The notion that is common to all these methods is the use of an additional input source, e.g., style or language, to conditionally transform intermediate representations of a network. In few-shot learning, Zhou et al. (2018) suggested that it is easier to operate in the concept space in the form of a lower dimensional representation. This is compatible with our proposed approach that uses the metric space as concept-level representation to modulate intermediate features of the base-learner.
# 5 EXPERIMENTS
We use miniImageNet to evaluate the proposed Conditional class-Aware Meta-Learning algorithm. miniImageNet (Vinyals et al., 2016) is composed of $8 4 \times 8 4$ colored images from 100 classes, with 600 examples in each class. We adopt the class split by Ravi & Larochelle (2016) that uses 64 classes for training, 16 for validation, and 20 for test. For $N .$ -way $K$ -shot training, we randomly sample $N$ classes from the meta-train classes each containing $K$ examples for training and 20 examples for testing. At meta-testing time, we randomly sample 600 $N$ -way $K$ -shot tasks from the test classes.
# 5.1 RESULTS
The results presented in Table 1 show that our proposed algorithm has comparable performance on the state-of-the-art miniImageNet 5-way 1-shot classification task, and competitive results on the 5-way 5-shot task. Unlike LEO (Rusu et al., 2018) that applies meta-learning on pre-trained representations, our meta-learner is able to effectively operate on the high-dimensional parameter space. Our method also does not require co-training compared with TADAM (Oreshkin et al., 2018).
Figure 5 shows the t-SNE plot of the learned metric space for both meta-train and meta-validation classes. As seen in Figure 4b, examples from the meta-validation set form clusters consistent with their class membership, even though the metric space is not trained on these classes. For example, “mierkat”, “tundrarum” and “podenco” are all animals and they are clustered close together.
The first main baseline we report is MAML. CAML improves upon MAML by about $10 \%$ on both 1-shot and 5-shot tasks. This means incorporating class dependencies in the form of a metric space can greatly facilitate gradient-based meta-learning. We also compare with MAML using our base-learner architecture equipped with skip connections from the input to the last convolutional layer. MAML trained with our base-learner’s architecture yields similar performance as the original MAML, suggesting the improvement is resulted from the proposed CAML framework, rather than changes in the base-learner’s architecture.
Table 1: miniImageNet classification accuracy with $9 5 \%$ confidence intervals.
<table><tr><td>Model</td><td>5-way 1-shot</td><td>5-way 5-shot</td></tr><tr><td>Meta-Learner LSTM (Ravi & Larochelle, 2016)</td><td>43.44% ± 0.77%</td><td>60.60% ± 0.71%</td></tr><tr><td>Matching Networks (Vinyals et al.,2016)</td><td>46.6%</td><td>60.0%</td></tr><tr><td>Prototypical Network with Soft k-Means (Ren et al., 2018)</td><td>50.41% ± 0.31%</td><td>69.88%± 0.20%</td></tr><tr><td>MetaNet (Munkhdalai & Yu, 2017)</td><td>49.21% ± 0.96%</td><td></td></tr><tr><td>TCML (Mishra et al., 2018)</td><td>55.71% ± 0.99%</td><td>68.88% ± 0.92%</td></tr><tr><td>adaResNet (Munkhdalai etal., 2018)</td><td>56.88% ± 0.62%</td><td>71.94 ± 0.57%</td></tr><tr><td>Cosine Classifier (Gidaris & Komodakis, 2018)</td><td>56.20% ± 0.86%</td><td>73.00% ± 0.64%</td></tr><tr><td>TADAM (Oreshkin et al., 2018)</td><td>58.5%</td><td>76.7%</td></tr><tr><td>LEO (Rusu et al., 2018)</td><td>61.76% ± 0.08%</td><td>77.59% ± 0.12%</td></tr><tr><td>MAML (Finn et al., 2017)</td><td>48.7% ±1.84%</td><td>63.11% ± 0.92%</td></tr><tr><td>MAML on our architecture</td><td>48.26% ±1.04%</td><td>64.25% ± 0.78%</td></tr><tr><td>Prototypical Network (Snell et al., 2017)</td><td>49.42% ± 0.78%</td><td>68.2% ± 0.66%</td></tr><tr><td>Prototypical Network on our metric space</td><td>55.96% ± 0.91%</td><td>71.64% ± 0.70%</td></tr><tr><td>CAML (with multitask learning alone)</td><td>52.56% ± 0.83%</td><td>71.35% ±1.13%</td></tr><tr><td>CAML (with class-aware grouping alone)</td><td>55.28% ±0.90%</td><td>71.14% ± 0.81%</td></tr><tr><td>CAML (full model)</td><td>59.23% ± 0.99%</td><td>72.35% ± 0.71%</td></tr></table>
The confidence intervals are constructed by sampling 600 evaluation tasks from the meta-test classes.
 Figure 6: PCA visualization of feature maps from the last convolutional layer colored by category.
The second baseline we use is prototypical network. We measure the classification ability of our metric space using prototypical network as a classifier, shown in Table 1 (Prototypical Network in our metric space). These results suggest that making predictions on the metric space alone is inferior to CAML.This can be explained by CAML’s ability to fast-adapt representations even when the metric space does not provide good separations. We also find that CAML has larger improvements in 1-shot tasks than 5-shot ones. This is because, in 1-shot learning, metric-based methods estimate class representations from a single example, making it difficult to provide a robust class estimation.
# 5.2 THE EFFECT OF CONDITIONAL TRANSFORMATION
We compare activations before and after the conditional transformation to better understand how conditional transformation modulates the feature representations. Figure 6 shows the PCA projections of the last convolutional layer in the base-learner. We observe in Figure 5a that, before conditional transformation, examples from three classes (“parallel bars”, “tile roof” and “reel”) are mixed together. In Figure 5b, after the conditional transformation is applied, one of the previously cluttered classes (“tile roof”) become separated from the rest classes. This confirms that metric space can alleviate the difficulty in few-shot learning by means of conditional transformations.
We undertake ablation studies to show the impact of multitask learning and class-aware grouping. Empirical results in Table 1 suggest that, while 1-shot learning is sensitive to multitask learning and class-aware grouping, 5-shot learning is not affected by those techniques. This is owing to a lack of statistical strength in 1-shot learning, which requires more explicit guidance in the training procedure. This means exploiting metric-based channel mean and variance can provide valuable information to improve meta-learning. More detailed ablation studies are included in Appendix A.
# 6 CONCLUSION
In this work, we propose Conditional class-Aware Meta-Learning (CAML) that incorporates class information by means of an embedding space to conditionally modulate representations of the base-learner. By conditionally transforming the intermediate representations of the base-learner, our goal is to reshape the representation with a global sense of class structure. Experiments reveal that the proposed conditional transformation can modulate the convolutional feature maps towards a more disentangled representation. We also introduce class-aware grouping to address a lack of statistical strength in few-shot learning. The proposed approach obtains competitive results with the current state-of-the-art performance on 5-way 1-shot and 5-shot miniImageNet benchmark.
# REFERENCES
Marcin Andrychowicz, Misha Denil, Sergio Gomez, Matthew W Hoffman, David Pfau, Tom Schaul, and Nando de Freitas. Learning to learn by gradient descent by gradient descent. In Advances in Neural Information Processing Systems, pp. 3981–3989, 2016.
Samy Bengio, Yoshua Bengio, Jocelyn Cloutier, and Jan Gecsei. On the optimization of a synaptic learning rule. In Preprints Conf. Optimality in Artificial and Biological Neural Networks, pp. 6–8. Univ. of Texas, 1992.
Rich Caruana. Multitask learning. Machine learning, 28(1):41–75, 1997.
Harm De Vries, Florian Strub, Jer´ emie Mary, Hugo Larochelle, Olivier Pietquin, and Aaron C Courville. ´ Modulating early visual processing by language. In Advances in Neural Information Processing Systems, pp. 6594–6604, 2017.
Vincent Dumoulin, Jonathon Shlens, and Manjunath Kudlur. A LEARNED REPRESENTATION FOR ARTISTIC STYLE. ICLR, 2017. URL https://arxiv.org/pdf/1610.07629.pdf.
Vincent Dumoulin, Ethan Perez, Nathan Schucher, Florian Strub, Harm de Vries, Aaron Courville, and Yoshua Bengio. Feature-wise transformations. Distill, 3(7):e11, 2018.
Chelsea Finn, Pieter Abbeel, and Sergey Levine. Model-agnostic meta-learning for fast adaptation of deep networks. In International Conference on Machine Learning, pp. 1126–1135, 2017.
Spyros Gidaris and Nikos Komodakis. Dynamic few-shot visual learning without forgetting. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 4367–4375, 2018.
Faustino Gomez and Jurgen Schmidhuber. Evolving modular fast-weight networks for control. In ¨ International Conference on Artificial Neural Networks, pp. 383–389. Springer, 2005.
David Ha, Andrew Dai, and Quoc V Le. Hypernetworks. arXiv preprint arXiv:1609.09106, 2016.
Sepp Hochreiter, A Steven Younger, and Peter R Conwell. Learning to learn using gradient descent. In International Conference on Artificial Neural Networks, pp. 87–94. Springer, 2001.
Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. arXiv preprint arXiv:1502.03167, 2015.
Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014.
Gregory Koch, Richard Zemel, and Ruslan Salakhutdinov. Siamese neural networks for one-shot image recognition. In ICML Deep Learning Workshop, volume 2, 2015.
Ke Li and Jitendra Malik. Learning to optimize neural nets. arXiv preprint arXiv:1703.00441, 2017.
Nikhil Mishra, Mostafa Rohaninejad, Xi Chen, and Pieter Abbeel. Meta-learning with temporal convolutions. arXiv preprint arXiv:1707.03141, 2017.
Nikhil Mishra, Mostafa Rohaninejad, Xi Chen, and Pieter Abbeel. A simple neural attentive meta-learner. 2018.
Tom M Mitchell and Sebastian B Thrun. Explanation-based neural network learning for robot control. In Advances in neural information processing systems, pp. 287–294, 1993.
Tsendsuren Munkhdalai and Hong Yu. Meta networks. arXiv preprint arXiv:1703.00837, 2017.
Tsendsuren Munkhdalai, Xingdi Yuan, Soroush Mehri, and Adam Trischler. Rapid adaptation with conditionally shifted neurons. In International Conference on Machine Learning, pp. 3661–3670, 2018.
Alex Nichol, Joshua Achiam, and John Schulman. On first-order meta-learning algorithms. CoRR, abs/1803.02999, 2018.
Boris N Oreshkin, Alexandre Lacoste, and Pau Rodriguez. Tadam: Task dependent adaptive metric for improved few-shot learning. arXiv preprint arXiv:1805.10123, 2018.
Ethan Perez, Florian Strub, Harm De Vries, Vincent Dumoulin, and Aaron Courville. Film: Visual reasoning with a general conditioning layer. arXiv preprint arXiv:1709.07871, 2017.
Sachin Ravi and Hugo Larochelle. Optimization as a model for few-shot learning. 2016.
Mengye Ren, Eleni Triantafillou, Sachin Ravi, Jake Snell, Kevin Swersky, Joshua B Tenenbaum, Hugo Larochelle, and Richard S Zemel. Meta-learning for semi-supervised few-shot classification. arXiv preprint arXiv:1803.00676, 2018.
Andrei A Rusu, Dushyant Rao, Jakub Sygnowski, Oriol Vinyals, Razvan Pascanu, Simon Osindero, and Raia Hadsell. Meta-learning with latent embedding optimization. arXiv preprint arXiv:1807.05960, 2018.
Adam Santoro, Sergey Bartunov, Matthew Botvinick, Daan Wierstra, and Timothy Lillicrap. Meta-learning with memory-augmented neural networks. In International conference on machine learning, pp. 1842–1850, 2016.
Jurgen Schmidhuber. Evolutionary principles in self-referential learning. on learning now to learn: The meta-meta-meta...-hook. Diploma thesis, Technische Universitat Munchen, Germany, 14 May 1987. URL http://www.idsia.ch/˜juergen/diploma.html.
Jake Snell, Kevin Swersky, and Richard S. Zemel. Prototypical networks for few-shot learning. CoRR, abs/1703.05175, 2017. URL http://arxiv.org/abs/1703.05175.
Ricardo Vilalta and Youssef Drissi. A perspective view and survey of meta-learning. Artificial Intelligence Review, 18(2):77–95, 2002.
Oriol Vinyals, Charles Blundell, Tim Lillicrap, Daan Wierstra, et al. Matching networks for one shot learning. In Advances in Neural Information Processing Systems, pp. 3630–3638, 2016.
Fengwei Zhou, Bin Wu, and Zhenguo Li. Deep meta-learning: Learning to learn in the concept space. arXiv preprint arXiv:1802.03596, 2018.
# A ADDITIONAL ABLATION STUDIES
# A.1 THE IMPACT OF MULTITASK LEARNING AND CLASS-AWARE GROUPING
To better understand the role of different components in the proposed conditional transformation, we undertake ablation studies to provide further insights into CBN. We study the impact of multitask learning detailed in Section 3.3.1 and class-aware grouping described in Section 3.3.2.
Table 2: Ablation study on the impact of multitask learning and class-aware grouping miniImageNet.
<table><tr><td>CBN</td><td>multitask</td><td>class-aware grouping</td><td>5-way 1-shot</td><td>5-way 5-shot</td></tr><tr><td>×</td><td>×</td><td>×</td><td>48.26% ± 1.04%</td><td>64.25% ± 0.78%</td></tr><tr><td>√</td><td>×</td><td>×</td><td>52.06% ± 1.12%</td><td>69.84% ± 1.28%</td></tr><tr><td>√</td><td>√</td><td>×</td><td>52.56% ± 0.83%</td><td>71.35% ± 1.13%</td></tr><tr><td>√</td><td>×</td><td>√</td><td>55.28% ± 0.90%</td><td>71.14% ± 0.81%</td></tr><tr><td>√</td><td>√</td><td>√</td><td>59.23% ± 0.99%</td><td>72.35% ± 0.71%</td></tr></table>
Table 3: Ablation study on the impact of conditional transformation operators for miniImageNet.
<table><tr><td>Model</td><td>BN</td><td>CBN with βc alone (</td><td> CBN with c alone</td><td>CBN</td></tr><tr><td>5-way 1-shot48.7% ± 1.84%</td><td></td><td>56.04% ± 0.99%</td><td>57.83% ± 1.04%</td><td>59.23% ± 0.99%</td></tr></table>
Empirical results from Table 2 suggest that, while 1-shot learning is sensitive to multitask learning and class-aware grouping, 5-shot learning is less sensitive those techniques. This is owing to a lack of sufficient training examples in 1-shot learning tasks, which requires more explicit guidance in the training procedure. We further note that, in 1-shot learning, using class-aware grouping alone can improve CBN’s performance by $3 \%$ . This means exploiting metric-based channel mean and variance can provide valuable information for gradient-based meta-learning.
# A.2 THE IMPACT OF SCALE AND SHIFT TRANSFORMATIONS
For CBN parameters, we observe that more than half of the predicted $\hat { \boldsymbol \beta } _ { c }$ are negative. This is inline with findings from Perez et al. (2017) that CBN selectively suppresses activations of a feature map when followed by a ReLU. To further examine the impact of the scale and shift operators, we train CBN with each operator alone. Table 3 shows CBN works the best when both $\hat { \gamma } _ { c }$ and $\hat { \boldsymbol \beta } _ { c }$ are used, and $\hat { \gamma } _ { c }$ contributes more than $\hat { \boldsymbol { \beta } } _ { c }$ , owing to its multiplicative interactions between the metric space and convolutional feature representations.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229# Celebrating Diversity in Shared Multi-Agent Reinforcement Learning
Chenghao Li, Tonghan Wang, Chengjie Wu, Qianchuan Zhao, Jun Yang∗, Chongjie Zhang∗
Tsinghua University {lich18, wangth18, wucj19} $@$ mails.tsinghua.edu.cn, {zhaoqc, yangjun603, chongjie}@tsinghua.edu.cn
# Abstract
Recently, deep multi-agent reinforcement learning (MARL) has shown the promise to solve complex cooperative tasks. Its success is partly because of parameter sharing among agents. However, such sharing may lead agents to behave similarly and limit their coordination capacity. In this paper, we aim to introduce diversity in both optimization and representation of shared multi-agent reinforcement learning. Specifically, we propose an information-theoretical regularization to maximize the mutual information between agents’ identities and their trajectories, encouraging extensive exploration and diverse individualized behaviors. In representation, we incorporate agent-specific modules in the shared neural network architecture, which are regularized by L1-norm to promote learning sharing among agents while keeping necessary diversity. Empirical results show that our method achieves state-of-the-art performance on Google Research Football and super hard StarCraft II micromanagement tasks†.
# 1 Introduction
Cooperative multi-agent reinforcement learning (MARL) has drawn increasing interest in recent years, which provides a promise for solving many real-world challenging problems, such as sensor networks [1], traffic management [2], and coordination of robot swarms [3]. However, learning effective policies for such complex multi-agent systems remains challenging. One central problem is that the joint action-observation space grows exponentially with the number of agents, which imposes high demand on the scalability of learning algorithms.
To address this scalability challenge, policy decentralization with shared parameters (PDSP) is widely used, where agents share their neural network weights. Parameter sharing significantly improves learning efficiency because it dramatically reduces the total number of policy parameters, while experiences and gradients of one agent can be used to train others. Enjoying these advantages, many advanced deep MARL approaches adopt the PDSP paradigm, including value-based methods [4–8], policy gradients [9–13] and communication learning algorithms [14, 15]. These approaches achieve state-of-the-art performance on tasks such as StarCraft II micromanagement [16].
While parameter sharing has been proven to accelerate training [17], its drawbacks are also apparent in complex tasks. These tasks typically require substantial exploration and diversified strategies among agents. When parameters are shared, agents tend to acquire homogeneous behaviors because they typically adopt similar actions under similar observations, preventing efficient exploration and the emergence of sophisticated cooperative policies. This tendency becomes particularly problematic for many challenging multi-agent coordination tasks, hindering deep MARL from broader applications. For example, the unsatisfactory performance of state-of-the-art MARL algorithms on Google Research Football (Fig. 1, and [18]) highlights an urgent demand for diverse behaviors.
Notably, sacrificing the merits of parameter sharing for diversity is also unfavorable. Like humans, sharing necessary experience or understanding of tasks can broadly accelerate cooperation learning. Without parameter sharing, agents search in a much larger parameter space, which may be wasteful because they do not need to behave differently all the time. Therefore, the question is how to adaptively trade-off diversity and sharing. In this paper, we solve this dilemma by proposing several structural and learning novelties.
To encourage diversity, we propose a novel information-theoretical objective to maximize the mutual information between agents’ identi
 Figure 1: Shared parameters induce behaviors (left) and can hardly learn successful policies on the challenging Google Research Football task. Our method learns sophisticated cooperative strategies by trading off diversity and sharing (right).
ties and trajectories. This objective enables each agent to distinguish themselves from others and thus involves the contribution of all agents. Accordingly, we derive an intrinsic reward for motivating diversity and optimize it with the global environmental reward by learning the total Q-function as a combination of individual Q-functions. Structurally, we further decompose individual Q-functions as the sum of shared and non-shared local Q-functions for sharing experiences while maintaining representation diversity. We hope agents can use and expand shared knowledge whenever possible. Thus we introduce L1 regularization on each non-shared Q-function, encouraging agents to share and be diverse when necessary on several critical actions. Combining these novelties achieves a dynamic balance between diversity and homogeneity, efficiently catalyzing adaptive and sophisticated cooperation.
We benchmark our approach on Google Research Football (GRF) [18], and StarCraft II micromanagement tasks (SMAC) [16]. The extraordinary performance of our approach on challenging benchmarking tasks shows that our approach achieve significantly higher coordination capacity than baselines while using diversity as a catalyst for more robust and talent policies. To our best knowledge, our approach achieves state-of-the-art performance on SMAC super hard maps and challenging GRF multi-agent tasks like academy_3_vs_1_with_keeper, academy_counterattack_hard, and a full-field scenario 3_vs_1_with_keeper (full field).
# 2 Background
A fully cooperative multi-agent task can be formulated as a Dec-POMDP [19], which is defined as a tuple $\mathcal { G } = \left. N , S , A , P , R , \bar { O } , \Omega , n , \gamma \right.$ , where $N$ is a finite set of $n$ agents, $s \in S$ is the true state of the environment, $A$ is the set of actions, and $\gamma \in [ 0 , 1 )$ is a discount factor. At each time step, each agent $i \in N$ receives his own observation $o _ { i } \in \Omega$ according to the observation function $O ( s , i )$ , and selects an action $a _ { i } \in A$ , which results in a joint action vector $^ { a }$ . The environment then transitions to a new state $s ^ { \prime }$ based on the transition function $P ( s ^ { \prime } | s , \pmb { a } )$ , and inducing a global reward $r = R ( s , { \pmb a } )$ shared by all the agents. Each agent has its own action-observation history $\tau _ { i } \in \mathcal { T } _ { i } \doteq ( \Omega _ { i } \times A ) ^ { * }$ . Due to partial observability, each agent conditions its policy $\pi _ { i } ( a _ { i } | \tau _ { i } )$ on $\tau _ { i }$ . The joint policy $\pi$ induces the joint action-value function $\begin{array} { r } { Q _ { t o t } ^ { \pi } ( s , \pmb { a } ) = \mathbb { E } _ { s _ { 0 : \infty } , \pmb { a } _ { 0 : \infty } } \left[ \sum _ { t = 0 } ^ { \infty } \gamma ^ { t } r _ { t } \ | \ s _ { 0 } = s , \pmb { a } _ { 0 } = \pmb { a } , \pi \right] , } \end{array}$ .
# 2.1 Centralized Training with Decentralized Execution
Our method adopts the framework of centralized training with decentralized execution (CTDE) [9, 20, 4, 5, 21, 22, 6, 11]. This framework tackles the exponentially growing joint action space by decentralizing the control policies while adopting centralized training to learn cooperation. Agents learn in a centralized manner with access to global information but execute based on their local action-observation history. One promising approach to implement the CTDE framework is value function factorization. The IGM (individual-global-max) principle [21] guarantees the consistency between the local and global greedy actions. When IGM is satisfied, agents can obtain the optimal global action by simply choosing the local greedy action that maximizes each agent’s individual utility function $Q _ { i }$ . Some algorithms have successfully used the IGM principle [5, 6, 23] to push forward the progress of MARL.
# 3 Method
In this section, we present a novel diversity-driven MARL framework (Fig. 2) that balances each agent’s individuality with group coordination, which is a general approach that can be combined with existing CDTE value factorization methods.
# 3.1 Identity-Aware Diversity
We first introduce how to encourage behavioral diversity by designing intrinsic motivations. Intuitively, to encourage the specialty of individual trajectories, agents need to behave differently to highlight themselves from others, taking different actions and visiting different local observations. To achieve this goal, we use an information-theoretic objective for maximizing the mutual information between individual trajectory and agents’ identity:
 Figure 2: Schematics of our approach.
$$I ^ { \pi } ( \tau _ { T } ; i d ) = H ( \tau _ { T } ) - H ( \tau _ { T } | i d ) = E _ { i d , \tau _ { T } \sim \pi } \left[ \log \frac { p ( \tau _ { T } | i d ) } { p ( \tau _ { T } ) } \right] ,$$
where $\tau _ { T }$ and $i d$ is the random variable for agent’s local trajectory and identity, respectively. $\pi$ is the joint policy. To optimize Eq. 1, we expand $p ( \tau _ { T } )$ as $\begin{array} { r } { p ( o _ { 0 } ) \prod _ { t = 0 } ^ { T - 1 } \dot { p } ( a _ { t } | \tau _ { t } ) p ( o _ { t + 1 } | \tau _ { t } , a _ { t } ) } \end{array}$ , and $p ( \tau _ { T } | i d )$ as $\begin{array} { r } { p ( o _ { 0 } | i d ) \prod _ { t = 0 } ^ { T - 1 } p ( a _ { t } | \tau _ { t } , i d ) p ( o _ { t + 1 } | \tau _ { t } , a _ { t } , i d ) } \end{array}$ . Therefore, the mutual information can be written as:
$$I ^ { \pi } ( \tau _ { T } ; i d ) = E _ { i d , \tau } \underbrace { [ \log \frac { p ( o _ { 0 } | i d ) } { p ( o _ { 0 } ) } } _ { \textcircled { \backslash } } + \underbrace { \sum _ { t = 0 } ^ { T - 1 } \log \frac { p ( a _ { t } | \tau _ { t } , i d ) } { p ( a _ { t } | \tau _ { t } ) } } _ { \textcircled { \emptyset } } + \underbrace { \sum _ { t = 0 } ^ { T - 1 } \log \frac { p ( o _ { t + 1 } | \tau _ { t } , a _ { t } , i d ) } { p ( o _ { t + 1 } | \tau _ { t } , a _ { t } ) } } _ { \textcircled { \emptyset } } ] .$$
Term $\textcircled{1}$ is determined by the environment, and we can ignore it when optimizing the mutual information. The second term quantifies the information gain about agent’s action selection when the identity is given, which measures action-aware diversity as $I ( a ; i d | \tau )$ . However, $p ( a _ { t } | \tau _ { t } , i d )$ is typically the distribution induced by $\epsilon$ -greedy, which only distinguishes the action with the highest possibility. Therefore, directly optimizing this term conceals most information about the local Qfunctions. To solve this problem, we use the Boltzmann softmax distribution of local Q values to replace $p ( a _ { t } | \tau _ { t } , i d )$ , which forms a lower bound of term $\textcircled{2}$ :
$$E _ { i d , \tau } \left[ \log \frac { p ( a _ { t } | \tau _ { t } , i d ) } { p ( a _ { t } | \tau _ { t } ) } \right] \geq E _ { i d , \tau } \left[ \log \frac { \mathrm { S o f t M a x } ( \frac { 1 } { \alpha } Q ( a _ { t } | \tau _ { t } , i d ) ) } { p ( a _ { t } | \tau _ { t } ) } \right] .$$
The inequity holds because the KL divergence $D _ { \mathrm { K L } } \big ( p ( \cdot | \tau _ { t } , i d ) \| \mathrm { S o f t M a x } ( \frac { 1 } { \alpha } Q ( \cdot | \tau _ { t } , i d ) ) \big )$ is nonnegative. We maximize this lower bound to optimize Term $\textcircled{2}$ . Inspired by variational inference approaches [24], we derive and optimize a tractable lower bound for Term $\textcircled{3}$ at each timestep by introducing a variational posterior estimator $q _ { \phi }$ parameterized by $\phi$ :
$$E _ { i d , \tau } \left[ \log \frac { p ( o _ { t + 1 } | \tau _ { t } , a _ { t } , i d ) } { p ( o _ { t + 1 } | \tau _ { t } , a _ { t } ) } \right] \geq E _ { i d , \tau } \left[ \log \frac { q _ { \phi } ( o _ { t + 1 } | \tau _ { t } , a _ { t } , i d ) } { p ( o _ { t + 1 } | \tau _ { t } , a _ { t } ) } \right] ,$$
Similar to the second term, the inequality holds because for any $q _ { \phi }$ , the $\mathrm { K L }$ divergence $D _ { \mathrm { K L } } ( p ( \cdot | \tau _ { t } , a _ { t } , i d ) | | q _ { \phi } ( \cdot | \tau _ { t } , a _ { t } , i d ) )$ is non-negative. Intuitively, optimizing Eq. 4 encourages agents
to have diverse observations that are distinguishable by agents’ identification and thus measures observation-aware diversity as $I ( o ^ { \prime } ; i d | \tau , \bar { a ) }$ . To tighten the this lower bound, we minimize the KL divergence with respect to the parameters $\phi$ . The gradient for updating $\phi$ is:
$$\begin{array} { r l } & { \nabla _ { \phi } \mathcal { L } ( \phi ) = \nabla _ { \phi } \mathbb { E } _ { \tau , a , i d } \left[ D _ { \mathrm { K L } } \left( p \left( \cdot | \tau , a , i d \right) \| q _ { \phi } \left( \cdot | \tau , a , i d \right) \right) \right] = \nabla _ { \phi } \mathbb { E } _ { \tau , a , i d , o ^ { \prime } } \left[ \log \frac { p \left( o ^ { \prime } | \tau , a , i d \right) } { q _ { \phi } \left( o ^ { \prime } | \tau , a , i d \right) } \right] } \\ & { \quad \quad \quad = - \mathbb { E } _ { \tau , a , i d , o ^ { \prime } } \left[ \nabla _ { \phi } \log q _ { \phi } \left( o ^ { \prime } | \tau , a , i d \right) \right] . } \end{array}$$
Based on the lower bounds shown in Eq. 3 and Eq. 4, we introduce intrinsic rewards to optimise the information-theoretic objective (Eq. 1) for encouraging diverse behaviors:
$$\begin{array} { r } { r ^ { I } = E _ { i d } \left[ \beta _ { 2 } D _ { \mathrm { K L } } ( \mathrm { S o f t M a x } ( \beta _ { 1 } Q ( \cdot | \tau _ { t } , i d ) ) | | p ( \cdot | \tau _ { t } ) ) \right. } \\ { \left. + \beta _ { 1 } \log q _ { \phi } ( o _ { t + 1 } | \tau _ { t } , a _ { t } , i d ) - \log p ( o _ { t + 1 } | \tau _ { t } , a _ { t } ) \right] . } \end{array}$$
We introduce two scaling factors $\beta _ { 1 } , \beta _ { 2 } \geq 0$ when calculating intrinsic rewards. When $\beta _ { 1 }$ is $_ 0$ , we only optimize the entropy term $H ( \tau _ { T } )$ in the mutual information objective (Eq. 1). $\beta _ { 2 }$ is used to adjust the importance of policy diversity compared with transition diversity. In Appendix A, we discuss and compare two different approaches for estimating $p \left( \boldsymbol { a } _ { t } | \tau _ { t } \right)$ and $p \left( o _ { t + 1 } \vert \tau _ { t } , a _ { t } \right)$ .
# 3.2 Action-Value Learning for Balancing Diversity and Sharing
In the previous section, we introduce an information-theoretic objective for encouraging each agent to behave differently from general trajectories. However, the shared local Q-function does not have enough capacity to present different policies for each agent. For solving this problem, we additionally equip each agent $i$ with an individual local Q-function $Q _ { i } ^ { I }$ . Defining experiences that need to be shared or exclusively learned is inefficient and usually can not generalize. Therefore, we let agents adaptively decide whether to share experiences by decomposing $Q _ { i }$ as:
$$Q _ { i } ( a _ { i } | \tau _ { i } ) = Q ^ { S } ( a _ { i } | \tau _ { i } ) + Q _ { i } ^ { I } ( a _ { i } | \tau _ { i } ) ,$$
where $Q ^ { S }$ is the shared Q-function among agents. In its current form, agents may learn to decompose their local Q-function arbitrarily. On the contrary, we expect that agents can share as much knowledge as possible so that we apply an L1 regularization on individual local Q-function $Q ^ { I }$ as shown in Fig.2. Such a regularization can also prevent agents from being too diverse and ignore cooperating to finish the task. In our experiments, we show that the L1 regularization is critical to achieving a balance between diversity and cooperation.
# 3.3 Overall Learning Objective
In this section, we discuss how to use the diversity-encouraging reward to train the proposed learning framework. Since the intrinsic rewards $r ^ { I }$ inevitably involves the influence from all agents, we add $r ^ { I }$ to environment rewards $r ^ { e }$ and use the following TD loss:
$$\mathcal { L } _ { T D } ( \theta ) = \left[ r ^ { e } + \beta r ^ { I } + \gamma \operatorname* { m a x } _ { a ^ { \prime } } Q _ { t o t } \left( s ^ { \prime } , a ^ { \prime } ; \theta ^ { - } \right) - Q _ { t o t } ( s , a ; \theta ) \right] ^ { 2 } ,$$
where $\theta$ is the parameters in the whole framework, $\theta ^ { - }$ is periodically frozen parameters copied from $\theta$ for a stable update, and $\beta$ is a hyper-parameter adjusting the weight of intrinsic rewards compared with environment rewards. We use QPLEX to decompose $Q _ { t o t }$ as mixing of local Q-functions $Q _ { i }$ and train the framework end-to-end by minimizing the loss:
$$\mathcal { L } ( \boldsymbol { \theta } ) = \mathcal { L } _ { T D } ( \boldsymbol { \theta } ) + \lambda \sum _ { i } \mathcal { L } _ { L _ { 1 } } ( Q _ { i } ^ { I } ( \boldsymbol { \theta } _ { i } ^ { I } ) ) ,$$
where $\theta _ { i } ^ { I }$ is the parameters of $Q _ { i } ^ { I }$ $, \mathcal { L } _ { L _ { 1 } } ( Q _ { i } ^ { I } )$ is the L1 regularization term for independent Q-functions, and $\lambda$ is a scaling factor.
# 4 Case study: outperforming by being diverse only when necessary
We design Pac-Men shown in Fig. 3 to demonstrate how our approach works. In this task, four agents are initialized at the center room and can only observe a $5 \times 5$ grid around them. Three dots are initialized randomly in each edge room. To make this environment more challenging, paths to different rooms have different lengths, which are $\mathrm { d o w n : l e f t : u p : r i g h t } = 4 : 8 : 1 2 : 8$ . Three out of four paths are outside agents’ observation scope, which brings about the difficulty of exploration. Dots will refresh randomly after all rooms are empty. An ineffective competition between agents occurs when they come together in one room. The total environmental reward is the number of dots eaten in one step or -0.1 if no one eats dots. The time limit of this environment is set to 100 steps.
 Figure 3: Why does our method work? The balance between identity-aware diversity and experience sharing encourages sophisticated strategies.
Fig. 3-middle demonstrates the learned strategies of our approach, with a heatmap showing the visitation number. Driven by the objective of mutual information between individual trajectory and identity, agents achieve diversity and scatter in different rooms to eat dots. We further analyze the role of independent and shared Q-functions during different stages in Fig. 3 right. We visualize the value of $S D \dot { ( } Q _ { i } ^ { I } ( \cdot ) ) / S D ( Q ^ { S } ( \cdot ) )$ , where SD denotes the standard deviation (SD) of Q values for different actions. A higher SD ratio indicates the independent Q-functions play a leading role, while a lower SD ratio indicates the shared Q function’s domination.
We notice that the SD ratio is considerably larger in the central room and four paths than in four edge rooms. This observation means that agents use independent Q networks to reach different rooms while use the shared Q network to search for dots in them. The result shows that our method achieves a good balance between diversity and knowledge sharing. Taking this advantage, our approach outperforms baselines (Fig. 3 left, baselines are introduced in Sec. 6). Other methods, such as variational exploration (MAVEN [25]) and individuality emergence (EOI [26]), are slower to learn optimal strategies.
# 5 Related Work
Deep multi-agent reinforcement learning algorithms have witnessed significant advances in recent years. COMA [20], MADDPG [9], PR2 [27], and DOP [10] study the problem of policy-based multi-agent reinforcement learning. They use a (decomposed) centralized critic to calculate gradients for decentralized actors. Value-based algorithms decompose the joint value function into individual utility functions in order to enable efficient optimization and decentralized execution. VDN [4], QMIX [5], and QTRAN [21] progressively expand the representation capabilities of the mixing network. QPLEX [6] implements the full IGM class [21] by encoding the IGM principle into a duplex dueling network architecture. Weighted QMIX [23] proposes weighted projection to decompose any joint action-value functions. There are other works that investigate into MARL from the perspective of coordination graphs [28–30], communication [31, 32, 15], and role-based learning [17, 33].
Knowledge sharing in MARL From IQL [34] to QPLEX, many works focus on designing mixing network structures and have provided promising empirical and theoretical results. For these works, experience sharing among agents has been an important component. Learning from others is one essential skill engraved in humans’ genes to survive in society. Based on the relationship between teachers and students in human society, a series of research work hopes each agent can learn from others or selectively share its knowledge with others [35–37]. But it is challenging to specify knowledge in practice, let alone deciding what to share or learn. SEAC [38] partially solves this problem by sharing trajectories only for off-policy training. NCC [32] maintains cognition consistency by representation alignment between neighbors. Roy et al. [39] force each agent to predict others’ local policies and adds a coach for group experience alignment. Christianos et al. [40] group agents during pre-training and force agents in the same group to use one policy. In this paper, we do not try to let agents choose whether to learn or share experiences. Our neural network structure shown in Fig. 2 can balance group coordination and diversity by gradient backpropagation.
Diversity In single-agent settings, diversity emerges for exploration or solving sparse reward problems. Existing methods such as curiosity-driven algorithms [41–44] or maximising mutual information [45–47] have shown great promise. When encouraging diversity in MARL settings, agents’ coordination must be considered. Several recent works study this problem, such as MAVEN [25], EITI & EDTI [48], and EOI [26]. MAVEN learns a diverse ensemble of monotonic approximations with the help of a latent space to explore. EITI and EDTI consider pairwise mutual influence to encourage the interdependence between agents. EOI combines the gradient from the intrinsic value function (IVF) and the total Q-function to train each agent’s local Q-function. In this paper, we encourage agents to explore unique trajectories by optimizing the mutual information between agent’s identity and trajectory. Moreover, we propose a novel network structure to enable experience sharing or consensus, which combines all agents’ rare ideas, while still maintain independent action-value functions for each agent to behave differently when necessary. Our approach considers the trade-off relationship between knowledge sharing and diversity, and learns to establish a balance and leverage their advantages for joint task solving.
# 6 Experiments
In Sec. 4, we use a toy game to illustrate how our approach adaptively balances experience sharing and identity-aware diversity. In this section, we use challenging tasks from GRF and SMAC benchmark to further demonstrate and illustrate the outperformance of our approach. We compare our approach against multi-agent value-based methods (QMIX [5], QPLEX [6]), variational exploration (MAVEN [25]), and individuality emergence (EOI [26]) methods. Different from baselines, we do not include agents’ identification in inputs when calculating local Q-functions. We show the average and variance of the performance for our method, baselines, and ablations tested with five random seeds.
 6.1 Performance on Google Research Football (GRF) Figure 4: Comparison of our approach against baseline algorithms on Google Research Football.
We first benchmark our approach on three challenging Google Research Football (GRF) offensive scenarios academy_3_vs_1_with_keeper, academy_counterattack_hard, and our own designed full-field scenario 3_vs_1_with_keeper (full field). Agents’ initial locations for each scenario are shown in Appendix B.3. In GRF tasks, agents need to coordinate timing and positions for organizing offense to seize fleeting opportunities, and only scoring leads to rewards. In our experiments, we control left-side players (in yellow) except the goalkeeper. The right-side players are rule-based bots controlled by the game engine. Agents have a discrete action space of 19, including moving in eight directions, sliding, shooting, and passing. The observation contains the positions and moving directions of the ego-agent, other agents, and the ball. The $z$ -coordinate of the ball is also included.
We make a small and reasonable change to the half-court offensive scenarios: our players will lose if they or the ball returns to our half-court. All baselines and ablations are tested with this modification. Environmental reward only occurs at the end of the game. They will get $+ 1 0 0$ if they win, else get -1.
We show the performance comparison against baselines in Fig. 4. Our approach outperforms all the scenarios. MAVEN needs more time to explore sophisticated strategies, demonstrating that CDS incentives more efficient exploration. EOI lets each agent consider individuality and cooperation simultaneously by setting local learning objectives but without exclusive Q networks, making cooperation and individuality hard to be persistently coordinated. In comparison, taking advantage of the partially shared network structure, CDS agents learn diverse but coordinated strategies. For example, as shown in Fig. 1, three agents have different behaviors, with the first agent passing the ball, the second scoring, while the third running to threaten. These diverse behaviors closely coordinate, forming a perfect scoring strategy and leading to significant outperformance against EOI.
 6.2 Performance on StarCraft II Figure 5: Comparison of our approach against baseline algorithms on four super hard SMAC maps: corridor, MMM2, 6h_vs_8z, and $3 { \bf s } 5 z \_ { \bf V } { \bf s } \_ 3 { \bf s } 6 z$ and two hard SMAC maps: 5m_vs_6m and 3s_vs_5z.
In this section, we test our approach on the StarCraft II micromanagement (SMAC) benchmarks [16]. This benchmark consists of various maps classified as easy, hard, and super hard. Here we test our method on four super hard maps: corridor, MMM2, 6h_vs_ $_ { 8 z }$ , and $3 { \bf s } 5 z \_ { \bf V } { \bf s } \_ 3 { \bf s } 6 z .$ , and two hard SMAC maps: 5m_vs_6m and 3s_vs_5z. For the four super hard maps, our approach outperforms all baselines with acceptable variance across random seeds, as shown in Fig. 5. The baselines QPLEX and QMIX can achieve satisfactory performance on some challenging benchmarks, such as $ { 3 \mathbf { s } } 5 { \mathbf { z } } _ { - } { \mathbf { v } } { \mathbf { s } } _ { - } 3 { \mathbf { s } } 6 { \mathbf { z } }$ and MMM2. But on other maps, they need the proposed diversity-celebrating method to get better performance. Compared with MAVEN and EOI, our approach maintains its out-performance with the balance between diversity and homogeneity for learning sophisticated cooperation. Our approach performs similarly with baselines for the two hard maps, indicating our balancing process may not improve the learning efficiency in environments that require pure homogeneity. But for challenging environments, where sophisticated strategies are laborious to explore, our approach can efficiently search for valuable strategies with stable updates.
# 6.3 Ablations and Visualization
To understand the contribution of each component in the proposed CDS framework, we carry out ablation studies to test the contribution of its three main components: Identity-aware diversity (A) encouragement and partially shared (B) neural network structure with $L I$ regularization (C) on non-shared Q-functions. To test component A, we ablate our intrinsic rewards to four different levels. (1) CDS-Raw ablates all intrinsic rewards by setting $\beta$ in Eq. 8 to zero. (2) CDS-No-Identity ablates
$H \left( \tau _ { T } | i d \right)$ and only optimize $H \left( \tau _ { T } \right)$ in Eq. 1 by setting $\beta _ { 1 }$ in Eq. 6 to zero. (3) CDS-No-Action ablates item $\textcircled{2}$ in Eq. 2 by setting $\beta _ { 2 }$ in Eq. 6 to zero. (4) CDS-No-Obs ablates item $\textcircled{3}$ in Eq. 2 by ablating $\beta _ { 1 } \log q _ { \phi } \left( o _ { t + 1 } | \tau _ { t } , a _ { t } , i d \right) - \log p \left( o _ { t + 1 } | \tau _ { t } , a _ { t } \right)$ in Eq. 6. To test component B, we design CDS-All-Shared, which ablates independent action-value functions together with the L1 loss and, like baselines, adds agents’ identification to the input. To test component C, we design CDS-No-L1, which ablates L1 regularization terms by setting $\lambda$ in Eq. 9 to zero.
 Figure 6: Left. Ablation studies on academy_counterattack_hard. Right. Visualization of trained policies, which achieve complex cooperation with impressive off-the-ball moving strategies.
We first carry out ablation studies on academy_counterattack_hard to analyze which part of our novelties lead to the outstanding performance as shown on the left side of Fig. 6. The ablation of each part of our intrinsic reward will bring a noticeable decrease in performance. Among them, the least impact on performance is the ablation of action-aware diversity. CDS-No-L1 performs similarly to MAVEN, which indicates that unlimited diversity is harmful to cooperation. CDS-All-Shared performs even worse than QPLEX, demonstrating that identity-aware diversity is difficult to emerge without our specially designed network structure.
We further visualize the final trained strategies on the right side of Fig. 6, which shows complex cooperation between agents. Our players first attack down the wing by dribbling and passing the ball. Then one of them draws the attention of the enemy defenders and the goalkeeper, while the ball being passed across the penalty area. Another player catches the ball and completes the shot. The most impressive part of our sophisticated strategies is off-the-ball moving strategies. All agents without the ball try to use their unique and valuable moves to create more scoring opportunities, which shows behavior and position diversity for finishing the goal.
 Figure 7: Left. Ablation studies in super hard map corridor. Right. Visualization of the final trained strategies, which achieves a hard-earned victory brought by the sacrifice of a warrior.
We also carry out ablation studies on the super hard map corridor as shown in Fig. 7 left. Same as results on academy_counterattack_hard, the ablation of action-aware diversity causes the least performance gap. Among all the ablations, CDS-No-L1 and CDS-No-Identity perform worst, whose performance is similar to QPLEX. This phenomenon indicates excessive diversity is harmful to the emerge of complex cooperation. CDS-All-Shared achieves acceptable performance, different from the GRF scenario, reflecting the different demand levels for the representation diversity of these two kinds of benchmarks.
To better explain why our approach performs well. On corridor, we also visualize the final strategies in Fig. 7 right. In this super hard map, six friendly Zealots are facing 24 enemy Zerglings. The disparity in quantity means our agents are doomed to lose if they attack together. One Zealot, whose route is highlighted blue, becomes a warrior leaving the team to attract the attention of most enemies in the blue oval. Although doomed to sacrifice, he brings enough time for the team to eliminate a small part of the enemies in the green oval. After that, another Zealot stands out to attract some enemies and enables teammates to eradicate them. These sophisticated strategies reflect the leverage between diversity and homogeneity by encouraging agents to be diverse only when necessary.
# 7 Closing Remarks
Observing that behavioral diversity among agents is essential for many challenging and complex multi-agent tasks, in this paper, we introduce a novel mechanism of being diverse when necessary into shared multi-agent reinforcement learning. The balance between individual diversity and group coordination induced by our CDS approach pushes forward state-of-the-art of deep MARL on challenging benchmark tasks while keeping parameter sharing benefits. We hope that our method can shed light on future works to motivate agents to cooperate with diversity to further explore complex multi-agent coordination problems.
# Acknowledgments
This work was funded by the National Key Research and Development Project of China under Grant 2017YFC0704100 and 2016YFB0901900, in part by the National Natural Science Foundation of China under Grant 61425027 and U1813216, in part by Science and Technology Innovation $2 0 3 0 -$ “New Generation Artificial Intelligence” Major Project (No. 2018AAA0100904), a grant from the Institute of Guo Qiang,Tsinghua University, and a grant from Turing AI Institute of Nanjing.
# References
[1] Chongjie Zhang and Victor Lesser. Coordinated multi-agent reinforcement learning in networked distributed pomdps. In Twenty-Fifth AAAI Conference on Artificial Intelligence, 2011. [2] Arambam James Singh, Akshat Kumar, and Hoong Chuin Lau. Hierarchical multiagent reinforcement learning for maritime traffic management. In Proceedings of the 19th International Conference on Autonomous Agents and MultiAgent Systems, pages 1278–1286, 2020. [3] Maximilian Hüttenrauch, Adrian Šošic, and Gerhard Neumann. Guided deep reinforcement ´ learning for swarm systems. arXiv preprint arXiv:1709.06011, 2017. [4] Peter Sunehag, Guy Lever, Audrunas Gruslys, Wojciech Marian Czarnecki, Vinicius Zambaldi, Max Jaderberg, Marc Lanctot, Nicolas Sonnerat, Joel Z Leibo, Karl Tuyls, et al. Valuedecomposition networks for cooperative multi-agent learning based on team reward. In Proceedings of the 17th International Conference on Autonomous Agents and MultiAgent Systems, pages 2085–2087. International Foundation for Autonomous Agents and Multiagent Systems, 2018. [5] Tabish Rashid, Mikayel Samvelyan, Christian Schroeder Witt, Gregory Farquhar, Jakob Foerster, and Shimon Whiteson. Qmix: Monotonic value function factorisation for deep multi-agent reinforcement learning. In International Conference on Machine Learning, pages 4292–4301, 2018. [6] Jianhao Wang, Zhizhou Ren, Terry Liu, Yang Yu, and Chongjie Zhang. Qplex: Duplex dueling multi-agent q-learning. International Conference on Learning Representations (ICLR), 2021. [7] Yiqin Yang, Xiaoteng Ma, Chenghao Li, Zewu Zheng, Qiyuan Zhang, Gao Huang, Jun Yang, and Qianchuan Zhao. Believe what you see: Implicit constraint approach for offline multi-agent reinforcement learning. arXiv preprint arXiv:2106.03400, 2021. [8] Shariq Iqbal, Christian A Schroeder De Witt, Bei Peng, Wendelin Böhmer, Shimon Whiteson, and Fei Sha. Randomized entity-wise factorization for multi-agent reinforcement learning. In International Conference on Machine Learning, pages 4596–4606. PMLR, 2021. [9] Ryan Lowe, Yi Wu, Aviv Tamar, Jean Harb, OpenAI Pieter Abbeel, and Igor Mordatch. Multiagent actor-critic for mixed cooperative-competitive environments. In Advances in Neural Information Processing Systems, pages 6379–6390, 2017. [10] Yihan Wang, Beining Han, Tonghan Wang, Heng Dong, and Chongjie Zhang. Dop: Off-policy multi-agent decomposed policy gradients. In Proceedings of the International Conference on Learning Representations (ICLR), 2021. [11] Xiaoteng Ma, Yiqin Yang, Chenghao Li, Yiwen Lu, Qianchuan Zhao, and Jun Yang. Modeling the interaction between agents in cooperative multi-agent reinforcement learning. In Proceedings of the 20th International Conference on Autonomous Agents and MultiAgent Systems, pages 853–861, 2021. [12] Kamal K Ndousse, Douglas Eck, Sergey Levine, and Natasha Jaques. Emergent social learning via multi-agent reinforcement learning. In International Conference on Machine Learning, pages 7991–8004. PMLR, 2021. [13] Tianhao Zhang, Yueheng Li, Chen Wang, Guangming Xie, and Zongqing Lu. Fop: Factorizing optimal joint policy of maximum-entropy multi-agent reinforcement learning. In International Conference on Machine Learning, pages 12491–12500. PMLR, 2021. [14] Jakob Foerster, Ioannis Alexandros Assael, Nando de Freitas, and Shimon Whiteson. Learning to communicate with deep multi-agent reinforcement learning. In Advances in Neural Information Processing Systems, pages 2137–2145, 2016. [15] Tonghan Wang, Jianhao Wang, Chongyi Zheng, and Chongjie Zhang. Learning nearly decomposable value functions with communication minimization. In Proceedings of the International Conference on Learning Representations (ICLR), 2020. [16] Mikayel Samvelyan, Tabish Rashid, Christian Schroeder de Witt, Gregory Farquhar, Nantas Nardelli, Tim GJ Rudner, Chia-Man Hung, Philip HS Torr, Jakob Foerster, and Shimon Whiteson. The starcraft multi-agent challenge. arXiv preprint arXiv:1902.04043, 2019. [17] Tonghan Wang, Heng Dong, Victor Lesser, and Chongjie Zhang. Roma: Multi-agent reinforcement learning with emergent roles. In Proceedings of the 37th International Conference on Machine Learning, 2020. [18] Karol Kurach, Anton Raichuk, Piotr Stanczyk, Michał Zaj ˛ac, Olivier Bachem, Lasse Espeholt, ´ Carlos Riquelme, Damien Vincent, Marcin Michalski, Olivier Bousquet, et al. Google research football: A novel reinforcement learning environment. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 34, pages 4501–4510, 2020. [19] Frans A Oliehoek, Christopher Amato, et al. A concise introduction to decentralized POMDPs, volume 1. Springer, 2016. [20] Jakob N Foerster, Gregory Farquhar, Triantafyllos Afouras, Nantas Nardelli, and Shimon Whiteson. Counterfactual multi-agent policy gradients. In Thirty-Second AAAI Conference on Artificial Intelligence, 2018. [21] Kyunghwan Son, Daewoo Kim, Wan Ju Kang, David Earl Hostallero, and Yung Yi. Qtran: Learning to factorize with transformation for cooperative multi-agent reinforcement learning. In International Conference on Machine Learning, pages 5887–5896, 2019. [22] Kyunghwan Son, Sungsoo Ahn, Roben Delos Reyes, Jinwoo Shin, and Yung Yi. Qtran $^ { + + }$ : Improved value transformation for cooperative multi-agent reinforcement learning, 2020. [23] Tabish Rashid, Gregory Farquhar, Bei Peng, and Shimon Whiteson. Weighted qmix: Expanding monotonic value function factorisation for deep multi-agent reinforcement learning. Advances in Neural Information Processing Systems, 33, 2020. [24] Martin J Wainwright, Michael I Jordan, et al. Graphical models, exponential families, and variational inference. Foundations and Trends® in Machine Learning, 1(1–2):1–305, 2008. [25] Anuj Mahajan, Tabish Rashid, Mikayel Samvelyan, and Shimon Whiteson. Maven: Multiagent variational exploration. In Advances in Neural Information Processing Systems, pages 7611–7622, 2019. [26] Jiechuan Jiang and Zongqing Lu. The emergence of individuality in multi-agent reinforcement learning. arXiv preprint arXiv:2006.05842, 2020. [27] Ying Wen, Yaodong Yang, Rui Luo, Jun Wang, and Wei Pan. Probabilistic recursive reasoning for multi-agent reinforcement learning. In Proceedings of the International Conference on Learning Representations (ICLR), 2019. [28] Carlos Guestrin, Michail Lagoudakis, and Ronald Parr. Coordinated reinforcement learning. In ICML, volume 2, pages 227–234. Citeseer, 2002. [29] Carlos Guestrin, Daphne Koller, and Ronald Parr. Multiagent planning with factored mdps. In Advances in neural information processing systems, pages 1523–1530, 2002. [30] Wendelin Böhmer, Vitaly Kurin, and Shimon Whiteson. Deep coordination graphs. In Proceedings of the 37th International Conference on Machine Learning, 2020. [31] Amanpreet Singh, Tushar Jain, and Sainbayar Sukhbaatar. Learning when to communicate at scale in multiagent cooperative and competitive tasks. In Proceedings of the International Conference on Learning Representations (ICLR), 2019. [32] Hangyu Mao, Wulong Liu, Jianye Hao, Jun Luo, Dong Li, Zhengchao Zhang, Jun Wang, and Zhen Xiao. Neighborhood cognition consistent multi-agent reinforcement learning. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 34, pages 7219–7226, 2020. [33] Tonghan Wang, Tarun Gupta, Anuj Mahajan, Bei Peng, Shimon Whiteson, and Chongjie Zhang. Rode: Learning roles to decompose multi-agent tasks. In Proceedings of the International Conference on Learning Representations (ICLR), 2021. [34] Ming Tan. Multi-agent reinforcement learning: Independent vs. cooperative agents. In Proceedings of the tenth international conference on machine learning, pages 330–337, 1993. [35] Changxi Zhu, Ho-fung Leung, Shuyue Hu, and Yi Cai. A q-values sharing framework for multiple independent q-learners. In Proceedings of the 18th International Conference on Autonomous Agents and MultiAgent Systems, pages 2324–2326, 2019. [36] Yongyuan Liang and Bangwei Li. Parallel knowledge transfer in multi-agent reinforcement learning. arXiv preprint arXiv:2003.13085, 2020. [37] Yonggan Fu, Zhongzhi Yu, Yongan Zhang, and Yingyan Lin. Auto-agent-distiller: Towards efficient deep reinforcement learning agents via neural architecture search. arXiv preprint arXiv:2012.13091, 2020. [38] Filippos Christianos, Lukas Schäfer, and Stefano Albrecht. Shared experience actor-critic for multi-agent reinforcement learning. Advances in Neural Information Processing Systems, 33, 2020. [39] Julien Roy, Paul Barde, Félix Harvey, Derek Nowrouzezahrai, and Chris Pal. Promoting coordination through policy regularization in multi-agent deep reinforcement learning. Advances in Neural Information Processing Systems, 33, 2020. [40] Filippos Christianos, Georgios Papoudakis, Arrasy Rahman, and Stefano V Albrecht. Scaling multi-agent reinforcement learning with selective parameter sharing. arXiv preprint arXiv:2102.07475, 2021. [41] Deepak Pathak, Pulkit Agrawal, Alexei A Efros, and Trevor Darrell. Curiosity-driven exploration by self-supervised prediction. In International Conference on Machine Learning, pages 2778– 2787, 2017. [42] Yuri Burda, Harrison Edwards, Amos Storkey, and Oleg Klimov. Exploration by random network distillation. arXiv preprint arXiv:1810.12894, 2018. [43] Adrià Puigdomènech Badia, Pablo Sprechmann, Alex Vitvitskyi, Daniel Guo, Bilal Piot, Steven Kapturowski, Olivier Tieleman, Martín Arjovsky, Alexander Pritzel, Andew Bolt, et al. Never give up: Learning directed exploration strategies. arXiv preprint arXiv:2002.06038, 2020. [44] Adrià Puigdomènech Badia, Bilal Piot, Steven Kapturowski, Pablo Sprechmann, Alex Vitvitskyi, Zhaohan Daniel Guo, and Charles Blundell. Agent57: Outperforming the atari human benchmark. In International Conference on Machine Learning, pages 507–517. PMLR, 2020. [45] Benjamin Eysenbach, Abhishek Gupta, Julian Ibarz, and Sergey Levine. Diversity is all you need: Learning skills without a reward function. In International Conference on Learning Representations, 2018. [46] Archit Sharma, Shixiang Gu, Sergey Levine, Vikash Kumar, and Karol Hausman. Dynamicsaware unsupervised discovery of skills. In International Conference on Learning Representations, 2020. [47] Víctor Campos, Alexander Trott, Caiming Xiong, Richard Socher, Xavier Giro-i Nieto, and Jordi Torres. Explore, discover and learn: Unsupervised discovery of state-covering skills. In International Conference on Machine Learning, pages 1317–1327. PMLR, 2020. [48] Tonghan Wang, Jianhao Wang, Wu Yi, and Chongjie Zhang. Influence-based multi-agent exploration. In Proceedings of the International Conference on Learning Representations (ICLR), 2020.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258# ReSSL: Relational Self-Supervised Learning with Weak Augmentation
Mingkai Zheng1,2 Shan $\mathbf { Y o u } ^ { 2 , 4 * }$ Fei Wang3 Chen Qian2 Changshui Zhang4 Xiaogang Wang2,5 Chang Xu1
1School of Computer Science, Faculty of Engineering, The University of Sydney 2SenseTime Research 3University of Science and Technology of China 4Department of Automation, Tsinghua University, Institute for Artificial Intelligence, Tsinghua University (THUAI), Beijing National Research Center for Information Science and Technology (BNRist) 5The Chinese University of Hong Kong
# Abstract
Self-supervised Learning (SSL) including the mainstream contrastive learning has achieved great success in learning visual representations without data annotations. However, most of methods mainly focus on the instance level information (i.e., the different augmented images of the same instance should have the same feature or cluster into the same class), but there is a lack of attention on the relationships between different instances. In this paper, we introduced a novel SSL paradigm, which we term as relational self-supervised learning (ReSSL) framework that learns representations by modeling the relationship between different instances. Specifically, our proposed method employs sharpened distribution of pairwise similarities among different instances as relation metric, which is thus utilized to match the feature embeddings of different augmentations. Moreover, to boost the performance, we argue that weak augmentations matter to represent a more reliable relation, and leverage momentum strategy for practical efficiency. Experimental results show that our proposed ReSSL significantly outperforms the previous stateof-the-art algorithms in terms of both performance and training efficiency. Code is available at https://github.com/KyleZheng1997/ReSSL
# 1 Introduction
Recently, self-supervised learning (SSL) has shown its superiority and achieved promising results for unsupervised visual representation learning in computer vision tasks [40, 27, 32, 6, 9, 47, 23, 24]. The purpose of a typical self-supervised learning algorithm is to learn general visual representations from a large amount of data without human annotations, which can be transferred or leveraged in downstream tasks (e.g., classification, detection, and segmentation). Some previous works [5, 23] even have proven that a good unsupervised pretraining can lead to a better downstream performance than supervised pretraining.
Among various SSL algorithms, contrastive learning [47, 45, 6] serves as a state-of-the-art framework, which mainly focuses on learning an invariant feature from different views. For example, instance discrimination is a widely adopted pre-text task as in [6, 24, 47], which utilizes the noisy contrastive estimation (NCE) to encourage two augmented views of the same image to be pulled closer on the embedding space but pushes apart all the other images away. Deep Clustering [4, 48, 5] is an alternative pre-text task that forces different augmented views of the same instance to be clustered into the same class. However, instance discrimination based methods will inevitably induce a class collision problem [1, 36, 10], where similar images should be pulled closer instead of being pushed away. Deep clustering based methods cooperated with traditional clustering algorithms to assign a label for each instance, which relaxed the constraint of instance discrimination, but most of these algorithms adopt a strong assumption, i.e., the labels must induce an equipartition of the data, which might introduce some noise and hurt the learned representations.
In this paper, we introduce a novel Relational Self-Supervised Learning framework (ReSSL), which does not encourage explicitly to push away different instances, but uses relation as a manner to investigate the inter-instance relationships and highlight the intra-instance invariance. Concretely, we aim to maintain the consistency of pairwise similarities among different instances for two different augmentations. For example, if we have three instances $\mathbf { x } ^ { 1 }$ , $\mathbf { x } ^ { 2 }$ , y and $\mathbf { z }$ where $\mathbf { x } ^ { 1 }$ , $\mathbf { x } ^ { 2 }$ are two different augmentations of $\mathbf { x }$ , $\mathbf { y }$ and $\mathbf { z }$ are different samples. Then, if $\mathbf { x } ^ { 1 }$ is similar to y but different to $\mathbf { z }$ , we wish $\bar { \mathbf { x } } ^ { 2 }$ can maintain such relationship and vice versa. In this way, the relation can be modelled as a similarity distribution between a set of augmented images, and then use it as a metric to align the same images with different augmentations, so that the relationship between different instances could be maintained across different views.
However, this simple manner induces unexpectedly horrible performance if we follow the same training recipe as other contrastive learning methods [6, 24]. We argue that construction of a proper relation matters for ReSSL; aggressive data augmentations as in [6, 7, 41] are usually leveraged by default to generate diverse positive pairs that increase the difficulty of the pre-text task. However, this hurts the reliability of the target relation. Views generated by aggressive augmentations might cause the loss of semantic information, so the target relation might be noisy and not that reliable. In this way, we propose to leverage weaker augmentations to represent the relation, since much lesser disturbances provide more stable and meaningful relationships between different instances. Besides, we also sharpen the target distribution to emphasize the most important relationship and utilize the memory buffer with a momentum-updated network to reduce the demand of large batch size for more efficiency. Experimental results on multiple benchmark datasets show the superiority of ReSSL in terms of both performance and efficiency. For example, with 200 epochs of pre-training, our ReSSL achieved $6 9 . 9 \%$ on ImageNet [14] linear evaluation protocol, which is $2 . 4 \%$ higher than our baseline method (MoCoV2 [8]). When working with the Multi-Crop strategy (200 epochs), ReSSL achieved new state-of-the-art $7 4 . 7 \%$ Top-1 accuracy, which is $1 . 4 \%$ higher than CLSA-Multi [46].
Our contributions can be summarized as follows.
• We proposed a novel SSL paradigm, which we term it as relational self-supervised learning (ReSSL). ReSSL maintains the relational consistency between the instances under different augmentations instead of explicitly pushing different instances away. • Our proposed weak augmentation and sharpening distribution strategy provide a stable and high quality target similarity distribution, which makes the framework works well. • ReSSL is a simple and effective SSL framework since it replaces the widely adopted contrastive loss with our proposed relational consistency loss. It achieved state-of-the-art performance under the same training cost.
# 2 Related Work
Self-Supervised Learning. Early works in self-supervised learning methods rely on all sorts of pretext to learn visual representations. For example, colorizing gray-scale images [50], image jigsaw puzzle [39], image super-resolution [34], image inpainting [19], predicting a relative offset for a pair of patches [16], predicting the rotation angle [35], and image reconstruction [2, 22, 3, 17]. Although these methods have shown their effectiveness, they lack the generality of the learned representations.
Instance Discrimination. The recent contrastive learning methods [32, 40, 6, 24, 41, 38, 29, 27, 30] have made a lot of progress in the field of self-supervised learning. Most of the previous contrastive learning methods are based on the instance discrimination [47] task in which positive pairs are defined as different views of the same image, while negative pairs are formed by sampling views from different images. SimCLR [6, 7] shows that image augmentation (e.g.Grayscale, Random Resized Cropping, Color Jittering, and Gaussian Blur), nonlinear projection head and large batch size plays a critical role in contrastive learning. Since large batch size usually requires a lot of GPU memory, which is not very friendly to most of researchers. MoCo [24, 8] proposed a momentum contrast mechanism that forces the query encoder to learn the representation from a slowly progressing key encoder and maintain a memory buffer to store a large number of negative samples. InfoMin [41] proposed a set of stronger augmentation that reduces the mutual information between views while keeping task-relevant information intact. AlignUniform [45] shows that alignment and uniformity are two critical properties of contrastive learning.
Deep Clustering. In contrast to instance discrimination which treats every instance as a distinct class, deep clustering [4] adopts the traditional clustering method (e.g.KMeans) to label each image iteratively. Eventually, similar samples will be clustered into the same class. Simply apply the KMeans algorithm might lead to a degenerate solution where all data points are mapped to the same cluster; SeLa [48] solved this issue by adding the constraint that the labels must induce equipartition of the data and proposed a fast version of the Sinkhorn-Knopp to achieve this. SwAV [5] further extended this idea and proposed a scalable online clustering framework. PCL [36] reveals the class collision problem and simply performed instance discrimination and unsupervised clustering simultaneously; although it gets the same linear classification accuracy with MoCoV2, it has better performance on downstream tasks.
Contrastive Learning Without Negatives. Most previous contrastive learning methods prevent the model collapse in an explicit manner (e.g. push different instances away from each other or force different instances to be clustered into different groups.) BYOL [23] can learn a high-quality representation without negatives. Specifically, it trains an online network to predict the target network representation of the same image under a different augmented view and using an additional predictor network on top of the online encoder to avoiding the model collapse. SimSiam [9] shows that simple Siamese networks can learn meaningful representations even without the use of negative pairs, large batch size, and momentum encoders.
# 3 Methodology
In this section, we will first revisit the preliminary work on contrastive learning; then, we will introduce our proposed relational self-supervised learning framework. After that, the algorithm and the implementation details will also be explained.
# 3.1 Preliminaries on Self-supervised Learning
Given $N$ unlabeled samples $\mathbf { x }$ , we randomly apply a composition of augmentation functions $T ( \cdot )$ to obtain two different views $\mathbf { x } ^ { 1 }$ and $\mathbf { x } ^ { 2 }$ through $T ( \mathbf { x } , \theta _ { 1 } ^ { \top } )$ and $T ( \mathbf { x } , \theta _ { 2 } )$ where $\theta$ is the random seed for $T$ . Then, a convolutional neural network based encoder $\mathcal F ( \cdot )$ is employed to extract the information from these samples, i.e., $\mathbf { h } = \mathcal { F } ( T ( \mathbf { x } , \theta ) )$ . Finally, a two-layer non-linear projection head $g ( \cdot )$ is utilized to map $\mathbf { h }$ into embedding space, which can be written as: ${ \mathbf z } = g ( { \mathbf h } )$ . SimCLR [6] and MoCo [24] style framework adopt the noise contrastive estimation (NCE) objective for discriminating different instances in the dataset. Suppose $\mathbf { z } _ { i } ^ { 1 }$ and $\mathbf { z } _ { i } ^ { 2 }$ are the representations of two augmented views of $\mathbf { x } _ { i }$ and $\mathbf { z } _ { k }$ is a different instance. The NCE objective can be expressed by Eq. (1), where the similarity function $s i m ( \cdot )$ represents the dot product between $L _ { 2 }$ normalized vectors $s i m ( \mathbf { u } , \mathbf { v } ) = \mathbf { u } ^ { T } \mathbf { v } / \| \mathbf { u } \| \| \mathbf { v } \|$ and $\tau$ is the temperature parameter.
$$\mathcal { L } _ { N C E } = - \log \frac { \exp ( s i m ( \mathbf { z } ^ { 1 } , \mathbf { z } ^ { 2 } ) / \tau ) } { \exp ( s i m ( \mathbf { z } _ { i } ^ { 1 } , \mathbf { z } _ { i } ^ { 2 } ) / \tau ) + \sum _ { k = 1 } ^ { N } \exp ( s i m ( \mathbf { z } _ { i } ^ { 1 } , \mathbf { z } _ { k } ) / \tau ) } .$$
BYOL [23] and SimSiam [9] style framework add an additional non-linear predictor head $q ( \cdot )$ which further maps $\mathbf { z }$ to $\mathbf { p }$ . The model will minimize the negative cosine similarity (equivalent to minimize the L2 distance) between $\mathbf { z }$ to $\mathbf { p }$ .
$$\mathcal { L } _ { c o s } = - \frac { \mathbf { p } ^ { 1 } } { \Vert \mathbf { p } ^ { 1 } \Vert } \cdot \frac { \mathbf { z } ^ { 2 } } { \Vert \mathbf { z } ^ { 2 } \Vert } , \qquad \mathcal { L } _ { m s e } = \Vert \mathbf { p } ^ { 1 } - \mathbf { z } ^ { 2 } \Vert _ { 2 } ^ { 2 } .$$
Tricks like stop-gradient and momentum teacher are often applied to avoid model collapsing.
# 3.2 Relational Self-Supervised Learning
In classical self-supervised learning, different instances are to be pushed away from each other, and augmented views of the same instance is expected to be of exactly the same features. However, both constrains are too restricted because of the existence of similar samples and the distorted semantic information if aggressive augmentation is adopted. In this way, we do not encourage explicit negative instances (those to be pushed away) for each instance; instead, we leverage the pairwise similarities as a manner to explore their relationships. And we pull the features of two different augmentations in this sense of relation metric. As a result, our method relaxes both (1) and (2), where different instances do not always need to be pushed away from each other; and augmented views of the same instance only need to share the similar but not exactly the same features.
 Figure 1: The overall framework of our proposed method. We adopt the student-teacher framework where the student is trained to predict the representation of the teacher, and the teacher is updated with a “momentum update” (exponential moving average) of the student. The relationship consistency is achieve by align the conditional distribution for student and teacher model. Please see more details in our method part.
Concretely, given a image $\mathbf { x }$ in a batch of samples , two different augmented views can be obtained by $\mathbf { x } ^ { 1 } = \mathbf { \check { \Gamma } } T ( \mathbf { x } , \theta _ { 1 } )$ , $\mathbf { x } ^ { 2 } = T ( \mathbf { x } , \theta _ { 2 } )$ and calculate the corresponds embedding $\mathbf { z } ^ { 1 } = g ( \mathcal { F } ( \mathbf { x } ^ { 1 } ) )$ , $\mathbf { z } ^ { 2 } = g ( \mathcal { F } ( \mathbf { x } ^ { 2 } ) )$ . Then, we calculate the similarities between the instances of the first augmented images. Which can be measured by $s i m ( \mathbf { z } ^ { 1 } , \mathbf { z } _ { i } )$ . A softmax layer can be adopted to process the calculated similarities, which then produces a relationship distribution:
$${ \bf p } _ { i } ^ { 1 } = \frac { \exp ( s i m ( { \bf z } ^ { 1 } , { \bf z } _ { i } ) / \tau _ { t } ) } { \sum _ { k = 1 } ^ { K } \exp ( s i m ( { \bf z } ^ { 1 } , { \bf z } _ { k } ) / \tau _ { t } , ) } .$$
where $\tau _ { t }$ is the temperature parameter. At the same time, we can calculate the relationship between $\mathbf { x } ^ { 2 }$ and the $i$ -th instance as $s i m ( \mathbf { z } ^ { 2 } , \mathbf { z } _ { i } )$ . The resulting relationship distribution can be written as:
$${ { \bf { p } } _ { i } ^ { 2 } } = \frac { { \exp ( { s i m ( { { \bf { z } } ^ { 2 } } , { \bf { z } } _ { i } ) / { \tau _ { s } } } ) } } { { \sum _ { k = 1 } ^ { K } { \exp ( { s i m ( { { \bf { z } } ^ { 2 } } , { \bf { z } } _ { k } ) / { \tau _ { s } } } , ) } } } .$$
where $\tau _ { s }$ is a different temperature parameter. We propose to push the relational consistency between $p _ { i } ^ { 1 }$ and $p _ { i } ^ { 2 }$ by minimizing the Kullback–Leibler divergence, which can be formulated as:
$$\mathcal { L } _ { r e l a t i o n } = D _ { K L } ( \mathbf { p } ^ { 1 } | | \mathbf { p } ^ { 2 } ) = H ( \mathbf { p } ^ { 1 } , \mathbf { p } ^ { 2 } ) - H ( \mathbf { p } ^ { 1 } ) .$$
Since the $\mathbf { p } ^ { 1 }$ will only be used as a target, we only minimize $H ( \mathbf { p } ^ { 1 } , \mathbf { p } ^ { 2 } )$ in our implementation.
More efficiency with Momentum targets. However, the quality of the target similarity distribution $\mathbf { p } ^ { 1 }$ is crucial, to make the similarity distribution reliable and stable, we usually require a large batch size which is very unfriendly to GPU memories. To resolve this issue, we utilize a “momentum update" network as in [24, 8], and maintain a large memory buffer $\mathcal { Q }$ of $K$ past samples $\{ { \bf { z } } _ { k } | k = $ $1 , . . . , K \}$ (following the FIFO principle) for storing the feature embeddings from the past batches, which can then be used for simulating the large batch size relationship and providing a stable similarity distribution.
$$\mathcal { F } _ { t } \gets m \mathcal { F } _ { t } + ( 1 - m ) \mathcal { F } _ { s } , \quad g _ { t } \gets m g _ { t } + ( 1 - m ) g _ { s } ,$$
where $\mathcal { F } _ { s }$ and $g _ { s }$ denote the most latest encoder and head, respectively, so we name them as the student model with a subscript $s$ . On the other hand, $\mathcal { F } _ { t }$ and $g _ { t }$ stand for ensembles of the past encoder and head, respectively, so we name them as the teacher model with a subscript $t , m$ represents the momentum coefficient which controls how fast the teacher $\mathcal { F } _ { t }$ will be updated.
Sharper Distribution as Target. Note, the value of $\tau _ { t }$ has to be smaller than $\tau _ { s }$ since $\tau _ { t }$ will be used to generate the target distribution. A smaller $\tau$ will result in a “sharper" distribution which can be interpreted as highlight the most similar feature for $\mathbf { z } ^ { 1 }$ . Align $ { \mathbf { p } } ^ { 2 }$ with $\mathbf { p } ^ { 1 }$ can be regarded as pulling $\mathbf { z } ^ { 2 }$ towards the features that are similar with $\mathbf { z } ^ { 1 }$ .
Weak Augmentation Strategy for Teacher. To further improve the quality and stability of the target distribution, we adopt a weak augmentation strategy for the teacher model since the standard contrastive augmentation is too aggressive, which introduced too many disturbances and will mislead the student network. Please refer to more details in our empirical study.
Compare with SEED and CLSA. SEED [21] follows the standard Knowledge Distillation (KD) paradigm [26, 49, 18] where it aims to distill the knowledge from a larger network into a smaller architecture. The knowledge transfer happens in the same view but between different models. In our framework, we are trying to maintain the relational consistency between different augmentations; the knowledge transfer happens between different views but in the same network. CLSA [46] also introduced the concept of using weak augmentation to guide a stronger augmentation. However, the “weak" augmentation in CLSA is equivalent to the “strong" augmentation in our method (We do not use any stronger augmentations such as [12, 13]). On the other hand, CLSA still adopts the InfoNCE loss (1) for instance discrimination, where our proposed method only utilized the relational consistency loss (5). Finally, CLSA requires at least one additional sample during training, which will slow down the training speed.
# Algorithm 1: Relational Self-supervised Learning with Weak Augmentation (ReSSL)
<table><tr><td colspan="2">the non-linear projection head for teacher and student. Q: the memory buffer while network not converge do for i=1 to step do Fetch x from current batch B z1=gt(Ft(Tw(x,01)))); z²=gs(Fs(Tc(x,02));</td></tr><tr><td colspan="2">p1 = SoftMax(z1QT/ Tt); p² =SoftMax(z²QT / Ts); // Eq.(3)(4) Calculate Lrelation loss by CrossEntropy(p1,p²) ; // Eq.(5) Update Fs and gs with loss Lrelation Update Ft and gt by Ft ← mFt +(1-m)Fs,gt ←mgt+(1-m)gs ; // Eq.</td></tr></table>
# 4 Empirical Study
In this section, we will empirically study our proposed method on 4 popular self-supervised learning benchmarks and compare to previous state-of-the-art algorithms (SimCLR [6], BYOL [23], SimSiam [9], MoCoV2 [8]).
Small Dataset. CIFAR-10 and CIFAR-100 [31]. The CIFAR-10 dataset consists of $6 0 0 0 0 \ 3 2 { \mathrm { x } } 3 2$ colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images. CIFAR-100 is just like the CIFAR-10, except it has 100 classes containing 600 images each. There are 500 training images and 100 testing images per class.
Medium Dataset. STL-10 [11] and Tiny ImageNet [33]. STL10 [11] dataset is composed of $9 6 \mathbf { x } 9 6$ resolution images of 10 classes, 5K labeled training images, 8K validation images, and 100K unlabeled images. The Tiny ImageNet dataset is composed of $6 4 \mathrm { x } 6 4$ resolution images of 200 classes with 100K training images and 10k validation images.
Implementation Details We adopt the ResNet18 [25] as our backbone network. Because most of our dataset contains low-resolution images, we replace the first $7 \mathbf { x } 7$ Conv of stride 2 with $3 { \tt X } 3$ Conv of stride 1 and remove the first max pooling operation for a small dataset. For data augmentations, we use the random resized crops (the lower bound of random crop ratio is set to 0.2), color distortion (strength $= 0 . 5$ ) with a probability of 0.8, and Gaussian blur with a probability of 0.5. The images from the small and medium datasets will be resized to $3 2 \mathrm { x } 3 2 $ and 64x64 resolution respectively. Our method is based on MoCoV2 [8]; in order to simulate the shuffle BN trick on one GPU, we simply divide a batch of data into different groups and then calculate BN statistics within each group. The momentum value and memory buffer size are set to 0.99/0.996 and 4096/16384 for small and medium datasets respectively. Moreover, The model is trained using SGD optimizer with a momentum of 0.9 and weight decay of $5 e ^ { - 4 }$ . We linear warm up the learning rate for 5 epochs until it reaches $0 . 0 6 \times B a t c h S i z e / 2 5 6$ , then switch to the cosine decay scheduler [37].
Table 1: Compare to other SSL algorithms on small and medium dataset.
<table><tr><td>Method</td><td>BackProp</td><td>EMA</td><td>CIFAR-10</td><td>CIFAR-100</td><td>STL-10</td><td>Tiny ImageNet</td></tr><tr><td>Supervised</td><td>1</td><td>-</td><td>94.22</td><td>74.66</td><td>82.55</td><td>59.26</td></tr><tr><td>SimCLR [6]</td><td>2x</td><td>No</td><td>84.92</td><td>59.28</td><td>85.48</td><td>44.38</td></tr><tr><td>BYOL [23]</td><td>2x</td><td>Yes</td><td>85.82</td><td>57.75</td><td>87.45</td><td>42.70</td></tr><tr><td>SimSiam [9]</td><td>2x</td><td>No</td><td>88.51</td><td>60.00</td><td>87.47</td><td>37.04</td></tr><tr><td>MoCoV2 [8]</td><td>1x</td><td>Yes</td><td>86.18</td><td>59.51</td><td>85.88</td><td>43.36</td></tr><tr><td>ReSSL (Ours)</td><td>1x</td><td>Yes</td><td>90.20</td><td>63.79</td><td>88.25</td><td>46.60</td></tr></table>
Evaluation Protocol. All the models will be trained for 200 epochs. For testing the representation quality, we evaluate the pre-trained model on the widely adopted linear evaluation protocol - We will freeze the encoder parameters and train a linear classifier on top of the average pooling features for 100 epochs. To test the classifier, we use the center crop of the test set and computes accuracy according to predicted output. We train the classifier with a learning rate of 30, no weight decay, and momentum of 0.9. The learning rate will be times 0.1 in 60 and 80 epochs. Note, for STL-10; the pretraining will be applied on both labeled and unlabeled images. During the linear evaluation, only the labeled 5K images will be used.
Result. As we can see the result in Table 1, our proposed method outperforms the previous method on all four benchmarks. Reminder, most of the previous method requires twice back-propagation, which results in a much higher training cost than MoCoV2 and our method.
# 4.1 A Properly Sharpened Relation is A Better Target
The temperature parameter is very crucial in most contrastive learning algorithms. To verify the effective of $\tau _ { s }$ and $\tau _ { t }$ for our proposed method, we fixed $\tau _ { s } = 0 . 1$ or 0.2, and sweep over $\tau _ { t } =$ $\{ 0 . 0 1 , 0 . 0 2 , . . . , 0 . 0 7 \}$ . The result is shown in Table 2. For $\tau _ { t }$ , the optimal value is either 0.04 or 0.05 across all different datasets. As we can see, the performance is increasing when we increase $\tau _ { t }$ from 0 to 0.04 and 0.05. After that, the performance will start to decrease. Note, $\tau _ { t } \to 0$ correspond to the Top-1 or argmax operation which produce a one-hot distribution as the target. On the other hand, when $\tau _ { t } 0 . 1$ , the target will be a much flatter distribution that cannot highlight the most similar features for students. Hence, $\tau _ { t }$ can not be either too small or too large, but it has to be smaller than $\tau _ { s }$ $\mathbf { \bar { p } } ^ { 1 }$ has to be sharper than $ { \mathbf { p } } ^ { 2 }$ ) so that the target distribution can provide effective guidance to the student model.
Table 2: Effect of different $\tau _ { t }$ and $\tau _ { s }$ for ReSSL
<table><tr><td>Dataset</td><td>Ts</td><td>Tt =0.01</td><td>Tt =0.02</td><td>Tt=0.03</td><td>Tt = 0.04</td><td>Tt=0.05</td><td>Tt =0.06</td><td>Tt = 0.07</td></tr><tr><td>CIFAR-10</td><td>0.1</td><td>89.35</td><td>89.74</td><td>90.09</td><td>90.04</td><td>90.20</td><td>90.18</td><td>88.67</td></tr><tr><td>CIFAR-10</td><td>0.2</td><td>89.52</td><td>89.67</td><td>89.24</td><td>89.50</td><td>89.22</td><td>89.40</td><td>89.50</td></tr><tr><td>CIFAR-100</td><td>0.1</td><td>62.34</td><td>62.79</td><td>62.71</td><td>63.79</td><td>63.46</td><td>63.20</td><td>61.31</td></tr><tr><td>CIFAR-100</td><td>0.2</td><td>60.37</td><td>60.05</td><td>60.24</td><td>60.09</td><td>59.09</td><td>59.12</td><td>59.76</td></tr><tr><td>STL-10</td><td>0.1</td><td>86.65</td><td>86.96</td><td>87.16</td><td>87.32</td><td>88.25</td><td>87.83</td><td>87.08</td></tr><tr><td>STL-10</td><td>0.2</td><td>85.17</td><td>86.12</td><td>85.01</td><td>85.67</td><td>85.21</td><td>85.51</td><td>85.28</td></tr><tr><td>Tiny ImageNet</td><td>0.1</td><td>45.20</td><td>45.40</td><td>46.30</td><td>46.60</td><td>45.08</td><td>45.24</td><td>44.18</td></tr><tr><td>Tiny ImageNet</td><td>0.2</td><td>43.28</td><td>42.98</td><td>43.58</td><td>42.12</td><td>42.70</td><td>42.76</td><td>42.60</td></tr></table>
For $\tau _ { t }$ , it is clearly to see that the result of $\tau _ { s } = 0 . 1$ can always result a much higher performance than $\tau _ { s } = 0 . 2$ , which is different to $\mathbf { M o C o V } 2$ where $\tau _ { s } = 0 . 2$ is the optimal value. According to [43, 44, 15], a greater temperature will result in a larger angular margin in the hypersphere. Since MoCoV2 adopts instance discrimination as the pretext task, a large temperature can enhance the compactness for the same instance and discrepancy for different instances. In contrast to instance discrimination, our method can be interpreted as pulling similar instances closer on the hypersphere; when the ground truth label is not available, the large angular margin might hurt the performance.
 Figure 2: Visualization of the 10 nearest neighbour of the query image. The top half is the result when we apply the weak augmentation. The bottom half is the case when the typical contrastive augmentation is adopted. Note, we use the red square to highlight the images that has different ground truth label with the query image.
# 4.2 Weak Augmentation Makes Better Relation
As we have mentioned, the weaker augmentation strategy for the teacher model is the key to the success of our framework. Here, We implement the weak augmentation as a random resized crop (the random ratio is set to $( 0 . 2 , 1 )$ ) and a random horizontal flip. For temperature parameter, we simply adopt the same setting as in Table 2 and report the performance of the best setting. The result is shown in Table 3, as we can see that when we use the weak augmentation for the teacher model, the performance is significantly boosted across all datasets. We believe that this phenomenon is because relatively small disturbances in the teacher model can provide more accurate similarity guidance to the student model. To further verify this hypothesis, we random sampled three image from STL-10 training set as the query images, and then find the 10 nearest neighbour based on the weak / contrastive augmented query. We visualized the result in Figure 2,
Table 3: Effect of weak augmentation guided ReSSL
<table><tr><td>Teacher Aug</td><td>Student Aug</td><td>CIFAR-10</td><td>CIFAR-100</td><td>STL-10</td><td>Tiny ImageNet</td></tr><tr><td>Contrastive</td><td>Contrastive</td><td>86.17</td><td>57.60</td><td>84.71</td><td>40.38</td></tr><tr><td>Weak</td><td>Contrastive</td><td>90.20</td><td>63.79</td><td>88.25</td><td>46.60</td></tr></table>
# 4.3 More Experiments on Weak Augmentation
Since the weak augmentation for the teacher model is one of the crucial points in ReSSL, we further analyze the effect of applying different augmentations on the teacher model. In this experiment, we simply set $\tau _ { t } = 0 . 0 4$ and report the linear evaluation performance on the Tiny ImageNet dataset. The results are shown in Table 4. The first row is the baseline, where we simply resize all images to the same resolution (no extra augmentation is applied). Then, we applied random resized crops, random flip, color jitter, grayscale, gaussian blur, and various combinations. We empirically find that if we use no augmentation (e.g., no random resized crops) for the teacher model, the performance tends to degrade. This might result from that the gap of features between two views is way too smaller, which undermines the learning of representations. However, too strong augmentations of teacher model will introduce too much noise and make the target distribution inaccurate (see Figure 2). Thus mildly weak augmentations are better option for the teacher, and random resized crops with random flip is the combination with the highest performance as Table 4 shows.
Table 4: Effect of different augmentation for teacher model (Tiny ImageNet)
<table><tr><td>Random Resized Crops</td><td>Random Flip</td><td>Color Jitter</td><td>GrayScale</td><td>Gaussian Blur</td><td>Acc</td></tr><tr><td></td><td></td><td></td><td></td><td></td><td>31.74</td></tr><tr><td>√</td><td></td><td></td><td></td><td></td><td>46.00</td></tr><tr><td></td><td>√</td><td></td><td></td><td></td><td>30.98</td></tr><tr><td></td><td></td><td>√</td><td></td><td></td><td>29.46</td></tr><tr><td></td><td></td><td></td><td>√</td><td></td><td>29.68</td></tr><tr><td></td><td></td><td></td><td></td><td>√</td><td>30.10</td></tr><tr><td>√</td><td>√</td><td></td><td></td><td></td><td>46.60</td></tr><tr><td>√</td><td></td><td>√</td><td></td><td></td><td>44.44</td></tr><tr><td>√</td><td></td><td></td><td>4</td><td></td><td>42.28</td></tr><tr><td>√</td><td></td><td></td><td></td><td>√</td><td>44.88</td></tr><tr><td>√</td><td>√</td><td>√</td><td></td><td></td><td>43.70</td></tr><tr><td>√</td><td>√</td><td></td><td></td><td></td><td>42.28</td></tr><tr><td>√</td><td>√</td><td></td><td></td><td>√</td><td>44.52</td></tr></table>
# 4.4 Dimension of the Relation
Since we also adopt the memory buffer as in MoCo [24], the buffer size will be equivalent to the dimension of the distribution $\mathbf { p } ^ { 1 } \mathbf { p } ^ { 2 }$ . Thus, it will be one of the crucial points in our framework. To verify the effect the memory buffer size, we simply keep $\tau _ { s } = 0 . 1$ and $\tau _ { t } = 0 . 0 4$ , then varying the memory buffer size from 256 to 32768. The result is shown in Table 5, as we can see that a larger memory buffer can significantly boost the performance. However, a further increase in the buffer size can only bring a marginal improvement when the buffer is large enough.
Table 5: Effect of different memory buffer size on small and medium dataset
<table><tr><td>Dataset (Small) CIFAR-10</td><td>K=256 89.37</td><td>K=512 89.53</td><td>K= 1024 89.83</td><td>K= 4096 90.04</td><td>K=8192 90.15</td><td>K=16384 90.35</td></tr><tr><td>CIFAR-100 Dataset (Medium)</td><td>61.17 K=256</td><td>62.47 K=1024</td><td>63.20 K = 4096</td><td>63.79 K=8192</td><td>63.84 K=16384</td><td>64.06 K=32768</td></tr><tr><td>STL-10</td><td>85.88</td><td>87.23</td><td>87.72</td><td>87.42</td><td>87.32</td><td>87.47</td></tr><tr><td>Tiny ImageNet</td><td>43.08</td><td>45.32</td><td>45.78</td><td>45.42</td><td>46.60</td><td>46.48</td></tr></table>
# 4.5 Visualization of Learned Representations
We also show the t-SNE [42] visualizations of the representations learned by our proposed method and MoCov2 on the training set of CIFAR-10. Our proposed relational consistency loss leads to better class separation than the contrastive loss.
 Figure 3: t-SNE visualizations on CIFAR-10. Classes are indicated by colors.
# 5 Results on Large-scale Datasets
We also performed our algorithm on the large-scale ImageNet-1k dataset [14]. In the experiments, we adopt a learning rate of $0 . 0 5 * B a t c h S i z e / 2 5 6$ , a memory buffer size of $1 3 0 \mathrm { k }$ , and a 2-layer non-linear projection head with a hidden dimension 4096 and output dimension 512. For $\tau _ { t }$ and $\tau _ { s }$ , we simply adopt the best setting from Table 2 where $\tau _ { t } = 0 . 0 4$ and $\tau _ { s } = 0 . 1$ .
Linear Evaluation. For the linear evaluation of ImageNet-1k, we strictly follow the setting in SwAV [5]. The results are shown in Table 6. As we can see clearly that ReSSL consistently outperforms previous methods on both $1 \mathbf { x }$ and $2 \mathbf { x }$ backprop setting. (Please noted that the student network will be passed in one $2 2 4 \mathbf { x } 2 2 4$ augmented view and two $2 2 4 \mathbf { x } 2 2 4$ augmented views for 1x backprob and $2 \mathbf { x }$ backprob setting respectively.)
Table 6: Top-1 accuracy under the linear evaluation on ImageNet with the ResNet-50 backbone. The table compares the methods over 200 epochs of pretraining.
<table><tr><td>Method Supervised</td><td>Arch R50</td><td>Backprop 1x</td><td>EMA No</td><td>Batch Size 256</td><td>Param 24</td><td>Epochs 120</td><td>Top-1 76.5</td></tr><tr><td>1xBackpropMethods</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>InstDisc [47]</td><td>R50</td><td>1x</td><td>No</td><td>256</td><td>24</td><td>200</td><td>58.5</td></tr><tr><td>LocalAgg [52]</td><td>R50</td><td>1x</td><td>No</td><td>128</td><td>24</td><td>200</td><td>58.8</td></tr><tr><td>MoCo v2 [8]</td><td>R50</td><td>1x</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>67.5</td></tr><tr><td>MoCHi [30]</td><td>R50</td><td>1x</td><td>Yes</td><td>512</td><td>24</td><td>200</td><td>68.0</td></tr><tr><td>CPC v2 [32]</td><td>R50</td><td>1x</td><td>No</td><td>512</td><td>24</td><td>200</td><td>63.8</td></tr><tr><td>PCL v2 [36]</td><td>R50</td><td>1x</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>67.6</td></tr><tr><td>AdCo [28]</td><td>R50</td><td>1x</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>68.6</td></tr><tr><td>ReSSL (Ours)</td><td>R50</td><td>1x</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>69.9</td></tr><tr><td>2xBackprop Methods</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr><td>CLSA-Single [46]</td><td>R50</td><td>2x</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>69.4</td></tr><tr><td>SimCLR [6]</td><td>R50</td><td>2x</td><td>No</td><td>4096</td><td>24</td><td>200</td><td>66.8</td></tr><tr><td>SwAV [5]</td><td>R50</td><td>2x</td><td>No</td><td>4096</td><td>24</td><td>200</td><td>69.1</td></tr><tr><td>SimSiam [23]</td><td>R50</td><td>2x</td><td>No</td><td>256</td><td>24</td><td>200</td><td>70.0</td></tr><tr><td>BYOL[23]</td><td>R50</td><td>2x</td><td>Yes</td><td>4096</td><td>24</td><td>200</td><td>70.6</td></tr><tr><td>WCL [51]</td><td>R50</td><td>2x</td><td>No</td><td>4096</td><td>24</td><td>200</td><td>70.3</td></tr><tr><td>ReSSL (Ours)</td><td>R50</td><td>2x</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>71.4</td></tr></table>
Working with Multi-Crop Strategy. We also performed ReSSL with Multi-Crop strategy. The result is shown below in Table 7. Specifically, the result of 4 crops is trained with the resolution of $2 2 4 \times 2 2 4$ , $1 6 0 \times 1 6 0$ , $1 2 8 \times 1 2 8$ , $9 6 \times 9 6$ . For the result of 5 crops, we add an additional $1 9 2 \times 1 9 2$ image which is exactly the same with AdCo [28]. As we can see, our proposed ReSSL is significantly better than previous state-of-the-art methods.
Table 7: Working with Multi-Crop Strategy (Linear Evaluation on ImageNet)
<table><tr><td>Method</td><td>Arch</td><td>EMA</td><td>Batch Size</td><td>Param</td><td>Epochs</td><td>Top-1</td></tr><tr><td>SwAV [5]</td><td>R50</td><td>No</td><td>256</td><td>24</td><td>200</td><td>72.7</td></tr><tr><td>AdCo [28]</td><td>R50</td><td>No</td><td>256</td><td>24</td><td>200</td><td>73.2</td></tr><tr><td>CLSA-Multi [46]</td><td>R50</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>73.3</td></tr><tr><td>ReSSL (4 crops)</td><td>R50</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>73.8</td></tr><tr><td>ReSSL (5 crops)</td><td>R50</td><td>Yes</td><td>256</td><td>24</td><td>200</td><td>74.7</td></tr></table>
Working with Smaller Architecture. We also applied our proposed method on the smaller architecture (ResNet-18). The result is shown in Table 8. Following the same training recipe of the ResNet-50 in above, our proposed method has a higher performance than SEED [21] without a larger pretrained teacher network.
Table 8: Experiments on ResNet-18 (Linear Evaluation on ImageNet)
<table><tr><td>Method</td><td>Epochs</td><td>Student</td><td>Teacher</td><td>Acc</td></tr><tr><td>MoCo v2</td><td>200</td><td>ResNet-18</td><td>EMA</td><td>52.2</td></tr><tr><td>SEED</td><td>200</td><td>ResNet-18</td><td>ResNet-50 (MoCoV2)</td><td>57.6</td></tr><tr><td>ReSSL (1x backprop)</td><td>200</td><td>ResNet-18</td><td>EMA</td><td>58.1</td></tr></table>
Low-shot Classification. We further evaluate the quality of the learned representations by transferring them to other datasets. Following [36], we perform linear classification on the PASCAL
VOC2007 dataset [20]. Specifically, we resize all images to 256 pixels along the shorter side and taking a $2 2 4 \times 2 2 4$ center crop. Then, we train a linear SVM on top of corresponding global average pooled final representations. To study the transferability of the representations in few-shot scenarios, we vary the number of labeled examples $K$ and report the mAP. Table 9 shows the comparison between our method with previous works. We report the average performance over 5 runs (except for $\mathbf { k } =$ full).It’s clearly to see that our proposed method is consistently outperform MoCo v2 and PCL v2 across all different $K$ .
Table 9: Transfer learning on low-shot image classification
<table><tr><td>Method Random</td><td>Epochs 1</td><td>ImageNet 1</td><td>K=16 10.10</td><td>K=32 11.34</td><td>K=64 11.96</td><td>Full 12.42</td></tr><tr><td>Supervised</td><td>90</td><td>76.1</td><td>82.26</td><td>84.00</td><td>85.13</td><td>87.27</td></tr><tr><td>MoCo V2 [8]</td><td>200</td><td>67.5</td><td>76.14</td><td>79.16</td><td>81.52</td><td>84.60</td></tr><tr><td>PCL V2 [36]</td><td>200</td><td>67.5</td><td>78.34</td><td>80.72 81.96</td><td>82.67</td><td>85.43</td></tr><tr><td>ReSSL (1x backprob)</td><td>200</td><td>69.9</td><td>79.17</td><td></td><td>83.81</td><td>86.31</td></tr></table>
Semi-Supervised Learning. Next, we evaluate the performance obtained when fine-tuning the model representation using a small subset of labeled data. In this experiments, we adopt our 5 crops pre-trained model. The result is shown in Table 10. Notably, with just 200 epochs of pre-training, ReSSL outperforms all previous methods.
Table 10: Semi-supervised Learning
<table><tr><td>Method</td><td>Epochs</td><td>Linear Eval</td><td>1% Labels</td><td>10% Labels</td></tr><tr><td>SimCLR [6]</td><td>1000</td><td>69.3</td><td>48.3</td><td>65.6</td></tr><tr><td>BYOL[23]</td><td>1000</td><td>74.3</td><td>53.2</td><td>68.6</td></tr><tr><td>SwAV[5]</td><td>800</td><td>75.3</td><td>53.9</td><td>70.2</td></tr><tr><td>ReSSL (5 crops)</td><td>200</td><td>74.7</td><td>57.9</td><td>70.4</td></tr></table>
# 6 Conclusion
In this work, we propose relational self-supervised learning (ReSSL), a new paradigm for unsupervised visual representation learning framework that maintains the relational consistency between instances under different augmentations. Our proposed ReSSL relaxes the typical constraints in contrastive learning where different instances do not always need to be pushed away on the embedding space, and the augmented views do not need to share exactly the same feature. An extensive empirical study shows the effect of each component in our framework. The experiments on large-scaled datasets demonstrate the efficiency and state-of-the-art performance for unsupervised representation learning.
# Broader Impact
This work provides a technical advancement in the field of unsupervised visual representation learning. An immediate application of this work is to give a pre-trained model for the tasks where the data annotation is very hard to collect (e.g.medical images and fine-grained images.) Moreover, the most significant advantage of ReSSL is that we do not need to train the model for a long time as the previous method (generally 800 or 1000 epochs), which will cause a lot of carbon dioxide emissions. We believe ReSSL is a more environment-friendly method since it can achieve a competitive performance with much lesser training costs.
# Acknowledgment
This work is funded by the National Key Research and Development Program of China (No. 2018AAA0100701) and the NSFC 61876095. Chang Xu was supported in part by the Australian Research Council under Projects DE180101438 and DP210101859. Shan You is supported by Beijing Postdoctoral Research Foundation.
# References
[1] S. Arora, Hrishikesh Khandeparkar, M. Khodak, Orestis Plevrakis, and Nikunj Saunshi. A theoretical analysis of contrastive unsupervised representation learning. ArXiv, abs/1902.09229, 2019. 2 [2] Pierre Baldi. Autoencoders, unsupervised learning and deep architectures. In Proceedings of the 2011 International Conference on Unsupervised and Transfer Learning Workshop - Volume 27, UTLW’11, page 37–50. JMLR.org, 2011. 2 [3] A. Brock, J. Donahue, and K. Simonyan. Large scale gan training for high fidelity natural image synthesis. ArXiv, abs/1809.11096, 2019. 2 [4] Mathilde Caron, Piotr Bojanowski, Armand Joulin, and Matthijs Douze. Deep clustering for unsupervised learning of visual features. In European Conference on Computer Vision, 2018. 1, 3 [5] Mathilde Caron, Ishan Misra, Julien Mairal, Priya Goyal, Piotr Bojanowski, and Armand Joulin. Unsupervised learning of visual features by contrasting cluster assignments. 2020. 1, 3, 9, 10 [6] Ting Chen, Simon Kornblith, Mohammad Norouzi, and Geoffrey Hinton. A simple framework for contrastive learning of visual representations. arXiv preprint arXiv:2002.05709, 2020. 1, 2, 3, 5, 6, 9, 10 [7] Ting Chen, Simon Kornblith, Kevin Swersky, Mohammad Norouzi, and Geoffrey Hinton. Big selfsupervised models are strong semi-supervised learners. arXiv preprint arXiv:2006.10029, 2020. 2 [8] Xinlei Chen, Haoqi Fan, Ross Girshick, and Kaiming He. Improved baselines with momentum contrastive learning. arXiv preprint arXiv:2003.04297, 2020. 2, 4, 5, 6, 9, 10 [9] Xinlei Chen and Kaiming He. Exploring simple siamese representation learning. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 15750–15758, 2021. 1, 3, 5, 6 [10] Ching-Yao Chuang, Joshua Robinson, Yen-Chen Lin, Antonio Torralba, and Stefanie Jegelka. Debiased contrastive learning. In H. Larochelle, M. Ranzato, R. Hadsell, M. F. Balcan, and H. Lin, editors, Advances in Neural Information Processing Systems, volume 33, pages 8765–8775. Curran Associates, Inc., 2020. 2 [11] Adam Coates, Andrew Ng, and Honglak Lee. An analysis of single-layer networks in unsupervised feature learning. volume 15 of Proceedings of Machine Learning Research, pages 215–223, Fort Lauderdale, FL, USA, 11–13 Apr 2011. JMLR Workshop and Conference Proceedings. 5 [12] Ekin D Cubuk, Barret Zoph, Dandelion Mane, Vijay Vasudevan, and Quoc V Le. Autoaugment: Learning augmentation policies from data. arXiv preprint arXiv:1805.09501, 2018. 5 [13] Ekin D Cubuk, Barret Zoph, Jonathon Shlens, and Quoc V Le. Randaugment: Practical automated data augmentation with a reduced search space. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops, pages 702–703, 2020. 5 [14] J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li, and L. Fei-Fei. ImageNet: A Large-Scale Hierarchical Image Database. In CVPR09, 2009. 2, 8 [15] Jiankang Deng, J. Guo, and S. Zafeiriou. Arcface: Additive angular margin loss for deep face recognition. 2019 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), pages 4685–4694, 2019. 6 [16] Carl Doersch, Abhinav Gupta, and Alexei A. Efros. Unsupervised visual representation learning by context prediction. In International Conference on Computer Vision (ICCV), 2015. 2 [17] J. Donahue and K. Simonyan. Large scale adversarial representation learning. In NeurIPS, 2019. 2 [18] Shangchen Du, Shan You, Xiaojie Li, Jianlong Wu, Fei Wang, Chen Qian, and Changshui Zhang. Agree to disagree: Adaptive ensemble knowledge distillation in gradient space. Advances in Neural Information Processing Systems, 33, 2020. 5 [19] Omar ElHarrouss, Noor Almaadeed, S. Al-Máadeed, and Y. Akbari. Image inpainting: A review. Neural Processing Letters, 51:2007–2028, 2019. 2 [20] Mark Everingham, Luc Van Gool, Christopher KI Williams, John Winn, and Andrew Zisserman. The pascal visual object classes (voc) challenge. International journal of computer vision, 88(2):303–338, 2010. 10 [21] Zhiyuan Fang, Jianfeng Wang, Lijuan Wang, Lei Zhang, Yezhou Yang, and Zicheng Liu. {SEED}: Selfsupervised distillation for visual representation. In International Conference on Learning Representations, 2021. 5, 9 [22] Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, and Yoshua Bengio. Generative adversarial nets. In Z. Ghahramani, M. Welling, C. Cortes, N. Lawrence, and K. Q. Weinberger, editors, Advances in Neural Information Processing Systems, volume 27, pages 2672–2680. Curran Associates, Inc., 2014. 2 [23] Jean-Bastien Grill, Florian Strub, Florent Altché, Corentin Tallec, Pierre H Richemond, Elena Buchatskaya, Carl Doersch, Bernardo Avila Pires, Zhaohan Daniel Guo, Mohammad Gheshlaghi Azar, et al. Bootstrap your own latent: A new approach to self-supervised learning. arXiv preprint arXiv:2006.07733, 2020. 1, 3, 5, 6, 9, 10 [24] Kaiming He, Haoqi Fan, Yuxin Wu, Saining Xie, and Ross Girshick. Momentum contrast for unsupervised visual representation learning. arXiv preprint arXiv:1911.05722, 2019. 1, 2, 3, 4, 8 [25] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. arXiv preprint arXiv:1512.03385, 2015. 5 [26] Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv preprint arXiv:1503.02531, 2015. 5 [27] R Devon Hjelm, Alex Fedorov, Samuel Lavoie-Marchildon, Karan Grewal, Phil Bachman, Adam Trischler, and Yoshua Bengio. Learning deep representations by mutual information estimation and maximization. arXiv preprint arXiv:1808.06670, 2018. 1, 2 [28] Qianjiang Hu, Xiao Wang, Wei Hu, and Guo-Jun Qi. Adco: Adversarial contrast for efficient learning of unsupervised representations from self-trained negative adversaries. arXiv preprint arXiv:2011.08435, 2020. 9 [29] Lang Huang, Chao Zhang, and Hongyang Zhang. Self-adaptive training: Bridging the supervised and self-supervised learning. arXiv preprint arXiv:2101.08732, 2021. 2 [30] Yannis Kalantidis, Mert Bulent Sariyildiz, Noe Pion, Philippe Weinzaepfel, and Diane Larlus. Hard negative mixing for contrastive learning. In Neural Information Processing Systems (NeurIPS), 2020. 2, 9 [31] A. Krizhevsky. Learning multiple layers of features from tiny images. 2009. 5 [32] Cheng-I Lai. Contrastive predictive coding based feature for automatic speaker verification. arXiv preprint arXiv:1904.01575, 2019. 1, 2, 9 [33] Ya Le and Xuan Yang. Tiny imagenet visual recognition challenge. CS 231N, 7(7):3, 2015. 5 [34] C. Ledig, L. Theis, Ferenc Huszár, J. Caballero, Andrew Aitken, Alykhan Tejani, J. Totz, Zehan Wang, and W. Shi. Photo-realistic single image super-resolution using a generative adversarial network. 2017 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), pages 105–114, 2017. 2 [35] Hankook Lee, Sung Ju Hwang, and Jinwoo Shin. Self-supervised label augmentation via input transformations. In International Conference on Machine Learning, pages 5714–5724. PMLR, 2020. 2 [36] Junnan Li, Pan Zhou, Caiming Xiong, and Steven Hoi. Prototypical contrastive learning of unsupervised representations. In International Conference on Learning Representations, 2021. 2, 3, 9, 10 [37] Ilya Loshchilov and Frank Hutter. Sgdr: Stochastic gradient descent with warm restarts. arXiv preprint arXiv:1608.03983, 2016. 6 [38] Ishan Misra and Laurens van der Maaten. Self-supervised learning of pretext-invariant representations. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), June 2020. 2 [39] M. Noroozi and P. Favaro. Unsupervised learning of visual representations by solving jigsaw puzzles. In ECCV, 2016. 2 [40] Yonglong Tian, Dilip Krishnan, and Phillip Isola. Contrastive multiview coding. arXiv preprint arXiv:1906.05849, 2019. 1, 2 [41] Yonglong Tian, Chen Sun, Ben Poole, Dilip Krishnan, Cordelia Schmid, and Phillip Isola. What makes for good views for contrastive learning? arXiv preprint arXiv:2005.10243, 2020. 2, 3 [42] Laurens Van der Maaten and Geoffrey Hinton. Visualizing data using t-sne. Journal of machine learning research, 9(11), 2008. 8 [43] Feng Wang, Xiang Xiang, Jian Cheng, and A. Yuille. Normface: L2 hypersphere embedding for face verification. Proceedings of the 25th ACM international conference on Multimedia, 2017. 6 [44] H. Wang, Yitong Wang, Z. Zhou, Xing Ji, Zhifeng Li, Dihong Gong, Jingchao Zhou, and Wenyu Liu. Cosface: Large margin cosine loss for deep face recognition. 2018 IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 5265–5274, 2018. 6 [45] Tongzhou Wang and Phillip Isola. Understanding contrastive representation learning through alignment and uniformity on the hypersphere. arXiv preprint arXiv:2005.10242, 2020. 1, 3 [46] Xiao Wang and Guo-Jun Qi. Contrastive learning with stronger augmentations. arXiv preprint arXiv:2104.07713, 2021. 2, 5, 9 [47] Zhirong Wu, Yuanjun Xiong, X Yu Stella, and Dahua Lin. Unsupervised feature learning via nonparametric instance discrimination. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2018. 1, 2, 9 [48] Asano YM., Rupprecht C., and Vedaldi A. Self-labelling via simultaneous clustering and representation learning. In International Conference on Learning Representations, 2020. 1, 3 [49] Shan You, Chang Xu, Chao Xu, and Dacheng Tao. Learning from multiple teacher networks. In Proceedings of the 23rd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, pages 1285–1294, 2017. 5 [50] Richard Zhang, Phillip Isola, and Alexei A. Efros. Colorful image colorization. In ECCV, 2016. 2 [51] Mingkai Zheng, Fei Wang, Shan You, Chen Qian, Changshui Zhang, Xiaogang Wang, and Chang Xu. Weakly supervised contrastive learning. In Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), pages 10042–10051, October 2021. 9 [52] Chengxu Zhuang, Alex Lin Zhai, and Daniel Yamins. Local aggregation for unsupervised learning of visual embeddings. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 6002–6012, 2019. 9123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704# STOCHASTIC OPTIMIZATION OF SORTING NETWORKS VIA CONTINUOUS RELAXATIONS
Aditya Grover∗, Eric Wang∗, Aaron Zweig & Stefano Ermon Computer Science Department Stanford University {adityag,ejwang,azweig,ermon}@cs.stanford.edu
# ABSTRACT
Sorting input objects is an important step in many machine learning pipelines. However, the sorting operator is non-differentiable with respect to its inputs, which prohibits end-to-end gradient-based optimization. In this work, we propose NeuralSort, a general-purpose continuous relaxation of the output of the sorting operator from permutation matrices to the set of unimodal row-stochastic matrices, where every row sums to one and has a distinct arg max. This relaxation permits straight-through optimization of any computational graph involve a sorting operation. Further, we use this relaxation to enable gradient-based stochastic optimization over the combinatorially large space of permutations by deriving a reparameterized gradient estimator for the Plackett-Luce family of distributions over permutations. We demonstrate the usefulness of our framework on three tasks that require learning semantic orderings of high-dimensional objects, including a fully differentiable, parameterized extension of the $k$ -nearest neighbors algorithm.
# 1 INTRODUCTION
Learning to automatically sort objects is useful in many machine learning applications, such as top$k$ multi-class classification (Berrada et al., 2018), ranking documents for information retrieval (Liu et al., 2009), and multi-object target tracking in computer vision (Bar-Shalom & Li, 1995). Such algorithms typically require learning informative representations of complex, high-dimensional data, such as images, before sorting and subsequent downstream processing. For instance, the $k$ -nearest neighbors image classification algorithm, which orders the neighbors based on distances in the canonical pixel basis, can be highly suboptimal for classification (Weinberger et al., 2006). Deep neural networks can instead be used to learn representations, but these representations cannot be optimized end-to-end for a downstream sorting-based objective, since the sorting operator is not differentiable with respect to its input.
In this work, we seek to remedy this shortcoming by proposing NeuralSort, a continuous relaxation to the sorting operator that is differentiable almost everywhere with respect to the inputs. The output of any sorting algorithm can be viewed as a permutation matrix, which is a square matrix with entries in $\{ 0 , 1 \}$ such that every row and every column sums to 1. Instead of a permutation matrix, NeuralSort returns a unimodal row-stochastic matrix. A unimodal row-stochastic matrix is defined as a square matrix with positive real entries, where each row sums to 1 and has a distinct arg max. All permutation matrices are unimodal row-stochastic matrices. NeuralSort has a temperature knob that controls the degree of approximation, such that in the limit of zero temperature, we recover a permutation matrix that sorts the inputs. Even for a non-zero temperature, we can efficiently project any unimodal matrix to the desired permutation matrix via a simple row-wise arg max operation. Hence, NeuralSort is also suitable for efficient straight-through gradient optimization (Bengio et al., 2013), which requires “exact” permutation matrices to evaluate learning objectives.
As the second primary contribution, we consider the use of NeuralSort for stochastic optimization over permutations. In many cases, such as latent variable models, the permutations may be latent but directly influence observed behavior, e.g., utility and choice models are often expressed as distributions over permutations which govern the observed decisions of agents (Regenwetter et al.,
2006; Chierichetti et al., 2018). By learning distributions over unobserved permutations, we can account for the uncertainty in these permutations in a principled manner. However, the challenge with stochastic optimization over discrete distributions lies in gradient estimation with respect to the distribution parameters. Vanilla REINFORCE estimators are impractical for most cases, or necessitate custom control variates for low-variance gradient estimation (Glasserman, 2013).
In this regard, we consider the Plackett-Luce (PL) family of distributions over permutations (Plackett, 1975; Luce, 1959). A common modeling choice for ranking models, the PL distribution is parameterized by $n$ scores, with its support defined over the symmetric group consisting of $n !$ permutations. We derive a reparameterizable sampler for stochastic optimization with respect to this distribution, based on Gumbel perturbations to the $n$ (log-)scores. However, the reparameterized sampler requires sorting these perturbed scores, and hence the gradients of a downstream learning objective with respect to the scores are not defined. By using NeuralSort instead, we can approximate the objective and obtain well-defined reparameterized gradient estimates for stochastic optimization.
Finally, we apply NeuralSort to tasks that require us to learn semantic orderings of complex, highdimensional input data. First, we consider sorting images of handwritten digits, where the goal is to learn to sort images by their unobserved labels. Our second task extends the first one to quantile regression, where we want to estimate the median (50-th percentile) of a set of handwritten numbers. In addition to identifying the index of the median image in the sequence, we need to learn to map the inferred median digit to its scalar representation. In the third task, we propose an algorithm that learns a basis representation for the $k$ -nearest neighbors (kNN) classifier in an end-to-end procedure. Because the choice of the $k$ nearest neighbors requires a non-differentiable sorting, we use NeuralSort to obtain an approximate, differentiable surrogate. On all tasks, we observe significant empirical improvements due to NeuralSort over the relevant baselines and competing relaxations to permutation matrices.
# 2 PRELIMINARIES
An $n$ -dimensional permutation $\mathbf { z } = [ z _ { 1 } , z _ { 2 } , \ldots , z _ { n } ] ^ { T }$ is a list of unique indices $\{ 1 , 2 , \ldots , n \}$ . Every permutation $\mathbf { z }$ is associated with a permutation matrix $P _ { \mathbf { z } } \in \{ 0 , 1 \} ^ { n \times n }$ with entries given as:
$$P _ { \mathbf { z } } [ i , j ] = { \Big \{ } _ { 0 } ^ { 1 { \mathrm { i f } } \ j } = z _ { i } $$
Let ${ \mathcal { Z } } _ { n }$ denote the set of all $n !$ possible permutations in the symmetric group. We define the sort : $\mathbb { R } ^ { n } \to { \mathcal Z } _ { n }$ operator as a mapping of $n$ real-valued inputs to a permutation corresponding to a descending ordering of these inputs. E.g., if the input vector $\mathbf { s } ~ = ~ [ 9 , 1 , 5 , 2 ] ^ { T }$ , then $\mathsf { s o r t } ( \mathbf { s } ) = [ 1 , 3 , \bar { 4 } , 2 ] ^ { T }$ since the largest element is at the first index, second largest element is at the third index and so on. In case of ties, elements are assigned indices in the order they appear. We can obtain the sorted vector simply via $P _ { \mathrm { s o r t } ( \mathbf { s } ) } \mathbf { s }$ .
# 2.1 PLACKETT-LUCE DISTRIBUTIONS
The family of Plackett-Luce distributions over permutations is best described via a generative process: Consider a sequence of $n$ items, each associated with a canonical index $i = 1 , 2 , \ldots , n$ . A common assumption in ranking models is that the underlying generating process for any observed permutation of $n$ items satisfies Luce’s choice axiom (Luce, 1959). Mathematically, this axiom defines the ‘choice’ probability of an item with index $i$ as: $q ( i ) \propto s _ { i }$ where $s _ { i } > 0$ is interpreted as the score of item with index i. The normalization constant is given by Z = Pi∈{1,2,...,n} si.
If we choose the $n$ items one at a time (without replacement) based on these choice probabilities, we obtain a discrete distribution over all possible permutations. This distribution is referred to as the Plackett-Luce (PL) distribution, and its probability mass function for any $\mathbf { z } \in \mathcal { Z } _ { n }$ is given by:
$$q ( \mathbf { z } | \mathbf { s } ) = { \frac { s _ { z _ { 1 } } } { Z } } { \frac { s _ { z _ { 2 } } } { Z - s _ { z _ { 1 } } } } \cdot \cdot \cdot { \frac { s _ { z _ { n } } } { Z - \sum _ { i = 1 } ^ { n - 1 } s _ { z _ { i } } } }$$
where $\mathbf { s } = \{ s _ { 1 } , s _ { 2 } , \ldots , s _ { n } \}$ is the vector of scores parameterizing this distribution (Plackett, 1975).
 Figure 1: Stochastic computation graphs with a deterministic node z corresponding to the output of a sort operator applied to the scores s.
# 2.2 STOCHASTIC COMPUTATION GRAPHS
The abstraction of stochastic computation graphs (SCG) compactly specifies the forward value and the backward gradient computation for computational circuits. An SCG is a directed acyclic graph that consists of three kinds of nodes: input nodes which specify external inputs (including parameters), deterministic nodes which are deterministic functions of their parents, and stochastic nodes which are distributed conditionally on their parents. See Schulman et al. (2015) for a review.
To define gradients of an objective function with respect to any node in the graph, the chain rule necessitates that the gradients with respect to the intermediate nodes are well-defined. This is not the case for the sort operator. In Section 3, we propose to extend stochastic computation graphs with nodes corresponding to a relaxation of the deterministic sort operator. In Section 4, we further use this relaxation to extend computation graphs to include stochastic nodes corresponding to distributions over permutations. The proofs of all theoretical results in this work are deferred to Appendix B.
# 3 NEURALSORT: THE RELAXED SORTING OPERATOR
Our goal is to optimize training objectives involving a sort operator with gradient-based methods. Consider the optimization of objectives written in the following form:
$$L ( \boldsymbol { \theta } , \mathbf { s } ) = f ( P _ { \mathbf { z } } ; \boldsymbol { \theta } )$$
Here, $\mathbf { s } \in \mathbb { R } ^ { n }$ denotes a vector of $n$ real-valued scores, $\mathbf { z }$ is the permutation that (deterministically) sorts the scores s, and $f ( \cdot )$ is an arbitrary function of interest assumed to be differentiable w.r.t a set of parameters $\theta$ and $\mathbf { z }$ . For example, in a ranking application, these scores could correspond to the inferred relevances of $n$ webpages and $f ( \cdot )$ could be a ranking loss. Figure 1 shows the stochastic computation graph corresponding to the objective in Eq. 2. We note that this could represent part of a more complex computation graph, which we skip for ease of presentation while maintaining the generality of the scope of this work.
While the gradient of the above objective w.r.t. $\theta$ is well-defined and can be computed via standard backpropogation, the gradient w.r.t. the scores s is not defined since the sort operator is not differentiable w.r.t. s. Our solution is to derive a relaxation to the sort operator that leads to a surrogate objective with well-defined gradients. In particular, we seek to use such a relaxation to replace the permutation matrix $P _ { \mathbf { z } }$ in Eq. 2 with an approximation $\widehat { P } _ { \mathbf { z } }$ such that the surrogate objective $f ( \widehat { P } _ { \mathbf { z } } ; \theta )$ is differentiable w.r.t. the scores s.
The general recipe to relax non-differentiable operators with discrete codomains $\mathcal { N }$ is to consider differentiable alternatives that map the input to a larger continuous codomain $\mathcal { M }$ with desirable properties. For gradient-based optimization, we are interested in two key properties:
1. The relaxation is continuous everywhere and differentiable (almost-)everywhere with respect to elements in the input domain. 2. There exists a computationally efficient projection from $\mathcal { M }$ back to $\mathcal { N }$ .
Relaxations satisfying the first requirement are amenable to automatic differentiation for optimizing stochastic computational graphs. The second requirement is useful for evaluating metrics and losses that necessarily require a discrete output akin to the one obtained from the original, non-relaxed operator. E.g., in straight-through gradient estimation (Bengio et al., 2013; Jang et al., 2017), the non-relaxed operator is used for evaluating the learning objective in the forward pass and the relaxed operator is used in the backward pass for gradient estimation.
 Figure 2: Center: Venn Diagram relationships between permutation matrices $( \mathcal { P } )$ , doubly-stochastic matrices $( \mathcal { D } )$ , unimodal row stochastic matrices $( \mathcal { U } )$ , and row stochastic matrices $( { \mathcal { R } } )$ . Left: A doubly-stochastic matrix that is not unimodal. Right: A unimodal matrix that is not doublystochastic.
The canonical example is the $0 / 1$ loss used for binary classification. While the $0 / 1$ loss is discontinuous w.r.t. its inputs (real-valued predictions from a model), surrogates such as the logistic and hinge losses are continuous everywhere and differentiable almost-everywhere (property 1), and can give hard binary predictions via thresholding (property 2).
Note: For brevity, we assume that the arg max operator is applied over a set of elements with a unique maximizer and hence, the operator has well-defined semantics. With some additional bookkeeping for resolving ties, the results in this section hold even if the elements to be sorted are not unique. See Appendix C.
Unimodal Row Stochastic Matrices. The sort operator maps the input vector to a permutation, or equivalently a permutation matrix. Our relaxation to sort is motivated by the geometric structure of permutation matrices. The set of permutation matrices is a subset of doubly-stochastic matrices, i.e., a non-negative matrix such that the every row and column sums to one. If we remove the requirement that every column should sum to one, we obtain a larger set of row stochastic matrices. In this work, we propose a relaxation to sort that maps inputs to an alternate subset of row stochastic matrices, which we refer to as the unimodal row stochastic matrices.
Definition 1 (Unimodal Row Stochastic Matrices). An $n \times n$ matrix is Unimodal Row Stochastic if it satisfies the following conditions:
1. Non-negativity: $U [ i , j ] \geq 0 \quad \forall i , j \in \{ 1 , 2 , . . . , n \} .$ .
2. Row Affinity: $\begin{array} { r } { \sum _ { j = 1 } ^ { n } U [ i , j ] = 1 \quad \forall i \in \{ 1 , 2 , \ldots , n \} . } \end{array}$
3. Argmax Permutation: Let u denote an $n$ -dimensional vector with entries such that $u _ { i } =$ ar $\operatorname { g m a x } _ { j } U [ i , j ] \quad \forall i \in \{ 1 , 2 , \dots , n \}$ . Then, $\mathbf { u } \in \mathcal { Z } _ { n }$ , i.e., it is a valid permuation.
We denote $\mathcal { U } _ { n }$ as the set of $n \times n$ unimodal row stochastic matrices.
All row stochastic matrices satisfy the first two conditions. The third condition is useful for gradient based optimization involving sorting-based losses. The condition provides a straightforward mechanism for extracting a permutation from a unimodal row stochastic matrix via a row-wise arg max operation. Figure 2 shows the relationships between the different subsets of square matrices.
NeuralSort. Our relaxation to the sort operator is based on a standard identity for evaluating the sum of the $k$ largest elements in any input vector.
Lemma 2. [Lemma $I$ in Ogryczak & Tamir (2003)] For an input vector $\mathbf { s } = [ s _ { 1 } , s _ { 2 } , \ldots , s _ { n } ] ^ { T }$ that is sorted as $s _ { [ 1 ] } \geq s _ { [ 2 ] } \geq . . . \geq s _ { [ n ] }$ , we have the sum of the $k$ -largest elements given as:
$$\sum _ { i = 1 } ^ { k } s _ { [ i ] } = \operatorname* { m i n } _ { \substack { \lambda \in \{ s _ { 1 } , s _ { 2 } , \ldots , s _ { n } \} } } \lambda k + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } ( s _ { i } - \lambda , 0 ) .$$
The identity in Lemma 2 outputs the sum of the top- $k$ elements. The $k$ -th largest element itself can be recovered by taking the difference of the sum of top- $k$ elements and the top- $\left( k - 1 \right)$ elements.
 Figure 3: Stochastic computation graphs with stochastic nodes corresponding to permutations. Squares denote deterministic nodes and circles denote stochastic nodes.
Corollary 3. Let $\mathbf { s } = [ s _ { 1 } , s _ { 2 } , \ldots , s _ { n } ] ^ { T }$ be a real-valued vector of length n. Let $A _ { \mathrm { s } }$ denote the matrix of absolute pairwise differences of the elements of s such that $A _ { \mathbf { s } } [ i , j ] = | s _ { i } - s _ { j } |$ . The permutation matrix $P _ { s o r t ( \mathbf { s } ) }$ corresponding to sort(s) is given by:
$$P _ { s o r t ( \mathbf { s } ) } [ i , j ] = \left\{ { 1 i f j = \arg \operatorname* { m a x } [ ( n + 1 - 2 i ) \mathbf { s } - A _ { \mathbf { s } } \mathbf { \mathbb { 1 } } ] } \right.$$
where 1 denotes the column vector of all ones.
$E . g .$ , if we set $i = \lfloor ( n + 1 ) / 2 \rfloor$ then the non-zero entry in the $i$ -th row $P _ { \mathrm { s o r t } ( \mathbf { s } ) } [ i , : ]$ corresponds to the element with the minimum sum of (absolute) distance to the other elements. As desired, this corresponds to the median element. The relaxation requires $O ( n ^ { 2 } )$ operations to compute $A _ { \mathrm { s } }$ , as opposed to the $O ( n \log n )$ overall complexity for the best known sorting algorithms. In practice however, it is highly parallelizable and can be implemented efficiently on GPU hardware.
The arg max operator is non-differentiable which prohibits the direct use of Corollary 3 for gradient computation. Instead, we propose to replace the arg max operator with soft max to obtain a continuous relaxation $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } ( \tau )$ . In particular, the $i$ -th row of $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } ( \tau )$ is given by:
$$\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } [ i , : ] ( \tau ) = \mathrm { s o f t m a x } \left[ ( ( n + 1 - 2 i ) \mathbf { s } - A _ { \mathbf { s } } \mathbf { 1 } ) / \tau \right]$$
where $\tau > 0$ is a temperature parameter. Our relaxation is continuous everywhere and differentiable almost everywhere with respect to the elements of s. Furthermore, we have the following result.
Theorem 4. Let $\widehat { P } _ { s o r t ( s ) }$ denote the continuous relaxation to the permutation matrix $P _ { s o r t ( \pmb { s } ) }$ for an arbitrary input vector s and temperature $\tau$ defined in Eq. 5. Then, we have:
1. Unimodality: $\forall \tau > 0$ , $\widehat { P } _ { s o r t ( s ) }$ is a unimodal row stochastic matrix. Further, let u denote the permutation obtained by applying arg max row-wise to $\widehat { P } _ { s o r t ( s ) }$ . Then, $\mathbf { u } = s o r t ( \pmb { s } )$
2. Limiting behavior: If we assume that the entries of s are drawn independently from a distribution that is absolutely continuous w.r.t. the Lebesgue measure in $\mathbb { R }$ , then the following convergence holds almost surely:
$$\operatorname* { l i m } _ { \tau 0 ^ { + } } \widehat { P } _ { s o r t ( \mathbf { s } ) } [ i , : ] ( \tau ) = P _ { s o r t ( \mathbf { s } ) } [ i , : ] \quad \forall i \in \{ 1 , 2 , \ldots , n \} .$$
Unimodality allows for efficient projection of the relaxed permutation matrix $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) }$ to the hard matrix $P _ { \mathsf { s o r t } ( \mathbf { s } ) }$ via a row-wise arg max, e.g., for straight-through gradients. For analyzing limiting behavior, independent draws ensure that the elements of s are distinct almost surely. The temperature $\tau$ controls the degree of smoothness of our approximation. At one extreme, the approximation becomes tighter as the temperature is reduced. In practice however, the trade-off is in the variance of these estimates, which is typically lower for larger temperatures.
# 4 STOCHASTIC OPTIMIZATION OVER PERMUTATIONS
In many scenarios, we would like the ability to express our uncertainty in inferring a permutation e.g., latent variable models with latent nodes corresponding to permutations. Random variables that assume values corresponding to permutations can be represented via stochastic nodes in the
stochastic computation graph. For optimizing the parameters of such a graph, consider the following class of objectives:
$$L ( \boldsymbol { \theta } , \mathbf { s } ) = \mathbb { E } _ { q ( \mathbf { z } | \mathbf { s } ) } \left[ f ( P _ { \mathbf { z } } ; \boldsymbol { \theta } ) \right]$$
where $\theta$ and s denote sets of parameters, $P _ { \mathbf { z } }$ is the permutation matrix corresponding to the permutation $\mathbf { z }$ , $q ( \cdot )$ is a parameterized distribution over the elements of the symmetric group ${ \mathcal { Z } } _ { n }$ , and $f ( \cdot )$ is an arbitrary function of interest assumed to be differentiable in $\theta$ and $\mathbf { z }$ . The SCG is shown in Figure 3a. In contrast to the SCG considered in the previous section (Figure 1), here we are dealing with a distribution over permutations as opposed to a single (deterministically computed) one.
While such objectives are typically intractable to evaluate exactly since they require summing over a combinatorially large set, we can obtain unbiased estimates efficiently via Monte Carlo. Monte Carlo estimates of gradients w.r.t. $\theta$ can be derived simply via linearity of expectation. However, the gradient estimates w.r.t. s cannot be obtained directly since the sampling distribution depends on s. The REINFORCE gradient estimator (Glynn, 1990; Williams, 1992; Fu, 2006) uses the fact that $\nabla _ { \mathbf { s } } q ( \mathbf { z } | \mathbf { s } ) = q ( \mathbf { z } | \mathbf { s } ) \nabla _ { \mathbf { s } } \log q ( \mathbf { z } | \mathbf { s } )$ to derive the following Monte Carlo gradient estimates:
$$\nabla _ { \mathbf { s } } L ( \theta , \mathbf { s } ) = \mathbb { E } _ { q ( \mathbf { z } | \mathbf { s } ) } \left[ f ( P _ { \mathbf { z } } ; \theta ) \nabla _ { \mathbf { s } } \log q ( \mathbf { z } | \mathbf { s } ) \right] + \mathbb { E } _ { q ( \mathbf { z } | \mathbf { s } ) } \left[ \nabla _ { \mathbf { s } } f ( P _ { \mathbf { z } } ; \theta ) \right] .$$
# 4.1 REPARAMETERIZED GRADIENT ESTIMATORS FOR PL DISTRIBUTIONS
REINFORCE gradient estimators typically suffer from high variance (Schulman et al., 2015; Glasserman, 2013). Reparameterized samplers provide an alternate gradient estimator by expressing samples from a distribution as a deterministic function of its parameters and a fixed source of randomness (Kingma & Welling, 2014; Rezende et al., 2014; Titsias & Lazaro-Gredilla, 2014). ´ Since the randomness is from a fixed distribution, Monte Carlo gradient estimates can be derived by pushing the gradient operator inside the expectation (via linearity). In this section, we will derive a reparameterized sampler and gradient estimator for the Plackett-Luce (PL) family of distributions.
Let the score $s _ { i }$ for an item $i \in \{ 1 , 2 , \ldots , n \}$ be an unobserved random variable drawn from some underlying score distribution (Thurstone, 1927). Now for each item, we draw a score from its corresponding score distribution. Next, we generate a permutation by applying the deterministic sort operator to these $n$ randomly sampled scores. Interestingly, prior work has shown that the resulting distribution over permutations corresponds to a PL distribution if and only if the scores are sampled independently from Gumbel distributions with identical scales.
Proposition 5. [adapted from Yellott Jr (1977)] Let s be a vector of scores for the n items. For each item $i$ , sample $g _ { i } \sim { \tt G u m b e l } ( 0 , \beta )$ independently with zero mean and a fixed scale $\beta$ . Let ˜s denote the vector of Gumbel perturbed log-scores with entries such that $\tilde { s } _ { i } = \beta \log s _ { i } + g _ { i }$ . Then:
$$q \bigl ( \tilde { s } _ { z _ { 1 } } \geq \cdot \cdot \cdot \geq \tilde { s } _ { z _ { n } } \bigr ) = \frac { s _ { z _ { 1 } } } { Z } \frac { s _ { z _ { 2 } } } { Z - s _ { z _ { 1 } } } \cdot \cdot \cdot \frac { s _ { z _ { n } } } { Z - \sum _ { i = 1 } ^ { n - 1 } s _ { z _ { i } } } .$$
For ease of presentation, we assume $\beta = 1$ in the rest of this work. Proposition 5 provides a method for sampling from PL distributions with parameters s by adding Gumbel perturbations to the logscores and applying the sort operator to the perturbed log-scores. This procedure can be seen as a reparameterization trick that expresses a sample from the PL distribution as a deterministic function of the scores and a fixed source of randomness (Figure 3b). Letting $\mathbf { g }$ denote the vector of i.i.d. Gumbel perturbations, we can express the objective in Eq. 7 as:
$$L ( \boldsymbol { \theta } , \mathbf { s } ) = \mathbb { E } _ { \mathbf { g } } \left[ f ( P _ { \mathrm { s o r t ( l o g \mathbf { s } + \mathbf { g } ) } } ; \boldsymbol { \theta } ) \right] .$$
While the reparameterized sampler removes the dependence of the expectation on the parameters s, it introduces a sort operator in the computation graph such that the overall objective is nondifferentiable in s. In order to obtain a differentiable surrogate, we approximate the objective based on the NeuralSort relaxation to the sort operator:
$$\begin{array} { r } { \mathbb { E } _ { \mathbf { g } } \left[ f \left( P _ { \mathrm { s o r t } \left( \log \mathbf { s } + \mathbf { g } \right) } ; \theta \right) \right] \approx \mathbb { E } _ { \mathbf { g } } \left[ f \left( \widehat { P } _ { \mathrm { s o r t } \left( \log \mathbf { s } + \mathbf { g } \right) } ; \theta \right) \right] : = \widehat { L } ( \theta , \mathbf { s } ) . } \end{array}$$
Accordingly, we get the following reparameterized gradient estimates for the approximation:
$$\nabla _ { \mathbf { s } } \widehat { L } ( \theta , \mathbf { s } ) = \mathbb { E } _ { \mathbf { g } } \left[ \nabla _ { \mathbf { s } } f ( \widehat { P } _ { \mathrm { s o r t ( l o g } \mathbf { s } + \mathbf { g } ) } ; \theta ) \right]$$
which can be estimated efficiently via Monte Carlo because the expectation is with respect to a distribution that does not depend on s.
# 5 DISCUSSION AND RELATED WORK
The problem of learning to rank documents based on relevance has been studied extensively in the context of information retrieval. In particular, listwise approaches learn functions that map objects to scores. Much of this work concerns the PL distribution: the RankNet algorithm (Burges et al., 2005) can be interpreted as maximizing the PL likelihood of pairwise comparisons between items, while the ListMLE ranking algorithm in Xia et al. (2008) extends this with a loss that maximizes the PL likelihood of ground-truth permutations directly. The differentiable pairwise approaches to ranking, such as Rigutini et al. (2011), learn to approximate the comparator between pairs of objects. Our work considers a generalized setting where sorting based operators can be inserted anywhere in computation graphs to extend traditional pipelines e.g., kNN.
Prior works have proposed relaxations of permutation matrices to the Birkhoff polytope, which is defined as the convex hull of the set of permutation matrices a.k.a. the set of doubly-stochastic matrices. A doubly-stochastic matrix is a permutation matrix iff it is orthogonal and continuous relaxations based on these matrices have been used previously for solving NP-complete problems such as seriation and graph matching (Fogel et al., 2013; Fiori et al., 2013; Lim & Wright, 2014). Adams & Zemel (2011) proposed the use of the Sinkhorn operator to map any square matrix to the Birkhoff polytope. They interpret the resulting doubly-stochastic matrix as the marginals of a distribution over permutations. Mena et al. (2018) propose an alternate method where the square matrix defines a latent distribution over the doubly-stochastic matrices themselves. These distributions can be sampled from by adding elementwise Gumbel perturbations. Linderman et al. (2018) propose a rounding procedure that uses the Sinkhorn operator to directly sample matrices near the Birkhoff polytope. Unlike Mena et al. (2018), the resulting distribution over matrices has a tractable density. In practice, however, the approach of Mena et al. (2018) performs better and will be the main baseline we will be comparing against in our experiments in Section 6.
As discussed in Section 3, NeuralSort maps permutation matrices to the set of unimodal rowstochastic matrices. For the stochastic setting, the PL distribution permits efficient sampling, exact and tractable density estimation, making it an attractive choice for several applications, e.g., variational inference over latent permutations. Our reparameterizable sampler, while also making use of the Gumbel distribution, is based on a result unique to the PL distribution (Proposition 5).
The use of the Gumbel distribution for defining continuous relaxations to discrete distributions was first proposed concurrently by Jang et al. (2017) and Maddison et al. (2017) for categorical variables, referred to as Gumbel-Softmax. The number of possible permutations grow factorially with the dimension, and thus any distribution over $n$ -dimensional permutations can be equivalently seen as a distribution over $n !$ categories. Gumbel-softmax does not scale to a combinatorially large number of categories (Kim et al., 2016; Mussmann et al., 2017), necessitating the use of alternate relaxations, such as the one considered in this work.
# 6 EXPERIMENTS
We refer to the two approaches proposed in Sections 3, 4 as Deterministic NeuralSort and Stochastic NeuralSort, respectively. For additional hyperparameter details and analysis, see Appendix D.
# 6.1 SORTING HANDWRITTEN NUMBERS
Dataset. We first create the large-MNIST dataset, which extends the MNIST dataset of handwritten digits. The dataset consists of multi-digit images, each a concatenation of 4 randomly selected individual images from MNIST, e.g., is one such image in this dataset. Each image is associated with a real-valued label, which corresponds to its concatenated MNIST labels, e.g., the label of is 1810. Using the large-MNIST dataset, we finally create a dataset of sequences. Every sequence is this dataset consists of $n$ randomly sampled large-MNIST images.
Setup. Given a dataset of sequences of large-MNIST images, our goal is to learn to predict the permutation that sorts the labels of the sequence of images, given a training set of ground-truth permutations. Figure 4 (Task 1) illustrates this task on an example sequence of $n = 5$ large-MNIST images. This task is a challenging extension of the one considered by Mena et al. (2018) in sorting scalars, since it involves learning the semantics of high-dimensional objects prior to sorting. A good model needs to learn to dissect the individual digits in an image, rank these digits, and finally, compose such rankings based on the digit positions within an image. The available supervision, in the form of the ground-truth permutation, is very weak compared to a classification setting that gives direct access to the image labels.
 Figure 4: Sorting and quantile regression. The model is trained to sort sequences of $n = 5$ largeMNIST images $\mathbf { x } _ { 1 } , \mathbf { x } _ { 2 } , \ldots , \mathbf { x } _ { 5 }$ (Task 1) and regress the median value (Task 2). In the above example, the ground-truth permutation that sorts the input sequence from largest to smallest is $[ 3 , 5 , \bar { 1 } , 4 , 2 ] ^ { T }$ , 9803 being the largest and 1270 the smallest. Blue illustrates the true median image $\mathbf { x } _ { 1 }$ with ground-truth sorted index 3 and value 2960.
Table 1: Average sorting accuracy on the test set. First value is proportion of permutations correctly identified; value in parentheses is the proportion of individual element ranks correctly identified.
<table><tr><td>Algorithm</td><td>n=3</td><td>n=5</td><td>n=7</td><td>n=9</td><td>n=15</td></tr><tr><td>Vanilla RS</td><td>0.467 (0.801)</td><td>0.093 (0.603)</td><td>0.009 (0.492)</td><td>0. (0.113)</td><td>0. (0.067)</td></tr><tr><td>Sinkhorn</td><td>0.462 (0.561)</td><td>0.038 (0.293)</td><td>0.001 (0.197)</td><td>0. (0.143)</td><td>0.(0.078)</td></tr><tr><td>Gumbel-Sinkhorn</td><td>0.484 (0.575)</td><td>0.033 (0.295)</td><td>0.001 (0.189)</td><td>0. (0.146)</td><td>0. (0.078)</td></tr><tr><td>Deterministic NeuralSort</td><td>0.930 (0.951)</td><td>0.837 (0.927)</td><td>0.738 (0.909)</td><td>0.649 (0.896)</td><td>0.386 (0.857)</td></tr><tr><td>Stochastic NeuralSort</td><td>0.927 (0.950)</td><td>0.835 (0.926)</td><td>0.741 (0.909)</td><td>0.646 (0.895)</td><td>0.418 (0.862)</td></tr></table>
Baselines. All baselines use a CNN that is shared across all images in a sequence to map each large-MNIST image to a feature space. The vanilla row-stochastic (RS) baseline concatenates the CNN representations for $n$ images into a single vector that is fed into a multilayer perceptron that outputs $n$ multiclass predictions of the image probabilities for each rank. The Sinkhorn and GumbelSinkhorn baselines, as discussed in Section 5, use the Sinkhorn operator to map the stacked CNN representations for the $n$ objects into a doubly-stochastic matrix. For all methods, we minimized the cross-entropy loss between the predicted matrix and the ground-truth permutation matrix.
Results. Following Mena et al. (2018), our evaluation metric is the the proportion of correctly predicted permutations on a test set of sequences. Additionally, we evaluate the proportion of individual elements ranked correctly. Table 1 demonstrates that the approaches based on the proposed sorting relaxation significantly outperform the baseline approaches for all $n$ considered. The performance of the deterministic and stochastic variants are comparable. The vanilla RS baseline performs well in ranking individual elements, but is not good at recovering the overall square matrix.
We believe the poor performance of the Sinkhorn baselines is partly because these methods were designed and evaluated for matchings. Like the output of sort, matchings can also be represented as permutation matrices. However, distributions over matchings need not satisfy Luce’s choice axiom or imply a total ordering, which could explain the poor performance on the tasks considered.
# 6.2 QUANTILE REGRESSION
Setup. In this experiment, we extend the sorting task to regression. Again, each sequence contains $n$ large-MNIST images, and the regression target for each sequence is the 50-th quantile (i.e., the median) of the $n$ labels of the images in the sequence. Figure 4 (Task 2) illustrates this task on an example sequence of $n = 5$ large-MNIST images, where the goal is to output the third largest label. The design of this task highlights two key challenges since it explicitly requires learning both a suitable representation for sorting high-dimensional inputs and a secondary function that approximates the label itself (regression). Again, the supervision available in the form of the label of only a single image at an arbitrary and unknown location in the sequence is weak.
Table 2: Test mean squared error $( \times 1 0 ^ { - 4 } )$ ) and $R ^ { 2 }$ values (in parenthesis) for quantile regression.
<table><tr><td>Algorithm</td><td>n=5</td><td>n=9</td><td>n=15</td></tr><tr><td>Constant (Simulated)</td><td>356.79 (0.00)</td><td>227.31 (0.00)</td><td>146.94 (0.00)</td></tr><tr><td>Vanilla NN</td><td>1004.70 (0.85)</td><td>699.15 (0.82)</td><td>562.97 (0.79)</td></tr><tr><td>Sinkhorn</td><td>343.60 (0.25)</td><td>231.87 (0.19)</td><td>156.27 (0.04)</td></tr><tr><td>Gumbel-Sinkhorn</td><td>344.28 (0.25)</td><td>232.56 (0.23)</td><td>157.34 (0.06)</td></tr><tr><td>Deterministic NeuralSort</td><td>45.50 (0.95)</td><td>34.98 (0.94)</td><td>34.78 (0.92)</td></tr><tr><td>Stochastic NeuralSort</td><td>33.80 (0.94)</td><td>31.43 (0.93)</td><td>29.34 (0.90)</td></tr></table>
 Figure 5: Differentiable kNN. The model is trained such that the representations $\mathbf { e } _ { i }$ for the training points $\left\{ \mathbf { x } _ { 1 } , \ldots , \mathbf { x } _ { n } \right\}$ that have the same label $y _ { 0 }$ as $\mathbf { x } _ { \mathrm { 0 } }$ are closer to $\mathbf { e } _ { 0 }$ (included in top- $k$ ) than others.
Baselines. In addition to Sinkhorn and Gumbel-Sinkhorn, we design two more baselines. The Constant baseline always returns the median of the full range of possible outputs, ignoring the input sequence. This corresponds to 4999.5 since we are sampling large-MNIST images uniformly in the range of four-digit numbers. The vanilla neural net (NN) baseline directly maps the input sequence of images to a real-valued prediction for the median.
Results. Our evaluation metric is the mean squared error (MSE) and $R ^ { 2 }$ on a test set of sequences. Results for $n = \{ 5 , 9 , 1 5 \}$ images are shown in Table 2. The Vanilla NN baseline while incurring a large MSE, is competitive on the $R ^ { 2 }$ metric. The other baselines give comparable performance on the MSE metric. The proposed NeuralSort approaches outperform the competing methods on both the metrics considered. The stochastic NeuralSort approach is the consistent best performer on MSE, while the deterministic NeuralSort is slightly better on the $R ^ { 2 }$ metric.
# 6.3 END-TO-END, DIFFERENTIABLE $k$ -NEAREST NEIGHBORS
Setup. In this experiment, we design a fully differentiable, end-to-end $k$ -nearest neighbors (kNN) classifier. Unlike a standard kNN classifier which computes distances between points in a predefined space, we learn a representation of the data points before evaluating the $k$ -nearest neighbors.
We are given access to a dataset $\mathcal { D }$ of $( \mathbf { x } , y )$ pairs of standard input data and their class labels respectively. The differentiable kNN algorithm consists of two hyperparameters: the number of training neighbors $n$ , the number of top candidates $k$ , and the sorting temperature $\tau$ . Every sequence of items here consists of a query point $\mathbf { x }$ and a randomly sampled subset of $n$ candidate nearest neighbors from the training set, say $\left\{ \mathbf { x } _ { 1 } , \mathbf { x } _ { 2 } , \ldots , \mathbf { x } _ { n } \right\}$ . In principle, we could use the entire training set (excluding the query point) as candidate points, but this can hurt the learning both computationally and statistically. The query points are randomly sampled from the train/validation/test sets as appropriate but the nearest neighbors are always sampled from the training set. The loss function optimizes for a representation space $h _ { \phi } ( \cdot )$ (e.g., CNN) such that the top- $k$ candidate points with the minimum Euclidean distance to the query point in the representation space have the same label as the query point. Note that at test time, once the representation space $h _ { \phi }$ is learned, we can use the entire training set as the set of candidate points, akin to a standard kNN classifier. Figure 5 illustrates the proposed algorithm.
Formally, for any datapoint $\mathbf { x }$ , let $_ { z }$ denote a permutation of the $n$ candidate points. The uniformlyweighted kNN loss, denoted as $\ell _ { \mathrm { k N N } } ( \cdot )$ , can be written as follows:
$$\ell _ { \mathrm { k N N } } ( \widehat { P } _ { \mathbf { z } } , y , y _ { 1 } , y _ { 2 } , \ldots , y _ { n } ) = - \frac { 1 } { k } \sum _ { j = 1 } ^ { k } \sum _ { i = 1 } ^ { n } \mathbb { 1 } ( y _ { i } = y ) \widehat { P } _ { \mathbf { z } } [ i , j ]$$
Table 3: Average test kNN classification accuracies from $n$ neighbors for best value of $k$ .
<table><tr><td>Algorithm</td><td>MNIST</td><td>Fashion-MNIST</td><td>CIFAR-10</td></tr><tr><td>kNN</td><td>97.2%</td><td>85.8%</td><td>35.4%</td></tr><tr><td>kNN+PCA</td><td>97.6%</td><td>85.9%</td><td>40.9%</td></tr><tr><td>kNN+AE</td><td>97.6%</td><td>87.5%</td><td>44.2%</td></tr><tr><td>kNN + Deterministic NeuralSort</td><td>99.5%</td><td>93.5%</td><td>90.7%</td></tr><tr><td>kNN + Stochastic NeuralSort</td><td>99.4%</td><td>93.4%</td><td>89.5%</td></tr><tr><td>CNN (w/o kNN)</td><td>一 99.4%</td><td>93.4%</td><td>95.1%</td></tr></table>
where $\left\{ y _ { 1 } , y _ { 2 } , \ldots , y _ { n } \right\}$ are the labels for the candidate points. Note that when $\widehat { P } _ { \mathbf { z } }$ is an exact permutation matrix (i.e., temperature $\tau 0$ ), this expression is exactly the negative of the fraction of $k$ nearest neighbors that have the same label as $\mathbf { x }$ .
Using Eq. 13, the training objectives for Deterministic and Stochastic NeuralSort are given as:
$$\operatorname* { m i n } _ { \phi } \frac { 1 } { | \mathcal { D } | } \sum _ { ( \mathbf { x } , y ) \in \mathcal { D } } \ell _ { \mathrm { k N N } } \big ( \widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } , y , y _ { 1 } , \dots , y _ { n } \big )$$
$$\operatorname* { m i n } _ { \phi } \frac { 1 } { | \mathcal { D } | } \sum _ { ( \mathbf { x } , y ) \in \mathcal { D } } \mathbb { E } _ { \mathbf { z } \sim q ( \mathbf { z } | \mathbf { s } ) } \left[ \ell _ { \mathrm { k N N } } ( \widehat { P } _ { \mathbf { z } } , y , y _ { 1 } , y _ { 2 } , \dots , y _ { n } ) \right]$$
where each entry of $\mathbf { s }$ is given as $s _ { j } = - \| h _ { \phi } ( \mathbf x ) - h _ { \phi } ( \mathbf x _ { j } ) \| _ { 2 } ^ { 2 }$ .
Datasets. We consider three benchmark datasetes: MNIST dataset of handwritten digits, FashionMNIST dataset of fashion apparel, and the CIFAR-10 dataset of natural images (no data augmentation) with the canonical splits for training and testing.
Baselines. We consider kNN baselines that operate in three standard representation spaces: the canonical pixel basis, the basis specified by the top 50 principal components (PCA), an autonencoder (AE). Additionally, we experimented with $k = 1 , 3 , 5 , 9$ nearest neighbors and across two distance metrics: uniform weighting of all $k$ -nearest neighbors and weighting nearest neighbors by the inverse of their distance. For completeness, we trained a CNN with the same architecture as the one used for NeuralSort (except the final layer) using the cross-entropy loss.
Results. We report the classification accuracies on the standard test sets in Table 3. On both datasets, the differentiable kNN classifier outperforms all the baseline kNN variants including the convolutional autoencoder approach. The performance is much closer to the accuracy of a standard CNN.
# 7 CONCLUSION
In this paper, we proposed NeuralSort, a continuous relaxation of the sorting operator to the set of unimodal row-stochastic matrices. Our relaxation facilitates gradient estimation on any computation graph involving a sort operator. Further, we derived a reparameterized gradient estimator for the Plackett-Luce distribution for efficient stochastic optimization over permutations. On three illustrative tasks including a fully differentiable $k$ -nearest neighbors, our proposed relaxations outperform prior work in end-to-end learning of semantic orderings of high-dimensional objects.
In the future, we would like to explore alternate relaxations to sorting as well as applications that extend widely-used algorithms such as beam search (Goyal et al., 2018). Both deterministic and stochastic NeuralSort are easy to implement. We provide reference implementations in Tensorflow (Abadi et al., 2016) and PyTorch (Paszke et al., 2017) in Appendix A. The full codebase for this work is open-sourced at https://github.com/ermongroup/neuralsort.
# ACKNOWLEDGEMENTS
This research was supported by NSF (#1651565, #1522054, #1733686), ONR, AFOSR (FA9550- 19-1-0024), FLI, and Amazon AWS. AG is supported by MSR fellowship and Stanford Data Science scholarship. We are thankful to Jordan Alexander, Kristy Choi, Adithya Ganesh, Karan Goel, Neal Jean, Daniel Levy, Jiaming Song, Yang Song, Serena Yeung, and Hugh Zhang for feedback.
# REFERENCES
Mart´ın Abadi, Paul Barham, Jianmin Chen, Zhifeng Chen, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Geoffrey Irving, Michael Isard, et al. Tensorflow: a system for largescale machine learning. In Operating Systems Design and Implementation, 2016.
Ryan Prescott Adams and Richard S Zemel. Ranking via Sinkhorn propagation. arXiv preprint arXiv:1106.1925, 2011.
Matej Balog, Nilesh Tripuraneni, Zoubin Ghahramani, and Adrian Weller. Lost relatives of the Gumbel trick. In International Conference on Machine Learning, 2017.
Yaakov Bar-Shalom and Xiao-Rong Li. Multitarget-multisensor tracking: principles and techniques. 1995.
Yoshua Bengio, Nicholas Leonard, and Aaron Courville. Estimating or propagating gradients ´ through stochastic neurons for conditional computation. arXiv preprint arXiv:1308.3432, 2013.
Leonard Berrada, Andrew Zisserman, and M Pawan Kumar. Smooth loss functions for deep top- $\mathbf { \nabla } \cdot \mathbf { k }$ classification. In International Conference on Learning Representations, 2018.
Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton, and Greg Hullender. Learning to rank using gradient descent. In International Conference on Machine learning, 2005.
Flavio Chierichetti, Ravi Kumar, and Andrew Tomkins. Discrete choice, permutations, and reconstruction. In Symposium on Discrete Algorithms, 2018.
Marcelo Fiori, Pablo Sprechmann, Joshua Vogelstein, Pablo Muse, and Guillermo Sapiro. Robust ´ multimodal graph matching: Sparse coding meets graph matching. In Advances in Neural Information Processing Systems, 2013.
Fajwel Fogel, Rodolphe Jenatton, Francis Bach, and Alexandre d’Aspremont. Convex relaxations for permutation problems. In Advances in Neural Information Processing Systems, 2013.
Michael C Fu. Gradient estimation. Handbooks in operations research and management science, 13:575–616, 2006.
Bolin Gao and Lacra Pavel. On the properties of the softmax function with application in game theory and reinforcement learning. arXiv preprint arXiv:1704.00805, 2017.
Paul Glasserman. Monte Carlo methods in financial engineering, volume 53. Springer Science & Business Media, 2013.
Peter W Glynn. Likelihood ratio gradient estimation for stochastic systems. Communications of the ACM, 33(10):75–84, 1990.
Kartik Goyal, Graham Neubig, Chris Dyer, and Taylor Berg-Kirkpatrick. A continuous relaxation of beam search for end-to-end training of neural sequence models. In AAAI Conference on Artificial Intelligence, 2018.
Eric Jang, Shixiang Gu, and Ben Poole. Categorical reparameterization with Gumbel-softmax. In International Conference on Learning Representations, 2017.
Carolyn Kim, Ashish Sabharwal, and Stefano Ermon. Exact sampling with integer linear programs and random perturbations. In AAAI Conference on Artificial Intelligence, 2016.
Diederik P Kingma and Max Welling. Auto-encoding variational Bayes. In International Conference on Learning Representations, 2014.
Cong Han Lim and Stephen J Wright. Sorting network relaxations for vector permutation problems. arXiv preprint arXiv:1407.6609, 2014.
Scott W Linderman, Gonzalo E Mena, Hal Cooper, Liam Paninski, and John P Cunningham. Reparameterizing the birkhoff polytope for variational permutation inference. In International Conference on Artificial Intelligence and Statistics, 2018.
Tie-Yan Liu et al. Learning to rank for information retrieval. Foundations and Trends $\textsuperscript { \textregistered }$ in Information Retrieval, 3(3):225–331, 2009.
R Duncan Luce. Individual choice behavior: A theoretical analysis. Courier Corporation, 1959.
Chris J Maddison, Andriy Mnih, and Yee Whye Teh. The concrete distribution: A continuous relaxation of discrete random variables. In International Conference on Learning Representations, 2017.
Gonzalo Mena, David Belanger, Scott Linderman, and Jasper Snoek. Learning latent permutations with gumbel-sinkhorn networks. In International Conference on Learning Representations, 2018.
Stephen Mussmann, Daniel Levy, and Stefano Ermon. Fast amortized inference and learning in log-linear models with randomly perturbed nearest neighbor search. In Uncertainty in Artificial Intelligence, 2017.
Wlodzimierz Ogryczak and Arie Tamir. Minimizing the sum of the $k$ largest functions in linear time. Information Processing Letters, 85(3):117–122, 2003.
Adam Paszke, Sam Gross, Soumith Chintala, Gregory Chanan, Edward Yang, Zachary DeVito, Zeming Lin, Alban Desmaison, Luca Antiga, and Adam Lerer. Automatic differentiation in pytorch. 2017.
Robin L Plackett. The analysis of permutations. Applied Statistics, pp. 193–202, 1975.
Michel Regenwetter, Bernard Grofman, Ilia Tsetlin, and AAJ Marley. Behavioral social choice: probabilistic models, statistical inference, and applications. Cambridge University Press, 2006.
Danilo Jimenez Rezende, Shakir Mohamed, and Daan Wierstra. Stochastic backpropagation and approximate inference in deep generative models. In International Conference on Machine Learning, 2014.
Leonardo Rigutini, Tiziano Papini, Marco Maggini, and Franco Scarselli. Sortnet: Learning to rank by a neural preference function. IEEE transactions on neural networks, 22(9):1368–1380, 2011.
John Schulman, Nicolas Heess, Theophane Weber, and Pieter Abbeel. Gradient estimation using stochastic computation graphs. In Advances in Neural Information Processing Systems, 2015.
Louis L Thurstone. A law of comparative judgment. Psychological review, 34(4):273, 1927.
Michalis Titsias and Miguel Lazaro-Gredilla. Doubly stochastic variational Bayes for non-conjugate ´ inference. In International Conference on Machine Learning, 2014.
Kilian Q Weinberger, John Blitzer, and Lawrence K Saul. Distance metric learning for large margin nearest neighbor classification. In Advances in Neural Information Processing Systems, 2006.
Ronald J Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine learning, 8(3-4):229–256, 1992.
Fen Xia, Tie-Yan Liu, Jue Wang, Wensheng Zhang, and Hang Li. Listwise approach to learning to rank: theory and algorithm. In International Conference on Machine Learning, 2008.
John I Yellott Jr. The relationship between luce’s choice axiom, thurstone’s theory of comparative judgment, and the double exponential distribution. Journal of Mathematical Psychology, 15(2): 109–144, 1977.
# APPENDICES
# A SORTING OPERATOR
A.1 TENSORFLOW
Sorting Relaxation for Deterministic NeuralSort:
import tensorflow as tf
def deterministic_NeuralSort(s, tau): """ s: input elements to be sorted. Shape: batch_size x n x 1 tau: temperature for relaxation. Scalar. """ $\begin{array} { r l } { \boldsymbol { \mathrm { n } } } & { { } = } \end{array}$ tf.shape(s)[1] one $=$ tf.ones((n, 1), dtype $=$ tf.float32) $\begin{array} { r l } { \mathbb { A } \_ s } & { { } = } \end{array}$ tf.abs(s - tf.transpose(s, perm $1 =$ [0, 2, 1])) $\begin{array} { r l } { \mathrm { \large ~ B ~ } } & { { } = } \end{array}$ tf.matmul(A_s, tf.matmul(one, tf.transpose(one))) scaling $=$ tf.cast(n + 1 - 2 $\star$ (tf.range(n) + 1), dtype $=$ tf.float32) ${ \mathrm { ~ \small ~ \mathscr ~ { ~ C ~ } ~ } } =$ tf.matmul(s, tf.expand_dims(scaling, 0)) P_max $=$ tf.transpose(C-B, perm ${ \_ }$ [0, 2, 1]) P_hat $=$ tf.nn.softmax(P_max / tau, $^ { - 1 }$ )
return P_hat
# Reparameterized Sampler for Stochastic NeuralSort:
def sample_gumbel(samples_shape, eps = 1e-10):
U $=$ tf.random_uniform(samples_shape, minval ${ } = 0$ , maxval $^ { = 1 }$ ) return -tf.log(-tf.log(U $^ +$ eps) $^ +$ eps)
def stochastic_NeuralSort(s, n_samples, tau):
s: parameters of the PL distribution. Shape: batch_size x n x 1. n_samples: number of samples from the PL distribution. Scalar. tau: temperature for the relaxation. Scalar. """ batch_size $=$ tf.shape(s)[0] $\begin{array} { r l } { \boldsymbol { \mathrm { n } } } & { { } = } \end{array}$ tf.shape(s)[1] log_s_perturb $=$ s $^ +$ sample_gumbel([n_samples, batch_size, n, 1]) log_s_perturb $=$ tf.reshape(log_s_perturb, [n_samples $\star$ batch_size, n, 1])
P_hat $=$ deterministic_NeuralSort(log_s_perturb, tau) P_hat $=$ tf.reshape(P_hat, [n_samples, batch_size, n, n])
return P_hat
# A.2 PYTORCH
Sorting Relaxation for Deterministic NeuralSort:
# import torch
def deterministic_NeuralSort(s, tau): """ s: input elements to be sorted. Shape: batch_size x n x 1 tau: temperature for relaxation. Scalar. """ $\mathrm { ~ \scriptsize ~ n ~ } = \mathrm { ~ \scriptsize ~ s ~ }$ .size()[1] one $=$ torch.ones((n, 1), dtype $=$ torch.float32) $\begin{array} { r l } { \mathbb { A } \_ s } & { { } = } \end{array}$ torch.abs(s - s.permute(0, 2, 1)) $\begin{array} { r l } { \mathrm { \large ~ B ~ } } & { { } = } \end{array}$ torch.matmul(A_s, torch.matmul(one, torch.transpose(one, 0, 1))) scali $\begin{array} { r } { \mathbf { { \nabla } } \cdot \boldsymbol { \nabla } \mathrm { ~ ~ \psi ~ } = \mathrm { ~ ~ \psi ~ } ( \mathrm { ~ n ~ \xi ~ } + \mathrm { ~ ~ \xi ~ } ] } \end{array}$ - 2 \* (torch.arange(n) $^ { + } ~ \bot )$ ).type(torch.float32) ${ \mathrm { ~ \small ~ \mathscr ~ { ~ C ~ } ~ } } =$ torch.matmul(s, scaling.unsqueeze(0)) P_max $=$ (C-B).permute(0, 2, 1) sm $=$ torch.nn.Softmax(-1) P_hat $=$ sm(P_max / tau) return P_hat
# Reparamterized Sampler for Stochastic NeuralSort:
def sample_gumbel(samples_shape, eps $=$ 1e-10): U $=$ torch.rand(samples_shape) return -torch.log(-torch.log(U + eps) + eps) def stochastic_NeuralSort(s, n_samples, tau): """ s: parameters of the PL distribution. Shape: batch_size x n x 1. n_samples: number of samples from the PL distribution. Scalar. tau: temperature for the relaxation. Scalar. """ batch_size $=$ s.size()[0] $\mathrm { ~ \scriptsize ~ n ~ } = \mathrm { ~ \scriptsize ~ s ~ }$ .size()[1] log_s_perturb $=$ torch.log(s) $^ +$ sample_gumbel([n_samples, batch_size, n, 1]) log_s_perturb $=$ log_s_perturb.view(n_samples $\star$ batch_size, n, 1) P_hat $=$ deterministic_NeuralSort(log_s_perturb, tau) P_hat $=$ P_hat.view(n_samples, batch_size, n, n) return P_hat
# B PROOFS OF THEORETICAL RESULTS
B.1 LEMMA 2
Proof. For any value of $\lambda$ , the following inequalities hold:
$$\begin{array} { l } { \displaystyle \sum _ { i = 1 } ^ { k } s _ { [ i ] } = \lambda k + \sum _ { i = 1 } ^ { k } ( s _ { [ i ] } - \lambda ) } \\ { \displaystyle \qquad \leq \lambda k + \sum _ { i = 1 } ^ { k } \operatorname* { m a x } ( s _ { [ i ] } - \lambda , 0 ) } \\ { \displaystyle \qquad \leq \lambda k + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } ( s _ { i } - \lambda , 0 ) . } \end{array}$$
Furthermore, for $\lambda = s _ { [ k ] }$ :
$$\begin{array} { l } { { \displaystyle \lambda k + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } \bigl ( s _ { i } - \lambda , 0 \bigr ) = s _ { [ k ] } k + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } \bigl ( s _ { i } - s _ { [ k ] } , 0 \bigr ) } } \\ { ~ } \\ { { \displaystyle ~ = s _ { [ k ] } k + \sum _ { i = 1 } ^ { k } ( s _ { [ i ] } - s _ { [ k ] } ) } } \\ { { \displaystyle ~ = \sum _ { i = 1 } ^ { k } s _ { [ i ] } . } } \end{array}$$
This finishes the proof.
# B.2 COROLLARY 3
Proof. We first consider at exactly what values of $\lambda$ the sum in Lemma 2 is minimized. For simplicity we will only prove the case where all values of s are distinct.
The equality Lemma 2, the $\begin{array} { r } { \sum _ { i = 1 } ^ { k } s _ { [ i ] } = \lambda k + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } ( s _ { i } - \lambda , 0 ) } \end{array}$ holds only when he equality. $s _ { [ k ] } \leq \lambda \leq s _ { [ k + 1 ] }$ . By $\lambda$
Symmetrically, if one considers the score vector $\mathbf { t } = - \mathbf { s }$ , then $\begin{array} { r } { \lambda ( n - k + 1 ) + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } ( t _ { i } - \lambda , 0 ) } \end{array}$ is minimized at t[n−k+1] ≤ λ ≤ t[n−k+2].
Replacing $\lambda$ by $- \lambda$ and using the definition of $\mathbf { t }$ implies that $\begin{array} { r } { \lambda ( k - 1 - n ) + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } ( \lambda - s _ { i } , 0 ) } \end{array}$ is minimized at s[k−1] ≤ λ ≤ s[k].
It follows that:
$$\begin{array} { l } { { \displaystyle s _ { [ k ] } = \arg \operatorname* { m i n } _ { \lambda \in \mathbf { s } } \left( \lambda k + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } ( s _ { i } - \lambda , 0 ) \right) + \left( \lambda ( k - 1 - n ) + \sum _ { i = 1 } ^ { n } \operatorname* { m a x } ( \lambda - s _ { i } , 0 ) \right) } } \\ { { \displaystyle \quad = \arg \operatorname* { m i n } _ { \lambda \in \mathbf { s } } \lambda ( 2 k - 1 - n ) + \sum _ { i = 1 } ^ { n } \vert s _ { i } - \lambda \vert . } } \end{array}$$
Thus, if $s _ { i } = s _ { [ k ] }$ , then $i = \arg \operatorname* { m i n } ( 2 k - 1 - n ) \mathbf { s } + A _ { \mathbf { s } } \mathbf { 1 }$ . This finishes the proof.
# B.3 THEOREM 4
We prove the two properties in the statement of the theorem independently:
# 1. Unimodality
Proof. By definition of the softmax function, the entries ef $\widehat { P }$ are positive and sum to 1. To show that $\widehat { P }$ satisfies the argmax permutation property, . Formally, for any given row $i$ , we construct the argmax permutation vector $\mathbf { u }$ as:
$$\begin{array} { l } { u _ { i } = \arg \operatorname* { m a x } [ \operatorname { s o f t } \operatorname* { m a x } ( ( n + 1 - 2 i ) \mathbf { s } - A _ { \mathbf { s } } \mathbf { \mathbb { 1 } } ) ] } \\ { \quad = \arg \operatorname* { m a x } [ ( n + 1 - 2 i ) \mathbf { s } - A _ { \mathbf { s } } \mathbf { \mathbb { 1 } } ] } \\ { \quad = [ i ] } \end{array}$$
where the square notation $[ i ]$ denotes the index of the $i$ -th largest element. The first step follows from the fact that the softmax function is monotonically increasing and hence, it preserves the argmax. The second equality directly follows from Corollary 3. By definition, $\mathsf { \bar { s o r t } } ( \mathbf { s } ) = \{ [ 1 ] , [ 2 ] , \dots , [ n ] \}$ , finishing the proof. □
# 2. Limiting behavior
Proof. As shown in Gao & Pavel (2017), the softmax function may be equivalently defined as soft $\begin{array} { r } { \mathrm { m a x } ( z / \tau ) ~ = ~ \mathrm { a r g } \mathrm { m a x } _ { x \in \Delta ^ { n - 1 } } \langle x , z \rangle - \tau \sum _ { i = 1 } ^ { n } x _ { i } \log \dot { x } _ { i } } \end{array}$ . In particular, $\mathrm { l i m } _ { \tau \to 0 }$ soft $\operatorname* { m a x } ( z / \tau ) = \arg \operatorname* { m a x } x$ . The distributional assumptions ensure that the elements of s are distinct a.s., so plugging in $z = ( n + 1 - 2 k ) \mathbf { s } - A _ { \mathbf { s } } \mathbf { 1 }$ completes the proof. □
# B.4 PROPOSITION 5
This result follows from an earlier result by Yellott Jr (1977). We give the proof sketch below and refer the reader to Yellott Jr (1977) for more details.
Sketch. Consider random variables $\{ X _ { i } \} _ { i = 1 } ^ { n }$ such that $X _ { i } \sim \mathrm { E x p } ( s _ { z _ { i } } ) )$ .
We may prove by induction a generalization of the memoryless property:
$$\begin{array} { r l } { { q ( X _ { 1 } \leq \cdots \leq X _ { n } | x \leq \operatorname* { m i n } X _ { i } ) } } \\ & { = \int _ { 0 } ^ { \infty } q ( x \leq X _ { 1 } \leq x + t | x \leq \operatorname* { m i n } _ { i } X _ { i } ) q ( X _ { 2 } \leq \cdots \leq X _ { n } | x + t \leq \operatorname* { m i n } _ { i \geq 2 } X _ { i } ) \mathrm { d } t } \\ & { = \displaystyle \int _ { 0 } ^ { \infty } q ( 0 \leq X _ { 1 } \leq t ) q ( X _ { 2 } \leq \cdots \leq X _ { n } | x + t \leq \operatorname* { m i n } _ { i \geq 2 } X _ { i } ) \mathrm { d } t . } \end{array}$$
If we assume as inductive hypothesis that $q ( X _ { 2 } \leq \cdots \leq X _ { n } | x + t \leq \operatorname* { m i n } _ { i \geq 2 } X _ { i } ) = q ( X _ { 2 } \leq \cdots \leq$ $X _ { n } | t \leq \operatorname* { m i n } _ { i \geq 2 } X _ { i } )$ , we complete the induction as:
$$\begin{array} { l } { \displaystyle q ( X _ { 1 } \leq \cdots \leq X _ { n } | x \leq \operatorname* { m i n } X _ { i } ) } \\ { \displaystyle = \int _ { 0 } ^ { \infty } q ( 0 \leq X _ { 1 } \leq t ) q ( X _ { 2 } \leq \cdots \leq X _ { n } | t \leq \operatorname* { m i n } X _ { i } ) \mathrm { d } t } \\ { \displaystyle = q ( X _ { 1 } \leq X _ { 2 } \leq \cdots \leq X _ { n } | 0 \leq \operatorname* { m i n } X _ { i } ) . } \end{array}$$
It follows from a familiar property of argmin of exponential distributions that:
$$\begin{array} { r l } { q ( X _ { 1 } \leq X _ { 2 } \leq \cdots \leq X _ { n } ) = q ( X _ { 1 } \leq \operatorname* { m i n } X _ { i } ) q ( X _ { 2 } \leq \cdots \leq X _ { n } | X _ { 1 } \leq \operatorname* { m i n } X _ { i } ) } & { } \\ { \quad } & { = \frac { s _ { z _ { 1 } } } { Z } q ( X _ { 2 } \leq \cdots \leq X _ { n } | X _ { 1 } \leq \operatorname* { m i n } X _ { i } ) } \\ { \quad } & { = \frac { s _ { z _ { 1 } } } { Z } \displaystyle \int _ { 0 } ^ { \infty } q ( X _ { 1 } = x ) q ( X _ { 2 } \leq \cdots \leq X _ { n } | x \leq \operatorname* { m i n } X _ { i } ) \mathrm { d } x } \\ { \quad } & { = \frac { s _ { z _ { 1 } } } { Z } q ( X _ { 2 } \leq \cdots \leq X _ { n } ) , } \end{array}$$
and by another induction, we have q(X1 ≤ · · · ≤ Xn) = Qni=1 sziZ−Pi−1k=1 szk .
Finally, following the argument of Balog et al. (2017), we apply the strictly decreasing function $g ( x ) = - \beta \log x$ to this identity, which from the definition of the Gumbel distribution implies:
$$q ( \tilde { s } _ { z _ { 1 } } \geq \cdot \cdot \cdot \geq \tilde { s } _ { z _ { n } } ) = \prod _ { i = 1 } ^ { n } { \frac { s _ { z _ { i } } } { Z - \sum _ { k = 1 } ^ { i - 1 } s _ { z _ { k } } } } .$$
# C ARG MAX SEMANTICS FOR TIED MAX ELEMENTS
While applying the arg max operator to a vector with duplicate entries attaining the max value, we need to define the operator semantics for arg max to handle ties in the context of the proposed relaxation.
Definition 6. For any vector with ties, let arg max set denote the operator that returns the set of all indices containing the max element. We define the arg max of the i-th in a matrix M recursively:
1. If there exists an index $j \in \{ 1 , 2 , \dots , n \}$ that is a member of arg max $\mathrm { s e t } ( M [ i , : ] )$ and has not been assigned as an arg max of any row $k < i ,$ , then the arg max is the smallest such index.
2. Otherwise, the arg max is the smallest index that is a member of the arg max $\mathrm { s e t } ( M [ i , : ] )$
This function is efficiently computable with additional bookkeeping.
Lemma 7. For an input vector s with the sort permutation matrix given as $P _ { s o r t ( \mathbf { s } ) }$ , we have $s _ { j _ { 1 } } =$ $s _ { j _ { 2 } }$ if and only if there exists a row $i$ such that $\widehat { P } [ i , j _ { 1 } ] = \widehat { P } [ i , j _ { 2 } ]$ for all $j _ { 1 } , j _ { 2 } \in \{ 1 , 2 , . . . , n \}$ .
Proof. From Eq. 5, we have the $i$ -th row of ${ \widehat P } [ i , : ]$ given as:
$$\widehat { P } [ i , : ] = \mathrm { s o f t } \operatorname* { m a x } \left[ ( ( n + 1 - 2 i ) \mathbf { s } - A _ { \mathbf { s } } \mathbf { 1 } ) / \tau \right]$$
. Therefore, we have the equations:
$${ \widehat { P } } [ i , j _ { 1 } ] = { \frac { \exp ( ( ( n + 1 - 2 i ) s _ { j _ { 1 } } - ( A _ { { \mathbf { s } } } \mathbb { 1 } ) _ { i } ) / \tau ) } { Z } }$$
$$= \widehat { P } [ i , j _ { 2 } ] = \frac { \exp ( ( ( n + 1 - 2 i ) s _ { j _ { 2 } } - ( A _ { \mathbf { s } } \mathbf { 1 } ) _ { i } ) / \tau ) } { Z }$$
for some fixed normalization constant Z. As the function f (x) = exp(((n+1−2i)x−(As1)i)/τ)Z is invertible, both directions of the lemma follow immediately.
Lemma 8. If arg max $\mathrm { s e t } ( \widehat { P } [ i _ { 1 } , : ] )$ and arg max $\mathrm { s e t } ( \widehat { P } [ i _ { 2 } , : ] )$ have a non-zero intersection, then arg max $\begin{array} { r } { \mathrm { s e t } ( \widehat { P } [ i _ { 1 } , : ] ) = \arg \operatorname* { m a x } \mathrm { s e t } ( \widehat { P } [ i _ { 2 } , : ] ) } \end{array}$ .
Proof. Assume without loss of generality that | arg max $\mathrm { s e t } ( \widehat { P } [ i _ { 1 } , : ] ) | \ > \ 1$ for some $i$ . Let $j _ { 1 } , j _ { 2 }$ be two members of $| \arg \operatorname* { m a x } \sec ( \widehat { P } [ i _ { 1 } , : ] ) |$ . By Lemma 7, $\begin{array} { r l r } { s _ { j _ { 1 } } } & { { } = } & { s _ { j _ { 2 } } } \end{array}$ , and therefore $\widehat { P } [ i _ { 2 } , j _ { 1 } ] = \widehat { P } [ i _ { 2 } , j _ { 2 } ]$ . Hence if $j _ { 1 } \in \arg \operatorname* { m a x } \mathrm { s e t } ( \widehat { P } [ i _ { 2 } , : ] )$ , then $j _ { 2 }$ is also an element. A symmetric argument implies that if $j _ { 2 } \in \arg \operatorname* { m a x } \mathrm { s e t } ( \widehat { P } [ i _ { 2 } , : ] )$ , then $j _ { 1 }$ is also an element for arbitrary $j _ { 1 } , j _ { 2 } \in | \arg \operatorname* { m a x } \mathrm { s e t } ( \widehat { P } [ i _ { 1 } , : ] ) |$ . This completes the proof. □
Proposition 9. (Argmax Permutation with Ties) For $\mathbf { s } ~ = ~ [ s _ { 1 } , s _ { 2 } , \ldots , s _ { n } ] ^ { T } ~ \in ~ \mathbb { R } ^ { n }$ , the vector $\mathbf { z }$ defined by $z _ { i } = \arg \operatorname* { m a x } _ { j } \widehat { P } _ { s o r t ( \mathbf { s } ) } [ i , j ]$ is such that $\mathbf { z } \in \mathcal { Z } _ { n }$ .
 Figure 6: A stochastic computation graph for an arbitrary input $x$ , intermediate node $y$ , and a single parameter $\theta$ . Squares denote deterministic nodes and circles denote stochastic nodes.
Proof. From Corollary 3, we know that the row $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } [ i , : ]$ attains its maximum (perhaps nonuniquely) at some $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } [ i , j ]$ where $s _ { j } = s _ { [ i ] }$ . Note that $s _ { [ i ] }$ is well-defined even in the case of ties.
Consider an arbitrary row $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } [ i , : ]$ and let arg max $\sec ( { \widehat { P } } _ { \mathrm { s o r t } ( \mathbf { s } ) } [ i , : ] ) = \{ j _ { 1 } , \dots , j _ { m } \}$ . It follows from Lemma 7 that there are exactly $m$ scores in s that are equal to $s _ { [ i ] }$ : $: s _ { j _ { 1 } } , \ldots , s _ { j _ { m } }$ . These scores corresponds to $m$ values of $s _ { [ i ^ { \prime } ] }$ such that $s _ { [ i ^ { \prime } ] } = s _ { [ i ] }$ , and consequently to $m$ rows $P [ i ^ { \prime } , : ]$ that are maximized with values $s _ { [ i ^ { \prime } ] } = s _ { [ i ] }$ and consequently (by Lemma 8) at indices $j _ { 1 } , \dots , j _ { m }$ .
Suppose we now chose an $i ^ { \prime }$ such that $s _ { [ i ^ { \prime } ] } \neq s _ { [ i ] }$ . Then $\widehat { P } [ i ^ { \prime } , : ]$ attains its maximum at some $\widehat { P } \mathrm { s o r t } ( \mathbf { s } ) [ i ^ { \prime } , j ^ { \prime } ]$ where $s _ { j ^ { \prime } } = s _ { [ i ^ { \prime } ] }$ . Because $s _ { j ^ { \prime } } = s _ { [ i ^ { \prime } ] } \neq s _ { [ i ] } = s _ { j }$ , Lemma 7 tells us that $\widehat { P } [ i ^ { \prime } , : ]$ does not attain its maximum at any of $j _ { 1 } , \dots , j _ { m }$ . Therefore, only $m$ rows have a non-zero arg max set intersection with arg max se $\mathrm { t } ( P [ i , : ] )$ .
Because $P [ i , : ]$ is one of these rows, there can be up to $m - 1$ such rows above it. Because each row above only has one arg max assigned via the tie-breaking protocol, it is only possible for up to $m - 1$ elements of arg max $\mathrm { s e t } ( P [ i , : ] )$ to have been an arg max of a previous row $k < i$ . As | arg max $\mathrm { s e t } ( P [ i , : ] ) | = { \bar { m } }$ , there exists at least one element that has not been specified as the arg max of a previous row (pigeon-hole principle). Thus, the arg max of each row are distinct. Because each argmax is also an element of $\{ 1 , \ldots , n \}$ , it follows that $\mathbf { z } \in \mathcal { Z } _ { n }$ . □
# D EXPERIMENTAL DETAILS AND ANALYSIS
We used Tensorflow (Abadi et al., 2016) and PyTorch (Paszke et al., 2017) for our experiments. In Appendix A, we provide “plug-in” snippets for implementing our proposed relaxations in both Tensorflow and PyTorch. The full codebase for reproducing the experiments can be found at https://github.com/ermongroup/neuralsort.
For the sorting and quantile regression experiments, we used standard training/validation/test splits of $5 0 , 0 0 0 / 1 0 \bar { , } 0 0 0 / \bar { 1 0 } , 0 0 0$ images of MNIST for constructing the large-MNIST dataset. We ensure that only digits in the standard training/validation/test sets of the MNIST dataset are composed together to generate the corresponding sets of the large-MNIST dataset. For CIFAR-10, we used a split of 45, 000/5000/10, 000 examples for training/validation/test. With regards to the baselines considered, we note that the REINFORCE based estimators were empirically observed to be worse than almost all baselines for all our experiments.
# D.1 SORTING HANDWRITTEN NUMBERS
Architectures. We control for the choice of computer vision models by using the same convolutional network architecture for each sorting method. This architecture is as follows:
Conv[Kernel: 5x5, Stride: 1, Output: 140x28x32, Activation: Relu] Pool[Stride: 2, Output: 70x14x32] Conv[Kernel: 5x5, Stride: 1, Output: 70x14x64, Activation: Relu] Pool[Stride: 2, Output: 35x7x64] FC[Units: 64, Activation: Relu]
 Figure 7: Running average of the log-variance in gradient estimates during training for varying temperatures $\tau$ .
Note that the dimension of a 5-digit large-MNIST image is $1 4 0 \times 2 8$ . The primary difference between our methods is how we combine the scores to output a row-stochastic prediction matrix.
For NeuralSort-based methods, we use another fully-connected layer of dimension 1 to map the image representations to $n$ scalar scores. In the case of Stochastic NeuralSort, we then sample from the PL distribution by perturbing the scores multiple times with Gumbel noise. Finally, we use the NeuralSort operator to map the set of $n$ scores (or each set of $n$ perturbed scores) to its corresponding unimodal row-stochastic matrix.
For Sinkhorn-based methods, we use a fully-connected layer of dimension $n$ to map each image to an $n$ -dimensional vector. These vectors are then stacked into an $n \times n$ matrix. We then either map this matrix to a corresponding doubly-stochastic matrix (Sinkhorn) or sample directly from a distribution over permutation matrices via Gumbel perturbations (Gumbel-Sinkhorn). We implemented the Sinkhorn operator based on code snippets obtained from the open source implementation of Mena et al. (2018) available at https://github.com/google/gumbel sinkhorn.
For the Vanilla RS baseline, we ran each element through a fully-connected $n$ dimensional layer, concatenated the representations of each element and then fed the results through three fullyconnected $n ^ { 2 }$ -unit layers to output multiclass predictions for each rank.
All our methods yield row-stochastic $n \times n$ matrices as their final output. Our loss is the row-wise cross-entropy loss between the true permutation matrix and the row-stochastic output.
Hyperparameters. For this experiment, we used an Adam optimizer with an initial learning rate of $1 0 ^ { - 4 }$ and a batch size of 20. Continuous relaxations to sorting also introduce another hyperparameter: the temperature $\tau$ for the Sinkhorn-based and NeuralSort-based approaches. We tuned this hyperparameter on the set $\{ 1 , 2 , 4 , 8 , 1 6 \}$ by picking the model with the best validation accuracy on predicting entire permutations (as opposed to predicting individual maps between elements and ranks).
Effect of temperature. In Figure 7, we report the log-variance in gradient estimates as a function of the temperature $\tau$ . Similar to the effect of temperature observed for other continuous relaxations to discrete objects such as Gumbel-softmax (Jang et al., 2017; Maddison et al., 2017), we note that higher temperatures lead to lower variance in gradient estimates. The element-wise mean squared difference between unimodal approximations Pbsort(s) and the projected hard permutation matrices $P _ { \mathsf { s o r t } ( \mathbf { s } ) }$ for the best $\tau$ on the test set is shown in Table 4.
Table 4: Element-wise mean squared difference between unimodal approximations and the projected hard permutation matrices for the best temperature $\tau$ , averaged over the test set.
<table><tr><td>Algorithm</td><td>|n=3</td><td>n=5</td><td>n=7</td><td>n=9</td><td>n=15</td></tr><tr><td>Deterministic NeuralSort</td><td>0.0052</td><td>0.0272</td><td>0.0339</td><td>0.0105</td><td>0.0220</td></tr><tr><td>Stochastic NeuralSort</td><td>0.0095</td><td>0.0327</td><td>0.0189</td><td>0.0111</td><td>0.0179</td></tr></table>
 Figure 8: True vs. predicted medians for quantile regression on the large-MNIST dataset.
# D.2 QUANTILE REGRESSION
Architectures. Due to resource constraints, we ran the quantile regression experiment on 4-digit numbers instead of 5-digit numbers. We use the same neural network architecture as previously used in the sorting experiment.
Conv[Kernel: 5x5, Stride: 1, Output: 112x28x32, Activation: Relu] Pool[Stride: 2, Output: 56x14x32] Conv[Kernel: 5x5, Stride: 1, Output: 56x14x64, Activation: Relu] Pool[Stride: 2, Output: 28x7x64] FC[Units: 64, Activation: Relu]
The vanilla NN baseline for quantile regression was generated by feeding the CNN representations into a series of three fully-connected layers of ten units each, the last of which mapped to a singleunit estimate of the median. In the other experiments, one copy of this network was used to estimate each element’s rank through a method like Gumbel-Sinkhorn or NeuralSort that produces a rowstochastic matrix, while another copy was used to estimate each element’s value directly. Point predictions are obtained by multiplying the center row of the matrix with the column vector of estimated values, and we minimize the $\ell _ { 2 }$ loss between these point predictions and the true median, learning information about ordering and value simultaneously.
Hyperparameters. We used the Adam optimizer with an initial learning rate of $1 0 ^ { - 4 }$ and a batch size of 5. The temperature $\tau$ was tuned on the set $\{ 1 , 2 , 4 , 8 , 1 6 \}$ based on the validation loss.
Further Analysis. In Figure 8, we show the scatter plots for the true vs. predicted medians on 2000 test points from the large-MNIST dataset as we vary $n$ . For stochastic NeuralSort, we average the predictions across 5 samples. As we increase $n$ , the distribution of true medians concentrates, leading to an easier prediction problem (at an absolute scale) and hence, we observe lower MSE for larger $n$ in Table 2. However, the relatively difficulty of the problem increases with increasing $n$ , as the model is trying to learn a semantic sorting across a larger set of elements. This is reflected in the $R ^ { 2 }$ values in Table 2 which show a slight dip as $n$ increases.
D.3 END-TO-END, DIFFERENTIABLE $k$ -NEAREST NEIGHBORS
Architectures. The baseline kNN implementation for the pixel basis, PCA basis and the autoencoder basis was done using sklearn. For the autoencoder baselines for kNN, we used the following standard architectures.
MNIST and Fashion-MNIST: The dimension of the encoding used for distance computation in kNN is 50.
$$\begin{array} { r l } & { \mathrm { F C [ U n i t s : ~ 5 0 0 , ~ A c t i v a t i o n : ~ R e l u ] } } \\ & { ~ \mathrm { F C [ U n i t s : ~ 5 0 0 , ~ A c t i v a t i o n : ~ R e l u ] } } \\ & { ~ \mathrm { F C [ U n i t s : ~ 5 0 , ~ A c t i v a t i o n : ~ R e l u ] } } \\ & { ~ = ( e m b e d d i n g ) } \\ & { ~ \mathrm { F C [ U n i t s : ~ 5 0 0 , ~ A c t i v a t i o n : ~ R e l u ] } } \\ & { ~ \mathrm { F C [ U n i t s : ~ 5 0 0 , ~ A c t i v a t i o n : ~ R e l u ] } } \\ & { ~ \mathrm { F C [ U n i t s : ~ 7 8 4 , ~ A c t i v a t i o n : ~ S i g m o i d } } \end{array}$$
CIFAR-10: The dimension of the encoding used for distance computation in kNN is 256. The architecture and training procedure follows the one available at https://github.com/shibuiwilliam/Keras Autoencoder.
Conv[Kernel: 3x3, Stride: 1, Output: 32x32x64, Activation: Relu] Pool[Stride: 2, Output: 16x16x64] Conv[Kernel: 3x3, Stride: 1, Output: 16x16x32, Normalization: BatchNorm, Activation: Relu] Pool[Stride: 2, Output: 8x8x32] Conv[Stride: 3, Output: 8x8x16, Normalization: BatchNorm, Activation: Relu] MaxPool[Stride: 2, Output: 4x4x16] $=$ (embedding) Conv[Kernel: 3x3, Stride: 1, Output: 4x4x16, Normalization: BatchNorm, Activation: Relu] UpSampling[Size: 2x2, Output: 8x8x16] Conv[Kernel: 3x3, Stride: 1, Output: 8x8x32, Normalization: BatchNorm, Activation: Relu] UpSampling[Size: 2x2, Output: 16x16x32] Conv[Kernel: 3x3, Output: 16x16x64, Normalization: BatchNorm, Activation: Relu] UpSampling[Size: 2x2, Output: 32x32x64] Conv[Kernel: 3x3, Stride: 1, Output: 32x32x3, Normalization: BatchNorm, Activation: Sigmoid
Table 5: Accuracies of Deterministic and Stochastic NeuralSort for differentiable $k$ -nearest neighbors, broken down by $k$ .
<table><tr><td>Dataset</td><td>k</td><td>Deterministic NeuralSort</td><td>Stochastic NeuralSort</td></tr><tr><td rowspan="4">MNIST</td><td>1</td><td>99.2%</td><td>99.1%</td></tr><tr><td>35</td><td>99.5%</td><td>99.3%</td></tr><tr><td></td><td>99.3%</td><td>99.4%</td></tr><tr><td>9</td><td>99.3%</td><td>99.4%</td></tr><tr><td rowspan="4">Fashion-MNIST</td><td></td><td>92.6%</td><td>92.2%</td></tr><tr><td></td><td>93.2%</td><td>93.1%</td></tr><tr><td></td><td>93.5%</td><td>93.3%</td></tr><tr><td>1359</td><td>93.0%</td><td>93.4%</td></tr><tr><td rowspan="4">CIFAR-10</td><td>1</td><td>88.7%</td><td>85.1%</td></tr><tr><td>1359</td><td>90.0%</td><td>87.8%</td></tr><tr><td></td><td>90.2%</td><td>88.0%</td></tr><tr><td></td><td>90.7%</td><td>89.5%</td></tr></table>
For the MNIST experiments with NeuralSort, we used a network similar to the large-MNIST network used in the previous experiments:
Conv[Kernel: 5x5, Stride: 1, Output: $2 4 \mathrm { x } 2 4 \mathrm { x } 2 0$ , Activation: Relu] Pool[Stride: 2, Output: $1 2 \mathrm { x } 1 2 \mathrm { x } 2 0 $ ] Conv[Kernel: 5x5, Stride: 1, Output: 8x8x50, Activation: Relu] Pool[Stride: 2, Output: 4x4x50] FC[Units: 500, Activation: Relu]
For the Fashion-MNIST and CIFAR experiments with NeuralSort, we use the ResNet18 architecture as described in https://github.com/kuangliu/pytorch-cifar.
Hyperparameters. For this experiment, we used an SGD optimizer with a momentum parameter of 0.9, with a batch size of 100 queries and 100 neighbor candidates at a time. We chose the temperature hyperparameter from the set $\{ 1 , 1 6 , 6 4 \}$ , the constant learning rate from $\lbrace 1 0 ^ { - 4 } , 1 0 ^ { - 5 } \rbrace$ , and the number of nearest neighbors $k$ from the set $\{ 1 , 3 , 5 , 9 \}$ . The model with the best evaluation loss was evaluated on the test set. We suspect that accuracy improvements can be made by a more expensive hyperparameter search and a more fine-grained learning rate schedule.
Accuracy for different $k$ . In Table 5, we show the performance of Deterministic and Stochastic NeuralSort for different choice of the hyperparameter $k$ for the differentiable $k$ -nearest neighbors algorithm.
# E LOSS FUNCTIONS
For each of the experiments in this work, we assume we have access to a finite dataset $\mathcal { D } =$ $\{ ( { \bf x } ^ { ( 1 ) } , { \bf y } ^ { ( 1 ) } ) , ( { \bf x } ^ { ( 2 ) } , { \bf \bar { y } } ^ { ( 2 ) } ) , \dots \}$ . Our goal is to learn a predictor for $\mathbf { y }$ given $\mathbf { x }$ , as in a standard supervised learning (classification/regression) setting. Below, we state and elucidate the semantics of the training objective optimized by Deterministic and Stochastic NeuralSort for the sorting and quantile regression experiments.
# E.1 SORTING HANDWRITTEN NUMBERS
We are given a dataset $\mathcal { D }$ of sequences of large-MNIST images and the permutations that sort the sequences. That is, every datapoint in $\mathcal { D }$ consists of an input $\mathbf { x }$ , which corresponds to a sequence containing $n$ images, and the desired output label $\mathbf { y }$ , which corresponds to the permutation that sorts this sequence (as per the numerical values of the images in the input sequence). For example, Figure 4 shows one input sequence of $n = 5$ images, and the permutation $\mathbf { \bar { y } } = [ 3 , 5 , 1 , 4 , 2 ]$ that sorts this sequence.
For any datapoint $\mathbf { x }$ , let $\ell _ { \mathrm { C E } } ( \cdot )$ denote the average multiclass cross entropy (CE) error between the rows of the true permutation matrix $P _ { \mathbf { y } }$ and a permutation matrix $P _ { \widehat { \mathbf { y } } }$ corresponding to a predicted permutation, say $\widehat { \mathbf { y } }$ .
$$\ell _ { \mathrm { { C E } } } ( P _ { \mathbf { y } } , P _ { \widehat { \mathbf { y } } } ) = \frac { 1 } { n } \sum _ { i = 1 } ^ { n } \sum _ { j = 1 } ^ { n } \mathbb { 1 } ( P _ { \mathbf { y } } [ i , j ] = 1 ) \log P _ { \widehat { \mathbf { y } } } [ i , j ]$$
where $\mathbb { 1 } ( \cdot )$ denotes the indicator function. Now, we state the training objective functions for the Deterministic and Stochastic NeuralSort approaches respectively.
1. Deterministic NeuralSort
$$\operatorname* { m i n } _ { \phi } \frac { 1 } { | \mathcal { D } | } \sum _ { ( \mathbf { x } , \mathbf { y } ) \in \mathcal { D } } \ell _ { \mathrm { C E } } ( P _ { \mathbf { y } } , \widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } )$$
where each entry of $\mathbf { s }$ is given as $s _ { j } = h _ { \phi } ( \mathbf { x } _ { j } )$
2. Stochastic NeuralSort
$$\operatorname* { m i n } _ { \phi } \frac { 1 } { | \mathcal { D } | } \sum _ { ( \mathbf { x } , \mathbf { y } ) \in \mathcal { D } } \mathbb { E } _ { \mathbf { z } \sim q ( \mathbf { z } | \mathbf { s } ) } \left[ \ell _ { \mathrm { C E } } ( P _ { \mathbf { y } } , \widehat { P } _ { \mathbf { z } } ) ) \right]$$
where each entry of $\mathbf { s }$ is given as $s _ { j } = h _ { \phi } ( \mathbf { x } _ { j } )$ .
To ground this in our experimental setup, the score $s _ { j }$ for each large-MNIST image $\mathbf { x } _ { j }$ in any input sequence $\mathbf { x }$ of $n = 5$ images is obtained via a CNN $h _ { \phi } ( )$ with parameters $\phi$ . Note that the CNN parameters $\phi$ are shared across the different images $\mathbf { x } _ { 1 } , \mathbf { x } _ { 2 } , \ldots , \mathbf { x } _ { n }$ in the sequence for efficient learning.
# E.2 QUANTILE REGRESSION
In contrast to the previous experiment, here we are given a dataset $\mathcal { D }$ of sequences of large-MNIST images and only the numerical value of the median element for each sequence. For example, the desired label corresponds to $y = 2 9 6 0$ (a real-valued scalar) for the input sequence of $n = 5$ images in Figure 4.
For any datapoint $\mathbf { x }$ , let $\ell _ { \mathrm { M S E } } ( \cdot )$ denote the mean-squared error between the true median $y$ and the prediction, say $\widehat { y }$ .
$$\ell _ { \mathrm { M S E } } ( y , \widehat { y } ) = \| y - \widehat { y } \| _ { 2 } ^ { 2 }$$
For the NeuralSort approaches, we optimize the following objective functions.
1. Deterministic NeuralSort
$$\operatorname* { m i n } _ { \phi , \theta } \frac { 1 } { | \mathcal { D } | } \sum _ { ( \mathbf { x } , y ) \in \mathcal { D } } \ell _ { \mathrm { M S E } } \big ( y , g _ { \theta } \big ( \widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) } \mathbf { x } \big ) \big )$$
where each entry of $\mathbf { s }$ is given as $s _ { j } = h _ { \phi } ( \mathbf { x } _ { j } )$ .
2. Stochastic NeuralSort
$$\operatorname* { m i n } _ { \phi , \theta } \frac { 1 } { | \mathcal { D } | } \sum _ { ( \mathbf { x } , \mathbf { y } ) \in \mathcal { D } } \mathbb { E } _ { \mathbf { z } \sim q ( \mathbf { z } | \mathbf { s } ) } \left[ \ell _ { \mathrm { M S E } } ( y , g _ { \theta } ( \widehat { P } _ { \mathbf { z } } \mathbf { x } ) ) \right]$$
where each entry of $\mathbf { s }$ is given as $s _ { j } = h _ { \phi } ( \mathbf { x } _ { j } )$ .
As before, the score $s _ { j }$ for each large-MNIST image $\mathbf { x } _ { j }$ in any input sequence $\mathbf { x }$ of $n$ images is obtained via a $\mathrm { C N N } h _ { \phi } ( )$ with parameters $\phi$ . Once we have a predicted permutation matrix $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) }$ (or $\widehat { P } _ { \mathbf { z } }$ ) for deterministic (or stochastic) approaches, we extract the median image via $\widehat { P } _ { \mathrm { s o r t } ( \mathbf { s } ) \mathbf { x } }$ (or $\widehat { P } _ { \mathbf { z } } \mathbf { x } )$ . Finally, we use a neural network $g _ { \boldsymbol { \theta } } ( \cdot )$ with parameters $\theta$ to regress this image to a scalar prediction for the median.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515# LOCAL STABILITY AND PERFORMANCE OF SIMPLE GRADIENT PENALTY $\mu$ -WASSERSTEIN GAN
Anonymous authors Paper under double-blind review
# ABSTRACT
Wasserstein GAN(WGAN) is a model that minimizes the Wasserstein distance between a data distribution and sample distribution. Recent studies have proposed stabilizing the training process for the WGAN and implementing the Lipschitz constraint. In this study, we prove the local stability of optimizing the simple gradient penalty $\mu$ -WGAN(SGP $\mu$ -WGAN) under suitable assumptions regarding the equilibrium and penalty measure $\mu$ . The measure valued differentiation concept is employed to deal with the derivative of the penalty terms, which is helpful for handling abstract singular measures with lower dimensional support. Based on this analysis, we claim that penalizing the data manifold or sample manifold is the key to regularizing the original WGAN with a gradient penalty. Experimental results obtained with unintuitive penalty measures that satisfy our assumptions are also provided to support our theoretical results.
# 1 INTRODUCTION
Deep generative models reached a turning point after generative adversarial networks (GANs) were proposed by Goodfellow et al. (2014). GANs are capable of modeling data with complex structures. For example, DCGAN can sample realistic images using a convolutional neural network (CNN) structure(Radford et al., 2015). GANs have been implemented in many applications in the field of computer vision with good results, such as super-resolution, image translation, and text-to-image generation(Ledig et al., 2017; Isola et al., 2017; Zhang et al., 2017; Reed et al., 2016).
However, despite these successes, GANs are affected by training instability and mode collapse problems. GANs often fail to converge, which can result in unrealistic fake samples. Furthermore, even if GANs successfully synthesize realistic data, the fake samples exhibit little variability.
A common solution to this instability problem is injecting an instance noise and finding different divergences. The injection of instance noise into real and fake samples during the training procedure was proposed by Sønderby et al. (2017), where its positive impact on the low dimensional support for the data distribution was shown to be a regularizing factor based on the Wasserstein distance, as demonstrated analytically by Arjovsky & Bottou (2017). In $f$ -GAN, $f$ -divergence between the target and generator distributions was suggested which generalizes the divergence between two distributions(Nowozin et al., 2016). In addition, a gradient penalty term which is related with Sobolev IPM(Integral Probability Metric) between data distribution and sample distribution was suggested by Mroueh et al. (2018).
The Wasserstein GAN (WGAN) is known to resolve the problems of generic GANs by selecting the Wasserstein distance as the divergence(Arjovsky et al., 2017). However, WGAN often fails with simple examples because the Lipschitz constraint on discriminator is rarely achieved during the optimization process and weight clipping. Thus, mimicking the Lipschitz constraint on the discriminator by using a gradient penalty was proposed by Gulrajani et al. (2017).
Noise injection and regularizing with a gradient penalty appear to be equivalent. The addition of instance noise in $f$ -GAN can be approximated to adding a zero centered gradient penalty(Roth et al., 2017). Thus, regularizing GAN with a simple gradient penalty term was suggested by Mescheder et al. (2018) who provided a proof of its stability.
Based on a theoretical analysis of the dynamic system, Nagarajan & Kolter (2017) proved the local exponential stability of the gradient-based optimization dynamics in GANs by treating the simultaneous gradient descent algorithm with a dynamic system approach. These previous studies were useful because they showed that the local behavior of GANs can be explained using dynamic system tools and the related Jacobian’s eigenvalues.
In this study, we aim to prove the convergence property of the simple gradient penalty $\mu$ -Wasserstein GAN(SGP $\mu$ -WGAN) dynamic system under general gradient penalty measures $\mu$ . To the best of our knowledge, our study is the first theoretical approach to GAN stability analysis which deals with abstract singular penalty measure. In addition, measure valued differentiation(Heidergott & Vazquez-Abad, 2008) is applied to take the derivative on the integral with a parametric measure, ´ which is helpful for handling an abstract measure and its integral in our proof.
The main contributions of this study are as follows.
• We prove the regularized effect and local stability of the dynamic system for a general penalty measure under suitable assumptions. The assumptions are written as both a tractable strong version and intractable weak version. To prove the main theorem, we also introduce the measure valued differentiation concept to handle the parametric measure. Based on the proof of the stability, we explain the reason for the success of previous penalty measures. We claim that the support of a penalty measure will be strongly related to the stability, where the weight on the limiting penalty measure might affect the speed of convergence. • We experimentally examined the general convergence results by applying two test penalty measures to several examples. The proposed test measures are unintuitive but they still satisfy the assumptions and similar convergence results were obtained in the experiment.
# 2 PRELIMINARIES
First, we introduce our notations and basic measure-theoretic concepts. Second, we define our SGP $\mu$ -WGAN optimization problem and treat this problem as a continuous dynamic system. Preliminary measure theoretic concepts are required to justify that the dynamic system changes in a sufficiently smooth manner as the parameter changes, so it is possible to use linearization theorem. They are also important for dealing with the parametric measure and its derivative. The problem setting with a simple gradient term is also discussed. The squared gradient size and simple gradient penalty term are used to build a differentiable dynamic system and to apply soft regularization as a resolving constraint, respectively. The continuous dynamic system approach, which is a so-called ODE method, is used to analyze the GAN optimization problem with the simultaneous gradient descent algorithm, as described by Nagarajan & Kolter (2017).
# 2.1 NOTATIONS AND PRELIMINARIES REGARDING MEASURE THEORY
$D ( x ; \psi ) : \mathcal { X } \to \mathbb { R }$ is a discriminator function with its parameter $\psi$ and $G ( z ; \theta ) : \mathcal { Z } \to \mathcal { X }$ is a generator function with its parameter $\theta$ . $p _ { d }$ is the distribution of real data and $p _ { g } ~ = ~ p _ { \theta }$ is the distribution of the generated samples in $\mathcal { X }$ , which is induced from the generator function $G ( z ; \theta )$ and a known initial distribution $p _ { l a t e n t } ( z )$ in the latent space $\mathcal { Z } . \ \Vert \cdot \Vert$ denotes the $L ^ { 2 }$ Euclidean norm if no special subscript is present.
The concept of weak convergence for finite measures is used to ensure the continuity of the integral term over the measure in the dynamic system, which must be checked before applying the theorems related to stability. Throughout this study, we assume that the measures in the sample space are all finite and bounded.
Definition 1. For a set of finite measures $\{ \mu _ { i } \} _ { i \in \mathcal { I } }$ in $( \mathbb { R } ^ { n } , d )$ with euclidean distance $d _ { \mathrm { { z } } }$ , $\{ \mu _ { i } \} _ { i \in \mathbb { Z } }$ is referred to as bounded if there exists some $M > 0$ such that for all $i \in \mathcal { Z }$ ,
$$\mu _ { i } ( \mathbb { R } ^ { n } ) \leq M$$
For instance, $M$ can be set as 1 if $\{ \mu _ { i } \}$ are probability measures on $\mathbb { R } ^ { n }$ . Assuming that the penalty measures are bounded, Portmanteau theorem offers the equivalent definition of the weak convergence for finite measures. This definition is important for ensuring that the integrals over $p _ { \theta }$ and $\mu$ in the dynamic system change continuously.
Definition 2. (Portmanteau Theorem) For a bounded sequence of finite measures $\{ \mu _ { n } \} _ { n \in \mathbb { N } }$ on the Euclidean space $\mathbb { R } ^ { n }$ with a $\sigma$ -field of Borel subsets $B ( \mathbb { R } ^ { n } )$ , $\mu _ { n }$ converges weakly to $\mu$ if and only $i f$ for every continuous bounded function $\phi$ on $\mathbb { R } ^ { n }$ , its integrals with respect to $\mu _ { n }$ converge to $\int \phi \dot { d \mu }$ , i.e.,
$$\mu _ { n } \mu \Longleftrightarrow \int \phi d \mu _ { n } \int \phi d \mu$$
The most challenging problem in our analysis with the general penalty measure is taking the derivative of the integral, where the measure depends on the variable that we want to differentiate. If our penalty measure is either absolutely continuous or discrete, then it is easy to deal with the integral. However, in the case of singular penalty measure, dealing with the integral term is not an easy task. Therefore, we introduce the concept of a weak derivative of a probability measure in the following(Heidergott & Vazquez-Abad, 2008). The weak derivative of a measure is useful for handling a ´ parametric measure that is not absolutely continuous with low dimensional support.
Definition 3. (Weak Derivatives of a Probability Measure) Consider the Euclidean space and its $\sigma$ -field of Borel subsets $( \mathbb { R } ^ { d } , B ( \mathbb { R } ^ { d } ) )$ . The probability measure $P _ { \theta }$ is called weakly differentiable at $\theta$ if a signed finite measure $P _ { \theta } ^ { \prime }$ exists where
$$\frac { d } { d \theta } \int \phi ( x ) d P _ { \theta } = \operatorname * { l i m } _ { \Delta 0 } \frac { 1 } { \Delta } \{ \int \phi ( x ) d P _ { \theta + \Delta } - \int \phi ( x ) d P _ { \theta } \} = \int \phi ( x ) d P _ { \theta } ^ { \prime }$$
is satisfied for every continuous bounded function $\phi$ on $\mathbb { R } ^ { n }$ . For the multidimensional parameter $\theta$ , this can be defined similar manner.
We can show that the positive part and negative part of $P _ { \theta } ^ { \prime }$ have the same mass by putting $\phi ( x ) = 1$ and the Hahn–Jordan decomposition on $P _ { \theta } ^ { \prime }$ . Therefore, the following triple $( c _ { \theta } , P _ { \theta } ^ { + } , P _ { \theta } ^ { - } )$ is called a weak derivative of $P _ { \theta }$ , where $P _ { \theta } ^ { \pm }$ are probability measures and $P _ { \theta } ^ { \prime }$ is rewritten as:
$$P _ { \theta } ^ { \prime } = c _ { \theta } P _ { \theta } ^ { + } - c _ { \theta } P _ { \theta } ^ { - }$$
Therefore,
$$\frac { d } { d \theta } \int \phi ( x ) d P _ { \theta } = \int \phi ( x ) d P _ { \theta } ^ { \prime } = c _ { \theta } ( \int \phi ( x ) d P _ { \theta } ^ { + } - \int \phi ( x ) d P _ { \theta } ^ { - } )$$
holds for every continuous bounded function $\phi$ on $\mathbb { R } ^ { n }$ . It is known that the representation of $( c _ { \theta } , P _ { \theta } ^ { + } , P _ { \theta } ^ { - } )$ for $P _ { \theta } ^ { \prime }$ is not unique because $( c _ { \theta } + C _ { \theta } , P _ { \theta } ^ { + } + q _ { \theta } , P _ { \theta } ^ { - } + q _ { \theta } )$ is also another representation of $P _ { \theta } ^ { \prime }$ .
For the general finite measure $Q _ { \theta }$ , a normalizing coefficient $M ( \theta ) < \infty$ can be introduced. The product rule for differentiating can also be applied in a similar manner to calculus.
$$\frac { d } { d \theta } \int \phi ( x ; \theta ) d P _ { \theta } = \int \nabla _ { \theta } \phi ( x ; \theta ) d P _ { \theta } + \int \phi ( x ; \theta ) d P _ { \theta } ^ { \prime }$$
Therefore, for the general finite measure $Q _ { \theta } = M ( \theta ) P _ { \theta }$ , its derivative $Q _ { \theta } ^ { \prime }$ can be represented as below.
$$Q _ { \theta } ^ { \prime } = M ^ { \prime } ( \theta ) P _ { \theta } + M ( \theta ) P _ { \theta } ^ { \prime } = M ^ { \prime } ( \theta ) P _ { \theta } + c _ { \theta } M ( \theta ) P _ { \theta } ^ { + } - c _ { \theta } M ( \theta ) P _ { \theta } ^ { - }$$
# 2.2 PROBLEM SETTING AS A DYNAMIC SYSTEM
Previous work of Mescheder et al. (2018) showed that the dynamic system of WGAN-GP is not necessarily stable at equilibrium by demonstrating that the sequence of parameters is not Cauchy sequence. This is mainly due to the term $\| x \|$ in the dynamic system which has a derivative $\frac { x } { \| x \| }$ that is not defined at $x = 0$ . WGAN-GP has a penalty term $\mathbb { E } _ { \mu _ { G P } } [ ( \| \nabla _ { x } D ( x ; \psi ) \| - 1 ) ^ { 2 } ]$ that can lead to a discontinuity in its dynamic system.
These problems can be avoided by using the squared value of the gradient’s norm $\| \nabla _ { x } D \| ^ { 2 }$ , which is a differentiable function. In contrast to the WGAN-GP, recent methods based on a gradient penalty such as the simple gradient penalty employed by Mescheder et al. (2018) and the Sobolev GAN used the average of the squared values for the penalty area, whereas the WGAN-GP penalizes the size of the discriminator’s gradient $\lVert \nabla _ { x } D \rVert$ away from 1 in a pointwise manner.
This advantage of squared gradient term1, $\mathbb { E } _ { \mu } [ \| \nabla _ { x } D \| ^ { 2 } ]$ , makes the dynamic system differentiable and we define the WGAN problem with the square of the gradient’s norm as a simple gradient penalty. This simple gradient penalty can be treated as soft regularization based on the size of the discriminator’s gradient, especially in case where $\mu$ is the probability measure (Roth et al., 2017). It is convenient to determine whether the system is stable by observing the spectrum of the Jacobian matrix. In the following, $( D ( x ; \psi ) , p _ { d } , p _ { \theta } , \mu )$ is defined as an SGP $\mu$ -WGAN optimization problem (SGP-form) with a simple gradient penalty term on the penalty measure $\mu$ .
Definition 4. The WGAN optimization problem with a simple gradient penalty term $\| \nabla _ { x } D \| ^ { 2 }$ , penalty measure $\mu _ { ; }$ , and penalty weight hyperparameter $\rho > 0$ is given as follows, where the penalty term is only introduced to update the discriminator.
$$\begin{array} { r l } & { \displaystyle \operatorname* { m a x } _ { \psi } : \mathbb { E } _ { p _ { d } } [ D ( x ; \psi ) ] - \mathbb { E } _ { p _ { \theta } } [ D ( x ; \psi ) ] - \frac { \rho } { 2 } \mathbb { E } _ { \mu } [ \| \nabla _ { x } D ( x ; \psi ) \| ^ { 2 } ] } \\ & { \displaystyle \operatorname* { m i n } _ { \theta } : \mathbb { E } _ { p _ { d } } [ D ( x ; \psi ) ] - \mathbb { E } _ { p _ { \theta } } [ D ( x ; \psi ) ] } \end{array}$$
According to Nagarajan & Kolter (2017) and many other optimization problem studies, the simultaneous gradient descent algorithm for GAN updating can be viewed as an autonomous dynamic system of discriminator parameters and generator parameters, which we denote as $\psi$ and $\theta$ . As a result, the related dynamic system is given as follows.
$$\begin{array} { r l } & { \dot { \boldsymbol { \psi } } = \mathbb { E } _ { \boldsymbol { p } _ { d } } [ \nabla _ { \boldsymbol { \psi } } D ] - \mathbb { E } _ { \boldsymbol { p } _ { \boldsymbol { \theta } } } [ \nabla _ { \boldsymbol { \psi } } D ] - \frac { \rho } { 2 } \nabla _ { \boldsymbol { \psi } } \mathbb { E } _ { \boldsymbol { \mu } } [ \nabla _ { \boldsymbol { x } } ^ { T } D \nabla _ { \boldsymbol { x } } D ] } \\ & { \dot { \boldsymbol { \theta } } = \nabla _ { \boldsymbol { \theta } } \mathbb { E } _ { \boldsymbol { p } _ { \boldsymbol { \theta } } } [ D ] } \end{array}$$
# 3 TOY EXAMPLES
We investigate two examples considered in previous studies by Mescheder et al. (2018) and Nagarajan & Kolter (2017). We then generalize the results to a finite measure case. The first example is the univariate Dirac GAN, which was introduced by Mescheder et al. (2018).
Definition 5. (Dirac GAN) The Dirac GAN comprises a linear discriminator $D ( x ; \psi ) = \psi x$ , data distribution $p _ { d } = \delta _ { 0 }$ , and sample distribution $p _ { \theta } = \delta _ { \theta }$ .
The Dirac GAN with a gradient penalty with an arbitrary probability measure is known to be globally convergent(Mescheder et al., 2018). We argue that this result can be generalized to a finite penalty measure case.
Lemma 1. Consider the Dirac GAN problem with SGP form $\begin{array} { r } { ( D ( x ; \psi ) = \psi x , \delta _ { 0 } , \delta _ { \theta } , \mu _ { \psi , \theta } ) } \end{array}$ . Suppose that some small $\eta > 0$ exists such that its finite penalty measure $\mu _ { \psi , \theta }$ with mass $M ( \psi , \theta ) =$ $\mathbf { \bar { \rho } } _ { \int 1 d \mu _ { \psi , \theta } } \geq 0$ satisfies either
$$M ( \psi , \theta ) > 0 f o r \left( \psi , \theta \right) \in B _ { \eta } ( ( 0 , 0 ) ) o$$
$$^ { \prime } \psi \nabla _ { \psi } M ( \psi , \theta ) \geq 0 f o r ( \psi , \theta ) \in B _ { \eta } ( ( 0 , 0 ) ) .$$
Then, the SGP $\mu$ -WGAN optimization dynamics with $\begin{array} { r } { ( D ( x ; \psi ) = \psi x , \delta _ { 0 } , \delta _ { \theta } , \mu _ { \psi , \theta } ) } \end{array}$ are locally stable at the origin and the basin of attraction $B = B _ { R } ( ( 0 , 0 ) )$ is open ball with radius $R$ . Its radius is given as follows.
Motivated by this example, we can extend this idea to the other toy example given by Nagarajan & Kolter (2017), where WGAN fails to converge to the equilibrium points $( \psi , \theta ) = ( 0 , \pm 1 )$ .
Lemma 2. Consider the toy example $\begin{array} { r c l } { ( D ( x ; \psi ) } & { = } & { \psi x ^ { 2 } , U ( - 1 , 1 ) , U ( - | \theta | , | \theta | ) , \mu _ { \theta } ) } \end{array}$ where $U ( 0 , 0 ) = \delta _ { 0 }$ and the ideal equilibrium points are given by $( \psi ^ { * } , \theta ^ { * } ) = ( 0 , \pm 1 )$ . For a finite measure $\mu = \mu _ { \theta }$ on $\mathbb { R }$ which is independent of $\psi$ , suppose that $\mu _ { \boldsymbol { \theta } } \to \mu ^ { * }$ with $\mu ^ { * } \neq C \delta _ { 0 }$ for $C \geq 0$ . The dynamic system is locally stable near the desired equilibrium $( 0 , \pm 1 )$ , where the spectrum of the
Jacobian at $( 0 , \pm 1 )$ is given by $\begin{array} { r } { \lambda = - 2 \rho \mathbb { E } _ { \mu ^ { * } } [ x ^ { 2 } ] \pm \sqrt { 4 \rho ^ { 2 } \mathbb { E } _ { \mu ^ { * } } [ x ^ { 2 } ] ^ { 2 } - \frac { 4 } { 9 } } } \end{array}$
# 4 MAIN CONVERGENCE THEOREM
We propose the convergence property of WGAN with a simple gradient penalty on an arbitrary penalty measure $\mu$ for a realizable case: $\theta = \theta ^ { * }$ with $p _ { d } = p _ { \theta ^ { \ast } }$ exists. In subsection 4.1, we provide the necessary assumptions, which comprise our main convergence theorem. In subsection 4.2, we give the main convergence theorem with a sketch of the proof. A more rigorous analysis is given in the Appendix.
# 4.1 ASSUMPTIONS
The first assumption is made regarding the equilibrium condition for GANs, where we state the ideal conditions for the discriminator parameter and generator parameter. As the parameters converge to the ideal equilibrium, the sample distribution $\left( p _ { \theta } \right)$ converges to the real data distribution $\left( p _ { d } \right)$ and the discriminator cannot distinguish the generated sample and the real data.
Assumption 1. $p _ { \theta } p _ { d }$ as $\theta ~ \to ~ \theta ^ { * }$ and $D ( x ; \psi ^ { * } ) ~ = ~ 0$ on supp $\left( p _ { d } \right)$ and its small open neighborhood, i.e., $x \in \cup _ { x ^ { \prime } \in s u p p ( p _ { d } ) } B _ { \epsilon _ { x ^ { \prime } } } ( x ^ { \prime } )$ implies $D ( x ; \psi ^ { * } ) = 0$ . For simplicity, we denote $\cup _ { x ^ { \prime } \in s u p p ( p _ { d } ) } B _ { \epsilon _ { x ^ { \prime } } } ( x ^ { \prime } )$ as $B ( s u p p ( p _ { d } ) )$ .
The second assumption ensures that the higher order terms cannot affect the stability of the SGP $\mu$ -WGAN. In the Appendix, we consider the case where the WGAN fails to converge when Assumption 2 is not satisfied. Compared with the previous study by Nagarajan & Kolter (2017), the conditions for the discriminator parameter are slightly modified.
# Assumption 2.
$$\begin{array} { r } { g ( \theta ) = \| \mathbb { E } _ { p _ { d } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } ) ] - \mathbb { E } _ { p _ { \theta } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } ) ] \| ^ { 2 } , h ( \psi ) = \mathbb { E } _ { \mu _ { \psi , \theta ^ { * } } } [ \| \nabla _ { x } D ( x ; \psi ) \| ^ { 2 } ] } \end{array}$$
are locally constant along the nullspace of the Hessian matrix.
The third assumption allows us to extend our results to discrete probability distribution cases, as described by Mescheder et al. (2018).
Assumption 3. $\exists \epsilon _ { g } > 0$ such that $D ( x ; \psi ^ { * } ) = 0$ on $\cup _ { | \theta - \theta ^ { * } | < \epsilon _ { g } } s u p p ( p _ { \theta } ) .$ .
The fourth assumption indicates that there are no other “bad” equilibrium points near $( \psi ^ { * } , \theta ^ { * } )$ , which justifies the projection along the axis perpendicular to the null space.
Assumption 4. A bad equilibrium does not exist near the desired equilibrium point. Thus, $( \psi ^ { * } , \theta ^ { * } )$ is an isolated equilibrium or there exist $\delta _ { d } , \delta _ { g } > 0$ such that all equilibrium points in $B _ { \delta _ { d } } ( \psi ^ { * } ) \times$ $B _ { \delta _ { g } } ( \theta ^ { * } )$ satisfy the other assumptions.
The last assumption is related to the necessary conditions for the penalty measure. A calculation of the gradient penalty based on samples from the data manifold and generator manifold or the interpolation of both was introduced in recent studies (Gulrajani et al., 2017; Roth et al., 2017; Mescheder et al., 2018). First, we propose strong conditions for the penalty measure.
Assumption 5. The finite penalty measure $\mu = \mu _ { \theta }$ satisfies the followings:
a $\mu _ { \theta } \to \mu _ { \theta ^ { * } } = \mu ^ { * }$ and $\mu _ { \theta }$ is independent of the discriminator parameter $\psi$ . $\begin{array} { r l } & { b \ s u p p ( p _ { d } ) \subset s u p p ( \mu ^ { * } ) } \\ & { c \ \exists \epsilon _ { \mu } > 0 \ s u c h \ t h a t \ s u p p ( \mu _ { \theta } ) \subset B ( s u p p ( p _ { d } ) ) f o r \vert \theta - \theta ^ { * } \vert < \epsilon _ { \mu } . } \end{array}$
The assumption given above means that the support of the penalty measure $\mu _ { \theta }$ should approach the data manifolds smoothly as $\theta \to \theta ^ { * }$ . However, the penalty measure from WGAN-GP with a simple gradient penalty still reaches equilibrium without satisfying Assumption 5c. Therefore, we suggest Assumption 6, which is a weak version of Assumption 5. Assumption $6 \mathrm { a } ^ { 2 }$ is technically required to take the derivative of the integral $\mathbb { E } _ { \mu _ { \psi , \theta } } [ \| \nabla _ { x } D ( x ; \psi ) \| ^ { 2 } ]$ with respect to $\psi$ .
Assumption 6. (Weak version of Assumption 5) The finite penalty measure $\mu = \mu _ { \psi , \theta }$ satisfies the following.
a $\mu _ { \psi , \theta } \mu _ { \psi ^ { * } , \theta ^ { * } } = \mu ^ { * }$ , where supp $( \mu _ { \psi , \theta } )$ only depends on $\theta$ . Near the equilibrium, $\mu _ { \psi , \theta }$ can be weakly differentiated twice with respect to $\psi$ . In addition, its mass $M ( \psi , \theta ) \stackrel { \cdot } { = }$ $\int 1 d \mu _ { \psi , \theta }$ is a twice-differentiable function of $\psi$ and bounded near the equilibrium.
b $E _ { \mu ^ { * } } [ \nabla _ { \psi x } D \nabla _ { \psi x } ^ { T } D ]$ is positive definite or $s u p p ( p _ { d } ) \subset s u p p ( \mu ^ { * } ) .$
c $\ : \exists \epsilon _ { \mu } > 0 \ :$ such that $\operatorname { s u p p } ( \mu _ { \theta } ) \subset V$ for $| \theta - \theta ^ { * } | < \epsilon _ { \mu }$ , where $V = \{ x | \nabla _ { x } D ( x ; \psi ^ { * } ) = 0 \}$ .
The assumption above implies the following situations; The penalty measure’s support approaches to data manifold and its weight changes smoothly with respect to $\psi$ and $\theta$ . At the equilibrium, penalty measure’s support contains data manifold. Also, ideal discriminator will remain flat on the penalty area.
In summary, the gradient penalty regularization term with any penalty measure where the support approaches $B ( s u p p ( p _ { d } ) )$ in a smooth manner works well and this main result can explain the regularization effect of previously proposed penalty measures such as $\mu _ { G P } , p _ { d } , p _ { \ell }$ , and their mixtures.
# 4.2 MAIN CONVERGENCE THEOREM
According to the modified assumptions given above, we prove that the related dynamic system is locally stable near the equilibrium. The tools used for analyzing stability are mainly based on those described by Nagarajan & Kolter (2017). Our main contributions comprise proposing the necessary conditions for the penalty measure and proving the local stability for all penalty measures that satisfy Assumption 6.
Theorem 1. Suppose that our SGP $\mu$ -WGAN optimization problem $( D , p _ { d } , p _ { \theta } , \mu )$ with equilibrium point $( \psi ^ { * } , \theta ^ { * } )$ satisfies the assumptions given above. Then, the related dynamic system is locally stable at the equilibrium.
A detailed proof of the main convergence theorem is given in the Appendix. A sketch of the proof is given in three steps. First, the undesired terms in the Jacobian matrix of the system at the equilibrium are cancelled out. Next, the Jacobian matrix at equilibrium is given by $\left[ \begin{array} { c c } { \therefore } & { \mathbf { 0 } } \\ { R ^ { T } } & { 0 } \end{array} \right]$ , where $Q =$ $\mathbb { E } _ { \mu ^ { * } } [ \nabla _ { \psi x } D \nabla _ { \psi x } ^ { T } D ]$ and $R = \nabla _ { \theta } \mathbb { E } _ { p _ { \theta } } [ \nabla _ { \psi } D ] | _ { \theta = \theta ^ { * } }$ . The system is locally stable when both $Q$ and $R ^ { T } R$ are positive definite. We can complete the proof by dealing with zero eigenvalues by showing that ${ \cal N } ( Q ^ { \hat { T } } ) \subset { \cal N } ( R ^ { T } )$ and the projected system’s stability implies the original system’s stability.
Our analysis mainly focuses on WGAN, which is the simplest case of general GAN minimax optimization
$$\begin{array} { r l } & { \underset { \psi } { \operatorname* { m a x } } : \mathbb { E } _ { p _ { d } } [ f ( D ( x ; \psi ) ) ] + \mathbb { E } _ { p _ { \theta } } [ f ( - D ( x ; \psi ) ) ] - \frac { \rho } { 2 } \mathbb { E } _ { \mu } [ \| \nabla _ { x } D ( x ; \psi ) \| ^ { 2 } ] } \\ & { \underset { \theta } { \operatorname* { m i n } } : \mathbb { E } _ { p _ { d } } [ f ( D ( x ; \psi ) ) ] + \mathbb { E } _ { p _ { \theta } } [ f ( - D ( x ; \psi ) ) ] } \end{array}$$
with $f ( x ) = x$ . Similar approach is still valid for general GANs with concave function $f$ with $f ^ { \prime \prime } ( x ) < 0$ and $f ^ { \prime } ( 0 ) \neq 0$ .
# 5 EXPERIMENTAL RESULTS
We claim that every penalty measure that satisfies the assumptions can regularize the WGAN and generate similar results to the recently proposed gradient penalty methods. Several penalty measures were tested based on two-dimensional problems (mixture of 8 Gaussians, mixture of 25 Gaussians, and swissroll), MNIST and CIFAR-10 datasets using a simple gradient penalty term. In the comparisons with WGAN, the recently proposed penalty measures and our test penalty measures used the same network settings and hyperparameters. The penalty measures and its detailed sampling methods are listed in Table 1, where $x _ { d } \sim p _ { d } , x _ { g } \sim p _ { \theta }$ , and $\alpha \sim U ( 0 , 1 )$ . $\mathcal { A }$ indicates fixed anchor point in $\mathcal { X }$ .
Table 1: List of benchmark WGANs (WGAN and WGAN-GP with non-zero centered gradient penalty) and 5 penalty measures with a simple gradient penalty term. In this table, WGAN-GP represents the previous model proposed by (Gulrajani et al., 2017), which penalizes the WGAN with non-zero centered gradient penalty terms, whereas $\mu _ { G P }$ represents the simple method. In our experiment, no additional weights are applied on 5 penalty measures and they are all probability distributions.
<table><tr><td>Penalty</td><td>Penalty term</td><td>Penalty measure, sampling method</td></tr><tr><td>WGAN WGAN-GP</td><td>None(Weight Clipping) Eμ[(IVxD|-1)2]</td><td>None x=axd+(1-α)xg</td></tr><tr><td></td><td>Eμ[VxD|2]</td><td></td></tr><tr><td>Pg Pd</td><td>Eμ[VxDii2]</td><td>x=xg x=xd</td></tr><tr><td>μGP</td><td>EμVDii2]</td><td>x=axd+(1-α)xg</td></tr><tr><td>μmid</td><td>Eμ[VxDii2]</td><td>x= 0.5xd+0.5xg</td></tr><tr><td>μg,anc</td><td>EμVDii2]</td><td>x=αA+(1-α)xg</td></tr></table>
By setting the previously proposed WGAN with weight-clipping(Arjovsky et al., 2017) and WGANGP(Gulrajani et al., 2017) as the baseline models, $\operatorname { S G P } \mu$ -WGAN was examined with various penalty measures comprising three recently proposed measures and two artificially generated measures. $p _ { \theta }$ and $p _ { d }$ were suggested by Mescheder et al. (2018) and $\mu _ { G P }$ was introduced from the WGAN-GP. We analyzed the artificial penalty measures $\mu _ { m i d }$ and $\mu _ { g , a n c }$ as the test penalty measures.
The experiments were conducted based on the implementation of the Gulrajani et al. (2017). The hyperparameters, generator/discriminator structures, and related TensorFlow implementations can be found at https://github.com/igul222/improved_wgan_training (Gulrajani et al., 2017). Only the loss function was modified slightly from a non-zero centered gradient penalty to a simple penalty. For the CIFAR-10 image generation tasks, the inception score(Salimans et al., 2016) and FID(Heusel et al., 2017) were used as benchmark scores to evaluate the generated images.
# 5.1 2D EXAMPLES AND MNIST
We checked the convergence of $p _ { \theta }$ for the 2D examples (8 Gaussians, swissroll data, and 25 Gaussians) and MNIST digit generation for the SGP-WGANs with five penalty measures. MNIST and 25 Gaussians were trained over 200K iterations, the 8 Gaussians were trained for 30K iterations, and the Swiss Roll data were trained for 100K iterations. The anchor $\mathcal { A }$ for $\mu _ { g , a n c }$ was set as $( 2 , - 1 )$ for the 2D examples and 784 gray pixels for MNIST. We only present the results obtained for the MNIST dataset with the penalty measures comprising $\mu _ { m i d }$ and $\mu _ { g , a n c }$ in Figure 1. The others are presented in the Appendix.
 Figure 1: MNIST example. Images generated with $\mu _ { m i d }$ (left) and $\mu _ { g , a n c } ( \mathrm { r i g h t } )$ .
# 5.2 CIFAR-10
DCGAN and ResNet architectures were tested on the CIFAR-10 dataset. The generators were trained for 200K iterations. The anchor $\mathcal { A }$ for $\mu _ { g , a n c }$ during CIFAR-10 generation was set as fixed random pixels. The WGAN, WGAN-GP, and five penalty measures were evaluated based on the inception score and FID, as shown in Table 2, which are useful tools for scoring the quality of generated images. The images generated from $\mu _ { m i d }$ and $\mu _ { g , a n c }$ with ResNet are shown in Figure 2. The others are presented in the Appendix.
Table 2: Benchmark score results obtained based on the CIFAR-10 dataset under DCGAN and ResNet architectures. The higher inception score and lower FID indicate the good quality of the generated images.
<table><tr><td>Penalty</td><td>DCGAN Inception FID</td><td>ResNet Inception</td><td>FID</td></tr><tr><td>WGAN 3</td><td>5.64 ± 0.09 48.7</td><td>=</td><td>=</td></tr><tr><td>WGAN-GP</td><td>6.48 ± 0.10 35.0</td><td>7.82 ± 0.09</td><td>18.1</td></tr><tr><td>Pg</td><td>6.46 ± 0.09 38.0</td><td>7.63 ± 0.10</td><td>20.9</td></tr><tr><td>pd</td><td>6.33 ± 0.07</td><td>38.9 7.63 ± 0.09</td><td>20.3</td></tr><tr><td>μGP</td><td>6.40 ±0.08</td><td>35.4 7.60 ± 0.09</td><td>18.3</td></tr><tr><td>μmid</td><td>6.60 ± 0.07</td><td>33.9 7.86 ± 0.07</td><td>16.4</td></tr><tr><td>μg,anc</td><td>6.45 ± 0.07</td><td>33.7 7.36 ± 0.09</td><td>22.4</td></tr></table>
 Figure 2: CIFAR-10 example. Images generated with $\mu _ { m i d }$ (left) and $\mu _ { g , a n c }$ (right) under the ResNet architecture.
# 6 CONCLUSION
In this study, we proved the local stability of simple gradient penalty $\mu$ -WGAN optimization for a general class of finite measure $\mu$ . This proof provides insight into the success of regularization with previously proposed penalty measures. We explored previously proposed analyses based on various gradient penalty methods. Furthermore, our theoretical approach was supported by experiments using unintuitive penalty measures. In future research, our works can be extended to alternative gradient descent algorithm and its related optimal hyperparameters. Stability at non-realizable equilibrium points is one of the important topics on stability of GANs. Optimal penalty measure for achieving the best convergence speed can be also investigated using a spectral theory, which provides the mathematical analysis on stability of GAN with a precise information on the convergence theory.
# REFERENCES
Mart´ın Arjovsky and Leon Bottou. Towards principled methods for training generative adversarial ´ networks. In International Conference on Learning Representations, 2017.
Mart´ın Arjovsky, Soumith Chintala, and Leon Bottou. Wasserstein generative adversarial networks. ´ In Proceedings of the 34th International Conference on Machine Learning, pp. 214–223, 2017.
Ian J. Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron C. Courville, and Yoshua Bengio. Generative adversarial nets. In Advances in Neural Information Processing Systems, pp. 2672–2680, 2014.
Ishaan Gulrajani, Faruk Ahmed, Mart´ın Arjovsky, Vincent Dumoulin, and Aaron C. Courville. Improved training of wasserstein gans. In Advances in Neural Information Processing Systems, pp. 5769–5779, 2017.
B. Heidergott and F. J. Vazquez-Abad. Measure-valued differentiation for markov chains. ´ Journal of Optimization Theory and Applications, 136:187–209, 2008. ISSN 1573-2878. doi: 10.1007/ s10957-007-9297-7.
Martin Heusel, Hubert Ramsauer, Thomas Unterthiner, Bernhard Nessler, and Sepp Hochreiter. Gans trained by a two time-scale update rule converge to a local nash equilibrium. In Advances in Neural Information Processing Systems, pp. 6629–6640, 2017.
Phillip Isola, Jun-Yan Zhu, Tinghui Zhou, and Alexei A. Efros. Image-to-image translation with conditional adversarial networks. In 2017 IEEE Conference on Computer Vision and Pattern Recognition, CVPR 2017, Honolulu, HI, USA, July 21-26, 2017, pp. 5967–5976, 2017.
Christian Ledig, Lucas Theis, Ferenc Huszar, Jose Caballero, Andrew Cunningham, Alejandro Acosta, Andrew P. Aitken, Alykhan Tejani, Johannes Totz, Zehan Wang, and Wenzhe Shi. Photorealistic single image super-resolution using a generative adversarial network. In 2017 IEEE Conference on Computer Vision and Pattern Recognition, CVPR 2017, Honolulu, HI, USA, July 21-26, 2017, pp. 105–114, 2017.
Lars M. Mescheder, Andreas Geiger, and Sebastian Nowozin. Which training methods for gans do actually converge? In Proceedings of the 35th International Conference on Machine Learning, pp. 3478–3487, 2018.
Youssef Mroueh, Chun-Liang Li, Tom Sercu, Anant Raj, and Yu Cheng. Sobolev GAN. In International Conference on Learning Representations, 2018.
Vaishnavh Nagarajan and J. Zico Kolter. Gradient descent GAN optimization is locally stable. In Advances in Neural Information Processing Systems, pp. 5591–5600, 2017.
Sebastian Nowozin, Botond Cseke, and Ryota Tomioka. f-gan: Training generative neural samplers using variational divergence minimization. In Advances in Neural Information Processing Systems, pp. 271–279, 2016.
Alec Radford, Luke Metz, and Soumith Chintala. Unsupervised representation learning with deep convolutional generative adversarial networks. CoRR, abs/1511.06434, 2015. URL http:// arxiv.org/abs/1511.06434.
Scott E. Reed, Zeynep Akata, Xinchen Yan, Lajanugen Logeswaran, Bernt Schiele, and Honglak Lee. Generative adversarial text to image synthesis. In Proceedings of the 33nd International Conference on Machine Learning, ICML 2016, New York City, NY, USA, June 19-24, 2016, pp. 1060– 1069, 2016. URL http://jmlr.org/proceedings/papers/v48/reed16.html.
Kevin Roth, Aurelien Lucchi, Sebastian Nowozin, and Thomas Hofmann. Stabilizing training of ´ generative adversarial networks through regularization. In Advances in Neural Information Processing Systems, pp. 2015–2025, 2017.
Tim Salimans, Ian J. Goodfellow, Wojciech Zaremba, Vicki Cheung, Alec Radford, and Xi Chen. Improved techniques for training gans. In Advances in Neural Information Processing Systems, pp. 2226–2234, 2016.
Casper Kaae Sønderby, Jose Caballero, Lucas Theis, Wenzhe Shi, and Ferenc Huszar. Amortised ´ MAP inference for image super-resolution. International Conference on Learning Representations, 2017.
Han Zhang, Tao Xu, and Hongsheng Li. Stackgan: Text to photo-realistic image synthesis with stacked generative adversarial networks. In IEEE International Conference on Computer Vision, ICCV 2017, Venice, Italy, October 22-29, 2017, pp. 5908–5916, 2017.
# APPENDIX A : PROOF OF LEMMAS BASED ON TOY EXAMPLES
Proof of Lemma 1. The related dynamic system of $\begin{array} { r } { ( D ( x ; \psi ) = \psi x , \delta _ { 0 } , \delta _ { \theta } , \mu _ { \psi , \theta } ) } \end{array}$ can be written as follows.
$$\begin{array} { l } { \displaystyle \dot { \psi } = - \theta - \frac { \rho } { 2 } \nabla \psi \mathbb { E } _ { \mu _ { \psi , \theta } } [ \psi ^ { 2 } ] } \\ { \displaystyle \dot { \theta } = \psi } \end{array}$$
First, the only equilibrium point is given by $( \psi ^ { * } , \theta ^ { * } ) = ( 0 , 0 )$ from
$$\begin{array} { l } { 0 = - \theta - 2 \psi M ( \psi , \theta ) - \psi ^ { 2 } \nabla _ { \psi } M ( \psi , \theta ) } \\ { \quad 0 = \psi } \end{array}$$
The corresponding Jacobian matrix for the dynamic system is written as:
$$J = \left[ { \begin{array} { r r } { Z } & { - 1 } \\ { 1 } & { 0 } \end{array} } \right]$$
where
$$Z = - \frac { \rho } { 2 } \nabla _ { \psi \psi } \mathbb { E } _ { \mu _ { \psi , \theta } } [ \psi ^ { 2 } ] \bigg | _ { \psi = 0 , \theta = 0 }$$
$\nabla _ { \psi } D ( x ; \psi ) = \psi$ does not depend on $x$ , so this can be rewritten as:
$$Z = - \frac { \rho } { 2 } \nabla _ { \psi \psi } ( \psi ^ { 2 } \mathbb { E } _ { \mu _ { \psi } , \theta } [ 1 ] ) = - \frac { \rho } { 2 } ( 2 M ( \psi , \theta ) + 4 \psi \nabla _ { \psi } M ( \psi , \theta ) + \psi ^ { 2 } M _ { \psi \psi } ( \psi , \theta ) ) \bigg | _ { \psi = 0 , \theta = 0 }$$
Therefore, if $M ( 0 , 0 ) > 0$ , then the given system is locally stable because the eigenvalues of its linearized system have negative real parts. If $M ( 0 , 0 ) = 0$ , then the stability of the system cannot be proved by the linearization theorem. In this case, we consider the following Lyapunov function.
$$L ( \psi ( t ) , \theta ( t ) ) = \psi ( t ) ^ { 2 } + \theta ( t ) ^ { 2 }$$
By differentiating with $t$ , we obtain
$$\begin{array} { r l } & { \dot { L } = 2 ( \psi \psi ^ { \prime } + \theta \theta ^ { \prime } ) = - \rho \psi \nabla _ { \psi } ( \psi ^ { 2 } M ( \psi , \theta ) ) = - \rho \psi ( 2 \psi M ( \psi , \theta ) + \psi ^ { 2 } \nabla _ { \psi } M ( \psi , \theta ) ) } \\ & { \quad = - \rho \psi ^ { 2 } ( 2 M ( \psi , \theta ) + \psi \nabla _ { \psi } M ( \psi , \theta ) ) \leq 0 } \end{array}$$
Clearly, $L ( \psi , \theta ) \geq 0$ and the equality holds iff $\psi = \theta = 0$ . In addition, $\dot { L } \leq 0$ since $M ( \psi , \theta ) \geq$ 0 and $\psi \nabla _ { \psi } M ( \psi , \theta ) \geq 0$ from the assumption. Furthermore, it is clear that if $( \psi ( 0 ) , \theta ( 0 ) ) \ \in \qquad $ $B _ { \eta } ( ( 0 , 0 ) )$ , then $( \psi ( \tau ) , \theta ( \tau ) ) \in B _ { \eta } ( ( 0 , 0 ) )$ for all $\tau \geq 0$ because the Lyapunov function (square of the distance between the origin and $( \psi ( \tau ) , \theta ( \tau ) ) )$ always decreases as $\tau \infty$ . Therefore, the given system is stable according to the Lyapunov stability theorem.
Again, we can check that if $\mu _ { \psi , \theta }$ is a probability measure, then the system is globally stable, as shown by Mescheder et al. (2018). The basin of attraction is given by the whole $\mathbb { R } ^ { 2 }$ plane since $M ( \psi , \theta ) = 1$ , so $\dot { L } = - \rho \psi ^ { 2 } ( 2 M + \psi \nabla _ { \psi } M ) = - 2 \rho \psi ^ { 2 } \leq 0$ for every $( \psi , \theta ) \in \mathbb { R } ^ { 2 }$ . □
Proof of Lemma 2. From the general setup of the $\operatorname { S G P } \mu$ -WGAN optimization problem, the dynamic system corresponding to the simple-GAN in Definition 6 can be written as follows.
$$\begin{array} { l } { { \displaystyle { \dot { \psi } = \frac { 1 } { 3 } - \frac { \theta ^ { 2 } } { 3 } - 4 \rho \psi \mathbb { E } _ { \mu } [ x ^ { 2 } ] } } } \\ { { \displaystyle { \dot { \theta } = \frac { 2 \psi \theta } { 3 } } } } \end{array}$$
If we let $\mathbb { E } _ { \mu ^ { * } } [ x ^ { 2 } ] = A ^ { 2 }$ , then the Jacobian matrix at the equilibrium $( 0 , \pm 1 )$ is given by ${ \boldsymbol { J } } =$ $\left[ { \begin{array} { c c } { - 4 \rho A ^ { 2 } } & { { \mp } { \frac { 2 } { 3 } } } \\ { \pm { \frac { 2 } { 3 } } } & { 0 } \end{array} } \right]$ Therefore, the given system is locally stable when $A \neq 0$ .
# APPENDIX B : PROOF OF LEMMA RELATED WITH ASSUMPTION 2
Lemma 3. Consider the Dirac-GAN setup and SGP $\mu$ -WGAN optimization system with a slightly changed discriminator function $D _ { 2 } ( x ; \psi ) \stackrel { \textstyle - } { = } \psi x ^ { 2 }$ . The system $( D _ { 2 } , \delta _ { 0 } , \delta _ { \theta } , \mu _ { G P } )$ does not converge to $( 0 , 0 )$ but for any point $( a , 0 )$ with $a < 0$ , the system has equilibrium points on the whole $\psi$ -axis and it violates Assumption 2.
Proof of Lemma 3. For the SGP $\mu$ -WGAN optimization problem $( D _ { 2 } , \delta _ { 0 } , \delta _ { \theta } , \mu _ { G P } )$ , the dynamic system can be written as follows.
$$\begin{array} { l } { { \dot { \psi } = - \theta ^ { 2 } - \frac { 4 } { 3 } \rho \psi \theta ^ { 2 } } } \\ { { \dot { \theta } = 2 \psi \theta } } \end{array}$$
$2 \psi \theta = 0$ and $\begin{array} { r } { \theta ^ { 2 } ( 1 + \frac { 4 } { 3 } \rho \psi ) = 0 } \end{array}$ implies that $\theta = 0$ , so the $\psi$ -axis is the set of all equilibrium points. By drawing the nullclines $\psi = 0$ and $\begin{array} { r } { \psi = - \frac { 3 } { 4 \rho } } \end{array}$ in the $\psi \theta$ -plane, it is clear that no solution curve converges to $( b , 0 )$ with $b \geq 0$ , as shown in Figure 3. □
 Figure 3: Phase portrait of the SGP $\mu$ -WGAN optimization problem $( D _ { 2 } , \delta _ { 0 } , \delta _ { \theta } , \mu _ { G P } )$ with $\textstyle \rho = { \frac { 3 } { 8 } }$ . Along the line $\theta = 0$ , the system is stable so no updating will occur. Every solution curve that passes the nullcline $\psi = 0$ has $\dot { \theta } = 0$ . For the nullcline $\begin{array} { r } { \psi = - \frac { 3 } { 4 \rho } = - 2 } \end{array}$ , no updating on $\psi$ will occur and only $\theta$ will be updated. Given that the solution curves do not intersect with each other, every solution curve is exactly one of the followinstays in area A. (2) Solution curve converges to $\begin{array} { r } { \bar { ( \psi , \theta ) } \overset { * } { = } ( - \frac { 3 } { 4 \rho } , 0 ) } \end{array}$ trivial cases; (1) Solalong the nullcline $\begin{array} { r } { \psi = - \frac { 3 } { 4 \rho } } \end{array}$ e. (3) Solution curve stays in area B. (4) Solution curve starts from area C, crosses the nullcline $\psi = 0$ perpendicularly, and converges to $( b , 0 )$ with $b < 0$ . Therefore, no solution curve converges to $( 0 , 0 )$ .
# APPENDIX C : PROOF OF THE MAIN CONVERGENCE THEOREM
Proof. Let us consider the Jacobian matrix $J = \left[ \begin{array} { l l } { K _ { D D } } & { K _ { D G } } \\ { K _ { G D } } & { K _ { G G } } \end{array} \right]$ at the first equilibrium $( \psi ^ { * } , \theta ^ { * } ) ^ { 4 }$
$$\begin{array} { r l } { J = \left[ \mathbb { E } _ { p _ { d } } [ \nabla _ { \psi \psi } D ] - \mathbb { E } _ { p _ { \theta ^ { \star } } } [ \nabla _ { \psi \psi } D ] - \frac { \rho } { 2 } \nabla _ { \psi \psi } \mathbb { E } _ { \mu } [ \| \nabla _ { x } D \| ^ { 2 } ] } & { - \nabla _ { \theta \psi } \mathbb { E } _ { p _ { \theta } } [ D ] - \frac { \rho } { 2 } \nabla _ { \theta \psi } \mathbb { E } _ { \mu } [ \| \nabla _ { x } D \| ^ { 2 } ] \right] } \\ & { \qquad \nabla _ { \psi \theta } \mathbb { E } _ { p _ { \theta } } [ D ] ^ { 2 } } \end{array}$$
First, Assumption 1 implies that $\mathbb { E } _ { p _ { d } } [ \nabla _ { \psi \psi } D ] - \mathbb { E } _ { p _ { \theta ^ { * } } } [ \nabla _ { \psi \psi } D ] = 0$ since $p _ { \theta } p _ { d }$ as $\theta \to \theta ^ { * }$ . From Assumption 3, $\mathbb { E } _ { p _ { \theta } } [ D ( x ; \psi ^ { * } ) ]$ is locally zero near the equilibrium $\theta ^ { * }$ , which implies that
$$K _ { G G } = \nabla _ { \theta \theta } \mathbb { E } _ { p _ { \theta } } [ D ( x ; \psi ^ { * } ) ] \bigg \rvert _ { \theta = \theta ^ { * } } = 0$$
We still need to evaluate $\nabla _ { \psi \psi } \mathbb { E } _ { \mu } [ \| \nabla _ { x } D \| ^ { 2 } ]$ and $\nabla _ { \theta \psi } \mathbb { E } _ { \mu } [ \| \nabla _ { x } D \| ^ { 2 } ]$ . According to Assumption 6a, finite signed measures $\mu _ { \psi , \theta } ^ { \prime }$ and $\mu _ { \psi , \theta } ^ { \prime \prime }$ exist5, so they are the first and second weak derivatives of $\mu _ { \psi , \theta }$ with respect to the parameter $\psi$ at $\left( \psi ^ { * } , \theta ^ { * } \right)$ . Therefore, the expectations given above can be rewritten as below.
$$\begin{array} { l } { I = \nabla _ { \psi \psi } \displaystyle \int _ { s u p p ( \mu _ { \psi } , \theta ) } \| \nabla _ { x } D \| ^ { 2 } d \mu _ { \psi , \theta } } \\ { = \displaystyle \int _ { s u p p ( \mu _ { \psi , \theta } ) } ( 2 \nabla _ { \psi x } ^ { T } D \nabla _ { \psi x } D + 2 K _ { 0 } ) d \mu _ { \psi , \theta } + \displaystyle \int _ { s u p p ( \mu _ { \psi , \theta } ) } 2 ( \nabla _ { \psi x } ^ { T } D \nabla _ { x } D ) d \mu _ { \psi , \theta } ^ { \prime } + \displaystyle \int _ { s u p p ( \mu _ { \psi , \theta } ) } \| \nabla _ { x } \nabla _ { \psi } D \nabla _ { x } \| ^ { 2 } d \mu _ { \psi , \theta } ^ { \prime } } \\ { \cdot I = \nabla _ { \theta \psi } \displaystyle \int _ { s u p p ( \mu _ { \psi , \theta } ) } \| \nabla _ { x } D \| ^ { 2 } d \mu _ { \psi , \theta } } \\ { = \nabla _ { \theta } ( \displaystyle \int _ { s u p p ( \mu _ { \psi , \theta } ) } 2 ( \nabla _ { \psi x } ^ { T } D \nabla _ { x } D ) d \mu _ { \psi , \theta } + \displaystyle \int _ { s u p p ( \mu _ { \psi , \theta } ) } \| \nabla _ { x } D \| ^ { 2 } d \mu _ { \psi , \theta } ^ { \prime } ) } \end{array}$$
where
$$\begin{array} { r } { K _ { 0 } ( x ; \psi ) = \left[ \sum _ { k } \frac { \partial ^ { 3 } } { \partial \psi _ { i } \partial \psi _ { j } \partial x _ { k } } D ( x ; \psi ) \frac { \partial } { \partial x _ { k } } D ( x ; \psi ) \right] _ { i j } } \end{array}$$
From Assumption 6c and the fact that the weak derivative of $\mu _ { \psi , \theta }$ vanishes outside of $s u p p ( \mu _ { \psi , \theta } )$ , $\nabla _ { x } D ( x ; \psi ^ { * } ) = 0$ on $s u p p ( \mu _ { \psi , \theta } ) \subset V$ for all $\theta$ with $\left| \theta - \theta ^ { * } \right| < \epsilon _ { \mu }$ and $\mu _ { \psi , \theta } ^ { \prime } = \mu _ { \psi , \theta } ^ { \prime \prime } = 0$ on the outside of $s u p p ( \mu _ { \psi , \theta } )$ , which leads to the desired results:
$$\begin{array} { c } { \displaystyle { I = \int _ { s u p p ( \mu ^ { * } ) } 2 ( \nabla _ { \psi x } ^ { T } D ( x ; \psi ^ { * } ) \nabla _ { \psi x } D ( x ; \psi ^ { * } ) ) d \mu ^ { * } } } \\ { \displaystyle { I I = 0 } } \end{array}$$
After cancelling the undesired terms, the Jacobian matrix at the equilibrium $( \psi ^ { * } , \theta ^ { * } )$ is given as:
$$J = \left[ \begin{array} { c c } { - \rho Q } & { - R } \\ { R ^ { T } } & { 0 } \end{array} \right]$$
where
$$\begin{array} { r } { Q = \mathbb { E } _ { \mu ^ { * } } [ \nabla _ { \psi x } ^ { T } D \nabla _ { \psi x } D ] } \\ { \boldsymbol { R } = \nabla _ { \theta } \mathbb { E } _ { p _ { \theta } } [ \nabla _ { \psi } D ] \bigg | _ { \theta = \theta ^ { * } } } \end{array}$$
From the definition of $Q$ , it is easy to check that $Q$ is at least positive semi-definite. It is known that for a negative definite matrix $A$ and full column rank matrix $B$ , the block matrix $\left[ \begin{array} { l l } { A } & { B } \\ { - B ^ { T } } & { 0 } \end{array} \right]$ is Hurwitz, i.e., all eigenvalues of the matrix have a negative real part. Therefore, if $\bar { Q }$ is positive definite and $R$ is full column rank, the proof is complete. We consider the complementary case.
Suppose that $Q$ or $R ^ { T } R$ have some zero eigenvalues. Let $Q = U _ { D } \Lambda _ { D } U _ { D } ^ { T }$ and $R ^ { T } R = U _ { G } \Lambda _ { G } U _ { G } ^ { T }$ with $U _ { D } ~ = ~ \lbrack T _ { D } ~ S _ { D } \rbrack$ and $U _ { G } ~ = ~ [ T _ { G } ^ { ~ - } ~ S _ { G } ]$ , where $T _ { D }$ and $T _ { G }$ are the eigenvectors of $\bar { Q }$ and $R ^ { T } R$ that correspond to non-zero eigenvalues. First, we assume that $T _ { D }$ and $T _ { G }$ are not empty. We can show that $( \psi ^ { * } + \xi v , \theta ^ { * } \overset { \cdot } { + } \nu w )$ is also an equilibrium point for a sufficiently small $\xi , \nu$ and $v \in N ( Q ) , w \in N ( R ^ { T } R )$ by using the techniques given by Nagarajan & Kolter (2017). If the system does not update at the equilibrium point $( \psi ^ { * } , \theta ^ { * } )$ and its small neighborhood $\left( \psi ^ { * } + \xi v , \theta ^ { * } + \nu w \right)$ is perturbed along $N ( Q )$ and $N ( \bar { R } ^ { T } R )$ , then it is reasonable to project the system orthogonal to $N ( Q )$ and $N ( R ^ { T } { \bar { R } } )$ .
First, we assume that $v \in N ( Q )$ . By Assumption 2, $h ( \psi ^ { * } + \xi v ) = h ( \psi ^ { * } ) = 0$ for $| \xi | < \xi _ { d }$ , which implies that $\nabla _ { \boldsymbol { x } } D ( \boldsymbol { x } ; \psi ^ { * } + \xi \boldsymbol { v } ) = 0$ for $x \in s u p p ( \mu _ { \psi ^ { * } + \xi v , \theta ^ { * } } ) = s u p p ( \mu ^ { * } )$ and $| \xi | < \xi _ { d }$ . Thus, we obtain
$$\mathbb { E } _ { \mu _ { \psi ^ { * } + \xi v , \theta ^ { * } } } [ \nabla _ { \psi x } ^ { T } D ( x ; \psi ^ { * } + \xi v ) \nabla _ { x } D ( x ; \psi ^ { * } + \xi v ) ] = 0$$
and
$$\int _ { s u p p ( \mu ^ { * } ) } \left\| \nabla _ { x } D ( x ; \psi ^ { * } + \xi v ) \right\| ^ { 2 } d \mu _ { \psi ^ { * } + \xi v , \theta ^ { * } } ^ { \prime } = 0$$
By Assumption 4, $\begin{array} { r } { \mathbb { E } _ { p _ { d } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } + \xi v ) ] - \mathbb { E } _ { p _ { \theta ^ { * } } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } + \xi v ) ] = 0 } \end{array}$ since $p _ { d } = p _ { \theta ^ { \ast } }$ . By adding these equations, we obtain
$$\begin{array} { l } { \displaystyle \dot { \psi } = \mathbb { E } _ { p _ { d } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } + \xi v ) ] - \mathbb { E } _ { p _ { \theta ^ { * } } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } + \xi v ) ] } \\ { \displaystyle - \frac { \rho } { 2 } \int _ { s u p p ( \mu _ { \psi ^ { * } + \xi v , \theta ^ { * } } ) } 2 \nabla _ { \psi x } ^ { T } D ( x ; \psi ^ { * } + \xi v ) \nabla _ { x } D ( x ; \psi ^ { * } + \xi v ) d \mu _ { \psi ^ { * } + \xi v , \theta ^ { * } } } \\ { \displaystyle - \frac { \rho } { 2 } \int _ { s u p p ( \mu _ { \psi ^ { * } + \xi v , \theta ^ { * } } ) } \| \nabla _ { x } D ( x ; \psi ^ { * } + \xi v ) \| ^ { 2 } d \mu _ { \psi ^ { * } + \xi v , \theta ^ { * } } ^ { \prime } } \\ { \displaystyle = 0 } \end{array}$$
In addition,
$$\begin{array} { l } { \displaystyle \dot { \theta } = \frac { \partial } { \partial \theta } \int _ { \mathcal X } D ( x ; \psi ^ { * } + \xi v ) d p _ { \theta } \bigg \vert _ { \theta = \theta ^ { * } } } \\ { \displaystyle = \int _ { \mathcal Z } \nabla _ { \theta } ^ { T } G ( z ; \theta ^ { * } ) \nabla _ { x } D ( G ( z ; \theta ^ { * } ) ; \psi ^ { * } + \xi v ) p _ { l a t e n t } ( z ) d z = 0 . } \end{array}$$
Therefore, the point $( \psi ^ { * } + \xi v , \theta ^ { * } )$ with $| \xi | < \xi _ { d }$ is an equilibrium point. According to Assumption 4, $D ( x ; \psi ^ { * } + \xi v )$ is an equilibrium discriminator for $| \xi | < \delta _ { d }$ , and thus $D ( x ; \psi ^ { * } + \bar { \xi } v )$ is already an optimal discriminator for $| \xi | < \operatorname* { m i n } ( \xi _ { d } , \delta _ { d } )$ .
Suppose that $w \ \in \ N ( R ^ { T } R )$ . By Assumption 2, $g ( \theta ^ { * } ) ~ = ~ g ( \theta ^ { * } + \nu w ) ~ = ~ 0$ for $| \nu | < \nu _ { g }$ , and thus $\begin{array} { r l } { \mathbb { E } _ { p _ { d } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } ) ] - \mathbb { E } _ { p _ { \theta ^ { * } + \nu w } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } ) ] ~ = ~ 0 } \end{array}$ for $| \nu | ~ < ~ \nu _ { g }$ . Furthermore, Assumption 3 gives $\mathbb { E } _ { p _ { \theta ^ { * } + \nu w } } [ D ( x ; \psi ^ { * } ) ] = 0$ for a sufficiently close $| \nu | < \epsilon _ { g }$ , which implies that $\begin{array} { r } { \dot { \theta } = \nabla _ { \theta } \mathbb { E } _ { p _ { \theta } } [ D ( x ; \psi ^ { * } ) ] \bigg \rvert _ { \theta = \theta ^ { * } + \nu w } = 0 } \end{array}$ for $| \nu | < \epsilon _ { g }$ . Finally,
$$\int _ { s u p p ( \mu _ { \psi ^ { * } , \theta ^ { * } + s w } ) } 2 \nabla _ { \psi x } ^ { T } D ( x ; \psi ^ { * } ) \nabla _ { x } D ( x ; \psi ^ { * } ) d \mu _ { i \psi ^ { * } , \theta ^ { * } + \nu w } + \int _ { s u p p ( \mu _ { \psi ^ { * } , \theta ^ { * } + s w } ) } \| \nabla _ { x } D ( x ; \psi ^ { * } ) \| ^ { 2 } d \mu _ { i \psi ^ { * } , \theta ^ { * } + \nu w } ^ { \prime }$$
since $s u p p ( \mu _ { \psi ^ { * } , \theta ^ { * } + \nu w } ) \subset V$ and $\nabla _ { x } D ( x ; \psi ^ { * } ) = 0$ on $V$ for a sufficiently small $| \nu | < \epsilon _ { \mu }$ (Assumption 6c). By adding these results, we obtain
$$\begin{array} { l } { \displaystyle \dot { \psi } = \mathbb { E } _ { p _ { d } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } ) ] - \mathbb { E } _ { p _ { \theta ^ { * } + \nu w } } [ \nabla _ { \psi } D ( x ; \psi ^ { * } ) ] } \\ { \displaystyle \quad - \frac { \rho } { 2 } \int _ { s u p p ( \mu _ { \psi ^ { * } , \theta ^ { * } + \nu w } ) } 2 \nabla _ { \psi x } ^ { T } D ( x ; \psi ^ { * } ) \nabla _ { x } D ( x ; \psi ^ { * } ) d \mu _ { \psi ^ { * } , \theta ^ { * } + \nu w } } \\ { \displaystyle \quad - \frac { \rho } { 2 } \int _ { s u p p ( \mu _ { \psi ^ { * } , \theta ^ { * } + \nu w } ) } \left\| \nabla _ { x } D ( x ; \psi ^ { * } ) \right\| ^ { 2 } d \mu _ { \psi ^ { * } , \theta ^ { * } + \nu w } ^ { \prime } } \\ { \displaystyle = 0 } \end{array}$$
Therefore, the point $( \psi ^ { * } , \theta ^ { * } + \nu w )$ with $| \nu | < \operatorname* { m i n } ( \epsilon _ { \mu } , \epsilon _ { g } , \nu _ { g } , \delta _ { g } )$ is an equilibrium point, which implies that $p _ { \theta ^ { * } + \nu w } = p _ { d }$ according to Assumption 4.
If we consider the projected system $( \alpha , \beta ) \ : = \ : ( T _ { D } ^ { T } \psi , T _ { G } ^ { T } \theta )$ , then the projected dynamic system’s Jacobian at $( T _ { D } ^ { T } \psi ^ { * } , T _ { G } ^ { T } \theta ^ { * } )$ is given as follows.
$$J ^ { \prime } = \left[ \begin{array} { c c } { { - \rho T _ { D } ^ { T } Q T _ { D } } } & { { - T _ { D } ^ { T } R T _ { G } } } \\ { { T _ { G } ^ { T } R ^ { T } T _ { D } } } & { { 0 } } \end{array} \right] = \left[ \begin{array} { c c } { { - \rho \Lambda _ { D } ^ { ( + ) } } } & { { - T _ { D } ^ { T } R T _ { G } } } \\ { { T _ { G } ^ { T } R ^ { T } T _ { D } } } & { { 0 } } \end{array} \right]$$
Therefore, we only need to prove that $T _ { D } ^ { T } R T _ { G }$ is of full column rank. Suppose that $u \in N ( Q ^ { T } ) =$ $N ( Q )$ . According to Assumption 2, $h ( \psi )$ is locally constant at $\psi ^ { * }$ along the direction $u$ . Therefore, for a sufficiently small scalar $\xi$ with $| \xi | < \xi _ { u }$ ,
$$h ( \psi ^ { * } + \xi u ) = h ( \psi ^ { * } ) = 0$$
where the last equality comes from the Assumption 6. This implies that $\nabla _ { x } D ( x ; \psi ^ { * } + \xi u ) = 0$ on $x \in s u p p ( \mu ^ { * } )$ for a small value of $| \xi | < \epsilon _ { u }$ . By taking directional derivative w.r.t. $\psi$ along the direction $u$ , we obtain:
$$u ^ { T } \nabla _ { \psi x } ^ { T } D ( x ; \psi ^ { * } ) = 0 , x \in s u p p ( \mu _ { \psi ^ { * } + \xi u , \theta ^ { * } } ) = s u p p ( \mu ^ { * } )$$
and thus
$$u ^ { T } \nabla _ { \psi x } ^ { T } D ( x ; \psi ^ { * } ) = u ^ { T } \nabla _ { x \psi } D ( x ; \psi ^ { * } ) = 0 , x \in s u p p ( p _ { \theta ^ { + } } ) = s u p p ( p _ { d } )$$
according to Assumption $^ \mathrm { 6 b }$ (the inclusion condition that $s u p p ( p _ { d } ) = s u p p ( p _ { \theta ^ { * } } ) \subset s u p p ( \mu ^ { * } )$ is required). By calculating $u ^ { T } R$ directly, we obtain
$$\begin{array} { r l } & { \displaystyle \boldsymbol { u } ^ { T } \boldsymbol { R } = u ^ { T } \frac { \partial } { \partial \boldsymbol { \theta } } \int _ { \mathcal { X } } \nabla _ { \boldsymbol { \psi } } D ( \boldsymbol { x } ; \boldsymbol { \psi } ^ { * } ) d p _ { \boldsymbol { \theta } } \bigg \rvert _ { \boldsymbol { \theta = \theta } ^ { = } } } \\ & { \qquad = u ^ { T } \frac { \partial } { \partial \boldsymbol { \theta } } \int _ { \mathcal { X } } \nabla _ { \boldsymbol { \psi } } D ( G ( \boldsymbol { z } ; \boldsymbol { \theta } ) ; \boldsymbol { \psi } ^ { * } ) p _ { l a t e n t } ( \boldsymbol { z } ) d \boldsymbol { z } \bigg \rvert _ { \boldsymbol { \theta = \theta } ^ { * } } } \\ & { \quad = \int _ { \mathcal { X } } u ^ { T } \nabla _ { \boldsymbol { x } \boldsymbol { \psi } } D ( G ( \boldsymbol { z } ; \boldsymbol { \theta } ^ { * } ) ; \boldsymbol { \psi } ^ { * } ) \nabla _ { \boldsymbol { \theta } } G ( \boldsymbol { z } ; \boldsymbol { \theta } ^ { * } ) p _ { l a t e n t } ( \boldsymbol { z } ) d \boldsymbol { z } = 0 } \end{array}$$
Thus, we obtain $u \in N ( R ^ { T } )$ , which implies that $N ( Q ^ { T } ) \subset N ( R ^ { T } )$ and $C ( R ) \subset C ( Q )$ . Now, we can check that $R T _ { G }$ is of full column rank since $T _ { G } ^ { T } R ^ { T } R T _ { G } = \Lambda _ { G } ^ { ( + ) }$ is positive definite. Therefore,
$$R T _ { G } w = 0 \Rightarrow w = 0$$
We note that the projection matrix on $C ( Q )$ is given by $T _ { D } ( T _ { D } ^ { T } T _ { D } ) ^ { - 1 } T _ { D } ^ { T } = T _ { D } T _ { D } ^ { T }$ . In addition, we know that $C ( R T _ { G } ) \subset C ( R ) \subset C ( Q )$ . Therefore,
$$\begin{array} { r l } & { T _ { D } ^ { T } R T _ { G } w = 0 } \\ & { \Rightarrow T _ { D } T _ { D } ^ { T } R T _ { G } w = 0 } \\ & { \Rightarrow T _ { D } T _ { D } ^ { T } w ^ { \prime } = 0 , w ^ { \prime } = R T _ { G } w \in C ( R T _ { G } ) } \end{array}$$
$$\begin{array} { l } { { \Rightarrow w ^ { \prime } = R T _ { G } w = 0 } } \\ { { \Rightarrow w = 0 } } \end{array}$$
which completes the proof that $T _ { D } ^ { T } R T _ { G }$ is a full column rank matrix.
Now, we only need to obtain proofs for the trivial cases where either one of $T _ { D }$ or $T _ { G }$ is empty. First, suppose that $T _ { G }$ is empty. Similar to the analysis given above, we can find that the point $( \psi ^ { * } , \theta )$ with $| \theta - \theta ^ { * } | < \mathrm { m i n } ( \epsilon _ { \mu } , \epsilon _ { g } , \delta _ { g } , \nu )$ is an equilibrium point, where $g ( \theta ^ { * } ) = g ( \theta )$ for a sufficiently small $\lvert \theta - \theta ^ { * } \rvert < \nu$ . We conclude that $p _ { \theta } = p _ { d }$ for $| \theta - \theta ^ { * } | < \operatorname * { m i n } ( \epsilon _ { \mu } , \epsilon _ { g } , \delta _ { g } , \nu )$ . Under the generator initialization that is sufficiently close according to $\theta ^ { * }$ , we can only observe the discriminator update
$$\dot { \psi } = - \frac { \rho } { 2 } \nabla _ { \psi } \mathbb { E } _ { \mu _ { \psi , \theta } } [ \| \nabla _ { x } D ( x ; \psi ) \| ^ { 2 } ]$$
since $\mathbb { E } _ { p _ { d } } [ D ( x ; \psi ) ] - \mathbb { E } _ { p _ { \theta } } [ D ( x ; \psi ) ] = 0$ for any $\psi$ and $| \theta - \theta ^ { * } | < \mathrm { m i n } ( \epsilon _ { \mu } , \epsilon _ { g } , \delta _ { g } , \nu )$ . The discriminator update described above is locally stable system near the equilibrium $\psi = \psi ^ { * }$ since the Jacobian of the update on $\psi$ is given as $- \rho Q$ and the zero eigenvalues can be ignored in a similar manner to the previous step. Therefore, the given system is stable near the equilibrium.
Suppose that $T _ { D }$ is empty. Given that $N ( Q ^ { T } ) \subset N ( R ^ { T } ) .$ , $R = 0$ , then the results are similar to those presented above, but our goal is to show that $( \psi , \theta )$ is an equilibrium point, where $( \psi , \theta )$ is sufficiently close to the original equilibrium point. We note that $( \psi ^ { * } , \theta )$ is also an equilibrium point that satisfies the assumptions.
By Assumption 2, $h ( \psi ) = h ( \psi ^ { * } ) = 0$ for $| \psi - \psi ^ { * } | < \xi$ , which implies that $\nabla _ { x } D ( x ; \psi ) = 0$ for $x \in s u p p ( \mu _ { \psi , \theta ^ { * } } ) = s u p p ( \mu ^ { * } )$ and $| \psi - \psi ^ { * } | < \xi$ . Thus, we obtain
$$\begin{array} { l } { \displaystyle \mathbb { E } _ { \mu _ { \psi , \theta ^ { * } } } \big [ \nabla _ { \psi x } ^ { T } D ( \boldsymbol { x } ; \psi ) \nabla _ { x } D ( \boldsymbol { x } ; \psi ) \big ] = 0 } \\ { \displaystyle \frac { \rho } { 2 } \int _ { s u p p ( \mu ^ { * } ) } \big \| \nabla _ { x } D \big \| ^ { 2 } d \mu _ { \psi , \theta ^ { * } } ^ { \prime } d \boldsymbol { x } = 0 } \end{array}$$
By Assumption 4, $\mathbb { E } _ { p _ { d } } [ \nabla _ { \psi } D ( x ; \psi ) ] - \mathbb { E } _ { p _ { \theta ^ { * } } } [ \nabla _ { \psi } D ( x ; \psi ) ] = 0$ since $p _ { d } = p _ { \theta ^ { \ast } }$ . In addition,
$$\dot { \theta } = \frac { \partial } { \partial \theta } \int _ { \mathcal { X } } D ( x ; \psi ) d p _ { \theta } \bigg | _ { \theta = \theta ^ { * } } = \int _ { \mathcal { Z } } \nabla _ { \theta } ^ { T } G ( z ; \theta ^ { * } ) \nabla _ { x } D ( G ( z ; \theta ^ { * } ) ; \psi ) p _ { l a t e n t } ( z ) d z = 0$$
Therefore, the point $( \psi , \theta ^ { * } )$ with $| \psi - \psi ^ { * } | < \operatorname* { m i n } ( \xi , \delta _ { d } )$ is an equilibrium point. From Assumption 4, $D ( x ; \psi )$ is an equilibrium discriminator, and thus $D ( x ; \psi )$ is already an optimal discriminator for $| \psi - \psi ^ { * } | < \operatorname* { m i n } ( \xi , \delta _ { d } )$ and $p _ { \theta }$ coincides with the data distribution $p _ { d }$ for $| \theta - \bar { \theta } ^ { * } | < \operatorname* { m i n } ( \epsilon _ { \mu } , \epsilon _ { g } , \delta _ { g } )$ , which indicates that every discriminator and generator near $( \psi ^ { * } , \theta ^ { * } )$ is an equilibrium point and this completes the proof of the main theorem. □
# APPENDIX D : DETAILED EXPERIMENTAL RESULTS

Figure 4: 2D example on 8 Gaussians, swissroll, 25 Gaussians datasets. Images generated with 5 penalty measures: $\mu _ { G P } , \mu _ { m i d } , p _ { g } , p _ { d } , \mu _ { g , a n c }$ .
 Figure 5: MNIST example. Images generated with $\mu _ { G P } , \mu _ { m i d } , p _ { g } , p _ { d } , \mu _ { g , a n c }$
 Figure 6: CIFAR-10 example. Images generated with WGAN, WGAN-GP, $\mu _ { G P } , \mu _ { m i d } , p _ { g } , p _ { d } , \mu _ { g , a n c }$ under the DCGAN architecture.
 Figure 7: CIFAR-10 example. Images generated with WGAN, WGAN-GP, $\mu _ { G P } , \mu _ { m i d } , p _ { g } , p _ { d } , \mu _ { g , a n c }$ under the ResNet architecture.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264# MATRIX CAPSULES WITH EM ROUTING
Geoffrey Hinton, Sara Sabour, Nicholas Frosst Google Brain Toronto, Canada {geoffhinton, sasabour, frosst}@google.com
# ABSTRACT
A capsule is a group of neurons whose outputs represent different properties of the same entity. Each layer in a capsule network contains many capsules. We describe a version of capsules in which each capsule has a logistic unit to represent the presence of an entity and a $4 \mathbf { x } 4$ matrix which could learn to represent the relationship between that entity and the viewer (the pose). A capsule in one layer votes for the pose matrix of many different capsules in the layer above by multiplying its own pose matrix by trainable viewpoint-invariant transformation matrices that could learn to represent part-whole relationships. Each of these votes is weighted by an assignment coefficient. These coefficients are iteratively updated for each image using the Expectation-Maximization algorithm such that the output of each capsule is routed to a capsule in the layer above that receives a cluster of similar votes. The transformation matrices are trained discriminatively by backpropagating through the unrolled iterations of EM between each pair of adjacent capsule layers. On the smallNORB benchmark, capsules reduce the number of test errors by $45 \%$ compared to the state-of-the-art. Capsules also show far more resistance to white box adversarial attacks than our baseline convolutional neural network.
# 1 INTRODUCTION
Convolutional neural nets are based on the simple fact that a vision system needs to use the same knowledge at all locations in the image. This is achieved by tying the weights of feature detectors so that features learned at one location are available at other locations. Convolutional capsules extend the sharing of knowledge across locations to include knowledge about the part-whole relationships that characterize a familiar shape. Viewpoint changes have complicated effects on pixel intensities but simple, linear effects on the pose matrix that represents the relationship between an object or object-part and the viewer. The aim of capsules is to make good use of this underlying linearity, both for dealing with viewpoint variations and for improving segmentation decisions.
Capsules use high-dimensional coincidence filtering: a familiar object can be detected by looking for agreement between votes for its pose matrix. These votes come from parts that have already been detected. A part produces a vote by multiplying its own pose matrix by a learned transformation matrix that represents the viewpoint invariant relationship between the part and the whole. As the viewpoint changes, the pose matrices of the parts and the whole will change in a coordinated way so that any agreement between votes from different parts will persist.
Finding tight clusters of high-dimensional votes that agree in a mist of irrelevant votes is one way of solving the problem of assigning parts to wholes. This is non-trivial because we cannot grid the high-dimensional pose space in the way the low-dimensional translation space is gridded to facilitate convolutions. To solve this challenge, we use a fast iterative process called “routingby-agreement” that updates the probability with which a part is assigned to a whole based on the proximity of the vote coming from that part to the votes coming from other parts that are assigned to that whole. This is a powerful segmentation principle that allows knowledge of familiar shapes to derive segmentation, rather than just using low-level cues such as proximity or agreement in color or velocity. An important difference between capsules and standard neural nets is that the activation of a capsule is based on a comparison between multiple incoming pose predictions whereas in a standard neural net it is based on a comparison between a single incoming activity vector and a learned weight vector.
# 2 HOW CAPSULES WORK
Neural nets typically use simple non-linearities in which a non-linear function is applied to the scalar output of a linear filter. They may also use softmax non-linearities that convert a whole vector of logits into a vector of probabilities. Capsules use a much more complicated non-linearity that converts the whole set of activation probabilities and poses of the capsules in one layer into the activation probabilities and poses of capsules in the next layer.
A capsule network consists of several layers of capsules. The set of capsules in layer $L$ is denoted as $\Omega _ { L }$ . Each capsule has a 4x4 pose matrix, $M$ , and an activation probability, $a$ . These are like the activities in a standard neural net: they depend on the current input and are not stored. In between each capsule $i$ in layer $L$ and each capsule $j$ in layer $L + 1$ is a 4x4 trainable transformation matrix, $W _ { i j }$ . These $W _ { i j } { \bf s }$ (and two learned biases per capsule) are the only stored parameters and they are learned discriminatively. The pose matrix of capsule $i$ is transformed by $W _ { i j }$ to cast a vote $V _ { i j } = M _ { i } W _ { i j }$ for the pose matrix of capsule $j$ . The poses and activations of all the capsules in layer $L + 1$ are calculated by using a non-linear routing procedure which gets as input $V _ { i j }$ and $a _ { i }$ for all $i \in \Omega _ { L } , j \in \Omega _ { L + 1 }$ .
The non-linear procedure is a version of the Expectation-Maximization procedure. It iteratively adjusts the means, variances, and activation probabilities of the capsules in layer $L + 1$ and the assignment probabilities between all $i \in \Omega _ { L } , j \in \Omega _ { L + 1 }$ . In appendix 1, we give a gentle intuitive introduction to routing-by-agreement and describe in detail how it relates to the EM algorithm for fitting a mixture of Gaussians.
# 3 USING EM FOR ROUTING-BY-AGREEMENT
Let us suppose that we have already decided on the poses and activation probabilities of all the capsules in a layer and we now want to decide which capsules to activate in the layer above and how to assign each active lower-level capsule to one active higher-level capsule. Each capsule in the higher-layer corresponds to a Gaussian and the pose of each active capsule in the lower-layer (converted to a vector) corresponds to a data-point (or a fraction of a data-point if the capsule is partially active).
Using the minimum description length principle we have a choice when deciding whether or not to activate a higher-level capsule. Choice 0: if we do not activate it, we must pay a fixed cost of $- \beta _ { u }$ per data-point for describing the poses of all the lower-level capsules that are assigned to the higher-level capsule. This cost is the negative log probability density of the data-point under an improper uniform prior. For fractional assignments we pay that fraction of the fixed cost. Choice 1: if we do activate the higher-level capsule we must pay a fixed cost of $- \beta _ { a }$ for coding its mean and variance and the fact that it is active and then pay additional costs, pro-rated by the assignment probabilities, for describing the discrepancies between the lower-level means and the values predicted for them when the mean of the higher-level capsule is used to predict them via the inverse of the transformation matrix. A much simpler way to compute the cost of describing a datapoint is to use the negative log probability density of that datapoint’s vote under the Gaussian distribution fitted by whatever higher-level capsule it gets assigned to. This is incorrect for reasons explained in appendix 1, but we use it because it requires much less computation (also explained in the appendix). The difference in cost between choice 0 and choice 1, is then put through the logistic function on each iteration to determine the higher-level capsule’s activation probability. Appendix 1 explains why the logistic is the correct function to use.
Using our efficient approximation for choice 1 above, the incremental cost of explaining a whole data-point $i$ by using an active capsule $j$ that has an axis-aligned covariance matrix is simply the sum over all dimensions of the cost of explaining each dimension, $h$ , of the vote $V _ { i j }$ . This is simply $- l n ( P _ { i | j } ^ { h } )$ where $P _ { i | j } ^ { h }$ is the probability density of the $h ^ { t h }$ component of the vectorized vote $V _ { i j }$ under $j$ ’s Gaussian model for dimension $h$ which has variance $( \sigma _ { j } ^ { h } ) ^ { 2 }$ and mean $\mu _ { j } ^ { h }$ where $\mu _ { j }$ is the vectorized version of $j$ ’s pose matrix $M _ { j }$ .
$${ \bf \Phi } _ { i \vert j } ^ { o h } = \frac { 1 } { \sqrt { 2 \pi ( \sigma _ { j } ^ { h } ) ^ { 2 } } } \exp \left( - \frac { ( V _ { i j } ^ { h } - \mu _ { j } ^ { h } ) ^ { 2 } } { 2 ( \sigma _ { j } ^ { h } ) ^ { 2 } } \right) , \quad \quad \quad l n ( P _ { i \vert j } ^ { h } ) = - \frac { ( V _ { i j } ^ { h } - \mu _ { j } ^ { h } ) ^ { 2 } } { 2 ( \sigma _ { j } ^ { h } ) ^ { 2 } } - l n ( \sigma _ { j } ^ { h } ) - l n ( 2 \pi ) / 2$$
Summing over all lower-level capsules for a single dimension, $h$ , of $j$ we get:
$$\begin{array} { l } { { c o s t _ { j } ^ { h } = \displaystyle \sum _ { i } - r _ { i j } l n ( P _ { i | j } ^ { h } ) } } \\ { { = \displaystyle \frac { \sum _ { i } r _ { i j } ( V _ { i j } ^ { h } - \mu _ { j } ^ { h } ) ^ { 2 } } { 2 ( \sigma _ { j } ^ { h } ) ^ { 2 } } + \left( l n ( \sigma _ { j } ^ { h } ) + \displaystyle \frac { l n ( 2 \pi ) } { 2 } \right) \sum _ { i } r _ { i j } } } \\ { { = \left( l n ( \sigma _ { j } ^ { h } ) + \displaystyle \frac { 1 } { 2 } + \frac { l n ( 2 \pi ) } { 2 } \right) \sum _ { i } r _ { i j } } } \end{array}$$
where $\sum _ { i } r _ { i j }$ is the amount of data assigned to $j$ and $V _ { i j } ^ { h }$ is the value on dimension $h$ of $V _ { i j }$ . Turningon capsule $j$ increases the description length for the means of the lower-level capsules assigned to $j$ from $- \beta _ { u }$ per lower-level capsule to $- \beta _ { a }$ plus the sum of the cost over all dimensions so we define the activation function of capsule $j$ to be:
$$a _ { j } = l o g i s t i c \left( \lambda \left( \beta _ { a } - \beta _ { u } \sum _ { i } r _ { i j } - \sum _ { h } c o s t _ { j } ^ { h } \right) \right)$$
where $\beta _ { a }$ is the same for all capsules and $\lambda$ is an inverse temperature parameter. We learn $\beta _ { a }$ and $\beta _ { u }$ discriminatively and set a fixed schedule for $\lambda$ as a hyper-parameter.
For finalizing the pose parameters and activations of the capsules in layer $L + 1$ we run the EM algorithm for few iterations (normally 3) after the pose parameters and activations have already been finalized in layer $L$ . The non-linearity implemented by a whole capsule layer is a form of cluster finding using the EM algorithm, so we call it EM Routing.
Procedure 1 Routing algorithm returns activation and pose of the capsules in layer $L + 1$ given the activations and votes of capsules in layer $L$ . $V _ { i j } ^ { h }$ is the $h ^ { t h }$ dimension of the vote from capsule $i$ with activation $a _ { i }$ in layer $L$ to capsule $j$ in layer $\boldsymbol { L } + 1$ . $\beta _ { a }$ , $\beta _ { u }$ are learned discriminatively and the inverse temperature $\lambda$ increases at each iteration with a fixed schedule.
<table><tr><td colspan="2">1: procedure EM RoUTING(a, V)</td></tr><tr><td>2:</td><td>∀i∈ΩL,j∈ΩL+1:Rij←1/|ΩL+1l</td></tr><tr><td>3:</td><td>for t iterations do</td></tr><tr><td>4:</td><td>∀j ∈ ΩL+1: M-STEP(a,R,V,j)</td></tr><tr><td>5: return a, M</td><td>∀i∈ΩL:E-STEP(μ,σ,a,V,i)</td></tr><tr><td>1: procedure M-sTEP(a,R, V, j)</td><td>for one higher-level capsule, j</td></tr><tr><td>2:</td><td>∀i∈ΩL:Rij ←Rij *ai</td></tr><tr><td>3:</td><td>Ah:←RV ∑Rij</td></tr><tr><td>4:</td><td>Vh:(o)²∑Rij(V-μ)²</td></tr><tr><td>5:</td><td>∑Rij costh ←(βu+log(o))∑Rij</td></tr><tr><td>6:</td><td>aj ← logistic(λ(βa -∑ncostʰ))</td></tr><tr><td>1: procedure E-STEP(μ,σ,a,V,i)</td><td></td></tr><tr><td>1</td><td>>for one lower-level capsule, i H exp £h</td></tr><tr><td>2: ∀j ∈ΩL+1: Pj ← √II 2π()2</td><td>2()</td></tr><tr><td>3:</td><td>j ∈ΩL+1: Rij ← ∑κeΩL+1 ajpj akPk</td></tr></table>
# 4 THE CAPSULES ARCHITECTURE
The general architecture of our model is shown in Fig. 1. The model starts with a 5x5 convolutional layer with 32 channels $\scriptstyle ( \mathrm { A } = 3 2 )$ and a stride of 2 with a ReLU non-linearity. All the other layers are capsule layers starting with the primary capsule layer. The 4x4 pose of each of the $\scriptstyle \mathbf { B } = 3 2$ primary capsule types is a learned linear transformation of the output of all the lower-layer ReLUs centered at that location. The activations of the primary capsules are produced by applying the sigmoid function to the weighted sums of the same set of lower-layer ReLUs.
 Figure 1: A network with one ReLU convolutional layer followed by a primary convolutional capsule layer and two more convolutional capsule layers.
The primary capsules are followed by two $3 { \bf x } 3$ convolutional capsule layers $\left( \mathrm { K } \mathrm { = } 3 \right)$ , each with 32 capsule types $\mathrm { ( C = D } { = } 3 2$ ) with strides of 2 and one, respectively. The last layer of convolutional capsules is connected to the final capsule layer which has one capsule per output class.
When connecting the last convolutional capsule layer to the final layer we do not want to throw away information about the location of the convolutional capsules but we also want to make use of the fact that all capsules of the same type are extracting the same entity at different positions. We therefore share the transformation matrices between different positions of the same capsule type and add the scaled coordinate (row, column) of the center of the receptive field of each capsule to the first two elements of the right-hand column of its vote matrix. We refer to this technique as Coordinate Addition. This should encourage the shared final transformations to produce values for those two elements that represent the fine position of the entity relative to the center of the capsule’s receptive field.
The routing procedure is used between each adjacent pair of capsule layers. For convolutional capsules, each capsule in layer $L + 1$ sends feedback only to capsules within its receptive field in layer $L$ . Therefore each convolutional instance of a capsule in layer $L$ receives at most kernel size X kernel size feedback from each capsule type in layer $L + 1$ . The instances closer to the border of the image receive fewer feedbacks with corner ones receiving only one feedback per capsule type in layer $L + 1$ .
# 4.1 SPREAD LOSS
In order to make the training less sensitive to the initialization and hyper-parameters of the model, we use “spread loss” to directly maximize the gap between the activation of the target class $\left( { { a } _ { t } } \right)$ and the activation of the other classes. If the activation of a wrong class, $a _ { i }$ , is closer than the margin, $m$ , to $a _ { t }$ then it is penalized by the squared distance to the margin:
$$L _ { i } = ( m a x ( 0 , m - ( a _ { t } - a _ { i } ) ) ^ { 2 } , L = \sum _ { i \neq t } L _ { i }$$
By starting with a small margin of 0.2 and linearly increasing it during training to 0.9, we avoid dead capsules in the earlier layers. Spread loss is equivalent to squared Hinge loss with $m = 1$ . Guermeur & Monfrini (2011) studies a variant of this loss in the context of multi class SVMs.
# 5 EXPERIMENTS
The smallNORB dataset (LeCun et al. (2004)) has gray-level stereo images of 5 classes of toys: airplanes, cars, trucks, humans and animals. There are 10 physical instances of each class which are painted matte green. 5 physical instances of a class are selected for the training data and the other 5 for the test data. Every individual toy is pictured at 18 different azimuths (0-340), 9 elevations and 6 lighting conditions, so the training and test sets each contain 24,300 stereo pairs of 96x96 images. We selected smallNORB as a benchmark for developing our capsules system because it is carefully designed to be a pure shape recognition task that is not confounded by context and color, but it is much closer to natural images than MNIST.
Table 1: The effect of varying different components of our capsules architecture on smallNORB.
<table><tr><td>Routing iterations</td><td>Pose structure</td><td>Loss</td><td>Coordinate Addition</td><td>Test error rate</td></tr><tr><td>1</td><td>Matrix</td><td>Spread</td><td>Yes</td><td>9.7%</td></tr><tr><td>2</td><td>Matrix</td><td>Spread</td><td>Yes</td><td>2.2%</td></tr><tr><td>3</td><td>Matrix</td><td>Spread</td><td>Yes</td><td>1.8%</td></tr><tr><td>5</td><td>Matrix</td><td>Spread</td><td>Yes</td><td>3.9%</td></tr><tr><td>3</td><td>Vector</td><td>Spread</td><td>Yes</td><td>2.9%</td></tr><tr><td>3</td><td>Matrix</td><td>Spread</td><td>No</td><td>2.6%</td></tr><tr><td>3</td><td>Vector</td><td>Spread</td><td>No</td><td>3.2%</td></tr><tr><td>3</td><td>Matrix</td><td>Margin1</td><td>Yes</td><td>3.2%</td></tr><tr><td>3</td><td>Matrix</td><td>CrossEnt</td><td>Yes</td><td>5.8%</td></tr><tr><td colspan="3">Baseline CNN with 4.2M parameters</td><td></td><td>5.2%</td></tr><tr><td colspan="4">CNN of Ciresan et al. (2O11) with extra input images & deformations</td><td>2.56%</td></tr><tr><td colspan="3">Our Best model (third row), with multiple crops during testing</td><td></td><td>1.4%</td></tr></table>
We downsample smallNORB to $4 8 \times 4 8$ pixels and normalize each image to have zero mean and unit variance. During training, we randomly crop $3 2 \times 3 2$ patches and add random brightness and contrast to the cropped images. During test, we crop a $3 2 \times 3 2$ patch from the center of the image and achieve $\mathbf { 1 . 8 \% }$ test error on smallNORB. If we average the class activations over multiple crops at test time we achieve $1 . 4 \%$ . The best reported result on smallNORB without using meta data is $2 . 5 6 \%$ (Cires¸an et al. (2011)). To achieve this, they added two additional stereo pairs of input images that are created by using an on-center off-surround filter and an off-center on-surround filter. They also applied affine distortions to the images. Our work also beats the Sabour et al. (2017) capsule work which achieves $2 . 7 \%$ on smallNORB. We also tested our model on NORB which is a jittered version of smallNORB with added background and we achieved a $2 . 6 \%$ error rate which is on par with the state-of-the-art of $2 . 7 \%$ (Ciresan et al. (2012)).
As the baseline for our experiments on generalization to novel viewpoints we train a CNN which has two convolutional layers with 32 and 64 channels respectively. Both layers have a kernel size of 5 and a stride of 1 with a $2 \times 2$ max pooling. The third layer is a 1024 unit fully connected layer with dropout and connects to the 5-way softmax output layer. All hidden units use the ReLU non-linearity. We use the same image preparation for the CNN baseline as described above for the capsule network. Our baseline CNN was the result of an extensive hyperparameter search over filter sizes, numbers of channels and learning rates.
The CNN baseline achieves $5 . 2 \%$ test error rate on smallNORB and has $4 . 2 \mathbf { M }$ parameters. We deduce that the Cires¸an et al. (2011) network has $2 . 7 \mathbf { M }$ parameters. By using small matrix multiplies, we reduced the number of parameters by a factor of 15 to 310K compared with our baseline CNN (and a factor of 9 w.r.t Cires¸an et al. (2011)). A smaller capsule network of $A = 6 4 , B = 8 , C =$ $D = 1 6$ with only 68K trainable parameters achieves $2 . 2 \%$ test error rate which also beats the prior state-of-the-art.
Fig. 2 shows how EM routing adjusts the vote assignments and the capsule means to find the tight clusters in the votes. The histograms show the distribution of vote distances to the mean (pose) of each class capsule during routing iterations. At the first iteration, votes are distributed equally between 5 final layer capsules. Therefore, all capsules receive votes closer than 0.05 to their calculated mean. In the second iteration, the assignment probability for agreeing votes increases. Therefore, most of the votes are assigned to the detected clusters, the animal and human class in the middle row, and the other capsules only receive scattered votes which are further than 0.05 from the calculated mean. The zoomed-out version of Fig. 2 in the Appendix shows the full distribution of vote distances at each routing iteration.
Instead of using our MDL-derived capsule activation term which computes a separate activation probability per capsule, we could view the capsule activations like the mixing proportions in a mixture of Gaussians and set them to be proportional to the sum of the assignment probabilities of a capsule and to sum to 1 over all the capsules in a layer. This increases the test error rate on smallNORB to $4 . 5 \%$ . Tab. 1 summarizes the effects of the number of routing iterations, the type of loss, and the use of matrices rather than vectors for the poses.
 Figure 2: Histogram of distances of votes to the mean of each of the 5 final capsules after each routing iteration. Each distance point is weighted by its assignment probability. All three images are selected from the smallNORB test set. The routing procedure correctly routes the votes in the truck and the human example. The plane example shows a rare failure case of the model where the plane is confused with a car in the third routing iteration. The histograms are zoomed-in to visualize only votes with distances less than 0.05. Fig. B.2 shows the complete histograms for the ”human” capsule without clipping the $\mathbf { X } ^ { } -$ -axis or fixing the scale of the y-axis.
Table 2: A comparison of the smallNORB test error rate of the baseline CNN and the capsules model on novel viewpoints when both models are matched on error rate for familiar viewpoints.
<table><tr><td rowspan="2">Test set</td><td colspan="2">Azimuth</td><td colspan="2">Elevation</td></tr><tr><td>CNN</td><td>Capsules</td><td>1 CNN</td><td>Capsules</td></tr><tr><td>Novel viewpoints</td><td>20%</td><td>13.5%</td><td>17.8%</td><td>12.3%</td></tr><tr><td>Familiar viewpoints</td><td>3.7%</td><td>3.7%</td><td>4.3%</td><td>4.3%</td></tr></table>
The same capsules architecture as Fig. 1 achieves $0 . 4 4 \%$ test error rate on MNIST. If the number of channels in the first hidden layer is increased to 256, it achieves $1 1 . 9 \%$ test error rate on Cifar10 (Krizhevsky & Hinton (2009)).
# 5.1 GENERALIZATION TO NOVEL VIEWPOINTS
A more severe test of generalization is to use a limited range of viewpoints for training and to test on a much wider range. We trained both our convolutional baseline and our capsule model on one-third of the training data containing azimuths of (300, 320, 340, 0, 20, 40) and tested on the two-thirds of the test data that contained azimuths from 60 to 280. In a separate experiment, we trained on the 3 smaller elevations and tested on the 6 larger elevations.
It is hard to decide if the capsules model is better at generalizing to novel viewpoints because it achieves better test accuracy on all viewpoints. To eliminate this confounding factor, we stopped training the capsule model when its performance matched the baseline CNN on the third of the test set that used the training viewpoints. Then, we compared these matched models on the twothirds of the test set with novel viewpoints. Results in Tab. 2 show that compared with the baseline CNN capsules with matched performance on familiar viewpoints reduce the test error rate on novel viewpoints by about $3 0 \%$ for both novel azimuths and novel elevations.
# 6 ADVERSARIAL ROBUSTNESS
There is growing interest in the vulnerability of neural networks to adversarial examples; inputs that have been slightly changed by an attacker to trick a neural net classifier into making the wrong classification. These inputs can be created in a variety of ways, but straightforward strategies such as FGSM (Goodfellow et al. (2014)) have been shown to drastically decrease accuracy in convolutional neural networks on image classification tasks. We compare our capsule model and a traditional convolutional model on their ability to withstand such attacks.
FGSM computes the gradient of the loss w.r.t. each pixel intensity and then changes the pixel intensity by a fixed amount $\epsilon$ in the direction that increases the loss. So the changes only depend on the sign of the gradient at each pixel. This can be extended to a targeted attack by updating the input to maximize the classification probability of a particular wrong class. We generated adversarial attacks using FGSM because it has only one hyper-parameter and it is easy to compare models that have very different gradient magnitudes. To test the robustness of our model, we generated adversarial images from the test set using a fully trained model. We then reported the accuracy of the model on these images.
We found that our model is significantly less vulnerable to both general and targeted FGSM adversarial attacks; a small $\epsilon$ can be used to reduce a convolutional model’s accuracy much more than an equivalent $\epsilon$ can on the capsule model (Fig. 3). It should also be noted that the capsule model’s accuracy after the untargeted attack never drops below chance $( 2 0 \% )$ whereas the convolutional model’s accuracy is reduced to significantly below chance with an $\epsilon$ as small as 0.2.
We also tested our model on the slightly more sophisticated adversarial attack of the Basic Iterative Method (Kurakin et al. (2016)), which is simply the aforementioned attack except it takes multiple smaller steps when creating the adversarial image. Here too we find that our model is much more robust to the attack than the traditional convolutional model.
 Figure 3: Accuracy against $\epsilon$ after an adversarial attack (left) and Success Rate after a targeted adversarial attack (right). The targeted attack results were evaluated by averaging the success rate after the attack for each of the 5 possible classes.
It has been shown that some robustness to adversarial attacks in models can be due to simple numerical instability in the calculation of the gradient Brendel & Bethge (2017). To ensure that this was not the sole cause of our model’s robustness, we calculated the percentage of zero values in the gradient with respect to the image in the capsule model and found it to be smaller than that of the CNN. Furthermore, the capsule gradients, although smaller that those of the CNN, are only smaller by 2 orders of magnitude, as opposed to 16 orders of magnitude seen in Brendel & Bethge (2017)’s work.
Finally we tested our model’s robustness to black box attacks by generating adversarial examples with a CNN and testing them on both our capsule model and a different CNN. We found that the capsule model did not perform noticeably better at this task than the CNN.
# 7 RELATED WORK
Among the multiple recent attempts at improving the ability of neural networks to deal with viewpoint variations, there are two main streams. One stream attempts to achieve viewpoint invariance and the other aims for viewpoint equivariance. The work presented by Jaderberg et al. (2015)), Spatial Transformer Networks, seeks viewpoint invariance by changing the sampling of CNNs according to a selection of affine transformations. De Brabandere et al. (2016) extends spatial transformer networks where the filters are adapted during inference depending on the input. They generate different filters for each locality in the feature map rather than applying the same transformation to all filters. Their approach is a step toward input covariance detection from traditional pattern matching frameworks like standard CNNs (LeCun et al. (1990)). Dai et al. (2017) improves upon spatial transformer networks by generalizing the sampling method of filters. Our work differs substantially in that a unit is not activated based on the matching score with a filter (either fixed or dynamically changing during inference). In our case, a capsule is activated only if the transformed poses coming from the layer below match each other. This is a more effective way to capture covariance and leads to models with many fewer parameters that generalize better.
The success of CNNs has motivated many researchers to extend the translational equivariance built in to CNNs to include rotational equivariance (Cohen & Welling (2016), Dieleman et al. (2016), Oyallon & Mallat (2015)). The recent approach in Harmonic Networks (Worrall et al. (2017)) achieves rotation equivariant feature maps by using circular harmonic filters and returning both the maximal response and orientation using complex numbers. This shares the basic representational idea of capsules: By assuming that there is only one instance of the entity at a location, we can use several different numbers to represent its properties. They use a fixed number of streams of rotation orders. By enforcing the equality of the sum of rotation orders along any path, they achieve patch-wise rotation equivariance. This approach is more parameter-efficient than data augmentation approaches, duplicating feature maps, or duplicating filters (Fasel & Gatica-Perez (2006), Laptev et al. (2016)). Our approach encodes general viewpoint equivariance rather than only affine 2D rotations. Symmetry networks (Gens & Domingos (2014)) use iterative Lucas-Kanade optimization to find poses that are supported by the most low-level features. Their key weakness is that the iterative algorithm always starts at the same pose, rather than the mean of the bottom-up votes.
Lenc & Vedaldi (2016) proposes a feature detection mechanism (DetNet) that is equivariant to affine transformations. DetNet is designed to detect the same points in the image under different viewpoint variations. This effort is orthogonal to our work but DetNet might be a good way to implement the de-rendering first-stage that activates the layer of primary capsules.
Our routing algorithm can be seen as an attention mechanism. In this view, it is related to the work of Gregor et al. (2015), where they improved the decoder performance in a generative model by using Gaussian kernels to attend to different parts of the feature map generated by the encoder. Vaswani et al. (2017) uses a softmax attention mechanism to match parts of the query sequence to parts of the input sequence for the translation task and when generating an encoding for the query. They show improvement upon previous translation efforts using recurrent architectures. Our algorithm has attention in the opposite direction. The competition is not between the lower-level capsules that a higher-level capsule might attend to. It is between the higher-level capsules that a lower-level capsule might send its vote to.
# 7.1 PREVIOUS WORK ON CAPSULES
Hinton et al. (2011) used a transformation matrix in a transforming autoencoder that learned to transform a stereo pair of images into a stereo pair from a slightly different viewpoint. However, that system requires the transformation matrix to be supplied externally. More recently, routing-byagreement was shown to be effective for segmenting highly overlapping digits (Sabour et al. (2017)), but that system has several deficiencies that we have overcome in this paper:
1. It uses the length of the pose vector to represent the probability that the entity represented by a capsule is present. To keep the length less than 1, requires an unprincipled non-linearity and this prevents the existence of any sensible objective function that is minimized by the iterative routing procedure. 2. It uses the cosine of the angle between two pose vectors to measure their agreement. Unlike the negative log variance of a Gaussian cluster, the cosine saturates at 1, which makes it insensitive to the difference between a quite good agreement and a very good agreement. 3. It uses a vector of length $n$ rather than a matrix with $n$ elements to represent a pose, so its transformation matrices have $n ^ { 2 }$ parameters rather than just $n$ .
# 8 CONCLUSION
Building on the work of Sabour et al. (2017), we have proposed a new type of capsule system in which each capsule has a logistic unit to represent the presence of an entity and a 4x4 pose matrix to represent the pose of that entity. We also introduced a new iterative routing procedure between capsule layers, based on the EM algorithm, which allows the output of each lower-level capsule to be routed to a capsule in the layer above in such a way that active capsules receive a cluster of similar pose votes. This new system achieves significantly better accuracy on the smallNORB data set than the state-of-the-art CNN, reducing the number of errors by $45 \%$ . We have also shown it to be significantly more robust to white box adversarial attacks than a baseline CNN.
SmallNORB is an ideal data-set for developing new shape-recognition models precisely because it lacks many of the additional features of images in the wild. Now that our capsules model works well on NORB, we plan to implement an efficient version to test much larger models on much larger data-sets such as ImageNet.
ACKNOWLEDGMENTS Thanks to Robert Gens, Eric Langlois, Taco Cohen and anonymous commentators for helpful discussions and to everyone who made TensorFlow.
# REFERENCES
Wieland Brendel and Matthias Bethge. Comment on” biologically inspired protection of deep networks from adversarial attacks”. arXiv preprint arXiv:1704.01547, 2017.
Dan Ciresan, Ueli Meier, and Jurgen Schmidhuber. Multi-column deep neural networks for image ¨ classification. In Computer Vision and Pattern Recognition (CVPR), 2012 IEEE Conference on, pp. 3642–3649. IEEE, 2012.
Dan C Cires¸an, Ueli Meier, Jonathan Masci, Luca M Gambardella, and Jurgen Schmidhuber. High- ¨ performance neural networks for visual object classification. arXiv preprint arXiv:1102.0183, 2011.
Taco Cohen and Max Welling. Group equivariant convolutional networks. In International Conference on Machine Learning, pp. 2990–2999, 2016.
Jifeng Dai, Haozhi Qi, Yuwen Xiong, Yi Li, Guodong Zhang, Han Hu, and Yichen Wei. Deformable convolutional networks. arXiv preprint arXiv:1703.06211, 2017.
Bert De Brabandere, Xu Jia, Tinne Tuytelaars, and Luc Van Gool. Dynamic filter networks. In Neural Information Processing Systems (NIPS), 2016.
Sander Dieleman, Jeffrey De Fauw, and Koray Kavukcuoglu. Exploiting cyclic symmetry in convolutional neural networks. In Proceedings of the 33rd International Conference on International Conference on Machine Learning - Volume 48, ICML’16, pp. 1889–1898. JMLR.org, 2016. URL http://dl.acm.org/citation.cfm?id=3045390.3045590.
Beat Fasel and Daniel Gatica-Perez. Rotation-invariant neoperceptron. In Pattern Recognition, 2006. ICPR 2006. 18th International Conference on, volume 3, pp. 336–339. IEEE, 2006.
Robert Gens and Pedro M Domingos. Deep symmetry networks. In Advances in neural information processing systems, pp. 2537–2545, 2014.
Ian J Goodfellow, Jonathon Shlens, and Christian Szegedy. Explaining and harnessing adversarial examples. arXiv preprint arXiv:1412.6572, 2014.
Karol Gregor, Ivo Danihelka, Alex Graves, Danilo Rezende, and Daan Wierstra. Draw: A recurrent neural network for image generation. In International Conference on Machine Learning, pp. 1462–1471, 2015.
Yann Guermeur and Emmanuel Monfrini. A quadratic loss multi-class svm for which a radius– margin bound applies. Informatica, 22(1):73–96, 2011.
Geoffrey E Hinton, Alex Krizhevsky, and Sida D Wang. Transforming auto-encoders. In International Conference on Artificial Neural Networks, pp. 44–51. Springer, 2011.
Max Jaderberg, Karen Simonyan, Andrew Zisserman, and Koray Kavukcuoglu. Spatial transformer networks. In Advances in Neural Information Processing Systems, pp. 2017–2025, 2015.
Alex Krizhevsky and Geoffrey Hinton. Learning multiple layers of features from tiny images. 2009.
Alexey Kurakin, Ian Goodfellow, and Samy Bengio. Adversarial examples in the physical world. arXiv preprint arXiv:1607.02533, 2016.
Dmitry Laptev, Nikolay Savinov, Joachim M Buhmann, and Marc Pollefeys. Ti-pooling: transformation-invariant pooling for feature learning in convolutional neural networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 289–297, 2016.
Yann LeCun, Bernhard E Boser, John S Denker, Donnie Henderson, Richard E Howard, Wayne E Hubbard, and Lawrence D Jackel. Handwritten digit recognition with a back-propagation network. In Advances in neural information processing systems, pp. 396–404, 1990.
Yann LeCun, Fu Jie Huang, and Leon Bottou. Learning methods for generic object recognition with invariance to pose and lighting. In Computer Vision and Pattern Recognition, 2004. CVPR 2004. Proceedings of the 2004 IEEE Computer Society Conference on, volume 2, pp. II–104. IEEE, 2004.
Karel Lenc and Andrea Vedaldi. Learning covariant feature detectors. In Computer Vision–ECCV 2016 Workshops, pp. 100–117. Springer, 2016.
Edouard Oyallon and Stephane Mallat. Deep roto-translation scattering for object classification. ´ In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 2865– 2873, 2015.
Sara Sabour, Nicholas Fross, and Geoffrey E Hinton. Dynamic routing between capsules. In Neural Information Processing Systems (NIPS), 2017.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Neural Information Processing Systems (NIPS), 2017.
Daniel E. Worrall, Stephan J. Garbin, Daniyar Turmukhambetov, and Gabriel J. Brostow. Harmonic networks: Deep translation and rotation equivariance. In The IEEE Conference on Computer Vision and Pattern Recognition (CVPR), July 2017.
# A APPENDIX 1: AN INTUITIVE EXPLANATION OF THE COST FUNCTION THATIS MINIMIZED DURING DYNAMIC ROUTING
Dynamic routing is performed between two adjacent layers of capsules. We will refer to these layers as the higher-level and the lower-level. We complete the routing between one pair of layers before starting the routing between the next pair of layers. The routing process has a strong resemblance to fitting a mixture of Gaussians using EM, where the higher-level capsules play the role of the Gaussians and the means of the activated lower-level capsules for a single input image play the role of the datapoints.
We start by explaining the cost function that is minimized when using the EM procedure to fit a mixture of Gaussians. We then derive our dynamic routing procedure by making two modifications to the procedure for fitting a mixture of Gaussians.
# A.1 THE COST FUNCTION FOR FITTING A MIXTURE OF GAUSSIANS
The EM algorithm for fitting a mixture of Gaussians alternates between an E-step and an M-step. The E-step is used to determine, for each datapoint, the probability with which it is assigned to each of the Gaussians. These assignment probabilities act as weights and the M-step for each Gaussian consists of finding the mean of these weighted datapoints and the variance about that mean. If we are also fitting mixing proportions for each Gaussian, they are set to the fraction of the data assigned to the Gaussian.
The M-step holds the assignment probabilities constant and adjusts each Gaussian to maximize the sum of the weighted log probabilities that the Gaussian would generate the datapoints assigned to it. The negative log probability density of a datapoint under a Gaussian can be treated like the energy of a physical system and the M-step is minimizing the expected energy where the expectations are taken using the assignment probabilities.
The E-step adjusts the assignment probabilities for each datapoint to minimize a quantity called “free energy” which is the expected energy minus the entropy. We can minimize the expected energy by assigning each datapoint with probabilty 1 to whichever Gaussian gives it the lowest energy (i. e. the highest probability density). We can maximize the entropy by assigning each datapoint with equal probability to every Gaussian ignoring the energy. The best trade-off is to make the assignment probabilities be proportional to $e x p ( - E )$ . This is known as the Boltzmann distribution in physics or the posterior distribution in statistics. Since the $\mathrm { E }$ -step minimizes the free energy w.r.t. the assignment distribution and the M-step leaves the entropy term unchanged and minimizes the expected energy w.r.t. the parameters of the Gaussians, the free energy is an objective function for both steps.
The softmax function computes the distribution that minimizes free energy when the logits are viewed as negative energies. So when we use a softmax in our routing procedure to recompute assignment probabilities we are minimizing a free energy. When we refit the Gaussian model of each capsule we are minimizing the same free energy provided the logits of the softmax are based on the same energies as are optimized when refitting the Gaussians. The energies we use are the negative log probabilities of the votes coming from a lower-level capsule under the Gaussian model of a higher-level capsule. These are not the correct energies for maximizing the log probability of the data (see the discussion of determinants below) but this does not matter for convergence so long as we use the same energies for fitting the Gaussians and for revising the assignment probabilities.
The objective function minimizes Eq. 4 which consists of:
• MDL cost $- \beta _ { a }$ scaled by the probability of presence of capsules in layer $L + 1 ( a _ { j } , j \in$ $\Omega _ { L + 1 } )$ . • Negative entropy of activations $a _ { j } , j \in \Omega _ { L + 1 }$ . • The expected energy minimized in M-step: sum of the weighted log probabilities $( c o s t _ { j } ^ { h } )$ . • Negative entropy of routing softmax assignments $( R _ { i j } )$ ) scaled by the probability of presence of the datapoint $( a _ { i } , i \in \Omega _ { L } )$ .
$$\sum _ { j \in \Omega _ { L + 1 } } { a _ { j } ( - \beta _ { a } ) } + a _ { j } l n ( a _ { j } ) + ( 1 - a _ { j } ) l n ( 1 - a _ { j } ) + \sum _ { h } { c o s t _ { j } ^ { h } } + \beta _ { u } \sum _ { i \in \Omega _ { L } } { r _ { i j } } + \sum _ { i \in \Omega _ { L } } { a _ { i } * r _ { i j } } * l n ( { r _ { i j } } )$$
# A.2 MODIFICATION 1: MIXTURES OF TRANSFORMING GAUSSIANS
In a standard mixture of Gaussians, each Gaussian only has a subset of the datapoints assigned to it but all of the Gaussians see the same data. If we view the capsules in the higher-layer as the Gaussians and the means of the active capsules in the lower-layer as the dataset, each Gaussian sees a dataset in which the datapoints have been transformed by transformation matrices and these matrices are different for different Gaussians. For one higher-level capsule, two transformed datapoints may be close together and for another higher-level capsule the same two datapoints may be transformed into points that are far apart. Every Gaussian has a different view of the data. This is a far more effective way to break symmetry than simply initializing the Gaussians with different means and it generally leads to much faster convergence.
If the fitting procedure is allowed to modify the transformation matrices, there is a trivial solution in which the transformation matrices all collapse to zero and the transformed data points are all identical. We avoid this problem by learning the transformation matrices discriminatively in an outer loop and we restrict the dynamic routing to modifying the means and variances of the Gaussians and the probabilities with which the datapoints are assigned to the Gaussians.
There is a more subtle version of the collapse problem that arises when different transformation matrices have different determinants. Suppose that the datapoints in a particular subset are transformed into a cluster of points in the pose space of higher-level capsule $j$ and they are transformed into a different but equally tight cluster of points in the pose space of higher-level capsule $k$ . It may seem that $j$ and $k$ provide equally good models of this subset of the datapoints, but this is not correct from a generative modeling perspective. If the transformation matrices that map the datapoints into the pose space used by capsule $j$ have bigger determinants, then $j$ provides a better model. This is because the probability density of a point in the pose space of a lower-level capsule gets diluted by the determinant of the relevant transformation matrix when it is mapped to the pose of a higherlevel capsule. This would be a serious issue if we wanted to learn the transformation matrices by maximizing the probability of the observed datapoints, but we are learning the transformation matrices discriminatively so it does not matter. It does, however, mean that when the dynamic routing maximizes the probability of the transformed datapoints it cannot be viewed as also maximizing the probability of the untransformed points.
The obvious way to avoid the determinant issue is to take the mean in pose space of a higher-level capsule and to map this mean back into the pose space of each lower-level capsule using the inverses of the transformation matrices. A mean in a higher-level pose space will generally map to different points in the pose spaces of different lower-level capsules because the pose of a whole will generally make different predictions for the poses of the different parts of that whole. If we use the lowerlevel pose space when measuring the misfit between the actual pose of a lower-level capsule and the top-down prediction of that pose obtained by applying the inverse transformation matrix to the mean of the higher-level capsule, the collapse problem disappears and we can base decisions about routing on a fair comparison of how well two different top-down predictions fit the actual pose of the lower-level capsule. We do not use this correct method for two reasons. First, it involves inverting the transformation matrices. Second, it requires a new multiplication by the inverse transformation matrices every time the higher-level mean is modified during the dynamic routing. By measuring misfits in the higher-level pose space we avoid matrix inversions and, more importantly, we avoid having to multiply by the inverses in each iteration of the dynamic routing. This allows us to do many iterations of dynamic routing for the same computational cost as one forward propagation through the transformation matrices.
# A.3 MODIFICATION 2: MIXTURES OF SWITCHABLE TRANSFORMING GAUSSIANS
In a standard mixture of Gaussians, the modifiable parameters are the means, (co)variances, and mixing proportions and the only thing that distinguishes different Gaussians is the values of these parameters. In a mixture of transforming Gaussians, however, Gaussians also differ in the transformation matrices they use. If these transformation matrices are fixed during the fitting of the other parameters, it makes sense to have a large set of transforming Gaussians available but to only use the small subset of them that have appropriate transformation matrices for explaining the data at hand. Fitting to a dataset will then involve deciding which of the transforming Gaussians should be “switched on”. We therefore give each transforming Gaussian an additional activation parameter which is its probability of being switched on for the current dataset. The activation parameters are not mixing proportions because they do not sum to 1.
To set the activation probability for a particular higher-level capsule, $j$ , we compare the description lengths of two different ways of coding the poses of the activated lower-level capsules assigned to $j$ by the routing, as described in section 3. “Description length” is just another term for energy. The difference in the two description lengths (in nats) is put through a logistic function to determine the activation probability of capsule $j$ . The logistic function computes the distribution $( p , 1 - p )$ that minimizes free energy when the difference in the energies of the two alternatives is the argument of the logistic function. The energies we use for determining the activation probabilities are the same energies as we use for fitting the Gaussians and computing the assignment probabilities. So all three steps minimize the same free energy but with respect to different parameters for each step.
In some of the explanations above we have implicitly assumed that the lower-level capsules have activities of 1 or 0 and the assignment probabilities computed during the dynamic routing are also 1 or 0. In fact, these numbers are both probabilities and we use the product of these two probabilities as a multiplier on both the baseline description length of each lower-level mean and its alternative description length obtained by making use of the Gaussian fitted by a higher-level capsule.
# B SUPPLEMENTARY FIGURES
 Figure B.1: Sample smallNORB images at different viewpoints. All images in first row are at azimuth 0 and elevation 0. The second row shows a set of images at a higher-elevation and different azimuth.
 Figure B.2: Log scale histogram of distances between the receiving votes and the center of each of the 5 final capsules. The three rows show the 5 histograms for iterations 1, 2 and 3. Unlike Fig. 2 the histograms are independently log scaled so that small and large counts can both be seen. Also, the considered distance range is 60 and the number of bins is much larger.
 Figure B.3: Adverserial images generated with FGSM with $\epsilon = 0 . 1$ and $\epsilon = 0 . 4$ on the CNN model and the Capsule model. (a) $\epsilon = 0 . 1$ on CNN (b) $\epsilon = 0 . 4$ on CNN (c) $\epsilon = 0 . 1$ on Capsules (d) $\epsilon = 0 . 4$ on Capsules123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# IMPROVED LEARNING IN CONVOLUTIONAL NEURAL NETWORKS WITH SHIFTED EXPONENTIAL LINEAR UNITS (SHELUS)
Anonymous authors Paper under double-blind review
# ABSTRACT
The Exponential Linear Unit (ELU) has been proven to speed up learning and improve the classification performance over activation functions such as ReLU and Leaky ReLU for convolutional neural networks. The reasons behind the improved behavior are that ELU reduces the bias shift, it saturates for large negative inputs and it is continuously differentiable. However, it remains open whether ELU has the optimal shape and we address the quest for a superior activation function.
We use a new formulation to tune a piecewise linear activation function during training, to investigate the above question, and learn the shape of the locally optimal activation function. With this tuned activation function, the classification performance is improved and the resulting, learned activation function shows to be ELU-shaped irrespective if it is initialized as a RELU, LReLU or ELU. Interestingly, the learned activation function does not exactly pass through the origin indicating that a shifted ELU-shaped activation function is preferable. This observation leads us to introduce the Shifted Exponential Linear Unit (ShELU) as a new activation function.
Experiments on Cifar-100 show that the classification performance is further improved when using the ShELU activation function in comparison with ELU. The improvement is achieved when learning an individual bias shift for each neuron.
# 1 INTRODUCTION
The classification accuracy of Convolutional Neural Networks (CNNs) has improved remarkably over the last years. The reason for the improvement is manifold: more sophisticated layer designs (Lin et al., 2013; He et al., 2016), effective regularization techniques reducing overfitting such as dropout (Srivastava et al., 2014) and batch normalization (Ioffe & Szegedy, 2015), new nonlinear activation functions (Clevert et al., 2015; Trottier et al., 2016), improved weight initialization methods (Glorot & Bengio, 2010; He et al., 2016), data augmentation and large scale data as ImageNet (Deng et al., 2009).
In this work, we focus on the nonlinear activation function and its effect on the network learning behavior. Since the introduction of the Rectified Linear Unit (ReLU) (Glorot et al., 2011), it is generally accepted that the activation should be noncontractive to avoid the vanishing gradient problem. The vanishing gradient hampered the learning for the sigmoid and tanh activations. As ReLU is not symmetric, its mean response will be non-negative and will introduce a bias shift for the units in the next layer. The Leaky Rectified Linear Unit (LReLU) (Maas et al., 2013) was proposed to alleviate this bias shift. The LReLU introduces a small linear activation for negative inputs controlled by a constant hyperparameter $\alpha$ .
Centering the activation, i.e. reducing the bias shift, is claimed to speed up learning (Le Cun et al., 1991). When the Exponential Linear Unit (ELU) was introduced by Clevert et al. (2015), one of the reason for its success and fast learning capability was claimed to be that the activation saturates for large negative inputs. ELU is also controlled by a hyperparameter that determines the saturation level. Another activation that is saturated for negative inputs is the Shifted ReLU (SReLU). Its shape is similar to ReLU, but the ”kink” is at -1 instead of 0. This reduces the bias shift while being saturated for negative inputs. ELU learns both faster and better than SReLU (Clevert et al.,
Table 1: Activation functions.
<table><tr><td>Activation</td><td>x>0</td><td>x≤0</td></tr><tr><td rowspan="3">ReLU LReLU SReLU</td><td>X</td><td>0</td></tr><tr><td>X</td><td>αx</td></tr><tr><td>X</td><td>max(x,-1)</td></tr><tr><td rowspan="3">ELU PELU</td><td>X</td><td>α(exp(x)-1)</td></tr><tr><td>X</td><td>α(exp(β x)-1)</td></tr><tr><td></td><td></td></tr></table>
2015), but it is not obvious which properties of ELU that actually create this improvement. It may be the smooth exponential decay for small negative inputs and/or the fact that it is continuously differentiable. The question also remains whether the shape of ELU is truly the optimal activation function or if there are other shapes, not yet found, that would further speed up and improve learning. And if they exist, how are they to be found. These were the type of issues that we wanted to explore when starting this work.
To improve the learning capabilities for the above mentioned activation functions, tuneable variants of them have been published where the control parameters are tuneable and learned instead of being set as a constant parameter according to their original publications. The Parametric ReLU (PReLU) was introduced by He et al. (2016) where the single control parameter $\alpha$ for LReLU is now learned during training. The Parametric ELU (PELU) was introduced by Trottier et al. (2016), also tuning the control parameters for ELU. Classification results were shown to improve with parameter tuning in both papers. The Scaled ELU (SELU)1 was defined by Klambauer et al. (2017) and is essentially a more simple variant of PELU. The activation functions mentioned so far are defined in Table 1.
Piecewise linear activation functions have previously been used by Agostinelli et al. (2014) to improve the performance compared to LReLU. In this work, we use the same concept with tuneable piecewise linear activation functions, but now with the additional objective to investigate the shape of the learned activation function. We apply this approach for nonlinear regression of the optimal activation function. We initialized the activation as linearized versions of ReLU, LReLU and ELU, and they all resulted in the same shape after tuning the network. The ReLU and LReLU activation functions are tuned into an ELU-shaped function whereas the ELU activation function retains its shape. However, we also noted that the tuned ELU-shaped activation function does not exactly pass through the origin. There is a small shift introduced around the origin while retaining the overall shape of the activation function.
Based on this observation, we introduce a shifted variant of the ELU activation function. In our experiments, we found that a horizontal shift is favorable and we call this new activation function Shifted Exponential Linear Unit (ShELU). The shift is tuneable during training and the shift is individual for each neuron. Experiments show that the classification performance is improved when allowing this shift in the activation function.
Our main contribution is the introduction of the shifted activation function ShELU. The second contribution is a new formulation of a tuneable piecewise linear activation function with constraints to make it continuous. This formulation can be used to explore for other, up to now unseen, shapes of activation functions. The third contribution is experimental support that an ELU-shaped activation function is favorable for learning; the tuneable piecewise linear activation function adapts to an ELU-shape during training, but with a small shift around the origin.
# 2 PIECEWISE LINEAR ACTIVATION FUNCTIONS
Piecewise linear activation functions were first introduced by Agostinelli et al. (2014). In this work, we use the same idea but now with the additional objective to investigate the shape of the learned activation function. If we initialize the activation function as a linearized version of ReLU, LReLU or ELU, how will the shape be changed during training?
Our formulation of a piecewise linear and continuous activation function is different from the one in Agostinelli et al. (2014) and consists of two steps: first a soft histogram is formed as in Felsberg & Granlund (2006), second, a weighted sum of the histogram outputs is computed. The piecewise linear activation functions are learned individually for each neuron.
# 2.1 SOFT HISTOGRAM
As it has been shown by Felsberg & Granlund (2006), a soft histogram can be represented by two components; one offset component and one histogram component. We use $N$ bins for positive input values and another $N$ bins for negative input values. All bins in the histogram have constant and unity width. The bin limits take integer values and the bin centers are at -0.5, 0.5, 1.5 etc. The concept of the soft histogram is illustrated in Figure 1. In the figure, $N$ is equal to 4, but in the experiments we also used more bins like $N = 8$ and 16. Within a certain activation layer, we extract the maximum and the minimum input over a minibatch. We then linearly scale the positive input values to lie in the range $[ 0 \mathrm { N } ]$ and the negative input values to lie in the range $[ - \mathbf { N } \mathbf { \Lambda } 0 ]$ . Now, as an example, consider two units with scaled input values of 2.68 and -1.80, respectively. For the first unit, the histogram component will be 1 for the bin centered at 2.5 and 0 for all other bins. The corresponding offset component will be 0.18, i.e. the signed distance from the bin center. For the second unit, the histogram component will be 1 for the bin centered at -1.5 and 0 for all other bins. The corresponding offset component will be -0.30. The output from the soft histogram for the two units will be
$$y ( 2 . 6 8 ) = { \left[ \begin{array} { l l l l l l l l l } { 0 } & { 0 } & { 0 } & { 0 } & { 0 } & { 0 } & { 0 } & { 0 . 1 8 } & { 0 } \\ { 0 } & { 0 } & { 0 } & { 0 } & { 0 } & { 0 } & { 1 } & { 0 } \end{array} \right] }$$
$$y ( - 1 . 8 0 ) = { \left[ \begin{array} { l l l l l l l l l } { 0 } & { 0 } & { - 0 . 3 0 } & { 0 } & { 0 } & { 0 } & { 0 } & { 0 } \\ { 0 } & { 0 } & { 1 } & { 0 } & { 0 } & { 0 } & { 0 } & { 0 } \end{array} \right] }$$
An analytical formulation of the soft histogram can be given as
$$y ( x ) = \left[ { \begin{array} { c } { \left( x - { \mathrm { \mathrm { H o o r } } } ( x ) - 0 . 5 \right) m _ { \nu } ( x ) } \\ { m _ { \nu } ( x ) } \end{array} } \right] _ { 2 \times 2 \mathrm { N } } = \left[ { \begin{array} { c c c c } { o _ { 0 } } & { o _ { 1 } } & { \cdots } & { o _ { 2 \mathrm { N } - 1 } } \\ { h _ { 0 } } & { h _ { 1 } } & { \cdots } & { h _ { 2 \mathrm { N } - 1 } } \end{array} } \right] ,$$
where $m _ { \nu } ( x )$ denotes the membership of the respective bins. The membership is 1 if the unit belongs to that bin and 0 for all other bins. The soft histogram output can alternatively be expressed with the offset and histogram components as in the right hand side of (2).
For backpropagation we need to compute the derivative of the soft histogram. In our formulation, we consider the membership $m _ { \nu } ( x )$ to be locally constant. This leads to a particular choice of subgradient that is also used in most implementations of max pooling, and it works well in practice. The derivative is computed as
$${ \frac { d y } { d x } } = \left[ { m _ { \nu } ( x ) } \right] _ { 2 \times 2 \mathrm { N } }$$
The output from the soft histogram is independent of the activation function, but any activation function can be represented or approximated by a weighted sum of the histogram output.
# 2.2 WEIGHTED SUM
Different piecewise linear activation functions can now be realized by varying the weights applied to the soft histogram outputs. For each activation layer, we define a matrix $W$ with weights for the
 Figure 1: Soft histogram decomposed into rectangular and linear basis functions.
 Figure 2: Weighted sum examples, ReLU activation (left) and LReLU activation (right).
offset components and the histogram components
$$W = \left[ { \begin{array} { l l l l } { w _ { o _ { 0 } } } & { w _ { o _ { 1 } } } & { \cdot \cdot \cdot } & { w _ { o _ { 2 \mathrm { N } - 1 } } } \\ { w _ { h _ { 0 } } } & { w _ { h _ { 1 } } } & { \cdot \cdot \cdot } & { w _ { h _ { 2 \mathrm { N } - 1 } } } \end{array} } \right] \quad .$$
To obtain a ReLU activation function, we set all weights to 1 for the offset components on the positive side and 0 for all offset components on the negative side. The weights for the offset components correspond to the slope of the activation function for each linear piece. Further, for a ReLU, we set the weights for the histogram components to 0.5, 1.5, 2.5, etc. on the positive side and to 0 on the negative side. The weights for the histogram components correspond to the bias level at the bin centers of the activation function for each linear piece.
To obtain a LReLU activation function, the weights (slopes) for the negative offset components are set to the value for the hyperparameter $\alpha$ , e.g. to 0.1. The weights for the offset components on the positive side are the same as for ReLU. For $\alpha = 0 . 1$ , the weights for the histogram components on the negative side are set to -0.35, -0.25, -0.15 and -0.05, i.e. the bias level at the bin centers.
To summarize, the weight matrices for the ReLU and LReLU activation functions are defined as
$$W _ { \mathrm { R e L U } } = \left[ { \begin{array} { c c c c c c c c } { 0 } & { 0 } & { 0 } & { 0 } & { 1 } & { 1 } & { 1 } & { 1 } \\ { 0 } & { 0 } & { 0 } & { 0 } & { 0 . 5 } & { 1 . 5 } & { 2 . 5 } & { 3 . 5 } \end{array} } \right]$$
$$W _ { \mathrm { L R e L U } } = \left[ \begin{array} { c c c c c c c c } { { 0 . 1 } } & { { 0 . 1 } } & { { 0 . 1 } } & { { 0 . 1 } } & { { 1 } } & { { 1 } } & { { 1 } } & { { 1 } } \\ { { - 0 . 3 5 } } & { { - 0 . 2 5 } } & { { - 0 . 1 5 } } & { { - 0 . 0 5 } } & { { 0 . 5 } } & { { 1 . 5 } } & { { 2 . 5 } } & { { 3 . 5 } } \end{array} \right] .$$
The output for the weighted sum is the sum of an elementwise multiplication of the soft histogram with the weight matrix
$$y = \sum _ { \nu } w _ { o _ { \nu } } o _ { \nu } + w _ { h _ { \nu } } h _ { \nu } .$$
The weighted sum output for the two example units is illustrated in Figure 2. For the ReLU activation, the outputs will be $2 . 5 \times 1 + 1 \times 0 . 1 8 = 2 . 6 8$ and $0 \times 1 + 0 \times ( - 0 . 3 0 ) = 0$ , respectively. For the LReLU activation, the output for the unit with input value -1.80 will be $- 0 . 1 5 \times 1 + 0 . 1 \times ( - 0 . 3 0 ) =$ -0.18, as desired.
Our formulation will generate a piecewise linear activation function for any values chosen as weights for the offset and histogram components. However, it is obvious that constraints need to be put on the weights if a continuous activation function is to be obtained. The weights (slopes) for the offset components can be set independently but only one weight for the histogram component is independent from the other weights. Assume that $w _ { h _ { 0 } }$ is set as desired. To obtain a continuous linear function, the remaining histogram weights then need to be set as
$$\begin{array} { r c l } { { w _ { h _ { 1 } } } } & { { = } } & { { w _ { h _ { 0 } } + 0 . 5 ( w _ { o _ { 0 } } + w _ { o _ { 1 } } ) } } \\ { { w _ { h _ { 2 } } } } & { { = } } & { { w _ { h _ { 0 } } + 0 . 5 ( w _ { o _ { 0 } } + 2 w _ { o _ { 1 } } + w _ { o _ { 2 } } ) } } \\ { { \vdots } } & { { } } & { { } } \\ { { w _ { h _ { 2 N - 1 } } } } & { { = } } & { { w _ { h _ { 0 } } + 0 . 5 ( w _ { o _ { 0 } } + 2 w _ { o _ { 1 } } + \cdots + 2 w _ { o _ { 2 N - 2 } } + w _ { o _ { 2 N - 1 } } ) . } } \end{array}$$
The constraints in (7) must be enforced when updating the weights in the backpropagation step.
# 3 SHIFTED ACTIVATION FUNCTIONS
The results presented in section 4.1 show that an ELU-shaped activation function which is shifted around the origin seems favorable to improve learning. Hence, we introduce the ShELU activation function with horizontal shift and the SvELU activation function with vertical shift and define them as in Table 2. The hyperparameter $\alpha$ is considered to be a pre-set constant and it is not tuned during training. In our experiments, we set $\alpha = 1$ . We also define PShELU, a variant of PELU with horizontal shift. The parameters $\alpha$ and $\beta$ for PShELU are learned during training. In the experiments, they were initialized as $\alpha = \beta = 1 . 0$ , i.e. as an original ELU activation.
Table 2: Shifted activation functions.
<table><tr><td rowspan=1 colspan=1>Activation</td><td rowspan=1 colspan=1>Value</td><td rowspan=1 colspan=1>Region 1</td><td rowspan=1 colspan=1>Value</td><td rowspan=1 colspan=1>Region 2</td></tr><tr><td rowspan=1 colspan=1>ShELUSvELUPShELU</td><td rowspan=1 colspan=1>x+8x+8(c+)</td><td rowspan=1 colspan=1>x+δ>0x>0x+δ>0</td><td rowspan=1 colspan=1>α(exp(x+δ)-1)α(exp(𝑥)-1)+δa(exp(+)-1)</td><td rowspan=1 colspan=1>x+δ≤0x≤0x+δ≤0</td></tr></table>
Note that the introduced shifts $\delta$ in Table 2 are individual for all neurons. As an example, consider the first layers in the Lenet network (LeCun et al., 1998) shown in Figure 3. The input is an image $3 2 \times 3 2 \times 3$ . In the first convolutional layer, there are 192 filters with size $5 \times 5 \times 3$ . The output from the convolutional layer consists of 192 feature maps with size $3 2 \times 3 2$ . The output includes a bias level for each feature map (each large square in the convolutional output), i.e. a total of 192 bias levels. The activation function is applied to the individual neurons resulting in an output with size $3 2 \times 3 2 \times 1 9 2$ . When we say that we introduce individual shifts for all neurons, it means that there is one tuneable shift for each of the $3 2 \times 3 2 \times 1 9 2$ neurons (all small squares in the activation output) where the activation function is applied.
In Goodfellow et al. (2016), chapter 9.5, it is stated that for CNNs it is natural to have shared biases with the same tiling pattern as the convolutional kernels, but that individual biases for each neuron ”would allow the model to correct for differences in the image statistics at different locations”. By introducing the activation function ShELU, with individual shifts for each neuron, we have indirectly created individual biases for the convolutional layer feature map output. Note that a convolutional layer with a shared bias level for each feature map output followed by a ShELU activation is equivalent with a convolutional layer with individual bias levels for each feature map output followed by an ELU activation. This equivalence was verified with experiments presented in section 4.2.1. However, frameworks as Caffe (Jia et al., 2014) and MatConvNet do not allow for individual biases in a convolutional layer but is restricted to shared biases.
# 4 EXPERIMENTS
# 4.1 EXPERIMENTS WITH PIECEWISE LINEAR ACTIVATION FUNCTIONS
To investigate the behavior of the piecewise linear activation function we made some experiments with the Lenet network and the Cifar-100 dataset (Krizhevsky & Hinton, 2009). We used the implementation of Lenet as provided when downloading the MatConvNet framework. We ran the Lenet network with the ReLU activation function, and also replaced all activation layers with LReLU and
 Figure 3: Bias levels for convolutional layers and shifts for activation function. Biases/shifts can either be shared (large squares) or individual for each neuron (small squares).
Table 3: Top1error on Cifar-100 with Lenet network.
<table><tr><td>Activation</td><td>Toplerror (%)</td><td>Activation</td><td>Toplerror (%)</td><td>Activation</td><td>Toplerror (%)</td></tr><tr><td>ReLU</td><td>46.58</td><td>LReLU</td><td>45.41</td><td>ELU</td><td>44.96</td></tr><tr><td>Tuned ReLU</td><td>45.92</td><td>Tuned LReLU</td><td>45.18</td><td>Tuned ELU</td><td>44.51</td></tr></table>
ELU. We then exchanged the activation layers with the piecewise linear activation layer. We initialized the layers as a linear version of ReLU, LReLU and ELU respectively. We consistently noticed a slight improvement (a few tenths of a percent) in classification performance when using the tuneable piecewise linear activation function compared to its corresponding fixed activation function, see Table 3. Besides the slight classification improvement, it is also interesting to analyse the shape of the activation functions after tuning, see Figure 4. All three activation functions remain linear and with almost unity slope on the positive side. All three tuned activation functions exhibit a smooth exponential decay for small negative inputs and then remain fairly constant for larger negative inputs. The resulting shape after tuning for all three initializations is close to the ELU shape. However, notice that all tuned activation functions tend to return a variable but negative output for zero input and that they do not pass through the origin. These results suggest that we introduce the Shifted Exponential Linear Unit (ShELU) as an activation function. From the results it is not obvious whether the introduced shift around the origin should be vertical or horizontal. For a horizontal shift, the saturation level remains constant for large negative inputs which may seem more intuitive. For a vertical shift, the saturation level will vary depending on the shift which better matches the achieved results on the Lenet network.
# 4.2 EXPERIMENTS WITH SHIFTED ACTIVATION FUNCTIONS
# 4.2.1 EXPERIMENTS ON CIFAR-100 WITH LENET NETWORK
We now want to evaluate if the classification performance improves with the new activation functions ShELU and SvELU compared to ELU. We start with the Lenet network and replace all ELU activations with either the ShELU or the SvELU activation. The learning rate was set to 0.005 for the first 40 epochs, then lowered by a factor of 10 every 20 epochs, running a total of 80 epochs. The learning rate momentum was set to 0.9 and the weight decay to 0.0005. Image data was preprocessed with global contrast normalization and whitening (Coates et al., 2011). Note that the complete dataset was divided by a factor of 10 (compared to the preprocessing provided with the MatConvNet download) to better match the variance with Xavier initialization. During training the dataset was augmented with random horizontal flipping and by randomly cropping images from the original images zero padded with a frame of width four.
The classification errors for the training and test sets shown in Figure 5 are the average over 8 runs for each activation function. The top1errors in Table 4 are the average over the last 15 epochs for the lowest learning rate. The learning rate for the ShELU and SvELU activation layer weights was set to $2 \%$ of the base learning rate. The results show that there is a small improvement on the top1error using the ShELU and SvELU activation functions compared with the original ELU. Futhermore, the shifted activation function PShELU achieves a slightly better test results than both ELU and PELU.
 Figure 4: Initialization (red) and 20, 50 and 80 percentiles for tuned activation functions in last layer; ReLU (left), LReLU (middle) and ELU (right).
 Figure 5: Training (dashed) and test (solid) errors on Cifar-100 with network Lenet (left). Test errors (final part) for ELU, SvELU and ShELU (middle), and ELU, PELU and PShELU (right).
Table 4: Top1 test errors on Cifar-100 with Lenet and Clevert-11 networks.
<table><tr><td>Activation</td><td>Lenetnetwork</td><td>Clevert-11 network</td></tr><tr><td>ELU</td><td>44.96</td><td>28.76</td></tr><tr><td>SvELU</td><td>44.70</td><td>28.85</td></tr><tr><td>ShELU</td><td>44.77</td><td>28.57</td></tr><tr><td>PELU</td><td>45.03</td><td>28.78</td></tr><tr><td>PShELU</td><td>44.76</td><td>28.74</td></tr><tr><td>ConvIndBias+ELU</td><td>44.78</td><td>1</td></tr></table>
The training behavior is very similar for all activation functions but the shifted activation functions exhibit a slightly better generalization behavior. However, the significance of these results is limited as Lenet is a rather shallow network.
We also created a network layer named ”ConvIndBias”, which is an identity mapping but it also adds an individually learned bias shift for each neuron. The results in Table 4 confirm that a ShELU activation is equivalent to the combination of a ConvIndBias layer and an ELU activation as was stated in section 3.
# 4.2.2 EXPERIMENTS ON CIFAR-100 WITH CLEVERT-11
To further evaluate the shifted activation functions in comparison with ELU, we built the 11-layer network used by Clevert et al. (2015) to replicate the experiments when ELU was introduced. We denote the network Clevert-11. Parameter settings and weight initializations were as in Clevert et al. (2015). Our results are the average over 9 runs for each activation function. Our classification results with the network Clevert-11 on the Cifar-100 dataset for the activation functions ELU, SvELU, ShELU, PELU and PShELU are presented in Figure 6 and summarized in Table 4. The results in the table are the average top1error over the last 20 epochs for each activation function. The results show that the test error for the ShELU activation function is significantly better than for ELU, whereas the error for SvELU is slightly inferior. The results suggest that a horizontal shift for the activation function is preferable to a vertical shift. The training behavior is almost identical for ELU and
 Figure 6: Training (dashed) and test (solid) errors on Cifar-100 with network Clevert-11 (left). Test errors (final part) for ELU, SvELU and ShELU (middle), and ELU, PELU and PShELU (right).
 Figure 7: Learned shifts for ShELU activation function, relative frequency (left), kurtosis (middle) and spatial variation (right).
ShELU. We believe that the improved test result can be attributed to that ShELU adaptively learns where to set the reference level between the linear and exponential parts of the activation function.
ELU, PELU and PShELU all show very similar test errors. Note, however, that the training error is by far lower for PELU indicating pronounced overfitting compared to ELU. The training error is lower for PShELU than for ShELU but the test error is inferior. This suggests that PShELU suffers from overfitting when allowed to tune the hyperparameters $\alpha$ and $\beta$ . Note that we were able to almost exactly reproduce the results for ELU achieved in Clevert et al. (2015) who report a top1error of $2 8 . 7 5 \%$ .
# 4.3 LEARNED SHIFTS FOR SHELU
In all experments, we initialized the individual shifts for the ShELU activation from a Gaussian distribution with standard deviation 0.001. The learned shifts after training in the 10 activation layers of the Clevert-11 network are shown as normalized frequency histograms in Figure 7, together with the kurtosis and the spatial variation for the shifts.
The shape of the learned shifts is almost a perfect Gaussian distribution for all layers. This is supported by the computed kurtosis which is close to 3.0. The kurtosis increases slightly for the last three layers where the distribution tends to be somewhat skewed towards the negative side. The standard deviation for the shift is relatively constant for the first nine layers but grows considerably for the last layer.
Figure 7 shows the learned shifts for the first ShELU activation layer where the shifts for the 192 feature maps have been placed as $1 2 \times 1 6$ tiles side by side. Interestingly, the spatial variation for the learned shift seems to be completely random. Any statistical difference spatially over the image cannot be perceived.
# 5 CONCLUSIONS
We use a new formulation to tune a continuous piecewise linear activation function during training and learn the shape of the locally optimal activation function. With this tuned activation function, the classification performance for convolutional neural networks is improved and the resulting, learned activation function shows to be ELU-shaped irrespective whether it is initialized as a RELU, LReLU or ELU activation function. The learned activation function exhibits a variable shift around the origin for each neuron, indicating that a shifted ELU-shaped activation function is preferable. This observation leads us to introduce the Shifted Exponential Linear Unit (ShELU) as a new activation function.
Experiments on Cifar-100 show that the classification performance is further improved when using the ShELU activation function in comparison with ELU. Normally in a convolutional network layer, one shared bias shift is learned for each feature map output. The improvement for the ShELU activation is achieved when learning an individual bias shift for each neuron. The equivalent to the ShELU activation function would be to learn an individual bias shift for each neuron in the convolutional layer output and then apply an ELU activation, which however is not supported by commonly used deep learning frameworks. The implementation of individual biases in the activation function is therefore preferable and leads to the ShELU activation function.
# REFERENCES
Forest Agostinelli, Matthew Hoffman, Peter Sadowski, and Pierre Baldi. Learning activation functions to improve deep neural networks. arXiv preprint arXiv:1412.6830, 2014.
Djork-Arne Clevert, Thomas Unterthiner, and Sepp Hochreiter. Fast and accurate deep network ´ learning by exponential linear units (elus). arXiv preprint arXiv:1511.07289, 2015.
Adam Coates, Andrew Ng, and Honglak Lee. An analysis of single-layer networks in unsupervised feature learning. In Proceedings of the fourteenth international conference on artificial intelligence and statistics, pp. 215–223, 2011.
J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li, and L. Fei-Fei. ImageNet: A Large-Scale Hierarchical Image Database. In CVPR09, 2009.
Michael Felsberg and Gosta Granlund. P-channels: Robust multivariate m-estimation of large ¨ datasets. In Pattern Recognition, 2006. ICPR 2006. 18th International Conference on, volume 3, pp. 262–267. IEEE, 2006.
Xavier Glorot and Yoshua Bengio. Understanding the difficulty of training deep feedforward neural networks. In Proceedings of the Thirteenth International Conference on Artificial Intelligence and Statistics, pp. 249–256, 2010.
Xavier Glorot, Antoine Bordes, and Yoshua Bengio. Deep sparse rectifier neural networks. In Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics, pp. 315–323, 2011.
Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Deep learning. MIT press, 2016.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 770–778, 2016.
Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. In Francis Bach and David Blei (eds.), Proceedings of the 32nd International Conference on Machine Learning, volume 37 of Proceedings of Machine Learning Research, pp. 448–456, Lille, France, 07–09 Jul 2015. PMLR. URL http://proceedings. mlr.press/v37/ioffe15.html.
Yangqing Jia, Evan Shelhamer, Jeff Donahue, Sergey Karayev, Jonathan Long, Ross Girshick, Sergio Guadarrama, and Trevor Darrell. Caffe: Convolutional architecture for fast feature embedding. arXiv preprint arXiv:1408.5093, 2014.
Gunter Klambauer, Thomas Unterthiner, Andreas Mayr, and Sepp Hochreiter. Self-normalizing ¨ neural networks. arXiv preprint arXiv:1706.02515, 2017.
Alex Krizhevsky and Geoffrey Hinton. Learning multiple layers of features from tiny images. 2009.
Yann Le Cun, Ido Kanter, and Sara A Solla. Eigenvalues of covariance matrices: Application to neural-network learning. Physical Review Letters, 66(18):2396, 1991.
Yann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner. Gradient-based learning applied to ´ document recognition. Proceedings of the IEEE, 86(11):2278–2324, 1998.
Min Lin, Qiang Chen, and Shuicheng Yan. Network in network. arXiv preprint arXiv:1312.4400, 2013.
Andrew L Maas, Awni Y Hannun, and Andrew Y Ng. Rectifier nonlinearities improve neural network acoustic models. In Proc. ICML, volume 30, 2013.
MatConvNet. http://www.vlfeat.org/matconvnet/,v.beta-20.
Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. Dropout: a simple way to prevent neural networks from overfitting. Journal of machine learning research, 15(1):1929–1958, 2014.
Ludovic Trottier, Philippe Giguere, and Brahim Chaib-draa. Parametric exponential linear unit for \` deep convolutional neural networks. arXiv preprint arXiv:1605.09332, 2016.
# APPENDIX
# DERIVATIVES OF SHELU AND SVELU
For backpropagation, the derivates of ShELU and SvELU with respect to the input $x$ and the shift $\delta$ are computed as
$$\begin{array} { r l } & { \frac { d \mathrm { S h E L U } } { d x } = \left\{ 1 , \mathrm { ~ i f ~ } x + \delta > 0 \right. } \\ & { \frac { d \mathrm { S h E L U } } { d \delta } = \left\{ 1 , \mathrm { ~ i f ~ } x + \delta > 0 \right. } \\ & { \frac { d \mathrm { S h E L U } } { d \delta } = \left\{ 1 , \mathrm { ~ i f ~ } x + \delta > 0 \right. } \\ & { \frac { d \mathrm { S v E L U } } { d x } = \left\{ 1 , \mathrm { ~ i f ~ } x > 0 \right. } \\ & { \frac { d \mathrm { S v E L U } } { d \delta } = \left\{ \alpha ( \exp ( x ) ) , \mathrm { i f ~ } x \leq 0 \right. } \\ & { \frac { d \mathrm { S v E L U } } { d \delta } = 1 } \end{array}$$
# DERIVATIVES OF PSHELU
For backpropagation, the derivates of PShELU with respect to the input $x$ , the hyperparameters $\alpha$ and $\beta$ , and the shift $\delta$ are computed as
$$\begin{array} { r l } & { \frac { d \mathrm { P S h e L U } } { d x } = \left\{ \frac { \alpha } { \beta } , \ \mathrm { i f } \ x + \delta > 0 \right. } \\ & { \frac { d \mathrm { P S h e L U } } { d \alpha } = \left\{ \frac { \alpha + \delta } { \beta } , \ \mathrm { i f } \ x + \delta > 0 \right. } \\ & { \frac { d \mathrm { P S h e L U } } { d \alpha } = \left\{ \frac { \alpha + \delta } { \beta } , \ \mathrm { i f } \ x + \delta > 0 \right. } \\ & { \frac { d \mathrm { P S h e L U } } { d \beta } = \left\{ - \frac { \alpha } { \beta ^ { 2 } } ( x + \delta ) , \ \mathrm { i f } \ x + \delta > 0 \right. } \\ & { \frac { d \mathrm { P S h e L U } } { d \beta } = \left\{ - \frac { \alpha } { \beta ^ { 2 } } ( \exp ( \frac { \alpha + \delta } { \beta } ) ) , \ \mathrm { i f } \ x + \delta \leq 0 \right. } \\ & { \frac { d \mathrm { P S h e L U } } { d \delta } = \left\{ \frac { \alpha } { \beta } , \ \mathrm { i f } \ x + \delta > 0 \right. } \end{array}$$123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303# SSE-PT: SEQUENTIAL RECOMMENDATION VIA PERSONALIZED TRANSFORMER
Anonymous authors Paper under double-blind review
# ABSTRACT
Temporal information is crucial for recommendation problems because user preferences are naturally dynamic in the real world. Recent advances in deep learning, especially the discovery of various attention mechanisms and newer architectures in addition to widely used RNN and CNN in natural language processing, have allowed for better use of the temporal ordering of items that each user has engaged with. In particular, the SASRec model, inspired by the popular Transformer model in natural languages processing, has achieved state-of-the-art results. However, SASRec, just like the original Transformer model, is inherently an un-personalized model and does not include personalized user embeddings. To overcome this limitation, we propose a Personalized Transformer (SSE-PT) model, outperforming SASRec by almost $5 \%$ in terms of NDCG $@ 1 0$ on 5 real-world datasets. Furthermore, after examining some random users’ engagement history, we find our model not only more interpretable but also able to focus on recent engagement patterns for each user. Moreover, our SSE-PT model with a slight modification, which we call $\mathrm { S S E – P T + + }$ , can handle extremely long sequences and outperform SASRec in ranking results with comparable training speed, striking a balance between performance and speed requirements. Our novel application of the Stochastic Shared Embeddings (SSE) regularization is essential to the success of personalization. Code and data are open-sourced at https://github.com/SSE-PT/SSE-PT.
# 1 INTRODUCTION
The sequential recommendation problem has been an important open research question, yet using temporal information to improve recommendation performance has proven to be challenging. SASRec, proposed by (Kang and McAuley, 2018) for sequential recommendation problems, has achieved stateof-the-art results and enjoyed more than 10x speed-up when compared to earlier CNN/RNN-based methods. However, the model used in SASRec is the standard Transformer which is inherently an un-personalized model. In practice, it is important to include a personalized Transformer in SASRec especially for recommender systems, but (Kang and McAuley, 2018) found that adding additional personalized embeddings did not improve the performance of their Transformer model, and postulate that the failure of adding personalization is due to the fact that they already use the user history and the user embeddings only contribute to overfitting. In this work, we propose a novel method, Personalized Transformer (SSE-PT), that successfully introduces personalization into self-attentive neural network architectures.
Introducing user embeddings into the standard transformer model is intrinsically difficult with existing regularization techniques, as unavoidably a large number of user parameters are introduced, which is often at the same scale of the number of training data. But we show that personalization can greatly improve ranking performance with a recent regularization technique called Stochastic Shared Embeddings (SSE) (Wu et al., 2019). The personalized Transformer (SSE-PT) model with SSE regularization works well for all 5 real-world datasets we consider without overfitting, outperforming previous state-of-the-art algorithm SASRec by almost $5 \%$ in terms of ${ \mathrm { N D C G } } @ 1 0 .$ . Furthermore, after examining some random users’ engagement history, we find our model is not only more interpretable but also able to focus on recent engagement patterns for each user. Moreover, our SSE-PT model with a slight modification, which we call SSE- $\mathrm { \cdot P T } { + } { + }$ , can handle extremely long sequences and outperform SASRec in ranking results with comparable training speed, striking a balance between performance and speed requirements.
# 2 RELATED WORK
# 2.1 SESSION-BASED AND SEQUENTIAL RECOMMENDATION
Both session-based and sequential (i.e., next-basket) recommendation algorithms take advantage of additional temporal information to make better personalized recommendations. The main difference between session-based recommendations (Hidasi et al., 2015) and sequential recommendations (Kang and McAuley, 2018) is that the former assumes that the user ids are not recorded and therefore the length of engagement sequences are relatively short. Therefore, session-based recommendations normally do not consider user factors. On the other hand, sequential recommendation treats each sequence as a user’s engagement history (Kang and McAuley, 2018). Both settings, do not explicitly require time-stamps: only the relative temporal orderings are assumed known (in contrast to, for example, timeS $\mathrm { V D } { + } { + }$ (Koren, 2009) using time-stamps). Initially, sequence data in temporal order are usually modelled with Markov models, in which a future observation is conditioned on the last few observed items (Rendle et al., 2010). In (Rendle et al., 2010), a personalized Markov model with user latent factors is proposed for more personalized results.
In recent years, deep learning techniques, borrowed from natural language processing (NLP) literature, are getting widely used in tackling sequential data. Like word sentences in NLP, item sequences in recommendations can be similarly modelled by recurrent neural networks (RNN) (Hidasi et al., 2015; Hidasi and Karatzoglou, 2018) and convolutional neural network (CNN) (Tang and Wang, 2018) models. Recently, attention models are increasingly used in both NLP (Vaswani et al., 2017; Devlin et al., 2018) and recommender systems (Liu et al., 2018; Kang and McAuley, 2018). SASRec (Kang and McAuley, 2018) is a recent method with state-of-the-art performance among the many deep learning models. Motivated by the Transformer model in neural machine translation (Vaswani et al., 2017), SASRec utilizes a similar architecture to the encoder part of the Transformer model. Our proposed model, SSE-PT, is a personalized extension of the transformer model.
# 2.2 REGULARIZATION TECHNIQUES
In deep learning, models with many more parameters than data points can easily overfit to the training data. This may prevent us from adding user embeddings as additional parameters into complicated models like the Transformer model (Kang and McAuley, 2018), which can easily have 20 layers with millions of parameters for a medium-sized dataset like Movielens10M (Harper and Konstan, 2016). $\ell _ { 2 }$ regularization (Hoerl and Kennard, 1970) is the most widely used approach and has been used in many matrix factorization models in recommender systems; $\ell _ { 1 }$ regularization (Tibshirani, 1996) is used when a sparse model is preferred. For deep neural networks, it has been shown that $\ell _ { p }$ regularizations are often too weak, while dropout (Hinton et al., 2012; Srivastava et al., 2014) is more effective in practice. There are many other regularization techniques, including parameter sharing (Goodfellow et al., 2016), max-norm regularization (Srebro et al., 2005), gradient clipping (Pascanu et al., 2013), etc. Very recently, a new regularization technique called Stochastic Shared Embeddings (SSE) (Wu et al., 2019) is proposed as a new means of regularizing embedding layers. We find that the base version SSE-SE is essential to the success of our Personalized Transformer (SSE-PT) model.
# 3 METHODOLOGY
# 3.1 SEQUENTIAL RECOMMENDATION
Given $n$ users and each user engaging with a subset of $m$ items in a temporal order, the goal of sequential recommendation is to learn a good personalized ranking of top $K$ items out of total $m$ items for any given user at any given time point. We assume data in the format of $n$ item sequences:
$$s _ { i } = ( j _ { i 1 } , j _ { i 2 } , \ldots , j _ { i T } ) \mathrm { f o r } 1 \le i \le n .$$
Sequences $s _ { i }$ of length $T$ contain indices of the last $T$ items that user $i$ has interacted with in the temporal order (from old to new). For different users, the sequence lengths can vary, but we can pad the shorter sequences so all of them have length $T$ . We cannot simply randomly split data points into train/validation/test sets because they come in temporal orders. Instead, we need to make sure our training data is before validation data which is before test data temporally. We use last items in sequences as test sets, second-to-last items as validation sets and the rest as training sets. We use ranking metrics such as NDCG $@ K$ and Recal $@ K$ for evaluations, which are defined in the Appendix.
# 3.2 PERSONALIZED TRANSFORMER ARCHITECTURE
Our model, which we call SSE-PT, is motivated by the Transformer model in (Vaswani et al., 2017) and (Kang and McAuley, 2018). It also utilizes a new regularization technique called stochastic shared embeddings (Wu et al., 2019). In the following sections, we are going to examine each important component of our Personalized Transformer (SSE-PT) model, especially the embedding layer, and the novel application of stochastic shared embeddings (SSE) regularization technique.
Embedding Layer We define a learnable user embedding look-up table $U \in R ^ { n \times d _ { u } }$ and item embedding look-up table $V \in R ^ { m \times d _ { i } }$ , where $d _ { u }$ , $d _ { i }$ are the number of hidden units for user and item respectively. We also specify learnable positional encoding table $P \in R ^ { T \times d }$ , where $d = d _ { u } + d _ { i }$ . So each input sequence $s _ { i } \in \dot { R ^ { T } }$ will be represented by the following embedding:
$$E = \left[ \begin{array} { c } { \left[ v _ { j _ { i 1 } } ; u _ { i } \right] + p _ { 1 } } \\ { \left[ v _ { j _ { i 2 } } ; u _ { i } \right] + p _ { 2 } } \\ { \vdots } \\ { \left[ v _ { j _ { i T } } ; u _ { i } \right] + p _ { T } } \end{array} \right] \in R ^ { T \times d } ,$$
where $[ v _ { j _ { i t } } ; u _ { i } ]$ represents concatenating item embedding $v _ { j _ { i t } } \in R ^ { d _ { i } }$ and user embedding $u _ { i } \in R ^ { d _ { u } }$ into embedding $E _ { t } \in R ^ { d }$ for time $t$ . Note that the main difference between our model and (Kang and McAuley, 2018) is that we introduce the user embeddings $u _ { i }$ , making our model personalized.
 Figure 1: Illustration of our proposed SSE-PT model
Transformer Encoder On top of the embedding layer, we have $B$ blocks of self-attention layers and fully connected layers, where each layer extracts features for each time step based on the previous layer’s outputs. Since this part is identical to the Transformer encoder used in the original papers (Vaswani et al., 2017; Kang and McAuley, 2018), we will skip the details.
Prediction Layer At time $t$ , the predicted probability of user $i$ engaged item $l$ is:
$$p _ { i t l } = \sigma ( r _ { i t l } ) ,$$
where $\sigma$ is the sigmoid function and $r _ { i t l }$ is the predicted score of item $l$ by user $l$ at time point $t$ defined as:
$$r _ { i t l } = F _ { t - 1 } ^ { B } \cdot [ v _ { l } ; u _ { i } ] ,$$
where $F _ { t - 1 } ^ { B }$ is the output hidden units associated with the transformer encoder at the last timestamp. Although we can use another set of user and item embedding look-up tables for the $u _ { i }$ and $v _ { l }$ , we
find it better to use the same set of embedding look-up tables $U , V$ as in the embedding layer. But regularization for those embeddings can be different. To distinguish the $u _ { i }$ and $v _ { l }$ in (4) from $u _ { i } , v _ { j }$ in (2), we call embeddings in (4) output embeddings and those in (2) input embeddings.
The binary cross entropy loss between predicted probability for the positive item $l = j _ { i ( t + 1 ) }$ and one uniformly sampled negative item $k \in \Omega$ is given as $- [ \log ( p _ { i t l } ) + \log ( 1 - p _ { i t k } ) ]$ . Summing over $s _ { i }$ and $t$ , we obtain the objective function that we want to minimize is:
$$\sum _ { i } \sum _ { t = 1 } ^ { T - 1 } \sum _ { k \in \Omega } - \big [ \log ( p _ { i t l } ) + \log ( 1 - p _ { i t k } ) \big ] .$$
At the inference time, top- $K$ recommendations for user $i$ at time $t$ can be made by sorting scores $r _ { i t l }$ for all items $\ell$ and recommending the first $K$ items in the sorted list.
Novel Application of Stochastic Shared Embeddings The most important regularization technique to SSE-PT model is the Stochastic Shared Embeddings (SSE) (Wu et al., 2019). The main idea of SSE is to stochastically replace embeddings with another embedding with some pre-defined probability during SGD, which has the effect of regularizing the embedding layers. Without SSE, all the existing well-known regularization techniques like layer normalization, dropout and weight decay fail and cannot prevent the model from over-fitting badly after introducing user embeddings. (Wu et al., 2019) develops two versions of SSE, SSE-Graph and SSE-SE. In the simplest uniform case, SSE-SE replaces one embedding with another embedding uniformly with probability $p$ , which is called SSE probability in (Wu et al., 2019). Since we don’t have knowledge graphs for user or items, we simply apply the SSE-SE to our SSE-PT model. We find SSE-SE makes possible training this personalized model with $O ( n d _ { u } )$ additional parameters.
There are 3 different places in our model that SSE-SE can be applied. We can apply SSE-SE to input/output user embeddings, input item embeddings, and output item embeddings with probabilities $p _ { u }$ , $p _ { i }$ and $p _ { y }$ respectively. Note that input user embedding and output user embedding are always replaced at the same time with SSE probability $p _ { u }$ . Empirically, we find that SSE-SE to user embeddings and output item embeddings always helps, but SSE-SE to input item embeddings is only useful when the average sequence length is large, e.g., more than 100 in Movielens1M and Movielens10M datasets.
Other Regularization Techniques Besides the SSE (Wu et al., 2019), we also utilized other widely used regularization techniques, including layer normalization (Ba et al., 2016), batch normalization (Ioffe and Szegedy, 2015), residual connections (He et al., 2016), weight decay (Krogh and Hertz, 1992), and dropout (Srivastava et al., 2014). Since they are used in the same way in the previous paper (Kang and McAuley, 2018), we omit the details to the Appendix.
# 3.3 HANDLING LONG SEQUENCES: SSE-PT $^ { + + }$
To handle extremely long sequences, a slight modification can be made on the base SSE-PT model in terms of how input sequences $s _ { i }$ ’s are fed into the SSE-PT neural network. We call the enhanced model SSE- $\mathrm { P T } { + } { + }$ to distinguish it from the previously discussed SSE-PT model, which cannot handle sequences longer than $T$ .
The motivation of SSE- $\mathbf { \nabla } \cdot \mathbf { P } \mathbf { T } + +$ over SSE-PT comes from: sometimes we want to make use of extremely long sequences, $s _ { i } = ( j _ { i 1 } , j _ { i 2 } , . ~ . ~ . ~ , j _ { i t } )$ for $1 \leq i \leq n$ , where $t > T$ , but our SSE-PT model can only handle sequences of maximum length of $T$ . The simplest way is to sample starting index $1 \leq v \leq t$ uniformly and use $s _ { i } = ( j _ { i v } , j _ { i ( v + 1 ) } , . ~ . ~ . , j _ { i z } )$ , where $z = \operatorname* { m i n } ( t , v + T - 1 )$ . Although sampling the starting index uniformly from $[ 1 , t ]$ can accommodate long sequences of length $t > T$ , this does not work well in practice. Uniform sampling does not take into account the importance of recent items in a long sequence. To solve this dilemma, we introduce an additional hyper-parameter $p _ { s }$ which we call sampling probability. It implies that with probability $p _ { s }$ , we sample the starting index $v$ uniformly from $[ 1 , t - T ]$ and use sequence $s _ { i } = \left( j _ { i v } , j _ { i ( v + 1 ) } , \ldots , j _ { i ( v + T - 1 ) } \right)$ as input. With probability $1 - p _ { s }$ we simply use the recent $T$ items $( j _ { i ( t - T + 1 ) } , \ldots , j _ { i t } )$ as input. If the sequence $s _ { i }$ is already shorter than $T$ , then we always use the recent input sequence for user $i$ .
Our proposed SSE- $\mathrm { P T } { + } { + }$ model can work almost as well as SSE-PT with a much smaller $T$ . One can see in Table 2 with $T = 1 0 0$ , SSE-PT++ can perform almost as well as SSE-PT. The time complexity of the SSE-PT model is of order $O ( T ^ { 2 } d + T d ^ { 2 } )$ . Therefore, reducing $T$ by one half would lead to a theoretically $4 \mathbf { x }$ speed-up in terms of the training and inference speeds. As to the model’s space complexity, both SSE-PT and SSE- $\mathrm { P T } { + } { + }$ are of order $O ( n d _ { u } + m \dot { d _ { i } } + T d + d ^ { 2 } )$ .
# 4 EXPERIMENTS
In this section, we compare our proposed algorithms, Personalized Transformer (SSE-PT) and SSE$\mathrm { P T } { + } { + }$ , with other state-of-the-art algorithms on real-world datasets. We implement our codes in Tensorflow and conduct all our experiments on a server with 40-core Intel Xeon E5-2630 v4 $@$ 2.20GHz CPU, 256G RAM and Nvidia GTX 1080 GPUs.
Datasets We use 5 datasets. The first 4 have exactly the same train/dev/test splits as in (Kang and McAuley, 2018). The datasets are: Beauty and Games categories from Amazon product review datasets1; Steam dataset introduced in (Kang and McAuley, 2018), which contains reviews crawled from a large video game distribution platform; Movielens1M dataset (Harper and Konstan, 2016), a widely used benchmark datasets containing one million user movie ratings; Movielens10M dataset with ten million user ratings cleaned by us. Detailed dataset statistics are given in Table 4. One can easily see that the first 3 datasets have short sequences (average length $< 1 2$ ) while the last 2 datasets have very long sequences $\mathrm { \Phi } > 1 0 \mathrm { \mathbf { x } }$ longer).
Evaluation Metrics The evaluation metrics we use are standard ranking metrics, namely NDCG and Recall for top recommendations (See Appendix). We follow the same evaluation setting as the previous paper (Kang and McAuley, 2018): predicting ratings at time point $t + 1$ given the previous $t$ ratings. For a large dataset with numerous users and items, the evaluation procedure would be slow because (6) would require computing the ranking of all items based on their predicted scores for every single user. As a means of speed-up evaluations, we sample a fixed number $C$ (e.g., 100) of negative candidates while always keeping the positive item that we know the user will engage next. This way, both $R _ { i j }$ and $\Pi _ { i }$ will be narrowed down to a small set of item candidates, and prediction scores will only be computed for those items through a single forward pass of the neural network.
Ideally, we want both NDCG and Recall to be as close to 1 as possible, because $\operatorname { N D C G @ } K = 1$ means the positive item is always put on the top-1 position of the top- $K$ ranking list, and Recall $\Theta K = 1$ means the positive item is always contained by the top- $K$ recommendations the model makes.
Table 1: Comparing various state-of-the-art temporal collaborative ranking algorithms on various datasets. The (A) to (E) are non-deep-learning methods, the $( \mathrm { F } )$ to (K) are deep-learning methods and the (L) to (O) are our variants. We did not report SSE- $\mathbf { \nabla } \cdot \mathbf { P } \mathbf { T } + +$ results for beauty, games and steam, as the input sequence lengths are very short (see Table 4), so there is no need for SSE- $\mathrm { P T } { + } { + }$ .
<table><tr><td rowspan="2">DATASET METRIC</td><td colspan="2">BEAUTY</td><td colspan="2">GAMES</td><td colspan="2">STEAM</td><td colspan="2"></td><td colspan="2">ML-1M</td></tr><tr><td>RECALL@10 NDCG@10</td><td></td><td></td><td>RECALL@10 NDCG@10</td><td></td><td></td><td>RECALL@10 NDCG@10</td><td></td><td>RECALL@10 NDCG@10</td><td></td></tr><tr><td>(A)POPREC</td><td>0.4003</td><td>0.2277</td><td>1</td><td>0.4724</td><td>0.2779</td><td>0.7172</td><td>0.4535</td><td>1</td><td>0.4329</td><td>0.2377</td></tr><tr><td>(B)BPR</td><td>0.3775</td><td>0.2183</td><td>一 1</td><td>0.4853</td><td>0.2875</td><td>0.7061</td><td>0.4436</td><td>1 1</td><td>0.5781</td><td>0.3287</td></tr><tr><td>(C)FMC</td><td>0.3771</td><td>0.2477</td><td>一</td><td>0.6358</td><td>0.4456</td><td>0.7731</td><td>0.5193</td><td>1</td><td>0.6983</td><td>0.4676</td></tr><tr><td>(D)FPMC</td><td>0.4310</td><td>0.2891</td><td>一</td><td>0.6802</td><td>0.4680</td><td>0.7710</td><td>0.5011</td><td>1</td><td>0.7599</td><td>0.5176</td></tr><tr><td>(E)TRANSREC</td><td>0.4607</td><td>0.3020</td><td>一</td><td>0.6838</td><td>0.4557</td><td>0.7624</td><td>0.4852</td><td>1 1</td><td>0.6413</td><td>0.3969</td></tr><tr><td>(F) GRU4REC</td><td>0.2125</td><td>0.1203</td><td>1</td><td>0.2938</td><td>0.1837</td><td>0.4190</td><td>0.2691</td><td>1</td><td>0.5581</td><td>0.3381</td></tr><tr><td>(G) STAMP</td><td>0.4607</td><td>0.3020</td><td>一</td><td>0.6838</td><td>0.4557</td><td>0.7624</td><td>0.4852</td><td>1</td><td>0.6413</td><td>0.3969</td></tr><tr><td>(H) GRU4REC+</td><td>0.3949</td><td>0.2556</td><td>一 一</td><td>0.6599</td><td>0.4759</td><td>0.8018</td><td>0.5595</td><td>1 1</td><td>0.7501</td><td>0.5513</td></tr><tr><td>(I) CASER</td><td>0.4264</td><td>0.2547</td><td>1</td><td>0.5282</td><td>0.3214</td><td>0.7874</td><td>0.5381</td><td>1</td><td>0.7886</td><td>0.5538</td></tr><tr><td>(J) SASREC</td><td>0.4837</td><td>0.3220</td><td>1</td><td>0.7434</td><td>0.5401</td><td>0.8732</td><td>0.6293</td><td>1</td><td>0.8233</td><td>0.5936</td></tr><tr><td>(K)HGN</td><td>0.4469</td><td>0.2994</td><td>1 1</td><td>0.7164</td><td>0.5209</td><td>0.7426</td><td>0.4871</td><td>1 1</td><td>0.7584</td><td>0.5241</td></tr><tr><td>(L) SSE-SASREC</td><td>0.4878</td><td>0.3342</td><td>1</td><td>0.7517</td><td>0.5535</td><td>0.8697</td><td>0.6333</td><td>1</td><td>0.8230</td><td>0.5995</td></tr><tr><td>(M)PT</td><td>0.3954</td><td>0.2449</td><td>1 1</td><td>0.6427</td><td>0.4434</td><td>0.7535</td><td>0.4853</td><td>1 1</td><td>0.7658</td><td>0.5241</td></tr><tr><td>(N) SSE-PT</td><td>0.5028</td><td>0.3370</td><td>一</td><td>0.7757</td><td>0.5660</td><td>0.8772</td><td>0.6378</td><td>一</td><td>0.8341</td><td>0.6281</td></tr><tr><td>(O) SSE-PT++</td><td>二</td><td>=</td><td>一</td><td>二</td><td>二</td><td></td><td></td><td>1</td><td>0.8389</td><td>0.6292</td></tr></table>
Baselines We include 5 non-deep-learning and 6 deep-learning algorithms in our comparisons.
Table 2: Comparing SASRec, SSE-PT and SSE- $\mathbf { \nabla \cdot P T + + }$ on Movielens1M Dataset while varying the maximum length allowed and dimension of embeddings.
<table><tr><td>METHODS</td><td>NDCG@10</td><td>RECALL @10</td><td>MAX LEN</td><td>USER DIM</td><td>ITEMDIM</td></tr><tr><td>SASREC</td><td>0.5769</td><td>0.8045</td><td>100</td><td>N/A</td><td>100</td></tr><tr><td>SASREC</td><td>0.5936</td><td>0.8233</td><td>200</td><td>N/A</td><td>50</td></tr><tr><td>SASREC</td><td>0.5919</td><td>0.8202</td><td>200</td><td>N/A</td><td>100</td></tr><tr><td>SSE-PT</td><td>0.6142</td><td>0.8212</td><td>100</td><td>50</td><td>100</td></tr><tr><td>SSE-PT</td><td>0.6191</td><td>0.8358</td><td>200</td><td>50</td><td>50</td></tr><tr><td>SSE-PT</td><td>0.6281</td><td>0.8341</td><td>200</td><td>50</td><td>100</td></tr><tr><td>SSE-PT++</td><td>0.6186</td><td>0.8318</td><td>100</td><td>50</td><td>100</td></tr><tr><td>SSE-PT++</td><td>0.6208</td><td>0.8358</td><td>200</td><td>50</td><td>50</td></tr><tr><td>SSE-PT++</td><td>0.6292</td><td>0.8389</td><td>200</td><td>50</td><td>100</td></tr></table>
Non-deep-learning Baselines The simplest baseline is PopRec, basically ranking items according to their popularity. More advanced methods such as matrix factorization based baselines include Bayesian personalized ranking for implicit feedback (Rendle et al., 2009), namely $B P R$ ; Factorized Markov Chains and Personalized Factorized Markov Chains models (Rendle et al., 2010) also known as FMC and PFMC; and translation based method (He et al., 2017) called TransRec.
Deep-learning Baselines Recent years have seen many advances in deep learning for sequential recommendations. GRU4Rec is the first RNN-based method proposed for this problem (Hidasi et al., 2015); $G R U 4 R e c ^ { + }$ (Hidasi and Karatzoglou, 2018) later is proposed to address some shortcomings of the initial version. Caser is the corresponding CNN-based method (Tang and Wang, 2018). STAMP (Liu et al., 2018) utilizes the attention mechanism without using RNN or CNN as building blocks. Very recently, SASRec utilizes state-of-art Transformer encoder (Vaswani et al., 2017) with selfattention mechanisms. Hierarchical gating networks, also known as HGN (Ma et al., 2019) are also proposed to solve this problem.
Table 3: Comparing Different Regularizations for SSE-PT on Movielen1M Dataset. NO REG stands for no regularization. PS stands for parameter sharing across all users while PS(AGE) means PS is used within each age group. SASRec is added to last row after all SSE-PT results as a baseline.
<table><tr><td>REGULARIZATION</td><td>NDCG@5</td><td>% GAIN</td><td>RECALL@5</td><td>%GAIN</td></tr><tr><td>NO REG (BASELINE)</td><td>0.4855</td><td>1</td><td>0.6500</td><td>-</td></tr><tr><td>PS</td><td>0.5065</td><td>4.3</td><td>0.6656</td><td>2.4</td></tr><tr><td>PS (JOB)</td><td>0.4938</td><td>1.7</td><td>0.6570</td><td>1.1</td></tr><tr><td>PS (GENDER)</td><td>0.5110</td><td>5.3</td><td>0.6672</td><td>2.6</td></tr><tr><td>PS (AGE)</td><td>0.5133</td><td>5.7</td><td>0.6743</td><td>3.7</td></tr><tr><td>l2</td><td>0.5149</td><td>6.0</td><td>0.6786</td><td>4.4</td></tr><tr><td>DROPOUT</td><td>0.5165</td><td>6.4</td><td>0.6823</td><td>5.0</td></tr><tr><td>l2+DROPOUT</td><td>0.5293</td><td>9.0</td><td>0.6921</td><td>6.5</td></tr><tr><td>SSE-SE</td><td>0.5393</td><td>11.1</td><td>0.6977</td><td>7.3</td></tr><tr><td>l2 + SSE-SE + DROPOUT</td><td>0.5870</td><td>20.9</td><td>0.7442</td><td>14.5</td></tr><tr><td>SASREC (l2+DROPOUT)</td><td>0.5601</td><td></td><td>0.7164</td><td></td></tr></table>
Experiment Setup We use the same datasets as in (Kang and McAuley, 2018) and follow the same procedure in the paper: use last items for each user as test data, second-to-last as validation data and the rest as training data. We implemented our method in Tensorflow and solve it with Adam Optimizer (Kingma and Ba, 2014) with a learning rate of 0.001, momentum exponential decay rates $\beta _ { 1 } = 0 . 9 , \beta _ { 2 } = 0 . 9 8$ and a batch size of 128. In Table 1, since we use the same data, the performance of previous methods except STAMP have been reported in (Kang and McAuley, 2018). We tune the dropout rate, and SSE probabilities $p _ { u } , p _ { i } , p _ { y }$ for input user/item embeddings and output embeddings on validation sets and report the best NDCG and Recall for top- $K$ recommendations on test sets. For a fair comparison, we restrict all algorithms to use up to 50 hidden units for item embeddings. For the SSE-PT and SASRec models, we use the same number of transformer encoder blocks (i.e. $B = 2$ ) and set the maximum length $T = 2 0 0$ for Movielens 1M and 10M dataset and $T = 5 0$ for other datasets. We use top- $K$ with $K = 1 0$ and the number of negatives $C = 1 0 0$ in the evaluation procedure. In practice, using a different $K$ and $C$ does not affect our conclusions.
Comparisons One can easily see from Table 1 that our proposed SSE-PT has the best performance over all previous methods on all four datasets. On most datasets, our SSE-PT improves NDCG by more than $4 \%$ when compared with SASRec (Kang and McAuley, 2018) and more than $20 \%$ when compared to non-deep-learning methods. SSE-SE, together with dropout and weight decay, is the best choice for regularization, which is evident from Table 3. SSE-SE is a more effective way to regularize our neural networks than any existent techniques including parameter sharing, dropout, weight decay. In practice, these SSE probabilities, just like dropout rate, can be treated as tuning parameters and easily tuned. Movielens10M results are left to Table 6 in the Appendix.

Figure 2: Illustration of how SASRec (Left) and SSE-PT (Right) differs on utilizing the Engagement History of A Random User in Movielens1M Dataset.
# 4.1 ATTENTION MECHANISM VISUALIZATION
Apart from evaluating our SSE-PT against SASRec using well-defined ranking metrics on realworld datasets, we also visualize the differences between both methods in terms of their attention mechanisms. In Figure 2, a random user’s engagement history in Movielens1M dataset is given in temporal order (column-wise). We hide the last item whose index is 26 in test set and hope that a temporal collaborative ranking model can figure out item-26 is the one this user will watch next using only previous engagement history. One can see for a typical user; they tend to look at a different style of movies at different times. Earlier on, they watched a variety of movies, including Sci-Fi, animation, thriller, romance, horror, action, comedy and adventure. But later on, in the last two columns of Figure 2, drama and thriller are the two types they like to watch most, especially the drama type. In fact, they watched 9 drama movies out of recent 10 movies. For humans, it is natural to reason that the hidden movie should probably also be drama type. So what about the machine’s reasoning?
For our SSE-PT, the hidden item indexed 26 is put in the first place among its top-5 recommendations. Intelligently, the SSE-PT recommends 3 drama movies, 2 thriller movies and mixing them up in positions. Interestingly, the top recommendation is ‘Othello’, which like the recently watched ‘Richard III’, is an adaptation of a Shakespeare play, and this dependence is reflected in the attention weight. On the contrast, SASRec cannot provide top-5 recommendations that are personalized enough. It recommends a variety of action, Sci-Fi, comedy, horror, and drama movies but none of them match item-26. Although this user has watched all these types of movies in the past, they do not watch these anymore as one can easily tell from his recent history. Unfortunately, SASRec cannot capture this and does not provide personalized recommendations for this user by focusing more on drama and thriller movies. It is easy to see that in contrast, our SSE-PT model shares with human reasoning that more emphasis should be placed on recent movies.
# 4.2 TRAINING SPEED
In (Kang and McAuley, 2018), it has been shown that SASRec is about 11 times faster than Caser and 17 times faster than $\mathrm { G R U 4 R e c ^ { + } }$ and achieves much better NDCG $@ 1 0$ results so we did not include Caser and GRU4Rec+ in our comparisons. In Figure 3, we only compare the training speeds and ranking performances among SASRec, SSEPT and SSE- $\mathrm { P T } { + } { + }$ for Movielens1M dataset. Given that we added additional user embeddings into our SSE-PT model, it is expected that it will take slightly longer to train our model than un-personalized SASRec. We find empirically that training speed of the SSE-PT and SSE$\mathrm { P T } { + } { + }$ model are comparable to that of SASRec, with SSE$\mathrm { P T } { + } { + }$ being the fastest and the best performing model. It is clear that our SSE-PT and $\mathrm { S S E – P T + + }$ achieve much better ranking performances than our baseline SASRec using the same training time.
 Figure 3: Illustration of the speed of SSE-PT
# 4.3 ABLATION STUDY
SSE probability Given the importance of SSE regularization for our SSE-PT model, we carefully examined the SSE probability for input user embedding in Table 7 in Appendix. We find that the appropriate hyper-parameter SSE probability is not very sensitive: anywhere between 0.4 and 1.0 gives good results, better than parameter sharing and not using SSE-SE. This is also evident based on comparison results in Table 3.
Sampling Probability Recall that the sampling probability is unique to our SSE- $\mathrm { P T } { + } { + }$ model. We show in Table 8 in Appendix using an appropriate sampling probability like $0 . 2 0 . 3$ would allow it to outperform SSE-PT when the same maximum length is used.
Number of Attention Blocks We find for our SSE-PT model, a larger number of attention blocks is preferred. One can easily see in Table 9 in Appendix, the optimal ranking performances are achieved at $B = 4$ or 5 for Movielens1M dataset and at $B = 6$ for Movielens10M dataset.
Personalization and Number of Negatives Sampled Based on the results in Table 10 in Appendix, we are positive that the personalized model always outperforms the un-personalized one when we use the same regularization techniques. This holds true regardless of how many negatives sampled or what ranking metrics are used during evaluation.
# 5 CONCLUSION
In this paper, we propose a novel neural network architecture called Personalized Transformer for the temporal collaborative ranking problem. It enjoys the benefits of being a personalized model, therefore achieving better ranking results for individual users than the current state-of-the-art. By examining the attention mechanisms during inference, the model is also more interpretable and tends to pay more attention to recent items in long sequences than un-personalized deep learning models.
# REFERENCES
Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016.
Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. arXiv preprint arXiv:1412.3555, 2014.
Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Bert: Pre-training of deep bidirectional transformers for language understanding. arXiv preprint arXiv:1810.04805, 2018.
Ian Goodfellow, Yoshua Bengio, Aaron Courville, and Yoshua Bengio. Deep learning, volume 1. MIT press Cambridge, 2016.
F Maxwell Harper and Joseph A Konstan. The movielens datasets: History and context. Acm transactions on interactive intelligent systems (tiis), 5(4):19, 2016.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 770–778, 2016.
Ruining He, Wang-Cheng Kang, and Julian McAuley. Translation-based recommendation. In Proceedings of the Eleventh ACM Conference on Recommender Systems, pages 161–169. ACM, 2017.
Balázs Hidasi and Alexandros Karatzoglou. Recurrent neural networks with top- $\mathbf { \nabla } _ { k }$ gains for sessionbased recommendations. In Proceedings of the 27th ACM International Conference on Information and Knowledge Management, pages 843–852. ACM, 2018.
Balázs Hidasi, Alexandros Karatzoglou, Linas Baltrunas, and Domonkos Tikk. Session-based recommendations with recurrent neural networks. arXiv preprint arXiv:1511.06939, 2015.
Geoffrey E Hinton, Nitish Srivastava, Alex Krizhevsky, Ilya Sutskever, and Ruslan R Salakhutdinov. Improving neural networks by preventing co-adaptation of feature detectors. arXiv preprint arXiv:1207.0580, 2012.
Arthur E Hoerl and Robert W Kennard. Ridge regression: Biased estimation for nonorthogonal problems. Technometrics, 12(1):55–67, 1970.
Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. arXiv preprint arXiv:1502.03167, 2015.
Wang-Cheng Kang and Julian McAuley. Self-attentive sequential recommendation. arXiv preprint arXiv:1808.09781, 2018.
Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014.
Yehuda Koren. Collaborative filtering with temporal dynamics. In Proceedings of the 15th ACM SIGKDD international conference on Knowledge discovery and data mining, pages 447–456. ACM, 2009.
Anders Krogh and John A Hertz. A simple weight decay can improve generalization. In Advances in neural information processing systems, pages 950–957, 1992.
Qiao Liu, Yifu Zeng, Refuoe Mokhosi, and Haibin Zhang. Stamp: short-term attention/memory priority model for session-based recommendation. In Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining, pages 1831–1839. ACM, 2018.
Chen Ma, Peng Kang, and Xue Liu. Hierarchical gating networks for sequential recommendation. arXiv preprint arXiv:1906.09217, 2019.
Razvan Pascanu, Tomas Mikolov, and Yoshua Bengio. On the difficulty of training recurrent neural networks. In International Conference on Machine Learning, pages 1310–1318, 2013.
Steffen Rendle, Christoph Freudenthaler, Zeno Gantner, and Lars Schmidt-Thieme. Bpr: Bayesian personalized ranking from implicit feedback. In Proceedings of the twenty-fifth conference on uncertainty in artificial intelligence, pages 452–461. AUAI Press, 2009.
Steffen Rendle, Christoph Freudenthaler, and Lars Schmidt-Thieme. Factorizing personalized markov chains for next-basket recommendation. In Proceedings of the 19th international conference on World wide web, pages 811–820. ACM, 2010.
Badrul Munir Sarwar, George Karypis, Joseph A Konstan, John Riedl, et al. Item-based collaborative filtering recommendation algorithms. Www, 1:285–295, 2001.
Nathan Srebro, Jason Rennie, and Tommi S Jaakkola. Maximum-margin matrix factorization. In Advances in neural information processing systems, pages 1329–1336, 2005.
Nitish Srivastava, Geoffrey Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. Dropout: a simple way to prevent neural networks from overfitting. The Journal of Machine Learning Research, 15(1):1929–1958, 2014.
Jiaxi Tang and Ke Wang. Personalized top-n sequential recommendation via convolutional sequence embedding. In Proceedings of the Eleventh ACM International Conference on Web Search and Data Mining, pages 565–573. ACM, 2018.
Robert Tibshirani. Regression shrinkage and selection via the lasso. Journal of the Royal Statistical Society. Series B (Methodological), pages 267–288, 1996.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in Neural Information Processing Systems, pages 5998–6008, 2017.
Liwei Wu, Cho-Jui Hsieh, and James Sharpnack. Sql-rank: A listwise approach to collaborative ranking. In Proceedings of Machine Learning Research (35th International Conference on Machine Learning), volume 80, 2018.
Liwei Wu, Shuqing Li, Cho-Jui Hsieh, and James Sharpnack. Stochastic shared embeddings: Datadriven regularization of embedding layers. arXiv preprint arXiv:1905.10630, 2019.
# 6 APPENDIX
• $\operatorname { N D C G @ } K$ : defined as:
$$\mathrm { N D C G @ } K = \frac { 1 } { n } \sum _ { i = 1 } ^ { n } \frac { \mathrm { D C G @ } K ( i , \Pi _ { i } ) } { \mathrm { D C G @ } K ( i , \Pi _ { i } ^ { * } ) } ,$$
where $i$ represents $i$ -th user and
$$\mathrm { D C G @ } K ( i , \Pi _ { i } ) = \sum _ { l = 1 } ^ { K } \frac { 2 ^ { R _ { i \Pi _ { i l } } } - 1 } { \log _ { 2 } ( l + 1 ) } .$$
In the DCG definition, $\Pi _ { i l }$ represents the index of the $l$ -th ranked item for user $i$ in test data based on the learned score matrix $X$ . $R$ is the rating matrix and $R _ { i j }$ is the rating given to item $j$ by user $i$ . $\Pi _ { i } ^ { * }$ is the ordering provided by the ground truth rating.
• Recall $@ K$ : defined as a fraction of positive items retrieved by the top $K$ recommendations the model makes:
$${ \mathrm { R e c a l l @ } } K = { \frac { \sum _ { i = 1 } ^ { n } \mathbb { 1 } \left\{ \exists 1 \leq l \leq K : R _ { i \Pi _ { i l } } = 1 \right\} } { n } } ,$$
here we already assume there is only a single positive item that user will engage next and the indicator function $\mathbb { 1 } \{ \exists 1 \leq l \leq k : { R _ { i \Pi _ { i l } } } = \hat { 1 } \}$ is defined to indicate whether the positive item falls into the top $K$ position in our obtained ranked list using scores predicted in (4).
Layer Normalization Layer normalization (Ba et al., 2016) normalizes neurons within a layer. Previous studies (Ba et al., 2016) show it is more effective than batch normalization for training recurrent neural networks (RNNs). One alternative is the batch normalization (Ioffe and Szegedy, 2015) but we find it does not work as well as the layer normalization in practice even for a reasonable large batch size of 128. Therefore, our SSE-PT model adopts layer normalization.
Residual Connections Residual connections are firstly proposed in ResNet for image classification problems (He et al., 2016). Recent research finds that residual connections can help training very deep neural networks even if they are not convolutional neural networks (Vaswani et al., 2017). Using residual connections allows us to train very deep neural networks here. For example, the best performing model for Movielens10M dataset in Table 9 is the SSE-PT with 6 attention blocks, in which $1 + 6 * 3 + 1 = 2 0$ layers are trained end-to-end.
Weight Decay Weight decay (Krogh and Hertz, 1992), also known as $l _ { 2 }$ regularization (Hoerl and Kennard, 1970), is applied to all embeddings, including both user and item embeddings.
Dropout Dropout (Srivastava et al., 2014) is applied to the embedding layer $E$ , self-attention layer and pointwise feed-forward layer by stochastically dropping some percentage of hidden units to prevent co-adaption of neurons. Dropout has been shown to be an effective way of regularizing deep learning models.
In summary, layer normalization and dropout are used in all layers except prediction layer. Residual connections are used in both self-attention layer and pointwise feed-forward layer. SSE-SE is used in embedding layer and prediction layer.
Table 4: Description of Datasets Used in Evaluations.
<table><tr><td>DATASET</td><td>#USERS</td><td>#ITEMS</td><td>AVG SEQUENCELEN</td><td>MAX SEQUENCE LEN</td></tr><tr><td>BEAUTY</td><td>52,024</td><td>57,289</td><td>7.6</td><td>291</td></tr><tr><td>GAMES</td><td>31,013</td><td>23,715</td><td>7.3</td><td>858</td></tr><tr><td>STEAM</td><td>334,730</td><td>13,047</td><td>11.0</td><td>1,229</td></tr><tr><td>ML-1M</td><td>6,040</td><td>3,416</td><td>163.5</td><td>2,275</td></tr><tr><td>ML-10M</td><td>69,878</td><td>65,133</td><td>141.1</td><td>7,357</td></tr></table>
Table 5: Comparing our SSE-PT, SSE- $\mathrm { P T } { + } { + }$ with SASRec on Movielen1M dataset. We use number of negatives $C = 1 0 0$ , dropout probability of 0.2 and learning rate of $1 e ^ { - 3 }$ for all experiments while varying others. $p _ { u } , p _ { i } , p _ { u }$ are SSE probabilities for user embedding, input item embedding and output item embedding respectively.
<table><tr><td rowspan="2">Model</td><td colspan="2">Movielens1m</td><td colspan="2">Dimensions</td><td colspan="2">Number of Blocks</td><td colspan="3">Sampling Probability SSE-SE Parameters</td></tr><tr><td>NDCG@10</td><td>Recall@10</td><td>du</td><td>di</td><td>b</td><td>ps</td><td>Pu</td><td>Pi</td><td>Py</td></tr><tr><td>SASRec</td><td>0.5961</td><td>0.8195</td><td>-</td><td>50</td><td>2</td><td></td><td>-</td><td>=</td><td>-</td></tr><tr><td>SASRec</td><td>0.5941</td><td>0.8182</td><td>-</td><td>100</td><td>2</td><td></td><td></td><td>=</td><td>-</td></tr><tr><td>SASRec</td><td>0.5996</td><td>0.8272</td><td>-</td><td>100</td><td>6</td><td></td><td>-</td><td>-</td><td>-</td></tr><tr><td>SSE-PT</td><td>0.6101</td><td>0.8343</td><td>50</td><td>50</td><td>2</td><td></td><td>0.92</td><td>0.1</td><td>0</td></tr><tr><td>SSE-PT</td><td>0.6164</td><td>0.8336</td><td>50</td><td>50</td><td>2</td><td></td><td>0.92</td><td>0</td><td>0.1</td></tr><tr><td>SSE-PT</td><td>0.5832</td><td>0.8091</td><td>50</td><td>50</td><td>2</td><td></td><td>0</td><td>0.1</td><td>0.1</td></tr><tr><td>SSE-PT</td><td>0.6174</td><td>0.8351</td><td>50</td><td>50</td><td>2</td><td></td><td>0.92</td><td>0.1</td><td>0.1</td></tr><tr><td>SSE-PT</td><td>0.5949</td><td>0.8205</td><td>75</td><td>25</td><td>2</td><td></td><td>0.92</td><td>0.1</td><td>0.1</td></tr><tr><td>SSE-PT</td><td>0.6214</td><td>0.8359</td><td>25</td><td>75</td><td>2</td><td></td><td>0.92</td><td>0.1</td><td>0.1</td></tr><tr><td>SSE-PT</td><td>0.6281</td><td>0.8341</td><td>50</td><td>100</td><td>2</td><td></td><td>0.92</td><td>0.1</td><td>0.1</td></tr><tr><td>SSE-PT++</td><td>0.6292</td><td>0.8389</td><td>50</td><td>100</td><td>2</td><td>0.3</td><td>0.92</td><td>0.1</td><td>0.1</td></tr></table>
Table 6: Comparing our SSE-PT with SASRec on Movielens10M dataset. Unlike Table 5, we use the number of negatives $C = 5 0 0$ instead of 100 as $C = 1 0 0$ is too easy for this dataset and it gets too difficult to tell the differences between different methods: Hit Ratio $@ 1 0$ approaches 1.
<table><tr><td rowspan="2"></td><td colspan="2">Movielens1m</td><td colspan="2">Dimensions</td><td colspan="2">Number of Blocks</td><td colspan="3">SSE-SE Parameters</td></tr><tr><td>Model NDCG@10</td><td>Hit Ratio@10</td><td>d</td><td>di</td><td></td><td>b</td><td>Pu</td><td>Pi</td><td>Py</td></tr><tr><td>SASRec</td><td>0.7268</td><td>0.9429</td><td>-</td><td>50</td><td>2</td><td></td><td>1</td><td>-</td><td>1</td></tr><tr><td>SASRec</td><td>0.7413</td><td>0.9474</td><td>1</td><td>100</td><td>2</td><td></td><td>1</td><td>1</td><td>1</td></tr><tr><td>SSE-PT</td><td>0.7199</td><td>0.9331</td><td>50</td><td>100</td><td>2</td><td></td><td>PS</td><td>0.01</td><td>0.01</td></tr><tr><td>SSE-PT</td><td>0.7169</td><td>0.9296</td><td>50</td><td>100</td><td>2</td><td></td><td>0.0</td><td>0.01</td><td>0.01</td></tr><tr><td>SSE-PT</td><td>0.7398</td><td>0.9418</td><td>50</td><td>100</td><td>2</td><td></td><td>0.2</td><td>0.01</td><td>0.01</td></tr><tr><td>SSE-PT</td><td>0.7500</td><td>0.9500</td><td>50</td><td>100</td><td>2</td><td></td><td>0.4</td><td>0.01</td><td>0.01</td></tr><tr><td>SSE-PT</td><td>0.7484</td><td>0.9480</td><td>50</td><td>100</td><td></td><td>2</td><td>0.6</td><td>0.01</td><td>0.01</td></tr><tr><td>SSE-PT</td><td>0.7529</td><td>0.9485</td><td>50</td><td>100</td><td></td><td>2</td><td>0.8</td><td>0.01</td><td>0.01</td></tr><tr><td>SSE-PT</td><td>0.7503</td><td>0.9505</td><td>50</td><td>100</td><td></td><td>2</td><td>1.0</td><td>0.01</td><td>0.01</td></tr></table>
• PopRec: ranking items according to their popularity.
• BPR: Bayesian personalized ranking for implicit feedback setting (Rendle et al., 2009). It is a low-rank matrix factorization model with a pairwise loss function. But it does not utilize the temporal information. Therefore, it serves as a strong baseline for non-temporal methods.
• FMC: Factorized Markov Chains: a first-order Markov Chain method, in which predictions are made only based on previously engaged item.
• PFMC: a personalized Markov chain model (Rendle et al., 2010) that combines matrix factorization and first-order Markov Chain to take advantage of both users’ latent long-term preferences as well as short-term item transitions.
• TransRec: a first-order sequential recommendation method (He et al., 2017) in which items are embedded into a transition space and users are modelled as translation vectors operating on item sequences.
SQL-Rank (Wu et al., 2018) and item-based recommendations (Sarwar et al., 2001) are omitted because the former is similar to BPR (Rendle et al., 2009) except using the listwise loss function instead of the pairwise loss function and the latter has been shown inferior to TransRec (He et al., 2017).
# 6.0.1 DEEP-LEARNING BASELINES
• GRU4Rec: the first RNN-based method proposed for the session-based recommendation problem (Hidasi et al., 2015). It utilizes the GRU structures (Chung et al., 2014) initially proposed for speech modelling.
• GRU4Rec+: follow-up work of GRU4Rec by the same authors: the model has a very similar architecture to GRU4Rec but has a more complicated loss function (Hidasi and Karatzoglou, 2018).
• Caser: a CNN-based method (Tang and Wang, 2018) which embeds a sequence of recent items in both time and latent spaces forming an ‘image’ before learning local features through horizontal and vertical convolutional filters. In (Tang and Wang, 2018), user embeddings are included in the prediction layer only. On the contrast, in our Personalized Transformer, user embeddings are also introduced in the lowest embedding layer so they can play an important role in self-attention mechanisms as well as in prediction stages.
• STAMP: a session-based recommendation algorithm (Liu et al., 2018) using attention mechanism. (Liu et al., 2018) only uses fully connected layers with one attention block that is not self-attentive.
• SASRec: a self-attentive sequential recommendation method (Kang and McAuley, 2018) motivated by Transformer in NLP (Vaswani et al., 2017). Unlike our method SSE-PT, SASRec does not incorporate user embedding and therefore is not a personalized method. SASRec paper (Kang and McAuley, 2018) also does not utilize SSE (Wu et al., 2019) for further regularization: only dropout and weight decay are used.
• HGN: hierarchical gating networks method to solve the sequential recommendation problem (Ma et al., 2019), which incorporates the user embeddings and gating networks for better personalization than the SASRec model.
Table 7: Comparing Different SSE probability for user embeddings for SSE-PT on Movielens1M Dataset. Embedding hidden units of 50 for users and 100 for items, attention blocks of 2, SSE probability of 0.01 for item embeddings, dropout probability of 0.2 and max length of 200 are used.
<table><tr><td>USER-SIDE SSE-SE PROBABILITY</td><td>NDCG@10</td><td>RECALL@10</td></tr><tr><td>PARAMETER SHARING</td><td>0.6188</td><td>0.8294</td></tr><tr><td>1.0</td><td>0.6258</td><td>0.8346</td></tr><tr><td>0.9</td><td>0.6275</td><td>0.8321</td></tr><tr><td>0.8</td><td>0.6244</td><td>0.8359</td></tr><tr><td>0.6</td><td>0.6256</td><td>0.8341</td></tr><tr><td>0.4</td><td>0.6237</td><td>0.8369</td></tr><tr><td>0.2</td><td>0.6163</td><td>0.8281</td></tr><tr><td>0.0</td><td>0.5908</td><td>0.8048</td></tr></table>
Table 8: Comparing Different Sampling Probability, $p _ { s }$ , of SSE- $\mathrm { P T } { + } { + }$ on Movielens1M Dataset. Hyper-parameters the same as Table 7, except that the max length $T$ allowed is set 100 instead of 200 to show effects of sampling sequences.
<table><tr><td>SAMPLING PROBABILITY</td><td>NDCG@10</td><td>RECALL@10</td></tr><tr><td>SASREC (T: =100)</td><td>0.5769</td><td>0.8045</td></tr><tr><td>SSE-PT(T: = 100)</td><td>0.6142</td><td>0.8212</td></tr><tr><td>1.0</td><td>0.5697</td><td>0.7977</td></tr><tr><td>0.8</td><td>0.5735</td><td>0.7801</td></tr><tr><td>0.6</td><td>0.6062</td><td>0.8242</td></tr><tr><td>0.4</td><td>0.6113</td><td>0.8273</td></tr><tr><td>0.3</td><td>0.6186</td><td>0.8318</td></tr><tr><td>0.2</td><td>0.6193</td><td>0.8233</td></tr><tr><td>0.0</td><td>0.6142</td><td>0.8212</td></tr></table>
Table 9: Comparing Different Number of Blocks for SSE-PT while Keeping The Rest Fixed on Movielens1M and Movielens10M Datasets.
<table><tr><td>DATASETS</td><td># OF BLOCKS</td><td>NDCG@10</td><td>RECALL@10</td></tr><tr><td rowspan="7">MOVIELENS1M</td><td>SASREC (6 BLOCKS)</td><td>0.5984</td><td>0.8207</td></tr><tr><td>1</td><td>0.6162</td><td>0.8301</td></tr><tr><td>2</td><td>0.6280</td><td>0.8365</td></tr><tr><td>3</td><td>0.6293</td><td>0.8376</td></tr><tr><td>4</td><td>0.6270</td><td>0.8401</td></tr><tr><td>5</td><td>0.6308</td><td>0.8361</td></tr><tr><td>6</td><td>0.6270</td><td>0.8397</td></tr><tr><td rowspan="6">MOVIELENS10M</td><td>SASREC(6 BLOCKS)</td><td>0.7531</td><td>0.9490</td></tr><tr><td>1</td><td>0.7454</td><td>0.9478</td></tr><tr><td>2</td><td>0.7512</td><td>0.9522</td></tr><tr><td>3</td><td>0.7543</td><td>0.9491</td></tr><tr><td>4</td><td>0.7608</td><td>0.9485</td></tr><tr><td>5</td><td>0.7619</td><td>0.9524</td></tr><tr><td></td><td>6</td><td>0.7683</td><td>0.9537</td></tr></table>
Table 10: Varying number of negatives $C$ in evaluation on Movielens1M dataset. Other hyperparameters are fixed for a fair comparison.
<table><tr><td>METRIC</td><td>NDCG@10</td><td>RECALL @10</td><td>C</td></tr><tr><td>UN-PERSONALIZED</td><td>0.3787</td><td>0.6119</td><td>500</td></tr><tr><td>PERSONALIZED</td><td>0.3846</td><td>0.6171</td><td>500</td></tr><tr><td>UN-PERSONALIZED</td><td>0.2791</td><td>0.4781</td><td>1000</td></tr><tr><td>PERSONALIZED</td><td>0.2860</td><td>0.4929</td><td>1000</td></tr><tr><td>UN-PERSONALIZED</td><td>0.1939</td><td>0.3515</td><td>2000</td></tr><tr><td>PERSONALIZED</td><td>0.1993</td><td>0.3667</td><td>2000</td></tr></table>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306# RELAXED QUANTIZATION FOR DISCRETIZED NEURAL NETWORKS
Christos Louizos∗ University of Amsterdam TNO Intelligent Imaging c.louizos@uva.nl
Matthias Reisser QUVA Lab University of Amsterdam m.reisser@uva.nl
Tijmen Blankevoort Qualcomm AI Research tijmen@qti.qualcomm.com
Efstratios Gavves QUVA Lab University of Amsterdam egavves@uva.nl
Max Welling University of Amsterdam Qualcomm m.welling@uva.nl
# ABSTRACT
Neural network quantization has become an important research area due to its great impact on deployment of large models on resource constrained devices. In order to train networks that can be effectively discretized without loss of performance, we introduce a differentiable quantization procedure. Differentiability can be achieved by transforming continuous distributions over the weights and activations of the network to categorical distributions over the quantization grid. These are subsequently relaxed to continuous surrogates that can allow for efficient gradient-based optimization. We further show that stochastic rounding can be seen as a special case of the proposed approach and that under this formulation the quantization grid itself can also be optimized with gradient descent. We experimentally validate the performance of our method on MNIST, CIFAR 10 and Imagenet classification.
# 1 INTRODUCTION
Neural networks excel in a variety of large scale problems due to their highly flexible parametric nature. However, deploying big models on resource constrained devices, such as mobile phones, drones or IoT devices is still challenging because they require a large amount of power, memory and computation. Neural network compression is a means to tackle this issue and has therefore become an important research topic.
Neural network compression can be, roughly, divided into two not mutually exclusive categories: pruning and quantization. While pruning (LeCun et al., 1990; Han et al., 2015) aims to make the model “smaller” by altering the architecture, quantization aims to reduce the precision of the arithmetic operations in the network. In this paper we focus on the latter. Most network quantization methods either simulate or enforce discretization of the network during training, e.g. via rounding of the weights and activations. Although seemingly straighforward, the discontinuity of the discretization makes the gradient-based optimization infeasible. The reason is that there is no gradient of the loss with respect to the parameters. A workaround to the discontinuity are the “pseudo-gradients” according to the straight-through estimator (Bengio et al., 2013), which have been successfully used for training low-bit width architectures at e.g. Hubara et al. (2016); Zhu et al. (2016).
The purpose of this work is to introduce a novel quantization procedure, Relaxed Quantization (RQ). RQ can bypass the non-differentiability of the quantization operation during training by smoothing it appropriately. The contributions of this paper are four-fold: First, we show how to make the set of quantization targets part of the training process such that we can optimize them with gradient descent. Second, we introduce a way to discretize the network by converting distributions over the weights and activations to categorical distributions over the quantization grid. Third, we show that we can obtain a “smooth” quantization procedure by replacing the categorical distributions with concrete (Maddison et al., 2016; Jang et al., 2016) equivalents. Finally we show that stochastic rounding (Gupta et al., 2015), one of the most popular quantization techniques, can be seen as a special case of the proposed framework. We present the details of our approach in Section 2, discuss related work in Section 3 and experimentally validate it in Section 4. Finally we conclude and provide fruitful directions for future research in Section 5.
 Figure 1: The proposed discretization process. (a) Given a distribution $p ( \tilde { x } )$ over the real line we partition it into $K$ intervals of width $\alpha$ where the center of each of the intervals is a grid point $g _ { i }$ . The shaded area corresponds to the probability of $\tilde { x }$ falling inside the interval containing that specific $g _ { i }$ . (b) Categorical distribution over the grid obtained after discretization. The probability of each of the grid points $g _ { i }$ is equal to the probability of $\tilde { x }$ falling inside their respective intervals.
# 2 RELAXED QUANTIZATION FOR DISCRETIZING NEURAL NETWORKS
The central element for the discretization of weights and activations of a neural network is a quantizer $q ( \cdot )$ . The quantizer receives a (usually) continous signal as input and discretizes it to a countable set of values. This process is inherently lossy and non-invertible: given the output of the quantizer, it is impossible to determine the exact value of the input. One of the simplest quantizers is the rounding function:
$$q ( x ) = \alpha \left\lfloor { \frac { x } { \alpha } } + { \frac { 1 } { 2 } } \right\rfloor ,$$
where $\alpha$ corresponds to the step size of the quantizer. With $\alpha = 1$ , the quantizer rounds $x$ to its nearest integer number.
Unfortunately, we cannot simply apply the rounding quantizer to discretize the weights and activations of a neural network. Because of the quantizers’ lossy and non-invertible nature, important information might be destroyed and lead to a decrease in accuracy. To this end, it is preferable to train the neural network while simulating the effects of quantization during the training procedure. This encourages the weights and activations to be robust to quantization and therefore decreases the performance gap between a full-precision neural network and its discretized version.
However, the aforementioned rounding process is non-differentiable. As a result, we cannot directly optimize the discretized network with stochastic gradient descent, the workhorse of neural network optimization. In this work, we posit a “smooth” quantizer as a possible way for enabling gradient based optimization.
# 2.1 LEARNING (FIXED POINT) QUANTIZERS VIA GRADIENT DESCENT
The proposed quantizer comprises four elements: a vocabulary, its noise model and the resulting discretization procedure, as well as a final relaxation step to enable gradient based optimization.
The first element of the quantizer is the vocabulary: it is the set of (countable) output values that the quantizer can produce. In our case, this vocabulary has an inherent structure, as it is a grid of ordered
scalars. For fixed point quantization the grid $\mathcal { G }$ is defined as
$$\mathcal { G } = \left[ - 2 ^ { b - 1 } , \ldots , 0 , \ldots , 2 ^ { b - 1 } - 1 \right] ,$$
where $b$ is the number of available bits that allow for $K = 2 ^ { b }$ possible integer values. By construction this grid of values is agnostic to the input signal $x$ and hence suboptimal; to allow for the grid to adapt to $x$ we introduce two free parameters, a scale $\alpha$ and an offset $\beta$ . This leads to a learnable grid via $\hat { \mathcal { G } } = \alpha \mathcal { G } + \beta$ that can adapt to the range and location of the input signal.
The second element of the quantizer is the assumption about the input noise $\epsilon$ ; it determines how probable it is for a specific value of the input signal to move to each grid point. Adding noise to $x$ will result in a quantizer that is, on average, a smooth function of its input. In essense, this is an application of variational optimization (Staines & Barber, 2012) to the non-differentiable rounding function, which enables us to do gradient based optimization.
We model this form of noise as acting additively to the input signal $x$ and being governed by a distribution $p ( \epsilon )$ . This process induces a distribution $p ( \tilde { x } )$ where $\tilde { x } = x + \epsilon$ . In the next step of the quantization procedure, we discretize $p ( \tilde { x } )$ according to the quantization grid $\hat { \mathcal G }$ ; this neccesitates the evaluation of the cumulative distribution function (CDF). For this reason, we will assume that the noise is distributed according to a zero mean logistic distribution with a standard deviation $\sigma$ , i.e. $L ( 0 , \sigma )$ , hence leading to $p ( \bar { \tilde { x } } ) = L ( x , \sigma )$ . The CDF of the logistic distribution is the sigmoid function which is easy to evaluate and backpropagate through. Using Gaussian distributions proved to be less effective in preliminary experiments. Other distributions are conceivable and we will briefly discuss the choice of a uniform distribution in Section 2.3.
The third element is, given the aforementioned assumptions, how the quantizer determines an appropriate assignment for each realization of the input signal $x$ . Due to the stochastic nature of $\tilde { x }$ , a deterministic round-to-nearest operation will result in a stochastic quantizer for $x$ . Quantizing $x$ in this manner corresponds to discretizing $p ( \tilde { x } )$ onto $\hat { \mathcal G }$ and then sampling grid points $g _ { i }$ from it. More specifically, we construct a categorical distribution over the grid by adopting intervals of width equal to $\alpha$ centered at each of the grid points. The probability of selecting that particular grid point will now be equal to the probability of $\tilde { x }$ falling inside those intervals:
$$\begin{array} { r l } & { p ( \hat { x } = g _ { i } | x , \sigma ) = P ( \tilde { x } \leq ( g _ { i } + \alpha / 2 ) ) - P ( \tilde { x } < ( g _ { i } - \alpha / 2 ) ) ) } \\ & { \qquad = \mathrm { S i g m o i d } ( ( g _ { i } + \alpha / 2 - x ) / \sigma ) - \mathrm { S i g m o i d } ( ( g _ { i } - \alpha / 2 - x ) / \sigma ) , } \end{array}$$
where $\hat { x }$ corresponds to the quantized variable, $P ( \cdot )$ corresponds to the CDF and the step from Equation 2 to Equation 3 is due to the logistic noise assumption. A visualization of the aforementioned process can be seen in Figure 1. For the first and last grid point we will assume that they reside within $( g _ { 0 } - \alpha / 2 , g _ { 0 } + \alpha / 2 ]$ and $\left( g _ { K } - \alpha / 2 , g _ { K } + \alpha / 2 \right]$ respectively. Under this assumption we will have to truncate $p ( \tilde { x } )$ such that it only has support within $\left( g _ { 0 } - \alpha / 2 , g _ { K } + \alpha / 2 \right]$ . Fortunately this is easy to do, as it corresponds to just a simple modification of the CDF:
$$P ( \tilde { x } \le c | \tilde { x } \in ( g _ { 0 } - \alpha / 2 , g _ { K } + \alpha / 2 ] ) = \frac { P ( \tilde { x } \le c ) - P ( \tilde { x } < ( g _ { 0 } - \alpha / 2 ) ) } { P ( \tilde { x } \le ( g _ { K } + \alpha / 2 ) ) - P ( \tilde { x } < ( g _ { 0 } - \alpha / 2 ) ) } .$$
Armed with this categorical distribution over the grid, the quantizer proceeds to assign a specific grid value to $\hat { x }$ by drawing a random sample. This procedure emulates quantization noise, which prevents the model from fitting the data. This noise can be reduced in two ways: by clustering the weights and activations around the points of the grid and by reducing the logistic noise $\sigma$ . As $\sigma 0$ , the CDF converges towards the step function, prohibiting gradient flow. On the other hand, if $\epsilon$ is too high, the optimization procedure is very noisy, prohibiting convergence. For this reason, during optimization we initialize $\sigma$ in a sensible range, such that $L ( x , \sigma )$ covers a significant portion of the grid. Please confer Appendix A for details. We then let $\sigma$ be freely optimized via gradient descent such that the loss is minimized. Both effects reduce the gap between the function that the neural network computes during training time vs. test time. We illustrate this in Figure 2.
The fourth element of the procedure is the relaxation of the non-differentiable categorical distribution sampling. While we can use an unbiased gradient estimator via REINFORCE (Williams, 1992), we opt for a continuous relaxation due to high variances with REINFORCE. This is achieved by replacing the categorical distribution with a concrete distribution (Maddison et al., 2016; Jang et al., 2016). This relaxation procedure corresponds to adopting a “smooth” categorical distribution that can be seen as a “noisy” softmax. Let $\pi _ { i }$ be the categorical probability of sampling grid point $i$ , i.e. $\pi _ { i } = p ( { \hat { x } } = g _ { i } )$ ; the “smoothed” quantized value $\hat { x }$ can be obtained via:
 Figure 2: Best viewed in color. Illustration of the inductive bias obtained via training with the proposed quantizer; means of the logistic distribution over the weights for each layer of the LeNet-5 when trained with 2 bits per weight and activation. Each color corresponds to an assignment to a particular grid point and the vertical dashed lines correspond to the grid points $\beta = 0$ ). We can clearly see that the real valued weights are naturally encouraged through training to cluster into multiple modes, one for each grid point. It should also be mentioned, that for the right and leftmost grid points the probability of selecting them is maximized by moving the corresponding weight furthest right or left respectively. Interestingly, we observe that the network converged to ternary weights for the input and (almost) binary weights for the output layer.
$$u _ { i } \sim \mathrm { G u m b e l } ( 0 , 1 ) , \qquad z _ { i } = \frac { \exp ( ( \log \pi _ { i } + u _ { i } ) / \lambda ) } { \sum _ { j } \exp ( ( \log \pi _ { j } + u _ { j } ) / \lambda ) } , \qquad \hat { x } = \sum _ { i = 1 } ^ { K } z _ { i } g _ { i } ,$$
where $z _ { i }$ is the random sample from the concrete distribution and $\lambda$ is a temperature parameter that controls the degree of approximation, since as $\lambda 0$ the concrete distribution becomes a categorical.
We have thus defined a fully differentiable “soft” quantization procedure that allows for stochastic gradients for both the quantizer parameters $\alpha , \beta , \sigma$ as well as the input signal $x$ (e.g. the weights or the activations of a neural network). We refer to this algorithm as Relaxed Quantization (RQ). We summarize its forward pass as performed during training in Algorithm 1. It is also worthwhile to notice that if there were no noise at the input $x$ then the categorical distribution would have non-zero mass only at a single value, thus prohibiting gradient based optimization for $x$ and $\sigma$ .
One drawback of this approach is that the smoothed quantized values defined in Equation 5 do not have to coincide with grid points, as $z$ is not a one-hot vector. Instead, these values can lie anywhere between the smallest and largest grid point, something which is impossible with e.g. stochastic rounding (Gupta et al., 2015). In order to make sure that only grid-points are sampled, we propose an alternative algorithm RQ ST in which we use the variant of the straight-through (ST) estimator proposed in Jang et al. (2016). Here we sample the actual categorical distribution during the forward pass but assume a sample from the concrete distribution for the backward pass. While this gradient estimator is obviously biased, in practice it works as the “gradients” seem to point towards a valid direction. This effect was also recently studied at Yin et al. (2019). We perform experiments with both variants.
After convergence, we can obtain a “hard” quantization procedure, i.e. select points from the grid, at test time by either reverting to a categorical distribution (instead of the continuous surrogate) or by rounding to the nearest grid point. In this paper we chose the latter as it is more aligned with the low-resource environments in which quantized models will be deployed. Furthermore, with this goal in mind, we employ two quantization grids with their own learnable scalar $\alpha , \sigma$ (and potentially $\beta$ ) parameters for each layer; one for the weights and one for the activations.
# 2.2 SCALABLE QUANTIZATION VIA A LOCAL GRID
Sampling $\hat { x }$ based on drawing $K$ random numbers for the concrete distribution as described in Equation 5 can be very expensive for larger values of $K$ . Firstly, drawing $K$ random numbers for every individual weight and activation in a neural network drastically increases the number of operations required in the forward pass. Secondly, it also requires keeping many more numbers in memory for gradient computations during the backward pass. Compared to a standard neural network or stochastic rounding approaches, the proposed procedure can thus be infeasible for larger models and datasets.
<table><tr><td>Algorithm 1 Quantization during training.</td><td>Algorithm 2 Quantization during testing.</td></tr><tr><td>Require: Input x, grid G, scale of the grid α, scale of noise o, temperature 入, fuzz param. e r =[- α/2,gk +α/2] #interval points c = Sigmoid((r - x)/σ)# evaluate CDF Ti= cK+1]-c[1]+Ke c[i+1]-c[i]+∈ # categorical distr. z ~ Concrete(π,λ) return ∑i zigi</td><td>Require: Input x, scale and offset of the grid α, β, minimum and maximum values go, gK y = α·round((x - β)/α) + β return min(gk,max(go,y)</td></tr></table>
Fortunately, we can make sampling $\hat { x }$ independent of the grid size by assuming zero probability for grid-points that lie far away from the signal $x$ . Specifically, by only considering grid points that are within $\delta$ standard deviations away from $x$ , we truncate $p ( \tilde { x } )$ such that it lies within a “localized” grid around $x$ .
To simplify the computation required for determining the local grid elements, we choose the grid point closest to $x$ , $\lfloor x \rceil$ , as the center of the local grid (Figure 3). Since $\sigma$ is shared between all elements of the weight matrix or activation, the local grid has the same width for every element.
The computation of the probabilities over the localized grid is similar to the truncation happening in Equation 4 and the smoothed quantized value is obtained via a manner similar to Equation 5:
 Figure 3: Local grid construction
$$\begin{array} { c } { P ( \tilde { x } \leq c | \tilde { x } \in ( \lfloor x \rceil - \delta \sigma , \lfloor x \rceil + \delta \sigma ] ) = \displaystyle \frac { P ( \tilde { x } \leq c ) - P ( \tilde { x } < \lfloor x \rceil - \delta \sigma ) } { P ( \tilde { x } \leq \lfloor x \rceil + \delta \sigma ) - P ( \tilde { x } < \lfloor x \rceil - \delta \sigma ) } } \\ { \displaystyle \hat { x } = \displaystyle \sum _ { g _ { i } \in ( \lfloor x \rceil - \delta \sigma , \lfloor x \rceil + \delta \sigma ] } z _ { i } g _ { i } } \end{array}$$
# 2.3 RELATION TO STOCHASTIC ROUNDING
One of the pioneering works in neural network quantization has been the work of Gupta et al. (2015); it introduced stochastic rounding, a technique that is one of the most popular approaches for training neural networks with reduced numerical precision. Instead of rounding to the nearest representable value, the stochastic rounding procedure selects one of the two closest grid points with probability depending on the distance of the high precision input from these grid points. In fact, we can view stochastic rounding as a special case of RQ where $\begin{array} { r } { p ( \tilde { x } ) = U ( x - \frac { \alpha } { 2 } , \tilde { x } + \frac { \bar { \alpha } } { 2 } ) } \end{array}$ . This uniform distribution centered at $x$ of width equal to the grid width $\alpha$ generally has support only for the closest grid point. Discretizing this distribution to a categorical over the quantization grid however assigns probabilities to the two closest grid points as in stochastic rounding, following Equation 2:
$$p ( \hat { x } = \left\lfloor \frac { x } { \alpha } \right\rfloor \alpha \left. x \right. = P ( \tilde { x } \leq ( \left\lfloor \frac { x } { \alpha } \right\rfloor \alpha + \alpha / 2 ) ) - P ( \tilde { x } < ( \left\lfloor \frac { x } { \alpha } \right\rfloor \alpha - \alpha / 2 ) ) = \left\lceil \frac { x } { \alpha } \right\rceil - \frac { x } { \alpha } .$$
Stochastic rounding has proven to be a very powerful quantization scheme, even though it relies on biased gradient estimates for the rounding procedure. On the one hand, RQ provides a way to circumvent this estimator at the cost of optimizing a surrogate objective. On the other hand, RQ ST makes use of the unreasonably effective straight-through estimator as used in Jang et al. (2016)
to avoid optimizing a surrogate objective, at the cost of biased gradients. Compared to stochastic rounding, RQ ST further allows sampling of not only the two closest grid points, but also has support for more distant ones depending on the estimated input noise $\sigma$ . Intuitively, this allows for larger steps in the input space without first having to decrease variance at the traversion between grid sections.
# 3 RELATED WORK
In this work we focus on hardware oriented quantization approaches. As opposed to methods that focus only on weight quantization and network compression for a reduced memory footprint, quantizing all operations within the network aims to additionally provide reduced execution times. Within the body of work that considers quantizing weights and activations fall papers using stochastic rounding (Gupta et al., 2015; Hubara et al., 2016; Gysel et al., 2018; Wu et al., 2018). (Wu et al., 2018) also consider quantized backpropagation, which is out-of-scope for this work.
Furthermore, another line of work considers binarizing (Courbariaux et al., 2015; Zhou et al., 2018) or ternarizing (Li et al., 2016; Zhou et al., 2018) weights and activations (Hubara et al., 2016; Rastegari et al., 2016; Zhou et al., 2016) via the straight-through gradient estimator (Bengio et al., 2013); these allow for fast implementations of convolutions using only bit-shift operations. In a similar vein, the straight through estimator has also been used in Cai et al. (2017); Faraone et al. (2018); Jacob et al. (2017); Zhou et al. (2017); Mishra & Marr (2017) for quantizing neural networks to arbitrary bit-precision. In these approaches, the full precision weights that are updated during training correspond to the means of the logistic distributions that are used in RQ. Furthermore, Jacob et al. (2017) maintains moving averages for the minimum and maximum observed values for activations while parameterises the network’s weights’ grids via their minimum and maximum values directly. This fixed-point grid is therefore learned during training, however without gradient descent; unlike the proposed RQ. Alternatively, instead of discretizing real valued weights, Shayer et al. (2018) directly optimize discrete distributions over them. While providing promising results, this approach does not generalize straightforwardly to activation quantization. A bayesian approach to binarized models was taken in Soudry et al. (2014), which provided encouraging results on small scale experiments with an ensemble of quantized models sampled from the approximate posterior distribution. For small vocabulary sizes (e.g. ternary weights / activations) Yin et al. (2016) proposed explicit formulas to compute the closest (according to the Euclidean distance) quantized value.
Another line of work quantizes networks through regularization. (Louizos et al., 2017a) formulate a variational approach that allows for heuristically determining the required bit-width precision for each weight of the model. Improving upon this work, (Achterhold et al., 2018) proposed a quantizing prior that encourages ternary weights during training. Similarly to RQ, this method also allows for optimizing the scale of the ternary grid. In contrast to RQ, this is only done implicitly via the regularization term. One drawback of these approaches is that the strength of the regularization decays with the amount of training data, thus potentially reducing their effectiveness on large datasets. Alternatively, one could directly regularize towards a set of specific values via the approach described at Yin et al. (2018).
Weights in a neural network are usually not distributed uniformly within a layer. As a result, performing non-uniform quantization is usually more effective. (Baskin et al., 2018) employ a stochastic quantizer by first uniformizing the weight or activation distribution through a non-linear transformation and then injecting uniform noise into this transformed space. (Polino et al., 2018) propose a version of their method in which the quantizer’s code book is learned by gradient descent, resulting in a non-uniformly spaced grid. Another line of works quantizes by clustering and therefore falls into this category; (Han et al., 2015; Ullrich et al., 2017) represent each of the weights by the centroid of its closest cluster. While such non-uniform techniques can be indeed effective, they do not allow for efficient implementations on todays hardware. Nevertheless, there is encouraging recent work (Zhang et al., 2018) on non-uniform grids that can be implemented with bit operations.
Within the liteterature on quantizing neural networks there are many approaches that are orthogonal to our work and could potentially be combined for additional improvements. (Mishra & Marr, 2017; Polino et al., 2018) use knowledge distrillation techniques to good effect, whereas works such as (Mishra et al., 2017) modify the architecture to compensate for lower precision computations. (Zhou et al., 2017; 2018; Baskin et al., 2018) perform quantization in an step-by-step manner going from input layer to output, thus allowing the later layers to more easily adapt to the rounding errors introduced. Polino et al. (2018); Faraone et al. (2018) further employ “bucketing”, where small groups of weights share a grid, instead of one grid per layer. As an example from Polino et al. (2018), a bucket size of 256 weights per grid on Resnet-18 translates to $\sim 9 1 . 4 k$ separate scaling factors / offsets as opposed to 22 in RQ.
# 4 EXPERIMENTS
For the subsequent experiments RQ will correspond to the proposed procedure that has concrete sampling and RQ ST will correspond to the proposed procedure that uses the Gumbel-softmax straight-through estimator (Jang et al., 2016) for the gradient. We did not optimize an offset for the grids in order to be able to represent the number zero exactly, which allows for sparsity and is required for zero-padding. Furthermore we assumed a grid that starts from zero when quantizing the outputs of ReLU. We provide further details on the experimental settings at Appendix A. We will also provide results of our own implementation of stochastic rounding (Gupta et al., 2015) with the dynamic fixed point format (Gysel et al., 2018) $\mathrm { S R + D R } )$ . Here we used the same hyperparameters as for RQ. All experiments were implemented with TensorFlow (Abadi et al., 2015), using the Keras library (Chollet et al., 2015).
# 4.1 LENET-5 ON MNIST AND VGG7 ON CIFAR 10
For the first task we considered the toy LeNet-5 network trained on MNIST with the 32C5 - MP2 - 64C5 - MP2 - 512FC - Softmax architecture and the VGG $2 \mathrm { x } ( 1 2 8 \mathrm { C } 3 ) - \mathrm { M P } 2 - 2 \mathrm { x } ( 2 5 6 \mathrm { C } 3 ) - \mathrm { M P } 2$ - 2x(512C3) - MP2 - 1024FC - Softmax architecture on the CIFAR 10 dataset. Details about the hyperparameter settings can be found in Appendix A.
By observing the results in Table 1, we see that our method can achieve competitive results that improve upon several recent works on neural network quantization. Considering that we achieve lower test error for 8 bit quantization than the high-precision models, we can see how RQ has a regularizing effect. Generally speaking we found that the gradient variance for low bit-widths (i.e. 2-4 bits) in RQ needs to be kept in check through appropriate learning rates.
# 4.2 RESNET-18 AND MOBILENET ON IMAGENET
In order to demonstrate the effectiveness of our proposed approach on large scale tasks we considered the task of quantizing a Resnet-18 (He et al., 2016) as well as a Mobilenet (Howard et al., 2017) trained on the Imagenet (ILSVRC2012) dataset. For the Resnet-18 experiment, we started from a pre-trained full precision model that was trained for 90 epochs. We provide further details about the training procedure in Appendix C. The Mobilenet was initialized with the pretrained model available on the tensorflow github repository1. We quantized the weights of all layers, post ReLU activations and average pooling layer for various bit-widths via fine-tuning for ten epochs. Further details can be found in Appendix C.
Some of the existing quantization works do not quantize the first (and sometimes) last layer. Doing so simplifies the problem but it can, depending on the model and input dimensions, significantly increase the amount of computation required. We therefore make use of the bit operations (BOPs) metric (Baskin et al., 2018), which can be seen as a proxy for the execution speed on appropriate hardware. In BOPs, the impact of not quantizing the first layer in, for example, the Resnet-18 model on Imagenet, becomes apparent: keeping the first layer in full precision requires roughly 1.3 times as many BOPs for one forward pass through the whole network compared to quantizing all weights and activations to 5 bits.
Figure 4 compares a wide range of methods in terms of accuracy and BOPs. We choose to compare only against methods that employ fixed-point quantization on Resnet-18 and Mobilenet, hence do not compare with non-uniform quantization techniques, such as the one described at Baskin et al. (2018). In addition to our own implementation of (Gupta et al., 2015) with the dynamic fixed point format (Gysel et al., 2018), we also report results of “rounding”. This corresponds to simply rounding the pre-trained high-precision model followed by re-estimation of the batchnorm statistics. The grid in this case is defined as the initial grid used for fine-tuning with RQ. For batchnorm re-estimation and grid initialization, please confer Appendix A.
Table 1: Test error $( \% )$ on MNIST and CIFAR 10 using LeNet5-Caffe and VGG-7 respectively. Two and four bit for VGG with $\mathrm { S R + D R }$ resulted in a big gap between training and validation accuracy, so we omit those results.
<table><tr><td>Method</td><td># Bits weights/act.</td><td>MNIST</td><td>CIFAR 10</td></tr><tr><td>Original</td><td>32/32</td><td>0.64</td><td>6.95</td></tr><tr><td rowspan="3">SR+DR (Gupta et al.,2015; Gysel et al., 2018)</td><td>8/8</td><td>0.58</td><td>7.06</td></tr><tr><td>4/4</td><td>0.66</td><td>1</td></tr><tr><td>2/2</td><td>1.03</td><td>1</td></tr><tr><td>Deep Comp. (Han et al., 2015)</td><td>(5-8)/32</td><td>0.74</td><td>-</td></tr><tr><td>TWN (Li et al., 2016)</td><td>2/32</td><td>0.65a</td><td>7.44</td></tr><tr><td>BWN (Rastegari et al., 2016)</td><td>1/32</td><td>-</td><td>9.88</td></tr><tr><td>XNOR-net (Rastegari et al., 2016) SWS (Ullrich et al., 2017)</td><td>1/1</td><td>1</td><td>10.17</td></tr><tr><td>Bayesian Comp. (Louizos et al., 2017a)</td><td>3/32</td><td>0.97</td><td>-</td></tr><tr><td>VNQ(Achterhold et al.,2018)</td><td>(7-18)/32</td><td>1.00</td><td>-</td></tr><tr><td>WAGE (Wu et al., 2018)</td><td>2/32</td><td>0.73</td><td>1</td></tr><tr><td>LR Net (Shayer et al., 2018)b</td><td>2/8</td><td>0.40</td><td>6.78</td></tr><tr><td rowspan="2"></td><td>1/32 2/32</td><td>0.53a 0.50a</td><td>6.82 6.74</td></tr><tr><td></td><td></td><td></td></tr><tr><td rowspan="3">RQ (ours)</td><td>8/8</td><td>0.55</td><td>6.70</td></tr><tr><td>4/4 2/2</td><td>0.58</td><td>8.43</td></tr><tr><td></td><td>0.76</td><td>11.75</td></tr><tr><td rowspan="3">RQ ST (ours)</td><td>8/8</td><td>0.56</td><td>6.72</td></tr><tr><td>4/4</td><td>0.61</td><td>7.96</td></tr><tr><td>2/2</td><td>0.63</td><td>9.08</td></tr></table>
aWith batch normalization after convolution bLast layer in full precision
In Figure 4a we observe that on ResNet-18 the RQ variants form the “Pareto frontier” in the trade-off between accuracy and efficiency, along with SYQ, Apprentice and Jacob et al. (2017). SYQ, however, employs “bucketing” and Apprentice uses distillation, both of which can be combined with RQ and improve performance. Jacob et al. (2017) does better than RQ with 8 bits, however RQ improved w.r.t. to its pretrained model, whereas Jacob et al. (2017) decreased slightly. For experimental details with Jacob et al. (2017), please confer Appendix C.1. $\mathrm { S R + D R }$ underperforms in this setting and is worse than simple rounding for 5 to 8 bits.
For Mobilenet, 4b shows that RQ is competitive to existing approaches. Simple rounding resulted in almost random chance for all of the bit configurations. $\mathrm { S R + D R }$ shows its strength for the 8 bit scenario, while in the lower bit regime, RQ outperforms competitive approaches.
# 5 DISCUSSION
We have introduced Relaxed Quantization (RQ), a powerful and versatile algorithm for learning low-bit neural networks using a uniform quantization scheme. As such, the models trained by this method can be easily transferred and executed on low-bit fixed point chipsets. We have extensively evaluated RQ on various image classification benchmarks and have shown that it allows for the better trade-offs between accuracy and bit operations per second.
Future hardware might enable us to cheaply do non-uniform quantization, for which this method can be easily extended. (Lai et al., 2017; Ortiz et al., 2018) for example, show the benefits of low-bit floating point weights that can be efficiently implemented in hardware. The floating point quantization grid can be easily learned with RQ by redefining $\hat { \mathcal G }$ . General non-uniform quantization, as described for example in (Baskin et al., 2018), is a natural extension to RQ, whose exploration we leave to future work. For example, we could experiment with a base grid that is defined as in Zhang et al. (2018). Currently, the bit-width of every quantizer is determined beforehand, but in future work we will explore learning the required bit precision within this framework. In our experiments, batch normalization was implemented as a sequence of convolution, batch normalization and quantization. On a low-precision chip, however, batch normalization would be ”folded” (Jacob et al., 2017) into the kernel and bias of the convolution, the result of which is then rounded to low precision. In order to accurately reflect this folding at test time, future work on the proposed algorithm will emulate folded batchnorm at training time and learn the corresponding quantization grid of the modified kernel and bias. For fast model evaluation on low-precision hardware, quantization goes hand-in-hand with network pruning. The proposed method is orthogonal to pruning methods such as, for example, $L _ { 0 }$ regularization (Louizos et al., 2017b), which allows for group sparsity and pruning of hidden units.
 Figure 4: Best viewed in color. Comparison of various methods on Resnet-18 and Mobilenet according to top-1 error (on the y-axis) and bit operations (on the $\mathbf { X }$ -axis) computed according to the formula described in Baskin et al. (2018). Each dashed line corresponds to employing a specific bit configuration for every layer’s weights and activations. Values for top-1 and top-5 errors are given in Table 2 in the Appendix. We compare against multiple works that employ fixed-point quantization: $\mathrm { S R + D R }$ (Gupta et al., 2015; Gysel et al., 2018), LR Net (Shayer et al., 2018), Jacob et al. (2017), TWN (Li et al., 2016), INQ (Zhou et al., 2017), BWN (Rastegari et al., 2016), XNORnet (Rastegari et al., 2016), DoReFa (Zhou et al., 2016), HWGQ (Cai et al., 2017), ELQ Zhou et al. (2018), SYQ (Faraone et al., 2018), Apprentice (Mishra & Marr, 2017), QSM (Sheng et al., 2018) and rounding.
# REFERENCES
Mart´ın Abadi, Ashish Agarwal, Paul Barham, Eugene Brevdo, Zhifeng Chen, Craig Citro, Greg S. Corrado, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Ian Goodfellow, Andrew Harp, Geoffrey Irving, Michael Isard, Yangqing Jia, Rafal Jozefowicz, Lukasz Kaiser, Manjunath Kudlur, Josh Levenberg, Dandelion Mane, Rajat Monga, Sherry Moore, Derek Murray, Chris Olah, ´ Mike Schuster, Jonathon Shlens, Benoit Steiner, Ilya Sutskever, Kunal Talwar, Paul Tucker, Vincent Vanhoucke, Vijay Vasudevan, Fernanda Viegas, Oriol Vinyals, Pete Warden, Martin Wattenberg, ´ Martin Wicke, Yuan Yu, and Xiaoqiang Zheng. TensorFlow: Large-scale machine learning on heterogeneous systems, 2015. URL https://www.tensorflow.org/. Software available from tensorflow.org.
Jan Achterhold, Jan Mathias Koehler, Anke Schmeink, and Tim Genewein. Variational network quantization. In International Conference on Learning Representations, 2018. URL https: //openreview.net/forum?id $\underline { { \underline { { \mathbf { \Pi } } } } } =$ ry-TW-WAb.
Chaim Baskin, Eli Schwartz, Evgenii Zheltonozhskii, Natan Liss, Raja Giryes, Alex M Bronstein, and Avi Mendelson. Uniq: Uniform noise injection for the quantization of neural networks. arXiv
preprint arXiv:1804.10969, 2018.
Yoshua Bengio, Nicholas Leonard, and Aaron Courville. Estimating or propagating gradients through ´ stochastic neurons for conditional computation. arXiv preprint arXiv:1308.3432, 2013.
Zhaowei Cai, Xiaodong He, Jian Sun, and Nuno Vasconcelos. Deep learning with low precision by half-wave gaussian quantization. arXiv preprint arXiv:1702.00953, 2017.
Franc¸ois Chollet et al. Keras. https://keras.io, 2015.
Matthieu Courbariaux, Yoshua Bengio, and Jean-Pierre David. Binaryconnect: Training deep neural networks with binary weights during propagations. In Advances in neural information processing systems, pp. 3123–3131, 2015.
Julian Faraone, Nicholas Fraser, Michaela Blott, and Philip HW Leong. Syq: Learning symmetric quantization for efficient deep neural networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 4300–4309, 2018.
Suyog Gupta, Ankur Agrawal, Kailash Gopalakrishnan, and Pritish Narayanan. Deep learning with limited numerical precision. In International Conference on Machine Learning, pp. 1737–1746, 2015.
Philipp Gysel, Jon Pimentel, Mohammad Motamedi, and Soheil Ghiasi. Ristretto: A framework for empirical study of resource-efficient inference in convolutional neural networks. IEEE Transactions on Neural Networks and Learning Systems, 2018. doi: 10.1109/TNNLS.2018.2808319.
Song Han, Huizi Mao, and William J Dally. Deep compression: Compressing deep neural networks with pruning, trained quantization and huffman coding. arXiv preprint arXiv:1510.00149, 2015.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 770–778, 2016.
Andrew G Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, and Hartwig Adam. Mobilenets: Efficient convolutional neural networks for mobile vision applications. arXiv preprint arXiv:1704.04861, 2017.
Itay Hubara, Matthieu Courbariaux, Daniel Soudry, Ran El-Yaniv, and Yoshua Bengio. Quantized neural networks: Training neural networks with low precision weights and activations. arXiv preprint arXiv:1609.07061, 2016.
Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, Matthew Tang, Andrew Howard, Hartwig Adam, and Dmitry Kalenichenko. Quantization and training of neural networks for efficient integer-arithmetic-only inference. arXiv preprint arXiv:1712.05877, 2017.
Eric Jang, Shixiang Gu, and Ben Poole. Categorical reparameterization with gumbel-softmax. arXiv preprint arXiv:1611.01144, 2016.
Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014.
Liangzhen Lai, Naveen Suda, and Vikas Chandra. Deep convolutional neural network inference with floating-point weights and fixed-point activations. arXiv preprint arXiv:1703.03073, 2017.
Yann LeCun, John S Denker, and Sara A Solla. Optimal brain damage. In Advances in neural information processing systems 2, NIPS 1989, volume 2, pp. 598–605. Morgan-Kaufmann Publishers, 1990.
Fengfu Li, Bo Zhang, and Bin Liu. Ternary weight networks. arXiv preprint arXiv:1605.04711, 2016.
Christos Louizos, Karen Ullrich, and Max Welling. Bayesian compression for deep learning. arXiv preprint arXiv:1705.08665, 2017a.
Christos Louizos, Max Welling, and Diederik P Kingma. Learning sparse neural networks through $l _ { 0 }$ regularization. arXiv preprint arXiv:1712.01312, 2017b.
Chris J Maddison, Andriy Mnih, and Yee Whye Teh. The concrete distribution: A continuous relaxation of discrete random variables. arXiv preprint arXiv:1611.00712, 2016.
Asit Mishra and Debbie Marr. Apprentice: Using knowledge distillation techniques to improve low-precision network accuracy. arXiv preprint arXiv:1711.05852, 2017.
Asit Mishra, Eriko Nurvitadhi, Jeffrey J Cook, and Debbie Marr. Wrpn: wide reduced-precision networks. arXiv preprint arXiv:1709.01134, 2017.
Marc Ortiz, Adrian Cristal, Eduard Ayguad ´ e, and Marc Casas. Low-precision floating-point schemes ´ for neural network training. arXiv preprint arXiv:1804.05267, 2018.
Jorn WT Peters and Max Welling. Probabilistic binary neural networks. arXiv preprint arXiv:1809.03368, 2018.
Antonio Polino, Razvan Pascanu, and Dan Alistarh. Model compression via distillation and quantization. arXiv preprint arXiv:1802.05668, 2018.
Mohammad Rastegari, Vicente Ordonez, Joseph Redmon, and Ali Farhadi. Xnor-net: Imagenet classification using binary convolutional neural networks. In European Conference on Computer Vision, pp. 525–542. Springer, 2016.
Oran Shayer, Dan Levi, and Ethan Fetaya. Learning discrete weights using the local reparameterization trick. In International Conference on Learning Representations, 2018. URL https://openreview.net/forum?id $\underline { { \underline { { \mathbf { \Pi } } } } } =$ BySRH6CpW.
Tao Sheng, Chen Feng, Shaojie Zhuo, Xiaopeng Zhang, Liang Shen, and Mickey Aleksic. A quantization-friendly separable convolution for mobilenets. 2018.
Daniel Soudry, Itay Hubara, and Ron Meir. Expectation backpropagation: Parameter-free training of multilayer neural networks with continuous or discrete weights. In Advances in Neural Information Processing Systems, pp. 963–971, 2014.
Joe Staines and David Barber. Variational optimization. arXiv preprint arXiv:1212.4507, 2012.
Karen Ullrich, Edward Meeds, and Max Welling. Soft weight-sharing for neural network compression. ICLR, 2017.
Ronald J Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine learning, 8(3-4):229–256, 1992.
Shuang Wu, Guoqi Li, Feng Chen, and Luping Shi. Training and inference with integers in deep neural networks. In International Conference on Learning Representations, 2018. URL https: //openreview.net/forum?id $\underline { { \underline { { \mathbf { \Pi } } } } } =$ HJGXzmspb.
Penghang Yin, Shuai Zhang, Yingyong Qi, and Jack Xin. Quantization and training of low bit-width convolutional neural networks for object detection. arXiv preprint arXiv:1612.06052, 2016.
Penghang Yin, Shuai Zhang, Jiancheng Lyu, Stanley Osher, Yingyong Qi, and Jack Xin. Binaryrelax: A relaxation approach for training deep neural networks with quantized weights. SIAM Journal on Imaging Sciences, 11(4):2205–2223, 2018.
Penghang Yin, Shuai Zhang, Jiancheng Lyu, Stanley Osher, Yingyong Qi, and Jack Xin. Blended coarse gradient descent for full quantization of deep neural networks. Research in the Mathematical Sciences, 6(1):14, 2019.
Dongqing Zhang, Jiaolong Yang, Dongqiangzi Ye, and Gang Hua. Lq-nets: Learned quantization for highly accurate and compact deep neural networks. In European Conference on Computer Vision (ECCV), 2018.
Aojun Zhou, Anbang Yao, Yiwen Guo, Lin Xu, and Yurong Chen. Incremental network quantization: Towards lossless cnns with low-precision weights. arXiv preprint arXiv:1702.03044, 2017.
Aojun Zhou, Anbang Yao, Kuan Wang, and Yurong Chen. Explicit loss-error-aware quantization for low-bit deep neural networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 9426–9435, 2018.
Shuchang Zhou, Yuxin Wu, Zekun Ni, Xinyu Zhou, He Wen, and Yuheng Zou. Dorefa-net: Training low bitwidth convolutional neural networks with low bitwidth gradients. arXiv preprint arXiv:1606.06160, 2016.
Chenzhuo Zhu, Song Han, Huizi Mao, and William J Dally. Trained ternary quantization. arXiv preprint arXiv:1612.01064, 2016.
# A EXPERIMENTAL DETAILS
The grid width $\alpha$ of each grid was initialized according to the bit-width $b$ and the maximum and minimum values of the input $x$ to the quantizer2. Since the inputs $\tilde { x }$ in both cases for our approach are stochastic it makes sense to assume a width for the grid that is slightly larger than the standard width $t = ( \operatorname* { m a x } ( x ) - \operatorname* { m i n } ( x ) ) / 2 ^ { b }$ ; for the activations, whenever $b > 4$ , we initialize $\alpha = t + 3 t / 2 ^ { b }$ , for $4 \geq b > 2$ we used $\alpha = { { t + 3 t } \ o { / { 2 ^ { b + 1 } } } }$ and finally for $b = 2$ we used $\alpha = t$ . Since with ReLU activations the magnitude can become quite large (thus leading to increased quantization noise for smaller bit widths), this scheme keeps the noise injected to the network in check. For the weights we always used an initial $\alpha = t + 3 t / \dot { 2 } ^ { b }$ . The standard deviation of the logistic noise $\sigma$ was initialized to be three times smaller than the width $\alpha$ , i.e. $\sigma = \alpha / 3$ . Under this specification, most of the probability mass of the logistic distribution is initially (roughly) in the bins containing the closest grid point and its’ two neighbors.
The moving averages of layer statistics that are aggregated during the training phase for the batch normalization do not necessarily reflect the statistics of the quantized model accurately. Even though RQ aims to minimize the gap between training and testing phase, we found that the aggregated statistics in combination with the learned scale and shift parameters of batch normalization lead to decreased test performance. In order to avoid this drop in accuracy, we apply the insights from (Peters & Welling, 2018) and recompute the statistics of the quantized model before reporting the final test error rate. The final models were determined through early stopping using the validation loss computed with minibatch statistics, in case the model uses batch normalization.
For the MNIST experiment we rescaled the input to the [-1, 1] range, employed no regularization and the network was trained with Adam (Kingma & Ba, 2014) and a batch size of 128. We used a local grid whenever the bit width was larger than 2 for both, weights and biases (shared grid parameters), as well as for the ouputs of the ReLU, with $\delta = 3$ . For the 8 and 4 bit networks we used a temperature $\lambda$ of 2 whereas for the 2 bit models we used a temperature of 1 for RQ. We trained the 8 and 4 bit networks for 100 epochs using a learning rate of 1e-3 and the 2 bit networks for 200 epochs with a learning rate of 5e-4. In all of the cases the learning rate was annealed to zero during the last 50 epochs.
For the CIFAR 10 experiment, the hyperparameters were chosen identically to the LeNet-5 experiments except a few differences. We chose a learning rate ot 1e-4 instead of 1e-3 for 8 and 4 bit networks and trained for 300 epochs with a batch size of 100. We also included a weight decay term of 1e-4 for the 8 bit networks. For the 2 bit model we started with a learning rate of 1e-3. The VGG model contains a batch normalization layer after every convolutional layer, but preceeded by max pooling, if present.
# B CONVERGENCE SPEED OF VGG ON CIFAR 10
Training a neural network with RQ imposes an additional sampling burden for every weight and activation in the network. Here, we investigate whether the extra “noise” that is introduced hampers the convergence speed of the network when we train from a random initialization. We recorded the learning curves for a $2 / 2$ bit RQ-VGG network on CIFAR 10 (as this quantization level exhibits the largest amount of noise) and compare it to the full precision baseline. The results can be seen in
Figure 5. As we can observe, the 2/2 bit network has qualitatively similar trends to the full precision baseline. Therefore we can conclude that the noise is not detrimental for the task at hand, at least for this particular model. In terms of wall-clock time, training the RQ model with a full (4 elements) grid took approximately 15 times as long as the high-precision baseline with an implementation in Tensorflow v1.11.0 and running on a single Titan-X Nvidia GPU.
 Figure 5: Learning curves for the VGG on CIFAR 10.
# C IMAGENET DETAILS
Each channel of the input images was preprocessed by subtracting the mean and dividing by the standard deviation of that channel across the training set. We then resized the images such that the shorter side is set to 256 and then applied random $2 2 4 \mathrm { x } 2 2 4$ crops and random horizontal flips for data augmentation. For evaluation we consider the center $2 2 4 \mathbf { x } 2 2 4$ crop of the images.
We trained the base Resnet-18 model with stochastic gradient descent, a batch size of 128, nesterov momentum of 0.9 and a learning rate of 0.1 which was multiplied by 0.1 at the 30th and 60th epoch. We also applied weight decay with a strength of 1e-4. For the quantized model fine-tuning phase, we used Adam with a learning rate of $5 e ^ { - \tilde { 6 } }$ , a batch size of 24 and a momentum of 0.99. We used a temperature of 2 for both RQ variants. Following the strategy in (Jacob et al., 2017), we did not quantize the biases.
Table 2 contains the error rates for Resnet-18 and Mobilenet on which Figure 1 is based on. Algorithm and architecture specific changes are mentioned explicitly through footnotes.
# C.1 JACOB ET AL. (2017) FOR RESNET18
We used the code provided at https://github.com/tensorflow/models/tree/ master/official/resnet and modified the construction of the training and evaluation graph by inserting quantization operations provided by the tensorflow.contrib.quantize package. In a first step, the unmodified code was used to train a high-precision Resnet18 model using the hyper-parameter settings for the learning rate scheduling that are provided in the github repository. More specifically, the model was trained for 90 epochs with a batch size of 128. The learning rate scheduling involved a ”warm up” period in which the learning rate was annealed from zero to 0.64 over the first $5 0 k$ steps, after which it was divided by 10 after epochs 30, 60 and 80 respectively. Gradients were modified using a momentum of 0.9. Final test performance under this procedure is $2 9 . 5 3 \%$ top-1 error and $1 0 . 4 4 \%$ top-5 error. From the high-precision model checkpoint, the final quantized model was then fine-tuned for 10 epochs using a constant learning rate of $1 e ^ { - 4 }$ and momentum of 0.9. We did not freeze the moving averages of the batch normalization layers. Finally, we found that re-estimating the batchnorm statistics was harmful for this algorithm. We hypothesise that this is due to the usage of folded batch normalization, which incorporates the statistics into the construction of the grid at training time.
Table 2: Top-1 and top-5 error $( \% )$ with Resnet18 and Mobilenet (full resolution and multiplier of one) on Imagenet
<table><tr><td colspan="2"></td><td colspan="2">Resnet18</td><td colspan="2">Mobilenet</td></tr><tr><td>Method</td><td># Bits weights/act.</td><td>Top-1</td><td>Top-5</td><td>Top-1</td><td>Top-5</td></tr><tr><td>Original</td><td>32/32</td><td>30.46</td><td>10.81</td><td>29.39</td><td>10.53</td></tr><tr><td rowspan="2">SR+DR (Gupta et al., 2015; Gysel et al., 2018)</td><td>8/8</td><td>31.83</td><td>11.48</td><td>28.70</td><td>10.04</td></tr><tr><td>6/6</td><td>40.75 45.48</td><td>16.90 20.16</td><td>33.34 40.61</td><td>12.83</td></tr><tr><td rowspan="2">Rounding</td><td>5/5</td><td></td><td></td><td></td><td>17.65</td></tr><tr><td>8/8</td><td>30.22</td><td>10.60</td><td>1</td><td>1</td></tr><tr><td rowspan="3">(Jacob et al., 2017)a</td><td>6/6</td><td>31.61 36.97</td><td>11.32 14.95</td><td></td><td></td></tr><tr><td>5/5</td><td>78.79</td><td>57.10</td><td>= 1</td><td></td></tr><tr><td>4/4</td><td>29.62</td><td>10.45</td><td></td><td>1</td></tr><tr><td rowspan="3"></td><td>8/8</td><td>32.69</td><td>12.46</td><td>30.30</td><td>10.50</td></tr><tr><td>6/6 5/5</td><td>35.36</td><td>13.33</td><td>1 =</td><td>1</td></tr><tr><td>1/32b</td><td>40.10</td><td>17.70</td><td></td><td></td></tr><tr><td rowspan="2">LR Net (Shayer et al., 2018)</td><td>2/32℃</td><td>36.50</td><td>15.20</td><td></td><td></td></tr><tr><td>8/8</td><td>1</td><td>1</td><td>31.97</td><td></td></tr><tr><td>QSM (Sheng et al., 2018)a d</td><td></td><td>38.20</td><td>15.80</td><td></td><td></td></tr><tr><td>TWN (Li et al., 2016) INQ (Zhou et al., 2017)</td><td>2/32 5/32</td><td>31.02</td><td>10.90</td><td></td><td></td></tr><tr><td>BWN (Rastegari et al., 2016)</td><td>1/32</td><td>39.20</td><td>17.00</td><td></td><td></td></tr><tr><td>XNOR-net (Rastegari et al., 2016)</td><td>1/1</td><td>48.80</td><td>26.80</td><td></td><td></td></tr><tr><td>HWGQ (Cai et al., 2017)b</td><td>1/2</td><td>40.4</td><td>17.8</td><td></td><td></td></tr><tr><td>DoReFa (Zhou et al., 2016)be</td><td>1/4</td><td>40.8</td><td>18.5</td><td></td><td></td></tr><tr><td>ELQ (Zhou et al., 2018)</td><td>1/32</td><td>35.28</td><td>13.96</td><td></td><td></td></tr><tr><td></td><td>2/32</td><td>32.48</td><td>11.95</td><td></td><td></td></tr><tr><td rowspan="2">SYQ (Faraone et al., 2018)f</td><td>1/8</td><td>37.1</td><td>15.4</td><td></td><td></td></tr><tr><td>2/8</td><td>32.3</td><td>12.2</td><td></td><td></td></tr><tr><td rowspan="2">Apprentice (Mishra & Marr,2017)b</td><td></td><td>32</td><td></td><td></td><td></td></tr><tr><td>2/8 4/8</td><td>29.6</td><td>一</td><td></td><td></td></tr><tr><td rowspan="3">RQ (ours)</td><td>8/8</td><td></td><td></td><td></td><td></td></tr><tr><td>6/6</td><td>30.03 31.35</td><td>10.56 11.22</td><td>29.57 31.98</td><td>10.58 12.00</td></tr><tr><td>5/5</td><td>34.90</td><td>13.43</td><td>38.62</td><td>16.27</td></tr><tr><td rowspan="4">RQ ST (ours)</td><td>4/4</td><td>38.48</td><td>16.01</td><td>1</td><td>1</td></tr><tr><td>8/8</td><td>30.37</td><td>10.67</td><td>29.94</td><td>10.48</td></tr><tr><td>6/6</td><td>31.85</td><td>11.62</td><td>32.38</td><td>12.22</td></tr><tr><td>5/5</td><td>36.65</td><td>14.54</td><td>43.15</td><td>19.65</td></tr><tr><td></td><td>4/4</td><td>37.54</td><td>15.22</td><td>1</td><td>1</td></tr></table>
aIncludes folded batch normalization bFirst and last layer not quantized cFirst layer not quantized dModified architecture eResults taken from https://github.com/tensorpack/tensorpack/blob/master/ examples/DoReFa-Net/resnet-dorefa.py fWeights of first and last layer not quantized
# C.2 JACOB ET AL. (2017) FOR MOBILENET
The $8 / 8$ bit results for quantizing Mobilenet provided in table 2 are read off from Figure 4.1 in Jacob et al. (2017). The pre-trained models published at https://github.com/tensorflow/ models/blob/master/research/slim/nets/mobilenet_v1.md originally reflected that number up until commit 4415c2613b0c74032a7c631769ef9fa7f5477d88, but have since been updated to improved error rates of 29.9 and 11.1 respectively. Unfortunately, there are several conflicting sources for quantized Mobilenet results and pretrainedmodels within the tensorflow github repository. https://github.com/tensorflow/ tensorflow/blob/master/tensorflow/contrib/lite/g3doc/models.md# image-classification-quantized-models, for example, reports error rates of 30.0 and 11.0, whereas at https://github.com/tensorflow/tensorflow/tree/master/ tensorflow/contrib/quantize the reported top-1 error rate is 30.3.
We attempted to use the provided training scripts in the https://github.com/tensorflow/ models/blob/master/research/slim repository to train lower-bit mobilenet variants, but did not succeed in doing so. We experimented with learning rates in the range of $[ 5 e ^ { - 6 } , 5 e ^ { - 5 } , 1 e ^ { - 4 } ]$ for $5 / 5 , \ 6 / 6$ and $8 / 8$ bit-width variants, but could not achieve significant accuracy improvements within the first 10 epochs of fine-tuning of the high-precision model published at https://github.com/tensorflow/models/blob/master/research/ slim/nets/mobilenet_v1.md. After 10 epochs, the $8 / 8$ version achieved 31.39 top-1 error with a learning rate of $1 e ^ { - 4 }$ and as such is worse than the published results. We therefore chose to only include the published numbers for the $8 / 8$ bit model and leave addition hyperparameter tuning to future work.md/dev/89ia77nZ8u/89ia77nZ8u.mdAdded
md/dev/Loek7hfb46P/Loek7hfb46P.mdAdded
md/dev/T8wHz4rnuGL/T8wHz4rnuGL.mdAdded
md/dev/Uuf2q9TfXGA/Uuf2q9TfXGA.mdAdded+355
md/dev/VYYf6S67pQc/VYYf6S67pQc.mdAdded+335
md/dev/VpYBxaPLaj-/VpYBxaPLaj-.mdAdded+537
md/dev/jQgsZDspz5h/jQgsZDspz5h.mdAdded+378
md/train/-xEk43f_EO6/-xEk43f_EO6.mdAdded+277
md/train/2-0wS9-cSL/2-0wS9-cSL.mdAdded+424
md/train/3Aoft6NWFej/3Aoft6NWFej.mdAdded+274
md/train/B1M8JF9xx/B1M8JF9xx.mdAdded+324
md/train/BJfOXnActQ/BJfOXnActQ.mdAdded+284
md/train/CO87OIEOGU8/CO87OIEOGU8.mdAdded+229
md/train/ErivP29kYnx/ErivP29kYnx.mdAdded+258
md/train/H1eSS3CcKX/H1eSS3CcKX.mdAdded+704
md/train/H1ecDoR5Y7/H1ecDoR5Y7.mdAdded+515
md/train/HJWLfGWRb/HJWLfGWRb.mdAdded+264
md/train/HkSZyinVG/HkSZyinVG.mdAdded+250
md/train/HkeuD34KPH/HkeuD34KPH.mdAdded+303
md/train/HkxjYoCqKX/HkxjYoCqKX.mdAdded+306
md/train/HyAddcLge/HyAddcLge.mdAdded
md/train/HylsTT4FvB/HylsTT4FvB.mdAdded
md/train/HyxfGCVYDr/HyxfGCVYDr.mdAdded
md/train/Hyxu6oAqYX/Hyxu6oAqYX.mdAdded
md/train/LKUfuWxajHc/LKUfuWxajHc.mdAdded
md/train/LKoMTwTuQnC/LKoMTwTuQnC.mdAdded
md/train/MBH29cOeohr/MBH29cOeohr.mdAdded
md/train/S1Bb3D5gg/S1Bb3D5gg.mdAdded
md/train/S1sRrN-CW/S1sRrN-CW.mdAdded
md/train/SJxSOJStPr/SJxSOJStPr.mdAdded
md/train/SklD9yrFPS/SklD9yrFPS.mdAdded
md/train/SyProzZAW/SyProzZAW.mdAdded
md/train/SyevYxHtDB/SyevYxHtDB.mdAdded
md/train/T6AxtOaWydQ/T6AxtOaWydQ.mdAdded
md/train/Xb8xvrtB8Ce/Xb8xvrtB8Ce.mdAdded
md/train/dx11_7vm5_r/dx11_7vm5_r.mdAdded
md/train/fSTD6NFIW_b/fSTD6NFIW_b.mdAdded
md/train/hl3v8io3ZYt/hl3v8io3ZYt.mdAdded
md/train/hw2VfWAr6t6/hw2VfWAr6t6.mdAdded
md/train/ioyq7NsR1KJ/ioyq7NsR1KJ.mdAdded
md/train/jnRqf0CzBK/jnRqf0CzBK.mdAdded
md/train/lE1AB4stmX/lE1AB4stmX.mdAdded
md/train/luGQiBeRMxd/luGQiBeRMxd.mdAdded
md/train/r1CE9GWR-/r1CE9GWR-.mdAdded
md/train/r1fYuytex/r1fYuytex.mdAdded
md/train/rkRwGg-0Z/rkRwGg-0Z.mdAdded
md/train/rkeMHjR9Ym/rkeMHjR9Ym.mdAdded
md/train/rkmtTJZCb/rkmtTJZCb.mdAdded
md/train/rylnK6VtDH/rylnK6VtDH.mdAdded
md/train/tHgJoMfy6nI/tHgJoMfy6nI.mdAdded