Simple Algorithm
Deep Learning · Emergence · 26 min

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 σ2/(Bh2T)\sigma^2/(Bh^2T) 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 ρ→ρκ\rho\to\rho^\kappa.
  • 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 η/B\eta/B. 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.

DerivationThe average of a stationary run
  1. v=ησ2Bh (2−ηh),Cov⁡(θk,θk+j)=v (1−ηh)∣j∣v=\frac{\eta\sigma^2}{Bh\,(2-\eta h)},\qquad\Cov(\theta_k,\theta_{k+j})=v\,(1-\eta h)^{\abs j}

    In one direction, θk+1=(1−ηh)θk−ηξk\theta_{k+1}=(1-\eta h)\theta_k-\eta\xi_k with Var⁡ξk=σ2/B\Var\xi_k=\sigma^2/B. At stationarity the variance is vv, and each step keeps a fraction 1−ηh1-\eta h of the previous deviation, so the autocovariance decays geometrically:

  2. Var⁡[1T∑k=1Tθk]≈vT(1+2∑j≥1(1−ηh)j)=vT⋅2−ηhηh=σ2Bh2T\Var\Big[\frac1T\sum_{k=1}^{T}\theta_k\Big]\approx\frac vT\Big(1+2\sum_{j\ge1}(1-\eta h)^j\Big)=\frac vT\cdot\frac{2-\eta h}{\eta h}=\frac{\sigma^2}{Bh^2T}

    The variance of the mean of TT consecutive iterates sums all these covariances. For T≫1/(ηh)T\gg1/(\eta h) the geometric series gives

  3. E[L(θˉT)]−L⋆≈σ22BhTversusησ24B for a single iterate\E\big[\loss(\bar\theta_T)\big]-\loss^\star\approx\frac{\sigma^2}{2BhT}\qquad\text{versus}\qquad\frac{\eta\sigma^2}{4B}\ \text{for a single iterate}

    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 1/T1/T instead of sitting on a floor:

  4. ηk=1h(k+1)⟹θT=−1hT∑k=0T−1ξk,Var⁡[θT]=σ2Bh2T\eta_k=\frac{1}{h(k+1)}\quad\Longrightarrow\quad\theta_T=-\frac{1}{hT}\sum_{k=0}^{T-1}\xi_k,\qquad\Var[\theta_T]=\frac{\sigma^2}{Bh^2T}

    The best decaying schedule achieves the same: with ηk=1/(h(k+1))\eta_k=1/(h(k+1)), multiplying the update by k+1k+1 telescopes, and the last iterate is exactly the scaled average of the noise. Averaging with a constant step matches it without knowing hh. In dd dimensions, with Hessian HH and noise covariance C/BC/B, the average's covariance is H−1CH−1/(BT)H^{-1}CH^{-1}/(BT).

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 θ0/(ηhT)\theta_0/(\eta hT), which decays only like 1/T1/T instead of geometrically, and in flat directions, where ηh\eta h 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.

Predict before you look

In the one-direction model with ηh=0.5\eta h=0.5, 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 v/σ2Bh2T=ηhT2−ηh=5001.5≈333v\big/\frac{\sigma^2}{Bh^2T}=\frac{\eta hT}{2-\eta h}=\frac{500}{1.5}\approx333. A thousand iterates are worth about 333 independent samples, because the correlations add 1+2∑j≥1(1−ηh)j=31+2\sum_{j\ge1}(1-\eta h)^j=3 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, θˉt=ρ θˉt−1+(1−ρ) θt\bar{\boldsymbol\theta}_t=\rho\,\bar{\boldsymbol\theta}_{t-1}+(1-\rho)\,\boldsymbol\theta_t with ρ\rho 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 jj steps back is (1−ρ)ρj(1-\rho)\rho^j, its mean age is ρ/(1−ρ)\rho/(1-\rho) steps, and its half-life is ln⁡2/(1−ρ)\ln2/(1-\rho), about 693 steps for ρ=0.999\rho=0.999.

