File size: 1,913 Bytes
565b868
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
"""Small OpenVINO helpers: compile with timing, GPU memory statistics, cached models."""
import gc
import json
import os
import time

import numpy as np
import openvino as ov

CACHE = "/opt/mossimage/cache"


def make_core(cache=True):
    core = ov.Core()
    if cache:
        os.makedirs(CACHE, exist_ok=True)
        core.set_property({"CACHE_DIR": CACHE})
    return core


def gpu_mem(core):
    try:
        st = core.get_property("GPU", "GPU_MEMORY_STATISTICS")
        return {k: round(v / 2**20) for k, v in st.items()}  # MB
    except Exception as e:  # noqa: BLE001
        return {"err": repr(e)[:100]}


def gpu_mem_total_mb(core):
    m = gpu_mem(core)
    return sum(v for k, v in m.items() if isinstance(v, (int, float)) and k.startswith("usm_device")) if "err" not in m else -1


def compile_model(core, path, device, precision=None, reshape=None, extra=None, label=""):
    t0 = time.time()
    model = core.read_model(path)
    t_read = time.time() - t0
    if reshape:
        model.reshape(reshape)
    cfg = {}
    if precision:
        cfg["INFERENCE_PRECISION_HINT"] = precision
    if extra:
        cfg.update(extra)
    t1 = time.time()
    cm = core.compile_model(model, device, cfg)
    t_comp = time.time() - t1
    print(f"[compile] {label or os.path.basename(path)} on {device} prec={precision}: read {t_read:.1f}s compile {t_comp:.1f}s", flush=True)
    return cm, {"read_s": round(t_read, 2), "compile_s": round(t_comp, 2)}


def infer(cm, inputs, repeat=1):
    """inputs: dict name -> np array. Returns (first output ndarray, list of seconds)."""
    req = cm.create_infer_request()
    times = []
    out = None
    for _ in range(repeat):
        t = time.time()
        res = req.infer(inputs)
        times.append(time.time() - t)
        out = list(res.values())[0]
    return np.array(out), times


def release(*objs):
    for o in objs:
        del o
    gc.collect()