pp_option.py 12 KB

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