train.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. __dir__ = os.path.dirname(os.path.abspath(__file__))
  20. sys.path.append(__dir__)
  21. sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))
  22. import yaml
  23. import paddle
  24. import paddle.distributed as dist
  25. paddle.seed(2)
  26. from ppocr.data import build_dataloader
  27. from ppocr.modeling.architectures import build_model
  28. from ppocr.losses import build_loss
  29. from ppocr.optimizer import build_optimizer
  30. from ppocr.postprocess import build_post_process
  31. from ppocr.metrics import build_metric
  32. from ppocr.utils.save_load import init_model
  33. import tools.program as program
  34. dist.get_world_size()
  35. def main(config, device, logger, vdl_writer):
  36. # init dist environment
  37. if config['Global']['distributed']:
  38. dist.init_parallel_env()
  39. global_config = config['Global']
  40. # build dataloader
  41. train_dataloader = build_dataloader(config, 'Train', device, logger)
  42. if len(train_dataloader) == 0:
  43. logger.error(
  44. 'No Images in train dataset, please check annotation file and path in the configuration file'
  45. )
  46. return
  47. if config['Eval']:
  48. valid_dataloader = build_dataloader(config, 'Eval', device, logger)
  49. else:
  50. valid_dataloader = None
  51. # build post process
  52. post_process_class = build_post_process(config['PostProcess'],
  53. global_config)
  54. # build model
  55. # for rec algorithm
  56. if hasattr(post_process_class, 'character'):
  57. char_num = len(getattr(post_process_class, 'character'))
  58. config['Architecture']["Head"]['out_channels'] = char_num
  59. model = build_model(config['Architecture'])
  60. if config['Global']['distributed']:
  61. model = paddle.DataParallel(model)
  62. # build loss
  63. loss_class = build_loss(config['Loss'])
  64. # build optim
  65. optimizer, lr_scheduler = build_optimizer(
  66. config['Optimizer'],
  67. epochs=config['Global']['epoch_num'],
  68. step_each_epoch=len(train_dataloader),
  69. parameters=model.parameters())
  70. # build metric
  71. eval_class = build_metric(config['Metric'])
  72. # load pretrain model
  73. pre_best_model_dict = init_model(config, model, logger, optimizer)
  74. logger.info('train dataloader has {} iters, valid dataloader has {} iters'.
  75. format(len(train_dataloader), len(valid_dataloader)))
  76. # start train
  77. program.train(config, train_dataloader, valid_dataloader, device, model,
  78. loss_class, optimizer, lr_scheduler, post_process_class,
  79. eval_class, pre_best_model_dict, logger, vdl_writer)
  80. def test_reader(config, device, logger):
  81. loader = build_dataloader(config, 'Train', device, logger)
  82. import time
  83. starttime = time.time()
  84. count = 0
  85. try:
  86. for data in loader():
  87. count += 1
  88. if count % 1 == 0:
  89. batch_time = time.time() - starttime
  90. starttime = time.time()
  91. logger.info("reader: {}, {}, {}".format(
  92. count, len(data[0]), batch_time))
  93. except Exception as e:
  94. logger.info(e)
  95. logger.info("finish reader: {}, Success!".format(count))
  96. if __name__ == '__main__':
  97. config, device, logger, vdl_writer = program.preprocess(is_train=True)
  98. main(config, device, logger, vdl_writer)
  99. # test_reader(config, device, logger)