|
| 1 | +import os |
| 2 | +import numpy as np |
| 3 | +import torch |
| 4 | + |
| 5 | +try: |
| 6 | + from openvino.inference_engine import IECore, StatusCode |
| 7 | +except ImportError: |
| 8 | + pass |
| 9 | + |
| 10 | +class OpenVINOModel: |
| 11 | + |
| 12 | + def __init__(self, model, half, dirname): |
| 13 | + self.model = model |
| 14 | + self.alphabet = model.alphabet |
| 15 | + |
| 16 | + onnx_path = os.path.join(dirname, model.config['model']) + '.onnx' |
| 17 | + model_name = model.config['model'] + ('_fp16' if half else '') |
| 18 | + xml_path, bin_path = [os.path.join(dirname, model_name) + ext for ext in ['.xml', '.bin']] |
| 19 | + if not os.path.exists(xml_path) or not os.path.exists(bin_path): |
| 20 | + |
| 21 | + # Convert to ONNX |
| 22 | + if not os.path.exists(onnx_path): |
| 23 | + inp = torch.randn(1, 1, 1000) # Just dummy input shape. We will reshape model later |
| 24 | + model.eval() |
| 25 | + with torch.no_grad(): |
| 26 | + torch.onnx.export(model, inp, onnx_path, |
| 27 | + input_names=['input'], |
| 28 | + output_names=['output'], |
| 29 | + operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK) |
| 30 | + |
| 31 | + # Convert to IR |
| 32 | + import mo_onnx |
| 33 | + import subprocess |
| 34 | + subprocess.call([mo_onnx.__file__, |
| 35 | + '--input_model', onnx_path, |
| 36 | + '--extension', os.path.join(os.path.dirname(__file__), 'mo_extension'), |
| 37 | + '--keep_shape_ops', |
| 38 | + '--model_name', model_name, |
| 39 | + '--data_type', 'FP16' if half else 'FP32', |
| 40 | + '--input_shape=[1,1,1,1000]', |
| 41 | + '--output_dir', dirname]) |
| 42 | + |
| 43 | + self.ie = IECore() |
| 44 | + self.net = self.ie.read_network(xml_path, bin_path) |
| 45 | + self.exec_net = None |
| 46 | + |
| 47 | + |
| 48 | + def eval(self): |
| 49 | + pass |
| 50 | + |
| 51 | + |
| 52 | + def half(self): |
| 53 | + return self |
| 54 | + |
| 55 | + |
| 56 | + def to(self, device): |
| 57 | + self.device = str(device).upper() |
| 58 | + |
| 59 | + |
| 60 | + def __call__(self, data): |
| 61 | + data = np.expand_dims(data, axis=2) # 1D->2D |
| 62 | + batch_size = data.shape[0] |
| 63 | + if not self.exec_net: |
| 64 | + inp_shape = list(data.shape) |
| 65 | + inp_shape[0] = 1 # We will run the batch asynchronously |
| 66 | + self.net.reshape({'input': inp_shape}) |
| 67 | + config = {} |
| 68 | + if self.device == 'CPU': |
| 69 | + config={'CPU_THROUGHPUT_STREAMS': 'CPU_THROUGHPUT_AUTO'} |
| 70 | + self.exec_net = self.ie.load_network(self.net, self.device, |
| 71 | + config=config, num_requests=0) |
| 72 | + |
| 73 | + # List that maps infer requests to index of processed chunk from batch. |
| 74 | + # -1 means that request has not been started yet. |
| 75 | + infer_request_input_id = [-1] * len(self.exec_net.requests) |
| 76 | + output = np.zeros([batch_size] + self.net.outputs['output'].shape[1:], dtype=np.float32) |
| 77 | + |
| 78 | + for inp_id in range(batch_size): |
| 79 | + # Get idle infer request |
| 80 | + infer_request_id = self.exec_net.get_idle_request_id() |
| 81 | + if infer_request_id < 0: |
| 82 | + status = self.exec_net.wait(num_requests=1) |
| 83 | + if status != StatusCode.OK: |
| 84 | + raise Exception("Wait for idle request failed!") |
| 85 | + infer_request_id = self.exec_net.get_idle_request_id() |
| 86 | + if infer_request_id < 0: |
| 87 | + raise Exception("Invalid request id!") |
| 88 | + |
| 89 | + out_id = infer_request_input_id[infer_request_id] |
| 90 | + request = self.exec_net.requests[infer_request_id] |
| 91 | + |
| 92 | + # Copy output prediction |
| 93 | + if out_id != -1: |
| 94 | + output[out_id] = request.output_blobs['output'].buffer |
| 95 | + |
| 96 | + # Start this request on new data |
| 97 | + infer_request_input_id[infer_request_id] = inp_id |
| 98 | + request.async_infer({'input': data[inp_id]}) |
| 99 | + inp_id += 1 |
| 100 | + |
| 101 | + # Wait for the rest of requests |
| 102 | + status = self.exec_net.wait() |
| 103 | + if status != StatusCode.OK: |
| 104 | + raise Exception("Wait for idle request failed!") |
| 105 | + for infer_request_id, out_id in enumerate(infer_request_input_id): |
| 106 | + request = self.exec_net.requests[infer_request_id] |
| 107 | + output[out_id] = request.output_blobs['output'].buffer |
| 108 | + |
| 109 | + output = np.squeeze(output, axis=2) # 2D->1D |
| 110 | + return torch.tensor(output) |
| 111 | + |
| 112 | + |
| 113 | + def decode(self, post, beamsize): |
| 114 | + return self.model.decode(post, beamsize=beamsize) |
0 commit comments