base.py 3.5 KB

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