pp_option.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 typing import Dict, List
  16. from ...utils import logging
  17. from ...utils.device import (
  18. check_supported_device_type,
  19. get_default_device,
  20. parse_device,
  21. set_env_for_device_type,
  22. )
  23. from .new_ir_blacklist import NEWIR_BLOCKLIST
  24. from .trt_blacklist import TRT_BLOCKLIST
  25. class PaddlePredictorOption(object):
  26. """Paddle Inference Engine Option"""
  27. # NOTE: TRT modes start with `trt_`
  28. SUPPORT_RUN_MODE = (
  29. "paddle",
  30. "paddle_fp32",
  31. "paddle_fp16",
  32. "trt_fp32",
  33. "trt_fp16",
  34. "trt_int8",
  35. "mkldnn",
  36. "mkldnn_bf16",
  37. )
  38. SUPPORT_DEVICE = ("gpu", "cpu", "npu", "xpu", "mlu", "dcu", "gcu")
  39. def __init__(self, model_name=None, **kwargs):
  40. super().__init__()
  41. self.model_name = model_name
  42. self._cfg = {}
  43. self._init_option(**kwargs)
  44. self._changed = False
  45. @property
  46. def changed(self):
  47. return self._changed
  48. @changed.setter
  49. def changed(self, v):
  50. assert isinstance(v, bool)
  51. self._changed = v
  52. def _init_option(self, **kwargs):
  53. for k, v in kwargs.items():
  54. if self._has_setter(k):
  55. setattr(self, k, v)
  56. else:
  57. raise Exception(
  58. f"{k} is not supported to set! The supported option is: {self._get_settable_attributes()}"
  59. )
  60. for k, v in self._get_default_config().items():
  61. self._cfg.setdefault(k, v)
  62. def _get_default_config(self):
  63. """get default config"""
  64. device_type, device_ids = parse_device(get_default_device())
  65. return {
  66. "run_mode": "paddle",
  67. "device_type": device_type,
  68. "device_id": None if device_ids is None else device_ids[0],
  69. "cpu_threads": 8,
  70. "delete_pass": [],
  71. "enable_new_ir": True if self.model_name not in NEWIR_BLOCKLIST else False,
  72. "trt_max_workspace_size": 1 << 30, # only for trt
  73. "trt_max_batch_size": 32, # only for trt
  74. "trt_min_subgraph_size": 3, # only for trt
  75. "trt_use_static": True, # only for trt
  76. "trt_use_calib_mode": False, # only for trt
  77. "trt_use_dynamic_shapes": True, # only for trt
  78. "trt_collect_shape_range_info": True, # only for trt
  79. "trt_discard_cached_shape_range_info": False, # only for trt
  80. "trt_dynamic_shapes": None, # only for trt
  81. "trt_dynamic_shape_input_data": None, # only for trt
  82. "trt_shape_range_info_path": None, # only for trt
  83. "trt_allow_rebuild_at_runtime": True, # only for trt
  84. }
  85. def _update(self, k, v):
  86. self._cfg[k] = v
  87. self.changed = True
  88. @property
  89. def run_mode(self):
  90. return self._cfg["run_mode"]
  91. @run_mode.setter
  92. def run_mode(self, run_mode: str):
  93. """set run mode"""
  94. if run_mode not in self.SUPPORT_RUN_MODE:
  95. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  96. raise ValueError(
  97. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  98. )
  99. # TRT Blocklist
  100. if run_mode.startswith("trt") and self.model_name in TRT_BLOCKLIST:
  101. logging.warning(
  102. f"The model({self.model_name}) is not supported to run in trt mode! Using `paddle` instead!"
  103. )
  104. run_mode = "paddle"
  105. self._update("run_mode", run_mode)
  106. @property
  107. def device_type(self):
  108. return self._cfg["device_type"]
  109. @device_type.setter
  110. def device_type(self, device_type):
  111. if device_type not in self.SUPPORT_DEVICE:
  112. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  113. raise ValueError(
  114. f"The device type must be one of {support_run_mode_str}, but received {repr(device_type)}."
  115. )
  116. check_supported_device_type(device_type, self.model_name)
  117. self._update("device_type", device_type)
  118. set_env_for_device_type(device_type)
  119. # XXX(gaotingquan): set flag to accelerate inference in paddle 3.0b2
  120. if device_type in ("gpu", "cpu"):
  121. os.environ["FLAGS_enable_pir_api"] = "1"
  122. @property
  123. def device_id(self):
  124. return self._cfg["device_id"]
  125. @device_id.setter
  126. def device_id(self, device_id):
  127. self._update("device_id", device_id)
  128. @property
  129. def cpu_threads(self):
  130. return self._cfg["cpu_threads"]
  131. @cpu_threads.setter
  132. def cpu_threads(self, cpu_threads):
  133. """set cpu threads"""
  134. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  135. raise Exception()
  136. self._update("cpu_threads", cpu_threads)
  137. @property
  138. def delete_pass(self):
  139. return self._cfg["delete_pass"]
  140. @delete_pass.setter
  141. def delete_pass(self, delete_pass):
  142. self._update("delete_pass", delete_pass)
  143. @property
  144. def enable_new_ir(self):
  145. return self._cfg["enable_new_ir"]
  146. @enable_new_ir.setter
  147. def enable_new_ir(self, enable_new_ir: bool):
  148. """set run mode"""
  149. self._update("enable_new_ir", enable_new_ir)
  150. @property
  151. def trt_max_workspace_size(self):
  152. return self._cfg["trt_max_workspace_size"]
  153. @trt_max_workspace_size.setter
  154. def trt_max_workspace_size(self, trt_max_workspace_size):
  155. self._update("trt_max_workspace_size", trt_max_workspace_size)
  156. @property
  157. def trt_max_batch_size(self):
  158. return self._cfg["trt_max_batch_size"]
  159. @trt_max_batch_size.setter
  160. def trt_max_batch_size(self, trt_max_batch_size):
  161. self._update("trt_max_batch_size", trt_max_batch_size)
  162. @property
  163. def trt_min_subgraph_size(self):
  164. return self._cfg["trt_min_subgraph_size"]
  165. @trt_min_subgraph_size.setter
  166. def trt_min_subgraph_size(self, trt_min_subgraph_size: int):
  167. """set min subgraph size"""
  168. if not isinstance(trt_min_subgraph_size, int):
  169. raise Exception()
  170. self._update("trt_min_subgraph_size", trt_min_subgraph_size)
  171. @property
  172. def trt_use_static(self):
  173. return self._cfg["trt_use_static"]
  174. @trt_use_static.setter
  175. def trt_use_static(self, trt_use_static):
  176. """set trt use static"""
  177. self._update("trt_use_static", trt_use_static)
  178. @property
  179. def trt_use_calib_mode(self):
  180. return self._cfg["trt_use_calib_mode"]
  181. @trt_use_calib_mode.setter
  182. def trt_use_calib_mode(self, trt_use_calib_mode):
  183. """set trt calib mode"""
  184. self._update("trt_use_calib_mode", trt_use_calib_mode)
  185. @property
  186. def trt_use_dynamic_shapes(self):
  187. return self._cfg["trt_use_dynamic_shapes"]
  188. @trt_use_dynamic_shapes.setter
  189. def trt_use_dynamic_shapes(self, trt_use_dynamic_shapes):
  190. self._update("trt_use_dynamic_shapes", trt_use_dynamic_shapes)
  191. @property
  192. def trt_collect_shape_range_info(self):
  193. return self._cfg["trt_collect_shape_range_info"]
  194. @trt_collect_shape_range_info.setter
  195. def trt_collect_shape_range_info(self, trt_collect_shape_range_info):
  196. self._update("trt_collect_shape_range_info", trt_collect_shape_range_info)
  197. @property
  198. def trt_discard_cached_shape_range_info(self):
  199. return self._cfg["trt_discard_cached_shape_range_info"]
  200. @trt_discard_cached_shape_range_info.setter
  201. def trt_discard_cached_shape_range_info(self, trt_discard_cached_shape_range_info):
  202. self._update(
  203. "trt_discard_cached_shape_range_info", trt_discard_cached_shape_range_info
  204. )
  205. @property
  206. def trt_dynamic_shapes(self):
  207. return self._cfg["trt_dynamic_shapes"]
  208. @trt_dynamic_shapes.setter
  209. def trt_dynamic_shapes(self, trt_dynamic_shapes: Dict[str, List[List[int]]]):
  210. assert isinstance(trt_dynamic_shapes, dict)
  211. for input_k in trt_dynamic_shapes:
  212. assert isinstance(trt_dynamic_shapes[input_k], list)
  213. self._update("trt_dynamic_shapes", trt_dynamic_shapes)
  214. @property
  215. def trt_dynamic_shape_input_data(self):
  216. return self._cfg["trt_dynamic_shape_input_data"]
  217. @trt_dynamic_shape_input_data.setter
  218. def trt_dynamic_shape_input_data(
  219. self, trt_dynamic_shape_input_data: Dict[str, List[float]]
  220. ):
  221. self._update("trt_dynamic_shape_input_data", trt_dynamic_shape_input_data)
  222. @property
  223. def trt_shape_range_info_path(self):
  224. return self._cfg["trt_shape_range_info_path"]
  225. @trt_shape_range_info_path.setter
  226. def trt_shape_range_info_path(self, trt_shape_range_info_path: str):
  227. """set shape info filename"""
  228. self._update("trt_shape_range_info_path", trt_shape_range_info_path)
  229. @property
  230. def trt_allow_rebuild_at_runtime(self):
  231. return self._cfg["trt_allow_rebuild_at_runtime"]
  232. @trt_allow_rebuild_at_runtime.setter
  233. def trt_allow_rebuild_at_runtime(self, trt_allow_rebuild_at_runtime):
  234. self._update("trt_allow_rebuild_at_runtime", trt_allow_rebuild_at_runtime)
  235. # For backward compatibility
  236. # TODO: Issue deprecation warnings
  237. @property
  238. def min_subgraph_size(self):
  239. return self.trt_min_subgraph_size
  240. @min_subgraph_size.setter
  241. def min_subgraph_size(self, min_subgraph_size):
  242. self.trt_min_subgraph_size = min_subgraph_size
  243. @property
  244. def shape_info_filename(self):
  245. return self.trt_shape_range_info_path
  246. @shape_info_filename.setter
  247. def shape_info_filename(self, shape_info_filename):
  248. self.trt_shape_range_info_path = shape_info_filename
  249. @property
  250. def trt_calib_mode(self):
  251. return self.trt_use_calib_mode
  252. @trt_calib_mode.setter
  253. def trt_calib_mode(self, trt_calib_mode):
  254. self.trt_use_calib_mode = trt_calib_mode
  255. @property
  256. def batch_size(self):
  257. return self.trt_max_batch_size
  258. @batch_size.setter
  259. def batch_size(self, batch_size):
  260. self.trt_max_batch_size = batch_size
  261. def set_device(self, device: str):
  262. """set device"""
  263. if not device:
  264. return
  265. device_type, device_ids = parse_device(device)
  266. self.device_type = device_type
  267. device_id = device_ids[0] if device_ids is not None else None
  268. self.device_id = device_id
  269. if device_ids is None or len(device_ids) > 1:
  270. logging.debug(f"The device ID has been set to {device_id}.")
  271. def get_support_run_mode(self):
  272. """get supported run mode"""
  273. return self.SUPPORT_RUN_MODE
  274. def get_support_device(self):
  275. """get supported device"""
  276. return self.SUPPORT_DEVICE
  277. def __str__(self):
  278. return ", ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  279. def __getattr__(self, key):
  280. if key not in self._cfg:
  281. raise Exception(f"The key ({key}) is not found in cfg: \n {self._cfg}")
  282. return self._cfg.get(key)
  283. def __eq__(self, obj):
  284. if isinstance(obj, PaddlePredictorOption):
  285. return obj._cfg == self._cfg
  286. return False
  287. def _has_setter(self, attr):
  288. prop = getattr(self.__class__, attr, None)
  289. return isinstance(prop, property) and prop.fset is not None
  290. def _get_settable_attributes(self):
  291. return [
  292. name
  293. for name, prop in vars(self.__class__).items()
  294. if isinstance(prop, property) and prop.fset is not None
  295. ]