kernel_option.py 5.3 KB

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