trainer.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. import os
  15. import shutil
  16. from pathlib import Path
  17. import lazy_paddle as paddle
  18. from ..base import BaseTrainer, BaseTrainDeamon
  19. from ...utils.config import AttrDict
  20. from .model_list import MODELS
  21. class TextRecTrainer(BaseTrainer):
  22. """Text Recognition Model Trainer"""
  23. entities = MODELS
  24. def dump_label_dict(self, src_label_dict_path: str):
  25. """dump label dict config
  26. Args:
  27. src_label_dict_path (str): path to label dict file to be saved.
  28. """
  29. dst_label_dict_path = Path(self.global_config.output).joinpath("label_dict.txt")
  30. shutil.copyfile(src_label_dict_path, dst_label_dict_path)
  31. def build_deamon(self, config: AttrDict) -> "TextRecTrainDeamon":
  32. """build deamon thread for saving training outputs timely
  33. Args:
  34. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  35. Returns:
  36. TextRecTrainDeamon: the training deamon thread object for saving training outputs timely.
  37. """
  38. return TextRecTrainDeamon(config)
  39. def update_config(self):
  40. """update training config"""
  41. if self.train_config.log_interval:
  42. self.pdx_config.update_log_interval(self.train_config.log_interval)
  43. if self.train_config.eval_interval:
  44. self.pdx_config._update_eval_interval_by_epoch(
  45. self.train_config.eval_interval
  46. )
  47. if self.train_config.save_interval:
  48. self.pdx_config.update_save_interval(self.train_config.save_interval)
  49. if self.global_config["model"] == "LaTeX_OCR_rec":
  50. self.pdx_config.update_dataset(
  51. self.global_config.dataset_dir, "LaTeXOCRDataSet"
  52. )
  53. else:
  54. self.pdx_config.update_dataset(
  55. self.global_config.dataset_dir, "MSTextRecDataset"
  56. )
  57. label_dict_path = Path(self.global_config.dataset_dir).joinpath("dict.txt")
  58. if label_dict_path.exists():
  59. self.pdx_config.update_label_dict_path(label_dict_path)
  60. self.dump_label_dict(label_dict_path)
  61. if self.train_config.pretrain_weight_path:
  62. self.pdx_config.update_pretrained_weights(
  63. self.train_config.pretrain_weight_path
  64. )
  65. if self.global_config["model"] == "LaTeX_OCR_rec":
  66. if (
  67. self.train_config.batch_size_train is not None
  68. and self.train_config.batch_size_val
  69. ):
  70. self.pdx_config.update_batch_size_pair(
  71. self.train_config.batch_size_train, self.train_config.batch_size_val
  72. )
  73. else:
  74. if self.train_config.batch_size is not None:
  75. self.pdx_config.update_batch_size(self.train_config.batch_size)
  76. if self.train_config.learning_rate is not None:
  77. self.pdx_config.update_learning_rate(self.train_config.learning_rate)
  78. if self.train_config.epochs_iters is not None:
  79. self.pdx_config._update_epochs(self.train_config.epochs_iters)
  80. if (
  81. self.train_config.resume_path is not None
  82. and self.train_config.resume_path != ""
  83. ):
  84. self.pdx_config._update_checkpoints(self.train_config.resume_path)
  85. if self.global_config.output is not None:
  86. self.pdx_config._update_output_dir(self.global_config.output)
  87. def get_train_kwargs(self) -> dict:
  88. """get key-value arguments of model training function
  89. Returns:
  90. dict: the arguments of training function.
  91. """
  92. return {
  93. "device": self.get_device(),
  94. "dy2st": self.train_config.get("dy2st", False),
  95. }
  96. class TextRecTrainDeamon(BaseTrainDeamon):
  97. """TableRecTrainDeamon"""
  98. def __init__(self, *args, **kwargs):
  99. super().__init__(*args, **kwargs)
  100. def get_the_pdparams_suffix(self):
  101. """get the suffix of pdparams file"""
  102. return "pdparams"
  103. def get_the_pdema_suffix(self):
  104. """get the suffix of pdema file"""
  105. return "pdema"
  106. def get_the_pdopt_suffix(self):
  107. """get the suffix of pdopt file"""
  108. return "pdopt"
  109. def get_the_pdstates_suffix(self):
  110. """get the suffix of pdstates file"""
  111. return "states"
  112. def get_ith_ckp_prefix(self, epoch_id):
  113. """get the prefix of the epoch_id checkpoint file"""
  114. return f"iter_epoch_{epoch_id}"
  115. def get_best_ckp_prefix(self):
  116. """get the prefix of the best checkpoint file"""
  117. return "best_accuracy"
  118. def get_score(self, pdstates_path):
  119. """get the score by pdstates file"""
  120. if not Path(pdstates_path).exists():
  121. return 0
  122. if self.global_config["model"] == "LaTeX_OCR_rec":
  123. return paddle.load(pdstates_path)["best_model_dict"]["exp_rate"]
  124. else:
  125. return paddle.load(pdstates_path)["best_model_dict"]["acc"]
  126. def get_epoch_id_by_pdparams_prefix(self, pdparams_prefix):
  127. """get the epoch_id by pdparams file"""
  128. return int(pdparams_prefix.split("_")[-1])