Sign in

EMA and SWA

Exponential moving average and stochastic weight averaging

Keeps a running average of a model's weights during training, as an exponential moving average or a plain mean, and uses the average for evaluation.

Overview

Training with small random batches never settles on one point. Near the end, the weights jitter around a good region, and where the last step happens to land is partly luck. Averaging the weights over many steps cancels much of that jitter and tends to give a point nearer the middle of the region, which often generalises better. An exponential moving average (EMA) follows training continuously and slowly forgets old weights. Stochastic weight averaging (SWA) takes a plain mean of weights collected late in training. In both cases the optimizer keeps working on the live weights and the average is a separate copy.

A short history

Averaging the iterates of stochastic gradient descent was analysed by David Ruppert in 1988 and by Boris Polyak and Anatoli Juditsky in 1992, who showed it speeds convergence. Deep learning adopted an exponential moving average of weights for evaluation, notably in generative models. In 2018 Pavel Izmailov and colleagues proposed stochastic weight averaging: a plain mean of weights collected late in training, which tends to find flatter solutions that generalise better.

How it works

  1. Create a WeightAverager and choose the mode, ema or swa.
  2. After each optimizer step, call update with the current weights. The values are copied, so later in-place steps do not disturb the average.
  3. Calls before start_step are ignored, and after that only every update_every-th call is collected. For SWA this is how you average once per epoch in the late phase.
  4. In ema mode the stored average is multiplied by the decay and the new weights are added with weight one minus the decay.
  5. With bias_correction the average starts at zero and is divided by the total weight collected so far, which removes the pull toward zero.
  6. In swa mode the stored average moves toward the new weights by one part in the number collected, which keeps an exact mean.
  7. Call averaged to get the averaged copy for evaluation, or copy_to to write it into the live weight arrays.

Watch out for

  • An EMA with decay 0.999 remembers about 1000 steps. Early in training the average lags far behind the live weights, so its scores look poor until enough steps have passed.
  • Without bias correction or decay warmup, an EMA started at the first weights stays biased toward the random initialisation for many steps.
  • Batch normalisation statistics were collected for the live weights, not the averaged ones. After swapping in the average they must be recomputed with a pass over the data, or accuracy drops.
  • Averaging weights from distant stages of training can land between two good regions, where the loss is high. Start SWA only after training has settled.
  • This template averages plain arrays. Recomputing normalisation statistics and scheduling the SWA learning rate are left to the training loop.

Use cases

When to use it

For evaluating or shipping a model trained with noisy steps: EMA is standard for diffusion models and large networks, and SWA is used at the end of a run with a constant or cyclical learning rate.

In industry

Image generation
Diffusion models and GANs are usually sampled from an exponential moving average of the weights, which gives visibly cleaner outputs than the raw weights.
Semi-supervised learning
Methods such as Mean Teacher use an averaged copy of the model as a stable teacher that provides targets for the student.
Computer vision
Image classifiers and detectors are often trained with an averaged copy of the weights, which is the one evaluated and shipped.

Choosing it: what must hold

  • Memory for a second copy of the weights, and a small extra cost per step.
  • For EMA, a decay matched to the length of training, often with a warmup so early weights do not dominate.
  • For SWA, a late training phase with a constant or cyclical learning rate, so the averaged weights sit in one basin.
  • With batch normalisation, a pass over the data to recompute its statistics for the averaged weights.

When to choose something else

IfUse instead
Training is short, or you are fine-tuning for a few hundred stepsThe final weights with a decaying learning rate schedule
You can afford several models at prediction timeAn ensemble of separately trained models
Validation loss is noisy because of exploding updates, not ordinary noiseGradient clipping and a lower learning rate

