|
| 1 | +# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. |
| 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 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import platform |
| 18 | +from os import path as osp |
| 19 | +from typing import TYPE_CHECKING |
| 20 | +from typing import Optional |
| 21 | +from typing import Tuple |
| 22 | + |
| 23 | +from paddle import inference as paddle_inference |
| 24 | +from typing_extensions import Literal |
| 25 | + |
| 26 | +from ppsci.utils import logger |
| 27 | + |
| 28 | +if TYPE_CHECKING: |
| 29 | + import onnxruntime |
| 30 | + |
| 31 | + |
| 32 | +class Predictor: |
| 33 | + """ |
| 34 | + Initializes the inference engine with the given parameters. |
| 35 | +
|
| 36 | + Args: |
| 37 | + pdmodel_path (Optional[str]): Path to the PaddlePaddle model file. Defaults to None. |
| 38 | + pdpiparams_path (Optional[str]): Path to the PaddlePaddle model parameters file. Defaults to None. |
| 39 | + device (Literal["gpu", "cpu", "npu", "xpu"], optional): Device to use for inference. Defaults to "cpu". |
| 40 | + engine (Literal["native", "tensorrt", "onnx", "mkldnn"], optional): Inference engine to use. Defaults to "native". |
| 41 | + precision (Literal["fp32", "fp16", "int8"], optional): Precision to use for inference. Defaults to "fp32". |
| 42 | + onnx_path (Optional[str], optional): Path to the ONNX model file. Defaults to None. |
| 43 | + ir_optim (bool, optional): Whether to use IR optimization. Defaults to True. |
| 44 | + min_subgraph_size (int, optional): Minimum subgraph size for IR optimization. Defaults to 15. |
| 45 | + gpu_mem (int, optional): Initial size of GPU memory pool(MB). Defaults to 500(MB). |
| 46 | + gpu_id (int, optional): GPU ID to use. Defaults to 0. |
| 47 | + num_cpu_threads (int, optional): Number of CPU threads to use. Defaults to 1. |
| 48 | + """ |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + pdmodel_path: Optional[str] = None, |
| 53 | + pdpiparams_path: Optional[str] = None, |
| 54 | + *, |
| 55 | + device: Literal["gpu", "cpu", "npu", "xpu"] = "cpu", |
| 56 | + engine: Literal["native", "tensorrt", "onnx", "mkldnn"] = "native", |
| 57 | + precision: Literal["fp32", "fp16", "int8"] = "fp32", |
| 58 | + onnx_path: Optional[str] = None, |
| 59 | + ir_optim: bool = True, |
| 60 | + min_subgraph_size: int = 15, |
| 61 | + gpu_mem: int = 500, |
| 62 | + gpu_id: int = 0, |
| 63 | + max_batch_size: int = 10, |
| 64 | + num_cpu_threads: int = 10, |
| 65 | + ): |
| 66 | + self.pdmodel_path = pdmodel_path |
| 67 | + self.pdpiparams_path = pdpiparams_path |
| 68 | + |
| 69 | + self._check_device(device) |
| 70 | + self.device = device |
| 71 | + self._check_engine(engine) |
| 72 | + self.engine = engine |
| 73 | + self._check_precision(precision) |
| 74 | + self.precision = precision |
| 75 | + |
| 76 | + self.onnx_path = onnx_path |
| 77 | + self.ir_optim = ir_optim |
| 78 | + self.min_subgraph_size = min_subgraph_size |
| 79 | + self.gpu_mem = gpu_mem |
| 80 | + self.gpu_id = gpu_id |
| 81 | + self.max_batch_size = max_batch_size |
| 82 | + self.num_cpu_threads = num_cpu_threads |
| 83 | + |
| 84 | + if self.engine == "onnx": |
| 85 | + self.predictor, self.config = self._create_onnx_predictor() |
| 86 | + else: |
| 87 | + self.predictor, self.config = self._create_paddle_predictor() |
| 88 | + |
| 89 | + logger.message( |
| 90 | + f"Inference with engine: {self.engine}, precision: {self.precision}, " |
| 91 | + f"device: {self.device}." |
| 92 | + ) |
| 93 | + |
| 94 | + def predict(self, image): |
| 95 | + raise NotImplementedError |
| 96 | + |
| 97 | + def _create_paddle_predictor( |
| 98 | + self, |
| 99 | + ) -> Tuple[paddle_inference.Predictor, paddle_inference.Config]: |
| 100 | + if not osp.exists(self.pdmodel_path): |
| 101 | + raise FileNotFoundError( |
| 102 | + f"Given 'pdmodel_path': {self.pdmodel_path} does not exist. " |
| 103 | + "Please check if it is correct." |
| 104 | + ) |
| 105 | + if not osp.exists(self.pdpiparams_path): |
| 106 | + raise FileNotFoundError( |
| 107 | + f"Given 'pdpiparams_path': {self.pdpiparams_path} does not exist. " |
| 108 | + "Please check if it is correct." |
| 109 | + ) |
| 110 | + |
| 111 | + config = paddle_inference.Config(self.pdmodel_path, self.pdpiparams_path) |
| 112 | + if self.device == "gpu": |
| 113 | + config.enable_use_gpu(self.gpu_mem, self.gpu_id) |
| 114 | + if self.engine == "tensorrt": |
| 115 | + if self.precision == "fp16": |
| 116 | + precision = paddle_inference.Config.Precision.Half |
| 117 | + elif self.precision == "int8": |
| 118 | + precision = paddle_inference.Config.Precision.Int8 |
| 119 | + else: |
| 120 | + precision = paddle_inference.Config.Precision.Float32 |
| 121 | + config.enable_tensorrt_engine( |
| 122 | + workspace_size=1 << 30, |
| 123 | + precision_mode=precision, |
| 124 | + max_batch_size=self.max_batch_size, |
| 125 | + min_subgraph_size=self.min_subgraph_size, |
| 126 | + use_calib_mode=False, |
| 127 | + ) |
| 128 | + # collect shape |
| 129 | + pdmodel_dir = osp.dirname(self.pdmodel_path) |
| 130 | + trt_shape_path = osp.join(pdmodel_dir, "trt_dynamic_shape.txt") |
| 131 | + |
| 132 | + if not osp.exists(trt_shape_path): |
| 133 | + config.collect_shape_range_info(trt_shape_path) |
| 134 | + logger.info( |
| 135 | + f"Save collected dynamic shape info to: {trt_shape_path}" |
| 136 | + ) |
| 137 | + try: |
| 138 | + config.enable_tuned_tensorrt_dynamic_shape(trt_shape_path, True) |
| 139 | + except Exception as e: |
| 140 | + logger.warning(e) |
| 141 | + logger.warning( |
| 142 | + "TRT dynamic shape is disabled for your paddlepaddle < 2.3.0" |
| 143 | + ) |
| 144 | + |
| 145 | + elif self.device == "npu": |
| 146 | + config.enable_custom_device("npu") |
| 147 | + elif self.device == "xpu": |
| 148 | + config.enable_xpu(10 * 1024 * 1024) |
| 149 | + else: |
| 150 | + config.disable_gpu() |
| 151 | + if self.engine == "mkldnn": |
| 152 | + # 'set_mkldnn_cache_capatity' is not available on macOS |
| 153 | + if platform.system() != "Darwin": |
| 154 | + ... |
| 155 | + # cache 10 different shapes for mkldnn to avoid memory leak |
| 156 | + # config.set_mkldnn_cache_capacity(10) |
| 157 | + config.enable_mkldnn() |
| 158 | + |
| 159 | + if self.precision == "fp16": |
| 160 | + config.enable_mkldnn_bfloat16() |
| 161 | + |
| 162 | + config.set_cpu_math_library_num_threads(self.num_cpu_threads) |
| 163 | + |
| 164 | + # enable memory optim |
| 165 | + config.enable_memory_optim() |
| 166 | + config.disable_glog_info() |
| 167 | + # enable zero copy |
| 168 | + config.switch_use_feed_fetch_ops(False) |
| 169 | + config.switch_ir_optim(self.ir_optim) |
| 170 | + |
| 171 | + predictor = paddle_inference.create_predictor(config) |
| 172 | + return predictor, config |
| 173 | + |
| 174 | + def _create_onnx_predictor( |
| 175 | + self, |
| 176 | + ) -> Tuple["onnxruntime.InferenceSession", "onnxruntime.SessionOptions"]: |
| 177 | + if not osp.exists(self.onnx_path): |
| 178 | + raise FileNotFoundError( |
| 179 | + f"Given 'onnx_path' {self.onnx_path} does not exist. " |
| 180 | + "Please check if it is correct." |
| 181 | + ) |
| 182 | + |
| 183 | + try: |
| 184 | + import onnxruntime as ort |
| 185 | + except ModuleNotFoundError: |
| 186 | + raise ModuleNotFoundError( |
| 187 | + "Please install onnxruntime with `pip install onnxruntime`." |
| 188 | + ) |
| 189 | + |
| 190 | + # set config for onnx predictor |
| 191 | + config = ort.SessionOptions() |
| 192 | + config.intra_op_num_threads = self.num_cpu_threads |
| 193 | + if self.ir_optim: |
| 194 | + config.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL |
| 195 | + |
| 196 | + # instantiate onnx predictor |
| 197 | + predictor = ort.InferenceSession(self.onnx_path, sess_options=config) |
| 198 | + return predictor, config |
| 199 | + |
| 200 | + def _check_device(self, device: str): |
| 201 | + if device not in ["gpu", "cpu", "npu", "xpu"]: |
| 202 | + raise ValueError( |
| 203 | + "Inference only supports 'gpu', 'cpu', 'npu' and 'xpu' devices, " |
| 204 | + f"but got {device}." |
| 205 | + ) |
| 206 | + |
| 207 | + def _check_engine(self, engine: str): |
| 208 | + if engine not in ["native", "tensorrt", "onnx", "mkldnn"]: |
| 209 | + raise ValueError( |
| 210 | + "Inference only supports 'native', 'tensorrt', 'onnx' and 'mkldnn' " |
| 211 | + f"engines, but got {engine}." |
| 212 | + ) |
| 213 | + |
| 214 | + def _check_precision(self, precision: str): |
| 215 | + if precision not in ["fp32", "fp16", "int8"]: |
| 216 | + raise ValueError( |
| 217 | + "Inference only supports 'fp32', 'fp16' and 'int8' " |
| 218 | + f"precision, but got {precision}." |
| 219 | + ) |
0 commit comments