Implement an EMA class that maintains a shadow copy of a model's parameters.
__init__(self, model, decay) - store decay and a detached clone of every parameter, keyed by its name from model.named_parameters().update(self, model) - move each shadow value toward the live parameter:
This must not modify the live model.copy_to(self, model) - write the shadow values into the model's parameters, in place.ema = EMA(model, decay=0.9)
for batch in loader:
...
optimizer.step()
ema.update(model)
ema.copy_to(model) # evaluate the averaged weights
torch.no_grad() - the shadow weights are not part of any graph.mul_ / add_ / copy_ so copy_to leaves the parameters as parameters.decay=1.0 means the shadow never moves; decay=0.0 means it tracks the live weights exactly.