predictor.py 6.7 KB

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