trainer.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. from pathlib import Path
  16. import paddle
  17. from ..base import BaseTrainer, BaseTrainDeamon
  18. from ...utils.config import AttrDict
  19. from .model_list import MODELS
  20. class TextDetTrainer(BaseTrainer):
  21. """Text Detection Model Trainer"""
  22. entities = MODELS
  23. def build_deamon(self, config: AttrDict) -> "TextDetTrainDeamon":
  24. """build deamon thread for saving training outputs timely
  25. Args:
  26. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  27. Returns:
  28. TextDetTrainDeamon: the training deamon thread object for saving training outputs timely.
  29. """
  30. return TextDetTrainDeamon(config)
  31. def update_config(self):
  32. """update training config"""
  33. if self.train_config.log_interval:
  34. self.pdx_config.update_log_interval(self.train_config.log_interval)
  35. if self.train_config.eval_interval:
  36. self.pdx_config._update_eval_interval_by_epoch(
  37. self.train_config.eval_interval
  38. )
  39. if self.train_config.save_interval:
  40. self.pdx_config.update_save_interval(self.train_config.save_interval)
  41. self.pdx_config.update_dataset(self.global_config.dataset_dir, "TextDetDataset")
  42. if self.train_config.pretrain_weight_path:
  43. self.pdx_config.update_pretrained_weights(
  44. self.train_config.pretrain_weight_path
  45. )
  46. if self.train_config.batch_size is not None:
  47. self.pdx_config.update_batch_size(self.train_config.batch_size)
  48. if self.train_config.learning_rate is not None:
  49. self.pdx_config.update_learning_rate(self.train_config.learning_rate)
  50. if self.train_config.epochs_iters is not None:
  51. self.pdx_config._update_epochs(self.train_config.epochs_iters)
  52. if (
  53. self.train_config.resume_path is not None
  54. and self.train_config.resume_path != ""
  55. ):
  56. self.pdx_config._update_checkpoints(self.train_config.resume_path)
  57. if self.global_config.output is not None:
  58. self.pdx_config._update_output_dir(self.global_config.output)
  59. def get_train_kwargs(self) -> dict:
  60. """get key-value arguments of model training function
  61. Returns:
  62. dict: the arguments of training function.
  63. """
  64. return {"device": self.get_device(), "dy2st": self.train_config.get("dy2st", False)}
  65. class TextDetTrainDeamon(BaseTrainDeamon):
  66. """TableRecTrainDeamon"""
  67. def __init__(self, *args, **kwargs):
  68. super().__init__(*args, **kwargs)
  69. def get_the_pdparams_suffix(self):
  70. """get the suffix of pdparams file"""
  71. return "pdparams"
  72. def get_the_pdema_suffix(self):
  73. """get the suffix of pdema file"""
  74. return "pdema"
  75. def get_the_pdopt_suffix(self):
  76. """get the suffix of pdopt file"""
  77. return "pdopt"
  78. def get_the_pdstates_suffix(self):
  79. """get the suffix of pdstates file"""
  80. return "states"
  81. def get_ith_ckp_prefix(self, epoch_id):
  82. """get the prefix of the epoch_id checkpoint file"""
  83. return f"iter_epoch_{epoch_id}"
  84. def get_best_ckp_prefix(self):
  85. """get the prefix of the best checkpoint file"""
  86. return "best_accuracy"
  87. def get_score(self, pdstates_path):
  88. """get the score by pdstates file"""
  89. if not Path(pdstates_path).exists():
  90. return 0
  91. return paddle.load(pdstates_path)["best_model_dict"]["hmean"]
  92. def get_epoch_id_by_pdparams_prefix(self, pdparams_prefix):
  93. """get the epoch_id by pdparams file"""
  94. return int(pdparams_prefix.split(".")[0].split("_")[-1])