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

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 Resnet50 on ImageNet"""
  16. import os
  17. import argparse
  18. from mindspore import context
  19. from mindspore import Tensor
  20. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  21. from mindspore.nn.optim.momentum import Momentum
  22. from mindspore.train.model import Model
  23. from mindspore.context import ParallelMode
  24. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  25. from mindspore.train.loss_scale_manager import FixedLossScaleManager
  26. from mindspore.train.serialization import load_checkpoint
  27. from mindspore.train.quant import quant
  28. from mindspore.train.quant.quant_utils import load_nonquant_param_into_quant_net
  29. from mindspore.communication.management import init
  30. import mindspore.nn as nn
  31. import mindspore.common.initializer as weight_init
  32. #from models.resnet_quant import resnet50_quant #auto construct quantative network of resnet50
  33. from models.resnet_quant_manual import resnet50_quant #manually construct quantative network of resnet50
  34. from src.dataset import create_dataset
  35. from src.lr_generator import get_lr
  36. from src.config import config_quant
  37. from src.crossentropy import CrossEntropy
  38. parser = argparse.ArgumentParser(description='Image classification')
  39. parser.add_argument('--run_distribute', type=bool, default=False, help='Run distribute')
  40. parser.add_argument('--device_num', type=int, default=1, help='Device num.')
  41. parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
  42. parser.add_argument('--device_target', type=str, default='Ascend', help='Device target')
  43. parser.add_argument('--pre_trained', type=str, default=None, help='Pertained checkpoint path')
  44. args_opt = parser.parse_args()
  45. config = config_quant
  46. if args_opt.device_target == "Ascend":
  47. device_id = int(os.getenv('DEVICE_ID'))
  48. rank_id = int(os.getenv('RANK_ID'))
  49. rank_size = int(os.getenv('RANK_SIZE'))
  50. run_distribute = rank_size > 1
  51. context.set_context(mode=context.GRAPH_MODE,
  52. device_target="Ascend",
  53. save_graphs=False,
  54. device_id=device_id,
  55. enable_auto_mixed_precision=True)
  56. else:
  57. raise ValueError("Unsupported device target.")
  58. if __name__ == '__main__':
  59. # train on ascend
  60. print("training args: {}".format(args_opt))
  61. print("training configure: {}".format(config))
  62. print("parallel args: rank_id {}, device_id {}, rank_size {}".format(rank_id, device_id, rank_size))
  63. epoch_size = config.epoch_size
  64. # distribute init
  65. if run_distribute:
  66. context.set_auto_parallel_context(device_num=rank_size,
  67. parallel_mode=ParallelMode.DATA_PARALLEL,
  68. parameter_broadcast=True,
  69. mirror_mean=True)
  70. init()
  71. context.set_auto_parallel_context(device_num=args_opt.device_num,
  72. parallel_mode=ParallelMode.DATA_PARALLEL,
  73. mirror_mean=True)
  74. auto_parallel_context().set_all_reduce_fusion_split_indices([107, 160])
  75. # define network
  76. net = resnet50_quant(class_num=config.class_num)
  77. net.set_train(True)
  78. # weight init and load checkpoint file
  79. if args_opt.pre_trained:
  80. param_dict = load_checkpoint(args_opt.pre_trained)
  81. load_nonquant_param_into_quant_net(net, param_dict, ['step'])
  82. epoch_size = config.epoch_size - config.pretrained_epoch_size
  83. else:
  84. for _, cell in net.cells_and_names():
  85. if isinstance(cell, nn.Conv2d):
  86. cell.weight.default_input = weight_init.initializer(weight_init.XavierUniform(),
  87. cell.weight.shape,
  88. cell.weight.dtype)
  89. if isinstance(cell, nn.Dense):
  90. cell.weight.default_input = weight_init.initializer(weight_init.TruncatedNormal(),
  91. cell.weight.shape,
  92. cell.weight.dtype)
  93. if not config.use_label_smooth:
  94. config.label_smooth_factor = 0.0
  95. loss = CrossEntropy(smooth_factor=config.label_smooth_factor, num_classes=config.class_num)
  96. loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)
  97. # define dataset
  98. dataset = create_dataset(dataset_path=args_opt.dataset_path,
  99. do_train=True,
  100. repeat_num=1,
  101. batch_size=config.batch_size,
  102. target=args_opt.device_target)
  103. step_size = dataset.get_dataset_size()
  104. # convert fusion network to quantization aware network
  105. net = quant.convert_quant_network(net, bn_fold=True, per_channel=[True, False], symmetric=[True, False])
  106. # get learning rate
  107. lr = get_lr(lr_init=config.lr_init,
  108. lr_end=0.0,
  109. lr_max=config.lr_max,
  110. warmup_epochs=config.warmup_epochs,
  111. total_epochs=config.epoch_size,
  112. steps_per_epoch=step_size,
  113. lr_decay_mode='cosine')
  114. if args_opt.pre_trained:
  115. lr = lr[config.pretrained_epoch_size * step_size:]
  116. lr = Tensor(lr)
  117. # define optimization
  118. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum,
  119. config.weight_decay, config.loss_scale)
  120. # define model
  121. model = Model(net, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale, metrics={'acc'})
  122. print("============== Starting Training ==============")
  123. time_callback = TimeMonitor(data_size=step_size)
  124. loss_callback = LossMonitor()
  125. callbacks = [time_callback, loss_callback]
  126. if rank_id == 0:
  127. if config.save_checkpoint:
  128. config_ckpt = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs * step_size,
  129. keep_checkpoint_max=config.keep_checkpoint_max)
  130. ckpt_callback = ModelCheckpoint(prefix="ResNet50",
  131. directory=config.save_checkpoint_path,
  132. config=config_ckpt)
  133. callbacks += [ckpt_callback]
  134. model.train(epoch_size, dataset, callbacks=callbacks)
  135. print("============== End Training ==============")