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# ============================================================================ 15import datetime 16import numpy as np 17 18import mindspore.context as context 19import mindspore.nn as nn 20from mindspore import Tensor 21from mindspore.common import dtype as mstype 22from mindspore.communication.management import init, get_group_size 23from mindspore.nn import TrainOneStepCell, WithLossCell 24from mindspore.nn.optim import Momentum 25from mindspore.ops import operations as P 26 27context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 28init() 29 30epoch = 5 31total = 5000 32batch_size = 32 33mini_batch = total // batch_size 34 35 36class LeNet(nn.Cell): 37 def __init__(self): 38 super(LeNet, self).__init__() 39 40 self.relu = P.ReLU() 41 self.batch_size = 32 42 weight1 = Tensor(np.ones([6, 3, 5, 5]).astype(np.float32) * 0.01) 43 weight2 = Tensor(np.ones([16, 6, 5, 5]).astype(np.float32) * 0.01) 44 self.conv1 = nn.Conv2d(3, 6, (5, 5), weight_init=weight1, stride=1, padding=0, pad_mode='valid') 45 self.conv2 = nn.Conv2d(6, 16, (5, 5), weight_init=weight2, pad_mode='valid', stride=1, padding=0) 46 self.pool = nn.MaxPool2d(kernel_size=2, stride=2, pad_mode="valid") 47 self.reshape = P.Reshape() 48 49 weight1 = Tensor(np.ones([120, 400]).astype(np.float32) * 0.01) 50 self.fc1 = nn.Dense(400, 120, weight_init=weight1) 51 52 weight2 = Tensor(np.ones([84, 120]).astype(np.float32) * 0.01) 53 self.fc2 = nn.Dense(120, 84, weight_init=weight2) 54 55 weight3 = Tensor(np.ones([10, 84]).astype(np.float32) * 0.01) 56 self.fc3 = nn.Dense(84, 10, weight_init=weight3) 57 58 def construct(self, input_x): 59 output = self.conv1(input_x) 60 output = self.relu(output) 61 output = self.pool(output) 62 output = self.conv2(output) 63 output = self.relu(output) 64 output = self.pool(output) 65 output = self.reshape(output, (self.batch_size, -1)) 66 output = self.fc1(output) 67 output = self.fc2(output) 68 output = self.fc3(output) 69 return output 70 71 72def multisteplr(total_steps, gap, base_lr=0.9, gamma=0.1, dtype=mstype.float32): 73 lr = [] 74 for step in range(total_steps): 75 lr_ = base_lr * gamma ** (step // gap) 76 lr.append(lr_) 77 return Tensor(np.array(lr), dtype) 78 79 80def test_lenet_nccl(): 81 context.set_auto_parallel_context(parallel_mode="data_parallel", gradients_mean=True, device_num=get_group_size()) 82 net = LeNet() 83 net.set_train() 84 85 learning_rate = multisteplr(epoch, 2) 86 momentum = 0.9 87 mom_optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum) 88 criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean') 89 net_with_criterion = WithLossCell(net, criterion) 90 train_network = TrainOneStepCell(net_with_criterion, mom_optimizer) 91 train_network.set_train() 92 losses = [] 93 94 data = Tensor(np.ones([net.batch_size, 3, 32, 32]).astype(np.float32) * 0.01) 95 label = Tensor(np.ones([net.batch_size]).astype(np.int32)) 96 start = datetime.datetime.now() 97 for _ in range(epoch): 98 for _ in range(mini_batch): 99 loss = train_network(data, label) 100 losses.append(loss.asnumpy()) 101 end = datetime.datetime.now() 102 with open("ms_time.txt", "w") as fo1: 103 fo1.write("time:") 104 fo1.write(str(end - start)) 105 with open("ms_loss.txt", "w") as fo2: 106 fo2.write("loss:") 107 fo2.write(str(losses[-5:])) 108 assert losses[-1] < 0.01 109