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.6 kB

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