exportor.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 pathlib import Path
  16. from abc import ABC, abstractmethod
  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 import logging
  22. def build_exportor(config: AttrDict) -> "BaseExportor":
  23. """build model exportor
  24. Args:
  25. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  26. Returns:
  27. BaseExportor: the exportor, which is subclass of BaseExportor.
  28. """
  29. model_name = config.Global.model
  30. try:
  31. import feature_line_modules
  32. except ModuleNotFoundError:
  33. logging.info(
  34. "The PaddleX FeaTure Line plugin is not installed, but continuing execution."
  35. )
  36. return BaseExportor.get(model_name)(config)
  37. class BaseExportor(ABC, metaclass=AutoRegisterABCMetaClass):
  38. """Base Model Exportor"""
  39. __is_base = True
  40. def __init__(self, config):
  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.global_config = config.Global
  47. self.export_config = config.Export
  48. config_path = self.get_config_path(self.export_config.weight_path)
  49. if self.export_config.get("basic_config_path", None):
  50. config_path = self.export_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 get_config_path(self, weight_path):
  55. """
  56. get config path
  57. Args:
  58. weight_path (str): The path to the weight
  59. Returns:
  60. config_path (str): The path to the config
  61. """
  62. config_path = Path(weight_path).parent / "config.yaml"
  63. # `Path("https://xxx/xxx")` would cause error on Windows
  64. try:
  65. is_exists = config_path.exists()
  66. except Exception:
  67. is_exists = False
  68. if not is_exists:
  69. logging.warning(
  70. f"The config file(`{config_path}`) related to weight file(`{weight_path}`) is not exist, use default instead."
  71. )
  72. config_path = None
  73. return config_path
  74. def export(self) -> dict:
  75. """execute model exporting
  76. Returns:
  77. dict: the export metrics
  78. """
  79. self.update_config()
  80. export_result = self.pdx_model.export(**self.get_export_kwargs())
  81. assert (
  82. export_result.returncode == 0
  83. ), f"Encountered an unexpected error({export_result.returncode}) in \
  84. exporting!"
  85. return None
  86. def get_device(self, using_device_number: int = None) -> str:
  87. """get device setting from config
  88. Args:
  89. using_device_number (int, optional): specify device number to use.
  90. Defaults to None, means that base on config setting.
  91. Returns:
  92. str: device setting, such as: `gpu:0,1`, `npu:0,1`, `cpu`.
  93. """
  94. set_env_for_device(self.global_config.device)
  95. if using_device_number:
  96. return update_device_num(self.global_config.device, using_device_number)
  97. return self.global_config.device
  98. def update_config(self):
  99. """update export config"""
  100. pass
  101. def get_export_kwargs(self):
  102. """get key-value arguments of model export function"""
  103. export_with_pir = self.global_config.get("export_with_pir", False) or os.getenv(
  104. "FLAGS_json_format_model"
  105. ) in ["1", "True"]
  106. return {
  107. "weight_path": self.export_config.weight_path,
  108. "save_dir": self.global_config.output,
  109. "device": self.get_device(1),
  110. "export_with_pir": export_with_pir,
  111. }