predictor.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. import os
  15. from abc import abstractmethod
  16. import lazy_paddle as paddle
  17. import numpy as np
  18. from ....utils import logging
  19. from ...utils.pp_option import PaddlePredictorOption
  20. from ..utils.mixin import PPEngineMixin
  21. from ..base import BaseComponent
  22. class BasePaddlePredictor(BaseComponent, PPEngineMixin):
  23. """Predictor based on Paddle Inference"""
  24. OUTPUT_KEYS = "pred"
  25. DEAULT_OUTPUTS = {"pred": "pred"}
  26. ENABLE_BATCH = True
  27. def __init__(self, model_dir, model_prefix, option: PaddlePredictorOption = None):
  28. super().__init__()
  29. PPEngineMixin.__init__(self, option)
  30. self.model_dir = model_dir
  31. self.model_prefix = model_prefix
  32. self._is_initialized = False
  33. def _reset(self):
  34. if not self.option:
  35. self.option = PaddlePredictorOption()
  36. (
  37. self.predictor,
  38. self.inference_config,
  39. self.input_names,
  40. self.input_handlers,
  41. self.output_handlers,
  42. ) = self._create()
  43. self._is_initialized = True
  44. logging.debug(f"Env: {self.option}")
  45. def _create(self):
  46. """_create"""
  47. from lazy_paddle.inference import Config, create_predictor
  48. use_pir = (
  49. hasattr(paddle.framework, "use_pir_api") and paddle.framework.use_pir_api()
  50. )
  51. model_postfix = ".json" if use_pir else ".pdmodel"
  52. model_file = (self.model_dir / f"{self.model_prefix}{model_postfix}").as_posix()
  53. params_file = (self.model_dir / f"{self.model_prefix}.pdiparams").as_posix()
  54. config = Config(model_file, params_file)
  55. if self.option.device == "gpu":
  56. config.enable_use_gpu(200, self.option.device_id)
  57. if paddle.is_compiled_with_rocm():
  58. os.environ["FLAGS_conv_workspace_size_limit"] = "2000"
  59. elif hasattr(config, "enable_new_ir"):
  60. config.enable_new_ir(self.option.enable_new_ir)
  61. elif self.option.device == "npu":
  62. config.enable_custom_device("npu")
  63. os.environ["FLAGS_npu_jit_compile"] = "0"
  64. os.environ["FLAGS_use_stride_kernel"] = "0"
  65. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  66. os.environ["CUSTOM_DEVICE_BLACK_LIST"] = (
  67. "pad3d,pad3d_grad,set_value,set_value_with_tensor"
  68. )
  69. os.environ["FLAGS_npu_scale_aclnn"] = "True"
  70. os.environ["FLAGS_npu_split_aclnn"] = "True"
  71. elif self.option.device == "xpu":
  72. os.environ["BKCL_FORCE_SYNC"] = "1"
  73. os.environ["BKCL_TIMEOUT"] = "1800"
  74. os.environ["FLAGS_use_stride_kernel"] = "0"
  75. elif self.option.device == "mlu":
  76. config.enable_custom_device("mlu")
  77. os.environ["FLAGS_use_stride_kernel"] = "0"
  78. else:
  79. assert self.option.device == "cpu"
  80. config.disable_gpu()
  81. if hasattr(config, "enable_new_ir"):
  82. config.enable_new_ir(self.option.enable_new_ir)
  83. if hasattr(config, "enable_new_executor"):
  84. config.enable_new_executor(True)
  85. if "mkldnn" in self.option.run_mode:
  86. try:
  87. config.enable_mkldnn()
  88. config.set_cpu_math_library_num_threads(self.option.cpu_threads)
  89. if "bf16" in self.option.run_mode:
  90. config.enable_mkldnn_bfloat16()
  91. except Exception as e:
  92. logging.warning(
  93. "MKL-DNN is not available. We will disable MKL-DNN."
  94. )
  95. precision_map = {
  96. "trt_int8": Config.Precision.Int8,
  97. "trt_fp32": Config.Precision.Float32,
  98. "trt_fp16": Config.Precision.Half,
  99. }
  100. if self.option.run_mode in precision_map.keys():
  101. config.enable_tensorrt_engine(
  102. workspace_size=(1 << 25) * self.option.batch_size,
  103. max_batch_size=self.option.batch_size,
  104. min_subgraph_size=self.option.min_subgraph_size,
  105. precision_mode=precision_map[self.option.run_mode],
  106. trt_use_static=self.option.trt_use_static,
  107. use_calib_mode=self.option.trt_calib_mode,
  108. )
  109. if self.option.shape_info_filename is not None:
  110. if not os.path.exists(self.option.shape_info_filename):
  111. config.collect_shape_range_info(self.option.shape_info_filename)
  112. logging.info(
  113. f"Dynamic shape info is collected into: {self.option.shape_info_filename}"
  114. )
  115. else:
  116. logging.info(
  117. f"A dynamic shape info file ( {self.option.shape_info_filename} ) already exists. \
  118. No need to generate again."
  119. )
  120. config.enable_tuned_tensorrt_dynamic_shape(
  121. self.option.shape_info_filename, True
  122. )
  123. # Disable paddle inference logging
  124. config.disable_glog_info()
  125. for del_p in self.option.delete_pass:
  126. config.delete_pass(del_p)
  127. # Enable shared memory
  128. config.enable_memory_optim()
  129. config.switch_ir_optim(True)
  130. # Disable feed, fetch OP, needed by zero_copy_run
  131. config.switch_use_feed_fetch_ops(False)
  132. predictor = create_predictor(config)
  133. # Get input and output handlers
  134. input_names = predictor.get_input_names()
  135. input_names.sort()
  136. input_handlers = []
  137. output_handlers = []
  138. for input_name in input_names:
  139. input_handler = predictor.get_input_handle(input_name)
  140. input_handlers.append(input_handler)
  141. output_names = predictor.get_output_names()
  142. for output_name in output_names:
  143. output_handler = predictor.get_output_handle(output_name)
  144. output_handlers.append(output_handler)
  145. return predictor, config, input_names, input_handlers, output_handlers
  146. def get_input_names(self):
  147. """get input names"""
  148. return self.input_names
  149. def apply(self, **kwargs):
  150. if not self._is_initialized:
  151. self._reset()
  152. x = self.to_batch(**kwargs)
  153. for idx in range(len(x)):
  154. self.input_handlers[idx].reshape(x[idx].shape)
  155. self.input_handlers[idx].copy_from_cpu(x[idx])
  156. self.predictor.run()
  157. output = []
  158. for out_tensor in self.output_handlers:
  159. batch = out_tensor.copy_to_cpu()
  160. output.append(batch)
  161. return self.format_output(output)
  162. def format_output(self, pred):
  163. return [{"pred": res} for res in zip(*pred)]
  164. @abstractmethod
  165. def to_batch(self):
  166. raise NotImplementedError
  167. class ImagePredictor(BasePaddlePredictor):
  168. INPUT_KEYS = "img"
  169. DEAULT_INPUTS = {"img": "img"}
  170. def to_batch(self, img):
  171. return [np.stack(img, axis=0).astype(dtype=np.float32, copy=False)]
  172. class ImageDetPredictor(BasePaddlePredictor):
  173. INPUT_KEYS = [["img", "scale_factors"], ["img", "scale_factors", "img_size"]]
  174. OUTPUT_KEYS = [["boxes"], ["boxes", "masks"]]
  175. DEAULT_INPUTS = {"img": "img", "scale_factors": "scale_factors"}
  176. DEAULT_OUTPUTS = None
  177. def to_batch(self, img, scale_factors, img_size=None):
  178. scale_factors = [scale_factor[::-1] for scale_factor in scale_factors]
  179. if img_size is None:
  180. return [
  181. np.stack(img, axis=0).astype(dtype=np.float32, copy=False),
  182. np.stack(scale_factors, axis=0).astype(dtype=np.float32, copy=False),
  183. ]
  184. else:
  185. return [
  186. np.stack(img_size, axis=0).astype(dtype=np.float32, copy=False),
  187. np.stack(img, axis=0).astype(dtype=np.float32, copy=False),
  188. np.stack(scale_factors, axis=0).astype(dtype=np.float32, copy=False),
  189. ]
  190. def format_output(self, pred):
  191. box_idx_start = 0
  192. pred_box = []
  193. if len(pred) == 3:
  194. pred_mask = []
  195. for idx in range(len(pred[1])):
  196. np_boxes_num = pred[1][idx]
  197. box_idx_end = box_idx_start + np_boxes_num
  198. np_boxes = pred[0][box_idx_start:box_idx_end]
  199. pred_box.append(np_boxes)
  200. if len(pred) == 3:
  201. np_masks = pred[2][box_idx_start:box_idx_end]
  202. pred_mask.append(np_masks)
  203. box_idx_start = box_idx_end
  204. boxes = [{"boxes": np.array(res)} for res in pred_box]
  205. if len(pred) == 3:
  206. masks = [{"masks": np.array(res)} for res in pred_mask]
  207. return [{"boxes": boxes[0]["boxes"], "masks": masks[0]["masks"]}]
  208. else:
  209. return [{"boxes": np.array(res)} for res in pred_box]
  210. class TSPPPredictor(BasePaddlePredictor):
  211. INPUT_KEYS = "ts"
  212. DEAULT_INPUTS = {"ts": "ts"}
  213. def to_batch(self, ts):
  214. n = len(ts[0])
  215. x = [np.stack([lst[i] for lst in ts], axis=0) for i in range(n)]
  216. return x