Exponential Moving Average of models weights
| 274 | |
| 275 | # Adapted from torch-ema https://github.com/fadel/pytorch_ema/blob/master/torch_ema/ema.py#L14 |
| 276 | class EMAModel: |
| 277 | """ |
| 278 | Exponential Moving Average of models weights |
| 279 | """ |
| 280 | |
| 281 | def __init__( |
| 282 | self, |
| 283 | parameters: Iterable[torch.nn.Parameter], |
| 284 | decay: float = 0.9999, |
| 285 | min_decay: float = 0.0, |
| 286 | update_after_step: int = 0, |
| 287 | use_ema_warmup: bool = False, |
| 288 | inv_gamma: Union[float, int] = 1.0, |
| 289 | power: Union[float, int] = 2 / 3, |
| 290 | foreach: bool = False, |
| 291 | model_cls: Optional[Any] = None, |
| 292 | model_config: Dict[str, Any] = None, |
| 293 | **kwargs, |
| 294 | ): |
| 295 | """ |
| 296 | Args: |
| 297 | parameters (Iterable[torch.nn.Parameter]): The parameters to track. |
| 298 | decay (float): The decay factor for the exponential moving average. |
| 299 | min_decay (float): The minimum decay factor for the exponential moving average. |
| 300 | update_after_step (int): The number of steps to wait before starting to update the EMA weights. |
| 301 | use_ema_warmup (bool): Whether to use EMA warmup. |
| 302 | inv_gamma (float): |
| 303 | Inverse multiplicative factor of EMA warmup. Default: 1. Only used if `use_ema_warmup` is True. |
| 304 | power (float): Exponential factor of EMA warmup. Default: 2/3. Only used if `use_ema_warmup` is True. |
| 305 | foreach (bool): Use torch._foreach functions for updating shadow parameters. Should be faster. |
| 306 | device (Optional[Union[str, torch.device]]): The device to store the EMA weights on. If None, the EMA |
| 307 | weights will be stored on CPU. |
| 308 | |
| 309 | @crowsonkb's notes on EMA Warmup: |
| 310 | If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan |
| 311 | to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps), |
| 312 | gamma=1, power=3/4 for models you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 |
| 313 | at 215.4k steps). |
| 314 | """ |
| 315 | |
| 316 | if isinstance(parameters, torch.nn.Module): |
| 317 | deprecation_message = ( |
| 318 | "Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. " |
| 319 | "Please pass the parameters of the module instead." |
| 320 | ) |
| 321 | deprecate( |
| 322 | "passing a `torch.nn.Module` to `ExponentialMovingAverage`", |
| 323 | "1.0.0", |
| 324 | deprecation_message, |
| 325 | standard_warn=False, |
| 326 | ) |
| 327 | parameters = parameters.parameters() |
| 328 | |
| 329 | # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility |
| 330 | use_ema_warmup = True |
| 331 | |
| 332 | if kwargs.get("max_value", None) is not None: |
| 333 | deprecation_message = "The `max_value` argument is deprecated. Please use `decay` instead." |
no outgoing calls