basic_predictor.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. if INFER_BENCHMARK_WARMUP > 0:
  49. output = super().__call__(input)
  50. for _ in range(INFER_BENCHMARK_WARMUP):
  51. next(output)
  52. self.benchmark.reset()
  53. output = list(super().__call__(input))
  54. self.benchmark.collect(len(output))
  55. else:
  56. yield from super().__call__(input)
  57. def apply(self, input):
  58. """predict"""
  59. yield from self._generate_res(self.engine(input))
  60. @generatorable_method
  61. def _generate_res(self, batch_data):
  62. return [{"result": self._pack_res(data)} for data in batch_data]
  63. def _add_component(self, cmps):
  64. if not isinstance(cmps, list):
  65. cmps = [cmps]
  66. for cmp in cmps:
  67. if not isinstance(cmp, (list, tuple)):
  68. key = cmp.name
  69. else:
  70. assert len(cmp) == 2
  71. key = cmp[0]
  72. cmp = cmp[1]
  73. assert isinstance(key, str)
  74. assert isinstance(cmp, BaseComponent)
  75. assert (
  76. key not in self.components
  77. ), f"The key ({key}) has been used: {self.components}!"
  78. self.components[key] = cmp
  79. def set_predictor(self, batch_size=None, device=None, pp_option=None):
  80. if batch_size:
  81. self.components["ReadCmp"].batch_size = batch_size
  82. self.pp_option.batch_size = batch_size
  83. if device and device != self.pp_option.device:
  84. self.pp_option.device = device
  85. if pp_option and pp_option != self.pp_option:
  86. self.pp_option = pp_option
  87. def _has_setter(self, attr):
  88. prop = getattr(self.__class__, attr, None)
  89. return isinstance(prop, property) and prop.fset is not None
  90. @abstractmethod
  91. def _build_components(self):
  92. raise NotImplementedError
  93. @abstractmethod
  94. def _pack_res(self, data):
  95. raise NotImplementedError