pp_option.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. from .device import parse_device
  15. from ...utils.func_register import FuncRegister
  16. from ...utils import logging
  17. class PaddlePredictorOption(object):
  18. """Paddle Inference Engine Option"""
  19. SUPPORT_RUN_MODE = (
  20. "paddle",
  21. "trt_fp32",
  22. "trt_fp16",
  23. "trt_int8",
  24. "mkldnn",
  25. "mkldnn_bf16",
  26. )
  27. SUPPORT_DEVICE = ("gpu", "cpu", "npu", "xpu", "mlu")
  28. _FUNC_MAP = {}
  29. register = FuncRegister(_FUNC_MAP)
  30. def __init__(self, **kwargs):
  31. super().__init__()
  32. self._cfg = {}
  33. self._init_option(**kwargs)
  34. def _init_option(self, **kwargs):
  35. for k, v in kwargs.items():
  36. if k not in self._FUNC_MAP:
  37. raise Exception(
  38. f"{k} is not supported to set! The supported option is: \
  39. {list(self._FUNC_MAP.keys())}"
  40. )
  41. self._FUNC_MAP.get(k)(self, v)
  42. for k, v in self._get_default_config().items():
  43. self._cfg.setdefault(k, v)
  44. def _get_default_config(cls):
  45. """get default config"""
  46. return {
  47. "run_mode": "paddle",
  48. "device": "gpu",
  49. "device_id": 0,
  50. "min_subgraph_size": 3,
  51. "shape_info_filename": None,
  52. "trt_calib_mode": False,
  53. "cpu_threads": 1,
  54. "trt_use_static": False,
  55. "delete_pass": [],
  56. "enable_new_ir": True,
  57. }
  58. @register("run_mode")
  59. def set_run_mode(self, run_mode: str):
  60. """set run mode"""
  61. if run_mode not in self.SUPPORT_RUN_MODE:
  62. support_run_mode_str = ", ".join(self.SUPPORT_RUN_MODE)
  63. raise ValueError(
  64. f"`run_mode` must be {support_run_mode_str}, but received {repr(run_mode)}."
  65. )
  66. self._cfg["run_mode"] = run_mode
  67. @register("device")
  68. def set_device(self, device: str):
  69. """set device"""
  70. if not device:
  71. return
  72. device_type, device_ids = parse_device(device)
  73. self._cfg["device"] = device_type
  74. if device_type not in self.SUPPORT_DEVICE:
  75. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  76. raise ValueError(
  77. f"The device type must be one of {support_run_mode_str}, but received {repr(device_type)}."
  78. )
  79. device_id = device_ids[0] if device_ids is not None else 0
  80. self._cfg["device_id"] = device_id
  81. if device_type not in ("cpu"):
  82. if device_ids is None or len(device_ids) > 1:
  83. logging.warning(f"The device ID has been set to {device_id}.")
  84. @register("min_subgraph_size")
  85. def set_min_subgraph_size(self, min_subgraph_size: int):
  86. """set min subgraph size"""
  87. if not isinstance(min_subgraph_size, int):
  88. raise Exception()
  89. self._cfg["min_subgraph_size"] = min_subgraph_size
  90. @register("shape_info_filename")
  91. def set_shape_info_filename(self, shape_info_filename: str):
  92. """set shape info filename"""
  93. self._cfg["shape_info_filename"] = shape_info_filename
  94. @register("trt_calib_mode")
  95. def set_trt_calib_mode(self, trt_calib_mode):
  96. """set trt calib mode"""
  97. self._cfg["trt_calib_mode"] = trt_calib_mode
  98. @register("cpu_threads")
  99. def set_cpu_threads(self, cpu_threads):
  100. """set cpu threads"""
  101. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  102. raise Exception()
  103. self._cfg["cpu_threads"] = cpu_threads
  104. @register("trt_use_static")
  105. def set_trt_use_static(self, trt_use_static):
  106. """set trt use static"""
  107. self._cfg["trt_use_static"] = trt_use_static
  108. @register("delete_pass")
  109. def set_delete_pass(self, delete_pass):
  110. self._cfg["delete_pass"] = delete_pass
  111. @register("enable_new_ir")
  112. def set_enable_new_ir(self, enable_new_ir: bool):
  113. """set run mode"""
  114. self._cfg["enable_new_ir"] = enable_new_ir
  115. def get_support_run_mode(self):
  116. """get supported run mode"""
  117. return self.SUPPORT_RUN_MODE
  118. def get_support_device(self):
  119. """get supported device"""
  120. return self.SUPPORT_DEVICE
  121. def get_device(self):
  122. """get device"""
  123. return f"{self._cfg['device']}:{self._cfg['device_id']}"
  124. def __str__(self):
  125. return ", ".join([f"{k}: {v}" for k, v in self._cfg.items()])
  126. def __getattr__(self, key):
  127. if key not in self._cfg:
  128. raise Exception(f"The key ({key}) is not found in cfg: \n {self._cfg}")
  129. return self._cfg.get(key)
  130. def __eq__(self, obj):
  131. if isinstance(obj, PaddlePredictorOption):
  132. return obj._cfg == self._cfg
  133. return False