pp_option.py 11 KB

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