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

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