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.

ftrl.py 9.9 kB

6 years ago
5 years ago
5 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. """FTRL"""
  16. from mindspore.ops import functional as F, composite as C, operations as P
  17. from mindspore.common import Tensor
  18. import mindspore.common.dtype as mstype
  19. from mindspore._checkparam import Validator as validator
  20. from mindspore._checkparam import Rel
  21. from .optimizer import Optimizer, _apply_decay, _grad_scale
  22. _ftrl_opt = C.MultitypeFuncGraph("ftrl_opt")
  23. @_ftrl_opt.register("Function", "Function", "Function", "Function", "Number", "Number", "Number", "Tensor", "Tensor",
  24. "RowTensor", "Tensor", "Tensor", "Bool")
  25. def _tensor_run_opt_with_sparse(opt, spars_opt, push, pull, l1, l2, lr_power, learning_rate, linear,
  26. gradient, weight, moment, ps_parameter):
  27. """Apply sparse ftrl optimizer to the weight parameter when the gradient is sparse."""
  28. success = True
  29. indices = gradient.indices
  30. values = gradient.values
  31. if ps_parameter:
  32. op_shape = P.Shape()
  33. shapes = (op_shape(weight), op_shape(moment), op_shape(linear), op_shape(values), op_shape(indices))
  34. success = F.depend(success, pull(push((values, indices), shapes), weight))
  35. else:
  36. success = F.depend(success, spars_opt(weight, moment, linear, values, indices))
  37. return success
  38. @_ftrl_opt.register("Function", "Function", "Function", "Function", "Number", "Number", "Number", "Tensor", "Tensor",
  39. "Tensor", "Tensor", "Tensor", "Bool")
  40. def _tensor_run_opt(opt, spars_opt, push, pull, l1, l2, lr_power, learning_rate, linear,
  41. gradient, weight, moment, ps_parameter):
  42. """Apply ftrl optimizer to the weight parameter."""
  43. success = True
  44. if ps_parameter:
  45. op_shape = P.Shape()
  46. success = F.depend(success, pull(push((gradient, learning_rate, l1, l2, lr_power),
  47. (op_shape(weight), op_shape(moment), op_shape(linear))), weight))
  48. else:
  49. success = F.depend(success, opt(weight, moment, linear, gradient, learning_rate, l1, l2, lr_power))
  50. return success
  51. def _check_param(initial_accum, lr_power, l1, l2, use_locking, prim_name=None):
  52. """Check param."""
  53. validator.check_value_type("initial_accum", initial_accum, [float], prim_name)
  54. validator.check_number("initial_accum", initial_accum, 0.0, Rel.GE, prim_name)
  55. validator.check_value_type("lr_power", lr_power, [float], prim_name)
  56. validator.check_number("lr_power", lr_power, 0.0, Rel.LE, prim_name)
  57. validator.check_value_type("l1", l1, [float], prim_name)
  58. validator.check_number("l1", l1, 0.0, Rel.GE, prim_name)
  59. validator.check_value_type("l2", l2, [float], prim_name)
  60. validator.check_number("l2", l2, 0.0, Rel.GE, prim_name)
  61. validator.check_value_type("use_locking", use_locking, [bool], prim_name)
  62. class FTRL(Optimizer):
  63. """
  64. Implement the FTRL algorithm with ApplyFtrl Operator.
  65. FTRL is an online convex optimization algorithm that adaptively chooses its regularization function
  66. based on the loss functions. Refer to paper `Adaptive Bound Optimization for Online Convex Optimization
  67. <https://arxiv.org/abs/1002.4908>`_. Refer to paper `Ad Click Prediction: a View from the Trenches
  68. <https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf>`_ for engineering document.
  69. Note:
  70. When separating parameter groups, the weight decay in each group will be applied on the parameters if the
  71. weight decay is positive. When not separating parameter groups, the `weight_decay` in the API will be applied
  72. on all of the parameters.
  73. To improve parameter groups performance, the customized order of parameters can be supported.
  74. The sparse strategy is applied while the SparseGatherV2 operator being used for forward network.
  75. The sparse feature is under continuous development. The sparse behavior is currently performed on the CPU.
  76. Args:
  77. params (Union[list[Parameter], list[dict]]): When the `params` is a list of `Parameter` which will be updated,
  78. the element in `params` must be class `Parameter`. When the `params` is a list of `dict`, the "params",
  79. "lr", "weight_decay" and "order_params" are the keys can be parsed.
  80. - params: Required. The value must be a list of `Parameter`.
  81. - lr: Using different learning rate by separating parameters is currently not supported.
  82. - weight_decay: Optional. If "weight_decay" in the keys, the value of corresponding weight decay
  83. will be used. If not, the `weight_decay` in the API will be used.
  84. - order_params: Optional. If "order_params" in the keys, the value must be the order of parameters and
  85. the order will be followed in optimizer. There are no other keys in the `dict` and the parameters which
  86. in the value of 'order_params' must be in one of group parameters.
  87. initial_accum (float): The starting value for accumulators, must be zero or positive values. Default: 0.1.
  88. learning_rate (float): The learning rate value, must be zero or positive, dynamic learning rate is currently
  89. not supported. Default: 0.001.
  90. lr_power (float): Learning rate power controls how the learning rate decreases during training, must be less
  91. than or equal to zero. Use fixed learning rate if lr_power is zero. Default: -0.5.
  92. l1 (float): l1 regularization strength, must be greater than or equal to zero. Default: 0.0.
  93. l2 (float): l2 regularization strength, must be greater than or equal to zero. Default: 0.0.
  94. use_locking (bool): If true, use locks for updating operation. Default: False.
  95. loss_scale (float): Value for the loss scale. It must be equal to or greater than 1.0. Default: 1.0.
  96. weight_decay (float): Weight decay value to multiply weight, must be zero or positive value. Default: 0.0.
  97. Inputs:
  98. - **grads** (tuple[Tensor]) - The gradients of `params` in the optimizer, the shape is the same as the `params`
  99. in optimizer.
  100. Outputs:
  101. tuple[Parameter], the updated parameters, the shape is the same as `params`.
  102. Examples:
  103. >>> net = Net()
  104. >>> #1) All parameters use the same learning rate and weight decay
  105. >>> optim = nn.FTRL(params=net.trainable_params())
  106. >>>
  107. >>> #2) Use parameter groups and set different values
  108. >>> conv_params = list(filter(lambda x: 'conv' in x.name, net.trainable_params()))
  109. >>> no_conv_params = list(filter(lambda x: 'conv' not in x.name, net.trainable_params()))
  110. >>> group_params = [{'params': conv_params, 'weight_decay': 0.01},
  111. >>> {'params': no_conv_params},
  112. >>> {'order_params': net.trainable_params()}]
  113. >>> optim = nn.FTRL(group_params, learning_rate=0.1, weight_decay=0.0)
  114. >>> # The conv_params's parameters will use weight decay of 0.01.
  115. >>> # The no_conv_params's parameters will use default weight decay of 0.0.
  116. >>> # The final parameters order in which the optimizer will be followed is the value of 'order_params'.
  117. >>>
  118. >>> loss = nn.SoftmaxCrossEntropyWithLogits()
  119. >>> model = Model(net, loss_fn=loss, optimizer=optim)
  120. """
  121. def __init__(self, params, initial_accum=0.1, learning_rate=0.001, lr_power=-0.5, l1=0.0, l2=0.0,
  122. use_locking=False, loss_scale=1.0, weight_decay=0.0):
  123. super(FTRL, self).__init__(learning_rate, params, weight_decay, loss_scale=loss_scale)
  124. if self.dynamic_lr or self.is_group_lr:
  125. raise ValueError('Dynamic learning rate or group learning rate is currently not supported.')
  126. _check_param(initial_accum, lr_power, l1, l2, use_locking, self.cls_name)
  127. self.moments = self.parameters.clone(prefix="moments", init=initial_accum)
  128. self.linear = self.parameters.clone(prefix="linear", init='zeros')
  129. self.l1 = l1
  130. self.l2 = l2
  131. self.lr_power = lr_power
  132. if not self.is_group:
  133. self.decay_flags = tuple((lambda: True)() for x in self.parameters)
  134. self.hyper_map = C.HyperMap()
  135. self.opt = P.ApplyFtrl(use_locking=use_locking)
  136. self.sparse_opt = P.FusedSparseFtrl(learning_rate, l1, l2, lr_power, use_locking=use_locking)
  137. self._ps_pull = P.Pull()
  138. self._ps_push = P.Push("Ftrl", [0, 1, 2])
  139. self._ps_push.add_prim_attr("init_accum", initial_accum)
  140. self._ps_push.add_prim_attr("lr", learning_rate)
  141. self._ps_push.add_prim_attr("l1", l1)
  142. self._ps_push.add_prim_attr("l2", l2)
  143. self._ps_push.add_prim_attr("lr_power", lr_power)
  144. def construct(self, grads):
  145. params = self.parameters
  146. moments = self.moments
  147. linear = self.linear
  148. grads = self.decay_weight(grads)
  149. grads = self.scale_grad(grads)
  150. lr = self.get_lr()
  151. success = self.map_(F.partial(_ftrl_opt, self.opt, self.sparse_opt, self._ps_push, self._ps_pull,
  152. self.l1, self.l2, self.lr_power, lr),
  153. linear, grads, params, moments, self.ps_parameters)
  154. return success