1# Copyright 2019 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 26context.set_context(device_target="Ascend") 27 28 29class Grad(nn.Cell): 30 def __init__(self, network): 31 super(Grad, self).__init__() 32 self.grad = GradOperation(get_all=True, sens_param=True) 33 self.network = network 34 35 @ms_function 36 def construct(self, input_, output_grad): 37 return self.grad(self.network)(input_, output_grad) 38 39 40class Net(nn.Cell): 41 def __init__(self): 42 super(Net, self).__init__() 43 out_channel = 512 44 kernel_size = 2048 45 self.conv = P.Conv2D(out_channel, 46 (kernel_size, kernel_size), 47 mode=1, 48 pad_mode="same", 49 pad=3, 50 stride=2, 51 dilation=1, 52 group=1) 53 self.w = Parameter(initializer( 54 'normal', [512, 2048, 1, 1]), name='w') 55 56 @ms_function 57 def construct(self, x): 58 return self.conv(x, self.w) 59 60 61def test_net(): 62 x = np.ones([32, 2048, 7, 7]).astype(np.float32) 63 sens = np.ones([32, 512, 7, 7]).astype(np.float32) 64 net = Grad(Net()) 65 output = net(Tensor(x), Tensor(sens)) 66 print(output.asnumpy()) 67