Math foundations

  1. The EMA update

    at=β at−1+(1−β) wta_t = \beta\,a_{t-1} + (1 - \beta)\,w_t

    The new average keeps a share β\beta of the old average and takes a share 1−β1 - \beta of the current weights. With β\beta near 1 it moves slowly.

  2. What the EMA holds

    at=(1−β)∑i=1tβ t−i wi(a0=0)a_t = (1 - \beta) \sum_{i=1}^{t} \beta^{\,t-i}\,w_i \qquad (a_0 = 0)

    Unrolling the update shows a weighted sum of all past weights. The weight of a step shrinks by a factor β\beta for every step of age, so old weights fade out geometrically.

  3. Bias correction

    a^t=at1−β t\hat{a}_t = \frac{a_t}{1 - \beta^{\,t}}

    The weights in the sum add up to 1−βt1 - \beta^t, not 1, because the average started at zero. Dividing by that total gives a true weighted mean of the weights seen so far.

  4. Effective memory

    Neff≈11−βN_{\text{eff}} \approx \frac{1}{1 - \beta}

    Roughly how many recent steps the EMA averages over. A decay of 0.99 looks back about 100 steps, and 0.999 about 1000.

  5. Decay warmup

    βt=min⁡ ⁣(β, 1+t10+t)\beta_t = \min\!\left(\beta,\ \frac{1 + t}{10 + t}\right)

    An optional schedule that starts with a small decay so the average follows the fast early changes, then rises to the configured β\beta. Here tt counts the updates collected so far.

  6. The SWA running mean

    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}

    This keeps the exact mean of all collected weights without storing them. Every collected point counts equally, however old it is.

Symbols

wtw_t
the live model weights at update t
ata_t
the stored exponential moving average after update t
a^t\hat{a}_t
the bias-corrected average returned by averaged
β\beta
the decay setting
βt\beta_t
the decay actually used at update t when decay_warmup is on
NeffN_{\text{eff}}
the approximate number of recent steps the EMA averages over
wˉn\bar{w}_n
the SWA mean of the first n collected weights
nn
the number of weights collected so far (n_averaged)

Worked by hand

A single weight takes the values w1=1.0w_1 = 1.0 and w2=2.0w_2 = 2.0. Use an EMA with β=0.9\beta = 0.9 and bias correction, starting from a0=0a_0 = 0, and compare with SWA.

a1=0.9×0+0.1×1.0=0.10,a^1=0.101−0.9=1.0a_1 = 0.9 \times 0 + 0.1 \times 1.0 = 0.10, \qquad \hat{a}_1 = \frac{0.10}{1 - 0.9} = 1.0
a2=0.9×0.10+0.1×2.0=0.29a_2 = 0.9 \times 0.10 + 0.1 \times 2.0 = 0.29
a^2=0.291−0.81=0.290.19≈1.526\hat{a}_2 = \frac{0.29}{1 - 0.81} = \frac{0.29}{0.19} \approx 1.526
wˉ2=1.0+2.0−1.02=1.5\bar{w}_2 = 1.0 + \frac{2.0 - 1.0}{2} = 1.5

Without correction the stored value 0.29 is far below both weights. The corrected EMA is 1.526, a mean that leans slightly toward the newer weight. SWA gives exactly 1.5.

Visual example

Loading the example.

Try this

  • Raise the EMA decay toward 0.99: smoother, and slower to follow.
  • Move the SWA start later to average only the settled part.

Code sample

import numpy as np
from impl import WeightAverager
from config import WeightAveragerConfig

rng = np.random.default_rng(0)
params = {"w": np.array([5.0, -5.0])}                   # noisy SGD on f(w) = 0.5 * ||w||^2
ema = WeightAverager(WeightAveragerConfig(mode="ema", decay=0.98))
for _ in range(2000):
    params["w"] -= 0.1 * (params["w"] + rng.normal(size=2))
    ema.update(params)
