rmsprop_tf.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. """ RMSProp modified to behave like Tensorflow impl
  2. Originally cut & paste from PyTorch RMSProp
  3. https://github.com/pytorch/pytorch/blob/063946d2b3f3f1e953a2a3b54e0b34f1393de295/torch/optim/rmsprop.py
  4. Licensed under BSD-Clause 3 (ish), https://github.com/pytorch/pytorch/blob/master/LICENSE
  5. References for added functionality:
  6. Cautious Optimizers: https://arxiv.org/abs/2411.16085
  7. Why Gradients Rapidly Increase Near the End of Training: https://arxiv.org/abs/2506.02285
  8. Modifications Copyright 2021 Ross Wightman
  9. """
  10. import torch
  11. from torch.optim import Optimizer
  12. from ._types import ParamsT
  13. class RMSpropTF(Optimizer):
  14. """Implements RMSprop algorithm (TensorFlow style epsilon)
  15. NOTE: This is a direct cut-and-paste of PyTorch RMSprop with eps applied before sqrt
  16. and a few other modifications to closer match Tensorflow for matching hyper-params.
  17. Noteworthy changes include:
  18. 1. Epsilon applied inside square-root
  19. 2. square_avg initialized to ones
  20. 3. LR scaling of update accumulated in momentum buffer
  21. Proposed by G. Hinton in his
  22. `course <http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf>`_.
  23. The centered version first appears in `Generating Sequences
  24. With Recurrent Neural Networks <https://arxiv.org/pdf/1308.0850v5.pdf>`_.
  25. Args:
  26. params: iterable of parameters to optimize or dicts defining parameter groups
  27. lr: learning rate
  28. momentum: momentum factor
  29. alpha: smoothing (decay) constant
  30. eps: term added to the denominator to improve numerical stability
  31. centered: if ``True``, compute the centered RMSProp, the gradient is normalized by an estimation of its variance
  32. weight_decay: weight decay (L2 penalty) (default: 0)
  33. decoupled_decay: decoupled weight decay as per https://arxiv.org/abs/1711.05101
  34. corrected_weight_decay: apply corrected weight decay (lr**2 / max_lr) when decoupled_decay is True
  35. lr_in_momentum: learning rate scaling is included in the momentum buffer update as per defaults in Tensorflow
  36. caution: apply caution
  37. """
  38. def __init__(
  39. self,
  40. params: ParamsT,
  41. lr: float = 1e-2,
  42. alpha: float = 0.9,
  43. eps: float = 1e-10,
  44. weight_decay: float = 0,
  45. momentum: float = 0.,
  46. centered: bool = False,
  47. decoupled_decay: bool = False,
  48. corrected_weight_decay: bool = False,
  49. lr_in_momentum: bool = True,
  50. caution: bool = False,
  51. ):
  52. if not 0.0 <= lr:
  53. raise ValueError("Invalid learning rate: {}".format(lr))
  54. if not 0.0 <= eps:
  55. raise ValueError("Invalid epsilon value: {}".format(eps))
  56. if not 0.0 <= momentum:
  57. raise ValueError("Invalid momentum value: {}".format(momentum))
  58. if not 0.0 <= weight_decay:
  59. raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
  60. if not 0.0 <= alpha:
  61. raise ValueError("Invalid alpha value: {}".format(alpha))
  62. defaults = dict(
  63. lr=lr,
  64. momentum=momentum,
  65. alpha=alpha,
  66. eps=eps,
  67. centered=centered,
  68. weight_decay=weight_decay,
  69. decoupled_decay=decoupled_decay,
  70. corrected_weight_decay=corrected_weight_decay,
  71. lr_in_momentum=lr_in_momentum,
  72. caution=caution,
  73. )
  74. super(RMSpropTF, self).__init__(params, defaults)
  75. def __setstate__(self, state):
  76. super(RMSpropTF, self).__setstate__(state)
  77. for group in self.param_groups:
  78. group.setdefault('momentum', 0)
  79. group.setdefault('centered', False)
  80. group.setdefault('caution', False)
  81. group.setdefault('corrected_weight_decay', False)
  82. @torch.no_grad()
  83. def step(self, closure=None):
  84. """Performs a single optimization step.
  85. Arguments:
  86. closure (callable, optional): A closure that reevaluates the model
  87. and returns the loss.
  88. """
  89. loss = None
  90. if closure is not None:
  91. with torch.enable_grad():
  92. loss = closure()
  93. for group in self.param_groups:
  94. for p in group['params']:
  95. if p.grad is None:
  96. continue
  97. grad = p.grad
  98. if grad.is_sparse:
  99. raise RuntimeError('RMSprop does not support sparse gradients')
  100. state = self.state[p]
  101. # State initialization
  102. if len(state) == 0:
  103. state['step'] = 0
  104. state['square_avg'] = torch.ones_like(p) # PyTorch inits to zero
  105. if group['momentum'] > 0:
  106. state['momentum_buffer'] = torch.zeros_like(p)
  107. if group['centered']:
  108. state['grad_avg'] = torch.zeros_like(p)
  109. square_avg = state['square_avg']
  110. one_minus_alpha = 1. - group['alpha']
  111. state['step'] += 1
  112. if group['weight_decay'] != 0:
  113. if group['decoupled_decay']:
  114. if group['corrected_weight_decay']:
  115. wd_scale = group['lr'] ** 2 / self.defaults['lr']
  116. else:
  117. wd_scale = group['lr']
  118. p.mul_(1. - wd_scale * group['weight_decay'])
  119. else:
  120. grad = grad.add(p, alpha=group['weight_decay'])
  121. # Tensorflow order of ops for updating squared avg
  122. square_avg.add_(grad.pow(2) - square_avg, alpha=one_minus_alpha)
  123. # square_avg.mul_(alpha).addcmul_(grad, grad, value=1 - alpha) # PyTorch original
  124. if group['centered']:
  125. grad_avg = state['grad_avg']
  126. grad_avg.add_(grad - grad_avg, alpha=one_minus_alpha)
  127. avg = square_avg.addcmul(grad_avg, grad_avg, value=-1).add(group['eps']).sqrt_() # eps in sqrt
  128. # grad_avg.mul_(alpha).add_(grad, alpha=1 - alpha) # PyTorch original
  129. else:
  130. avg = square_avg.add(group['eps']).sqrt_() # eps moved in sqrt
  131. if group['momentum'] > 0:
  132. buf = state['momentum_buffer']
  133. buf.mul_(group['momentum'])
  134. def _apply_caution(_m, _g):
  135. # Apply caution as per 'Cautious Optimizers' - https://arxiv.org/abs/2411.16085
  136. mask = (_m * _g > 0).to(_g.dtype)
  137. mask.div_(mask.mean().clamp_(min=1e-3))
  138. return _m * mask
  139. if group['lr_in_momentum']:
  140. # Tensorflow accumulates the LR scaling in the momentum buffer
  141. buf.addcdiv_(grad, avg, value=group['lr'])
  142. if group['caution']:
  143. buf = _apply_caution(buf, grad)
  144. p.add_(-buf)
  145. else:
  146. # PyTorch scales the param update by LR
  147. buf.addcdiv_(grad, avg)
  148. if group['caution']:
  149. buf = _apply_caution(buf, grad)
  150. p.add_(buf, alpha=-group['lr'])
  151. else:
  152. p.addcdiv_(grad, avg, value=-group['lr'])
  153. return loss