param_attr.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # Copyright (c) 2018 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 paddle
  15. from paddle.base.data_feeder import check_type
  16. from paddle.regularizer import WeightDecayRegularizer
  17. __all__ = []
  18. class ParamAttr:
  19. """
  20. Note:
  21. ``gradient_clip`` of ``ParamAttr`` HAS BEEN DEPRECATED since 2.0.
  22. Please use ``need_clip`` in ``ParamAttr`` to specify the clip scope.
  23. There are three clipping strategies: :ref:`api_paddle_nn_ClipGradByGlobalNorm` ,
  24. :ref:`api_paddle_nn_ClipGradByNorm` , :ref:`api_paddle_nn_ClipGradByValue` .
  25. Create a object to represent the attribute of parameter. The attributes are:
  26. name, initializer, learning rate, regularizer, trainable, gradient clip,
  27. and model average.
  28. Parameters:
  29. name (str, optional): The parameter's name. Default None, meaning that the name
  30. would be created automatically.
  31. initializer (Initializer, optional): The method to initial this parameter. Default
  32. None, meaning that the weight parameter is initialized by Xavier initializer,
  33. and the bias parameter is initialized by 0.
  34. learning_rate (float, optional): The parameter's learning rate. The learning rate when
  35. optimize is the global learning rates times the parameter's learning rate times
  36. the factor of learning rate scheduler. Default 1.0.
  37. regularizer (WeightDecayRegularizer, optional): Regularization strategy. There are two method:
  38. :ref:`api_paddle_regularizer_L1Decay` , :ref:`api_paddle_regularizer_L2Decay` . If
  39. regularizer is also set in ``optimizer`` (such as :ref:`api_paddle_optimizer_SGD` ),
  40. that regularizer setting in optimizer will be ignored. Default None, meaning there is
  41. no regularization.
  42. trainable (bool, optional): Whether this parameter is trainable. Default True.
  43. do_model_average (bool, optional): Whether this parameter should do model average
  44. when model average is enabled. Only used in ExponentialMovingAverage. Default True.
  45. need_clip (bool, optional): Whether the parameter gradient need to be clipped in optimizer. Default is True.
  46. Returns:
  47. ParamAttr Object.
  48. Examples:
  49. .. code-block:: python
  50. >>> import paddle
  51. >>> weight_attr = paddle.ParamAttr(name="weight",
  52. ... learning_rate=0.5,
  53. ... regularizer=paddle.regularizer.L2Decay(1.0),
  54. ... trainable=True)
  55. >>> print(weight_attr.name)
  56. weight
  57. >>> paddle.nn.Linear(3, 4, weight_attr=weight_attr)
  58. """
  59. def __init__(
  60. self,
  61. name=None,
  62. initializer=None,
  63. learning_rate=1.0,
  64. regularizer=None,
  65. trainable=True,
  66. do_model_average=True,
  67. need_clip=True,
  68. ):
  69. check_type(name, "name", (str, type(None)), "ParamAttr")
  70. check_type(learning_rate, "learning_rate", (float, int), "ParamAttr")
  71. check_type(trainable, "trainable", (bool), "ParamAttr")
  72. check_type(do_model_average, "do_model_average", (bool), "ParamAttr")
  73. check_type(need_clip, "need_clip", (bool), "ParamAttr")
  74. check_type(
  75. initializer,
  76. "initializer",
  77. (paddle.nn.initializer.Initializer, type(None)),
  78. "ParamAttr",
  79. )
  80. check_type(
  81. regularizer,
  82. "regularizer",
  83. (WeightDecayRegularizer, type(None)),
  84. "ParamAttr",
  85. )
  86. self.name = name
  87. if self.name == "":
  88. raise ValueError("name of ParamAttr can not be empty str")
  89. self.initializer = initializer
  90. self.learning_rate = learning_rate
  91. self.regularizer = regularizer
  92. self.trainable = trainable
  93. self.do_model_average = do_model_average
  94. self.need_clip = need_clip
  95. def _set_default_initializer(self, initializer):
  96. """
  97. Set the default initializer, the initializer should be Constant,
  98. Uniform, Normal, Xavier, MSRA.
  99. Args:
  100. initializer(Initializer): the initializer to set.
  101. Returns:
  102. None
  103. """
  104. if initializer is None:
  105. if self.initializer is None:
  106. raise ValueError("ParamAttr.initializer is not set")
  107. return
  108. if self.initializer is not None:
  109. return
  110. self.initializer = initializer
  111. def _set_default_param_initializer(self):
  112. """
  113. Set the default initializer for the parameter with Xavier.
  114. Args:
  115. None.
  116. Returns:
  117. None.
  118. """
  119. self._set_default_initializer(paddle.nn.initializer.XavierUniform())
  120. def _set_default_bias_initializer(self):
  121. """
  122. Set the default initializer for the bias with Constant(0.0).
  123. Args:
  124. None.
  125. Returns:
  126. None.
  127. """
  128. self._set_default_initializer(paddle.nn.initializer.Constant(0.0))
  129. @staticmethod
  130. def _to_attr(arg):
  131. """
  132. Create ParamAttr[s].
  133. Args:
  134. arg: Arguments to initialize ParamAttr[s]. arg's type can be
  135. str, Initializer, float, WeightDecayRegularizer, BaseGradientClipAttr,
  136. bool, ParamAttr, or a list of above type.
  137. Returns:
  138. ParamAttr[s]: ParamAttr[s] initialized with arg.
  139. Raises:
  140. arg can not initialize a ParamAttr.
  141. """
  142. if arg is None:
  143. return ParamAttr()
  144. elif isinstance(arg, (list, tuple)):
  145. return [ParamAttr._to_attr(a) for a in arg]
  146. elif isinstance(arg, ParamAttr):
  147. return arg
  148. elif isinstance(arg, str):
  149. return ParamAttr(name=arg)
  150. elif isinstance(arg, paddle.nn.initializer.Initializer):
  151. return ParamAttr(initializer=arg)
  152. elif isinstance(arg, WeightDecayRegularizer):
  153. return ParamAttr(regularizer=arg)
  154. elif isinstance(arg, bool):
  155. return ParamAttr._to_attr(None) if arg else False
  156. else:
  157. raise TypeError(f"{type(arg)} cast to ParamAttr")
  158. def _to_kwargs(self, with_initializer=False):
  159. """
  160. Returns the attributes of this parameter.
  161. Args:
  162. with_initializer(bool): Whether to add initializer attr.
  163. Returns:
  164. Parameter attributes(map): The attributes of this parameter.
  165. """
  166. kwargs = {
  167. 'name': self.name,
  168. 'optimize_attr': {'learning_rate': self.learning_rate},
  169. 'regularizer': self.regularizer,
  170. 'trainable': self.trainable,
  171. 'do_model_average': self.do_model_average,
  172. 'need_clip': self.need_clip,
  173. }
  174. if with_initializer:
  175. kwargs['initializer'] = self.initializer
  176. return kwargs
  177. class WeightNormParamAttr(ParamAttr):
  178. r"""
  179. Note:
  180. Please use 'paddle.nn.utils.weight_norm' in dygraph mode.
  181. Note:
  182. ``gradient_clip`` of ``ParamAttr`` HAS BEEN DEPRECATED since 2.0.
  183. Please use ``need_clip`` in ``ParamAttr`` to specify the clip scope.
  184. There are three clipping strategies: :ref:`api_paddle_nn_ClipGradByGlobalNorm` ,
  185. :ref:`api_paddle_nn_ClipGradByNorm` , :ref:`api_paddle_nn_ClipGradByValue` .
  186. Parameter of weight Norm. Weight Norm is a reparameterization of the weight vectors
  187. in a neural network that decouples the magnitude of those weight vectors from
  188. their direction. Weight Norm has been implemented as discussed in this
  189. paper: `Weight Normalization: A Simple Reparameterization to Accelerate
  190. Training of Deep Neural Networks
  191. <https://arxiv.org/pdf/1602.07868.pdf>`_.
  192. Args:
  193. dim(int, optional): Dimension over which to compute the norm. Dim is a non-negative
  194. number which is less than the rank of weight Tensor. For Example, dim can
  195. be chosen from 0, 1, 2, 3 for convolution whose weight shape is [cout, cin, kh, kw]
  196. and rank is 4. Default None, meaning that all elements will be normalized.
  197. name(str, optional): The parameter's name. Default None, meaning that the name would
  198. be created automatically. Please refer to :ref:`api_guide_Name` for more details.
  199. initializer(Initializer, optional): The method to initialize this parameter, such as
  200. ``initializer = paddle.nn.initializer.Constant(1.0)``. Default None,
  201. meaning that the weight parameter is initialized by Xavier initializer, and
  202. the bias parameter is initialized by 0.
  203. learning_rate(float32, optional): The parameter's learning rate when
  204. optimizer is :math:`global\_lr * parameter\_lr * scheduler\_factor`.
  205. Default 1.0.
  206. regularizer (WeightDecayRegularizer, optional): Regularization strategy. There are
  207. two method: :ref:`api_paddle_regularizer_L1Decay` ,
  208. :ref:`api_paddle_regularizer_L2Decay`.
  209. If regularizer is also set in ``optimizer``
  210. (such as :ref:`api_paddle_optimizer_SGD` ), that regularizer setting in
  211. optimizer will be ignored. Default None, meaning there is no regularization.
  212. trainable(bool, optional): Whether this parameter is trainable. Default True.
  213. do_model_average(bool, optional): Whether this parameter should do model average.
  214. Default False.
  215. need_clip (bool, optional): Whether the parameter gradient need to be clipped in optimizer. Default is True.
  216. Examples:
  217. .. code-block:: python
  218. >>> import paddle
  219. >>> paddle.enable_static()
  220. >>> data = paddle.static.data(name="data", shape=[3, 32, 32], dtype="float32")
  221. >>> fc = paddle.static.nn.fc(x=data,
  222. ... size=1000,
  223. ... weight_attr=paddle.static.WeightNormParamAttr(
  224. ... dim=None,
  225. ... name='weight_norm_param',
  226. ... initializer=paddle.nn.initializer.Constant(1.0),
  227. ... learning_rate=1.0,
  228. ... regularizer=paddle.regularizer.L2Decay(0.1),
  229. ... trainable=True,
  230. ... do_model_average=False,
  231. ... need_clip=True))
  232. ...
  233. """
  234. # List to record the parameters reparameterized by weight normalization.
  235. # If these parameters are treated as Variable rather than Parameter,
  236. # it can be used to discriminate these parameters and help to serialize
  237. # these parameters for inference.
  238. params_with_weight_norm = []
  239. def __init__(
  240. self,
  241. dim=None,
  242. name=None,
  243. initializer=None,
  244. learning_rate=1.0,
  245. regularizer=None,
  246. trainable=True,
  247. do_model_average=False,
  248. need_clip=True,
  249. ):
  250. super().__init__(
  251. name=name,
  252. initializer=initializer,
  253. learning_rate=learning_rate,
  254. regularizer=regularizer,
  255. trainable=trainable,
  256. do_model_average=do_model_average,
  257. need_clip=need_clip,
  258. )
  259. self.dim = dim