Search

Search papers and lessons

A Simple Baseline for Bayesian Uncertainty in Deep Learning

Wesley Maddox, Timur Garipov, Pavel Izmailov et al. · 2019

SWAG fits a Gaussian to the weights a network visits late in SGD training at a constant learning rate, then averages predictions over samples from it to get calibrated uncertainty at almost no extra cost.

On this page

  • Colour = topic mix
  • Linear algebra
  • Probability
  • Discrete math
  • Calculus
  • Neural network basics
  • Inference
  • ReadReady to readNot yet

TL;DR

SWAG (SWA-Gaussian) gives a neural network calibrated uncertainty by treating its training run as a sample of plausible weights. It takes the mean of the weights the network visits late in a stochastic gradient descent (SGD) run at a constant learning rate, as stochastic weight averaging does, and adds a Gaussian whose covariance is estimated from the same iterates. Predictions are then averaged over weights sampled from that Gaussian, which is Bayesian model averaging. Across image classification, out-of-domain detection and transfer tasks, the paper reports predictions that are comparable to or better than dropout, temperature scaling and several other methods, at close to the cost of a single training run.

Builds on: Stochastic Weight Averaging, Posterior Distribution, Bayesian Model Averaging · Leads to: On Calibration of Modern Neural Networks (the temperature-scaling baseline it is measured against)

Why it mattered

Bayesian methods were the state of the art for neural networks in the late 1990s, but they struggled to scale to modern networks with millions of weights, and they were sensitive to their settings. Most deep networks give overconfident predictions, which is a problem wherever a costly mistake matters, such as medical diagnosis or autonomous driving; the paper's introduction names both. SWAG offered a Bayesian-style answer that reuses a standard training run, needs no change to the training procedure when SGD with weight decay is used, and ships with PyTorch code.

The problem

A network trained by maximum likelihood gives one set of weights and one prediction. That prediction carries no information about how sure the network should be. The Bayesian answer is to keep a distribution over the weights, the posterior, and average predictions over it. Exact posteriors over millions of weights are out of reach, so every practical method approximates them. The older approximations were:

  • Markov chain Monte Carlo methods such as Hamiltonian Monte Carlo, which need full gradients, and stochastic-gradient versions such as SGLD, which need tuning and are hard to get right at finite step sizes.
  • Variational methods, which fit a Gaussian to the weights by optimising a bound. They work well on moderate networks but are hard to train on large residual networks, as the paper notes.
  • Dropout at test time, which averages random forward passes. It is cheap, and the paper treats it as an approximate variational method that it compares against.
  • Laplace approximations, which fit a Gaussian at a maximum a posteriori solution using curvature. They need a Hessian or Fisher approximation that is expensive for deep networks.

The paper asks whether the SGD trajectory itself contains enough information to fit a useful Gaussian.

How it works

Take a tiny example with one weight, whose iterates after four epochs of SGD are θ1=1\theta_1 = 1, θ2=2\theta_2 = 2, θ3=3\theta_3 = 3 and θ4=4\theta_4 = 4.

