pp_option.py 11 KB

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