adamax.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 core, framework
  17. from ..base.dygraph import no_grad
  18. from ..base.framework import name_scope
  19. from .optimizer import Optimizer
  20. __all__ = []
  21. class Adamax(Optimizer):
  22. r"""
  23. The Adamax optimizer is implemented based on the Adamax Optimization
  24. in Section 7 of `Adam paper <https://arxiv.org/abs/1412.6980>`_.
  25. The Adamax algorithm is a variant of the Adam algorithm based on the infinite norm,
  26. which makes the learning rate update algorithm more stable and simple.
  27. The parameter ``param_out`` update rule with gradient ``grad``:
  28. .. math::
  29. t & = t + 1
  30. moment\_out & = {\beta}_1 * moment + (1 - {\beta}_1) * grad
  31. inf\_norm\_out & = max({\beta}_2 * inf\_norm + \epsilon, |grad|)
  32. learning\_rate & = \frac{learning\_rate}{1 - {\beta}_1^t}
  33. param\_out & = param - learning\_rate * \frac{moment\_out}{inf\_norm\_out}
  34. Related paper: `Adam: A Method for Stochastic Optimization <https://arxiv.org/abs/1412.6980>`_
  35. The original paper does not have an ``epsilon`` attribute,
  36. it is added here for numerical stability to prevent the division by 0 error.
  37. Args:
  38. learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``.
  39. It can be a float value or a LRScheduler. The default value is 0.001.
  40. beta1 (float, optional): The exponential decay rate for the 1st moment estimates.
  41. The default value is 0.9.
  42. beta2 (float, optional): The exponential decay rate for the 2nd moment estimates.
  43. The default value is 0.999.
  44. epsilon (float, optional): A small float value for numerical stability.
  45. The default value is 1e-08.
  46. parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``.
  47. This parameter is required in dygraph mode. And you can specify different options for
  48. different parameter groups such as the learning rate, weight decay, etc,
  49. then the parameters are list of dict. Note that the learning_rate in parameter groups
  50. represents the scale of base learning_rate.
  51. The default value is None in static graph mode, at this time all parameters will be updated.
  52. weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization.
  53. It can be a float value as coeff of L2 regularization or
  54. :ref:`api_paddle_regularizer_L1Decay`, :ref:`api_paddle_regularizer_L2Decay`.
  55. If a parameter has set regularizer using :ref:`api_paddle_ParamAttr` already,
  56. the regularization setting here in optimizer will be ignored for this parameter.
  57. Otherwise, the regularization setting here in optimizer will take effect.
  58. Default None, meaning there is no regularization.
  59. grad_clip (GradientClipBase, optional): Gradient clipping strategy, it's an instance of
  60. some derived class of ``GradientClipBase`` . There are three clipping strategies
  61. ( :ref:`api_paddle_nn_ClipGradByGlobalNorm` , :ref:`api_paddle_nn_ClipGradByNorm` ,
  62. :ref:`api_paddle_nn_ClipGradByValue` ). Default None, meaning there is no gradient clipping.
  63. name (str, optional): Normally there is no need for user to set this property.
  64. For more information, please refer to :ref:`api_guide_Name`.
  65. The default value is None.
  66. **Notes**:
  67. **Currently, Adamax doesn't support sparse parameter optimization.**
  68. Examples:
  69. .. code-block:: python
  70. >>> import paddle
  71. >>> inp = paddle.uniform([10, 10], dtype="float32", min=-0.1, max=0.1)
  72. >>> linear = paddle.nn.Linear(10, 10)
  73. >>> inp = paddle.to_tensor(inp)
  74. >>> out = linear(inp)
  75. >>> loss = paddle.mean(out)
  76. >>> beta1 = paddle.to_tensor([0.9], dtype="float32")
  77. >>> beta2 = paddle.to_tensor([0.99], dtype="float32")
  78. >>> adam = paddle.optimizer.Adamax(learning_rate=0.1,
  79. ... parameters=linear.parameters(),
  80. ... beta1=beta1,
  81. ... beta2=beta2,
  82. ... weight_decay=0.01
  83. ... )
  84. >>> out.backward()
  85. >>> adam.step()
  86. >>> adam.clear_grad()
  87. >>> # Note that the learning_rate of linear_2 is 0.01.
  88. >>> linear_1 = paddle.nn.Linear(10, 10)
  89. >>> linear_2 = paddle.nn.Linear(10, 10)
  90. >>> inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
  91. >>> out = linear_1(inp)
  92. >>> out = linear_2(out)
  93. >>> loss = paddle.mean(out)
  94. >>> adam = paddle.optimizer.Adamax(
  95. ... learning_rate=0.1,
  96. ... parameters=[{
  97. ... 'params': linear_1.parameters()
  98. ... }, {
  99. ... 'params': linear_2.parameters(),
  100. ... 'weight_decay': 0.001,
  101. ... 'learning_rate': 0.1,
  102. ... 'beta1': 0.8
  103. ... }],
  104. ... weight_decay=0.01,
  105. ... beta1=0.9
  106. ... )
  107. >>> out.backward()
  108. >>> adam.step()
  109. >>> adam.clear_grad()
  110. """
  111. _moment_acc_str = "moment"
  112. _inf_norm_acc_str = "inf_norm"
  113. _beta1_pow_acc_str = "beta1_pow_acc"
  114. def __init__(
  115. self,
  116. learning_rate=0.001,
  117. beta1=0.9,
  118. beta2=0.999,
  119. epsilon=1e-8,
  120. parameters=None,
  121. weight_decay=None,
  122. grad_clip=None,
  123. name=None,
  124. ):
  125. assert learning_rate is not None
  126. assert beta1 is not None
  127. assert beta2 is not None
  128. assert epsilon is not None
  129. if not 0 <= beta1 < 1:
  130. raise ValueError("Invalid value of beta1, expect beta1 in [0,1).")
  131. if not 0 <= beta2 < 1:
  132. raise ValueError("Invalid value of beta2, expect beta2 in [0,1).")
  133. if not 0 <= epsilon:
  134. raise ValueError("Invalid value of epsilon, expect epsilon >= 0.")
  135. super().__init__(
  136. learning_rate=learning_rate,
  137. parameters=parameters,
  138. weight_decay=weight_decay,
  139. grad_clip=grad_clip,
  140. name=name,
  141. )
  142. self.type = "adamax"
  143. self._beta1 = beta1
  144. self._beta2 = beta2
  145. self._epsilon = epsilon
  146. self._multi_precision = False
  147. self._master_weights = {}
  148. self._default_dict = {
  149. 'beta1': beta1,
  150. 'beta2': beta2,
  151. 'epsilon': epsilon,
  152. }
  153. def _add_moments_pows(self, p):
  154. acc_dtype = p.dtype
  155. if self._is_dtype_fp16_or_bf16(acc_dtype):
  156. acc_dtype = core.VarDesc.VarType.FP32
  157. self._add_accumulator(self._moment_acc_str, p, dtype=acc_dtype)
  158. self._add_accumulator(self._inf_norm_acc_str, p, dtype=acc_dtype)
  159. self._add_accumulator(
  160. name=self._beta1_pow_acc_str,
  161. param=p,
  162. fill_value=self._beta1,
  163. shape=[1],
  164. )
  165. def _create_accumulators(self, block, parameters):
  166. if isinstance(parameters, dict):
  167. parameters = self._update_param_group(parameters)
  168. # Create accumulator tensors for first moment and infinity norm
  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_moments_pows(master_p)
  175. self._already_create_accumulator.add(p.name)
  176. continue
  177. if (
  178. self._is_dtype_fp16_or_bf16(p.dtype)
  179. and not self._multi_precision
  180. ):
  181. warnings.warn(
  182. "Accumulating with FP16/BF16 in optimizer can lead to poor accuracy or slow convergence."
  183. "Consider using multi_precision=True option of the Adam optimizer."
  184. )
  185. self._add_moments_pows(p)
  186. self._already_create_accumulator.add(p.name)
  187. def _append_optimize_op(self, block, param_and_grad):
  188. assert isinstance(block, framework.Block)
  189. if isinstance(param_and_grad, dict):
  190. param_and_grad = self._update_param_group(param_and_grad)
  191. moment = self._get_accumulator_master(
  192. self._moment_acc_str, param_and_grad[0]
  193. )
  194. inf_norm = self._get_accumulator_master(
  195. self._inf_norm_acc_str, param_and_grad[0]
  196. )
  197. find_master = self._multi_precision and self._is_dtype_fp16_or_bf16(
  198. param_and_grad[0].dtype
  199. )
  200. master_weight = (
  201. self._master_weights[param_and_grad[0].name]
  202. if find_master
  203. else None
  204. )
  205. beta1_pow_acc = self._get_accumulator_master(
  206. self._beta1_pow_acc_str, param_and_grad[0]
  207. )
  208. if framework.in_dygraph_mode():
  209. _C_ops.adamax_(
  210. param_and_grad[0],
  211. param_and_grad[1],
  212. self._create_param_lr(param_and_grad),
  213. moment,
  214. inf_norm,
  215. beta1_pow_acc,
  216. master_weight,
  217. self._beta1,
  218. self._beta2,
  219. self._epsilon,
  220. find_master,
  221. )
  222. else:
  223. # create the adamax optimize op
  224. inputs = {
  225. "Param": param_and_grad[0],
  226. "Grad": param_and_grad[1],
  227. "LearningRate": self._create_param_lr(param_and_grad),
  228. "Moment": moment,
  229. "InfNorm": inf_norm,
  230. "Beta1Pow": beta1_pow_acc,
  231. }
  232. outputs = {
  233. "ParamOut": param_and_grad[0],
  234. "MomentOut": moment,
  235. "InfNormOut": inf_norm,
  236. }
  237. if find_master:
  238. inputs["MasterParam"] = master_weight
  239. outputs["MasterParamOut"] = master_weight
  240. attrs = {
  241. "beta1": self._beta1,
  242. "beta2": self._beta2,
  243. "epsilon": self._epsilon,
  244. "multi_precision": find_master,
  245. }
  246. adamax_op = block.append_op(
  247. type=self.type,
  248. inputs=inputs,
  249. outputs=outputs,
  250. attrs=attrs,
  251. stop_gradient=True,
  252. )
  253. return adamax_op
  254. def _finish_update(self, block, parameters_and_grads):
  255. """Update Beta1 Power accumulator"""
  256. assert isinstance(block, framework.Block)
  257. if isinstance(parameters_and_grads, list):
  258. for param, grad in parameters_and_grads:
  259. if grad is None or param.stop_gradient is True:
  260. continue
  261. if framework.in_dygraph_mode():
  262. beta1_pow_acc = self._get_accumulator_master(
  263. self._beta1_pow_acc_str, param
  264. )
  265. with no_grad():
  266. tmp = _C_ops.scale(
  267. beta1_pow_acc, self._beta1, 0.0, True
  268. )
  269. beta1_pow_acc.copy_(tmp, False)
  270. else:
  271. with param.block.program._optimized_guard(
  272. [param, grad]
  273. ), name_scope('adamax'):
  274. beta1_pow_acc = self._get_accumulator_master(
  275. self._beta1_pow_acc_str, param
  276. )
  277. block.append_op(
  278. type="scale",
  279. inputs={"X": beta1_pow_acc},
  280. outputs={"Out": beta1_pow_acc},
  281. attrs={"scale": self._beta1},
  282. stop_gradient=True,
  283. )
  284. else:
  285. for param, grad in parameters_and_grads['params']:
  286. if grad is None or param.stop_gradient is True:
  287. continue
  288. if framework.in_dygraph_mode():
  289. beta1_pow_acc = self._get_accumulator_master(
  290. self._beta1_pow_acc_str, param
  291. )
  292. self._beta1 = parameters_and_grads.get(
  293. 'beta1', self._default_dict['beta1']
  294. )
  295. with no_grad():
  296. tmp = _C_ops.scale(
  297. beta1_pow_acc, self._beta1, 0.0, True
  298. )
  299. beta1_pow_acc.copy_(tmp, False)
  300. else:
  301. with param.block.program._optimized_guard(
  302. [param, grad]
  303. ), name_scope('adamax'):
  304. beta1_pow_acc = self._get_accumulator_master(
  305. self._beta1_pow_acc_str, param
  306. )
  307. self._beta1 = parameters_and_grads.get(
  308. 'beta1', self._default_dict['beta1']
  309. )
  310. block.append_op(
  311. type="scale",
  312. inputs={"X": beta1_pow_acc},
  313. outputs={"Out": beta1_pow_acc},
  314. attrs={"scale": self._beta1},
  315. stop_gradient=True,
  316. )
  317. def _update_param_group(self, parameters):
  318. self._beta1 = parameters.get('beta1', self._default_dict['beta1'])
  319. self._beta2 = parameters.get('beta2', self._default_dict['beta2'])
  320. self._epsilon = parameters.get('epsilon', self._default_dict['epsilon'])
  321. parameters = parameters.get('params')
  322. return parameters