You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_gpu_lenet.py 7.8 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. import os
  16. import numpy as np
  17. import pytest
  18. import mindspore.context as context
  19. import mindspore.dataset as ds
  20. import mindspore.dataset.transforms.c_transforms as C
  21. import mindspore.dataset.transforms.vision.c_transforms as CV
  22. import mindspore.nn as nn
  23. from mindspore import Tensor
  24. from mindspore.common import dtype as mstype
  25. from mindspore.dataset.transforms.vision import Inter
  26. from mindspore.nn import Dense, TrainOneStepCell, WithLossCell
  27. from mindspore.nn.metrics import Accuracy
  28. from mindspore.nn.optim import Momentum
  29. from mindspore.ops import operations as P
  30. from mindspore.train import Model
  31. from mindspore.train.callback import LossMonitor
  32. from mindspore.common.initializer import TruncatedNormal
  33. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  34. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  35. """weight initial for conv layer"""
  36. weight = weight_variable()
  37. return nn.Conv2d(in_channels, out_channels,
  38. kernel_size=kernel_size, stride=stride, padding=padding,
  39. weight_init=weight, has_bias=False, pad_mode="valid")
  40. def fc_with_initialize(input_channels, out_channels):
  41. """weight initial for fc layer"""
  42. weight = weight_variable()
  43. bias = weight_variable()
  44. return nn.Dense(input_channels, out_channels, weight, bias)
  45. def weight_variable():
  46. """weight initial"""
  47. return TruncatedNormal(0.02)
  48. class LeNet5(nn.Cell):
  49. def __init__(self, num_class=10, channel=1):
  50. super(LeNet5, self).__init__()
  51. self.num_class = num_class
  52. self.conv1 = conv(channel, 6, 5)
  53. self.conv2 = conv(6, 16, 5)
  54. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  55. self.fc2 = fc_with_initialize(120, 84)
  56. self.fc3 = fc_with_initialize(84, self.num_class)
  57. self.relu = nn.ReLU()
  58. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  59. self.flatten = nn.Flatten()
  60. def construct(self, x):
  61. x = self.conv1(x)
  62. x = self.relu(x)
  63. x = self.max_pool2d(x)
  64. x = self.conv2(x)
  65. x = self.relu(x)
  66. x = self.max_pool2d(x)
  67. x = self.flatten(x)
  68. x = self.fc1(x)
  69. x = self.relu(x)
  70. x = self.fc2(x)
  71. x = self.relu(x)
  72. x = self.fc3(x)
  73. return x
  74. class LeNet(nn.Cell):
  75. def __init__(self):
  76. super(LeNet, self).__init__()
  77. self.relu = P.ReLU()
  78. self.batch_size = 1
  79. weight1 = Tensor(np.ones([6, 3, 5, 5]).astype(np.float32) * 0.01)
  80. weight2 = Tensor(np.ones([16, 6, 5, 5]).astype(np.float32) * 0.01)
  81. self.conv1 = nn.Conv2d(3, 6, (5, 5), weight_init=weight1, stride=1, padding=0, pad_mode='valid')
  82. self.conv2 = nn.Conv2d(6, 16, (5, 5), weight_init=weight2, pad_mode='valid', stride=1, padding=0)
  83. self.pool = nn.MaxPool2d(kernel_size=2, stride=2, pad_mode="valid")
  84. self.reshape = P.Reshape()
  85. self.reshape1 = P.Reshape()
  86. self.fc1 = Dense(400, 120)
  87. self.fc2 = Dense(120, 84)
  88. self.fc3 = Dense(84, 10)
  89. def construct(self, input_x):
  90. output = self.conv1(input_x)
  91. output = self.relu(output)
  92. output = self.pool(output)
  93. output = self.conv2(output)
  94. output = self.relu(output)
  95. output = self.pool(output)
  96. output = self.reshape(output, (self.batch_size, -1))
  97. output = self.fc1(output)
  98. output = self.fc2(output)
  99. output = self.fc3(output)
  100. return output
  101. def multisteplr(total_steps, gap, base_lr=0.9, gamma=0.1, dtype=mstype.float32):
  102. lr = []
  103. for step in range(total_steps):
  104. lr_ = base_lr * gamma ** (step // gap)
  105. lr.append(lr_)
  106. return Tensor(np.array(lr), dtype)
  107. @pytest.mark.level0
  108. @pytest.mark.platform_x86_gpu_training
  109. @pytest.mark.env_onecard
  110. def test_train_lenet():
  111. epoch = 100
  112. net = LeNet()
  113. momentum = 0.9
  114. learning_rate = multisteplr(epoch, 30)
  115. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum)
  116. criterion = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  117. net_with_criterion = WithLossCell(net, criterion)
  118. train_network = TrainOneStepCell(net_with_criterion, optimizer) # optimizer
  119. train_network.set_train()
  120. losses = []
  121. for i in range(epoch):
  122. data = Tensor(np.ones([net.batch_size, 3, 32, 32]).astype(np.float32) * 0.01)
  123. label = Tensor(np.ones([net.batch_size]).astype(np.int32))
  124. loss = train_network(data, label)
  125. losses.append(loss)
  126. print(losses)
  127. def create_dataset(data_path, batch_size=32, repeat_size=1,
  128. num_parallel_workers=1):
  129. """
  130. create dataset for train or test
  131. """
  132. # define dataset
  133. mnist_ds = ds.MnistDataset(data_path)
  134. resize_height, resize_width = 32, 32
  135. rescale = 1.0 / 255.0
  136. shift = 0.0
  137. rescale_nml = 1 / 0.3081
  138. shift_nml = -1 * 0.1307 / 0.3081
  139. # define map operations
  140. resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR) # Bilinear mode
  141. rescale_nml_op = CV.Rescale(rescale_nml, shift_nml)
  142. rescale_op = CV.Rescale(rescale, shift)
  143. hwc2chw_op = CV.HWC2CHW()
  144. type_cast_op = C.TypeCast(mstype.int32)
  145. # apply map operations on images
  146. mnist_ds = mnist_ds.map(input_columns="label", operations=type_cast_op, num_parallel_workers=num_parallel_workers)
  147. mnist_ds = mnist_ds.map(input_columns="image", operations=resize_op, num_parallel_workers=num_parallel_workers)
  148. mnist_ds = mnist_ds.map(input_columns="image", operations=rescale_op, num_parallel_workers=num_parallel_workers)
  149. mnist_ds = mnist_ds.map(input_columns="image", operations=rescale_nml_op, num_parallel_workers=num_parallel_workers)
  150. mnist_ds = mnist_ds.map(input_columns="image", operations=hwc2chw_op, num_parallel_workers=num_parallel_workers)
  151. # apply DatasetOps
  152. buffer_size = 10000
  153. mnist_ds = mnist_ds.shuffle(buffer_size=buffer_size) # 10000 as in LeNet train script
  154. mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True)
  155. mnist_ds = mnist_ds.repeat(repeat_size)
  156. return mnist_ds
  157. @pytest.mark.level0
  158. @pytest.mark.platform_x86_gpu_training
  159. @pytest.mark.env_onecard
  160. def test_train_and_eval_lenet():
  161. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  162. network = LeNet5(10)
  163. net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True, reduction="mean")
  164. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  165. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()})
  166. print("============== Starting Training ==============")
  167. ds_train = create_dataset(os.path.join('/home/workspace/mindspore_dataset/mnist', "train"), 32, 1)
  168. model.train(1, ds_train, callbacks=[LossMonitor()], dataset_sink_mode=True)
  169. print("============== Starting Testing ==============")
  170. ds_eval = create_dataset(os.path.join('/home/workspace/mindspore_dataset/mnist', "test"), 32, 1)
  171. acc = model.eval(ds_eval, dataset_sink_mode=True)
  172. print("============== {} ==============".format(acc))