1# Copyright 2019-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 numpy as np 16 17import mindspore.context as context 18import mindspore.nn as nn 19from mindspore import Tensor 20from mindspore.common.api import ms_function 21from mindspore.common.initializer import initializer 22from mindspore.common.parameter import Parameter 23from mindspore.ops import operations as P 24from mindspore.ops.composite import GradOperation 25 26# context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") 27context.set_context(device_target="Ascend") 28 29 30class Grad(nn.Cell): 31 def __init__(self, network): 32 super(Grad, self).__init__() 33 self.grad = GradOperation(get_all=True, sens_param=True) 34 self.network = network 35 36 @ms_function 37 def construct(self, input_, output_grad): 38 return self.grad(self.network)(input_, output_grad) 39 40 41class Net(nn.Cell): 42 def __init__(self): 43 super(Net, self).__init__() 44 self.bn = P.BatchNorm() 45 self.scale = Parameter(initializer('ones', [64]), name='scale') 46 self.b = Parameter(initializer('zeros', [64]), name='b') 47 self.mean = Parameter(initializer('ones', [64]), name='mean') 48 self.variance = Parameter(initializer('zeros', [64]), name='variance') 49 50 def construct(self, x): 51 return self.bn(x, self.scale, self.b, self.mean, self.variance)[0] 52 53 54def test_net(): 55 x = np.random.randn(1, 64, 112, 112).astype(np.float32) 56 sens = np.random.randn(1, 64, 112, 112).astype(np.float32) 57 net = Grad(Net()) 58 output = net(Tensor(x), Tensor(sens)) 59 print("***********x*********") 60 print(x) 61 62 print("***********output y*********") 63 print(output.asnumpy()) 64