Search

Search papers and lessons

Stochastic Weight Averaging

Level 3 · 14 min read

Stochastic weight averaging keeps a running mean of the weights a model passes through late in training and uses it as the final model, often generalising better than any single checkpoint at almost no cost.

On this page

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

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.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

−1.5−1−0.500.511.502468weight shift from the minimumloss
  • sharp minimum
  • wide minimum
Both minima sit at zero. Moving the weights by the same amount costs far more loss in the sharp valley than in the wide one.

The math

Definition: Stochastic weight averaging

Let w1,w2,…,wTw_1, w_2, \dots, w_T be the weight vectors saved at the chosen checkpoints, from a start point late in training. The SWA model is their mean

wˉ=1T∑t=1Twt.\bar{w} = \frac{1}{T}\sum_{t=1}^{T} w_t .

Each wtw_t 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 t0t_0 be the start point. The checkpoints are wt0,wt0+1,…w_{t_0}, w_{t_0+1}, \dots, saved once per epoch or once per fixed number of steps. Write TT for how many were saved.

Step 2 in symbols: the running update

Let wˉn\bar{w}_n be the average of the first nn checkpoints. When checkpoint n+1n+1 arrives, the average becomes

wˉn+1=n wˉn+wn+1n+1=wˉn+wn+1−wˉnn+1.\bar{w}_{n+1} = \frac{n\,\bar{w}_n + w_{n+1}}{n+1} = \bar{w}_n + \frac{w_{n+1} - \bar{w}_n}{n+1}.

The two forms are equal: multiply the first out and the wˉn\bar{w}_n terms collect into (n+1)wˉn+1=nwˉn+wn+1(n+1)\bar{w}_{n+1} = n\bar{w}_n + w_{n+1}. The second form is the one to implement, since it moves the stored average a fraction 1n+1\frac{1}{n+1} of the way toward the new checkpoint.

Check with the walkthrough: wˉ1=1.0\bar{w}_1 = 1.0, then wˉ2=1.0+3.0−1.02=2.0\bar{w}_2 = 1.0 + \frac{3.0 - 1.0}{2} = 2.0.

Step 3 in symbols: the same average, unrolled

Repeat the update and the average is exactly the plain mean, wˉT=1T∑t=1Twt\bar{w}_T = \frac{1}{T}\sum_{t=1}^{T} w_t. 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 xx in a batch BB, batch normalisation uses

μB=1∣B∣∑x∈Bx,σB2=1∣B∣∑x∈B(x−μB)2.\mu_B = \frac{1}{|B|}\sum_{x \in B} x, \qquad \sigma_B^2 = \frac{1}{|B|}\sum_{x \in B}(x - \mu_B)^2 .

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 wˉ\bar{w} before evaluation.

Worked examples

Example
1. A single weight, three checkpoints

Checkpoints of one weight are 22, 44 and 66.

  1. The plain average is (2+4+6)÷3=12÷3=4(2 + 4 + 6) \div 3 = 12 \div 3 = 4.
  2. Run the update. Start with wˉ1=2\bar{w}_1 = 2.
  3. Add w2=4w_2 = 4: wˉ2=(1×2+4)÷2=3\bar{w}_2 = (1 \times 2 + 4) \div 2 = 3.
  4. Add w3=6w_3 = 6: wˉ3=(2×3+6)÷3=12÷3=4\bar{w}_3 = (2 \times 3 + 6) \div 3 = 12 \div 3 = 4.
  5. The two routes agree. The SWA weight is 44, which is the middle checkpoint here. Averaging pulled the result back from the last value, 66, toward the centre of the trajectory.
Example
2. Two weights, four checkpoints

Four checkpoints of a two-weight model are (1,2)(1, 2), (3,4)(3, 4), (5,0)(5, 0) and (3,2)(3, 2). Each coordinate is averaged separately.

  1. First coordinates: 1+3+5+3=121 + 3 + 5 + 3 = 12, and 12÷4=312 \div 4 = 3.
  2. Second coordinates: 2+4+0+2=82 + 4 + 0 + 2 = 8, and 8÷4=28 \div 4 = 2.
  3. The SWA model is (3,2)(3, 2).
  4. Run the update to be sure. Start with wˉ1=(1,2)\bar{w}_1 = (1, 2).
  5. Add (3,4)(3, 4): wˉ2=((1,2)⋅1+(3,4))÷2=(4,6)÷2=(2,3)\bar{w}_2 = \big((1, 2)\cdot 1 + (3, 4)\big) \div 2 = (4, 6) \div 2 = (2, 3).
  6. Add (5,0)(5, 0): wˉ3=((2,3)⋅2+(5,0))÷3=(9,6)÷3=(3,2)\bar{w}_3 = \big((2, 3)\cdot 2 + (5, 0)\big) \div 3 = (9, 6) \div 3 = (3, 2).
  7. Add (3,2)(3, 2): wˉ4=((3,2)⋅3+(3,2))÷4=(12,8)÷4=(3,2)\bar{w}_4 = \big((3, 2)\cdot 3 + (3, 2)\big) \div 4 = (12, 8) \div 4 = (3, 2).
  8. The running version reaches (3,2)(3, 2) as well. The SWA answer is (3,2)(3, 2), which here happens to equal the last checkpoint, so this small case does not show the difference that averaging makes.
Example
3. A realistic cost check

A team trains a vision model with 2525 million parameters for 200200 epochs. The last 5050 epochs are the averaging window, and they save one checkpoint per epoch. Each parameter is a 32-bit float, which takes 44 bytes.

  1. One copy of the model: 25,000,000×4=100,000,00025{,}000{,}000 \times 4 = 100{,}000{,}000 bytes, which is 100100 MB.
  2. Keeping all 5050 checkpoints would need 50×10050 \times 100 MB =5,000= 5{,}000 MB, or 55 GB.
  3. The running average needs only one extra copy: 100100 MB, whatever the number of checkpoints.
  4. 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.
  5. 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 4040 million parameters and 3030 saved checkpoints. How much storage would keeping every checkpoint take, and how much does the running average take? Answer: one copy is 40,000,000×4=160,000,00040{,}000{,}000 \times 4 = 160{,}000{,}000 bytes, or 160160 MB. Keeping 3030 copies takes 30×16030 \times 160 MB =4,800= 4{,}800 MB, or 4.84.8 GB. The running average takes one copy, 160160 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 wˉn+1=wˉn+wn+1−wˉnn+1\bar{w}_{n+1} = \bar{w}_n + \frac{w_{n+1} - \bar{w}_n}{n+1}, 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 55, 11 and 33. What is the SWA value, and what does the running update give after the second checkpoint?Show answer

The mean is (5+1+3)÷3=9÷3=3(5 + 1 + 3) \div 3 = 9 \div 3 = 3. After the second checkpoint the running update gives (5+1)÷2=3(5 + 1) \div 2 = 3, which is the average of the first two values. The third update, (2×3+3)÷3=3(2 \times 3 + 3) \div 3 = 3, 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 10,000,000×4=40,000,00010{,}000{,}000 \times 4 = 40{,}000{,}000 bytes, or 4040 MB, which is what the running average needs. Keeping all 2020 checkpoints takes 20×40=80020 \times 40 = 800 MB.

Sources