paddle_inference_predictor.py 6.1 KB

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