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.

utils_const.py 14 kB

4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. """internal graph-compatible utility functions"""
  16. import math
  17. from itertools import zip_longest, accumulate
  18. from collections import deque
  19. import operator
  20. import mindspore.context as context
  21. from ..ops import functional as F
  22. from ..ops.primitive import constexpr
  23. from ..common import dtype as mstype
  24. from ..common import Tensor
  25. from .._c_expression import Tensor as Tensor_
  26. from .._c_expression import typing
  27. from .._checkparam import Validator as validator
  28. from .dtypes import promotion_rule, dtype_tuple, all_types, dtype_map, rule_for_trigonometric
  29. _check_axis_type = constexpr(validator.check_axis_type)
  30. @constexpr
  31. def _check_shape(shape):
  32. """check the shape param to match the numpy style"""
  33. if not isinstance(shape, (int, tuple, list, typing.Tuple, typing.List)):
  34. raise TypeError(f"only int, tuple and list are allowed for shape, but got {type(shape)}")
  35. if isinstance(shape, int):
  36. shape = (shape,)
  37. if isinstance(shape, (list, typing.List)):
  38. shape = tuple(shape)
  39. for s in shape:
  40. if not isinstance(s, int):
  41. raise TypeError("each entry in shape should be int.")
  42. if s < 0:
  43. raise ValueError("each entry in shape should no less than 0.")
  44. return shape
  45. @constexpr
  46. def _check_dtype(dtype):
  47. """check the input dtype and make conversions"""
  48. # convert the string dtype to mstype.dtype
  49. if isinstance(dtype, str):
  50. dtype = dtype.lower()
  51. dtype = dtype_map[dtype]
  52. elif isinstance(dtype, type):
  53. if dtype is int:
  54. dtype = mstype.int32
  55. elif dtype is float:
  56. dtype = mstype.float32
  57. else:
  58. dtype = mstype.pytype_to_dtype(dtype)
  59. if dtype not in dtype_tuple:
  60. raise TypeError(f"only {all_types} are allowed for dtype, but got {type(dtype)}")
  61. return dtype
  62. @constexpr
  63. def _is_shape_empty(shp):
  64. """Check whether shape contains zero"""
  65. if isinstance(shp, int):
  66. return shp == 0
  67. return F.shape_mul(shp) == 0
  68. @constexpr
  69. def _check_start_normalize(start, ndim):
  70. """check and normalize start argument for rollaxis."""
  71. if start < -ndim or start > ndim:
  72. raise ValueError(f"For rollaxis, start {start} is out of bounds. Ranging from {-ndim} to {ndim} is allowed.")
  73. if start < 0:
  74. start = start + ndim
  75. return start
  76. @constexpr
  77. def _check_axes_range(axes, ndim):
  78. """
  79. Check axes type and normalize the negative axes.
  80. Args:
  81. axes: Axes of the tensor.
  82. ndim (int): The number of dimensions of the tensor.
  83. Return:
  84. Axes (Union[int, tuple(int)]). If input is integer, return integer, else tuple.
  85. Raises:
  86. TypeError: If the axes are not integer, tuple(int) or list(int).
  87. ValueError: If duplicate axes exists or some axis is out of bounds.
  88. """
  89. _check_axis_type(axes, True, True, True)
  90. if isinstance(axes, (list, tuple)):
  91. _check_element_int(axes)
  92. axes = _canonicalize_axis(axes, ndim)
  93. return axes
  94. @constexpr
  95. def _get_device():
  96. """Get the current device (`GPU`, `CPU`, `Ascend`)"""
  97. return context.get_context('device_target')
  98. @constexpr
  99. def _infer_out_shape(*shapes):
  100. """
  101. Returns shape of output after broadcasting. Raises ValueError if shapes cannot be broadcast.
  102. """
  103. shape_out = deque()
  104. reversed_shapes = map(reversed, shapes)
  105. for items in zip_longest(*reversed_shapes, fillvalue=1):
  106. max_size = 0 if 0 in items else max(items)
  107. if any(item not in (1, max_size) for item in items):
  108. raise ValueError(f'operands could not be broadcast together with shapes {*shapes,}')
  109. shape_out.appendleft(max_size)
  110. return tuple(shape_out)
  111. @constexpr
  112. def _can_broadcast(*shapes):
  113. """
  114. Returns Ture if shapes can broadcast, False if they cannot.
  115. """
  116. try:
  117. _infer_out_shape(*shapes)
  118. except ValueError:
  119. return False
  120. finally:
  121. pass
  122. return True
  123. @constexpr
  124. def _check_axis_in_range(axis, ndim):
  125. """Checks axes are with the bounds of ndim"""
  126. if not isinstance(axis, int):
  127. raise TypeError(f'axes should be integers, not {type(axis)}')
  128. if not -ndim <= axis < ndim:
  129. raise ValueError(f'axis {axis} is out of bounds for array of dimension {ndim}')
  130. return axis % ndim
  131. @constexpr
  132. def _check_axis_valid(axes, ndim):
  133. """
  134. Checks axes are valid given ndim, and returns axes that can be passed
  135. to the built-in operator (non-negative, int or tuple)
  136. """
  137. if axes is None:
  138. axes = F.make_range(ndim)
  139. return axes
  140. if isinstance(axes, (tuple, list)):
  141. axes = tuple(map(lambda x: _check_axis_in_range(x, ndim), axes))
  142. if any(axes.count(el) > 1 for el in axes):
  143. raise ValueError('duplicate value in "axis"')
  144. return axes
  145. return (_check_axis_in_range(axes, ndim),)
  146. @constexpr
  147. def _check_shape_aligned(shape1, shape2):
  148. """Checks shape1 and shape2 are valid shapes to perform inner product"""
  149. if shape1[-1] != shape2[-1]:
  150. raise ValueError(f'shapes {shape1} {shape2} not aligned: {shape1[-1]} (dim 0) != {shape2[-1]} (dim 0)')
  151. @constexpr
  152. def _tile_size(shape, out_shape, ndim):
  153. """Returns tile_size such that shape*tile_size = out_shape"""
  154. size = [1]*ndim
  155. for idx, (i, j) in enumerate(zip(shape, out_shape)):
  156. if i != j:
  157. size[idx] = j
  158. return tuple(size)
  159. @constexpr
  160. def _raise_type_error(info, param=None):
  161. """
  162. Raise TypeError in both graph/pynative mode
  163. Args:
  164. info(str): info string to display
  165. param(python obj): any object that can be recognized by graph mode. If is
  166. not None, then param's type information will be extracted and displayed.
  167. Default is None.
  168. """
  169. if param is None:
  170. raise TypeError(info)
  171. raise TypeError(info + f"{type(param)}")
  172. @constexpr
  173. def _raise_value_error(info, param=None):
  174. """
  175. Raise TypeError in both graph/pynative mode
  176. Args:
  177. info(str): info string to display
  178. param(python obj): any object that can be recognized by graph mode. If is
  179. not None, then param's value information will be extracted and displayed.
  180. Default is None.
  181. """
  182. if param is None:
  183. raise ValueError(info)
  184. raise ValueError(info + f"{param}")
  185. @constexpr
  186. def _raise_runtime_error(info, param=None):
  187. """
  188. Raise RuntimeError in both graph/pynative mode
  189. Args:
  190. info(str): info string to display
  191. param(python obj): any object that can be recognized by graph mode. If is
  192. not None, then param's value information will be extracted and displayed.
  193. Default is None.
  194. """
  195. if param is None:
  196. raise RuntimeError(info)
  197. raise RuntimeError(info + f"{param}")
  198. @constexpr
  199. def _raise_unimplemented_error(info, param=None):
  200. """
  201. Raise NotImplementedError in both graph/pynative mode
  202. Args:
  203. info(str): info string to display
  204. param(python obj): any object that can be recognized by graph mode. If is
  205. not None, then param's value information will be extracted and displayed.
  206. Default is None.
  207. """
  208. if param is None:
  209. raise NotImplementedError(info)
  210. raise NotImplementedError(info + f"{param}")
  211. @constexpr
  212. def _empty(dtype, shape):
  213. """Returns an uninitialized array with dtype and shape."""
  214. return Tensor_(dtype, shape)
  215. @constexpr
  216. def _promote(dtype1, dtype2):
  217. if dtype1 == dtype2:
  218. return dtype1
  219. if (dtype1, dtype2) in promotion_rule:
  220. return promotion_rule[dtype1, dtype2]
  221. return promotion_rule[dtype2, dtype1]
  222. @constexpr
  223. def _promote_for_trigonometric(dtype):
  224. return rule_for_trigonometric[dtype]
  225. @constexpr
  226. def _max(*args):
  227. """Returns the maximum value."""
  228. return max(*args)
  229. @constexpr
  230. def _min(*args):
  231. """"Returns the minimum value."""
  232. return min(*args)
  233. @constexpr
  234. def _abs(arg):
  235. """Returns the absolute value."""
  236. return abs(arg)
  237. @constexpr
  238. def _check_same_type(dtype1, dtype2):
  239. return dtype1 == dtype2
  240. @constexpr
  241. def _check_is_float(dtype):
  242. """Returns whether dtype is float16 or float32."""
  243. return dtype in (mstype.float16, mstype.float32)
  244. @constexpr
  245. def _check_is_int(dtype):
  246. return isinstance(dtype, typing.Int)
  247. @constexpr
  248. def _canonicalize_axis(axis, ndim):
  249. """
  250. Check axes are within the number of dimensions of tensor x and normalize the negative axes.
  251. Args:
  252. axis (Union[int, tuple(int), list(int)]): Axes of the tensor.
  253. ndim (int): The number of dimensions of the tensor.
  254. Return:
  255. Axis (Union[int, tuple(int)]). If input is integer, return integer, else tuple.
  256. """
  257. if isinstance(axis, int):
  258. axis = [axis]
  259. for ax in axis:
  260. _check_axis_in_range(ax, ndim)
  261. def canonicalizer(ax):
  262. return ax + ndim if ax < 0 else ax
  263. axis = tuple([canonicalizer(axis) for axis in axis])
  264. if all(axis.count(el) <= 1 for el in axis):
  265. return tuple(sorted(axis)) if len(axis) > 1 else axis[0]
  266. raise ValueError(f"duplicate axes in {axis}.")
  267. @constexpr
  268. def _broadcast_tuples(tup1, tup2):
  269. """
  270. Broadcast two 1D tuples to the same length, if inputs are ints, convert to
  271. tuples first.
  272. """
  273. tup1 = (tup1,) if isinstance(tup1, int) else tup1
  274. tup2 = (tup2,) if isinstance(tup2, int) else tup2
  275. if not isinstance(tup1, (tuple, list)) or not isinstance(tup2, (tuple, list)):
  276. raise TypeError("input shift and axis must be tuple or list or int.")
  277. if len(tup1) == len(tup2):
  278. return tup1, tup2
  279. if len(tup1) == 1:
  280. tup1 *= len(tup2)
  281. elif len(tup2) == 1:
  282. tup2 *= len(tup1)
  283. else:
  284. raise ValueError("shape mismatch: objects cannot be broadcast to a single shape")
  285. return tup1, tup2
  286. @constexpr
  287. def _expanded_shape(ndim, axis_size, axis):
  288. """
  289. Returns a shape with size = 1 for all dimensions
  290. except at axis.
  291. """
  292. return tuple([axis_size if i == axis else 1 for i in range(ndim)])
  293. @constexpr
  294. def _add_unit_axes(shape, ndim, append=False):
  295. """
  296. Prepends shape with 1s so that it has the number of dimensions ndim.
  297. If append is set to True, returns shape appended with 1s instead.
  298. """
  299. if isinstance(shape, int):
  300. shape = (shape,)
  301. ndim_diff = ndim - len(shape)
  302. if ndim_diff > 0:
  303. if append:
  304. shape = [i for i in shape] + [1]*ndim_diff
  305. else:
  306. shape = [1]*ndim_diff + [i for i in shape]
  307. return tuple(shape)
  308. @constexpr
  309. def _check_element_int(lst):
  310. """
  311. Check whether each element in `lst` is an integer.
  312. """
  313. for item in lst:
  314. if not isinstance(item, int):
  315. raise TypeError(f"Each element in {lst} should be integer, but got {type(item)}.")
  316. return True
  317. @constexpr
  318. def _type_convert(force, obj):
  319. """
  320. Convert type of `obj` to `force`.
  321. """
  322. return force(obj)
  323. @constexpr
  324. def _list_comprehensions(obj, item=None, return_tuple=False, make_none=False):
  325. """
  326. Generates a new list/tuple by list comprehension.
  327. Args:
  328. obj (Union[int, list, tuple]):
  329. If integer, it will be the length of the returned tuple/list.
  330. item: The value to be filled. Default: None.
  331. If None, the values in the new list/tuple are the same as obj
  332. or range(obj) when obj is integer.
  333. return_tuple(bool): If true, returns tuple, else returns list.
  334. Returns:
  335. List or tuple.
  336. """
  337. res = []
  338. lst = obj
  339. if isinstance(obj, int):
  340. lst = range(obj)
  341. if make_none:
  342. res = [None for _ in lst]
  343. elif item is None:
  344. res = [i for i in lst]
  345. else:
  346. res = [item for i in lst]
  347. if return_tuple:
  348. return tuple(res)
  349. return res
  350. @constexpr
  351. def _tuple_setitem(tup, idx, value):
  352. """
  353. Returns a tuple with specified `idx` set to `value`.
  354. """
  355. tup = list(tup)
  356. tup[idx] = value
  357. return tuple(tup)
  358. @constexpr
  359. def _iota(dtype, num, increasing=True):
  360. """Creates a 1-D tensor with value: [0,1,...num-1] and dtype."""
  361. # Change to P.Linspace when the kernel is implemented on CPU.
  362. if num <= 0:
  363. raise ValueError("zero shape Tensor is not currently supported.")
  364. if increasing:
  365. return Tensor(list(range(int(num))), dtype)
  366. return Tensor(list(range(int(num)-1, -1, -1)), dtype)
  367. @constexpr
  368. def _ceil(number):
  369. """Ceils the number in graph mode."""
  370. return math.ceil(number)
  371. @constexpr
  372. def _seq_prod(seq1, seq2):
  373. """Returns the element-wise product of seq1 and seq2."""
  374. return tuple(map(lambda x, y: x*y, seq1, seq2))
  375. @constexpr
  376. def _make_tensor(val, dtype):
  377. """Returns the tensor with value `val` and dtype `dtype`."""
  378. return Tensor(val, dtype)
  379. @constexpr
  380. def _tuple_slice(tup, start, end):
  381. """get sliced tuple from start and end."""
  382. return tup[start:end]
  383. @constexpr
  384. def _isscalar(x):
  385. """Returns True if x is a scalar type"""
  386. return isinstance(x, (typing.Number, typing.Int, typing.UInt, typing.Float,
  387. typing.Bool, typing.String))
  388. @constexpr
  389. def _cumprod(x):
  390. return tuple(accumulate(x, operator.mul))
  391. @constexpr
  392. def _in(x, y):
  393. return x in y
  394. @constexpr
  395. def _callable_const(x):
  396. """Returns true if x is a function in graph mode."""
  397. return isinstance(x, typing.Function)
  398. @constexpr
  399. def _check_is_inf(x, negative=False):
  400. if not negative:
  401. return x == float('inf')
  402. return x == float('-inf')