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.

parameter.py 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. """Parameter for cell."""
  16. import numbers
  17. from copy import copy, deepcopy
  18. from . import dtype as mstype
  19. from .initializer import initializer, Initializer
  20. from .tensor import Tensor, MetaTensor
  21. from .._checkparam import _check_str_by_regular
  22. from ..parallel._utils import _set_clone_info, _CloneInfo
  23. from ..parallel._tensor import _get_seed
  24. __all__ = ['Parameter', 'ParameterTuple']
  25. PARAMETER_NAME_DEFAULT = "Parameter"
  26. PARAMETER_NAME_PREFIX_MAX_LEN = 1024
  27. def _check_type(x):
  28. """Check input data type"""
  29. if not isinstance(x, Parameter):
  30. raise ValueError("Should be `Parameter` collection.")
  31. return True
  32. class Parameter:
  33. """
  34. Parameter types of cell models.
  35. Note:
  36. Each parameter of Cell is represented by Parameter class.
  37. Args:
  38. default_input (Union[Tensor, Initializer]): Parameter data, when `default_input` is` Initializer`,
  39. the data stored by Parameter is `MetaTensor`, otherwise it is `Tensor`.
  40. name (str): Name of the child parameter.
  41. requires_grad (bool): True if the parameter requires gradient. Default: True.
  42. layerwise_parallel (bool): A kind of model parallel mode. When layerwise_parallel is true in paralle mode,
  43. broadcast and gradients communication would not be applied on parameters. Default: False.
  44. sparse_grad (bool): True if the parameter's gradient is sparse. Default: False.
  45. """
  46. def __init__(self, default_input, name, requires_grad=True, layerwise_parallel=False, sparse_grad=False):
  47. self.set_parameter_data(default_input)
  48. self.name = name
  49. self.requires_grad = requires_grad
  50. self.layerwise_parallel = layerwise_parallel
  51. self.sparse_grad = sparse_grad
  52. self._is_init = False
  53. self._sliced = False
  54. self.clone_info = _CloneInfo()
  55. def __repr__(self):
  56. format_str = 'Parameter (name={name})'
  57. return format_str.format(name=self._name)
  58. def __parameter__(self):
  59. """For parse check."""
  60. @property
  61. def name(self):
  62. """Get the name of the parameter."""
  63. return self._name
  64. @name.setter
  65. def name(self, name_):
  66. """
  67. Define a name for the parameter.
  68. Args:
  69. name_ (`str` or `None`): The name of the parameter. When the parameter is None or an empty string,
  70. the default value `PARAMETER_NAME_DEFAULT` is used.
  71. """
  72. if name_ is None:
  73. name_ = PARAMETER_NAME_DEFAULT
  74. elif isinstance(name_, str):
  75. name_ = name_.strip()
  76. if name_ == '':
  77. name_ = PARAMETER_NAME_DEFAULT
  78. if len(name_) > PARAMETER_NAME_PREFIX_MAX_LEN:
  79. raise ValueError("The length of the '{}' name should be less than {}.".
  80. format(name_, PARAMETER_NAME_PREFIX_MAX_LEN))
  81. else:
  82. raise ValueError("The type of the name should be `str` or `None`.")
  83. self._name = name_
  84. @property
  85. def sliced(self):
  86. """Get slice status of the parameter."""
  87. return self._sliced
  88. @sliced.setter
  89. def sliced(self, sliced_):
  90. self._sliced = sliced_
  91. @property
  92. def is_init(self):
  93. """Get init status of the parameter."""
  94. return self._is_init
  95. @is_init.setter
  96. def is_init(self, is_init_):
  97. """
  98. Set init status of the parameter.
  99. Args:
  100. is_init_ (bool): The init status of the parameter.
  101. """
  102. self._is_init = is_init_
  103. def clone(self, prefix, init='same'):
  104. """
  105. Clone the parameter.
  106. Args:
  107. prefix (str): Namespace of parameter.
  108. init (Union[Tensor, str, Initializer, numbers.Number]): Initialize the shape of the parameter.
  109. Default: 'same'.
  110. Returns:
  111. Parameter, a new parameter.
  112. """
  113. _check_str_by_regular(prefix)
  114. x = copy(self)
  115. x.name = prefix + '.' + x.name
  116. x.is_init = False
  117. if init != 'same':
  118. shape = self.default_input.shape()
  119. dtype = self.default_input.dtype()
  120. if isinstance(init, (str, Initializer, numbers.Number)):
  121. x.init_mode = initializer(init, shape=shape, dtype=dtype)
  122. x.default_input = MetaTensor(dtype, shape)
  123. else:
  124. x.default_input = initializer(init, shape=shape, dtype=dtype)
  125. x.clone_info = copy(self.clone_info)
  126. _set_clone_info(self.clone_info, x.clone_info)
  127. return x
  128. @property
  129. def layerwise_parallel(self):
  130. return self._layerwise_parallel
  131. @layerwise_parallel.setter
  132. def layerwise_parallel(self, value=True):
  133. if not isinstance(value, bool):
  134. raise TypeError("`layerwise_parallel` parameter must be bool type")
  135. self._layerwise_parallel = value
  136. @property
  137. def requires_grad(self):
  138. """Return whether the parameter requires gradient."""
  139. return self._requires_grad
  140. @requires_grad.setter
  141. def requires_grad(self, value=True):
  142. if not isinstance(value, bool):
  143. raise TypeError("`requires_grad` parameter must be bool type")
  144. self._requires_grad = value
  145. @property
  146. def sparse_grad(self):
  147. """Return whether the parameter's gradient is sparse."""
  148. return self._sparse_grad
  149. @sparse_grad.setter
  150. def sparse_grad(self, value=True):
  151. if not isinstance(value, bool):
  152. raise TypeError("`sparse_grad` parameter must be bool type")
  153. self._sparse_grad = value
  154. @property
  155. def data(self):
  156. return self.default_input
  157. def __add__(self, other):
  158. res = deepcopy(self)
  159. res.default_input = res.default_input + other
  160. return res
  161. def __sub__(self, other):
  162. res = deepcopy(self)
  163. res.default_input = res.default_input - other
  164. return res
  165. def __mul__(self, other):
  166. res = deepcopy(self)
  167. default_input = res.default_input * other
  168. res.default_input = Tensor(default_input.asnumpy().copy())
  169. return res
  170. def __truediv__(self, other):
  171. res = deepcopy(self)
  172. res.default_input = res.default_input / other
  173. return res
  174. def __setitem__(self, index, value):
  175. return self
  176. def set_parameter_data(self, data):
  177. """Set `default_input` of current `Parameter`."""
  178. if isinstance(data, bool):
  179. raise ValueError('Parameter data can not be `bool`')
  180. if isinstance(data, Tensor):
  181. # make a copy of Tensor to init the parameter
  182. data = Tensor(data.asnumpy().copy())
  183. data.init_flag = False
  184. elif isinstance(data, Initializer):
  185. self.init_mode = data
  186. data = MetaTensor(self.init_mode.dtype, self.init_mode.shape)
  187. elif isinstance(data, int):
  188. data = Tensor(data, dtype=mstype.int32)
  189. elif isinstance(data, float):
  190. data = Tensor(data, dtype=mstype.float32)
  191. else:
  192. data = Tensor(data)
  193. data.init_flag = False
  194. self.default_input = data
  195. def init_data(self, layout=None, set_sliced=False):
  196. """
  197. Init data of the parameter.
  198. Args:
  199. layout (list[list[int]]): Parameter slice layout [dev_mat, tensor_map, slice_shape].
  200. - dev_mat (list[int]): Device matrix.
  201. - tensor_map (list[int]): Tensor map.
  202. - slice_shape (list[int]): Shape of slice.
  203. set_sliced (bool): True if should set parameter sliced after init the data of initializer.
  204. Default: False.
  205. """
  206. if not isinstance(self.default_input, MetaTensor):
  207. return
  208. if layout is not None:
  209. if not isinstance(layout, list):
  210. raise TypeError("The layout should be list! layout is {}."
  211. .format(layout))
  212. if len(layout) != 3:
  213. raise ValueError("The length of layout must be 3! layout is {}."
  214. .format(layout))
  215. self.init_mode.shape = layout[2]
  216. self.init_mode.seed = int(_get_seed(layout[0], layout[1]))
  217. self.default_input = self.init_mode.to_tensor()
  218. self.init_mode = None
  219. if set_sliced:
  220. self.sliced = True
  221. class ParameterTuple(tuple):
  222. """
  223. Class for storing tuple of parameters.
  224. Note:
  225. Used to store the parameters of the network into the parameter tuple collection.
  226. """
  227. def __new__(cls, iterable):
  228. """Create instance object of ParameterTuple."""
  229. g = (x for x in iterable if _check_type(x))
  230. return tuple.__new__(ParameterTuple, g)
  231. def clone(self, prefix, init='same'):
  232. """
  233. Clone the parameter.
  234. Args:
  235. prefix (str): Namespace of parameter.
  236. init (str): Initialize the shape of the parameter. Default: 'same'.
  237. Returns:
  238. Tuple, the new Parameter tuple.
  239. """
  240. _check_str_by_regular(prefix)
  241. new = []
  242. for x in self:
  243. x1 = x.clone(prefix, init)
  244. new.append(x1)
  245. return ParameterTuple(new)
  246. def __parameter_tuple__(self):
  247. """For parse check."""