paddle_inference_predictor.py 5.5 KB

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