print(params["w"], ema.averaged()["w"])                 # the average is much closer to [0, 0]
Read the implementation (97 lines)
"""Weight averaging on plain NumPy arrays: exponential moving average (EMA) and stochastic weight
averaging (SWA).

NumPy only. Parameters are a list of arrays or a dict of name -> array. Call `update(params)` after each
optimizer step; `averaged()` returns the averaged copy to evaluate or deploy, and `copy_to(params)` writes
it into the live parameter arrays.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import WeightAveragerConfig
except ImportError:  # run from the template's own folder
    from config import WeightAveragerConfig


def _items(params) -> list[tuple]:
    """[(key, array), ...] for a dict (names) or a list (indices)."""
    return list(params.items()) if isinstance(params, dict) else list(enumerate(params))


class WeightAverager:
    """Keeps a running average of a model's weights.

    `step` counts every call to `update`; `n_averaged` counts the calls that entered the average.
    """

    def __init__(self, config: WeightAveragerConfig | None = None) -> None:
        self.config = config or WeightAveragerConfig()
        self.step = 0
        self.n_averaged = 0
        self._avg: dict = {}  # key -> running average (for bias-corrected EMA: the uncorrected sum)
        self._weight = 0.0  # bias-corrected EMA: total weight in the sum, 1 - product of the decays so far
        self._is_dict = False

    def _decay(self) -> float:
        """Decay used for the current update."""
        cfg = self.config
        if cfg.decay_warmup:
            return min(cfg.decay, (1.0 + self.n_averaged) / (10.0 + self.n_averaged))
        return cfg.decay

    def update(self, params) -> bool:
        """Fold the current weights into the average. Returns True when they were collected.

        params: list or dict of arrays. The values are copied, so later in-place optimizer steps do not
        change the average.
        """
        cfg = self.config
        index = self.step
        self.step += 1
        if index < cfg.start_step or (index - cfg.start_step) % cfg.update_every != 0:
            return False
        self._is_dict = isinstance(params, dict)
        items = [(k, np.asarray(p, dtype=float)) for k, p in _items(params)]
        if cfg.mode == "swa":
            n = self.n_averaged
            for k, p in items:
                self._avg[k] = p.copy() if n == 0 else self._avg[k] + (p - self._avg[k]) / (n + 1)
        elif cfg.bias_correction:
            d = self._decay()
            for k, p in items:
                self._avg[k] = d * self._avg.get(k, np.zeros_like(p)) + (1.0 - d) * p
            self._weight = d * self._weight + (1.0 - d)
        else:
            d = self._decay()
            for k, p in items:
                self._avg[k] = p.copy() if self.n_averaged == 0 else d * self._avg[k] + (1.0 - d) * p
        self.n_averaged += 1
        return True

    def averaged(self):
        """The averaged weights as new arrays, in the structure (list or dict) passed to `update`."""
        if self.n_averaged == 0:
            raise RuntimeError("nothing has been averaged yet: call update (after start_step) first")
        corrected = self.config.mode == "ema" and self.config.bias_correction
        scale = 1.0 / self._weight if corrected and self._weight > 0 else 1.0
        out = {k: a * scale for k, a in self._avg.items()}
        return out if self._is_dict else [out[i] for i in range(len(out))]

    def copy_to(self, params) -> None:
        """Overwrite the arrays in `params` with the averaged weights, in place."""
        avg = self.averaged()
        for k, p in _items(params):
            p[...] = avg[k]

    def state_dict(self) -> dict:
        """Everything needed to resume averaging."""
        return {"step": self.step, "n_averaged": self.n_averaged, "weight": self._weight,
                "is_dict": self._is_dict, "avg": {k: a.copy() for k, a in self._avg.items()}}

    def load_state_dict(self, state: dict) -> None:
        """Resume from a saved `state_dict`."""
        self.step, self.n_averaged = int(state["step"]), int(state["n_averaged"])
        self._weight, self._is_dict = float(state["weight"]), bool(state["is_dict"])
        self._avg = {k: np.array(a, dtype=float) for k, a in state["avg"].items()}
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Simulate noisy training of one weight: start at 5 and at each of 2000 steps move it toward 0 by 1 percent, then add random noise. Feed each value to a WeightAverager in ema mode with decay 0.99 and to another in swa mode with start_step 1000, both set through WeightAveragerConfig. Plot the live weight and both results of averaged. Then turn bias_correction off and compare the first 200 steps.

Check on learning

  1. Why can the average of several weight vectors have a lower test loss than every one of the vectors that went into it?
    A way to think about it

    Picture points scattered around the rim of a bowl-shaped valley. Ask where their average lies. Then ask when this picture fails.

  2. You evaluate the EMA weights after 200 steps with decay 0.9999 and no bias correction or warmup. The score is close to that of a random model. Why?
    A way to think about it

    Compute how much total weight the 200 real updates have received compared with the starting point.

  3. EMA forgets old weights and SWA does not. For a run whose learning rate is still decaying, which would you trust more, and why does SWA use start_step?
    A way to think about it

    Early weights come from a different, worse region. An equal-weight mean keeps them for ever unless collection starts late.

  4. After copy_to, a network with batch normalisation gets worse, although the averaged weights should be better. What was missed?
    A way to think about it

    The running means and variances inside the normalisation layers describe activations produced by particular weights. Ask which weights.