"""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