paddle_inference_predictor.py 5.8 KB

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