File size: 2,656 Bytes
fd280c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""Load a pinned local graph on the explicitly selected runtime."""
from hashlib import sha256

import numpy as np


def digest(path):
    with path.open("rb") as stream:
        checksum = sha256()
        for piece in iter(lambda: stream.read(1024 * 1024), b""):
            checksum.update(piece)
    return checksum.hexdigest()


class Graphs:
    def __init__(self, backend, prepare=None):
        self.backend = backend
        self.artifact_paths = set()
        if backend == "cpu":
            import onnxruntime as ort

            self.ort = ort
            self.identity = {"backend": "cpu", "runtime": ort.__version__}
        elif backend == "ncs1":
            if prepare is None:
                raise ValueError("The NCS1 runtime requires a device identity probe")
            identity = prepare()
            if identity.get("boot_usb_id") != "03E7:2150":
                raise RuntimeError("The original NCS1 must be present in its cold USB state")
            from openvino.inference_engine import IECore, get_version

            self.core = IECore()
            self.identity = {"backend": "ncs1", "runtime": get_version(), "device": identity}
        else:
            raise ValueError("Select either the cpu or ncs1 backend")

    def load(self, onnx, ir, *, output=None, packed=False):
        if self.backend == "cpu":
            opts = self.ort.SessionOptions()
            opts.intra_op_num_threads = 1
            net = self.ort.InferenceSession(str(onnx), opts, providers=["CPUExecutionProvider"])
            self.artifact_paths.add(onnx)
            target = output or net.get_outputs()[0].name
            return lambda data: net.run([target], data)[0]

        graph = self.core.read_network(model=str(ir.with_suffix(".xml")), weights=str(ir.with_suffix(".bin")))
        if packed:
            ports = graph.input_info if hasattr(graph, "input_info") else graph.inputs
            for port in list(ports.values()) + list(graph.outputs.values()):
                port.precision = "FP16"
        target = output or next(iter(graph.outputs))
        net = self.core.load_network(graph, "MYRIAD", num_requests=1)
        self.artifact_paths.update((ir.with_suffix(".xml"), ir.with_suffix(".bin")))

        def predict(data):
            if packed:
                data = {name: np.ascontiguousarray(value, dtype=np.float16).view(np.int16)
                        for name, value in data.items()}
            result = net.infer(data)[target]
            if packed and result.dtype == np.int16:
                result = result.view(np.float16)
            return result.astype(np.float32, copy=True)

        return predict