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

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. """
  16. ######################## train YOLOv3 example ########################
  17. train YOLOv3 and get network model files(.ckpt) :
  18. python train.py --image_dir /data --anno_path /data/coco/train_coco.txt --mindrecord_dir=/data/Mindrecord_train
  19. If the mindrecord_dir is empty, it wil generate mindrecord file by image_dir and anno_path.
  20. Note if mindrecord_dir isn't empty, it will use mindrecord_dir rather than image_dir and anno_path.
  21. """
  22. import os
  23. import argparse
  24. import numpy as np
  25. import mindspore.nn as nn
  26. from mindspore import context, Tensor
  27. from mindspore.communication.management import init
  28. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, LossMonitor, TimeMonitor
  29. from mindspore.train import Model, ParallelMode
  30. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  31. from mindspore.common.initializer import initializer
  32. from mindspore.model_zoo.yolov3 import yolov3_resnet18, YoloWithLossCell, TrainingWrapper
  33. from dataset import create_yolo_dataset, data_to_mindrecord_byte_image
  34. from config import ConfigYOLOV3ResNet18
  35. def get_lr(learning_rate, start_step, global_step, decay_step, decay_rate, steps=False):
  36. """Set learning rate."""
  37. lr_each_step = []
  38. for i in range(global_step):
  39. if steps:
  40. lr_each_step.append(learning_rate * (decay_rate ** (i // decay_step)))
  41. else:
  42. lr_each_step.append(learning_rate * (decay_rate ** (i / decay_step)))
  43. lr_each_step = np.array(lr_each_step).astype(np.float32)
  44. lr_each_step = lr_each_step[start_step:]
  45. return lr_each_step
  46. def init_net_param(network, init_value='ones'):
  47. """Init:wq the parameters in network."""
  48. params = network.trainable_params()
  49. for p in params:
  50. if isinstance(p.data, Tensor) and 'beta' not in p.name and 'gamma' not in p.name and 'bias' not in p.name:
  51. p.set_parameter_data(initializer(init_value, p.data.shape(), p.data.dtype()))
  52. def main():
  53. parser = argparse.ArgumentParser(description="YOLOv3 train")
  54. parser.add_argument("--only_create_dataset", type=bool, default=False, help="If set it true, only create "
  55. "Mindrecord, default is false.")
  56. parser.add_argument("--distribute", type=bool, default=False, help="Run distribute, default is false.")
  57. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  58. parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default is 1.")
  59. parser.add_argument("--lr", type=float, default=0.001, help="Learning rate, default is 0.001.")
  60. parser.add_argument("--mode", type=str, default="sink", help="Run sink mode or not, default is sink")
  61. parser.add_argument("--epoch_size", type=int, default=10, help="Epoch size, default is 10")
  62. parser.add_argument("--batch_size", type=int, default=32, help="Batch size, default is 32.")
  63. parser.add_argument("--pre_trained", type=str, default=None, help="Pretrained checkpoint file path")
  64. parser.add_argument("--save_checkpoint_epochs", type=int, default=5, help="Save checkpoint epochs, default is 5.")
  65. parser.add_argument("--loss_scale", type=int, default=1024, help="Loss scale, default is 1024.")
  66. parser.add_argument("--mindrecord_dir", type=str, default="./Mindrecord_train",
  67. help="Mindrecord directory. If the mindrecord_dir is empty, it wil generate mindrecord file by"
  68. "image_dir and anno_path. Note if mindrecord_dir isn't empty, it will use mindrecord_dir "
  69. "rather than image_dir and anno_path. Default is ./Mindrecord_train")
  70. parser.add_argument("--image_dir", type=str, default="", help="Dataset directory, "
  71. "the absolute image path is joined by the image_dir "
  72. "and the relative path in anno_path")
  73. parser.add_argument("--anno_path", type=str, default="", help="Annotation path.")
  74. args_opt = parser.parse_args()
  75. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=args_opt.device_id)
  76. if args_opt.distribute:
  77. device_num = args_opt.device_num
  78. context.reset_auto_parallel_context()
  79. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, mirror_mean=True,
  80. device_num=device_num)
  81. init()
  82. rank = args_opt.device_id % device_num
  83. else:
  84. rank = 0
  85. device_num = 1
  86. print("Start create dataset!")
  87. # It will generate mindrecord file in args_opt.mindrecord_dir,
  88. # and the file name is yolo.mindrecord0, 1, ... file_num.
  89. if not os.path.isdir(args_opt.mindrecord_dir):
  90. os.makedirs(args_opt.mindrecord_dir)
  91. prefix = "yolo.mindrecord"
  92. mindrecord_file = os.path.join(args_opt.mindrecord_dir, prefix + "0")
  93. if not os.path.exists(mindrecord_file):
  94. if os.path.isdir(args_opt.image_dir) and os.path.exists(args_opt.anno_path):
  95. print("Create Mindrecord.")
  96. data_to_mindrecord_byte_image(args_opt.image_dir,
  97. args_opt.anno_path,
  98. args_opt.mindrecord_dir,
  99. prefix=prefix,
  100. file_num=8)
  101. print("Create Mindrecord Done, at {}".format(args_opt.mindrecord_dir))
  102. else:
  103. print("image_dir or anno_path not exits.")
  104. if not args_opt.only_create_dataset:
  105. loss_scale = float(args_opt.loss_scale)
  106. # When create MindDataset, using the fitst mindrecord file, such as yolo.mindrecord0.
  107. dataset = create_yolo_dataset(mindrecord_file, repeat_num=args_opt.epoch_size,
  108. batch_size=args_opt.batch_size, device_num=device_num, rank=rank)
  109. dataset_size = dataset.get_dataset_size()
  110. print("Create dataset done!")
  111. net = yolov3_resnet18(ConfigYOLOV3ResNet18())
  112. net = YoloWithLossCell(net, ConfigYOLOV3ResNet18())
  113. init_net_param(net, "XavierUniform")
  114. # checkpoint
  115. ckpt_config = CheckpointConfig(save_checkpoint_steps=dataset_size * args_opt.save_checkpoint_epochs)
  116. ckpoint_cb = ModelCheckpoint(prefix="yolov3", directory=None, config=ckpt_config)
  117. lr = Tensor(get_lr(learning_rate=args_opt.lr, start_step=0, global_step=args_opt.epoch_size * dataset_size,
  118. decay_step=1000, decay_rate=0.95, steps=True))
  119. opt = nn.Adam(filter(lambda x: x.requires_grad, net.get_parameters()), lr, loss_scale=loss_scale)
  120. net = TrainingWrapper(net, opt, loss_scale)
  121. if args_opt.pre_trained:
  122. param_dict = load_checkpoint(args_opt.pre_trained)
  123. load_param_into_net(net, param_dict)
  124. callback = [TimeMonitor(data_size=dataset_size), LossMonitor(), ckpoint_cb]
  125. model = Model(net)
  126. dataset_sink_mode = False
  127. if args_opt.mode == "sink":
  128. print("In sink mode, one epoch return a loss.")
  129. dataset_sink_mode = True
  130. print("Start train YOLOv3, the first epoch will be slower because of the graph compilation.")
  131. model.train(args_opt.epoch_size, dataset, callbacks=callback, dataset_sink_mode=dataset_sink_mode)
  132. if __name__ == '__main__':
  133. main()