• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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# ============================================================================
15import numpy as np
16import pytest
17
18import mindspore.context as context
19import mindspore.nn as nn
20from mindspore import Tensor
21from mindspore.nn import TrainOneStepCell, WithLossCell
22from mindspore.nn.optim import Momentum
23from mindspore.ops import operations as P
24
25context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
26
27
28class LeNet(nn.Cell):
29    def __init__(self):
30        super(LeNet, self).__init__()
31        self.relu = P.ReLU()
32        self.batch_size = 32
33
34        self.conv1 = nn.Conv2d(1, 6, kernel_size=5, stride=1, padding=0, has_bias=False, pad_mode='valid')
35        self.conv2 = nn.Conv2d(6, 16, kernel_size=5, stride=1, padding=0, has_bias=False, pad_mode='valid')
36        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
37        self.reshape = P.Reshape()
38        self.fc1 = nn.Dense(400, 120)
39        self.fc1.matmul.add_prim_attr("primitive_target", "CPU")
40        self.fc1.bias_add.add_prim_attr("primitive_target", "CPU")
41        self.fc2 = nn.Dense(120, 84)
42        self.fc2.matmul.add_prim_attr("primitive_target", "CPU")
43        self.fc2.bias_add.add_prim_attr("primitive_target", "CPU")
44        self.fc3 = nn.Dense(84, 10)
45        self.fc3.matmul.add_prim_attr("primitive_target", "CPU")
46        self.fc3.bias_add.add_prim_attr("primitive_target", "CPU")
47
48    def construct(self, input_x):
49        output = self.conv1(input_x)
50        output = self.relu(output)
51        output = self.pool(output)
52        output = self.conv2(output)
53        output = self.relu(output)
54        output = self.pool(output)
55        output = self.reshape(output, (self.batch_size, -1))
56        output = self.fc1(output)
57        output = self.relu(output)
58        output = self.fc2(output)
59        output = self.relu(output)
60        output = self.fc3(output)
61        return output
62
63
64def train(net, data, label):
65    learning_rate = 0.01
66    momentum = 0.9
67
68    optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum)
69    criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
70    net_with_criterion = WithLossCell(net, criterion)
71    train_network = TrainOneStepCell(net_with_criterion, optimizer)  # optimizer
72    train_network.set_train()
73    res = train_network(data, label)
74    print("+++++++++Loss+++++++++++++")
75    print(res)
76    print("+++++++++++++++++++++++++++")
77    diff = res.asnumpy()[0] - 2.3025851
78    assert np.all(diff < 1.e-6)
79
80
81@pytest.mark.level1
82@pytest.mark.platform_arm_ascend_training
83@pytest.mark.platform_x86_ascend_training
84@pytest.mark.env_onecard
85def test_lenet():
86    data = Tensor(np.ones([32, 1, 32, 32]).astype(np.float32) * 0.01)
87    label = Tensor(np.ones([32]).astype(np.int32))
88    net = LeNet()
89    train(net, data, label)
90