flowchart LR
  A["Constant-rate SGD run"] --> B["Running mean of weights: SWA solution"]
  A --> C["Running mean of squared weights: diagonal variance"]
  A --> D["Last K deviations from the running mean: low-rank part"]
  B --> E["Gaussian posterior over weights"]
  C --> E
  D --> E
  E --> F["Sample S weight vectors"]
  F --> G["Predict with each sample, then average"]
  1. Run SGD at a constant learning rate. The paper keeps the learning rate high, so the iterates keep exploring the set of good solutions rather than settling on one point. Check: four iterates for our one weight.
  2. Average the weights. The SWA mean is θSWA=(1+2+3+4)/4=2.5\theta_{\text{SWA}} = (1 + 2 + 3 + 4)/4 = 2.5. This is the centre of the Gaussian, and it is also the model that SWA would deploy. Check: the mean lies between the smallest and largest iterate.
  3. Track the diagonal variance. Keep a running mean of the squared weights, here (1+4+9+16)/4=7.5(1 + 4 + 9 + 16)/4 = 7.5. The diagonal variance is 7.5−2.52=1.257.5 - 2.5^2 = 1.25. Check: the variance is positive because the iterates spread out.
  4. Track the low-rank part. For the last KK epochs, store each deviation of the iterate from the running mean. These deviations span a low-dimensional subspace where the iterates actually moved. In the one-weight example there is only one direction, so this step adds nothing extra.
  5. Form the Gaussian. The paper's posterior is a Gaussian centred on θSWA\theta_{\text{SWA}} with covariance 12(Σdiag+Σlow-rank)\tfrac{1}{2}(\Sigma_{\text{diag}} + \Sigma_{\text{low-rank}}). In the one-weight example, the diagonal-only version (SWAG-Diagonal, which omits the half) is a Gaussian with mean 2.52.5 and variance 1.251.25. Check: the spread matches the width of the iterates.
  6. Sample and predict. Draw a weight from that Gaussian. With a standard normal draw z=1z = 1, the sample is θ=2.5+1.25×1≈3.62\theta = 2.5 + \sqrt{1.25} \times 1 \approx 3.62. Run the network with that weight, updating its batch-normalisation statistics first if the network uses them. Repeat for SS samples and average the predicted probabilities. For example, three samples might give a probability of "cat" of 0.90.9, 0.70.7 and 0.80.8. The average is 2.4/3=0.82.4 / 3 = 0.8, and the spread from 0.70.7 to 0.90.9 is the model's own uncertainty about this image. Check: the average is a probability, because it averages probabilities.
012345600.10.20.30.40.5weight valuedensity
  • SWAG-Diagonal posterior, mean 2.5, variance 1.25
The Gaussian is centred on the SWA solution, and its width reflects how far the SGD iterates spread. The marked points are the iterates 1 and 4, and the centre 2.5.

The math

Let θi\theta_i be the network weights after epoch ii of training, for i=1,…,Ti = 1, \dots, T.

Step 2 in symbols: the mean

The SWA solution is the average of the iterates:

θSWA=1T∑i=1Tθi.\theta_{\text{SWA}} = \frac{1}{T}\sum_{i=1}^{T} \theta_i.

The paper reads this as an estimate of the mean of the stationary distribution of SGD iterates, which is why it can serve as a Gaussian centre.

Step 3 in symbols: the diagonal covariance

Keep the running mean of the squared weights, θ2‾=1T∑iθi2\overline{\theta^{2}} = \frac{1}{T}\sum_i \theta_i^2, with the square taken elementwise. The diagonal covariance is

Σdiag=diag⁡ ⁣(θ2‾−θSWA2).\Sigma_{\text{diag}} = \operatorname{diag}\!\left(\overline{\theta^{2}} - \theta_{\text{SWA}}^{2}\right).

This is the identity Var⁡(θ)=E[θ2]−(Eθ)2\operatorname{Var}(\theta) = \mathbb{E}[\theta^2] - (\mathbb{E}\theta)^2 applied to each weight separately. For the tiny example, 7.5−2.52=1.257.5 - 2.5^2 = 1.25. It needs two extra copies of the weights, which need not live on the GPU.

Step 4 in symbols: the low-rank covariance

A full covariance over millions of weights is too large to store, so the paper keeps the deviations Di=θi−θˉiD_i = \theta_i - \bar{\theta}_i, where θˉi\bar{\theta}_i is the running mean after ii iterates, for the last KK epochs. Collect them as the columns of a matrix D^\widehat{D}. Then

Σlow-rank=1K−1 D^ D^⊤.\Sigma_{\text{low-rank}} = \frac{1}{K-1}\,\widehat{D}\,\widehat{D}^{\top}.

This is a [[low-rank-matrix|rank-KK]] approximation to the sample covariance of the iterates. The full sample covariance has rank TT, and KK is a hyperparameter that trades memory for fidelity.

Step 5 in symbols: the posterior and its sample

The approximate posterior is

q(θ)=N ⁣(θSWA, 12(Σdiag+Σlow-rank)).q(\theta) = \mathcal{N}\!\left(\theta_{\text{SWA}},\ \tfrac{1}{2}\left(\Sigma_{\text{diag}} + \Sigma_{\text{low-rank}}\right)\right).

The half appears because both terms already contain the spread of the weights, so averaging them keeps the scale right. A sample from this multivariate Gaussian can be drawn without forming the covariance:

