Foundations to Frontier
Tests

SWA and SWAG

Stochastic weight averaging (SWA; Izmailov et al., 2018) keeps training with a constant or cyclic learning rate after convergence and averages the weights it visits. The average lies nearer the centre of a wide low-loss region and often generalises better than the last iterate. SWAG (Maddox et al., 2019) also records the iterates' spread. It fits a Gaussian with the SWA mean and a diagonal-plus-low-rank covariance built from the same snapshots, then samples weights from it for Bayesian model averaging. The cost is one training run plus a few stored vectors. Its uncertainty describes only one basin, and its covariance comes from SGD noise, so it depends on the learning rate. MultiSWAG (Wilson and Izmailov, 2020) combines several runs. This page covers SWA, the SWAG Gaussian, the link between SGD noise and posterior width, and practical recipes. In the exercises you implement running moments and SWAG sampling. You then compare SGD, SWA, SWAG-diagonal, SWAG and MultiSWAG on a 91-parameter network. SWA improved the in-distribution NLL (−0.71 → −0.75). Extrapolating, each step helped: NLL 7.6 (SGD), 7.3 (SWA), 7.0 (diagonal), 5.7 (SWAG), 2.0 (MultiSWAG with 4 runs). A plain ensemble of the 4 final SGD iterates scored 1.3. With a SWAG learning rate of 0.01 instead of 0.05, its spread far away shrank from 0.05 to 0.01.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Let SGD wander, then average

With a fixed learning rate, SGD never settles exactly: noisy gradients make the weights jitter around the bottom of the valley. SWA averages the weights along this jitter, which lands near the centre of the valley, usually a better place than any single point. SWAG goes one step further: the size and shape of the jitter become a bell curve over weights, giving uncertainty almost for free. The demo shows SGD iterates on a simple valley: the dots, their average and their spread. Raise the learning rate and the spread grows.

Bayesian deep learning lab
SGD with learning rate 0.1 and noisy gradients on a loss with curvatures 1 and 6 (grey contours). Dots: iterates; big dot: their mean (SWA); ellipse: their 2-std covariance (SWAG), std 0.22 and 0.13. Raise the learning rate and the ellipse grows: SWAG's covariance reflects the optimiser, not only the posterior.
Why engineers care

SWA is a one-line addition in PyTorch (torch.optim.swa_utils) and is used to make perception and forecasting models more robust; checkpoint averaging and model soups apply the same idea to large models.

📝 Quick check (Level 0)
0/3 answered
  1. 1. SWA averages…
  2. 2. SWAG turns the spread of those weights into…
  3. 3. A higher learning rate makes the SWAG spread…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • SWA: after a normal training budget, continue with a constant or cyclic learning rate and average snapshots (one per epoch or cycle): θ_SWA = (1/T) Σ θ_t, updated as a running mean. Recompute BatchNorm statistics for the averaged weights.
  • SWAG-diagonal: also keep the running second moment; Σ_diag = θ²‾ − θ_SWA².
  • SWAG: add a low-rank part from the last K deviations D = [θ_t − θ_SWA]: Σ = ½ Σ_diag + D Dᵀ/(2(K − 1)), K ≈ 20. Sample θ = θ_SWA + (1/√2) Σ_diag^½ z₁ + D z₂/√(2(K − 1)) and average predictions over about 30 samples.
  • Why SGD iterates resemble a posterior: constant-rate SGD is a stochastic process whose stationary distribution around a minimum is Gaussian, with covariance set by the learning rate, batch size and gradient noise (Mandt, Hoffman and Blei, 2017). With the right rate it approximates the posterior; in general it is only proportional to it.
  • MultiSWAG: run SWAG from several initialisations and mix the Gaussians, combining local spread with multiple modes (Wilson and Izmailov, 2020).
  • Relatives: exponential moving averages of weights, checkpoint averaging and model soups (Wortsman et al., 2022) use the same flatness idea; mode connectivity (Garipov et al., 2018) explains why averages stay in low loss.
📝 Quick check (Level 1)
0/3 answered
  1. 1. SWAG's covariance has a diagonal part and…
  2. 2. After SWA you must recompute…
  3. 3. MultiSWAG combines…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

SWA and SWAG in practice

Exercise 1.

  • Running first and second moments of the snapshots.
  • One SWAG sample (diagonal plus low rank).
  • The covariance SWAG samples have.

Practice.

  • Train normally, then run 10–25% more epochs at a constant (or cyclic) learning rate, taking one snapshot per epoch.
  • Use torch.optim.swa_utils: AveragedModel for the mean, SWALR for the schedule, update_bn afterwards.
  • For SWAG keep K = 20 deviations; draw about 30 samples, update BatchNorm for each, average the predictions.
  • Tune the SWAG learning rate and a covariance scale on validation NLL: the spread is set by the optimiser.
  • If uncertainty under shift matters most, use MultiSWAG or an ensemble; one SWAG Gaussian covers one basin.
import torch
from torch.optim.swa_utils import AveragedModel, SWALR, update_bn
swa_model = AveragedModel(model); swa_sched = SWALR(opt, swa_lr=0.05)
for epoch in range(epochs):
    train_one_epoch(model, opt, loader)
    if epoch >= swa_start:
        swa_model.update_parameters(model); swa_sched.step()     # running mean of the weights
    else:
        sched.step()
update_bn(loader, swa_model)                                     # BatchNorm statistics for the averaged weights
# SWAG: also keep running means of squared weights and the last K deviations (e.g. the swag package or your own)
🐍 Exercise 1: SWA moments and SWAG samples
Update running moments of weight snapshots and draw samples from the SWAG Gaussian.
📝 Quick check (Level 2)
0/3 answered
  1. 1. PyTorch's helper for averaging weights:
  2. 2. Typical number of SWAG deviation columns K:
  3. 3. SWAG's covariance scale should be tuned on…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

