adamw.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # Copyright (c) 2022 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. from paddle.optimizer import AdamW
  19. from functools import partial
  20. import re
  21. IS_PADDLE_LATER_2_4 = (
  22. int(paddle.version.major) >= 2 and
  23. int(paddle.version.minor) >= 4) or int(paddle.version.major) == 0
  24. def layerwise_lr_decay(decay_rate, name_dict, n_layers, param):
  25. """
  26. Args:
  27. decay_rate (float):
  28. The layer-wise decay ratio.
  29. name_dict (dict):
  30. The keys of name_dict is dynamic name of model while the value
  31. of name_dict is static name.
  32. Use model.named_parameters() to get name_dict.
  33. n_layers (int):
  34. Total number of layers in the transformer encoder.
  35. """
  36. ratio = 1.0
  37. static_name = name_dict[param.name]
  38. if 'blocks.' in static_name or 'layers.' in static_name:
  39. idx_1 = static_name.find('blocks.')
  40. idx_2 = static_name.find('layers.')
  41. assert any([x >= 0 for x in [idx_1, idx_2]]), ''
  42. idx = idx_1 if idx_1 >= 0 else idx_2
  43. # idx = re.findall('[blocks|layers]\.(\d+)\.', static_name)[0]
  44. layer = int(static_name[idx:].split('.')[1])
  45. ratio = decay_rate**(n_layers - layer)
  46. elif 'cls_token' in static_name or 'patch_embed' in static_name:
  47. ratio = decay_rate**(n_layers + 1)
  48. if IS_PADDLE_LATER_2_4:
  49. return ratio
  50. else:
  51. param.optimize_attr['learning_rate'] *= ratio
  52. class AdamWDL(AdamW):
  53. r"""
  54. The AdamWDL optimizer is implemented based on the AdamW Optimization with dynamic lr setting.
  55. Generally it's used for transformer model.
  56. We use "layerwise_lr_decay" as default dynamic lr setting method of AdamWDL.
  57. “Layer-wise decay” means exponentially decaying the learning rates of individual
  58. layers in a top-down manner. For example, suppose the 24-th layer uses a learning
  59. rate l, and the Layer-wise decay rate is α, then the learning rate of layer m
  60. is lα^(24-m). See more details on: https://arxiv.org/abs/1906.08237.
  61. .. math::
  62. & t = t + 1
  63. & moment\_1\_out = {\beta}_1 * moment\_1 + (1 - {\beta}_1) * grad
  64. & moment\_2\_out = {\beta}_2 * moment\_2 + (1 - {\beta}_2) * grad * grad
  65. & learning\_rate = learning\_rate * \frac{\sqrt{1 - {\beta}_2^t}}{1 - {\beta}_1^t}
  66. & param\_out = param - learning\_rate * (\frac{moment\_1}{\sqrt{moment\_2} + \epsilon} + \lambda * param)
  67. Args:
  68. learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``.
  69. It can be a float value or a LRScheduler. The default value is 0.001.
  70. beta1 (float, optional): The exponential decay rate for the 1st moment estimates.
  71. It should be a float number or a Tensor with shape [1] and data type as float32.
  72. The default value is 0.9.
  73. beta2 (float, optional): The exponential decay rate for the 2nd moment estimates.
  74. It should be a float number or a Tensor with shape [1] and data type as float32.
  75. The default value is 0.999.
  76. epsilon (float, optional): A small float value for numerical stability.
  77. It should be a float number or a Tensor with shape [1] and data type as float32.
  78. The default value is 1e-08.
  79. parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \
  80. This parameter is required in dygraph mode. \
  81. The default value is None in static mode, at this time all parameters will be updated.
  82. weight_decay (float, optional): The weight decay coefficient, it can be float or Tensor. The default value is 0.01.
  83. apply_decay_param_fun (function|None, optional): If it is not None,
  84. only tensors that makes apply_decay_param_fun(Tensor.name)==True
  85. will be updated. It only works when we want to specify tensors.
  86. Default: None.
  87. grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of
  88. some derived class of ``GradientClipBase`` . There are three cliping strategies
  89. ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` ,
  90. :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping.
  91. lazy_mode (bool, optional): The official Adam algorithm has two moving-average accumulators.
  92. The accumulators are updated at every step. Every element of the two moving-average
  93. is updated in both dense mode and sparse mode. If the size of parameter is very large,
  94. then the update may be very slow. The lazy mode only update the element that has
  95. gradient in current mini-batch, so it will be much more faster. But this mode has
  96. different semantics with the original Adam algorithm and may lead to different result.
  97. The default value is False.
  98. multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false.
  99. layerwise_decay (float, optional): The layer-wise decay ratio. Defaults to 1.0.
  100. n_layers (int, optional): The total number of encoder layers. Defaults to 12.
  101. set_param_lr_fun (function|None, optional): If it's not None, set_param_lr_fun() will set the the parameter
  102. learning rate before it executes Adam Operator. Defaults to :ref:`layerwise_lr_decay`.
  103. name_dict (dict, optional): The keys of name_dict is dynamic name of model while the value
  104. of name_dict is static name. Use model.named_parameters() to get name_dict.
  105. name (str, optional): Normally there is no need for user to set this property.
  106. For more information, please refer to :ref:`api_guide_Name`.
  107. The default value is None.
  108. Examples:
  109. .. code-block:: python
  110. import paddle
  111. from paddlenlp.ops.optimizer import AdamWDL
  112. def simple_lr_setting(decay_rate, name_dict, n_layers, param):
  113. ratio = 1.0
  114. static_name = name_dict[param.name]
  115. if "weight" in static_name:
  116. ratio = decay_rate**0.5
  117. param.optimize_attr["learning_rate"] *= ratio
  118. linear = paddle.nn.Linear(10, 10)
  119. name_dict = dict()
  120. for n, p in linear.named_parameters():
  121. name_dict[p.name] = n
  122. inp = paddle.rand([10,10], dtype="float32")
  123. out = linear(inp)
  124. loss = paddle.mean(out)
  125. adamwdl = AdamWDL(
  126. learning_rate=1e-4,
  127. parameters=linear.parameters(),
  128. set_param_lr_fun=simple_lr_setting,
  129. layerwise_decay=0.8,
  130. name_dict=name_dict)
  131. loss.backward()
  132. adamwdl.step()
  133. adamwdl.clear_grad()
  134. """
  135. def __init__(self,
  136. learning_rate=0.001,
  137. beta1=0.9,
  138. beta2=0.999,
  139. epsilon=1e-8,
  140. parameters=None,
  141. weight_decay=0.01,
  142. apply_decay_param_fun=None,
  143. grad_clip=None,
  144. lazy_mode=False,
  145. multi_precision=False,
  146. layerwise_decay=1.0,
  147. n_layers=12,
  148. set_param_lr_func=None,
  149. name_dict=None,
  150. name=None):
  151. if not isinstance(layerwise_decay, float):
  152. raise TypeError("coeff should be float or Tensor.")
  153. self.layerwise_decay = layerwise_decay
  154. self.n_layers = n_layers
  155. self.set_param_lr_func = partial(
  156. set_param_lr_func, layerwise_decay, name_dict,
  157. n_layers) if set_param_lr_func is not None else set_param_lr_func
  158. if IS_PADDLE_LATER_2_4:
  159. super(AdamWDL, self).__init__(
  160. learning_rate=learning_rate,
  161. parameters=parameters,
  162. beta1=beta1,
  163. beta2=beta2,
  164. epsilon=epsilon,
  165. grad_clip=grad_clip,
  166. name=name,
  167. apply_decay_param_fun=apply_decay_param_fun,
  168. weight_decay=weight_decay,
  169. lazy_mode=lazy_mode,
  170. multi_precision=multi_precision,
  171. lr_ratio=self.set_param_lr_func)
  172. else:
  173. super(AdamWDL, self).__init__(
  174. learning_rate=learning_rate,
  175. parameters=parameters,
  176. beta1=beta1,
  177. beta2=beta2,
  178. epsilon=epsilon,
  179. grad_clip=grad_clip,
  180. name=name,
  181. apply_decay_param_fun=apply_decay_param_fun,
  182. weight_decay=weight_decay,
  183. lazy_mode=lazy_mode,
  184. multi_precision=multi_precision)
  185. def _append_optimize_op(self, block, param_and_grad):
  186. if self.set_param_lr_func is None:
  187. return super(AdamWDL, self)._append_optimize_op(block, param_and_grad)
  188. self._append_decoupled_weight_decay(block, param_and_grad)
  189. prev_lr = param_and_grad[0].optimize_attr["learning_rate"]
  190. self.set_param_lr_func(param_and_grad[0])
  191. # excute Adam op
  192. res = super(AdamW, self)._append_optimize_op(block, param_and_grad)
  193. param_and_grad[0].optimize_attr["learning_rate"] = prev_lr
  194. return res
  195. if not IS_PADDLE_LATER_2_4:
  196. AdamWDL._append_optimize_op = _append_optimize_op
  197. def build_adamwdl(model,
  198. lr=1e-4,
  199. weight_decay=0.05,
  200. betas=(0.9, 0.999),
  201. layer_decay=0.65,
  202. num_layers=None,
  203. filter_bias_and_bn=True,
  204. skip_decay_names=None,
  205. set_param_lr_func='layerwise_lr_decay'):
  206. if skip_decay_names and filter_bias_and_bn:
  207. decay_dict = {
  208. param.name: not (len(param.shape) == 1 or name.endswith('.bias') or
  209. any([_n in name for _n in skip_decay_names]))
  210. for name, param in model.named_parameters()
  211. }
  212. parameters = [p for p in model.parameters()]
  213. else:
  214. parameters = model.parameters()
  215. opt_args = dict(
  216. parameters=parameters, learning_rate=lr, weight_decay=weight_decay)
  217. if decay_dict is not None:
  218. opt_args['apply_decay_param_fun'] = lambda n: decay_dict[n]
  219. if isinstance(set_param_lr_func, str):
  220. set_param_lr_func = eval(set_param_lr_func)
  221. opt_args['set_param_lr_func'] = set_param_lr_func
  222. opt_args['beta1'] = betas[0]
  223. opt_args['beta2'] = betas[1]
  224. opt_args['layerwise_decay'] = layer_decay
  225. name_dict = {p.name: n for n, p in model.named_parameters()}
  226. opt_args['name_dict'] = name_dict
  227. opt_args['n_layers'] = num_layers
  228. optimizer = AdamWDL(**opt_args)
  229. return optimizer