predictor.py 8.9 KB

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