1# Copyright 2020 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 operations as P 22from mindspore.ops.operations import _grad_ops as G 23 24context.set_context(mode=context.GRAPH_MODE, device_target='CPU') 25 26class NetSqrtGrad(nn.Cell): 27 def __init__(self): 28 super(NetSqrtGrad, self).__init__() 29 self.sqrt_grad = G.SqrtGrad() 30 31 def construct(self, x, dx): 32 return self.sqrt_grad(x, dx) 33 34 35class Net(nn.Cell): 36 def __init__(self): 37 super(Net, self).__init__() 38 self.ops = P.Sqrt() 39 40 def construct(self, x): 41 return self.ops(x) 42 43@pytest.mark.level0 44@pytest.mark.platform_x86_cpu 45@pytest.mark.env_onecard 46def test_net(): 47 x = np.abs(np.random.randn(2, 3, 3, 4)).astype(np.float32) 48 y_expect = np.sqrt(x) 49 net = Net() 50 out = net(Tensor(x)) 51 diff = out.asnumpy() - y_expect 52 err = np.ones(shape=y_expect.shape) * 1.0e-5 53 assert np.all(diff < err) 54 assert out.shape == y_expect.shape 55 56 57@pytest.mark.level0 58@pytest.mark.platform_x86_cpu 59@pytest.mark.env_onecard 60def test_sqrt_grad(): 61 x = Tensor(np.array([[[[-1, 1, 10], 62 [5.9, 6.1, 6], 63 [10, 1, -1]]]]).astype(np.float32)) 64 dx = Tensor(np.array([[[[1, 1, 1], 65 [2, 2, 2], 66 [3, 3, 3]]]]).astype(np.float32)) 67 expect = np.array([[[[-0.5, 0.5, 0.05,], 68 [0.16949153, 0.16393442, 0.16666667,], 69 [0.15, 1.5, -1.5,]]]]).astype(np.float32) 70 error = np.ones(shape=[3, 3]) * 1.0e-6 71 72 sqrt_grad = NetSqrtGrad() 73 output = sqrt_grad(x, dx) 74 diff = np.abs(output.asnumpy() - expect) 75 assert np.all(np.abs(diff) < error) 76