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