B
AYESIAN
H
YPERNETWORKS
Anonymous authors
Paper under double-blind review
A BSTRACT
We propose Bayesian hypernetworks: a framework for approximate Bayesian inference in neural networks.
A Bayesian hypernetwork h is a neural network which learns to transform a simple noise distribution, p ( (cid:15) )
=
N ( 0 , I ) , to a distribution q ( θ ) :
= q ( h ( (cid:15) )) over the parameters θ of another neural network (the “primary network”).
We train q with variational inference, using an invertible h to enable efﬁcient estimation of the variational lower bound on the posterior p ( θ |D ) via sampling.
In contrast to most methods for Bayesian deep learning, Bayesian hypernets can represent a complex multimodal approximate posterior with correlations between parameters, while enabling cheap iid sampling of q ( θ ) .
In practice, Bayesian hypernets provide a better defense against adversarial examples than dropout, and also exhibit competitive performance on a suite of tasks which evaluate model uncertainty, including regularization, active learning, and anomaly detection.
I NTRODUCTION
Simple and powerful techniques for Bayesian inference of deep neural networks’ (DNNs) parameters have the potential to dramatically increase the scope of applications for deep learning techniques.
In real-world applications, unanticipated mistakes may be costly and dangerous, whereas anticipating mistakes allows an agent to seek human guidance (as in active learning), engage safe default behavior (such as shutting down), or use a “reject option” in a classiﬁcation context.
DNNs are typically trained to ﬁnd the single most likely value of the parameters (the “MAP estimate”), but this approach neglects uncertainty about which parameters are the best (“parameter uncertainty”), which may translate into higher predictive uncertainty when likely parameter values yield highly conﬁdent but contradictory predictions.
Conversely, Bayesian DNNs model the full posterior distribution of a model’s parameters given the data, and thus provides better calibrated conﬁdence estimates, with corresponding safety beneﬁts (Gal & Ghahramani, 2016; Amodei et al., 2016).
1 Maintaining a distribution over parameters is also one of the most effective defenses against adversarial attacks (Carlini & Wagner, 2017).
Techniques for Bayesian DNNs are an active research topic.
The most popular approach is variational inference (Blundell et al., 2015; Gal, 2016), which typically restricts the variational posterior to a simple family of distributions, for instance a factorial Gaussian (Blundell et al., 2015; Graves, 2011).
Unfortunately, from a safety perspective, variational approximations tend to underestimate uncertainty, by heavily penalizing approximate distributions which place mass in regions where the true posterior has low density.
This problem can be exacerbated by using a restricted family of posterior distribution; for instance a unimodal approximate posterior will generally only capture a single mode of the true posterior.
With this in mind, we propose learning an extremely ﬂexible and powerful posterior, parametrized by a DNN h , which we refer to as a Bayesian hypernetwork in reference to Ha et al.
A Bayesian hypernetwork (BHN) takes random noise (cid:15) ∼ N ( 0 , I ) as input and outputs a sample from the approximate posterior q ( θ ) for another DNN of interest (the “primary network”).
The key insight for building such a model is the use of an invertible hypernet, which enables Monte Carlo estimation of the entropy term − log q ( θ ) in the variational inference training objective.
We begin the paper by reviewing previous work on Bayesian DNNs, and explaining the necessary components of our approach (Section 2).
Then we explain how to compose these techniques to yield Bayesian hypernets, as well as design choices which make training BHNs efﬁcient, stable and robust (Section 3).
Finally, we present experiments which validate the expressivity of BHNs, and demonstrate their competitive performance across several tasks (Section 4).
R ELATED W ORK
We begin with an overview of prior work on Bayesian neural networks in Section 2.1 before discussing the speciﬁc components of our technique in Sections 2.2 and 2.3.
2. B AYESIAN DNN S
Bayesian DNNs have been studied since the 1990s (Neal, 1996; MacKay, 1994).
For a thorough review, see Gal (2016).
Broadly speaking, existing methods either 1) use Markov chain Monte
Carlo (Welling & Teh, 2011; Neal, 1996), or 2) directly learn an approximate posterior distribution using (stochastic) variational inference (Graves, 2011; Gal & Ghahramani, 2016; Salimans et al., 2015; Blundell et al., 2015), expectation propagation (Hernandez-Lobato & Adams, 2015; Soudry et al., 2014), or α -divergences (Li & Gal, 2017).
We focus here on the most popular approach: variational inference.
Notable recent work in this area includes Gal & Ghahramani (2016), who interprets the popular dropout (Srivastava et al., 2014) algorithm as a variational inference method (“MC dropout”).
This has the advantages of being simple to implement and allowing cheap samples from q ( θ ) .
Kingma et al.
(2015) emulates Gaussian dropout, but yields a unimodal approximate posterior, and does not allow arbitrary dependencies between the parameters.
The other important points of reference for our work are Bayes by Backprop (BbB) (Blundell et al., 2015), and multiplicative normalizing ﬂows (Louizos & Welling, 2017).
Bayes by Backprop can be viewed as a special instance of a Bayesian hypernet, where the hypernetwork only performs an element-wise scale and shift of the input noise (yielding a factorial Gaussian distribution).
More similar is the work of Louizos & Welling (2017), who propose and dismiss BHNs due to the issues of scaling BHNs to large primary networks, which we address in Section 3.3.
2 Instead, in their work, they use a hypernet to generate scaling factors, z on the means µ of a factorial Gaussian distribution.
Because z follows a complicated distribution, this forms a highly ﬂexible approximate posterior: q ( θ ) =
(cid:82) q ( θ | z ) q ( z ) d z .
However, this approach also requires them to introduce an auxiliary inference network to approximate q ( z | θ ) in order to estimate the entropy term of the variational lower bound, resulting in lower bound on the variational lower bound .
Finally, the variational autoencoder (VAE) (Jimenez Rezende et al., 2014; Kingma & Welling, 2013) family of generative models is likely the best known application of variational inference in DNNs, but note that the VAE is not a Bayesian DNN in our sense.
VAEs approximate the posterior over latent variables, given a datapoint; Bayesian DNNs approximate the posterior over model parameters, given a dataset.
2. H YPERNETWORKS
A hypernetwork (Ha et al., 2017; Brabandere et al., 2016; Bertinetto et al., 2016) is a neural net that outputs parameters of another neural net (the “primary network”).
The hypernet and primary net together form a single model which is trained by backpropagation.
The number of parameters of a DNN scales quadratically in the number of units per layer, meaning naively parametrizing a large primary net requires an impractically large hypernet.
One method of addressing this challenge is Conditional Batch Norm (CBN) (Dumoulin et al., 2016), and the closely related Conditional
Instance Normalization (CIN) (Huang & Belongie, 2017; Ulyanov et al., 2016), and Feature-wise
Linear Modulation (FiLM) (Perez et al., 2017; Kirkpatrick et al., 2016), which can be viewed as speciﬁc forms of a hypernet.
In these works, the weights of the primary net are parametrized directly, and the hypernet only outputs scale ( γ ) and shift ( β ) parameters for every neuron; this can be viewed as selecting which features are signiﬁcant (scaling) or present (shifting).
In our work, we employ the related technique of weight normalization (Salimans & Kingma, 2016), which normalizes the input weights for every neuron and introduces a separate parameter g for their scale.
2. I NVERTIBLE G ENERATIVE M ODELS
Our proposed Bayesian hypernetworks employ a differentiable directed generator network (DDGN) (Goodfellow et al., 2016) as a generative model of the primary net parameters.
DDGNs use a neural net to transform simple noise (most commonly isotropic Gaussian) into samples from a complex distribution, and are a common component of modern deep generative models such as variational autoencoders (VAEs) (Kingma & Welling, 2013; Jimenez Rezende et al., 2014) and generative adversarial networks (GANs) (Goodfellow et al., 2014a; Goodfellow, 2017).
We take advantage of techniques for invertible DDGNs developed in several recent works on generative modeling (Dinh et al., 2014; 2016) and variational inference of latent variables (Rezende &
Mohamed, 2015; Kingma et al., 2016).
Training these models uses the change of variables formula, which involves computing the log-determinant of the inverse Jacobian of the generator network.
This computation involves a potentially costly matrix determinant, and these works propose innovative architectures which reduce the cost of this operation but can still express complicated deformations, which are referred to as “normalizing ﬂows”.
M ETHODS
We now describe how variational inference is applied to Bayesian deep nets (Section 3.1), and how we compose the methods described in Sections 2.2 and 2.3 to produce Bayesian hypernets (Section 3.2).
3. V ARIATIONAL I NFERENCE
In variational inference, the goal is to maximize a lower bound on the marginal log-likelihood of the data, log p ( D ) under some statistical model.
This involves both estimating parameters of the model, and approximating the posterior distribution over unobserved random variables (which may themselves also be parameters, e.g., as in the case of Bayesian DNNs).
Let θ ∈ R D be parameters given the Bayesian treatment as random variables, D a training set of observed data, and q ( θ ) a learned approximation to the true posterior p ( θ |D ) .
Since the KL divergence is always non-negative, we have, for any q ( θ ) :
[Equation]
The right hand side of (2) is the evidence lower bound, or “ELBO”.
The above derivation applies to any statistical model and any dataset.
In our experiments, we focus on modeling conditional likelihoods p ( D ) =
p ( Y|X ) .
Using the conditional independence assumption, we further decompose log p ( D| θ ) :
= log p ( Y|X , θ ) as (cid:80) ni =1 log p ( y i | x i , θ ) , and apply stochastic gradient methods for optimization.
3.1. V ARIATIONAL I NFERENCE FOR D EEP N ETWORKS
Computing the expectation in (2) is generally intractable for deep nets, but can be estimated by
Monte Carlo sampling.
For a given value of θ , log p ( D| θ ) and log( θ ) can be computed and differentiated exactly as in a non-Bayesian DNN, allowing training by backpropagation.
The entropy term E q [ − log q ( θ )] is also straightforward to evaluate for simple families of approximate posteriors such as Gaussians.
Similarly, the likelihood of a test data-point under the predictive posterior using
S samples can be estimated using Monte Carlo:
[Equation]
3. B AYESIAN H YPERNETS
Bayesian hypernets (BHNs) express a ﬂexible q ( θ ) by using a DDGN (section 2.3), h ∈ R D
→ R D , to transform random noise (cid:15) ∼ N ( 0 , I D ) into independent samples from q ( θ ) .
This makes it cheap to compute Monte Carlo estimations of expectations with respect to q ; these include the ELBO, and its derivatives, which can be backpropagated to train the hypernet h .
Since BHNs are both trained and evaluated via samples of q ( θ ) , expressing q ( θ ) as a generative model is a natural strategy.
However, while DDGNs are convenient to sample from, computing the entropy term ( E q [ − log q ( θ )] ) of the ELBO additionally requires evaluating the likelihood of generated samples, and most popular DDGNs (such as VAEs and GANs) do not provide a convenient way of doing so.
In general, these models can be many-to-one mappings, and computing the likelihood of a given parameter value requires integrating over the latent noise variables (
cid:15) ∈ R D :
[Equation]
To avoid this issue, we use an invertible h , allowing us to compute q ( θ ) simply by using the change of variables formula:
[Equation]
where q (cid:15) is the distribution of (cid:15) .
As discussed in Section 2.3, a number of techniques have been developed for efﬁciently training such invertible DDGNs.
In this work, we employ both RealNVP (RNVP)
(Dinh et al., 2016) and
Inverse Autoregressive Flows (IAF) (Kingma et al., 2016).
Note that the latter can be efﬁciently applied, since we only require the ability to evaluate likelihood of generated samples (not arbitrary points in the range of h , as in generative modeling applications, e.g., Dinh et al.
; and this also means that we can use a lower-dimensional (cid:15) to generate samples along a submanifold of the entire parameter space, as detailed below.
3. E FFICIENT P ARAMETRIZATION AND T RAINING OF B AYESIAN H YPERNETS
In order to scale BHNs to large primary networks, we use the weight normalization reparametrization (Salimans & Kingma, 2016):
[Equation]
where θ j are the input weights associated with a single unit j in the primary network.
We only output the scaling factors g from the hypernet, and learn a maximum likelihood estimate of v .
This allows us to overcome the computational limitations of naively-parametrized BHNs noted by Louizos &
Welling (2017), since computation now scales linearly, instead of quadratically, in the number of primary net units.
Using this parametrization restricts the family of approximate posteriors, but still allows for a high degree of multimodality and dependence between the parameters.
Note
[Figure]
We also employ weight normalization within the hypernet, and found this stabilizes training dramatically.
Initialization plays an important role as well; we recommend initializing the hypernet weights to small values to limit the impact of noise at the beginning of training.
We also ﬁnd clipping the outputs of the softmax to be within (0 . 001 , 0 . 999) critical for numerical stability.
E XPERIMENTS
We perform experiments on MNIST, CIFAR10, and a 1D regression task.
There is no single metric for how well a model captures uncertainty; to evaluate our model, we perform experiments on regularization (Section 4.2), active learning (Section 4.3), anomaly detection (Section 4.4), and detection of adversarial examples (Section 4.5).
Active learning and anomaly detection problems make natural use of uncertainty estimates: In anomaly detection, higher uncertainty indicates a likely anomaly.
In active learning, higher uncertainty indicates a greater opportunity for learning.
Parameter uncertainty also has regularization beneﬁts: integrating over the posterior creates an implicit ensemble.
Intuitively, when the most likely hypothesis predicts “A”, but the posterior places more total mass on hypotheses predicting “B”, we prefer predicting “B”.
By improving our estimate of the posterior, we more accurately weigh the evidence for different hypotheses.
Adversarial examples are an especially difﬁcult kind of anomaly designed to fool a classiﬁer, and ﬁnding effective defenses against adversarial attacks remains an open challenge in deep learning.
For the hypernet architecture, we try both RealNVP (Dinh et al., 2016) and IAF(Kingma et al., 2016) with MADE(Germain et al., 2015), with 1-layer ReLU-MLP coupling functions with 200 hidden units (each).
In general, we ﬁnd that IAF performs better.
We use an isotropic standard normal prior on the weights of the network.
We use Adam with default hyper-parameter settings (Kingma & Ba, 2014) and gradient clipping in all of our experiments.
Our mini-batch size is 128, and to reduce computation, we use the same noise-sample (and thus the same primary net parameters) for all examples in a mini-batch.
We experimented with independent noise, but did not notice any beneﬁt.
Our baselines for comparison are Bayes by Backprop (BbB) (Blundell et al., 2015),
MC dropout (MCdropout) (Gal & Ghahramani, 2016), and non-Bayesian DNN baselines (with and without dropout).
4. Q UALITATIVE R ESULTS AND V ISUALIZATION
We ﬁrst demonstrate the behavior of the network on the toy 1D-regression problem from Blundell et al.
(2015) in Figure 1.
As expected, the uncertainty of the network increases away from the observed data, although the model still suffers from overconﬁdence to some extent compared with
Hamiltonian Monte Carlo (Neal et al., 2011), which excels on low-dimensional problems.
Next, we demonstrate the distinctive ability of Bayesian hypernets to learn multi-modal, dependent distributions.
Figure 6 (appendix) shows that BHNs do learn approximate posteriors with dependence be- [Figure] tween different parameters, as measured by the Pearson correlation coefﬁcient.
Meanwhile, Figureshows that BHNs are capable of learning multimodal posteriors.
For this experiment, we trained an over-parametrized linear (primary) network: ˆ y = a · b · x on a dataset generated as y = x + (cid:15)
[Figure]
and the BHN learns capture both the modes of a = b = 1 and a = b = −
[Figure]
4. C LASSIFICATION
[Figure]
We now show that BHNs act as a regularizer, outperforming dropout and traditional mean ﬁeld (BbB).
Results are presented in Table 1.
In our experiments, we ﬁnd that
BHNs perform on par with dropout on full datasets of
MNIST and CIFAR10; furthermore, increasing the ﬂexibility of the posterior by adding more coupling layers improves performance, especially compared with models with 0 coupling layers, which cannot model dependencies between the parameters.
We also evaluate on a subset of
MNIST (the ﬁrst 5,000 examples); results are presented in the last two columns of Table 1.
Replicating these experiments (with 8 coupling layers) for 10 trials yields Figure 3.
In these MNIST experiments, we use MLPs with 2 hidden layers of 800 or 1200 hidden units each.
For CIFAR10, we train a convolutional neural net (CNN) with 4 hidden layers of [64 , 64 , 128 , 128] channels, 2 × 2 max pooling after the second and the fourth layers, ﬁlter size of 3 , and a single fully connected layer of 512 units.
4. A CTIVE L EARNING
We now turn to active learning, where we compare to the MNIST experiments of Gal et al.
(2017), replicating their architecture and training procedure.
Brieﬂy, they use an initial dataset of 20 examples (2 from each class), and acquire 10 new examples at a time, training for 50 epochs between each acquisition.
While Gal et al.
(2017) re-initialize the network after every acquisition, we found that “warm-starting” from the current learned parameters was essential for good performance with
BHNs, although it is likely that longer training or better initialization schemes could perform the same role.
Overall, warm-started BHNs suffered at the beginning of training, but outperformed all other methods for moderate to large numbers of acquisitions.
[Table]
4. A NOMALY D ETECTION
For anomaly detection, we take Hendrycks & Gimpel (2016) as a starting point, and perform the same suite of MNIST experiments, evaluating the ability of networks to determine whether an input came from their training distribution (“Out of distribution detection”).
Hendrycks & Gimpel (2016) found that the conﬁdence expressed in the softmax probabilities of a (non-Bayesian) DNN trained on a single dataset provides a good signal for both of these detection problems.
We demonstrate that
Bayesian DNNs outperform their non-Bayesian counterparts.
[Table]
Just as in active learning
[Table]
in anomaly detection
[Table]
we use MC to estimate the predictive posterior
[Table]
and use this to score datapoints.
For active learning, we would generally like to acquire points where there is higher uncertainty.
In a well-calibrated model, these points are also likely to be challenging or anomalous examples
[Table]
and thus acquisition functions from the active learning literature are good candidates for scoring anomalies.
We consider all of the acquisition functions listed in (Gal et al., 2017) as possible scores for the
Area Under the Curve (AUC) of Precision-Recall (PR) and Receiver Operating Characteristic (ROC) metrics, but found that the maximum conﬁdence of the softmax probabilities (i
[Table]
e., “variation ratio”) acquisition function used by Hendrycks & Gimpel (2016) gave the best performance.
Both BHN and
MCdropout achieve signiﬁcant performance gains over the non-Bayesian baseline, and MCdropout performs signiﬁcantly better than BHN in this task.
Results are presented in Table 2.
Second, we follow the same experimental setup, using all the acquisition functions, and exclude one class in the training set of MNIST at a time.
We take the excluded class of the training data as out-of-distribution samples.
The result is presented in Table 3 (Appendix).
This experiment shows the beneﬁt of using scores that reﬂect dispersion in the posterior samples (such as mean standard deviation and BALD value) in Bayesian DNNs.
4. A DVERSARY D ETECTION
Finally, we consider this same anomaly detection procedure as a novel tool for detecting adversarial examples.
Our setup is similar to Li & Gal (2017) and Louizos & Welling (2017), where it is shown that when more perturbation is added to the data, model uncertainty increases and then drops.
We use the Fast Gradient Sign method (FGS)
(Goodfellow et al., 2014b) for adversarial attack, and use one sample of our model to estimate the gradient.
9 We ﬁnd that, compared with dropout, BHNs are less conﬁdent on data points which are far from the data manifold.
In particular, BHNs constructed with IAF consistently outperform RealNVP-BHNs and dropout in detecting adversarial examples and errors.
Results are shown in Figure 5.
C ONCLUSIONS
We introduce Bayesian hypernets (BHNs), a new method for variational Bayesian deep learning which uses an invertible hypernetwork as a generative model of parameters.
BHNs feature efﬁcient training and sampling, and can express complicated multimodal distributions, thereby addressing issues of overconﬁdence present in simpler variational approximations.
We present a method of parametrizing BHNs which allows them to scale successfully to real world tasks, and show that
BHNs can offer signiﬁcant beneﬁts over simpler methods for Bayesian deep learning.
Future work could explore other methods of parametrizing BHNs, for instance using the same hypernet to output different subsets of the primary net parameters.
[Figure]
A A DDITIONAL R ESULTS
A.
L
A. U NSEEN MODE DETECTION
We replicate the experiments of anomaly detection with unseen classes of MNIST.
[Table]
A. S TRONGER ATTACK
Here we use 32 samples to estimate the gradient direction with respect to the input.
A better estimate of gradient amounts to a stronger attack, so accuracy drops lower for a given step size while an adversarial example can be more easily detected with a more informative uncertainty measure
[Figure]