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