REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Own EMA weights and copy non-parameter buffers

An exponential moving average is another owned model state, not a shallow alias of the current model.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Own EMA weights and copy non-parameter buffers →

Your task

Update an independent average module in place and return it. Floating named parameters use decay*old+(1-decay)*live under no_grad. All other state entries, including running-statistic and integer buffers, copy the live value. Require matching state keys/shapes/dtypes and decay in [0,1]; reject shared tensor storage before changing anything. Live model state must remain unchanged. Update exact tied aliases once; reject inconsistent shadow aliases before mutation.

Starter

import torch


def update_ema(average, model, decay):
    return None
Inspect the worked answer
import math
import torch


def update_ema(average, model, decay):
    if not math.isfinite(decay) or not 0 <= decay <= 1:
        raise ValueError('EMA decay in 0..1 required')
    old, new = average.state_dict(), model.state_dict()
    if old.keys() != new.keys() or any(old[k].shape != new[k].shape or old[k].dtype != new[k].dtype for k in old):
        raise ValueError('matching model state required')
    live_storage = {value.data_ptr() for value in new.values() if value.numel()}
    if any(value.numel() and value.data_ptr() in live_storage for value in old.values()):
        raise ValueError('the average must own separate tensor storage')
    parameter_names = {name for name, _ in model.named_parameters(remove_duplicate=False)}
    aliases = {}
    for name, value in old.items():
        if not value.numel():
            continue
        identity = value.data_ptr()
        signature = (new[name].data_ptr(), tuple(value.shape), tuple(value.stride()), name in parameter_names)
        if identity in aliases and aliases[identity] != signature:
            raise ValueError('shared shadow storage needs matching live aliases')
        aliases[identity] = signature
    updated = set()
    with torch.no_grad():
        for name in old:
            identity = old[name].data_ptr() if old[name].numel() else name
            if identity in updated:
                continue
            updated.add(identity)
            if name in parameter_names and old[name].is_floating_point():
                old[name].mul_(decay).add_(new[name], alpha=1 - decay)
            else:
                old[name].copy_(new[name])
    return average

About this algorithm

How Own EMA weights and copy non-parameter buffers works

The idea

An exponential moving average (EMA) model is a second copy of a network whose weights trail the training weights. After each optimizer step, every averaged weight becomes decay * old + (1 - decay) * live. With decay close to 1 the copy blends many recent steps, which smooths out step-to-step noise and often evaluates better than the raw weights.

What this Lab stresses is ownership. The average must hold its own tensor storage, because an alias of the live model averages nothing. Only floating-point parameters are blended. Everything else in the state, such as running statistics and integer counters, is copied from the live model, since blending a counter makes no sense.

How it works

  1. Check that decay is in 0..1 and that both state_dict()s have the same keys, shapes and dtypes.
  2. Compare data_ptr() values and reject an average that shares storage with the live model.
  3. Verify that tied tensors inside average correspond to matching ties in the live model, before anything is changed.
  4. Under torch.no_grad(), visit each state entry, skipping storage that was already updated through an alias.
  5. Blend floating-point parameters in place with old.mul_(decay).add_(new, alpha=1 - decay).
  6. Copy every other entry, including running statistics and integer buffers, straight from the live model.

What it costs

Per update
O(P)
Memory
one extra model copy
Scales with
parameter count P

Each update touches every weight once without building an autograd graph, and the price is keeping a second full copy of the model's state.

Where it is used

  • Stable Diffusion v1.5 was published as v1-5-pruned-emaonly, a checkpoint that keeps only the EMA weights, for image generation.
  • BYOL and MoCo train against a target encoder whose weights are an EMA of the online encoder.
  • PyTorch ships torch.optim.swa_utils.AveragedModel, which keeps EMA weights when given get_ema_multi_avg_fn.

Watch out for

  • Creating the average with average = model or a shallow copy: both names share tensors, so nothing is averaged. Use copy.deepcopy.
  • Blending every state entry: integer buffers such as BatchNorm's num_batches_tracked cannot be averaged and must be copied.
  • Judging the average too early: with decay 0.9999 it is still mostly the initial weights after a thousand steps.