predictor.py 8.8 KB

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