basic_predictor.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. )
  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. from ...utils.benchmark import Benchmark
  26. from .base_predictor import BasePredictor
  27. class BasicPredictor(
  28. BasePredictor,
  29. metaclass=AutoRegisterABCMetaClass,
  30. ):
  31. __is_base = True
  32. def __init__(self, model_dir, config=None, device=None, pp_option=None):
  33. super().__init__(model_dir=model_dir, config=config)
  34. if not pp_option:
  35. pp_option = PaddlePredictorOption(model_name=self.model_name)
  36. if device:
  37. pp_option.device = device
  38. trt_dynamic_shapes = (
  39. self.config.get("Hpi", {})
  40. .get("backend_configs", {})
  41. .get("paddle_infer", {})
  42. .get("trt_dynamic_shapes", None)
  43. )
  44. if trt_dynamic_shapes:
  45. pp_option.trt_dynamic_shapes = trt_dynamic_shapes
  46. self.pp_option = pp_option
  47. self.components = {}
  48. self._build_components()
  49. self.engine = ComponentsEngine(self.components)
  50. logging.debug(f"{self.__class__.__name__}: {self.model_dir}")
  51. if INFER_BENCHMARK:
  52. self.benchmark = Benchmark(self.components)
  53. def __call__(self, input, **kwargs):
  54. self.set_predictor(**kwargs)
  55. if self.benchmark:
  56. self.benchmark.start()
  57. if INFER_BENCHMARK_WARMUP > 0:
  58. output = super().__call__(input)
  59. warmup_num = 0
  60. for _ in range(INFER_BENCHMARK_WARMUP):
  61. try:
  62. next(output)
  63. warmup_num += 1
  64. except StopIteration:
  65. logging.warning(
  66. f"There are only {warmup_num} batches in input data, but `INFER_BENCHMARK_WARMUP` has been set to {INFER_BENCHMARK_WARMUP}."
  67. )
  68. break
  69. self.benchmark.warmup_stop(warmup_num)
  70. output = list(super().__call__(input))
  71. self.benchmark.collect(len(output))
  72. else:
  73. yield from super().__call__(input)
  74. def apply(self, input):
  75. """predict"""
  76. yield from self._generate_res(self.engine(input))
  77. @generatorable_method
  78. def _generate_res(self, batch_data):
  79. return [{"result": self._pack_res(data)} for data in batch_data]
  80. def _add_component(self, cmps):
  81. if not isinstance(cmps, list):
  82. cmps = [cmps]
  83. for cmp in cmps:
  84. if not isinstance(cmp, (list, tuple)):
  85. key = cmp.name
  86. else:
  87. assert len(cmp) == 2
  88. key = cmp[0]
  89. cmp = cmp[1]
  90. assert isinstance(key, str)
  91. assert isinstance(cmp, BaseComponent)
  92. assert (
  93. key not in self.components
  94. ), f"The key ({key}) has been used: {self.components}!"
  95. self.components[key] = cmp
  96. def set_predictor(self, batch_size=None, device=None, pp_option=None):
  97. if batch_size:
  98. self.components["ReadCmp"].batch_size = batch_size
  99. self.pp_option.batch_size = batch_size
  100. if device and device != self.pp_option.device:
  101. self.pp_option.device = device
  102. if pp_option and pp_option != self.pp_option:
  103. self.pp_option = pp_option
  104. def _has_setter(self, attr):
  105. prop = getattr(self.__class__, attr, None)
  106. return isinstance(prop, property) and prop.fset is not None
  107. @abstractmethod
  108. def _build_components(self):
  109. raise NotImplementedError
  110. @abstractmethod
  111. def _pack_res(self, data):
  112. raise NotImplementedError