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.

train.py 8.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. """train_imagenet."""
  16. import time
  17. import argparse
  18. import random
  19. import numpy as np
  20. from mindspore import context
  21. from mindspore import Tensor
  22. from mindspore import nn
  23. from mindspore.nn.optim.momentum import Momentum
  24. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  25. from mindspore.nn.loss.loss import _Loss
  26. from mindspore.ops import operations as P
  27. from mindspore.ops import functional as F
  28. from mindspore.common import dtype as mstype
  29. from mindspore.train.model import Model, ParallelMode
  30. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, Callback
  31. from mindspore.train.loss_scale_manager import FixedLossScaleManager
  32. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  33. import mindspore.dataset.engine as de
  34. from mindspore.communication.management import init, get_group_size, get_rank
  35. from src.dataset import create_dataset
  36. from src.lr_generator import get_lr
  37. from src.config import config_gpu
  38. from src.mobilenetV3 import mobilenet_v3_large
  39. random.seed(1)
  40. np.random.seed(1)
  41. de.config.set_seed(1)
  42. parser = argparse.ArgumentParser(description='Image classification')
  43. parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
  44. parser.add_argument('--pre_trained', type=str, default=None, help='Pretrained checkpoint path')
  45. parser.add_argument('--device_target', type=str, default="GPU", help='run device_target')
  46. args_opt = parser.parse_args()
  47. if args_opt.device_target == "GPU":
  48. context.set_context(mode=context.GRAPH_MODE,
  49. device_target="GPU",
  50. save_graphs=False)
  51. init()
  52. context.set_auto_parallel_context(device_num=get_group_size(),
  53. parallel_mode=ParallelMode.DATA_PARALLEL,
  54. mirror_mean=True)
  55. else:
  56. raise ValueError("Unsupported device_target.")
  57. class CrossEntropyWithLabelSmooth(_Loss):
  58. """
  59. CrossEntropyWith LabelSmooth.
  60. Args:
  61. smooth_factor (float): smooth factor, default=0.
  62. num_classes (int): num classes
  63. Returns:
  64. None.
  65. Examples:
  66. >>> CrossEntropyWithLabelSmooth(smooth_factor=0., num_classes=1000)
  67. """
  68. def __init__(self, smooth_factor=0., num_classes=1000):
  69. super(CrossEntropyWithLabelSmooth, self).__init__()
  70. self.onehot = P.OneHot()
  71. self.on_value = Tensor(1.0 - smooth_factor, mstype.float32)
  72. self.off_value = Tensor(1.0 * smooth_factor /
  73. (num_classes - 1), mstype.float32)
  74. self.ce = nn.SoftmaxCrossEntropyWithLogits()
  75. self.mean = P.ReduceMean(False)
  76. self.cast = P.Cast()
  77. def construct(self, logit, label):
  78. one_hot_label = self.onehot(self.cast(label, mstype.int32), F.shape(logit)[1],
  79. self.on_value, self.off_value)
  80. out_loss = self.ce(logit, one_hot_label)
  81. out_loss = self.mean(out_loss, 0)
  82. return out_loss
  83. class Monitor(Callback):
  84. """
  85. Monitor loss and time.
  86. Args:
  87. lr_init (numpy array): train lr
  88. Returns:
  89. None
  90. Examples:
  91. >>> Monitor(100,lr_init=Tensor([0.05]*100).asnumpy())
  92. """
  93. def __init__(self, lr_init=None):
  94. super(Monitor, self).__init__()
  95. self.lr_init = lr_init
  96. self.lr_init_len = len(lr_init)
  97. def epoch_begin(self, run_context):
  98. self.losses = []
  99. self.epoch_time = time.time()
  100. def epoch_end(self, run_context):
  101. cb_params = run_context.original_args()
  102. epoch_mseconds = (time.time() - self.epoch_time) * 1000
  103. per_step_mseconds = epoch_mseconds / cb_params.batch_num
  104. print("epoch time: {:5.3f}, per step time: {:5.3f}, avg loss: {:5.3f}".format(epoch_mseconds,
  105. per_step_mseconds,
  106. np.mean(self.losses)))
  107. def step_begin(self, run_context):
  108. self.step_time = time.time()
  109. def step_end(self, run_context):
  110. cb_params = run_context.original_args()
  111. step_mseconds = (time.time() - self.step_time) * 1000
  112. step_loss = cb_params.net_outputs
  113. if isinstance(step_loss, (tuple, list)) and isinstance(step_loss[0], Tensor):
  114. step_loss = step_loss[0]
  115. if isinstance(step_loss, Tensor):
  116. step_loss = np.mean(step_loss.asnumpy())
  117. self.losses.append(step_loss)
  118. cur_step_in_epoch = (cb_params.cur_step_num - 1) % cb_params.batch_num
  119. print("epoch: [{:3d}/{:3d}], step:[{:5d}/{:5d}], loss:[{:5.3f}/{:5.3f}], time:[{:5.3f}], lr:[{:5.3f}]".format(
  120. cb_params.cur_epoch_num -
  121. 1, cb_params.epoch_num, cur_step_in_epoch, cb_params.batch_num, step_loss,
  122. np.mean(self.losses), step_mseconds, self.lr_init[cb_params.cur_step_num - 1]))
  123. if __name__ == '__main__':
  124. if args_opt.device_target == "GPU":
  125. # train on gpu
  126. print("train args: ", args_opt)
  127. print("cfg: ", config_gpu)
  128. # define net
  129. net = mobilenet_v3_large(num_classes=config_gpu.num_classes)
  130. # define loss
  131. if config_gpu.label_smooth > 0:
  132. loss = CrossEntropyWithLabelSmooth(
  133. smooth_factor=config_gpu.label_smooth, num_classes=config_gpu.num_classes)
  134. else:
  135. loss = SoftmaxCrossEntropyWithLogits(
  136. is_grad=False, sparse=True, reduction='mean')
  137. # define dataset
  138. epoch_size = config_gpu.epoch_size
  139. dataset = create_dataset(dataset_path=args_opt.dataset_path,
  140. do_train=True,
  141. config=config_gpu,
  142. device_target=args_opt.device_target,
  143. repeat_num=1,
  144. batch_size=config_gpu.batch_size)
  145. step_size = dataset.get_dataset_size()
  146. # resume
  147. if args_opt.pre_trained:
  148. param_dict = load_checkpoint(args_opt.pre_trained)
  149. load_param_into_net(net, param_dict)
  150. # define optimizer
  151. loss_scale = FixedLossScaleManager(
  152. config_gpu.loss_scale, drop_overflow_update=False)
  153. lr = Tensor(get_lr(global_step=0,
  154. lr_init=0,
  155. lr_end=0,
  156. lr_max=config_gpu.lr,
  157. warmup_epochs=config_gpu.warmup_epochs,
  158. total_epochs=epoch_size,
  159. steps_per_epoch=step_size))
  160. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config_gpu.momentum,
  161. config_gpu.weight_decay, config_gpu.loss_scale)
  162. # define model
  163. model = Model(net, loss_fn=loss, optimizer=opt,
  164. loss_scale_manager=loss_scale)
  165. cb = [Monitor(lr_init=lr.asnumpy())]
  166. ckpt_save_dir = config_gpu.save_checkpoint_path + "ckpt_" + str(get_rank()) + "/"
  167. if config_gpu.save_checkpoint:
  168. config_ck = CheckpointConfig(save_checkpoint_steps=config_gpu.save_checkpoint_epochs * step_size,
  169. keep_checkpoint_max=config_gpu.keep_checkpoint_max)
  170. ckpt_cb = ModelCheckpoint(prefix="mobilenetV3", directory=ckpt_save_dir, config=config_ck)
  171. cb += [ckpt_cb]
  172. # begine train
  173. model.train(epoch_size, dataset, callbacks=cb)