basic_predictor.py 3.8 KB

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