pp_option.py 7.0 KB

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