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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. # less 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 Retinaface_resnet50."""
  16. from __future__ import print_function
  17. import math
  18. import mindspore
  19. from mindspore import context
  20. from mindspore.context import ParallelMode
  21. from mindspore.train import Model
  22. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  23. from mindspore.communication.management import init, get_rank, get_group_size
  24. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  25. from src.config import cfg_res50
  26. from src.network import RetinaFace, RetinaFaceWithLossCell, TrainingWrapper, resnet50
  27. from src.loss import MultiBoxLoss
  28. from src.dataset import create_dataset
  29. from src.lr_schedule import adjust_learning_rate
  30. def train(cfg):
  31. context.set_context(mode=context.GRAPH_MODE, device_target='GPU', save_graphs=False)
  32. if cfg['ngpu'] > 1:
  33. init("nccl")
  34. context.set_auto_parallel_context(device_num=get_group_size(), parallel_mode=ParallelMode.DATA_PARALLEL,
  35. gradients_mean=True)
  36. cfg['ckpt_path'] = cfg['ckpt_path'] + "ckpt_" + str(get_rank()) + "/"
  37. else:
  38. raise ValueError('cfg_num_gpu <= 1')
  39. batch_size = cfg['batch_size']
  40. max_epoch = cfg['epoch']
  41. momentum = cfg['momentum']
  42. weight_decay = cfg['weight_decay']
  43. initial_lr = cfg['initial_lr']
  44. gamma = cfg['gamma']
  45. training_dataset = cfg['training_dataset']
  46. num_classes = 2
  47. negative_ratio = 7
  48. stepvalues = (cfg['decay1'], cfg['decay2'])
  49. ds_train = create_dataset(training_dataset, cfg, batch_size, multiprocessing=True, num_worker=cfg['num_workers'])
  50. print('dataset size is : \n', ds_train.get_dataset_size())
  51. steps_per_epoch = math.ceil(ds_train.get_dataset_size())
  52. multibox_loss = MultiBoxLoss(num_classes, cfg['num_anchor'], negative_ratio, cfg['batch_size'])
  53. backbone = resnet50(1001)
  54. backbone.set_train(True)
  55. if cfg['pretrain'] and cfg['resume_net'] is None:
  56. pretrained_res50 = cfg['pretrain_path']
  57. param_dict_res50 = load_checkpoint(pretrained_res50)
  58. load_param_into_net(backbone, param_dict_res50)
  59. print('Load resnet50 from [{}] done.'.format(pretrained_res50))
  60. net = RetinaFace(phase='train', backbone=backbone)
  61. net.set_train(True)
  62. if cfg['resume_net'] is not None:
  63. pretrain_model_path = cfg['resume_net']
  64. param_dict_retinaface = load_checkpoint(pretrain_model_path)
  65. load_param_into_net(net, param_dict_retinaface)
  66. print('Resume Model from [{}] Done.'.format(cfg['resume_net']))
  67. net = RetinaFaceWithLossCell(net, multibox_loss, cfg)
  68. lr = adjust_learning_rate(initial_lr, gamma, stepvalues, steps_per_epoch, max_epoch,
  69. warmup_epoch=cfg['warmup_epoch'])
  70. if cfg['optim'] == 'momentum':
  71. opt = mindspore.nn.Momentum(net.trainable_params(), lr, momentum)
  72. elif cfg['optim'] == 'sgd':
  73. opt = mindspore.nn.SGD(params=net.trainable_params(), learning_rate=lr, momentum=momentum,
  74. weight_decay=weight_decay, loss_scale=1)
  75. else:
  76. raise ValueError('optim is not define.')
  77. net = TrainingWrapper(net, opt)
  78. model = Model(net)
  79. config_ck = CheckpointConfig(save_checkpoint_steps=cfg['save_checkpoint_steps'],
  80. keep_checkpoint_max=cfg['keep_checkpoint_max'])
  81. ckpoint_cb = ModelCheckpoint(prefix="RetinaFace", directory=cfg['ckpt_path'], config=config_ck)
  82. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  83. callback_list = [LossMonitor(), time_cb, ckpoint_cb]
  84. print("============== Starting Training ==============")
  85. model.train(max_epoch, ds_train, callbacks=callback_list,
  86. dataset_sink_mode=True)
  87. if __name__ == '__main__':
  88. config = cfg_res50
  89. mindspore.common.seed.set_seed(config['seed'])
  90. print('train config:\n', config)
  91. train(cfg=config)