option.py 5.3 KB

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