basic_predictor.py 4.2 KB

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