diffusion_models.utils.ema

Module Contents

unwrap_model(model)[source]

Return the module underneath a torch.compile wrapper (if any).

torch.compile returns an OptimizedModule that shares its parameters with the original module but prefixes every state dict key with _orig_mod.. The EMA, checkpoints and optimizer must always deal with the original module so that keys stay stable whether or not compilation is on.

class ExponentialMovingAverage(model, decay=0.999, warmup_steps=0)[source]

Keeps an exponential moving average (EMA) of a model’s weights.

The EMA model is a frozen, eval-mode deep copy of the tracked model. The EMA is compile-aware: a torch.compile-d model can be passed in, as both the copy and every update operate on the underlying module, and the EMA model itself is never compiled, so its keys stay free of _orig_mod. prefixes. Floating point parameters are averaged, while buffers (e.g. BatchNorm running statistics and integer counters) are copied verbatim from the tracked model, as averaging them is meaningless.

Parameters:
  • model (Module) – The model to track.

  • decay (float) – The decay of the moving average, in [0, 1).

  • warmup_steps (int) – When positive, the effective decay at update n is min(decay, (1 + n) / (warmup_steps + n)). This makes the average follow the model closely at the start of training. 0 disables it.

decay = 0.999[source]

The target decay.

warmup_steps = 0[source]

The warmup horizon, in updates.

num_updates = 0[source]

The number of updates performed so far.

model[source]

The averaged model.

get_decay()[source]

The decay to use for the next update.

update(model)[source]

Update the averaged weights from the tracked model.

Parameters:

model (Module) – The tracked model (after an optimizer step). May be compiled.

state_dict()[source]

The state dict of the averaged model.

load_state_dict(state_dict, num_updates=None)[source]

Load averaged weights into the EMA model.