trainer.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 abc import ABC, abstractmethod
  16. from pathlib import Path
  17. from ..build_model import build_model
  18. from ....utils.device import get_device
  19. from ....utils.misc import AutoRegisterABCMetaClass
  20. from ....utils.config import AttrDict
  21. def build_trainer(config: AttrDict) -> "BaseTrainer":
  22. """build model trainer
  23. Args:
  24. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  25. Returns:
  26. BaseTrainer: the trainer, which is subclass of BaseTrainer.
  27. """
  28. model_name = config.Global.model
  29. return BaseTrainer.get(model_name)(config)
  30. class BaseTrainer(ABC, metaclass=AutoRegisterABCMetaClass):
  31. """ Base Model Trainer """
  32. __is_base = True
  33. def __init__(self, config: AttrDict):
  34. """Initialize the instance.
  35. Args:
  36. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  37. """
  38. super().__init__()
  39. self.config = config
  40. self.global_config = config.Global
  41. self.train_config = config.Train
  42. self.benchmark_config = config.get('Benchmark', None)
  43. self.deamon = self.build_deamon(self.config)
  44. self.pdx_config, self.pdx_model = build_model(self.global_config.model)
  45. def train(self, *args, **kwargs):
  46. """execute model training
  47. """
  48. os.makedirs(self.global_config.output, exist_ok=True)
  49. self.update_config()
  50. self.dump_config()
  51. train_args = self.get_train_kwargs()
  52. if self.benchmark_config is not None:
  53. train_args.update({'benchmark': self.benchmark_config})
  54. train_result = self.pdx_model.train(**train_args)
  55. assert train_result.returncode == 0, f"Encountered an unexpected error({train_result.returncode}) in \
  56. training!"
  57. self.deamon.stop()
  58. def dump_config(self, config_file_path: str=None):
  59. """dump the config
  60. Args:
  61. config_file_path (str, optional): the path to save dumped config. Defaults to None,
  62. means that save in `Global.output` as `config.yaml`.
  63. """
  64. if config_file_path is None:
  65. config_file_path = os.path.join(self.global_config.output,
  66. "config.yaml")
  67. self.pdx_config.dump(config_file_path)
  68. def get_device(self, using_device_number: int=None) -> str:
  69. """get device setting from config
  70. Args:
  71. using_device_number (int, optional): specify device number to use. Defaults to None,
  72. means that base on config setting.
  73. Returns:
  74. str: device setting, such as: `gpu:0,1`, `npu:0,1` `cpu`.
  75. """
  76. return get_device(
  77. self.global_config.device, using_device_number=using_device_number)
  78. @abstractmethod
  79. def build_deamon(self):
  80. """build deamon thread for saving training outputs timely
  81. """
  82. raise NotImplementedError
  83. @abstractmethod
  84. def update_config(self):
  85. """update training config
  86. """
  87. raise NotImplementedError
  88. @abstractmethod
  89. def get_train_kwargs(self):
  90. """get key-value arguments of model training function
  91. """
  92. raise NotImplementedError