pp_option.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 (
  19. check_supported_device_type,
  20. get_default_device,
  21. parse_device,
  22. set_env_for_device_type,
  23. )
  24. from ...utils.flags import (
  25. DISABLE_MKLDNN_MODEL_BL,
  26. DISABLE_TRT_MODEL_BL,
  27. ENABLE_MKLDNN_BYDEFAULT,
  28. USE_PIR_TRT,
  29. )
  30. from .misc import is_mkldnn_available
  31. from .mkldnn_blocklist import MKLDNN_BLOCKLIST
  32. from .new_ir_blocklist import NEWIR_BLOCKLIST
  33. from .trt_blocklist import TRT_BLOCKLIST
  34. from .trt_config import TRT_CFG_SETTING, TRT_PRECISION_MAP
  35. def get_default_run_mode(model_name, device_type):
  36. if not model_name:
  37. return "paddle"
  38. if device_type != "cpu":
  39. return "paddle"
  40. if (
  41. ENABLE_MKLDNN_BYDEFAULT
  42. and is_mkldnn_available()
  43. and model_name not in MKLDNN_BLOCKLIST
  44. ):
  45. return "mkldnn"
  46. else:
  47. return "paddle"
  48. class PaddlePredictorOption(object):
  49. """Paddle Inference Engine Option"""
  50. # NOTE: TRT modes start with `trt_`
  51. SUPPORT_RUN_MODE = (
  52. "paddle",
  53. "paddle_fp32",
  54. "paddle_fp16",
  55. "trt_fp32",
  56. "trt_fp16",
  57. "trt_int8",
  58. "mkldnn",
  59. "mkldnn_bf16",
  60. )
  61. SUPPORT_DEVICE = ("gpu", "cpu", "npu", "xpu", "mlu", "dcu", "gcu")
  62. def __init__(self, model_name=None, **kwargs):
  63. super().__init__()
  64. self._is_default_run_mode = True
  65. self._model_name = model_name
  66. self._cfg = {}
  67. self._init_option(**kwargs)
  68. self._changed = False
  69. @property
  70. def model_name(self):
  71. return self._model_name
  72. @model_name.setter
  73. def model_name(self, model_name):
  74. self._model_name = model_name
  75. @property
  76. def changed(self):
  77. return self._changed
  78. @changed.setter
  79. def changed(self, v):
  80. assert isinstance(v, bool)
  81. self._changed = v
  82. def copy(self):
  83. obj = type(self)(self._model_name)
  84. obj._cfg = deepcopy(self._cfg)
  85. if hasattr(self, "trt_cfg_setting"):
  86. obj.trt_cfg_setting = self.trt_cfg_setting
  87. return obj
  88. def _init_option(self, **kwargs):
  89. for k, v in kwargs.items():
  90. if self._has_setter(k):
  91. setattr(self, k, v)
  92. else:
  93. raise Exception(
  94. f"{k} is not supported to set! The supported option is: {self._get_settable_attributes()}"
  95. )
  96. if "run_mode" in self._cfg:
  97. self._is_default_run_mode = False
  98. for k, v in self._get_default_config().items():
  99. self._cfg.setdefault(k, v)
  100. # for trt
  101. if self.run_mode in ("trt_int8", "trt_fp32", "trt_fp16"):
  102. trt_cfg_setting = TRT_CFG_SETTING[self.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):
  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(self.model_name, device_type),
  119. "device_type": device_type,
  120. "device_id": device_id,
  121. "cpu_threads": 8,
  122. "delete_pass": [],
  123. "enable_new_ir": True if self.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. self.changed = True
  139. def reset_run_mode_by_default(self, model_name=None, device_type=None):
  140. if self._is_default_run_mode:
  141. model_name = model_name or self.model_name
  142. device_type = device_type or self.device_type
  143. self._update("run_mode", get_default_run_mode(model_name, device_type))
  144. @property
  145. def run_mode(self):
  146. return self._cfg.get("run_mode")
  147. @run_mode.setter
  148. def run_mode(self, run_mode: str):
  149. """set run mode"""
  150. if run_mode not in self.SUPPORT_RUN_MODE:
  151. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  152. raise ValueError(
  153. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  154. )
  155. if run_mode.startswith("mkldnn") and not is_mkldnn_available():
  156. logging.warning("MKL-DNN is not available. Using `paddle` instead.")
  157. run_mode = "paddle"
  158. # TODO: Check if trt is available
  159. if self._model_name is not None:
  160. # TRT Blocklist
  161. if (
  162. not DISABLE_TRT_MODEL_BL
  163. and run_mode.startswith("trt")
  164. and self._model_name in TRT_BLOCKLIST
  165. ):
  166. logging.warning(
  167. f"The model({self._model_name}) is not supported to run in trt mode! Using `paddle` instead!"
  168. )
  169. run_mode = "paddle"
  170. # MKLDNN Blocklist
  171. elif (
  172. not DISABLE_MKLDNN_MODEL_BL
  173. and run_mode.startswith("mkldnn")
  174. and self._model_name in MKLDNN_BLOCKLIST
  175. ):
  176. logging.warning(
  177. f"The model({self._model_name}) is not supported to run in MKLDNN mode! Using `paddle` instead!"
  178. )
  179. run_mode = "paddle"
  180. self._is_default_run_mode = False
  181. self._update("run_mode", run_mode)
  182. @property
  183. def device_type(self):
  184. return self._cfg.get("device_type")
  185. @device_type.setter
  186. def device_type(self, device_type):
  187. if device_type not in self.SUPPORT_DEVICE:
  188. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  189. raise ValueError(
  190. f"The device type must be one of {support_run_mode_str}, but received {repr(device_type)}."
  191. )
  192. check_supported_device_type(device_type, self.model_name)
  193. self._update("device_type", device_type)
  194. set_env_for_device_type(device_type)
  195. # XXX(gaotingquan): set flag to accelerate inference in paddle 3.0b2
  196. if device_type in ("gpu", "cpu"):
  197. os.environ["FLAGS_enable_pir_api"] = "1"
  198. @property
  199. def device_id(self):
  200. return self._cfg.get("device_id")
  201. @device_id.setter
  202. def device_id(self, device_id):
  203. self._update("device_id", device_id)
  204. @property
  205. def cpu_threads(self):
  206. return self._cfg.get("cpu_threads")
  207. @cpu_threads.setter
  208. def cpu_threads(self, cpu_threads):
  209. """set cpu threads"""
  210. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  211. raise Exception()
  212. self._update("cpu_threads", cpu_threads)
  213. @property
  214. def delete_pass(self):
  215. return self._cfg.get("delete_pass")
  216. @delete_pass.setter
  217. def delete_pass(self, delete_pass):
  218. self._update("delete_pass", delete_pass)
  219. @property
  220. def enable_new_ir(self):
  221. return self._cfg.get("enable_new_ir")
  222. @enable_new_ir.setter
  223. def enable_new_ir(self, enable_new_ir: bool):
  224. """set run mode"""
  225. self._update("enable_new_ir", enable_new_ir)
  226. @property
  227. def enable_cinn(self):
  228. return self._cfg.get("enable_cinn")
  229. @enable_cinn.setter
  230. def enable_cinn(self, enable_cinn: bool):
  231. """set run mode"""
  232. self._update("enable_cinn", enable_cinn)
  233. @property
  234. def trt_cfg_setting(self):
  235. return self._cfg.get("trt_cfg_setting")
  236. @trt_cfg_setting.setter
  237. def trt_cfg_setting(self, config: Dict):
  238. """set trt config"""
  239. assert isinstance(
  240. config, dict
  241. ), f"The trt_cfg_setting must be `dict` type, but received `{type(config)}` type!"
  242. self._update("trt_cfg_setting", config)
  243. @property
  244. def trt_use_dynamic_shapes(self):
  245. return self._cfg.get("trt_use_dynamic_shapes")
  246. @trt_use_dynamic_shapes.setter
  247. def trt_use_dynamic_shapes(self, trt_use_dynamic_shapes):
  248. self._update("trt_use_dynamic_shapes", trt_use_dynamic_shapes)
  249. @property
  250. def trt_collect_shape_range_info(self):
  251. return self._cfg.get("trt_collect_shape_range_info")
  252. @trt_collect_shape_range_info.setter
  253. def trt_collect_shape_range_info(self, trt_collect_shape_range_info):
  254. self._update("trt_collect_shape_range_info", trt_collect_shape_range_info)
  255. @property
  256. def trt_discard_cached_shape_range_info(self):
  257. return self._cfg.get("trt_discard_cached_shape_range_info")
  258. @trt_discard_cached_shape_range_info.setter
  259. def trt_discard_cached_shape_range_info(self, trt_discard_cached_shape_range_info):
  260. self._update(
  261. "trt_discard_cached_shape_range_info", trt_discard_cached_shape_range_info
  262. )
  263. @property
  264. def trt_dynamic_shapes(self):
  265. return self._cfg.get("trt_dynamic_shapes")
  266. @trt_dynamic_shapes.setter
  267. def trt_dynamic_shapes(self, trt_dynamic_shapes: Dict[str, List[List[int]]]):
  268. assert isinstance(trt_dynamic_shapes, dict)
  269. for input_k in trt_dynamic_shapes:
  270. assert isinstance(trt_dynamic_shapes[input_k], list)
  271. self._update("trt_dynamic_shapes", trt_dynamic_shapes)
  272. @property
  273. def trt_dynamic_shape_input_data(self):
  274. return self._cfg.get("trt_dynamic_shape_input_data")
  275. @trt_dynamic_shape_input_data.setter
  276. def trt_dynamic_shape_input_data(
  277. self, trt_dynamic_shape_input_data: Dict[str, List[float]]
  278. ):
  279. self._update("trt_dynamic_shape_input_data", trt_dynamic_shape_input_data)
  280. @property
  281. def trt_shape_range_info_path(self):
  282. return self._cfg.get("trt_shape_range_info_path")
  283. @trt_shape_range_info_path.setter
  284. def trt_shape_range_info_path(self, trt_shape_range_info_path: str):
  285. """set shape info filename"""
  286. self._update("trt_shape_range_info_path", trt_shape_range_info_path)
  287. @property
  288. def trt_allow_rebuild_at_runtime(self):
  289. return self._cfg.get("trt_allow_rebuild_at_runtime")
  290. @trt_allow_rebuild_at_runtime.setter
  291. def trt_allow_rebuild_at_runtime(self, trt_allow_rebuild_at_runtime):
  292. self._update("trt_allow_rebuild_at_runtime", trt_allow_rebuild_at_runtime)
  293. @property
  294. def mkldnn_cache_capacity(self):
  295. return self._cfg.get("mkldnn_cache_capacity")
  296. @mkldnn_cache_capacity.setter
  297. def mkldnn_cache_capacity(self, capacity: int):
  298. self._update("mkldnn_cache_capacity", capacity)
  299. # For backward compatibility
  300. # TODO: Issue deprecation warnings
  301. @property
  302. def shape_info_filename(self):
  303. return self.trt_shape_range_info_path
  304. @shape_info_filename.setter
  305. def shape_info_filename(self, shape_info_filename):
  306. self.trt_shape_range_info_path = shape_info_filename
  307. def set_device(self, device: str):
  308. """set device"""
  309. if not device:
  310. return
  311. device_type, device_ids = parse_device(device)
  312. self.device_type = device_type
  313. device_id = device_ids[0] if device_ids is not None else None
  314. self.device_id = device_id
  315. if device_ids is None or len(device_ids) > 1:
  316. logging.debug(f"The device ID has been set to {device_id}.")
  317. def get_support_run_mode(self):
  318. """get supported run mode"""
  319. return self.SUPPORT_RUN_MODE
  320. def get_support_device(self):
  321. """get supported device"""
  322. return self.SUPPORT_DEVICE
  323. def __str__(self):
  324. return ", ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  325. def __getattr__(self, key):
  326. if key not in self._cfg:
  327. raise Exception(f"The key ({key}) is not found in cfg: \n {self._cfg}")
  328. return self._cfg.get(key)
  329. def __eq__(self, obj):
  330. if isinstance(obj, PaddlePredictorOption):
  331. return obj._cfg == self._cfg
  332. return False
  333. def _has_setter(self, attr):
  334. prop = getattr(self.__class__, attr, None)
  335. return isinstance(prop, property) and prop.fset is not None
  336. def _get_settable_attributes(self):
  337. return [
  338. name
  339. for name, prop in vars(self.__class__).items()
  340. if isinstance(prop, property) and prop.fset is not None
  341. ]