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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 MaskRcnn and get checkpoint files."""
  16. import os
  17. import argparse
  18. import random
  19. import numpy as np
  20. import mindspore.common.dtype as mstype
  21. from mindspore import context, Tensor
  22. from mindspore.communication.management import init
  23. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, TimeMonitor
  24. from mindspore.train import Model, ParallelMode
  25. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  26. from mindspore.nn import SGD
  27. import mindspore.dataset.engine as de
  28. from src.MaskRcnn.mask_rcnn_r50 import Mask_Rcnn_Resnet50
  29. from src.network_define import LossCallBack, WithLossCell, TrainOneStepCell, LossNet
  30. from src.config import config
  31. from src.dataset import data_to_mindrecord_byte_image, create_maskrcnn_dataset
  32. from src.lr_schedule import dynamic_lr
  33. random.seed(1)
  34. np.random.seed(1)
  35. de.config.set_seed(1)
  36. parser = argparse.ArgumentParser(description="MaskRcnn training")
  37. parser.add_argument("--only_create_dataset", type=bool, default=False, help="If set it true, only create "
  38. "Mindrecord, default is false.")
  39. parser.add_argument("--run_distribute", type=bool, default=False, help="Run distribute, default is false.")
  40. parser.add_argument("--do_train", type=bool, default=True, help="Do train or not, default is true.")
  41. parser.add_argument("--do_eval", type=bool, default=False, help="Do eval or not, default is false.")
  42. parser.add_argument("--dataset", type=str, default="coco", help="Dataset, default is coco.")
  43. parser.add_argument("--pre_trained", type=str, default="", help="Pretrain file path.")
  44. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  45. parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default is 1.")
  46. parser.add_argument("--rank_id", type=int, default=0, help="Rank id, default is 0.")
  47. args_opt = parser.parse_args()
  48. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=True, device_id=args_opt.device_id)
  49. if __name__ == '__main__':
  50. print("Start train for maskrcnn!")
  51. if not args_opt.do_eval and args_opt.run_distribute:
  52. rank = args_opt.rank_id
  53. device_num = args_opt.device_num
  54. context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  55. mirror_mean=True, parameter_broadcast=True)
  56. init()
  57. else:
  58. rank = 0
  59. device_num = 1
  60. print("Start create dataset!")
  61. # It will generate mindrecord file in args_opt.mindrecord_dir,
  62. # and the file name is MaskRcnn.mindrecord0, 1, ... file_num.
  63. prefix = "MaskRcnn.mindrecord"
  64. mindrecord_dir = config.mindrecord_dir
  65. mindrecord_file = os.path.join(mindrecord_dir, prefix + "0")
  66. if not os.path.exists(mindrecord_file):
  67. if not os.path.isdir(mindrecord_dir):
  68. os.makedirs(mindrecord_dir)
  69. if args_opt.dataset == "coco":
  70. if os.path.isdir(config.coco_root):
  71. print("Create Mindrecord.")
  72. data_to_mindrecord_byte_image("coco", True, prefix)
  73. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  74. else:
  75. print("coco_root not exits.")
  76. else:
  77. if os.path.isdir(config.IMAGE_DIR) and os.path.exists(config.ANNO_PATH):
  78. print("Create Mindrecord.")
  79. data_to_mindrecord_byte_image("other", True, prefix)
  80. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  81. else:
  82. print("IMAGE_DIR or ANNO_PATH not exits.")
  83. if not args_opt.only_create_dataset:
  84. loss_scale = float(config.loss_scale)
  85. # When create MindDataset, using the fitst mindrecord file, such as MaskRcnn.mindrecord0.
  86. dataset = create_maskrcnn_dataset(mindrecord_file, batch_size=config.batch_size,
  87. device_num=device_num, rank_id=rank)
  88. dataset_size = dataset.get_dataset_size()
  89. print("total images num: ", dataset_size)
  90. print("Create dataset done!")
  91. net = Mask_Rcnn_Resnet50(config=config)
  92. net = net.set_train()
  93. load_path = args_opt.pre_trained
  94. if load_path != "":
  95. param_dict = load_checkpoint(load_path)
  96. for item in list(param_dict.keys()):
  97. if not (item.startswith('backbone') or item.startswith('rcnn_mask')):
  98. param_dict.pop(item)
  99. load_param_into_net(net, param_dict)
  100. loss = LossNet()
  101. lr = Tensor(dynamic_lr(config, rank_size=device_num), mstype.float32)
  102. opt = SGD(params=net.trainable_params(), learning_rate=lr, momentum=config.momentum,
  103. weight_decay=config.weight_decay, loss_scale=config.loss_scale)
  104. net_with_loss = WithLossCell(net, loss)
  105. if args_opt.run_distribute:
  106. net = TrainOneStepCell(net_with_loss, net, opt, sens=config.loss_scale, reduce_flag=True,
  107. mean=True, degree=device_num)
  108. else:
  109. net = TrainOneStepCell(net_with_loss, net, opt, sens=config.loss_scale)
  110. time_cb = TimeMonitor(data_size=dataset_size)
  111. loss_cb = LossCallBack()
  112. cb = [time_cb, loss_cb]
  113. if config.save_checkpoint:
  114. ckptconfig = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs * dataset_size,
  115. keep_checkpoint_max=config.keep_checkpoint_max)
  116. ckpoint_cb = ModelCheckpoint(prefix='mask_rcnn', directory=config.save_checkpoint_path, config=ckptconfig)
  117. cb += [ckpoint_cb]
  118. model = Model(net)
  119. model.train(config.epoch_size, dataset, callbacks=cb)