ema.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import math
  18. import paddle
  19. import weakref
  20. from copy import deepcopy
  21. __all__ = ['ModelEMA', 'SimpleModelEMA']
  22. class ModelEMA(object):
  23. """
  24. Exponential Weighted Average for Deep Neutal Networks
  25. Args:
  26. model (nn.Layer): Detector of model.
  27. decay (int): The decay used for updating ema parameter.
  28. Ema's parameter are updated with the formula:
  29. `ema_param = decay * ema_param + (1 - decay) * cur_param`.
  30. Defaults is 0.9998.
  31. ema_decay_type (str): type in ['threshold', 'normal', 'exponential'],
  32. 'threshold' as default.
  33. cycle_epoch (int): The epoch of interval to reset ema_param and
  34. step. Defaults is -1, which means not reset. Its function is to
  35. add a regular effect to ema, which is set according to experience
  36. and is effective when the total training epoch is large.
  37. ema_black_list (set|list|tuple, optional): The custom EMA black_list.
  38. Blacklist of weight names that will not participate in EMA
  39. calculation. Default: None.
  40. """
  41. def __init__(self,
  42. model,
  43. decay=0.9998,
  44. ema_decay_type='threshold',
  45. cycle_epoch=-1,
  46. ema_black_list=None):
  47. self.step = 0
  48. self.epoch = 0
  49. self.decay = decay
  50. self.ema_decay_type = ema_decay_type
  51. self.cycle_epoch = cycle_epoch
  52. self.ema_black_list = self._match_ema_black_list(
  53. model.state_dict().keys(), ema_black_list)
  54. self.state_dict = dict()
  55. for k, v in model.state_dict().items():
  56. if k in self.ema_black_list:
  57. self.state_dict[k] = v
  58. else:
  59. self.state_dict[k] = paddle.zeros_like(v)
  60. self._model_state = {
  61. k: weakref.ref(p)
  62. for k, p in model.state_dict().items()
  63. }
  64. def reset(self):
  65. self.step = 0
  66. self.epoch = 0
  67. for k, v in self.state_dict.items():
  68. if k in self.ema_black_list:
  69. self.state_dict[k] = v
  70. else:
  71. self.state_dict[k] = paddle.zeros_like(v)
  72. def resume(self, state_dict, step=0):
  73. for k, v in state_dict.items():
  74. if k in self.state_dict:
  75. if self.state_dict[k].dtype == v.dtype:
  76. self.state_dict[k] = v
  77. else:
  78. self.state_dict[k] = v.astype(self.state_dict[k].dtype)
  79. self.step = step
  80. def update(self, model=None):
  81. if self.ema_decay_type == 'threshold':
  82. decay = min(self.decay, (1 + self.step) / (10 + self.step))
  83. elif self.ema_decay_type == 'exponential':
  84. decay = self.decay * (1 - math.exp(-(self.step + 1) / 2000))
  85. else:
  86. decay = self.decay
  87. self._decay = decay
  88. if model is not None:
  89. model_dict = model.state_dict()
  90. else:
  91. model_dict = {k: p() for k, p in self._model_state.items()}
  92. assert all(
  93. [v is not None for _, v in model_dict.items()]), 'python gc.'
  94. for k, v in self.state_dict.items():
  95. if k not in self.ema_black_list:
  96. v = decay * v + (1 - decay) * model_dict[k]
  97. v.stop_gradient = True
  98. self.state_dict[k] = v
  99. self.step += 1
  100. def apply(self):
  101. if self.step == 0:
  102. return self.state_dict
  103. state_dict = dict()
  104. for k, v in self.state_dict.items():
  105. if k in self.ema_black_list:
  106. v.stop_gradient = True
  107. state_dict[k] = v
  108. else:
  109. if self.ema_decay_type != 'exponential':
  110. v = v / (1 - self._decay**self.step)
  111. v.stop_gradient = True
  112. state_dict[k] = v
  113. self.epoch += 1
  114. if self.cycle_epoch > 0 and self.epoch == self.cycle_epoch:
  115. self.reset()
  116. return state_dict
  117. def _match_ema_black_list(self, weight_name, ema_black_list=None):
  118. out_list = set()
  119. if ema_black_list:
  120. for name in weight_name:
  121. for key in ema_black_list:
  122. if key in name:
  123. out_list.add(name)
  124. return out_list
  125. class SimpleModelEMA(object):
  126. """
  127. Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
  128. Keep a moving average of everything in the model state_dict (parameters and buffers).
  129. This is intended to allow functionality like
  130. https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
  131. A smoothed version of the weights is necessary for some training schemes to perform well.
  132. This class is sensitive where it is initialized in the sequence of model init,
  133. GPU assignment and distributed training wrappers.
  134. """
  135. def __init__(self, model=None, decay=0.9996):
  136. """
  137. Args:
  138. model (nn.Module): model to apply EMA.
  139. decay (float): ema decay reate.
  140. """
  141. self.model = deepcopy(model)
  142. self.decay = decay
  143. def update(self, model, decay=None):
  144. if decay is None:
  145. decay = self.decay
  146. with paddle.no_grad():
  147. state = {}
  148. msd = model.state_dict()
  149. for k, v in self.model.state_dict().items():
  150. if paddle.is_floating_point(v):
  151. v *= decay
  152. v += (1.0 - decay) * msd[k].detach()
  153. state[k] = v
  154. self.model.set_state_dict(state)
  155. def resume(self, state_dict, step=0):
  156. state = {}
  157. msd = state_dict
  158. for k, v in self.model.state_dict().items():
  159. if paddle.is_floating_point(v):
  160. v = msd[k].detach()
  161. state[k] = v
  162. self.model.set_state_dict(state)
  163. self.step = step