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# ============================================================================ 15"""Test high order grad with respect to parameter first, then input.""" 16 17import pytest 18import numpy as np 19import mindspore.nn as nn 20import mindspore.ops as ops 21from mindspore import Tensor, context 22from mindspore import ParameterTuple, Parameter 23 24 25class Net(nn.Cell): 26 def __init__(self): 27 super(Net, self).__init__() 28 self.mul = ops.Mul() 29 weight_np = np.array([2, 2]).astype(np.float32) 30 self.weight = Parameter(Tensor(weight_np), name="weight", requires_grad=True) 31 32 def construct(self, x): 33 x_square = self.mul(x, x) 34 x_square_z = self.mul(x_square, self.weight) 35 output = self.mul(x_square_z, self.weight) 36 return output 37 38 39class Grad(nn.Cell): 40 def __init__(self, network): 41 super(Grad, self).__init__() 42 self.grad = ops.GradOperation(get_by_list=True, sens_param=False) 43 self.network = network 44 self.params = ParameterTuple(network.trainable_params()) 45 46 def construct(self, x): 47 output = self.grad(self.network, self.params)(x) 48 return output 49 50 51class GradSec(nn.Cell): 52 def __init__(self, network): 53 super(GradSec, self).__init__() 54 self.grad = ops.GradOperation(get_all=True, sens_param=False) 55 self.network = network 56 57 def construct(self, x): 58 output = self.grad(self.network)(x) 59 return output 60 61 62@pytest.mark.level1 63@pytest.mark.platform_arm_ascend_training 64@pytest.mark.platform_x86_ascend_training 65@pytest.mark.platform_x86_gpu_training 66@pytest.mark.platform_x86_cpu_training 67@pytest.mark.env_onecard 68def test_sit_high_order_grad_params(): 69 context.set_context(mode=context.GRAPH_MODE) 70 x = Tensor(np.array([1, 1]).astype(np.float32)) 71 net = Net() 72 first_grad = Grad(net) 73 second_grad = GradSec(first_grad) 74 grad = second_grad(x) 75 assert (grad[0].asnumpy() == np.array([8, 8])).all() 76