You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

optimizer.py 27 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """optimizer"""
  16. from typing import Iterable
  17. import numpy as np
  18. import mindspore
  19. from mindspore.ops import functional as F, composite as C, operations as P
  20. from mindspore.nn.cell import Cell
  21. from mindspore.nn.layer.container import CellList
  22. from mindspore.common.parameter import Parameter, ParameterTuple
  23. from mindspore.common.initializer import initializer
  24. from mindspore.common.tensor import Tensor, RowTensor
  25. import mindspore.common.dtype as mstype
  26. from mindspore._checkparam import Validator as validator
  27. from mindspore import log as logger
  28. from mindspore.parallel._utils import _get_global_rank, _get_device_num, _get_parallel_mode
  29. from mindspore.context import ParallelMode
  30. from mindspore import context
  31. from mindspore.nn.learning_rate_schedule import LearningRateSchedule
  32. __all__ = ['Optimizer']
  33. class Optimizer(Cell):
  34. """
  35. Base class for all optimizers.
  36. Note:
  37. This class defines the API to add Ops to train a model. Never use
  38. this class directly, but instead instantiate one of its subclasses.
  39. Different parameter groups can set different `learning_rate` and `weight_decay`.
  40. When separating parameter groups, the weight decay in each group will be applied on the parameters if the
  41. weight_decay is positive. For most optimizer, when not separating parameters, the `weight_decay` in the API will
  42. be applied on the parameters without 'beta' or 'gamma' in their names if `weight_decay` is positive.
  43. To improve parameter groups performance, the customized order of parameters can be supported.
  44. Args:
  45. learning_rate (Union[float, Tensor, Iterable, LearningRateSchedule]): A value or a graph for the learning
  46. rate. When the learning_rate is an Iterable or a Tensor in a 1D dimension, use dynamic learning rate, then
  47. the i-th step will take the i-th value as the learning rate. When the learning_rate is LearningRateSchedule,
  48. use dynamic learning rate, the i-th learning rate will be calculated during the process of training
  49. according to the formula of LearningRateSchedule. When the learning_rate is a float or a Tensor in a zero
  50. dimension, use fixed learning rate. Other cases are not supported. The float learning rate must be
  51. equal to or greater than 0. If the type of `learning_rate` is int, it will be converted to float.
  52. parameters (Union[list[Parameter], list[dict]]): When the `parameters` is a list of `Parameter` which will be
  53. updated, the element in `parameters` must be class `Parameter`. When the `parameters` is a list of `dict`,
  54. the "params", "lr", "weight_decay" and "order_params" are the keys can be parsed.
  55. - params: Required. The value must be a list of `Parameter`.
  56. - lr: Optional. If "lr" in the keys, the value of corresponding learning rate will be used.
  57. If not, the `learning_rate` in the API will be used.
  58. - weight_decay: Optional. If "weight_decay" in the keys, the value of corresponding weight decay
  59. will be used. If not, the `weight_decay` in the API will be used.
  60. - order_params: Optional. If "order_params" in the keys, the value must be the order of parameters and
  61. the order will be followed in optimizer. There are no other keys in the `dict` and the parameters which
  62. in the value of 'order_params' must be in one of group parameters.
  63. weight_decay (float): A floating point value for the weight decay. It must be equal to or greater than 0.
  64. If the type of `weight_decay` input is int, it will be converted to float. Default: 0.0.
  65. loss_scale (float): A floating point value for the loss scale. It must be greater than 0. If the
  66. type of `loss_scale` input is int, it will be converted to float. Default: 1.0.
  67. Raises:
  68. ValueError: If the learning_rate is a Tensor, but the dimension of tensor is greater than 1.
  69. TypeError: If the learning_rate is not any of the three types: float, Tensor, nor Iterable.
  70. """
  71. def __init__(self, learning_rate, parameters, weight_decay=0.0, loss_scale=1.0):
  72. super(Optimizer, self).__init__(auto_prefix=False)
  73. if parameters is not None and not isinstance(parameters, list):
  74. parameters = list(parameters)
  75. if not parameters:
  76. raise ValueError("Optimizer got an empty parameter list.")
  77. if not isinstance(parameters[0], (dict, Parameter)):
  78. raise TypeError("Only a list of Parameter or dict can be supported.")
  79. if isinstance(loss_scale, int):
  80. loss_scale = float(loss_scale)
  81. validator.check_value_type("loss_scale", loss_scale, [float], self.cls_name)
  82. validator.check_positive_float(loss_scale, "loss_scale", self.cls_name)
  83. self.loss_scale = loss_scale
  84. weight_decay = self._preprocess_weight_decay(weight_decay)
  85. self._unique = True
  86. self._target = 'Ascend'
  87. self.dynamic_lr = False
  88. self.assignadd = None
  89. self.global_step = None
  90. self.is_group = False
  91. self.is_group_lr = False
  92. self.is_group_params_ordered = False
  93. learning_rate = self._preprocess_single_lr(learning_rate)
  94. if isinstance(parameters[0], dict):
  95. self.is_group = True
  96. self.group_params = []
  97. self.group_lr = []
  98. self.group_weight_decay = []
  99. self._init_group_params(parameters, learning_rate, weight_decay)
  100. # The final value of dynamic_lr can be determined after the process of parse_single_lr and init_group_params
  101. if self.dynamic_lr:
  102. self.assignadd = P.AssignAdd()
  103. self.global_step = Parameter(initializer(0, [1], mindspore.int32), name='global_step')
  104. if self.is_group_lr:
  105. if self.dynamic_lr:
  106. self.learning_rate = CellList(self.group_lr)
  107. else:
  108. self.learning_rate = ParameterTuple(self.group_lr)
  109. else:
  110. self.learning_rate = self._build_single_lr(learning_rate, 'learning_rate')
  111. if self.is_group:
  112. self.parameters = ParameterTuple(self.group_params)
  113. self.weight_decay = tuple(self.group_weight_decay)
  114. decay_filter = lambda x: x > 0
  115. self.decay_flags = tuple(decay_filter(x) for x in self.weight_decay)
  116. self.exec_weight_decay = any(self.decay_flags)
  117. else:
  118. self.parameters = ParameterTuple(parameters)
  119. self.weight_decay = weight_decay * loss_scale
  120. decay_filter = lambda x: 'beta' not in x.name and 'gamma' not in x.name
  121. self.decay_flags = tuple(decay_filter(x) for x in self.parameters)
  122. self.exec_weight_decay = self.weight_decay > 0
  123. ps_filter = lambda x: x.is_param_ps
  124. self.ps_parameters = tuple(ps_filter(x) for x in self.parameters)
  125. self.reciprocal_scale = 1.0 / loss_scale
  126. self.param_length = len(self.parameters)
  127. self.map_ = C.Map()
  128. if context.get_auto_parallel_context("enable_parallel_optimizer"):
  129. if _get_parallel_mode() == ParallelMode.DATA_PARALLEL:
  130. self.use_parallel = True
  131. elif _get_parallel_mode() in (ParallelMode.STAND_ALONE, ParallelMode.HYBRID_PARALLEL):
  132. raise RuntimeError("Parallel optimizer is not supported in {}.".format(_get_parallel_mode()))
  133. else:
  134. self.use_parallel = False
  135. else:
  136. self.use_parallel = False
  137. if self.use_parallel:
  138. if self.cls_name not in ["Lamb", "AdamWeightDecay"]:
  139. raise RuntimeError("Optimizer segmentation does not support optimizer {}".format(self.cls_name))
  140. self.dev_num = _get_device_num()
  141. if self.dev_num > self.param_length:
  142. raise RuntimeError("Optimizer segmentation can not be applied when the number of parameters {} is"
  143. " less than the number of devices {}".format(self.param_length, self.dev_num))
  144. self.param_rank = self._get_parameter_group_id()
  145. self.optim_filter = tuple(map(lambda x: x == _get_global_rank(), self.param_rank))
  146. self.param_names = []
  147. for param in self.parameters:
  148. self.param_names.append(param.name)
  149. else:
  150. self.optim_filter = (True,) * self.param_length
  151. @property
  152. def unique(self):
  153. """The method is to see whether to make unique. The input type is bool. The method is read-only."""
  154. return self._unique
  155. @unique.setter
  156. def unique(self, value):
  157. """Set whether the input value is unique."""
  158. if not isinstance(value, bool):
  159. raise TypeError("The value type must be bool, but got value type is {}".format(type(value)))
  160. self._unique = value
  161. @property
  162. def target(self):
  163. """The method is used to determine whether the parameter is updated on host or device. The input type is str
  164. and can only be 'CPU' and 'Ascend'. In GPU environment, users can only configure value as 'CPU'.
  165. The method is read-only."""
  166. return self._target
  167. @target.setter
  168. def target(self, value):
  169. """If the input value is set to "CPU", the parameters will be updated on the host using the Fused
  170. optimizer operation."""
  171. raise NotImplementedError
  172. def decay_weight(self, gradients):
  173. """
  174. Weight decay.
  175. An approach to reduce the overfitting of a deep learning neural network model.
  176. Args:
  177. gradients (tuple[Tensor]): The gradients of `self.parameters`, and have the same shape as
  178. `self.parameters`.
  179. Returns:
  180. tuple[Tensor], The gradients after weight decay.
  181. """
  182. if self.exec_weight_decay:
  183. params = self.parameters
  184. if self.is_group:
  185. gradients = self.map_(F.partial(_apply_decay), self.weight_decay, self.decay_flags,
  186. params, gradients)
  187. else:
  188. gradients = self.map_(F.partial(_apply_decay, self.weight_decay), self.decay_flags,
  189. params, gradients)
  190. return gradients
  191. def scale_grad(self, gradients):
  192. """
  193. Loss scale for mixed precision.
  194. An approach of mixed precision training to improve the speed and energy efficiency of training deep neural
  195. network.
  196. Args:
  197. gradients (tuple[Tensor]): The gradients of `self.parameters`, and have the same shape as
  198. `self.parameters`.
  199. Returns:
  200. tuple[Tensor], The gradients after loss scale.
  201. """
  202. if self.reciprocal_scale != 1.0:
  203. gradients = self.map_(F.partial(_grad_scale, self.reciprocal_scale), gradients)
  204. return gradients
  205. def _grad_sparse_indices_deduplicate(self, gradients):
  206. """ In the case of using big operators, de duplicate the 'indexes' in gradients."""
  207. if self._target != 'CPU' and self._unique:
  208. gradients = self.map_(F.partial(_indices_deduplicate), gradients)
  209. return gradients
  210. def _preprocess_weight_decay(self, weight_decay):
  211. """Check weight decay, and convert int to float."""
  212. if isinstance(weight_decay, (float, int)):
  213. weight_decay = float(weight_decay)
  214. validator.check_non_negative_float(weight_decay, "weight_decay", self.cls_name)
  215. return weight_decay
  216. raise TypeError("Weight decay should be int or float.")
  217. def _preprocess_single_lr(self, learning_rate):
  218. """Check lr value, and convert lr to a float, a Tensor or a LearningRateSchedule."""
  219. if isinstance(learning_rate, (float, int)):
  220. learning_rate = float(learning_rate)
  221. validator.check_non_negative_float(learning_rate, "learning rate", self.cls_name)
  222. return learning_rate
  223. if isinstance(learning_rate, Tensor) and learning_rate.dim() == 0:
  224. return learning_rate
  225. self.dynamic_lr = True
  226. if isinstance(learning_rate, Iterable):
  227. return Tensor(np.array(list(learning_rate)).astype(np.float32))
  228. if isinstance(learning_rate, Tensor):
  229. if learning_rate.dim() > 1:
  230. raise ValueError("The dim of `Tensor` type Learning rate should be a 0 or 1,"
  231. f"but got {learning_rate.dim()}.")
  232. if learning_rate.dim() == 1 and learning_rate.size() < 2:
  233. logger.warning("If use `Tensor` type dynamic learning rate, please make sure that the number"
  234. "of elements in the tensor passed is greater than 1.")
  235. return learning_rate
  236. if isinstance(learning_rate, LearningRateSchedule):
  237. return learning_rate
  238. raise TypeError("Learning rate should be int, float, Tensor, Iterable or LearningRateSchedule.")
  239. def _build_single_lr(self, learning_rate, name):
  240. """Build learning rate value, convert learning rate to a Parameter or a LearningRateSchedule."""
  241. if isinstance(learning_rate, float):
  242. learning_rate = Parameter(Tensor(learning_rate, mstype.float32), name)
  243. if self.is_group_lr and self.dynamic_lr:
  244. learning_rate = _ConvertToCell(learning_rate)
  245. return learning_rate
  246. if isinstance(learning_rate, Tensor) and learning_rate.dim() == 0:
  247. learning_rate = Parameter(learning_rate, name)
  248. if self.is_group_lr and self.dynamic_lr:
  249. learning_rate = _ConvertToCell(learning_rate)
  250. return learning_rate
  251. if isinstance(learning_rate, Tensor) and learning_rate.dim() == 1:
  252. return _IteratorLearningRate(learning_rate, name)
  253. return learning_rate
  254. def _check_group_params(self, parameters):
  255. """Check group params."""
  256. parse_keys = ['params', 'lr', 'weight_decay', 'order_params']
  257. for group_param in parameters:
  258. invalid_key = list(filter(lambda x: x not in parse_keys, group_param.keys()))
  259. if invalid_key:
  260. raise KeyError(f'The key "{invalid_key}" cannot be recognized in group params.')
  261. if 'order_params' in group_param.keys():
  262. if len(group_param.keys()) > 1:
  263. raise ValueError("The order params dict in group parameters should "
  264. "only include the 'order_params' key.")
  265. if not isinstance(group_param['order_params'], Iterable):
  266. raise TypeError("The value of 'order_params' should be an Iterable type.")
  267. continue
  268. if not group_param['params']:
  269. raise ValueError("Optimizer got an empty group parameter list.")
  270. for param in group_param['params']:
  271. if not isinstance(param, Parameter):
  272. raise TypeError("The group param should be an iterator of Parameter type.")
  273. def _parse_group_params(self, parameters, learning_rate):
  274. """Parse group params."""
  275. self._check_group_params(parameters)
  276. if isinstance(learning_rate, Tensor) and learning_rate.dim() == 1:
  277. tensor_lr_length = learning_rate.size()
  278. else:
  279. tensor_lr_length = 0
  280. for group_param in parameters:
  281. if 'order_params' in group_param.keys():
  282. if len(group_param.keys()) > 1:
  283. raise ValueError("The order params dict in group parameters should "
  284. "only include the 'order_params' key.")
  285. if not isinstance(group_param['order_params'], Iterable):
  286. raise TypeError("The value of 'order_params' should be an Iterable type.")
  287. self.is_group_params_ordered = True
  288. continue
  289. if 'lr' in group_param.keys():
  290. self.is_group_lr = True
  291. group_lr = self._preprocess_single_lr(group_param['lr'])
  292. if isinstance(group_lr, Tensor) and group_lr.dim() == 1:
  293. group_lr_length = group_lr.size()
  294. if tensor_lr_length == 0:
  295. tensor_lr_length = group_lr_length
  296. elif group_lr_length != tensor_lr_length:
  297. raise ValueError("The Tensor type dynamic learning rate in group should be the same size.")
  298. def _init_group_params(self, parameters, learning_rate, weight_decay):
  299. """Initialize learning rate or weight decay in group params."""
  300. self._parse_group_params(parameters, learning_rate)
  301. default_lr = self._build_single_lr(learning_rate, 'learning_rate')
  302. params_store = []
  303. for group_num, group_param in enumerate(parameters):
  304. if 'order_params' in group_param.keys():
  305. ordered_parameters = group_param['order_params']
  306. continue
  307. self.group_params += group_param['params']
  308. if 'lr' in group_param.keys():
  309. lr_param_name = 'learning_rate_group_' + str(group_num)
  310. lr = self._preprocess_single_lr(group_param['lr'])
  311. lr = self._build_single_lr(lr, lr_param_name)
  312. else:
  313. lr = default_lr
  314. if 'weight_decay' in group_param.keys():
  315. cur_weight_decay = self._preprocess_weight_decay(group_param['weight_decay'])
  316. weight_decay_ = cur_weight_decay * self.loss_scale
  317. else:
  318. weight_decay_ = weight_decay * self.loss_scale
  319. for key in group_param.keys():
  320. if key not in ('params', 'lr', 'weight_decay'):
  321. logger.warning(f"The optimizer cannot parse '{key}' when setting parameter groups.")
  322. for param in group_param['params']:
  323. validator.check_value_type("parameter", param, [Parameter], self.cls_name)
  324. if param.name in params_store:
  325. raise RuntimeError(f"The {param.name} parameter has appeared in parameter groups.")
  326. params_store.append(param.name)
  327. self.group_lr.append(lr)
  328. self.group_weight_decay.append(weight_decay_)
  329. if self.is_group_params_ordered:
  330. self._order_and_adjust_group_params(ordered_parameters)
  331. def _order_and_adjust_group_params(self, ordered_parameters):
  332. """
  333. Order group parameter, learning rate and weight decay in group params.
  334. """
  335. params_length = len(self.group_params)
  336. if len(ordered_parameters) != len(self.group_params):
  337. raise ValueError(f"The value of 'order_params' should be same with all group parameters.")
  338. ordered_params = [None] * params_length
  339. ordered_learning_rate = [None] * params_length
  340. ordered_weight_decay = [None] * params_length
  341. params_name = [param.name for param in ordered_parameters]
  342. for param, lr, wd in zip(self.group_params, self.group_lr, self.group_weight_decay):
  343. index = params_name.index(param.name)
  344. ordered_params[index] = param
  345. ordered_learning_rate[index] = lr
  346. ordered_weight_decay[index] = wd
  347. self.group_params = ordered_params
  348. self.group_lr = ordered_learning_rate
  349. self.group_weight_decay = ordered_weight_decay
  350. def get_lr(self):
  351. """
  352. Get the learning rate of current step.
  353. Returns:
  354. float, the learning rate of current step.
  355. """
  356. lr = self.learning_rate
  357. if self.dynamic_lr:
  358. if self.is_group_lr:
  359. lr = ()
  360. for learning_rate in self.learning_rate:
  361. current_dynamic_lr = learning_rate(self.global_step)
  362. lr += (current_dynamic_lr,)
  363. else:
  364. lr = self.learning_rate(self.global_step)
  365. F.control_depend(lr, self.assignadd(self.global_step, 1))
  366. return lr
  367. def get_lr_parameter(self, param):
  368. """
  369. Get the learning rate of parameter.
  370. Args:
  371. param (Union[Parameter, list[Parameter]]): The `Parameter` or list of `Parameter`.
  372. Returns:
  373. Parameter, single `Parameter` or `list[Parameter]` according to the input type.
  374. """
  375. def get_lr_value(learning_rate):
  376. if isinstance(learning_rate, (_ConvertToCell, _IteratorLearningRate)):
  377. return learning_rate.learning_rate
  378. return learning_rate
  379. if isinstance(param, Parameter):
  380. param_list = [param]
  381. elif isinstance(param, list):
  382. param_list = param
  383. else:
  384. raise TypeError(f"The parameter only support 'Parameter' or 'list' type.")
  385. lr = []
  386. ids = [id(p) for p in self.parameters]
  387. for p in param_list:
  388. validator.check_value_type("parameter", p, [Parameter], self.cls_name)
  389. if id(p) not in ids:
  390. raise ValueError(f"The parameter {p.name} is not in optimizer.")
  391. if self.is_group_lr:
  392. index = ids.index(id(p))
  393. lr.append(get_lr_value(self.learning_rate[index]))
  394. else:
  395. lr.append(get_lr_value(self.learning_rate))
  396. return lr if isinstance(param, list) else lr[0]
  397. def _get_parameter_group_id(self):
  398. """
  399. Get the parameter partition group id, which is less than the number of devices.
  400. Returns:
  401. tuple, the group id tuple of parameters.
  402. """
  403. rank_list = ()
  404. count = 0
  405. for _ in range(self.param_length):
  406. rank_list = rank_list + (count,)
  407. count = count + 1
  408. if count == self.dev_num:
  409. count = 0
  410. return rank_list
  411. def broadcast_params(self, optim_result):
  412. """
  413. Apply Broadcast operations in the sequential order of parameter groups.
  414. Returns:
  415. bool, the status flag.
  416. """
  417. param_group = []
  418. key_group = []
  419. for _ in range(self.dev_num):
  420. param_group.append(F.make_tuple())
  421. key_group.append(F.make_tuple())
  422. for i in range(self.param_length):
  423. param_group[self.param_rank[i]] = param_group[self.param_rank[i]] + (self.parameters[i],)
  424. key = P.MakeRefKey(self.param_names[i])()
  425. key_group[self.param_rank[i]] = key_group[self.param_rank[i]] + (key,)
  426. new_param_group = []
  427. for root in range(self.dev_num):
  428. ops = P.Broadcast(root)
  429. next_params = ops(param_group[root])
  430. new_param_group.append(next_params)
  431. for i in range(F.tuple_len(next_params)):
  432. F.assign(key_group[root][i], next_params[i])
  433. status = F.control_depend(optim_result, new_param_group[0][0])
  434. for i in range(self.dev_num - 1):
  435. status = F.depend(F.control_depend(new_param_group[i], new_param_group[i+1][0]), status)
  436. return status
  437. def construct(self, *hyper_params):
  438. raise NotImplementedError
  439. op_add = P.AddN()
  440. op_gather = P.GatherV2()
  441. _apply_decay = C.MultitypeFuncGraph("apply_decay")
  442. @_apply_decay.register("Number", "Bool", "Tensor", "RowTensor")
  443. def _tensor_apply_decay_with_sparse(weight_decay, if_apply, weight, gradient):
  444. """Get grad with weight_decay."""
  445. if if_apply:
  446. indices = gradient.indices
  447. values = op_add((op_gather(weight, indices, 0) * weight_decay, gradient.values))
  448. shape = gradient.dense_shape
  449. return RowTensor(indices, values, shape)
  450. return gradient
  451. @_apply_decay.register("Number", "Bool", "Tensor", "Tensor")
  452. def _tensor_apply_decay(weight_decay, if_apply, weight, gradient):
  453. """Get grad with weight_decay."""
  454. if if_apply:
  455. return op_add((weight * weight_decay, gradient))
  456. return gradient
  457. _grad_scale = C.MultitypeFuncGraph("grad_scale")
  458. _indices_deduplicate = C.MultitypeFuncGraph("indices_deduplicate")
  459. @_grad_scale.register("Number", "Tensor")
  460. def tensor_grad_scale(scale, grad):
  461. """Get grad with scale."""
  462. if scale == 1.0:
  463. return grad
  464. return grad * scale
  465. @_grad_scale.register("Number", "RowTensor")
  466. def tensor_grad_scale_with_sparse(scale, grad):
  467. """Get grad with scale."""
  468. if scale == 1.0:
  469. return grad
  470. return RowTensor(grad.indices, grad.values * scale, grad.dense_shape)
  471. @_indices_deduplicate.register("RowTensor")
  472. def rowtensor_deduplicate_indices_slices(grad):
  473. """Unique the indices and sums the 'values' corresponding to the duplicate indices."""
  474. indices = grad.indices
  475. values = grad.values
  476. unique_indices, index_position = P.Unique()(indices)
  477. summed_values = P.UnsortedSegmentSum()(values, index_position, P.DynamicShape()(unique_indices)[0])
  478. return RowTensor(unique_indices, summed_values, grad.dense_shape)
  479. @_indices_deduplicate.register("Tensor")
  480. def tensor_deduplicate_indice_slices(grad):
  481. """Return the input gradient directly in the dense sences."""
  482. return grad
  483. class _ConvertToCell(LearningRateSchedule):
  484. """Inner api, convert learning rate of scalar to LearningRateSchedule."""
  485. def __init__(self, learning_rate):
  486. super(_ConvertToCell, self).__init__()
  487. if not isinstance(learning_rate, Parameter):
  488. raise TypeError('Learning rate must be Parameter.')
  489. self.learning_rate = learning_rate
  490. def construct(self, global_step):
  491. return self.learning_rate + 1.0 - 1.0
  492. class _IteratorLearningRate(LearningRateSchedule):
  493. """Inner api, convert learning rate of Tensor(list) to LearningRateSchedule."""
  494. def __init__(self, learning_rate, name):
  495. super(_IteratorLearningRate, self).__init__()
  496. if isinstance(learning_rate, Tensor):
  497. if learning_rate.dim() != 1:
  498. raise ValueError("The dim of `Tensor` type dynamic learning rate should be a 1,"
  499. f"but got {learning_rate.dim()}.")
  500. else:
  501. raise TypeError("Learning rate should be Tensor.")
  502. self.learning_rate = Parameter(learning_rate, name)
  503. self.gather = P.GatherV2()
  504. def construct(self, global_step):
  505. return self.gather(self.learning_rate, global_step, 0)