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

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