tatjr13 commited on
Commit
55fd594
·
verified ·
1 Parent(s): c10e825

scorevision: push artifact

Browse files
Files changed (4) hide show
  1. chute_config.yml +24 -0
  2. config.json +17 -0
  3. miner.py +555 -0
  4. weights.onnx +3 -0
chute_config.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chutes runtime config for this model repository. Sections map to chutes.image.Image,
2
+ # chutes.chute.NodeSelector and chutes.chute.Chute; unknown keys are dropped, keep names exact.
3
+
4
+ Image:
5
+ from_base: parachutes/python:3.12
6
+ run_command:
7
+ - pip install --upgrade setuptools wheel
8
+ - pip install 'numpy>=1.23' 'onnxruntime-gpu[cuda,cudnn]>=1.16' 'opencv-python>=4.7' 'pillow>=9.5' 'huggingface_hub>=0.19.4' 'pydantic>=2.0' 'pyyaml>=6.0' 'aiohttp>=3.9'
9
+ - pip install torch torchvision
10
+
11
+ NodeSelector:
12
+ gpu_count: 1
13
+ min_vram_gb_per_gpu: 16
14
+ max_hourly_price_per_gpu: 2
15
+ include:
16
+ - pro_6000
17
+
18
+ Chute:
19
+ timeout_seconds: 900
20
+ concurrency: 4
21
+ max_instances: 5
22
+ scaling_threshold: 0.5
23
+ shutdown_after_seconds: 288000
24
+ tee: true
config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "element_id": "person",
3
+ "classes": [
4
+ "person"
5
+ ],
6
+ "coco_ids": [
7
+ 0
8
+ ],
9
+ "emit_order": [
10
+ "person"
11
+ ],
12
+ "missing_classes": [],
13
+ "imgsz": 832,
14
+ "conf": 0.6,
15
+ "nms_iou": 0.4,
16
+ "max_det": 300
17
+ }
miner.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict config-driven consumer for Ultralytics end-to-end NMS ONNX.
2
+
3
+ The model contract is a static batch-1 input and one fixed ``[1, 300, 6]``
4
+ output whose rows are ``x1, y1, x2, y2, confidence, model_class_id``. NMS is
5
+ inside the ONNX graph. Python only validates, applies the element confidence
6
+ threshold and model-class mapping from ``config.json``, unletterboxes, filters
7
+ geometrically impossible boxes, sorts, and caps the configured result count.
8
+
9
+ This module intentionally uses no ``dataclass`` declarations. ScoreVision's
10
+ current ``spec_from_file_location`` loader does not register the dynamic module
11
+ in ``sys.modules`` before executing it, which makes Python dataclass decoration
12
+ fail during import.
13
+ """
14
+
15
+ import ast
16
+ import json
17
+ import math
18
+ import os
19
+ from collections.abc import Mapping
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import cv2
24
+ import numpy as np
25
+ import onnxruntime as ort
26
+ from numpy import ndarray
27
+ from pydantic import BaseModel
28
+
29
+
30
+ # The deployment rail currently recognizes this strict-inference contract
31
+ # version for every cycle-2 miner. The tensor layout is separately enforced by
32
+ # this module's fixed [1, 300, 6] startup check.
33
+ API_VERSION = "c2-strict-v1"
34
+ STRICT_INFERENCE_ENV = "SV_STRICT_INFERENCE"
35
+ INPUT_CHANNELS = 3
36
+ OUTPUT_ROWS = 300
37
+ OUTPUT_COLUMNS = 6
38
+ IMGSZ_MIN, IMGSZ_MAX, IMGSZ_MULTIPLE = 320, 1280, 32
39
+ MAX_DET_LIMIT = 300
40
+ _ROOT_KEYS = {
41
+ "element_id", "classes", "emit_order", "coco_ids", "missing_classes", "imgsz",
42
+ "conf", "nms_iou", "max_det",
43
+ }
44
+
45
+
46
+ class InferenceInvariantError(RuntimeError):
47
+ """A model tensor or decoded detection violated the serving contract."""
48
+
49
+
50
+ class BoundingBox(BaseModel):
51
+ x1: int
52
+ y1: int
53
+ x2: int
54
+ y2: int
55
+ cls_id: int
56
+ conf: float
57
+
58
+
59
+ class TVFrameResult(BaseModel):
60
+ frame_id: int
61
+ boxes: list[BoundingBox]
62
+ keypoints: list[tuple[int, int]]
63
+
64
+
65
+ def strict_inference_from_env(environ: Mapping[str, str] | None = None) -> bool:
66
+ raw = (os.environ if environ is None else environ).get(STRICT_INFERENCE_ENV, "")
67
+ if raw in ("", "0"):
68
+ return False
69
+ if raw == "1":
70
+ return True
71
+ raise ValueError(
72
+ f"{STRICT_INFERENCE_ENV} must be '1' or unset/'0', got {raw!r}"
73
+ )
74
+
75
+
76
+ def _strict_int(value: Any, where: str, low: int, high: int) -> int:
77
+ if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
78
+ raise ValueError(f"element config {where} must be an integer in [{low}, {high}], got {value!r}")
79
+ return value
80
+
81
+
82
+ def _strict_unit(value: Any, where: str) -> float:
83
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
84
+ raise ValueError(f"element config {where} must be a finite number in (0, 1], got {value!r}")
85
+ number = float(value)
86
+ if not math.isfinite(number) or not 0.0 < number <= 1.0:
87
+ raise ValueError(f"element config {where} must be a finite number in (0, 1], got {value!r}")
88
+ return number
89
+
90
+
91
+ class ElementConfig:
92
+ """Strict immutable-by-convention config without dynamic-loader dataclasses."""
93
+
94
+ __slots__ = (
95
+ "element_id", "classes", "emit_order", "output_cls_ids", "coco_ids", "emitted_cls_ids",
96
+ "missing_classes", "imgsz", "conf", "nms_iou", "max_det",
97
+ )
98
+
99
+ def __init__(
100
+ self,
101
+ element_id: str,
102
+ classes: tuple[str, ...],
103
+ coco_ids: tuple[int, ...],
104
+ emitted_cls_ids: tuple[int, ...],
105
+ missing_classes: tuple[str, ...],
106
+ imgsz: int,
107
+ conf: float,
108
+ nms_iou: float,
109
+ max_det: int,
110
+ *,
111
+ emit_order: tuple[str, ...] | None = None,
112
+ output_cls_ids: tuple[int, ...] = (),
113
+ ) -> None:
114
+ self.element_id = element_id
115
+ self.classes = classes
116
+ self.emit_order = emit_order
117
+ self.output_cls_ids = output_cls_ids
118
+ self.coco_ids = coco_ids
119
+ self.emitted_cls_ids = emitted_cls_ids
120
+ self.missing_classes = missing_classes
121
+ self.imgsz = imgsz
122
+ self.conf = conf
123
+ self.nms_iou = nms_iou
124
+ self.max_det = max_det
125
+
126
+ @classmethod
127
+ def from_mapping(cls, data: dict[str, Any]) -> "ElementConfig":
128
+ required = {"element_id", "classes", "coco_ids", "imgsz", "conf", "nms_iou", "max_det"}
129
+ missing = sorted(required - set(data))
130
+ if missing:
131
+ raise ValueError(f"element config missing required field(s): {', '.join(missing)}")
132
+ unknown = sorted(set(data) - _ROOT_KEYS)
133
+ if unknown:
134
+ raise ValueError(f"element config root has unknown key(s): {', '.join(unknown)}")
135
+ element_id = data["element_id"]
136
+ classes = data["classes"]
137
+ coco_ids = data["coco_ids"]
138
+ missing_classes = data.get("missing_classes", [])
139
+ if not isinstance(element_id, str) or not element_id:
140
+ raise ValueError("element config element_id must be a non-empty string")
141
+ if not isinstance(classes, list) or not classes or not all(isinstance(name, str) and name for name in classes):
142
+ raise ValueError("element config classes must be a non-empty list of strings")
143
+ if len(set(classes)) != len(classes):
144
+ raise ValueError("element config classes must not contain duplicates")
145
+ emit_order_raw = data.get("emit_order")
146
+ if "emit_order" not in data:
147
+ emit_order = None
148
+ else:
149
+ if not isinstance(emit_order_raw, list) or not emit_order_raw \
150
+ or not all(isinstance(name, str) and name for name in emit_order_raw):
151
+ raise ValueError("element config emit_order must be a non-empty list of class names")
152
+ if len(set(emit_order_raw)) != len(emit_order_raw):
153
+ raise ValueError("element config emit_order must not contain duplicates")
154
+ unknown = sorted(set(emit_order_raw) - set(classes))
155
+ omitted = sorted(set(classes) - set(emit_order_raw))
156
+ if unknown or omitted or len(emit_order_raw) != len(classes):
157
+ raise ValueError(
158
+ "element config emit_order must be an exact permutation of classes; "
159
+ f"unknown={unknown}, missing={omitted}"
160
+ )
161
+ emit_order = tuple(emit_order_raw)
162
+ output_order = emit_order if emit_order is not None else tuple(classes)
163
+ output_cls_ids = tuple(output_order.index(name) for name in classes)
164
+ if not isinstance(missing_classes, list) or not all(isinstance(name, str) for name in missing_classes):
165
+ raise ValueError("element config missing_classes must be a list of strings")
166
+ if len(set(missing_classes)) != len(missing_classes) or any(name not in classes for name in missing_classes):
167
+ raise ValueError("element config missing_classes must be unique members of classes")
168
+ if not isinstance(coco_ids, list) or not all(
169
+ isinstance(class_id, int) and not isinstance(class_id, bool) and class_id >= 0
170
+ for class_id in coco_ids
171
+ ):
172
+ raise ValueError("element config coco_ids must be non-negative integer model class ids")
173
+ if len(set(coco_ids)) != len(coco_ids):
174
+ raise ValueError("element config coco_ids must not contain duplicates")
175
+ emitted_cls_ids = tuple(index for index, name in enumerate(classes) if name not in missing_classes)
176
+ if len(coco_ids) != len(emitted_cls_ids):
177
+ raise ValueError(
178
+ "element config classes/coco_ids length mismatch: "
179
+ f"{len(classes)} classes minus {len(missing_classes)} missing classes requires "
180
+ f"{len(emitted_cls_ids)} ids, got {len(coco_ids)}"
181
+ )
182
+ imgsz = _strict_int(data["imgsz"], "imgsz", IMGSZ_MIN, IMGSZ_MAX)
183
+ if imgsz % IMGSZ_MULTIPLE:
184
+ raise ValueError(f"element config imgsz must be a multiple of {IMGSZ_MULTIPLE}, got {imgsz}")
185
+ return cls(
186
+ element_id,
187
+ tuple(classes),
188
+ tuple(coco_ids),
189
+ emitted_cls_ids,
190
+ tuple(missing_classes),
191
+ imgsz,
192
+ _strict_unit(data["conf"], "conf"),
193
+ _strict_unit(data["nms_iou"], "nms_iou"),
194
+ _strict_int(data["max_det"], "max_det", 1, MAX_DET_LIMIT),
195
+ emit_order=emit_order,
196
+ output_cls_ids=output_cls_ids,
197
+ )
198
+
199
+
200
+ def load_config(path: Path) -> ElementConfig:
201
+ try:
202
+ data = json.loads(path.read_text(encoding="utf-8"))
203
+ except Exception as exc:
204
+ raise ValueError(f"cannot parse element config {path}: {exc}") from exc
205
+ if not isinstance(data, dict):
206
+ raise ValueError("element config root must be a JSON object")
207
+ return ElementConfig.from_mapping(data)
208
+
209
+
210
+ class Miner:
211
+ api_version = API_VERSION
212
+ strict_inference = False
213
+ inference_failures = 0
214
+ invariant_failures = 0
215
+ input_dims_source = "unbound"
216
+ input_shape_declared: list[Any] = []
217
+ min_side = 3.0
218
+ max_aspect_ratio = 10.0
219
+
220
+ def __init__(self, path_hf_repo: Path) -> None:
221
+ repo = Path(path_hf_repo)
222
+ self.config = load_config(repo / "config.json")
223
+ self.class_names = list(self.config.emit_order or self.config.classes)
224
+ self.conf_threshold = self.config.conf
225
+ self.nms_iou = self.config.nms_iou # retained for API parity; NMS is in the graph
226
+ self.max_det = self.config.max_det
227
+ self.strict_inference = strict_inference_from_env()
228
+ self.inference_failures = 0
229
+ self.invariant_failures = 0
230
+
231
+ # The referee grants one physical core (two SMT threads). Let ORT own
232
+ # both threads for the convolution graph, but keep OpenCV's short
233
+ # resize/blob stages single-threaded: a second OpenCV worker is slower
234
+ # and adds tail jitter on two sibling logical CPUs.
235
+ cv2.setNumThreads(1)
236
+
237
+ options = ort.SessionOptions()
238
+ options.intra_op_num_threads = 2
239
+ options.inter_op_num_threads = 1
240
+ options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
241
+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
242
+ model_path = repo / "weights.onnx"
243
+ try:
244
+ self.session = ort.InferenceSession(
245
+ str(model_path), sess_options=options,
246
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
247
+ )
248
+ except Exception as exc:
249
+ print(f"CUDA session failed, falling back to CPU: {exc}")
250
+ self.session = ort.InferenceSession(
251
+ str(model_path), sess_options=options, providers=["CPUExecutionProvider"]
252
+ )
253
+ self.input_name = self.session.get_inputs()[0].name
254
+ self.output_names = [output.name for output in self.session.get_outputs()]
255
+ self._bind_input_dims(self.session.get_inputs()[0].shape)
256
+ self._check_output_shape(self.session.get_outputs()[0].shape)
257
+ self.model_names = self._read_model_names()
258
+ self._bind_class_map()
259
+ self._warmup(3)
260
+ print(
261
+ f"api_version={self.api_version} element={self.config.element_id} "
262
+ f"imgsz={self.config.imgsz} conf={self.conf_threshold} "
263
+ f"providers={self.session.get_providers()} warmups=3"
264
+ )
265
+
266
+ @staticmethod
267
+ def _static_dim(value: Any) -> bool:
268
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
269
+
270
+ def _bind_input_dims(self, shape: Any) -> None:
271
+ if not isinstance(shape, (list, tuple)) or len(shape) != 4:
272
+ raise ValueError(f"model input must be rank-4 NCHW, got {shape!r}")
273
+ batch, channels, height, width = shape
274
+ self.input_shape_declared = [value if self._static_dim(value) else str(value) for value in shape]
275
+ if self._static_dim(batch) and batch != 1:
276
+ raise ValueError(f"model input batch must be 1, got {batch}")
277
+ if self._static_dim(channels) and channels != INPUT_CHANNELS:
278
+ raise ValueError(f"model input channels must be 3, got {channels}")
279
+ if not (self._static_dim(height) and self._static_dim(width)):
280
+ raise ValueError(f"e2e shipping export must have static spatial dims, got {height}x{width}")
281
+ if (height, width) != (self.config.imgsz, self.config.imgsz):
282
+ raise ValueError(
283
+ f"model input spatial dims {height}x{width} != config imgsz "
284
+ f"{self.config.imgsz}x{self.config.imgsz}"
285
+ )
286
+ self.input_height = self.input_width = self.config.imgsz
287
+ self.input_dims_source = "static"
288
+
289
+ @staticmethod
290
+ def _check_output_shape(shape: Any) -> None:
291
+ if list(shape) != [1, OUTPUT_ROWS, OUTPUT_COLUMNS]:
292
+ raise ValueError(
293
+ f"e2e model output must be exactly [1, {OUTPUT_ROWS}, {OUTPUT_COLUMNS}], got {shape!r}"
294
+ )
295
+
296
+ def _read_model_names(self) -> tuple[str, ...]:
297
+ try:
298
+ raw = self.session.get_modelmeta().custom_metadata_map["names"]
299
+ parsed = ast.literal_eval(raw)
300
+ if not isinstance(parsed, dict):
301
+ raise TypeError("names metadata is not a dict")
302
+ keys = sorted(parsed)
303
+ if keys != list(range(len(keys))):
304
+ raise ValueError(f"names metadata keys are not consecutive from zero: {keys[:8]}")
305
+ names = tuple(str(parsed[index]) for index in keys)
306
+ except Exception as exc:
307
+ raise ValueError(f"e2e ONNX requires valid consecutive names metadata: {exc}") from exc
308
+ if not names:
309
+ raise ValueError("e2e ONNX names metadata is empty")
310
+ return names
311
+
312
+ def _bind_class_map(self) -> None:
313
+ self.model_to_element: dict[int, int] = {}
314
+ for model_id, element_id in zip(self.config.coco_ids, self.config.emitted_cls_ids):
315
+ if model_id >= len(self.model_names):
316
+ raise ValueError(
317
+ f"config model class id {model_id} outside ONNX names range 0..{len(self.model_names)-1}"
318
+ )
319
+ expected = self.config.classes[element_id]
320
+ actual = self.model_names[model_id]
321
+ if actual != expected:
322
+ raise ValueError(
323
+ f"config class mapping mismatch: model class {model_id} is {actual!r}, "
324
+ f"element class {element_id} is {expected!r}"
325
+ )
326
+ self.model_to_element[model_id] = element_id
327
+
328
+ @staticmethod
329
+ def _letterbox(image: ndarray, new_shape: tuple[int, int], color=(114, 114, 114)):
330
+ height, width = image.shape[:2]
331
+ new_width, new_height = new_shape
332
+ ratio = min(new_width / width, new_height / height)
333
+ resized_width, resized_height = int(round(width * ratio)), int(round(height * ratio))
334
+ if (resized_width, resized_height) != (width, height):
335
+ image = cv2.resize(
336
+ image, (resized_width, resized_height),
337
+ interpolation=cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR,
338
+ )
339
+ dw, dh = (new_width - resized_width) / 2.0, (new_height - resized_height) / 2.0
340
+ padded = cv2.copyMakeBorder(
341
+ image,
342
+ int(round(dh - 0.1)), int(round(dh + 0.1)),
343
+ int(round(dw - 0.1)), int(round(dw + 0.1)),
344
+ cv2.BORDER_CONSTANT, value=color,
345
+ )
346
+ return padded, ratio, (dw, dh)
347
+
348
+ def _preprocess(self, image: ndarray):
349
+ original_height, original_width = image.shape[:2]
350
+ padded, ratio, pad = self._letterbox(image, (self.input_width, self.input_height))
351
+ blob = cv2.dnn.blobFromImage(padded, scalefactor=1 / 255.0, swapRB=True)
352
+ return blob, ratio, pad, (original_width, original_height)
353
+
354
+ @staticmethod
355
+ def _check_image(image: np.ndarray) -> np.ndarray:
356
+ if not isinstance(image, np.ndarray) or image.ndim != 3 or image.shape[2] != 3:
357
+ raise ValueError(f"expected HWC 3-channel image, got {getattr(image, 'shape', type(image))}")
358
+ return image if image.dtype == np.uint8 else image.astype(np.uint8)
359
+
360
+ @staticmethod
361
+ def _check_finite(tensor: np.ndarray, where: str) -> None:
362
+ if not np.isfinite(tensor).all():
363
+ raise InferenceInvariantError(
364
+ f"{where} must be finite everywhere: NaN={int(np.isnan(tensor).sum())} "
365
+ f"Inf={int(np.isinf(tensor).sum())}"
366
+ )
367
+
368
+ def _check_outputs(self, outputs: Any) -> np.ndarray:
369
+ if not isinstance(outputs, (list, tuple)) or len(outputs) != len(self.output_names):
370
+ raise ValueError(f"session returned invalid output list, expected {len(self.output_names)} tensors")
371
+ for name, tensor in zip(self.output_names, outputs):
372
+ if not isinstance(tensor, np.ndarray):
373
+ raise ValueError(f"model output {name!r} is not an ndarray")
374
+ if np.issubdtype(tensor.dtype, np.floating):
375
+ self._check_finite(tensor, f"model output {name!r}")
376
+ output = outputs[0]
377
+ if not np.issubdtype(output.dtype, np.floating) or list(output.shape) != [1, OUTPUT_ROWS, OUTPUT_COLUMNS]:
378
+ raise ValueError(
379
+ f"e2e output tensor must be float [1, {OUTPUT_ROWS}, {OUTPUT_COLUMNS}], "
380
+ f"got {output.dtype} {list(output.shape)}"
381
+ )
382
+ return output
383
+
384
+ def _decode_e2e(
385
+ self,
386
+ output: np.ndarray,
387
+ ratio: float,
388
+ pad: tuple[float, float],
389
+ original_size: tuple[int, int],
390
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
391
+ rows = output[0]
392
+ boxes = rows[:, :4].astype(np.float32, copy=True)
393
+ scores = rows[:, 4].astype(np.float32, copy=False)
394
+ raw_classes = rows[:, 5]
395
+ if (scores < 0).any() or (scores > 1).any():
396
+ raise InferenceInvariantError("e2e confidence outside [0, 1]")
397
+ rounded = np.rint(raw_classes)
398
+ if not np.array_equal(raw_classes, rounded):
399
+ raise InferenceInvariantError("e2e model class ids must be exact integers")
400
+ model_classes = rounded.astype(np.int64)
401
+ if (model_classes < 0).any() or (model_classes >= len(self.model_names)).any():
402
+ bad = model_classes[(model_classes < 0) | (model_classes >= len(self.model_names))]
403
+ raise InferenceInvariantError(f"e2e model class id outside range: {bad[:8].tolist()}")
404
+
405
+ active = scores > 0.0
406
+ reversed_rows = active & ((boxes[:, 2] < boxes[:, 0]) | (boxes[:, 3] < boxes[:, 1]))
407
+ if reversed_rows.any():
408
+ raise InferenceInvariantError(f"e2e output contains reversed boxes: {boxes[reversed_rows][:4].tolist()}")
409
+ mapped = np.fromiter((int(class_id) in self.model_to_element for class_id in model_classes), bool, len(rows))
410
+ keep = mapped & (scores >= np.float32(self.conf_threshold))
411
+ if not keep.any():
412
+ return (
413
+ np.empty((0, 4), np.float32),
414
+ np.empty((0,), np.float32),
415
+ np.empty((0,), np.int64),
416
+ )
417
+ boxes = boxes[keep]
418
+ scores = scores[keep]
419
+ model_classes = model_classes[keep]
420
+ element_classes = np.fromiter(
421
+ (self.model_to_element[int(class_id)] for class_id in model_classes),
422
+ dtype=np.int64,
423
+ count=len(model_classes),
424
+ )
425
+ boxes[:, [0, 2]] = (boxes[:, [0, 2]] - pad[0]) / ratio
426
+ boxes[:, [1, 3]] = (boxes[:, [1, 3]] - pad[1]) / ratio
427
+ width, height = original_size
428
+ boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, width - 1)
429
+ boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0, height - 1)
430
+ self._check_decoded(boxes, scores, element_classes, original_size)
431
+
432
+ box_widths = boxes[:, 2] - boxes[:, 0]
433
+ box_heights = boxes[:, 3] - boxes[:, 1]
434
+ areas = box_widths * box_heights
435
+ image_area = float(width * height)
436
+ sane = (
437
+ (box_widths >= self.min_side)
438
+ & (box_heights >= self.min_side)
439
+ & (areas <= 0.95 * image_area)
440
+ & (
441
+ np.maximum(
442
+ box_widths / np.maximum(box_heights, 1e-6),
443
+ box_heights / np.maximum(box_widths, 1e-6),
444
+ )
445
+ <= self.max_aspect_ratio
446
+ )
447
+ )
448
+ boxes, scores, element_classes = boxes[sane], scores[sane], element_classes[sane]
449
+ if len(scores):
450
+ order = np.argsort(-scores, kind="stable")[: self.max_det]
451
+ boxes, scores, element_classes = boxes[order], scores[order], element_classes[order]
452
+ # Thresholds, model-name checks and all head semantics above stay in
453
+ # ``classes`` order. Only the validator-facing ids are remapped here.
454
+ if len(element_classes):
455
+ element_classes = np.asarray(self.config.output_cls_ids, dtype=np.int64)[element_classes]
456
+ return boxes, scores, element_classes
457
+
458
+ def _check_decoded(
459
+ self,
460
+ boxes: np.ndarray,
461
+ scores: np.ndarray,
462
+ class_ids: np.ndarray,
463
+ original_size: tuple[int, int],
464
+ ) -> None:
465
+ if not len(boxes):
466
+ return
467
+ width, height = original_size
468
+ if not np.isfinite(boxes).all():
469
+ raise InferenceInvariantError("decoded boxes contain non-finite coordinates")
470
+ if (boxes[:, 2] < boxes[:, 0]).any() or (boxes[:, 3] < boxes[:, 1]).any():
471
+ raise InferenceInvariantError("decoded boxes are reversed")
472
+ xs, ys = boxes[:, [0, 2]], boxes[:, [1, 3]]
473
+ if (xs < 0).any() or (xs > width - 1).any() or (ys < 0).any() or (ys > height - 1).any():
474
+ raise InferenceInvariantError(f"decoded boxes outside {width}x{height} image")
475
+ if not np.isfinite(scores).all() or (scores < 0).any() or (scores > 1).any():
476
+ raise InferenceInvariantError("decoded confidence outside [0, 1]")
477
+ if (class_ids < 0).any() or (class_ids >= len(self.class_names)).any():
478
+ raise InferenceInvariantError("decoded cls_id outside element class range")
479
+
480
+ @staticmethod
481
+ def _to_bounding_boxes(
482
+ boxes: np.ndarray,
483
+ scores: np.ndarray,
484
+ class_ids: np.ndarray,
485
+ ) -> list[BoundingBox]:
486
+ return [
487
+ BoundingBox(
488
+ x1=int(math.floor(box[0])), y1=int(math.floor(box[1])),
489
+ x2=int(math.ceil(box[2])), y2=int(math.ceil(box[3])),
490
+ cls_id=int(class_id), conf=float(score),
491
+ )
492
+ for box, score, class_id in zip(boxes, scores, class_ids)
493
+ if box[2] > box[0] and box[3] > box[1]
494
+ ]
495
+
496
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
497
+ image = self._check_image(image)
498
+ blob, ratio, pad, original_size = self._preprocess(image)
499
+ outputs = self.session.run(self.output_names, {self.input_name: blob})
500
+ output = self._check_outputs(outputs)
501
+ arrays = self._decode_e2e(output, ratio, pad, original_size)
502
+ return self._to_bounding_boxes(*arrays)
503
+
504
+ def _warmup(self, iterations: int) -> None:
505
+ dummy = np.zeros((720, 1280, 3), dtype=np.uint8)
506
+ original_strict = self.strict_inference
507
+ self.strict_inference = True
508
+ try:
509
+ for _ in range(iterations):
510
+ self.predict_batch(batch_images=[dummy], offset=0, n_keypoints=0)
511
+ except Exception as exc:
512
+ raise RuntimeError(f"warmup failed, refusing to serve: {type(exc).__name__}: {exc}") from exc
513
+ finally:
514
+ self.strict_inference = original_strict
515
+
516
+ def _record_failure(self, frame_id: int, exc: Exception) -> None:
517
+ self.inference_failures += 1
518
+ invariant = isinstance(exc, InferenceInvariantError)
519
+ if invariant:
520
+ self.invariant_failures += 1
521
+ print(json.dumps({
522
+ "event": "inference_failure",
523
+ "frame_id": frame_id,
524
+ "error_type": type(exc).__name__,
525
+ "error": str(exc),
526
+ "invariant": invariant,
527
+ "inference_failures": self.inference_failures,
528
+ "invariant_failures": self.invariant_failures,
529
+ }, sort_keys=True))
530
+
531
+ def predict_batch(
532
+ self,
533
+ batch_images: list[np.ndarray],
534
+ offset: int,
535
+ n_keypoints: int,
536
+ ) -> list[TVFrameResult]:
537
+ _ = n_keypoints
538
+ results: list[TVFrameResult] = []
539
+ for index, image in enumerate(batch_images):
540
+ frame_id = offset + index
541
+ try:
542
+ boxes = self._predict_single(image)
543
+ except Exception as exc:
544
+ if self.strict_inference:
545
+ raise
546
+ self._record_failure(frame_id, exc)
547
+ boxes = []
548
+ results.append(TVFrameResult(frame_id=frame_id, boxes=boxes, keypoints=[]))
549
+ return results
550
+
551
+ def __repr__(self) -> str:
552
+ return (
553
+ f"E2EONNXRuntime(session={type(self.session).__name__}, "
554
+ f"providers={self.session.get_providers()})"
555
+ )
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ac036d9a2b0170b36ef9d6c8bc1d68b010b1ff4bf940475f6c8276bc85aa2c6
3
+ size 4966886