adamw.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. # Copyright (c) 2021 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 collections import defaultdict
  16. from collections.abc import Callable
  17. import paddle
  18. from paddle import pir
  19. from paddle.base.libpaddle import DataType
  20. from paddle.pir import Value
  21. from .. import _C_ops
  22. from ..base import core, framework
  23. from ..base.dygraph import base as imperative_base
  24. from ..base.framework import (
  25. Parameter,
  26. Variable,
  27. in_dynamic_or_pir_mode,
  28. in_pir_mode,
  29. )
  30. from ..nn.clip import GradientClipBase
  31. from .lr import LRScheduler
  32. from .optimizer import Optimizer
  33. __all__ = []
  34. class AdamW(Optimizer):
  35. r"""
  36. The AdamW optimizer is implemented based on the AdamW Optimization
  37. in paper `DECOUPLED WEIGHT DECAY REGULARIZATION <https://arxiv.org/pdf/1711.05101.pdf>`_.
  38. it can resolves the problem of L2 regularization failure in the Adam optimizer.
  39. .. math::
  40. t & = t + 1
  41. moment\_1\_out & = {\beta}_1 * moment\_1 + (1 - {\beta}_1) * grad
  42. moment\_2\_out & = {\beta}_2 * moment\_2 + (1 - {\beta}_2) * grad * grad
  43. learning\_rate & = learning\_rate *
  44. \frac{\sqrt{1 - {\beta}_2^t}}{1 - {beta}_1^t}
  45. param\_out & = param - learning\_rate * (\frac{moment\_1}{\sqrt{moment\_2} + \epsilon} + \lambda * param)
  46. Args:
  47. learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``.
  48. It can be a float value or a LRScheduler. The default value is 0.001.
  49. parameters (list|tuple, optional): List/Tuple of ``Tensor`` names to update to minimize ``loss``.
  50. This parameter is required in dygraph mode. And you can specify different options for
  51. different parameter groups such as the learning rate, weight decay, etc,
  52. then the parameters are list of dict. Note that the learning_rate in parameter groups
  53. represents the scale of base learning_rate.
  54. The default value is None in static graph mode, at this time all parameters will be updated.
  55. beta1 (float|Tensor, optional): The exponential decay rate for the 1st moment estimates.
  56. It should be a float number or a 0-D Tensor with shape [] and data type as float32.
  57. The default value is 0.9.
  58. beta2 (float|Tensor, optional): The exponential decay rate for the 2nd moment estimates.
  59. It should be a float number or a 0-D Tensor with shape [] and data type as float32.
  60. The default value is 0.999.
  61. epsilon (float, optional): A small float value for numerical stability.
  62. The default value is 1e-08.
  63. weight_decay (float|Tensor, optional): The weight decay coefficient, it can be float or Tensor. The default value is 0.01.
  64. lr_ratio (function|None, optional): If it is not None,
  65. the learning rate will be updated with layer-wise learning rate ratio.
  66. Otherwise, the learning rate is the original.
  67. Default: None.
  68. apply_decay_param_fun (function|None, optional): If it is not None,
  69. only tensors that makes apply_decay_param_fun(Tensor.name)==True
  70. will be updated with weight decay. It only works when we want to specify tensors.
  71. Default: None.
  72. grad_clip (GradientClipBase, optional): Gradient clipping strategy, it's an instance of
  73. some derived class of ``GradientClipBase`` . There are three clipping strategies
  74. ( :ref:`api_paddle_nn_ClipGradByGlobalNorm` , :ref:`api_paddle_nn_ClipGradByNorm` ,
  75. :ref:`api_paddle_nn_ClipGradByValue` ). Default None, meaning there is no gradient clipping.
  76. lazy_mode (bool, optional): The official Adam algorithm has two moving-average accumulators.
  77. The accumulators are updated at every step. Every element of the two moving-average
  78. is updated in both dense mode and sparse mode. If the size of parameter is very large,
  79. then the update may be very slow. The lazy mode only update the element that has
  80. gradient in current mini-batch, so it will be much more faster. But this mode has
  81. different semantics with the original Adam algorithm and may lead to different result.
  82. The default value is False.
  83. multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false.
  84. name (str, optional): Normally there is no need for user to set this property.
  85. For more information, please refer to :ref:`api_guide_Name`.
  86. The default value is None.
  87. Notes:
  88. **Currently, AdamW doesn't support sparse parameter optimization.**
  89. Examples:
  90. .. code-block:: python
  91. >>> import paddle
  92. >>> linear = paddle.nn.Linear(10, 10)
  93. >>> inp = paddle.rand([10,10], dtype="float32")
  94. >>> out = linear(inp)
  95. >>> loss = paddle.mean(out)
  96. >>> beta1 = paddle.to_tensor([0.9], dtype="float32")
  97. >>> beta2 = paddle.to_tensor([0.99], dtype="float32")
  98. >>> opt = paddle.optimizer.AdamW(learning_rate=0.1,
  99. ... parameters=linear.parameters(),
  100. ... beta1=beta1,
  101. ... beta2=beta2,
  102. ... weight_decay=0.01
  103. ... )
  104. >>> loss.backward()
  105. >>> opt.step()
  106. >>> opt.clear_grad()
  107. >>> # Note that the learning_rate of linear_2 is 0.01.
  108. >>> linear_1 = paddle.nn.Linear(10, 10)
  109. >>> linear_2 = paddle.nn.Linear(10, 10)
  110. >>> inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
  111. >>> out = linear_1(inp)
  112. >>> out = linear_2(out)
  113. >>> loss = paddle.mean(out)
  114. >>> opt = paddle.optimizer.AdamW(
  115. ... learning_rate=0.1,
  116. ... parameters=[{
  117. ... 'params': linear_1.parameters()
  118. ... }, {
  119. ... 'params': linear_2.parameters(),
  120. ... 'weight_decay': 0.001,
  121. ... 'learning_rate': 0.1,
  122. ... 'beta1': 0.8
  123. ... }],
  124. ... weight_decay=0.01,
  125. ... beta1=0.9
  126. ... )
  127. >>> loss.backward()
  128. >>> opt.step()
  129. >>> opt.clear_grad()
  130. """
  131. _moment1_acc_str = "moment1"
  132. _moment2_acc_str = "moment2"
  133. _beta1_pow_acc_str = "beta1_pow_acc"
  134. _beta2_pow_acc_str = "beta2_pow_acc"
  135. def __init__(
  136. self,
  137. learning_rate=0.001,
  138. beta1=0.9,
  139. beta2=0.999,
  140. epsilon=1e-8,
  141. parameters=None,
  142. weight_decay=0.01,
  143. lr_ratio=None,
  144. apply_decay_param_fun=None,
  145. grad_clip=None,
  146. lazy_mode=False,
  147. multi_precision=False,
  148. name=None,
  149. ):
  150. assert learning_rate is not None
  151. assert beta1 is not None
  152. assert beta2 is not None
  153. assert epsilon is not None
  154. if not isinstance(beta1, Value) and not 0 <= beta1 < 1:
  155. raise ValueError("Invalid value of beta1, expect beta1 in [0,1).")
  156. if not isinstance(beta2, Value) and not 0 <= beta2 < 1:
  157. raise ValueError("Invalid value of beta2, expect beta2 in [0,1).")
  158. if not isinstance(epsilon, Value) and not 0 <= epsilon:
  159. raise ValueError("Invalid value of epsilon, expect epsilon >= 0.")
  160. if not isinstance(weight_decay, float) and not isinstance(
  161. weight_decay, (framework.Variable, Value)
  162. ):
  163. raise TypeError("weight_decay should be float or Tensor.")
  164. if lr_ratio is not None:
  165. assert isinstance(lr_ratio, Callable)
  166. if (
  167. not core.is_compiled_with_cuda()
  168. and not core.is_compiled_with_xpu()
  169. and paddle.device.get_device().split(":")[0]
  170. not in paddle.device.get_all_custom_device_type()
  171. ):
  172. raise NotImplementedError("'lr_ratio' is unimplemented in CPU.")
  173. if parameters is not None:
  174. # paddle.Tensor is also iterable, so here we don't check whether
  175. # the input is iterable, if the input is paddle.Tensor, the
  176. # list(paddle.Tensor) will be a error value
  177. if isinstance(parameters, (paddle.Tensor, core.eager.Tensor)):
  178. raise TypeError(
  179. "`parameters` argument given to the optimizer should be "
  180. f"an iterable of paddle Tensors, but got argument type is `{type(parameters)}`."
  181. )
  182. if isinstance(parameters, dict):
  183. raise TypeError(
  184. "`parameters` argument should not get dict type, "
  185. "if parameter groups is needed, please set `parameters`"
  186. " as list of dict"
  187. )
  188. self._parameter_list = list(parameters)
  189. else:
  190. self._parameter_list = None
  191. self._name = name
  192. if framework.in_dygraph_mode():
  193. if self._parameter_list is None:
  194. raise AttributeError(
  195. "parameters argument given to the Optimizer should not be None in dygraph mode."
  196. )
  197. if not isinstance(learning_rate, (float, LRScheduler)):
  198. raise TypeError(
  199. "learning rate should be float or LRScheduler, got %s here"
  200. % type(learning_rate)
  201. )
  202. if grad_clip is not None:
  203. if not isinstance(grad_clip, GradientClipBase):
  204. raise TypeError(
  205. "'grad_clip' should be an instance of GradientClipBase's derived class"
  206. )
  207. self._dtype = None
  208. # Infer the dtype form parameter
  209. if self._parameter_list:
  210. if isinstance(self._parameter_list[0], dict):
  211. for param_group in self._parameter_list:
  212. assert (
  213. 'params' in param_group
  214. ), 'params should be set in parameters if parameter groups are optimized in different options'
  215. self._dtype = self._parameter_list[0]['params'][0].dtype
  216. else:
  217. self._dtype = self._parameter_list[0].dtype
  218. # each program should have a independent learning rate
  219. # program -> tensor(learning_rate)
  220. self._learning_rate_map = {}
  221. # Dictionary of accumulators. Some optimizer subclasses need to
  222. # allocate and manage extra tensors associated with the parameters
  223. # to train. These tensors are called accumulators.
  224. # {accum_name : { parameter_name : accumulator_for_parameter, ...}, ...}
  225. self._accumulators = defaultdict(lambda: {})
  226. self.helper = None
  227. self._opti_name_list = []
  228. self._accumulators_holder = {}
  229. self._param_device_map = {}
  230. self.clear_gradients = self.clear_grad
  231. self.type = "adamw"
  232. self._learning_rate = learning_rate
  233. self._params_name = set()
  234. self._apply_decay_param_fun = apply_decay_param_fun
  235. self._weight_decay = weight_decay
  236. self._grad_clip = grad_clip
  237. self._lr_ratio = lr_ratio
  238. self._beta1 = beta1
  239. self._beta2 = beta2
  240. self._epsilon = epsilon
  241. self._lazy_mode = lazy_mode
  242. self._multi_precision = multi_precision
  243. self._master_weights = {}
  244. self._default_dict = {
  245. 'weight_decay': weight_decay,
  246. 'beta1': beta1,
  247. 'beta2': beta2,
  248. 'epsilon': epsilon,
  249. 'lazy_mode': lazy_mode,
  250. 'grad_clip': grad_clip,
  251. }
  252. self._param_groups = []
  253. if self._parameter_list and isinstance(self._parameter_list[0], dict):
  254. for param_group in self._parameter_list:
  255. self._add_param_group(param_group.copy())
  256. else:
  257. self._param_groups = self._parameter_list
  258. self._use_multi_tensor = None
  259. self.regularization = None
  260. self._auxiliary_vars = {}
  261. self._already_create_accumulator = set()
  262. self._create_master_grad_states()
  263. def _set_auxiliary_var(self, key, val):
  264. self._auxiliary_vars[key] = val
  265. def _get_auxiliary_var(self, key):
  266. if key in self._auxiliary_vars:
  267. return self._auxiliary_vars[key]
  268. else:
  269. return None
  270. def _add_param_group(self, param_group):
  271. """
  272. Add a param group to parameter_list.
  273. Args:
  274. param_group (dict): The group of Tensors to be optimized with
  275. different optimization options.
  276. """
  277. params = param_group['params']
  278. if isinstance(params, (Parameter, pir.core.ParameterMeta)):
  279. param_group['params'] = [params]
  280. elif isinstance(params, set):
  281. raise TypeError(
  282. "optimizer parameters should be in ordered collections,"
  283. "but received set, please use list instead."
  284. )
  285. else:
  286. param_group['params'] = list(params)
  287. # Update optimization options for each groups
  288. for k, v in self._default_dict.items():
  289. param_group.setdefault(k, v)
  290. param_set = set()
  291. for group in self._param_groups:
  292. param_set.update(set(group['params']))
  293. if not param_set.isdisjoint(set(param_group['params'])):
  294. raise ValueError(
  295. "some parameters appear in more than one parameter group"
  296. )
  297. for param in param_group['params']:
  298. param.optimize_attr['learning_rate'] = param_group.get(
  299. 'learning_rate', 1.0
  300. )
  301. self._param_groups.append(param_group)
  302. def _add_moments_pows(self, p):
  303. acc_dtype = p.dtype
  304. if self._is_dtype_fp16_or_bf16(acc_dtype):
  305. acc_dtype = (
  306. DataType.FLOAT32 if in_pir_mode() else core.VarDesc.VarType.FP32
  307. )
  308. if core.is_compiled_with_xpu():
  309. import os
  310. xpu_adamw_moment_dtype = os.getenv(
  311. "xpu_adamw_moment_dtype", default="fp32"
  312. )
  313. if xpu_adamw_moment_dtype == "fp16":
  314. self._add_accumulator(
  315. self._moment1_acc_str, p, dtype=core.VarDesc.VarType.FP16
  316. )
  317. self._add_accumulator(
  318. self._moment2_acc_str, p, dtype=core.VarDesc.VarType.FP16
  319. )
  320. else:
  321. self._add_accumulator(self._moment1_acc_str, p, dtype=acc_dtype)
  322. self._add_accumulator(self._moment2_acc_str, p, dtype=acc_dtype)
  323. else:
  324. self._add_accumulator(self._moment1_acc_str, p, dtype=acc_dtype)
  325. self._add_accumulator(self._moment2_acc_str, p, dtype=acc_dtype)
  326. self._add_accumulator(
  327. name=self._beta1_pow_acc_str,
  328. param=p,
  329. dtype=acc_dtype,
  330. fill_value=0.9
  331. if isinstance(self._beta1, (Variable, Value))
  332. else self._beta1,
  333. shape=[1],
  334. type=core.VarDesc.VarType.LOD_TENSOR,
  335. device='cpu',
  336. )
  337. self._add_accumulator(
  338. name=self._beta2_pow_acc_str,
  339. param=p,
  340. dtype=acc_dtype,
  341. fill_value=0.999
  342. if isinstance(self._beta2, (Variable, Value))
  343. else self._beta2,
  344. shape=[1],
  345. type=core.VarDesc.VarType.LOD_TENSOR,
  346. device='cpu',
  347. )
  348. def _create_accumulators(self, block, parameters):
  349. assert isinstance(block, (framework.Block, pir.Block))
  350. if isinstance(parameters, dict):
  351. parameters = self._update_param_group(parameters)
  352. # Create accumulator tensors for first and second moments
  353. for p in parameters:
  354. if p.name in self._already_create_accumulator:
  355. continue
  356. if self._multi_precision and self._is_dtype_fp16_or_bf16(p.dtype):
  357. master_p = self._create_master_weight(p)
  358. self._add_moments_pows(master_p)
  359. self._already_create_accumulator.add(p.name)
  360. continue
  361. if (
  362. self._is_dtype_fp16_or_bf16(p.dtype)
  363. and not self._multi_precision
  364. ):
  365. warnings.warn(
  366. "Accumulating with FP16 or BF16 in optimizer can lead to poor accuracy or slow convergence."
  367. "Consider using multi_precision=True option of the Adam optimizer."
  368. )
  369. self._add_moments_pows(p)
  370. self._already_create_accumulator.add(p.name)
  371. def _append_optimize_op(self, block, param_and_grad):
  372. assert isinstance(block, (framework.Block, pir.Block))
  373. if isinstance(param_and_grad, dict):
  374. param_and_grad = self._update_param_group(param_and_grad)
  375. param, grad = param_and_grad
  376. # Whether we should do weight decay for the parameter.
  377. with_decay = True
  378. if (
  379. self._apply_decay_param_fun is not None
  380. and not self._apply_decay_param_fun(param.name)
  381. ):
  382. with_decay = False
  383. moment1 = self._get_accumulator_master(
  384. self._moment1_acc_str, param_and_grad[0]
  385. )
  386. moment2 = self._get_accumulator_master(
  387. self._moment2_acc_str, param_and_grad[0]
  388. )
  389. beta1_pow_acc = self._get_accumulator_master(
  390. self._beta1_pow_acc_str, param_and_grad[0]
  391. )
  392. beta2_pow_acc = self._get_accumulator_master(
  393. self._beta2_pow_acc_str, param_and_grad[0]
  394. )
  395. find_master = self._multi_precision and self._is_dtype_fp16_or_bf16(
  396. param_and_grad[0].dtype
  397. )
  398. master_weight = (
  399. self._master_weights[param_and_grad[0].name]
  400. if find_master
  401. else None
  402. )
  403. lr = self._create_param_lr(param_and_grad)
  404. # create the adamw optimize op
  405. if in_dynamic_or_pir_mode():
  406. lr_ratio_ = (
  407. 1.0
  408. if self._lr_ratio is None
  409. else self._lr_ratio(param_and_grad[0])
  410. )
  411. _beta1 = (
  412. self._beta1
  413. if not isinstance(self._beta1, Variable)
  414. else self._beta1.item(0)
  415. )
  416. _beta2 = (
  417. self._beta2
  418. if not isinstance(self._beta2, Variable)
  419. else self._beta2.item(0)
  420. )
  421. found_inf = (
  422. self._get_auxiliary_var('found_inf') if in_pir_mode() else None
  423. )
  424. _, _, _, _, _, _ = _C_ops.adamw_(
  425. param_and_grad[0],
  426. param_and_grad[1],
  427. lr,
  428. moment1,
  429. moment2,
  430. beta1_pow_acc,
  431. beta2_pow_acc,
  432. master_weight,
  433. found_inf,
  434. _beta1,
  435. _beta2,
  436. self._epsilon,
  437. lr_ratio_,
  438. self._weight_decay,
  439. with_decay,
  440. self._lazy_mode,
  441. 1000,
  442. find_master,
  443. False,
  444. )
  445. return None
  446. else:
  447. inputs = {
  448. "Param": [param_and_grad[0]],
  449. "Grad": [param_and_grad[1]],
  450. "LearningRate": [lr],
  451. "Moment1": [moment1],
  452. "Moment2": [moment2],
  453. "Beta1Pow": [beta1_pow_acc],
  454. "Beta2Pow": [beta2_pow_acc],
  455. }
  456. # Pass found_inf to adamw, to skip update for not only param, but also momentum and beta_pow
  457. found_inf = self._get_auxiliary_var('found_inf')
  458. if found_inf:
  459. inputs['SkipUpdate'] = found_inf
  460. outputs = {
  461. "ParamOut": [param_and_grad[0]],
  462. "Moment1Out": [moment1],
  463. "Moment2Out": [moment2],
  464. "Beta1PowOut": [beta1_pow_acc],
  465. "Beta2PowOut": [beta2_pow_acc],
  466. }
  467. attrs = {
  468. "lazy_mode": self._lazy_mode,
  469. "min_row_size_to_use_multithread": 1000,
  470. "multi_precision": find_master,
  471. "with_decay": with_decay,
  472. "coeff": self._weight_decay,
  473. "lr_ratio": 1.0
  474. if self._lr_ratio is None
  475. else self._lr_ratio(param_and_grad[0]),
  476. }
  477. if isinstance(self._beta1, Variable):
  478. inputs['Beta1Tensor'] = self._beta1
  479. else:
  480. attrs['beta1'] = self._beta1
  481. if isinstance(self._beta2, Variable):
  482. inputs['Beta2Tensor'] = self._beta2
  483. else:
  484. attrs['beta2'] = self._beta2
  485. if isinstance(self._epsilon, Variable):
  486. inputs['EpsilonTensor'] = self._epsilon
  487. else:
  488. attrs['epsilon'] = self._epsilon
  489. if find_master:
  490. inputs["MasterParam"] = master_weight
  491. outputs["MasterParamOut"] = master_weight
  492. adamw_op = block.append_op(
  493. type=self.type,
  494. inputs=inputs,
  495. outputs=outputs,
  496. attrs=attrs,
  497. stop_gradient=True,
  498. )
  499. return adamw_op
  500. def __str__(self):
  501. return " ".join(["Weight Decay, params:", ",".join(self._params_name)])
  502. @imperative_base.no_grad
  503. @framework.non_static_only
  504. def step(self):
  505. """
  506. Execute the optimizer and update parameters once.
  507. Returns:
  508. None
  509. Examples:
  510. .. code-block:: python
  511. >>> import paddle
  512. >>> a = paddle.rand([2,13], dtype="float32")
  513. >>> linear = paddle.nn.Linear(13, 5)
  514. >>> # This can be any optimizer supported by dygraph.
  515. >>> opt = paddle.optimizer.AdamW(learning_rate = 0.01,
  516. ... parameters = linear.parameters())
  517. >>> out = linear(a)
  518. >>> out.backward()
  519. >>> opt.step()
  520. >>> opt.clear_grad()
  521. """
  522. if paddle.base.dygraph.base.in_to_static_mode():
  523. self._declarative_step()
  524. return
  525. if not isinstance(self._parameter_list[0], dict):
  526. params_grads = []
  527. for param in self._parameter_list:
  528. if param.stop_gradient:
  529. continue
  530. if param._grad_ivar() is not None:
  531. grad_var = param._grad_ivar()
  532. if framework.in_dygraph_mode():
  533. if (
  534. hasattr(grad_var, "is_selected_rows")
  535. and grad_var.is_selected_rows()
  536. and self.regularization is not None
  537. ):
  538. raise RuntimeError(
  539. "AdamW don't support weight_decay with sparse parameters, please set it to None."
  540. )
  541. else:
  542. if (
  543. hasattr(grad_var, "_is_sparse")
  544. and grad_var._is_sparse()
  545. and self.regularization is not None
  546. ):
  547. raise RuntimeError(
  548. "AdamW don't support weight_decay with sparse parameters, please set it to None."
  549. )
  550. params_grads.append((param, grad_var))
  551. optimize_ops = self._apply_optimize(
  552. loss=None, startup_program=None, params_grads=params_grads
  553. )
  554. else:
  555. # optimize parameters in groups
  556. for param_group in self._param_groups:
  557. params_grads = defaultdict(lambda: [])
  558. for param in param_group['params']:
  559. if param.stop_gradient:
  560. continue
  561. if param._grad_ivar() is not None:
  562. grad_var = param._grad_ivar()
  563. if framework.in_dygraph_mode():
  564. if (
  565. hasattr(grad_var, "is_selected_rows")
  566. and grad_var.is_selected_rows()
  567. and self.regularization is not None
  568. ):
  569. raise RuntimeError(
  570. "AdamW don't support weight_decay with sparse parameters, please set it to None."
  571. )
  572. else:
  573. if (
  574. hasattr(grad_var, "_is_sparse")
  575. and grad_var._is_sparse()
  576. and self.regularization is not None
  577. ):
  578. raise RuntimeError(
  579. "AdamW don't support weight_decay with sparse parameters, please set it to None."
  580. )
  581. params_grads['params'].append((param, grad_var))
  582. params_grads.update(
  583. {k: v for k, v in param_group.items() if k != 'params'}
  584. )
  585. self._apply_optimize(
  586. loss=None, startup_program=None, params_grads=params_grads
  587. )
  588. def _update_param_group(self, parameters):
  589. self._beta1 = parameters.get('beta1', self._default_dict['beta1'])
  590. self._beta2 = parameters.get('beta2', self._default_dict['beta2'])
  591. self._epsilon = parameters.get('epsilon', self._default_dict['epsilon'])
  592. self._lazy_mode = parameters.get(
  593. 'lazy_mode', self._default_dict['lazy_mode']
  594. )
  595. self._weight_decay = parameters.get(
  596. 'weight_decay', self._default_dict['weight_decay']
  597. )
  598. parameters = parameters.get('params')
  599. return parameters