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.

initializer.py 14 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. """Initializer for cell parameters."""
  16. import numbers
  17. import math
  18. from functools import reduce
  19. import numpy as np
  20. from scipy.stats import truncnorm
  21. from .seed import _get_graph_seed
  22. from . import dtype as mstype
  23. from .tensor import Tensor, MetaTensor
  24. from .._c_expression import random_normal
  25. _INITIALIZER_ALIAS = dict()
  26. class Initializer:
  27. """
  28. The base class of the initializer.
  29. Initialization of tensor basic attributes and model weight values.
  30. Args:
  31. kwargs (dict): Keyword arguments for Initializer.
  32. Returns:
  33. Array, an array after being initialized.
  34. """
  35. def __init__(self, **kwargs):
  36. self._kwargs = kwargs
  37. self._seed = None
  38. @property
  39. def seed(self):
  40. seed_ = self._seed if self._seed is not None else 1
  41. _, seed = _get_graph_seed(seed_, "init")
  42. return seed
  43. @seed.setter
  44. def seed(self, value):
  45. if not isinstance(value, int):
  46. raise TypeError("'value' must be int type.")
  47. self._seed = value
  48. def _initialize(self, *kwargs):
  49. raise NotImplementedError('Must be overridden!')
  50. def __call__(self, arr):
  51. return self._initialize(arr)
  52. def _register(*aliases):
  53. """Return the alias register."""
  54. def alias_reg(cls):
  55. name = cls.__name__
  56. name = name.lower()
  57. if name not in _INITIALIZER_ALIAS:
  58. _INITIALIZER_ALIAS[name] = cls
  59. for alias in aliases:
  60. if alias not in _INITIALIZER_ALIAS:
  61. _INITIALIZER_ALIAS[alias] = cls
  62. return cls
  63. return alias_reg
  64. def _assignment(arr, num):
  65. """Assign the value of `num` to `arr`."""
  66. if arr.shape == ():
  67. arr = arr.reshape((1))
  68. arr[:] = num
  69. arr = arr.reshape(())
  70. else:
  71. if isinstance(num, np.ndarray):
  72. arr[:] = num[:]
  73. else:
  74. arr[:] = num
  75. return arr
  76. @_register('zeros')
  77. class Zero(Initializer):
  78. """
  79. Initialize the array to zero.
  80. Args:
  81. arr (Array): The array to be assigned.
  82. Returns:
  83. Array, an array after being assigned.
  84. """
  85. def _initialize(self, arr):
  86. _assignment(arr, 0)
  87. @_register('ones')
  88. class One(Initializer):
  89. """
  90. Initialize the array to one.
  91. Args:
  92. arr (Array): The array to be assigned.
  93. Returns:
  94. Array, assigned array.
  95. """
  96. def _initialize(self, arr):
  97. _assignment(arr, 1)
  98. def _calculate_fan_in_and_fan_out(shape):
  99. """
  100. calculate fan_in and fan_out
  101. Args:
  102. shape (tuple): input shape.
  103. Returns:
  104. Tuple, a tuple with two elements, the first element is `n_in` and the second element is `n_out`.
  105. """
  106. dimensions = len(shape)
  107. if dimensions < 2:
  108. raise ValueError("Fan in and fan out can not be computed for tensor with fewer than 2 dimensions")
  109. if dimensions == 2: # Linear
  110. fan_in = shape[1]
  111. fan_out = shape[0]
  112. else:
  113. num_input_fmaps = shape[1]
  114. num_output_fmaps = shape[0]
  115. receptive_field_size = 1
  116. if dimensions > 2:
  117. receptive_field_size = shape[2] * shape[3]
  118. fan_in = num_input_fmaps * receptive_field_size
  119. fan_out = num_output_fmaps * receptive_field_size
  120. return fan_in, fan_out
  121. def _calculate_correct_fan(shape, mode):
  122. """
  123. Calculate fan.
  124. Args:
  125. shape (tuple): input shape.
  126. mode (str): only support fan_in and fan_out.
  127. Returns:
  128. fan_in or fan_out.
  129. """
  130. mode = mode.lower()
  131. valid_modes = ['fan_in', 'fan_out']
  132. if mode not in valid_modes:
  133. raise ValueError("Mode {} not supported, please use one of {}".format(mode, valid_modes))
  134. fan_in, fan_out = _calculate_fan_in_and_fan_out(shape)
  135. return fan_in if mode == 'fan_in' else fan_out
  136. def _calculate_gain(nonlinearity, param=None):
  137. """
  138. Calculate gain.
  139. Args:
  140. nonlinearity (str): nonlinearity function.
  141. param (str): used to calculate negative_slope.
  142. Returns:
  143. number.
  144. """
  145. linear_fns = ['linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d']
  146. if nonlinearity in linear_fns or nonlinearity == 'sigmoid':
  147. res = 1
  148. elif nonlinearity == 'tanh':
  149. res = 5.0 / 3
  150. elif nonlinearity == 'relu':
  151. res = math.sqrt(2.0)
  152. elif nonlinearity == 'leaky_relu':
  153. if param is None:
  154. negative_slope = 0.01
  155. elif not isinstance(param, bool) and isinstance(param, int) or isinstance(param, float):
  156. # True/False are instances of int, hence check above
  157. negative_slope = param
  158. else:
  159. raise ValueError("negative_slope {} not a valid number".format(param))
  160. res = math.sqrt(2.0 / (1 + negative_slope ** 2))
  161. else:
  162. raise ValueError("Unsupported nonlinearity {}".format(nonlinearity))
  163. return res
  164. def _calculate_in_and_out(arr):
  165. """
  166. Calculate n_in and n_out.
  167. Args:
  168. arr (Array): Input array.
  169. Returns:
  170. Tuple, a tuple with two elements, the first element is `n_in` and the second element is `n_out`.
  171. """
  172. dim = len(arr.shape)
  173. if dim < 2:
  174. raise ValueError("If initialize data with xavier uniform, the dimension of data must be greater than 1.")
  175. n_in = arr.shape[1]
  176. n_out = arr.shape[0]
  177. if dim > 2:
  178. counter = reduce(lambda x, y: x * y, arr.shape[2:])
  179. n_in *= counter
  180. n_out *= counter
  181. return n_in, n_out
  182. @_register('xavier_uniform')
  183. class XavierUniform(Initializer):
  184. r"""
  185. Initialize the array with xavier uniform algorithm, and from a uniform distribution collect samples within
  186. U[-boundary, boundary] The boundary is defined as :
  187. where :math:`boundary = gain * \sqrt{\frac{6}{n_{in} + n_{out}}}`.
  188. where :math:`n_{in}` is the number of input units in the weight tensor.
  189. where :math:`n_{out}` is the number of output units in the weight tensor.
  190. Args:
  191. gain (Array): The array to be assigned. Default: 1.
  192. Returns:
  193. Array, assigned array.
  194. """
  195. def __init__(self, gain=1):
  196. super(XavierUniform, self).__init__(gain=gain)
  197. self.gain = gain
  198. def _initialize(self, arr):
  199. n_in, n_out = _calculate_in_and_out(arr)
  200. boundary = self.gain * math.sqrt(6.0 / (n_in + n_out))
  201. data = np.random.uniform(-boundary, boundary, arr.shape)
  202. _assignment(arr, data)
  203. @_register('he_uniform')
  204. class HeUniform(Initializer):
  205. r"""
  206. Initialize the array with He kaiming uniform algorithm, and from a uniform distribution collect samples within
  207. U[-boundary, boundary] The boundary is defined as :
  208. where :math:`boundary = \sqrt{\frac{6}{n_{in}}}`.
  209. where :math:`n_{in}` is the number of input units in the weight tensor.
  210. Args:
  211. arr (Array): The array to be assigned.
  212. Returns:
  213. Array, assigned array.
  214. """
  215. def _initialize(self, arr):
  216. n_in, _ = _calculate_in_and_out(arr)
  217. boundary = math.sqrt(6.0 / n_in)
  218. data = np.random.uniform(-boundary, boundary, arr.shape)
  219. _assignment(arr, data)
  220. @_register('he_normal')
  221. class HeNormal(Initializer):
  222. r"""
  223. Initialize the array with He kaiming Normal algorithm, and from a normal distribution collect samples within
  224. N(0, sigma).
  225. Args:
  226. negative_slope (int, float, bool): Default: 0, used when nonlinearity is 'leaky_relu'.
  227. mode (str): Default: fan_in.
  228. nonlinearity (str): Default: leaky_relu.
  229. Returns:
  230. Array, assigned array.
  231. """
  232. def __init__(self, negative_slope=0, mode='fan_in', nonlinearity='leaky_relu'):
  233. super(HeNormal, self).__init__(negative_slope=negative_slope, mode=mode, nonlinearity=nonlinearity)
  234. self.negative_slope = negative_slope
  235. self.mode = mode
  236. self.nonlinearity = nonlinearity
  237. def _initialize(self, arr):
  238. fan = _calculate_correct_fan(arr.shape, self.mode)
  239. gain = _calculate_gain(self.nonlinearity, self.negative_slope)
  240. std = gain / math.sqrt(fan)
  241. data = np.random.normal(0, std, arr.shape)
  242. _assignment(arr, data)
  243. class Constant(Initializer):
  244. """
  245. Initialize a constant.
  246. Args:
  247. value (Union[int, numpy.ndarray]): The value to initialize.
  248. Returns:
  249. Array, an array after being assigned.
  250. """
  251. def __init__(self, value):
  252. super(Constant, self).__init__(value=value)
  253. self.value = value
  254. def _initialize(self, arr):
  255. _assignment(arr, self.value)
  256. @_register()
  257. class Uniform(Initializer):
  258. """
  259. Initialize a uniform array, and obtain values U(-scale, scale) from the uniform distribution
  260. to fill the input tensor.
  261. Args:
  262. scale (float): The scale of the array. Default: 0.07.
  263. Returns:
  264. Array, uniform array.
  265. """
  266. def __init__(self, scale=0.07):
  267. super(Uniform, self).__init__(scale=scale)
  268. self.scale = scale
  269. def _initialize(self, arr):
  270. tmp = np.random.uniform(-self.scale, self.scale, arr.shape)
  271. _assignment(arr, tmp)
  272. @_register()
  273. class Normal(Initializer):
  274. """
  275. Initialize a normal array, and obtain values N(0, sigma) from the uniform distribution
  276. to fill the input tensor.
  277. Args:
  278. sigma (float): The sigma of the array. Default: 0.01.
  279. Returns:
  280. Array, normal array.
  281. """
  282. def __init__(self, sigma=0.01):
  283. super(Normal, self).__init__(sigma=sigma)
  284. self.sigma = sigma
  285. def _initialize(self, arr):
  286. seed = self.seed
  287. output_tensor = Tensor(np.zeros(arr.shape, dtype=np.float32))
  288. random_normal(0, self.sigma, arr.shape, seed, output_tensor)
  289. output_data = output_tensor.asnumpy()
  290. output_data *= self.sigma
  291. _assignment(arr, output_data)
  292. @_register()
  293. class TruncatedNormal(Initializer):
  294. """
  295. Initialize a truncated normal distribution which is a bounded normal distribution within N(low, high).
  296. Args:
  297. sigma (float): The sigma of the array. Default: 0.01.
  298. Returns:
  299. Array, truncated normal array.
  300. """
  301. def __init__(self, sigma=0.01):
  302. super(TruncatedNormal, self).__init__(sigma=sigma)
  303. self.sigma = sigma
  304. def _initialize(self, arr):
  305. tmp = truncnorm.rvs(-2, 2, loc=0, scale=self.sigma, size=arr.shape, random_state=None)
  306. _assignment(arr, tmp)
  307. def initializer(init, shape=None, dtype=mstype.float32):
  308. """
  309. Create and initialize a tensor.
  310. Args:
  311. init (Union[Tensor, str, Initializer, numbers.Number]): Initialize value.
  312. - `str`: The `init` should be the alias of the class inheriting from `Initializer` and the corresponding
  313. class will be called.
  314. - `Initializer`: The `init` should be the class inheriting from `Initializer` to initialize tensor.
  315. - `numbers.Number`: The `Constant` will be called to initialize tensor.
  316. shape (Union[tuple, list, int]): A list of integers, a tuple of integers or an integer as the shape of
  317. output. Default: None.
  318. dtype (:class:`mindspore.dtype`): The type of data in initialized tensor. Default: mindspore.float32.
  319. Returns:
  320. Union[Tensor, Initializer], When `init` is Tensor, the return is Tensor object,
  321. otherwise the return is Initialize object.
  322. Examples:
  323. >>> tensor = initializer('ones', [1, 2, 3], mindspore.float32)
  324. >>> tensor = initializer(One(), [1, 2, 3], mindspore.float32)
  325. >>> tensor = initializer(0, [1, 2, 3], mindspore.float32)
  326. """
  327. if not isinstance(init, (Tensor, numbers.Number, str, Initializer)):
  328. raise TypeError("Unsupported init type '{}'.".format(type(init)))
  329. if isinstance(init, Tensor):
  330. init_shape = init.shape
  331. shape = shape if isinstance(shape, (tuple, list)) else [shape]
  332. if shape is not None and init_shape != tuple(shape):
  333. raise ValueError("The shape of init should be same as variable shape, but got the shape of init {} and "
  334. "the variable shape {}.".format(list(init.shape), shape))
  335. return init
  336. if isinstance(shape, list):
  337. shape = tuple(shape)
  338. elif isinstance(shape, numbers.Number):
  339. shape = (shape,)
  340. for value in shape if shape is not None else ():
  341. if not isinstance(value, int) or value <= 0:
  342. raise ValueError(f"shape is invalid, shape value must be positive integer, shape:{shape}")
  343. if isinstance(init, str):
  344. init = _INITIALIZER_ALIAS[init.lower()]()
  345. if init is None:
  346. raise ValueError("The class corresponding to '{}' was not found.".format(init))
  347. elif isinstance(init, numbers.Number):
  348. init = Constant(init)
  349. shape = shape if shape is not None else init.shape
  350. init_obj = MetaTensor(dtype, shape, init)
  351. return init_obj
  352. __all__ = [
  353. 'Initializer',
  354. 'initializer',
  355. 'TruncatedNormal',
  356. 'Normal',
  357. 'Uniform',
  358. 'HeUniform',
  359. 'HeNormal',
  360. 'XavierUniform',
  361. 'One',
  362. 'Zero',
  363. 'Constant']