pp_option.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 ...utils.device import parse_device, set_env_for_device, get_default_device
  15. from ...utils import logging
  16. from .new_ir_blacklist import NEWIR_BLOCKLIST
  17. class PaddlePredictorOption(object):
  18. """Paddle Inference Engine Option"""
  19. SUPPORT_RUN_MODE = (
  20. "paddle",
  21. "trt_fp32",
  22. "trt_fp16",
  23. "trt_int8",
  24. "mkldnn",
  25. "mkldnn_bf16",
  26. )
  27. SUPPORT_DEVICE = ("gpu", "cpu", "npu", "xpu", "mlu")
  28. def __init__(self, model_name=None, **kwargs):
  29. super().__init__()
  30. self.model_name = model_name
  31. self._cfg = {}
  32. self._init_option(**kwargs)
  33. def _init_option(self, **kwargs):
  34. for k, v in kwargs.items():
  35. if self._has_setter(k):
  36. setattr(self, k, v)
  37. else:
  38. raise Exception(
  39. f"{k} is not supported to set! The supported option is: {self._get_settable_attributes()}"
  40. )
  41. for k, v in self._get_default_config().items():
  42. self._cfg.setdefault(k, v)
  43. def _get_default_config(self):
  44. """get default config"""
  45. device_type, device_id = parse_device(get_default_device())
  46. return {
  47. "run_mode": "paddle",
  48. "device": device_type,
  49. "device_id": 0 if device_id is None else device_id[0],
  50. "min_subgraph_size": 3,
  51. "shape_info_filename": None,
  52. "trt_calib_mode": False,
  53. "cpu_threads": 1,
  54. "trt_use_static": False,
  55. "delete_pass": [],
  56. "enable_new_ir": True if self.model_name not in NEWIR_BLOCKLIST else False,
  57. }
  58. @property
  59. def run_mode(self):
  60. return self._cfg["run_mode"]
  61. @run_mode.setter
  62. def run_mode(self, run_mode: str):
  63. """set run mode"""
  64. if run_mode not in self.SUPPORT_RUN_MODE:
  65. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  66. raise ValueError(
  67. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  68. )
  69. self._cfg["run_mode"] = run_mode
  70. @property
  71. def device_type(self):
  72. return self._cfg["device"]
  73. @property
  74. def device_id(self):
  75. return self._cfg["device_id"]
  76. @property
  77. def device(self):
  78. return self._cfg["device"]
  79. @device.setter
  80. def device(self, device: str):
  81. """set device"""
  82. if not device:
  83. return
  84. device_type, device_ids = parse_device(device)
  85. self._cfg["device"] = device_type
  86. if device_type not in self.SUPPORT_DEVICE:
  87. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  88. raise ValueError(
  89. f"The device type must be one of {support_run_mode_str}, but received {repr(device_type)}."
  90. )
  91. device_id = device_ids[0] if device_ids is not None else 0
  92. self._cfg["device_id"] = device_id
  93. set_env_for_device(device)
  94. if device_type not in ("cpu"):
  95. if device_ids is None or len(device_ids) > 1:
  96. logging.debug(f"The device ID has been set to {device_id}.")
  97. @property
  98. def min_subgraph_size(self):
  99. return self._cfg["min_subgraph_size"]
  100. @min_subgraph_size.setter
  101. def min_subgraph_size(self, min_subgraph_size: int):
  102. """set min subgraph size"""
  103. if not isinstance(min_subgraph_size, int):
  104. raise Exception()
  105. self._cfg["min_subgraph_size"] = min_subgraph_size
  106. @property
  107. def shape_info_filename(self):
  108. return self._cfg["shape_info_filename"]
  109. @shape_info_filename.setter
  110. def shape_info_filename(self, shape_info_filename: str):
  111. """set shape info filename"""
  112. self._cfg["shape_info_filename"] = shape_info_filename
  113. @property
  114. def trt_calib_mode(self):
  115. return self._cfg["trt_calib_mode"]
  116. @trt_calib_mode.setter
  117. def trt_calib_mode(self, trt_calib_mode):
  118. """set trt calib mode"""
  119. self._cfg["trt_calib_mode"] = trt_calib_mode
  120. @property
  121. def cpu_threads(self):
  122. return self._cfg["cpu_threads"]
  123. @cpu_threads.setter
  124. def cpu_threads(self, cpu_threads):
  125. """set cpu threads"""
  126. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  127. raise Exception()
  128. self._cfg["cpu_threads"] = cpu_threads
  129. @property
  130. def trt_use_static(self):
  131. return self._cfg["trt_use_static"]
  132. @trt_use_static.setter
  133. def trt_use_static(self, trt_use_static):
  134. """set trt use static"""
  135. self._cfg["trt_use_static"] = trt_use_static
  136. @property
  137. def delete_pass(self):
  138. return self._cfg["delete_pass"]
  139. @delete_pass.setter
  140. def delete_pass(self, delete_pass):
  141. self._cfg["delete_pass"] = delete_pass
  142. @property
  143. def enable_new_ir(self):
  144. return self._cfg["enable_new_ir"]
  145. @enable_new_ir.setter
  146. def enable_new_ir(self, enable_new_ir: bool):
  147. """set run mode"""
  148. self._cfg["enable_new_ir"] = enable_new_ir
  149. def get_support_run_mode(self):
  150. """get supported run mode"""
  151. return self.SUPPORT_RUN_MODE
  152. def get_support_device(self):
  153. """get supported device"""
  154. return self.SUPPORT_DEVICE
  155. def __str__(self):
  156. return ", ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  157. def __getattr__(self, key):
  158. if key not in self._cfg:
  159. raise Exception(f"The key ({key}) is not found in cfg: \n {self._cfg}")
  160. return self._cfg.get(key)
  161. def __eq__(self, obj):
  162. if isinstance(obj, PaddlePredictorOption):
  163. return obj._cfg == self._cfg
  164. return False
  165. def _has_setter(self, attr):
  166. prop = getattr(self.__class__, attr, None)
  167. return isinstance(prop, property) and prop.fset is not None
  168. def _get_settable_attributes(self):
  169. return [
  170. name
  171. for name, prop in vars(self.__class__).items()
  172. if isinstance(prop, property) and prop.fset is not None
  173. ]