1# Copyright 2021 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 SGD 25from mindspore.ops import operations as P 26 27context.set_context(mode=context.GRAPH_MODE, device_target="CPU") 28 29class NetSGD(nn.Cell): 30 def __init__(self): 31 super(NetSGD, self).__init__() 32 self.batch_size = 1 33 self.reshape = P.Reshape() 34 weight = Tensor(np.ones([10, 16]).astype(np.float32) * 0.01) 35 self.fc1 = Dense(16, 10, weight_init=weight) 36 37 def construct(self, input_x): 38 output = self.reshape(input_x, (self.batch_size, -1)) 39 output = self.fc1(output) 40 return output 41 42 43@pytest.mark.level0 44@pytest.mark.platform_x86_cpu 45@pytest.mark.env_onecard 46def test_SGD(): 47 epoch = 3 48 net = NetSGD() 49 learning_rate = 0.1 50 momentum = 0.9 51 dampening = 0.0 52 weight_decay = 0.0 53 nesterov = True 54 loss_scale = 1.0 55 56 optimizer = SGD(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum, dampening, 57 weight_decay, nesterov, loss_scale) 58 criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean') 59 net_with_criterion = WithLossCell(net, criterion) 60 train_network = TrainOneStepCell(net_with_criterion, optimizer) # optimizer 61 train_network.set_train() 62 losses = [] 63 for _ in range(epoch): 64 data = Tensor(np.arange(0, 16).reshape(1, 1, 4, 4).astype(np.float32) * 0.01) 65 label = Tensor(np.array([0]).astype(np.int32)) 66 loss = train_network(data, label) 67 losses.append(loss.asnumpy()) 68 69 last_loss = 100.0 70 for loss in losses: 71 assert last_loss > loss 72 last_loss = loss 73