pp_option.py 7.2 KB

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