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 11 kB

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