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

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