Y OUR CLASSIFIER IS SECRETLY AN ENERGY BASED MODEL AND YOU SHOULD TREAT IT LIKE ONE
Anonymous authors
Paper under double-blind review
A BSTRACT
We propose to reinterpret a standard discriminative classiﬁer of p ( y | x ) as an energy based model for the joint distribution p ( x , y ) .
In this setting, the standard class probabilities can be easily computed as well as unnormalized values of p ( x ) and p ( x | y ) .
Within this framework, standard discriminative architectures may be used and the model can also be trained on unlabeled data.
We demonstrate that energy based training of the joint distribution improves calibration, robustness, and out-of-distribution detection while also enabling our models to generate samples rivaling the quality of recent GAN approaches.
We improve upon recently proposed techniques for scaling up the training of energy based models and present an approach which adds little overhead compared to standard classiﬁcation training.
Our approach is the ﬁrst to achieve performance rivaling the state-of-the-art in both generative and discriminative learning within one hybrid model.
I NTRODUCTION
For decades, research on generative models has been motivated by the promise that generative models can beneﬁt downstream problems such as semi-supervised learning, imputation of missing data, and calibration of uncertainty ( e.g., Chapelle et al.
; Dempster et al.
Yet, most recent research on deep generative models ignores these problems, and instead focuses on qualitative sample quality and log-likelihood on heldout validation sets.
Currently, there is a large performance gap between the strongest generative modeling approach to downstream tasks of interest and hand-tailored solutions for each speciﬁc problem.
One potential explanation is that most downstream tasks are discriminative in nature and stateof-the-art generative models have diverged quite heavily from state-of-the-art discriminative architectures.
Thus, even when trained solely as classiﬁers, the performance of generative models is far below the performance of the best discriminative models.
Hence, the potential beneﬁt from the generative component of the model is far outweighed by the decrease in discriminative performance.
Recent work (Behrmann et al., 2018; Chen et al., 2019) attempts to improve the discriminative performance of generative models by leveraging invertible architectures, but these methods still underperform their purely discriminative counterparts jointly trained as generative models.
This paper advocates the use of energy based models (EBMs) to help realize the potential of generative models on downstream discriminative problems.
While EBMs are currently challenging to work with, they ﬁt more naturally within a discriminative framework than other generative models and facilitate the use of modern classiﬁer architectures.
Figure 1 illustrates an overview of the architecture, where the logits of a classiﬁer are re-interpreted to deﬁne the joint density of data points and labels and the density of data points alone.
The contributions of this paper can be summarized as: 1) We present a novel and intuitive framework for joint modeling of labels and data.
Our models considerably outperform previous state-of-theart hybrid models at both generative and discriminative modeling.
We show that the incorporation of generative modeling gives our models improved calibration, out-of-distribution detection, and adversarial robustness, performing on par with or better than hand-tailored methods for each task.
E NERGY B ASED M ODELS
Energy based models (LeCun et al., 2006) hinge on the observation that any probability density p ( x ) for x ∈ R D can be expressed as
[Equation]
where E θ ( x ) : R D → R , known as the energy function , maps each point to a scalar, and Z ( θ )
= (cid:82) x exp( − E θ ( x )) is the normalizing constant (with respect to x ) also known as the partition function.
Thus, one can parameterize an EBM using any function that takes x as the input and returns a scalar.
For most choices of E θ , one cannot compute or even reliably estimate Z ( θ ) , which means estimating the normalized densities is intractable and standard maximum likelihood estimation of the parameters, θ , is not straightforward.
Thus, we must rely on other methods to train EBMs.
We note that the derivative of the log-likelihood for a single example x with respect to θ can be expressed as
[Equation]
where the expectation is over the model distribution.
Unfortunately, we cannot easily draw samples from p θ ( x ) , so we must resort to MCMC to use this gradient estimator.
This approach was used to train some of the earliest EBMs.
For example, Restricted Boltzmann Machines (Hinton, 2002) were trained using a block Gibbs sampler to approximate the expectation in Eq.
Despite a long period of little development, there has been recent work using this method to train large-scale EBMs on high-dimensional data, parameterized by deep neural networks (Nijkamp et al., 2019b;a; Du & Mordatch, 2019; Xie et al., 2016).
These recent successes have approximated the expectation in Eq.
(2) using a sampler based on Stochastic Gradient Langevin Dynamics (SGLD)
(Welling & Teh, 2011) which draws samples following
[Equation]
where p 0 ( x ) is typically a Uniform distribution over the input domain and the step-size α should be decayed following a polynomial schedule.
In practice the step-size, α , and the standard deviation of (cid:15) is often chosen separately leading to a biased sampler which allows for faster training.
See
Appendix H.1 for further discussion of samplers for EBM training.
W HAT YOUR CLASSIFIER IS HIDING
In modern machine learning, a classiﬁcation problem with K classes is typically addressed using a parametric function, f θ : R D
→ R K , which maps each data point x ∈ R D to K real-valued numbers known as logits.
These logits are used to parameterize a categorical distribution using the so-called Softmax transfer function:
[Equation]
where f θ ( x )[ y ] indicates the y th index of f θ ( x ) , i.e., the logit corresponding the the y th class label.
Our key observation in this work is that one can slightly re-interpret the logits obtained from f θ to deﬁne p ( x , y ) and p ( x ) as well.
Without changing f θ , one can re-use the logits to deﬁne an energy based model of the joint distribution of data point x and labels y via:
[Equation]
where Z ( θ ) is the unknown normalizing constant and E θ ( x , y )
=
− f θ ( x )[ y ] .
By marginalizing out y , we obtain an unnormalized density model for x as well,
[Equation]
Notice now that the LogSumExp ( · ) of the logits of any classiﬁer can be re-used to deﬁne the energy function at a data point x as
[Equation]
Unlike typical classiﬁers, where shifting the logits f θ ( x ) by an arbitrary scalar does not affect the model at all, in our framework, shifting the logits for a data point x will affect log p θ ( x ) .
Thus, we are making use of the extra degree of freedom hidden within the logits to deﬁne the density function over input examples as well as the joint density among examples and labels.
Finally, when we compute p θ ( y | x ) via p θ ( x , y ) /p
θ ( x ) by dividing Eq.
(5) to Eq.
(6), the normalizing constant cancels out, yielding the standard Softmax parameterization in Eq.
Thus, we have found a generative model hidden within every standard discriminative model!
Since our approach proposes to reinterpret a classiﬁer as a J oint E nergy based M odel we refer to it throughout this work as JEM.
O PTIMIZATION
We now wish to take advantage of our new interpretation of classiﬁer architectures to gain the beneﬁts of generative models while retaining strong discriminative performance.
Since our model’s parameterization of p ( y | x ) is normalized over y , it is simple to maximize its likelihood as in standard classiﬁer training.
Since our models for p ( x ) and p ( x , y ) are unnormalized, maximizing their likelihood is not as easy.
There are many ways we could train f θ to maximize the likelihood of the data under this model.
We could apply the gradient estimator of Equation 2 to the likelihood under the joint distribution of Equation 5.
Using Equations 6 and 4, we can also factor the likelihood as
[Equation]
The estimator of Equation 2 is biased when using a MCMC sampler with a ﬁnite number of steps.
Given that the goal of our work is to incorporate EBM training into the standard classiﬁcation setting, the distribution of interest is p ( y | x ) .
For this reason we propose to train using the factorization of
Equation 8 to ensure this distribution is being optimized with an unbiased objective.
We optimize p ( y | x ) using standard cross-entropy and optimize log p ( x ) using Equation 2 with SGLD where gradients are taken with respect to LogSumExp y
( f θ ( x )[ y ]) .
We ﬁnd alternative factorings of the likelihood lead to considerably worse performance as can be seen in Section 5.1.
Following Du & Mordatch (2019) we use persistent contrastive divergence (Tieleman, 2008) to estimate the expectation in the right-hand-side of Equation 2 since it gives an order of magnitude savings in computation compared to seeding new chains at each iteration as in Nijkamp et al.
(2019b).
This comes at the cost of decreased training stability.
These trade-offs are discussed in Appendix H.2.
A PPLICATIONS
We completed a thorough empirical investigation to demonstrate the beneﬁts of JEM over standard classiﬁers.
First, we achieved performance rivaling the state of the art in both discriminative and generative modeling.
Even more interesting, we observed a number of beneﬁts related to the practical application of discriminative models including improved uncertainty quantiﬁcation, outof-distribution detection, and robustness to adversarial examples.
Generative models have been long-expected to provide these beneﬁts but have never been demonstrated to do so at this scale.
All architectures used are based on Wide Residual Networks (Zagoruyko & Komodakis, 2016) where we have removed batch-normalization 1 to ensure that our models’ outputs are deterministic functions of the input.
This slightly increases classiﬁcation error of a WRN-28-10 from 4 .
2% to 6 .
4% on CIFAR10 and from 2 .
3 to 3 .
4% on SVHN.
Class
[Table]
All models were trained in the same way with the same hyper-parameters which were tuned on
CIFAR10.
Intriguingly, the SGLD sampler parameters found here generalized well across datasets and model architectures.
All models are trained on a single GPU in approximately 36 hours.
Full experimental details can be found in Appendix A.
5. H YBRID MODELING
SVHN
CIFAR
First, we show that a given classiﬁer architecture can be trained as an
EBM to achieve competitive performance as both a classiﬁer and a generative model.
We train JEM on CIFAR10, SVHN, and CIFAR100 and compare against other hybrid models as well as standalone generative and discriminative models.
We ﬁnd JEM performs near the state of the art in both tasks simultaneously, outperforming other hybrid models (Table 1).
Given that we cannot compute normalized likelihoods, we present inception scores (IS) (Salimans et al., 2016) and Frechet Inception Distance (FID) (Heusel et al., 2017) as a proxy for this quantity.
We ﬁnd that JEM is competitive with SOTA generative models at these metrics.
These metrics are not commonly reported on CIFAR100 and SVHN so we present accuracy and qualitative samples on these datasets.
Our models achieve 96.7% and 72.2% accuracy on SVHN and CIFAR100, respectively.
Samples from JEM can be seen in Figures 2, 3 and in Appendix C.
JEM is trained to maximize the likelihood factorization shown in Eq. 8.
This was to ensure that no bias is added into our estimate of log p ( y | x ) which can be computed exactly in our setup.
Prior work (Du & Mordatch, 2019; Xie et al., 2016) proposes to factorize the objective as log p ( x | y )
+log p ( y ) .
In these works, each p ( x | y ) is a separate
EBM with a distinct, unknown normalizing constant, meaning that their model cannot be used to compute p ( y | x ) or p ( x ) .
This explains why the model of Du & Mordatch (2019) (we will refer to this model as IGEBM) is not a competitive classiﬁer.
As an ablation, we trained JEM to maximize this objective and found a considerable decrease in discriminative performance (see Table 1, row 4).
5. C ALIBRATION
[Figure]
A classiﬁer is considered calibrated if its predictive conﬁdence, max y p ( y | x ) , aligns with its misclassiﬁcation rate. Thus, when a calibrated classiﬁer predicts label y with conﬁdence . 9 it should have a 90% chance of being correct.
This is an important feature for a model to have when deployed in real-world scenarios where outputting an incorrect decision can have catastrophic consequences.
The classiﬁer’s conﬁdence can be used to decide when to output a prediction or deffer to a human, for example. Here, a well-calibrated, but less accurate classiﬁer can be considerably more useful than a more accurate, but less-calibrated model. While classiﬁers have grown more accurate in recent years, they have also grown considerably less calibrated (Guo et al., 2017). Contrary to this behavior, we ﬁnd that JEM notably improves classiﬁcation while retaining high accuracy.
We focus on CIFAR100 since SOTA classiﬁers achieve approximately 80% accuracy.
We train JEM on this dataset and compare to a baseline of the same architecure without EBM training.
Our baseline model achieves 74 .
2% accuracy and JEM achieves 72 .
2% (for reference, a ResNetachieves 74 .
8% accuracy (Zagoruyko & Komodakis, 2016)).
We ﬁnd the baseline model is very poorly calibrated outputting highly over-conﬁdent predictions.
Conversely, we ﬁnd JEM produces a nearly perfectly calibrated classiﬁer when measured with Expected Calibration Error (see Appendix
E.1). Compared to other calibration methods such as Platt scaling (Guo et al., 2017), JEM requires no additional training data.
Results can be seen in Figure 4 and additional results can be found in Appendix E.2.
5. O UT -O F -D ISTRIBUTION D ETECTION
In general, out-of-distribution (OOD) detection is a binary classiﬁcation problem, where the model is required to produce a score
[Equation]
where x is the query, and θ is the set of learnable parameters.
We desire that the scores for in-distribution examples are higher than that out-of-distribution examples.
Typically for evaluation, threshold-free metrics are used, such as the area under the receiver-operating curve (AUROC)
(Hendrycks & Gimpel, 2016).
There exist a number of distinct OOD detection approaches to which JEM can be applied.
We expand on them below.
Further results and experimental details can be found in Appendix F.2.
5.3. I NPUT D ENSITY
A natural approach to OOD detection is to ﬁt a density model on the data and consider examples with low likelihood to be OOD.
While intuitive, this approach is currently not competitive on highdimensional data.
Nalisnick et al.
(2018) showed that tractable deep generative models such as
Kingma & Dhariwal (2018) and Salimans et al.
(2017) can assign higher densities to OOD examples than in-distribution examples.
Further work (Nalisnick et al., 2019) shows examples where the densities of an OOD dataset are completely indistinguishable from the in-distribution set, e.g., see
Table 2, column 1.
Conversely, Du & Mordatch (2019) have shown that the likelihoods from EBMs can be reliably used as a predictor for OOD inputs.
As can be seen in Table 2 column 2, JEM consistently assigns higher likelihoods to in-distribution data than OOD data.
One possible explanation for JEM’s further improvement over IGEBM is its ability to incorporate labeled information during training while also being able to derive a principled model of p ( x ) .
Intriguingly, Glow does not appear to beneﬁt in the same way from this supervision as is demonstrated by the little difference between our unconditional and class-conditional Glow results.
Quantitative results can be found in Table 3 (top).
5.3. P REDICTIVE D ISTRIBUTION
Many successful approaches have utilized a classiﬁer’s predictive distribution for OOD detection (Gal & Ghahramani, 2016;
Wang et al., 2018; Liang et al., 2017).
A useful OOD score that can be derived from this distribution is the maximum prediction probability: s θ ( x ) = max y p
θ ( y | x ) (Hendrycks & Gimpel, 2016).
It has been demonstrated that OOD performance using this score is highly correlated with a model’s classiﬁcation accuracy.
Since JEM is a competitive classiﬁer, we ﬁnd it performs on par (or beyond) the performance of a strong baseline classiﬁer and considerably outperforms other generative models.
Results can be seen in Table 3 (middle).
5.3. A NEW SCORE : A PPROXIMATE M ASS
It has been recently proposed that likelihood may not be enough for OOD detection in high dimensions (Nalisnick et al., 2019).
It is possible for a point to have high likelihood under a distribution yet be nearly impossible to be sampled.
Real samples from a distribution lie in what is known as the “typical” set.
This is the area of high probability mass .
A single point may have high density but if the surrounding areas have very low density, then that point is likely not in the typical set and therefore likely not a sample from the data distribution.
For a high-likelihood datapoint outside of the typical set, we expect the density to change rapidly around it, thus the norm of the gradient of the log-density will be large compared to examples in the typical set (otherwise it would be in an area of high mass).
We propose an alternative OOD score based on this quantity:
[Equation]
(cid:12)(cid:12)(cid:12)(cid:12)(cid:12)(cid:12)(cid:12)(cid:12) .
For EBMs (JEM and IGEBM), we ﬁnd this predictor greatly outperforms our own and other generative model’s likelihoods – see Table 2 column 3.
For tractable likelihood methods we ﬁnd this predictor is anti-correlated with the model’s likelihood and neither is reliable for OOD detection.
Results can be seen in Table 3 (bottom).
5. R OBUSTNESS
Recent work (Athalye et al., 2017) has demonstrated that classiﬁers trained to be adversarially robust can be re-purposed to generate convincing images, do in-painting, and translate examples from one class to another.
This is done through an iterative reﬁnement procedure, quite similar to the SGLD used to sample from EBMs.
We also note that adversarial training (Goodfellow et al., 2014) bears many similarities to SGLD training of EBMs.
In both settings, we use a gradient-based optimization procedure to generate examples which activate a speciﬁc high-level network activation, then optimize the weights of the network to minimize the generated example’s effect on that activation.
Further connections have been drawn between adversarial training and regularizing the gradients of the network’s activations around the data (Simon-Gabriel et al., 2018).
This is similar to the objective of Score Matching (Hyv ¨ arinen, 2005) which can also be used to train EBMs (Kingma & Lecun, 2010; Song & Ermon, 2019).
Given these connections one may wonder if a classiﬁer derived from an EBM would be more robust to adversarial examples than a standard model.
This behavior has been demonstrated in prior work on EBMs (Du & Mordatch, 2019) but their work did not produce a competitive discriminative model and is therefore of limited practical application for this purporse.
Similarly, we ﬁnd JEM achieves considerable robustness without sacriﬁcing discriminative performance.
5.4. I MPROVED R OBUSTNESS T HROUGH EBM T RAINING
A common threat model for adversarial robustness is that of perturbation-based adversarial examples with an L p -norm constraint (Goodfellow et al., 2014).
They are deﬁned as perturbed inputs ˜ x
= x + δ , which change a model’s prediction subject to || ˜ x − x || p < (cid:15) .
These examples exploit semantically meaningless perturbations to which the model is overly sensitive.
However, closeness to real inputs in terms of a given metric does not imply that adversarial examples reside within areas of high density according to the model distribution, hence it is not surprising that the model makes mistakes when asked to classify inputs it has rarely or never encountered during training. [Table] CIFAR [Table]
[Figure]
This insight has been used to detect and robustly classify adversarial examples with generative models (Song et al., 2017;
Li et al., 2018; Fetaya et al., 2019).
The state-of-theart method for adversarial robustness on MNIST classiﬁes by comparing an input to samples generated from a classconditional generative model (Schott et al., 2018).
This can be thought of as classifying an example similar to the input but from an area of higher density under the model’s learned distribution.
This reﬁned input resides in areas where the model has already “seen” sufﬁcient data and is thus able to accurately classify.
Albeit promising, this family of methods has not been able to scale beyond MNIST due to a lack of sufﬁciently powerful conditional generative models.
We believe JEM can help close this gap.
We propose to run a few iterations of our model’s sampling procedure seeded at a given input.
This should be able to transform low-probability inputs to a nearby point of high probability, “undoing” any adversarial attack and enabling the model to classify robustly.
Perturbation Robustness
We run a number of powerful adversarial attacks on our CIFAR10 models.
We run a white-box PGD attack, giving the attacker access to the gradients through our sampling procedure 2 .
Because our sampling procedure is stochastic, we compute the “expectation over transformations” Athalye et al.
(2018), the expected gradient over multiple runs of the sampling procedure.
We also run gradient-free black-box attacks; the boundary attack (Brendel et al., 2017) and the bruteforce pointwise attack (Rauber et al., 2017).
All attacks are run with respect to the L 2 and L ∞ norms and we test JEM with 0, 1, and 10 steps of sampling seeded at the input.
Results from the PGD experiments can be seen in Figure 5.
Experimental details and remaining results, including gradient-free attacks, can be found in Appendix G. Our model is considerably more robust than a baseline with standard classiﬁer training.
With respect to both norms, JEM performs competitive with, but slightly below state-of-the-art adversarial training (Madry et al., 2017; Santurkar et al., 2019) and the state-of-the-art certiﬁed robutness method of Salman et al.
(2019) (“RandAdvSmooth” in Figure 5).
We note that each of these baseline methods is trained to be robust to the norm through which it is being attacked and it has been shown that attacking an L ∞ adversarially trained model with an L 2 adversary decreases robustness considerably (Madry et al., 2017). However, we attack the same JEM model with both norms and observe competitive robustness in both cases.
JEM with 0 steps reﬁnement is noticeably more robust than the baseline model trained as a standard classiﬁer, thus simply adding EBM training can produce more robust models.
We also ﬁnd that increasing the number of reﬁnement steps further increases robustness to levels at robustness-speciﬁc approaches.
We expect that increasing the number of reﬁnement steps will lead to more robust models but due to computational constraints we could not run attacks in this setting. from that y
“car” Distal Adversarials Another common failure mode of non-robust models is their tendency to classify nonsensical inputs with high conﬁdence.
To analyze this property, we follow Schott et al.
Starting from noise we generate images to maximize p ( y = “car” | x ) .
Results are shown in ﬁgure 6.
The baseline conﬁdently classiﬁes unstructured noise images.
The L 2 adversarially trained ResNet with (cid:15) = 0 .
5 (Santurkar et al., 2019) conﬁdently classiﬁes somewhat structured, but unrealistic images.
JEM does not conﬁdently classify nonsensical images, so instead, car attributes and natural image properties visibly emerge.
L IMITATIONS
Energy based models can be very challenging to work with.
Since normalized likelihoods cannot be computed, it can be hard to verify that learning is taking place at all.
When working in domains such as images, samples can be drawn and checked to assess learning, but this is far from a generalizable strategy.
Even so, these samples are only samples from an approximation to the model so they can only be so useful.
Furthermore, the gradient estimators we use to train JEM are quite unstable and are prone to diverging if the sampling and optimization parameters are not tuned correctly.
Regularizers may be added (Du & Mordatch, 2019) to increase stability but it is not clear what effect they have on the ﬁnal model.
The models used to generate the results in this work regularly diverged throughout training, requiring them to be restarted with lower learning rates or with increased regularization.
See Appendix H.3 for a detailed description of how these difﬁculties were handled.
While this may seem prohibitive, we believe the results presented in this work are sufﬁcient to motivate the community to ﬁnd solutions to these issues as any improvement in the training of energy based models will further improve the results we have presented in this work.
R ELATED W ORK
Prior work (Xie et al., 2016) made a similar observation to ours about classiﬁers and EBMs but deﬁne the model differently.
They reinterpret the logits to deﬁne a class-conditional EBM p ( x | y ) , similar to Du & Mordatch (2019).
This setting requires additional parameters to be learned to derive a classiﬁer and an unconditional model.
We believe this subtle distinction is responsible for our model’s success.
The model of (Song & Ou, 2018) is similar as well but is trained using a GAN-like generator and is applied to different applications.
Our work builds heavily on Nijkamp et al.
(2019b;a); Du & Mordatch (2019) which scales the training of EBMs to high-dimensional data using Contrastive Divergence and SGLD.
While these works have pushed the boundaries of the types of data to which we can apply EBMs, many issues still exist.
These methods require many steps of SGLD to take place at each training iteration.
Each step requires approximately the same amount of computation as one iteration of standard discriminitive model training, therefore training EBMs at this scale is orders of magnitude slower than training a classiﬁer – limiting the size of problems we can attack with these methods.
There exist orthogonal approaches to training EBMs which we believe have promise to scale more gracefully.
Score matching (Hyv¨arinen, 2005) attempts to match the derivative of the model’s density with the derivative of the data density.
This approach saw some development towards high-dimensional data (Kingma & Lecun, 2010) and recently has been successfully applied to large natural images (Song & Ermon, 2019).
This approach required a model to output the derivatives of the density function, not the density function itself, so it is unclear what utility this model can provide to the applications we have discussed in this work.
Regardless, we believe this is a promising avenue for further research.
Noise Contrastive Estimation (Gutmann & Hyv¨arinen, 2010) rephrases the density estimation problem as a classiﬁcation problem, attempting to distinguish data from a known noise distribution.
If the classiﬁer is properly structured, then once the classiﬁcation problem is solved, an unnormalized density estimator can be derived from the classiﬁer and noise distribution.
While this method has been recently extended (Ceylan & Gutmann, 2018), these methods are challenging to extend to high-dimensional data.
C ONCLUSION AND F URTHER W ORK
In this work we have presented JEM, a novel reinterpretation of standard classiﬁer architectures which retains the strong performance of SOTA discriminative models while adding the beneﬁts of generative modeling approaches.
Our work is enabled by recent work scaling techniques for training EBMs to high dimensional data.
We have demonstrated the utility of incorporating this type of training into discriminative models.
While there exist many issues in training EBMs we hope the results presented here will encourage the community to improve upon current approaches
A T RAINING D ETAILS
We train all models with the Adam optimizer (Kingma & Ba, 2014) for 150 epochs through the dataset using a staircase decay schedule.
All network architecutres are based on WideResNet-28with no batch normalization.
We generate samples using PCD with hyperparameters in Table 4.
We evolve the chains with 20-steps of SGLD per iteration and with probability .
we reiniatilize the chains with uniform random noise.
For preprocessing, we scale images to the range [ − 1 , 1] and add
Gaussian noise of stddev = .
Pseudo-code for our training procedure is in Algorithm 1.
When training via contrastive divergence there are a few different ways one could potentially draw samples from p θ ( x ) .
We could:
Sample y ∼ p ( y ) then sample x ∼ p θ ( x | y ) via SGLD with energy E ( x | y )
=
− f θ ( x )[ y ] then throw away y .
Sample x ∼ p θ ( x ) via SGLD with energy E ( x ) = − LogSumExp
y f θ ( x )[ y ] .
We experimented with both methods during training and found that while method 1 produced more visually appealing samples (to a human’s perspective), method 2 produced slightly stronger discirminative performance – 92.9% vs. 91.2% accuracy on CIFAR10.
For this reason we use method 2 in all results presented.
Algorithm α σ
B , η reinitialization frequency ρ 1: while not converged do 2:
Sample x and y from dataset 3:
L clf ( θ ) =
xent ( f θ ( x ) , y ) 4:
Sample (cid:98) x 0 ∼ B with probability 1 − ρ , else (cid:98) x 0 ∼ U ( − 1 , 1) (cid:46) Initialize SGLD 5: for t ∈ [1 , 2 , . . .
, η ] do (cid:46) SGLD 6: (cid:98) x t
= (cid:98) x
t − 1 + α · ∂ LogSumExp y (cid:48)
( f θ ( (cid:98) x
t − 1 )
[ y (cid:48) ]) ∂ (cid:98) x
t −+ σ · N (0 , I ) 7: end for 8:
L gen ( θ ) =
LogSumExp y (cid:48)
( f ( x )[ y (cid:48) ]) − LogSumExp y (cid:48)
( f ( (cid:98) x t )
[ y (cid:48) ]) (cid:46) Surrogate for Eq9:
L ( θ ) =
L clf ( θ ) + L gen ( θ ) 10:
Obtain gradients ∂L ( θ ) ∂θ for training 11:
Add (cid:98) x t to B 12: end while
[Table]
B S AMPLE Q UALITY E VALUTION
In this section we describe the details for reproducing the Inception Score (IS) and FID results reported in the paper.
First we note that both IS and FID are scores computed based on a pretrained classiﬁer network, and thus can be very dependent on the exact model/code repository used.
For a more detailed discussion on the variability of IS, please refer to Barratt & Sharma (2018).
To gauge our model against the other papers, we document our attempt to fairly compare the scores across papers in Table 6.
As a direct comparison of IS, we got 8.76 using the code provided by Du &
Mordatch (2019), and is better than their best reported score of 8.3.
For FID, we used the ofﬁcial implementation from Heusel et al.
Note that FID computed from this repository assigned much worse FID than reported in Chen et al.
Conditional vs unconditional samples.
Since we are interested in training a Hybrid model, our model, by deﬁnition, is a conditional generative model as it has access to label information.
In
Table 5, unconditional samples mean samples directly obtained from running SGLD using p ( x ) .
Conditional samples are obtained by taking the max of our p ( y | x ) model.
The reported scores are obtained by keeping the top 10 percentile samples with the highest p ( y | x ) values.
Scores obtained on a “single” model are computed directly on the training replay buffer of the last checkpoint.
“Ensemble” here are obtained by lumping together 5 buffers over the last few epochs of training.
As we initialize SGLD with uniform noise, using the training buffer is exactly the same as re-sampling from the model.
[Table]
[Table]
C F URTHER H YBRID M ODEL S AMPLES
Additional samples from CIFAR10 and SVHN can be seen in Figure 7 and samples from CIFAR can be seen in Figure
D Q UALITATIVE A NALYSIS OF S AMPLES
Visual quality is difﬁcult to quantify.
Of the known metrics like IS and FID, using samples that have higher p ( y | x ) values results in higher scores, but not necessary if we use samples with higher log p ( x ) .
However, this is likely because of the downfalls of the evaluation metrics themselves rather than reﬂecting true sample quality.
Based on our analysis (below) we ﬁnd
Our log p ( x ) model assigns values that cluster around different means for different classes.
The class automobiles has the highest log p ( x ) .
Of all generated samples, all topsamples are of this class.
Given the class, the samples that have higher log p ( x ) values all have white background and centered object, and lower log p ( x ) samples have colorful (e.g., forest-like) background.
Of all samples, higher p ( y | x ) values means clearly centered objects, and lower p ( y | x ) otherwise.
E C ALIBRATION E. E XPECTED C ALIBRATION E RROR
Expected Calibration Error (ECE) is a metric to measure the calibration of a classiﬁer.
It works by ﬁrst computing the conﬁdence, max y p
( y | x i ) , for each x i in some dataset.
We then group the items into equally spaced buckets { B m } Mm =1 based on the classiﬁer’s output conﬁdence. For example, if M = 20 , then B 0 would represent all examples for which the classiﬁer’s conﬁdence was between 0 . 0 and 0 . We then deﬁne:
[Equation]
where n is the number of examples in the dataset, acc ( B m ) is the averaged accuracy of the classiﬁer of all examples in B m and conf ( B m ) is the averaged conﬁdence over all examples in B m .
For a perfectly calibrated classiﬁer, this value will be 0 for any choice of M .
In our analysis, we choose M = 20 throughout.
E. F URTHER RESULTS
We ﬁnd that JEM also improves calibration on CIFAR10 as can be seen in Table 13.
There we see an improvement in calibration, but both classiﬁers are well calibrated because their accuracy is so high.
In a more interesting experiment, we limit the size of the training set to 4,000 labeled examples.
In this setting the accuracy drops to 78.0% and 74.9% in the baseline and JEM, respectively.
Given the
JEM can be trained on unlabeled data, we treat the remainder of the training set as unlabeled and train in a semi-supervised manner.
We ﬁnd this gives a noticeable boost in the classiﬁer’s calibration as seen in Figure 13.
Surprisingly this did not improve generalization.
We leave exploring this phenomenon for future work.
[Equation]
[Figure]
F O UF -O F -D ISTRIBUTION D ETECTION F. E XPERIMENTAL DETAILS
To obtain OOD results for unconditional Glow, we used the pre-trained model and implementation of https://github.com/y0ast/Glow-PyTorch .
We trained a Class-Conditional model as well using this codebase which was used to generate the class-conditional OOD results.
We obtained the IGEBM of Du & Mordatch (2019) from their open-source implementation at https://github.com/openai/ebm_code_release .
For likelihood and likelihoodgradient OOD scores we used their pre-trained cifar10 large model uncond model.
We were able to replicate the likelihood based OOD results presented in their work.
We implemented our likelihood-gradient approximate-mass score on top of their codebase.
For predictive distribution based OOD scores we used their cifar cond model which was the model used in their work to generate their robustness results.
F. F URTHER RESULTS
Figure 7 contains results on two datasets, Constant and Uniform, which were omitted for space.
Most models perform very well at the Uniform dataset.
On the Constant dataset (all examples = 0) generative models mainly fail – with JEM being the only one whose likelihoods can be used to derive a predictive score function for OOD detection.
Intrestinly, we could not obtain approximate mass scores on this dataset from the Glow models due to numerical stability issues.
[Table]
G A TTACK D ETAILS AND F URTHER R OBUSTNESS R ESULTS
We use foolbox (Rauber et al., 2017) for our experiments.
PGD uses binary search to determine minimal epsilons for every input and we plot the resulting robustness-distortion curves.
PGD runs with 20 random restarts and 100 iterations.
For the boundary attack, we run default foolbox settings with one important difference.
The random initialization often fails for JEM and thus we initialize the attack with a correclty classiﬁed input of another class.
This other class is chosen based on the top-2 prediction for the image to be attacked.
As all our attacks are expensive to run, we only attacked 300 randomly chosen inputs.
The same randomly chosen inputs were used to attack each model.
In Figure 14 we see the results of the boundary attack and pointwise attack on JEM and a baseline.
The main point to running these attacks was to demonstrate that our model was not able to “cheat” by having vanishing gradients through our gradient-based sampling procedure.
Since PGD was more successful than these gradient-free methods, this is clearly not the case and the attacker was able to use the gradients of the sampling procedure to attack our model.
Further, we observe the same behavior across all attacks; the EBM with 0 steps sampling is more robust than the baseline and the robustness increases as we add more steps of sampling.
We also compare JEM to the IGEBM of Du & Mordatch (2019) with 10 steps of sampling reﬁnement, see Figure 15.
We run the same gradient-based attacks on their model and ﬁnd that despite not having competitive clean accuracy, it is quite robust to large (cid:15) attacks – especially with respect to the L ∞ norm.
After (cid:15) =
12 their model is more robust than ours and after (cid:15) =
18 it is more robust than the adversarial training baseline.
With respect to the L 2 norm their model is more robust than the adversarial training baseline above (cid:15) = 280 but remains less robust than JEM until (cid:15)
= 525 .
We believe these results demonstrate that EBMs are a compelling class of models to explore for further work on building robust models.
[Figure]
G. E XPECTATION O VER T RANSFORMATIONS
Our SGLD-based reﬁnement procedure is stochastic in nature and it has been shown that stochastic defenses to adversarial attacks can provide a false sense of security (Athalye et al., 2018).
To deal with this, when we attack our stochastically reﬁned classiﬁers, we average the classiﬁer’s predictions over multiple samples of this reﬁnement procedure.
This makes the defense more deterministic and easier to attack.
We redeﬁne the logits of our classiﬁer as:
[Equation] where we have deﬁned SGLD ( x , k ) as an SGLD chain run for k steps seeded at x . Intuitively, we draw n different samples { x i } ni =1 from our model seeded at input x , then compute log p ( y | x i ) for each of these samples, then average the results. We then attack these averaged logits with PGD to generate the results in Figure 5.
We experimented with different numbers of samples and found that [Figure] 10 samples yields very similar results to 5 samples on JEM with one reﬁnement step (see Figure 16). Because 10 samples took very long to run on the JEM model with ten reﬁnement steps
[Figure]
we settled on using 5 samples in the results reported in the main body of the paper
[Figure]
H A D ISCUSSION ON S AMPLERS H. I MPROPER SGLD
Recall the transition kernel of SGLD:
[Equation]
In the proper formulation of this sampler (Welling & Teh, 2011), the step-size and the variance of the Gaussian noise are related Var ( (cid:15) )
=
α .
If the stepsize is decayed with a polynomial schedule, then samples from SGLD converge to samples from our unnomralized density as the number of steps goes to ∞ .
In practice, we approximate these samples with a sampler that runs for a ﬁnite number of steps.
When using the proper step-size to noise ratio, the signal from the gradient is overtaken by the noise when step-sizes are large enough to be informative.
In practice the sampler is typically “relaxed” in that different values are used for the step-size and the amount of Guassian noise added – typically the amount of noise is signiﬁcantly reduced.
While we are no longer working with a valid MCMC sampler, this approximation has been successfully applied in practice in most recent work scaling EBM training to high dimensional data (Nijkamp et al., 2019b;a; Du & Mordatch, 2019) with the exception of Song & Ermon (2019) (which develops a clever work-around).
The model they train is actually an ensemble of models trained on data with different amounts of noise added.
They use a proper SGLD sampler decaying the step size as they sample, moving from their high-noise models to their low-noise models.
This provides one possible explanation for the compelling results of their model.
In our work we have set the step-size α = 2 and draw (cid:15) ∼ N (0 , .
We have found these parameters to work well across a variety of datasets, domains, architectures, and sampling procedures (persistent vs. short-run).
We believe they are a decent “starting place” for energy-functions parameterized by deep neural networks.
H. P ERSISTENT OR S HORT - RUN C HAINS ?
Both persistent and short-run markov chains have been able to succesfully train EBMs.
Nijkamp et al.
(2019a) presents a careful study of various samplers which can be used and the tradeoffs one makes when choosing one sampler over another.
In our work we have found that if computation allows, short-run MCMC chains are preferable in terms of training stability.
Given that each step of
SGLD requires approximately the computation of 1 training iteration of a standard classiﬁer we are incentivized to ﬁnd a sampler which can stably train EBMs requiring as few steps as possible per training iteration.
In our experiments we found the smallest number of SGLD steps we could take to stably train an
EBM at the scale of this work was 80 steps.
Even so, these models eventually would diverge late into training.
At 80 steps, we found the cost of training to be prohibitively high compared to a standard classiﬁer.
We found that by using persistent markov chains, we could further reduce the number of steps per iteration to 20 and still allow for relatively stable training.
This gave a 4x speedup over our fastest short-run MCMC sampler.
Still, this PCD sampler was noticebly less stable than the fastest shortrun sampler we could use
but we found the multiple factor increase in speed to be a worth-while trade-off.
If time allows, we recommend using a short-run MCMC sampler with a large enough number of steps to be stable.
Given that is not always possible on problems of scale, PCD can be made to work more efﬁciently, but at the cost of a greater number of stability-related hyper-parameters.
These additional parameters include the buffer size and the re-initialization frequency of the Markov chains.
We found both to be important for training stability and found no general recipe for which to set them.
We ran most of our experiments with re-initialization frequency at 5% .
A particualrly interesting observation we discovered while using PCD is that the model would use the length of the markov chains to encode semantic information.
We found that when training models on CIFAR10, when chains were young they almost always could be identiﬁed as frogs.
When chains were old they could almost always be identiﬁed as cars.
This behavior is likely some degeneracy of PCD which would not be possible with a short-run MCMC since all chains have the same length.
H. D EALING WITH I NSTABILITY
Training a model with the gradient estimator of Eq.
(2) can be quite unstable – especially when combined with other objective as was the case with all models presented in this work.
There exists a “stable region” of sorts when training these models where the energy values of the true data are in the same range as the energy values of the generated samples.
Intuitively, if the generated samples create energies that are not trivially separated from the training data, then real learning has to take place.
Nijkamp et al.
(2019b;a) provide a careful analysis of this and we refer the reader there for a more in-depth analysis.
We ﬁnd that when using PCD occasionally throughout training a sample will be drawn from the replay buffer that has a considerably higher-than average energy (higher than the energy of a random initialization).
This causes the gradients w.r.t this example to be orders of magnitude larger than gradients w.r.t the rest of the examples and causes the model to diverge.
We tried a number of heuristic approaches such as gradient clipping, energy clipping, ignoring examples with atypical energy values, and many others but could not ﬁnd an approach that stabilized training and did not hurt generative and discriminative performance.
The only two approaches we found to consistently work to increase stability of a model which has diverged is to 1) decrease the learning rate and 2) increase the number of SGLD steps in each PCD iteration.
Unfortunately, both of these approaches slow down learning.
We also had some success simply restarting models from a saved checkpoint with a different random seed.
This was the main approach taken unless the model was late into training.
In this case, random restarts were less effective and we increased the number of SGLD steps from 20 to 40 which stabilized training.
While we are very optimistic about the future of large-scale EBMs we believe these are the most important issues that must be addressed in order for these models to be succeful.