static_infer.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. from typing import Sequence, List
  15. from pathlib import Path
  16. import lazy_paddle
  17. import numpy as np
  18. from ....utils import logging
  19. from ....utils.device import constr_device
  20. from ....utils.flags import DEBUG, USE_PIR_TRT
  21. from ...utils.benchmark import benchmark, set_inference_operations
  22. from ...utils.hpi import get_model_paths
  23. from ...utils.pp_option import PaddlePredictorOption
  24. from ...utils.trt_config import TRT_CFG
  25. CACHE_DIR = ".cache"
  26. INFERENCE_OPERATIONS = ["PaddleCopyToDevice", "PaddleCopyToHost", "PaddleModelInfer"]
  27. set_inference_operations(INFERENCE_OPERATIONS)
  28. # XXX: Better use Paddle Inference API to do this
  29. def _pd_dtype_to_np_dtype(pd_dtype):
  30. if pd_dtype == lazy_paddle.inference.DataType.FLOAT64:
  31. return np.float64
  32. elif pd_dtype == lazy_paddle.inference.DataType.FLOAT32:
  33. return np.float32
  34. elif pd_dtype == lazy_paddle.inference.DataType.INT64:
  35. return np.int64
  36. elif pd_dtype == lazy_paddle.inference.DataType.INT32:
  37. return np.int32
  38. elif pd_dtype == lazy_paddle.inference.DataType.UINT8:
  39. return np.uint8
  40. elif pd_dtype == lazy_paddle.inference.DataType.INT8:
  41. return np.int8
  42. else:
  43. raise TypeError(f"Unsupported data type: {pd_dtype}")
  44. # old trt
  45. def _collect_trt_shape_range_info(
  46. model_file,
  47. model_params,
  48. gpu_id,
  49. shape_range_info_path,
  50. dynamic_shapes,
  51. dynamic_shape_input_data,
  52. ):
  53. dynamic_shape_input_data = dynamic_shape_input_data or {}
  54. config = lazy_paddle.inference.Config(model_file, model_params)
  55. config.enable_use_gpu(100, gpu_id)
  56. config.collect_shape_range_info(shape_range_info_path)
  57. # TODO: Add other needed options
  58. config.disable_glog_info()
  59. predictor = lazy_paddle.inference.create_predictor(config)
  60. input_names = predictor.get_input_names()
  61. for name in dynamic_shapes:
  62. if name not in input_names:
  63. raise ValueError(
  64. f"Invalid input name {repr(name)} found in `dynamic_shapes`"
  65. )
  66. for name in input_names:
  67. if name not in dynamic_shapes:
  68. raise ValueError(f"Input name {repr(name)} not found in `dynamic_shapes`")
  69. for name in dynamic_shape_input_data:
  70. if name not in input_names:
  71. raise ValueError(
  72. f"Invalid input name {repr(name)} found in `dynamic_shape_input_data`"
  73. )
  74. # It would be better to check if the shapes are valid.
  75. min_arrs, opt_arrs, max_arrs = {}, {}, {}
  76. for name, candidate_shapes in dynamic_shapes.items():
  77. # XXX: Currently we have no way to get the data type of the tensor
  78. # without creating an input handle.
  79. handle = predictor.get_input_handle(name)
  80. dtype = _pd_dtype_to_np_dtype(handle.type())
  81. min_shape, opt_shape, max_shape = candidate_shapes
  82. if name in dynamic_shape_input_data:
  83. min_arrs[name] = np.array(
  84. dynamic_shape_input_data[name][0], dtype=dtype
  85. ).reshape(min_shape)
  86. opt_arrs[name] = np.array(
  87. dynamic_shape_input_data[name][1], dtype=dtype
  88. ).reshape(opt_shape)
  89. max_arrs[name] = np.array(
  90. dynamic_shape_input_data[name][2], dtype=dtype
  91. ).reshape(max_shape)
  92. else:
  93. min_arrs[name] = np.ones(min_shape, dtype=dtype)
  94. opt_arrs[name] = np.ones(opt_shape, dtype=dtype)
  95. max_arrs[name] = np.ones(max_shape, dtype=dtype)
  96. # `opt_arrs` is used twice to ensure it is the most frequently used.
  97. for arrs in [min_arrs, opt_arrs, opt_arrs, max_arrs]:
  98. for name, arr in arrs.items():
  99. handle = predictor.get_input_handle(name)
  100. handle.reshape(arr.shape)
  101. handle.copy_from_cpu(arr)
  102. predictor.run()
  103. # HACK: The shape range info will be written to the file only when
  104. # `predictor` is garbage collected. It works in CPython, but it is
  105. # definitely a bad idea to count on the implementation-dependent behavior of
  106. # a garbage collector. Is there a more explicit and deterministic way to
  107. # handle this?
  108. # HACK: Manually delete the predictor to trigger its destructor, ensuring that the shape_range_info file would be saved.
  109. del predictor
  110. # pir trt
  111. def _convert_trt(
  112. model_name,
  113. mode,
  114. pp_model_file,
  115. pp_params_file,
  116. trt_save_path,
  117. dynamic_shapes,
  118. dynamic_shape_input_data,
  119. ):
  120. from lazy_paddle.tensorrt.export import (
  121. Input,
  122. TensorRTConfig,
  123. convert,
  124. PrecisionMode,
  125. )
  126. def _set_trt_config():
  127. if settings := TRT_CFG.get(model_name):
  128. for attr_name in settings:
  129. if not hasattr(trt_config, attr_name):
  130. logging.warning(f"The TensorRTConfig don't have the `{attr_name}`!")
  131. setattr(trt_config, attr_name, settings[attr_name])
  132. def _get_predictor(model_file, params_file):
  133. # HACK
  134. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  135. # NOTE: Disable oneDNN to circumvent a bug in Paddle Inference
  136. config.disable_mkldnn()
  137. config.disable_glog_info()
  138. return lazy_paddle.inference.create_predictor(config)
  139. dynamic_shape_input_data = dynamic_shape_input_data or {}
  140. predictor = _get_predictor(pp_model_file, pp_params_file)
  141. input_names = predictor.get_input_names()
  142. for name in dynamic_shapes:
  143. if name not in input_names:
  144. raise ValueError(
  145. f"Invalid input name {repr(name)} found in `dynamic_shapes`"
  146. )
  147. for name in input_names:
  148. if name not in dynamic_shapes:
  149. raise ValueError(f"Input name {repr(name)} not found in `dynamic_shapes`")
  150. for name in dynamic_shape_input_data:
  151. if name not in input_names:
  152. raise ValueError(
  153. f"Invalid input name {repr(name)} found in `dynamic_shape_input_data`"
  154. )
  155. precision_map = {
  156. "trt_int8": PrecisionMode.INT8,
  157. "trt_fp32": PrecisionMode.FP32,
  158. "trt_fp16": PrecisionMode.FP16,
  159. }
  160. trt_inputs = []
  161. for name, candidate_shapes in dynamic_shapes.items():
  162. # XXX: Currently we have no way to get the data type of the tensor
  163. # without creating an input handle.
  164. handle = predictor.get_input_handle(name)
  165. dtype = _pd_dtype_to_np_dtype(handle.type())
  166. min_shape, opt_shape, max_shape = candidate_shapes
  167. if name in dynamic_shape_input_data:
  168. min_arr = np.array(dynamic_shape_input_data[name][0], dtype=dtype).reshape(
  169. min_shape
  170. )
  171. opt_arr = np.array(dynamic_shape_input_data[name][1], dtype=dtype).reshape(
  172. opt_shape
  173. )
  174. max_arr = np.array(dynamic_shape_input_data[name][2], dtype=dtype).reshape(
  175. max_shape
  176. )
  177. else:
  178. min_arr = np.ones(min_shape, dtype=dtype)
  179. opt_arr = np.ones(opt_shape, dtype=dtype)
  180. max_arr = np.ones(max_shape, dtype=dtype)
  181. # refer to: https://github.com/PolaKuma/Paddle/blob/3347f225bc09f2ec09802a2090432dd5cb5b6739/test/tensorrt/test_converter_model_resnet50.py
  182. trt_input = Input((min_arr, opt_arr, max_arr))
  183. trt_inputs.append(trt_input)
  184. # Create TensorRTConfig
  185. trt_config = TensorRTConfig(inputs=trt_inputs)
  186. _set_trt_config()
  187. trt_config.precision_mode = precision_map[mode]
  188. trt_config.save_model_dir = str(trt_save_path)
  189. pp_model_path = str(pp_model_file.with_suffix(""))
  190. convert(pp_model_path, trt_config)
  191. def _sort_inputs(inputs, names):
  192. # NOTE: Adjust input tensors to match the sorted sequence.
  193. indices = sorted(range(len(names)), key=names.__getitem__)
  194. inputs = [inputs[indices.index(i)] for i in range(len(inputs))]
  195. return inputs
  196. def _concatenate(*callables):
  197. def _chain(x):
  198. for c in callables:
  199. x = c(x)
  200. return x
  201. return _chain
  202. @benchmark.timeit
  203. class PaddleCopyToDevice:
  204. def __init__(self, device_type, device_id):
  205. self.device_type = device_type
  206. self.device_id = device_id
  207. def __call__(self, arrs):
  208. device_id = [self.device_id] if self.device_id is not None else self.device_id
  209. device = constr_device(self.device_type, device_id)
  210. paddle_tensors = [lazy_paddle.to_tensor(i, place=device) for i in arrs]
  211. return paddle_tensors
  212. @benchmark.timeit
  213. class PaddleCopyToHost:
  214. def __call__(self, paddle_tensors):
  215. arrs = [i.numpy() for i in paddle_tensors]
  216. return arrs
  217. @benchmark.timeit
  218. class PaddleModelInfer:
  219. def __init__(self, predictor):
  220. super().__init__()
  221. self.predictor = predictor
  222. def __call__(self, x):
  223. return self.predictor.run(x)
  224. # FIXME: Name might be misleading
  225. @benchmark.timeit
  226. class PaddleInferChainLegacy:
  227. def __init__(self, predictor):
  228. self.predictor = predictor
  229. input_names = self.predictor.get_input_names()
  230. self.input_handles = []
  231. self.output_handles = []
  232. for input_name in input_names:
  233. input_handle = self.predictor.get_input_handle(input_name)
  234. self.input_handles.append(input_handle)
  235. output_names = self.predictor.get_output_names()
  236. for output_name in output_names:
  237. output_handle = self.predictor.get_output_handle(output_name)
  238. self.output_handles.append(output_handle)
  239. def __call__(self, x):
  240. for input_, input_handle in zip(x, self.input_handles):
  241. input_handle.reshape(input_.shape)
  242. input_handle.copy_from_cpu(input_)
  243. self.predictor.run()
  244. outputs = [o.copy_to_cpu() for o in self.output_handles]
  245. return outputs
  246. class StaticInfer(object):
  247. def __init__(
  248. self,
  249. model_dir: str,
  250. model_prefix: str,
  251. option: PaddlePredictorOption,
  252. ) -> None:
  253. super().__init__()
  254. self.model_dir = model_dir
  255. self.model_file_prefix = model_prefix
  256. self._option = option
  257. self.predictor = self._create()
  258. if not self._use_legacy_api:
  259. device_type = self._option.device_type
  260. device_type = "gpu" if device_type == "dcu" else device_type
  261. copy_to_device = PaddleCopyToDevice(device_type, self._option.device_id)
  262. copy_to_host = PaddleCopyToHost()
  263. model_infer = PaddleModelInfer(self.predictor)
  264. self.infer = _concatenate(copy_to_device, model_infer, copy_to_host)
  265. else:
  266. self.infer = PaddleInferChainLegacy(self.predictor)
  267. @property
  268. def _use_legacy_api(self):
  269. return self._option.device_type not in ("cpu", "gpu", "dcu")
  270. def __call__(self, x: Sequence[np.ndarray]) -> List[np.ndarray]:
  271. names = self.predictor.get_input_names()
  272. if len(names) != len(x):
  273. raise ValueError(
  274. f"The number of inputs does not match the model: {len(names)} vs {len(x)}"
  275. )
  276. # TODO:
  277. # Ensure that input tensors follow the model's input sequence without sorting.
  278. x = _sort_inputs(x, names)
  279. x = list(map(np.ascontiguousarray, x))
  280. pred = self.infer(x)
  281. return pred
  282. def _create(
  283. self,
  284. ):
  285. """_create"""
  286. model_paths = get_model_paths(self.model_dir, self.model_file_prefix)
  287. if "paddle" not in model_paths:
  288. raise RuntimeError("No valid Paddle model found")
  289. model_file, params_file = model_paths["paddle"]
  290. if (
  291. self._option.model_name == "LaTeX_OCR_rec"
  292. and self._option.device_type == "cpu"
  293. ):
  294. import cpuinfo
  295. if (
  296. "GenuineIntel" in cpuinfo.get_cpu_info().get("vendor_id_raw", "")
  297. and self._option.run_mode != "mkldnn"
  298. ):
  299. logging.warning(
  300. "Now, the `LaTeX_OCR_rec` model only support `mkldnn` mode when running on Intel CPU devices. So using `mkldnn` instead."
  301. )
  302. self._option.run_mode = "mkldnn"
  303. logging.debug("`run_mode` updated to 'mkldnn'")
  304. if self._option.device_type == "cpu" and self._option.device_id is not None:
  305. self._option.device_id = None
  306. logging.debug("`device_id` has been set to None")
  307. if (
  308. self._option.device_type in ("gpu", "dcu")
  309. and self._option.device_id is None
  310. ):
  311. self._option.device_id = 0
  312. logging.debug("`device_id` has been set to 0")
  313. # for TRT
  314. if self._option.run_mode.startswith("trt"):
  315. assert self._option.device_type == "gpu"
  316. cache_dir = self.model_dir / CACHE_DIR / "paddle"
  317. config = self._configure_trt(
  318. model_file,
  319. params_file,
  320. cache_dir,
  321. )
  322. else:
  323. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  324. if self._option.device_type == "gpu":
  325. config.exp_disable_mixed_precision_ops({"feed", "fetch"})
  326. config.enable_use_gpu(100, self._option.device_id)
  327. if not self._option.run_mode.startswith("trt"):
  328. if hasattr(config, "enable_new_ir"):
  329. config.enable_new_ir(self._option.enable_new_ir)
  330. if hasattr(config, "enable_new_executor"):
  331. config.enable_new_executor()
  332. config.set_optimization_level(3)
  333. elif self._option.device_type == "npu":
  334. config.enable_custom_device("npu")
  335. if hasattr(config, "enable_new_executor"):
  336. config.enable_new_executor()
  337. elif self._option.device_type == "xpu":
  338. if hasattr(config, "enable_new_executor"):
  339. config.enable_new_executor()
  340. elif self._option.device_type == "mlu":
  341. config.enable_custom_device("mlu")
  342. if hasattr(config, "enable_new_executor"):
  343. config.enable_new_executor()
  344. elif self._option.device_type == "dcu":
  345. config.enable_use_gpu(100, self._option.device_id)
  346. if hasattr(config, "enable_new_executor"):
  347. config.enable_new_executor()
  348. # XXX: is_compiled_with_rocm() must be True on dcu platform ?
  349. if lazy_paddle.is_compiled_with_rocm():
  350. # Delete unsupported passes in dcu
  351. config.delete_pass("conv2d_add_act_fuse_pass")
  352. config.delete_pass("conv2d_add_fuse_pass")
  353. else:
  354. assert self._option.device_type == "cpu"
  355. config.disable_gpu()
  356. if "mkldnn" in self._option.run_mode:
  357. try:
  358. config.enable_mkldnn()
  359. if "bf16" in self._option.run_mode:
  360. config.enable_mkldnn_bfloat16()
  361. except Exception as e:
  362. logging.warning(
  363. "MKL-DNN is not available. We will disable MKL-DNN."
  364. )
  365. config.set_mkldnn_cache_capacity(-1)
  366. else:
  367. if hasattr(config, "disable_mkldnn"):
  368. config.disable_mkldnn()
  369. config.set_cpu_math_library_num_threads(self._option.cpu_threads)
  370. if hasattr(config, "enable_new_ir"):
  371. config.enable_new_ir(self._option.enable_new_ir)
  372. if hasattr(config, "enable_new_executor"):
  373. config.enable_new_executor()
  374. config.set_optimization_level(3)
  375. config.enable_memory_optim()
  376. for del_p in self._option.delete_pass:
  377. config.delete_pass(del_p)
  378. # Disable paddle inference logging
  379. if not DEBUG:
  380. config.disable_glog_info()
  381. predictor = lazy_paddle.inference.create_predictor(config)
  382. return predictor
  383. def _configure_trt(self, model_file, params_file, cache_dir):
  384. # TODO: Support calibration
  385. if USE_PIR_TRT:
  386. trt_save_path = cache_dir / "trt" / self.model_file_prefix
  387. _convert_trt(
  388. self._option.model_name,
  389. self._option.run_mode,
  390. model_file,
  391. params_file,
  392. trt_save_path,
  393. self._option.trt_dynamic_shapes,
  394. self._option.trt_dynamic_shape_input_data,
  395. )
  396. model_file = trt_save_path.with_suffix(".json")
  397. params_file = trt_save_path.with_suffix(".pdiparams")
  398. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  399. else:
  400. PRECISION_MAP = {
  401. "trt_int8": lazy_paddle.inference.Config.Precision.Int8,
  402. "trt_fp32": lazy_paddle.inference.Config.Precision.Float32,
  403. "trt_fp16": lazy_paddle.inference.Config.Precision.Half,
  404. }
  405. config = lazy_paddle.inference.Config(str(model_file), str(params_file))
  406. config.set_optim_cache_dir(str(cache_dir / "optim_cache"))
  407. config.enable_use_gpu(100, self._option.device_id)
  408. config.enable_tensorrt_engine(
  409. workspace_size=self._option.trt_max_workspace_size,
  410. max_batch_size=self._option.trt_max_batch_size,
  411. min_subgraph_size=self._option.trt_min_subgraph_size,
  412. precision_mode=PRECISION_MAP[self._option.run_mode],
  413. use_static=self._option.trt_use_static,
  414. use_calib_mode=self._option.trt_use_calib_mode,
  415. )
  416. if self._option.trt_use_dynamic_shapes:
  417. if self._option.trt_collect_shape_range_info:
  418. # NOTE: We always use a shape range info file.
  419. if self._option.trt_shape_range_info_path is not None:
  420. trt_shape_range_info_path = Path(
  421. self._option.trt_shape_range_info_path
  422. )
  423. else:
  424. trt_shape_range_info_path = cache_dir / "shape_range_info.pbtxt"
  425. should_collect_shape_range_info = True
  426. if not trt_shape_range_info_path.exists():
  427. trt_shape_range_info_path.parent.mkdir(
  428. parents=True, exist_ok=True
  429. )
  430. logging.info(
  431. f"Shape range info will be collected into {trt_shape_range_info_path}"
  432. )
  433. elif self._option.trt_discard_cached_shape_range_info:
  434. trt_shape_range_info_path.unlink()
  435. logging.info(
  436. f"The shape range info file ({trt_shape_range_info_path}) has been removed, and the shape range info will be re-collected."
  437. )
  438. else:
  439. logging.info(
  440. f"A shape range info file ({trt_shape_range_info_path}) already exists. There is no need to collect the info again."
  441. )
  442. should_collect_shape_range_info = False
  443. if should_collect_shape_range_info:
  444. _collect_trt_shape_range_info(
  445. str(model_file),
  446. str(params_file),
  447. self._option.device_id,
  448. str(trt_shape_range_info_path),
  449. self._option.trt_dynamic_shapes,
  450. self._option.trt_dynamic_shape_input_data,
  451. )
  452. config.enable_tuned_tensorrt_dynamic_shape(
  453. str(trt_shape_range_info_path),
  454. self._option.trt_allow_rebuild_at_runtime,
  455. )
  456. else:
  457. if self._option.trt_dynamic_shapes is not None:
  458. min_shapes, opt_shapes, max_shapes = {}, {}, {}
  459. for (
  460. key,
  461. shapes,
  462. ) in self._option.trt_dynamic_shapes.items():
  463. min_shapes[key] = shapes[0]
  464. opt_shapes[key] = shapes[1]
  465. max_shapes[key] = shapes[2]
  466. config.set_trt_dynamic_shape_info(
  467. min_shapes, max_shapes, opt_shapes
  468. )
  469. else:
  470. raise RuntimeError("No dynamic shape information provided")
  471. return config