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 9.1 kB

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