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.py 5.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 utility functions"""
  16. from ..common import Tensor
  17. from ..ops import functional as F
  18. from ..common import dtype as mstype
  19. from .utils_const import _tile_size, _add_unit_axes, _raise_type_error, _type_convert
  20. def _deep_list(array_like):
  21. """convert nested tuple/list mixtures to pure nested list"""
  22. if isinstance(array_like, (list, tuple)):
  23. return list(map(_deep_list, array_like))
  24. return array_like
  25. def _deep_tensor_to_nparray(array_like):
  26. """
  27. convert a nested list of tensor to nested list of np_array.
  28. Args:
  29. array_like(list(tensor)): In any format of nested lists that may contain
  30. tensors.
  31. Returns:
  32. array_like(list(np_array)): Formatted array that can be directly processed
  33. by numpy.array(), with all tensor elements converted to numpy_array.
  34. """
  35. # Recursively check whether each element is a tensor or not, if is tensor,
  36. # convert it to a numpy array in place
  37. if isinstance(array_like, Tensor):
  38. return array_like.asnumpy()
  39. if isinstance(array_like, list):
  40. for idx, value in enumerate(array_like):
  41. array_like[idx] = _deep_tensor_to_nparray(value)
  42. return array_like
  43. def _check_input_for_asarray(array_like):
  44. """check whether array_like argument is a valid type for np.asarray conversion"""
  45. if not isinstance(array_like, (Tensor, list, tuple, int, float, bool)):
  46. _raise_type_error("input data must be `int`, `float`, `bool`, `Tensor`, `list`, `tuple`, but got ", array_like)
  47. def _is_scalar(shape):
  48. """check whether input shape is a scalar"""
  49. return F.shape_mul(shape) == 1
  50. def _convert_list_tensor_to_tuple_tensor(list_of_tensor):
  51. """Convert a list of tensor to a tuple of tensor"""
  52. if isinstance(list_of_tensor, list):
  53. tuple_of_tensor = ()
  54. for tensor in list_of_tensor:
  55. tuple_of_tensor += (tensor,)
  56. return tuple_of_tensor
  57. return list_of_tensor
  58. def _expand(x, ndim, axis=0):
  59. """Expand x to ndim from axis, which can be 0 or -1."""
  60. shape = _add_unit_axes(F.shape(x), ndim, axis == -1)
  61. return F.reshape(x, shape)
  62. def _broadcast_to(x, shape_cur, shape_to, ndim_to):
  63. """Broadcasts x from shape_cur to shape_to."""
  64. size = _tile_size(shape_cur, shape_to, ndim_to)
  65. return F.tile(x, size)
  66. def _broadcast_to_shape(x, shape):
  67. """Broadcasts x from current shape to shape"""
  68. ndim_to = len(shape)
  69. x = _expand(x, ndim_to)
  70. return _broadcast_to(x, F.shape(x), shape, ndim_to)
  71. def _get_size(x, axis=None):
  72. """Get the number of elements along the given axis of tensor x."""
  73. if axis is None or F.tuple_len(axis) == 0:
  74. axis = F.make_range(x.ndim)
  75. nums = 1
  76. for ax in axis:
  77. nums *= x.shape[ax]
  78. return nums
  79. def _check_input_tensor(*tensors):
  80. for tensor in tensors:
  81. if not isinstance(tensor, Tensor):
  82. _raise_type_error('expect Tensor, but got ', F.typeof(tensor))
  83. return True
  84. def _convert_64_to_32(tensor):
  85. """Convert tensor with float64/int64 types to float32/int32."""
  86. if tensor.dtype == mstype.float64:
  87. return tensor.astype("float32")
  88. if tensor.dtype == mstype.int64:
  89. return tensor.astype("int32")
  90. return tensor
  91. def _to_tensor(*args):
  92. """Returns each input as Tensor"""
  93. res = ()
  94. for arg in args:
  95. if isinstance(arg, (int, float, bool, list, tuple)):
  96. arg = _convert_64_to_32(_type_convert(Tensor, arg))
  97. elif not isinstance(arg, Tensor):
  98. _raise_type_error("Expect input to be array like.")
  99. res += (arg,)
  100. if len(res) == 1:
  101. return res[0]
  102. return res
  103. def _get_dtype_from_scalar(*input_numbers):
  104. """
  105. Get the final dtype from series of input numbers, compared with F.typeof, we
  106. return int32/float32 for python int/float instead.
  107. """
  108. bool_flag = True
  109. int_flag = True
  110. for number in input_numbers:
  111. if number is not None:
  112. if not isinstance(number, bool):
  113. bool_flag = False
  114. if not isinstance(number, int):
  115. int_flag = False
  116. if bool_flag:
  117. return mstype.bool_
  118. if int_flag:
  119. return mstype.int32
  120. return mstype.float32
  121. def _isnan(x):
  122. """Computes isnan."""
  123. return F.not_equal(x, x)