base_predictor.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 yaml
  15. import codecs
  16. from pathlib import Path
  17. from abc import abstractmethod
  18. from ....utils.subclass_register import AutoRegisterABCMetaClass
  19. from ....utils.func_register import FuncRegister
  20. from ....utils import logging
  21. from ...utils.device import constr_device
  22. from ...components.base import BaseComponent, ComponentsEngine
  23. from ...utils.pp_option import PaddlePredictorOption
  24. from ...utils.process_hook import generatorable_method
  25. from ..utils.predict_set import DeviceSetMixin, PPOptionSetMixin
  26. class BasePredictor(BaseComponent):
  27. KEEP_INPUT = False
  28. YIELD_BATCH = False
  29. INPUT_KEYS = "x"
  30. DEAULT_INPUTS = {"x": "x"}
  31. OUTPUT_KEYS = "result"
  32. DEAULT_OUTPUTS = {"result": "result"}
  33. MODEL_FILE_PREFIX = "inference"
  34. def __init__(self, model_dir, config=None):
  35. super().__init__()
  36. self.model_dir = Path(model_dir)
  37. self.config = config if config else self.load_config(self.model_dir)
  38. # alias predict() to the __call__()
  39. self.predict = self.__call__
  40. def __call__(self, input, **kwargs):
  41. self.set_predict(**kwargs)
  42. for res in super().__call__(input):
  43. yield res["result"]
  44. @property
  45. def config_path(self):
  46. return self.get_config_path(self.model_dir)
  47. @property
  48. def model_name(self) -> str:
  49. return self.config["Global"]["model_name"]
  50. @abstractmethod
  51. def apply(self, x):
  52. raise NotImplementedError
  53. @abstractmethod
  54. def set_predict(self):
  55. raise NotImplementedError
  56. @classmethod
  57. def get_config_path(cls, model_dir):
  58. return model_dir / f"{cls.MODEL_FILE_PREFIX}.yml"
  59. @classmethod
  60. def load_config(cls, model_dir):
  61. config_path = cls.get_config_path(model_dir)
  62. with codecs.open(config_path, "r", "utf-8") as file:
  63. dic = yaml.load(file, Loader=yaml.FullLoader)
  64. return dic
  65. class BasicPredictor(
  66. BasePredictor, DeviceSetMixin, PPOptionSetMixin, metaclass=AutoRegisterABCMetaClass
  67. ):
  68. __is_base = True
  69. def __init__(self, model_dir, config=None, device=None, pp_option=None):
  70. super().__init__(model_dir=model_dir, config=config)
  71. self._pred_set_func_map = {}
  72. self._pred_set_register = FuncRegister(self._pred_set_func_map)
  73. self._pred_set_register("device")(self.set_device)
  74. self._pred_set_register("pp_option")(self.set_pp_option)
  75. self.pp_option = pp_option if pp_option else PaddlePredictorOption()
  76. self.pp_option.set_device(device)
  77. self.components = {}
  78. self._build_components()
  79. self.engine = ComponentsEngine(self.components)
  80. logging.debug(
  81. f"-------------------- {self.__class__.__name__} --------------------\nModel: {self.model_dir}"
  82. )
  83. def apply(self, x):
  84. """predict"""
  85. yield from self._generate_res(self.engine(x))
  86. @generatorable_method
  87. def _generate_res(self, batch_data):
  88. return [{"result": self._pack_res(data)} for data in batch_data]
  89. def _add_component(self, cmps):
  90. if not isinstance(cmps, list):
  91. cmps = [cmps]
  92. for cmp in cmps:
  93. if not isinstance(cmp, (list, tuple)):
  94. key = cmp.__class__.__name__
  95. else:
  96. assert len(cmp) == 2
  97. key = cmp[0]
  98. cmp = cmp[1]
  99. assert isinstance(key, str)
  100. assert isinstance(cmp, BaseComponent)
  101. assert (
  102. key not in self.components
  103. ), f"The key ({key}) has been used: {self.components}!"
  104. self.components[key] = cmp
  105. def set_predict(self, **kwargs):
  106. for k in kwargs:
  107. self._pred_set_func_map[k](kwargs[k])
  108. @abstractmethod
  109. def _build_components(self):
  110. raise NotImplementedError
  111. @abstractmethod
  112. def _pack_res(self, data):
  113. raise NotImplementedError