base.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 ABC, abstractmethod
  15. from typing import Any, Dict, Optional, Union
  16. from ...utils import logging
  17. from ...utils.subclass_register import AutoRegisterABCMetaClass
  18. from ..models import BasePredictor
  19. from ..utils.hpi import HPIConfig
  20. from ..utils.pp_option import PaddlePredictorOption
  21. class BasePipeline(ABC, metaclass=AutoRegisterABCMetaClass):
  22. """Base class for all pipelines.
  23. This class serves as a foundation for creating various pipelines.
  24. It includes common attributes and methods that are shared among all
  25. pipeline implementations.
  26. """
  27. __is_base = True
  28. def __init__(
  29. self,
  30. device: str = None,
  31. pp_option: PaddlePredictorOption = None,
  32. use_hpip: bool = False,
  33. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  34. *args,
  35. **kwargs,
  36. ) -> None:
  37. """
  38. Initializes the class with specified parameters.
  39. Args:
  40. device (str, optional): The device to use for prediction. Defaults to None.
  41. pp_option (PaddlePredictorOption, optional): The options for PaddlePredictor. Defaults to None.
  42. use_hpip (bool, optional): Whether to use the high-performance
  43. inference plugin (HPIP) by default. Defaults to False.
  44. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  45. The default high-performance inference configuration dictionary.
  46. Defaults to None.
  47. """
  48. super().__init__()
  49. self.device = device
  50. self.pp_option = pp_option
  51. self.use_hpip = use_hpip
  52. self.hpi_config = hpi_config
  53. @abstractmethod
  54. def predict(self, input, **kwargs):
  55. """
  56. Declaration of an abstract method. Subclasses are expected to
  57. provide a concrete implementation of predict.
  58. Args:
  59. input: The input data to predict.
  60. **kwargs: Additional keyword arguments.
  61. """
  62. raise NotImplementedError("The method `predict` has not been implemented yet.")
  63. def create_model(self, config: Dict, **kwargs) -> BasePredictor:
  64. """
  65. Create a model instance based on the given configuration.
  66. Args:
  67. config (Dict): A dictionary containing configuration settings.
  68. **kwargs: The model arguments that needed to be pass.
  69. Returns:
  70. BasePredictor: An instance of the model.
  71. """
  72. if "model_config_error" in config:
  73. raise ValueError(config["model_config_error"])
  74. model_dir = config.get("model_dir", None)
  75. # Should we log if the actual parameter to use is different from the default?
  76. use_hpip = config.get("use_hpip", self.use_hpip)
  77. hpi_config = config.get("hpi_config", None)
  78. if self.hpi_config is not None:
  79. hpi_config = hpi_config or {}
  80. hpi_config = {**self.hpi_config, **hpi_config}
  81. from .. import create_predictor
  82. logging.info("Creating model: %s", (config["model_name"], model_dir))
  83. model = create_predictor(
  84. model_name=config["model_name"],
  85. model_dir=model_dir,
  86. device=self.device,
  87. batch_size=config.get("batch_size", 1),
  88. pp_option=(
  89. self.pp_option.copy() if self.pp_option is not None else self.pp_option
  90. ),
  91. use_hpip=use_hpip,
  92. hpi_config=hpi_config,
  93. **kwargs,
  94. )
  95. return model
  96. def create_pipeline(self, config: Dict):
  97. """
  98. Creates a pipeline based on the provided configuration.
  99. Args:
  100. config (Dict): A dictionary containing the pipeline configuration.
  101. Returns:
  102. BasePipeline: An instance of the created pipeline.
  103. """
  104. if "pipeline_config_error" in config:
  105. raise ValueError(config["pipeline_config_error"])
  106. from . import create_pipeline
  107. use_hpip = config.get("use_hpip", self.use_hpip)
  108. hpi_config = config.get("hpi_config", None)
  109. if self.hpi_config is not None:
  110. hpi_config = hpi_config or {}
  111. hpi_config = {**self.hpi_config, **hpi_config}
  112. pipeline = create_pipeline(
  113. config=config,
  114. device=self.device,
  115. pp_option=(
  116. self.pp_option.copy() if self.pp_option is not None else self.pp_option
  117. ),
  118. use_hpip=use_hpip,
  119. hpi_config=hpi_config,
  120. )
  121. return pipeline
  122. def __call__(self, input, **kwargs):
  123. """
  124. Calls the predict method with the given input and keyword arguments.
  125. Args:
  126. input: The input data to be predicted.
  127. **kwargs: Additional keyword arguments to be passed to the predict method.
  128. Returns:
  129. The prediction result from the predict method.
  130. """
  131. return self.predict(input, **kwargs)