|
| 1 | +import os |
| 2 | +import io |
| 3 | +import numpy as np |
| 4 | +import torch |
| 5 | + |
| 6 | +try: |
| 7 | + from openvino.inference_engine import IECore, StatusCode |
| 8 | + from .loader import convert_to_2d |
| 9 | +except ImportError: |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +def load_openvino_model(model, dirname): |
| 14 | + package = model.config['model']['package'] |
| 15 | + if package == 'bonito.ctc': |
| 16 | + return OpenVINOCTCModel(model, dirname) |
| 17 | + elif package == 'bonito.crf': |
| 18 | + return OpenVINOCRFModel(model, dirname) |
| 19 | + else: |
| 20 | + raise Exception('Unknown model configuration: ' + package) |
| 21 | + |
| 22 | + |
| 23 | +class OpenVINOModel: |
| 24 | + |
| 25 | + def __init__(self, model, dirname): |
| 26 | + self.model = model |
| 27 | + self.alphabet = model.alphabet |
| 28 | + self.parameters = model.parameters |
| 29 | + self.stride = model.stride |
| 30 | + self.net = None |
| 31 | + self.exec_net = None |
| 32 | + self.dirname = dirname |
| 33 | + self.ie = IECore() |
| 34 | + |
| 35 | + |
| 36 | + def eval(self): |
| 37 | + pass |
| 38 | + |
| 39 | + |
| 40 | + def half(self): |
| 41 | + return self |
| 42 | + |
| 43 | + |
| 44 | + @property |
| 45 | + def config(self): |
| 46 | + return self.model.config |
| 47 | + |
| 48 | + |
| 49 | + def to(self, device): |
| 50 | + self.device = str(device).upper() |
| 51 | + |
| 52 | + """ |
| 53 | + Call this method once to initialize executable network |
| 54 | + """ |
| 55 | + def init_model(self, model, inp_shape): |
| 56 | + # First, we try to check if there is IR on disk. If not - load model in runtime |
| 57 | + xml_path, bin_path = [os.path.join(self.dirname, 'model') + ext for ext in ['.xml', '.bin']] |
| 58 | + if os.path.exists(xml_path) and os.path.exists(bin_path): |
| 59 | + self.net = self.ie.read_network(xml_path, bin_path) |
| 60 | + else: |
| 61 | + # Convert model to ONNX buffer |
| 62 | + buf = io.BytesIO() |
| 63 | + inp = torch.randn(inp_shape) |
| 64 | + torch.onnx.export(model, inp, buf, input_names=['input'], output_names=['output'], |
| 65 | + opset_version=11) |
| 66 | + |
| 67 | + # Import network from memory buffer |
| 68 | + self.net = self.ie.read_network(buf.getvalue(), b'', init_from_buffer=True) |
| 69 | + |
| 70 | + # Load model to device |
| 71 | + config = {} |
| 72 | + if self.device == 'CPU': |
| 73 | + config={'CPU_THROUGHPUT_STREAMS': 'CPU_THROUGHPUT_AUTO'} |
| 74 | + self.exec_net = self.ie.load_network(self.net, self.device, |
| 75 | + config=config, num_requests=0) |
| 76 | + |
| 77 | + |
| 78 | + def process(self, data): |
| 79 | + data = data.float() |
| 80 | + batch_size = data.shape[0] |
| 81 | + inp_shape = list(data.shape) |
| 82 | + inp_shape[0] = 1 # We will run the batch asynchronously |
| 83 | + |
| 84 | + # List that maps infer requests to index of processed chunk from batch. |
| 85 | + # -1 means that request has not been started yet. |
| 86 | + infer_request_input_id = [-1] * len(self.exec_net.requests) |
| 87 | + out_shape = self.net.outputs['output'].shape |
| 88 | + # CTC network produces 1xWxNxC |
| 89 | + output = np.zeros([out_shape[-3], batch_size, out_shape[-1]], dtype=np.float32) |
| 90 | + |
| 91 | + for inp_id in range(batch_size): |
| 92 | + # Get idle infer request |
| 93 | + infer_request_id = self.exec_net.get_idle_request_id() |
| 94 | + if infer_request_id < 0: |
| 95 | + status = self.exec_net.wait(num_requests=1) |
| 96 | + if status != StatusCode.OK: |
| 97 | + raise Exception("Wait for idle request failed!") |
| 98 | + infer_request_id = self.exec_net.get_idle_request_id() |
| 99 | + if infer_request_id < 0: |
| 100 | + raise Exception("Invalid request id!") |
| 101 | + |
| 102 | + out_id = infer_request_input_id[infer_request_id] |
| 103 | + request = self.exec_net.requests[infer_request_id] |
| 104 | + |
| 105 | + # Copy output prediction |
| 106 | + if out_id != -1: |
| 107 | + output[:,out_id:out_id+1] = request.output_blobs['output'].buffer |
| 108 | + |
| 109 | + # Start this request on new data |
| 110 | + infer_request_input_id[infer_request_id] = inp_id |
| 111 | + request.async_infer({'input': data[inp_id]}) |
| 112 | + inp_id += 1 |
| 113 | + |
| 114 | + # Wait for the rest of requests |
| 115 | + status = self.exec_net.wait() |
| 116 | + if status != StatusCode.OK: |
| 117 | + raise Exception("Wait for idle request failed!") |
| 118 | + for infer_request_id, out_id in enumerate(infer_request_input_id): |
| 119 | + if out_id == -1: |
| 120 | + continue |
| 121 | + request = self.exec_net.requests[infer_request_id] |
| 122 | + output[:,out_id:out_id+1] = request.output_blobs['output'].buffer |
| 123 | + |
| 124 | + return torch.tensor(output) |
| 125 | + |
| 126 | + |
| 127 | +class OpenVINOCTCModel(OpenVINOModel): |
| 128 | + |
| 129 | + def __init__(self, model, dirname): |
| 130 | + super().__init__(model, dirname) |
| 131 | + |
| 132 | + |
| 133 | + def __call__(self, data): |
| 134 | + data = data.unsqueeze(2) # 1D->2D |
| 135 | + if self.exec_net is None: |
| 136 | + convert_to_2d(self.model) |
| 137 | + self.init_model(self.model, [1, 1, 1, data.shape[-1]]) |
| 138 | + |
| 139 | + return self.process(data) |
| 140 | + |
| 141 | + |
| 142 | + def decode(self, x, beamsize=5, threshold=1e-3, qscores=False, return_path=False): |
| 143 | + return self.model.decode(x, beamsize=beamsize, threshold=threshold, |
| 144 | + qscores=qscores, return_path=return_path) |
| 145 | + |
| 146 | + |
| 147 | +class OpenVINOCRFModel(OpenVINOModel): |
| 148 | + |
| 149 | + def __init__(self, model, dirname): |
| 150 | + super().__init__(model, dirname) |
| 151 | + self.seqdist = model.seqdist |
| 152 | + |
| 153 | + |
| 154 | + def __call__(self, data): |
| 155 | + if self.exec_net is None: |
| 156 | + self.init_model(self.model.encoder, [1, 1, data.shape[-1]]) |
| 157 | + |
| 158 | + return self.process(data) |
| 159 | + |
| 160 | + |
| 161 | + def decode(self, x): |
| 162 | + return self.model.decode(x) |
| 163 | + |
| 164 | + |
| 165 | + def decode_batch(self, x): |
| 166 | + return self.model.decode_batch(x) |
0 commit comments