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# ============================================================================ 15 16import numpy as np 17import pytest 18import mindspore.context as context 19from mindspore import Tensor 20from mindspore.nn import Cell 21import mindspore.ops.operations as P 22from mindspore.ops.operations import _grad_ops as G 23 24 25class Net(Cell): 26 def __init__(self): 27 super(Net, self).__init__() 28 self.add = P.Add() 29 self.sub = P.Sub() 30 self.mul = P.Mul() 31 self.sqrt_grad = G.SqrtGrad() 32 33 def construct(self, x, y, z): 34 sub_res = self.sub(x, y) 35 mul_res = self.mul(sub_res, x) 36 sqrt_grad_res = self.sqrt_grad(mul_res, z) 37 square_res = P.Square()(sqrt_grad_res) 38 add_res = self.add(sqrt_grad_res, square_res) 39 add1_res = self.add(add_res, add_res) 40 return self.add(add1_res, add1_res) 41 42 43def get_output(i0, i1, i2, enable_graph_kernel=False): 44 context.set_context(enable_graph_kernel=enable_graph_kernel) 45 net = Net() 46 output = net(i0, i1, i2) 47 return output 48 49 50def test_basic(): 51 i0 = Tensor(np.random.normal(0, 1, [2, 3, 4, 3]).astype(np.float32)) 52 i1 = Tensor(np.random.normal(0, 1, [2, 3, 4, 3]).astype(np.float32)) 53 i2 = Tensor(np.random.normal(0, 1, [2, 3, 4, 3]).astype(np.float32)) 54 55 expect = get_output(i0, i1, i2, False) 56 output = get_output(i0, i1, i2, True) 57 58 expect_np = expect.asnumpy().copy() 59 output_np = output.asnumpy().copy() 60 61 assert np.allclose(expect_np, output_np, 1.e-4, 1.e-7) 62 63 64@pytest.mark.level0 65@pytest.mark.platform_x86_gpu_training 66@pytest.mark.env_onecard 67def test_basic_gpu(): 68 context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 69 test_basic() 70 71 72@pytest.mark.level0 73@pytest.mark.platform_arm_ascend_training 74@pytest.mark.platform_x86_ascend_training 75@pytest.mark.env_onecard 76def test_basic_ascend(): 77 context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") 78 test_basic() 79