kernel_option.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. Author: PaddlePaddle Authors
  10. """
  11. from functools import wraps, partial
  12. from ....utils import logging
  13. def register(register_map, key):
  14. """register the option setting func
  15. """
  16. def decorator(func):
  17. register_map[key] = func
  18. @wraps(func)
  19. def wrapper(self, *args, **kwargs):
  20. return func(self, *args, **kwargs)
  21. return wrapper
  22. return decorator
  23. class PaddleInferenceOption(object):
  24. """Paddle Inference Engine Option
  25. """
  26. SUPPORT_RUN_MODE = ('paddle', 'trt_fp32', 'trt_fp16', 'trt_int8', 'mkldnn',
  27. 'mkldnn_bf16')
  28. SUPPORT_DEVICE = ('gpu', 'cpu', 'npu', 'xpu', 'mlu')
  29. _REGISTER_MAP = {}
  30. register2self = partial(register, _REGISTER_MAP)
  31. def __init__(self, **kwargs):
  32. super().__init__()
  33. self._cfg = {}
  34. self._init_option(**kwargs)
  35. def _init_option(self, **kwargs):
  36. for k, v in kwargs.items():
  37. if k not in self._REGISTER_MAP:
  38. raise Exception(
  39. f"{k} is not supported to set! The supported option is: \
  40. {list(self._REGISTER_MAP.keys())}")
  41. self._REGISTER_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. 'batch_size': 1,
  49. 'device': 'gpu',
  50. 'device_id': 0,
  51. 'min_subgraph_size': 3,
  52. 'shape_info_filename': None,
  53. 'trt_calib_mode': False,
  54. 'cpu_threads': 1,
  55. 'trt_use_static': False
  56. }
  57. @register2self('run_mode')
  58. def set_run_mode(self, run_mode: str):
  59. """set run mode
  60. """
  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. @register2self('batch_size')
  68. def set_batch_size(self, batch_size: int):
  69. """set batch size
  70. """
  71. if not isinstance(batch_size, int) or batch_size < 1:
  72. raise Exception()
  73. self._cfg['batch_size'] = batch_size
  74. @register2self('device')
  75. def set_device(self, device_setting: str):
  76. """set device
  77. """
  78. if len(device_setting.split(":")) == 1:
  79. device = device_setting.split(":")[0]
  80. device_id = 0
  81. else:
  82. assert len(device_setting.split(":")) == 2
  83. device = device_setting.split(":")[0]
  84. device_id = device_setting.split(":")[1].split(",")[0]
  85. logging.warning(f"The device id has been set to {device_id}.")
  86. if device.lower() not in self.SUPPORT_DEVICE:
  87. support_run_mode_str = ", ".join(self.SUPPORT_DEVICE)
  88. raise ValueError(
  89. f"`device` must be {support_run_mode_str}, but received {repr(device)}."
  90. )
  91. self._cfg['device'] = device.lower()
  92. self._cfg['device_id'] = int(device_id)
  93. @register2self('min_subgraph_size')
  94. def set_min_subgraph_size(self, min_subgraph_size: int):
  95. """set min subgraph size
  96. """
  97. if not isinstance(min_subgraph_size, int):
  98. raise Exception()
  99. self._cfg['min_subgraph_size'] = min_subgraph_size
  100. @register2self('shape_info_filename')
  101. def set_shape_info_filename(self, shape_info_filename: str):
  102. """set shape info filename
  103. """
  104. self._cfg['shape_info_filename'] = shape_info_filename
  105. @register2self('trt_calib_mode')
  106. def set_trt_calib_mode(self, trt_calib_mode):
  107. """set trt calib mode
  108. """
  109. self._cfg['trt_calib_mode'] = trt_calib_mode
  110. @register2self('cpu_threads')
  111. def set_cpu_threads(self, cpu_threads):
  112. """set cpu threads
  113. """
  114. if not isinstance(cpu_threads, int) or cpu_threads < 1:
  115. raise Exception()
  116. self._cfg['cpu_threads'] = cpu_threads
  117. @register2self('trt_use_static')
  118. def set_trt_use_static(self, trt_use_static):
  119. """set trt use static
  120. """
  121. self._cfg['trt_use_static'] = trt_use_static
  122. def get_support_run_mode(self):
  123. """get supported run mode
  124. """
  125. return self.SUPPORT_RUN_MODE
  126. def get_support_device(self):
  127. """get supported device
  128. """
  129. return self.SUPPORT_DEVICE
  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()
  135. return self._cfg.get(key)