pp_option.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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.device import (
  17. parse_device,
  18. set_env_for_device,
  19. get_default_device,
  20. check_supported_device,
  21. )
  22. from ...utils import logging
  23. from .new_ir_blacklist import NEWIR_BLOCKLIST
  24. class PaddlePredictorOption(object):
  25. """Paddle Inference Engine Option"""
  26. # NOTE: TRT modes start with `trt_`
  27. SUPPORT_RUN_MODE = (
  28. "paddle",
  29. "trt_fp32",
  30. "trt_fp16",
  31. "trt_int8",
  32. "mkldnn",
  33. "mkldnn_bf16",
  34. )
  35. SUPPORT_DEVICE = ("gpu", "cpu", "npu", "xpu", "mlu", "dcu", "gcu")
  36. def __init__(self, model_name=None, **kwargs):
  37. super().__init__()
  38. self.model_name = model_name
  39. self._cfg = {}
  40. self._init_option(**kwargs)
  41. self._changed = False
  42. @property
  43. def changed(self):
  44. return self._changed
  45. @changed.setter
  46. def changed(self, v):
  47. assert isinstance(v, bool)
  48. self._changed = v
  49. def _init_option(self, **kwargs):
  50. for k, v in kwargs.items():
  51. if self._has_setter(k):
  52. setattr(self, k, v)
  53. else:
  54. raise Exception(
  55. f"{k} is not supported to set! The supported option is: {self._get_settable_attributes()}"
  56. )
  57. for k, v in self._get_default_config().items():
  58. self._cfg.setdefault(k, v)
  59. def _get_default_config(self):
  60. """get default config"""
  61. device_type, device_id = parse_device(get_default_device())
  62. return {
  63. "run_mode": "paddle",
  64. "device": device_type,
  65. "device_id": 0 if device_id is None else device_id[0],
  66. "min_subgraph_size": 3,
  67. "shape_info_filename": None,
  68. "trt_calib_mode": False,
  69. "cpu_threads": 8,
  70. "trt_use_static": False,
  71. "delete_pass": [],
  72. "enable_new_ir": True if self.model_name not in NEWIR_BLOCKLIST else False,
  73. "batch_size": 1, # only for trt
  74. "trt_dynamic_shapes": {}, # only for trt
  75. }
  76. def _update(self, k, v):
  77. self._cfg[k] = v
  78. self.changed = True
  79. @property
  80. def run_mode(self):
  81. return self._cfg["run_mode"]
  82. @run_mode.setter
  83. def run_mode(self, run_mode: str):
  84. """set run mode"""
  85. if run_mode not in self.SUPPORT_RUN_MODE:
  86. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  87. raise ValueError(
  88. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  89. )
  90. self._update("run_mode", run_mode)
  91. @property
  92. def device_type(self):
  93. return self._cfg["device"]
  94. @property
  95. def device_id(self):
  96. return self._cfg["device_id"]
  97. @property
  98. def device(self):
  99. device = self._cfg["device"]
  100. check_supported_device(device, self.model_name)
  101. return device
  102. @device.setter
  103. def device(self, device: str):
  104. """set device"""
  105. if not device:
  106. return
  107. device_type, device_ids = parse_device(device)
  108. if device_type not in self.SUPPORT_DEVICE:
  109. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  110. raise ValueError(
  111. f"The device type must be one of {support_run_mode_str}, but received {repr(device_type)}."
  112. )
  113. self._update("device", device_type)
  114. device_id = device_ids[0] if device_ids is not None else 0
  115. self._update("device_id", device_id)
  116. set_env_for_device(device)
  117. if device_type not in ("cpu"):
  118. if device_ids is None or len(device_ids) > 1:
  119. logging.debug(f"The device ID has been set to {device_id}.")
  120. # XXX(gaotingquan): set flag to accelerate inference in paddle 3.0b2
  121. if device_type in ("gpu", "cpu"):
  122. os.environ["FLAGS_enable_pir_api"] = "1"
  123. @property
  124. def min_subgraph_size(self):
  125. return self._cfg["min_subgraph_size"]
  126. @min_subgraph_size.setter
  127. def min_subgraph_size(self, min_subgraph_size: int):
  128. """set min subgraph size"""
  129. if not isinstance(min_subgraph_size, int):
  130. raise Exception()
  131. self._update("min_subgraph_size", min_subgraph_size)
  132. @property
  133. def shape_info_filename(self):
  134. return self._cfg["shape_info_filename"]
  135. @shape_info_filename.setter
  136. def shape_info_filename(self, shape_info_filename: str):
  137. """set shape info filename"""
  138. self._update("shape_info_filename", shape_info_filename)
  139. @property
  140. def trt_dynamic_shapes(self):
  141. return self._cfg["trt_dynamic_shapes"]
  142. @trt_dynamic_shapes.setter
  143. def trt_dynamic_shapes(self, trt_dynamic_shapes: Dict[str, List[List[int]]]):
  144. assert isinstance(trt_dynamic_shapes, dict)
  145. for input_k in trt_dynamic_shapes:
  146. assert isinstance(trt_dynamic_shapes[input_k], list)
  147. self._update("trt_dynamic_shapes", trt_dynamic_shapes)
  148. @property
  149. def trt_calib_mode(self):
  150. return self._cfg["trt_calib_mode"]
  151. @trt_calib_mode.setter
  152. def trt_calib_mode(self, trt_calib_mode):
  153. """set trt calib mode"""
  154. self._update("trt_calib_mode", trt_calib_mode)
  155. @property
  156. def cpu_threads(self):
  157. return self._cfg["cpu_threads"]
  158. @cpu_threads.setter
  159. def cpu_threads(self, cpu_threads):
  160. """set cpu threads"""
  161. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  162. raise Exception()
  163. self._update("cpu_threads", cpu_threads)
  164. @property
  165. def trt_use_static(self):
  166. return self._cfg["trt_use_static"]
  167. @trt_use_static.setter
  168. def trt_use_static(self, trt_use_static):
  169. """set trt use static"""
  170. self._update("trt_use_static", trt_use_static)
  171. @property
  172. def delete_pass(self):
  173. return self._cfg["delete_pass"]
  174. @delete_pass.setter
  175. def delete_pass(self, delete_pass):
  176. self._update("delete_pass", delete_pass)
  177. @property
  178. def enable_new_ir(self):
  179. return self._cfg["enable_new_ir"]
  180. @enable_new_ir.setter
  181. def enable_new_ir(self, enable_new_ir: bool):
  182. """set run mode"""
  183. self._update("enable_new_ir", enable_new_ir)
  184. @property
  185. def batch_size(self):
  186. return self._cfg["batch_size"]
  187. @batch_size.setter
  188. def batch_size(self, batch_size):
  189. self._update("batch_size", batch_size)
  190. def get_support_run_mode(self):
  191. """get supported run mode"""
  192. return self.SUPPORT_RUN_MODE
  193. def get_support_device(self):
  194. """get supported device"""
  195. return self.SUPPORT_DEVICE
  196. def __str__(self):
  197. return ", ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  198. def __getattr__(self, key):
  199. if key not in self._cfg:
  200. raise Exception(f"The key ({key}) is not found in cfg: \n {self._cfg}")
  201. return self._cfg.get(key)
  202. def __eq__(self, obj):
  203. if isinstance(obj, PaddlePredictorOption):
  204. return obj._cfg == self._cfg
  205. return False
  206. def _has_setter(self, attr):
  207. prop = getattr(self.__class__, attr, None)
  208. return isinstance(prop, property) and prop.fset is not None
  209. def _get_settable_attributes(self):
  210. return [
  211. name
  212. for name, prop in vars(self.__class__).items()
  213. if isinstance(prop, property) and prop.fset is not None
  214. ]