basic_predictor.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. from abc import abstractmethod
  15. import inspect
  16. from ....utils.subclass_register import AutoRegisterABCMetaClass
  17. from ....utils.flags import (
  18. INFER_BENCHMARK,
  19. INFER_BENCHMARK_WARMUP,
  20. INFER_BENCHMARK_ITER,
  21. )
  22. from ....utils import logging
  23. from ...components.base import BaseComponent, ComponentsEngine
  24. from ...utils.pp_option import PaddlePredictorOption
  25. from ...utils.process_hook import generatorable_method
  26. from ...utils.benchmark import Benchmark
  27. from .base_predictor import BasePredictor
  28. class BasicPredictor(
  29. BasePredictor,
  30. metaclass=AutoRegisterABCMetaClass,
  31. ):
  32. __is_base = True
  33. def __init__(self, model_dir, config=None, device=None, pp_option=None):
  34. super().__init__(model_dir=model_dir, config=config)
  35. if not pp_option:
  36. pp_option = PaddlePredictorOption(model_name=self.model_name)
  37. if device:
  38. pp_option.device = device
  39. self.pp_option = pp_option
  40. self.components = {}
  41. self._build_components()
  42. self.engine = ComponentsEngine(self.components)
  43. logging.debug(f"{self.__class__.__name__}: {self.model_dir}")
  44. if INFER_BENCHMARK:
  45. self.benchmark = Benchmark(self.components)
  46. def __call__(self, input, **kwargs):
  47. if self.benchmark:
  48. for _ in range(INFER_BENCHMARK_WARMUP):
  49. list(super().__call__(None))
  50. self.benchmark.reset()
  51. if input is None:
  52. for _ in range(INFER_BENCHMARK_ITER):
  53. list(super().__call__(input))
  54. else:
  55. list(super().__call__(input))
  56. self.benchmark.collect()
  57. else:
  58. yield from super().__call__(input)
  59. def apply(self, input):
  60. """predict"""
  61. yield from self._generate_res(self.engine(input))
  62. @generatorable_method
  63. def _generate_res(self, batch_data):
  64. return [{"result": self._pack_res(data)} for data in batch_data]
  65. def _add_component(self, cmps):
  66. if not isinstance(cmps, list):
  67. cmps = [cmps]
  68. for cmp in cmps:
  69. if not isinstance(cmp, (list, tuple)):
  70. key = cmp.name
  71. else:
  72. assert len(cmp) == 2
  73. key = cmp[0]
  74. cmp = cmp[1]
  75. assert isinstance(key, str)
  76. assert isinstance(cmp, BaseComponent)
  77. assert (
  78. key not in self.components
  79. ), f"The key ({key}) has been used: {self.components}!"
  80. self.components[key] = cmp
  81. def set_predictor(self, batch_size=None, device=None, pp_option=None):
  82. if batch_size:
  83. self.components["ReadCmp"].batch_size = batch_size
  84. self.pp_option.batch_size = batch_size
  85. if device and device != self.pp_option.device:
  86. self.pp_option.device = device
  87. if pp_option and pp_option != self.pp_option:
  88. self.pp_option = pp_option
  89. def _has_setter(self, attr):
  90. prop = getattr(self.__class__, attr, None)
  91. return isinstance(prop, property) and prop.fset is not None
  92. @abstractmethod
  93. def _build_components(self):
  94. raise NotImplementedError
  95. @abstractmethod
  96. def _pack_res(self, data):
  97. raise NotImplementedError