base.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. genai_config = config.get("genai_config", None)
  82. from .. import create_predictor
  83. logging.info("Creating model: %s", (config["model_name"], model_dir))
  84. # TODO(gaotingquan): support to specify pp_option by model in pipeline
  85. if self.pp_option is not None:
  86. pp_option = self.pp_option.copy()
  87. else:
  88. pp_option = None
  89. model = create_predictor(
  90. model_name=config["model_name"],
  91. model_dir=model_dir,
  92. device=self.device,
  93. batch_size=config.get("batch_size", 1),
  94. pp_option=pp_option,
  95. use_hpip=use_hpip,
  96. hpi_config=hpi_config,
  97. genai_config=genai_config,
  98. **kwargs,
  99. )
  100. return model
  101. def create_pipeline(self, config: Dict):
  102. """
  103. Creates a pipeline based on the provided configuration.
  104. Args:
  105. config (Dict): A dictionary containing the pipeline configuration.
  106. Returns:
  107. BasePipeline: An instance of the created pipeline.
  108. """
  109. if "pipeline_config_error" in config:
  110. raise ValueError(config["pipeline_config_error"])
  111. from . import create_pipeline
  112. use_hpip = config.get("use_hpip", self.use_hpip)
  113. hpi_config = config.get("hpi_config", None)
  114. if self.hpi_config is not None:
  115. hpi_config = hpi_config or {}
  116. hpi_config = {**self.hpi_config, **hpi_config}
  117. pipeline = create_pipeline(
  118. config=config,
  119. device=self.device,
  120. pp_option=(
  121. self.pp_option.copy() if self.pp_option is not None else self.pp_option
  122. ),
  123. use_hpip=use_hpip,
  124. hpi_config=hpi_config,
  125. )
  126. return pipeline
  127. def close(self):
  128. pass
  129. def __call__(self, input, **kwargs):
  130. """
  131. Calls the predict method with the given input and keyword arguments.
  132. Args:
  133. input: The input data to be predicted.
  134. **kwargs: Additional keyword arguments to be passed to the predict method.
  135. Returns:
  136. The prediction result from the predict method.
  137. """
  138. return self.predict(input, **kwargs)