kernel_option.py 5.3 KB

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