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