trainer.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 ...utils.config import AttrDict
  17. from ...utils.device import (
  18. check_supported_device,
  19. set_env_for_device,
  20. update_device_num,
  21. )
  22. from ...utils.misc import AutoRegisterABCMetaClass
  23. from .build_model import build_model
  24. def build_trainer(config: AttrDict) -> "BaseTrainer":
  25. """build model trainer
  26. Args:
  27. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  28. Returns:
  29. BaseTrainer: the trainer, which is subclass of BaseTrainer.
  30. """
  31. model_name = config.Global.model
  32. try:
  33. pass
  34. except ModuleNotFoundError:
  35. pass
  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.eval_config = config.Evaluate
  50. self.benchmark_config = config.get("Benchmark", None)
  51. config_path = self.train_config.get("basic_config_path", None)
  52. self.pdx_config, self.pdx_model = build_model(
  53. self.global_config.model, config_path=config_path
  54. )
  55. def train(self, *args, **kwargs):
  56. """execute model training"""
  57. os.makedirs(self.global_config.output, exist_ok=True)
  58. self.update_config()
  59. self.dump_config()
  60. train_args = self.get_train_kwargs()
  61. if self.benchmark_config is not None:
  62. train_args.update({"benchmark": self.benchmark_config})
  63. export_with_pir = self.global_config.get("export_with_pir", False) or os.getenv(
  64. "FLAGS_json_format_model"
  65. ) in ["1", "True"]
  66. train_args.update(
  67. {
  68. "uniform_output_enabled": self.train_config.get(
  69. "uniform_output_enabled", True
  70. ),
  71. "export_with_pir": export_with_pir,
  72. }
  73. )
  74. train_result = self.pdx_model.train(**train_args)
  75. assert (
  76. train_result.returncode == 0
  77. ), f"Encountered an unexpected error({train_result.returncode}) in \
  78. training!"
  79. def dump_config(self, config_file_path: str = None):
  80. """dump the config
  81. Args:
  82. config_file_path (str, optional): the path to save dumped config. Defaults to None,
  83. means that save in `Global.output` as `config.yaml`.
  84. """
  85. if config_file_path is None:
  86. config_file_path = os.path.join(self.global_config.output, "config.yaml")
  87. self.pdx_config.dump(config_file_path)
  88. def get_device(self, using_device_number: int = None) -> str:
  89. """get device setting from config
  90. Args:
  91. using_device_number (int, optional): specify device number to use. Defaults to None,
  92. means that base on config setting.
  93. Returns:
  94. str: device setting, such as: `gpu:0,1`, `npu:0,1` `cpu`.
  95. """
  96. check_supported_device(self.global_config.device, self.global_config.model)
  97. set_env_for_device(self.global_config.device)
  98. device_setting = (
  99. update_device_num(self.global_config.device, using_device_number)
  100. if using_device_number
  101. else self.global_config.device
  102. )
  103. # replace "dcu" with "gpu"
  104. device_setting = device_setting.replace("dcu", "gpu")
  105. return device_setting
  106. @abstractmethod
  107. def update_config(self):
  108. """update training config"""
  109. raise NotImplementedError
  110. @abstractmethod
  111. def get_train_kwargs(self):
  112. """get key-value arguments of model training function"""
  113. raise NotImplementedError