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.2 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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 Deeptext and get checkpoint files."""
  16. import argparse
  17. import ast
  18. import os
  19. import time
  20. import numpy as np
  21. from src.Deeptext.deeptext_vgg16 import Deeptext_VGG16
  22. from src.config import config
  23. from src.dataset import data_to_mindrecord_byte_image, create_deeptext_dataset
  24. from src.lr_schedule import dynamic_lr
  25. from src.network_define import LossCallBack, WithLossCell, TrainOneStepCell, LossNet
  26. import mindspore.common.dtype as mstype
  27. from mindspore import context, Tensor
  28. from mindspore.common import set_seed
  29. from mindspore.communication.management import init
  30. from mindspore.context import ParallelMode
  31. from mindspore.nn import Momentum
  32. from mindspore.train import Model
  33. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, TimeMonitor
  34. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  35. np.set_printoptions(threshold=np.inf)
  36. set_seed(1)
  37. parser = argparse.ArgumentParser(description="Deeptext training")
  38. parser.add_argument("--run_distribute", type=ast.literal_eval, default=False, help="Run distribute, default: False.")
  39. parser.add_argument("--dataset", type=str, default="coco", help="Dataset name, default: coco.")
  40. parser.add_argument("--pre_trained", type=str, default="", help="Pretrained file path.")
  41. parser.add_argument("--device_id", type=int, default=5, help="Device id, default: 5.")
  42. parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default: 1.")
  43. parser.add_argument("--rank_id", type=int, default=0, help="Rank id, default: 0.")
  44. parser.add_argument("--imgs_path", type=str, required=True,
  45. help="Train images files paths, multiple paths can be separated by ','.")
  46. parser.add_argument("--annos_path", type=str, required=True,
  47. help="Annotations files paths of train images, multiple paths can be separated by ','.")
  48. parser.add_argument("--mindrecord_prefix", type=str, default='Deeptext-TRAIN', help="Prefix of mindrecord.")
  49. args_opt = parser.parse_args()
  50. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=args_opt.device_id)
  51. if __name__ == '__main__':
  52. if args_opt.run_distribute:
  53. rank = args_opt.rank_id
  54. device_num = args_opt.device_num
  55. context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  56. gradients_mean=True)
  57. init()
  58. else:
  59. rank = 0
  60. device_num = 1
  61. print("Start create dataset!")
  62. # It will generate mindrecord file in args_opt.mindrecord_dir,
  63. # and the file name is DeepText.mindrecord0, 1, ... file_num.
  64. prefix = args_opt.mindrecord_prefix
  65. config.train_images = args_opt.imgs_path
  66. config.train_txts = args_opt.annos_path
  67. mindrecord_dir = config.mindrecord_dir
  68. mindrecord_file = os.path.join(mindrecord_dir, prefix + "0")
  69. print("CHECKING MINDRECORD FILES ...")
  70. if rank == 0 and not os.path.exists(mindrecord_file):
  71. if not os.path.isdir(mindrecord_dir):
  72. os.makedirs(mindrecord_dir)
  73. if os.path.isdir(config.coco_root):
  74. if not os.path.exists(config.coco_root):
  75. print("Please make sure config:coco_root is valid.")
  76. raise ValueError(config.coco_root)
  77. print("Create Mindrecord. It may take some time.")
  78. data_to_mindrecord_byte_image(True, prefix)
  79. print("Create Mindrecord Done, at {}".format(mindrecord_dir))
  80. else:
  81. print("coco_root not exits.")
  82. while not os.path.exists(mindrecord_file + ".db"):
  83. time.sleep(5)
  84. print("CHECKING MINDRECORD FILES DONE!")
  85. loss_scale = float(config.loss_scale)
  86. # When create MindDataset, using the fitst mindrecord file, such as FasterRcnn.mindrecord0.
  87. dataset = create_deeptext_dataset(mindrecord_file, repeat_num=1,
  88. batch_size=config.batch_size, device_num=device_num, rank_id=rank)
  89. dataset_size = dataset.get_dataset_size()
  90. print("Create dataset done! dataset_size = ", dataset_size)
  91. net = Deeptext_VGG16(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. load_param_into_net(net, param_dict)
  97. loss = LossNet()
  98. lr = Tensor(dynamic_lr(config, rank_size=device_num), mstype.float32)
  99. opt = Momentum(params=net.trainable_params(), learning_rate=lr, momentum=config.momentum,
  100. weight_decay=config.weight_decay, loss_scale=config.loss_scale)
  101. net_with_loss = WithLossCell(net, loss)
  102. if args_opt.run_distribute:
  103. net = TrainOneStepCell(net_with_loss, opt, sens=config.loss_scale, reduce_flag=True,
  104. mean=True, degree=device_num)
  105. else:
  106. net = TrainOneStepCell(net_with_loss, opt, sens=config.loss_scale)
  107. time_cb = TimeMonitor(data_size=dataset_size)
  108. loss_cb = LossCallBack(rank_id=rank)
  109. cb = [time_cb, loss_cb]
  110. if config.save_checkpoint:
  111. ckptconfig = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs * dataset_size,
  112. keep_checkpoint_max=config.keep_checkpoint_max)
  113. save_checkpoint_path = os.path.join(config.save_checkpoint_path, "ckpt_" + str(rank) + "/")
  114. ckpoint_cb = ModelCheckpoint(prefix='deeptext', directory=save_checkpoint_path, config=ckptconfig)
  115. cb += [ckpoint_cb]
  116. model = Model(net)
  117. model.train(config.epoch_size, dataset, callbacks=cb, dataset_sink_mode=True)