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# ============================================================================ 15import pytest 16import numpy as np 17import mindspore.context as context 18import mindspore.nn as nn 19from mindspore import Tensor 20from mindspore.ops.operations import _grad_ops as G 21 22 23class Net(nn.Cell): 24 def __init__(self): 25 super(Net, self).__init__() 26 self.sqrt_grad = G.SqrtGrad() 27 28 def construct(self, x, dout): 29 return self.sqrt_grad(x, dout) 30 31 32def get_output(x, dout, enable_graph_kernel=False): 33 context.set_context(enable_graph_kernel=enable_graph_kernel) 34 net = Net() 35 output = net(x, dout) 36 return output 37 38 39def test_sqrt_grad(shape_x, shape_dout, dtype): 40 x = Tensor(np.random.normal(0, 1, shape_x).astype(dtype)) 41 dout = Tensor(np.random.normal(0, 1, shape_dout).astype(dtype)) 42 43 expect = get_output(x, dout, False) 44 output = get_output(x, dout, True) 45 46 expect_np = expect.asnumpy().copy() 47 output_np = output.asnumpy().copy() 48 49 rtol = 0.0001 50 atol = 0.0001 51 if dtype == np.float16: 52 rtol = 0.001 53 atol = 0.001 54 55 assert np.allclose(expect_np, output_np, rtol, atol) 56 57 58@pytest.mark.level0 59@pytest.mark.platform_arm_ascend_training 60@pytest.mark.platform_x86_ascend_training 61@pytest.mark.env_onecard 62def test_sqrt_grad_ascend(): 63 context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") 64 test_sqrt_grad((16, 16), (16, 16), np.float16) 65 test_sqrt_grad((16, 16), (16, 16), np.float32) 66