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 13 kB

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