θ~=θSWA+12 Σdiag1/2z1+12(K−1) D^ z2,z1∼N(0,Id),z2∼N(0,IK).\tilde{\theta} = \theta_{\text{SWA}} + \frac{1}{\sqrt{2}}\,\Sigma_{\text{diag}}^{1/2} z_1 + \frac{1}{\sqrt{2(K-1)}}\,\widehat{D}\, z_2, \qquad z_1 \sim \mathcal{N}(0, I_d),\quad z_2 \sim \mathcal{N}(0, I_K).

Check: the covariance of the two noise terms adds to 12Σdiag+12(K−1)D^D^⊤\tfrac{1}{2}\Sigma_{\text{diag}} + \tfrac{1}{2(K-1)}\widehat{D}\widehat{D}^{\top}, which is the covariance of qq. Here dd is the number of weights, so the diagonal term costs O(d)\mathcal{O}(d) and the low-rank term O(Kd)\mathcal{O}(Kd).

Step 6 in symbols: the prediction

Bayesian model averaging replaces the single weight vector by an average over the posterior:

p(y∗∣D,x∗)=∫p(y∗∣θ,x∗) p(θ∣D) dθ≈1S∑s=1Sp(y∗∣θ~s,x∗),p(y_\ast \mid \mathcal{D}, x_\ast) = \int p(y_\ast \mid \theta, x_\ast)\, p(\theta \mid \mathcal{D})\, d\theta \approx \frac{1}{S}\sum_{s=1}^{S} p(y_\ast \mid \tilde{\theta}_s, x_\ast),

where D\mathcal{D} is the training data, x∗x_\ast a test input and y∗y_\ast its label. The integral is approximated by the sample average, and each term is an ordinary forward pass with one sampled weight vector.

Results

All numbers are the paper's. Figure 2 reports mean and standard deviation over three runs.

Calibration and likelihood on image classification. On CIFAR-10, CIFAR-100 and ImageNet, SWAG and SWAG-Diagonal performed comparably to or better than standard SGD, SWA, MC-Dropout, temperature scaling, SGLD and K-FAC Laplace on every task tested, with SWAG the best overall. Temperature scaling applied to SWA was a competitive baseline on the non-transfer tasks, but it needs a validation set to fit its temperature. The reliability diagrams show SWAG and SWAG-Diagonal well calibrated, and the low-rank version better calibrated than the diagonal one.

Comparison with ensembles. Negative log-likelihood (NLL) is lower-is-better. On PreResNet-164 for CIFAR-100, three ordinary SGD solutions reached 82.182.1 percent accuracy but NLL 0.69220.6922, worse than one SWAG model at 0.65950.6595. Five SGD solutions reached 0.64780.6478, competitive with one SWAG model, which the paper notes trains with about one fifth of the computation. Three SWAG models gave 0.61780.6178. For the arithmetic: the five-model SGD ensemble is 0.6595−0.6478=0.01170.6595 - 0.6478 = 0.0117 better than one SWAG model, about 1.81.8 percent lower NLL, and the three-model SWAG ensemble is 0.04170.0417 better, about 6.36.3 percent lower. The paper also reports that SWAG had higher NLL than ensembles of the SGD iterates on VGG-16, but much lower NLL on the larger PreResNet-164 and WideResNet-28x10.

