pp_option.py 12 KB

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