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 , , and .
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"]
- 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.
- Average the weights. The SWA mean is . 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.
- Track the diagonal variance. Keep a running mean of the squared weights, here . The diagonal variance is . Check: the variance is positive because the iterates spread out.
- Track the low-rank part. For the last 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.
- Form the Gaussian. The paper's posterior is a Gaussian centred on with covariance . In the one-weight example, the diagonal-only version (SWAG-Diagonal, which omits the half) is a Gaussian with mean and variance . Check: the spread matches the width of the iterates.
- Sample and predict. Draw a weight from that Gaussian. With a standard normal draw , the sample is . Run the network with that weight, updating its batch-normalisation statistics first if the network uses them. Repeat for samples and average the predicted probabilities. For example, three samples might give a probability of "cat" of , and . The average is , and the spread from to is the model's own uncertainty about this image. Check: the average is a probability, because it averages probabilities.
- SWAG-Diagonal posterior, mean 2.5, variance 1.25
The math
Let be the network weights after epoch of training, for .
Step 2 in symbols: the mean
The SWA solution is the average of the iterates:
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, , with the square taken elementwise. The diagonal covariance is
This is the identity applied to each weight separately. For the tiny example, . 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 , where is the running mean after iterates, for the last epochs. Collect them as the columns of a matrix . Then
This is a [[low-rank-matrix|rank-]] approximation to the sample covariance of the iterates. The full sample covariance has rank , and is a hyperparameter that trades memory for fidelity.
Step 5 in symbols: the posterior and its sample
The approximate posterior is
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:
Check: the covariance of the two noise terms adds to , which is the covariance of . Here is the number of weights, so the diagonal term costs and the low-rank term .
Step 6 in symbols: the prediction
Bayesian model averaging replaces the single weight vector by an average over the posterior:
where is the training data, a test input and 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 percent accuracy but NLL , worse than one SWAG model at . Five SGD solutions reached , competitive with one SWAG model, which the paper notes trains with about one fifth of the computation. Three SWAG models gave . For the arithmetic: the five-model SGD ensemble is better than one SWAG model, about percent lower NLL, and the three-model SWAG ensemble is better, about 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 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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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 deviations of the iterates from their running mean. The posterior uses half of their sum.
QuestionComputation: a single weight has SWA solution and diagonal variance . Using SWAG-Diagonal without the half factor, what is the sample at ?Show answer
The standard deviation is . The sample is .
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 and , 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.