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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 isinstance(axes, int):
  144. _check_axis_in_range(axes, ndim)
  145. return (axes % ndim,)
  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 all(axes.count(el) <= 1 for el in axes):
  151. return axes
  152. if axes is None:
  153. axes = F.make_range(ndim)
  154. return axes
  155. raise ValueError('duplicate value in "axis"')
  156. @constexpr
  157. def _check_shape_aligned(shape1, shape2):
  158. """Checks shape1 and shape2 are valid shapes to perform inner product"""
  159. if shape1[-1] != shape2[-1]:
  160. raise ValueError(f'shapes {shape1} {shape2} not aligned: {shape1[-1]} (dim 0) != {shape2[-1]} (dim 0)')
  161. @constexpr
  162. def _tile_size(shape, out_shape, ndim):
  163. """Returns tile_size such that shape*tile_size = out_shape"""
  164. size = [1]*ndim
  165. for idx, (i, j) in enumerate(zip(shape, out_shape)):
  166. if i != j:
  167. size[idx] = j
  168. return tuple(size)
  169. @constexpr
  170. def _raise_type_error(info, param=None):
  171. """
  172. Raise TypeError in both graph/pynative mode
  173. Args:
  174. info(str): info string to display
  175. param(python obj): any object that can be recognized by graph mode. If is
  176. not None, then param's type information will be extracted and displayed.
  177. Default is None.
  178. """
  179. if param is None:
  180. raise TypeError(info)
  181. raise TypeError(info + f"{type(param)}")
  182. @constexpr
  183. def _raise_value_error(info, param=None):
  184. """
  185. Raise TypeError in both graph/pynative mode
  186. Args:
  187. info(str): info string to display
  188. param(python obj): any object that can be recognized by graph mode. If is
  189. not None, then param's value information will be extracted and displayed.
  190. Default is None.
  191. """
  192. if param is None:
  193. raise ValueError(info)
  194. raise ValueError(info + f"{param}")
  195. @constexpr
  196. def _empty(dtype, shape):
  197. """Returns an uninitialized array with dtype and shape."""
  198. return Tensor_(dtype, shape)
  199. @constexpr
  200. def _promote(dtype1, dtype2):
  201. if dtype1 == dtype2:
  202. return dtype1
  203. if (dtype1, dtype2) in promotion_rule:
  204. return promotion_rule[dtype1, dtype2]
  205. return promotion_rule[dtype2, dtype1]
  206. @constexpr
  207. def _max(*args):
  208. """Returns the maximum value."""
  209. return max(*args)
  210. @constexpr
  211. def _min(*args):
  212. """"Returns the minimum value."""
  213. return min(*args)
  214. @constexpr
  215. def _abs(arg):
  216. """Returns the absolute value."""
  217. return abs(arg)
  218. @constexpr
  219. def _check_same_type(dtype1, dtype2):
  220. return dtype1 == dtype2
  221. @constexpr
  222. def _check_is_float(dtype):
  223. """Returns whether dtype is float16 or float32."""
  224. return dtype in (mstype.float16, mstype.float32)
  225. @constexpr
  226. def _check_is_int(dtype):
  227. return isinstance(dtype, typing.Int)
  228. @constexpr
  229. def _check_matmul_shapes(shape1, shape2):
  230. """Checks shape1 and shape2 are valid shapes to perform matmul"""
  231. ndim1, ndim2 = len(shape1), len(shape2)
  232. if ndim1 < 1 or ndim2 < 1:
  233. raise ValueError('input operands must have at least 1 dimension')
  234. if ndim2 >= 2 and shape1[-1] != shape2[-2]:
  235. raise ValueError(f'mismatch in core dimension of input operands (size '
  236. f'{shape1[-1]} is different from {shape2[-2]})')
  237. @constexpr
  238. def _check_axis_type(axis, type_int=True, type_tuple=True, type_list=True):
  239. """Check axis argument type."""
  240. if type_int and isinstance(axis, int):
  241. return True
  242. if (type_tuple and isinstance(axis, tuple)) or (type_list and isinstance(axis, list)):
  243. for ax in axis:
  244. if not isinstance(ax, int):
  245. raise TypeError(f"Each axis should be integer, but got {type(ax)} in {axis}.")
  246. return True
  247. type_str = ""
  248. if type_int: type_str += "int, "
  249. if type_tuple: type_str += "tuple, "
  250. if type_list: type_str += "list, "
  251. raise TypeError(f"Axis should be {type_str}but got {type(axis)}.")
  252. @constexpr
  253. def _canonicalize_axis(axis, ndim):
  254. """
  255. Check axes are within the number of dimensions of tensor x and normalize the negative axes.
  256. Args:
  257. axis (Union[int, tuple(int), list(int)]): Axes of the tensor.
  258. ndim (int): The number of dimensions of the tensor.
  259. Return:
  260. Axis (Union[int, tuple(int)]). If input is integer, return integer, else tuple.
  261. """
  262. if isinstance(axis, int):
  263. axis = [axis]
  264. for ax in axis:
  265. _check_axis_in_range(ax, ndim)
  266. def canonicalizer(ax):
  267. return ax + ndim if ax < 0 else ax
  268. axis = tuple([canonicalizer(axis) for axis in axis])
  269. if all(axis.count(el) <= 1 for el in axis):
  270. return axis if len(axis) > 1 else axis[0]
  271. raise ValueError(f"duplicate axes in {axis}.")
  272. @constexpr
  273. def _broadcast_tuples(tup1, tup2):
  274. """
  275. Broadcast two 1D tuples to the same length, if inputs are ints, convert to
  276. tuples first.
  277. """
  278. tup1 = (tup1,) if isinstance(tup1, int) else tup1
  279. tup2 = (tup2,) if isinstance(tup2, int) else tup2
  280. if not isinstance(tup1, (tuple, list)) or not isinstance(tup2, (tuple, list)):
  281. raise TypeError("input shift and axis must be tuple or list or int.")
  282. if len(tup1) == len(tup2):
  283. return tup1, tup2
  284. if len(tup1) == 1:
  285. tup1 *= len(tup2)
  286. elif len(tup2) == 1:
  287. tup2 *= len(tup1)
  288. else:
  289. raise ValueError("shape mismatch: objects cannot be broadcast to a single shape")
  290. return tup1, tup2
  291. @constexpr
  292. def _expanded_shape(ndim, axis_size, axis):
  293. """
  294. Returns a shape with size = 1 for all dimensions
  295. except at axis.
  296. """
  297. return tuple([axis_size if i == axis else 1 for i in range(ndim)])
  298. @constexpr
  299. def _add_unit_axes(shape, ndim, append=False):
  300. """
  301. Prepends shape with 1s so that it has the number of dimensions ndim.
  302. If append is set to True, returns shape appended with 1s instead.
  303. """
  304. if isinstance(shape, int):
  305. shape = (shape,)
  306. ndim_diff = ndim - len(shape)
  307. if ndim_diff > 0:
  308. if append:
  309. shape = [i for i in shape] + [1]*ndim_diff
  310. else:
  311. shape = [1]*ndim_diff + [i for i in shape]
  312. return tuple(shape)
  313. @constexpr
  314. def _check_element_int(lst):
  315. """
  316. Check whether each element in `lst` is an integer.
  317. """
  318. for item in lst:
  319. if not isinstance(item, int):
  320. raise TypeError(f"Each element in {lst} should be integer, but got {type(item)}.")
  321. return True
  322. @constexpr
  323. def _type_convert(force, obj):
  324. """
  325. Convert type of `obj` to `force`.
  326. """
  327. return force(obj)
  328. @constexpr
  329. def _list_comprehensions(obj, item=None, return_tuple=False):
  330. """
  331. Generates a new list/tuple by list comprehension.
  332. Args:
  333. obj (Union[int, list, tuple]):
  334. If integer, it will be the length of the returned tuple/list.
  335. item: The value to be filled. Default: None.
  336. If None, the values in the new list/tuple are the same as obj
  337. or range(obj) when obj is integer.
  338. return_tuple(bool): If true, returns tuple, else returns list.
  339. Returns:
  340. List or tuple.
  341. """
  342. res = []
  343. lst = obj
  344. if isinstance(obj, int):
  345. lst = range(obj)
  346. if item is None:
  347. res = [i for i in lst]
  348. else:
  349. res = [item for i in lst]
  350. if return_tuple:
  351. return tuple(res)
  352. return res
  353. @constexpr
  354. def _tuple_getitem(tup, idx, startswith=True):
  355. """
  356. Returns a slice from tup starting with idx. If startswith is False,
  357. returns a lice from tup ending with idx instead.
  358. """
  359. if startswith:
  360. return tup[idx:]
  361. return tup[:idx]
  362. @constexpr
  363. def _iota(dtype, num):
  364. """Creates a 1-D tensor with value: [0,1,...num-1] and dtype."""
  365. # TODO: Change to P.Linspace when the kernel is implemented on CPU.
  366. return Tensor(list(range(int(num))), dtype)
  367. @constexpr
  368. def _ceil(number):
  369. """Ceils the number in graph mode."""
  370. return math.ceil(number)