DerivationHow much noise an EMA removes
  1. Var⁡[θˉ]Var⁡[θ]=(1−ρ)2∑i,j≥0ρ i+jϕ∣i−j∣=(1−ρ) (1+ρϕ)(1+ρ) (1−ρϕ)\frac{\Var[\bar\theta]}{\Var[\theta]}=(1-\rho)^2\sum_{i,j\ge0}\rho^{\,i+j}\phi^{\abs{i-j}}=\frac{(1-\rho)\,(1+\rho\phi)}{(1+\rho)\,(1-\rho\phi)}

    Apply the EMA's weights to the stationary iterates of the previous step, with ϕ=1−ηh\phi=1-\eta h, and sum the double geometric series of weights and autocovariances:

  2. Var⁡[θˉ]Var⁡[θ]≈(1−ρ)(2−ηh)2 ηh,Var⁡[θˉ]≈σ2Bh2⋅1−ρ2\frac{\Var[\bar\theta]}{\Var[\theta]}\approx\frac{(1-\rho)(2-\eta h)}{2\,\eta h},\qquad\Var[\bar\theta]\approx\frac{\sigma^2}{Bh^2}\cdot\frac{1-\rho}{2}

    If the EMA's memory is much longer than the iterate's relaxation time, 1−ρ≪ηh1-\rho\ll\eta h, it acts like a uniform average over 1+ρ1−ρ≈21−ρ\frac{1+\rho}{1-\rho}\approx\frac2{1-\rho} steps and removes most of the noise:

  3. ηh≪1−ρ:Var⁡[θˉ]Var⁡[θ]→1;lag=ρ1−ρ steps\eta h\ll1-\rho:\quad\frac{\Var[\bar\theta]}{\Var[\theta]}\to1;\qquad\text{lag}=\frac{\rho}{1-\rho}\ \text{steps}

    If instead the direction relaxes more slowly than the EMA forgets, ηh≪1−ρ\eta h\ll1-\rho, then ϕ→1\phi\to1 and the ratio tends to 11: 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 kk iterates acts like a learning rate that falls linearly to zero over those kk steps, averaging two points kk steps apart like halving the rate over those kk 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.

B→κB,η→κη⟹ρ→ρκB\to\kappa B,\quad\eta\to\kappa\eta\qquad\Longrightarrow\qquad\rho\to\rho^{\kappa}
The EMA scaling rule (Busbridge, Ramapuram, Ablin, Likhomanenko, Dhekane, Suau & Webb, 2023). One step at batch κB\kappa B replaces κ\kappa steps at batch BB (by the linear scaling rule for SGD; Adam uses its square-root rule), and κ\kappa EMA updates toward a nearly constant target compound into one update with momentum ρκ\rho^\kappa. Keeping ρ\rho fixed instead would stretch the EMA's memory, measured in examples, κ\kappa-fold. With the rule they trained BYOL, whose teacher is an EMA of the student, at batch sizes up to 24,576 without loss of performance.
Check your understanding

A recipe keeps an EMA of the weights with ρ=0.9999\rho=0.9999 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?

  1. 0.99990.9999: the momentum is a property of the model, not of the batch
  2. 0.999916≈0.99840.9999^{16}\approx0.9984
  3. 0.99991/16≈0.9999940.9999^{1/16}\approx0.999994
  4. 1−16×0.99991-16\times0.9999
Show the answer

B. 0.999916≈0.99840.9999^{16}\approx0.9984

The batch grows by κ=16\kappa=16, so each new step stands for 16 old ones and the EMA must forget 16 times faster per step: 0.999916≈0.99840.9999^{16}\approx0.9984. Its memory of about 1/(1−ρ)1/(1-\rho) 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 ρ=0.9999\rho=0.9999; 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 kk 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.

