pp_option.py 7.2 KB

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