paddle_inference_predictor.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 paddle.inference import Config, create_predictor
  16. from .....utils import logging
  17. class _PaddleInferencePredictor(object):
  18. """ Predictor based on Paddle Inference """
  19. def __init__(self, param_path, model_path, option, delete_pass=[]):
  20. super().__init__()
  21. self.predictor, self.inference_config, self.input_names, self.input_handlers, self.output_handlers = \
  22. self._create(param_path, model_path, option, delete_pass=delete_pass)
  23. def _create(self, param_path, model_path, option, delete_pass):
  24. """ _create """
  25. if not os.path.exists(model_path) or not os.path.exists(param_path):
  26. raise FileNotFoundError(
  27. f"Please ensure {model_path} and {param_path} exist.")
  28. model_buffer, param_buffer = self._read_model_param(model_path,
  29. param_path)
  30. config = Config()
  31. config.set_model_buffer(model_buffer,
  32. len(model_buffer), param_buffer,
  33. len(param_buffer))
  34. if option.device == 'gpu':
  35. config.enable_use_gpu(200, option.device_id)
  36. config.enable_new_ir(True)
  37. elif option.device == 'npu':
  38. config.enable_custom_device('npu')
  39. os.environ["FLAGS_npu_jit_compile"] = "0"
  40. os.environ["FLAGS_use_stride_kernel"] = "0"
  41. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  42. os.environ[
  43. "CUSTOM_DEVICE_BLACK_LIST"] = "pad3d,pad3d_grad,set_value,set_value_with_tensor"
  44. elif option.device == 'xpu':
  45. config.enable_custom_device('npu')
  46. elif option.device == 'mlu':
  47. config.enable_custom_device('mlu')
  48. else:
  49. assert option.device == 'cpu'
  50. config.disable_gpu()
  51. if 'mkldnn' in option.run_mode:
  52. try:
  53. config.enable_mkldnn()
  54. config.set_cpu_math_library_num_threads(option.cpu_threads)
  55. if 'bf16' in option.run_mode:
  56. config.enable_mkldnn_bfloat16()
  57. except Exception as e:
  58. logging.warning(
  59. "MKL-DNN is not available. We will disable MKL-DNN.")
  60. precision_map = {
  61. 'trt_int8': Config.Precision.Int8,
  62. 'trt_fp32': Config.Precision.Float32,
  63. 'trt_fp16': Config.Precision.Half
  64. }
  65. if option.run_mode in precision_map.keys():
  66. config.enable_tensorrt_engine(
  67. workspace_size=(1 << 25) * option.batch_size,
  68. max_batch_size=option.batch_size,
  69. min_subgraph_size=option.min_subgraph_size,
  70. precision_mode=precision_map[option.run_mode],
  71. trt_use_static=option.trt_use_static,
  72. use_calib_mode=option.trt_calib_mode)
  73. if option.shape_info_filename is not None:
  74. if not os.path.exists(option.shape_info_filename):
  75. config.collect_shape_range_info(option.shape_info_filename)
  76. logging.info(
  77. f"Dynamic shape info is collected into: {option.shape_info_filename}"
  78. )
  79. else:
  80. logging.info(
  81. f"A dynamic shape info file ( {option.shape_info_filename} ) already exists. \
  82. No need to generate again.")
  83. config.enable_tuned_tensorrt_dynamic_shape(
  84. option.shape_info_filename, True)
  85. # Disable paddle inference logging
  86. config.disable_glog_info()
  87. for del_p in delete_pass:
  88. config.delete_pass(del_p)
  89. # Enable shared memory
  90. config.enable_memory_optim()
  91. config.switch_ir_optim(True)
  92. # Disable feed, fetch OP, needed by zero_copy_run
  93. config.switch_use_feed_fetch_ops(False)
  94. predictor = create_predictor(config)
  95. # Get input and output handlers
  96. input_names = predictor.get_input_names()
  97. input_handlers = []
  98. output_handlers = []
  99. for input_name in input_names:
  100. input_handler = predictor.get_input_handle(input_name)
  101. input_handlers.append(input_handler)
  102. output_names = predictor.get_output_names()
  103. for output_name in output_names:
  104. output_handler = predictor.get_output_handle(output_name)
  105. output_handlers.append(output_handler)
  106. return predictor, config, input_names, input_handlers, output_handlers
  107. def _read_model_param(self, model_path, param_path):
  108. """ read model and param """
  109. model_file = open(model_path, 'rb')
  110. param_file = open(param_path, 'rb')
  111. model_buffer = model_file.read()
  112. param_buffer = param_file.read()
  113. return model_buffer, param_buffer
  114. def get_input_names(self):
  115. """ get input names """
  116. return self.input_names
  117. def predict(self, x):
  118. """ predict """
  119. for idx in range(len(x)):
  120. self.input_handlers[idx].reshape(x[idx].shape)
  121. self.input_handlers[idx].copy_from_cpu(x[idx])
  122. self.predictor.run()
  123. res = []
  124. for out_tensor in self.output_handlers:
  125. out_arr = out_tensor.copy_to_cpu()
  126. res.append(out_arr)
  127. return res