adagrad.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 ..base import framework
  16. from .optimizer import Optimizer
  17. __all__ = []
  18. class Adagrad(Optimizer):
  19. r"""
  20. The Adaptive Gradient optimizer (Adagrad for short) use an optimization described
  21. in paper: `Adaptive Subgradient Methods for Online Learning and
  22. Stochastic Optimization <http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf>`_.
  23. The parameter ``param_out`` update rule with gradient ``grad``:
  24. .. math::
  25. moment\_out &= moment + grad * grad
  26. param\_out &= param - \frac{learning\_rate * grad}{\sqrt{moment\_out} + \epsilon}
  27. The original paper does not have the ``epsilon`` attribute. It is added here
  28. in our implementation as also proposed `Per-parameter adaptive learning rate
  29. methods <http://cs231n.github.io/neural-networks-3/#ada>`_
  30. for numerical stability to avoid the division by zero error.
  31. Args:
  32. learning_rate (float|Tensor): The learning rate used to update ``Parameter``.
  33. It can be a float value or a ``Variable`` with a float type.
  34. epsilon (float, optional): A small float value for numerical stability.
  35. The default value is 1e-06.
  36. parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``.
  37. This parameter is required in dygraph mode. And you can specify different options for
  38. different parameter groups such as the learning rate, weight decay, etc,
  39. then the parameters are list of dict. Note that the learning_rate in parameter groups
  40. represents the scale of base learning_rate.
  41. The default value is None in static graph mode, at this time all parameters will be updated.
  42. weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization.
  43. It canbe a float value as coeff of L2 regularization or
  44. :ref:`api_paddle_regularizer_L1Decay`, :ref:`api_paddle_regularizer_L2Decay`.
  45. If a parameter has set regularizer using :ref:`api_paddle_base_param_attr_aramAttr` already,
  46. the regularization setting here in optimizer will be ignored for this parameter.
  47. Otherwise, the regularization setting here in optimizer will take effect.
  48. Default None, meaning there is no regularization.
  49. grad_clip (GradientClipBase, optional): Gradient clipping strategy, it's an instance of
  50. some derived class of ``GradientClipBase`` . There are three clipping strategies,
  51. ClipGradByGlobalNorm, ClipGradByNorm and ClipGradByValue. Default None,
  52. meaning there is no gradient clipping.
  53. name (str, optional): Normally there is no need for user to set this property.
  54. For more information, please refer to :ref:`api_guide_Name`.
  55. The default value is None.
  56. initial_accumulator_value (float, optional): Initial value for moment accumulator.
  57. The default value is 0.0.
  58. Examples:
  59. .. code-block:: python
  60. >>> import paddle
  61. >>> inp = paddle.rand(shape=[10, 10])
  62. >>> linear = paddle.nn.Linear(10, 10)
  63. >>> out = linear(inp)
  64. >>> loss = paddle.mean(out)
  65. >>> adagrad = paddle.optimizer.Adagrad(learning_rate=0.1,
  66. ... parameters=linear.parameters())
  67. >>> out.backward()
  68. >>> adagrad.step()
  69. >>> adagrad.clear_grad()
  70. >>> # Note that the learning_rate of linear_2 is 0.01.
  71. >>> linear_1 = paddle.nn.Linear(10, 10)
  72. >>> linear_2 = paddle.nn.Linear(10, 10)
  73. >>> inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
  74. >>> out = linear_1(inp)
  75. >>> out = linear_2(out)
  76. >>> loss = paddle.mean(out)
  77. >>> adagrad = paddle.optimizer.Adagrad(
  78. ... learning_rate=0.1,
  79. ... parameters=[{
  80. ... 'params': linear_1.parameters()
  81. ... }, {
  82. ... 'params': linear_2.parameters(),
  83. ... 'weight_decay': 0.001,
  84. ... 'learning_rate': 0.1,
  85. ... }],
  86. ... weight_decay=0.01)
  87. >>> out.backward()
  88. >>> adagrad.step()
  89. >>> adagrad.clear_grad()
  90. """
  91. _moment_acc_str = "moment"
  92. def __init__(
  93. self,
  94. learning_rate,
  95. epsilon=1.0e-6,
  96. parameters=None,
  97. weight_decay=None,
  98. grad_clip=None,
  99. name=None,
  100. initial_accumulator_value=0.0,
  101. ):
  102. assert learning_rate is not None
  103. assert epsilon is not None
  104. super().__init__(
  105. learning_rate=learning_rate,
  106. parameters=parameters,
  107. weight_decay=weight_decay,
  108. grad_clip=grad_clip,
  109. name=name,
  110. )
  111. self.type = "adagrad"
  112. self._epsilon = epsilon
  113. self._multi_precision = False
  114. self._master_weights = {}
  115. self.initial_accumulator_value = initial_accumulator_value
  116. self._default_dict = {
  117. 'epsilon': epsilon,
  118. 'initial_accumulator_value': initial_accumulator_value,
  119. }
  120. def _create_accumulators(self, block, parameters):
  121. assert isinstance(block, framework.Block)
  122. if isinstance(parameters, dict):
  123. parameters = self._update_param_group(parameters)
  124. for p in parameters:
  125. if p.name in self._already_create_accumulator:
  126. continue
  127. if self._multi_precision and self._is_dtype_fp16_or_bf16(p.dtype):
  128. master_p = self._create_master_weight(p)
  129. self._add_accumulator(
  130. self._moment_acc_str,
  131. master_p,
  132. fill_value=self.initial_accumulator_value,
  133. )
  134. self._already_create_accumulator.add(p.name)
  135. continue
  136. if (
  137. self._is_dtype_fp16_or_bf16(p.dtype)
  138. and not self._multi_precision
  139. ):
  140. warnings.warn(
  141. "Accumulating with FP16/BF16 in optimizer can lead to poor accuracy or slow convergence."
  142. "Consider using multi_precision=True option of the Momentum optimizer."
  143. )
  144. self._add_accumulator(
  145. self._moment_acc_str,
  146. p,
  147. fill_value=self.initial_accumulator_value,
  148. )
  149. self._already_create_accumulator.add(p.name)
  150. def _append_optimize_op(self, block, param_and_grad):
  151. assert isinstance(block, framework.Block)
  152. if isinstance(param_and_grad, dict):
  153. param_and_grad = self._update_param_group(param_and_grad)
  154. moment_acc = self._get_accumulator_master(
  155. self._moment_acc_str, param_and_grad[0]
  156. )
  157. find_master = self._multi_precision and self._is_dtype_fp16_or_bf16(
  158. param_and_grad[0].dtype
  159. )
  160. master_weight = (
  161. self._master_weights[param_and_grad[0].name]
  162. if find_master
  163. else None
  164. )
  165. # Create the adagrad optimizer op
  166. inputs = {
  167. "Param": param_and_grad[0],
  168. "Grad": param_and_grad[1],
  169. "Moment": moment_acc,
  170. "LearningRate": self._create_param_lr(param_and_grad),
  171. }
  172. outputs = {"ParamOut": param_and_grad[0], "MomentOut": moment_acc}
  173. if find_master:
  174. inputs["MasterParam"] = master_weight
  175. outputs["MasterParamOut"] = master_weight
  176. adagrad_op = block.append_op(
  177. type=self.type,
  178. inputs=inputs,
  179. outputs=outputs,
  180. attrs={"epsilon": self._epsilon, "multi_precision": find_master},
  181. stop_gradient=True,
  182. )
  183. return adagrad_op
  184. def _update_param_group(self, parameters):
  185. self._epsilon = parameters.get('epsilon', self._default_dict['epsilon'])
  186. self.initial_accumulator_value = parameters.get(
  187. 'initial_accumulator_value',
  188. self._default_dict['initial_accumulator_value'],
  189. )
  190. parameters = parameters.get('params')
  191. return parameters