pp_option.py 11 KB

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