rmsprop.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. # Copyright (c) 2020 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. import warnings
  15. from paddle import _C_ops
  16. from ..base import framework
  17. from ..base.framework import in_dynamic_or_pir_mode
  18. from .optimizer import Optimizer
  19. __all__ = []
  20. class RMSProp(Optimizer):
  21. r"""
  22. Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning
  23. rate method. The original slides proposed RMSProp: Slide 29 of
  24. http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf .
  25. The original equation is as follows:
  26. .. math::
  27. r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2
  28. w & = w - \frac{\eta} {\sqrt{r(w,t) + \epsilon}} \nabla Q_{i}(w)
  29. The first equation calculates moving average of the squared gradient for
  30. each weight. Then dividing the gradient by :math:`sqrt{v(w,t)}`.
  31. In some cases, adding a momentum term :math: `\\beta` is beneficial.
  32. In our implementation, Nesterov momentum is used:
  33. .. math::
  34. r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2
  35. v(w, t) & = \beta v(w, t-1) + \frac{\eta} {\sqrt{r(w,t) +
  36. \epsilon}} \nabla Q_{i}(w)
  37. w & = w - v(w, t)
  38. if centered is True:
  39. .. math::
  40. r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2
  41. g(w, t) & = \rho g(w, t-1) + (1 - \rho)\nabla Q_{i}(w)
  42. v(w, t) & = \beta v(w, t-1) + \frac{\eta} {\sqrt{r(w,t) - (g(w, t))^2 +
  43. \epsilon}} \nabla Q_{i}(w)
  44. w & = w - v(w, t)
  45. where, :math:`\rho` is a hyperparameter and typical values are 0.9, 0.95
  46. and so on. :math:`\beta` is the momentum term. :math:`\epsilon` is a
  47. smoothing term to avoid division by zero, usually set somewhere in range
  48. from 1e-4 to 1e-8.
  49. Parameters:
  50. learning_rate (float|LRScheduler): The learning rate used to update ``Parameter``.
  51. It can be a float value or a LRScheduler.
  52. rho(float, optional): rho is :math:`\rho` in equation, default is 0.95.
  53. epsilon(float, optional): :math:`\epsilon` in equation is smoothing term to
  54. avoid division by zero, default is 1e-6.
  55. momentum(float, optional): :math:`\beta` in equation is the momentum term,
  56. default is 0.0.
  57. centered(bool, optional): If True, gradients are normalized by the estimated variance of
  58. the gradient; if False, by the uncentered second moment. Setting this to
  59. True may help with training, but is slightly more expensive in terms of
  60. computation and memory. Defaults to False.
  61. parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``.
  62. This parameter is required in dygraph mode. And you can specify different options for
  63. different parameter groups such as the learning rate, weight decay, etc,
  64. then the parameters are list of dict. Note that the learning_rate in parameter groups
  65. represents the scale of base learning_rate.
  66. The default value is None in static graph mode, at this time all parameters will be updated.
  67. weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization.
  68. It can be a float value as coeff of L2 regularization or \
  69. :ref:`api_paddle_regularizer_L1Decay`, :ref:`api_paddle_regularizer_L2Decay`.
  70. If a parameter has set regularizer using :ref:`api_paddle_ParamAttr` already,
  71. the regularization setting here in optimizer will be ignored for this parameter.
  72. Otherwise, the regularization setting here in optimizer will take effect.
  73. Default None, meaning there is no regularization.
  74. grad_clip (GradientClipBase, optional): Gradient clipping strategy, it's an instance of
  75. some derived class of ``GradientClipBase`` . There are three clipping strategies
  76. ( :ref:`api_paddle_nn_ClipGradByGlobalNorm` , :ref:`api_paddle_nn_ClipGradByNorm` ,
  77. :ref:`api_paddle_nn_ClipGradByValue` ). Default None, meaning there is no gradient clipping.
  78. name (str, optional): This parameter is used by developers to print debugging information.
  79. For details, please refer to :ref:`api_guide_Name`. Default is None.
  80. Examples:
  81. .. code-block:: python
  82. >>> import paddle
  83. >>> inp = paddle.rand([10,10], dtype="float32")
  84. >>> linear = paddle.nn.Linear(10, 10)
  85. >>> out = linear(inp)
  86. >>> loss = paddle.mean(out)
  87. >>> rmsprop = paddle.optimizer.RMSProp(learning_rate=0.1,
  88. ... parameters=linear.parameters(),
  89. ... weight_decay=0.01)
  90. >>> out.backward()
  91. >>> rmsprop.step()
  92. >>> rmsprop.clear_grad()
  93. >>> # Note that the learning_rate of linear_2 is 0.01.
  94. >>> linear_1 = paddle.nn.Linear(10, 10)
  95. >>> linear_2 = paddle.nn.Linear(10, 10)
  96. >>> inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
  97. >>> out = linear_1(inp)
  98. >>> out = linear_2(out)
  99. >>> loss = paddle.mean(out)
  100. >>> rmsprop = paddle.optimizer.RMSProp(
  101. ... learning_rate=0.1,
  102. ... parameters=[{
  103. ... 'params': linear_1.parameters()
  104. ... }, {
  105. ... 'params': linear_2.parameters(),
  106. ... 'weight_decay': 0.001,
  107. ... 'learning_rate': 0.1
  108. ... }],
  109. ... weight_decay=0.01
  110. ... )
  111. >>> out.backward()
  112. >>> rmsprop.step()
  113. >>> rmsprop.clear_grad()
  114. """
  115. _momentum_acc_str = "momentum"
  116. _mean_square_acc_str = "mean_square"
  117. _mean_grad_acc_str = "mean_grad"
  118. def __init__(
  119. self,
  120. learning_rate,
  121. rho=0.95,
  122. epsilon=1.0e-6,
  123. momentum=0.0,
  124. centered=False,
  125. parameters=None,
  126. weight_decay=None,
  127. grad_clip=None,
  128. name=None,
  129. ):
  130. if learning_rate is None:
  131. raise ValueError("learning_rate is not set.")
  132. if rho is None:
  133. raise ValueError("rho is not set.")
  134. if epsilon is None:
  135. raise ValueError("epsilon is not set.")
  136. if momentum is None:
  137. raise ValueError("momentum is not set.")
  138. if not 0.0 <= epsilon:
  139. raise ValueError("Invalid value of epsilon, expect epsilon >= 0.")
  140. if not 0.0 <= momentum:
  141. raise ValueError("Invalid value of momentum, expect momentum >= 0.")
  142. if not 0.0 <= rho:
  143. raise ValueError("Invalid value of rho, expect rho >= 0.")
  144. super().__init__(
  145. learning_rate=learning_rate,
  146. parameters=parameters,
  147. weight_decay=weight_decay,
  148. grad_clip=grad_clip,
  149. name=name,
  150. )
  151. self.type = "rmsprop"
  152. self._rho = rho
  153. self._epsilon = epsilon
  154. self._momentum = momentum
  155. self._centered = centered
  156. self._multi_precision = False
  157. self._master_weights = {}
  158. self._default_dict = {
  159. 'rho': rho,
  160. 'epsilon': epsilon,
  161. 'momentum': momentum,
  162. 'centered': centered,
  163. }
  164. def _create_accumulators(self, block, parameters):
  165. if not isinstance(block, framework.Block):
  166. raise TypeError("block is not instance of framework.Block.")
  167. if isinstance(parameters, dict):
  168. parameters = parameters.get('params')
  169. for p in parameters:
  170. if p.name in self._already_create_accumulator:
  171. continue
  172. if self._multi_precision and self._is_dtype_fp16_or_bf16(p.dtype):
  173. master_p = self._create_master_weight(p)
  174. self._add_accumulator(self._momentum_acc_str, master_p)
  175. self._add_accumulator(self._mean_square_acc_str, master_p)
  176. self._add_accumulator(self._mean_grad_acc_str, master_p)
  177. self._already_create_accumulator.add(p.name)
  178. continue
  179. if (
  180. self._is_dtype_fp16_or_bf16(p.dtype)
  181. and not self._multi_precision
  182. ):
  183. warnings.warn(
  184. "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence."
  185. "Consider using multi_precision=True option of the Lars optimizer."
  186. )
  187. self._add_accumulator(self._momentum_acc_str, p)
  188. self._add_accumulator(self._mean_square_acc_str, p)
  189. self._add_accumulator(self._mean_grad_acc_str, p)
  190. self._already_create_accumulator.add(p.name)
  191. def _append_optimize_op(self, block, param_and_grad):
  192. if not isinstance(block, framework.Block):
  193. raise TypeError("block is not instance of framework.Block.")
  194. if isinstance(param_and_grad, dict):
  195. param_and_grad = self._update_param_group(param_and_grad)
  196. momentum_acc = self._get_accumulator_master(
  197. self._momentum_acc_str, param_and_grad[0]
  198. )
  199. mean_square_acc = self._get_accumulator_master(
  200. self._mean_square_acc_str, param_and_grad[0]
  201. )
  202. mean_grad_acc = self._get_accumulator_master(
  203. self._mean_grad_acc_str, param_and_grad[0]
  204. )
  205. find_master = self._multi_precision and self._is_dtype_fp16_or_bf16(
  206. param_and_grad[0].dtype
  207. )
  208. master_weight = (
  209. self._master_weights[param_and_grad[0].name]
  210. if find_master
  211. else None
  212. )
  213. if in_dynamic_or_pir_mode():
  214. _C_ops.rmsprop_(
  215. param_and_grad[0],
  216. mean_square_acc,
  217. param_and_grad[1],
  218. momentum_acc,
  219. self._create_param_lr(param_and_grad),
  220. mean_grad_acc,
  221. master_weight,
  222. self._epsilon,
  223. self._rho,
  224. self._momentum,
  225. self._centered,
  226. find_master,
  227. )
  228. return None
  229. else:
  230. inputs = {
  231. "Param": param_and_grad[0],
  232. "Grad": param_and_grad[1],
  233. "Moment": momentum_acc,
  234. "MeanSquare": mean_square_acc,
  235. "MeanGrad": mean_grad_acc,
  236. "LearningRate": self._create_param_lr(param_and_grad),
  237. }
  238. outputs = {
  239. "ParamOut": param_and_grad[0],
  240. "MomentOut": momentum_acc,
  241. "MeanSquareOut": mean_square_acc,
  242. "MeanGradOut": mean_grad_acc,
  243. }
  244. if find_master:
  245. inputs["MasterParam"] = master_weight
  246. outputs["MasterParamOut"] = master_weight
  247. rmsprop_op = block.append_op(
  248. type=self.type,
  249. inputs=inputs,
  250. outputs=outputs,
  251. attrs={
  252. "epsilon": self._epsilon,
  253. "decay": self._rho,
  254. "momentum": self._momentum,
  255. "centered": self._centered,
  256. },
  257. stop_gradient=True,
  258. )
  259. return rmsprop_op
  260. def _update_param_group(self, parameters):
  261. self._epsilon = parameters.get('epsilon', self._default_dict['epsilon'])
  262. self._rho = parameters.get('rho', self._default_dict['rho'])
  263. self._momentum = parameters.get(
  264. 'momentum', self._default_dict['momentum']
  265. )
  266. self._centered = parameters.get(
  267. 'centered', self._default_dict['centered']
  268. )
  269. parameters = parameters.get('params')
  270. return parameters