tatjr13 commited on
Commit
57916a2
·
verified ·
1 Parent(s): 0a3322c

scorevision: push artifact

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