trainer.py 4.1 KB

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