trainer.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 json
  15. import shutil
  16. import lazy_paddle as paddle
  17. from pathlib import Path
  18. from ..base import BaseTrainer, BaseTrainDeamon
  19. from .model_list import MODELS
  20. from ...utils.config import AttrDict
  21. class MLClsTrainer(BaseTrainer):
  22. """Image Classification 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) -> "ClsTrainDeamon":
  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. ClsTrainDeamon: the training deamon thread object for saving training outputs timely.
  37. """
  38. return ClsTrainDeamon(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(self.train_config.eval_interval)
  45. if self.train_config.save_interval:
  46. self.pdx_config.update_save_interval(self.train_config.save_interval)
  47. self.pdx_config.update_dataset(self.global_config.dataset_dir, "MLClsDataset")
  48. if self.train_config.num_classes is not None:
  49. self.pdx_config.update_num_classes(self.train_config.num_classes)
  50. if (
  51. self.train_config.pretrain_weight_path
  52. and self.train_config.pretrain_weight_path != ""
  53. ):
  54. self.pdx_config.update_pretrained_weights(
  55. self.train_config.pretrain_weight_path
  56. )
  57. label_dict_path = Path(self.global_config.dataset_dir).joinpath("label.txt")
  58. if label_dict_path.exists():
  59. self.dump_label_dict(label_dict_path)
  60. if self.train_config.batch_size is not None:
  61. self.pdx_config.update_batch_size(self.train_config.batch_size)
  62. if self.train_config.learning_rate is not None:
  63. self.pdx_config.update_learning_rate(self.train_config.learning_rate)
  64. if self.train_config.epochs_iters is not None:
  65. self.pdx_config._update_epochs(self.train_config.epochs_iters)
  66. if self.train_config.warmup_steps is not None:
  67. self.pdx_config.update_warmup_epochs(self.train_config.warmup_steps)
  68. if self.global_config.output is not None:
  69. self.pdx_config._update_output_dir(self.global_config.output)
  70. def get_train_kwargs(self) -> dict:
  71. """get key-value arguments of model training function
  72. Returns:
  73. dict: the arguments of training function.
  74. """
  75. train_args = {"device": self.get_device()}
  76. if (
  77. self.train_config.resume_path is not None
  78. and self.train_config.resume_path != ""
  79. ):
  80. train_args["resume_path"] = self.train_config.resume_path
  81. train_args["dy2st"] = self.train_config.get("dy2st", False)
  82. return train_args
  83. class ClsTrainDeamon(BaseTrainDeamon):
  84. """ClsTrainResultDemon"""
  85. def __init__(self, *args, **kwargs):
  86. super().__init__(*args, **kwargs)
  87. def get_the_pdparams_suffix(self):
  88. """get the suffix of pdparams file"""
  89. return "pdparams"
  90. def get_the_pdema_suffix(self):
  91. """get the suffix of pdema file"""
  92. return "pdema"
  93. def get_the_pdopt_suffix(self):
  94. """get the suffix of pdopt file"""
  95. return "pdopt"
  96. def get_the_pdstates_suffix(self):
  97. """get the suffix of pdstates file"""
  98. return "pdstates"
  99. def get_ith_ckp_prefix(self, epoch_id):
  100. """get the prefix of the epoch_id checkpoint file"""
  101. return f"epoch_{epoch_id}"
  102. def get_best_ckp_prefix(self):
  103. """get the prefix of the best checkpoint file"""
  104. return "best_model"
  105. def get_score(self, pdstates_path):
  106. """get the score by pdstates file"""
  107. if not Path(pdstates_path).exists():
  108. return 0
  109. return paddle.load(pdstates_path)["metric"]
  110. def get_epoch_id_by_pdparams_prefix(self, pdparams_prefix):
  111. """get the epoch_id by pdparams file"""
  112. return int(pdparams_prefix.split("_")[-1])
  113. def update_label_dict(self, train_output):
  114. """update label dict"""
  115. dict_path = train_output.joinpath("label_dict.txt")
  116. if not dict_path.exists():
  117. return ""
  118. return dict_path