swa_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import itertools
  2. import math
  3. from copy import deepcopy
  4. import warnings
  5. import torch
  6. from torch.nn import Module
  7. from torch.optim.lr_scheduler import _LRScheduler
  8. class AveragedModel(Module):
  9. r"""Implements averaged model for Stochastic Weight Averaging (SWA).
  10. Stochastic Weight Averaging was proposed in `Averaging Weights Leads to
  11. Wider Optima and Better Generalization`_ by Pavel Izmailov, Dmitrii
  12. Podoprikhin, Timur Garipov, Dmitry Vetrov and Andrew Gordon Wilson
  13. (UAI 2018).
  14. AveragedModel class creates a copy of the provided module :attr:`model`
  15. on the device :attr:`device` and allows to compute running averages of the
  16. parameters of the :attr:`model`.
  17. Args:
  18. model (torch.nn.Module): model to use with SWA
  19. device (torch.device, optional): if provided, the averaged model will be
  20. stored on the :attr:`device`
  21. avg_fn (function, optional): the averaging function used to update
  22. parameters; the function must take in the current value of the
  23. :class:`AveragedModel` parameter, the current value of :attr:`model`
  24. parameter and the number of models already averaged; if None,
  25. equally weighted average is used (default: None)
  26. use_buffers (bool): if ``True``, it will compute running averages for
  27. both the parameters and the buffers of the model. (default: ``False``)
  28. Example:
  29. >>> loader, optimizer, model, loss_fn = ...
  30. >>> swa_model = torch.optim.swa_utils.AveragedModel(model)
  31. >>> scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,
  32. >>> T_max=300)
  33. >>> swa_start = 160
  34. >>> swa_scheduler = SWALR(optimizer, swa_lr=0.05)
  35. >>> for i in range(300):
  36. >>> for input, target in loader:
  37. >>> optimizer.zero_grad()
  38. >>> loss_fn(model(input), target).backward()
  39. >>> optimizer.step()
  40. >>> if i > swa_start:
  41. >>> swa_model.update_parameters(model)
  42. >>> swa_scheduler.step()
  43. >>> else:
  44. >>> scheduler.step()
  45. >>>
  46. >>> # Update bn statistics for the swa_model at the end
  47. >>> torch.optim.swa_utils.update_bn(loader, swa_model)
  48. You can also use custom averaging functions with `avg_fn` parameter.
  49. If no averaging function is provided, the default is to compute
  50. equally-weighted average of the weights.
  51. Example:
  52. >>> # Compute exponential moving averages of the weights and buffers
  53. >>> ema_avg = lambda averaged_model_parameter, model_parameter, num_averaged:\
  54. 0.1 * averaged_model_parameter + 0.9 * model_parameter
  55. >>> swa_model = torch.optim.swa_utils.AveragedModel(model, avg_fn=ema_avg, use_buffers=True)
  56. .. note::
  57. When using SWA with models containing Batch Normalization you may
  58. need to update the activation statistics for Batch Normalization.
  59. This can be done either by using the :meth:`torch.optim.swa_utils.update_bn`
  60. or by setting :attr:`use_buffers` to `True`. The first approach updates the
  61. statistics in a post-training step by passing data through the model. The
  62. second does it during the parameter update phase by averaging all buffers.
  63. Empirical evidence has shown that updating the statistics in normalization
  64. layers increases accuracy, but you may wish to empirically test which
  65. approach yields the best results in your problem.
  66. .. note::
  67. :attr:`avg_fn` is not saved in the :meth:`state_dict` of the model.
  68. .. note::
  69. When :meth:`update_parameters` is called for the first time (i.e.
  70. :attr:`n_averaged` is `0`) the parameters of `model` are copied
  71. to the parameters of :class:`AveragedModel`. For every subsequent
  72. call of :meth:`update_parameters` the function `avg_fn` is used
  73. to update the parameters.
  74. .. _Averaging Weights Leads to Wider Optima and Better Generalization:
  75. https://arxiv.org/abs/1803.05407
  76. .. _There Are Many Consistent Explanations of Unlabeled Data: Why You Should
  77. Average:
  78. https://arxiv.org/abs/1806.05594
  79. .. _SWALP: Stochastic Weight Averaging in Low-Precision Training:
  80. https://arxiv.org/abs/1904.11943
  81. .. _Stochastic Weight Averaging in Parallel: Large-Batch Training That
  82. Generalizes Well:
  83. https://arxiv.org/abs/2001.02312
  84. """
  85. def __init__(self, model, device=None, avg_fn=None, use_buffers=False):
  86. super(AveragedModel, self).__init__()
  87. self.module = deepcopy(model)
  88. if device is not None:
  89. self.module = self.module.to(device)
  90. self.register_buffer('n_averaged',
  91. torch.tensor(0, dtype=torch.long, device=device))
  92. if avg_fn is None:
  93. def avg_fn(averaged_model_parameter, model_parameter, num_averaged):
  94. return averaged_model_parameter + \
  95. (model_parameter - averaged_model_parameter) / (num_averaged + 1)
  96. self.avg_fn = avg_fn
  97. self.use_buffers = use_buffers
  98. def forward(self, *args, **kwargs):
  99. return self.module(*args, **kwargs)
  100. def update_parameters(self, model):
  101. self_param = (
  102. itertools.chain(self.module.parameters(), self.module.buffers())
  103. if self.use_buffers else self.parameters()
  104. )
  105. model_param = (
  106. itertools.chain(model.parameters(), model.buffers())
  107. if self.use_buffers else model.parameters()
  108. )
  109. for p_swa, p_model in zip(self_param, model_param):
  110. device = p_swa.device
  111. p_model_ = p_model.detach().to(device)
  112. if self.n_averaged == 0:
  113. p_swa.detach().copy_(p_model_)
  114. else:
  115. p_swa.detach().copy_(self.avg_fn(p_swa.detach(), p_model_,
  116. self.n_averaged.to(device)))
  117. self.n_averaged += 1
  118. @torch.no_grad()
  119. def update_bn(loader, model, device=None):
  120. r"""Updates BatchNorm running_mean, running_var buffers in the model.
  121. It performs one pass over data in `loader` to estimate the activation
  122. statistics for BatchNorm layers in the model.
  123. Args:
  124. loader (torch.utils.data.DataLoader): dataset loader to compute the
  125. activation statistics on. Each data batch should be either a
  126. tensor, or a list/tuple whose first element is a tensor
  127. containing data.
  128. model (torch.nn.Module): model for which we seek to update BatchNorm
  129. statistics.
  130. device (torch.device, optional): If set, data will be transferred to
  131. :attr:`device` before being passed into :attr:`model`.
  132. Example:
  133. >>> loader, model = ...
  134. >>> torch.optim.swa_utils.update_bn(loader, model)
  135. .. note::
  136. The `update_bn` utility assumes that each data batch in :attr:`loader`
  137. is either a tensor or a list or tuple of tensors; in the latter case it
  138. is assumed that :meth:`model.forward()` should be called on the first
  139. element of the list or tuple corresponding to the data batch.
  140. """
  141. momenta = {}
  142. for module in model.modules():
  143. if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
  144. module.running_mean = torch.zeros_like(module.running_mean)
  145. module.running_var = torch.ones_like(module.running_var)
  146. momenta[module] = module.momentum
  147. if not momenta:
  148. return
  149. was_training = model.training
  150. model.train()
  151. for module in momenta.keys():
  152. module.momentum = None
  153. module.num_batches_tracked *= 0
  154. for input in loader:
  155. if isinstance(input, (list, tuple)):
  156. input = input[0]
  157. if device is not None:
  158. input = input.to(device)
  159. model(input)
  160. for bn_module in momenta.keys():
  161. bn_module.momentum = momenta[bn_module]
  162. model.train(was_training)
  163. class SWALR(_LRScheduler):
  164. r"""Anneals the learning rate in each parameter group to a fixed value.
  165. This learning rate scheduler is meant to be used with Stochastic Weight
  166. Averaging (SWA) method (see `torch.optim.swa_utils.AveragedModel`).
  167. Args:
  168. optimizer (torch.optim.Optimizer): wrapped optimizer
  169. swa_lrs (float or list): the learning rate value for all param groups
  170. together or separately for each group.
  171. annealing_epochs (int): number of epochs in the annealing phase
  172. (default: 10)
  173. annealing_strategy (str): "cos" or "linear"; specifies the annealing
  174. strategy: "cos" for cosine annealing, "linear" for linear annealing
  175. (default: "cos")
  176. last_epoch (int): the index of the last epoch (default: -1)
  177. The :class:`SWALR` scheduler is can be used together with other
  178. schedulers to switch to a constant learning rate late in the training
  179. as in the example below.
  180. Example:
  181. >>> loader, optimizer, model = ...
  182. >>> lr_lambda = lambda epoch: 0.9
  183. >>> scheduler = torch.optim.lr_scheduler.MultiplicativeLR(optimizer,
  184. >>> lr_lambda=lr_lambda)
  185. >>> swa_scheduler = torch.optim.swa_utils.SWALR(optimizer,
  186. >>> anneal_strategy="linear", anneal_epochs=20, swa_lr=0.05)
  187. >>> swa_start = 160
  188. >>> for i in range(300):
  189. >>> for input, target in loader:
  190. >>> optimizer.zero_grad()
  191. >>> loss_fn(model(input), target).backward()
  192. >>> optimizer.step()
  193. >>> if i > swa_start:
  194. >>> swa_scheduler.step()
  195. >>> else:
  196. >>> scheduler.step()
  197. .. _Averaging Weights Leads to Wider Optima and Better Generalization:
  198. https://arxiv.org/abs/1803.05407
  199. """
  200. def __init__(self, optimizer, swa_lr, anneal_epochs=10, anneal_strategy='cos', last_epoch=-1):
  201. swa_lrs = self._format_param(optimizer, swa_lr)
  202. for swa_lr, group in zip(swa_lrs, optimizer.param_groups):
  203. group['swa_lr'] = swa_lr
  204. if anneal_strategy not in ['cos', 'linear']:
  205. raise ValueError("anneal_strategy must by one of 'cos' or 'linear', "
  206. f"instead got {anneal_strategy}")
  207. elif anneal_strategy == 'cos':
  208. self.anneal_func = self._cosine_anneal
  209. elif anneal_strategy == 'linear':
  210. self.anneal_func = self._linear_anneal
  211. if not isinstance(anneal_epochs, int) or anneal_epochs < 0:
  212. raise ValueError(f"anneal_epochs must be equal or greater than 0, got {anneal_epochs}")
  213. self.anneal_epochs = anneal_epochs
  214. super(SWALR, self).__init__(optimizer, last_epoch)
  215. @staticmethod
  216. def _format_param(optimizer, swa_lrs):
  217. if isinstance(swa_lrs, (list, tuple)):
  218. if len(swa_lrs) != len(optimizer.param_groups):
  219. raise ValueError("swa_lr must have the same length as "
  220. f"optimizer.param_groups: swa_lr has {len(swa_lrs)}, "
  221. f"optimizer.param_groups has {len(optimizer.param_groups)}")
  222. return swa_lrs
  223. else:
  224. return [swa_lrs] * len(optimizer.param_groups)
  225. @staticmethod
  226. def _linear_anneal(t):
  227. return t
  228. @staticmethod
  229. def _cosine_anneal(t):
  230. return (1 - math.cos(math.pi * t)) / 2
  231. @staticmethod
  232. def _get_initial_lr(lr, swa_lr, alpha):
  233. if alpha == 1:
  234. return swa_lr
  235. return (lr - alpha * swa_lr) / (1 - alpha)
  236. def get_lr(self):
  237. if not self._get_lr_called_within_step:
  238. warnings.warn("To get the last learning rate computed by the scheduler, "
  239. "please use `get_last_lr()`.", UserWarning)
  240. step = self._step_count - 1
  241. if self.anneal_epochs == 0:
  242. step = max(1, step)
  243. prev_t = max(0, min(1, (step - 1) / max(1, self.anneal_epochs)))
  244. prev_alpha = self.anneal_func(prev_t)
  245. prev_lrs = [self._get_initial_lr(group['lr'], group['swa_lr'], prev_alpha)
  246. for group in self.optimizer.param_groups]
  247. t = max(0, min(1, step / max(1, self.anneal_epochs)))
  248. alpha = self.anneal_func(t)
  249. return [group['swa_lr'] * alpha + lr * (1 - alpha)
  250. for group, lr in zip(self.optimizer.param_groups, prev_lrs)]