trainer.py 5.3 KB

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