pp_option.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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", "dcu")
  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. self._observers = []
  34. def _init_option(self, **kwargs):
  35. for k, v in kwargs.items():
  36. if self._has_setter(k):
  37. setattr(self, k, v)
  38. else:
  39. raise Exception(
  40. f"{k} is not supported to set! The supported option is: {self._get_settable_attributes()}"
  41. )
  42. for k, v in self._get_default_config().items():
  43. self._cfg.setdefault(k, v)
  44. def _get_default_config(self):
  45. """get default config"""
  46. device_type, device_id = parse_device(get_default_device())
  47. return {
  48. "run_mode": "paddle",
  49. "device": device_type,
  50. "device_id": 0 if device_id is None else device_id[0],
  51. "min_subgraph_size": 3,
  52. "shape_info_filename": None,
  53. "trt_calib_mode": False,
  54. "cpu_threads": 1,
  55. "trt_use_static": False,
  56. "delete_pass": [],
  57. "enable_new_ir": True if self.model_name not in NEWIR_BLOCKLIST else False,
  58. }
  59. def _update(self, k, v):
  60. self._cfg[k] = v
  61. self.notify()
  62. @property
  63. def run_mode(self):
  64. return self._cfg["run_mode"]
  65. @run_mode.setter
  66. def run_mode(self, run_mode: str):
  67. """set run mode"""
  68. if run_mode not in self.SUPPORT_RUN_MODE:
  69. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  70. raise ValueError(
  71. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  72. )
  73. self._update("run_mode", run_mode)
  74. @property
  75. def device_type(self):
  76. return self._cfg["device"]
  77. @property
  78. def device_id(self):
  79. return self._cfg["device_id"]
  80. @property
  81. def device(self):
  82. return self._cfg["device"]
  83. @device.setter
  84. def device(self, device: str):
  85. """set device"""
  86. if not device:
  87. return
  88. device_type, device_ids = parse_device(device)
  89. if device_type not in self.SUPPORT_DEVICE:
  90. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  91. raise ValueError(
  92. f"The device type must be one of {support_run_mode_str}, but received {repr(device_type)}."
  93. )
  94. self._update("device", device_type)
  95. device_id = device_ids[0] if device_ids is not None else 0
  96. self._update("device_id", device_id)
  97. set_env_for_device(device)
  98. if device_type not in ("cpu"):
  99. if device_ids is None or len(device_ids) > 1:
  100. logging.debug(f"The device ID has been set to {device_id}.")
  101. @property
  102. def min_subgraph_size(self):
  103. return self._cfg["min_subgraph_size"]
  104. @min_subgraph_size.setter
  105. def min_subgraph_size(self, min_subgraph_size: int):
  106. """set min subgraph size"""
  107. if not isinstance(min_subgraph_size, int):
  108. raise Exception()
  109. self._update("min_subgraph_size", min_subgraph_size)
  110. @property
  111. def shape_info_filename(self):
  112. return self._cfg["shape_info_filename"]
  113. @shape_info_filename.setter
  114. def shape_info_filename(self, shape_info_filename: str):
  115. """set shape info filename"""
  116. self._update("shape_info_filename", shape_info_filename)
  117. @property
  118. def trt_calib_mode(self):
  119. return self._cfg["trt_calib_mode"]
  120. @trt_calib_mode.setter
  121. def trt_calib_mode(self, trt_calib_mode):
  122. """set trt calib mode"""
  123. self._update("trt_calib_mode", trt_calib_mode)
  124. @property
  125. def cpu_threads(self):
  126. return self._cfg["cpu_threads"]
  127. @cpu_threads.setter
  128. def cpu_threads(self, cpu_threads):
  129. """set cpu threads"""
  130. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  131. raise Exception()
  132. self._update("cpu_threads", cpu_threads)
  133. @property
  134. def trt_use_static(self):
  135. return self._cfg["trt_use_static"]
  136. @trt_use_static.setter
  137. def trt_use_static(self, trt_use_static):
  138. """set trt use static"""
  139. self._update("trt_use_static", trt_use_static)
  140. @property
  141. def delete_pass(self):
  142. return self._cfg["delete_pass"]
  143. @delete_pass.setter
  144. def delete_pass(self, delete_pass):
  145. self._update("delete_pass", delete_pass)
  146. @property
  147. def enable_new_ir(self):
  148. return self._cfg["enable_new_ir"]
  149. @enable_new_ir.setter
  150. def enable_new_ir(self, enable_new_ir: bool):
  151. """set run mode"""
  152. self._update("enable_new_ir", enable_new_ir)
  153. def get_support_run_mode(self):
  154. """get supported run mode"""
  155. return self.SUPPORT_RUN_MODE
  156. def get_support_device(self):
  157. """get supported device"""
  158. return self.SUPPORT_DEVICE
  159. def __str__(self):
  160. return ", ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  161. def __getattr__(self, key):
  162. if key not in self._cfg:
  163. raise Exception(f"The key ({key}) is not found in cfg: \n {self._cfg}")
  164. return self._cfg.get(key)
  165. def __eq__(self, obj):
  166. if isinstance(obj, PaddlePredictorOption):
  167. return obj._cfg == self._cfg
  168. return False
  169. def _has_setter(self, attr):
  170. prop = getattr(self.__class__, attr, None)
  171. return isinstance(prop, property) and prop.fset is not None
  172. def _get_settable_attributes(self):
  173. return [
  174. name
  175. for name, prop in vars(self.__class__).items()
  176. if isinstance(prop, property) and prop.fset is not None
  177. ]
  178. def attach(self, observer):
  179. if observer not in self._observers:
  180. self._observers.append(observer)
  181. def detach(self, observer):
  182. try:
  183. self._observers.remove(observer)
  184. except ValueError:
  185. pass
  186. def notify(self):
  187. for observer in self._observers:
  188. observer.reset()