Out-of-domain detection. A WideResNet trained on five CIFAR-10 classes was tested on the full set. SWAG and MC-Dropout gave the best separation of in-domain and out-of-domain predictive entropy, measured by symmetrised KL divergence between binned distributions (the paper's Table 2).

Transfer. Models trained on CIFAR-10 and tested on STL-10 showed the largest gains. The paper reports SWAG significantly outperforms temperature scaling there, where the target data come from a different distribution.

Language modelling. On Penn Treebank and WikiText-2 with LSTMs, SWAG substantially improved test perplexity over the SWA solution.

Limits and common misreadings. It is tempting to think a Gaussian around the SWA mean is the posterior. In fact it is an approximation whose quality the paper tests. Its own analysis finds the SGD trajectory lies in a low-dimensional subspace, so the variance is captured well along the directions the iterates moved and may be underestimated along the rest. It is tempting to think more stored iterates always means better uncertainty. In fact KK is a memory budget as well as an accuracy knob, because each stored deviation is as large as the network. It is tempting to think SWAG is just averaging. In fact the averaging gives the centre, and the uncertainty comes from the covariance and the sampling; without sampling you have SWA, which the paper treats as a separate baseline. And it is tempting to think the method works with any optimiser. In fact the paper's interpretation is for SGD with weight decay, which gives an implicit Gaussian-like prior on the weights; it notes that Adam may also work but leaves that to future work.

The paper's own analysis is the most important limit. The theory connecting the SGD stationary distribution to the posterior fails for deep networks, as the paper shows in its appendix, so the method is justified empirically rather than by that theory. SWAG-Diagonal has almost no variance along the eigen-directions of the SWAG covariance, and the authors expect SWAG to underestimate variance along random directions in weight space. The experiments use constant-rate SGD on specific architectures and datasets, and the sampling cost grows with the number of samples.

When to use it. Use SWAG when you need calibrated uncertainty from a network you already train with SGD, when you cannot afford a deep ensemble, and when you can accept some extra test-time cost for the samples. It also suits transfer, where the paper reports the largest gains. Avoid it when the network must give a single fast prediction, unless the samples are cached. And when you have a validation set and only need a better-calibrated single probability, temperature scaling is cheaper and often enough.

Reading guide

  1. Abstract and Section 1, Introduction. The claim and the motivation, including the old Bayesian methods and why they stopped scaling. Read with Posterior Distribution and Bayesian Neural Network in mind.
  2. Section 2, Related work. A map of the alternatives: Markov Chain Monte Carlo methods, dropout as in Dropout as a Bayesian Approximation, Laplace approximations that use Fisher Information, and Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles. Read this section for the list of baselines, not for the detail.
  3. Sections 3.1 and 3.2, SGD and SWA. The update rule and the averaging idea from Stochastic Gradient Descent and Stochastic Weight Averaging. Note the role of the constant learning rate.
  4. Sections 3.3 to 3.5, SWAG. The core method. Read Algorithm 1 closely, then the sampling identity. The prior discussion in 3.5 links the implicit regularisation of weight decay to the Gaussian prior, and the test-time procedure updates Batch Normalization statistics.
  5. Section 4, Does the SGD trajectory capture loss geometry? The analysis of Figure 1. It uses randomised SVD, described in Finding Structure with Randomness: Randomized Matrix Decompositions, and the covariance ideas in Covariance and Low-Rank Matrix.
  6. Section 5, Experiments. Figures 2 and 3 carry the calibration results, and the ensemble comparison in Section 5.2 is the clearest test of the claim. Read the transfer and out-of-domain sections for the robustness argument.

Check yourself

QuestionRecall: what are the two parts of the SWAG covariance, and what does the paper use as the Gaussian's centre?Show answer

The centre is the SWA solution, the mean of the SGD iterates. The covariance has two parts: a diagonal part from the running mean of squared weights minus the squared mean, and a low-rank part from the last KK deviations of the iterates from their running mean. The posterior uses half of their sum.

QuestionComputation: a single weight has SWA solution θSWA=1\theta_{\text{SWA}} = 1 and diagonal variance 0.360.36. Using SWAG-Diagonal without the half factor, what is the sample at z=2z = 2?Show answer

The standard deviation is 0.36=0.6\sqrt{0.36} = 0.6. The sample is 1+0.6×2=2.21 + 0.6 \times 2 = 2.2.

QuestionWhy: why does the paper combine the diagonal and low-rank parts with a factor of one half, rather than adding them?Show answer

Both parts already contain the variance of the weights, so adding them would double the spread. Multiplying the sum by one half gives a Gaussian whose covariance has the scale of the iterates' spread. The sampling identity shows this directly: the two noise terms carry factors of 1/21/\sqrt{2} and 1/2(K−1)1/\sqrt{2(K-1)}, so their covariances add to half the sum.

QuestionApplied: you train a large network with Adam, not SGD, and want SWAG-style uncertainty. What does the paper suggest about whether the method transfers, and what would you check first?Show answer

The paper derives its interpretation for SGD with weight decay, and says Adam and other stochastic methods may also work but leaves that for future work. You should not assume the Gaussian is a valid posterior for Adam. Check first whether the spread of the iterates is meaningful, by comparing the SWAG predictive distribution against held-out calibration and a deep ensemble on a validation set, rather than relying on the paper's results.

Sources

Read the full paper

Wesley Maddox, Timur Garipov, Pavel Izmailov et al., 2019. arXiv:1902.02476