trainer.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. Author: PaddlePaddle Authors
  10. """
  11. import os
  12. from abc import ABC, abstractmethod
  13. from pathlib import Path
  14. from ..build_model import build_model
  15. from ....utils.device import get_device
  16. from ....utils.misc import AutoRegisterABCMetaClass
  17. from ....utils.config import AttrDict
  18. def build_trainer(config: AttrDict) -> "BaseTrainer":
  19. """build model trainer
  20. Args:
  21. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  22. Returns:
  23. BaseTrainer: the trainer, which is subclass of BaseTrainer.
  24. """
  25. model_name = config.Global.model
  26. return BaseTrainer.get(model_name)(config)
  27. class BaseTrainer(ABC, metaclass=AutoRegisterABCMetaClass):
  28. """ Base Model Trainer """
  29. __is_base = True
  30. def __init__(self, config: AttrDict):
  31. """Initialize the instance.
  32. Args:
  33. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  34. """
  35. super().__init__()
  36. self.global_config = config.Global
  37. self.train_config = config.Train
  38. self.deamon = self.build_deamon(self.global_config)
  39. self.pdx_config, self.pdx_model = build_model(self.global_config.model)
  40. def train(self, *args, **kwargs):
  41. """execute model training
  42. """
  43. os.makedirs(self.global_config.output, exist_ok=True)
  44. self.update_config()
  45. self.dump_config()
  46. train_result = self.pdx_model.train(**self.get_train_kwargs())
  47. assert train_result.returncode == 0, f"Encountered an unexpected error({train_result.returncode}) in \
  48. training!"
  49. self.deamon.stop()
  50. def dump_config(self, config_file_path: str=None):
  51. """dump the config
  52. Args:
  53. config_file_path (str, optional): the path to save dumped config. Defaults to None,
  54. means that save in `Global.output` as `config.yaml`.
  55. """
  56. if config_file_path is None:
  57. config_file_path = os.path.join(self.global_config.output,
  58. "config.yaml")
  59. self.pdx_config.dump(config_file_path)
  60. def get_device(self, using_device_number: int=None) -> str:
  61. """get device setting from config
  62. Args:
  63. using_device_number (int, optional): specify device number to use. Defaults to None,
  64. means that base on config setting.
  65. Returns:
  66. str: device setting, such as: `gpu:0,1`, `npu:0,1` `cpu`.
  67. """
  68. return get_device(
  69. self.global_config.device, using_device_number=using_device_number)
  70. @abstractmethod
  71. def build_deamon(self):
  72. """build deamon thread for saving training outputs timely
  73. """
  74. raise NotImplementedError
  75. @abstractmethod
  76. def update_config(self):
  77. """update training config
  78. """
  79. raise NotImplementedError
  80. @abstractmethod
  81. def get_train_kwargs(self):
  82. """get key-value arguments of model training function
  83. """
  84. raise NotImplementedError