• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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# ============================================================================
15
16from __future__ import absolute_import
17from __future__ import division
18from __future__ import print_function
19
20import numpy as np
21import pytest
22
23import mindspore.context as context
24import mindspore.nn as nn
25from mindspore import Tensor
26from mindspore.nn import TrainOneStepCell, WithLossCell
27from mindspore.nn.optim import Momentum
28
29context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
30
31
32class AlexNet(nn.Cell):
33    def __init__(self, num_classes=10):
34        super(AlexNet, self).__init__()
35        self.batch_size = 32
36        self.conv1 = nn.Conv2d(3, 96, 11, stride=4, pad_mode="valid")
37        self.conv2 = nn.Conv2d(96, 256, 5, stride=1, pad_mode="same")
38        self.conv3 = nn.Conv2d(256, 384, 3, stride=1, pad_mode="same")
39        self.conv4 = nn.Conv2d(384, 384, 3, stride=1, pad_mode="same")
40        self.conv5 = nn.Conv2d(384, 256, 3, stride=1, pad_mode="same")
41        self.relu = nn.ReLU()
42        self.max_pool2d = nn.MaxPool2d(kernel_size=3, stride=2, pad_mode="valid")
43        self.flatten = nn.Flatten()
44        self.fc1 = nn.Dense(6 * 6 * 256, 4096)
45        self.fc2 = nn.Dense(4096, 4096)
46        self.fc3 = nn.Dense(4096, num_classes)
47
48    def construct(self, x):
49        x = self.conv1(x)
50        x = self.relu(x)
51        x = self.max_pool2d(x)
52        x = self.conv2(x)
53        x = self.relu(x)
54        x = self.max_pool2d(x)
55        x = self.conv3(x)
56        x = self.relu(x)
57        x = self.conv4(x)
58        x = self.relu(x)
59        x = self.conv5(x)
60        x = self.relu(x)
61        x = self.max_pool2d(x)
62        x = self.flatten(x)
63        x = self.fc1(x)
64        x = self.relu(x)
65        x = self.fc2(x)
66        x = self.relu(x)
67        x = self.fc3(x)
68        return x
69
70
71@pytest.mark.level0
72@pytest.mark.platform_x86_gpu_training
73@pytest.mark.env_onecard
74def test_trainTensor(num_classes=10, epoch=15, batch_size=32):
75    net = AlexNet(num_classes)
76    lr = 0.1
77    momentum = 0.9
78    optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, momentum, weight_decay=0.0001)
79    criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
80    net_with_criterion = WithLossCell(net, criterion)
81    train_network = TrainOneStepCell(net_with_criterion, optimizer)
82    train_network.set_train()
83    losses = []
84    for i in range(0, epoch):
85        data = Tensor(np.ones([batch_size, 3, 227, 227]).astype(np.float32) * 0.01)
86        label = Tensor(np.ones([batch_size]).astype(np.int32))
87        loss = train_network(data, label).asnumpy()
88        losses.append(loss)
89    assert losses[-1] < 0.01
90