asgd.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. import paddle
  16. from paddle import _C_ops
  17. from paddle.tensor.creation import to_tensor
  18. from ..base import framework
  19. from ..base.dygraph import no_grad
  20. from ..base.framework import in_dygraph_mode, in_pir_mode
  21. from .optimizer import Optimizer
  22. __all__ = []
  23. class ASGD(Optimizer):
  24. r"""
  25. Optimizer of the ASGD algorithm.Please refer to this for details:
  26. `Minimizing Finite Sums with the Stochastic Average Gradient <https://hal.science/hal-00860051v2>`_.
  27. .. math::
  28. \begin{aligned}
  29. &\hspace{0mm} d=0,\ y_i=0\ \textbf{for}\ i=1,2,...,n \\
  30. &\hspace{0mm} \textbf{for}\ \: m=0,1,...\ \textbf{do} \: \\
  31. &\hspace{5mm} i=m\ \%\ n \\
  32. &\hspace{5mm} d=d-y_i+f_i{}'(x) \\
  33. &\hspace{5mm} y_i=f_i{}'(x) \\
  34. &\hspace{5mm} x=x-learning\_rate(\frac{d}{\mathrm{min}(m+1,\ n)}+\lambda x) \\
  35. &\hspace{0mm} \textbf{end for} \\
  36. \end{aligned}
  37. Parameters:
  38. learning_rate (float|Tensor|LearningRateDecay, optional): The learning rate used to update ``Parameter``.
  39. It can be a float value, a ``Tensor`` with a float type or a LearningRateDecay. The default value is 0.001.
  40. batch_num (int, optional): The number of batches needed to complete one epoch.
  41. Assuming the total number of samples is ``all``,
  42. it is recommended to set ``batch_num`` to ``all`` / ``batch_size``.
  43. In situations where the graphics memory is tight,
  44. it is possible to reduce the batch_num appropriately.
  45. The default value is 1.
  46. parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``.
  47. This parameter is required in dygraph mode.
  48. The default value is None in static graph mode, at this time all parameters will be updated.
  49. weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization.
  50. It can be a float value as coeff of L2 regularization or :ref:`api_paddle_regularizer_L1Decay`, :ref:`api_paddle_regularizer_L2Decay`.
  51. If a parameter has set regularizer using :ref:`api_paddle_ParamAttr` already,
  52. the regularization setting here in optimizer will be ignored for this parameter.
  53. Otherwise, the regularization setting here in optimizer will take effect.
  54. Default None, meaning there is no regularization.
  55. grad_clip (GradientClipBase, optional): Gradient clipping strategy, it's an instance of some derived class of ``GradientClipBase`` .
  56. There are three clipping strategies ( :ref:`api_paddle_nn_ClipGradByGlobalNorm` , :ref:`api_paddle_nn_ClipGradByNorm` , :ref:`api_paddle_nn_ClipGradByValue` ).
  57. Default None, meaning there is no gradient clipping.
  58. multi_precision (bool, optional): In mixed precision training scenarios based on GPU,
  59. this parameter is mainly used to ensure the numerical stability of gradient updates.
  60. When it is set to True, the optimizer will save a backup of FP32 type parameters with an equal value for FP16 type parameters.
  61. When updating gradients, first increase the gradient type to FP32, and then assign it to the FP32 type parameter backup.
  62. Finally, the updated FP32 type value will be converted to FP16 type first,
  63. and then assigned to the actual FP16 type parameters participating in the calculation.
  64. The default value is False.
  65. name (str, optional): The default value is None. Normally there is no need for user to set this property.
  66. For more information, please refer to :ref:`api_guide_Name` .
  67. Examples:
  68. .. code-block:: python
  69. >>> import paddle
  70. >>> inp = paddle.uniform(min=-0.1, max=0.1, shape=[10, 10], dtype='float32')
  71. >>> linear = paddle.nn.Linear(10, 10)
  72. >>> inp = paddle.to_tensor(inp)
  73. >>> out = linear(inp)
  74. >>> loss = paddle.mean(out)
  75. >>> asgd = paddle.optimizer.ASGD(learning_rate=0.001, batch_num=10, parameters=linear.parameters(), weight_decay=0.01)
  76. >>> out.backward()
  77. >>> asgd.step()
  78. >>> asgd.clear_grad()
  79. """
  80. _d_acc_str = "d"
  81. _y_acc_str = "y"
  82. _m_acc_str = "m"
  83. def __init__(
  84. self,
  85. learning_rate=0.001,
  86. batch_num=1,
  87. parameters=None,
  88. weight_decay=None,
  89. grad_clip=None,
  90. multi_precision=False,
  91. name=None,
  92. ):
  93. if learning_rate is None:
  94. raise ValueError("learning_rate should not be none")
  95. if batch_num is None:
  96. raise ValueError("batch_num should not be none")
  97. if not 0 < batch_num:
  98. raise ValueError("batch_num should be greater than 0")
  99. super().__init__(
  100. learning_rate=learning_rate,
  101. parameters=parameters,
  102. weight_decay=weight_decay,
  103. grad_clip=grad_clip,
  104. name=name,
  105. )
  106. self.type = "asgd"
  107. self._multi_precision = multi_precision
  108. self._master_weights = {}
  109. self._n = batch_num
  110. self._n_tensor = None
  111. def _create_accumulators(self, block, parameters):
  112. assert isinstance(block, framework.Block)
  113. if isinstance(parameters, dict):
  114. parameters = self._update_param_group(parameters)
  115. for p in parameters:
  116. if p.name in self._already_create_accumulator:
  117. continue
  118. p_new = p
  119. if self._multi_precision and self._is_dtype_fp16_or_bf16(p.dtype):
  120. master_p = self._create_master_weight(p)
  121. p_new = master_p
  122. if (
  123. self._is_dtype_fp16_or_bf16(p.dtype)
  124. and not self._multi_precision
  125. ):
  126. warnings.warn(
  127. "Accumulating with FP16/BF16 in optimizer can lead to poor accuracy or slow convergence."
  128. "Consider using multi_precision=True option of the Adam optimizer."
  129. )
  130. self._add_accumulator(
  131. self._d_acc_str,
  132. p_new,
  133. p.dtype,
  134. 0,
  135. )
  136. # Sometimes p.shape is a tuple, so we need to change it to a list
  137. self._add_accumulator(
  138. self._y_acc_str,
  139. p_new,
  140. p.dtype,
  141. 0,
  142. [self._n] + list(p.shape),
  143. )
  144. self._add_accumulator(
  145. self._m_acc_str,
  146. p_new,
  147. "int64",
  148. 0,
  149. [1],
  150. )
  151. self._already_create_accumulator.add(p.name)
  152. def _assign_accumulator_master(
  153. self, block, name, param, assign_value, index
  154. ):
  155. if self._name is not None:
  156. name = self._name + "_" + name
  157. find_master = self._multi_precision and self._is_dtype_fp16_or_bf16(
  158. param.dtype
  159. )
  160. target_param = (
  161. self._master_weights[param.name] if find_master else param
  162. )
  163. target_name = target_param.name
  164. if (
  165. name not in self._accumulators
  166. or target_name not in self._accumulators[name]
  167. ):
  168. raise Exception(
  169. f"Accumulator {name} does not exist for parameter {target_name}"
  170. )
  171. if in_pir_mode():
  172. if index is None:
  173. self._accumulators[name][target_name] = paddle.assign(
  174. assign_value
  175. )
  176. else:
  177. self._accumulators[name][target_name][index] = paddle.assign(
  178. assign_value
  179. )
  180. else:
  181. assert isinstance(block, framework.Block)
  182. assign_inputs = {
  183. "X": assign_value,
  184. }
  185. assign_outputs = {
  186. "Out": self._accumulators[name][target_name],
  187. }
  188. block.append_op(
  189. type="assign",
  190. inputs=assign_inputs,
  191. outputs=assign_outputs,
  192. )
  193. @no_grad
  194. def _append_optimize_op(self, block, param_and_grad):
  195. if isinstance(param_and_grad, dict):
  196. param_and_grad = self._update_param_group(param_and_grad)
  197. if self._n_tensor is None:
  198. self._n_tensor = to_tensor(
  199. [self._n],
  200. )
  201. d = self._get_accumulator_master(self._d_acc_str, param_and_grad[0])
  202. m = self._get_accumulator_master(self._m_acc_str, param_and_grad[0])
  203. ys = self._get_accumulator_master(self._y_acc_str, param_and_grad[0])
  204. index = paddle.mod(m, self._n_tensor).item()
  205. y = paddle.assign(ys[index])
  206. find_master = self._multi_precision and self._is_dtype_fp16_or_bf16(
  207. param_and_grad[0].dtype
  208. )
  209. master_weight = (
  210. self._master_weights[param_and_grad[0].name]
  211. if find_master
  212. else None
  213. )
  214. lr = self._create_param_lr(param_and_grad)
  215. if in_dygraph_mode():
  216. m.add_(to_tensor([1], dtype=m.dtype))
  217. _C_ops.asgd_(
  218. param_and_grad[0],
  219. param_and_grad[1],
  220. lr,
  221. d,
  222. ys[index],
  223. paddle.fmin(m, self._n_tensor),
  224. master_weight,
  225. find_master,
  226. )
  227. return None
  228. elif in_pir_mode():
  229. m = paddle.assign(paddle.add(m, to_tensor([1], dtype=m.dtype)))
  230. self._assign_accumulator_master(
  231. block, self._m_acc_str, param_and_grad[0], m, None
  232. )
  233. # The y in the static graph has one more dimension than the y in the dynamic graph.
  234. # So we should unify the shape of y in both dynamic and static graph.
  235. # eg:
  236. # dynamic graph: y.shape is [2, 2]
  237. # static graph: y.shape is [1, 2, 2]
  238. # so we should do
  239. # static graph: y = y[0]
  240. y = y[0]
  241. _C_ops.asgd_(
  242. param_and_grad[0],
  243. param_and_grad[1],
  244. lr,
  245. d,
  246. y,
  247. paddle.fmin(m, self._n_tensor),
  248. master_weight,
  249. find_master,
  250. )
  251. self._assign_accumulator_master(
  252. block, self._y_acc_str, param_and_grad[0], y, index
  253. )
  254. return None
  255. else:
  256. assert isinstance(block, framework.Block)
  257. # create the optimize op
  258. add_inputs = {
  259. "X": m,
  260. "Y": to_tensor([1], dtype=m.dtype),
  261. }
  262. add_outputs = {
  263. "Out": m,
  264. }
  265. block.append_op(
  266. type="elementwise_add",
  267. inputs=add_inputs,
  268. outputs=add_outputs,
  269. )
  270. # The y in the static graph has one more dimension than the y in the dynamic graph.
  271. # So we should unify the shape of y in both dynamic and static graph.
  272. # eg:
  273. # dynamic graph: y.shape is [2, 2]
  274. # static graph: y.shape is [1, 2, 2]
  275. # so we should do
  276. # static graph: y = y[0]
  277. y = y[0]
  278. asgd_inputs = {
  279. "param": param_and_grad[0],
  280. "grad": param_and_grad[1],
  281. "learning_rate": lr,
  282. "d": d,
  283. "y": y,
  284. "n": paddle.fmin(m, self._n_tensor),
  285. }
  286. asgd_outputs = {
  287. "param_out": param_and_grad[0],
  288. "d_out": d,
  289. "y_out": y,
  290. }
  291. asgd_attrs = {"multi_precision": find_master}
  292. if find_master:
  293. asgd_inputs["master_param"] = master_weight
  294. asgd_outputs["master_param_out"] = master_weight
  295. asgd_op = block.append_op(
  296. type=self.type,
  297. inputs=asgd_inputs,
  298. outputs=asgd_outputs,
  299. attrs=asgd_attrs,
  300. stop_gradient=True,
  301. )
  302. ys = paddle.static.setitem(ys, index, y)
  303. self._assign_accumulator_master(
  304. block, self._y_acc_str, param_and_grad[0], ys, None
  305. )
  306. return asgd_op
  307. def _update_param_group(self, parameters):
  308. parameters = parameters.get('params')
  309. return parameters