|
| 1 | +import traceback |
| 2 | +from pathlib import Path |
| 3 | +from typing import Any, Dict, List |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +try: |
| 8 | + import openvino as ov |
| 9 | +except ImportError: |
| 10 | + raise ImportError( |
| 11 | + "openvino is not installed. Please install it with: pip install openvino" |
| 12 | + ) |
| 13 | + |
| 14 | +from omegaconf import DictConfig |
| 15 | + |
| 16 | +from ...model_handler.utils import ModelProcessor |
| 17 | +from ...utils.logger import Logger |
| 18 | +from ...utils.typings import RapidLayoutInput |
| 19 | +from ..base import InferSession |
| 20 | + |
| 21 | + |
| 22 | +class OpenVINOInferSession(InferSession): |
| 23 | + def __init__(self, cfg: RapidLayoutInput): |
| 24 | + self.logger = Logger(logger_name=__name__).get_log() |
| 25 | + |
| 26 | + if cfg.model_dir_or_path is None: |
| 27 | + model_path = ModelProcessor.get_model_path(cfg.model_type) |
| 28 | + else: |
| 29 | + model_path = Path(cfg.model_dir_or_path) |
| 30 | + |
| 31 | + self._verify_model(model_path) |
| 32 | + self.logger.info(f"Using {model_path}") |
| 33 | + |
| 34 | + engine_cfg = self.update_params( |
| 35 | + self.engine_cfg[cfg.engine_type.value], cfg.engine_cfg |
| 36 | + ) |
| 37 | + core = ov.Core() |
| 38 | + |
| 39 | + self.model = core.read_model(model=str(model_path)) |
| 40 | + self.input_tensor = self.model.inputs[0] |
| 41 | + self.output_tensors = self.model.outputs |
| 42 | + |
| 43 | + device = engine_cfg.get('device', 'CPU') |
| 44 | + ov_config = self._init_config(engine_cfg) |
| 45 | + self.compiled_model = core.compile_model( |
| 46 | + self.model, |
| 47 | + device, |
| 48 | + ov_config, |
| 49 | + ) |
| 50 | + self.infer_request = self.compiled_model.create_infer_request() |
| 51 | + |
| 52 | + def _init_config(self, cfg: DictConfig) -> Dict[str, str]: |
| 53 | + config = {} |
| 54 | + engine_cfg = cfg.get("engine_cfg", {}) |
| 55 | + |
| 56 | + def _set(k, v, *, cast=str): |
| 57 | + if v is not None and v != -1: |
| 58 | + config[k] = cast(v) |
| 59 | + |
| 60 | + _set("INFERENCE_NUM_THREADS", |
| 61 | + engine_cfg.get("inference_num_threads", -1), |
| 62 | + cast=lambda x: str(min(x, os.cpu_count())) if x > 0 else None) |
| 63 | + |
| 64 | + _set("PERFORMANCE_HINT", |
| 65 | + engine_cfg.get("performance_hint")) |
| 66 | + _set("PERFORMANCE_HINT_NUM_REQUESTS", |
| 67 | + engine_cfg.get("performance_num_requests")) |
| 68 | + _set("ENABLE_CPU_PINNING", |
| 69 | + engine_cfg.get("enable_cpu_pinning")) |
| 70 | + _set("NUM_STREAMS", |
| 71 | + engine_cfg.get("num_streams")) |
| 72 | + _set("ENABLE_HYPER_THREADING", |
| 73 | + engine_cfg.get("enable_hyper_threading")) |
| 74 | + _set("SCHEDULING_CORE_TYPE", |
| 75 | + engine_cfg.get("scheduling_core_type")) |
| 76 | + |
| 77 | + if config: |
| 78 | + self.logger.info("OpenVINO runtime config: %s", config) |
| 79 | + return config |
| 80 | + |
| 81 | + def __call__(self, input_content: np.ndarray) -> Any: |
| 82 | + try: |
| 83 | + input_tensor_name = self.input_tensor.get_any_name() |
| 84 | + self.infer_request.set_tensor(input_tensor_name, ov.Tensor(input_content)) |
| 85 | + self.infer_request.infer() |
| 86 | + |
| 87 | + outputs = [] |
| 88 | + for output_tensor in self.output_tensors: |
| 89 | + output_tensor_name = output_tensor.get_any_name() |
| 90 | + output = self.infer_request.get_tensor(output_tensor_name).data |
| 91 | + outputs.append(output) |
| 92 | + |
| 93 | + return outputs |
| 94 | + |
| 95 | + except Exception as e: |
| 96 | + error_info = traceback.format_exc() |
| 97 | + raise OpenVINOError(error_info) from e |
| 98 | + |
| 99 | + def get_input_names(self) -> List[str]: |
| 100 | + return [tensor.get_any_name() for tensor in self.model.inputs] |
| 101 | + |
| 102 | + def get_output_names(self) -> List[str]: |
| 103 | + return [tensor.get_any_name() for tensor in self.model.outputs] |
| 104 | + |
| 105 | + @property |
| 106 | + def characters(self): |
| 107 | + return self.get_character_list() |
| 108 | + |
| 109 | + def get_character_list(self, key: str = "character") -> List[str]: |
| 110 | + val = self.model.get_rt_info()["framework"][key] |
| 111 | + return val.value.splitlines() |
| 112 | + |
| 113 | + def have_key(self, key: str = "character") -> bool: |
| 114 | + try: |
| 115 | + rt_info = self.model.get_rt_info() |
| 116 | + return key in rt_info |
| 117 | + except: |
| 118 | + return False |
| 119 | + |
| 120 | + |
| 121 | +class OpenVINOError(Exception): |
| 122 | + pass |
0 commit comments