SGD as a sampler. Near a minimum, L(θ) ≈ ½ θᵀAθ. With minibatch gradient noise of covariance C, SGD θ ← θ − η(Aθ + ξ) is a linear stochastic recursion whose stationary covariance S solves S = (I − ηA) S (I − ηA)ᵀ + η² C. For small η, AS + SA ≈ ηC (Mandt et al., 2017). In one dimension, S = η g²/(a(2 − ηa)) ≈ η g²/(2a): proportional to the learning rate and inversely proportional to the curvature, like a posterior’s 1/a but with an optimiser-dependent scale.

Why averaging helps. The iterates scatter around the minimum along flat directions; their average sits at the centre of the low-loss region, which tends to generalise better than an edge point (the flat-minima argument). For SWA to work, the averaged weights must be in the same basin, which mode connectivity makes plausible.

What SWAG misses. Its Gaussian covers one basin’s local geometry; functionally different modes are invisible to it. It inherits the scale of SGD noise, so too small a learning rate gives near-zero uncertainty and too large a rate leaves the basin. The low-rank part captures the main directions of iterate motion, which is why it beats the diagonal.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The stationary variance of constant-rate SGD is roughly proportional to…
  2. 2. SWAG cannot represent…
  3. 3. SWA helps because the average lies…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much do SWA, SWAG and MultiSWAG improve on SGD, and how much does the learning rate matter?

History.

  • P. Izmailov, D. Podoprikhin, T. Garipov, D. Vetrov, A. G. Wilson, “Averaging weights leads to wider optima and better generalization” (SWA, 2018).
  • S. Mandt, M. Hoffman, D. Blei, “Stochastic gradient descent as approximate Bayesian inference” (2017).
  • W. Maddox, T. Garipov, P. Izmailov, D. Vetrov, A. G. Wilson, “A simple baseline for Bayesian uncertainty in deep learning” (SWAG, 2019).
  • A. G. Wilson, P. Izmailov, “Bayesian deep learning and a probabilistic perspective of generalization” (MultiSWAG, 2020).

Exercise 2. 1-30-1 tanh network (91 weights), MSE + weight decay 10⁻³, minibatch SGD (batch 4) at learning rate 0.05 for 400 epochs, then 60 epochs at the SWAG rate (0.05, or 0.01) with one snapshot per epoch, K = 10. SWAG predictive from 100 samples; MultiSWAG mixes 25 samples from each of 4 runs. Same data and test sets as the ensembles page (40 points with a gap; extrapolation to x in 1.2–2).

method NLL in distribution NLL extrapolating std far
SGD (last iterate) −0.71 7.60 0
SWA −0.75 7.32 0
SWAG-diagonal −0.75 6.95 0.02
SWAG −0.75 5.72 0.05
MultiSWAG, 4 runs −0.76 2.04 0.12
ensemble of 4 SGD runs −0.79 1.30 0.17
SWAG at rate 0.01 −0.67 8.47 0.01
  • SWA beat the last SGD iterate in distribution on all three seeds (−0.75 vs −0.71; −0.51 vs −0.23; −0.79 vs −0.70).
  • Under extrapolation each refinement helped, in the same order on every seed: SGD worse than SWA, then diagonal, then SWAG, then MultiSWAG.
  • One SWAG Gaussian stayed badly overconfident (std 0.05 far away); most of the gain comes from multiple runs.
  • MultiSWAG vs ensemble: the plain ensemble was better on seeds 0 and 1 (1.30 vs 2.04; 1.32 vs 1.48), MultiSWAG on seed 2 (1.40 vs 1.88).
  • Learning-rate dependence: at rate 0.01 the spread was several times smaller (0.01 vs 0.05 far away; 0.008 vs 0.098 on seed 1) and the extrapolation NLL (8.47) worse than plain SWA’s. That run also started from a different initialisation, so part of the difference is the run itself.
  • Seeds 1 and 2: extrapolation NLL SGD 11.5 and 5.19, SWAG 4.15 and 3.21, MultiSWAG 1.48 and 1.40.
🐍 Exercise 2 (research): how much do SWA, SWAG and MultiSWAG improve on SGD, and how much does the learning rate matter?
Run SGD with weight averaging, build SWAG and MultiSWAG predictives, and compare them with SGD and a small ensemble.

SWA and SWAG in AI, robotics and aerospace

  • Robust perception: SWA and EMA weights are common defaults in detection and segmentation training recipes, improving robustness to new conditions.
  • Weather and forecasting models: checkpoint averaging and SWA smooth out late-training noise in large forecasting models.
  • Cheap uncertainty for control: SWAG adds a posterior to a policy or dynamics model at the cost of a few extra epochs and stored vectors.

References

  1. P. Izmailov et al. (2018). “Averaging weights leads to wider optima and better generalization.” UAI.
  2. W. J. Maddox et al. (2019). “A simple baseline for Bayesian uncertainty in deep learning.” NeurIPS.
  3. S. Mandt, M. D. Hoffman, D. M. Blei (2017). “Stochastic gradient descent as approximate Bayesian inference.” JMLR.
  4. A. G. Wilson, P. Izmailov (2020). “Bayesian deep learning and a probabilistic perspective of generalization.” NeurIPS.
  5. M. Wortsman et al. (2022). “Model soups: averaging weights of multiple fine-tuned models improves accuracy without increasing inference time.” ICML.