predictor.py 9.5 KB

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