Weight Averaging: SWA, EMA & Model Soups
Averaging weights along a run or across runs, and why it works at all.
Average the weights of two networks trained from different random starts and you usually get a network worse than either. Yet averaging the iterates of a single run, or models fine-tuned from one checkpoint, reliably helps: it is how stochastic weight averaging improves ImageNet accuracy at almost no cost, why diffusion models are evaluated with a moving average of their weights, and how a model soup set a state of the art. This lesson derives what averaging does to SGD's noise, shows that it acts like a learning-rate decay, and explains when weights can be averaged at all.
What you’ll learn
- Derive the variance of averaged constant-step SGD on a quadratic, show that it reaches whatever the step, and state the Polyak–Juditsky theorem it illustrates.
- Analyze the exponential moving average of weights: its effective window, the noise it removes, its lag, and the EMA scaling rule .
- Describe SWA, SWAG, latest-weight averaging, EMA teachers and post-hoc EMA, and implement weight averaging with batch-norm statistics recomputed.
- Explain why averaging works within one basin but fails across independent runs, and compare model soups with output ensembles.
Averaging a noisy iterate
Gradient Noise, Batch Size & Scaling Rules showed that constant-step SGD settles into a stationary cloud around a minimum, with an excess loss proportional to . Decaying the rate shrinks the cloud. Averaging the iterates attacks it differently: the cloud is centered on the minimum, so the mean of many of its points lies close to the center. How close depends on how strongly successive iterates are correlated.
In one direction, with . At stationarity the variance is , and each step keeps a fraction of the previous deviation, so the autocovariance decays geometrically:
The variance of the mean of consecutive iterates sums all these covariances. For the geometric series gives
The learning rate has cancelled: a larger step makes each iterate noisier but makes successive iterates decorrelate faster, by exactly the same factor. The excess loss of the average falls like instead of sitting on a floor:
The best decaying schedule achieves the same: with , multiplying the update by telescopes, and the last iterate is exactly the scaled average of the noise. Averaging with a constant step matches it without knowing . In dimensions, with Hessian and noise covariance , the average's covariance is .
Average the tail, not the transient. Averaging from the first step also averages the descent from the starting point. In the one-direction model the average keeps a bias of about , which decays only like instead of geometrically, and in flat directions, where is small, it dominates. Practical averages therefore start late, once the iterates have reached their cloud: tail averaging (analyzed for least squares by Jain, Kakade, Kidambi, Netrapalli & Sidford, 2018), the last epochs of SWA, or an exponential moving average, which forgets the start by itself.
In the one-direction model with , how many times smaller is the variance of the average of 1,000 consecutive stationary iterates than the variance of a single iterate?
Show the answer
333
The ratio is . A thousand iterates are worth about 333 independent samples, because the correlations add times the single-iterate variance: each iterate stays correlated with its neighbors for a few steps.
The exponential moving average
An exponential moving average (EMA) of the weights, with close to 1, is the averaging used most in deep learning. It needs no stopping time and forgets the start by itself: the weight on the iterate steps back is , its mean age is steps, and its half-life is , about 693 steps for .
Apply the EMA's weights to the stationary iterates of the previous step, with , and sum the double geometric series of weights and autocovariances:
If the EMA's memory is much longer than the iterate's relaxation time, , it acts like a uniform average over steps and removes most of the noise:
If instead the direction relaxes more slowly than the EMA forgets, , then and the ratio tends to : an EMA cannot clean directions that move more slowly than its window. And it lags: if the weights drift at a steady velocity, the EMA trails them by its mean age.
Less noise for less responsiveness is the trade-off of a learning-rate decay, and Sandler, Zhmoginov, Vladymyrov & Miller (2023) made the correspondence explicit. In a model where the gradients change slowly, averaging the last iterates acts like a learning rate that falls linearly to zero over those steps, averaging two points steps apart like halving the rate over those steps, and an EMA like a smooth decay over its horizon; training trajectories on ImageNet matched these equivalences closely. To a good approximation, averaging and decaying are substitutes.
A recipe keeps an EMA of the weights with at batch size 256. You move to batch size 4,096 and rescale the learning rate by the appropriate rule. Which EMA momentum keeps the averaging equivalent?
- : the momentum is a property of the model, not of the batch
Show the answer
B.
The batch grows by , so each new step stands for 16 old ones and the EMA must forget 16 times faster per step: . Its memory of about steps goes from 10,000 old steps to 625 new ones, the same stretch of training.
SWA, EMA and their relatives
Averaging entered deep learning quietly. Inception-v3 was evaluated with "a running average of the parameters computed over time" (Szegedy et al., 2016), and the base transformer of Vaswani et al. (2017) was the average of its last 5 checkpoints, the big one of its last 20. Averaging the parameters of a GAN, uniformly or with an EMA, improved inception and FID scores across architectures and objectives (Yazıcı et al., 2019). Diffusion models are evaluated with an EMA of their weights (DDPM used ; Ho, Jain & Abbeel, 2020), self-supervised methods such as BYOL and DINO use an EMA of the network as the teacher (Non-Contrastive & Self-Distillation Methods), and reinforcement learning keeps slowly averaged copies of value networks as stable targets.
During training, not only after it. Kaddour (2022) averaged the latest end-of-epoch checkpoints along an ordinary run (latest weight averaging, LAWA) and reached a given loss and accuracy dozens of epochs earlier, saving up to about 68 GPU hours for ResNet-50 on ImageNet and 30 for RoBERTa-Base on WikiText-103. Sanyal, Neerkaje, Kaddour, Kumar & Sanghavi (2023) found the gains larger at high learning rates and with widely spaced checkpoints, pretraining language models of 125 to 770 million parameters and on Pythia checkpoints up to 12 billion. Hägele et al. (2024) found that averaging along a constant-rate run improves the loss at every point but does not reach a cooldown, and Morales-Brotons, Vogels & Hendrikx (2024) found that an EMA needs less learning-rate decay than the raw iterate, and that EMA models generalize better, are more robust to noisy labels, are better calibrated and transfer better.
from torch.optim.swa_utils import AveragedModel, SWALR, get_ema_multi_avg_fn, update_bn
ema = AveragedModel(model, multi_avg_fn=get_ema_multi_avg_fn(0.999),
use_buffers=True) # EMA of weights and batch-norm buffers
swa = AveragedModel(model) # uniform average (SWA)
swa_sched = SWALR(opt, swa_lr=0.05) # constant rate for the SWA phase
for epoch in range(epochs):
for x, y in loader:
loss = F.cross_entropy(model(x), y)
opt.zero_grad(); loss.backward(); opt.step()
ema.update_parameters(model) # every step
if epoch >= swa_start: # once per epoch, late in training
swa.update_parameters(model)
swa_sched.step()
update_bn(loader, swa) # recompute batch-norm statistics for the averaged weightsAveragedModel keeps a copy of the network and folds the current weights into it at each update_parameters call: uniformly by default, exponentially with get_ema_multi_avg_fn. With use_buffers=True the EMA also averages the batch-norm buffers; the SWA copy gets fresh statistics from update_bn, one pass over the training data. SWALR anneals the rate to swa_lr over anneal_epochs (10 by default) and then holds it. An EMA with averages over roughly the last 2,000 steps, so it only helps in runs much longer than that.
When can weights be averaged?
Averaging iterates assumes they lie in one basin, convex enough that their average is also a good network. Within a single run that becomes true early. Frankle, Dziugaite, Roy & Carbin (2020) trained two copies of a network from the same checkpoint with different data orders and augmentations and measured the error along the straight line between the results: from a point early in training on, the copies were linearly mode-connected, with no barrier between them. Fine-tuning shares the property: models fine-tuned from the same pretrained weights stay in one basin of the loss landscape, while networks trained from scratch do not (Neyshabur, Sedghi & Zhang, 2020). Two networks trained from different random starts are another matter.
Model soups. Wortsman et al. (2022) put the fine-tuning basin to work. Instead of keeping only the best model of a hyperparameter sweep, average the weights of several: a uniform soup averages them all, and a greedy soup adds models in order of held-out accuracy, keeping each only if held-out accuracy does not drop, so that on that held-out set it is never worse than the best single model. Fine-tuning a ViT-G/14 pretrained on JFT-3B, the greedy soup reached 90.94% top-1 on ImageNet against 90.78% for the best model of the sweep, a state of the art at the time, and it was also more accurate under distribution shift, all at the inference cost of one model. An output ensemble of the same models costs one forward pass per model; on ImageNet it was usually slightly more accurate than the soup, and under distribution shift slightly less. Averaging models fine-tuned on different tasks is the subject of Model Merging & Task Arithmetic.
Key takeaways
- For constant-step SGD on a quadratic, the average of stationary iterates has variance whatever the step, because the iterates' noise and their correlation time scale oppositely with . It matches the optimal schedule and illustrates Polyak–Juditsky's optimal covariance ; in practice, average the tail rather than the transient.
- An EMA with momentum averages over about steps, cleans only directions that relax faster than that, and lags by steps; averaging and learning-rate decay are near substitutes. When the batch grows -fold, use .
- SWA (a constant or cyclical rate, an average and recomputed batch-norm statistics), LAWA, EMA teachers and EMA weights for GANs and diffusion models all average along one run, and post-hoc EMA lets the averaging length be chosen after training. Averages improve on the raw iterate but trail a real cooldown.
- Averaging needs a shared basin: the late iterates of one run, or fine-tunes of one pretrained model, as in model soups (90.94% on ImageNet with ViT-G/14). Independent runs are separated by barriers created by permutation symmetry. A soup matches the ensemble when the loss is convex along the path and the predictions are confident.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the one-direction model, constant-step SGD has stationary variance . How does the variance of the average of stationary iterates depend on ?
- It grows in proportion to , like a single iterate's
- It does not depend on : it is
- It falls like
- It is zero, since the average converges exactly
Show the answer
B. It does not depend on : it is
A larger step makes each iterate noisier but shortens the correlation time by the same factor, so is free of : exactly what the optimal schedule achieves.
You raise an EMA's momentum from to . What changes?
- It averages over about ten times more steps, removing more noise in directions that relax quickly, but it lags about ten times further behind the current weights
- Nothing important, since both values are close to 1
- It removes noise in every direction, including those that relax more slowly than its window
- It gives more weight to the most recent iterate
Show the answer
A. It averages over about ten times more steps, removing more noise in directions that relax quickly, but it lags about ten times further behind the current weights
The window is about steps, 200 against 2,000, and the lag grows from 99 to 999 steps. A longer window helps only in directions that decorrelate within it, and a model that is still moving is tracked less closely.
By Wortsman et al.'s approximation, when does a weight-space soup of two fine-tuned models fall clearly behind their logit ensemble?
- When the loss is convex along the path and the soup's predictions are confident
- When the two models are nearly identical
- When the loss is not convex along the path, or the two models' logits differ a lot on inputs where the soup is uncertain
- Never: a soup is always at least as good as an ensemble
Show the answer
C. When the loss is not convex along the path, or the two models' logits differ a lot on inputs where the soup is uncertain
The gap is times the negative curvature of the soup's loss along the path plus a variance term . Concavity along the path, or large disagreements where the soup is uncertain, make it large; convexity with confident, similar predictions makes the soup as good as the ensemble at a fraction of the inference cost.
You average the weights of the last epochs of a ResNet with batch normalization, and the averaged model scores far worse than any of its checkpoints. What is the most likely cause and fix?
- The learning rate was too high; retrain with a lower one
- Averaging never works for ResNets; use an ensemble instead
- The averaged weights must be rescaled to the norm of the last checkpoint
- The stored batch-norm statistics belong to the individual checkpoints, not to the averaged weights; recompute them with a forward pass over training data
Show the answer
D. The stored batch-norm statistics belong to the individual checkpoints, not to the averaged weights; recompute them with a forward pass over training data
Batch normalization stores running means and variances collected for the weights that were being trained. The averaged weights produce different activations, so the stored statistics no longer match. One pass over training data in training mode (update_bn in PyTorch) recomputes them; SWA, schedule-free methods and EMAs that do not average their buffers all need this step.
Further reading
- B. T. Polyak & A. B. Juditsky, "Acceleration of stochastic approximation by averaging," SIAM Journal on Control and Optimization 30(4), 838–855 (1992).
- P. Izmailov, D. Podoprikhin, T. Garipov, D. Vetrov & A. G. Wilson, "Averaging weights leads to wider optima and better generalization," UAI (2018).
- M. Wortsman, G. Ilharco, S. Y. Gadre, R. Roelofs, R. Gontijo-Lopes, A. S. Morcos, H. Namkoong, A. Farhadi, Y. Carmon, S. Kornblith & L. Schmidt, "Model soups: Averaging weights of multiple fine-tuned models improves accuracy without increasing inference time," ICML (2022).
- D. Busbridge, J. Ramapuram, P. Ablin, T. Likhomanenko, E. G. Dhekane, X. Suau & R. Webb, "How to scale your EMA," NeurIPS (2023).
- T. Karras, M. Aittala, J. Lehtinen, J. Hellsten, T. Aila & S. Laine, "Analyzing and improving the training dynamics of diffusion models," CVPR (2024).