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""" 16@File : test_data_parallel_lenet.py 17@Desc : test data parallel lenet 18""" 19import os 20import numpy as np 21 22import mindspore.context as context 23import mindspore.nn as nn 24from mindspore import Tensor, Model 25from mindspore.context import ParallelMode 26from mindspore.nn.optim import Momentum 27from mindspore.ops import operations as P 28 29_current_dir = os.path.dirname(os.path.realpath(__file__)) + "/../test_data" 30 31 32class LeNet5(nn.Cell): 33 """LeNet5 definition""" 34 35 def __init__(self): 36 super(LeNet5, self).__init__() 37 self.conv1 = nn.Conv2d(1, 6, 5) 38 self.conv2 = nn.Conv2d(6, 16, 5) 39 self.fc1 = nn.Dense(16 * 5 * 5, 120) 40 self.fc2 = nn.Dense(120, 84) 41 self.fc3 = nn.Dense(84, 10) 42 self.relu = nn.ReLU() 43 self.max_pool2d = nn.MaxPool2d(kernel_size=2) 44 self.flatten = P.Flatten() 45 46 def construct(self, x): 47 x = self.max_pool2d(self.relu(self.conv1(x))) 48 x = self.max_pool2d(self.relu(self.conv2(x))) 49 x = self.flatten(x) 50 x = self.relu(self.fc1(x)) 51 x = self.relu(self.fc2(x)) 52 x = self.fc3(x) 53 return x 54 55 56class DatasetLenet(): 57 """DatasetLenet definition""" 58 59 def __init__(self, predict, label, length=3): 60 self.predict = predict 61 self.label = label 62 self.index = 0 63 self.length = length 64 65 def __iter__(self): 66 return self 67 68 def __next__(self): 69 if self.index >= self.length: 70 raise StopIteration 71 self.index += 1 72 return self.predict, self.label 73 74 def reset(self): 75 self.index = 0 76 77 78def test_lenet5_train_step_training_pynative(): 79 """test_lenet5_train_step_training_pynative""" 80 context.set_context(mode=context.PYNATIVE_MODE) 81 context.reset_auto_parallel_context() 82 context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, 83 device_num=8, gradients_mean=True) 84 predict = Tensor(np.ones([1, 1, 32, 32]).astype(np.float32) * 0.01) 85 label = Tensor(np.zeros([1, 10]).astype(np.float32)) 86 DatasetLenet(predict, label, 2) 87 network = LeNet5() 88 loss_fn = nn.SoftmaxCrossEntropyWithLogits() 89 optimizer = Momentum(network.get_parameters(), learning_rate=0.1, momentum=0.9) 90 Model(network=network, loss_fn=loss_fn, optimizer=optimizer) 91 context.set_context(mode=context.GRAPH_MODE) 92 context.reset_auto_parallel_context() 93