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.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. """utils for operator"""
  16. from mindspore.common.tensor import Tensor
  17. from ..._checkparam import Validator as validator
  18. from ..._checkparam import Rel
  19. from ...common import dtype as mstype
  20. from ..primitive import constexpr
  21. def get_broadcast_shape(x_shape, y_shape, prim_name):
  22. """
  23. Doing broadcast between tensor x and tensor y.
  24. Args:
  25. x_shape (list): The shape of tensor x.
  26. y_shape (list): The shape of tensor y.
  27. prim_name (str): Primitive name.
  28. Returns:
  29. List, the shape that broadcast between tensor x and tensor y.
  30. Raises:
  31. ValueError: If tensor x and tensor y are not equal and couldn't broadcast.
  32. Examples:
  33. >>> x_shape = [1, 2, 3]
  34. >>> y_shape = [1, 2]
  35. >>> broadcast_shape = get_broadcast_shape(x_shape, y_shape)
  36. """
  37. if x_shape == y_shape:
  38. return x_shape
  39. x_len = len(x_shape)
  40. y_len = len(y_shape)
  41. length = x_len if x_len < y_len else y_len
  42. broadcast_shape_back = []
  43. for i in range(-length, 0):
  44. if x_shape[i] == 1:
  45. broadcast_shape_back.append(y_shape[i])
  46. elif y_shape[i] == 1:
  47. broadcast_shape_back.append(x_shape[i])
  48. elif x_shape[i] == y_shape[i]:
  49. broadcast_shape_back.append(x_shape[i])
  50. elif x_shape[i] == -1 or y_shape[i] == -1:
  51. broadcast_shape_back.append(-1)
  52. else:
  53. raise ValueError(f"For '{prim_name}', the x_shape {x_shape} and y_shape {y_shape} can not broadcast.")
  54. broadcast_shape_front = y_shape[0: y_len - length] if length == x_len else x_shape[0: x_len - length]
  55. broadcast_shape = list(broadcast_shape_front) + broadcast_shape_back
  56. return broadcast_shape
  57. def get_concat_offset(x_shp, x_type, axis, prim_name):
  58. """for concat and concatoffset check args and compute offset"""
  59. validator.check_value_type("shape", x_shp, [tuple, list], prim_name)
  60. validator.check_positive_int(len(x_shp), "input_x rank", prim_name)
  61. validator.check_subclass("shape0", x_type[0], mstype.tensor, prim_name)
  62. validator.check_positive_int(len(x_shp[0]), "len of x_shp[0]", prim_name)
  63. rank_base = len(x_shp[0])
  64. validator.check_int_range(axis, -rank_base - 1, rank_base, Rel.INC_BOTH, 'axis', prim_name)
  65. if axis < 0:
  66. axis = axis + rank_base
  67. all_shp = x_shp[0][axis]
  68. offset = [0]
  69. for i in range(1, len(x_shp)):
  70. v = x_shp[i]
  71. validator.check('len of x_shp[%d]' % i, len(v), 'len of x_shp[0]', len(x_shp[0]), Rel.EQ, prim_name)
  72. validator.check('x_type[%d]' % i, x_type[i], 'x_type[0]', x_type[0], Rel.EQ, prim_name)
  73. for j in range(rank_base):
  74. if j != axis and v[j] != x_shp[0][j]:
  75. raise ValueError(f"The shape of the two input elements of the Concat operator do not match:"
  76. f"shape[0] = {x_shp[0]} and shape[1] = {x_shp[1]}.")
  77. offset.append(all_shp)
  78. if all_shp == -1 or v[axis] == -1:
  79. all_shp = -1
  80. else:
  81. all_shp += v[axis]
  82. return offset, all_shp, axis
  83. @constexpr
  84. def range_op(start, limit, delta, dtype):
  85. """helper function to get tensor in specified range."""
  86. output_tensor = Tensor(list(range(start, limit, delta)), dtype)
  87. return output_tensor
  88. @constexpr
  89. def get_1d_shape(in_shape):
  90. """helper function to get 1d shape."""
  91. out_shape = 1
  92. for i in in_shape:
  93. out_shape *= i
  94. return (out_shape,)
  95. @constexpr
  96. def generate_shape_index(out_shape, indices_shape, axis):
  97. out_rank = len(out_shape)
  98. ind_rank = len(indices_shape)
  99. if axis < 0:
  100. axis += out_rank - ind_rank + 1
  101. perm_part1 = tuple(range(axis, axis + ind_rank))
  102. index = tuple(range(out_rank))
  103. perm = perm_part1 + index[:axis] + index[axis + ind_rank:]
  104. return perm