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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Copyright 2020-2021 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. """Face Recognition train."""
  16. import os
  17. import time
  18. import argparse
  19. import datetime
  20. import warnings
  21. import random
  22. import numpy as np
  23. import mindspore
  24. from mindspore import context
  25. from mindspore import Tensor
  26. from mindspore.context import ParallelMode
  27. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  28. from mindspore.train.callback import ModelCheckpoint, RunContext, _InternalCallbackParam, CheckpointConfig
  29. from mindspore.nn.optim import SGD
  30. from mindspore.nn import TrainOneStepCell
  31. from mindspore.communication.management import get_group_size, init, get_rank
  32. from src.dataset import get_de_dataset
  33. from src.config import reid_1p_cfg_ascend, reid_1p_cfg, reid_8p_cfg_ascend, reid_8p_cfg_gpu
  34. from src.lr_generator import step_lr
  35. from src.log import get_logger, AverageMeter
  36. from src.reid import SphereNet, CombineMarginFCFp16, BuildTrainNetworkWithHead, CombineMarginFC
  37. from src.loss import CrossEntropy
  38. warnings.filterwarnings('ignore')
  39. random.seed(1)
  40. np.random.seed(1)
  41. def init_argument():
  42. """init config argument."""
  43. parser = argparse.ArgumentParser(description='Face Recognition For Tracking')
  44. parser.add_argument('--device_target', type=str, choices=['Ascend', 'GPU', 'CPU'], default='Ascend',
  45. help='device_target')
  46. parser.add_argument('--is_distributed', type=int, default=0, help='if multi device')
  47. parser.add_argument('--data_dir', type=str, default='', help='image folders')
  48. parser.add_argument('--pretrained', type=str, default='', help='pretrained model to load')
  49. args = parser.parse_args()
  50. graph_path = os.path.join('./graphs_graphmode', datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  51. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target, save_graphs=True,
  52. save_graphs_path=graph_path)
  53. if args.device_target == 'Ascend':
  54. devid = int(os.getenv('DEVICE_ID'))
  55. context.set_context(device_id=devid)
  56. if args.is_distributed == 0:
  57. if args.device_target == 'Ascend':
  58. cfg = reid_1p_cfg_ascend
  59. else:
  60. cfg = reid_1p_cfg
  61. else:
  62. if args.device_target == 'Ascend':
  63. cfg = reid_8p_cfg_ascend
  64. else:
  65. cfg = reid_8p_cfg_gpu
  66. cfg.pretrained = args.pretrained
  67. cfg.data_dir = args.data_dir
  68. # Init distributed
  69. if args.is_distributed:
  70. init()
  71. cfg.local_rank = get_rank()
  72. cfg.world_size = get_group_size()
  73. parallel_mode = ParallelMode.DATA_PARALLEL
  74. else:
  75. parallel_mode = ParallelMode.STAND_ALONE
  76. # parallel_mode 'STAND_ALONE' do not support parameter_broadcast and mirror_mean
  77. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=cfg.world_size,
  78. gradients_mean=True)
  79. mindspore.common.set_seed(1)
  80. # logger
  81. cfg.outputs_dir = os.path.join(cfg.ckpt_path, datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  82. cfg.logger = get_logger(cfg.outputs_dir, cfg.local_rank)
  83. # Show cfg
  84. cfg.logger.save_args(cfg)
  85. return cfg, args
  86. def main():
  87. cfg, args = init_argument()
  88. loss_meter = AverageMeter('loss')
  89. # dataloader
  90. cfg.logger.info('start create dataloader')
  91. de_dataset, steps_per_epoch, class_num = get_de_dataset(cfg)
  92. cfg.steps_per_epoch = steps_per_epoch
  93. cfg.logger.info('step per epoch: %s', cfg.steps_per_epoch)
  94. de_dataloader = de_dataset.create_tuple_iterator()
  95. cfg.logger.info('class num original: %s', class_num)
  96. if class_num % 16 != 0:
  97. class_num = (class_num // 16 + 1) * 16
  98. cfg.class_num = class_num
  99. cfg.logger.info('change the class num to: %s', cfg.class_num)
  100. cfg.logger.info('end create dataloader')
  101. # backbone and loss
  102. cfg.logger.important_info('start create network')
  103. create_network_start = time.time()
  104. network = SphereNet(num_layers=cfg.net_depth, feature_dim=cfg.embedding_size, shape=cfg.input_size)
  105. if args.device_target == 'CPU':
  106. head = CombineMarginFC(embbeding_size=cfg.embedding_size, classnum=cfg.class_num)
  107. else:
  108. head = CombineMarginFCFp16(embbeding_size=cfg.embedding_size, classnum=cfg.class_num)
  109. criterion = CrossEntropy()
  110. # load the pretrained model
  111. if os.path.isfile(cfg.pretrained):
  112. param_dict = load_checkpoint(cfg.pretrained)
  113. param_dict_new = {}
  114. for key, values in param_dict.items():
  115. if key.startswith('moments.'):
  116. continue
  117. elif key.startswith('network.'):
  118. param_dict_new[key[8:]] = values
  119. else:
  120. param_dict_new[key] = values
  121. load_param_into_net(network, param_dict_new)
  122. cfg.logger.info('load model %s success', cfg.pretrained)
  123. # mixed precision training
  124. if args.device_target == 'CPU':
  125. network.add_flags_recursive(fp32=True)
  126. head.add_flags_recursive(fp32=True)
  127. else:
  128. network.add_flags_recursive(fp16=True)
  129. head.add_flags_recursive(fp16=True)
  130. criterion.add_flags_recursive(fp32=True)
  131. train_net = BuildTrainNetworkWithHead(network, head, criterion)
  132. # optimizer and lr scheduler
  133. lr = step_lr(lr=cfg.lr, epoch_size=cfg.epoch_size, steps_per_epoch=cfg.steps_per_epoch, max_epoch=cfg.max_epoch,
  134. gamma=cfg.lr_gamma)
  135. opt = SGD(params=train_net.trainable_params(), learning_rate=lr, momentum=cfg.momentum,
  136. weight_decay=cfg.weight_decay, loss_scale=cfg.loss_scale)
  137. # package training process, adjust lr + forward + backward + optimizer
  138. train_net = TrainOneStepCell(train_net, opt, sens=cfg.loss_scale)
  139. # checkpoint save
  140. if cfg.local_rank == 0:
  141. ckpt_max_num = cfg.max_epoch * cfg.steps_per_epoch // cfg.ckpt_interval
  142. train_config = CheckpointConfig(save_checkpoint_steps=cfg.ckpt_interval, keep_checkpoint_max=ckpt_max_num)
  143. ckpt_cb = ModelCheckpoint(config=train_config, directory=cfg.outputs_dir, prefix='{}'.format(cfg.local_rank))
  144. cb_params = _InternalCallbackParam()
  145. cb_params.train_network = train_net
  146. cb_params.epoch_num = ckpt_max_num
  147. cb_params.cur_epoch_num = 1
  148. run_context = RunContext(cb_params)
  149. ckpt_cb.begin(run_context)
  150. train_net.set_train()
  151. t_end = time.time()
  152. t_epoch = time.time()
  153. old_progress = -1
  154. cfg.logger.important_info('====start train====')
  155. for i, total_data in enumerate(de_dataloader):
  156. data, gt = total_data
  157. data = Tensor(data)
  158. gt = Tensor(gt)
  159. loss = train_net(data, gt)
  160. loss_meter.update(loss.asnumpy())
  161. # ckpt
  162. if cfg.local_rank == 0:
  163. cb_params.cur_step_num = i + 1 # current step number
  164. cb_params.batch_num = i + 2
  165. ckpt_cb.step_end(run_context)
  166. # logging loss, fps, ...
  167. if i == 0:
  168. time_for_graph_compile = time.time() - create_network_start
  169. cfg.logger.important_info('{}, graph compile time={:.2f}s'.format(cfg.task, time_for_graph_compile))
  170. if i % cfg.log_interval == 0 and cfg.local_rank == 0:
  171. time_used = time.time() - t_end
  172. epoch = int(i / cfg.steps_per_epoch)
  173. fps = cfg.per_batch_size * (i - old_progress) * cfg.world_size / time_used
  174. cfg.logger.info('epoch[{}], iter[{}], {}, {:.2f} imgs/sec, lr={}'.format(epoch, i, loss_meter, fps, lr[i]))
  175. t_end = time.time()
  176. loss_meter.reset()
  177. old_progress = i
  178. if i % cfg.steps_per_epoch == 0 and cfg.local_rank == 0:
  179. epoch_time_used = time.time() - t_epoch
  180. epoch = int(i / cfg.steps_per_epoch)
  181. fps = cfg.per_batch_size * cfg.world_size * cfg.steps_per_epoch / epoch_time_used
  182. cfg.logger.info('=================================================')
  183. cfg.logger.info('epoch time: epoch[{}], iter[{}], {:.2f} imgs/sec'.format(epoch, i, fps))
  184. cfg.logger.info('=================================================')
  185. t_epoch = time.time()
  186. cfg.logger.important_info('====train end====')
  187. if __name__ == "__main__":
  188. main()