"""The whole sam3edge-mini runtime: four ONNX graphs, a tokenizer and numpy.""" from __future__ import annotations import json import os import time from collections import OrderedDict from typing import Dict, List, Optional, Sequence, Tuple import numpy as np from PIL import Image from .tokenizer import Tokenizer FORMAT = 1 HEADROOM_MB = 200 PROVIDERS = ("cpu", "cuda", "npu") 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. """ 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 Mini: """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; bundles with an ``image-npu.onnx`` only). A bundle may hold its image encoder in more than one form. The right one is picked for the provider; ``image_graph`` ("image", "image_fp32" or "image_npu") overrides that, for example to run the float encoder on a CPU. """ def __init__( self, bundle: str, threads: Optional[int] = None, force: bool = False, provider: str = "cpu", device: int = 0, text_cache: int = 256, image_graph: Optional[str] = None, ): if provider not in PROVIDERS: raise ValueError(f"provider must be one of {PROVIDERS}") with open(os.path.join(bundle, "mini.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}") files = self.meta["files"] self.resolution = int(self.meta["resolution"]) self.context_length = int(self.meta["context_length"]) self.threshold = float(self.meta.get("threshold", 0.5)) self.nms_iou = self.meta.get("nms_iou", 0.5) self.provider = provider # Which image graph: a GPU has no kernels for the 8-bit-weights form, an NPU # takes only the fixed-point one. image_key, image_provider = "image", provider if provider == "npu": if "image_npu" not in files: raise FileNotFoundError("this bundle has no image-npu.onnx; the NPU runs student encoders only") image_key = "image_npu" elif provider == "cuda" and self.meta["precision"].get("image") != "float32": if "image_fp32" in files: image_key = "image_fp32" else: image_provider = "cpu" # 8-bit weights: no GPU kernels, so it stays on the CPU if image_graph is not None: if image_graph not in files or not image_graph.startswith("image"): raise KeyError(f"this bundle has no {image_graph!r}; it has {[k for k in files if k.startswith('image')]}") image_key = image_graph image_provider = "cpu" if (provider == "cuda" and self.meta["precision"].get(image_key) != "float32") else provider self.image_graph = files[image_key] self.image_provider = image_provider # On a board with no swap, running out of memory stalls everything on it # rather than failing: refuse up front instead. sizes = self.meta.get("size_mb", {}) size_mb = sum(int(sizes.get(key, 0)) for key in (image_key, "text", "detect", "mask")) self.memory_needed_mb = 250 + int(1.3 * 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 machine 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"]) if image_provider == "npu": self._image = _npu_session(os.path.join(bundle, files[image_key]), ort) else: self._image = session(files[image_key], image_provider) rest = "cuda" if provider == "cuda" else "cpu" self._text = session(files["text"], rest) self._detect = session(files["detect"], rest) self._mask_path, self._mask_where, self._session = files["mask"], rest, session self._mask = None # loaded the first time masks are asked for self._tokenizer = Tokenizer() self._phrases: "OrderedDict[str, Tuple[np.ndarray, np.ndarray]]" = OrderedDict() self._text_cache = text_cache 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) -> Tuple[np.ndarray, np.ndarray]: """The image encoder's feature map and the level the detector reads. Reusable for any number of phrases.""" start = time.perf_counter() trunk, level = self._image.run(["trunk", "level"], {"image": self._preprocess(image)}) self.last = {"image_s": time.perf_counter() - start, "text_s": 0.0, "detect_s": 0.0, "mask_s": 0.0} return trunk, level def encode_text(self, concept: str) -> Tuple[np.ndarray, np.ndarray]: """A phrase's text tokens, remembered so a phrase is encoded once.""" key = " ".join(concept.lower().split()) if key in self._phrases: self._phrases.move_to_end(key) return self._phrases[key] feats, mask = self._text.run( ["text_feats", "text_mask"], {"tokens": self._tokenizer(key, self.context_length)} ) self._phrases[key] = (feats, mask) while len(self._phrases) > self._text_cache: self._phrases.popitem(last=False) return feats, mask def detect( self, image: Image.Image, concepts: Sequence[str], threshold: Optional[float] = None, masks: bool = False, max_detections: int = 100, features: Optional[Tuple[np.ndarray, np.ndarray]] = None, ) -> List[dict]: """Every instance of each phrase, best first: ``concept``, ``score``, ``box_xyxy`` in the image's pixels and, with ``masks=True``, ``mask`` (a boolean array the size of the image). ``features`` takes what ``encode_image`` returned for this image, to ask again without paying for the image pass. """ if isinstance(concepts, str): concepts = [concepts] threshold = self.threshold if threshold is None else threshold width, height = image.size if features is None: features = self.encode_image(image) else: self.last = {"image_s": 0.0, "text_s": 0.0, "detect_s": 0.0, "mask_s": 0.0} trunk, level = features scale = np.array([width, height, width, height], dtype=np.float32) found: List[dict] = [] for concept in concepts: start = time.perf_counter() text_feats, text_mask = self.encode_text(concept) self.last["text_s"] += time.perf_counter() - start start = time.perf_counter() wanted = ["logits", "boxes", "presence"] + (["queries", "memory", "prompt", "prompt_mask"] if masks else []) out = dict(zip(wanted, self._detect.run( wanted, {"feat": level, "text_feats": text_feats, "text_mask": text_mask} ))) scores = (_sigmoid(out["logits"][0, :, 0]) * _sigmoid(out["presence"].reshape(-1)[0])).astype(np.float32) keep = np.nonzero(scores > threshold)[0] self.last["detect_s"] += time.perf_counter() - start if keep.size == 0: continue start = time.perf_counter() keep = keep[np.argsort(-scores[keep])][:max_detections] cx, cy, w, h = out["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(range(len(keep))) )[:max_detections] self.last["detect_s"] += time.perf_counter() - start mask_arrays: List[Optional[np.ndarray]] = [None] * len(kept) if masks and kept: start = time.perf_counter() if self._mask is None: self._mask = self._session(self._mask_path, self._mask_where) 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"], } # the exporter drops any input the mask head turned out not to read logits = self._mask.run(["masks"], {k: v for k, v in feed.items() if k in self._mask_inputs})[0][0] for n, i in enumerate(kept): small = Image.fromarray(np.ascontiguousarray(logits[keep[i]], dtype=np.float32)) mask_arrays[n] = np.asarray(small.resize((width, height), Image.BILINEAR)) > 0 self.last["mask_s"] += time.perf_counter() - start for n, i in enumerate(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"] = mask_arrays[n] found.append(item) found.sort(key=lambda d: -d["score"]) return found