1# Copyright 2024 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 pytest 16import numpy as np 17 18import mindspore.context as context 19from mindspore import Tensor 20from mindspore import ops 21import tests.st.utils.test_utils as test_utils 22 23 24@test_utils.run_with_cell 25def forward_func(x, indices): 26 return ops.max_unpool2d(x, indices, kernel_size=1, stride=1, padding=0) 27 28 29@test_utils.run_with_cell 30def backward_func(x, indices): 31 return ops.grad(forward_func, (0))(x, indices) 32 33 34@pytest.mark.level0 35@pytest.mark.env_onecard 36@pytest.mark.platform_arm_ascend_training 37@pytest.mark.platform_x86_ascend_training 38@pytest.mark.parametrize("context_mode", [context.GRAPH_MODE, context.PYNATIVE_MODE]) 39def test_maxunpool2d_float32(context_mode): 40 """ 41 Feature: maxunpool2d 42 Description: test maxunpool2d 43 Expectation: expect correct result. 44 """ 45 context.set_context(mode=context_mode, device_target="Ascend") 46 x = Tensor(np.array([[[[0, 1], [8, 9]]]]).astype(np.float32)) 47 indices = Tensor(np.array([[[[0, 1], [2, 3]]]]).astype(np.int64)) 48 output = forward_func(x, indices) 49 expected = np.array([[[[0., 1.], 50 [8., 9.]]]], np.float32) 51 np.testing.assert_allclose(output.asnumpy(), expected, rtol=1e-3) 52 53 54@pytest.mark.level0 55@pytest.mark.env_onecard 56@pytest.mark.platform_arm_ascend_training 57@pytest.mark.platform_x86_ascend_training 58@pytest.mark.parametrize("context_mode", [context.GRAPH_MODE, context.PYNATIVE_MODE]) 59def test_maxunpool2d_grad_float32(context_mode): 60 """ 61 Feature: maxunpool2d grad 62 Description: test maxunpool2d grad 63 Expectation: expect correct result. 64 """ 65 context.set_context(mode=context_mode, device_target="Ascend") 66 x = Tensor(np.array([[[[0, 1], [8, 9]]]]).astype(np.float32)) 67 indices = Tensor(np.array([[[[0, 1], [2, 3]]]]).astype(np.int64)) 68 x_grad = backward_func(x, indices) 69 assert x_grad.asnumpy().shape == x.shape 70