• 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# ============================================================================
15
16import numpy as np
17import pytest
18
19import mindspore.context as context
20import mindspore.nn as nn
21from mindspore import Tensor
22from mindspore.nn import Dense
23from mindspore.nn import TrainOneStepCell, WithLossCell
24from mindspore.nn.optim import Adam
25from mindspore.ops import operations as P
26
27context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
28
29
30class NetAdam(nn.Cell):
31    def __init__(self):
32        super(NetAdam, self).__init__()
33        self.batch_size = 1
34        self.reshape = P.Reshape()
35        weight = Tensor(np.ones([10, 16]).astype(np.float32) * 0.01)
36        self.fc1 = Dense(16, 10, weight_init=weight)
37
38    def construct(self, input_x):
39        output = self.reshape(input_x, (self.batch_size, -1))
40        output = self.fc1(output)
41        return output
42
43
44@pytest.mark.level0
45@pytest.mark.platform_x86_gpu_training
46@pytest.mark.env_onecard
47def test_adam():
48    epoch = 3
49    net = NetAdam()
50    optimizer = Adam(filter(lambda x: x.requires_grad,
51                            net.get_parameters()), learning_rate=0.01)
52    criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
53    net_with_criterion = WithLossCell(net, criterion)
54    train_network = TrainOneStepCell(
55        net_with_criterion, optimizer)
56    train_network.set_train()
57
58    context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
59    losses1 = []
60    for _ in range(epoch):
61        data = Tensor(np.arange(0, 16).reshape(
62            1, 1, 4, 4).astype(np.float32) * 0.01)
63        label = Tensor(np.array([0]).astype(np.int32))
64        loss = train_network(data, label)
65        losses1.append(loss.asnumpy())
66    assert losses1[0] > losses1[1]
67    assert losses1[1] > losses1[2]
68
69    context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
70    losses2 = []
71    for _ in range(epoch):
72        data = Tensor(np.arange(0, 16).reshape(
73            1, 1, 4, 4).astype(np.float32) * 0.01)
74        label = Tensor(np.array([0]).astype(np.int32))
75        loss = train_network(data, label)
76        losses2.append(loss.asnumpy())
77    assert losses2[0] > losses2[1]
78    assert losses2[1] > losses2[2]
79