pp_option.py 13 KB

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