ema-pytorch is a Python library that provides an easy way to integrate Exponential Moving Average (EMA) into PyTorch models. It helps stabilize training and improve generalization by maintaining a smoothed version of model parameters over time. The library is actively developed, with frequent updates, and is currently at version 0.7.9.
pip install ema-pytorchVerified import paths — ran on the pinned version, not inferred.
Initialize your PyTorch model, then wrap it with the `EMA` class, specifying the decay factor (`beta`). During your training loop, call `ema.update()` after `optimizer.step()` to update the EMA parameters. For inference or validation, you can directly call the `ema` object, which will use the averaged parameters.
Consider using a lower weight decay rate when EMA is active, or apply EMA updates only to the optimizer's non-decayed weights through a custom schedule.
Ensure `ema.update()` is called after `scaler.update()` and outside the `with autocast():` block.
Experiment with resetting EMA decay to a lower rate after certain epochs and gradually increasing it, or implementing a decay rate schedule where it increases as the model converges (e.g., from 0.99 to 0.999 over epochs).
Use `torch.save(ema, 'ema_model.pth')` and `ema = torch.load('ema_model.pth')`. If saving only the state_dict, ensure you also save `ema.num_updates` and `ema.beta` (and potentially `update_after_step`).