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 16"""LeNet test.""" 17 18import numpy as np 19 20from lenet import LeNet5 21import mindspore.nn as nn 22import mindspore.ops.composite as C 23from mindspore import Tensor 24from mindspore import context 25from mindspore.common.api import _cell_graph_executor 26 27context.set_context(mode=context.GRAPH_MODE) 28 29 30grad_all_with_sens = C.GradOperation(get_all=True, sens_param=True) 31 32batch_size = 1 33channel = 1 34height = 32 35weight = 32 36num_class = 10 37 38 39class LeNetGrad(nn.Cell): 40 """Backward of LeNet""" 41 42 def __init__(self, network): 43 super(LeNetGrad, self).__init__() 44 self.grad_op = grad_all_with_sens 45 self.network = network 46 47 def construct(self, x, sens): 48 grad_op = self.grad_op(self.network)(x, sens) 49 50 return grad_op 51 52 53def test_compile(): 54 """Compile forward graph""" 55 net = LeNet(num_class=num_class) 56 np.random.seed(7) 57 inp = Tensor(np.array(np.random.randn(batch_size, 58 channel, 59 height, 60 weight) * 3, np.float32)) 61 62 _cell_graph_executor.compile(net, inp) 63 64 65def test_compile_grad(): 66 """Compile forward and backward graph""" 67 net = LeNet5(num_class=num_class) 68 inp = Tensor(np.array(np.random.randn(batch_size, 69 channel, 70 height, 71 weight) * 3, np.float32)) 72 sens = Tensor(np.ones([batch_size, num_class]).astype(np.float32)) 73 grad_op = LeNetGrad(net) 74 75 _cell_graph_executor.compile(grad_op, inp, sens) 76