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.

test_shift_op.py 7.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # Copyright 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. import numpy as np
  16. import pytest
  17. import mindspore.context as context
  18. import mindspore.nn as nn
  19. from mindspore import Tensor
  20. from mindspore.ops import PrimitiveWithInfer, prim_attr_register
  21. from mindspore._checkparam import Validator as validator
  22. from mindspore.common import dtype as mstype
  23. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  24. class Shift(PrimitiveWithInfer):
  25. """
  26. Shift op frontend implementation
  27. """
  28. @prim_attr_register
  29. def __init__(self, periods=1, axis=-1):
  30. """Initialize Sort"""
  31. self.periods = validator.check_value_type("periods", periods, [int], self.name)
  32. self.axis = validator.check_value_type("axis", axis, [int], self.name)
  33. self.init_prim_io_names(inputs=['x', 'fill_value'], outputs=['output'])
  34. def __infer__(self, x, fill_value):
  35. out_shapes = x['shape']
  36. return {
  37. 'shape': tuple(out_shapes),
  38. 'dtype': x['dtype'],
  39. 'value': None
  40. }
  41. def infer_dtype(self, x_dtype, fill_value_type):
  42. validator.check_scalar_or_tensor_types_same({"x_dtype": x_dtype, "fill_value": fill_value_type},
  43. [mstype.float32, mstype.float64, mstype.int32, mstype.int64,
  44. mstype.bool_],
  45. self.name, True)
  46. return x_dtype
  47. class ShiftNet(nn.Cell):
  48. def __init__(self, periods=1, axis=-1):
  49. super(ShiftNet, self).__init__()
  50. self.shift = Shift(periods, axis)
  51. def construct(self, x, fill_value):
  52. return self.shift(x, fill_value)
  53. def numpy_shift(array: np.ndarray, periods: int, axis: int, fill_value=np.nan) -> np.ndarray:
  54. """
  55. numpy implementation for validation
  56. """
  57. assert axis in range(-array.ndim, array.ndim)
  58. copy_src_indices = [slice(None)] * array.ndim
  59. copy_dst_indices = [slice(None)] * array.ndim
  60. fill_indices = [slice(None)] * array.ndim
  61. if periods > 0:
  62. fill_indices[axis] = slice(None, periods)
  63. copy_src_indices[axis] = slice(None, -periods)
  64. copy_dst_indices[axis] = slice(periods, None)
  65. elif periods < 0:
  66. fill_indices[axis] = slice(periods, None)
  67. copy_src_indices[axis] = slice(-periods, None)
  68. copy_dst_indices[axis] = slice(None, periods)
  69. else:
  70. return array.copy()
  71. result = np.empty_like(array)
  72. result[tuple(fill_indices)] = fill_value
  73. result[tuple(copy_dst_indices)] = array[tuple(copy_src_indices)]
  74. return result
  75. def compare(arr: np.ndarray, periods: int, axis: int, fill_value=np.nan):
  76. numpy_result = numpy_shift(arr, periods=periods, axis=axis, fill_value=fill_value)
  77. shift = ShiftNet(periods=periods, axis=axis)
  78. mindspore_result = shift(Tensor(arr), fill_value=fill_value).asnumpy()
  79. print('numpy:\n')
  80. print(numpy_result)
  81. print('mindspore:\n')
  82. print(mindspore_result)
  83. assert np.allclose(numpy_result, mindspore_result, equal_nan=True)
  84. @pytest.mark.level0
  85. @pytest.mark.platform_x86_cpu
  86. @pytest.mark.env_onecard
  87. @pytest.mark.parametrize('dtype, fill_value',
  88. [(np.float32, 0.0), (np.float32, 5.3), (np.float32, -5.5), (np.float32, np.nan),
  89. (np.float64, 0.0), (np.float64, 5.3), (np.float64, -5.5), (np.float64, np.nan),
  90. (np.int32, 0), (np.int32, 1), (np.int32, 5), (np.int32, -4),
  91. (np.int64, 0), (np.int64, 1), (np.int64, 5), (np.int64, -4),
  92. (np.bool_, True), (np.bool_, False)])
  93. @pytest.mark.parametrize('axis', [0, 1, 2, 3])
  94. def test_no_shift(fill_value, dtype, axis):
  95. arr = np.random.random((40, 60, 50, 30)).astype(dtype)
  96. compare(arr, axis=axis, periods=0, fill_value=fill_value)
  97. @pytest.mark.level0
  98. @pytest.mark.platform_x86_cpu
  99. @pytest.mark.env_onecard
  100. @pytest.mark.parametrize('dtype, fill_value',
  101. [(np.float32, 0.0), (np.float32, 5.3), (np.float32, -5.5), (np.float32, np.nan),
  102. (np.float64, 0.0), (np.float64, 5.3), (np.float64, -5.5), (np.float64, np.nan),
  103. (np.int32, 0), (np.int32, 1), (np.int32, 5), (np.int32, -4),
  104. (np.int64, 0), (np.int64, 1), (np.int64, 5), (np.int64, -4),
  105. (np.bool_, True), (np.bool_, False)])
  106. @pytest.mark.parametrize('periods', [-35, 28, 90])
  107. def test_fancy_1d(fill_value, dtype, periods):
  108. arr = np.random.random((1, 1, 50, 1)).astype(dtype)
  109. compare(arr, axis=2, periods=periods, fill_value=fill_value)
  110. arr = np.random.random((70, 1, 1, 1)).astype(dtype)
  111. compare(arr, axis=0, periods=periods, fill_value=fill_value)
  112. arr = np.random.random((1, 1, 1, 80)).astype(dtype)
  113. compare(arr, axis=3, periods=periods, fill_value=fill_value)
  114. @pytest.mark.level0
  115. @pytest.mark.platform_x86_cpu
  116. @pytest.mark.env_onecard
  117. @pytest.mark.parametrize('dtype, fill_value',
  118. [(np.float32, 0.0), (np.float32, 5.3), (np.float32, -5.5), (np.float32, np.nan),
  119. (np.float64, 0.0), (np.float64, 5.3), (np.float64, -5.5), (np.float64, np.nan),
  120. (np.int32, 0), (np.int32, 1), (np.int32, 5), (np.int32, -4),
  121. (np.int64, 0), (np.int64, 1), (np.int64, 5), (np.int64, -4),
  122. (np.bool_, True), (np.bool_, False)])
  123. @pytest.mark.parametrize('axis', [0, 1])
  124. @pytest.mark.parametrize('periods', [-24, 27, -35, 28, 100])
  125. def test_2d(fill_value, dtype, axis, periods):
  126. arr = np.random.random((30, 40)).astype(dtype)
  127. compare(arr, axis=axis, periods=periods, fill_value=fill_value)
  128. @pytest.mark.level0
  129. @pytest.mark.platform_x86_cpu
  130. @pytest.mark.env_onecard
  131. @pytest.mark.parametrize('dtype, fill_value',
  132. [(np.float32, 0.0), (np.float32, 5.3), (np.float32, -5.5), (np.float32, np.nan),
  133. (np.float64, 0.0), (np.float64, 5.3), (np.float64, -5.5), (np.float64, np.nan),
  134. (np.int32, 0), (np.int32, 1), (np.int32, 5), (np.int32, -4),
  135. (np.int64, 0), (np.int64, 1), (np.int64, 5), (np.int64, -4),
  136. (np.bool_, True), (np.bool_, False)])
  137. @pytest.mark.parametrize('axis', [0, 1, 2, 3])
  138. @pytest.mark.parametrize('periods', [-30, 30, -45, 55])
  139. def test_4d(fill_value, dtype, axis, periods):
  140. arr = np.random.random((30, 40, 50, 60)).astype(dtype)
  141. compare(arr, axis=axis, periods=periods, fill_value=fill_value)