TL;DR
Training a neural network with stochastic gradient descent gives a sequence of weight settings, and the last one is usually not the best one. Stochastic weight averaging (SWA) takes the average of many of those settings, collected late in training, and uses that average as the final model. The average tends to sit in a wider, flatter valley of the loss, so the model makes fewer mistakes on data it has not seen. Only one extra copy of the weights is needed.
Builds on: Stochastic Gradient Descent, Batch Normalization · Leads to: A Simple Baseline for Bayesian Uncertainty in Deep Learning, Ensemble Learning
Where it's used
Image classifiers trained once. The paper that introduced SWA (Izmailov and colleagues, 2018) trained image classifiers on the CIFAR-10 and CIFAR-100 benchmarks and on ImageNet. It reported better test accuracy than the usual final checkpoint, with the averaging itself adding almost no training time. The appeal is that you get the benefit of several models without training several models.
Uncertainty estimates. The SWAG method (Maddox and colleagues, 2019) starts from the same averaging idea and also tracks how much the weights spread across the late iterates. Those spreads are used as a rough picture of how uncertain the network is about its own predictions, which matters when a model's confidence has to be trusted. See A Simple Baseline for Bayesian Uncertainty in Deep Learning.
Off-the-shelf training tools. PyTorch ships SWA in its torch.optim.swa_utils module. A typical team turns it on for the last stretch of a run, lets it keep a running average of the weights, and then recomputes the batch-normalisation statistics once before evaluating. The whole change is a few lines around an existing training loop.
How it works
Take one weight, and imagine training has saved four checkpoints from the late part of the run. Their values are 1.0, 3.0, 2.0 and 4.0. Plain training would ship the last one, 4.0. SWA ships their average.
-
Pick a starting point late in training. Training runs normally until some point, often in the last quarter of the schedule, when the learning rate is still moderate. Before that point nothing changes. Check: the model is still improving, so averaging the early checkpoints would mix in weights that are far from good.
-
Keep a running average of the weights. After each checkpoint, update one stored copy: new average = (old average × number so far + new weight) ÷ (number so far + 1). Start with the first checkpoint, 1.0. Check: after the second checkpoint, (1.0 × 1 + 3.0) ÷ 2 = 2.0. The average is the midpoint of the two values so far.
-
Feed in the remaining checkpoints. The third checkpoint is 2.0: (2.0 × 2 + 2.0) ÷ 3 = 2.0. The fourth is 4.0: (2.0 × 3 + 4.0) ÷ 4 = 2.5. Check: 2.5 is the plain mean of 1.0, 3.0, 2.0 and 4.0, which is (10) ÷ 4 = 2.5. The running update and the direct mean agree.
-
Recompute the batch-normalisation statistics. A batch-normalised network keeps running estimates of the mean and variance of each layer's inputs, and those estimates were gathered while the weights were changing. The averaged weights produce different activations, so the stored statistics no longer match. Run the training data forward through the averaged network once, without any gradient steps, to re-estimate them. Check: this costs one pass of forward computation over the data, not a training epoch.
-
Use the averaged network. Evaluate it like any other model. It replaces the last checkpoint.
flowchart LR A[Normal training] --> B[Late start point] B --> C[Save weights each step] C --> D[Update running mean] D --> C D --> E[Recompute batch-norm statistics] E --> F[Averaged model]
Why does an average of wandering weights help at all? The picture below shows two minima of a loss, both at zero. The sharp one rises quickly as you move away from zero, so any small shift of the weights costs a lot. The wide one rises slowly, so the same shift costs little. The checkpoints bounce around the bottom of a valley, and their average lands near its centre. A flat minimum is one where that kind of shift barely changes the loss, and a model in a flat minimum usually behaves similarly on new data.
- sharp minimum
- wide minimum
The math
Let be the weight vectors saved at the chosen checkpoints, from a start point late in training. The SWA model is their mean
Each is a full vector of all the model's parameters, and the average is taken coordinate by coordinate.
Step 1 in symbols: collect the checkpoints
Let be the start point. The checkpoints are , saved once per epoch or once per fixed number of steps. Write for how many were saved.
Step 2 in symbols: the running update
Let be the average of the first checkpoints. When checkpoint arrives, the average becomes
The two forms are equal: multiply the first out and the terms collect into . The second form is the one to implement, since it moves the stored average a fraction of the way toward the new checkpoint.
Check with the walkthrough: , then .
Step 3 in symbols: the same average, unrolled
Repeat the update and the average is exactly the plain mean, . This is why the running version and the definition give the same model, and why only one stored vector is needed no matter how many checkpoints there are.
Step 4 in symbols: the batch-normalisation statistics
For a layer with inputs in a batch , batch normalisation uses
The network also keeps running estimates of these values for use at test time. After averaging, the activations change, so the running estimates must be recomputed on training batches with the averaged weights before evaluation.
Worked examples
Checkpoints of one weight are , and .
- The plain average is .
- Run the update. Start with .
- Add : .
- Add : .
- The two routes agree. The SWA weight is , which is the middle checkpoint here. Averaging pulled the result back from the last value, , toward the centre of the trajectory.
Four checkpoints of a two-weight model are , , and . Each coordinate is averaged separately.
- First coordinates: , and .
- Second coordinates: , and .
- The SWA model is .
- Run the update to be sure. Start with .
- Add : .
- Add : .
- Add : .
- The running version reaches as well. The SWA answer is , which here happens to equal the last checkpoint, so this small case does not show the difference that averaging makes.
A team trains a vision model with million parameters for epochs. The last epochs are the averaging window, and they save one checkpoint per epoch. Each parameter is a 32-bit float, which takes bytes.
- One copy of the model: bytes, which is MB.
- Keeping all checkpoints would need MB MB, or GB.
- The running average needs only one extra copy: MB, whatever the number of checkpoints.
- Recomputing the batch-normalisation statistics is one forward pass over the training data, which is cheaper than one epoch of training because nothing is stored for backpropagation.
- The running average uses about one fiftieth of the storage of the naive approach, and the final model has the same size and speed as before.
Try it: the same plan with million parameters and saved checkpoints. How much storage would keeping every checkpoint take, and how much does the running average take? Answer: one copy is bytes, or MB. Keeping copies takes MB MB, or GB. The running average takes one copy, MB.
Common mistakes and tradeoffs
It is tempting to think that averaging any set of trained networks gives a better network. In fact the checkpoints must come from one training run that stays in the same broad region of the loss. Averaging networks that started from different random initialisations, and so live in different regions, usually gives a broken model, because their weights do not line up. Averaging is safe along a single trajectory that is already converging.
It is tempting to think that SWA can start at any time. In fact averaging early checkpoints mixes in weights from far up the slope, which drags the result toward poor solutions. The start point is chosen late, when the model is already good and the learning rate is moderate.
It is tempting to skip the batch-normalisation step because the averaged weights look correct. In fact the stored statistics describe the old weights, so a model evaluated without recomputing them can score noticeably worse than the average deserves. One forward pass fixes it.
It is tempting to think SWA replaces an ensemble. In fact it gives one model, so inference costs the same as a single network, and it captures some of the benefit of averaging several models. A true ensemble of independently trained models often still does better on accuracy and uncertainty, at several times the training and inference cost. Use SWA when you want a single model with a small extra cost, and an ensemble when you can afford several full training runs.
Use SWA when training is already reliable, the model has a learning rate schedule that keeps it moving late in training, and you want a better single model for little extra work. Do not use it as a rescue for a run that has diverged, and do not expect it to fix a model that overfits badly; for that, see Overfitting and regularisation.
History
In the early 1990s, Boris Polyak and Anatoli Juditsky showed that averaging the iterates of a noisy gradient method such as SGD, rather than using the last one, can reach the best accuracy the method allows. The idea was known in statistics for stochastic optimisation, but it was rarely used when training neural networks. Deep learning practitioners mostly relied on the last checkpoint or on hand-picked snapshots.
In 2018, Pavel Izmailov, Dmitrii Podoprikhin, Timur Garipov, Dmitry Vetrov and Andrew Gordon Wilson showed that averaging the late SGD iterates of a neural network gives a model that generalises better than the usual final weights, and they tied the gain to the idea that the average lands in a wider region of the loss. The paper was published at the UAI 2018 conference. It caught on because the cost is almost nothing, the code is a few lines, and it works with the learning rate schedules people already used.
In 2019, the SWAG method by Wesley Maddox and colleagues built on the same iterates to estimate uncertainty, which widened interest beyond accuracy. Frameworks such as PyTorch later added the averaging as a built-in utility, which is why it now appears in ordinary training code.
Recap
- SGD produces a stream of weight settings late in training, and the last one is not reliably the best.
- SWA averages those settings with a running update, using , so only one extra copy of the weights is stored.
- The average tends to land in a wider, flatter region of the loss, which generalises better.
- Batch-normalisation statistics must be recomputed for the averaged weights before evaluation.
- Averaging works along one training trajectory, not across unrelated networks.
Read next: A Simple Baseline for Bayesian Uncertainty in Deep Learning for how the same iterates give an uncertainty estimate, and Ensemble Learning to compare a single averaged model with a set of independently trained ones.
Check yourself
QuestionWhich stored quantity does SWA need, beyond the model itself, no matter how many checkpoints it averages?Show answer
One running-average copy of the weights, the same size as the model. Each new checkpoint updates that copy, so storage does not grow with the number of checkpoints.
QuestionCheckpoints of one weight are , and . What is the SWA value, and what does the running update give after the second checkpoint?Show answer
The mean is . After the second checkpoint the running update gives , which is the average of the first two values. The third update, , confirms the mean.
QuestionWhy would you run the training data forward through an averaged network before evaluating it?Show answer
Batch normalisation stores running estimates of each layer's input mean and variance. Those estimates were gathered from the earlier weights, and the averaged weights produce different activations. Recomputing them on the averaged network makes the normalisation match the model that will be evaluated.
QuestionA colleague averages five networks, each trained from a different random seed, and gets a model that performs badly. Why?Show answer
Independently trained networks start from different random initialisations and can end up in different regions of the loss. Their weights do not correspond to one another, so their average is not a point in a good region. SWA works along one trajectory that stays in the same region.
QuestionA model with 10 million float32 parameters is averaged over 20 checkpoints. How many megabytes does the running average need, and how many would keeping every checkpoint take?Show answer
One copy is bytes, or MB, which is what the running average needs. Keeping all checkpoints takes MB.
Sources
- Izmailov, Podoprikhin, Garipov, Vetrov, Wilson (2018), "Averaging Weights Leads to Wider Optima and Better Generalization": https://arxiv.org/abs/1803.05407
- Maddox, Garipov, Izmailov, Vetrov, Wilson (2019), "A Simple Baseline for Bayesian Uncertainty in Deep Learning": https://arxiv.org/abs/1902.02476