eoinedge commited on
Commit
89e8bbb
·
verified ·
1 Parent(s): b5a353c

runtime renamed to sam3edge_micro; --provider cuda

Browse files
sam3edge_micro/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sam3edge-micro: SAM 3 text-prompted detection for 4 GB boards, with no PyTorch.
2
+
3
+ It runs a sam3edge-micro bundle using only numpy, Pillow and ONNX Runtime.
4
+ Very restricted on purpose: a fixed list of concepts chosen when the bundle
5
+ was made, boxes and scores only, one image at a time.
6
+
7
+ from sam3edge_micro import Micro
8
+ micro = Micro("bundle-folder")
9
+ for det in micro.detect(image, ["person", "car"]):
10
+ print(det["concept"], det["score"], det["box_xyxy"])
11
+ """
12
+
13
+ from .runtime import Micro, available_memory_mb
14
+
15
+ __all__ = ["Micro", "available_memory_mb"]
16
+ __version__ = "0.2.0"
sam3edge_micro/__main__.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Command line: ``python -m sam3edge_micro detect|bench|info BUNDLE ...``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import statistics
8
+ import sys
9
+
10
+ from PIL import Image
11
+
12
+ from .runtime import Micro, available_memory_mb
13
+
14
+
15
+ def _peak_rss_mb():
16
+ try:
17
+ import resource
18
+
19
+ return round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024)
20
+ except ImportError:
21
+ return None
22
+
23
+
24
+ def main(argv=None) -> int:
25
+ parser = argparse.ArgumentParser(prog="python -m sam3edge_micro", description=__doc__)
26
+ sub = parser.add_subparsers(dest="command", required=True)
27
+ for name in ("info", "detect", "bench"):
28
+ p = sub.add_parser(name)
29
+ p.add_argument("bundle")
30
+ p.add_argument("--threads", type=int)
31
+ p.add_argument("--force", action="store_true", help="load even when memory looks short")
32
+ p.add_argument("--npu", action="store_true", help="run the image encoder on a Hexagon NPU")
33
+ p.add_argument("--provider", choices=["cpu", "cuda", "npu"], help="where the graphs run (default: cpu)")
34
+ if name != "info":
35
+ p.add_argument("image")
36
+ p.add_argument("--concept", action="append", help="repeatable; default: every concept in the bundle")
37
+ p.add_argument("--threshold", type=float)
38
+ if name == "bench":
39
+ p.add_argument("--runs", type=int, default=5)
40
+ args = parser.parse_args(argv)
41
+
42
+ micro = Micro(args.bundle, threads=args.threads, force=args.force, npu=args.npu, provider=args.provider)
43
+ if args.command == "info":
44
+ print(json.dumps({**micro.meta, "memory_needed_mb": micro.memory_needed_mb,
45
+ "memory_available_mb": available_memory_mb()}, indent=2))
46
+ return 0
47
+ image = Image.open(args.image)
48
+ if args.command == "detect":
49
+ found = micro.detect(image, args.concept, args.threshold)
50
+ print(json.dumps({"width": image.width, "height": image.height, "detections": found,
51
+ "timing": {k: round(v, 3) for k, v in micro.last.items()}}, indent=2))
52
+ return 0
53
+ concepts = args.concept or micro.concepts[:1]
54
+ image_s, detect_s, count = [], [], 0
55
+ for run in range(args.runs + 1):
56
+ count = len(micro.detect(image, concepts, args.threshold))
57
+ if run: # the first run warms the sessions up
58
+ image_s.append(micro.last["image_s"])
59
+ detect_s.append(micro.last["detect_s"] / len(concepts))
60
+ print(json.dumps({
61
+ "resolution": micro.resolution, "grid": micro.meta["grid"], "npu": micro.npu, "provider": micro.provider,
62
+ "image_s": round(statistics.median(image_s), 3), "concept_s": round(statistics.median(detect_s), 3),
63
+ "first_concept_s": round(statistics.median(image_s) + statistics.median(detect_s), 3),
64
+ "detections": count, "peak_rss_mb": _peak_rss_mb(),
65
+ }))
66
+ return 0
67
+
68
+
69
+ if __name__ == "__main__":
70
+ sys.exit(main())
sam3edge_micro/runtime.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The whole sam3edge-micro runtime: two ONNX graphs, a vocabulary file and numpy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import time
8
+ from typing import Dict, List, Optional, Sequence
9
+
10
+ import numpy as np
11
+ from PIL import Image
12
+
13
+ FORMAT = 1
14
+ HEADROOM_MB = 200
15
+
16
+
17
+ def available_memory_mb() -> Optional[int]:
18
+ """MemAvailable on Linux; None where it cannot be read."""
19
+ try:
20
+ with open("/proc/meminfo") as f:
21
+ for line in f:
22
+ if line.startswith("MemAvailable:"):
23
+ return int(line.split()[1]) // 1024
24
+ except OSError:
25
+ pass
26
+ return None
27
+
28
+
29
+ def _sigmoid(x: np.ndarray) -> np.ndarray:
30
+ return 1.0 / (1.0 + np.exp(-x))
31
+
32
+
33
+ def _nms(boxes: np.ndarray, scores: np.ndarray, iou: float) -> List[int]:
34
+ """Indices of the boxes to keep, best first."""
35
+ order = list(np.argsort(-scores))
36
+ areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
37
+ keep: List[int] = []
38
+ while order:
39
+ i = order.pop(0)
40
+ keep.append(int(i))
41
+ if not order:
42
+ break
43
+ rest = np.array(order)
44
+ x0 = np.maximum(boxes[i, 0], boxes[rest, 0])
45
+ y0 = np.maximum(boxes[i, 1], boxes[rest, 1])
46
+ x1 = np.minimum(boxes[i, 2], boxes[rest, 2])
47
+ y1 = np.minimum(boxes[i, 3], boxes[rest, 3])
48
+ inter = np.clip(x1 - x0, 0, None) * np.clip(y1 - y0, 0, None)
49
+ overlap = inter / np.maximum(areas[i] + areas[rest] - inter, 1e-9)
50
+ order = [int(j) for j, o in zip(rest, overlap) if o <= iou]
51
+ return keep
52
+
53
+
54
+ def _cuda_session(path: str, ort, options, device: int):
55
+ """A graph on an NVIDIA GPU. ONNX Runtime falls back to the CPU without saying so
56
+ when its CUDA libraries are missing, so the result is checked."""
57
+ if hasattr(ort, "preload_dlls"): # finds the CUDA and cuDNN wheels pip installed
58
+ try:
59
+ ort.preload_dlls()
60
+ except Exception:
61
+ pass
62
+ settings = {
63
+ "device_id": str(device),
64
+ "arena_extend_strategy": "kSameAsRequested", # do not grab more memory than is asked for
65
+ "cudnn_conv_algo_search": "HEURISTIC", # the exhaustive search costs seconds and memory
66
+ }
67
+ session = ort.InferenceSession(
68
+ path, options, providers=[("CUDAExecutionProvider", settings), "CPUExecutionProvider"]
69
+ )
70
+ if "CUDAExecutionProvider" not in session.get_providers():
71
+ raise RuntimeError(
72
+ "ONNX Runtime did not load its CUDA provider, so this would run on the CPU. Install "
73
+ 'the GPU build with its libraries (pip install "onnxruntime-gpu[cuda,cudnn]") and check '
74
+ "that nvidia-smi works."
75
+ )
76
+ return session
77
+
78
+
79
+ def _npu_session(path: str, ort):
80
+ """The image graph on a Hexagon NPU, through the onnxruntime-qnn package.
81
+
82
+ The compiled form is cached beside the graph, since compiling takes far
83
+ longer than running. Anything the NPU cannot take falls back to the CPU.
84
+ """
85
+ if not os.path.isfile(path):
86
+ raise FileNotFoundError(
87
+ f"{path} is missing: export the bundle with calibration images to get the NPU graph"
88
+ )
89
+ try:
90
+ import onnxruntime_qnn as qnn
91
+ except ImportError:
92
+ raise RuntimeError("the NPU needs the onnxruntime-qnn package") from None
93
+ library = os.path.dirname(qnn.get_library_path())
94
+ current = os.environ.get("ADSP_LIBRARY_PATH", "")
95
+ if library not in current.split(";"): # where the DSP finds its half of the backend
96
+ os.environ["ADSP_LIBRARY_PATH"] = ";".join(p for p in (library, current) if p)
97
+ try:
98
+ ort.register_execution_provider_library(qnn.get_ep_name(), qnn.get_library_path())
99
+ except Exception: # already registered in this process
100
+ pass
101
+ options = ort.SessionOptions()
102
+ cached = path[: -len(".onnx")] + ".npu-ctx.onnx"
103
+ source = path
104
+ if os.path.isfile(cached) and os.path.getmtime(cached) >= os.path.getmtime(path):
105
+ source = cached
106
+ else:
107
+ options.add_session_config_entry("ep.context_enable", "1")
108
+ options.add_session_config_entry("ep.context_file_path", cached)
109
+ options.add_session_config_entry("ep.context_embed_mode", "0")
110
+ # A plug-in provider is chosen by device, not by name: passing its name in
111
+ # ``providers=`` is accepted and then quietly ignored (everything runs on the CPU).
112
+ devices = [d for d in ort.get_ep_devices() if d.ep_name == qnn.get_ep_name()]
113
+ if not devices:
114
+ raise RuntimeError("onnxruntime-qnn found no NPU on this machine")
115
+ options.add_provider_for_devices(
116
+ devices, {"backend_path": qnn.get_qnn_htp_path(), "htp_performance_mode": "burst"}
117
+ )
118
+ session = ort.InferenceSession(source, options)
119
+ if qnn.get_ep_name() not in session.get_providers():
120
+ raise RuntimeError("the NPU backend did not take the image graph")
121
+ return session
122
+
123
+
124
+ class Micro:
125
+ """Runs one bundle. ``detect`` is the only thing most callers need.
126
+
127
+ ``provider`` is where the graphs run: ``"cpu"`` (default), ``"cuda"`` (an NVIDIA GPU
128
+ through onnxruntime-gpu) or ``"npu"`` (the image encoder on a Qualcomm Hexagon NPU
129
+ through onnxruntime-qnn). ``npu=True`` is the older spelling of ``provider="npu"``.
130
+ """
131
+
132
+ def __init__(
133
+ self,
134
+ bundle: str,
135
+ threads: Optional[int] = None,
136
+ force: bool = False,
137
+ npu: bool = False,
138
+ provider: Optional[str] = None,
139
+ device: int = 0,
140
+ ):
141
+ provider = provider or ("npu" if npu else "cpu")
142
+ if provider not in ("cpu", "cuda", "npu"):
143
+ raise ValueError("provider must be cpu, cuda or npu")
144
+ self.provider = provider
145
+ with open(os.path.join(bundle, "micro.json"), encoding="utf-8") as f:
146
+ self.meta = json.load(f)
147
+ if self.meta.get("format") != FORMAT:
148
+ raise ValueError(f"bundle format {self.meta.get('format')!r} is not {FORMAT}")
149
+ self.resolution = int(self.meta["resolution"])
150
+ self.concepts: List[str] = list(self.meta["concepts"])
151
+ self.threshold = float(self.meta.get("threshold", 0.3))
152
+ self.nms_iou = self.meta.get("nms_iou", 0.5)
153
+
154
+ # On a board with no swap, running out of memory stalls everything on it
155
+ # rather than failing: refuse up front instead.
156
+ size_mb = sum(
157
+ os.path.getsize(os.path.join(bundle, f)) for f in os.listdir(bundle)
158
+ ) // (1024 * 1024)
159
+ self.memory_needed_mb = 150 + 2 * size_mb
160
+ have = available_memory_mb()
161
+ if provider != "cuda" and have is not None and not force and have < self.memory_needed_mb + HEADROOM_MB:
162
+ raise MemoryError(
163
+ f"this bundle needs about {self.memory_needed_mb} MB and the board has {have} MB "
164
+ "available; free some memory or pass force=True"
165
+ )
166
+
167
+ import onnxruntime as ort
168
+
169
+ options = ort.SessionOptions()
170
+ options.intra_op_num_threads = threads or (os.cpu_count() or 1)
171
+ options.inter_op_num_threads = 1
172
+ options.add_session_config_entry("session.intra_op.allow_spinning", "0")
173
+ options.enable_cpu_mem_arena = False # give memory back between calls
174
+ options.log_severity_level = 3 # errors only: the graphs load with harmless shape warnings
175
+ def session(name: str, where: str):
176
+ path = os.path.join(bundle, name)
177
+ if where == "cuda":
178
+ return _cuda_session(path, ort, options, device)
179
+ return ort.InferenceSession(path, options, providers=["CPUExecutionProvider"])
180
+
181
+ self.npu = provider == "npu"
182
+ # A GPU has no kernels for an image graph stored in 8-bit weights: that one stays on the CPU.
183
+ float_image = self.meta.get("precision", {}).get("image", "float32") == "float32"
184
+ self.image_provider = provider if (provider != "cuda" or float_image) else "cpu"
185
+ if self.npu:
186
+ self._image = _npu_session(os.path.join(bundle, "image-npu.onnx"), ort)
187
+ else:
188
+ self._image = session("image.onnx", self.image_provider)
189
+ self._detect = session("detect.onnx", "cuda" if provider == "cuda" else "cpu")
190
+ vocab = np.load(os.path.join(bundle, "vocab.npz"))
191
+ self._tokens = vocab["tokens"] # concepts x tokens x 256
192
+ self._masks = vocab["masks"] # concepts x tokens, True = padding
193
+ self.last: Dict[str, float] = {}
194
+
195
+ def _preprocess(self, image: Image.Image) -> np.ndarray:
196
+ rgb = image.convert("RGB").resize((self.resolution, self.resolution), Image.BILINEAR)
197
+ x = np.asarray(rgb, dtype=np.float32) / 255.0
198
+ return ((x - 0.5) / 0.5).transpose(2, 0, 1)[None]
199
+
200
+ def encode_image(self, image: Image.Image) -> np.ndarray:
201
+ start = time.perf_counter()
202
+ level = self._image.run(["level"], {"image": self._preprocess(image)})[0]
203
+ self.last = {"image_s": time.perf_counter() - start, "detect_s": 0.0}
204
+ return level
205
+
206
+ def detect(
207
+ self,
208
+ image: Image.Image,
209
+ concepts: Optional[Sequence[str]] = None,
210
+ threshold: Optional[float] = None,
211
+ max_detections: int = 100,
212
+ ) -> List[dict]:
213
+ """Boxes of every instance of each concept, best first.
214
+
215
+ Concepts must come from the bundle's list (``micro.concepts``); the text
216
+ encoder is not on the board, so anything else cannot be asked.
217
+ """
218
+ wanted = [" ".join(c.lower().split()) for c in (concepts or self.concepts)]
219
+ unknown = [c for c in wanted if c not in self.concepts]
220
+ if unknown:
221
+ raise KeyError(
222
+ f"not in this bundle's concept list: {unknown}; it has {self.concepts}"
223
+ )
224
+ threshold = self.threshold if threshold is None else threshold
225
+ width, height = image.size
226
+ level = self.encode_image(image)
227
+ scale = np.array([width, height, width, height], dtype=np.float32)
228
+ found: List[dict] = []
229
+ start = time.perf_counter()
230
+ for concept in wanted:
231
+ index = self.concepts.index(concept)
232
+ logits, boxes, presence = self._detect.run(
233
+ ["logits", "boxes", "presence"],
234
+ {
235
+ "feat": level,
236
+ "text_feats": self._tokens[index][:, None, :],
237
+ "text_mask": self._masks[index][None, :],
238
+ },
239
+ )
240
+ scores = (_sigmoid(logits[0, :, 0]) * _sigmoid(presence.reshape(-1)[0])).astype(np.float32)
241
+ keep = np.nonzero(scores > threshold)[0]
242
+ if keep.size == 0:
243
+ continue
244
+ # best first, and no more candidates than the caller asked for (as sam3.edge does)
245
+ keep = keep[np.argsort(-scores[keep])][:max_detections]
246
+ cx, cy, w, h = boxes[0, keep].T
247
+ xyxy = np.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], axis=1) * scale
248
+ xyxy[:, 0::2] = np.clip(xyxy[:, 0::2], 0, width)
249
+ xyxy[:, 1::2] = np.clip(xyxy[:, 1::2], 0, height)
250
+ kept = (
251
+ _nms(xyxy, scores[keep], float(self.nms_iou))
252
+ if self.nms_iou is not None
253
+ else list(np.argsort(-scores[keep]))
254
+ )
255
+ for i in kept[:max_detections]:
256
+ found.append(
257
+ {
258
+ "concept": concept,
259
+ "score": round(float(scores[keep][i]), 4),
260
+ "box_xyxy": [round(float(v), 1) for v in xyxy[i]],
261
+ }
262
+ )
263
+ self.last["detect_s"] = time.perf_counter() - start
264
+ found.sort(key=lambda d: -d["score"])
265
+ return found