File size: 14,540 Bytes
d9a3db2
89e8bbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6b20bd
 
 
 
 
 
 
 
 
d9a3db2
 
89e8bbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a3db2
89e8bbb
d9a3db2
 
89e8bbb
 
 
 
d9a3db2
 
89e8bbb
 
 
 
 
 
 
 
d9a3db2
 
 
c6b20bd
 
 
 
 
 
d9a3db2
 
 
 
89e8bbb
 
 
 
 
d9a3db2
 
 
89e8bbb
 
 
 
 
d9a3db2
 
89e8bbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a3db2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89e8bbb
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""The whole sam3edge-micro runtime: two ONNX graphs (three with masks), a vocabulary file and numpy."""

from __future__ import annotations

import json
import os
import time
from typing import Dict, List, Optional, Sequence

import numpy as np
from PIL import Image

FORMAT = 1
HEADROOM_MB = 200


def available_memory_mb() -> Optional[int]:
    """MemAvailable on Linux; None where it cannot be read."""
    try:
        with open("/proc/meminfo") as f:
            for line in f:
                if line.startswith("MemAvailable:"):
                    return int(line.split()[1]) // 1024
    except OSError:
        pass
    return None


def _sigmoid(x: np.ndarray) -> np.ndarray:
    return 1.0 / (1.0 + np.exp(-x))


def _nms(boxes: np.ndarray, scores: np.ndarray, iou: float) -> List[int]:
    """Indices of the boxes to keep, best first."""
    order = list(np.argsort(-scores))
    areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
    keep: List[int] = []
    while order:
        i = order.pop(0)
        keep.append(int(i))
        if not order:
            break
        rest = np.array(order)
        x0 = np.maximum(boxes[i, 0], boxes[rest, 0])
        y0 = np.maximum(boxes[i, 1], boxes[rest, 1])
        x1 = np.minimum(boxes[i, 2], boxes[rest, 2])
        y1 = np.minimum(boxes[i, 3], boxes[rest, 3])
        inter = np.clip(x1 - x0, 0, None) * np.clip(y1 - y0, 0, None)
        overlap = inter / np.maximum(areas[i] + areas[rest] - inter, 1e-9)
        order = [int(j) for j, o in zip(rest, overlap) if o <= iou]
    return keep


def _cuda_session(path: str, ort, options, device: int):
    """A graph on an NVIDIA GPU.  ONNX Runtime falls back to the CPU without saying so
    when its CUDA libraries are missing, so the result is checked."""
    if hasattr(ort, "preload_dlls"):  # finds the CUDA and cuDNN wheels pip installed
        try:
            ort.preload_dlls()
        except Exception:
            pass
    settings = {
        "device_id": str(device),
        "arena_extend_strategy": "kSameAsRequested",  # do not grab more memory than is asked for
        "cudnn_conv_algo_search": "HEURISTIC",  # the exhaustive search costs seconds and memory
    }
    session = ort.InferenceSession(
        path, options, providers=[("CUDAExecutionProvider", settings), "CPUExecutionProvider"]
    )
    if "CUDAExecutionProvider" not in session.get_providers():
        raise RuntimeError(
            "ONNX Runtime did not load its CUDA provider, so this would run on the CPU. Install "
            'the GPU build with its libraries (pip install "onnxruntime-gpu[cuda,cudnn]") and check '
            "that nvidia-smi works."
        )
    return session


def _npu_session(path: str, ort):
    """The image graph on a Hexagon NPU, through the onnxruntime-qnn package.

    The compiled form is cached beside the graph, since compiling takes far
    longer than running.  Anything the NPU cannot take falls back to the CPU.
    """
    if not os.path.isfile(path):
        raise FileNotFoundError(
            f"{path} is missing: export the bundle with calibration images to get the NPU graph"
        )
    try:
        import onnxruntime_qnn as qnn
    except ImportError:
        raise RuntimeError("the NPU needs the onnxruntime-qnn package") from None
    library = os.path.dirname(qnn.get_library_path())
    current = os.environ.get("ADSP_LIBRARY_PATH", "")
    if library not in current.split(";"):  # where the DSP finds its half of the backend
        os.environ["ADSP_LIBRARY_PATH"] = ";".join(p for p in (library, current) if p)
    try:
        ort.register_execution_provider_library(qnn.get_ep_name(), qnn.get_library_path())
    except Exception:  # already registered in this process
        pass
    options = ort.SessionOptions()
    cached = path[: -len(".onnx")] + ".npu-ctx.onnx"
    source = path
    if os.path.isfile(cached) and os.path.getmtime(cached) >= os.path.getmtime(path):
        source = cached
    else:
        options.add_session_config_entry("ep.context_enable", "1")
        options.add_session_config_entry("ep.context_file_path", cached)
        options.add_session_config_entry("ep.context_embed_mode", "0")
    # A plug-in provider is chosen by device, not by name: passing its name in
    # ``providers=`` is accepted and then quietly ignored (everything runs on the CPU).
    devices = [d for d in ort.get_ep_devices() if d.ep_name == qnn.get_ep_name()]
    if not devices:
        raise RuntimeError("onnxruntime-qnn found no NPU on this machine")
    options.add_provider_for_devices(
        devices, {"backend_path": qnn.get_qnn_htp_path(), "htp_performance_mode": "burst"}
    )
    session = ort.InferenceSession(source, options)
    if qnn.get_ep_name() not in session.get_providers():
        raise RuntimeError("the NPU backend did not take the image graph")
    return session


class Micro:
    """Runs one bundle.  ``detect`` is the only thing most callers need.

    ``provider`` is where the graphs run: ``"cpu"`` (default), ``"cuda"`` (an NVIDIA GPU
    through onnxruntime-gpu) or ``"npu"`` (the image encoder on a Qualcomm Hexagon NPU
    through onnxruntime-qnn).  ``npu=True`` is the older spelling of ``provider="npu"``.
    """

    def __init__(
        self,
        bundle: str,
        threads: Optional[int] = None,
        force: bool = False,
        npu: bool = False,
        provider: Optional[str] = None,
        device: int = 0,
    ):
        provider = provider or ("npu" if npu else "cpu")
        if provider not in ("cpu", "cuda", "npu"):
            raise ValueError("provider must be cpu, cuda or npu")
        self.provider = provider
        with open(os.path.join(bundle, "micro.json"), encoding="utf-8") as f:
            self.meta = json.load(f)
        if self.meta.get("format") != FORMAT:
            raise ValueError(f"bundle format {self.meta.get('format')!r} is not {FORMAT}")
        self.resolution = int(self.meta["resolution"])
        self.concepts: List[str] = list(self.meta["concepts"])
        self.threshold = float(self.meta.get("threshold", 0.3))
        self.nms_iou = self.meta.get("nms_iou", 0.5)

        # On a board with no swap, running out of memory stalls everything on it
        # rather than failing: refuse up front instead.
        size_mb = sum(
            os.path.getsize(os.path.join(bundle, f)) for f in os.listdir(bundle)
        ) // (1024 * 1024)
        self.memory_needed_mb = 150 + 2 * size_mb
        have = available_memory_mb()
        if provider != "cuda" and have is not None and not force and have < self.memory_needed_mb + HEADROOM_MB:
            raise MemoryError(
                f"this bundle needs about {self.memory_needed_mb} MB and the board has {have} MB "
                "available; free some memory or pass force=True"
            )

        import onnxruntime as ort

        options = ort.SessionOptions()
        options.intra_op_num_threads = threads or (os.cpu_count() or 1)
        options.inter_op_num_threads = 1
        options.add_session_config_entry("session.intra_op.allow_spinning", "0")
        options.enable_cpu_mem_arena = False  # give memory back between calls
        options.log_severity_level = 3  # errors only: the graphs load with harmless shape warnings
        def session(name: str, where: str):
            path = os.path.join(bundle, name)
            if where == "cuda":
                return _cuda_session(path, ort, options, device)
            return ort.InferenceSession(path, options, providers=["CPUExecutionProvider"])

        self.npu = provider == "npu"
        # A GPU has no kernels for an image graph stored in 8-bit weights: that one stays on the CPU.
        float_image = self.meta.get("precision", {}).get("image", "float32") == "float32"
        self.image_provider = provider if (provider != "cuda" or float_image) else "cpu"
        if self.npu:
            self._image = _npu_session(os.path.join(bundle, "image-npu.onnx"), ort)
        else:
            self._image = session("image.onnx", self.image_provider)
        self._detect = session("detect.onnx", "cuda" if provider == "cuda" else "cpu")
        # Masks are optional: the mask head is loaded the first time they are asked for.  It reads the
        # image encoder's last feature map ("trunk"); an NPU graph that does not give it hands the
        # image pass of a masks call to the CPU graph instead.
        self._image_gives_trunk = "trunk" in {o.name for o in self._image.get_outputs()}
        self.has_masks = os.path.isfile(os.path.join(bundle, "mask.onnx")) and (
            self._image_gives_trunk or (self.npu and os.path.isfile(os.path.join(bundle, "image.onnx")))
        )
        self._image_for_masks = None
        self._cpu_image_session = lambda: session("image.onnx", "cpu")
        self._mask = None
        self._mask_session = lambda: session("mask.onnx", "cuda" if provider == "cuda" else "cpu")
        vocab = np.load(os.path.join(bundle, "vocab.npz"))
        self._tokens = vocab["tokens"]  # concepts x tokens x 256
        self._masks = vocab["masks"]  # concepts x tokens, True = padding
        self.last: Dict[str, float] = {}

    def _preprocess(self, image: Image.Image) -> np.ndarray:
        rgb = image.convert("RGB").resize((self.resolution, self.resolution), Image.BILINEAR)
        x = np.asarray(rgb, dtype=np.float32) / 255.0
        return ((x - 0.5) / 0.5).transpose(2, 0, 1)[None]

    def encode_image(self, image: Image.Image) -> np.ndarray:
        start = time.perf_counter()
        level = self._image.run(["level"], {"image": self._preprocess(image)})[0]
        self.last = {"image_s": time.perf_counter() - start, "detect_s": 0.0}
        return level

    def detect(
        self,
        image: Image.Image,
        concepts: Optional[Sequence[str]] = None,
        threshold: Optional[float] = None,
        max_detections: int = 100,
        masks: bool = False,
    ) -> List[dict]:
        """Every instance of each concept, best first: ``concept``, ``score``, ``box_xyxy`` in the
        picture's pixels and, with ``masks=True``, ``mask`` (a boolean array the size of the picture).

        Concepts must come from the bundle's list (``micro.concepts``); the text
        encoder is not on the board, so anything else cannot be asked.
        """
        if masks and not self.has_masks:
            raise ValueError("this bundle has no mask head (mask.onnx): it returns boxes only")
        wanted = [" ".join(c.lower().split()) for c in (concepts or self.concepts)]
        unknown = [c for c in wanted if c not in self.concepts]
        if unknown:
            raise KeyError(
                f"not in this bundle's concept list: {unknown}; it has {self.concepts}"
            )
        threshold = self.threshold if threshold is None else threshold
        width, height = image.size
        trunk = None
        if masks:  # the mask head also reads the image encoder's last feature map
            start = time.perf_counter()
            encoder = self._image
            if not self._image_gives_trunk:
                if self._image_for_masks is None:
                    self._image_for_masks = self._cpu_image_session()
                encoder = self._image_for_masks
            trunk, level = encoder.run(["trunk", "level"], {"image": self._preprocess(image)})
            self.last = {"image_s": time.perf_counter() - start, "detect_s": 0.0}
        else:
            level = self.encode_image(image)
        self.last["mask_s"] = 0.0
        scale = np.array([width, height, width, height], dtype=np.float32)
        found: List[dict] = []
        start = time.perf_counter()
        for concept in wanted:
            index = self.concepts.index(concept)
            wanted_outputs = ["logits", "boxes", "presence"] + (["queries", "memory", "prompt", "prompt_mask"] if masks else [])
            out = dict(zip(wanted_outputs, self._detect.run(
                wanted_outputs,
                {
                    "feat": level,
                    "text_feats": self._tokens[index][:, None, :],
                    "text_mask": self._masks[index][None, :],
                },
            )))
            logits, boxes, presence = out["logits"], out["boxes"], out["presence"]
            scores = (_sigmoid(logits[0, :, 0]) * _sigmoid(presence.reshape(-1)[0])).astype(np.float32)
            keep = np.nonzero(scores > threshold)[0]
            if keep.size == 0:
                continue
            # best first, and no more candidates than the caller asked for (as sam3.edge does)
            keep = keep[np.argsort(-scores[keep])][:max_detections]
            cx, cy, w, h = boxes[0, keep].T
            xyxy = np.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], axis=1) * scale
            xyxy[:, 0::2] = np.clip(xyxy[:, 0::2], 0, width)
            xyxy[:, 1::2] = np.clip(xyxy[:, 1::2], 0, height)
            kept = (
                _nms(xyxy, scores[keep], float(self.nms_iou))
                if self.nms_iou is not None
                else list(np.argsort(-scores[keep]))
            )
            kept = kept[:max_detections]
            shapes = {}
            if masks and kept:
                mask_start = time.perf_counter()
                if self._mask is None:
                    self._mask = self._mask_session()
                    self._mask_inputs = {i.name for i in self._mask.get_inputs()}
                feed = {"trunk": trunk, "feat": level, "queries": out["queries"], "memory": out["memory"],
                        "prompt": out["prompt"], "prompt_mask": out["prompt_mask"]}
                mask_logits = self._mask.run(["masks"], {k: v for k, v in feed.items() if k in self._mask_inputs})[0][0]
                for i in kept:
                    small = Image.fromarray(np.ascontiguousarray(mask_logits[keep[i]], dtype=np.float32))
                    shapes[i] = np.asarray(small.resize((width, height), Image.BILINEAR)) > 0
                self.last["mask_s"] += time.perf_counter() - mask_start
            for i in kept:
                item = {
                    "concept": concept,
                    "score": round(float(scores[keep][i]), 4),
                    "box_xyxy": [round(float(v), 1) for v in xyxy[i]],
                }
                if masks:
                    item["mask"] = shapes[i]
                found.append(item)
        self.last["detect_s"] = time.perf_counter() - start - self.last["mask_s"]
        found.sort(key=lambda d: -d["score"])
        return found