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 30 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
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
code check for master # Conflicts: # mindspore/common/initializer.py # mindspore/nn/cell.py # # 似乎您正在做一个拣选提交。如果不对,请删除文件 # .git/CHERRY_PICK_HEAD # 然后重试。 # 请为您的变更输入提交说明。以 '#' 开始的行将被忽略,而一个空的提交 # 说明将会终止提交。 # # 日期: Fri Aug 13 18:40:19 2021 +0800 # # 位于分支 code_review_r1.3 # 您的分支与上游分支 'ma/r1.3' 一致。 # # 您在执行拣选提交 ffda6be35c 的操作。 # # 要提交的变更: # 修改: mindspore/common/__init__.py # 修改: mindspore/common/_register_for_tensor.py # 修改: mindspore/common/api.py # 修改: mindspore/common/dtype.py # 修改: mindspore/common/initializer.py # 修改: mindspore/common/monad.py # 修改: mindspore/common/parameter.py # 修改: mindspore/common/seed.py # 修改: mindspore/common/tensor.py # 修改: mindspore/nn/cell.py # 修改: mindspore/nn/metrics/__init__.py # 修改: mindspore/nn/metrics/confusion_matrix.py # 修改: mindspore/nn/metrics/error.py # 修改: mindspore/nn/metrics/fbeta.py # 修改: mindspore/nn/metrics/loss.py # 修改: mindspore/nn/metrics/metric.py # 修改: mindspore/nn/metrics/precision.py # 修改: mindspore/nn/metrics/recall.py # 修改: mindspore/nn/metrics/topk.py # 修改: mindspore/train/callback/_checkpoint.py # 修改: mindspore/train/model.py # 修改: mindspore/train/serialization.py # # Conflicts: # mindspore/common/api.py # mindspore/common/initializer.py # mindspore/nn/metrics/confusion_matrix.py # # 似乎您正在做一个拣选提交。如果不对,请删除文件 # .git/CHERRY_PICK_HEAD # 然后重试。 # 请为您的变更输入提交说明。以 '#' 开始的行将被忽略,而一个空的提交 # 说明将会终止提交。 # # 日期: Fri Aug 13 18:40:19 2021 +0800 # # 位于分支 code_review_master # 您的分支与上游分支 'ma/master' 一致。 # # 您在执行拣选提交 743f9fbff3 的操作。 # # 要提交的变更: # 修改: mindspore/common/__init__.py # 修改: mindspore/common/_monad.py # 修改: mindspore/common/_register_for_tensor.py # 修改: mindspore/common/api.py # 修改: mindspore/common/dtype.py # 修改: mindspore/common/initializer.py # 修改: mindspore/common/parameter.py # 修改: mindspore/common/seed.py # 修改: mindspore/common/tensor.py # 修改: mindspore/nn/cell.py # 修改: mindspore/nn/metrics/__init__.py # 修改: mindspore/nn/metrics/confusion_matrix.py # 修改: mindspore/nn/metrics/error.py # 修改: mindspore/nn/metrics/fbeta.py # 修改: mindspore/nn/metrics/loss.py # 修改: mindspore/nn/metrics/metric.py # 修改: mindspore/nn/metrics/precision.py # 修改: mindspore/nn/metrics/recall.py # 修改: mindspore/nn/metrics/topk.py # 修改: mindspore/train/callback/_checkpoint.py # 修改: mindspore/train/model.py # 修改: mindspore/train/serialization.py #
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. # Copyright 2020-2021 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. from copy import copy
  17. import numbers
  18. import numpy as np
  19. from .._c_expression import ParamInfo
  20. from . import dtype as mstype
  21. from .. import context
  22. from ..parallel._utils import _get_parallel_mode
  23. from .initializer import initializer
  24. from .tensor import Tensor
  25. from .._checkparam import Validator
  26. from .._c_expression import Tensor as Tensor_
  27. from ..parallel._tensor import _get_slice_index
  28. from ..parallel._auto_parallel_context import auto_parallel_context
  29. from ..parallel._ps_context import _is_role_worker, _is_role_pserver, _is_role_sched, _clone_hash_table
  30. from ..parallel._ps_context import _reinsert_hash_table_size
  31. from ..parallel._ps_context import _insert_weight_init_info, _insert_accumu_init_info
  32. from .seed import _get_global_and_op_seed
  33. __all__ = ['Parameter', 'ParameterTuple']
  34. PARAMETER_NAME_DEFAULT = "Parameter"
  35. PARAMETER_NAME_PREFIX_MAX_LEN = 1024
  36. def _is_in_parallel_mode():
  37. """Get parallel mode."""
  38. return auto_parallel_context().get_parallel_mode() in ["semi_auto_parallel", "auto_parallel"]
  39. def init_to_value(init):
  40. """
  41. Get value of initializer.
  42. Returns:
  43. Value of the initializer.
  44. Raises:
  45. ValueError: The value of the argument 'init' is not correct.
  46. """
  47. if isinstance(init, str):
  48. if init == 'zeros':
  49. return 0.0
  50. if init == 'ones':
  51. return 1.0
  52. raise ValueError("The argument 'init' should be one of values in ['zeros', 'ones'].")
  53. if isinstance(init, numbers.Number):
  54. return float(init)
  55. raise ValueError("The argument 'init' should be number or string, but got {}.".format(type(init)))
  56. class Parameter(Tensor_):
  57. """
  58. An object holding weights of cells, after initialized `Parameter` is a subtype of `Tensor`.
  59. Note:
  60. In auto_parallel mode of "semi_auto_parallel" and "auto_parallel", if init `Parameter` by
  61. a `Tensor`, the type of Parameter will be `Tensor`. `Tensor`
  62. will save the shape and type info of a tensor with no memory usage. The shape can be changed while
  63. compiling for auto-parallel. Call `init_data` will return a Tensor Parameter with initialized data.
  64. If there is an operator in the network that requires part of the inputs to be Parameter,
  65. then the Parameters as this part of the inputs are not allowed to be cast.
  66. It is recommended to use the default value of `name` when initialize a parameter as one attribute of a cell,
  67. otherwise, the parameter name may be different from expected.
  68. Args:
  69. default_input (Union[Tensor, int, float, numpy.ndarray, list]): Parameter data,
  70. to initialize the parameter data.
  71. name (str): Name of the parameter. Default: None.
  72. 1) If the parameter is not given a name, the default name is its variable name. For example, the name of
  73. param_a below is name_a, and the name of param_b is the variable name param_b.
  74. .. code-block::
  75. self.param_a = Parameter(Tensor([1], ms.float32), name="name_a")
  76. self.param_b = Parameter(Tensor([2], ms.float32))
  77. 2) If parameter in list or tuple is not given a name, will give it a unique name. For example, the names of
  78. parameters below are Parameter$1 and Parameter$2.
  79. .. code-block::
  80. self.param_list = [Parameter(Tensor([3], ms.float32)),
  81. Parameter(Tensor([4], ms.float32))]
  82. 3) If the parameter is given a name, and the same name exists between different parameters, an exception
  83. will be thrown. For example, "its name 'name_a' already exists." will be thrown.
  84. .. code-block::
  85. self.param_a = Parameter(Tensor([1], ms.float32), name="name_a")
  86. self.param_tuple = (Parameter(Tensor([5], ms.float32), name="name_a"),
  87. Parameter(Tensor([6], ms.float32)))
  88. 4) If a parameter appear multiple times in list or tuple, check the name of the object only once. For
  89. example, the following example will not throw an exception.
  90. .. code-block::
  91. self.param_a = Parameter(Tensor([1], ms.float32), name="name_a")
  92. self.param_tuple = (self.param_a, self.param_a)
  93. requires_grad (bool): True if the parameter requires gradient. Default: True.
  94. layerwise_parallel (bool): When layerwise_parallel is true in data/hybrid parallel mode,
  95. broadcast and gradients communication would not be applied to parameters. Default: False.
  96. parallel_optimizer (bool): It is used to filter the weight shard operation in semi auto or auto parallel
  97. mode. It works only when enable parallel optimizer in `mindspore.context.set_auto_parallel_context()`.
  98. Default: True.
  99. Examples:
  100. >>> import numpy as np
  101. >>> from mindspore import Parameter, Tensor
  102. >>> import mindspore.ops as ops
  103. >>> import mindspore.nn as nn
  104. >>> import mindspore
  105. >>>
  106. >>> class Net(nn.Cell):
  107. ... def __init__(self):
  108. ... super(Net, self).__init__()
  109. ... self.matmul = ops.MatMul()
  110. ... self.weight = Parameter(Tensor(np.ones((1, 2)), mindspore.float32), name="w", requires_grad=True)
  111. ...
  112. ... def construct(self, x):
  113. ... out = self.matmul(self.weight, x)
  114. ... return out
  115. >>> net = Net()
  116. >>> x = Tensor(np.ones((2, 1)), mindspore.float32)
  117. >>> print(net(x))
  118. [[2.]]
  119. >>> net.weight.set_data(Tensor(np.zeros((1, 2)), mindspore.float32))
  120. >>> print(net(x))
  121. [[0.]]
  122. """
  123. __base_type__ = {}
  124. def __new__(cls, default_input, *args, **kwargs):
  125. init_data_flag = bool(isinstance(default_input, Tensor) and default_input.has_init)
  126. input_class, *class_init_args = Parameter._get_parameter_new_args(default_input)
  127. new_type = Parameter._get_base_class(input_class)
  128. obj = input_class.__new__(new_type)
  129. input_class.__init__(obj, *class_init_args)
  130. # it's better to make the Initializer a kind of tensor.
  131. obj.init_mode = None
  132. obj.is_default_input_init = init_data_flag
  133. if obj.has_init:
  134. obj.init_mode = default_input
  135. return obj
  136. def __reduce_ex__(self, _):
  137. data = self
  138. if self.init_mode is not None:
  139. data = self.init_mode
  140. else:
  141. # cast to break deep infinite loop while deepcopy
  142. data = Tensor(self)
  143. return (
  144. Parameter, (data, self.name, self.requires_grad, self.layerwise_parallel))
  145. def __init__(self, default_input, name=None, requires_grad=True, layerwise_parallel=False, parallel_optimizer=True):
  146. self.param_info = ParamInfo()
  147. self.init_in_server = False
  148. self.cache_enable = False
  149. self.name = name
  150. self.requires_grad = requires_grad
  151. self.layerwise_parallel = layerwise_parallel
  152. self.parallel_optimizer = parallel_optimizer
  153. # this flag for tensor copy data.
  154. self.init_flag = False
  155. # this flag is for ge variable copy data.
  156. self.is_init = False
  157. self._inited_param = None
  158. self._sliced = False
  159. self.is_param_ps = False
  160. self.push_weight_to_server = False
  161. self.pull_weight_from_server = False
  162. self.requires_aggr = True
  163. self._cast_type = None
  164. self._unique = False
  165. self.is_in_parallel = _is_in_parallel_mode()
  166. self._pipeline_stage_list = []
  167. if isinstance(default_input, (Tensor_, Tensor)):
  168. Tensor_.__init__(self, default_input.dtype, default_input.shape)
  169. elif isinstance(default_input, int):
  170. Tensor_.__init__(self, mstype.int64, ())
  171. elif isinstance(default_input, float):
  172. Tensor_.__init__(self, mstype.float32, ())
  173. elif isinstance(default_input, (np.ndarray, list)):
  174. Tensor_.__init__(self, default_input)
  175. else:
  176. raise TypeError(f"The type of the argument 'default_input' must be in ['Tensor', 'int', 'float',"
  177. f" 'numpy.ndarray', 'list']. But got type {type(default_input)}.")
  178. def __deepcopy__(self, memodict):
  179. new_obj = Parameter(self)
  180. new_obj.name = self.name
  181. new_obj._inited_param = self._inited_param # pylint: disable=W0212
  182. return new_obj
  183. @staticmethod
  184. def _get_base_class(input_class):
  185. input_class_name = f'Parameter{input_class.__name__}'
  186. if input_class_name in Parameter.__base_type__:
  187. new_type = Parameter.__base_type__[input_class_name]
  188. else:
  189. new_type = type(input_class_name, (Parameter, input_class), {})
  190. Parameter.__base_type__[input_class_name] = new_type
  191. return new_type
  192. @staticmethod
  193. def _get_parameter_new_args(data):
  194. """Set `set_data` of current `Parameter`."""
  195. if isinstance(data, bool):
  196. raise ValueError('Parameter data can not be `bool`')
  197. if isinstance(data, Tensor) and data.has_init:
  198. if context.get_fl_context('server_mode') != 'FEDERATED_LEARNING':
  199. if _is_in_parallel_mode() or _is_role_worker() or _is_role_sched() or _is_role_pserver():
  200. # do not init data while in auto parallel.
  201. return (Tensor, None, data.dtype, data.shape, data.init)
  202. data = data.init_data().asnumpy()
  203. elif isinstance(data, Tensor):
  204. # make a copy of Tensor to init the parameter
  205. return (Tensor, data.asnumpy(),)
  206. if isinstance(data, int):
  207. return (Tensor, data, mstype.int32)
  208. if isinstance(data, float):
  209. return (Tensor, data, mstype.float32)
  210. return (Tensor, data)
  211. def __str__(self):
  212. return f'Parameter (name={self.name}, shape={self.shape}, dtype={self.dtype}, ' \
  213. f'requires_grad={self.requires_grad})'
  214. def __repr__(self):
  215. return self.__str__()
  216. def __parameter__(self):
  217. """For parse check."""
  218. def set_param_ps(self, init_in_server=False):
  219. """
  220. Set whether the trainable parameter is updated by parameter server and whether the
  221. trainable parameter is initialized on server.
  222. Note:
  223. It only works when a running task is in the parameter server mode.
  224. Args:
  225. init_in_server (bool): Whether trainable parameter updated by parameter server is
  226. initialized on server. Default: False.
  227. """
  228. if not(_is_role_worker() or _is_role_pserver() or _is_role_sched()):
  229. raise RuntimeError("Must complete following two steps before calling set_param_ps: \n"
  230. "1. context.set_ps_context(enable_ps=True) \n"
  231. "2. export MS_ROLE environment variable \n"
  232. "Please refer to the official website for detailed usage.")
  233. self.is_param_ps = True
  234. self.init_in_server = init_in_server
  235. self.param_info.init_in_server = init_in_server
  236. def set_param_fl(self, push_to_server=False, pull_from_server=False, requires_aggr=True):
  237. """
  238. Set the way of parameter and server interaction.
  239. Args:
  240. push_to_server (bool): Whether the parameter should be pushed to server. Default: False.
  241. pull_from_server (bool): Whether the parameter should be pulled from server. Default: False.
  242. requires_aggr (bool): Whether the parameter should be aggregated in the server. Default: True.
  243. """
  244. if push_to_server:
  245. self.push_weight_to_server = True
  246. if pull_from_server:
  247. self.pull_weight_from_server = True
  248. if not requires_aggr:
  249. self.requires_aggr = False
  250. self.param_info.requires_aggr = False
  251. @property
  252. def inited_param(self):
  253. """
  254. Get the new parameter after call the init_data.
  255. Default is a None, If `self` is a Parameter without data, after call the
  256. `init_data` the initialized Parameter with data will be recorded here.
  257. """
  258. return self._inited_param
  259. @property
  260. def name(self):
  261. """Get the name of the parameter."""
  262. return self.param_info.name
  263. @name.setter
  264. def name(self, name_):
  265. """
  266. Define a name for the parameter.
  267. Args:
  268. name_ (`str` or `None`): The name of the parameter. When the parameter is None or an empty string,
  269. the default value `PARAMETER_NAME_DEFAULT` is used.
  270. """
  271. if name_ is None:
  272. name_ = PARAMETER_NAME_DEFAULT
  273. elif isinstance(name_, str):
  274. name_ = name_.strip()
  275. if name_ == '':
  276. name_ = PARAMETER_NAME_DEFAULT
  277. if len(name_) > PARAMETER_NAME_PREFIX_MAX_LEN:
  278. raise ValueError("The length of the '{}' name should be less than {}.".
  279. format(name_, PARAMETER_NAME_PREFIX_MAX_LEN))
  280. else:
  281. raise ValueError("The type of the Parameter's name should be 'string' or 'None', "
  282. "but got {}.".format(type(name_)))
  283. if _is_role_worker() and self.cache_enable:
  284. if len(self.shape) != 2:
  285. raise RuntimeError("The dims of parameter '{}' must be 2, but got {}."
  286. .format(self.name, len(self.shape)))
  287. _reinsert_hash_table_size(name_, self.param_info.name, self.shape[0], self.shape[1])
  288. self.param_info.name = name_
  289. @property
  290. def sliced(self):
  291. """Get slice status of the parameter."""
  292. return self._sliced
  293. @sliced.setter
  294. def sliced(self, sliced_):
  295. self._sliced = sliced_
  296. @property
  297. def comm_fusion(self):
  298. """
  299. Get the fusion type (int) for communication operators corresponding to this parameter.
  300. In `AUTO_PARALLEL` and `SEMI_AUTO_PARALLEL` mode, some communication operators used for parameters or
  301. gradients aggregation are inserted automatically. The value of fusion must be greater than or equal to 0.
  302. When the value of fusion is 0, operators will not be fused together.
  303. """
  304. return self.param_info.comm_fusion
  305. @comm_fusion.setter
  306. def comm_fusion(self, comm_fusion_):
  307. if context.get_context("mode") == context.PYNATIVE_MODE and "auto_parallel" in _get_parallel_mode():
  308. raise RuntimeError(
  309. "`comm_fusion` does not support PYNATIVE_MODE in AUTO_PARALLEL and SEMI_AUTO_PARALLEL mode.")
  310. Validator.check_non_negative_int(comm_fusion_)
  311. self.param_info.comm_fusion = comm_fusion_
  312. @property
  313. def parallel_optimizer_comm_recompute(self):
  314. """
  315. Get the communication recompute status(bool) of optimizer parallel for the parameter.
  316. In `AUTO_PARALLEL` and `SEMI_AUTO_PARALLEL` mode, when applying parallel optimizer, some AllGather operators
  317. used for parameters gathering are inserted automatically. It is used to control the recompute attr for those
  318. AllGather operators.
  319. Note:
  320. - Only `Graph` mode is supported.
  321. - It is recommended to use cell.recompute(parallel_optimizer_comm_recompute=True/False) to configure
  322. the AllGather operators introducing by parallel optimizer rather than using this interface directly.
  323. """
  324. return self.param_info.parallel_optimizer_comm_recompute
  325. @parallel_optimizer_comm_recompute.setter
  326. def parallel_optimizer_comm_recompute(self, parallel_optimizer_comm_recompute_):
  327. Validator.check_bool(parallel_optimizer_comm_recompute_)
  328. self.param_info.parallel_optimizer_comm_recompute = parallel_optimizer_comm_recompute_
  329. @property
  330. def unique(self):
  331. """whether the parameter is already unique or not."""
  332. return self._unique
  333. @unique.setter
  334. def unique(self, unique_):
  335. self._unique = unique_
  336. def clone(self, init='same'):
  337. """
  338. Clone the parameter.
  339. Args:
  340. init (Union[Tensor, str, numbers.Number]): Initialize the shape and dtype of the parameter.
  341. If `init` is a `Tensor` or `numbers.Number`, clone a new parameter with the same shape
  342. and dtype, and the data of the new parameter will be set according to `init`. If `init`
  343. is a `str`, the `init` should be the alias of the class inheriting from `Initializer`.
  344. For example, if `init` is 'same', clone a new parameter with the same data, shape, and
  345. dtype. Default: 'same'.
  346. Returns:
  347. Parameter, a new parameter.
  348. """
  349. x = copy(self)
  350. x.param_info = self.param_info.clone()
  351. x.is_init = False
  352. x.init = self.init
  353. x.is_param_ps = self.is_param_ps
  354. x.init_in_server = self.init_in_server
  355. x.cache_enable = self.cache_enable
  356. x.requires_aggr = self.requires_aggr
  357. if self.cache_shape:
  358. x.cache_shape = self.cache_shape
  359. if init != 'same':
  360. shape = self.shape
  361. dtype = self.dtype
  362. x.set_data(initializer(init, shape=shape, dtype=dtype))
  363. return x
  364. @property
  365. def layerwise_parallel(self):
  366. """
  367. Get the layerwise parallel status(bool) of the parameter.
  368. When layerwise_parallel is true in `DATA_PARALLEL` and `HYBRID_PARALLEL` parallel mode, broadcast and gradients
  369. communication would not be applied to parameters.
  370. """
  371. return self.param_info.layerwise_parallel
  372. @layerwise_parallel.setter
  373. def layerwise_parallel(self, value=True):
  374. if not isinstance(value, bool):
  375. raise TypeError("The argument `layerwise_parallel` must be bool type.")
  376. self.param_info.layerwise_parallel = value
  377. @property
  378. def parallel_optimizer(self):
  379. """
  380. Get the optimizer parallel status(bool) of the parameter.
  381. It is used to filter the weight shard operation in `AUTO_PARALLEL` and `SEMI_AUTO_PARALLEL` mode. It works only
  382. when enable parallel optimizer in `mindspore.context.set_auto_parallel_context()`.
  383. """
  384. return self.param_info.parallel_optimizer
  385. @parallel_optimizer.setter
  386. def parallel_optimizer(self, value=True):
  387. if not isinstance(value, bool):
  388. raise TypeError("The argument `parallel_optimizer` must be bool type.")
  389. self.param_info.parallel_optimizer = value
  390. @property
  391. def cache_enable(self):
  392. """Return whether the parameter is cache enable."""
  393. return self.param_info.cache_enable
  394. @cache_enable.setter
  395. def cache_enable(self, value=True):
  396. if not isinstance(value, bool):
  397. raise TypeError("The argument `cache_enable` must be bool type.")
  398. self.param_info.cache_enable = value
  399. @property
  400. def cache_shape(self):
  401. """Return the cache shape corresponding to the parameter if use cache."""
  402. return self.param_info.cache_shape
  403. @cache_shape.setter
  404. def cache_shape(self, value):
  405. if not isinstance(value, (tuple, list)):
  406. raise TypeError("The argument `cache_shape` must be tuple or list type.")
  407. self.param_info.cache_shape = value
  408. @property
  409. def requires_grad(self):
  410. """
  411. Return whether the parameter requires gradient.
  412. The main function of requires_grad is to tell auto grad to start recording operations on a Tensor.
  413. If a Tensor has requires_grad=False, then Tensor requires_grad will make auto grad start recording
  414. operations on the tensor.
  415. """
  416. return self.param_info.requires_grad
  417. @requires_grad.setter
  418. def requires_grad(self, value=True):
  419. if not isinstance(value, bool):
  420. raise TypeError("The argument `requires_grad` must be bool type")
  421. self.param_info.requires_grad = value
  422. @property
  423. def data(self):
  424. """Return the parameter object."""
  425. return self
  426. def _update_tensor_data(self, data):
  427. """Update the parameter by a Tensor."""
  428. if isinstance(self, Tensor):
  429. self.init_flag = False
  430. self.init = None
  431. return self.assign_value(data)
  432. new_param = Parameter(data, self.name, self.requires_grad)
  433. new_param.param_info = self.param_info
  434. return new_param
  435. def add_pipeline_stage(self, stage):
  436. if not isinstance(stage, int) or stage < 0:
  437. raise TypeError("`stage` must be a positive number of int type")
  438. self._pipeline_stage_list.append(stage)
  439. def set_data(self, data, slice_shape=False):
  440. """
  441. Set Parameter's data.
  442. Args:
  443. data (Union[Tensor, int, float]): new data.
  444. slice_shape (bool): If slice the parameter is set to true, the shape is not checked for consistency.
  445. Default: False.
  446. Returns:
  447. Parameter, the parameter after set data.
  448. """
  449. def raise_type_error(incoming):
  450. raise TypeError(f"Incoming Parameter dtype can not be converted to current dtype implicitly. "
  451. f"Current dtype is {self.dtype}, and incoming is {incoming}. "
  452. f"Use .set_dtype(xxx) to change the dtype.")
  453. if not isinstance(data, (Tensor, int, float)):
  454. raise TypeError(f"Parameter data must be [`Tensor`, `int`, `float`] or a kind of `Tensor` "
  455. f"(like `Tensor`). But with type {type(data)}.")
  456. if isinstance(data, (int, float)):
  457. if self.dtype in mstype.int_type and isinstance(data, float):
  458. raise_type_error(mstype.float_)
  459. data = Tensor(data, self.dtype)
  460. # both not init.
  461. incoming_tensor_is_init = isinstance(data, Tensor) and not data.has_init
  462. current_tensor_is_init = isinstance(self, Tensor) and not self.has_init
  463. if incoming_tensor_is_init and not current_tensor_is_init:
  464. raise TypeError("The original tensor data is initialized, but the argument 'data' is not initialized."
  465. "Please initialize 'data' before call this method.")
  466. if tuple(self.shape) != tuple(data.shape):
  467. # If Slice create Parameter shape can be change.
  468. if not slice_shape:
  469. raise ValueError(f"Can not change the shape of Parameter which has been initialized."
  470. f" Current shape is {self.shape}, and incoming is {data.shape}.")
  471. if self.dtype != data.dtype:
  472. if mstype.implicit_conversion_seq[self.dtype] < mstype.implicit_conversion_seq[data.dtype]:
  473. raise_type_error(data.dtype)
  474. else:
  475. from mindspore.ops import functional as F
  476. data = F.cast(data, self.dtype)
  477. if isinstance(data, Tensor) and data.has_init:
  478. # The parameter has been initialized, directly update by the data
  479. if current_tensor_is_init:
  480. self._update_tensor_data(data.init_data())
  481. else:
  482. # also update the related inited parameter data
  483. if self.inited_param is not None:
  484. self.inited_param.set_data(data)
  485. self.init_mode = data
  486. elif incoming_tensor_is_init or current_tensor_is_init:
  487. self._update_tensor_data(data)
  488. self.sliced = slice_shape
  489. return self
  490. def init_data(self, layout=None, set_sliced=False):
  491. """
  492. Initialize the parameter's data.
  493. Args:
  494. layout (Union[None, tuple]): The parameter's layout info.
  495. layout [dev_mat, tensor_map, slice_shape, filed_size, uniform_split, opt_shard_group]. Default: None.
  496. It's not None only in 'SEMI_AUTO_PARALLEL' or 'AUTO_PARALLEL' mode.
  497. - dev_mat (list(int)): The parameter's device matrix.
  498. - tensor_map (list(int)): The parameter's tensor map.
  499. - slice_shape (list(int)): The parameter's slice shape.
  500. - filed_size (int): The parameter's filed size.
  501. - uniform_split (bool): Whether the parameter is split evenly.
  502. - opt_shard_group (str): The group of the parameter while running optimizer parallel.
  503. set_sliced (bool): True if the parameter is set sliced after initializing the data.
  504. Default: False.
  505. Raises:
  506. RuntimeError: If it is from Initializer, and parallel mode has changed after the Initializer created.
  507. ValueError: If the length of the layout is less than 6.
  508. TypeError: If `layout` is not tuple.
  509. Returns:
  510. Parameter, the `Parameter` after initializing data. If current `Parameter` was already initialized before,
  511. returns the same initialized `Parameter`.
  512. """
  513. if self.is_default_input_init and self.is_in_parallel != _is_in_parallel_mode():
  514. raise RuntimeError("Must set or change parallel mode before any Tensor created.")
  515. if self.init_mode is None:
  516. return self
  517. if self.inited_param is not None:
  518. return self.inited_param
  519. if _is_role_worker() and self.cache_enable:
  520. global_seed, op_seed = _get_global_and_op_seed()
  521. _insert_weight_init_info(self.name, global_seed, op_seed)
  522. init_data_args = ()
  523. if layout is not None:
  524. if not isinstance(layout, tuple):
  525. raise TypeError("The argument 'layout' should be tuple, but got {}.".format(type(layout)))
  526. if len(layout) < 6:
  527. raise ValueError("The length of 'layout' must be larger than 5, but got {}.".format(len(layout)))
  528. slice_index = int(_get_slice_index(layout[0], layout[1]))
  529. init_data_args += (slice_index, layout[2], layout[5])
  530. if _is_role_pserver():
  531. return self
  532. if self.init_in_server and self.is_param_ps and isinstance(self.init_mode, Tensor) and \
  533. self.init_mode.init is not None and (_is_role_worker() or _is_role_sched()):
  534. if self.cache_enable:
  535. data = self.init_mode.init_data(*init_data_args)
  536. else:
  537. data = self.init_mode.init_data(0, [1])
  538. else:
  539. data = self.init_mode.init_data(*init_data_args)
  540. obj = self._update_tensor_data(data)
  541. if id(obj) != id(self):
  542. self._inited_param = obj
  543. obj.init_mode = None
  544. obj.sliced = set_sliced
  545. return obj
  546. class ParameterTuple(tuple):
  547. """
  548. Class for storing tuple of parameters.
  549. Note:
  550. It is used to store the parameters of the network into the parameter tuple collection.
  551. """
  552. def __new__(cls, iterable):
  553. """Create instance object of ParameterTuple."""
  554. data = tuple(iterable)
  555. ids = set()
  556. orders = {}
  557. for x in data:
  558. if not isinstance(x, Parameter):
  559. raise TypeError(f"ParameterTuple input should be `Parameter` collection."
  560. f"But got a {type(iterable)}, {iterable}")
  561. if id(x) not in ids:
  562. ids.add(id(x))
  563. if x.name not in orders.keys():
  564. orders[x.name] = [0, x]
  565. else:
  566. if isinstance(orders[x.name], list):
  567. name = x.name
  568. orders[name][1].name = name + "_" + str(0)
  569. x.name = x.name + "_" + str(1)
  570. orders[name] = 1
  571. else:
  572. orders[x.name] += 1
  573. x.name = x.name + "_" + str(orders[x.name])
  574. return tuple.__new__(ParameterTuple, tuple(data))
  575. def clone(self, prefix, init='same'):
  576. """
  577. Clone the parameters in ParameterTuple element-wisely to generate a new ParameterTuple.
  578. Args:
  579. prefix (str): Namespace of parameter.
  580. init (Union[Tensor, str, numbers.Number]): Initialize the shape and dtype of the parameters.
  581. The definition of `init` is the same as in `Parameter` API. If `init` is 'same', the
  582. parameters in the new parameter tuple are the same as those in the original parameter tuple.
  583. Default: 'same'.
  584. Returns:
  585. Tuple, the new Parameter tuple.
  586. """
  587. Validator.check_str_by_regular(prefix)
  588. new = []
  589. for x in self:
  590. x1 = x.clone(init)
  591. x1.name = prefix + "." + x1.name
  592. new.append(x1)
  593. if not x1.cache_enable:
  594. continue
  595. if _is_role_worker():
  596. _clone_hash_table(x.name, x1.name)
  597. _insert_accumu_init_info(x1.name, init_to_value(init))
  598. return ParameterTuple(new)
  599. def __parameter_tuple__(self):
  600. """For parse check."""