trainer.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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.flags import DISABLE_CINN_MODEL_WL, FLAGS_json_format_model
  23. from ...utils.misc import AutoRegisterABCMetaClass
  24. from .build_model import build_model
  25. from .utils.cinn_setting import CINN_WHITELIST, enable_cinn_backend
  26. def build_trainer(config: AttrDict) -> "BaseTrainer":
  27. """build model trainer
  28. Args:
  29. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  30. Returns:
  31. BaseTrainer: the trainer, which is subclass of BaseTrainer.
  32. """
  33. model_name = config.Global.model
  34. try:
  35. pass
  36. except ModuleNotFoundError:
  37. pass
  38. return BaseTrainer.get(model_name)(config)
  39. class BaseTrainer(ABC, metaclass=AutoRegisterABCMetaClass):
  40. """Base Model Trainer"""
  41. __is_base = True
  42. def __init__(self, config: AttrDict):
  43. """Initialize the instance.
  44. Args:
  45. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  46. """
  47. super().__init__()
  48. self.config = config
  49. self.global_config = config.Global
  50. self.train_config = config.Train
  51. self.eval_config = config.Evaluate
  52. self.benchmark_config = config.get("Benchmark", None)
  53. config_path = self.train_config.get("basic_config_path", None)
  54. self.pdx_config, self.pdx_model = build_model(
  55. self.global_config.model, config_path=config_path
  56. )
  57. def train(self, *args, **kwargs):
  58. """execute model training"""
  59. os.makedirs(self.global_config.output, exist_ok=True)
  60. self.update_config()
  61. self.dump_config()
  62. train_args = self.get_train_kwargs()
  63. if self.benchmark_config is not None:
  64. train_args.update({"benchmark": self.benchmark_config})
  65. export_with_pir = (
  66. self.global_config.get("export_with_pir", False) or FLAGS_json_format_model
  67. )
  68. train_args.update(
  69. {
  70. "uniform_output_enabled": self.train_config.get(
  71. "uniform_output_enabled", True
  72. ),
  73. "export_with_pir": export_with_pir,
  74. "ips": self.train_config.get("dist_ips", None)
  75. }
  76. )
  77. # apply CINN when model is supported
  78. if (
  79. not DISABLE_CINN_MODEL_WL
  80. and self.train_config.get("dy2st", False)
  81. and self.global_config.model in CINN_WHITELIST
  82. ):
  83. enable_cinn_backend()
  84. train_result = self.pdx_model.train(**train_args)
  85. assert (
  86. train_result.returncode == 0
  87. ), f"Encountered an unexpected error({train_result.returncode}) in \
  88. training!"
  89. def dump_config(self, config_file_path: str = None):
  90. """dump the config
  91. Args:
  92. config_file_path (str, optional): the path to save dumped config. Defaults to None,
  93. means that save in `Global.output` as `config.yaml`.
  94. """
  95. if config_file_path is None:
  96. config_file_path = os.path.join(self.global_config.output, "config.yaml")
  97. self.pdx_config.dump(config_file_path)
  98. def get_device(self, using_device_number: int = None) -> str:
  99. """get device setting from config
  100. Args:
  101. using_device_number (int, optional): specify device number to use. Defaults to None,
  102. means that base on config setting.
  103. Returns:
  104. str: device setting, such as: `gpu:0,1`, `npu:0,1` `cpu`.
  105. """
  106. check_supported_device(self.global_config.device, self.global_config.model)
  107. set_env_for_device(self.global_config.device)
  108. device_setting = (
  109. update_device_num(self.global_config.device, using_device_number)
  110. if using_device_number
  111. else self.global_config.device
  112. )
  113. # replace "dcu" with "gpu"
  114. device_setting = device_setting.replace("dcu", "gpu")
  115. return device_setting
  116. @abstractmethod
  117. def update_config(self):
  118. """update training config"""
  119. raise NotImplementedError
  120. @abstractmethod
  121. def get_train_kwargs(self):
  122. """get key-value arguments of model training function"""
  123. raise NotImplementedError