base.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. import GPUtil
  19. from ...utils.subclass_register import AutoRegisterABCMetaClass
  20. from ..utils.device import constr_device
  21. from ...utils import logging
  22. from ..components.base import BaseComponent, ComponentsEngine
  23. from ..utils.pp_option import PaddlePredictorOption
  24. from ..utils.process_hook import generatorable_method
  25. def _get_default_device():
  26. avail_gpus = GPUtil.getAvailable()
  27. if not avail_gpus:
  28. return "cpu"
  29. else:
  30. return constr_device("gpu", [avail_gpus[0]])
  31. class BasePredictor(BaseComponent):
  32. KEEP_INPUT = False
  33. YIELD_BATCH = False
  34. INPUT_KEYS = "x"
  35. DEAULT_INPUTS = {"x": "x"}
  36. OUTPUT_KEYS = "result"
  37. DEAULT_OUTPUTS = {"result": "result"}
  38. MODEL_FILE_PREFIX = "inference"
  39. def __init__(self, model_dir, config=None, device=None, **kwargs):
  40. super().__init__()
  41. self.model_dir = Path(model_dir)
  42. self.config = config if config else self.load_config(self.model_dir)
  43. self.device = device if device else _get_default_device()
  44. self.kwargs = self._check_args(kwargs)
  45. # alias predict() to the __call__()
  46. self.predict = self.__call__
  47. def __call__(self, *args, **kwargs):
  48. for res in super().__call__(*args, **kwargs):
  49. yield res["result"]
  50. @property
  51. def config_path(self):
  52. return self.get_config_path(self.model_dir)
  53. @property
  54. def model_name(self) -> str:
  55. return self.config["Global"]["model_name"]
  56. @abstractmethod
  57. def apply(self, x):
  58. raise NotImplementedError
  59. @classmethod
  60. def get_config_path(cls, model_dir):
  61. return model_dir / f"{cls.MODEL_FILE_PREFIX}.yml"
  62. @classmethod
  63. def load_config(cls, model_dir):
  64. config_path = cls.get_config_path(model_dir)
  65. with codecs.open(config_path, "r", "utf-8") as file:
  66. dic = yaml.load(file, Loader=yaml.FullLoader)
  67. return dic
  68. def _check_args(self, kwargs):
  69. return kwargs
  70. class BasicPredictor(BasePredictor, metaclass=AutoRegisterABCMetaClass):
  71. __is_base = True
  72. def __init__(self, model_dir, config=None, device=None, pp_option=None, **kwargs):
  73. super().__init__(model_dir=model_dir, config=config, device=device, **kwargs)
  74. self.pp_option = PaddlePredictorOption() if pp_option is None else pp_option
  75. self.pp_option.set_device(self.device)
  76. self.components = self._build_components()
  77. self.engine = ComponentsEngine(self.components)
  78. logging.debug(
  79. f"-------------------- {self.__class__.__name__} --------------------\nModel: {self.model_dir}\nEnv: {self.pp_option}"
  80. )
  81. def apply(self, x):
  82. """predict"""
  83. yield from self._generate_res(self.engine(x))
  84. @generatorable_method
  85. def _generate_res(self, batch_data):
  86. return [{"result": self._pack_res(data)} for data in batch_data]
  87. @abstractmethod
  88. def _build_components(self):
  89. raise NotImplementedError
  90. @abstractmethod
  91. def _pack_res(self, data):
  92. raise NotImplementedError