trainer.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 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(
  30. "label_dict.txt")
  31. shutil.copyfile(src_label_dict_path, dst_label_dict_path)
  32. def build_deamon(self, config: AttrDict) -> "TextRecTrainDeamon":
  33. """build deamon thread for saving training outputs timely
  34. Args:
  35. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  36. Returns:
  37. TextRecTrainDeamon: the training deamon thread object for saving training outputs timely.
  38. """
  39. return TextRecTrainDeamon(config)
  40. def update_config(self):
  41. """update training config
  42. """
  43. if self.train_config.log_interval:
  44. self.pdx_config.update_log_interval(self.train_config.log_interval)
  45. if self.train_config.eval_interval:
  46. self.pdx_config._update_eval_interval_by_epoch(
  47. self.train_config.eval_interval)
  48. if self.train_config.save_interval:
  49. self.pdx_config.update_save_interval(
  50. self.train_config.save_interval)
  51. self.pdx_config.update_dataset(self.global_config.dataset_dir,
  52. "MSTextRecDataset")
  53. label_dict_path = Path(self.global_config.dataset_dir).joinpath(
  54. "dict.txt")
  55. if label_dict_path.exists():
  56. self.pdx_config.update_label_dict_path(label_dict_path)
  57. self.dump_label_dict(label_dict_path)
  58. if self.train_config.pretrain_weight_path:
  59. self.pdx_config.update_pretrained_weights(
  60. self.train_config.pretrain_weight_path)
  61. if self.train_config.batch_size is not None:
  62. self.pdx_config.update_batch_size(self.train_config.batch_size)
  63. if self.train_config.learning_rate is not None:
  64. self.pdx_config.update_learning_rate(
  65. self.train_config.learning_rate)
  66. if self.train_config.epochs_iters is not None:
  67. self.pdx_config._update_epochs(self.train_config.epochs_iters)
  68. if self.train_config.resume_path is not None and self.train_config.resume_path != "":
  69. self.pdx_config._update_checkpoints(self.train_config.resume_path)
  70. if self.global_config.output is not None:
  71. self.pdx_config._update_output_dir(self.global_config.output)
  72. def get_train_kwargs(self) -> dict:
  73. """get key-value arguments of model training function
  74. Returns:
  75. dict: the arguments of training function.
  76. """
  77. return {"device": self.get_device()}
  78. class TextRecTrainDeamon(BaseTrainDeamon):
  79. """ TableRecTrainDeamon """
  80. def __init__(self, *args, **kwargs):
  81. super().__init__(*args, **kwargs)
  82. def get_the_pdparams_suffix(self):
  83. """ get the suffix of pdparams file """
  84. return "pdparams"
  85. def get_the_pdema_suffix(self):
  86. """ get the suffix of pdema file """
  87. return "pdema"
  88. def get_the_pdopt_suffix(self):
  89. """ get the suffix of pdopt file """
  90. return "pdopt"
  91. def get_the_pdstates_suffix(self):
  92. """ get the suffix of pdstates file """
  93. return "states"
  94. def get_ith_ckp_prefix(self, epoch_id):
  95. """ get the prefix of the epoch_id checkpoint file """
  96. return f"iter_epoch_{epoch_id}"
  97. def get_best_ckp_prefix(self):
  98. """ get the prefix of the best checkpoint file """
  99. return "best_accuracy"
  100. def get_score(self, pdstates_path):
  101. """ get the score by pdstates file """
  102. if not Path(pdstates_path).exists():
  103. return 0
  104. return paddle.load(pdstates_path)['best_model_dict']['acc']
  105. def get_epoch_id_by_pdparams_prefix(self, pdparams_prefix):
  106. """ get the epoch_id by pdparams file """
  107. return int(pdparams_prefix.split("_")[-1])