pp_option.py 12 KB

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