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