θ^γ(t)=γ+1tγ+1∫0tτγ θ(τ) dτ,θ^γ(t)=(1−1t)γ+1θ^γ(t−1)+[1−(1−1t)γ+1]θ(t)\hat{\boldsymbol\theta}_\gamma(t)=\frac{\gamma+1}{t^{\gamma+1}}\int_0^t\tau^{\gamma}\,\boldsymbol\theta(\tau)\,d\tau,\qquad\hat{\boldsymbol\theta}_\gamma(t)=\Big(1-\frac1t\Big)^{\gamma+1}\hat{\boldsymbol\theta}_\gamma(t-1)+\Big[1-\Big(1-\frac1t\Big)^{\gamma+1}\Big]\boldsymbol\theta(t)
The power-function average that Karras, Aittala, Lehtinen, Hellsten, Aila & Laine (2024) introduced for diffusion models. Its window grows in proportion to the training time, so it needs no horizon, and it gives the random initialization zero weight; γ=0\gamma=0 is the uniform average. Storing two such averages (γ=16.97\gamma=16.97 and 6.946.94, of widths 5% and 10% of the run) in periodic snapshots lets any averaging length be reconstructed after training, by least squares. With post-hoc EMA they also observed, as a preliminary finding, that the best averaging length shrinks when the learning rate grows and lengthens when it falls.
python
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 weights

AveragedModel 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 ρ=0.999\rho=0.999 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 TT stationary iterates has variance σ2/(Bh2T)\sigma^2/(Bh^2T) whatever the step, because the iterates' noise and their correlation time scale oppositely with η\eta. It matches the optimal 1/(h(k+1))1/(h(k+1)) schedule and illustrates Polyak–Juditsky's optimal covariance H−1SH−1/TH^{-1}SH^{-1}/T; in practice, average the tail rather than the transient.
  • An EMA with momentum ρ\rho averages over about 2/(1−ρ)2/(1-\rho) steps, cleans only directions that relax faster than that, and lags by ρ/(1−ρ)\rho/(1-\rho) steps; averaging and learning-rate decay are near substitutes. When the batch grows κ\kappa-fold, use ρκ\rho^\kappa.
  • 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.

Question 1

In the one-direction model, constant-step SGD has stationary variance ησ2/(Bh(2−ηh))\eta\sigma^2/(Bh(2-\eta h)). How does the variance of the average of T≫1/(ηh)T\gg1/(\eta h) stationary iterates depend on η\eta?

  1. It grows in proportion to η\eta, like a single iterate's
  2. It does not depend on η\eta: it is σ2/(Bh2T)\sigma^2/(Bh^2T)
  3. It falls like 1/η21/\eta^2
  4. It is zero, since the average converges exactly
Show the answer

B. It does not depend on η\eta: it is σ2/(Bh2T)\sigma^2/(Bh^2T)

A larger step makes each iterate noisier but shortens the correlation time by the same factor, so vT⋅2−ηhηh=σ2Bh2T\frac vT\cdot\frac{2-\eta h}{\eta h}=\frac{\sigma^2}{Bh^2T} is free of η\eta: exactly what the optimal schedule ηk=1/(h(k+1))\eta_k=1/(h(k+1)) achieves.

Question 2

You raise an EMA's momentum from ρ=0.99\rho=0.99 to ρ=0.999\rho=0.999. What changes?

  1. 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
  2. Nothing important, since both values are close to 1
  3. It removes noise in every direction, including those that relax more slowly than its window
  4. 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 2/(1−ρ)2/(1-\rho) steps, 200 against 2,000, and the lag ρ/(1−ρ)\rho/(1-\rho) 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.

Question 3

By Wortsman et al.'s approximation, when does a weight-space soup of two fine-tuned models fall clearly behind their logit ensemble?

  1. When the loss is convex along the path and the soup's predictions are confident
  2. When the two models are nearly identical
  3. When the loss is not convex along the path, or the two models' logits differ a lot on inputs where the soup is uncertain
  4. 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 α(1−α)2\frac{\alpha(1-\alpha)}{2} times the negative curvature of the soup's loss along the path plus a variance term s2ExVar⁡Y[ΔfY]s^2\E_{\mathbf x}\Var_Y[\Delta f_Y]. 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.

Question 4

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?

  1. The learning rate was too high; retrain with a lower one
  2. Averaging never works for ResNets; use an ensemble instead
  3. The averaged weights must be rescaled to the norm of the last checkpoint
  4. 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).