1import copy
2from typing import Optional
3
4import torch
5from torch import nn
6
7
[docs]
8def unwrap_model(model: nn.Module) -> nn.Module:
9 """Return the module underneath a ``torch.compile`` wrapper (if any).
10
11 ``torch.compile`` returns an ``OptimizedModule`` that shares its parameters
12 with the original module but prefixes every state dict key with
13 ``_orig_mod.``. The EMA, checkpoints and optimizer must always deal with the
14 original module so that keys stay stable whether or not compilation is on.
15 """
16 return getattr(model, "_orig_mod", model)
17
18
[docs]
19class ExponentialMovingAverage:
20 def __init__(
21 self,
22 model: nn.Module,
23 decay: float = 0.999,
24 warmup_steps: int = 0,
25 ):
26 """Keeps an exponential moving average (EMA) of a model's weights.
27
28 The EMA model is a frozen, eval-mode deep copy of the tracked model.
29 The EMA is compile-aware: a ``torch.compile``-d model can be passed in, as
30 both the copy and every update operate on the underlying module, and the
31 EMA model itself is never compiled, so its keys stay free of
32 ``_orig_mod.`` prefixes.
33 Floating point parameters are averaged, while buffers (e.g. BatchNorm
34 running statistics and integer counters) are copied verbatim from the
35 tracked model, as averaging them is meaningless.
36
37 Args:
38 model: The model to track.
39 decay: The decay of the moving average, in ``[0, 1)``.
40 warmup_steps: When positive, the effective decay at update ``n`` is
41 ``min(decay, (1 + n) / (warmup_steps + n))``. This makes the average
42 follow the model closely at the start of training. ``0`` disables it.
43 """
44 if not 0.0 <= decay < 1.0:
45 raise ValueError(f"EMA decay must be in [0, 1), got {decay}.")
47 """The target decay."""
[docs]
48 self.warmup_steps = warmup_steps
49 """The warmup horizon, in updates."""
[docs]
50 self.num_updates = 0
51 """The number of updates performed so far."""
[docs]
52 self.model = copy.deepcopy(unwrap_model(model))
53 """The averaged model."""
54 self.model.eval()
55 self.model.requires_grad_(False)
56
[docs]
57 def get_decay(self) -> float:
58 """The decay to use for the next update."""
59 if self.warmup_steps > 0:
60 n = self.num_updates
61 return min(self.decay, (1 + n) / (self.warmup_steps + n))
62 return self.decay
63
64 @torch.no_grad()
[docs]
65 def update(self, model: nn.Module) -> None:
66 """Update the averaged weights from the tracked model.
67
68 Args:
69 model: The tracked model (after an optimizer step). May be compiled.
70 """
71 model = unwrap_model(model)
72 decay = self.get_decay()
73 ema_parameters = dict(self.model.named_parameters())
74 averaged_ema, averaged_model = [], []
75 for name, parameter in model.named_parameters():
76 if parameter.dtype.is_floating_point:
77 averaged_ema.append(ema_parameters[name])
78 averaged_model.append(parameter.detach())
79 if averaged_ema:
80 # ema <- ema + (1 - decay) * (model - ema), fused over all parameters.
81 torch._foreach_lerp_(averaged_ema, averaged_model, 1.0 - decay)
82 ema_buffers = dict(self.model.named_buffers())
83 for name, buffer in model.named_buffers():
84 ema_buffers[name].copy_(buffer)
85 self.num_updates += 1
86
[docs]
87 def state_dict(self) -> dict:
88 """The state dict of the averaged model."""
89 return self.model.state_dict()
90
[docs]
91 def load_state_dict(
92 self, state_dict: dict, num_updates: Optional[int] = None
93 ) -> None:
94 """Load averaged weights into the EMA model."""
95 self.model.load_state_dict(state_dict)
96 if num_updates is not None:
97 self.num_updates = num_updates