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