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.

math.py 21 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. """math"""
  16. import math
  17. import numpy as np
  18. from mindspore.ops import operations as P
  19. from mindspore.ops.operations import _inner_ops as inner
  20. from mindspore.common.tensor import Tensor
  21. from mindspore.ops.primitive import constexpr
  22. from mindspore.ops import functional as F
  23. from ..cell import Cell
  24. from ...common import dtype as mstype
  25. from ..._checkparam import Validator as validator
  26. __all__ = ['ReduceLogSumExp', 'Range', 'LinSpace', 'LGamma', 'MatMul', 'Moments']
  27. class ReduceLogSumExp(Cell):
  28. r"""
  29. Reduce a dimension of a tensor by calculating exponential for all elements in the dimension,
  30. then calculate logarithm of the sum.
  31. The dtype of the tensor to be reduced is number.
  32. Args:
  33. keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
  34. If False, don't keep these dimensions.
  35. Default : False.
  36. axis (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  37. Only constant value is allowed.
  38. Inputs:
  39. - **input_x** (Tensor[Number]) - The input tensor. With float16 or float32 data type.
  40. Outputs:
  41. Tensor, has the same dtype as the `input_x`.
  42. - If axis is (), and keep_dims is False,
  43. the output is a 0-D tensor representing the sum of all elements in the input tensor.
  44. - If axis is int, set as 2, and keep_dims is False,
  45. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  46. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  47. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  48. Examples:
  49. >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  50. >>> op = nn.ReduceLogSumExp(keep_dims=True, 1)
  51. >>> output = op(input_x)
  52. >>> output.shape
  53. (3, 1, 5, 6)
  54. """
  55. def __init__(self, axis, keep_dims=False):
  56. super(ReduceLogSumExp, self).__init__()
  57. validator.check_value_type('axis', axis, [int, list, tuple], self.cls_name)
  58. validator.check_value_type('keep_dims', keep_dims, [bool], self.cls_name)
  59. self.axis = axis
  60. self.exp = P.Exp()
  61. self.sum = P.ReduceSum(keep_dims)
  62. self.log = P.Log()
  63. def construct(self, input_x):
  64. exp = self.exp(input_x)
  65. sumexp = self.sum(exp, self.axis)
  66. logsumexp = self.log(sumexp)
  67. return logsumexp
  68. class Range(Cell):
  69. r"""
  70. Creates a sequence of numbers.
  71. Args:
  72. start (Union[int, float]): If `limit` is `None`, the value acts as limit in the range and first entry
  73. defaults to `0`. Otherwise, it acts as first entry in the range.
  74. limit (Union[int, float]): Acts as upper limit of sequence. If `None`, defaults to the value of `start`
  75. while set the first entry of the range to `0`. It can not be equal to `start`.
  76. delta (Union[int, float]): Increment of the range. It can not be equal to zero. Default: 1.
  77. Outputs:
  78. Tensor, the dtype is int if the dtype of `start`, `limit` and `delta` all are int. Otherwise, dtype is float.
  79. Examples:
  80. >>> net = nn.Range(1, 8, 2)
  81. >>> out = net()
  82. [1, 3, 5, 7]
  83. """
  84. def __init__(self, start, limit=None, delta=1):
  85. super(Range, self).__init__()
  86. validator.check_value_type("start", start, [int, float], self.cls_name)
  87. validator.check_value_type("delta", delta, [int, float], self.cls_name)
  88. if delta == 0:
  89. raise ValueError("The input of `delta` can not be equal to zero.")
  90. if limit is not None:
  91. validator.check_value_type("limit", limit, [int, float], self.cls_name)
  92. if isinstance(start, int) and isinstance(limit, int) and isinstance(delta, int):
  93. self.dtype = mstype.int32
  94. else:
  95. self.dtype = mstype.float32
  96. else:
  97. if isinstance(start, int) and isinstance(delta, int):
  98. self.dtype = mstype.int32
  99. else:
  100. self.dtype = mstype.float32
  101. if isinstance(start, int):
  102. start = float(start)
  103. if isinstance(limit, int):
  104. limit = float(limit)
  105. if isinstance(delta, int):
  106. delta = float(delta)
  107. self.range_x = inner.Range(start, limit, delta)
  108. if limit is None:
  109. length_input = math.ceil(start / delta)
  110. else:
  111. length_input = math.ceil((limit - start) / delta)
  112. self.input_tensor = Tensor(list(range(length_input)), self.dtype)
  113. def construct(self):
  114. range_out = self.range_x(self.input_tensor)
  115. return range_out
  116. class LinSpace(Cell):
  117. r"""
  118. Generates values in an interval.
  119. Args:
  120. start (Union[int, float]): The start of interval. With shape of 0-D.
  121. stop (Union[int, float]): The end of interval. With shape of 0-D.
  122. num (int): ticks number in the interval, the ticks include start and stop value. With shape of 0-D.
  123. Outputs:
  124. Tensor, With type same as `start`. The shape is 1-D with length of `num`.
  125. Examples:
  126. >>> linspace = nn.LinSpace(1, 10, 5)
  127. >>> output = linspace()
  128. [1, 3.25, 5.5, 7.75, 10]
  129. """
  130. def __init__(self, start, stop, num):
  131. super(LinSpace, self).__init__()
  132. validator.check_value_type("start", start, [int, float], self.cls_name)
  133. validator.check_value_type("stop", stop, [int, float], self.cls_name)
  134. validator.check_value_type("num", num, [int], self.cls_name)
  135. validator.check_positive_int(num, "num", self.cls_name)
  136. self.is_single = bool(num == 1)
  137. self.lin_space = inner.LinSpace()
  138. self.start = Tensor(start, mstype.float32)
  139. self.stop = Tensor(stop, mstype.float32)
  140. self.assist = Tensor(list(range(num)), mstype.float32)
  141. self.num = Tensor(num, mstype.int32)
  142. self.start_array = Tensor([start], mstype.float32)
  143. def construct(self):
  144. if self.is_single:
  145. return self.start_array
  146. lin_space_out = self.lin_space(self.assist, self.start, self.stop, self.num)
  147. return lin_space_out
  148. @constexpr
  149. def check_tensors_dtype_same(data_dtype, value_dtype, op_name):
  150. """Check tensors data type same."""
  151. if data_dtype in value_dtype:
  152. return True
  153. raise TypeError(f"For '{op_name}', the value data type '{value_dtype}' "
  154. f"is not consistent with assigned tensor data type {data_dtype}.")
  155. class LGamma(Cell):
  156. r"""
  157. Calculate LGamma using Lanczos' approximation refering to "A Precision Approximationof the Gamma Function".
  158. The algorithm is:
  159. .. math::
  160. lgamma(z + 1) = \frac{(\log(2) + \log(pi))}{2} + (z + 1/2) * log(t(z)) - t(z) + A(z)
  161. t(z) = z + kLanczosGamma + 1/2
  162. A(z) = kBaseLanczosCoeff + \sum_{k=1}^n \frac{kLanczosCoefficients[i]}{z + k}
  163. However, if the input is less than 0.5 use Euler's reflection formula:
  164. .. math::
  165. lgamma(x) = \log(pi) - lgamma(1-x) - \log(abs(sin(pi * x)))
  166. And please note that
  167. .. math::
  168. lgamma(+/-inf) = +inf
  169. Thus, the behaviour of LGamma follows:
  170. when x > 0.5, return log(Gamma(x))
  171. when x < 0.5 and is not an interger, return the real part of Log(Gamma(x)) where Log is the complex logarithm
  172. when x is an integer less or equal to 0, return +inf
  173. when x = +/- inf, return +inf
  174. Inputs:
  175. - **input_x** (Tensor[Number]) - The input tensor. Only float16, float32 are supported.
  176. Outputs:
  177. Tensor, has the same shape and dtype as the `input_x`.
  178. Examples:
  179. >>> input_x = Tensor(np.array([2, 3, 4]).astype(np.float32))
  180. >>> op = nn.LGamma()
  181. >>> output = op(input_x)
  182. [3.5762787e-07 6.9314754e-01 1.7917603e+00]
  183. """
  184. def __init__(self):
  185. super(LGamma, self).__init__()
  186. # const numbers
  187. self.k_lanczos_gamma = 7
  188. self.k_base_lanczos_coeff = 0.99999999999980993227684700473478
  189. self.k_lanczos_coefficients = [676.520368121885098567009190444019,
  190. -1259.13921672240287047156078755283,
  191. 771.3234287776530788486528258894,
  192. -176.61502916214059906584551354,
  193. 12.507343278686904814458936853,
  194. -0.13857109526572011689554707,
  195. 9.984369578019570859563e-6,
  196. 1.50563273514931155834e-7]
  197. self.one_half = 0.5
  198. self.one = 1
  199. self.two = 2
  200. self.inf = np.inf
  201. self.pi = np.pi
  202. self.log_2 = np.log(self.two)
  203. self.log_pi = np.log(np.pi)
  204. self.log_sqrt_two_pi = (self.log_2 + self.log_pi) / self.two
  205. self.lanczos_gamma_plus_one_half = self.k_lanczos_gamma + 0.5
  206. self.log_lanczos_gamma_plus_one_half = np.log(self.lanczos_gamma_plus_one_half)
  207. # operations
  208. self.log = P.Log()
  209. self.log1p = P.Log1p()
  210. self.abs = P.Abs()
  211. self.shape = P.Shape()
  212. self.dtype = P.DType()
  213. self.fill = P.Fill()
  214. self.floor = P.Floor()
  215. self.equal = P.Equal()
  216. self.greater = P.Greater()
  217. self.less = P.Less()
  218. self.lessequal = P.LessEqual()
  219. self.select = P.Select()
  220. self.sin = P.Sin()
  221. self.isfinite = P.IsFinite()
  222. def construct(self, input_x):
  223. input_dtype = self.dtype(input_x)
  224. check_tensors_dtype_same(input_dtype, [mstype.float16, mstype.float32], "LGamma")
  225. infinity = self.fill(input_dtype, self.shape(input_x), self.inf)
  226. need_to_reflect = self.less(input_x, 0.5)
  227. neg_input = -input_x
  228. z = self.select(need_to_reflect, neg_input, input_x - 1)
  229. @constexpr
  230. def _calculate_x(z, k_base_lanczos_coeff, k_lanczos_coefficients):
  231. x = k_base_lanczos_coeff
  232. for i in range(8):
  233. product_ = k_lanczos_coefficients[i] / (z + i + 1)
  234. x = product_ + x
  235. return x
  236. x = _calculate_x(z, self.k_base_lanczos_coeff, self.k_lanczos_coefficients)
  237. t = z + self.lanczos_gamma_plus_one_half
  238. log_t = self.log1p(z / self.lanczos_gamma_plus_one_half) + self.log_lanczos_gamma_plus_one_half
  239. log_y = self.log(x) + (z + self.one_half - t / log_t) * log_t + self.log_sqrt_two_pi
  240. abs_input = self.abs(input_x)
  241. abs_frac_input = abs_input - self.floor(abs_input)
  242. input_x = self.select(self.lessequal(input_x, 0.0),
  243. self.select(self.equal(abs_frac_input, 0.0),
  244. infinity, input_x),
  245. input_x)
  246. reduced_frac_input = self.select(self.greater(abs_frac_input, 0.5),
  247. 1 - abs_frac_input, abs_frac_input)
  248. reflection_denom = self.log(self.sin(self.pi * reduced_frac_input))
  249. reflection = self.select(self.isfinite(reflection_denom),
  250. -reflection_denom - log_y + self.log_pi,
  251. -reflection_denom)
  252. result = self.select(need_to_reflect, reflection, log_y)
  253. return self.select(self.isfinite(input_x), result, infinity)
  254. @constexpr
  255. def get_broadcast_matmul_shape(x_shape, y_shape):
  256. """get broadcast_matmul shape"""
  257. if (len(x_shape) < 2) or (len(y_shape) < 2):
  258. raise ValueError('For matmul, rank of x1 and x2 should be equal to or greater than 2, '
  259. + f'but got {x_shape} and {y_shape}.')
  260. x_shape_batch = x_shape[:-2]
  261. y_shape_batch = y_shape[:-2]
  262. if x_shape_batch == y_shape_batch:
  263. return x_shape, y_shape
  264. x_len = len(x_shape)
  265. y_len = len(y_shape)
  266. length = x_len if x_len < y_len else y_len
  267. broadcast_shape_back = []
  268. for i in range(-length, -2):
  269. if x_shape[i] == 1:
  270. broadcast_shape_back.append(y_shape[i])
  271. elif y_shape[i] == 1:
  272. broadcast_shape_back.append(x_shape[i])
  273. elif x_shape[i] == y_shape[i]:
  274. broadcast_shape_back.append(x_shape[i])
  275. else:
  276. raise ValueError(f"For MatMul, the x1_shape {x_shape} and x2_shape {y_shape} can not broadcast.")
  277. broadcast_shape_front = y_shape[0: y_len - length] if length == x_len else x_shape[0: x_len - length]
  278. x_broadcast_shape = broadcast_shape_front + tuple(broadcast_shape_back) + x_shape[-2:]
  279. y_broadcast_shape = broadcast_shape_front + tuple(broadcast_shape_back) + y_shape[-2:]
  280. return x_broadcast_shape, y_broadcast_shape
  281. @constexpr
  282. def check_col_row_equal(x1_shape, x2_shape, transpose_x1, transpose_x2):
  283. """check col and row equal"""
  284. if len(x1_shape) == 1:
  285. transpose_x1 = False
  286. x1_shape = (1,) + x1_shape
  287. if len(x2_shape) == 1:
  288. transpose_x2 = False
  289. x2_shape = x2_shape + (1,)
  290. x1_last = x1_shape[-2:]
  291. x2_last = x2_shape[-2:]
  292. x1_col = x1_last[not transpose_x1] # x1_col = x1_last[1] if (not transpose_a) else x1_last[0]
  293. x2_row = x2_last[transpose_x2] # x2_row = x2_last[0] if (not transpose_b) else x2_last[1]
  294. if x1_col != x2_row:
  295. raise ValueError('The column of matrix dimensions of x1 should be equal to '
  296. + f'the row of matrix dimensions of x2, but got {x1_col} and {x2_row}.')
  297. def matmul_op_select(x1_shape, x2_shape, transpose_x1, transpose_x2):
  298. """select matmul op"""
  299. x1_dim, x2_dim = len(x1_shape), len(x2_shape)
  300. if x1_dim == 1 and x2_dim == 1:
  301. matmul_op = P.Mul()
  302. elif x1_dim <= 2 and x2_dim <= 2:
  303. transpose_x1 = False if x1_dim == 1 else transpose_x1
  304. transpose_x2 = False if x2_dim == 1 else transpose_x2
  305. matmul_op = P.MatMul(transpose_x1, transpose_x2)
  306. elif x1_dim == 1 and x2_dim > 2:
  307. matmul_op = P.BatchMatMul(False, transpose_x2)
  308. elif x1_dim > 2 and x2_dim == 1:
  309. matmul_op = P.BatchMatMul(transpose_x1, False)
  310. else:
  311. matmul_op = P.BatchMatMul(transpose_x1, transpose_x2)
  312. return matmul_op
  313. class MatMul(Cell):
  314. """
  315. Multiplies matrix `x1` by matrix `x2`.
  316. - If both x1 and x2 are 1-dimensional, the dot product is returned.
  317. - If the dimensions of x1 and x2 are all not greater than 2, the matrix-matrix product will be returned. Note if
  318. one of 'x1' and 'x2' is 1-dimensional, the argument will first be expanded to 2 dimension. After the matrix
  319. multiply, the expanded dimension will be removed.
  320. - If at least one of x1 and x2 is N-dimensional (N>2), the none-matrix dimensions(batch) of inputs will be
  321. broadcasted and must be broadcastable. Note if one of 'x1' and 'x2' is 1-dimensional, the argument will first be
  322. expanded to 2 dimension and then the none-matrix dimensions will be broadcasted. After the matrix multiply, the
  323. expanded dimension will be removed.
  324. Args:
  325. transpose_x1 (bool): If true, `a` is transposed before multiplication. Default: False.
  326. transpose_x2 (bool): If true, `b` is transposed before multiplication. Default: False.
  327. Inputs:
  328. - **input_x1** (Tensor) - The first tensor to be multiplied.
  329. - **input_x2** (Tensor) - The second tensor to be multiplied.
  330. Outputs:
  331. Tensor, the shape of the output tensor depends on the dimension of input tensors.
  332. Examples:
  333. >>> net = nn.MatMul()
  334. >>> input_x1 = Tensor(np.ones(shape=[3, 2, 3]), mindspore.float32)
  335. >>> input_x2 = Tensor(np.ones(shape=[3, 4]), mindspore.float32)
  336. >>> output = net(input_x1, input_x2)
  337. >>> print(output.shape)
  338. (3, 2, 4)
  339. """
  340. def __init__(self, transpose_x1=False, transpose_x2=False):
  341. super(MatMul, self).__init__()
  342. validator.check_value_type('transpose_x1', transpose_x1, [bool], self.cls_name)
  343. validator.check_value_type('transpose_x2', transpose_x2, [bool], self.cls_name)
  344. self.transpose_x1 = transpose_x1
  345. self.transpose_x2 = transpose_x2
  346. self.shape_op = P.Shape()
  347. self.expand_op = P.ExpandDims()
  348. self.squeeze_left_op = P.Squeeze(-2)
  349. self.squeeze_right_op = P.Squeeze(-1)
  350. self.reduce_sum_op = P.ReduceSum(keep_dims=False)
  351. def construct(self, x1, x2):
  352. x1_shape = self.shape_op(x1)
  353. x2_shape = self.shape_op(x2)
  354. check_col_row_equal(x1_shape, x2_shape, self.transpose_x1, self.transpose_x2)
  355. matmul_op = matmul_op_select(x1_shape, x2_shape, self.transpose_x1, self.transpose_x2)
  356. x1_dim, x2_dim = len(x1_shape), len(x2_shape)
  357. if x1_dim == x2_dim and x2_dim == 1:
  358. return self.reduce_sum_op(matmul_op(x1, x2), -1)
  359. if x1_dim == 1:
  360. x1 = self.expand_op(x1, 0)
  361. x1_shape = self.shape_op(x1)
  362. if x2_dim == 1:
  363. x2 = self.expand_op(x2, 1)
  364. x2_shape = self.shape_op(x2)
  365. x1_broadcast_shape, x2_broadcast_shape = get_broadcast_matmul_shape(x1_shape, x2_shape)
  366. x1_broadcast_to = P.BroadcastTo(x1_broadcast_shape)
  367. x2_broadcast_to = P.BroadcastTo(x2_broadcast_shape)
  368. if x1_broadcast_shape != x1_shape:
  369. x1 = x1_broadcast_to(x1)
  370. if x2_broadcast_shape != x2_shape:
  371. x2 = x2_broadcast_to(x2)
  372. matmul_broadcast = matmul_op(x1, x2)
  373. if x1_dim == 1:
  374. matmul_broadcast = self.squeeze_left_op(matmul_broadcast)
  375. if x2_dim == 1:
  376. matmul_broadcast = self.squeeze_right_op(matmul_broadcast)
  377. return matmul_broadcast
  378. @constexpr
  379. def _check_input_dtype(param_name, input_dtype, allow_dtypes, cls_name):
  380. validator.check_type_name(param_name, input_dtype, allow_dtypes, cls_name)
  381. class Moments(Cell):
  382. """
  383. Calculate the mean and variance of `x`.
  384. Args:
  385. axis (Union[int, tuple(int)]): Calculates the mean and variance along the specified axis. Default: ().
  386. keep_dims (bool): If true, The dimension of mean and variance are identical with input's.
  387. If false, don't keep these dimensions. Default: False.
  388. Inputs:
  389. - **input_x** (Tensor) - The tensor to be calculated. Only float16 and float32 are supported.
  390. Outputs:
  391. - **mean** (Tensor) - The mean of input x, with the same date type as input x.
  392. - **variance** (Tensor) - The variance of input x, with the same date type as input x.
  393. Examples:
  394. >>> net = nn.Moments(axis=3, keep_dims=True)
  395. >>> input_x = Tensor(np.array([[[[1, 2, 3, 4], [3, 4, 5, 6]]]]), mindspore.float32)
  396. >>> mean, var = net(input_x)
  397. mean: [[[[2.5], [4.5]]]]
  398. var: [[[[1.25], [1.25]]]]
  399. """
  400. def __init__(self, axis=None, keep_dims=None):
  401. super(Moments, self).__init__()
  402. if axis is None:
  403. axis = ()
  404. if isinstance(axis, tuple):
  405. for idx, item in enumerate(axis):
  406. validator.check_value_type("axis[%d]" % idx, item, [int], self.cls_name)
  407. self.axis = validator.check_value_type('axis', axis, [int, tuple], self.cls_name)
  408. if keep_dims is None:
  409. keep_dims = False
  410. self.keep_dims = validator.check_value_type('keep_dims', keep_dims, [bool], self.cls_name)
  411. self.cast = P.Cast()
  412. self.reduce_mean = P.ReduceMean(keep_dims=True)
  413. self.square_diff = P.SquaredDifference()
  414. self.squeeze = P.Squeeze(self.axis)
  415. def construct(self, x):
  416. tensor_dtype = x.dtype
  417. _check_input_dtype("input x", tensor_dtype, [mstype.float16, mstype.float32], self.cls_name)
  418. if tensor_dtype == mstype.float16:
  419. x = self.cast(x, mstype.float32)
  420. mean = self.reduce_mean(x, self.axis)
  421. variance = self.reduce_mean(self.square_diff(x, F.stop_gradient(mean)), self.axis)
  422. if not self.keep_dims:
  423. mean = self.squeeze(mean)
  424. variance = self.squeeze(variance)
  425. if tensor_dtype == mstype.float16:
  426. mean = self.cast(mean, mstype.float16)
  427. variance = self.cast(variance, mstype.float16)
  428. return mean, variance
  429. return mean, variance