|
| 1 | +# This script provides a method which builds OpenVINO network in runtime |
| 2 | +import numpy as np |
| 3 | +from openvino.inference_engine import IECore, IENetwork |
| 4 | + |
| 5 | +import ngraph.opset4 as ng |
| 6 | +from ngraph.impl.op import Parameter |
| 7 | +from ngraph.impl import Function, Shape, Type |
| 8 | + |
| 9 | +import torch |
| 10 | +from torch.autograd import Variable |
| 11 | + |
| 12 | + |
| 13 | +nodes = {} |
| 14 | +out = None |
| 15 | + |
| 16 | +def forward_hook(self, inputs, output): |
| 17 | + global out |
| 18 | + layer_type = self.__class__.__name__ |
| 19 | + |
| 20 | + params = [value.numpy() for value in self.state_dict().values()] |
| 21 | + |
| 22 | + inp = nodes[inputs[0].data_ptr()] |
| 23 | + if layer_type == 'Conv1d': |
| 24 | + weights = np.expand_dims(params[0], axis=2) |
| 25 | + if self.groups == 1: |
| 26 | + out = ng.convolution(inp, weights, |
| 27 | + [1, self.stride[0]], |
| 28 | + [0, self.padding[0]], |
| 29 | + [0, self.padding[0]], |
| 30 | + [1, self.dilation[0]]) |
| 31 | + |
| 32 | + else: |
| 33 | + weights = weights.reshape(self.groups, weights.shape[0] // self.groups, weights.shape[1], weights.shape[2], weights.shape[3]) |
| 34 | + out = ng.group_convolution(inp, weights, |
| 35 | + [1, self.stride[0]], |
| 36 | + [0, self.padding[0]], |
| 37 | + [0, self.padding[0]], |
| 38 | + [1, self.dilation[0]]) |
| 39 | + if len(params) > 1: |
| 40 | + assert(len(params) == 2) |
| 41 | + bias = params[1].reshape(1, params[1].shape[0], 1, 1) |
| 42 | + out = ng.add(out, bias) |
| 43 | + |
| 44 | + elif layer_type == 'BatchNorm1d': |
| 45 | + out = ng.batch_norm_inference(inp, params[0], params[1], params[2], params[3], self.eps) |
| 46 | + elif layer_type == 'Swish': |
| 47 | + out = ng.swish(inp) |
| 48 | + elif layer_type == 'Add': |
| 49 | + out = ng.add(inp, nodes[inputs[1].data_ptr()]) |
| 50 | + elif layer_type == 'Dropout': |
| 51 | + return |
| 52 | + elif layer_type == 'Permute': |
| 53 | + order = [] |
| 54 | + # 1D to 2D: i.e. (2, 0, 1) -> (2, 3, 0, 1) |
| 55 | + for d in self.dims: |
| 56 | + assert(d <= 2) |
| 57 | + order.append(d) |
| 58 | + if d == 2: |
| 59 | + order.append(3) |
| 60 | + out = ng.transpose(inp, order) |
| 61 | + else: |
| 62 | + raise Exception('Unknown layer type: ' + layer_type) |
| 63 | + |
| 64 | + nodes[output.data_ptr()] = out |
| 65 | + |
| 66 | + |
| 67 | +def sanity_check(net, inp, ref): |
| 68 | + ie = IECore() |
| 69 | + exec_net = ie.load_network(net, 'CPU') |
| 70 | + ie_out = exec_net.infer({'input': inp.numpy()}) |
| 71 | + ie_out = next(iter(ie_out.values())) |
| 72 | + |
| 73 | + ref = ref.numpy().reshape(ie_out.shape) |
| 74 | + diff = np.max(np.abs(ie_out - ref)) |
| 75 | + print('PyTorch / OpenVINO diff:', diff) |
| 76 | + print('Reference values range: [{}, {}]'.format(np.min(ref), np.max(ref))) |
| 77 | + if diff > 1.1e-4: |
| 78 | + raise Exception('Sanity check failed with diff', diff) |
| 79 | + |
| 80 | + |
| 81 | +def torch2openvino(model): |
| 82 | + with torch.no_grad(): |
| 83 | + model.eval() |
| 84 | + hooks = [] |
| 85 | + for module in model.modules(): |
| 86 | + if len([m for m in module.modules()]) != 1: |
| 87 | + continue |
| 88 | + hooks.append(module.register_forward_hook(forward_hook)) |
| 89 | + |
| 90 | + # Just a dummy input to make forward pass |
| 91 | + inp = Variable(torch.randn([1, 1, 1000])) |
| 92 | + |
| 93 | + param = Parameter(Type.f32, Shape([1, 1, 1, 1000])) |
| 94 | + nodes[inp.data_ptr()] = param |
| 95 | + ref = model(inp) |
| 96 | + |
| 97 | + for hook in hooks: |
| 98 | + hook.remove() |
| 99 | + |
| 100 | + out_node = ng.log(ng.softmax(out, axis=3)) |
| 101 | + |
| 102 | + param.set_friendly_name('input') |
| 103 | + out_node.set_friendly_name('output') |
| 104 | + func = Function([out_node], [param], '') |
| 105 | + |
| 106 | + caps = Function.to_capsule(func) |
| 107 | + net = IENetwork(caps) |
| 108 | + |
| 109 | + # Uncomment to perform conversion check |
| 110 | + # sanity_check(net, inp, ref) |
| 111 | + |
| 112 | + return net |
0 commit comments